Index: /trunk/sources/HeuristicLab 3.3.sln
===================================================================
--- /trunk/sources/HeuristicLab 3.3.sln	(revision 11806)
+++ /trunk/sources/HeuristicLab 3.3.sln	(revision 11807)
@@ -20,5 +20,4 @@
 		{DBFD7205-61AF-40EF-8776-3052DEF91CF3} = {DBFD7205-61AF-40EF-8776-3052DEF91CF3}
 		{315BDA09-3F4F-49B3-9790-B37CFC1C5750} = {315BDA09-3F4F-49B3-9790-B37CFC1C5750}
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD} = {489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}
 		{72104A0B-90E7-42F3-9ABE-9BBBADD4B943} = {72104A0B-90E7-42F3-9ABE-9BBBADD4B943}
 		{3081630C-9521-47D7-8075-1777C12F212C} = {3081630C-9521-47D7-8075-1777C12F212C}
@@ -186,6 +185,4 @@
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.Operators.Views.GraphVisualization-3.3", "HeuristicLab.Operators.Views.GraphVisualization\3.3\HeuristicLab.Operators.Views.GraphVisualization-3.3.csproj", "{57F38579-409D-4DD8-AB19-3F2C4A665126}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.CodeEditor-3.3", "HeuristicLab.CodeEditor\3.3\HeuristicLab.CodeEditor-3.3.csproj", "{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}"
-EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.Optimization-3.3", "HeuristicLab.Optimization\3.3\HeuristicLab.Optimization-3.3.csproj", "{14AB8D24-25BC-400C-A846-4627AA945192}"
 EndProject
@@ -410,4 +407,6 @@
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.Analysis.Statistics.Views-3.3", "HeuristicLab.Analysis.Statistics.Views\3.3\HeuristicLab.Analysis.Statistics.Views-3.3.csproj", "{052881B5-4D5D-41C5-9555-FECA01E0BAC8}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.CodeEditor-3.4", "HeuristicLab.CodeEditor\3.4\HeuristicLab.CodeEditor-3.4.csproj", "{C38691AE-ECB4-489A-A05D-B035554E0168}"
 EndProject
 Global
@@ -673,16 +672,4 @@
 		{57F38579-409D-4DD8-AB19-3F2C4A665126}.Release|x86.ActiveCfg = Release|x86
 		{57F38579-409D-4DD8-AB19-3F2C4A665126}.Release|x86.Build.0 = Release|x86
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x64.ActiveCfg = Debug|x64
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x64.Build.0 = Debug|x64
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x86.ActiveCfg = Debug|x86
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Debug|x86.Build.0 = Debug|x86
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|Any CPU.Build.0 = Release|Any CPU
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x64.ActiveCfg = Release|x64
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x64.Build.0 = Release|x64
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x86.ActiveCfg = Release|x86
-		{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}.Release|x86.Build.0 = Release|x86
 		{14AB8D24-25BC-400C-A846-4627AA945192}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{14AB8D24-25BC-400C-A846-4627AA945192}.Debug|Any CPU.Build.0 = Debug|Any CPU
@@ -1991,4 +1978,16 @@
 		{052881B5-4D5D-41C5-9555-FECA01E0BAC8}.Release|x86.ActiveCfg = Release|x86
 		{052881B5-4D5D-41C5-9555-FECA01E0BAC8}.Release|x86.Build.0 = Release|x86
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Debug|x64.ActiveCfg = Debug|x64
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Debug|x64.Build.0 = Debug|x64
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Debug|x86.ActiveCfg = Debug|x86
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Debug|x86.Build.0 = Debug|x86
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Release|Any CPU.Build.0 = Release|Any CPU
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Release|x64.ActiveCfg = Release|x64
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Release|x64.Build.0 = Release|x64
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Release|x86.ActiveCfg = Release|x86
+		{C38691AE-ECB4-489A-A05D-B035554E0168}.Release|x86.Build.0 = Release|x86
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/AssemblyLoader.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/AssemblyLoader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/AssemblyLoader.cs	(revision 11807)
@@ -0,0 +1,145 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Threading.Tasks;
+using HeuristicLab.Common;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace HeuristicLab.CodeEditor {
+  internal class AssemblyLoader {
+    private readonly HashSet<IUnresolvedAssembly> assemblySet = new HashSet<IUnresolvedAssembly>();
+    private readonly object locker = new object();
+
+    public void AddAssembly(Assembly assembly) {
+      var assemblies = new[] { assembly };
+      OnAssembliesLoading(assemblies);
+      var unresolvedAssembly = Load(assembly);
+      lock (locker)
+        assemblySet.Add(unresolvedAssembly);
+      OnInternalAssembliesLoaded(new[] { unresolvedAssembly });
+      OnAssembliesLoaded(assemblies);
+    }
+
+    public void AddAssemblies(IEnumerable<Assembly> assemblies) {
+      var a = assemblies.ToArray();
+      OnAssembliesLoading(a);
+      var ua = new IUnresolvedAssembly[a.Length];
+      Parallel.For(0, a.Length, i => ua[i] = Load(a[i]));
+
+      lock (locker)
+        foreach (var asm in ua)
+          assemblySet.Add(asm);
+
+      OnInternalAssembliesLoaded(ua);
+      OnAssembliesLoaded(a);
+    }
+
+    public async Task AddAssembliesAsync(IEnumerable<Assembly> assemblies) {
+      await Task.Run(() => AddAssemblies(assemblies));
+    }
+
+    public void RemoveAssembly(Assembly assembly) {
+      var assemblies = new[] { assembly };
+      OnAssembliesUnloading(assemblies);
+      IUnresolvedAssembly unresolvedAssembly;
+      lock (locker) {
+        unresolvedAssembly = assemblySet.SingleOrDefault(x => x.FullAssemblyName == assembly.FullName);
+        assemblySet.Remove(unresolvedAssembly);
+      }
+      OnInternalAssembliesUnloaded(new[] { unresolvedAssembly });
+      OnAssembliesUnloaded(assemblies);
+    }
+
+    #region Loading Helper
+    private IUnresolvedAssembly Load(Assembly assembly) {
+      var loader = new CecilLoader {
+        IncludeInternalMembers = true,
+        DocumentationProvider = GetXmlDocumentation(assembly.Location)
+      };
+      return loader.LoadAssemblyFile(assembly.Location);
+    }
+    #endregion
+
+    #region XML Documentation Helpers
+    private static readonly List<string> xmlDocLookupDirectories = new List<string> {
+      Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"),
+      System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()
+    };
+
+    private static IDocumentationProvider GetXmlDocumentation(string assemblyLocation) {
+      if (!File.Exists(assemblyLocation)) return null;
+
+      string xmlDocFileName = Path.GetFileNameWithoutExtension(assemblyLocation) + ".xml";
+
+      foreach (var dir in xmlDocLookupDirectories) {
+        string xmlDocFileLocation = Path.Combine(dir, xmlDocFileName);
+        if (File.Exists(xmlDocFileLocation)) return new XmlDocumentationProvider(xmlDocFileLocation);
+      }
+
+      return null;
+    }
+    #endregion
+
+    #region Events
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesLoading;
+    private void OnAssembliesLoading(IEnumerable<Assembly> args) {
+      var handler = AssembliesLoading;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesLoaded;
+    private void OnAssembliesLoaded(IEnumerable<Assembly> args) {
+      var handler = AssembliesLoaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<IUnresolvedAssembly>>> InternalAssembliesLoaded;
+    private void OnInternalAssembliesLoaded(IEnumerable<IUnresolvedAssembly> args) {
+      var handler = InternalAssembliesLoaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<IUnresolvedAssembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesUnloading;
+    private void OnAssembliesUnloading(IEnumerable<Assembly> args) {
+      var handler = AssembliesUnloading;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesUnloaded;
+    private void OnAssembliesUnloaded(IEnumerable<Assembly> args) {
+      var handler = AssembliesUnloaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<IUnresolvedAssembly>>> InternalAssembliesUnloaded;
+    private void OnInternalAssembliesUnloaded(IEnumerable<IUnresolvedAssembly> args) {
+      var handler = InternalAssembliesUnloaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<IUnresolvedAssembly>>(args));
+    }
+    #endregion
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/AvalonEditWrapper.xaml
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/AvalonEditWrapper.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/AvalonEditWrapper.xaml	(revision 11807)
@@ -0,0 +1,14 @@
+﻿<UserControl
+             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+             xmlns:avalonedit="http://icsharpcode.net/sharpdevelop/avalonedit"
+             x:ClassModifier="internal"
+             x:Class="HeuristicLab.CodeEditor.AvalonEditWrapper"
+             mc:Ignorable="d" 
+             d:DesignHeight="300" d:DesignWidth="300">
+    <Grid>
+        <avalonedit:TextEditor Name="TextEditor"/>
+    </Grid>
+</UserControl>
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/AvalonEditWrapper.xaml.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/AvalonEditWrapper.xaml.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/AvalonEditWrapper.xaml.cs	(revision 11807)
@@ -0,0 +1,33 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Windows.Controls;
+
+namespace HeuristicLab.CodeEditor {
+  /// <summary>
+  /// Interaction logic for CodeEditorWrapper.xaml
+  /// </summary>
+  internal partial class AvalonEditWrapper : UserControl {
+    public AvalonEditWrapper() {
+      InitializeComponent();
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeEditor.Designer.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeEditor.Designer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeEditor.Designer.cs	(revision 11807)
@@ -0,0 +1,53 @@
+﻿namespace HeuristicLab.CodeEditor {
+  partial class CodeEditor {
+    /// <summary> 
+    /// Required designer variable.
+    /// </summary>
+    private System.ComponentModel.IContainer components = null;
+
+    /// <summary> 
+    /// Clean up any resources being used.
+    /// </summary>
+    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+    protected override void Dispose(bool disposing) {
+      if (disposing && (components != null)) {
+        components.Dispose();
+      }
+      base.Dispose(disposing);
+    }
+
+    #region Component Designer generated code
+
+    /// <summary> 
+    /// Required method for Designer support - do not modify 
+    /// the contents of this method with the code editor.
+    /// </summary>
+    private void InitializeComponent() {
+      this.elementHost = new System.Windows.Forms.Integration.ElementHost();
+      this.avalonEditWrapper = new HeuristicLab.CodeEditor.AvalonEditWrapper();
+      this.SuspendLayout();
+      // 
+      // elementHost
+      // 
+      this.elementHost.Dock = System.Windows.Forms.DockStyle.Fill;
+      this.elementHost.Location = new System.Drawing.Point(0, 0);
+      this.elementHost.Name = "elementHost";
+      this.elementHost.Size = new System.Drawing.Size(150, 150);
+      this.elementHost.TabIndex = 0;
+      this.elementHost.Child = this.avalonEditWrapper;
+      // 
+      // CodeEditor
+      // 
+      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+      this.Controls.Add(this.elementHost);
+      this.Name = "CodeEditor";
+      this.ResumeLayout(false);
+
+    }
+
+    #endregion
+
+    private System.Windows.Forms.Integration.ElementHost elementHost;
+    private AvalonEditWrapper avalonEditWrapper;
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeEditor.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeEditor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeEditor.cs	(revision 11807)
@@ -0,0 +1,483 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.CodeDom.Compiler;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Threading.Tasks;
+using System.Windows.Documents;
+using HeuristicLab.Common;
+using ICSharpCode.AvalonEdit;
+using ICSharpCode.AvalonEdit.AddIn;
+using ICSharpCode.AvalonEdit.CodeCompletion;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Highlighting;
+using ICSharpCode.AvalonEdit.Indentation.CSharp;
+using ICSharpCode.AvalonEdit.Search;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.SharpDevelop.Editor;
+using Forms = System.Windows.Forms;
+using Input = System.Windows.Input;
+using Media = System.Windows.Media;
+
+namespace HeuristicLab.CodeEditor {
+  public partial class CodeEditor : Forms.UserControl {
+    private static readonly Media.Color WarningColor = Media.Colors.Blue;
+    private static readonly Media.Color ErrorColor = Media.Colors.Red;
+    private static readonly Media.Color ReadOnlyColor = Media.Colors.Moccasin;
+
+    private const string DefaultDocumentFileName = "Document";
+    private const string DefaultTextEditorSyntaxHighlighting = "C#";
+    private const string DefaultTextEditorFontFamily = "Consolas";
+    private const double DefaultTextEditorFontSize = 13.0;
+    private const bool DefaultTextEditorShowLineNumbers = true;
+    private const bool DefaultTextEditorShowSpaces = true;
+    private const bool DefaultTextEditorShowTabs = true;
+    private const bool DefaultTextEditorConvertTabsToSpaces = true;
+    private const bool DefaultTextEditorHighlightCurrentLine = true;
+    private const int DefaultTextEditorIndentationSize = 2;
+
+    private AssemblyLoader assemblyLoader;
+    private ILanguageFeatures languageFeatures;
+    private TextMarkerService textMarkerService;
+
+    #region Properties
+    internal TextEditor TextEditor { get { return avalonEditWrapper.TextEditor; } }
+    internal Input.RoutedCommand CompletionCommand;
+    internal CompletionWindow CompletionWindow;
+    internal OverloadInsightWindow OverloadInsightWindow;
+
+    private TextDocument Doc { get { return TextEditor.Document; } }
+
+    private ITextMarker prefixMarker;
+    private string prefix = string.Empty;
+    public string Prefix {
+      get { return prefix; }
+      set {
+        if (value == null) value = string.Empty;
+        if (prefix == value) return;
+        if (prefixMarker != null) textMarkerService.Remove(prefixMarker);
+        Doc.Remove(0, prefix.Length);
+        prefix = value;
+        if (value.Length > 0) {
+          Doc.Insert(0, prefix);
+          prefixMarker = textMarkerService.Create(0, prefix.Length);
+          prefixMarker.BackgroundColor = ReadOnlyColor;
+        }
+      }
+    }
+
+    private ITextMarker suffixMarker;
+    private string suffix = string.Empty;
+    public string Suffix {
+      get { return suffix; }
+      set {
+        if (value == null) value = string.Empty;
+        if (suffix == value) return;
+        if (suffixMarker != null) textMarkerService.Remove(suffixMarker);
+        Doc.Remove(Doc.TextLength - suffix.Length, suffix.Length);
+        suffix = value;
+        if (value.Length > 0) {
+          int offset = Doc.TextLength;
+          Doc.Insert(offset, suffix);
+          suffixMarker = textMarkerService.Create(offset, suffix.Length);
+          suffixMarker.BackgroundColor = ReadOnlyColor;
+        }
+      }
+    }
+
+    public string UserCode {
+      get { return Doc.GetText(prefix.Length, Doc.TextLength - suffix.Length - prefix.Length); }
+      set {
+        if (Doc.Text == value) return;
+        Doc.Replace(prefix.Length, Doc.TextLength - suffix.Length - prefix.Length, value);
+      }
+    }
+
+    #region TextEditor
+    [DefaultValue(DefaultTextEditorSyntaxHighlighting)]
+    public string TextEditorSyntaxHighlighting {
+      get { return TextEditor.SyntaxHighlighting.Name; }
+      set {
+        TextEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition(value);
+        ApplyLanguageFeatures();
+      }
+    }
+
+    [DefaultValue(DefaultTextEditorShowLineNumbers)]
+    public bool TextEditorShowLineNumbers {
+      get { return TextEditor.ShowLineNumbers; }
+      set { TextEditor.ShowLineNumbers = value; }
+    }
+
+    [DefaultValue(DefaultTextEditorShowSpaces)]
+    public bool TextEditorShowSpaces {
+      get { return TextEditor.Options.ShowSpaces; }
+      set { TextEditor.Options.ShowSpaces = value; }
+    }
+
+    [DefaultValue(DefaultTextEditorShowTabs)]
+    public bool TextEditorShowTabs {
+      get { return TextEditor.Options.ShowTabs; }
+      set { TextEditor.Options.ShowTabs = value; }
+    }
+
+    [DefaultValue(DefaultTextEditorConvertTabsToSpaces)]
+    public bool TextEditorConvertTabsToSpaces {
+      get { return TextEditor.Options.ConvertTabsToSpaces; }
+      set { TextEditor.Options.ConvertTabsToSpaces = value; }
+    }
+
+    [DefaultValue(DefaultTextEditorHighlightCurrentLine)]
+    public bool TextEditorHighlightCurrentLine {
+      get { return TextEditor.Options.HighlightCurrentLine; }
+      set { TextEditor.Options.HighlightCurrentLine = value; }
+    }
+
+    [DefaultValue(DefaultTextEditorIndentationSize)]
+    public int TextEditorIndentationSize {
+      get { return TextEditor.Options.IndentationSize; }
+      set { TextEditor.Options.IndentationSize = value; }
+    }
+    #endregion
+
+    public bool ReadOnly {
+      get { return TextEditor.IsReadOnly; }
+      set { TextEditor.IsReadOnly = value; }
+    }
+    #endregion
+
+    public CodeEditor() {
+      InitializeComponent();
+      InitializeTextEditor();
+    }
+
+    private void InitializeTextEditor() {
+      #region AssemblyLoader
+      assemblyLoader = new AssemblyLoader();
+      assemblyLoader.AssembliesLoading += (sender, args) => OnAssembliesLoading(args.Value);
+      assemblyLoader.InternalAssembliesLoaded += (sender, args) => OnInternalAssembliesLoaded(args.Value);
+      assemblyLoader.AssembliesLoaded += (sender, args) => OnAssembliesLoaded(args.Value);
+      assemblyLoader.AssembliesUnloading += (sender, args) => OnAssembliesUnloading(args.Value);
+      assemblyLoader.InternalAssembliesUnloaded += (sender, args) => OnInternalAssembliesUnloaded(args.Value);
+      assemblyLoader.AssembliesUnloaded += (sender, args) => OnAssembliesUnloaded(args.Value);
+      #endregion
+
+      #region TextMarkerService
+      textMarkerService = new TextMarkerService(TextEditor.Document);
+      TextEditor.TextArea.TextView.BackgroundRenderers.Add(textMarkerService);
+      TextEditor.TextArea.TextView.LineTransformers.Add(textMarkerService);
+      TextEditor.TextArea.TextView.Services.AddService(typeof(ITextMarkerService), textMarkerService);
+
+      #endregion
+
+      #region ReadOnlySectionProvider
+      TextEditor.TextArea.ReadOnlySectionProvider = new MethodDefinitionReadOnlySectionProvider(this);
+      #endregion
+
+      #region SearchPanel
+      SearchPanel.Install(TextEditor);
+      #endregion
+
+      #region CompletionCommand
+      CompletionCommand = new Input.RoutedCommand();
+      CompletionCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.Space, Input.ModifierKeys.Control));
+      #endregion
+
+      #region MoveLinesUpCommand
+      var moveLinesUpCommand = new Input.RoutedCommand();
+      moveLinesUpCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.Up, Input.ModifierKeys.Alt));
+      var moveLinesUpCommandBinding = new Input.CommandBinding(moveLinesUpCommand, (sender, args) => ExecuteMoveLinesCommand(MovementDirection.Up));
+      TextEditor.CommandBindings.Add(moveLinesUpCommandBinding);
+      #endregion
+
+      #region MoveLinesDownCommand
+      var moveLinesDownCommand = new Input.RoutedCommand();
+      moveLinesDownCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.Down, Input.ModifierKeys.Alt));
+      var moveLinesDownCommandBinding = new Input.CommandBinding(moveLinesDownCommand, (sender, args) => ExecuteMoveLinesCommand(MovementDirection.Down));
+      TextEditor.CommandBindings.Add(moveLinesDownCommandBinding);
+      #endregion
+
+      #region GoToLineCommand
+      var goToLineCommand = new Input.RoutedCommand();
+      goToLineCommand.InputGestures.Add(new Input.KeyGesture(Input.Key.G, Input.ModifierKeys.Control));
+      var goToLineCommandBinding = new Input.CommandBinding(goToLineCommand, (sender, args) => ExecuteGoToLineCommand());
+      TextEditor.CommandBindings.Add(goToLineCommandBinding);
+      #endregion
+
+      TextEditorSyntaxHighlighting = DefaultTextEditorSyntaxHighlighting;
+      TextEditorShowLineNumbers = DefaultTextEditorShowLineNumbers;
+      TextEditorShowSpaces = DefaultTextEditorShowSpaces;
+      TextEditorShowTabs = DefaultTextEditorShowTabs;
+      TextEditorConvertTabsToSpaces = DefaultTextEditorConvertTabsToSpaces;
+      TextEditorHighlightCurrentLine = DefaultTextEditorHighlightCurrentLine;
+      TextEditorIndentationSize = DefaultTextEditorIndentationSize;
+
+      Doc.FileName = DefaultDocumentFileName;
+
+      TextEditor.FontFamily = new Media.FontFamily(DefaultTextEditorFontFamily);
+      TextEditor.FontSize = DefaultTextEditorFontSize;
+      TextEditor.Options.EnableVirtualSpace = true;
+      TextEditor.TextArea.IndentationStrategy = new CSharpIndentationStrategy(TextEditor.Options);
+
+      TextEditor.TextChanged += (sender, args) => {
+        textMarkerService.RemoveAll(x => x != prefixMarker && x != suffixMarker);
+        OnTextEditorTextChanged();
+      };
+    }
+
+    #region Assembly Management
+    public void AddAssembly(Assembly a) {
+      assemblyLoader.AddAssembly(a);
+    }
+
+    public void AddAssemblies(IEnumerable<Assembly> assemblies) {
+      assemblyLoader.AddAssemblies(assemblies);
+    }
+
+    public async Task AddAssembliesAsync(IEnumerable<Assembly> assemblies) {
+      await assemblyLoader.AddAssembliesAsync(assemblies);
+    }
+
+    public void RemoveAssembly(Assembly a) {
+      assemblyLoader.RemoveAssembly(a);
+    }
+    #endregion
+
+    public void ScrollToPosition(int line, int column) {
+      var segment = GetSegmentAtLocation(line, column);
+      TextEditor.CaretOffset = segment.Offset + segment.Length;
+      TextEditor.ScrollToLine(line);
+    }
+
+    public void ScrollAfterPrefix() {
+      var location = Doc.GetLocation(prefix.Length);
+      ScrollToPosition(location.Line, location.Column);
+    }
+
+    private enum MovementDirection { Up, Down }
+    private void ExecuteMoveLinesCommand(MovementDirection movementDirection) {
+      var textArea = TextEditor.TextArea;
+      var selection = textArea.Selection;
+      var caret = textArea.Caret;
+
+      var selectionStartPosition = selection.StartPosition;
+      var selectionEndPosition = selection.EndPosition;
+      var caretPosition = caret.Position;
+      int caretOffset = caret.Offset;
+
+      bool advancedPositionCalcualtion = selection is RectangleSelection || !selection.IsEmpty;
+
+      int selectionStartOffset, selectionEndOffset;
+      if (advancedPositionCalcualtion) {
+        if (selectionStartPosition.CompareTo(selectionEndPosition) > 0) {
+          var temp = selectionStartPosition;
+          selectionStartPosition = selectionEndPosition;
+          selectionEndPosition = temp;
+        }
+        selectionStartOffset = Doc.GetOffset(selectionStartPosition.Location);
+        selectionEndOffset = Doc.GetOffset(selectionEndPosition.Location);
+      } else {
+        selectionStartOffset = selectionEndOffset = TextEditor.SelectionStart;
+      }
+
+      int selectionLength = selection.Length;
+
+      var startLine = Doc.GetLineByOffset(selectionStartOffset);
+      var endLine = Doc.GetLineByOffset(selectionEndOffset);
+
+      if (selection.IsMultiline && selectionEndOffset == endLine.Offset) {
+        if (movementDirection == MovementDirection.Down && endLine.TotalLength == 0) return;
+        endLine = endLine.PreviousLine;
+      }
+
+      if (movementDirection == MovementDirection.Up && startLine.LineNumber == 1) return;
+      if (movementDirection == MovementDirection.Down && endLine.LineNumber == Doc.LineCount) return;
+
+      int startOffset = startLine.Offset;
+      string primaryText = Doc.GetText(startOffset, endLine.EndOffset - startOffset);
+      string primaryDelimiter = Doc.GetText(endLine.EndOffset, endLine.DelimiterLength);
+
+      var secondaryLine = movementDirection == MovementDirection.Up ? startLine.PreviousLine : endLine.NextLine;
+      string secondaryText = Doc.GetText(secondaryLine.Offset, secondaryLine.Length);
+      string secondaryDelimiter = Doc.GetText(secondaryLine.EndOffset, secondaryLine.DelimiterLength);
+
+      if (string.IsNullOrEmpty(primaryText + primaryDelimiter) || string.IsNullOrEmpty(secondaryText + secondaryDelimiter)) return;
+
+      if (movementDirection == MovementDirection.Up) {
+        string replacementText = primaryText + secondaryDelimiter + secondaryText + primaryDelimiter;
+        Doc.Replace(secondaryLine.Offset, replacementText.Length, replacementText);
+        int correctionLength = secondaryText.Length + secondaryDelimiter.Length;
+        selectionStartOffset -= correctionLength;
+        caretOffset -= correctionLength;
+      } else {
+        string replacementText = secondaryText + primaryDelimiter + primaryText + secondaryDelimiter;
+        Doc.Replace(startLine.Offset, replacementText.Length, replacementText);
+        int correctionLength = secondaryText.Length + primaryDelimiter.Length;
+        selectionStartOffset += correctionLength;
+        caretOffset += correctionLength;
+      }
+
+      if (advancedPositionCalcualtion) {
+        var newSelectionStartLocation = Doc.GetLocation(selectionStartOffset);
+        int selectionLineOffset = newSelectionStartLocation.Line - Math.Min(selectionStartPosition.Line, selectionEndPosition.Line);
+        selectionStartPosition.Line += selectionLineOffset;
+        selectionEndPosition.Line += selectionLineOffset;
+        if (selectionEndPosition.Line > Doc.LineCount) {
+          var newLocation = Doc.GetLocation(Doc.TextLength);
+          selectionEndPosition.Line = newLocation.Line;
+          selectionEndPosition.Column = newLocation.Column;
+          selectionEndPosition.VisualColumn = newLocation.Column - 1;
+          selectionEndPosition.IsAtEndOfLine = selectionStartPosition.IsAtEndOfLine; // actual value does not matter; needed for comparison
+        }
+
+        if (selectionStartPosition == selectionEndPosition)
+          textArea.ClearSelection();
+        else {
+          if (selection is RectangleSelection)
+            textArea.Selection = new RectangleSelection(textArea, selectionStartPosition, selectionEndPosition);
+          else
+            textArea.Selection = new SimpleSelection(textArea, selectionStartPosition, selectionEndPosition);
+        }
+      } else {
+        TextEditor.SelectionStart = selectionStartOffset;
+        TextEditor.SelectionLength = selectionLength;
+      }
+
+      var newCaretLocation = Doc.GetLocation(Math.Min(caretOffset, Doc.TextLength));
+      var newCaretPosition = new TextViewPosition(newCaretLocation);
+      if (caretPosition.VisualColumn > caretPosition.Column) {
+        newCaretPosition.VisualColumn = caretPosition.VisualColumn;
+      }
+      caret.Position = newCaretPosition;
+    }
+
+    private void ExecuteGoToLineCommand() {
+      using (var dlg = new GoToLineDialog(TextEditor)) {
+        var result = dlg.ShowDialog(this);
+        if (result == Forms.DialogResult.OK) {
+          int lineNumber = dlg.Line;
+          var line = Doc.GetLineByNumber(lineNumber);
+          int offset = line.Offset;
+          if (TextUtilities.GetLeadingWhitespace(Doc, line).Length > 0)
+            offset = TextUtilities.GetNextCaretPosition(Doc, offset, LogicalDirection.Forward, CaretPositioningMode.WordStart);
+          TextEditor.CaretOffset = offset;
+        }
+      }
+    }
+
+    #region Compiler Errors
+    public void ShowCompileErrors(CompilerErrorCollection compilerErrors) {
+      if (compilerErrors == null) return;
+
+      textMarkerService.RemoveAll(x => x != prefixMarker && x != suffixMarker);
+
+      foreach (CompilerError error in compilerErrors) {
+        var startLocation = Doc.GetLocation(prefix.Length);
+        if (error.Line == 1) error.Column += startLocation.Column;
+        error.Line += startLocation.Line;
+        AddErrorMarker(error);
+      }
+    }
+
+    private void AddErrorMarker(CompilerError error) {
+      var segment = GetSegmentAtLocation(error.Line, error.Column);
+      var marker = textMarkerService.Create(segment.Offset, segment.Length);
+      marker.MarkerTypes = TextMarkerTypes.SquigglyUnderline;
+      marker.MarkerColor = error.IsWarning ? WarningColor : ErrorColor;
+    }
+
+    private ISegment GetSegmentAtLocation(int line, int column) {
+      line = Math.Max(Doc.GetLocation(prefix.Length).Line, line - 1);
+      line = Math.Min(Doc.GetLocation(Doc.TextLength - suffix.Length).Line, line);
+
+      var startOffset = Doc.GetOffset(line, column);
+      var lineEndOffset = Doc.GetLineByNumber(line).EndOffset;
+      var endOffset = TextUtilities.GetNextCaretPosition(Doc, startOffset, LogicalDirection.Forward, CaretPositioningMode.WordBorder);
+      if (endOffset < 0) endOffset = startOffset;
+      endOffset = Math.Min(lineEndOffset + 1, endOffset);
+
+      var segment = new TextSegment { StartOffset = startOffset, EndOffset = endOffset };
+
+      return segment;
+    }
+    #endregion
+
+    private void ApplyLanguageFeatures() {
+      switch (TextEditorSyntaxHighlighting) {
+        case "XML":
+          languageFeatures = new XmlLanguageFeatures(this);
+          break;
+        default:
+          languageFeatures = new CSharpLanguageFeatures(this);
+          break;
+      }
+    }
+
+    #region Events
+    public event EventHandler TextEditorTextChanged;
+    private void OnTextEditorTextChanged() {
+      var handler = TextEditorTextChanged;
+      if (handler != null) handler(this, EventArgs.Empty);
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesLoading;
+    private void OnAssembliesLoading(IEnumerable<Assembly> args) {
+      var handler = AssembliesLoading;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesLoaded;
+    private void OnAssembliesLoaded(IEnumerable<Assembly> args) {
+      var handler = AssembliesLoaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<IUnresolvedAssembly>>> InternalAssembliesLoaded;
+    private void OnInternalAssembliesLoaded(IEnumerable<IUnresolvedAssembly> args) {
+      var handler = InternalAssembliesLoaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<IUnresolvedAssembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesUnloading;
+    private void OnAssembliesUnloading(IEnumerable<Assembly> args) {
+      var handler = AssembliesUnloading;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<Assembly>>> AssembliesUnloaded;
+    private void OnAssembliesUnloaded(IEnumerable<Assembly> args) {
+      var handler = AssembliesUnloaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<Assembly>>(args));
+    }
+
+    public event EventHandler<EventArgs<IEnumerable<IUnresolvedAssembly>>> InternalAssembliesUnloaded;
+    private void OnInternalAssembliesUnloaded(IEnumerable<IUnresolvedAssembly> args) {
+      var handler = InternalAssembliesUnloaded;
+      if (handler != null) handler(this, new EventArgs<IEnumerable<IUnresolvedAssembly>>(args));
+    }
+    #endregion
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeViewer.Designer.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeViewer.Designer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeViewer.Designer.cs	(revision 11807)
@@ -0,0 +1,72 @@
+﻿namespace HeuristicLab.CodeEditor {
+  partial class CodeViewer {
+    /// <summary>
+    /// Required designer variable.
+    /// </summary>
+    private System.ComponentModel.IContainer components = null;
+
+    /// <summary>
+    /// Clean up any resources being used.
+    /// </summary>
+    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+    protected override void Dispose(bool disposing) {
+      if (disposing && (components != null)) {
+        components.Dispose();
+      }
+      base.Dispose(disposing);
+    }
+
+    #region Windows Form Designer generated code
+
+    /// <summary>
+    /// Required method for Designer support - do not modify
+    /// the contents of this method with the code editor.
+    /// </summary>
+    private void InitializeComponent() {
+      this.okButton = new System.Windows.Forms.Button();
+      this.elementHost = new System.Windows.Forms.Integration.ElementHost();
+      this.avalonEditWrapper = new HeuristicLab.CodeEditor.AvalonEditWrapper();
+      this.SuspendLayout();
+      // 
+      // okButton
+      // 
+      this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+      this.okButton.Location = new System.Drawing.Point(647, 426);
+      this.okButton.Name = "okButton";
+      this.okButton.Size = new System.Drawing.Size(75, 23);
+      this.okButton.TabIndex = 0;
+      this.okButton.Text = "OK";
+      this.okButton.UseVisualStyleBackColor = true;
+      this.okButton.Click += new System.EventHandler(this.okButton_Click);
+      // 
+      // elementHost
+      // 
+      this.elementHost.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+            | System.Windows.Forms.AnchorStyles.Left)
+            | System.Windows.Forms.AnchorStyles.Right)));
+      this.elementHost.Location = new System.Drawing.Point(12, 12);
+      this.elementHost.Name = "elementHost";
+      this.elementHost.Size = new System.Drawing.Size(710, 408);
+      this.elementHost.TabIndex = 1;
+      this.elementHost.Child = this.avalonEditWrapper;
+      // 
+      // CodeViewer
+      // 
+      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+      this.ClientSize = new System.Drawing.Size(734, 461);
+      this.Controls.Add(this.elementHost);
+      this.Controls.Add(this.okButton);
+      this.Icon = HeuristicLab.Common.Resources.HeuristicLab.Icon;
+      this.Name = "CodeViewer";
+      this.Text = "CodeViewer";
+      this.ResumeLayout(false);
+
+    }
+
+    #endregion
+
+    private System.Windows.Forms.Button okButton;
+    private System.Windows.Forms.Integration.ElementHost elementHost;
+    private AvalonEditWrapper avalonEditWrapper;
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeViewer.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeViewer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/CodeViewer.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Windows.Forms;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit;
+using ICSharpCode.AvalonEdit.Highlighting;
+
+namespace HeuristicLab.CodeEditor {
+  public partial class CodeViewer : Form {
+    private const string DefaultTextEditorSyntaxHighlighting = "C#";
+    private const string DefaultTextEditorFontFamily = "Consolas";
+    private const double DefaultTextEditorFontSize = 13.0;
+    private const bool DefaultTextEditorShowLineNumbers = true;
+    private const bool DefaultTextEditorShowEndOfLine = true;
+    private const bool DefaultTextEditorShowSpaces = true;
+    private const bool DefaultTextEditorShowTabs = true;
+    private const bool DefaultTextEditorConvertTabsToSpaces = true;
+
+    private TextEditor TextEditor { get { return avalonEditWrapper.TextEditor; } }
+
+    public CodeViewer() {
+      InitializeComponent();
+      TextEditor.IsReadOnly = true;
+      TextEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition(DefaultTextEditorSyntaxHighlighting);
+      TextEditor.FontFamily = new FontFamily(DefaultTextEditorFontFamily);
+      TextEditor.FontSize = DefaultTextEditorFontSize;
+      TextEditor.ShowLineNumbers = DefaultTextEditorShowLineNumbers;
+      TextEditor.Options.ShowEndOfLine = DefaultTextEditorShowEndOfLine;
+      TextEditor.Options.ShowSpaces = DefaultTextEditorShowSpaces;
+      TextEditor.Options.ShowTabs = DefaultTextEditorShowTabs;
+      TextEditor.Options.ConvertTabsToSpaces = DefaultTextEditorConvertTabsToSpaces;
+    }
+
+    public CodeViewer(string code)
+      : this() {
+      TextEditor.Text = code;
+    }
+
+    private void okButton_Click(object sender, EventArgs e) {
+      Close();
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/GoToLineDialog.Designer.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/GoToLineDialog.Designer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/GoToLineDialog.Designer.cs	(revision 11807)
@@ -0,0 +1,113 @@
+﻿namespace HeuristicLab.CodeEditor {
+  partial class GoToLineDialog {
+    /// <summary>
+    /// Required designer variable.
+    /// </summary>
+    private System.ComponentModel.IContainer components = null;
+
+    /// <summary>
+    /// Clean up any resources being used.
+    /// </summary>
+    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
+    protected override void Dispose(bool disposing) {
+      if (disposing && (components != null)) {
+        components.Dispose();
+      }
+      base.Dispose(disposing);
+    }
+
+    #region Windows Form Designer generated code
+
+    /// <summary>
+    /// Required method for Designer support - do not modify
+    /// the contents of this method with the code editor.
+    /// </summary>
+    private void InitializeComponent() {
+      this.components = new System.ComponentModel.Container();
+      this.cancelButton = new System.Windows.Forms.Button();
+      this.okButton = new System.Windows.Forms.Button();
+      this.lineNumberLabel = new System.Windows.Forms.Label();
+      this.lineNumberTextBox = new System.Windows.Forms.TextBox();
+      this.errorProvider = new System.Windows.Forms.ErrorProvider(this.components);
+      ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
+      this.SuspendLayout();
+      // 
+      // cancelButton
+      // 
+      this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+      this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
+      this.cancelButton.Location = new System.Drawing.Point(156, 51);
+      this.cancelButton.Name = "cancelButton";
+      this.cancelButton.Size = new System.Drawing.Size(75, 23);
+      this.cancelButton.TabIndex = 2;
+      this.cancelButton.Text = "&Cancel";
+      this.cancelButton.UseVisualStyleBackColor = true;
+      // 
+      // okButton
+      // 
+      this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
+      this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
+      this.okButton.Enabled = false;
+      this.okButton.Location = new System.Drawing.Point(75, 51);
+      this.okButton.Name = "okButton";
+      this.okButton.Size = new System.Drawing.Size(75, 23);
+      this.okButton.TabIndex = 1;
+      this.okButton.Text = "&OK";
+      this.okButton.UseVisualStyleBackColor = true;
+      // 
+      // lineNumberLabel
+      // 
+      this.lineNumberLabel.AutoSize = true;
+      this.lineNumberLabel.Location = new System.Drawing.Point(12, 9);
+      this.lineNumberLabel.Name = "lineNumberLabel";
+      this.lineNumberLabel.Size = new System.Drawing.Size(94, 13);
+      this.lineNumberLabel.TabIndex = 3;
+      this.lineNumberLabel.Text = "Line Number (1-1):";
+      // 
+      // lineNumberTextBox
+      // 
+      this.lineNumberTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
+            | System.Windows.Forms.AnchorStyles.Right)));
+      this.lineNumberTextBox.Location = new System.Drawing.Point(15, 25);
+      this.lineNumberTextBox.Name = "lineNumberTextBox";
+      this.lineNumberTextBox.Size = new System.Drawing.Size(212, 20);
+      this.lineNumberTextBox.TabIndex = 0;
+      this.lineNumberTextBox.TextChanged += new System.EventHandler(this.lineNumberTextBox_TextChanged);
+      // 
+      // errorProvider
+      // 
+      this.errorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
+      this.errorProvider.ContainerControl = this;
+      // 
+      // GoToLineDialog
+      // 
+      this.AcceptButton = this.okButton;
+      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+      this.CancelButton = this.cancelButton;
+      this.ClientSize = new System.Drawing.Size(243, 86);
+      this.Controls.Add(this.lineNumberTextBox);
+      this.Controls.Add(this.lineNumberLabel);
+      this.Controls.Add(this.cancelButton);
+      this.Controls.Add(this.okButton);
+      this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
+      this.MaximizeBox = false;
+      this.MinimizeBox = false;
+      this.Name = "GoToLineDialog";
+      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
+      this.Text = "Go To Line";
+      this.Load += new System.EventHandler(this.GoToLineDialog_Load);
+      ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit();
+      this.ResumeLayout(false);
+      this.PerformLayout();
+
+    }
+
+    #endregion
+
+    private System.Windows.Forms.Button cancelButton;
+    private System.Windows.Forms.Button okButton;
+    private System.Windows.Forms.Label lineNumberLabel;
+    private System.Windows.Forms.TextBox lineNumberTextBox;
+    private System.Windows.Forms.ErrorProvider errorProvider;
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/GoToLineDialog.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/GoToLineDialog.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/GoToLineDialog.cs	(revision 11807)
@@ -0,0 +1,59 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Windows.Forms;
+using ICSharpCode.AvalonEdit;
+
+namespace HeuristicLab.CodeEditor {
+  internal partial class GoToLineDialog : Form {
+    private readonly TextEditor textEditor;
+    private readonly int lowerLimit, upperLimit;
+
+    public int Line { get; set; }
+
+    public GoToLineDialog(TextEditor textEditor) {
+      InitializeComponent();
+      this.textEditor = textEditor;
+      lowerLimit = 1;
+      upperLimit = textEditor.LineCount;
+      lineNumberLabel.Text = string.Format("Line Number ({0}-{1}):", lowerLimit, upperLimit);
+    }
+
+    private void GoToLineDialog_Load(object sender, EventArgs e) {
+      var caret = textEditor.TextArea.Caret;
+      lineNumberTextBox.Text = caret.Line.ToString();
+      lineNumberTextBox.SelectAll();
+    }
+
+    private void lineNumberTextBox_TextChanged(object sender, EventArgs e) {
+      int line;
+      if (!int.TryParse(lineNumberTextBox.Text, out line) || line < lowerLimit || line > upperLimit) {
+        errorProvider.SetError(lineNumberTextBox, string.Format("Value must be an integer in the range [{0},{1}].", lowerLimit, upperLimit));
+        okButton.Enabled = false;
+      } else {
+        errorProvider.SetError(lineNumberTextBox, null);
+        okButton.Enabled = true;
+      }
+      Line = line;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/HeuristicLab.CodeEditor-3.4.csproj
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/HeuristicLab.CodeEditor-3.4.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/HeuristicLab.CodeEditor-3.4.csproj	(revision 11807)
@@ -0,0 +1,252 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{C38691AE-ECB4-489A-A05D-B035554E0168}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.CodeEditor</RootNamespace>
+    <AssemblyName>HeuristicLab.CodeEditor-3.4</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <DocumentationFile>
+    </DocumentationFile>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <DocumentationFile>
+    </DocumentationFile>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <DocumentationFile>
+    </DocumentationFile>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="ICSharpCode.AvalonEdit, Version=5.0.1.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\bin\ICSharpCode.AvalonEdit.dll</HintPath>
+      <Private>False</Private>
+    </Reference>
+    <Reference Include="ICSharpCode.NRefactory, Version=5.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\bin\ICSharpCode.NRefactory.dll</HintPath>
+      <Private>False</Private>
+    </Reference>
+    <Reference Include="ICSharpCode.NRefactory.Cecil, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\bin\ICSharpCode.NRefactory.Cecil.dll</HintPath>
+      <Private>False</Private>
+    </Reference>
+    <Reference Include="ICSharpCode.NRefactory.CSharp, Version=5.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\bin\ICSharpCode.NRefactory.CSharp.dll</HintPath>
+      <Private>False</Private>
+    </Reference>
+    <Reference Include="ICSharpCode.NRefactory.Xml, Version=5.0.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\bin\ICSharpCode.NRefactory.Xml.dll</HintPath>
+      <Private>False</Private>
+    </Reference>
+    <Reference Include="PresentationCore" />
+    <Reference Include="PresentationFramework" />
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Windows.Forms" />
+    <Reference Include="System.Xaml" />
+    <Reference Include="System.Xml" />
+    <Reference Include="WindowsBase" />
+    <Reference Include="WindowsFormsIntegration" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="AssemblyLoader.cs" />
+    <Compile Include="CodeViewer.cs">
+      <SubType>Form</SubType>
+    </Compile>
+    <Compile Include="CodeViewer.Designer.cs">
+      <DependentUpon>CodeViewer.cs</DependentUpon>
+    </Compile>
+    <Compile Include="GoToLineDialog.cs">
+      <SubType>Form</SubType>
+    </Compile>
+    <Compile Include="GoToLineDialog.Designer.cs">
+      <DependentUpon>GoToLineDialog.cs</DependentUpon>
+    </Compile>
+    <Compile Include="LanguageFeatures\CodeFolding\CodeFoldingResult.cs" />
+    <Compile Include="LanguageFeatures\CodeFolding\CodeFoldingStrategy.cs" />
+    <Compile Include="LanguageFeatures\CodeFolding\CSharp\CSharpCodeFoldingContext.cs" />
+    <Compile Include="LanguageFeatures\CodeFolding\CSharp\CSharpCodeFoldingStrategy.cs" />
+    <Compile Include="LanguageFeatures\CodeFolding\CSharp\FoldingVisitor.cs" />
+    <Compile Include="LanguageFeatures\CodeFolding\XML\XmlCodeFoldingStrategy.cs" />
+    <Compile Include="ITextMarker.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CodeCompletionResult.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CodeCompletionStrategy.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\CompletionImage.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpInsightItem.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpOverloadProvider.cs" />
+    <Compile Include="LanguageFeatures\Interfaces\IUpdatableOverloadProvider.cs" />
+    <Compile Include="LanguageFeatures\Interfaces\ICodeCompletionStrategy.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\CodeCompletionData.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpCodeCompletionStrategy.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpDocumentationBuilder.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpCodeCompletionContext.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpCodeCompletionDataFactory.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CSharpCodeCompletionHelpers.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\EntityCompletionData.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\ImportCompletionData.cs" />
+    <Compile Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\VariableCompletionData.cs" />
+    <Compile Include="LanguageFeatures\Interfaces\ICodeFoldingStrategy.cs" />
+    <Compile Include="LanguageFeatures\LanguageFeatures.cs" />
+    <Compile Include="MethodDefinitionReadOnlySectionProvider.cs" />
+    <Compile Include="TextMarkerService.cs" />
+    <Compile Include="LanguageFeatures\XmlLanguageFeatures.cs" />
+    <None Include="HeuristicLab.snk" />
+    <None Include="Properties\AssemblyInfo.cs.frame" />
+    <None Include="Plugin.cs.frame" />
+    <Compile Include="CodeEditor.cs">
+      <SubType>UserControl</SubType>
+    </Compile>
+    <Compile Include="CodeEditor.Designer.cs">
+      <DependentUpon>CodeEditor.cs</DependentUpon>
+    </Compile>
+    <Compile Include="AvalonEditWrapper.xaml.cs">
+      <DependentUpon>AvalonEditWrapper.xaml</DependentUpon>
+    </Compile>
+    <Compile Include="LanguageFeatures\CSharpLanguageFeatures.cs" />
+    <Compile Include="LanguageFeatures\Interfaces\ILanguageFeatures.cs" />
+    <Compile Include="Plugin.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\HeuristicLab.Common.Resources\3.3\HeuristicLab.Common.Resources-3.3.csproj">
+      <Project>{0e27a536-1c4a-4624-a65e-dc4f4f23e3e1}</Project>
+      <Name>HeuristicLab.Common.Resources-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.Common\3.3\HeuristicLab.Common-3.3.csproj">
+      <Project>{a9ad58b9-3ef9-4cc1-97e5-8d909039ff5c}</Project>
+      <Name>HeuristicLab.Common-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\..\HeuristicLab.PluginInfrastructure\3.3\HeuristicLab.PluginInfrastructure-3.3.csproj">
+      <Project>{94186a6a-5176-4402-ae83-886557b53cca}</Project>
+      <Name>HeuristicLab.PluginInfrastructure-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <Page Include="AvalonEditWrapper.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
+  </ItemGroup>
+  <ItemGroup>
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Class.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Constructor.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Delegate.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Enum.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\EnumValue.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Event.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\ExtensionMethod.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Field.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\FieldReadOnly.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Indexer.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Interface.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Literal.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Method.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\NameSpace.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Operator.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\OverlayInternal.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\OverlayPrivate.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\OverlayProtected.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\OverlayProtectedInternal.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\OverlayStatic.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\PInvokeMethod.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Property.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\StaticClass.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Struct.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\Template.png" />
+    <Resource Include="LanguageFeatures\CodeCompletion\CSharp\CompletionData\Images\VirtualMethod.png" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd
+</PreBuildEvent>
+  </PropertyGroup>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/ITextMarker.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/ITextMarker.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/ITextMarker.cs	(revision 11807)
@@ -0,0 +1,185 @@
+﻿#region License Information
+// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using System.Windows.Media;
+
+namespace ICSharpCode.SharpDevelop.Editor {
+  /// <summary>
+  /// Represents a text marker.
+  /// </summary>
+  public interface ITextMarker {
+    /// <summary>
+    /// Gets the start offset of the marked text region.
+    /// </summary>
+    int StartOffset { get; }
+
+    /// <summary>
+    /// Gets the end offset of the marked text region.
+    /// </summary>
+    int EndOffset { get; }
+
+    /// <summary>
+    /// Gets the length of the marked region.
+    /// </summary>
+    int Length { get; }
+
+    /// <summary>
+    /// Deletes the text marker.
+    /// </summary>
+    void Delete();
+
+    /// <summary>
+    /// Gets whether the text marker was deleted.
+    /// </summary>
+    bool IsDeleted { get; }
+
+    /// <summary>
+    /// Event that occurs when the text marker is deleted.
+    /// </summary>
+    event EventHandler Deleted;
+
+    /// <summary>
+    /// Gets/Sets the background color.
+    /// </summary>
+    Color? BackgroundColor { get; set; }
+
+    /// <summary>
+    /// Gets/Sets the foreground color.
+    /// </summary>
+    Color? ForegroundColor { get; set; }
+
+    /// <summary>
+    /// Gets/Sets the font weight.
+    /// </summary>
+    FontWeight? FontWeight { get; set; }
+
+    /// <summary>
+    /// Gets/Sets the font style.
+    /// </summary>
+    FontStyle? FontStyle { get; set; }
+
+    /// <summary>
+    /// Gets/Sets the type of the marker. Use TextMarkerType.None for normal markers.
+    /// </summary>
+    TextMarkerTypes MarkerTypes { get; set; }
+
+    /// <summary>
+    /// Gets/Sets the color of the marker.
+    /// </summary>
+    Color MarkerColor { get; set; }
+
+    /// <summary>
+    /// Gets/Sets an object with additional data for this text marker.
+    /// </summary>
+    object Tag { get; set; }
+
+    /// <summary>
+    /// Gets/Sets an object that will be displayed as tooltip in the text editor.
+    /// </summary>
+    object ToolTip { get; set; }
+  }
+
+  [Flags]
+  public enum TextMarkerTypes {
+    /// <summary>
+    /// Use no marker
+    /// </summary>
+    None = 0x0000,
+    /// <summary>
+    /// Use squiggly underline marker
+    /// </summary>
+    SquigglyUnderline = 0x001,
+    /// <summary>
+    /// Normal underline.
+    /// </summary>
+    NormalUnderline = 0x002,
+    /// <summary>
+    /// Dotted underline.
+    /// </summary>
+    DottedUnderline = 0x004,
+
+    /// <summary>
+    /// Horizontal line in the scroll bar.
+    /// </summary>
+    LineInScrollBar = 0x0100,
+    /// <summary>
+    /// Small triangle in the scroll bar, pointing to the right.
+    /// </summary>
+    ScrollBarRightTriangle = 0x0400,
+    /// <summary>
+    /// Small triangle in the scroll bar, pointing to the left.
+    /// </summary>
+    ScrollBarLeftTriangle = 0x0800,
+    /// <summary>
+    /// Small circle in the scroll bar.
+    /// </summary>
+    CircleInScrollBar = 0x1000
+  }
+
+  public interface ITextMarkerService {
+    /// <summary>
+    /// Creates a new text marker. The text marker will be invisible at first,
+    /// you need to set one of the Color properties to make it visible.
+    /// </summary>
+    ITextMarker Create(int startOffset, int length);
+
+    /// <summary>
+    /// Gets the list of text markers.
+    /// </summary>
+    IEnumerable<ITextMarker> TextMarkers { get; }
+
+    /// <summary>
+    /// Removes the specified text marker.
+    /// </summary>
+    void Remove(ITextMarker marker);
+
+    /// <summary>
+    /// Removes all text markers that match the condition.
+    /// </summary>
+    void RemoveAll(Predicate<ITextMarker> predicate);
+
+    /// <summary>
+    /// Finds all text markers at the specified offset.
+    /// </summary>
+    IEnumerable<ITextMarker> GetMarkersAtOffset(int offset);
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CSharpLanguageFeatures.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CSharpLanguageFeatures.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CSharpLanguageFeatures.cs	(revision 11807)
@@ -0,0 +1,28 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpLanguageFeatures : LanguageFeatures {
+    public CSharpLanguageFeatures(CodeEditor codeEditor)
+      : base(codeEditor, new CSharpCodeFoldingStrategy(codeEditor), new CSharpCodeCompletionStrategy(codeEditor)) {
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionContext.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using ICSharpCode.NRefactory.CSharp.Completion;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpCodeCompletionContext {
+    private readonly IDocument document;
+    public IDocument Document { get { return document; } }
+
+    private readonly int offset;
+    public int Offset { get { return offset; } }
+
+    private readonly IProjectContent projectContent;
+    public IProjectContent ProjectContent { get { return projectContent; } }
+
+    private readonly CSharpTypeResolveContext typeResolveContextAtCaret;
+    public CSharpTypeResolveContext TypeResolveContextAtCaret { get { return typeResolveContextAtCaret; } }
+
+    private readonly ICompletionContextProvider completionContextProvider;
+    public ICompletionContextProvider CompletionContextProvider { get { return completionContextProvider; } }
+
+    public CSharpCodeCompletionContext(IDocument document, int offset, IProjectContent projectContent) {
+      this.document = new ReadOnlyDocument(document, document.FileName);
+      this.offset = offset;
+
+      var unresolvedFile = CSharpCodeCompletionHelpers.CreateCSharpUnresolvedFile(this.document);
+      this.projectContent = projectContent.AddOrUpdateFiles(unresolvedFile);
+
+      completionContextProvider = new DefaultCompletionContextProvider(this.document, unresolvedFile);
+
+      var compilation = this.projectContent.CreateCompilation();
+      var location = this.document.GetLocation(this.offset);
+      typeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(compilation, location);
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionDataFactory.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionDataFactory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionDataFactory.cs	(revision 11807)
@@ -0,0 +1,152 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.AvalonEdit.CodeCompletion;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp.Completion;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICompletionData = ICSharpCode.NRefactory.Completion.ICompletionData;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpCodeCompletionDataFactory : ICompletionDataFactory, IParameterCompletionDataFactory {
+    private readonly CSharpCodeCompletionContext context;
+
+    public CSharpCodeCompletionDataFactory(CSharpCodeCompletionContext context) {
+      this.context = context;
+    }
+
+    #region ICompletionDataFactory Members
+    public ICompletionData CreateEntityCompletionData(IEntity entity) {
+      return new EntityCompletionData(entity);
+    }
+
+    public ICompletionData CreateEntityCompletionData(IEntity entity, string text) {
+      return new EntityCompletionData(entity) { CompletionText = text, DisplayText = text };
+    }
+
+    public ICompletionData CreateTypeCompletionData(IType type, bool fullName, bool isInAttributeContext, bool addForTypeCreation) {
+      var typeDef = type.GetDefinition();
+      if (typeDef != null) { return new EntityCompletionData(typeDef); }
+
+      string name = fullName ? type.FullName : type.Name;
+      if (isInAttributeContext && name.EndsWith("Attribute", StringComparison.Ordinal) && name.Length > "Attribute".Length) {
+        name = name.Substring(0, name.Length - "Attribute".Length);
+      }
+      return new CompletionData(name);
+    }
+
+    public ICompletionData CreateMemberCompletionData(IType type, IEntity member) {
+      return new EntityCompletionData(member);
+    }
+
+    public ICompletionData CreateLiteralCompletionData(string title, string description = null, string insertText = null) {
+      return new CompletionData(title) {
+        Description = description,
+        CompletionText = insertText ?? title,
+        Image = CompletionImage.Literal.BaseImage,
+        Priority = 2
+      };
+    }
+
+    public ICompletionData CreateXmlDocCompletionData(string title, string description = null, string insertText = null) {
+      return new CompletionData(title) {
+        Description = description,
+        CompletionText = insertText ?? title,
+        Image = CompletionImage.Template.BaseImage,
+      };
+    }
+
+    public ICompletionData CreateNamespaceCompletionData(INamespace ns) {
+      return new CompletionData(ns.Name) { Image = CompletionImage.NamespaceImage };
+    }
+
+    public ICompletionData CreateVariableCompletionData(IVariable variable) {
+      return new VariableCompletionData(variable);
+    }
+
+    public ICompletionData CreateVariableCompletionData(ITypeParameter parameter) {
+      return new CompletionData(parameter.Name);
+    }
+
+    public ICompletionData CreateEventCreationCompletionData(string varName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType) {
+      return new CompletionData(varName);
+    }
+
+    public ICompletionData CreateNewOverrideCompletionData(int declarationBegin, IUnresolvedTypeDefinition type, IMember m) {
+      return new CompletionData(m.Name);
+    }
+
+    public ICompletionData CreateNewPartialCompletionData(int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m) {
+      return new CompletionData(m.Name);
+    }
+
+    public ICompletionData CreateImportCompletionData(IType type, bool useFullName, bool addForTypeCreation) {
+      var typeDef = type.GetDefinition();
+      return new ImportCompletionData(typeDef, context.TypeResolveContextAtCaret, useFullName);
+    }
+
+    public IEnumerable<ICompletionData> CreateCodeTemplateCompletionData() {
+      yield break;
+    }
+
+    public ICompletionData CreateFormatItemCompletionData(string format, string description, object example) {
+      return null;
+    }
+
+    public IEnumerable<ICompletionData> CreatePreProcessorDefinesCompletionData() {
+      yield break;
+    }
+    #endregion
+
+    #region IParameterCompletionDataFactory Members
+    public IParameterDataProvider CreateConstructorProvider(int startOffset, IType type, ICSharpCode.NRefactory.CSharp.AstNode thisInitializer) {
+      return CreateMethodDataProvider(startOffset, type.GetConstructors());
+    }
+
+    public IParameterDataProvider CreateConstructorProvider(int startOffset, IType type) {
+      return CreateMethodDataProvider(startOffset, type.GetConstructors());
+    }
+
+    public IParameterDataProvider CreateDelegateDataProvider(int startOffset, IType type) {
+      return CreateMethodDataProvider(startOffset, new[] { type.GetDelegateInvokeMethod() });
+    }
+
+    public IParameterDataProvider CreateIndexerParameterDataProvider(int startOffset, IType type, IEnumerable<IProperty> accessibleIndexers, ICSharpCode.NRefactory.CSharp.AstNode resolvedNode) {
+      return null;
+    }
+
+    public IParameterDataProvider CreateMethodDataProvider(int startOffset, IEnumerable<IMethod> methods) {
+      return new CSharpOverloadProvider(context, startOffset, from m in methods where m != null select new CSharpInsightItem(m));
+    }
+
+    public IParameterDataProvider CreateTypeParameterDataProvider(int startOffset, IEnumerable<IMethod> methods) {
+      return CreateMethodDataProvider(startOffset, methods);
+    }
+
+    public IParameterDataProvider CreateTypeParameterDataProvider(int startOffset, IEnumerable<IType> types) {
+      return null;
+    }
+    #endregion
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionHelpers.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionHelpers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionHelpers.cs	(revision 11807)
@@ -0,0 +1,35 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Editor;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpCodeCompletionHelpers {
+    public static CSharpUnresolvedFile CreateCSharpUnresolvedFile(IDocument document) {
+      var parser = new CSharpParser();
+      var syntaxTree = parser.Parse(document, document.FileName);
+      syntaxTree.Freeze();
+      return syntaxTree.ToTypeSystem();
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpCodeCompletionStrategy.cs	(revision 11807)
@@ -0,0 +1,125 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.CSharp.Completion;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpCodeCompletionStrategy : CodeCompletionStrategy {
+    private IProjectContent projectContent = new CSharpProjectContent();
+
+    public CSharpCodeCompletionStrategy(CodeEditor codeEditor)
+      : base(codeEditor) {
+      codeEditor.InternalAssembliesLoaded += (sender, args) => {
+        projectContent = projectContent.AddAssemblyReferences(args.Value);
+      };
+      codeEditor.InternalAssembliesUnloaded += (sender, args) => {
+        projectContent = projectContent.RemoveAssemblyReferences(args.Value);
+      };
+    }
+
+    protected override CodeCompletionResult GetCodeCompletionResult(bool controlSpace) {
+      var document = codeEditor.TextEditor.Document;
+      int offset = codeEditor.TextEditor.CaretOffset;
+
+      var result = new CodeCompletionResult();
+      var completionContext = new CSharpCodeCompletionContext(document, offset, projectContent);
+      var completionFactory = new CSharpCodeCompletionDataFactory(completionContext);
+      var cce = new CSharpCompletionEngine(
+        completionContext.Document,
+        completionContext.CompletionContextProvider,
+        completionFactory,
+        completionContext.ProjectContent,
+        completionContext.TypeResolveContextAtCaret
+      ) { EolMarker = Environment.NewLine };
+
+      char completionChar = completionContext.Document.GetCharAt(completionContext.Offset - 1);
+      int startPos, triggerWordLength;
+      IEnumerable<ICompletionData> completionData;
+
+      if (controlSpace) {
+        if (!cce.TryGetCompletionWord(completionContext.Offset, out startPos, out triggerWordLength)) {
+          startPos = completionContext.Offset;
+          triggerWordLength = 0;
+        }
+        completionData = cce.GetCompletionData(startPos, true);
+      } else {
+        startPos = completionContext.Offset;
+        if (char.IsLetterOrDigit(completionChar) || completionChar == '_') {
+          if (startPos > 1 && char.IsLetterOrDigit(completionContext.Document.GetCharAt((startPos - 2))))
+            return result;
+          completionData = cce.GetCompletionData(startPos, false);
+          triggerWordLength = 1;
+        } else {
+          completionData = cce.GetCompletionData(startPos, false);
+          triggerWordLength = 0;
+        }
+      }
+
+      result.TriggerWordLength = triggerWordLength;
+      result.TriggerWord = completionContext.Document.GetText(completionContext.Offset - triggerWordLength, triggerWordLength);
+
+      if (completionData.Any() && cce.AutoCompleteEmptyMatch) {
+        foreach (var completion in completionData) {
+          var cast = completion as CompletionData;
+          if (cast != null) {
+            cast.TriggerWord = result.TriggerWord;
+            cast.TriggerWordLength = result.TriggerWordLength;
+            result.CompletionData.Add(cast);
+          }
+        }
+      }
+
+      if (!controlSpace) {
+        var pce = new CSharpParameterCompletionEngine(
+          completionContext.Document,
+          completionContext.CompletionContextProvider,
+          completionFactory,
+          completionContext.ProjectContent,
+          completionContext.TypeResolveContextAtCaret
+        );
+
+        var parameterDataProvider = pce.GetParameterDataProvider(completionContext.Offset, completionChar);
+        result.OverloadProvider = parameterDataProvider as IUpdatableOverloadProvider;
+      }
+
+      return result;
+    }
+
+    protected override void DoParseStep() {
+      var document = (IDocument)codeEditor.Invoke(
+        (Func<IDocument>)(() => {
+          var doc = codeEditor.TextEditor.Document;
+          return new ReadOnlyDocument(doc, doc.FileName);
+        })
+      );
+
+      var unresolvedFile = CSharpCodeCompletionHelpers.CreateCSharpUnresolvedFile(document);
+      projectContent = projectContent.AddOrUpdateFiles(unresolvedFile);
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpDocumentationBuilder.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpDocumentationBuilder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpDocumentationBuilder.cs	(revision 11807)
@@ -0,0 +1,510 @@
+﻿#region License Information
+// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+/* HeuristicLab
+ * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Highlighting;
+using ICSharpCode.AvalonEdit.Utils;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Xml;
+
+namespace HeuristicLab.CodeEditor {
+  /// <summary>
+  /// Builds a FlowDocument for XML documentation.
+  /// </summary>
+  public class CSharpDocumentationBuilder {
+    const string SyntaxHighlighting = "C#";
+    const string FontFamily = "Consolas";
+    const double FontSize = 13.0;
+    const string MsdnLibraryUrl = "http://msdn.microsoft.com/library/";
+    readonly FlowDocument flowDocument;
+    readonly IAmbience ambience;
+    BlockCollection blockCollection;
+    InlineCollection inlineCollection;
+
+    public CSharpDocumentationBuilder(IAmbience ambience) {
+      this.ambience = ambience;
+      this.flowDocument = new FlowDocument();
+      this.blockCollection = flowDocument.Blocks;
+
+      this.ShowSummary = true;
+      this.ShowAllParameters = true;
+      this.ShowReturns = true;
+      this.ShowThreadSafety = true;
+      this.ShowExceptions = true;
+      this.ShowTypeParameters = true;
+
+      this.ShowExample = true;
+      this.ShowPreliminary = true;
+      this.ShowSeeAlso = true;
+      this.ShowValue = true;
+      this.ShowPermissions = true;
+      this.ShowRemarks = true;
+    }
+
+    public FlowDocument CreateFlowDocument() {
+      FlushAddedText(true);
+      flowDocument.FontSize = FontSize;
+      return flowDocument;
+    }
+
+    public bool ShowExceptions { get; set; }
+    public bool ShowPermissions { get; set; }
+    public bool ShowExample { get; set; }
+    public bool ShowPreliminary { get; set; }
+    public bool ShowRemarks { get; set; }
+    public bool ShowSummary { get; set; }
+    public bool ShowReturns { get; set; }
+    public bool ShowSeeAlso { get; set; }
+    public bool ShowThreadSafety { get; set; }
+    public bool ShowTypeParameters { get; set; }
+    public bool ShowValue { get; set; }
+    public bool ShowAllParameters { get; set; }
+
+    /// <summary>
+    /// Gets/Sets the name of the parameter that should be shown.
+    /// </summary>
+    public string ParameterName { get; set; }
+
+    public void AddDocumentationElement(XmlDocumentationElement element) {
+      if (element == null)
+        throw new ArgumentNullException("element");
+      if (element.IsTextNode) {
+        AddText(element.TextContent);
+        return;
+      }
+      switch (element.Name) {
+        case "b":
+          AddSpan(new Bold(), element.Children);
+          break;
+        case "i":
+          AddSpan(new Italic(), element.Children);
+          break;
+        case "c":
+          AddSpan(new Span { FontFamily = GetCodeFont() }, element.Children);
+          break;
+        case "code":
+          AddCodeBlock(element.TextContent);
+          break;
+        case "example":
+          if (ShowExample)
+            AddSection("Example: ", element.Children);
+          break;
+        case "exception":
+          if (ShowExceptions)
+            AddException(element.ReferencedEntity, element.Children);
+          break;
+        case "list":
+          AddList(element.GetAttribute("type"), element.Children);
+          break;
+        //case "note":
+        //	throw new NotImplementedException();
+        case "para":
+          AddParagraph(new Paragraph { Margin = new Thickness(0, 5, 0, 5) }, element.Children);
+          break;
+        case "param":
+          if (ShowAllParameters || (ParameterName != null && ParameterName == element.GetAttribute("name")))
+            AddParam(element.GetAttribute("name"), element.Children);
+          break;
+        case "paramref":
+          AddParamRef(element.GetAttribute("name"));
+          break;
+        case "permission":
+          if (ShowPermissions)
+            AddPermission(element.ReferencedEntity, element.Children);
+          break;
+        case "preliminary":
+          if (ShowPreliminary)
+            AddPreliminary(element.Children);
+          break;
+        case "remarks":
+          if (ShowRemarks)
+            AddSection("Remarks: ", element.Children);
+          break;
+        case "returns":
+          if (ShowReturns)
+            AddSection("Returns: ", element.Children);
+          break;
+        case "see":
+          AddSee(element);
+          break;
+        case "seealso":
+          if (inlineCollection != null)
+            AddSee(element);
+          else if (ShowSeeAlso)
+            AddSection(new Run("See also: "), () => AddSee(element));
+          break;
+        case "summary":
+          if (ShowSummary)
+            AddSection("Summary: ", element.Children);
+          break;
+        case "threadsafety":
+          if (ShowThreadSafety)
+            AddThreadSafety(ParseBool(element.GetAttribute("static")), ParseBool(element.GetAttribute("instance")), element.Children);
+          break;
+        case "typeparam":
+          if (ShowTypeParameters)
+            AddSection("Type parameter " + element.GetAttribute("name") + ": ", element.Children);
+          break;
+        case "typeparamref":
+          AddText(element.GetAttribute("name"));
+          break;
+        case "value":
+          if (ShowValue)
+            AddSection("Value: ", element.Children);
+          break;
+        case "exclude":
+        case "filterpriority":
+        case "overloads":
+          // ignore children
+          break;
+        case "br":
+          AddLineBreak();
+          break;
+        default:
+          foreach (var child in element.Children)
+            AddDocumentationElement(child);
+          break;
+      }
+    }
+
+    void AddList(string type, IEnumerable<XmlDocumentationElement> items) {
+      List list = new List();
+      AddBlock(list);
+      list.Margin = new Thickness(0, 5, 0, 5);
+      if (type == "number")
+        list.MarkerStyle = TextMarkerStyle.Decimal;
+      else if (type == "bullet")
+        list.MarkerStyle = TextMarkerStyle.Disc;
+      var oldBlockCollection = blockCollection;
+      try {
+        foreach (var itemElement in items) {
+          if (itemElement.Name == "listheader" || itemElement.Name == "item") {
+            ListItem item = new ListItem();
+            blockCollection = item.Blocks;
+            inlineCollection = null;
+            foreach (var prop in itemElement.Children) {
+              AddDocumentationElement(prop);
+            }
+            FlushAddedText(false);
+            list.ListItems.Add(item);
+          }
+        }
+      } finally {
+        blockCollection = oldBlockCollection;
+      }
+    }
+
+    public void AddCodeBlock(string textContent, bool keepLargeMargin = false) {
+      var document = new ReadOnlyDocument(textContent);
+      var highlightingDefinition = HighlightingManager.Instance.GetDefinition(SyntaxHighlighting);
+
+      var block = DocumentPrinter.ConvertTextDocumentToBlock(document, highlightingDefinition);
+      block.FontFamily = GetCodeFont();
+      if (!keepLargeMargin)
+        block.Margin = new Thickness(0, 6, 0, 6);
+      AddBlock(block);
+    }
+
+    public void AddSignatureBlock(string signature, int currentParameterOffset, int currentParameterLength, string currentParameterName) {
+      ParameterName = currentParameterName;
+      var document = new ReadOnlyDocument(signature);
+      var highlightingDefinition = HighlightingManager.Instance.GetDefinition(SyntaxHighlighting);
+
+      var richText = DocumentPrinter.ConvertTextDocumentToRichText(document, highlightingDefinition).ToRichTextModel();
+      richText.SetFontWeight(currentParameterOffset, currentParameterLength, FontWeights.Bold);
+      var block = new Paragraph();
+      block.Inlines.AddRange(richText.CreateRuns(document));
+      block.FontFamily = GetCodeFont();
+      block.TextAlignment = TextAlignment.Left;
+      AddBlock(block);
+    }
+
+    bool? ParseBool(string input) {
+      bool result;
+      if (bool.TryParse(input, out result))
+        return result;
+      else
+        return null;
+    }
+
+    void AddThreadSafety(bool? staticThreadSafe, bool? instanceThreadSafe, IEnumerable<XmlDocumentationElement> children) {
+      AddSection(
+        new Run("Thread-safety: "),
+        delegate {
+          if (staticThreadSafe == true)
+            AddText("Any public static members of this type are thread safe. ");
+          else if (staticThreadSafe == false)
+            AddText("The static members of this type are not thread safe. ");
+
+          if (instanceThreadSafe == true)
+            AddText("Any public instance members of this type are thread safe. ");
+          else if (instanceThreadSafe == false)
+            AddText("Any instance members are not guaranteed to be thread safe. ");
+
+          foreach (var child in children)
+            AddDocumentationElement(child);
+        });
+    }
+
+    FontFamily GetCodeFont() {
+      return new FontFamily(FontFamily);
+    }
+
+    void AddException(IEntity referencedEntity, IList<XmlDocumentationElement> children) {
+      Span span = new Span();
+      if (referencedEntity != null)
+        span.Inlines.Add(ConvertReference(referencedEntity));
+      else
+        span.Inlines.Add("Exception");
+      span.Inlines.Add(": ");
+      AddSection(span, children);
+    }
+
+
+    void AddPermission(IEntity referencedEntity, IList<XmlDocumentationElement> children) {
+      Span span = new Span();
+      span.Inlines.Add("Permission");
+      if (referencedEntity != null) {
+        span.Inlines.Add(" ");
+        span.Inlines.Add(ConvertReference(referencedEntity));
+      }
+      span.Inlines.Add(": ");
+      AddSection(span, children);
+    }
+
+    Inline ConvertReference(IEntity referencedEntity) {
+      var h = new Hyperlink(new Run(ambience.ConvertSymbol(referencedEntity)));
+      h.Click += CreateNavigateOnClickHandler(referencedEntity);
+      return h;
+    }
+
+    void AddParam(string name, IEnumerable<XmlDocumentationElement> children) {
+      Span span = new Span();
+      span.Inlines.Add(new Run(name ?? string.Empty) { FontStyle = FontStyles.Italic });
+      span.Inlines.Add(": ");
+      AddSection(span, children);
+    }
+
+    void AddParamRef(string name) {
+      if (name != null) {
+        AddInline(new Run(name) { FontStyle = FontStyles.Italic });
+      }
+    }
+
+    void AddPreliminary(IEnumerable<XmlDocumentationElement> children) {
+      if (children.Any()) {
+        foreach (var child in children)
+          AddDocumentationElement(child);
+      } else {
+        AddText("[This is preliminary documentation and subject to change.]");
+      }
+    }
+
+    void AddSee(XmlDocumentationElement element) {
+      IEntity referencedEntity = element.ReferencedEntity;
+      if (referencedEntity != null) {
+        if (element.Children.Any()) {
+          Hyperlink link = new Hyperlink();
+          link.Click += CreateNavigateOnClickHandler(referencedEntity);
+          AddSpan(link, element.Children);
+        } else {
+          AddInline(ConvertReference(referencedEntity));
+        }
+      } else if (element.GetAttribute("langword") != null) {
+        AddInline(new Run(element.GetAttribute("langword")) { FontFamily = GetCodeFont() });
+      } else if (element.GetAttribute("href") != null) {
+        Uri uri;
+        if (Uri.TryCreate(element.GetAttribute("href"), UriKind.Absolute, out uri)) {
+          if (element.Children.Any()) {
+            AddSpan(new Hyperlink { NavigateUri = uri }, element.Children);
+          } else {
+            AddInline(new Hyperlink(new Run(element.GetAttribute("href"))) { NavigateUri = uri });
+          }
+        }
+      } else {
+        // Invalid reference: print the cref value
+        AddText(element.GetAttribute("cref"));
+      }
+    }
+
+    RoutedEventHandler CreateNavigateOnClickHandler(IEntity referencedEntity) {
+      return delegate(object sender, RoutedEventArgs e) {
+        Process.Start(MsdnLibraryUrl + referencedEntity.FullName);
+        e.Handled = true;
+      };
+    }
+
+    void AddSection(string title, IEnumerable<XmlDocumentationElement> children) {
+      AddSection(new Run(title), children);
+    }
+
+    void AddSection(Inline title, IEnumerable<XmlDocumentationElement> children) {
+      AddSection(
+        title, delegate {
+        foreach (var child in children)
+          AddDocumentationElement(child);
+      });
+    }
+
+    void AddSection(Inline title, Action addChildren) {
+      var section = new Section();
+      AddBlock(section);
+      var oldBlockCollection = blockCollection;
+      try {
+        blockCollection = section.Blocks;
+        inlineCollection = null;
+
+        if (title != null)
+          AddInline(new Bold(title));
+
+        addChildren();
+        FlushAddedText(false);
+      } finally {
+        blockCollection = oldBlockCollection;
+        inlineCollection = null;
+      }
+    }
+
+    void AddParagraph(Paragraph para, IEnumerable<XmlDocumentationElement> children) {
+      AddBlock(para);
+      try {
+        inlineCollection = para.Inlines;
+
+        foreach (var child in children)
+          AddDocumentationElement(child);
+        FlushAddedText(false);
+      } finally {
+        inlineCollection = null;
+      }
+    }
+
+    void AddSpan(Span span, IEnumerable<XmlDocumentationElement> children) {
+      AddInline(span);
+      var oldInlineCollection = inlineCollection;
+      try {
+        inlineCollection = span.Inlines;
+        foreach (var child in children)
+          AddDocumentationElement(child);
+        FlushAddedText(false);
+      } finally {
+        inlineCollection = oldInlineCollection;
+      }
+    }
+
+    public void AddInline(Inline inline) {
+      FlushAddedText(false);
+      if (inlineCollection == null) {
+        var para = new Paragraph();
+        para.Margin = new Thickness(0, 0, 0, 5);
+        inlineCollection = para.Inlines;
+        AddBlock(para);
+      }
+      inlineCollection.Add(inline);
+      ignoreWhitespace = false;
+    }
+
+    public void AddBlock(Block block) {
+      FlushAddedText(true);
+      blockCollection.Add(block);
+    }
+
+    StringBuilder addedText = new StringBuilder();
+    bool ignoreWhitespace;
+
+    public void AddLineBreak() {
+      TrimEndOfAddedText();
+      addedText.AppendLine();
+      ignoreWhitespace = true;
+    }
+
+    public void AddText(string textContent) {
+      if (string.IsNullOrEmpty(textContent))
+        return;
+      for (int i = 0; i < textContent.Length; i++) {
+        char c = textContent[i];
+        if (c == '\n' && IsEmptyLineBefore(textContent, i)) {
+          AddLineBreak(); // empty line -> line break
+        } else if (char.IsWhiteSpace(c)) {
+          // any whitespace sequence gets converted to a single space (like HTML)
+          if (!ignoreWhitespace) {
+            addedText.Append(' ');
+            ignoreWhitespace = true;
+          }
+        } else {
+          addedText.Append(c);
+          ignoreWhitespace = false;
+        }
+      }
+    }
+
+    bool IsEmptyLineBefore(string text, int i) {
+      // Skip previous whitespace
+      do {
+        i--;
+      } while (i >= 0 && (text[i] == ' ' || text[i] == '\r'));
+      // Check if previous non-whitespace char is \n
+      return i >= 0 && text[i] == '\n';
+    }
+
+    void TrimEndOfAddedText() {
+      while (addedText.Length > 0 && addedText[addedText.Length - 1] == ' ') {
+        addedText.Length--;
+      }
+    }
+
+    void FlushAddedText(bool trim) {
+      if (trim) // trim end of current text element
+        TrimEndOfAddedText();
+      if (addedText.Length == 0)
+        return;
+      string text = addedText.ToString();
+      addedText.Length = 0;
+      AddInline(new Run(text));
+      ignoreWhitespace = trim; // trim start of next text element
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpInsightItem.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpInsightItem.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpInsightItem.cs	(revision 11807)
@@ -0,0 +1,158 @@
+﻿#region License Information
+// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+/* HeuristicLab
+ * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.IO;
+using System.Text;
+using System.Windows;
+using System.Windows.Controls;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Xml;
+
+namespace HeuristicLab.CodeEditor {
+  sealed class CSharpInsightItem {
+    public readonly IParameterizedMember Method;
+
+    public CSharpInsightItem(IParameterizedMember method) {
+      this.Method = method;
+    }
+
+    FlowDocumentScrollViewer header;
+
+    public object Header {
+      get {
+        if (header == null) {
+          header = GenerateHeader();
+        }
+        return header;
+      }
+    }
+
+    int highlightedParameterIndex = -1;
+
+    public void HighlightParameter(int parameterIndex) {
+      if (highlightedParameterIndex == parameterIndex)
+        return;
+      this.highlightedParameterIndex = parameterIndex;
+      if (header != null)
+        header = GenerateHeader();
+    }
+
+    FlowDocumentScrollViewer GenerateHeader() {
+      var ambience = new CSharpAmbience();
+      ambience.ConversionFlags = ConversionFlags.StandardConversionFlags;
+      var stringBuilder = new StringBuilder();
+      var formatter = new ParameterHighlightingOutputFormatter(stringBuilder, highlightedParameterIndex);
+      ambience.ConvertSymbol(Method, formatter, FormattingOptionsFactory.CreateSharpDevelop());
+
+      var documentation = XmlDocumentationElement.Get(Method);
+      ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;
+
+      var b = new CSharpDocumentationBuilder(ambience);
+      string parameterName = null;
+      if (Method.Parameters.Count > highlightedParameterIndex)
+        parameterName = Method.Parameters[highlightedParameterIndex].Name;
+      b.AddSignatureBlock(stringBuilder.ToString(), formatter.parameterStartOffset, formatter.parameterLength, parameterName);
+
+      var b2 = new CSharpDocumentationBuilder(ambience);
+      b2.ParameterName = parameterName;
+      b2.ShowAllParameters = false;
+
+      if (documentation != null) {
+        foreach (var child in documentation.Children) {
+          b2.AddDocumentationElement(child);
+        }
+      }
+
+      content = new FlowDocumentScrollViewer {
+        Document = b2.CreateFlowDocument(),
+        VerticalScrollBarVisibility = ScrollBarVisibility.Auto
+      };
+
+      var flowDocument = b.CreateFlowDocument();
+      flowDocument.PagePadding = new Thickness(0); // default is NOT Thickness(0), but Thickness(Auto), which adds unnecessary space
+
+      return new FlowDocumentScrollViewer {
+        Document = flowDocument,
+        VerticalScrollBarVisibility = ScrollBarVisibility.Auto
+      };
+    }
+
+    FlowDocumentScrollViewer content;
+
+    public object Content {
+      get {
+        if (content == null) {
+          GenerateHeader();
+        }
+        return content;
+      }
+    }
+
+    sealed class ParameterHighlightingOutputFormatter : TextWriterTokenWriter {
+      StringBuilder b;
+      int highlightedParameterIndex;
+      int parameterIndex;
+      internal int parameterStartOffset;
+      internal int parameterLength;
+
+      public ParameterHighlightingOutputFormatter(StringBuilder b, int highlightedParameterIndex)
+        : base(new StringWriter(b)) {
+        this.b = b;
+        this.highlightedParameterIndex = highlightedParameterIndex;
+      }
+
+      public override void StartNode(AstNode node) {
+        if (parameterIndex == highlightedParameterIndex && node is ParameterDeclaration) {
+          parameterStartOffset = b.Length;
+        }
+        base.StartNode(node);
+      }
+
+      public override void EndNode(AstNode node) {
+        base.EndNode(node);
+        if (node is ParameterDeclaration) {
+          if (parameterIndex == highlightedParameterIndex)
+            parameterLength = b.Length - parameterStartOffset;
+          parameterIndex++;
+        }
+      }
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpOverloadProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpOverloadProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CSharpOverloadProvider.cs	(revision 11807)
@@ -0,0 +1,172 @@
+﻿#region License Information
+// CShell, A Simple C# Scripting IDE
+// Copyright (C) 2013  Arnova Asset Management Ltd., Lukas Buhler
+// 
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+// 
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+// 
+// You should have received a copy of the GNU General Public License
+// along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+// This file is based on code from the SharpDevelop project:
+//   Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \Doc\sharpdevelop-copyright.txt)
+//   This code is distributed under the GNU LGPL (for details please see \Doc\COPYING.LESSER.txt)
+
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp.Completion;
+using ICSharpCode.NRefactory.Editor;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpOverloadProvider : IUpdatableOverloadProvider, IParameterDataProvider {
+    private readonly CSharpCodeCompletionContext context;
+    private readonly int startOffset;
+    internal readonly IList<CSharpInsightItem> items;
+    private int selectedIndex;
+
+    public CSharpOverloadProvider(CSharpCodeCompletionContext context, int startOffset, IEnumerable<CSharpInsightItem> items) {
+      Debug.Assert(items != null);
+      this.context = context;
+      this.startOffset = startOffset;
+      this.selectedIndex = 0;
+      this.items = items.ToList();
+
+      Update(context);
+    }
+
+    public bool RequestClose { get; set; }
+
+    public int Count {
+      get { return items.Count; }
+    }
+
+    public object CurrentContent {
+      get { return items[selectedIndex].Content; }
+    }
+
+    public object CurrentHeader {
+      get { return items[selectedIndex].Header; }
+    }
+
+    public string CurrentIndexText {
+      get { return (selectedIndex + 1).ToString() + " of " + this.Count.ToString(); }
+    }
+
+    public int SelectedIndex {
+      get { return selectedIndex; }
+      set {
+        selectedIndex = value;
+        if (selectedIndex >= items.Count)
+          selectedIndex = items.Count - 1;
+        if (selectedIndex < 0)
+          selectedIndex = 0;
+        OnPropertyChanged("SelectedIndex");
+        OnPropertyChanged("CurrentIndexText");
+        OnPropertyChanged("CurrentHeader");
+        OnPropertyChanged("CurrentContent");
+      }
+    }
+
+    public void Update(IDocument document, int offset) {
+      var completionContext = new CSharpCodeCompletionContext(document, offset, context.ProjectContent);
+      Update(completionContext);
+    }
+
+    public void Update(CSharpCodeCompletionContext completionContext) {
+      var completionFactory = new CSharpCodeCompletionDataFactory(completionContext);
+      var pce = new CSharpParameterCompletionEngine(
+          completionContext.Document,
+          completionContext.CompletionContextProvider,
+          completionFactory,
+          completionContext.ProjectContent,
+          completionContext.TypeResolveContextAtCaret
+      );
+
+      int parameterIndex = pce.GetCurrentParameterIndex(startOffset, completionContext.Offset);
+      if (parameterIndex < 0) {
+        RequestClose = true;
+        return;
+      } else {
+        if (parameterIndex > items[selectedIndex].Method.Parameters.Count) {
+          var newItem = items.FirstOrDefault(i => parameterIndex <= i.Method.Parameters.Count);
+          SelectedIndex = items.IndexOf(newItem);
+        }
+        if (parameterIndex > 0)
+          parameterIndex--; // NR returns 1-based parameter index
+        foreach (var item in items) {
+          item.HighlightParameter(parameterIndex);
+        }
+      }
+    }
+
+    #region IParameterDataProvider implementation
+    int IParameterDataProvider.StartOffset {
+      get { return startOffset; }
+    }
+
+    string IParameterDataProvider.GetHeading(int overload, string[] parameterDescription, int currentParameter) {
+      throw new NotImplementedException();
+    }
+
+    string IParameterDataProvider.GetDescription(int overload, int currentParameter) {
+      throw new NotImplementedException();
+    }
+
+    string IParameterDataProvider.GetParameterDescription(int overload, int paramIndex) {
+      throw new NotImplementedException();
+    }
+
+    string IParameterDataProvider.GetParameterName(int overload, int currentParameter) {
+      throw new NotImplementedException();
+    }
+
+    int IParameterDataProvider.GetParameterCount(int overload) {
+      throw new NotImplementedException();
+    }
+
+    bool IParameterDataProvider.AllowParameterList(int overload) {
+      throw new NotImplementedException();
+    }
+    #endregion
+
+
+    public event PropertyChangedEventHandler PropertyChanged;
+
+    private void OnPropertyChanged(string propertyName) {
+      var args = new PropertyChangedEventArgs(propertyName);
+      if (PropertyChanged != null)
+        PropertyChanged(this, args);
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/CodeCompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/CodeCompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/CodeCompletionData.cs	(revision 11807)
@@ -0,0 +1,90 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.NRefactory.Editor;
+using ACC = ICSharpCode.AvalonEdit.CodeCompletion;
+using NCC = ICSharpCode.NRefactory.Completion;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CompletionData : NCC.ICompletionData, ACC.ICompletionData {
+    public string TriggerWord { get; set; }
+    public int TriggerWordLength { get; set; }
+
+    #region Constructors
+    protected CompletionData() { }
+
+    public CompletionData(string text) {
+      DisplayText = CompletionText = Description = text;
+    }
+    #endregion
+
+    #region ICSharpCode.NRefactory.Completion.ICompletionData Members
+    public NCC.CompletionCategory CompletionCategory { get; set; }
+    public string DisplayText { get; set; }
+    public virtual string Description { get; set; }
+    public string CompletionText { get; set; }
+    public NCC.DisplayFlags DisplayFlags { get; set; }
+    public bool HasOverloads { get { return overloadedData.Count > 0; } }
+
+    private readonly List<NCC.ICompletionData> overloadedData = new List<NCC.ICompletionData>();
+    public IEnumerable<NCC.ICompletionData> OverloadedData {
+      get { return overloadedData; }
+      set { throw new InvalidOperationException(); }
+    }
+
+    public void AddOverload(NCC.ICompletionData data) {
+      if (overloadedData.Count == 0)
+        overloadedData.Add(this);
+      overloadedData.Add(data);
+    }
+    #endregion
+
+    #region ICSharpCode.AvalonEdit.CodeCompletion.ICompletionData Members
+    public object Content { get { return DisplayText; } }
+
+    object fancyDescription;
+    object ACC.ICompletionData.Description {
+      get {
+        if (fancyDescription == null) {
+          fancyDescription = CreateFancyDescription();
+        }
+        return fancyDescription;
+      }
+    }
+
+    public virtual ImageSource Image { get; set; }
+    public double Priority { get; set; }
+    public string Text { get { return CompletionText; } }
+
+    public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) {
+      textArea.Document.Replace(completionSegment, CompletionText);
+    }
+    #endregion
+
+    protected virtual object CreateFancyDescription() {
+      return Description;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/EntityCompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/EntityCompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/EntityCompletionData.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using ICSharpCode.AvalonEdit.CodeCompletion;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Xml;
+
+namespace HeuristicLab.CodeEditor {
+  internal class EntityCompletionData : CompletionData, IEntityCompletionData {
+    private static readonly CSharpAmbience Ambience = new CSharpAmbience();
+
+    #region IEntityCompletionData Members
+    public IEntity Entity { get; private set; }
+    #endregion
+
+    public EntityCompletionData(IEntity entity)
+      : base() {
+      if (entity == null) throw new ArgumentException("entity");
+
+      Entity = entity;
+      Ambience.ConversionFlags = entity is ITypeDefinition ? ConversionFlags.ShowTypeParameterList : ConversionFlags.None;
+      CompletionText = DisplayText = entity.Name;
+      Image = CompletionImage.GetImage(entity);
+    }
+
+    protected override object CreateFancyDescription() {
+      var ambience = new CSharpAmbience();
+      ambience.ConversionFlags = ConversionFlags.StandardConversionFlags | ConversionFlags.ShowDeclaringType;
+      string header = ambience.ConvertSymbol(Entity);
+      var documentation = XmlDocumentationElement.Get(Entity);
+
+      ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;
+      var b = new CSharpDocumentationBuilder(ambience);
+      b.AddCodeBlock(header, keepLargeMargin: true);
+      if (documentation != null) {
+        foreach (var child in documentation.Children) {
+          b.AddDocumentationElement(child);
+        }
+      }
+
+      var flowDocument = b.CreateFlowDocument();
+      flowDocument.PagePadding = new Thickness(0); // default is NOT Thickness(0), but Thickness(Auto), which adds unnecessary space
+
+      return new FlowDocumentScrollViewer {
+        Document = flowDocument,
+        VerticalScrollBarVisibility = ScrollBarVisibility.Auto
+      };
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/Images/CompletionImage.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/Images/CompletionImage.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/Images/CompletionImage.cs	(revision 11807)
@@ -0,0 +1,370 @@
+﻿#region License Information
+// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
+// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
+
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Threading;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion {
+  /// <summary>
+  /// Provides icons for code-completion.
+  /// </summary>
+  public class CompletionImage {
+    #region Non-Entity Images
+    static readonly BitmapImage namespaceImage = LoadBitmap("NameSpace");
+
+    /// <summary>
+    /// Gets the image for namespaces.
+    /// </summary>
+    public static ImageSource NamespaceImage {
+      get { return namespaceImage; }
+    }
+
+    static BitmapImage LoadBitmap(string name) {
+      BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/HeuristicLab.CodeEditor-3.4;component/LanguageFeatures/CodeCompletion/CSharp/CompletionData/Images/" + name + ".png"));
+      image.Freeze();
+      return image;
+    }
+    #endregion
+
+    #region Entity Images
+    static readonly CompletionImage imageClass = new CompletionImage("Class", false);
+    static readonly CompletionImage imageStruct = new CompletionImage("Struct", false);
+    static readonly CompletionImage imageInterface = new CompletionImage("Interface", false);
+    static readonly CompletionImage imageDelegate = new CompletionImage("Delegate", false);
+    static readonly CompletionImage imageEnum = new CompletionImage("Enum", false);
+    static readonly CompletionImage imageStaticClass = new CompletionImage("StaticClass", false);
+
+    /// <summary>Gets the image used for non-static classes.</summary>
+    public static CompletionImage Class { get { return imageClass; } }
+
+    /// <summary>Gets the image used for structs.</summary>
+    public static CompletionImage Struct { get { return imageStruct; } }
+
+    /// <summary>Gets the image used for interfaces.</summary>
+    public static CompletionImage Interface { get { return imageInterface; } }
+
+    /// <summary>Gets the image used for delegates.</summary>
+    public static CompletionImage Delegate { get { return imageDelegate; } }
+
+    /// <summary>Gets the image used for enums.</summary>
+    public static CompletionImage Enum { get { return imageEnum; } }
+
+    /// <summary>Gets the image used for modules/static classes.</summary>
+    public static CompletionImage StaticClass { get { return imageStaticClass; } }
+
+    static readonly CompletionImage imageField = new CompletionImage("Field", true);
+    static readonly CompletionImage imageFieldReadOnly = new CompletionImage("FieldReadOnly", true);
+    static readonly CompletionImage imageLiteral = new CompletionImage("Literal", false);
+    static readonly CompletionImage imageEnumValue = new CompletionImage("EnumValue", false);
+    static readonly CompletionImage imageTemplate = new CompletionImage("Template", false);
+
+    /// <summary>Gets the image used for non-static classes.</summary>
+    public static CompletionImage Field { get { return imageField; } }
+
+    /// <summary>Gets the image used for structs.</summary>
+    public static CompletionImage ReadOnlyField { get { return imageFieldReadOnly; } }
+
+    /// <summary>Gets the image used for constants.</summary>
+    public static CompletionImage Literal { get { return imageLiteral; } }
+
+    /// <summary>Gets the image used for enum values.</summary>
+    public static CompletionImage EnumValue { get { return imageEnumValue; } }
+
+    /// <summary>Gets the image used for templates.</summary>
+    public static CompletionImage Template { get { return imageTemplate; } }
+
+    static readonly CompletionImage imageMethod = new CompletionImage("Method", true);
+    static readonly CompletionImage imageConstructor = new CompletionImage("Constructor", true);
+    static readonly CompletionImage imageVirtualMethod = new CompletionImage("VirtualMethod", true);
+    static readonly CompletionImage imageOperator = new CompletionImage("Operator", false);
+    static readonly CompletionImage imageExtensionMethod = new CompletionImage("ExtensionMethod", true);
+    static readonly CompletionImage imagePInvokeMethod = new CompletionImage("PInvokeMethod", true);
+    static readonly CompletionImage imageProperty = new CompletionImage("Property", true);
+    static readonly CompletionImage imageIndexer = new CompletionImage("Indexer", true);
+    static readonly CompletionImage imageEvent = new CompletionImage("Event", true);
+
+    /// <summary>Gets the image used for methods.</summary>
+    public static CompletionImage Method { get { return imageMethod; } }
+
+    /// <summary>Gets the image used for constructos.</summary>
+    public static CompletionImage Constructor { get { return imageConstructor; } }
+
+    /// <summary>Gets the image used for virtual methods.</summary>
+    public static CompletionImage VirtualMethod { get { return imageVirtualMethod; } }
+
+    /// <summary>Gets the image used for operators.</summary>
+    public static CompletionImage Operator { get { return imageOperator; } }
+
+    /// <summary>Gets the image used for extension methods.</summary>
+    public static CompletionImage ExtensionMethod { get { return imageExtensionMethod; } }
+
+    /// <summary>Gets the image used for P/Invoke methods.</summary>
+    public static CompletionImage PInvokeMethod { get { return imagePInvokeMethod; } }
+
+    /// <summary>Gets the image used for properties.</summary>
+    public static CompletionImage Property { get { return imageProperty; } }
+
+    /// <summary>Gets the image used for indexers.</summary>
+    public static CompletionImage Indexer { get { return imageIndexer; } }
+
+    /// <summary>Gets the image used for events.</summary>
+    public static CompletionImage Event { get { return imageEvent; } }
+
+    /// <summary>
+    /// Gets the CompletionImage instance for the specified entity.
+    /// Returns null when no image is available for the entity type.
+    /// </summary>
+    public static CompletionImage GetCompletionImage(IEntity entity) {
+      if (entity == null)
+        throw new ArgumentNullException("entity");
+      switch (entity.SymbolKind) {
+        case SymbolKind.TypeDefinition:
+          return GetCompletionImageForType(((ITypeDefinition)entity).Kind, entity.IsStatic);
+        case SymbolKind.Field:
+          IField field = (IField)entity;
+          if (field.IsConst) {
+            if (field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Kind == TypeKind.Enum)
+              return imageEnumValue;
+            else
+              return imageLiteral;
+          }
+          return field.IsReadOnly ? imageFieldReadOnly : imageField;
+        case SymbolKind.Method:
+          IMethod method = (IMethod)entity;
+          if (method.IsExtensionMethod)
+            return imageExtensionMethod;
+          else
+            return method.IsOverridable ? imageVirtualMethod : imageMethod;
+        case SymbolKind.Property:
+          return imageProperty;
+        case SymbolKind.Indexer:
+          return imageIndexer;
+        case SymbolKind.Event:
+          return imageEvent;
+        case SymbolKind.Operator:
+        case SymbolKind.Destructor:
+          return imageOperator;
+        case SymbolKind.Constructor:
+          return imageConstructor;
+        default:
+          return null;
+      }
+    }
+
+    /// <summary>
+    /// Gets the CompletionImage instance for the specified entity.
+    /// Returns null when no image is available for the entity type.
+    /// </summary>
+    public static CompletionImage GetCompletionImage(IUnresolvedEntity entity) {
+      if (entity == null)
+        throw new ArgumentNullException("entity");
+      switch (entity.SymbolKind) {
+        case SymbolKind.TypeDefinition:
+          return GetCompletionImageForType(((IUnresolvedTypeDefinition)entity).Kind, entity.IsStatic);
+        case SymbolKind.Field:
+          IUnresolvedField field = (IUnresolvedField)entity;
+          if (field.IsConst) {
+            if (field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Kind == TypeKind.Enum)
+              return imageEnumValue;
+            else
+              return imageLiteral;
+          }
+          return field.IsReadOnly ? imageFieldReadOnly : imageField;
+        case SymbolKind.Method:
+          IUnresolvedMethod method = (IUnresolvedMethod)entity;
+          return method.IsOverridable ? imageVirtualMethod : imageMethod;
+        case SymbolKind.Property:
+          return imageProperty;
+        case SymbolKind.Indexer:
+          return imageIndexer;
+        case SymbolKind.Event:
+          return imageEvent;
+        case SymbolKind.Operator:
+        case SymbolKind.Destructor:
+          return imageOperator;
+        case SymbolKind.Constructor:
+          return imageConstructor;
+        default:
+          return null;
+      }
+    }
+
+    static CompletionImage GetCompletionImageForType(TypeKind typeKind, bool isStatic) {
+      switch (typeKind) {
+        case TypeKind.Interface:
+          return imageInterface;
+        case TypeKind.Struct:
+        case TypeKind.Void:
+          return imageStruct;
+        case TypeKind.Delegate:
+          return imageDelegate;
+        case TypeKind.Enum:
+          return imageEnum;
+        case TypeKind.Class:
+          return isStatic ? imageStaticClass : imageClass;
+        case TypeKind.Module:
+          return imageStaticClass;
+        default:
+          return null;
+      }
+    }
+
+    /// <summary>
+    /// Gets the image for the specified entity.
+    /// Returns null when no image is available for the entity type.
+    /// </summary>
+    public static ImageSource GetImage(IEntity entity) {
+      CompletionImage image = GetCompletionImage(entity);
+      if (image != null)
+        return image.GetImage(entity.Accessibility, entity.IsStatic);
+      else
+        return null;
+    }
+
+    /// <summary>
+    /// Gets the image for the specified entity.
+    /// Returns null when no image is available for the entity type.
+    /// </summary>
+    public static ImageSource GetImage(IUnresolvedEntity entity) {
+      CompletionImage image = GetCompletionImage(entity);
+      if (image != null)
+        return image.GetImage(entity.Accessibility, entity.IsStatic);
+      else
+        return null;
+    }
+    #endregion
+
+    #region Overlays
+    static readonly BitmapImage overlayStatic = LoadBitmap("OverlayStatic");
+
+    /// <summary>
+    /// Gets the overlay image for the static modifier.
+    /// </summary>
+    public ImageSource StaticOverlay { get { return overlayStatic; } }
+
+    const int AccessibilityOverlaysLength = 5;
+
+    static readonly BitmapImage[] accessibilityOverlays = new BitmapImage[AccessibilityOverlaysLength] {
+      null,
+      LoadBitmap("OverlayPrivate"),
+      LoadBitmap("OverlayProtected"),
+      LoadBitmap("OverlayInternal"),
+      LoadBitmap("OverlayProtectedInternal")
+    };
+
+    /// <summary>
+    /// Gets an overlay image for the specified accessibility.
+    /// Returns null if no overlay exists (for example, public members don't use overlays).
+    /// </summary>
+    public static ImageSource GetAccessibilityOverlay(Accessibility accessibility) {
+      return accessibilityOverlays[GetAccessibilityOverlayIndex(accessibility)];
+    }
+
+    static int GetAccessibilityOverlayIndex(Accessibility accessibility) {
+      switch (accessibility) {
+        case Accessibility.Private:
+          return 1;
+        case Accessibility.Protected:
+          return 2;
+        case Accessibility.Internal:
+          return 3;
+        case Accessibility.ProtectedOrInternal:
+        case Accessibility.ProtectedAndInternal:
+          return 4;
+        default:
+          return 0;
+      }
+    }
+    #endregion
+
+    #region Instance Members (add overlay to entity image)
+    readonly string imageName;
+    readonly bool showStaticOverlay;
+
+    private CompletionImage(string imageName, bool showStaticOverlay) {
+      this.imageName = imageName;
+      this.showStaticOverlay = showStaticOverlay;
+    }
+
+    ImageSource[] images = new ImageSource[2 * AccessibilityOverlaysLength];
+    // 0..N-1  = base image + accessibility overlay
+    // N..2N-1 = base image + static overlay + accessibility overlay
+
+    /// <summary>
+    /// Gets the image without any overlays.
+    /// </summary>
+    public ImageSource BaseImage {
+      get {
+        ImageSource image = images[0];
+        if (image == null) {
+          image = LoadBitmap(imageName);
+          Thread.MemoryBarrier();
+          images[0] = image;
+        }
+        return image;
+      }
+    }
+
+    /// <summary>
+    /// Gets this image combined with the specified accessibility overlay.
+    /// </summary>
+    public ImageSource GetImage(Accessibility accessibility, bool isStatic = false) {
+      int accessibilityIndex = GetAccessibilityOverlayIndex(accessibility);
+      int index;
+      if (isStatic && showStaticOverlay)
+        index = accessibilityOverlays.Length + accessibilityIndex;
+      else
+        index = accessibilityIndex;
+
+      if (index == 0)
+        return this.BaseImage;
+
+      ImageSource image = images[index];
+      if (image == null) {
+        DrawingGroup g = new DrawingGroup();
+        Rect iconRect = new Rect(0, 0, 16, 16);
+        g.Children.Add(new ImageDrawing(this.BaseImage, iconRect));
+
+        if (accessibilityOverlays[accessibilityIndex] != null)
+          g.Children.Add(new ImageDrawing(accessibilityOverlays[accessibilityIndex], iconRect));
+
+        image = new DrawingImage(g);
+        image.Freeze();
+        Thread.MemoryBarrier();
+        images[index] = image;
+      }
+      return image;
+    }
+
+    /// <inheritdoc/>
+    public override string ToString() {
+      return "[CompletionImage " + imageName + "]";
+    }
+    #endregion
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/ImportCompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/ImportCompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/ImportCompletionData.cs	(revision 11807)
@@ -0,0 +1,40 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace HeuristicLab.CodeEditor {
+  internal class ImportCompletionData : EntityCompletionData {
+    public ImportCompletionData(ITypeDefinition typeDefinition, CSharpTypeResolveContext contextAtCaret, bool useFullName)
+      : base(typeDefinition) {
+      Description = string.Format("using {0};", typeDefinition.Namespace);
+      if (useFullName) {
+        var builder = new TypeSystemAstBuilder(new CSharpResolver(contextAtCaret));
+        CompletionText = builder.ConvertType(typeDefinition).ToString();
+      } else {
+        CompletionText = typeDefinition.Namespace;
+      }
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/VariableCompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/VariableCompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CSharp/CompletionData/VariableCompletionData.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using ICSharpCode.AvalonEdit.CodeCompletion;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace HeuristicLab.CodeEditor {
+  internal class VariableCompletionData : CompletionData, IVariableCompletionData {
+    private static readonly CSharpAmbience Ambience = new CSharpAmbience();
+
+    #region IVariableCompletionData Members
+    public IVariable Variable { get; private set; }
+    #endregion
+
+    public VariableCompletionData(IVariable variable)
+      : base() {
+      if (variable == null) throw new ArgumentException("variable");
+
+      Variable = variable;
+      Ambience.ConversionFlags = ConversionFlags.StandardConversionFlags;
+      DisplayText = CompletionText = variable.Name;
+      Description = Ambience.ConvertVariable(variable);
+      Image = CompletionImage.Field.BaseImage;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CodeCompletionResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CodeCompletionResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CodeCompletionResult.cs	(revision 11807)
@@ -0,0 +1,36 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.CodeCompletion;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CodeCompletionResult {
+    public IList<ICompletionData> CompletionData { get; set; }
+    public int TriggerWordLength { get; set; }
+    public string TriggerWord { get; set; }
+    public IOverloadProvider OverloadProvider { get; set; }
+
+    public CodeCompletionResult() {
+      CompletionData = new List<ICompletionData>();
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CodeCompletionStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CodeCompletionStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeCompletion/CodeCompletionStrategy.cs	(revision 11807)
@@ -0,0 +1,97 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ICSharpCode.AvalonEdit.CodeCompletion;
+
+namespace HeuristicLab.CodeEditor {
+  internal abstract class CodeCompletionStrategy : ICodeCompletionStrategy {
+    protected readonly CodeEditor codeEditor;
+    protected readonly Task backgroundParser;
+
+    protected CodeCompletionStrategy(CodeEditor codeEditor) {
+      this.codeEditor = codeEditor;
+      backgroundParser = new Task(DoBackgroundParsing);
+    }
+
+    public virtual void DoCodeCompletion(bool controlSpace) {
+      var codeCompletionResult = GetCodeCompletionResult(controlSpace);
+      ApplyCodeCompletionData(codeCompletionResult);
+    }
+
+    public virtual void RunBackgroundParser() {
+      backgroundParser.Start();
+    }
+
+    protected abstract CodeCompletionResult GetCodeCompletionResult(bool controlSpace);
+    protected abstract void DoParseStep();
+
+    protected virtual void ApplyCodeCompletionData(CodeCompletionResult codeCompletionResult) {
+      var textArea = codeEditor.TextEditor.TextArea;
+      var document = codeEditor.TextEditor.Document;
+      int offset = codeEditor.TextEditor.CaretOffset;
+
+      if (codeEditor.OverloadInsightWindow == null && codeCompletionResult.OverloadProvider != null) {
+        var iw = codeEditor.OverloadInsightWindow = new OverloadInsightWindow(textArea);
+        iw.Provider = codeCompletionResult.OverloadProvider;
+        iw.Show();
+        iw.Closed += (sender, args) => codeEditor.OverloadInsightWindow = null;
+      }
+
+      if (codeEditor.CompletionWindow == null && codeCompletionResult.CompletionData.Any()) {
+        var cw = codeEditor.CompletionWindow = new CompletionWindow(textArea);
+        cw.CloseWhenCaretAtBeginning = true;
+        cw.StartOffset -= codeCompletionResult.TriggerWordLength;
+        cw.Closed += (sender, args) => codeEditor.CompletionWindow = null;
+
+        var data = cw.CompletionList.CompletionData;
+        var newData = codeCompletionResult.CompletionData.OrderBy(x => x.Text).ToArray();
+        foreach (var completion in newData)
+          data.Add(completion);
+
+        if (codeCompletionResult.TriggerWordLength > 0)
+          cw.CompletionList.SelectItem(codeCompletionResult.TriggerWord);
+
+        cw.Show();
+      }
+
+      if (codeEditor.OverloadInsightWindow != null) {
+        var iw = codeEditor.OverloadInsightWindow;
+        var provider = iw.Provider as IUpdatableOverloadProvider;
+        if (provider != null) {
+          provider.Update(document, offset);
+          if (provider.RequestClose) {
+            iw.Close();
+          }
+        }
+      }
+    }
+
+    protected virtual void DoBackgroundParsing() {
+      while (!codeEditor.IsDisposed) {
+        DoParseStep();
+        Thread.Sleep(1000);
+      }
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/CSharpCodeFoldingContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/CSharpCodeFoldingContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/CSharpCodeFoldingContext.cs	(revision 11807)
@@ -0,0 +1,40 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.Editor;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpCodeFoldingContext {
+    public readonly IDocument Document;
+    public readonly SyntaxTree SyntaxTree;
+
+    public CSharpCodeFoldingContext(IDocument document) {
+      Document = new ReadOnlyDocument(document, document.FileName);
+
+      var parser = new CSharpParser();
+      var syntaxTree = parser.Parse(document, document.FileName);
+      syntaxTree.Freeze();
+
+      SyntaxTree = syntaxTree;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/CSharpCodeFoldingStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/CSharpCodeFoldingStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/CSharpCodeFoldingStrategy.cs	(revision 11807)
@@ -0,0 +1,59 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Linq;
+using CSharpBinding.Parser;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CSharpCodeFoldingStrategy : CodeFoldingStrategy {
+    private IProjectContent projectContent = new CSharpProjectContent();
+
+    public CSharpCodeFoldingStrategy(CodeEditor codeEditor)
+      : base(codeEditor) {
+      codeEditor.InternalAssembliesLoaded += (sender, args) => {
+        projectContent = projectContent.AddAssemblyReferences(args.Value);
+      };
+      codeEditor.InternalAssembliesUnloaded += (sender, args) => {
+        projectContent = projectContent.RemoveAssemblyReferences(args.Value);
+      };
+    }
+
+    protected override CodeFoldingResult GetCodeFoldingResult(out int firstErrorOffset) {
+      var document = codeEditor.TextEditor.Document;
+      var result = new CodeFoldingResult();
+
+      var foldingContext = new CSharpCodeFoldingContext(document);
+      var v = new FoldingVisitor();
+      v.document = foldingContext.Document;
+      foldingContext.SyntaxTree.AcceptVisitor(v);
+      result.FoldingData = v.foldings.OrderBy(x => x.StartOffset).ToList();
+
+      var firstError = foldingContext.SyntaxTree.Errors.FirstOrDefault();
+      firstErrorOffset = firstError != null
+        ? foldingContext.Document.GetOffset(firstError.Region.Begin)
+        : int.MaxValue;
+
+      return result;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/FoldingVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/FoldingVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CSharp/FoldingVisitor.cs	(revision 11807)
@@ -0,0 +1,252 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+using ICSharpCode.AvalonEdit.Folding;
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.Editor;
+
+namespace CSharpBinding.Parser
+{
+	// TODO: move this class + NewFolding to NRefactory
+	class FoldingVisitor : DepthFirstAstVisitor
+	{
+		internal List<NewFolding> foldings = new List<NewFolding> ();
+		internal IDocument document;
+		
+		int GetOffset(TextLocation location)
+		{
+			return document.GetOffset(location);
+		}
+		
+		NewFolding AddFolding(TextLocation start, TextLocation end, bool isDefinition = false)
+		{
+			if (end.Line <= start.Line || start.IsEmpty || end.IsEmpty)
+				return null;
+			NewFolding folding = new NewFolding(GetOffset(start), GetOffset(end));
+			folding.IsDefinition = isDefinition;
+			foldings.Add(folding);
+			return folding;
+		}
+		
+		TextLocation GetEndOfPrev(AstNode node)
+		{
+			do {
+				node = node.GetPrevNode();
+			} while (node.NodeType == NodeType.Whitespace);
+			return node.EndLocation;
+		}
+		
+		#region usings
+		void AddUsings (AstNode parent)
+		{
+			var firstChild = parent.Children.FirstOrDefault (child => child is UsingDeclaration || child is UsingAliasDeclaration);
+			var node = firstChild;
+			while (node != null) {
+				var next = node.GetNextNode ();
+				if (next is UsingDeclaration || next is UsingAliasDeclaration) {
+					node = next;
+				} else {
+					break;
+				}
+			}
+			if (firstChild != node) {
+				NewFolding folding = AddFolding(firstChild.StartLocation, node.EndLocation);
+				if (folding != null) {
+					folding.Name = "using...";
+					folding.DefaultClosed = true;
+				}
+			}
+		}
+		public override void VisitSyntaxTree (SyntaxTree unit)
+		{
+			AddUsings (unit);
+			base.VisitSyntaxTree (unit);
+		}
+
+		public override void VisitNamespaceDeclaration (NamespaceDeclaration namespaceDeclaration)
+		{
+			AddUsings (namespaceDeclaration);
+			if (!namespaceDeclaration.RBraceToken.IsNull)
+				AddFolding (namespaceDeclaration.LBraceToken.GetPrevNode ().EndLocation, namespaceDeclaration.RBraceToken.EndLocation);
+			base.VisitNamespaceDeclaration (namespaceDeclaration);
+		}
+		#endregion
+		
+		#region Entity Declarations
+		public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration)
+		{
+			if (!typeDeclaration.RBraceToken.IsNull)
+				AddFolding (GetEndOfPrev(typeDeclaration.LBraceToken), typeDeclaration.RBraceToken.EndLocation);
+			base.VisitTypeDeclaration (typeDeclaration);
+		}
+		
+		public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration)
+		{
+			if (!methodDeclaration.Body.IsNull) {
+				AddFolding (GetEndOfPrev(methodDeclaration.Body.LBraceToken),
+				            methodDeclaration.Body.RBraceToken.EndLocation, true);
+			}
+			base.VisitMethodDeclaration (methodDeclaration);
+		}
+		
+		public override void VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration)
+		{
+			if (!constructorDeclaration.Body.IsNull)
+				AddFolding (GetEndOfPrev(constructorDeclaration.Body.LBraceToken),
+				            constructorDeclaration.Body.RBraceToken.EndLocation, true);
+			base.VisitConstructorDeclaration (constructorDeclaration);
+		}
+		
+		public override void VisitDestructorDeclaration (DestructorDeclaration destructorDeclaration)
+		{
+			if (!destructorDeclaration.Body.IsNull)
+				AddFolding (GetEndOfPrev(destructorDeclaration.Body.LBraceToken),
+				            destructorDeclaration.Body.RBraceToken.EndLocation, true);
+			base.VisitDestructorDeclaration (destructorDeclaration);
+		}
+		
+		public override void VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration)
+		{
+			if (!operatorDeclaration.Body.IsNull)
+				AddFolding (GetEndOfPrev(operatorDeclaration.Body.LBraceToken),
+				            operatorDeclaration.Body.RBraceToken.EndLocation, true);
+			base.VisitOperatorDeclaration (operatorDeclaration);
+		}
+		
+		public override void VisitPropertyDeclaration (PropertyDeclaration propertyDeclaration)
+		{
+			if (!propertyDeclaration.LBraceToken.IsNull)
+				AddFolding (GetEndOfPrev(propertyDeclaration.LBraceToken),
+				            propertyDeclaration.RBraceToken.EndLocation, true);
+			base.VisitPropertyDeclaration (propertyDeclaration);
+		}
+		
+		public override void VisitIndexerDeclaration (IndexerDeclaration indexerDeclaration)
+		{
+			if (!indexerDeclaration.LBraceToken.IsNull)
+				AddFolding (GetEndOfPrev(indexerDeclaration.LBraceToken),
+				            indexerDeclaration.RBraceToken.EndLocation, true);
+			base.VisitIndexerDeclaration (indexerDeclaration);
+		}
+		
+		public override void VisitCustomEventDeclaration (CustomEventDeclaration eventDeclaration)
+		{
+			if (!eventDeclaration.LBraceToken.IsNull)
+				AddFolding (GetEndOfPrev(eventDeclaration.LBraceToken),
+				            eventDeclaration.RBraceToken.EndLocation, true);
+			base.VisitCustomEventDeclaration (eventDeclaration);
+		}
+		#endregion
+		
+		#region Statements
+		public override void VisitSwitchStatement (SwitchStatement switchStatement)
+		{
+			if (!switchStatement.RBraceToken.IsNull)
+				AddFolding (GetEndOfPrev(switchStatement.LBraceToken),
+				            switchStatement.RBraceToken.EndLocation);
+			base.VisitSwitchStatement (switchStatement);
+		}
+		
+		public override void VisitBlockStatement (BlockStatement blockStatement)
+		{
+			if (!(blockStatement.Parent is EntityDeclaration) && blockStatement.EndLocation.Line - blockStatement.StartLocation.Line > 2) {
+				AddFolding (GetEndOfPrev(blockStatement), blockStatement.EndLocation);
+			}
+
+			base.VisitBlockStatement (blockStatement);
+		}
+		#endregion
+		
+		#region Preprocessor directives
+		Stack<NewFolding> regions = new Stack<NewFolding>();
+		
+		public override void VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective)
+		{
+			switch (preProcessorDirective.Type) {
+				case PreProcessorDirectiveType.Region:
+					NewFolding folding = new NewFolding();
+					folding.DefaultClosed = true;
+					folding.Name = preProcessorDirective.Argument;
+					folding.StartOffset = GetOffset(preProcessorDirective.StartLocation);
+					regions.Push(folding);
+					break;
+				case PreProcessorDirectiveType.Endregion:
+					if (regions.Count > 0) {
+						folding = regions.Pop();
+						folding.EndOffset = GetOffset(preProcessorDirective.EndLocation);
+						foldings.Add(folding);
+					}
+					break;
+			}
+		}
+		#endregion
+		
+		#region Comments
+		public override void VisitComment(Comment comment)
+		{
+			if (comment.CommentType == CommentType.InactiveCode)
+				return; // don't fold the inactive code comment; instead fold the preprocessor directives
+			if (AreTwoSinglelineCommentsInConsecutiveLines(comment.PrevSibling as Comment, comment))
+				return; // already handled by previous comment
+			Comment lastComment = comment;
+			Comment nextComment;
+			while (true) {
+				nextComment = lastComment.NextSibling as Comment;
+				if (!AreTwoSinglelineCommentsInConsecutiveLines(lastComment, nextComment))
+					break;
+				lastComment = nextComment;
+			}
+			if (lastComment.EndLocation.Line - comment.StartLocation.Line > 2) {
+				var folding = AddFolding(comment.StartLocation, lastComment.EndLocation);
+				if (folding != null) {
+					switch (comment.CommentType) {
+						case CommentType.SingleLine:
+							folding.Name = "// ...";
+							break;
+						case CommentType.MultiLine:
+							folding.Name = "/* ... */";
+							break;
+						case CommentType.Documentation:
+							folding.Name = "/// ...";
+							break;
+						case CommentType.MultiLineDocumentation:
+							folding.Name = "/** ... */";
+							break;
+					}
+				}
+			}
+		}
+		
+		bool AreTwoSinglelineCommentsInConsecutiveLines(Comment comment1, Comment comment2)
+		{
+			if (comment1 == null || comment2 == null)
+				return false;
+			return comment1.CommentType == comment2.CommentType
+				&& comment1.StartLocation.Line == comment1.EndLocation.Line
+				&& comment1.EndLocation.Line + 1 == comment2.StartLocation.Line
+				&& comment1.StartLocation.Column == comment2.StartLocation.Column
+				&& comment2.StartLocation.Line == comment2.EndLocation.Line;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CodeFoldingResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CodeFoldingResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CodeFoldingResult.cs	(revision 11807)
@@ -0,0 +1,29 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Folding;
+
+namespace HeuristicLab.CodeEditor {
+  internal class CodeFoldingResult {
+    public List<NewFolding> FoldingData = new List<NewFolding>();
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CodeFoldingStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CodeFoldingStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/CodeFoldingStrategy.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using ICSharpCode.AvalonEdit.Folding;
+
+namespace HeuristicLab.CodeEditor {
+  internal abstract class CodeFoldingStrategy : ICodeFoldingStrategy {
+    protected readonly CodeEditor codeEditor;
+    protected readonly FoldingManager foldingManager;
+
+    protected CodeFoldingStrategy(CodeEditor codeEditor) {
+      this.codeEditor = codeEditor;
+      foldingManager = FoldingManager.Install(codeEditor.TextEditor.TextArea);
+    }
+
+    public virtual void DoCodeFolding() {
+      int firstErrorOffset;
+      var codeFoldingResult = GetCodeFoldingResult(out firstErrorOffset);
+      ApplyCodeFoldingData(codeFoldingResult, firstErrorOffset);
+    }
+
+    protected abstract CodeFoldingResult GetCodeFoldingResult(out int firstErrorOffset);
+
+    protected virtual void ApplyCodeFoldingData(CodeFoldingResult codeFoldingResult, int firstErrorOffset) {
+      var foldings = codeFoldingResult.FoldingData;
+      foldingManager.UpdateFoldings(foldings, firstErrorOffset);
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/XML/XmlCodeFoldingStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/XML/XmlCodeFoldingStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/CodeFolding/XML/XmlCodeFoldingStrategy.cs	(revision 11807)
@@ -0,0 +1,241 @@
+﻿#region License Information
+// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Xml;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Folding;
+
+namespace HeuristicLab.CodeEditor {
+  internal class XmlCodeFoldingStrategy : CodeFoldingStrategy {
+    /// <summary>
+    /// Holds information about the start of a fold in an xml string.
+    /// </summary>
+    sealed class XmlFoldStart : NewFolding {
+      internal int StartLine;
+    }
+
+    /// <summary>
+    /// Flag indicating whether attributes should be displayed on folded
+    /// elements.
+    /// </summary>
+    public bool ShowAttributesWhenFolded { get; set; }
+
+    public XmlCodeFoldingStrategy(CodeEditor codeEditor) : base(codeEditor) { }
+
+    protected override CodeFoldingResult GetCodeFoldingResult(out int firstErrorOffset) {
+      var document = codeEditor.TextEditor.Document;
+      var result = new CodeFoldingResult();
+
+      try {
+        var reader = new XmlTextReader(document.CreateReader()) { XmlResolver = null };
+        var foldings = CreateNewFoldings(document, reader, out firstErrorOffset);
+        result.FoldingData = foldings.ToList();
+      } catch (XmlException) {
+        firstErrorOffset = 0;
+        result.FoldingData = new List<NewFolding>();
+      }
+
+      return result;
+    }
+
+    /// <summary>
+    /// Create <see cref="NewFolding"/>s for the specified document.
+    /// </summary>
+    public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, XmlReader reader, out int firstErrorOffset) {
+      Stack<XmlFoldStart> stack = new Stack<XmlFoldStart>();
+      List<NewFolding> foldMarkers = new List<NewFolding>();
+      try {
+        while (reader.Read()) {
+          switch (reader.NodeType) {
+            case XmlNodeType.Element:
+              if (!reader.IsEmptyElement) {
+                XmlFoldStart newFoldStart = CreateElementFoldStart(document, reader);
+                stack.Push(newFoldStart);
+              }
+              break;
+
+            case XmlNodeType.EndElement:
+              XmlFoldStart foldStart = stack.Pop();
+              CreateElementFold(document, foldMarkers, reader, foldStart);
+              break;
+
+            case XmlNodeType.Comment:
+              CreateCommentFold(document, foldMarkers, reader);
+              break;
+          }
+        }
+        firstErrorOffset = -1;
+      } catch (XmlException ex) {
+        // ignore errors at invalid positions (prevent ArgumentOutOfRangeException)
+        if (ex.LineNumber >= 1 && ex.LineNumber <= document.LineCount)
+          firstErrorOffset = document.GetOffset(ex.LineNumber, ex.LinePosition);
+        else
+          firstErrorOffset = 0;
+      }
+      foldMarkers.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
+      return foldMarkers;
+    }
+
+    static int GetOffset(TextDocument document, XmlReader reader) {
+      IXmlLineInfo info = reader as IXmlLineInfo;
+      if (info != null && info.HasLineInfo()) {
+        return document.GetOffset(info.LineNumber, info.LinePosition);
+      } else {
+        throw new ArgumentException("XmlReader does not have positioning information.");
+      }
+    }
+
+    /// <summary>
+    /// Creates a comment fold if the comment spans more than one line.
+    /// </summary>
+    /// <remarks>The text displayed when the comment is folded is the first
+    /// line of the comment.</remarks>
+    static void CreateCommentFold(TextDocument document, List<NewFolding> foldMarkers, XmlReader reader) {
+      string comment = reader.Value;
+      if (comment != null) {
+        int firstNewLine = comment.IndexOf('\n');
+        if (firstNewLine >= 0) {
+
+          // Take off 4 chars to get the actual comment start (takes
+          // into account the <!-- chars.
+
+          int startOffset = GetOffset(document, reader) - 4;
+          int endOffset = startOffset + comment.Length + 7;
+
+          string foldText = String.Concat("<!--", comment.Substring(0, firstNewLine).TrimEnd('\r'), "-->");
+          foldMarkers.Add(new NewFolding(startOffset, endOffset) { Name = foldText });
+        }
+      }
+    }
+
+    /// <summary>
+    /// Creates an XmlFoldStart for the start tag of an element.
+    /// </summary>
+    XmlFoldStart CreateElementFoldStart(TextDocument document, XmlReader reader) {
+      // Take off 1 from the offset returned
+      // from the xml since it points to the start
+      // of the element name and not the beginning
+      // tag.
+      //XmlFoldStart newFoldStart = new XmlFoldStart(reader.Prefix, reader.LocalName, reader.LineNumber - 1, reader.LinePosition - 2);
+      XmlFoldStart newFoldStart = new XmlFoldStart();
+
+      IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
+      newFoldStart.StartLine = lineInfo.LineNumber;
+      newFoldStart.StartOffset = document.GetOffset(newFoldStart.StartLine, lineInfo.LinePosition - 1);
+
+      if (this.ShowAttributesWhenFolded && reader.HasAttributes) {
+        newFoldStart.Name = String.Concat("<", reader.Name, " ", GetAttributeFoldText(reader), ">");
+      } else {
+        newFoldStart.Name = String.Concat("<", reader.Name, ">");
+      }
+
+      return newFoldStart;
+    }
+
+    /// <summary>
+    /// Create an element fold if the start and end tag are on
+    /// different lines.
+    /// </summary>
+    static void CreateElementFold(TextDocument document, List<NewFolding> foldMarkers, XmlReader reader, XmlFoldStart foldStart) {
+      IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
+      int endLine = lineInfo.LineNumber;
+      if (endLine > foldStart.StartLine) {
+        int endCol = lineInfo.LinePosition + reader.Name.Length + 1;
+        foldStart.EndOffset = document.GetOffset(endLine, endCol);
+        foldMarkers.Add(foldStart);
+      }
+    }
+
+    /// <summary>
+    /// Gets the element's attributes as a string on one line that will
+    /// be displayed when the element is folded.
+    /// </summary>
+    /// <remarks>
+    /// Currently this puts all attributes from an element on the same
+    /// line of the start tag.  It does not cater for elements where attributes
+    /// are not on the same line as the start tag.
+    /// </remarks>
+    static string GetAttributeFoldText(XmlReader reader) {
+      StringBuilder text = new StringBuilder();
+
+      for (int i = 0; i < reader.AttributeCount; ++i) {
+        reader.MoveToAttribute(i);
+
+        text.Append(reader.Name);
+        text.Append("=");
+        text.Append(reader.QuoteChar.ToString());
+        text.Append(XmlEncodeAttributeValue(reader.Value, reader.QuoteChar));
+        text.Append(reader.QuoteChar.ToString());
+
+        // Append a space if this is not the
+        // last attribute.
+        if (i < reader.AttributeCount - 1) {
+          text.Append(" ");
+        }
+      }
+
+      return text.ToString();
+    }
+
+    /// <summary>
+    /// Xml encode the attribute string since the string returned from
+    /// the XmlTextReader is the plain unencoded string and .NET
+    /// does not provide us with an xml encode method.
+    /// </summary>
+    static string XmlEncodeAttributeValue(string attributeValue, char quoteChar) {
+      StringBuilder encodedValue = new StringBuilder(attributeValue);
+
+      encodedValue.Replace("&", "&amp;");
+      encodedValue.Replace("<", "&lt;");
+      encodedValue.Replace(">", "&gt;");
+
+      if (quoteChar == '"') {
+        encodedValue.Replace("\"", "&quot;");
+      } else {
+        encodedValue.Replace("'", "&apos;");
+      }
+
+      return encodedValue.ToString();
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ICodeCompletionStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ICodeCompletionStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ICodeCompletionStrategy.cs	(revision 11807)
@@ -0,0 +1,27 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+namespace HeuristicLab.CodeEditor {
+  internal interface ICodeCompletionStrategy {
+    void DoCodeCompletion(bool controlSpace);
+    void RunBackgroundParser();
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ICodeFoldingStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ICodeFoldingStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ICodeFoldingStrategy.cs	(revision 11807)
@@ -0,0 +1,26 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+namespace HeuristicLab.CodeEditor {
+  internal interface ICodeFoldingStrategy {
+    void DoCodeFolding();
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ILanguageFeatures.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ILanguageFeatures.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/ILanguageFeatures.cs	(revision 11807)
@@ -0,0 +1,27 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+namespace HeuristicLab.CodeEditor {
+  internal interface ILanguageFeatures {
+    ICodeFoldingStrategy CodeFoldingStrategy { get; }
+    ICodeCompletionStrategy CodeCompletionStrategy { get; }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/IUpdatableOverloadProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/IUpdatableOverloadProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/Interfaces/IUpdatableOverloadProvider.cs	(revision 11807)
@@ -0,0 +1,32 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using ICSharpCode.AvalonEdit.CodeCompletion;
+using ICSharpCode.NRefactory.Editor;
+
+namespace HeuristicLab.CodeEditor {
+  internal interface IUpdatableOverloadProvider : IOverloadProvider {
+    bool RequestClose { get; set; }
+
+    void Update(IDocument document, int offset);
+    void Update(CSharpCodeCompletionContext completionContext);
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/LanguageFeatures.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/LanguageFeatures.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/LanguageFeatures.cs	(revision 11807)
@@ -0,0 +1,88 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Windows.Input;
+
+namespace HeuristicLab.CodeEditor {
+  internal abstract class LanguageFeatures : ILanguageFeatures {
+    protected readonly CodeEditor codeEditor;
+    protected readonly CommandBinding commandBinding;
+
+    private readonly ICodeFoldingStrategy codeFoldingStrategy;
+    public ICodeFoldingStrategy CodeFoldingStrategy { get { return codeFoldingStrategy; } }
+
+    private readonly ICodeCompletionStrategy codeCompletionStrategy;
+    public ICodeCompletionStrategy CodeCompletionStrategy { get { return codeCompletionStrategy; } }
+
+    protected LanguageFeatures(CodeEditor codeEditor, ICodeFoldingStrategy codeFoldingStrategy, ICodeCompletionStrategy codeCompletionStrategy) {
+      this.codeEditor = codeEditor;
+      this.codeFoldingStrategy = codeFoldingStrategy;
+      this.codeCompletionStrategy = codeCompletionStrategy;
+
+      commandBinding = new CommandBinding(codeEditor.CompletionCommand, CodeCompletionRequestedHandler);
+      if (codeFoldingStrategy != null) AddCodeFoldingStrategy();
+      if (codeCompletionStrategy != null) AddCodeComplectionStrategy();
+    }
+
+    #region CodeFoldingStrategy
+    protected virtual void AddCodeFoldingStrategy() {
+      codeEditor.TextEditor.TextChanged += CodeFoldingHandler;
+    }
+
+    private void CodeFoldingHandler(object sender, EventArgs e) {
+      codeFoldingStrategy.DoCodeFolding();
+    }
+    #endregion
+
+    #region CodeCompletionStrategy
+    protected virtual void AddCodeComplectionStrategy() {
+      codeEditor.Load += LoadedHandler;
+      codeEditor.TextEditor.TextArea.TextEntered += CodeCompletionHandler;
+      codeEditor.TextEditor.TextArea.TextEntering += InsertionRequestedHandler;
+      codeEditor.TextEditor.CommandBindings.Add(commandBinding);
+    }
+
+    private void LoadedHandler(object sender, EventArgs e) {
+      codeCompletionStrategy.RunBackgroundParser();
+    }
+
+    private void CodeCompletionRequestedHandler(object sender, EventArgs e) {
+      var readOnlySectionProvider = codeEditor.TextEditor.TextArea.ReadOnlySectionProvider;
+      if (readOnlySectionProvider.CanInsert(codeEditor.TextEditor.CaretOffset))
+        codeCompletionStrategy.DoCodeCompletion(true);
+    }
+
+    private void CodeCompletionHandler(object sender, EventArgs e) {
+      var readOnlySectionProvider = codeEditor.TextEditor.TextArea.ReadOnlySectionProvider;
+      if (readOnlySectionProvider.CanInsert(codeEditor.TextEditor.CaretOffset))
+        codeCompletionStrategy.DoCodeCompletion(false);
+    }
+
+    private void InsertionRequestedHandler(object sender, TextCompositionEventArgs e) {
+      var cw = codeEditor.CompletionWindow;
+      if (cw != null && e.Text.Length > 0 && !char.IsLetterOrDigit(e.Text[0])) {
+        cw.CompletionList.RequestInsertion(e);
+      }
+    }
+    #endregion
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/XmlLanguageFeatures.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/XmlLanguageFeatures.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/LanguageFeatures/XmlLanguageFeatures.cs	(revision 11807)
@@ -0,0 +1,28 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+namespace HeuristicLab.CodeEditor {
+  internal class XmlLanguageFeatures : LanguageFeatures {
+    public XmlLanguageFeatures(CodeEditor codeEditor)
+      : base(codeEditor, new XmlCodeFoldingStrategy(codeEditor), null) {
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/MethodDefinitionReadOnlySectionProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/MethodDefinitionReadOnlySectionProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/MethodDefinitionReadOnlySectionProvider.cs	(revision 11807)
@@ -0,0 +1,53 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.NRefactory.Editor;
+
+namespace HeuristicLab.CodeEditor {
+  internal class MethodDefinitionReadOnlySectionProvider : IReadOnlySectionProvider {
+    private readonly CodeEditor codeEditor;
+
+    private IDocument Doc { get { return codeEditor.TextEditor.Document; } }
+    private string Prefix { get { return codeEditor.Prefix; } }
+    private string Suffix { get { return codeEditor.Suffix; } }
+
+    public MethodDefinitionReadOnlySectionProvider(CodeEditor codeEditor) {
+      this.codeEditor = codeEditor;
+    }
+
+    public bool CanInsert(int offset) {
+      return offset >= Prefix.Length && offset <= Doc.TextLength - Suffix.Length;
+    }
+
+    public IEnumerable<ISegment> GetDeletableSegments(ISegment segment) {
+      if (segment == null)
+        throw new ArgumentNullException("segment");
+
+      int offset = segment.Offset;
+      int length = segment.Length;
+      if (offset >= Prefix.Length && offset + length <= Doc.TextLength - Suffix.Length)
+        yield return segment;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/Plugin.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/Plugin.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/Plugin.cs.frame	(revision 11807)
@@ -0,0 +1,33 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.CodeEditor {
+  [Plugin("HeuristicLab.CodeEditor", "3.4.0.$WCREV$")]
+  [PluginFile("HeuristicLab.CodeEditor-3.4.dll", PluginFileType.Assembly)]
+  [PluginDependency("HeuristicLab.Common", "3.3")]
+  [PluginDependency("HeuristicLab.Common.Resources", "3.3")]
+  [PluginDependency("HeuristicLab.AvalonEdit", "5.0.1")]
+  [PluginDependency("HeuristicLab.NRefactory", "5.5.0")]
+  public class HeuristicLabCodeEditorPlugin : PluginBase {
+  }
+}
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/Properties/AssemblyInfo.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/Properties/AssemblyInfo.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/Properties/AssemblyInfo.cs.frame	(revision 11807)
@@ -0,0 +1,56 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.CodeEditor")]
+[assembly: AssemblyDescription("Code editor with syntax highlighting and code completion")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2014 HEAL & ic#code")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("89137802-6995-4da7-839b-1d09dc67b592")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("3.4.0.0")]
+[assembly: AssemblyFileVersion("3.4.0.$WCREV$")]
Index: /trunk/sources/HeuristicLab.CodeEditor/3.4/TextMarkerService.cs
===================================================================
--- /trunk/sources/HeuristicLab.CodeEditor/3.4/TextMarkerService.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.CodeEditor/3.4/TextMarkerService.cs	(revision 11807)
@@ -0,0 +1,370 @@
+﻿#region License Information
+// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.SharpDevelop.Editor;
+
+namespace ICSharpCode.AvalonEdit.AddIn {
+  /// <summary>
+  /// Handles the text markers for a code editor.
+  /// </summary>
+  public sealed class TextMarkerService : DocumentColorizingTransformer, IBackgroundRenderer, ITextMarkerService, ITextViewConnect {
+    TextSegmentCollection<TextMarker> markers;
+    TextDocument document;
+
+    public TextMarkerService(TextDocument document) {
+      if (document == null)
+        throw new ArgumentNullException("document");
+      this.document = document;
+      this.markers = new TextSegmentCollection<TextMarker>(document);
+    }
+
+    #region ITextMarkerService
+    public ITextMarker Create(int startOffset, int length) {
+      if (markers == null)
+        throw new InvalidOperationException("Cannot create a marker when not attached to a document");
+
+      int textLength = document.TextLength;
+      if (startOffset < 0 || startOffset > textLength)
+        throw new ArgumentOutOfRangeException("startOffset", startOffset, "Value must be between 0 and " + textLength);
+      if (length < 0 || startOffset + length > textLength)
+        throw new ArgumentOutOfRangeException("length", length, "length must not be negative and startOffset+length must not be after the end of the document");
+
+      TextMarker m = new TextMarker(this, startOffset, length);
+      markers.Add(m);
+      // no need to mark segment for redraw: the text marker is invisible until a property is set
+      return m;
+    }
+
+    public IEnumerable<ITextMarker> GetMarkersAtOffset(int offset) {
+      if (markers == null)
+        return Enumerable.Empty<ITextMarker>();
+      else
+        return markers.FindSegmentsContaining(offset);
+    }
+
+    public IEnumerable<ITextMarker> TextMarkers {
+      get { return markers ?? Enumerable.Empty<ITextMarker>(); }
+    }
+
+    public void RemoveAll(Predicate<ITextMarker> predicate) {
+      if (predicate == null)
+        throw new ArgumentNullException("predicate");
+      if (markers != null) {
+        foreach (TextMarker m in markers.ToArray()) {
+          if (predicate(m))
+            Remove(m);
+        }
+      }
+    }
+
+    public void Remove(ITextMarker marker) {
+      if (marker == null)
+        throw new ArgumentNullException("marker");
+      TextMarker m = marker as TextMarker;
+      if (markers != null && markers.Remove(m)) {
+        Redraw(m);
+        m.OnDeleted();
+      }
+    }
+
+    /// <summary>
+    /// Redraws the specified text segment.
+    /// </summary>
+    internal void Redraw(ISegment segment) {
+      foreach (var view in textViews) {
+        view.Redraw(segment, DispatcherPriority.Normal);
+      }
+      if (RedrawRequested != null)
+        RedrawRequested(this, EventArgs.Empty);
+    }
+
+    public event EventHandler RedrawRequested;
+    #endregion
+
+    #region DocumentColorizingTransformer
+    protected override void ColorizeLine(DocumentLine line) {
+      if (markers == null)
+        return;
+      int lineStart = line.Offset;
+      int lineEnd = lineStart + line.Length;
+      foreach (TextMarker marker in markers.FindOverlappingSegments(lineStart, line.Length)) {
+        Brush foregroundBrush = null;
+        if (marker.ForegroundColor != null) {
+          foregroundBrush = new SolidColorBrush(marker.ForegroundColor.Value);
+          foregroundBrush.Freeze();
+        }
+        ChangeLinePart(
+          Math.Max(marker.StartOffset, lineStart),
+          Math.Min(marker.EndOffset, lineEnd),
+          element => {
+            if (foregroundBrush != null) {
+              element.TextRunProperties.SetForegroundBrush(foregroundBrush);
+            }
+            Typeface tf = element.TextRunProperties.Typeface;
+            element.TextRunProperties.SetTypeface(new Typeface(
+              tf.FontFamily,
+              marker.FontStyle ?? tf.Style,
+              marker.FontWeight ?? tf.Weight,
+              tf.Stretch
+            ));
+          }
+        );
+      }
+    }
+    #endregion
+
+    #region IBackgroundRenderer
+    public KnownLayer Layer {
+      get {
+        // draw behind selection
+        return KnownLayer.Selection;
+      }
+    }
+
+    public void Draw(TextView textView, DrawingContext drawingContext) {
+      if (textView == null)
+        throw new ArgumentNullException("textView");
+      if (drawingContext == null)
+        throw new ArgumentNullException("drawingContext");
+      if (markers == null || !textView.VisualLinesValid)
+        return;
+      var visualLines = textView.VisualLines;
+      if (visualLines.Count == 0)
+        return;
+      int viewStart = visualLines.First().FirstDocumentLine.Offset;
+      int viewEnd = visualLines.Last().LastDocumentLine.EndOffset;
+      foreach (TextMarker marker in markers.FindOverlappingSegments(viewStart, viewEnd - viewStart)) {
+        if (marker.BackgroundColor != null) {
+          BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder();
+          geoBuilder.AlignToWholePixels = true;
+          geoBuilder.CornerRadius = 3;
+          geoBuilder.AddSegment(textView, marker);
+          Geometry geometry = geoBuilder.CreateGeometry();
+          if (geometry != null) {
+            Color color = marker.BackgroundColor.Value;
+            SolidColorBrush brush = new SolidColorBrush(color);
+            brush.Freeze();
+            drawingContext.DrawGeometry(brush, null, geometry);
+          }
+        }
+        var underlineMarkerTypes = TextMarkerTypes.SquigglyUnderline | TextMarkerTypes.NormalUnderline | TextMarkerTypes.DottedUnderline;
+        if ((marker.MarkerTypes & underlineMarkerTypes) != 0) {
+          foreach (Rect r in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker)) {
+            Point startPoint = r.BottomLeft;
+            Point endPoint = r.BottomRight;
+
+            Brush usedBrush = new SolidColorBrush(marker.MarkerColor);
+            usedBrush.Freeze();
+            if ((marker.MarkerTypes & TextMarkerTypes.SquigglyUnderline) != 0) {
+              double offset = 2.5;
+
+              int count = Math.Max((int)((endPoint.X - startPoint.X) / offset) + 1, 4);
+
+              StreamGeometry geometry = new StreamGeometry();
+
+              using (StreamGeometryContext ctx = geometry.Open()) {
+                ctx.BeginFigure(startPoint, false, false);
+                ctx.PolyLineTo(CreatePoints(startPoint, endPoint, offset, count).ToArray(), true, false);
+              }
+
+              geometry.Freeze();
+
+              Pen usedPen = new Pen(usedBrush, 1);
+              usedPen.Freeze();
+              drawingContext.DrawGeometry(Brushes.Transparent, usedPen, geometry);
+            }
+            if ((marker.MarkerTypes & TextMarkerTypes.NormalUnderline) != 0) {
+              Pen usedPen = new Pen(usedBrush, 1);
+              usedPen.Freeze();
+              drawingContext.DrawLine(usedPen, startPoint, endPoint);
+            }
+            if ((marker.MarkerTypes & TextMarkerTypes.DottedUnderline) != 0) {
+              Pen usedPen = new Pen(usedBrush, 1);
+              usedPen.DashStyle = DashStyles.Dot;
+              usedPen.Freeze();
+              drawingContext.DrawLine(usedPen, startPoint, endPoint);
+            }
+          }
+        }
+      }
+    }
+
+    IEnumerable<Point> CreatePoints(Point start, Point end, double offset, int count) {
+      for (int i = 0; i < count; i++)
+        yield return new Point(start.X + i * offset, start.Y - ((i + 1) % 2 == 0 ? offset : 0));
+    }
+    #endregion
+
+    #region ITextViewConnect
+    readonly List<TextView> textViews = new List<TextView>();
+
+    void ITextViewConnect.AddToTextView(TextView textView) {
+      if (textView != null && !textViews.Contains(textView)) {
+        Debug.Assert(textView.Document == document);
+        textViews.Add(textView);
+      }
+    }
+
+    void ITextViewConnect.RemoveFromTextView(TextView textView) {
+      if (textView != null) {
+        Debug.Assert(textView.Document == document);
+        textViews.Remove(textView);
+      }
+    }
+    #endregion
+  }
+
+  public sealed class TextMarker : TextSegment, ITextMarker {
+    readonly TextMarkerService service;
+
+    public TextMarker(TextMarkerService service, int startOffset, int length) {
+      if (service == null)
+        throw new ArgumentNullException("service");
+      this.service = service;
+      this.StartOffset = startOffset;
+      this.Length = length;
+      this.markerTypes = TextMarkerTypes.None;
+    }
+
+    public event EventHandler Deleted;
+
+    public bool IsDeleted {
+      get { return !this.IsConnectedToCollection; }
+    }
+
+    public void Delete() {
+      service.Remove(this);
+    }
+
+    internal void OnDeleted() {
+      if (Deleted != null)
+        Deleted(this, EventArgs.Empty);
+    }
+
+    void Redraw() {
+      service.Redraw(this);
+    }
+
+    Color? backgroundColor;
+
+    public Color? BackgroundColor {
+      get { return backgroundColor; }
+      set {
+        if (backgroundColor != value) {
+          backgroundColor = value;
+          Redraw();
+        }
+      }
+    }
+
+    Color? foregroundColor;
+
+    public Color? ForegroundColor {
+      get { return foregroundColor; }
+      set {
+        if (foregroundColor != value) {
+          foregroundColor = value;
+          Redraw();
+        }
+      }
+    }
+
+    FontWeight? fontWeight;
+
+    public FontWeight? FontWeight {
+      get { return fontWeight; }
+      set {
+        if (fontWeight != value) {
+          fontWeight = value;
+          Redraw();
+        }
+      }
+    }
+
+    FontStyle? fontStyle;
+
+    public FontStyle? FontStyle {
+      get { return fontStyle; }
+      set {
+        if (fontStyle != value) {
+          fontStyle = value;
+          Redraw();
+        }
+      }
+    }
+
+    public object Tag { get; set; }
+
+    TextMarkerTypes markerTypes;
+
+    public TextMarkerTypes MarkerTypes {
+      get { return markerTypes; }
+      set {
+        if (markerTypes != value) {
+          markerTypes = value;
+          Redraw();
+        }
+      }
+    }
+
+    Color markerColor;
+
+    public Color MarkerColor {
+      get { return markerColor; }
+      set {
+        if (markerColor != value) {
+          markerColor = value;
+          Redraw();
+        }
+      }
+    }
+
+    public object ToolTip { get; set; }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs.sln
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs.sln	(revision 11806)
+++ /trunk/sources/HeuristicLab.ExtLibs.sln	(revision 11807)
@@ -1,5 +1,7 @@
 ﻿
 Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 2012
+# Visual Studio 2013
+VisualStudioVersion = 12.0.21005.1
+MinimumVisualStudioVersion = 10.0.40219.1
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.DayView-1.0", "HeuristicLab.ExtLibs\HeuristicLab.DayView\1.0\HeuristicLab.DayView-1.0.csproj", "{02766ECC-D0F5-4115-9ECA-47409167B638}"
 EndProject
@@ -35,6 +37,4 @@
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoDiff-1.0", "HeuristicLab.ExtLibs\HeuristicLab.AutoDiff\1.0\AutoDiff-1.0\AutoDiff-1.0.csproj", "{62551FD3-C21F-4E16-A7FC-6A017508809C}"
 EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.SharpDevelop-3.2.1", "HeuristicLab.ExtLibs\HeuristicLab.SharpDevelop\3.2.1\HeuristicLab.SharpDevelop-3.2.1.csproj", "{8AF3BD99-3C84-4166-9EEA-B1403E20D926}"
-EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ALGLIB-3.7.0", "HeuristicLab.ExtLibs\HeuristicLab.ALGLIB\3.7.0\ALGLIB-3.7.0\ALGLIB-3.7.0.csproj", "{AE723DEF-1A44-4F9C-8670-DBCAB79626A2}"
 EndProject
@@ -50,4 +50,22 @@
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.MatlabConnector-1.0", "HeuristicLab.ExtLibs\HeuristicLab.MatlabConnector\1.0\HeuristicLab.MatlabConnector-1.0\HeuristicLab.MatlabConnector-1.0.csproj", "{52C66DEA-0250-477B-97F8-5CD2CD4B7332}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.AvalonEdit-5.0.1", "HeuristicLab.ExtLibs\HeuristicLab.AvalonEdit\5.0.1\AvalonEdit-5.0.1\ICSharpCode.AvalonEdit-5.0.1.csproj", "{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.AvalonEdit-5.0.1", "HeuristicLab.ExtLibs\HeuristicLab.AvalonEdit\5.0.1\HeuristicLab.AvalonEdit-5.0.1\HeuristicLab.AvalonEdit-5.0.1.csproj", "{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory-5.5.0", "HeuristicLab.ExtLibs\HeuristicLab.NRefactory\5.5.0\NRefactory-5.5.0\ICSharpCode.NRefactory-5.5.0.csproj", "{1022483B-7CF4-4162-827F-984B64EAF8B3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.NRefactory-5.5.0", "HeuristicLab.ExtLibs\HeuristicLab.NRefactory\5.5.0\HeuristicLab.NRefactory-5.5.0\HeuristicLab.NRefactory-5.5.0.csproj", "{168B628A-3815-4567-8ACF-2878AE92891A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.Cecil-5.5.0", "HeuristicLab.ExtLibs\HeuristicLab.NRefactory\5.5.0\NRefactory.Cecil-5.5.0\ICSharpCode.NRefactory.Cecil-5.5.0.csproj", "{6661EE06-91D3-489B-AE80-BC951EA65E9A}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.CSharp-5.5.0", "HeuristicLab.ExtLibs\HeuristicLab.NRefactory\5.5.0\NRefactory.CSharp-5.5.0\ICSharpCode.NRefactory.CSharp-5.5.0.csproj", "{C06A9187-4E8E-4129-BDA3-91D2297682D2}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Cecil-0.9.5", "HeuristicLab.ExtLibs\HeuristicLab.Cecil\0.9.5\Mono.Cecil-0.9.5\Mono.Cecil-0.9.5.csproj", "{CCF26BBC-5555-46EC-81F9-5B253CD24170}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HeuristicLab.Cecil-0.9.5", "HeuristicLab.ExtLibs\HeuristicLab.Cecil\0.9.5\HeuristicLab.Cecil-0.9.5\HeuristicLab.Cecil-0.9.5.csproj", "{03026CEF-4529-4F91-A8A3-761652CE14AD}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.NRefactory.Xml-5.5.0", "HeuristicLab.ExtLibs\HeuristicLab.NRefactory\5.5.0\NRefactory.Xml-5.5.0\ICSharpCode.NRefactory.Xml-5.5.0.csproj", "{C5AE5D30-AE8C-4017-B741-99E084281000}"
 EndProject
 Global
@@ -229,16 +247,4 @@
 		{62551FD3-C21F-4E16-A7FC-6A017508809C}.Release|x86.ActiveCfg = Release|x86
 		{62551FD3-C21F-4E16-A7FC-6A017508809C}.Release|x86.Build.0 = Release|x86
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Debug|x64.ActiveCfg = Debug|x64
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Debug|x64.Build.0 = Debug|x64
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Debug|x86.ActiveCfg = Debug|x86
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Debug|x86.Build.0 = Debug|x86
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Release|Any CPU.Build.0 = Release|Any CPU
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Release|x64.ActiveCfg = Release|x64
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Release|x64.Build.0 = Release|x64
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Release|x86.ActiveCfg = Release|x86
-		{8AF3BD99-3C84-4166-9EEA-B1403E20D926}.Release|x86.Build.0 = Release|x86
 		{AE723DEF-1A44-4F9C-8670-DBCAB79626A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 		{AE723DEF-1A44-4F9C-8670-DBCAB79626A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
@@ -325,4 +331,112 @@
 		{52C66DEA-0250-477B-97F8-5CD2CD4B7332}.Release|x86.ActiveCfg = Release|x86
 		{52C66DEA-0250-477B-97F8-5CD2CD4B7332}.Release|x86.Build.0 = Release|x86
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Debug|x64.ActiveCfg = Debug|x64
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Debug|x64.Build.0 = Debug|x64
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Debug|x86.ActiveCfg = Debug|x86
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Debug|x86.Build.0 = Debug|x86
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Release|Any CPU.Build.0 = Release|Any CPU
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Release|x64.ActiveCfg = Release|x64
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Release|x64.Build.0 = Release|x64
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Release|x86.ActiveCfg = Release|x86
+		{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}.Release|x86.Build.0 = Release|x86
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Debug|x64.ActiveCfg = Debug|x64
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Debug|x64.Build.0 = Debug|x64
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Debug|x86.ActiveCfg = Debug|x86
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Debug|x86.Build.0 = Debug|x86
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Release|Any CPU.Build.0 = Release|Any CPU
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Release|x64.ActiveCfg = Release|x64
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Release|x64.Build.0 = Release|x64
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Release|x86.ActiveCfg = Release|x86
+		{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}.Release|x86.Build.0 = Release|x86
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Debug|x64.ActiveCfg = Debug|x64
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Debug|x64.Build.0 = Debug|x64
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Debug|x86.ActiveCfg = Debug|x86
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Debug|x86.Build.0 = Debug|x86
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Release|Any CPU.Build.0 = Release|Any CPU
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Release|x64.ActiveCfg = Release|x64
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Release|x64.Build.0 = Release|x64
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Release|x86.ActiveCfg = Release|x86
+		{1022483B-7CF4-4162-827F-984B64EAF8B3}.Release|x86.Build.0 = Release|x86
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Debug|x64.ActiveCfg = Debug|x64
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Debug|x64.Build.0 = Debug|x64
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Debug|x86.ActiveCfg = Debug|x86
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Debug|x86.Build.0 = Debug|x86
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Release|Any CPU.Build.0 = Release|Any CPU
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Release|x64.ActiveCfg = Release|x64
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Release|x64.Build.0 = Release|x64
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Release|x86.ActiveCfg = Release|x86
+		{168B628A-3815-4567-8ACF-2878AE92891A}.Release|x86.Build.0 = Release|x86
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Debug|x64.ActiveCfg = Debug|x64
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Debug|x64.Build.0 = Debug|x64
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Debug|x86.ActiveCfg = Debug|x86
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Debug|x86.Build.0 = Debug|x86
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Release|Any CPU.Build.0 = Release|Any CPU
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Release|x64.ActiveCfg = Release|x64
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Release|x64.Build.0 = Release|x64
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Release|x86.ActiveCfg = Release|x86
+		{6661EE06-91D3-489B-AE80-BC951EA65E9A}.Release|x86.Build.0 = Release|x86
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Debug|x64.ActiveCfg = Debug|x64
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Debug|x64.Build.0 = Debug|x64
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Debug|x86.ActiveCfg = Debug|x86
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Debug|x86.Build.0 = Debug|x86
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Release|Any CPU.Build.0 = Release|Any CPU
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Release|x64.ActiveCfg = Release|x64
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Release|x64.Build.0 = Release|x64
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Release|x86.ActiveCfg = Release|x86
+		{C06A9187-4E8E-4129-BDA3-91D2297682D2}.Release|x86.Build.0 = Release|x86
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Debug|x64.ActiveCfg = Debug|x64
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Debug|x64.Build.0 = Debug|x64
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Debug|x86.ActiveCfg = Debug|x86
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Debug|x86.Build.0 = Debug|x86
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Release|Any CPU.Build.0 = Release|Any CPU
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Release|x64.ActiveCfg = Release|x64
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Release|x64.Build.0 = Release|x64
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Release|x86.ActiveCfg = Release|x86
+		{CCF26BBC-5555-46EC-81F9-5B253CD24170}.Release|x86.Build.0 = Release|x86
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Debug|x64.ActiveCfg = Debug|x64
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Debug|x64.Build.0 = Debug|x64
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Debug|x86.ActiveCfg = Debug|x86
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Debug|x86.Build.0 = Debug|x86
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Release|Any CPU.Build.0 = Release|Any CPU
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Release|x64.ActiveCfg = Release|x64
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Release|x64.Build.0 = Release|x64
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Release|x86.ActiveCfg = Release|x86
+		{03026CEF-4529-4F91-A8A3-761652CE14AD}.Release|x86.Build.0 = Release|x86
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Debug|x64.ActiveCfg = Debug|x64
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Debug|x64.Build.0 = Debug|x64
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Debug|x86.ActiveCfg = Debug|x86
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Debug|x86.Build.0 = Debug|x86
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Release|Any CPU.Build.0 = Release|Any CPU
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Release|x64.ActiveCfg = Release|x64
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Release|x64.Build.0 = Release|x64
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Release|x86.ActiveCfg = Release|x86
+		{C5AE5D30-AE8C-4017-B741-99E084281000}.Release|x86.Build.0 = Release|x86
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/AvalonEditCommands.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/AvalonEditCommands.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/AvalonEditCommands.cs	(revision 11807)
@@ -0,0 +1,102 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Input;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// Custom commands for AvalonEdit.
+	/// </summary>
+	public static class AvalonEditCommands
+	{
+		/// <summary>
+		/// Deletes the current line.
+		/// The default shortcut is Ctrl+D.
+		/// </summary>
+		public static readonly RoutedCommand DeleteLine = new RoutedCommand(
+			"DeleteLine", typeof(TextEditor),
+			new InputGestureCollection {
+				new KeyGesture(Key.D, ModifierKeys.Control)
+			});
+		
+		/// <summary>
+		/// Removes leading whitespace from the selected lines (or the whole document if the selection is empty).
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		public static readonly RoutedCommand RemoveLeadingWhitespace = new RoutedCommand("RemoveLeadingWhitespace", typeof(TextEditor));
+				
+		/// <summary>
+		/// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty).
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		public static readonly RoutedCommand RemoveTrailingWhitespace = new RoutedCommand("RemoveTrailingWhitespace", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts the selected text to upper case.
+		/// </summary>
+		public static readonly RoutedCommand ConvertToUppercase = new RoutedCommand("ConvertToUppercase", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts the selected text to lower case.
+		/// </summary>
+		public static readonly RoutedCommand ConvertToLowercase = new RoutedCommand("ConvertToLowercase", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts the selected text to title case.
+		/// </summary>
+		public static readonly RoutedCommand ConvertToTitleCase = new RoutedCommand("ConvertToTitleCase", typeof(TextEditor));
+		
+		/// <summary>
+		/// Inverts the case of the selected text.
+		/// </summary>
+		public static readonly RoutedCommand InvertCase = new RoutedCommand("InvertCase", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts tabs to spaces in the selected text.
+		/// </summary>
+		public static readonly RoutedCommand ConvertTabsToSpaces = new RoutedCommand("ConvertTabsToSpaces", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts spaces to tabs in the selected text.
+		/// </summary>
+		public static readonly RoutedCommand ConvertSpacesToTabs = new RoutedCommand("ConvertSpacesToTabs", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty).
+		/// </summary>
+		public static readonly RoutedCommand ConvertLeadingTabsToSpaces = new RoutedCommand("ConvertLeadingTabsToSpaces", typeof(TextEditor));
+		
+		/// <summary>
+		/// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty).
+		/// </summary>
+		public static readonly RoutedCommand ConvertLeadingSpacesToTabs = new RoutedCommand("ConvertLeadingSpacesToTabs", typeof(TextEditor));
+		
+		/// <summary>
+		/// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty).
+		/// </summary>
+		public static readonly RoutedCommand IndentSelection = new RoutedCommand(
+			"IndentSelection", typeof(TextEditor),
+			new InputGestureCollection {
+				new KeyGesture(Key.I, ModifierKeys.Control)
+			});
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionList.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionList.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionList.cs	(revision 11807)
@@ -0,0 +1,400 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Linq;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// The listbox used inside the CompletionWindow, contains CompletionListBox.
+	/// </summary>
+	public class CompletionList : Control
+	{
+		static CompletionList()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(CompletionList),
+			                                         new FrameworkPropertyMetadata(typeof(CompletionList)));
+		}
+		
+		bool isFiltering = true;
+		/// <summary>
+		/// If true, the CompletionList is filtered to show only matching items. Also enables search by substring.
+		/// If false, enables the old behavior: no filtering, search by string.StartsWith.
+		/// </summary>
+		public bool IsFiltering {
+			get { return isFiltering; }
+			set { isFiltering = value; }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="EmptyTemplate" />.
+		/// </summary>
+		public static readonly DependencyProperty EmptyTemplateProperty =
+			DependencyProperty.Register("EmptyTemplate", typeof(ControlTemplate), typeof(CompletionList),
+			                            new FrameworkPropertyMetadata());
+		
+		/// <summary>
+		/// Content of EmptyTemplate will be shown when CompletionList contains no items.
+		/// If EmptyTemplate is null, nothing will be shown.
+		/// </summary>
+		public ControlTemplate EmptyTemplate {
+			get { return (ControlTemplate)GetValue(EmptyTemplateProperty); }
+			set { SetValue(EmptyTemplateProperty, value); }
+		}
+		
+		/// <summary>
+		/// Is raised when the completion list indicates that the user has chosen
+		/// an entry to be completed.
+		/// </summary>
+		public event EventHandler InsertionRequested;
+		
+		/// <summary>
+		/// Raises the InsertionRequested event.
+		/// </summary>
+		public void RequestInsertion(EventArgs e)
+		{
+			if (InsertionRequested != null)
+				InsertionRequested(this, e);
+		}
+		
+		CompletionListBox listBox;
+		
+		/// <inheritdoc/>
+		public override void OnApplyTemplate()
+		{
+			base.OnApplyTemplate();
+			
+			listBox = GetTemplateChild("PART_ListBox") as CompletionListBox;
+			if (listBox != null) {
+				listBox.ItemsSource = completionData;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the list box.
+		/// </summary>
+		public CompletionListBox ListBox {
+			get {
+				if (listBox == null)
+					ApplyTemplate();
+				return listBox;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the scroll viewer used in this list box.
+		/// </summary>
+		public ScrollViewer ScrollViewer {
+			get { return listBox != null ? listBox.scrollViewer : null; }
+		}
+		
+		ObservableCollection<ICompletionData> completionData = new ObservableCollection<ICompletionData>();
+		
+		/// <summary>
+		/// Gets the list to which completion data can be added.
+		/// </summary>
+		public IList<ICompletionData> CompletionData {
+			get { return completionData; }
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnKeyDown(KeyEventArgs e)
+		{
+			base.OnKeyDown(e);
+			if (!e.Handled) {
+				HandleKey(e);
+			}
+		}
+		
+		/// <summary>
+		/// Handles a key press. Used to let the completion list handle key presses while the
+		/// focus is still on the text editor.
+		/// </summary>
+		public void HandleKey(KeyEventArgs e)
+		{
+			if (listBox == null)
+				return;
+			
+			// We have to do some key handling manually, because the default doesn't work with
+			// our simulated events.
+			// Also, the default PageUp/PageDown implementation changes the focus, so we avoid it.
+			switch (e.Key) {
+				case Key.Down:
+					e.Handled = true;
+					listBox.SelectIndex(listBox.SelectedIndex + 1);
+					break;
+				case Key.Up:
+					e.Handled = true;
+					listBox.SelectIndex(listBox.SelectedIndex - 1);
+					break;
+				case Key.PageDown:
+					e.Handled = true;
+					listBox.SelectIndex(listBox.SelectedIndex + listBox.VisibleItemCount);
+					break;
+				case Key.PageUp:
+					e.Handled = true;
+					listBox.SelectIndex(listBox.SelectedIndex - listBox.VisibleItemCount);
+					break;
+				case Key.Home:
+					e.Handled = true;
+					listBox.SelectIndex(0);
+					break;
+				case Key.End:
+					e.Handled = true;
+					listBox.SelectIndex(listBox.Items.Count - 1);
+					break;
+				case Key.Tab:
+				case Key.Enter:
+					e.Handled = true;
+					RequestInsertion(e);
+					break;
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
+		{
+			base.OnMouseDoubleClick(e);
+			if (e.ChangedButton == MouseButton.Left) {
+				// only process double clicks on the ListBoxItems, not on the scroll bar
+				if (ExtensionMethods.VisualAncestorsAndSelf(e.OriginalSource as DependencyObject).TakeWhile(obj => obj != this).Any(obj => obj is ListBoxItem)) {
+					e.Handled = true;
+					RequestInsertion(e);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the selected item.
+		/// </summary>
+		public ICompletionData SelectedItem {
+			get {
+				return (listBox != null ? listBox.SelectedItem : null) as ICompletionData;
+			}
+			set {
+				if (listBox == null && value != null)
+					ApplyTemplate();
+				listBox.SelectedItem = value;
+			}
+		}
+		
+		/// <summary>
+		/// Occurs when the SelectedItem property changes.
+		/// </summary>
+		public event SelectionChangedEventHandler SelectionChanged {
+			add { AddHandler(Selector.SelectionChangedEvent, value); }
+			remove { RemoveHandler(Selector.SelectionChangedEvent, value); }
+		}
+		
+		// SelectItem gets called twice for every typed character (once from FormatLine), this helps execute SelectItem only once
+		string currentText;
+		ObservableCollection<ICompletionData> currentList;
+		
+		/// <summary>
+		/// Selects the best match, and filter the items if turned on using <see cref="IsFiltering" />.
+		/// </summary>
+		public void SelectItem(string text)
+		{
+			if (text == currentText)
+				return;
+			if (listBox == null)
+				ApplyTemplate();
+			
+			if (this.IsFiltering) {
+				SelectItemFiltering(text);
+			}
+			else {
+				SelectItemWithStart(text);
+			}
+			currentText = text;
+		}
+		
+		/// <summary>
+		/// Filters CompletionList items to show only those matching given query, and selects the best match.
+		/// </summary>
+		void SelectItemFiltering(string query)
+		{
+			// if the user just typed one more character, don't filter all data but just filter what we are already displaying
+			var listToFilter = (this.currentList != null && (!string.IsNullOrEmpty(this.currentText)) && (!string.IsNullOrEmpty(query)) &&
+			                    query.StartsWith(this.currentText, StringComparison.Ordinal)) ?
+				this.currentList : this.completionData;
+			
+			var matchingItems =
+				from item in listToFilter
+				let quality = GetMatchQuality(item.Text, query)
+				where quality > 0
+				select new { Item = item, Quality = quality };
+			
+			// e.g. "DateTimeKind k = (*cc here suggests DateTimeKind*)"
+			ICompletionData suggestedItem = listBox.SelectedIndex != -1 ? (ICompletionData)(listBox.Items[listBox.SelectedIndex]) : null;
+			
+			var listBoxItems = new ObservableCollection<ICompletionData>();
+			int bestIndex = -1;
+			int bestQuality = -1;
+			double bestPriority = 0;
+			int i = 0;
+			foreach (var matchingItem in matchingItems) {
+				double priority = matchingItem.Item == suggestedItem ? double.PositiveInfinity : matchingItem.Item.Priority;
+				int quality = matchingItem.Quality;
+				if (quality > bestQuality || (quality == bestQuality && (priority > bestPriority))) {
+					bestIndex = i;
+					bestPriority = priority;
+					bestQuality = quality;
+				}
+				listBoxItems.Add(matchingItem.Item);
+				i++;
+			}
+			this.currentList = listBoxItems;
+			listBox.ItemsSource = listBoxItems;
+			SelectIndexCentered(bestIndex);
+		}
+		
+		/// <summary>
+		/// Selects the item that starts with the specified query.
+		/// </summary>
+		void SelectItemWithStart(string query)
+		{
+			if (string.IsNullOrEmpty(query))
+				return;
+			
+			int suggestedIndex = listBox.SelectedIndex;
+			
+			int bestIndex = -1;
+			int bestQuality = -1;
+			double bestPriority = 0;
+			for (int i = 0; i < completionData.Count; ++i) {
+				int quality = GetMatchQuality(completionData[i].Text, query);
+				if (quality < 0)
+					continue;
+				
+				double priority = completionData[i].Priority;
+				bool useThisItem;
+				if (bestQuality < quality) {
+					useThisItem = true;
+				} else {
+					if (bestIndex == suggestedIndex) {
+						useThisItem = false;
+					} else if (i == suggestedIndex) {
+						// prefer recommendedItem, regardless of its priority
+						useThisItem = bestQuality == quality;
+					} else {
+						useThisItem = bestQuality == quality && bestPriority < priority;
+					}
+				}
+				if (useThisItem) {
+					bestIndex = i;
+					bestPriority = priority;
+					bestQuality = quality;
+				}
+			}
+			SelectIndexCentered(bestIndex);
+		}
+
+		void SelectIndexCentered(int bestIndex)
+		{
+			if (bestIndex < 0) {
+				listBox.ClearSelection();
+			} else {
+				int firstItem = listBox.FirstVisibleItem;
+				if (bestIndex < firstItem || firstItem + listBox.VisibleItemCount <= bestIndex) {
+					// CenterViewOn does nothing as CompletionListBox.ScrollViewer is null
+					listBox.CenterViewOn(bestIndex);
+					listBox.SelectIndex(bestIndex);
+				} else {
+					listBox.SelectIndex(bestIndex);
+				}
+			}
+		}
+
+		int GetMatchQuality(string itemText, string query)
+		{
+			if (itemText == null)
+				throw new ArgumentNullException("itemText", "ICompletionData.Text returned null");
+			
+			// Qualities:
+			//  	8 = full match case sensitive
+			// 		7 = full match
+			// 		6 = match start case sensitive
+			//		5 = match start
+			//		4 = match CamelCase when length of query is 1 or 2 characters
+			// 		3 = match substring case sensitive
+			//		2 = match substring
+			//		1 = match CamelCase
+			//		-1 = no match
+			if (query == itemText)
+				return 8;
+			if (string.Equals(itemText, query, StringComparison.InvariantCultureIgnoreCase))
+				return 7;
+			
+			if (itemText.StartsWith(query, StringComparison.InvariantCulture))
+				return 6;
+			if (itemText.StartsWith(query, StringComparison.InvariantCultureIgnoreCase))
+				return 5;
+			
+			bool? camelCaseMatch = null;
+			if (query.Length <= 2) {
+				camelCaseMatch = CamelCaseMatch(itemText, query);
+				if (camelCaseMatch == true) return 4;
+			}
+			
+			// search by substring, if filtering (i.e. new behavior) turned on
+			if (IsFiltering) {
+				if (itemText.IndexOf(query, StringComparison.InvariantCulture) >= 0)
+					return 3;
+				if (itemText.IndexOf(query, StringComparison.InvariantCultureIgnoreCase) >= 0)
+					return 2;
+			}
+				
+			if (!camelCaseMatch.HasValue)
+				camelCaseMatch = CamelCaseMatch(itemText, query);
+			if (camelCaseMatch == true)
+				return 1;
+			
+			return -1;
+		}
+		
+		static bool CamelCaseMatch(string text, string query)
+		{
+			// We take the first letter of the text regardless of whether or not it's upper case so we match
+			// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
+			var theFirstLetterOfEachWord = text.Take(1).Concat(text.Skip(1).Where(char.IsUpper));
+			
+			int i = 0;
+			foreach (var letter in theFirstLetterOfEachWord) {
+				if (i > query.Length - 1)
+					return true;	// return true here for CamelCase partial match ("CQ" matches "CodeQualityAnalysis")
+				if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
+					return false;
+				i++;
+			}
+			if (i >= query.Length)
+				return true;
+			return false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionList.xaml
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionList.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionList.xaml	(revision 11807)
@@ -0,0 +1,56 @@
+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+	xmlns:AvalonEdit="clr-namespace:ICSharpCode.AvalonEdit"
+	xmlns:cc="clr-namespace:ICSharpCode.AvalonEdit.CodeCompletion"
+>
+	<Style TargetType="{x:Type ListBoxItem}" x:Key="CompletionListBoxItem">
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type ListBoxItem}">
+					<Border Name="Bd"
+					        Background="{TemplateBinding Background}"
+					        BorderBrush="{TemplateBinding BorderBrush}"
+					        BorderThickness="{TemplateBinding BorderThickness}"
+					        Padding="{TemplateBinding Padding}"
+					        SnapsToDevicePixels="true">
+						<ContentPresenter
+							HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
+							VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
+							SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
+					</Border>
+					<!-- Simplified triggers:
+ 						we don't want a gray selection background when the ListBox doesn't have focus
+					-->
+					<ControlTemplate.Triggers>
+						<Trigger Property="IsSelected" Value="true">
+							<Setter Property="Background"
+							        Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
+							<Setter Property="Foreground"
+							        Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
+						</Trigger>
+					</ControlTemplate.Triggers>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+	
+	<Style TargetType="{x:Type cc:CompletionList}">
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type cc:CompletionList}">
+					<cc:CompletionListBox x:Name="PART_ListBox"
+						ItemContainerStyle="{StaticResource CompletionListBoxItem}">
+						<ItemsControl.ItemTemplate>
+							<DataTemplate>
+								<StackPanel Orientation="Horizontal">
+									<Image Source="{Binding Image}" Width="16" Height="16" Margin="0,0,2,0"/>
+									<ContentPresenter Content="{Binding Content}"/>
+								</StackPanel>
+							</DataTemplate>
+						</ItemsControl.ItemTemplate>
+					</cc:CompletionListBox>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+</ResourceDictionary>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionListBox.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionListBox.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionListBox.cs	(revision 11807)
@@ -0,0 +1,111 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// The list box used inside the CompletionList.
+	/// </summary>
+	public class CompletionListBox : ListBox
+	{
+		internal ScrollViewer scrollViewer;
+		
+		/// <inheritdoc/>
+		public override void OnApplyTemplate()
+		{
+			base.OnApplyTemplate();
+			
+			// Find the scroll viewer:
+			scrollViewer = null;
+			if (this.VisualChildrenCount > 0) {
+				Border border = this.GetVisualChild(0) as Border;
+				if (border != null)
+					scrollViewer = border.Child as ScrollViewer;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the number of the first visible item.
+		/// </summary>
+		public int FirstVisibleItem {
+			get {
+				if (scrollViewer == null || scrollViewer.ExtentHeight == 0) {
+					return 0;
+				} else {
+					return (int)(this.Items.Count * scrollViewer.VerticalOffset / scrollViewer.ExtentHeight);
+				}
+			}
+			set {
+				value = value.CoerceValue(0, this.Items.Count - this.VisibleItemCount);
+				if (scrollViewer != null) {
+					scrollViewer.ScrollToVerticalOffset((double)value / this.Items.Count * scrollViewer.ExtentHeight);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the number of visible items.
+		/// </summary>
+		public int VisibleItemCount {
+			get {
+				if (scrollViewer == null || scrollViewer.ExtentHeight == 0) {
+					return 10;
+				} else {
+					return Math.Max(
+						3,
+						(int)Math.Ceiling(this.Items.Count * scrollViewer.ViewportHeight
+						                  / scrollViewer.ExtentHeight));
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Removes the selection.
+		/// </summary>
+		public void ClearSelection()
+		{
+			this.SelectedIndex = -1;
+		}
+		
+		/// <summary>
+		/// Selects the item with the specified index and scrolls it into view.
+		/// </summary>
+		public void SelectIndex(int index)
+		{
+			if (index >= this.Items.Count)
+				index = this.Items.Count - 1;
+			if (index < 0)
+				index = 0;
+			this.SelectedIndex = index;
+			this.ScrollIntoView(this.SelectedItem);
+		}
+		
+		/// <summary>
+		/// Centers the view on the item with the specified index.
+		/// </summary>
+		public void CenterViewOn(int index)
+		{
+			this.FirstVisibleItem = index - VisibleItemCount / 2;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionWindow.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionWindow.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionWindow.cs	(revision 11807)
@@ -0,0 +1,213 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// The code completion window.
+	/// </summary>
+	public class CompletionWindow : CompletionWindowBase
+	{
+		readonly CompletionList completionList = new CompletionList();
+		ToolTip toolTip = new ToolTip();
+		
+		/// <summary>
+		/// Gets the completion list used in this completion window.
+		/// </summary>
+		public CompletionList CompletionList {
+			get { return completionList; }
+		}
+		
+		/// <summary>
+		/// Creates a new code completion window.
+		/// </summary>
+		public CompletionWindow(TextArea textArea) : base(textArea)
+		{
+			// keep height automatic
+			this.CloseAutomatically = true;
+			this.SizeToContent = SizeToContent.Height;
+			this.MaxHeight = 300;
+			this.Width = 175;
+			this.Content = completionList;
+			// prevent user from resizing window to 0x0
+			this.MinHeight = 15;
+			this.MinWidth = 30;
+			
+			toolTip.PlacementTarget = this;
+			toolTip.Placement = PlacementMode.Right;
+			toolTip.Closed += toolTip_Closed;
+			
+			AttachEvents();
+		}
+		
+		#region ToolTip handling
+		void toolTip_Closed(object sender, RoutedEventArgs e)
+		{
+			// Clear content after tooltip is closed.
+			// We cannot clear is immediately when setting IsOpen=false
+			// because the tooltip uses an animation for closing.
+			if (toolTip != null)
+				toolTip.Content = null;
+		}
+		
+		void completionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			var item = completionList.SelectedItem;
+			if (item == null)
+				return;
+			object description = item.Description;
+			if (description != null) {
+				string descriptionText = description as string;
+				if (descriptionText != null) {
+					toolTip.Content = new TextBlock  {
+						Text = descriptionText,
+						TextWrapping = TextWrapping.Wrap
+					};
+				} else {
+					toolTip.Content = description;
+				}
+				toolTip.IsOpen = true;
+			} else {
+				toolTip.IsOpen = false;
+			}
+		}
+		#endregion
+		
+		void completionList_InsertionRequested(object sender, EventArgs e)
+		{
+			Close();
+			// The window must close before Complete() is called.
+			// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
+			var item = completionList.SelectedItem;
+			if (item != null)
+				item.Complete(this.TextArea, new AnchorSegment(this.TextArea.Document, this.StartOffset, this.EndOffset - this.StartOffset), e);
+		}
+		
+		void AttachEvents()
+		{
+			this.completionList.InsertionRequested += completionList_InsertionRequested;
+			this.completionList.SelectionChanged += completionList_SelectionChanged;
+			this.TextArea.Caret.PositionChanged += CaretPositionChanged;
+			this.TextArea.MouseWheel += textArea_MouseWheel;
+			this.TextArea.PreviewTextInput += textArea_PreviewTextInput;
+		}
+		
+		/// <inheritdoc/>
+		protected override void DetachEvents()
+		{
+			this.completionList.InsertionRequested -= completionList_InsertionRequested;
+			this.completionList.SelectionChanged -= completionList_SelectionChanged;
+			this.TextArea.Caret.PositionChanged -= CaretPositionChanged;
+			this.TextArea.MouseWheel -= textArea_MouseWheel;
+			this.TextArea.PreviewTextInput -= textArea_PreviewTextInput;
+			base.DetachEvents();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnClosed(EventArgs e)
+		{
+			base.OnClosed(e);
+			if (toolTip != null) {
+				toolTip.IsOpen = false;
+				toolTip = null;
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnKeyDown(KeyEventArgs e)
+		{
+			base.OnKeyDown(e);
+			if (!e.Handled) {
+				completionList.HandleKey(e);
+			}
+		}
+		
+		void textArea_PreviewTextInput(object sender, TextCompositionEventArgs e)
+		{
+			e.Handled = RaiseEventPair(this, PreviewTextInputEvent, TextInputEvent,
+			                           new TextCompositionEventArgs(e.Device, e.TextComposition));
+		}
+		
+		void textArea_MouseWheel(object sender, MouseWheelEventArgs e)
+		{
+			e.Handled = RaiseEventPair(GetScrollEventTarget(),
+			                           PreviewMouseWheelEvent, MouseWheelEvent,
+			                           new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta));
+		}
+		
+		UIElement GetScrollEventTarget()
+		{
+			if (completionList == null)
+				return this;
+			return completionList.ScrollViewer ?? completionList.ListBox ?? (UIElement)completionList;
+		}
+		
+		/// <summary>
+		/// Gets/Sets whether the completion window should close automatically.
+		/// The default value is true.
+		/// </summary>
+		public bool CloseAutomatically { get; set; }
+		
+		/// <inheritdoc/>
+		protected override bool CloseOnFocusLost {
+			get { return this.CloseAutomatically; }
+		}
+		
+		/// <summary>
+		/// When this flag is set, code completion closes if the caret moves to the
+		/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
+		/// but not in dot-completion.
+		/// Has no effect if CloseAutomatically is false.
+		/// </summary>
+		public bool CloseWhenCaretAtBeginning { get; set; }
+		
+		void CaretPositionChanged(object sender, EventArgs e)
+		{
+			int offset = this.TextArea.Caret.Offset;
+			if (offset == this.StartOffset) {
+				if (CloseAutomatically && CloseWhenCaretAtBeginning) {
+					Close();
+				} else {
+					completionList.SelectItem(string.Empty);
+				}
+				return;
+			}
+			if (offset < this.StartOffset || offset > this.EndOffset) {
+				if (CloseAutomatically) {
+					Close();
+				}
+			} else {
+				TextDocument document = this.TextArea.Document;
+				if (document != null) {
+					completionList.SelectItem(document.GetText(this.StartOffset, offset - this.StartOffset));
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionWindowBase.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionWindowBase.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/CompletionWindowBase.cs	(revision 11807)
@@ -0,0 +1,397 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Threading;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// Base class for completion windows. Handles positioning the window at the caret.
+	/// </summary>
+	public class CompletionWindowBase : Window
+	{
+		static CompletionWindowBase()
+		{
+			WindowStyleProperty.OverrideMetadata(typeof(CompletionWindowBase), new FrameworkPropertyMetadata(WindowStyle.None));
+			ShowActivatedProperty.OverrideMetadata(typeof(CompletionWindowBase), new FrameworkPropertyMetadata(Boxes.False));
+			ShowInTaskbarProperty.OverrideMetadata(typeof(CompletionWindowBase), new FrameworkPropertyMetadata(Boxes.False));
+		}
+		
+		/// <summary>
+		/// Gets the parent TextArea.
+		/// </summary>
+		public TextArea TextArea { get; private set; }
+		
+		Window parentWindow;
+		TextDocument document;
+		
+		/// <summary>
+		/// Gets/Sets the start of the text range in which the completion window stays open.
+		/// This text portion is used to determine the text used to select an entry in the completion list by typing.
+		/// </summary>
+		public int StartOffset { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the end of the text range in which the completion window stays open.
+		/// This text portion is used to determine the text used to select an entry in the completion list by typing.
+		/// </summary>
+		public int EndOffset { get; set; }
+		
+		/// <summary>
+		/// Gets whether the window was opened above the current line.
+		/// </summary>
+		protected bool IsUp { get; private set; }
+		
+		/// <summary>
+		/// Creates a new CompletionWindowBase.
+		/// </summary>
+		public CompletionWindowBase(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.TextArea = textArea;
+			parentWindow = Window.GetWindow(textArea);
+			this.Owner = parentWindow;
+			this.AddHandler(MouseUpEvent, new MouseButtonEventHandler(OnMouseUp), true);
+			
+			StartOffset = EndOffset = this.TextArea.Caret.Offset;
+			
+			AttachEvents();
+		}
+		
+		#region Event Handlers
+		void AttachEvents()
+		{
+			document = this.TextArea.Document;
+			if (document != null) {
+				document.Changing += textArea_Document_Changing;
+			}
+			// LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729
+			this.TextArea.LostKeyboardFocus += TextAreaLostFocus;
+			this.TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged;
+			this.TextArea.DocumentChanged += TextAreaDocumentChanged;
+			if (parentWindow != null) {
+				parentWindow.LocationChanged += parentWindow_LocationChanged;
+			}
+			
+			// close previous completion windows of same type
+			foreach (InputHandler x in this.TextArea.StackedInputHandlers.OfType<InputHandler>()) {
+				if (x.window.GetType() == this.GetType())
+					this.TextArea.PopStackedInputHandler(x);
+			}
+			
+			myInputHandler = new InputHandler(this);
+			this.TextArea.PushStackedInputHandler(myInputHandler);
+		}
+		
+		/// <summary>
+		/// Detaches events from the text area.
+		/// </summary>
+		protected virtual void DetachEvents()
+		{
+			if (document != null) {
+				document.Changing -= textArea_Document_Changing;
+			}
+			this.TextArea.LostKeyboardFocus -= TextAreaLostFocus;
+			this.TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged;
+			this.TextArea.DocumentChanged -= TextAreaDocumentChanged;
+			if (parentWindow != null) {
+				parentWindow.LocationChanged -= parentWindow_LocationChanged;
+			}
+			this.TextArea.PopStackedInputHandler(myInputHandler);
+		}
+		
+		#region InputHandler
+		InputHandler myInputHandler;
+		
+		/// <summary>
+		/// A dummy input handler (that justs invokes the default input handler).
+		/// This is used to ensure the completion window closes when any other input handler
+		/// becomes active.
+		/// </summary>
+		sealed class InputHandler : TextAreaStackedInputHandler
+		{
+			internal readonly CompletionWindowBase window;
+			
+			public InputHandler(CompletionWindowBase window)
+				: base(window.TextArea)
+			{
+				Debug.Assert(window != null);
+				this.window = window;
+			}
+			
+			public override void Detach()
+			{
+				base.Detach();
+				window.Close();
+			}
+			
+			const Key KeyDeadCharProcessed = (Key)0xac; // Key.DeadCharProcessed; // new in .NET 4
+			
+			public override void OnPreviewKeyDown(KeyEventArgs e)
+			{
+				// prevents crash when typing deadchar while CC window is open
+				if (e.Key == KeyDeadCharProcessed)
+					return;
+				e.Handled = RaiseEventPair(window, PreviewKeyDownEvent, KeyDownEvent,
+				                           new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, e.Key));
+			}
+			
+			public override void OnPreviewKeyUp(KeyEventArgs e)
+			{
+				if (e.Key == KeyDeadCharProcessed)
+					return;
+				e.Handled = RaiseEventPair(window, PreviewKeyUpEvent, KeyUpEvent,
+				                           new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, e.Key));
+			}
+		}
+		#endregion
+		
+		void TextViewScrollOffsetChanged(object sender, EventArgs e)
+		{
+			// Workaround for crash #1580 (reproduction steps unknown):
+			// NullReferenceException in System.Windows.Window.CreateSourceWindow()
+			if (!sourceIsInitialized)
+				return;
+			
+			IScrollInfo scrollInfo = this.TextArea.TextView;
+			Rect visibleRect = new Rect(scrollInfo.HorizontalOffset, scrollInfo.VerticalOffset, scrollInfo.ViewportWidth, scrollInfo.ViewportHeight);
+			// close completion window when the user scrolls so far that the anchor position is leaving the visible area
+			if (visibleRect.Contains(visualLocation) || visibleRect.Contains(visualLocationTop))
+				UpdatePosition();
+			else
+				Close();
+		}
+		
+		void TextAreaDocumentChanged(object sender, EventArgs e)
+		{
+			Close();
+		}
+		
+		void TextAreaLostFocus(object sender, RoutedEventArgs e)
+		{
+			Dispatcher.BeginInvoke(new Action(CloseIfFocusLost), DispatcherPriority.Background);
+		}
+		
+		void parentWindow_LocationChanged(object sender, EventArgs e)
+		{
+			UpdatePosition();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnDeactivated(EventArgs e)
+		{
+			base.OnDeactivated(e);
+			Dispatcher.BeginInvoke(new Action(CloseIfFocusLost), DispatcherPriority.Background);
+		}
+		#endregion
+		
+		/// <summary>
+		/// Raises a tunnel/bubble event pair for a WPF control.
+		/// </summary>
+		/// <param name="target">The WPF control for which the event should be raised.</param>
+		/// <param name="previewEvent">The tunneling event.</param>
+		/// <param name="event">The bubbling event.</param>
+		/// <param name="args">The event args to use.</param>
+		/// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
+		protected static bool RaiseEventPair(UIElement target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args)
+		{
+			if (target == null)
+				throw new ArgumentNullException("target");
+			if (previewEvent == null)
+				throw new ArgumentNullException("previewEvent");
+			if (@event == null)
+				throw new ArgumentNullException("event");
+			if (args == null)
+				throw new ArgumentNullException("args");
+			args.RoutedEvent = previewEvent;
+			target.RaiseEvent(args);
+			args.RoutedEvent = @event;
+			target.RaiseEvent(args);
+			return args.Handled;
+		}
+		
+		// Special handler: handledEventsToo
+		void OnMouseUp(object sender, MouseButtonEventArgs e)
+		{
+			ActivateParentWindow();
+		}
+		
+		/// <summary>
+		/// Activates the parent window.
+		/// </summary>
+		protected virtual void ActivateParentWindow()
+		{
+			if (parentWindow != null)
+				parentWindow.Activate();
+		}
+		
+		void CloseIfFocusLost()
+		{
+			if (CloseOnFocusLost) {
+				Debug.WriteLine("CloseIfFocusLost: this.IsActive=" + this.IsActive + " IsTextAreaFocused=" + IsTextAreaFocused);
+				if (!this.IsActive && !IsTextAreaFocused) {
+					Close();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether the completion window should automatically close when the text editor looses focus.
+		/// </summary>
+		protected virtual bool CloseOnFocusLost {
+			get { return true; }
+		}
+		
+		bool IsTextAreaFocused {
+			get {
+				if (parentWindow != null && !parentWindow.IsActive)
+					return false;
+				return this.TextArea.IsKeyboardFocused;
+			}
+		}
+		
+		bool sourceIsInitialized;
+		
+		/// <inheritdoc/>
+		protected override void OnSourceInitialized(EventArgs e)
+		{
+			base.OnSourceInitialized(e);
+			
+			if (document != null && this.StartOffset != this.TextArea.Caret.Offset) {
+				SetPosition(new TextViewPosition(document.GetLocation(this.StartOffset)));
+			} else {
+				SetPosition(this.TextArea.Caret.Position);
+			}
+			sourceIsInitialized = true;
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnClosed(EventArgs e)
+		{
+			base.OnClosed(e);
+			DetachEvents();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnKeyDown(KeyEventArgs e)
+		{
+			base.OnKeyDown(e);
+			if (!e.Handled && e.Key == Key.Escape) {
+				e.Handled = true;
+				Close();
+			}
+		}
+		
+		Point visualLocation, visualLocationTop;
+		
+		/// <summary>
+		/// Positions the completion window at the specified position.
+		/// </summary>
+		protected void SetPosition(TextViewPosition position)
+		{
+			TextView textView = this.TextArea.TextView;
+			
+			visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom);
+			visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop);
+			UpdatePosition();
+		}
+		
+		/// <summary>
+		/// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area.
+		/// It ensures that the CompletionWindow is completely visible on the screen.
+		/// </summary>
+		protected void UpdatePosition()
+		{
+			TextView textView = this.TextArea.TextView;
+			// PointToScreen returns device dependent units (physical pixels)
+			Point location = textView.PointToScreen(visualLocation - textView.ScrollOffset);
+			Point locationTop = textView.PointToScreen(visualLocationTop - textView.ScrollOffset);
+			
+			// Let's use device dependent units for everything
+			Size completionWindowSize = new Size(this.ActualWidth, this.ActualHeight).TransformToDevice(textView);
+			Rect bounds = new Rect(location, completionWindowSize);
+			Rect workingScreen = System.Windows.Forms.Screen.GetWorkingArea(location.ToSystemDrawing()).ToWpf();
+			if (!workingScreen.Contains(bounds)) {
+				if (bounds.Left < workingScreen.Left) {
+					bounds.X = workingScreen.Left;
+				} else if (bounds.Right > workingScreen.Right) {
+					bounds.X = workingScreen.Right - bounds.Width;
+				}
+				if (bounds.Bottom > workingScreen.Bottom) {
+					bounds.Y = locationTop.Y - bounds.Height;
+					IsUp = true;
+				} else {
+					IsUp = false;
+				}
+				if (bounds.Y < workingScreen.Top) {
+					bounds.Y = workingScreen.Top;
+				}
+			}
+			// Convert the window bounds to device independent units
+			bounds = bounds.TransformFromDevice(textView);
+			this.Left = bounds.X;
+			this.Top = bounds.Y;
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
+		{
+			base.OnRenderSizeChanged(sizeInfo);
+			if (sizeInfo.HeightChanged && IsUp) {
+				this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets whether the completion window should expect text insertion at the start offset,
+		/// which not go into the completion region, but before it.
+		/// </summary>
+		/// <remarks>This property allows only a single insertion, it is reset to false
+		/// when that insertion has occurred.</remarks>
+		public bool ExpectInsertionBeforeStart { get; set; }
+		
+		void textArea_Document_Changing(object sender, DocumentChangeEventArgs e)
+		{
+			if (e.Offset + e.RemovalLength == this.StartOffset && e.RemovalLength > 0) {
+				Close(); // removal immediately in front of completion segment: close the window
+				// this is necessary when pressing backspace after dot-completion
+			}
+			if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) {
+				StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion);
+				this.ExpectInsertionBeforeStart = false;
+			} else {
+				StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion);
+			}
+			EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/ICompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/ICompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/ICompletionData.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Editing;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// Describes an entry in the <see cref="CompletionList"/>.
+	/// </summary>
+	public interface ICompletionData
+	{
+		/// <summary>
+		/// Gets the image.
+		/// </summary>
+		ImageSource Image { get; }
+		
+		/// <summary>
+		/// Gets the text. This property is used to filter the list of visible elements.
+		/// </summary>
+		string Text { get; }
+		
+		/// <summary>
+		/// The displayed content. This can be the same as 'Text', or a WPF UIElement if
+		/// you want to display rich content.
+		/// </summary>
+		object Content { get; }
+		
+		/// <summary>
+		/// Gets the description.
+		/// </summary>
+		object Description { get; }
+		
+		/// <summary>
+		/// Gets the priority. This property is used in the selection logic. You can use it to prefer selecting those items
+		/// which the user is accessing most frequently.
+		/// </summary>
+		double Priority { get; }
+		
+		/// <summary>
+		/// Perform the completion.
+		/// </summary>
+		/// <param name="textArea">The text area on which completion is performed.</param>
+		/// <param name="completionSegment">The text segment that was used by the completion window if
+		/// the user types (segment between CompletionWindow.StartOffset and CompletionWindow.EndOffset).</param>
+		/// <param name="insertionRequestEventArgs">The EventArgs used for the insertion request.
+		/// These can be TextCompositionEventArgs, KeyEventArgs, MouseEventArgs, depending on how
+		/// the insertion was triggered.</param>
+		void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/IOverloadProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/IOverloadProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/IOverloadProvider.cs	(revision 11807)
@@ -0,0 +1,57 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Windows;
+using System.Windows.Controls;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// Provides the items for the OverloadViewer.
+	/// </summary>
+	public interface IOverloadProvider : INotifyPropertyChanged
+	{
+		/// <summary>
+		/// Gets/Sets the selected index.
+		/// </summary>
+		int SelectedIndex { get; set; }
+		
+		/// <summary>
+		/// Gets the number of overloads.
+		/// </summary>
+		int Count { get; }
+		
+		/// <summary>
+		/// Gets the text 'SelectedIndex of Count'.
+		/// </summary>
+		string CurrentIndexText { get; }
+		
+		/// <summary>
+		/// Gets the current header.
+		/// </summary>
+		object CurrentHeader { get; }
+		
+		/// <summary>
+		/// Gets the current content.
+		/// </summary>
+		object CurrentContent { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/InsightWindow.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/InsightWindow.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/InsightWindow.cs	(revision 11807)
@@ -0,0 +1,109 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// A popup-like window that is attached to a text segment.
+	/// </summary>
+	public class InsightWindow : CompletionWindowBase
+	{
+		static InsightWindow()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(InsightWindow),
+			                                         new FrameworkPropertyMetadata(typeof(InsightWindow)));
+			AllowsTransparencyProperty.OverrideMetadata(typeof(InsightWindow),
+			                                            new FrameworkPropertyMetadata(Boxes.True));
+		}
+		
+		/// <summary>
+		/// Creates a new InsightWindow.
+		/// </summary>
+		public InsightWindow(TextArea textArea) : base(textArea)
+		{
+			this.CloseAutomatically = true;
+			AttachEvents();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnSourceInitialized(EventArgs e)
+		{
+			Rect caret = this.TextArea.Caret.CalculateCaretRectangle();
+			Point pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset);
+			Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this);
+			
+			MaxHeight = workingArea.Height;
+			MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6));
+			
+			base.OnSourceInitialized(e);
+		}
+		
+		/// <summary>
+		/// Gets/Sets whether the insight window should close automatically.
+		/// The default value is true.
+		/// </summary>
+		public bool CloseAutomatically { get; set; }
+		
+		/// <inheritdoc/>
+		protected override bool CloseOnFocusLost {
+			get { return this.CloseAutomatically; }
+		}
+		
+		void AttachEvents()
+		{
+			this.TextArea.Caret.PositionChanged += CaretPositionChanged;
+		}
+		
+		/// <inheritdoc/>
+		protected override void DetachEvents()
+		{
+			this.TextArea.Caret.PositionChanged -= CaretPositionChanged;
+			base.DetachEvents();
+		}
+		
+		void CaretPositionChanged(object sender, EventArgs e)
+		{
+			if (this.CloseAutomatically) {
+				int offset = this.TextArea.Caret.Offset;
+				if (offset < this.StartOffset || offset > this.EndOffset) {
+					Close();
+				}
+			}
+		}
+	}
+	
+	/// <summary>
+	/// TemplateSelector for InsightWindow to replace plain string content by a TextBlock with TextWrapping.
+	/// </summary>
+	internal sealed class InsightWindowTemplateSelector : DataTemplateSelector
+	{
+		public override DataTemplate SelectTemplate(object item, DependencyObject container)
+		{
+			if (item is string)
+				return (DataTemplate)((FrameworkElement)container).FindResource("TextBlockTemplate");
+			
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/InsightWindow.xaml
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/InsightWindow.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/InsightWindow.xaml	(revision 11807)
@@ -0,0 +1,118 @@
+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+	xmlns:cc="clr-namespace:ICSharpCode.AvalonEdit.CodeCompletion"
+>
+	<cc:InsightWindowTemplateSelector x:Key="templateSelector" />
+	
+	<!-- Template for InsightWindow. Based on the template for ToolTip. -->
+	<Style TargetType="{x:Type cc:InsightWindow}">
+		<Setter Property="SizeToContent" Value="WidthAndHeight" />
+		
+		<Setter Property="BorderThickness" Value="1" />
+		<Setter Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" />
+		<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.InfoBrushKey}}" />
+		<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.InfoTextBrushKey}}" />
+		<Setter Property="FontFamily" Value="{DynamicResource {x:Static SystemFonts.StatusFontFamilyKey}}" />
+		<Setter Property="FontSize" Value="{DynamicResource {x:Static SystemFonts.StatusFontSizeKey}}" />
+		<Setter Property="FontStyle" Value="{DynamicResource {x:Static SystemFonts.StatusFontStyleKey}}" />
+		<Setter Property="FontWeight" Value="{DynamicResource {x:Static SystemFonts.StatusFontWeightKey}}" />
+		<Setter Property="Padding" Value="1,1,3,1" />
+		<Setter Property="HorizontalContentAlignment" Value="Left" />
+		<Setter Property="VerticalContentAlignment" Value="Center" />
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type cc:InsightWindow}">
+					<Border BorderThickness="{TemplateBinding Border.BorderThickness}"
+					        Padding="{TemplateBinding Control.Padding}"
+					        CornerRadius="2,2,2,2"
+					        BorderBrush="{TemplateBinding Border.BorderBrush}"
+					        Background="{TemplateBinding Panel.Background}">
+						<AdornerDecorator>
+							<ContentPresenter
+								Content="{TemplateBinding ContentControl.Content}"
+								ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
+								ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
+								HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
+								VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
+								SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
+						</AdornerDecorator>
+					</Border>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+	
+	<!-- Template for OverloadViewer. -->
+	<Style TargetType="{x:Type cc:OverloadViewer}">
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type cc:OverloadViewer}">
+					<Grid>
+						<Grid.Resources>
+							<cc:CollapseIfSingleOverloadConverter x:Key="collapseIfSingleOverloadConverter"/>
+							
+							<!-- Style of the UpDownButton -->
+							<Style TargetType="{x:Type Button}" x:Key="upDownButtonStyle">
+								<Style.Setters>
+									<Setter Property="Background" Value="LightGray"/>
+									<Setter Property="Padding" Value="2,2,2,2"/>
+									<Setter Property="Width" Value="9"/>
+									<Setter Property="Height" Value="9"/>
+									<Setter Property="SnapsToDevicePixels" Value="True"/>
+									<Setter Property="OverridesDefaultStyle" Value="True"/>
+									<Setter Property="Template">
+										<Setter.Value>
+											<ControlTemplate TargetType="{x:Type Button}">
+												<Border Name="bd"
+												        Background="{TemplateBinding Background}" CornerRadius="2">
+													<ContentPresenter Margin="{TemplateBinding Padding}"
+													                  Content="{TemplateBinding Content}"/>
+												</Border>
+												<ControlTemplate.Triggers>
+													<Trigger Property="IsMouseOver" Value="true">
+														<Setter TargetName="bd" Property="Background" Value="LightBlue"/>
+													</Trigger>
+												</ControlTemplate.Triggers>
+											</ControlTemplate>
+										</Setter.Value>
+									</Setter>
+								</Style.Setters>
+							</Style>
+						
+							<DataTemplate x:Key="TextBlockTemplate">
+								<TextBlock TextWrapping="Wrap" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" />
+							</DataTemplate>
+						</Grid.Resources>
+						
+						<Grid.ColumnDefinitions>
+							<ColumnDefinition Width="Auto"/>
+							<ColumnDefinition Width="1*"/>
+						</Grid.ColumnDefinitions>
+						<Grid.RowDefinitions>
+							<RowDefinition Height="Auto"/>
+							<RowDefinition Height="1*"/>
+						</Grid.RowDefinitions>
+						
+						<StackPanel Grid.Row="0" Grid.Column="0"
+						            Margin="0,0,4,0"
+						            Orientation="Horizontal"
+						            Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Provider.Count, Converter={StaticResource collapseIfSingleOverloadConverter}}">
+							<Button Name="PART_UP" Style="{StaticResource upDownButtonStyle}">
+								<Path Stroke="Black" Fill="Black" Data="M 0,0.866 L 1,0.866 L 0.5,0 Z" Stretch="UniformToFill" />
+							</Button>
+							<TextBlock Margin="2,0,2,0"
+							           Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Provider.CurrentIndexText}"/>
+							<Button Name="PART_DOWN" Style="{StaticResource upDownButtonStyle}">
+								<Path Stroke="Black" Fill="Black" Data="M 0,0 L 1,0 L 0.5,0.866 Z" Stretch="UniformToFill" />
+							</Button>
+						</StackPanel>
+						<ContentPresenter Grid.Row="0" Grid.Column="1" ContentTemplateSelector="{StaticResource templateSelector}"
+						                  Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Provider.CurrentHeader}" />
+						<ContentPresenter Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ContentTemplateSelector="{StaticResource templateSelector}"
+						                  Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Provider.CurrentContent}" />
+					</Grid>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+</ResourceDictionary>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/OverloadInsightWindow.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/OverloadInsightWindow.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/OverloadInsightWindow.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Input;
+
+using ICSharpCode.AvalonEdit.Editing;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// Insight window that shows an OverloadViewer.
+	/// </summary>
+	public class OverloadInsightWindow : InsightWindow
+	{
+		OverloadViewer overloadViewer = new OverloadViewer();
+		
+		/// <summary>
+		/// Creates a new OverloadInsightWindow.
+		/// </summary>
+		public OverloadInsightWindow(TextArea textArea) : base(textArea)
+		{
+			overloadViewer.Margin = new Thickness(2,0,0,0);
+			this.Content = overloadViewer;
+		}
+		
+		/// <summary>
+		/// Gets/Sets the item provider.
+		/// </summary>
+		public IOverloadProvider Provider {
+			get { return overloadViewer.Provider; }
+			set { overloadViewer.Provider = value; }
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnKeyDown(KeyEventArgs e)
+		{
+			base.OnKeyDown(e);
+			if (!e.Handled && this.Provider.Count > 1) {
+				switch (e.Key) {
+					case Key.Up:
+						e.Handled = true;
+						overloadViewer.ChangeIndex(-1);
+						break;
+					case Key.Down:
+						e.Handled = true;
+						overloadViewer.ChangeIndex(+1);
+						break;
+				}
+				if (e.Handled) {
+					UpdateLayout();
+					UpdatePosition();
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/OverloadViewer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/OverloadViewer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/CodeCompletion/OverloadViewer.cs	(revision 11807)
@@ -0,0 +1,116 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+
+namespace ICSharpCode.AvalonEdit.CodeCompletion
+{
+	/// <summary>
+	/// Represents a text between "Up" and "Down" buttons.
+	/// </summary>
+	public class OverloadViewer : Control
+	{
+		static OverloadViewer()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(OverloadViewer),
+			                                         new FrameworkPropertyMetadata(typeof(OverloadViewer)));
+		}
+		
+		/// <summary>
+		/// The text property.
+		/// </summary>
+		public static readonly DependencyProperty TextProperty =
+			DependencyProperty.Register("Text", typeof(string), typeof(OverloadViewer));
+		
+		/// <summary>
+		/// Gets/Sets the text between the Up and Down buttons.
+		/// </summary>
+		public string Text {
+			get { return (string)GetValue(TextProperty); }
+			set { SetValue(TextProperty, value); }
+		}
+		
+		/// <inheritdoc/>
+		public override void OnApplyTemplate()
+		{
+			base.OnApplyTemplate();
+			
+			Button upButton = (Button)this.Template.FindName("PART_UP", this);
+			upButton.Click += (sender, e) => {
+				e.Handled = true;
+				ChangeIndex(-1);
+			};
+			
+			Button downButton = (Button)this.Template.FindName("PART_DOWN", this);
+			downButton.Click += (sender, e) => {
+				e.Handled = true;
+				ChangeIndex(+1);
+			};
+		}
+		
+		/// <summary>
+		/// The ItemProvider property.
+		/// </summary>
+		public static readonly DependencyProperty ProviderProperty =
+			DependencyProperty.Register("Provider", typeof(IOverloadProvider), typeof(OverloadViewer));
+		
+		/// <summary>
+		/// Gets/Sets the item provider.
+		/// </summary>
+		public IOverloadProvider Provider {
+			get { return (IOverloadProvider)GetValue(ProviderProperty); }
+			set { SetValue(ProviderProperty, value); }
+		}
+		
+		/// <summary>
+		/// Changes the selected index.
+		/// </summary>
+		/// <param name="relativeIndexChange">The relative index change - usual values are +1 or -1.</param>
+		public void ChangeIndex(int relativeIndexChange)
+		{
+			IOverloadProvider p = this.Provider;
+			if (p != null) {
+				int newIndex = p.SelectedIndex + relativeIndexChange;
+				if (newIndex < 0)
+					newIndex = p.Count - 1;
+				if (newIndex >= p.Count)
+					newIndex = 0;
+				p.SelectedIndex = newIndex;
+			}
+		}
+	}
+	
+	sealed class CollapseIfSingleOverloadConverter : IValueConverter
+	{
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return ((int)value < 2) ? Visibility.Collapsed : Visibility.Visible;
+		}
+		
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentChangeEventArgs.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentChangeEventArgs.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentChangeEventArgs.cs	(revision 11807)
@@ -0,0 +1,123 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Describes a change of the document text.
+	/// This class is thread-safe.
+	/// </summary>
+	[Serializable]
+	public class DocumentChangeEventArgs : TextChangeEventArgs
+	{
+		volatile OffsetChangeMap offsetChangeMap;
+		
+		/// <summary>
+		/// Gets the OffsetChangeMap associated with this document change.
+		/// </summary>
+		/// <remarks>The OffsetChangeMap instance is guaranteed to be frozen and thus thread-safe.</remarks>
+		public OffsetChangeMap OffsetChangeMap {
+			get {
+				OffsetChangeMap map = offsetChangeMap;
+				if (map == null) {
+					// create OffsetChangeMap on demand
+					map = OffsetChangeMap.FromSingleElement(CreateSingleChangeMapEntry());
+					offsetChangeMap = map;
+				}
+				return map;
+			}
+		}
+		
+		internal OffsetChangeMapEntry CreateSingleChangeMapEntry()
+		{
+			return new OffsetChangeMapEntry(this.Offset, this.RemovalLength, this.InsertionLength);
+		}
+		
+		/// <summary>
+		/// Gets the OffsetChangeMap, or null if the default offset map (=single replacement) is being used.
+		/// </summary>
+		internal OffsetChangeMap OffsetChangeMapOrNull {
+			get {
+				return offsetChangeMap;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the new offset where the specified offset moves after this document change.
+		/// </summary>
+		public override int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
+		{
+			if (offsetChangeMap != null)
+				return offsetChangeMap.GetNewOffset(offset, movementType);
+			else
+				return CreateSingleChangeMapEntry().GetNewOffset(offset, movementType);
+		}
+		
+		/// <summary>
+		/// Creates a new DocumentChangeEventArgs object.
+		/// </summary>
+		public DocumentChangeEventArgs(int offset, string removedText, string insertedText)
+			: this(offset, removedText, insertedText, null)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new DocumentChangeEventArgs object.
+		/// </summary>
+		public DocumentChangeEventArgs(int offset, string removedText, string insertedText, OffsetChangeMap offsetChangeMap)
+			: base(offset, removedText, insertedText)
+		{
+			SetOffsetChangeMap(offsetChangeMap);
+		}
+		
+		/// <summary>
+		/// Creates a new DocumentChangeEventArgs object.
+		/// </summary>
+		public DocumentChangeEventArgs(int offset, ITextSource removedText, ITextSource insertedText, OffsetChangeMap offsetChangeMap)
+			: base(offset, removedText, insertedText)
+		{
+			SetOffsetChangeMap(offsetChangeMap);
+		}
+		
+		void SetOffsetChangeMap(OffsetChangeMap offsetChangeMap)
+		{
+			if (offsetChangeMap != null) {
+				if (!offsetChangeMap.IsFrozen)
+					throw new ArgumentException("The OffsetChangeMap must be frozen before it can be used in DocumentChangeEventArgs");
+				if (!offsetChangeMap.IsValidForDocumentChange(this.Offset, this.RemovalLength, this.InsertionLength))
+					throw new ArgumentException("OffsetChangeMap is not valid for this document change", "offsetChangeMap");
+				this.offsetChangeMap = offsetChangeMap;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override TextChangeEventArgs Invert()
+		{
+			OffsetChangeMap map = this.OffsetChangeMapOrNull;
+			if (map != null) {
+				map = map.Invert();
+				map.Freeze();
+			}
+			return new DocumentChangeEventArgs(this.Offset, this.InsertedText, this.RemovedText, map);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentChangeOperation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentChangeOperation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentChangeOperation.cs	(revision 11807)
@@ -0,0 +1,67 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Describes a change to a TextDocument.
+	/// </summary>
+	sealed class DocumentChangeOperation : IUndoableOperationWithContext
+	{
+		TextDocument document;
+		DocumentChangeEventArgs change;
+		
+		public DocumentChangeOperation(TextDocument document, DocumentChangeEventArgs change)
+		{
+			this.document = document;
+			this.change = change;
+		}
+		
+		public void Undo(UndoStack stack)
+		{
+			Debug.Assert(stack.state == UndoStack.StatePlayback);
+			stack.RegisterAffectedDocument(document);
+			stack.state = UndoStack.StatePlaybackModifyDocument;
+			this.Undo();
+			stack.state = UndoStack.StatePlayback;
+		}
+		
+		public void Redo(UndoStack stack)
+		{
+			Debug.Assert(stack.state == UndoStack.StatePlayback);
+			stack.RegisterAffectedDocument(document);
+			stack.state = UndoStack.StatePlaybackModifyDocument;
+			this.Redo();
+			stack.state = UndoStack.StatePlayback;
+		}
+		
+		public void Undo()
+		{
+			OffsetChangeMap map = change.OffsetChangeMapOrNull;
+			document.Replace(change.Offset, change.InsertionLength, change.RemovedText, map != null ? map.Invert() : null);
+		}
+		
+		public void Redo()
+		{
+			document.Replace(change.Offset, change.RemovalLength, change.InsertedText, change.OffsetChangeMapOrNull);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentLine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentLine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentLine.cs	(revision 11807)
@@ -0,0 +1,268 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Globalization;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Represents a line inside a <see cref="TextDocument"/>.
+	/// </summary>
+	/// <remarks>
+	/// <para>
+	/// The <see cref="TextDocument.Lines"/> collection contains one DocumentLine instance
+	/// for every line in the document. This collection is read-only to user code and is automatically
+	/// updated to reflect the current document content.
+	/// </para>
+	/// <para>
+	/// Internally, the DocumentLine instances are arranged in a binary tree that allows for both efficient updates and lookup.
+	/// Converting between offset and line number is possible in O(lg N) time,
+	/// and the data structure also updates all offsets in O(lg N) whenever a line is inserted or removed.
+	/// </para>
+	/// </remarks>
+	public sealed partial class DocumentLine : IDocumentLine
+	{
+		#region Constructor
+		#if DEBUG
+		// Required for thread safety check which is done only in debug builds.
+		// To save space, we don't store the document reference in release builds as we don't need it there.
+		readonly TextDocument document;
+		#endif
+		
+		internal bool isDeleted;
+		
+		internal DocumentLine(TextDocument document)
+		{
+			#if DEBUG
+			Debug.Assert(document != null);
+			this.document = document;
+			#endif
+		}
+		
+		[Conditional("DEBUG")]
+		void DebugVerifyAccess()
+		{
+			#if DEBUG
+			document.DebugVerifyAccess();
+			#endif
+		}
+		#endregion
+		
+		#region Events
+//		/// <summary>
+//		/// Is raised when the line is deleted.
+//		/// </summary>
+//		public event EventHandler Deleted;
+//
+//		/// <summary>
+//		/// Is raised when the line's text changes.
+//		/// </summary>
+//		public event EventHandler TextChanged;
+//
+//		/// <summary>
+//		/// Raises the Deleted or TextChanged event.
+//		/// </summary>
+//		internal void RaiseChanged()
+//		{
+//			if (IsDeleted) {
+//				if (Deleted != null)
+//					Deleted(this, EventArgs.Empty);
+//			} else {
+//				if (TextChanged != null)
+//					TextChanged(this, EventArgs.Empty);
+//			}
+//		}
+		#endregion
+		
+		#region Properties stored in tree
+		/// <summary>
+		/// Gets if this line was deleted from the document.
+		/// </summary>
+		public bool IsDeleted {
+			get {
+				DebugVerifyAccess();
+				return isDeleted;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the number of this line.
+		/// Runtime: O(log n)
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The line was deleted.</exception>
+		public int LineNumber {
+			get {
+				if (IsDeleted)
+					throw new InvalidOperationException();
+				return DocumentLineTree.GetIndexFromNode(this) + 1;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the starting offset of the line in the document's text.
+		/// Runtime: O(log n)
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The line was deleted.</exception>
+		public int Offset {
+			get {
+				if (IsDeleted)
+					throw new InvalidOperationException();
+				return DocumentLineTree.GetOffsetFromNode(this);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the end offset of the line in the document's text (the offset before the line delimiter).
+		/// Runtime: O(log n)
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The line was deleted.</exception>
+		/// <remarks>EndOffset = <see cref="Offset"/> + <see cref="Length"/>.</remarks>
+		public int EndOffset {
+			get { return this.Offset + this.Length; }
+		}
+		#endregion
+		
+		#region Length
+		int totalLength;
+		byte delimiterLength;
+		
+		/// <summary>
+		/// Gets the length of this line. The length does not include the line delimiter. O(1)
+		/// </summary>
+		/// <remarks>This property is still available even if the line was deleted;
+		/// in that case, it contains the line's length before the deletion.</remarks>
+		public int Length {
+			get {
+				DebugVerifyAccess();
+				return totalLength - delimiterLength;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the length of this line, including the line delimiter. O(1)
+		/// </summary>
+		/// <remarks>This property is still available even if the line was deleted;
+		/// in that case, it contains the line's length before the deletion.</remarks>
+		public int TotalLength {
+			get {
+				DebugVerifyAccess();
+				return totalLength;
+			}
+			internal set {
+				// this is set by DocumentLineTree
+				totalLength = value;
+			}
+		}
+		
+		/// <summary>
+		/// <para>Gets the length of the line delimiter.</para>
+		/// <para>The value is 1 for single <c>"\r"</c> or <c>"\n"</c>, 2 for the <c>"\r\n"</c> sequence;
+		/// and 0 for the last line in the document.</para>
+		/// </summary>
+		/// <remarks>This property is still available even if the line was deleted;
+		/// in that case, it contains the line delimiter's length before the deletion.</remarks>
+		public int DelimiterLength {
+			get {
+				DebugVerifyAccess();
+				return delimiterLength;
+			}
+			internal set {
+				Debug.Assert(value >= 0 && value <= 2);
+				delimiterLength = (byte)value;
+			}
+		}
+		#endregion
+		
+		#region Previous / Next Line
+		/// <summary>
+		/// Gets the next line in the document.
+		/// </summary>
+		/// <returns>The line following this line, or null if this is the last line.</returns>
+		public DocumentLine NextLine {
+			get {
+				DebugVerifyAccess();
+				
+				if (right != null) {
+					return right.LeftMost;
+				} else {
+					DocumentLine node = this;
+					DocumentLine oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// we are on the way up from the right part, don't output node again
+					} while (node != null && node.right == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the previous line in the document.
+		/// </summary>
+		/// <returns>The line before this line, or null if this is the first line.</returns>
+		public DocumentLine PreviousLine {
+			get {
+				DebugVerifyAccess();
+				
+				if (left != null) {
+					return left.RightMost;
+				} else {
+					DocumentLine node = this;
+					DocumentLine oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// we are on the way up from the left part, don't output node again
+					} while (node != null && node.left == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		IDocumentLine IDocumentLine.NextLine {
+			get { return this.NextLine; }
+		}
+		
+		IDocumentLine IDocumentLine.PreviousLine {
+			get { return this.PreviousLine; }
+		}
+		#endregion
+		
+		#region ToString
+		/// <summary>
+		/// Gets a string with debug output showing the line number and offset.
+		/// Does not include the line's text.
+		/// </summary>
+		public override string ToString()
+		{
+			if (IsDeleted)
+				return "[DocumentLine deleted]";
+			else
+				return string.Format(
+					CultureInfo.InvariantCulture,
+					"[DocumentLine Number={0} Offset={1} Length={2}]", LineNumber, Offset, Length);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentLineTree.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentLineTree.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentLineTree.cs	(revision 11807)
@@ -0,0 +1,727 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	using LineNode = DocumentLine;
+	
+	/// <summary>
+	/// Data structure for efficient management of the document lines (most operations are O(lg n)).
+	/// This implements an augmented red-black tree.
+	/// See <see cref="LineNode"/> for the augmented data.
+	/// 
+	/// NOTE: The tree is never empty, initially it contains an empty line.
+	/// </summary>
+	sealed class DocumentLineTree : IList<DocumentLine>
+	{
+		#region Constructor
+		readonly TextDocument document;
+		LineNode root;
+		
+		public DocumentLineTree(TextDocument document)
+		{
+			this.document = document;
+			
+			DocumentLine emptyLine = new DocumentLine(document);
+			root = emptyLine.InitLineNode();
+		}
+		#endregion
+		
+		#region Rotation callbacks
+		internal static void UpdateAfterChildrenChange(LineNode node)
+		{
+			int totalCount = 1;
+			int totalLength = node.TotalLength;
+			if (node.left != null) {
+				totalCount += node.left.nodeTotalCount;
+				totalLength += node.left.nodeTotalLength;
+			}
+			if (node.right != null) {
+				totalCount += node.right.nodeTotalCount;
+				totalLength += node.right.nodeTotalLength;
+			}
+			if (totalCount != node.nodeTotalCount
+			    || totalLength != node.nodeTotalLength)
+			{
+				node.nodeTotalCount = totalCount;
+				node.nodeTotalLength = totalLength;
+				if (node.parent != null) UpdateAfterChildrenChange(node.parent);
+			}
+		}
+		
+		static void UpdateAfterRotateLeft(LineNode node)
+		{
+			UpdateAfterChildrenChange(node);
+			
+			// not required: rotations only happen on insertions/deletions
+			// -> totalCount changes -> the parent is always updated
+			//UpdateAfterChildrenChange(node.parent);
+		}
+		
+		static void UpdateAfterRotateRight(LineNode node)
+		{
+			UpdateAfterChildrenChange(node);
+			
+			// not required: rotations only happen on insertions/deletions
+			// -> totalCount changes -> the parent is always updated
+			//UpdateAfterChildrenChange(node.parent);
+		}
+		#endregion
+		
+		#region RebuildDocument
+		/// <summary>
+		/// Rebuild the tree, in O(n).
+		/// </summary>
+		public void RebuildTree(List<DocumentLine> documentLines)
+		{
+			LineNode[] nodes = new LineNode[documentLines.Count];
+			for (int i = 0; i < documentLines.Count; i++) {
+				DocumentLine ls = documentLines[i];
+				LineNode node = ls.InitLineNode();
+				nodes[i] = node;
+			}
+			Debug.Assert(nodes.Length > 0);
+			// now build the corresponding balanced tree
+			int height = GetTreeHeight(nodes.Length);
+			Debug.WriteLine("DocumentLineTree will have height: " + height);
+			root = BuildTree(nodes, 0, nodes.Length, height);
+			root.color = BLACK;
+			#if DEBUG
+			CheckProperties();
+			#endif
+		}
+		
+		internal static int GetTreeHeight(int size)
+		{
+			if (size == 0)
+				return 0;
+			else
+				return GetTreeHeight(size / 2) + 1;
+		}
+		
+		/// <summary>
+		/// build a tree from a list of nodes
+		/// </summary>
+		LineNode BuildTree(LineNode[] nodes, int start, int end, int subtreeHeight)
+		{
+			Debug.Assert(start <= end);
+			if (start == end) {
+				return null;
+			}
+			int middle = (start + end) / 2;
+			LineNode node = nodes[middle];
+			node.left = BuildTree(nodes, start, middle, subtreeHeight - 1);
+			node.right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
+			if (node.left != null) node.left.parent = node;
+			if (node.right != null) node.right.parent = node;
+			if (subtreeHeight == 1)
+				node.color = RED;
+			UpdateAfterChildrenChange(node);
+			return node;
+		}
+		#endregion
+		
+		#region GetNodeBy... / Get...FromNode
+		LineNode GetNodeByIndex(int index)
+		{
+			Debug.Assert(index >= 0);
+			Debug.Assert(index < root.nodeTotalCount);
+			LineNode node = root;
+			while (true) {
+				if (node.left != null && index < node.left.nodeTotalCount) {
+					node = node.left;
+				} else {
+					if (node.left != null) {
+						index -= node.left.nodeTotalCount;
+					}
+					if (index == 0)
+						return node;
+					index--;
+					node = node.right;
+				}
+			}
+		}
+		
+		internal static int GetIndexFromNode(LineNode node)
+		{
+			int index = (node.left != null) ? node.left.nodeTotalCount : 0;
+			while (node.parent != null) {
+				if (node == node.parent.right) {
+					if (node.parent.left != null)
+						index += node.parent.left.nodeTotalCount;
+					index++;
+				}
+				node = node.parent;
+			}
+			return index;
+		}
+		
+		LineNode GetNodeByOffset(int offset)
+		{
+			Debug.Assert(offset >= 0);
+			Debug.Assert(offset <= root.nodeTotalLength);
+			if (offset == root.nodeTotalLength) {
+				return root.RightMost;
+			}
+			LineNode node = root;
+			while (true) {
+				if (node.left != null && offset < node.left.nodeTotalLength) {
+					node = node.left;
+				} else {
+					if (node.left != null) {
+						offset -= node.left.nodeTotalLength;
+					}
+					offset -= node.TotalLength;
+					if (offset < 0)
+						return node;
+					node = node.right;
+				}
+			}
+		}
+		
+		internal static int GetOffsetFromNode(LineNode node)
+		{
+			int offset = (node.left != null) ? node.left.nodeTotalLength : 0;
+			while (node.parent != null) {
+				if (node == node.parent.right) {
+					if (node.parent.left != null)
+						offset += node.parent.left.nodeTotalLength;
+					offset += node.parent.TotalLength;
+				}
+				node = node.parent;
+			}
+			return offset;
+		}
+		#endregion
+		
+		#region GetLineBy
+		public DocumentLine GetByNumber(int number)
+		{
+			return GetNodeByIndex(number - 1);
+		}
+		
+		public DocumentLine GetByOffset(int offset)
+		{
+			return GetNodeByOffset(offset);
+		}
+		#endregion
+		
+		#region LineCount
+		public int LineCount {
+			get {
+				return root.nodeTotalCount;
+			}
+		}
+		#endregion
+		
+		#region CheckProperties
+		#if DEBUG
+		[Conditional("DATACONSISTENCYTEST")]
+		internal void CheckProperties()
+		{
+			Debug.Assert(root.nodeTotalLength == document.TextLength);
+			CheckProperties(root);
+			
+			// check red-black property:
+			int blackCount = -1;
+			CheckNodeProperties(root, null, RED, 0, ref blackCount);
+		}
+		
+		void CheckProperties(LineNode node)
+		{
+			int totalCount = 1;
+			int totalLength = node.TotalLength;
+			if (node.left != null) {
+				CheckProperties(node.left);
+				totalCount += node.left.nodeTotalCount;
+				totalLength += node.left.nodeTotalLength;
+			}
+			if (node.right != null) {
+				CheckProperties(node.right);
+				totalCount += node.right.nodeTotalCount;
+				totalLength += node.right.nodeTotalLength;
+			}
+			Debug.Assert(node.nodeTotalCount == totalCount);
+			Debug.Assert(node.nodeTotalLength == totalLength);
+		}
+		
+		/*
+		1. A node is either red or black.
+		2. The root is black.
+		3. All leaves are black. (The leaves are the NIL children.)
+		4. Both children of every red node are black. (So every red node must have a black parent.)
+		5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
+		 */
+		void CheckNodeProperties(LineNode node, LineNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
+		{
+			if (node == null) return;
+			
+			Debug.Assert(node.parent == parentNode);
+			
+			if (parentColor == RED) {
+				Debug.Assert(node.color == BLACK);
+			}
+			if (node.color == BLACK) {
+				blackCount++;
+			}
+			if (node.left == null && node.right == null) {
+				// node is a leaf node:
+				if (expectedBlackCount == -1)
+					expectedBlackCount = blackCount;
+				else
+					Debug.Assert(expectedBlackCount == blackCount);
+			}
+			CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
+			CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+		public string GetTreeAsString()
+		{
+			StringBuilder b = new StringBuilder();
+			AppendTreeToString(root, b, 0);
+			return b.ToString();
+		}
+		
+		static void AppendTreeToString(LineNode node, StringBuilder b, int indent)
+		{
+			if (node.color == RED)
+				b.Append("RED   ");
+			else
+				b.Append("BLACK ");
+			b.AppendLine(node.ToString());
+			indent += 2;
+			if (node.left != null) {
+				b.Append(' ', indent);
+				b.Append("L: ");
+				AppendTreeToString(node.left, b, indent);
+			}
+			if (node.right != null) {
+				b.Append(' ', indent);
+				b.Append("R: ");
+				AppendTreeToString(node.right, b, indent);
+			}
+		}
+		#endif
+		#endregion
+		
+		#region Insert/Remove lines
+		public void RemoveLine(DocumentLine line)
+		{
+			RemoveNode(line);
+			line.isDeleted = true;
+		}
+		
+		public DocumentLine InsertLineAfter(DocumentLine line, int totalLength)
+		{
+			DocumentLine newLine = new DocumentLine(document);
+			newLine.TotalLength = totalLength;
+			
+			InsertAfter(line, newLine);
+			return newLine;
+		}
+		
+		void InsertAfter(LineNode node, DocumentLine newLine)
+		{
+			LineNode newNode = newLine.InitLineNode();
+			if (node.right == null) {
+				InsertAsRight(node, newNode);
+			} else {
+				InsertAsLeft(node.right.LeftMost, newNode);
+			}
+		}
+		#endregion
+		
+		#region Red/Black Tree
+		internal const bool RED = true;
+		internal const bool BLACK = false;
+		
+		void InsertAsLeft(LineNode parentNode, LineNode newNode)
+		{
+			Debug.Assert(parentNode.left == null);
+			parentNode.left = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAfterChildrenChange(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void InsertAsRight(LineNode parentNode, LineNode newNode)
+		{
+			Debug.Assert(parentNode.right == null);
+			parentNode.right = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAfterChildrenChange(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void FixTreeOnInsert(LineNode node)
+		{
+			Debug.Assert(node != null);
+			Debug.Assert(node.color == RED);
+			Debug.Assert(node.left == null || node.left.color == BLACK);
+			Debug.Assert(node.right == null || node.right.color == BLACK);
+			
+			LineNode parentNode = node.parent;
+			if (parentNode == null) {
+				// we inserted in the root -> the node must be black
+				// since this is a root node, making the node black increments the number of black nodes
+				// on all paths by one, so it is still the same for all paths.
+				node.color = BLACK;
+				return;
+			}
+			if (parentNode.color == BLACK) {
+				// if the parent node where we inserted was black, our red node is placed correctly.
+				// since we inserted a red node, the number of black nodes on each path is unchanged
+				// -> the tree is still balanced
+				return;
+			}
+			// parentNode is red, so there is a conflict here!
+			
+			// because the root is black, parentNode is not the root -> there is a grandparent node
+			LineNode grandparentNode = parentNode.parent;
+			LineNode uncleNode = Sibling(parentNode);
+			if (uncleNode != null && uncleNode.color == RED) {
+				parentNode.color = BLACK;
+				uncleNode.color = BLACK;
+				grandparentNode.color = RED;
+				FixTreeOnInsert(grandparentNode);
+				return;
+			}
+			// now we know: parent is red but uncle is black
+			// First rotation:
+			if (node == parentNode.right && parentNode == grandparentNode.left) {
+				RotateLeft(parentNode);
+				node = node.left;
+			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
+				RotateRight(parentNode);
+				node = node.right;
+			}
+			// because node might have changed, reassign variables:
+			parentNode = node.parent;
+			grandparentNode = parentNode.parent;
+			
+			// Now recolor a bit:
+			parentNode.color = BLACK;
+			grandparentNode.color = RED;
+			// Second rotation:
+			if (node == parentNode.left && parentNode == grandparentNode.left) {
+				RotateRight(grandparentNode);
+			} else {
+				// because of the first rotation, this is guaranteed:
+				Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
+				RotateLeft(grandparentNode);
+			}
+		}
+		
+		void RemoveNode(LineNode removedNode)
+		{
+			if (removedNode.left != null && removedNode.right != null) {
+				// replace removedNode with it's in-order successor
+				
+				LineNode leftMost = removedNode.right.LeftMost;
+				RemoveNode(leftMost); // remove leftMost from its current location
+				
+				// and overwrite the removedNode with it
+				ReplaceNode(removedNode, leftMost);
+				leftMost.left = removedNode.left;
+				if (leftMost.left != null) leftMost.left.parent = leftMost;
+				leftMost.right = removedNode.right;
+				if (leftMost.right != null) leftMost.right.parent = leftMost;
+				leftMost.color = removedNode.color;
+				
+				UpdateAfterChildrenChange(leftMost);
+				if (leftMost.parent != null) UpdateAfterChildrenChange(leftMost.parent);
+				return;
+			}
+			
+			// now either removedNode.left or removedNode.right is null
+			// get the remaining child
+			LineNode parentNode = removedNode.parent;
+			LineNode childNode = removedNode.left ?? removedNode.right;
+			ReplaceNode(removedNode, childNode);
+			if (parentNode != null) UpdateAfterChildrenChange(parentNode);
+			if (removedNode.color == BLACK) {
+				if (childNode != null && childNode.color == RED) {
+					childNode.color = BLACK;
+				} else {
+					FixTreeOnDelete(childNode, parentNode);
+				}
+			}
+		}
+		
+		void FixTreeOnDelete(LineNode node, LineNode parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (parentNode == null)
+				return;
+			
+			// warning: node may be null
+			LineNode sibling = Sibling(node, parentNode);
+			if (sibling.color == RED) {
+				parentNode.color = RED;
+				sibling.color = BLACK;
+				if (node == parentNode.left) {
+					RotateLeft(parentNode);
+				} else {
+					RotateRight(parentNode);
+				}
+				
+				sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			}
+			
+			if (parentNode.color == BLACK
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				FixTreeOnDelete(parentNode, parentNode.parent);
+				return;
+			}
+			
+			if (parentNode.color == RED
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				parentNode.color = BLACK;
+				return;
+			}
+			
+			if (node == parentNode.left &&
+			    sibling.color == BLACK &&
+			    GetColor(sibling.left) == RED &&
+			    GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.left.color = BLACK;
+				RotateRight(sibling);
+			}
+			else if (node == parentNode.right &&
+			         sibling.color == BLACK &&
+			         GetColor(sibling.right) == RED &&
+			         GetColor(sibling.left) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.right.color = BLACK;
+				RotateLeft(sibling);
+			}
+			sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			
+			sibling.color = parentNode.color;
+			parentNode.color = BLACK;
+			if (node == parentNode.left) {
+				if (sibling.right != null) {
+					Debug.Assert(sibling.right.color == RED);
+					sibling.right.color = BLACK;
+				}
+				RotateLeft(parentNode);
+			} else {
+				if (sibling.left != null) {
+					Debug.Assert(sibling.left.color == RED);
+					sibling.left.color = BLACK;
+				}
+				RotateRight(parentNode);
+			}
+		}
+		
+		void ReplaceNode(LineNode replacedNode, LineNode newNode)
+		{
+			if (replacedNode.parent == null) {
+				Debug.Assert(replacedNode == root);
+				root = newNode;
+			} else {
+				if (replacedNode.parent.left == replacedNode)
+					replacedNode.parent.left = newNode;
+				else
+					replacedNode.parent.right = newNode;
+			}
+			if (newNode != null) {
+				newNode.parent = replacedNode.parent;
+			}
+			replacedNode.parent = null;
+		}
+		
+		void RotateLeft(LineNode p)
+		{
+			// let q be p's right child
+			LineNode q = p.right;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's right child to be q's left child
+			p.right = q.left;
+			if (p.right != null) p.right.parent = p;
+			// set q's left child to be p
+			q.left = p;
+			p.parent = q;
+			UpdateAfterRotateLeft(p);
+		}
+		
+		void RotateRight(LineNode p)
+		{
+			// let q be p's left child
+			LineNode q = p.left;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's left child to be q's right child
+			p.left = q.right;
+			if (p.left != null) p.left.parent = p;
+			// set q's right child to be p
+			q.right = p;
+			p.parent = q;
+			UpdateAfterRotateRight(p);
+		}
+		
+		static LineNode Sibling(LineNode node)
+		{
+			if (node == node.parent.left)
+				return node.parent.right;
+			else
+				return node.parent.left;
+		}
+		
+		static LineNode Sibling(LineNode node, LineNode parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (node == parentNode.left)
+				return parentNode.right;
+			else
+				return parentNode.left;
+		}
+		
+		static bool GetColor(LineNode node)
+		{
+			return node != null ? node.color : BLACK;
+		}
+		#endregion
+		
+		#region IList implementation
+		DocumentLine IList<DocumentLine>.this[int index] {
+			get {
+				document.VerifyAccess();
+				return GetByNumber(1 + index);
+			}
+			set {
+				throw new NotSupportedException();
+			}
+		}
+		
+		int ICollection<DocumentLine>.Count {
+			get {
+				document.VerifyAccess();
+				return LineCount;
+			}
+		}
+		
+		bool ICollection<DocumentLine>.IsReadOnly {
+			get { return true; }
+		}
+		
+		int IList<DocumentLine>.IndexOf(DocumentLine item)
+		{
+			document.VerifyAccess();
+			if (item == null || item.IsDeleted)
+				return -1;
+			int index = item.LineNumber - 1;
+			if (index < LineCount && GetNodeByIndex(index) == item)
+				return index;
+			else
+				return -1;
+		}
+		
+		void IList<DocumentLine>.Insert(int index, DocumentLine item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IList<DocumentLine>.RemoveAt(int index)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<DocumentLine>.Add(DocumentLine item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<DocumentLine>.Clear()
+		{
+			throw new NotSupportedException();
+		}
+		
+		bool ICollection<DocumentLine>.Contains(DocumentLine item)
+		{
+			IList<DocumentLine> self = this;
+			return self.IndexOf(item) >= 0;
+		}
+		
+		void ICollection<DocumentLine>.CopyTo(DocumentLine[] array, int arrayIndex)
+		{
+			if (array == null)
+				throw new ArgumentNullException("array");
+			if (array.Length < LineCount)
+				throw new ArgumentException("The array is too small", "array");
+			if (arrayIndex < 0 || arrayIndex + LineCount > array.Length)
+				throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "Value must be between 0 and " + (array.Length - LineCount));
+			foreach (DocumentLine ls in this) {
+				array[arrayIndex++] = ls;
+			}
+		}
+		
+		bool ICollection<DocumentLine>.Remove(DocumentLine item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		public IEnumerator<DocumentLine> GetEnumerator()
+		{
+			document.VerifyAccess();
+			return Enumerate();
+		}
+		
+		IEnumerator<DocumentLine> Enumerate()
+		{
+			document.VerifyAccess();
+			DocumentLine line = root.LeftMost;
+			while (line != null) {
+				yield return line;
+				line = line.NextLine;
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.GetEnumerator();
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentTextWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentTextWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/DocumentTextWriter.cs	(revision 11807)
@@ -0,0 +1,86 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using System.Text;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// A TextWriter implementation that directly inserts into a document.
+	/// </summary>
+	public class DocumentTextWriter : TextWriter
+	{
+		readonly IDocument document;
+		int insertionOffset;
+		
+		/// <summary>
+		/// Creates a new DocumentTextWriter that inserts into document, starting at insertionOffset.
+		/// </summary>
+		public DocumentTextWriter(IDocument document, int insertionOffset)
+		{
+			this.insertionOffset = insertionOffset;
+			if (document == null)
+				throw new ArgumentNullException("document");
+			this.document = document;
+			var line = document.GetLineByOffset(insertionOffset);
+			if (line.DelimiterLength == 0)
+				line = line.PreviousLine;
+			if (line != null)
+				this.NewLine = document.GetText(line.EndOffset, line.DelimiterLength);
+		}
+		
+		/// <summary>
+		/// Gets/Sets the current insertion offset.
+		/// </summary>
+		public int InsertionOffset {
+			get { return insertionOffset; }
+			set { insertionOffset = value; }
+		}
+		
+		/// <inheritdoc/>
+		public override void Write(char value)
+		{
+			document.Insert(insertionOffset, value.ToString());
+			insertionOffset++;
+		}
+		
+		/// <inheritdoc/>
+		public override void Write(char[] buffer, int index, int count)
+		{
+			document.Insert(insertionOffset, new string(buffer, index, count));
+			insertionOffset += count;
+		}
+		
+		/// <inheritdoc/>
+		public override void Write(string value)
+		{
+			document.Insert(insertionOffset, value);
+			insertionOffset += value.Length;
+		}
+		
+		/// <inheritdoc/>
+		public override Encoding Encoding {
+			get { return Encoding.UTF8; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/GapTextBuffer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/GapTextBuffer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/GapTextBuffer.cs	(revision 11807)
@@ -0,0 +1,207 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Text;
+
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/*
+	/// <summary>
+	/// Implementation of a gap text buffer.
+	/// </summary>
+	sealed class GapTextBuffer
+	{
+		char[] buffer = Empty<char>.Array;
+		
+		/// <summary>
+		/// The current text content.
+		/// Is set to null whenever the buffer changes, and gets a value only when the
+		/// full text content is requested.
+		/// </summary>
+		string textContent;
+		
+		/// <summary>
+		/// last GetText result
+		/// </summary>
+		string lastGetTextResult;
+		int lastGetTextRequestOffset;
+		
+		int gapBeginOffset;
+		int gapEndOffset;
+		int gapLength; // gapLength == gapEndOffset - gapBeginOffset
+		
+		/// <summary>
+		/// when gap is too small for inserted text or gap is too large (exceeds maxGapLength),
+		/// a new buffer is reallocated with a new gap of at least this size.
+		/// </summary>
+		const int minGapLength = 128;
+		
+		/// <summary>
+		/// when the gap exceeds this size, reallocate a smaller buffer
+		/// </summary>
+		const int maxGapLength = 4096;
+		
+		public int Length {
+			get {
+				return buffer.Length - gapLength;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the buffer content.
+		/// </summary>
+		public string Text {
+			get {
+				if (textContent == null)
+					textContent = GetText(0, Length);
+				return textContent;
+			}
+			set {
+				Debug.Assert(value != null);
+				textContent = value;  lastGetTextResult = null;
+				buffer = new char[value.Length + minGapLength];
+				value.CopyTo(0, buffer, 0, value.Length);
+				gapBeginOffset = value.Length;
+				gapEndOffset = buffer.Length;
+				gapLength = gapEndOffset - gapBeginOffset;
+			}
+		}
+		
+		public char GetCharAt(int offset)
+		{
+			return offset < gapBeginOffset ? buffer[offset] : buffer[offset + gapLength];
+		}
+		
+		public string GetText(int offset, int length)
+		{
+			if (length == 0)
+				return string.Empty;
+			if (lastGetTextRequestOffset == offset && lastGetTextResult != null && length == lastGetTextResult.Length)
+				return lastGetTextResult;
+			
+			int end = offset + length;
+			string result;
+			if (end < gapBeginOffset) {
+				result = new string(buffer, offset, length);
+			} else if (offset > gapBeginOffset) {
+				result = new string(buffer, offset + gapLength, length);
+			} else {
+				int block1Size = gapBeginOffset - offset;
+				int block2Size = end - gapBeginOffset;
+				
+				StringBuilder buf = new StringBuilder(block1Size + block2Size);
+				buf.Append(buffer, offset,       block1Size);
+				buf.Append(buffer, gapEndOffset, block2Size);
+				result = buf.ToString();
+			}
+			lastGetTextRequestOffset = offset;
+			lastGetTextResult = result;
+			return result;
+		}
+		
+		/// <summary>
+		/// Inserts text at the specified offset.
+		/// </summary>
+		public void Insert(int offset, string text)
+		{
+			Debug.Assert(offset >= 0 && offset <= Length);
+			
+			if (text.Length == 0)
+				return;
+			
+			textContent = null; lastGetTextResult = null;
+			PlaceGap(offset, text.Length);
+			text.CopyTo(0, buffer, gapBeginOffset, text.Length);
+			gapBeginOffset += text.Length;
+			gapLength = gapEndOffset - gapBeginOffset;
+		}
+		
+		/// <summary>
+		/// Remove <paramref name="length"/> characters at <paramref name="offset"/>.
+		/// Leave a gap of at least <paramref name="reserveGapSize"/>.
+		/// </summary>
+		public void Remove(int offset, int length, int reserveGapSize)
+		{
+			Debug.Assert(offset >= 0 && offset <= Length);
+			Debug.Assert(length >= 0 && offset + length <= Length);
+			Debug.Assert(reserveGapSize >= 0);
+			
+			if (length == 0)
+				return;
+			
+			textContent = null; lastGetTextResult = null;
+			PlaceGap(offset, reserveGapSize - length);
+			gapEndOffset += length; // delete removed text
+			gapLength = gapEndOffset - gapBeginOffset;
+			if (gapLength - reserveGapSize > maxGapLength && gapLength - reserveGapSize > buffer.Length / 4) {
+				// shrink gap
+				MakeNewBuffer(gapBeginOffset, reserveGapSize + minGapLength);
+			}
+		}
+		
+		void PlaceGap(int newGapOffset, int minRequiredGapLength)
+		{
+			if (gapLength < minRequiredGapLength) {
+				// enlarge gap
+				MakeNewBuffer(newGapOffset, minRequiredGapLength + Math.Max(minGapLength, buffer.Length / 8));
+			} else {
+				while (newGapOffset < gapBeginOffset) {
+					buffer[--gapEndOffset] = buffer[--gapBeginOffset];
+				}
+				while (newGapOffset > gapBeginOffset) {
+					buffer[gapBeginOffset++] = buffer[gapEndOffset++];
+				}
+			}
+		}
+		
+		void MakeNewBuffer(int newGapOffset, int newGapLength)
+		{
+			char[] newBuffer = new char[Length + newGapLength];
+			Debug.WriteLine("GapTextBuffer was reallocated, new size=" + newBuffer.Length);
+			if (newGapOffset < gapBeginOffset) {
+				// gap is moving backwards
+				
+				// first part:
+				Array.Copy(buffer, 0, newBuffer, 0, newGapOffset);
+				// moving middle part:
+				Array.Copy(buffer, newGapOffset, newBuffer, newGapOffset + newGapLength, gapBeginOffset - newGapOffset);
+				// last part:
+				Array.Copy(buffer, gapEndOffset, newBuffer, newBuffer.Length - (buffer.Length - gapEndOffset), buffer.Length - gapEndOffset);
+			} else {
+				// gap is moving forwards
+				// first part:
+				Array.Copy(buffer, 0, newBuffer, 0, gapBeginOffset);
+				// moving middle part:
+				Array.Copy(buffer, gapEndOffset, newBuffer, gapBeginOffset, newGapOffset - gapBeginOffset);
+				// last part:
+				int lastPartLength = newBuffer.Length - (newGapOffset + newGapLength);
+				Array.Copy(buffer, buffer.Length - lastPartLength, newBuffer, newGapOffset + newGapLength, lastPartLength);
+			}
+			
+			gapBeginOffset = newGapOffset;
+			gapEndOffset = newGapOffset + newGapLength;
+			gapLength = newGapLength;
+			buffer = newBuffer;
+		}
+	}
+	*/
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/IDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/IDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/IDocument.cs	(revision 11807)
@@ -0,0 +1,343 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	#if !NREFACTORY
+	/// <summary>
+	/// A document representing a source code file for refactoring.
+	/// Line and column counting starts at 1.
+	/// Offset counting starts at 0.
+	/// </summary>
+	public interface IDocument : ITextSource, IServiceProvider
+	{
+		#if NREFACTORY
+		/// <summary>
+		/// Creates an immutable snapshot of this document.
+		/// </summary>
+		IDocument CreateDocumentSnapshot();
+		#endif
+		
+		/// <summary>
+		/// Gets/Sets the text of the whole document..
+		/// </summary>
+		new string Text { get; set; } // hides ITextSource.Text to add the setter
+		
+		/// <summary>
+		/// This event is called directly before a change is applied to the document.
+		/// </summary>
+		/// <remarks>
+		/// It is invalid to modify the document within this event handler.
+		/// Aborting the change (by throwing an exception) is likely to cause corruption of data structures
+		/// that listen to the Changing and Changed events.
+		/// </remarks>
+		event EventHandler<TextChangeEventArgs> TextChanging;
+		
+		/// <summary>
+		/// This event is called directly after a change is applied to the document.
+		/// </summary>
+		/// <remarks>
+		/// It is invalid to modify the document within this event handler.
+		/// Aborting the event handler (by throwing an exception) is likely to cause corruption of data structures
+		/// that listen to the Changing and Changed events.
+		/// </remarks>
+		event EventHandler<TextChangeEventArgs> TextChanged;
+		
+		/// <summary>
+		/// This event is called after a group of changes is completed.
+		/// </summary>
+		/// <seealso cref="EndUndoableAction"/>
+		event EventHandler ChangeCompleted;
+		
+		/// <summary>
+		/// Gets the number of lines in the document.
+		/// </summary>
+		int LineCount { get; }
+		
+		/// <summary>
+		/// Gets the document line with the specified number.
+		/// </summary>
+		/// <param name="lineNumber">The number of the line to retrieve. The first line has number 1.</param>
+		IDocumentLine GetLineByNumber(int lineNumber);
+		
+		/// <summary>
+		/// Gets the document line that contains the specified offset.
+		/// </summary>
+		IDocumentLine GetLineByOffset(int offset);
+		
+		/// <summary>
+		/// Gets the offset from a text location.
+		/// </summary>
+		/// <seealso cref="GetLocation"/>
+		int GetOffset(int line, int column);
+		
+		/// <summary>
+		/// Gets the offset from a text location.
+		/// </summary>
+		/// <seealso cref="GetLocation"/>
+		int GetOffset(TextLocation location);
+		
+		/// <summary>
+		/// Gets the location from an offset.
+		/// </summary>
+		/// <seealso cref="GetOffset(TextLocation)"/>
+		TextLocation GetLocation(int offset);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <remarks>
+		/// Anchors positioned exactly at the insertion offset will move according to their movement type.
+		/// For AnchorMovementType.Default, they will move behind the inserted text.
+		/// The caret will also move behind the inserted text.
+		/// </remarks>
+		void Insert(int offset, string text);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <remarks>
+		/// Anchors positioned exactly at the insertion offset will move according to their movement type.
+		/// For AnchorMovementType.Default, they will move behind the inserted text.
+		/// The caret will also move behind the inserted text.
+		/// </remarks>
+		void Insert(int offset, ITextSource text);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="defaultAnchorMovementType">
+		/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
+		/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
+		/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
+		/// </param>
+		void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="defaultAnchorMovementType">
+		/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
+		/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
+		/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
+		/// </param>
+		void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType);
+		
+		/// <summary>
+		/// Removes text.
+		/// </summary>
+		/// <param name="offset">Starting offset of the text to be removed.</param>
+		/// <param name="length">Length of the text to be removed.</param>
+		void Remove(int offset, int length);
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="newText">The new text.</param>
+		void Replace(int offset, int length, string newText);
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="newText">The new text.</param>
+		void Replace(int offset, int length, ITextSource newText);
+		
+		/// <summary>
+		/// Make the document combine the following actions into a single
+		/// action for undo purposes.
+		/// </summary>
+		void StartUndoableAction();
+		
+		/// <summary>
+		/// Ends the undoable action started with <see cref="StartUndoableAction"/>.
+		/// </summary>
+		void EndUndoableAction();
+		
+		/// <summary>
+		/// Creates an undo group. Dispose the returned value to close the undo group.
+		/// </summary>
+		/// <returns>An object that closes the undo group when Dispose() is called.</returns>
+		IDisposable OpenUndoGroup();
+		
+		/// <summary>
+		/// Creates a new <see cref="ITextAnchor"/> at the specified offset.
+		/// </summary>
+		/// <inheritdoc cref="ITextAnchor" select="remarks|example"/>
+		ITextAnchor CreateAnchor(int offset);
+		
+		/// <summary>
+		/// Gets the name of the file the document is stored in.
+		/// Could also be a non-existent dummy file name or null if no name has been set.
+		/// </summary>
+		string FileName { get; }
+		
+		/// <summary>
+		/// Fired when the file name of the document changes.
+		/// </summary>
+		event EventHandler FileNameChanged;
+	}
+	
+	/// <summary>
+	/// A line inside a <see cref="IDocument"/>.
+	/// </summary>
+	public interface IDocumentLine : ISegment
+	{
+		/// <summary>
+		/// Gets the length of this line, including the line delimiter.
+		/// </summary>
+		int TotalLength { get; }
+		
+		/// <summary>
+		/// Gets the length of the line terminator.
+		/// Returns 1 or 2; or 0 at the end of the document.
+		/// </summary>
+		int DelimiterLength { get; }
+		
+		/// <summary>
+		/// Gets the number of this line.
+		/// The first line has the number 1.
+		/// </summary>
+		int LineNumber { get; }
+		
+		/// <summary>
+		/// Gets the previous line. Returns null if this is the first line in the document.
+		/// </summary>
+		IDocumentLine PreviousLine { get; }
+		
+		/// <summary>
+		/// Gets the next line. Returns null if this is the last line in the document.
+		/// </summary>
+		IDocumentLine NextLine { get; }
+		
+		/// <summary>
+		/// Gets whether the line was deleted.
+		/// </summary>
+		bool IsDeleted { get; }
+	}
+	
+	/// <summary>
+	/// Describes a change of the document text.
+	/// This class is thread-safe.
+	/// </summary>
+	[Serializable]
+	public class TextChangeEventArgs : EventArgs
+	{
+		readonly int offset;
+		readonly ITextSource removedText;
+		readonly ITextSource insertedText;
+		
+		/// <summary>
+		/// The offset at which the change occurs.
+		/// </summary>
+		public int Offset {
+			get { return offset; }
+		}
+		
+		/// <summary>
+		/// The text that was removed.
+		/// </summary>
+		public ITextSource RemovedText {
+			get { return removedText; }
+		}
+		
+		/// <summary>
+		/// The number of characters removed.
+		/// </summary>
+		public int RemovalLength {
+			get { return removedText.TextLength; }
+		}
+		
+		/// <summary>
+		/// The text that was inserted.
+		/// </summary>
+		public ITextSource InsertedText {
+			get { return insertedText; }
+		}
+		
+		/// <summary>
+		/// The number of characters inserted.
+		/// </summary>
+		public int InsertionLength {
+			get { return insertedText.TextLength; }
+		}
+		
+		/// <summary>
+		/// Creates a new TextChangeEventArgs object.
+		/// </summary>
+		public TextChangeEventArgs(int offset, string removedText, string insertedText)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset", offset, "offset must not be negative");
+			this.offset = offset;
+			this.removedText = removedText != null ? new StringTextSource(removedText) : StringTextSource.Empty;
+			this.insertedText = insertedText != null ? new StringTextSource(insertedText) : StringTextSource.Empty;
+		}
+		
+		/// <summary>
+		/// Creates a new TextChangeEventArgs object.
+		/// </summary>
+		public TextChangeEventArgs(int offset, ITextSource removedText, ITextSource insertedText)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset", offset, "offset must not be negative");
+			this.offset = offset;
+			this.removedText = removedText ?? StringTextSource.Empty;
+			this.insertedText = insertedText ?? StringTextSource.Empty;
+		}
+		
+		/// <summary>
+		/// Gets the new offset where the specified offset moves after this document change.
+		/// </summary>
+		public virtual int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
+		{
+			if (offset >= this.Offset && offset <= this.Offset + this.RemovalLength) {
+				if (movementType == AnchorMovementType.BeforeInsertion)
+					return this.Offset;
+				else
+					return this.Offset + this.InsertionLength;
+			} else if (offset > this.Offset) {
+				return offset + this.InsertionLength - this.RemovalLength;
+			} else {
+				return offset;
+			}
+		}
+		
+		/// <summary>
+		/// Creates TextChangeEventArgs for the reverse change.
+		/// </summary>
+		public virtual TextChangeEventArgs Invert()
+		{
+			return new TextChangeEventArgs(offset, insertedText, removedText);
+		}
+	}
+	#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ILineTracker.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ILineTracker.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ILineTracker.cs	(revision 11807)
@@ -0,0 +1,77 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Allows for low-level line tracking.
+	/// </summary>
+	/// <remarks>
+	/// The methods on this interface are called by the TextDocument's LineManager immediately after the document
+	/// has changed, *while* the DocumentLineTree is updating.
+	/// Thus, the DocumentLineTree may be in an invalid state when these methods are called.
+	/// This interface should only be used to update per-line data structures like the HeightTree.
+	/// Line trackers must not cause any events to be raised during an update to prevent other code from seeing
+	/// the invalid state.
+	/// Line trackers may be called while the TextDocument has taken a lock.
+	/// You must be careful not to dead-lock inside ILineTracker callbacks.
+	/// </remarks>
+	public interface ILineTracker
+	{
+		/// <summary>
+		/// Is called immediately before a document line is removed.
+		/// </summary>
+		void BeforeRemoveLine(DocumentLine line);
+		
+//		/// <summary>
+//		/// Is called immediately after a document line is removed.
+//		/// </summary>
+//		void AfterRemoveLine(DocumentLine line);
+		
+		/// <summary>
+		/// Is called immediately before a document line changes length.
+		/// This method will be called whenever the line is changed, even when the length stays as it is.
+		/// The method might be called multiple times for a single line because
+		/// a replacement is internally handled as removal followed by insertion.
+		/// </summary>
+		void SetLineLength(DocumentLine line, int newTotalLength);
+		
+		/// <summary>
+		/// Is called immediately after a line was inserted.
+		/// </summary>
+		/// <param name="newLine">The new line</param>
+		/// <param name="insertionPos">The existing line before the new line</param>
+		void LineInserted(DocumentLine insertionPos, DocumentLine newLine);
+		
+		/// <summary>
+		/// Indicates that there were changes to the document that the line tracker was not notified of.
+		/// The document is in a consistent state (but the line trackers aren't), and line trackers should
+		/// throw away their data and rebuild the document.
+		/// </summary>
+		void RebuildDocument();
+		
+		/// <summary>
+		/// Notifies the line tracker that a document change (a single change, not a change group) has completed.
+		/// This method gets called after the change has been performed, but before the <see cref="TextDocument.Changed"/> event
+		/// is raised.
+		/// </summary>
+		void ChangeComplete(DocumentChangeEventArgs e);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ITextAnchor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ITextAnchor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ITextAnchor.cs	(revision 11807)
@@ -0,0 +1,142 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	#if !NREFACTORY
+	/// <summary>
+	/// The TextAnchor class references an offset (a position between two characters).
+	/// It automatically updates the offset when text is inserted/removed in front of the anchor.
+	/// </summary>
+	/// <remarks>
+	/// <para>Use the <see cref="ITextAnchor.Offset"/> property to get the offset from a text anchor.
+	/// Use the <see cref="IDocument.CreateAnchor"/> method to create an anchor from an offset.
+	/// </para>
+	/// <para>
+	/// The document will automatically update all text anchors; and because it uses weak references to do so,
+	/// the garbage collector can simply collect the anchor object when you don't need it anymore.
+	/// </para>
+	/// <para>Moreover, the document is able to efficiently update a large number of anchors without having to look
+	/// at each anchor object individually. Updating the offsets of all anchors usually only takes time logarithmic
+	/// to the number of anchors. Retrieving the <see cref="ITextAnchor.Offset"/> property also runs in O(lg N).</para>
+	/// </remarks>
+	/// <example>
+	/// Usage:
+	/// <code>TextAnchor anchor = document.CreateAnchor(offset);
+	/// ChangeMyDocument();
+	/// int newOffset = anchor.Offset;
+	/// </code>
+	/// </example>
+	public interface ITextAnchor
+	{
+		/// <summary>
+		/// Gets the text location of this anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		TextLocation Location { get; }
+		
+		/// <summary>
+		/// Gets the offset of the text anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		int Offset { get; }
+		
+		/// <summary>
+		/// Controls how the anchor moves.
+		/// </summary>
+		/// <remarks>Anchor movement is ambiguous if text is inserted exactly at the anchor's location.
+		/// Does the anchor stay before the inserted text, or does it move after it?
+		/// The property <see cref="MovementType"/> will be used to determine which of these two options the anchor will choose.
+		/// The default value is <see cref="AnchorMovementType.Default"/>.</remarks>
+		AnchorMovementType MovementType { get; set; }
+		
+		/// <summary>
+		/// <para>
+		/// Specifies whether the anchor survives deletion of the text containing it.
+		/// </para><para>
+		/// <c>false</c>: The anchor is deleted when the a selection that includes the anchor is deleted.
+		/// <c>true</c>: The anchor is not deleted.
+		/// </para>
+		/// </summary>
+		/// <remarks><inheritdoc cref="IsDeleted" /></remarks>
+		bool SurviveDeletion { get; set; }
+		
+		/// <summary>
+		/// Gets whether the anchor was deleted.
+		/// </summary>
+		/// <remarks>
+		/// <para>When a piece of text containing an anchor is removed, then that anchor will be deleted.
+		/// First, the <see cref="IsDeleted"/> property is set to true on all deleted anchors,
+		/// then the <see cref="Deleted"/> events are raised.
+		/// You cannot retrieve the offset from an anchor that has been deleted.</para>
+		/// <para>This deletion behavior might be useful when using anchors for building a bookmark feature,
+		/// but in other cases you want to still be able to use the anchor. For those cases, set <c><see cref="SurviveDeletion"/> = true</c>.</para>
+		/// </remarks>
+		bool IsDeleted { get; }
+		
+		/// <summary>
+		/// Occurs after the anchor was deleted.
+		/// </summary>
+		/// <remarks>
+		/// <inheritdoc cref="IsDeleted" />
+		/// <para>Due to the 'weak reference' nature of text anchors, you will receive
+		/// the Deleted event only while your code holds a reference to the TextAnchor object.
+		/// </para>
+		/// </remarks>
+		event EventHandler Deleted;
+		
+		/// <summary>
+		/// Gets the line number of the anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		int Line { get; }
+		
+		/// <summary>
+		/// Gets the column number of this anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		int Column { get; }
+	}
+	
+	/// <summary>
+	/// Defines how a text anchor moves.
+	/// </summary>
+	public enum AnchorMovementType
+	{
+		/// <summary>
+		/// When text is inserted at the anchor position, the type of the insertion
+		/// determines where the caret moves to. For normal insertions, the anchor will move
+		/// after the inserted text.
+		/// </summary>
+		Default,
+		/// <summary>
+		/// Behaves like a start marker - when text is inserted at the anchor position, the anchor will stay
+		/// before the inserted text.
+		/// </summary>
+		BeforeInsertion,
+		/// <summary>
+		/// Behave like an end marker - when text is insered at the anchor position, the anchor will move
+		/// after the inserted text.
+		/// </summary>
+		AfterInsertion
+	}
+	#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ITextSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ITextSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/ITextSource.cs	(revision 11807)
@@ -0,0 +1,357 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System.Collections.Generic;
+using System;
+using System.IO;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	#if !NREFACTORY
+	/// <summary>
+	/// A read-only view on a (potentially mutable) text source.
+	/// The IDocument interface derives from this interface.
+	/// </summary>
+	public interface ITextSource
+	{
+		/// <summary>
+		/// Gets a version identifier for this text source.
+		/// Returns null for unversioned text sources.
+		/// </summary>
+		ITextSourceVersion Version { get; }
+		
+		/// <summary>
+		/// Creates an immutable snapshot of this text source.
+		/// Unlike all other methods in this interface, this method is thread-safe.
+		/// </summary>
+		ITextSource CreateSnapshot();
+		
+		/// <summary>
+		/// Creates an immutable snapshot of a part of this text source.
+		/// Unlike all other methods in this interface, this method is thread-safe.
+		/// </summary>
+		ITextSource CreateSnapshot(int offset, int length);
+		
+		/// <summary>
+		/// Creates a new TextReader to read from this text source.
+		/// </summary>
+		TextReader CreateReader();
+		
+		/// <summary>
+		/// Creates a new TextReader to read from this text source.
+		/// </summary>
+		TextReader CreateReader(int offset, int length);
+		
+		/// <summary>
+		/// Gets the total text length.
+		/// </summary>
+		/// <returns>The length of the text, in characters.</returns>
+		/// <remarks>This is the same as Text.Length, but is more efficient because
+		///  it doesn't require creating a String object.</remarks>
+		int TextLength { get; }
+		
+		/// <summary>
+		/// Gets the whole text as string.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
+		string Text { get; }
+		
+		/// <summary>
+		/// Gets a character at the specified position in the document.
+		/// </summary>
+		/// <paramref name="offset">The index of the character to get.</paramref>
+		/// <exception cref="ArgumentOutOfRangeException">Offset is outside the valid range (0 to TextLength-1).</exception>
+		/// <returns>The character at the specified position.</returns>
+		/// <remarks>This is the same as Text[offset], but is more efficient because
+		///  it doesn't require creating a String object.</remarks>
+		char GetCharAt(int offset);
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the document.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		/// <remarks>This is the same as Text.Substring, but is more efficient because
+		///  it doesn't require creating a String object for the whole document.</remarks>
+		string GetText(int offset, int length);
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the document.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		string GetText(ISegment segment);
+		
+		/// <summary>
+		/// Writes the text from this document into the TextWriter.
+		/// </summary>
+		void WriteTextTo(TextWriter writer);
+		
+		/// <summary>
+		/// Writes the text from this document into the TextWriter.
+		/// </summary>
+		void WriteTextTo(TextWriter writer, int offset, int length);
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of the character in the specified array.
+		/// </summary>
+		/// <param name="c">Character to search for</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The first index where the character was found; or -1 if no occurrence was found.</returns>
+		int IndexOf(char c, int startIndex, int count);
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of any character in the specified array.
+		/// </summary>
+		/// <param name="anyOf">Characters to search for</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The first index where any character was found; or -1 if no occurrence was found.</returns>
+		int IndexOfAny(char[] anyOf, int startIndex, int count);
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of the specified search text in this text source.
+		/// </summary>
+		/// <param name="searchText">The search text</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <param name="comparisonType">String comparison to use.</param>
+		/// <returns>The first index where the search term was found; or -1 if no occurrence was found.</returns>
+		int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType);
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the specified character in this text source.
+		/// </summary>
+		/// <param name="c">The search character</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The last index where the search term was found; or -1 if no occurrence was found.</returns>
+		/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
+		/// This is different than the meaning of the parameters on string.LastIndexOf!</remarks>
+		int LastIndexOf(char c, int startIndex, int count);
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the specified search text in this text source.
+		/// </summary>
+		/// <param name="searchText">The search text</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <param name="comparisonType">String comparison to use.</param>
+		/// <returns>The last index where the search term was found; or -1 if no occurrence was found.</returns>
+		/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
+		/// This is different than the meaning of the parameters on string.LastIndexOf!</remarks>
+		int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType);
+		
+		/* What about:
+		void Insert (int offset, string value);
+		void Remove (int offset, int count);
+		void Remove (ISegment segment);
+		
+		void Replace (int offset, int count, string value);
+		
+		Or more search operations:
+		
+		IEnumerable<int> SearchForward (string pattern, int startIndex);
+		IEnumerable<int> SearchForwardIgnoreCase (string pattern, int startIndex);
+		
+		IEnumerable<int> SearchBackward (string pattern, int startIndex);
+		IEnumerable<int> SearchBackwardIgnoreCase (string pattern, int startIndex);
+		*/
+	}
+	
+	/// <summary>
+	/// Represents a version identifier for a text source.
+	/// </summary>
+	/// <remarks>
+	/// Verions can be used to efficiently detect whether a document has changed and needs reparsing;
+	/// or even to implement incremental parsers.
+	/// It is a separate class from ITextSource to allow the GC to collect the text source while
+	/// the version checkpoint is still in use.
+	/// </remarks>
+	public interface ITextSourceVersion
+	{
+		/// <summary>
+		/// Gets whether this checkpoint belongs to the same document as the other checkpoint.
+		/// </summary>
+		/// <remarks>
+		/// Returns false when given <c>null</c>.
+		/// </remarks>
+		bool BelongsToSameDocumentAs(ITextSourceVersion other);
+		
+		/// <summary>
+		/// Compares the age of this checkpoint to the other checkpoint.
+		/// </summary>
+		/// <remarks>This method is thread-safe.</remarks>
+		/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this version.</exception>
+		/// <returns>-1 if this version is older than <paramref name="other"/>.
+		/// 0 if <c>this</c> version instance represents the same version as <paramref name="other"/>.
+		/// 1 if this version is newer than <paramref name="other"/>.</returns>
+		int CompareAge(ITextSourceVersion other);
+		
+		/// <summary>
+		/// Gets the changes from this checkpoint to the other checkpoint.
+		/// If 'other' is older than this checkpoint, reverse changes are calculated.
+		/// </summary>
+		/// <remarks>This method is thread-safe.</remarks>
+		/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this checkpoint.</exception>
+		IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other);
+		
+		/// <summary>
+		/// Calculates where the offset has moved in the other buffer version.
+		/// </summary>
+		/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this checkpoint.</exception>
+		int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement = AnchorMovementType.Default);
+	}
+	
+	/// <summary>
+	/// Implements the ITextSource interface using a string.
+	/// </summary>
+	[Serializable]
+	public class StringTextSource : ITextSource
+	{
+		/// <summary>
+		/// Gets a text source containing the empty string.
+		/// </summary>
+		public static readonly StringTextSource Empty = new StringTextSource(string.Empty);
+		
+		readonly string text;
+		readonly ITextSourceVersion version;
+		
+		/// <summary>
+		/// Creates a new StringTextSource with the given text.
+		/// </summary>
+		public StringTextSource(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+		}
+		
+		/// <summary>
+		/// Creates a new StringTextSource with the given text.
+		/// </summary>
+		public StringTextSource(string text, ITextSourceVersion version)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+			this.version = version;
+		}
+		
+		/// <inheritdoc/>
+		public ITextSourceVersion Version {
+			get { return version; }
+		}
+		
+		/// <inheritdoc/>
+		public int TextLength {
+			get { return text.Length; }
+		}
+		
+		/// <inheritdoc/>
+		public string Text {
+			get { return text; }
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot()
+		{
+			return this; // StringTextSource is immutable
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot(int offset, int length)
+		{
+			return new StringTextSource(text.Substring(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader()
+		{
+			return new StringReader(text);
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader(int offset, int length)
+		{
+			return new StringReader(text.Substring(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer)
+		{
+			writer.Write(text);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer, int offset, int length)
+		{
+			writer.Write(text.Substring(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public char GetCharAt(int offset)
+		{
+			return text[offset];
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(int offset, int length)
+		{
+			return text.Substring(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return text.Substring(segment.Offset, segment.Length);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(char c, int startIndex, int count)
+		{
+			return text.IndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOfAny(char[] anyOf, int startIndex, int count)
+		{
+			return text.IndexOfAny(anyOf, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return text.IndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(char c, int startIndex, int count)
+		{
+			return text.LastIndexOf(c, startIndex + count - 1, count);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return text.LastIndexOf(searchText, startIndex + count - 1, count, comparisonType);
+		}
+	}
+	#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/IUndoableOperation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/IUndoableOperation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/IUndoableOperation.cs	(revision 11807)
@@ -0,0 +1,45 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// This Interface describes a the basic Undo/Redo operation
+	/// all Undo Operations must implement this interface.
+	/// </summary>
+	public interface IUndoableOperation
+	{
+		/// <summary>
+		/// Undo the last operation
+		/// </summary>
+		void Undo();
+		
+		/// <summary>
+		/// Redo the last operation
+		/// </summary>
+		void Redo();
+	}
+	
+	interface IUndoableOperationWithContext : IUndoableOperation
+	{
+		void Undo(UndoStack stack);
+		void Redo(UndoStack stack);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/LineManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/LineManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/LineManager.cs	(revision 11807)
@@ -0,0 +1,318 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Creates/Deletes lines when text is inserted/removed.
+	/// </summary>
+	sealed class LineManager
+	{
+		#region Constructor
+		readonly TextDocument document;
+		readonly DocumentLineTree documentLineTree;
+		
+		/// <summary>
+		/// A copy of the line trackers. We need a copy so that line trackers may remove themselves
+		/// while being notified (used e.g. by WeakLineTracker)
+		/// </summary>
+		ILineTracker[] lineTrackers;
+		
+		internal void UpdateListOfLineTrackers()
+		{
+			this.lineTrackers = document.LineTrackers.ToArray();
+		}
+		
+		public LineManager(DocumentLineTree documentLineTree, TextDocument document)
+		{
+			this.document = document;
+			this.documentLineTree = documentLineTree;
+			UpdateListOfLineTrackers();
+			
+			Rebuild();
+		}
+		#endregion
+		
+		#region Change events
+		/*
+		HashSet<DocumentLine> deletedLines = new HashSet<DocumentLine>();
+		readonly HashSet<DocumentLine> changedLines = new HashSet<DocumentLine>();
+		HashSet<DocumentLine> deletedOrChangedLines = new HashSet<DocumentLine>();
+		
+		/// <summary>
+		/// Gets the list of lines deleted since the last RetrieveChangedLines() call.
+		/// The returned list is unsorted.
+		/// </summary>
+		public ICollection<DocumentLine> RetrieveDeletedLines()
+		{
+			var r = deletedLines;
+			deletedLines = new HashSet<DocumentLine>();
+			return r;
+		}
+		
+		/// <summary>
+		/// Gets the list of lines changed since the last RetrieveChangedLines() call.
+		/// The returned list is sorted by line number and does not contain deleted lines.
+		/// </summary>
+		public List<DocumentLine> RetrieveChangedLines()
+		{
+			var list = (from line in changedLines
+			            where !line.IsDeleted
+			            let number = line.LineNumber
+			            orderby number
+			            select line).ToList();
+			changedLines.Clear();
+			return list;
+		}
+		
+		/// <summary>
+		/// Gets the list of lines changed since the last RetrieveDeletedOrChangedLines() call.
+		/// The returned list is not sorted.
+		/// </summary>
+		public ICollection<DocumentLine> RetrieveDeletedOrChangedLines()
+		{
+			var r = deletedOrChangedLines;
+			deletedOrChangedLines = new HashSet<DocumentLine>();
+			return r;
+		}
+		 */
+		#endregion
+		
+		#region Rebuild
+		public void Rebuild()
+		{
+			// keep the first document line
+			DocumentLine ls = documentLineTree.GetByNumber(1);
+			// but mark all other lines as deleted, and detach them from the other nodes
+			for (DocumentLine line = ls.NextLine; line != null; line = line.NextLine) {
+				line.isDeleted = true;
+				line.parent = line.left = line.right = null;
+			}
+			// Reset the first line to detach it from the deleted lines
+			ls.ResetLine();
+			SimpleSegment ds = NewLineFinder.NextNewLine(document, 0);
+			List<DocumentLine> lines = new List<DocumentLine>();
+			int lastDelimiterEnd = 0;
+			while (ds != SimpleSegment.Invalid) {
+				ls.TotalLength = ds.Offset + ds.Length - lastDelimiterEnd;
+				ls.DelimiterLength = ds.Length;
+				lastDelimiterEnd = ds.Offset + ds.Length;
+				lines.Add(ls);
+				
+				ls = new DocumentLine(document);
+				ds = NewLineFinder.NextNewLine(document, lastDelimiterEnd);
+			}
+			ls.TotalLength = document.TextLength - lastDelimiterEnd;
+			lines.Add(ls);
+			documentLineTree.RebuildTree(lines);
+			foreach (ILineTracker lineTracker in lineTrackers)
+				lineTracker.RebuildDocument();
+		}
+		#endregion
+		
+		#region Remove
+		public void Remove(int offset, int length)
+		{
+			Debug.Assert(length >= 0);
+			if (length == 0) return;
+			DocumentLine startLine = documentLineTree.GetByOffset(offset);
+			int startLineOffset = startLine.Offset;
+			
+			Debug.Assert(offset < startLineOffset + startLine.TotalLength);
+			if (offset > startLineOffset + startLine.Length) {
+				Debug.Assert(startLine.DelimiterLength == 2);
+				// we are deleting starting in the middle of a delimiter
+				
+				// remove last delimiter part
+				SetLineLength(startLine, startLine.TotalLength - 1);
+				// remove remaining text
+				Remove(offset, length - 1);
+				return;
+			}
+			
+			if (offset + length < startLineOffset + startLine.TotalLength) {
+				// just removing a part of this line
+				//startLine.RemovedLinePart(ref deferredEventList, offset - startLineOffset, length);
+				SetLineLength(startLine, startLine.TotalLength - length);
+				return;
+			}
+			// merge startLine with another line because startLine's delimiter was deleted
+			// possibly remove lines in between if multiple delimiters were deleted
+			int charactersRemovedInStartLine = startLineOffset + startLine.TotalLength - offset;
+			Debug.Assert(charactersRemovedInStartLine > 0);
+			//startLine.RemovedLinePart(ref deferredEventList, offset - startLineOffset, charactersRemovedInStartLine);
+			
+			
+			DocumentLine endLine = documentLineTree.GetByOffset(offset + length);
+			if (endLine == startLine) {
+				// special case: we are removing a part of the last line up to the
+				// end of the document
+				SetLineLength(startLine, startLine.TotalLength - length);
+				return;
+			}
+			int endLineOffset = endLine.Offset;
+			int charactersLeftInEndLine = endLineOffset + endLine.TotalLength - (offset + length);
+			//endLine.RemovedLinePart(ref deferredEventList, 0, endLine.TotalLength - charactersLeftInEndLine);
+			//startLine.MergedWith(endLine, offset - startLineOffset);
+			
+			// remove all lines between startLine (excl.) and endLine (incl.)
+			DocumentLine tmp = startLine.NextLine;
+			DocumentLine lineToRemove;
+			do {
+				lineToRemove = tmp;
+				tmp = tmp.NextLine;
+				RemoveLine(lineToRemove);
+			} while (lineToRemove != endLine);
+			
+			SetLineLength(startLine, startLine.TotalLength - charactersRemovedInStartLine + charactersLeftInEndLine);
+		}
+
+		void RemoveLine(DocumentLine lineToRemove)
+		{
+			foreach (ILineTracker lt in lineTrackers)
+				lt.BeforeRemoveLine(lineToRemove);
+			documentLineTree.RemoveLine(lineToRemove);
+//			foreach (ILineTracker lt in lineTracker)
+//				lt.AfterRemoveLine(lineToRemove);
+//			deletedLines.Add(lineToRemove);
+//			deletedOrChangedLines.Add(lineToRemove);
+		}
+
+		#endregion
+		
+		#region Insert
+		public void Insert(int offset, ITextSource text)
+		{
+			DocumentLine line = documentLineTree.GetByOffset(offset);
+			int lineOffset = line.Offset;
+			
+			Debug.Assert(offset <= lineOffset + line.TotalLength);
+			if (offset > lineOffset + line.Length) {
+				Debug.Assert(line.DelimiterLength == 2);
+				// we are inserting in the middle of a delimiter
+				
+				// shorten line
+				SetLineLength(line, line.TotalLength - 1);
+				// add new line
+				line = InsertLineAfter(line, 1);
+				line = SetLineLength(line, 1);
+			}
+			
+			SimpleSegment ds = NewLineFinder.NextNewLine(text, 0);
+			if (ds == SimpleSegment.Invalid) {
+				// no newline is being inserted, all text is inserted in a single line
+				//line.InsertedLinePart(offset - line.Offset, text.Length);
+				SetLineLength(line, line.TotalLength + text.TextLength);
+				return;
+			}
+			//DocumentLine firstLine = line;
+			//firstLine.InsertedLinePart(offset - firstLine.Offset, ds.Offset);
+			int lastDelimiterEnd = 0;
+			while (ds != SimpleSegment.Invalid) {
+				// split line segment at line delimiter
+				int lineBreakOffset = offset + ds.Offset + ds.Length;
+				lineOffset = line.Offset;
+				int lengthAfterInsertionPos = lineOffset + line.TotalLength - (offset + lastDelimiterEnd);
+				line = SetLineLength(line, lineBreakOffset - lineOffset);
+				DocumentLine newLine = InsertLineAfter(line, lengthAfterInsertionPos);
+				newLine = SetLineLength(newLine, lengthAfterInsertionPos);
+				
+				line = newLine;
+				lastDelimiterEnd = ds.Offset + ds.Length;
+				
+				ds = NewLineFinder.NextNewLine(text, lastDelimiterEnd);
+			}
+			//firstLine.SplitTo(line);
+			// insert rest after last delimiter
+			if (lastDelimiterEnd != text.TextLength) {
+				//line.InsertedLinePart(0, text.Length - lastDelimiterEnd);
+				SetLineLength(line, line.TotalLength + text.TextLength - lastDelimiterEnd);
+			}
+		}
+		
+		DocumentLine InsertLineAfter(DocumentLine line, int length)
+		{
+			DocumentLine newLine = documentLineTree.InsertLineAfter(line, length);
+			foreach (ILineTracker lt in lineTrackers)
+				lt.LineInserted(line, newLine);
+			return newLine;
+		}
+		#endregion
+		
+		#region SetLineLength
+		/// <summary>
+		/// Sets the total line length and checks the delimiter.
+		/// This method can cause line to be deleted when it contains a single '\n' character
+		/// and the previous line ends with '\r'.
+		/// </summary>
+		/// <returns>Usually returns <paramref name="line"/>, but if line was deleted due to
+		/// the "\r\n" merge, returns the previous line.</returns>
+		DocumentLine SetLineLength(DocumentLine line, int newTotalLength)
+		{
+//			changedLines.Add(line);
+//			deletedOrChangedLines.Add(line);
+			int delta = newTotalLength - line.TotalLength;
+			if (delta != 0) {
+				foreach (ILineTracker lt in lineTrackers)
+					lt.SetLineLength(line, newTotalLength);
+				line.TotalLength = newTotalLength;
+				DocumentLineTree.UpdateAfterChildrenChange(line);
+			}
+			// determine new DelimiterLength
+			if (newTotalLength == 0) {
+				line.DelimiterLength = 0;
+			} else {
+				int lineOffset = line.Offset;
+				char lastChar = document.GetCharAt(lineOffset + newTotalLength - 1);
+				if (lastChar == '\r') {
+					line.DelimiterLength = 1;
+				} else if (lastChar == '\n') {
+					if (newTotalLength >= 2 && document.GetCharAt(lineOffset + newTotalLength - 2) == '\r') {
+						line.DelimiterLength = 2;
+					} else if (newTotalLength == 1 && lineOffset > 0 && document.GetCharAt(lineOffset - 1) == '\r') {
+						// we need to join this line with the previous line
+						DocumentLine previousLine = line.PreviousLine;
+						RemoveLine(line);
+						return SetLineLength(previousLine, previousLine.TotalLength + 1);
+					} else {
+						line.DelimiterLength = 1;
+					}
+				} else {
+					line.DelimiterLength = 0;
+				}
+			}
+			return line;
+		}
+		#endregion
+		
+		#region ChangeComplete
+		public void ChangeComplete(DocumentChangeEventArgs e)
+		{
+			foreach (ILineTracker lt in lineTrackers) {
+				lt.ChangeComplete(e);
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/LineNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/LineNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/LineNode.cs	(revision 11807)
@@ -0,0 +1,98 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	using LineNode = DocumentLine;
+	
+	// A tree node in the document line tree.
+	// For the purpose of the invariants, "children", "descendents", "siblings" etc. include the DocumentLine object,
+	// it is treated as a third child node between left and right.
+	
+	// Originally, this was a separate class, with a reference to the documentLine. The documentLine had a reference
+	// back to the node. To save memory, the same object is used for both the documentLine and the line node.
+	// This saves 16 bytes per line (8 byte object overhead + two pointers).
+//	sealed class LineNode
+//	{
+//		internal readonly DocumentLine documentLine;
+	partial class DocumentLine
+	{
+		internal DocumentLine left, right, parent;
+		internal bool color;
+		// optimization note: I tried packing color and isDeleted into a single byte field, but that
+		// actually increased the memory requirements. The JIT packs two bools and a byte (delimiterSize)
+		// into a single DWORD, but two bytes get each their own DWORD. Three bytes end up in the same DWORD, so
+		// apparently the JIT only optimizes for memory when there are at least three small fields.
+		// Currently, DocumentLine takes 36 bytes on x86 (8 byte object overhead, 3 pointers, 3 ints, and another DWORD
+		// for the small fields).
+		// TODO: a possible optimization would be to combine 'totalLength' and the small fields into a single uint.
+		// delimiterSize takes only two bits, the two bools take another two bits; so there's still 
+		// 28 bits left for totalLength. 268435455 characters per line should be enough for everyone :)
+		
+		/// <summary>
+		/// Resets the line to enable its reuse after a document rebuild.
+		/// </summary>
+		internal void ResetLine()
+		{
+			totalLength = delimiterLength = 0;
+			isDeleted = color = false;
+			left = right = parent = null;
+		}
+		
+		internal LineNode InitLineNode()
+		{
+			this.nodeTotalCount = 1;
+			this.nodeTotalLength = this.TotalLength;
+			return this;
+		}
+		
+		internal LineNode LeftMost {
+			get {
+				LineNode node = this;
+				while (node.left != null)
+					node = node.left;
+				return node;
+			}
+		}
+		
+		internal LineNode RightMost {
+			get {
+				LineNode node = this;
+				while (node.right != null)
+					node = node.right;
+				return node;
+			}
+		}
+		
+		/// <summary>
+		/// The number of lines in this node and its child nodes.
+		/// Invariant:
+		///   nodeTotalCount = 1 + left.nodeTotalCount + right.nodeTotalCount
+		/// </summary>
+		internal int nodeTotalCount;
+		
+		/// <summary>
+		/// The total text length of this node and its child nodes.
+		/// Invariant:
+		///   nodeTotalLength = left.nodeTotalLength + documentLine.TotalLength + right.nodeTotalLength
+		/// </summary>
+		internal int nodeTotalLength;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/NewLineFinder.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/NewLineFinder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/NewLineFinder.cs	(revision 11807)
@@ -0,0 +1,150 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	static class NewLineFinder
+	{
+		static readonly char[] newline = { '\r', '\n' };
+		
+		internal static readonly string[] NewlineStrings = { "\r\n", "\r", "\n" };
+		
+		/// <summary>
+		/// Gets the location of the next new line character, or SimpleSegment.Invalid
+		/// if none is found.
+		/// </summary>
+		internal static SimpleSegment NextNewLine(string text, int offset)
+		{
+			int pos = text.IndexOfAny(newline, offset);
+			if (pos >= 0) {
+				if (text[pos] == '\r') {
+					if (pos + 1 < text.Length && text[pos + 1] == '\n')
+						return new SimpleSegment(pos, 2);
+				}
+				return new SimpleSegment(pos, 1);
+			}
+			return SimpleSegment.Invalid;
+		}
+		
+		/// <summary>
+		/// Gets the location of the next new line character, or SimpleSegment.Invalid
+		/// if none is found.
+		/// </summary>
+		internal static SimpleSegment NextNewLine(ITextSource text, int offset)
+		{
+			int textLength = text.TextLength;
+			int pos = text.IndexOfAny(newline, offset, textLength - offset);
+			if (pos >= 0) {
+				if (text.GetCharAt(pos) == '\r') {
+					if (pos + 1 < textLength && text.GetCharAt(pos + 1) == '\n')
+						return new SimpleSegment(pos, 2);
+				}
+				return new SimpleSegment(pos, 1);
+			}
+			return SimpleSegment.Invalid;
+		}
+	}
+	
+	partial class TextUtilities
+	{
+		/// <summary>
+		/// Finds the next new line character starting at offset.
+		/// </summary>
+		/// <param name="text">The text source to search in.</param>
+		/// <param name="offset">The starting offset for the search.</param>
+		/// <param name="newLineType">The string representing the new line that was found, or null if no new line was found.</param>
+		/// <returns>The position of the first new line starting at or after <paramref name="offset"/>,
+		/// or -1 if no new line was found.</returns>
+		public static int FindNextNewLine(ITextSource text, int offset, out string newLineType)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (offset < 0 || offset > text.TextLength)
+				throw new ArgumentOutOfRangeException("offset", offset, "offset is outside of text source");
+			SimpleSegment s = NewLineFinder.NextNewLine(text, offset);
+			if (s == SimpleSegment.Invalid) {
+				newLineType = null;
+				return -1;
+			} else {
+				if (s.Length == 2) {
+					newLineType = "\r\n";
+				} else if (text.GetCharAt(s.Offset) == '\n') {
+					newLineType = "\n";
+				} else {
+					newLineType = "\r";
+				}
+				return s.Offset;
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether the specified string is a newline sequence.
+		/// </summary>
+		public static bool IsNewLine(string newLine)
+		{
+			return newLine == "\r\n" || newLine == "\n" || newLine == "\r";
+		}
+		
+		/// <summary>
+		/// Normalizes all new lines in <paramref name="input"/> to be <paramref name="newLine"/>.
+		/// </summary>
+		public static string NormalizeNewLines(string input, string newLine)
+		{
+			if (input == null)
+				return null;
+			if (!IsNewLine(newLine))
+				throw new ArgumentException("newLine must be one of the known newline sequences");
+			SimpleSegment ds = NewLineFinder.NextNewLine(input, 0);
+			if (ds == SimpleSegment.Invalid) // text does not contain any new lines
+				return input;
+			StringBuilder b = new StringBuilder(input.Length);
+			int lastEndOffset = 0;
+			do {
+				b.Append(input, lastEndOffset, ds.Offset - lastEndOffset);
+				b.Append(newLine);
+				lastEndOffset = ds.EndOffset;
+				ds = NewLineFinder.NextNewLine(input, lastEndOffset);
+			} while (ds != SimpleSegment.Invalid);
+			// remaining string (after last newline)
+			b.Append(input, lastEndOffset, input.Length - lastEndOffset);
+			return b.ToString();
+		}
+		
+		/// <summary>
+		/// Gets the newline sequence used in the document at the specified line.
+		/// </summary>
+		public static string GetNewLineFromDocument(IDocument document, int lineNumber)
+		{
+			IDocumentLine line = document.GetLineByNumber(lineNumber);
+			if (line.DelimiterLength == 0) {
+				// at the end of the document, there's no line delimiter, so use the delimiter
+				// from the previous line
+				line = line.PreviousLine;
+				if (line == null)
+					return Environment.NewLine;
+			}
+			return document.GetText(line.Offset + line.Length, line.DelimiterLength);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/OffsetChangeMap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/OffsetChangeMap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/OffsetChangeMap.cs	(revision 11807)
@@ -0,0 +1,364 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Contains predefined offset change mapping types.
+	/// </summary>
+	public enum OffsetChangeMappingType
+	{
+		/// <summary>
+		/// Normal replace.
+		/// Anchors in front of the replaced region will stay in front, anchors after the replaced region will stay after.
+		/// Anchors in the middle of the removed region will be deleted. If they survive deletion,
+		/// they move depending on their AnchorMovementType.
+		/// </summary>
+		/// <remarks>
+		/// This is the default implementation of DocumentChangeEventArgs when OffsetChangeMap is null,
+		/// so using this option usually works without creating an OffsetChangeMap instance.
+		/// This is equivalent to an OffsetChangeMap with a single entry describing the replace operation.
+		/// </remarks>
+		Normal,
+		/// <summary>
+		/// First the old text is removed, then the new text is inserted.
+		/// Anchors immediately in front (or after) the replaced region may move to the other side of the insertion,
+		/// depending on the AnchorMovementType.
+		/// </summary>
+		/// <remarks>
+		/// This is implemented as an OffsetChangeMap with two entries: the removal, and the insertion.
+		/// </remarks>
+		RemoveAndInsert,
+		/// <summary>
+		/// The text is replaced character-by-character.
+		/// Anchors keep their position inside the replaced text.
+		/// Anchors after the replaced region will move accordingly if the replacement text has a different length than the replaced text.
+		/// If the new text is shorter than the old text, anchors inside the old text that would end up behind the replacement text
+		/// will be moved so that they point to the end of the replacement text.
+		/// </summary>
+		/// <remarks>
+		/// On the OffsetChangeMap level, growing text is implemented by replacing the last character in the replaced text
+		/// with itself and the additional text segment. A simple insertion of the additional text would have the undesired
+		/// effect of moving anchors immediately after the replaced text into the replacement text if they used
+		/// AnchorMovementStyle.BeforeInsertion.
+		/// Shrinking text is implemented by removing the text segment that's too long; but in a special mode that
+		/// causes anchors to always survive irrespective of their <see cref="TextAnchor.SurviveDeletion"/> setting.
+		/// If the text keeps its old size, this is implemented as OffsetChangeMap.Empty.
+		/// </remarks>
+		CharacterReplace,
+		/// <summary>
+		/// Like 'Normal', but anchors with <see cref="TextAnchor.MovementType"/> = Default will stay in front of the
+		/// insertion instead of being moved behind it.
+		/// </summary>
+		KeepAnchorBeforeInsertion
+	}
+	
+	/// <summary>
+	/// Describes a series of offset changes.
+	/// </summary>
+	[Serializable]
+	[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
+	                 Justification="It's a mapping old offsets -> new offsets")]
+	public sealed class OffsetChangeMap : Collection<OffsetChangeMapEntry>
+	{
+		/// <summary>
+		/// Immutable OffsetChangeMap that is empty.
+		/// </summary>
+		[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",
+		                 Justification="The Empty instance is immutable")]
+		public static readonly OffsetChangeMap Empty = new OffsetChangeMap(Empty<OffsetChangeMapEntry>.Array, true);
+		
+		/// <summary>
+		/// Creates a new OffsetChangeMap with a single element.
+		/// </summary>
+		/// <param name="entry">The entry.</param>
+		/// <returns>Returns a frozen OffsetChangeMap with a single entry.</returns>
+		public static OffsetChangeMap FromSingleElement(OffsetChangeMapEntry entry)
+		{
+			return new OffsetChangeMap(new OffsetChangeMapEntry[] { entry }, true);
+		}
+		
+		bool isFrozen;
+		
+		/// <summary>
+		/// Creates a new OffsetChangeMap instance.
+		/// </summary>
+		public OffsetChangeMap()
+		{
+		}
+		
+		internal OffsetChangeMap(int capacity)
+			: base(new List<OffsetChangeMapEntry>(capacity))
+		{
+		}
+		
+		private OffsetChangeMap(IList<OffsetChangeMapEntry> entries, bool isFrozen)
+			: base(entries)
+		{
+			this.isFrozen = isFrozen;
+		}
+		
+		/// <summary>
+		/// Gets the new offset where the specified offset moves after this document change.
+		/// </summary>
+		public int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
+		{
+			IList<OffsetChangeMapEntry> items = this.Items;
+			int count = items.Count;
+			for (int i = 0; i < count; i++) {
+				offset = items[i].GetNewOffset(offset, movementType);
+			}
+			return offset;
+		}
+		
+		/// <summary>
+		/// Gets whether this OffsetChangeMap is a valid explanation for the specified document change.
+		/// </summary>
+		public bool IsValidForDocumentChange(int offset, int removalLength, int insertionLength)
+		{
+			int endOffset = offset + removalLength;
+			foreach (OffsetChangeMapEntry entry in this) {
+				// check that ChangeMapEntry is in valid range for this document change
+				if (entry.Offset < offset || entry.Offset + entry.RemovalLength > endOffset)
+					return false;
+				endOffset += entry.InsertionLength - entry.RemovalLength;
+			}
+			// check that the total delta matches
+			return endOffset == offset + insertionLength;
+		}
+		
+		/// <summary>
+		/// Calculates the inverted OffsetChangeMap (used for the undo operation).
+		/// </summary>
+		public OffsetChangeMap Invert()
+		{
+			if (this == Empty)
+				return this;
+			OffsetChangeMap newMap = new OffsetChangeMap(this.Count);
+			for (int i = this.Count - 1; i >= 0; i--) {
+				OffsetChangeMapEntry entry = this[i];
+				// swap InsertionLength and RemovalLength
+				newMap.Add(new OffsetChangeMapEntry(entry.Offset, entry.InsertionLength, entry.RemovalLength));
+			}
+			return newMap;
+		}
+		
+		/// <inheritdoc/>
+		protected override void ClearItems()
+		{
+			CheckFrozen();
+			base.ClearItems();
+		}
+		
+		/// <inheritdoc/>
+		protected override void InsertItem(int index, OffsetChangeMapEntry item)
+		{
+			CheckFrozen();
+			base.InsertItem(index, item);
+		}
+		
+		/// <inheritdoc/>
+		protected override void RemoveItem(int index)
+		{
+			CheckFrozen();
+			base.RemoveItem(index);
+		}
+		
+		/// <inheritdoc/>
+		protected override void SetItem(int index, OffsetChangeMapEntry item)
+		{
+			CheckFrozen();
+			base.SetItem(index, item);
+		}
+		
+		void CheckFrozen()
+		{
+			if (isFrozen)
+				throw new InvalidOperationException("This instance is frozen and cannot be modified.");
+		}
+		
+		/// <summary>
+		/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
+		/// </summary>
+		public bool IsFrozen {
+			get { return isFrozen; }
+		}
+		
+		/// <summary>
+		/// Freezes this instance.
+		/// </summary>
+		public void Freeze()
+		{
+			isFrozen = true;
+		}
+	}
+	
+	/// <summary>
+	/// An entry in the OffsetChangeMap.
+	/// This represents the offset of a document change (either insertion or removal, not both at once).
+	/// </summary>
+	[Serializable]
+	public struct OffsetChangeMapEntry : IEquatable<OffsetChangeMapEntry>
+	{
+		readonly int offset;
+		
+		// MSB: DefaultAnchorMovementIsBeforeInsertion
+		readonly uint insertionLengthWithMovementFlag;
+		
+		// MSB: RemovalNeverCausesAnchorDeletion; other 31 bits: RemovalLength
+		readonly uint removalLengthWithDeletionFlag;
+		
+		/// <summary>
+		/// The offset at which the change occurs.
+		/// </summary>
+		public int Offset {
+			get { return offset; }
+		}
+		
+		/// <summary>
+		/// The number of characters inserted.
+		/// Returns 0 if this entry represents a removal.
+		/// </summary>
+		public int InsertionLength {
+			get { return (int)(insertionLengthWithMovementFlag & 0x7fffffff); }
+		}
+		
+		/// <summary>
+		/// The number of characters removed.
+		/// Returns 0 if this entry represents an insertion.
+		/// </summary>
+		public int RemovalLength {
+			get { return (int)(removalLengthWithDeletionFlag & 0x7fffffff); }
+		}
+		
+		/// <summary>
+		/// Gets whether the removal should not cause any anchor deletions.
+		/// </summary>
+		public bool RemovalNeverCausesAnchorDeletion {
+			get { return (removalLengthWithDeletionFlag & 0x80000000) != 0; }
+		}
+		
+		/// <summary>
+		/// Gets whether default anchor movement causes the anchor to stay in front of the caret.
+		/// </summary>
+		public bool DefaultAnchorMovementIsBeforeInsertion {
+			get { return (insertionLengthWithMovementFlag & 0x80000000) != 0; }
+		}
+		
+		/// <summary>
+		/// Gets the new offset where the specified offset moves after this document change.
+		/// </summary>
+		public int GetNewOffset(int oldOffset, AnchorMovementType movementType = AnchorMovementType.Default)
+		{
+			int insertionLength = this.InsertionLength;
+			int removalLength = this.RemovalLength;
+			if (!(removalLength == 0 && oldOffset == offset)) {
+				// we're getting trouble (both if statements in here would apply)
+				// if there's no removal and we insert at the offset
+				// -> we'd need to disambiguate by movementType, which is handled after the if
+				
+				// offset is before start of change: no movement
+				if (oldOffset <= offset)
+					return oldOffset;
+				// offset is after end of change: movement by normal delta
+				if (oldOffset >= offset + removalLength)
+					return oldOffset + insertionLength - removalLength;
+			}
+			// we reach this point if
+			// a) the oldOffset is inside the deleted segment
+			// b) there was no removal and we insert at the caret position
+			if (movementType == AnchorMovementType.AfterInsertion)
+				return offset + insertionLength;
+			else if (movementType == AnchorMovementType.BeforeInsertion)
+				return offset;
+			else
+				return this.DefaultAnchorMovementIsBeforeInsertion ? offset : offset + insertionLength;
+		}
+		
+		/// <summary>
+		/// Creates a new OffsetChangeMapEntry instance.
+		/// </summary>
+		public OffsetChangeMapEntry(int offset, int removalLength, int insertionLength)
+		{
+			ThrowUtil.CheckNotNegative(offset, "offset");
+			ThrowUtil.CheckNotNegative(removalLength, "removalLength");
+			ThrowUtil.CheckNotNegative(insertionLength, "insertionLength");
+			
+			this.offset = offset;
+			this.removalLengthWithDeletionFlag = (uint)removalLength;
+			this.insertionLengthWithMovementFlag = (uint)insertionLength;
+		}
+		
+		/// <summary>
+		/// Creates a new OffsetChangeMapEntry instance.
+		/// </summary>
+		public OffsetChangeMapEntry(int offset, int removalLength, int insertionLength, bool removalNeverCausesAnchorDeletion, bool defaultAnchorMovementIsBeforeInsertion)
+			: this(offset, removalLength, insertionLength)
+		{
+			if (removalNeverCausesAnchorDeletion)
+				this.removalLengthWithDeletionFlag |= 0x80000000;
+			if (defaultAnchorMovementIsBeforeInsertion)
+				this.insertionLengthWithMovementFlag |= 0x80000000;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			unchecked {
+				return offset + 3559 * (int)insertionLengthWithMovementFlag + 3571 * (int)removalLengthWithDeletionFlag;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			return obj is OffsetChangeMapEntry && this.Equals((OffsetChangeMapEntry)obj);
+		}
+		
+		/// <inheritdoc/>
+		public bool Equals(OffsetChangeMapEntry other)
+		{
+			return offset == other.offset && insertionLengthWithMovementFlag == other.insertionLengthWithMovementFlag && removalLengthWithDeletionFlag == other.removalLengthWithDeletionFlag;
+		}
+		
+		/// <summary>
+		/// Tests the two entries for equality.
+		/// </summary>
+		public static bool operator ==(OffsetChangeMapEntry left, OffsetChangeMapEntry right)
+		{
+			return left.Equals(right);
+		}
+		
+		/// <summary>
+		/// Tests the two entries for inequality.
+		/// </summary>
+		public static bool operator !=(OffsetChangeMapEntry left, OffsetChangeMapEntry right)
+		{
+			return !left.Equals(right);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/RopeTextSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/RopeTextSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/RopeTextSource.cs	(revision 11807)
@@ -0,0 +1,169 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Implements the ITextSource interface using a rope.
+	/// </summary>
+	[Serializable]
+	public sealed class RopeTextSource : ITextSource
+	{
+		readonly Rope<char> rope;
+		readonly ITextSourceVersion version;
+		
+		/// <summary>
+		/// Creates a new RopeTextSource.
+		/// </summary>
+		public RopeTextSource(Rope<char> rope)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			this.rope = rope.Clone();
+		}
+		
+		/// <summary>
+		/// Creates a new RopeTextSource.
+		/// </summary>
+		public RopeTextSource(Rope<char> rope, ITextSourceVersion version)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			this.rope = rope.Clone();
+			this.version = version;
+		}
+		
+		/// <summary>
+		/// Returns a clone of the rope used for this text source.
+		/// </summary>
+		/// <remarks>
+		/// RopeTextSource only publishes a copy of the contained rope to ensure that the underlying rope cannot be modified.
+		/// </remarks>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Not a property because it creates a clone")]
+		public Rope<char> GetRope()
+		{
+			return rope.Clone();
+		}
+		
+		/// <inheritdoc/>
+		public string Text {
+			get { return rope.ToString(); }
+		}
+		
+		/// <inheritdoc/>
+		public int TextLength {
+			get { return rope.Length; }
+		}
+		
+		/// <inheritdoc/>
+		public char GetCharAt(int offset)
+		{
+			return rope[offset];
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(int offset, int length)
+		{
+			return rope.ToString(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(ISegment segment)
+		{
+			return rope.ToString(segment.Offset, segment.Length);
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader()
+		{
+			return new RopeTextReader(rope);
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader(int offset, int length)
+		{
+			return new RopeTextReader(rope.GetRange(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot()
+		{
+			return this;
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot(int offset, int length)
+		{
+			return new RopeTextSource(rope.GetRange(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(char c, int startIndex, int count)
+		{
+			return rope.IndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOfAny(char[] anyOf, int startIndex, int count)
+		{
+			return rope.IndexOfAny(anyOf, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(char c, int startIndex, int count)
+		{
+			return rope.LastIndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public ITextSourceVersion Version {
+			get { return version; }
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return rope.IndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return rope.LastIndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer)
+		{
+			rope.WriteTo(writer, 0, rope.Length);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer, int offset, int length)
+		{
+			rope.WriteTo(writer, offset, length);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/SimpleSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/SimpleSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/SimpleSegment.cs	(revision 11807)
@@ -0,0 +1,197 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Represents a simple segment (Offset,Length pair) that is not automatically updated
+	/// on document changes.
+	/// </summary>
+	struct SimpleSegment : IEquatable<SimpleSegment>, ISegment
+	{
+		public static readonly SimpleSegment Invalid = new SimpleSegment(-1, -1);
+		
+		/// <summary>
+		/// Gets the overlapping portion of the segments.
+		/// Returns SimpleSegment.Invalid if the segments don't overlap.
+		/// </summary>
+		public static SimpleSegment GetOverlap(ISegment segment1, ISegment segment2)
+		{
+			int start = Math.Max(segment1.Offset, segment2.Offset);
+			int end = Math.Min(segment1.EndOffset, segment2.EndOffset);
+			if (end < start)
+				return SimpleSegment.Invalid;
+			else
+				return new SimpleSegment(start, end - start);
+		}
+		
+		public readonly int Offset, Length;
+		
+		int ISegment.Offset {
+			get { return Offset; }
+		}
+		
+		int ISegment.Length {
+			get { return Length; }
+		}
+		
+		public int EndOffset {
+			get {
+				return Offset + Length;
+			}
+		}
+		
+		public SimpleSegment(int offset, int length)
+		{
+			this.Offset = offset;
+			this.Length = length;
+		}
+		
+		public SimpleSegment(ISegment segment)
+		{
+			Debug.Assert(segment != null);
+			this.Offset = segment.Offset;
+			this.Length = segment.Length;
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				return Offset + 10301 * Length;
+			}
+		}
+		
+		public override bool Equals(object obj)
+		{
+			return (obj is SimpleSegment) && Equals((SimpleSegment)obj);
+		}
+		
+		public bool Equals(SimpleSegment other)
+		{
+			return this.Offset == other.Offset && this.Length == other.Length;
+		}
+		
+		public static bool operator ==(SimpleSegment left, SimpleSegment right)
+		{
+			return left.Equals(right);
+		}
+		
+		public static bool operator !=(SimpleSegment left, SimpleSegment right)
+		{
+			return !left.Equals(right);
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", Length=" + Length.ToString(CultureInfo.InvariantCulture) + "]";
+		}
+	}
+	
+	/// <summary>
+	/// A segment using <see cref="TextAnchor"/>s as start and end positions.
+	/// </summary>
+	/// <remarks>
+	/// <para>
+	/// For the constructors creating new anchors, the start position will be AfterInsertion and the end position will be BeforeInsertion.
+	/// Should the end position move before the start position, the segment will have length 0.
+	/// </para>
+	/// </remarks>
+	/// <seealso cref="ISegment"/>
+	/// <seealso cref="TextSegment"/>
+	public sealed class AnchorSegment : ISegment
+	{
+		readonly TextAnchor start, end;
+		
+		/// <inheritdoc/>
+		public int Offset {
+			get { return start.Offset; }
+		}
+		
+		/// <inheritdoc/>
+		public int Length {
+			get {
+				// Math.Max takes care of the fact that end.Offset might move before start.Offset.
+				return Math.Max(0, end.Offset - start.Offset);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public int EndOffset {
+			get {
+				// Math.Max takes care of the fact that end.Offset might move before start.Offset.
+				return Math.Max(start.Offset, end.Offset);
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new AnchorSegment using the specified anchors.
+		/// The anchors must have <see cref="TextAnchor.SurviveDeletion"/> set to true.
+		/// </summary>
+		public AnchorSegment(TextAnchor start, TextAnchor end)
+		{
+			if (start == null)
+				throw new ArgumentNullException("start");
+			if (end == null)
+				throw new ArgumentNullException("end");
+			if (!start.SurviveDeletion)
+				throw new ArgumentException("Anchors for AnchorSegment must use SurviveDeletion", "start");
+			if (!end.SurviveDeletion)
+				throw new ArgumentException("Anchors for AnchorSegment must use SurviveDeletion", "end");
+			this.start = start;
+			this.end = end;
+		}
+		
+		/// <summary>
+		/// Creates a new AnchorSegment that creates new anchors.
+		/// </summary>
+		public AnchorSegment(TextDocument document, ISegment segment)
+			: this(document, ThrowUtil.CheckNotNull(segment, "segment").Offset, segment.Length)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new AnchorSegment that creates new anchors.
+		/// </summary>
+		public AnchorSegment(TextDocument document, int offset, int length)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			this.start = document.CreateAnchor(offset);
+			this.start.SurviveDeletion = true;
+			this.start.MovementType = AnchorMovementType.AfterInsertion;
+			this.end = document.CreateAnchor(offset + length);
+			this.end.SurviveDeletion = true;
+			this.end.MovementType = AnchorMovementType.BeforeInsertion;
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[Offset=" + Offset.ToString(CultureInfo.InvariantCulture) + ", EndOffset=" + EndOffset.ToString(CultureInfo.InvariantCulture) + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchor.cs	(revision 11807)
@@ -0,0 +1,158 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Utils;
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// The TextAnchor class references an offset (a position between two characters).
+	/// It automatically updates the offset when text is inserted/removed in front of the anchor.
+	/// </summary>
+	/// <remarks>
+	/// <para>Use the <see cref="Offset"/> property to get the offset from a text anchor.
+	/// Use the <see cref="TextDocument.CreateAnchor"/> method to create an anchor from an offset.
+	/// </para>
+	/// <para>
+	/// The document will automatically update all text anchors; and because it uses weak references to do so,
+	/// the garbage collector can simply collect the anchor object when you don't need it anymore.
+	/// </para>
+	/// <para>Moreover, the document is able to efficiently update a large number of anchors without having to look
+	/// at each anchor object individually. Updating the offsets of all anchors usually only takes time logarithmic
+	/// to the number of anchors. Retrieving the <see cref="Offset"/> property also runs in O(lg N).</para>
+	/// <inheritdoc cref="IsDeleted" />
+	/// <inheritdoc cref="MovementType" />
+	/// <para>If you want to track a segment, you can use the <see cref="AnchorSegment"/> class which
+	/// implements <see cref="ISegment"/> using two text anchors.</para>
+	/// </remarks>
+	/// <example>
+	/// Usage:
+	/// <code>TextAnchor anchor = document.CreateAnchor(offset);
+	/// ChangeMyDocument();
+	/// int newOffset = anchor.Offset;
+	/// </code>
+	/// </example>
+	public sealed class TextAnchor : ITextAnchor
+	{
+		readonly TextDocument document;
+		internal TextAnchorNode node;
+		
+		internal TextAnchor(TextDocument document)
+		{
+			this.document = document;
+		}
+		
+		/// <summary>
+		/// Gets the document owning the anchor.
+		/// </summary>
+		public TextDocument Document {
+			get { return document; }
+		}
+		
+		/// <inheritdoc/>
+		public AnchorMovementType MovementType { get; set; }
+		
+		/// <inheritdoc/>
+		public bool SurviveDeletion { get; set; }
+		
+		/// <inheritdoc/>
+		public bool IsDeleted {
+			get {
+				document.DebugVerifyAccess();
+				return node == null;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public event EventHandler Deleted;
+		
+		internal void OnDeleted(DelayedEvents delayedEvents)
+		{
+			node = null;
+			delayedEvents.DelayedRaise(Deleted, this, EventArgs.Empty);
+		}
+		
+		/// <summary>
+		/// Gets the offset of the text anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		public int Offset {
+			get {
+				document.DebugVerifyAccess();
+				
+				TextAnchorNode n = this.node;
+				if (n == null)
+					throw new InvalidOperationException();
+				
+				int offset = n.length;
+				if (n.left != null)
+					offset += n.left.totalLength;
+				while (n.parent != null) {
+					if (n == n.parent.right) {
+						if (n.parent.left != null)
+							offset += n.parent.left.totalLength;
+						offset += n.parent.length;
+					}
+					n = n.parent;
+				}
+				return offset;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the line number of the anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		public int Line {
+			get {
+				return document.GetLineByOffset(this.Offset).LineNumber;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the column number of this anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		public int Column {
+			get {
+				int offset = this.Offset;
+				return offset - document.GetLineByOffset(offset).Offset + 1;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the text location of this anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		public TextLocation Location {
+			get {
+				return document.GetLocation(this.Offset);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[TextAnchor Offset=" + Offset + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchorNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchorNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchorNode.cs	(revision 11807)
@@ -0,0 +1,102 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// A TextAnchorNode is placed in the TextAnchorTree.
+	/// It describes a section of text with a text anchor at the end of the section.
+	/// A weak reference is used to refer to the TextAnchor. (to save memory, we derive from WeakReference instead of referencing it)
+	/// </summary>
+	sealed class TextAnchorNode : WeakReference
+	{
+		internal TextAnchorNode left, right, parent;
+		internal bool color;
+		internal int length;
+		internal int totalLength; // totalLength = length + left.totalLength + right.totalLength
+		
+		public TextAnchorNode(TextAnchor anchor) : base(anchor)
+		{
+		}
+		
+		internal TextAnchorNode LeftMost {
+			get {
+				TextAnchorNode node = this;
+				while (node.left != null)
+					node = node.left;
+				return node;
+			}
+		}
+		
+		internal TextAnchorNode RightMost {
+			get {
+				TextAnchorNode node = this;
+				while (node.right != null)
+					node = node.right;
+				return node;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the inorder successor of the node.
+		/// </summary>
+		internal TextAnchorNode Successor {
+			get {
+				if (right != null) {
+					return right.LeftMost;
+				} else {
+					TextAnchorNode node = this;
+					TextAnchorNode oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// go up until we are coming out of a left subtree
+					} while (node != null && node.right == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the inorder predecessor of the node.
+		/// </summary>
+		internal TextAnchorNode Predecessor {
+			get {
+				if (left != null) {
+					return left.RightMost;
+				} else {
+					TextAnchorNode node = this;
+					TextAnchorNode oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// go up until we are coming out of a right subtree
+					} while (node != null && node.left == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		public override string ToString()
+		{
+			return "[TextAnchorNode Length=" + length + " TotalLength=" + totalLength + " Target=" + Target + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchorTree.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchorTree.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextAnchorTree.cs	(revision 11807)
@@ -0,0 +1,770 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// A tree of TextAnchorNodes.
+	/// </summary>
+	sealed class TextAnchorTree
+	{
+		// The text anchor tree has difficult requirements:
+		// - it must QUICKLY update the offset in all anchors whenever there is a document change
+		// - it must not reference text anchors directly, using weak references instead
+		
+		// Clearly, we cannot afford updating an Offset property on all anchors (that would be O(N)).
+		// So instead, the anchors need to be able to calculate their offset from a data structure
+		// that can be efficiently updated.
+		
+		// This implementation is built using an augmented red-black-tree.
+		// There is a 'TextAnchorNode' for each text anchor.
+		// Such a node represents a section of text (just the length is stored) with a (weakly referenced) text anchor at the end.
+		
+		// Basically, you can imagine the list of text anchors as a sorted list of text anchors, where each anchor
+		// just stores the distance to the previous anchor.
+		// (next node = TextAnchorNode.Successor, distance = TextAnchorNode.length)
+		// Distances are never negative, so this representation means anchors are always sorted by offset
+		// (the order of anchors at the same offset is undefined)
+		
+		// Of course, a linked list of anchors would be way too slow (one would need to traverse the whole list
+		// every time the offset of an anchor is being looked up).
+		// Instead, we use a red-black-tree. We aren't actually using the tree for sorting - it's just a binary tree
+		// as storage format for what's conceptually a list, the red-black properties are used to keep the tree balanced.
+		// Other balanced binary trees would work, too.
+		
+		// What makes the tree-form efficient is that is augments the data by a 'totalLength'. Where 'length'
+		// represents the distance to the previous node, 'totalLength' is the sum of all 'length' values in the subtree
+		// under that node.
+		// This allows computing the Offset from an anchor by walking up the list of parent nodes instead of going
+		// through all predecessor nodes. So computing the Offset runs in O(log N).
+		
+		readonly TextDocument document;
+		readonly List<TextAnchorNode> nodesToDelete = new List<TextAnchorNode>();
+		TextAnchorNode root;
+		
+		public TextAnchorTree(TextDocument document)
+		{
+			this.document = document;
+		}
+		
+		[Conditional("DEBUG")]
+		static void Log(string text)
+		{
+			Debug.WriteLine("TextAnchorTree: " + text);
+		}
+		
+		#region Insert Text
+		void InsertText(int offset, int length, bool defaultAnchorMovementIsBeforeInsertion)
+		{
+			if (length == 0 || root == null || offset > root.totalLength)
+				return;
+			
+			// find the range of nodes that are placed exactly at offset
+			// beginNode is inclusive, endNode is exclusive
+			if (offset == root.totalLength) {
+				PerformInsertText(FindActualBeginNode(root.RightMost), null, length, defaultAnchorMovementIsBeforeInsertion);
+			} else {
+				TextAnchorNode endNode = FindNode(ref offset);
+				Debug.Assert(endNode.length > 0);
+				
+				if (offset > 0) {
+					// there are no nodes exactly at offset
+					endNode.length += length;
+					UpdateAugmentedData(endNode);
+				} else {
+					PerformInsertText(FindActualBeginNode(endNode.Predecessor), endNode, length, defaultAnchorMovementIsBeforeInsertion);
+				}
+			}
+			DeleteMarkedNodes();
+		}
+		
+		TextAnchorNode FindActualBeginNode(TextAnchorNode node)
+		{
+			// now find the actual beginNode
+			while (node != null && node.length == 0)
+				node = node.Predecessor;
+			if (node == null) {
+				// no predecessor = beginNode is first node in tree
+				node = root.LeftMost;
+			}
+			return node;
+		}
+		
+		// Sorts the nodes in the range [beginNode, endNode) by MovementType
+		// and inserts the length between the BeforeInsertion and the AfterInsertion nodes.
+		void PerformInsertText(TextAnchorNode beginNode, TextAnchorNode endNode, int length, bool defaultAnchorMovementIsBeforeInsertion)
+		{
+			Debug.Assert(beginNode != null);
+			// endNode may be null at the end of the anchor tree
+			
+			// now we need to sort the nodes in the range [beginNode, endNode); putting those with
+			// MovementType.BeforeInsertion in front of those with MovementType.AfterInsertion
+			List<TextAnchorNode> beforeInsert = new List<TextAnchorNode>();
+			//List<TextAnchorNode> afterInsert = new List<TextAnchorNode>();
+			TextAnchorNode temp = beginNode;
+			while (temp != endNode) {
+				TextAnchor anchor = (TextAnchor)temp.Target;
+				if (anchor == null) {
+					// afterInsert.Add(temp);
+					MarkNodeForDelete(temp);
+				} else if (defaultAnchorMovementIsBeforeInsertion
+				           ? anchor.MovementType != AnchorMovementType.AfterInsertion
+				           : anchor.MovementType == AnchorMovementType.BeforeInsertion)
+				{
+					beforeInsert.Add(temp);
+//				} else {
+//					afterInsert.Add(temp);
+				}
+				temp = temp.Successor;
+			}
+			// now again go through the range and swap the nodes with those in the beforeInsert list
+			temp = beginNode;
+			foreach (TextAnchorNode node in beforeInsert) {
+				SwapAnchors(node, temp);
+				temp = temp.Successor;
+			}
+			// now temp is pointing to the first node that is afterInsert,
+			// or to endNode, if there is no afterInsert node at the offset
+			// So add the length to temp
+			if (temp == null) {
+				// temp might be null if endNode==null and no afterInserts
+				Debug.Assert(endNode == null);
+			} else {
+				temp.length += length;
+				UpdateAugmentedData(temp);
+			}
+		}
+		
+		/// <summary>
+		/// Swaps the anchors stored in the two nodes.
+		/// </summary>
+		void SwapAnchors(TextAnchorNode n1, TextAnchorNode n2)
+		{
+			if (n1 != n2) {
+				TextAnchor anchor1 = (TextAnchor)n1.Target;
+				TextAnchor anchor2 = (TextAnchor)n2.Target;
+				if (anchor1 == null && anchor2 == null) {
+					// -> no swap required
+					return;
+				}
+				n1.Target = anchor2;
+				n2.Target = anchor1;
+				if (anchor1 == null) {
+					// unmark n1 from deletion, mark n2 for deletion
+					nodesToDelete.Remove(n1);
+					MarkNodeForDelete(n2);
+					anchor2.node = n1;
+				} else if (anchor2 == null) {
+					// unmark n2 from deletion, mark n1 for deletion
+					nodesToDelete.Remove(n2);
+					MarkNodeForDelete(n1);
+					anchor1.node = n2;
+				} else {
+					anchor1.node = n2;
+					anchor2.node = n1;
+				}
+			}
+		}
+		#endregion
+		
+		#region Remove or Replace text
+		public void HandleTextChange(OffsetChangeMapEntry entry, DelayedEvents delayedEvents)
+		{
+			//Log("HandleTextChange(" + entry + ")");
+			if (entry.RemovalLength == 0) {
+				// This is a pure insertion.
+				// Unlike a replace with removal, a pure insertion can result in nodes at the same location
+				// to split depending on their MovementType.
+				// Thus, we handle this case on a separate code path
+				// (the code below looks like it does something similar, but it can only split
+				// the set of deletion survivors, not all nodes at an offset)
+				InsertText(entry.Offset, entry.InsertionLength, entry.DefaultAnchorMovementIsBeforeInsertion);
+				return;
+			}
+			// When handling a replacing text change, we need to:
+			// - find all anchors in the deleted segment and delete them / move them to the appropriate
+			//   surviving side.
+			// - adjust the segment size between the left and right side
+			
+			int offset = entry.Offset;
+			int remainingRemovalLength = entry.RemovalLength;
+			// if the text change is happening after the last anchor, we don't have to do anything
+			if (root == null || offset >= root.totalLength)
+				return;
+			TextAnchorNode node = FindNode(ref offset);
+			TextAnchorNode firstDeletionSurvivor = null;
+			// go forward through the tree and delete all nodes in the removal segment
+			while (node != null && offset + remainingRemovalLength > node.length) {
+				TextAnchor anchor = (TextAnchor)node.Target;
+				if (anchor != null && (anchor.SurviveDeletion || entry.RemovalNeverCausesAnchorDeletion)) {
+					if (firstDeletionSurvivor == null)
+						firstDeletionSurvivor = node;
+					// This node should be deleted, but it wants to survive.
+					// We'll just remove the deleted length segment, so the node will be positioned
+					// in front of the removed segment.
+					remainingRemovalLength -= node.length - offset;
+					node.length = offset;
+					offset = 0;
+					UpdateAugmentedData(node);
+					node = node.Successor;
+				} else {
+					// delete node
+					TextAnchorNode s = node.Successor;
+					remainingRemovalLength -= node.length;
+					RemoveNode(node);
+					// we already deleted the node, don't delete it twice
+					nodesToDelete.Remove(node);
+					if (anchor != null)
+						anchor.OnDeleted(delayedEvents);
+					node = s;
+				}
+			}
+			// 'node' now is the first anchor after the deleted segment.
+			// If there are no anchors after the deleted segment, 'node' is null.
+			
+			// firstDeletionSurvivor was set to the first node surviving deletion.
+			// Because all non-surviving nodes up to 'node' were deleted, the node range
+			// [firstDeletionSurvivor, node) now refers to the set of all deletion survivors.
+			
+			// do the remaining job of the removal
+			if (node != null) {
+				node.length -= remainingRemovalLength;
+				Debug.Assert(node.length >= 0);
+			}
+			if (entry.InsertionLength > 0) {
+				// we are performing a replacement
+				if (firstDeletionSurvivor != null) {
+					// We got deletion survivors which need to be split into BeforeInsertion
+					// and AfterInsertion groups.
+					// Take care that we don't regroup everything at offset, but only the deletion
+					// survivors - from firstDeletionSurvivor (inclusive) to node (exclusive).
+					// This ensures that nodes immediately before or after the replaced segment
+					// stay where they are (independent from their MovementType)
+					PerformInsertText(firstDeletionSurvivor, node, entry.InsertionLength, entry.DefaultAnchorMovementIsBeforeInsertion);
+				} else if (node != null) {
+					// No deletion survivors:
+					// just perform the insertion
+					node.length += entry.InsertionLength;
+				}
+			}
+			if (node != null) {
+				UpdateAugmentedData(node);
+			}
+			DeleteMarkedNodes();
+		}
+		#endregion
+		
+		#region Node removal when TextAnchor was GC'ed
+		void MarkNodeForDelete(TextAnchorNode node)
+		{
+			if (!nodesToDelete.Contains(node))
+				nodesToDelete.Add(node);
+		}
+		
+		void DeleteMarkedNodes()
+		{
+			CheckProperties();
+			while (nodesToDelete.Count > 0) {
+				int pos = nodesToDelete.Count - 1;
+				TextAnchorNode n = nodesToDelete[pos];
+				// combine section of n with the following section
+				TextAnchorNode s = n.Successor;
+				if (s != null) {
+					s.length += n.length;
+				}
+				RemoveNode(n);
+				if (s != null) {
+					UpdateAugmentedData(s);
+				}
+				nodesToDelete.RemoveAt(pos);
+				CheckProperties();
+			}
+			CheckProperties();
+		}
+		#endregion
+		
+		#region FindNode
+		/// <summary>
+		/// Finds the node at the specified offset.
+		/// After the method has run, offset is relative to the beginning of the returned node.
+		/// </summary>
+		TextAnchorNode FindNode(ref int offset)
+		{
+			TextAnchorNode n = root;
+			while (true) {
+				if (n.left != null) {
+					if (offset < n.left.totalLength) {
+						n = n.left; // descend into left subtree
+						continue;
+					} else {
+						offset -= n.left.totalLength; // skip left subtree
+					}
+				}
+				if (!n.IsAlive)
+					MarkNodeForDelete(n);
+				if (offset < n.length) {
+					return n; // found correct node
+				} else {
+					offset -= n.length; // skip this node
+				}
+				if (n.right != null) {
+					n = n.right; // descend into right subtree
+				} else {
+					// didn't find any node containing the offset
+					return null;
+				}
+			}
+		}
+		#endregion
+		
+		#region UpdateAugmentedData
+		void UpdateAugmentedData(TextAnchorNode n)
+		{
+			if (!n.IsAlive)
+				MarkNodeForDelete(n);
+			
+			int totalLength = n.length;
+			if (n.left != null)
+				totalLength += n.left.totalLength;
+			if (n.right != null)
+				totalLength += n.right.totalLength;
+			if (n.totalLength != totalLength) {
+				n.totalLength = totalLength;
+				if (n.parent != null)
+					UpdateAugmentedData(n.parent);
+			}
+		}
+		#endregion
+		
+		#region CreateAnchor
+		public TextAnchor CreateAnchor(int offset)
+		{
+			Log("CreateAnchor(" + offset + ")");
+			TextAnchor anchor = new TextAnchor(document);
+			anchor.node = new TextAnchorNode(anchor);
+			if (root == null) {
+				// creating the first text anchor
+				root = anchor.node;
+				root.totalLength = root.length = offset;
+			} else if (offset >= root.totalLength) {
+				// append anchor at end of tree
+				anchor.node.totalLength = anchor.node.length = offset - root.totalLength;
+				InsertAsRight(root.RightMost, anchor.node);
+			} else {
+				// insert anchor in middle of tree
+				TextAnchorNode n = FindNode(ref offset);
+				Debug.Assert(offset < n.length);
+				// split segment 'n' at offset
+				anchor.node.totalLength = anchor.node.length = offset;
+				n.length -= offset;
+				InsertBefore(n, anchor.node);
+			}
+			DeleteMarkedNodes();
+			return anchor;
+		}
+		
+		void InsertBefore(TextAnchorNode node, TextAnchorNode newNode)
+		{
+			if (node.left == null) {
+				InsertAsLeft(node, newNode);
+			} else {
+				InsertAsRight(node.left.RightMost, newNode);
+			}
+		}
+		#endregion
+		
+		#region Red/Black Tree
+		internal const bool RED = true;
+		internal const bool BLACK = false;
+		
+		void InsertAsLeft(TextAnchorNode parentNode, TextAnchorNode newNode)
+		{
+			Debug.Assert(parentNode.left == null);
+			parentNode.left = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAugmentedData(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void InsertAsRight(TextAnchorNode parentNode, TextAnchorNode newNode)
+		{
+			Debug.Assert(parentNode.right == null);
+			parentNode.right = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAugmentedData(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void FixTreeOnInsert(TextAnchorNode node)
+		{
+			Debug.Assert(node != null);
+			Debug.Assert(node.color == RED);
+			Debug.Assert(node.left == null || node.left.color == BLACK);
+			Debug.Assert(node.right == null || node.right.color == BLACK);
+			
+			TextAnchorNode parentNode = node.parent;
+			if (parentNode == null) {
+				// we inserted in the root -> the node must be black
+				// since this is a root node, making the node black increments the number of black nodes
+				// on all paths by one, so it is still the same for all paths.
+				node.color = BLACK;
+				return;
+			}
+			if (parentNode.color == BLACK) {
+				// if the parent node where we inserted was black, our red node is placed correctly.
+				// since we inserted a red node, the number of black nodes on each path is unchanged
+				// -> the tree is still balanced
+				return;
+			}
+			// parentNode is red, so there is a conflict here!
+			
+			// because the root is black, parentNode is not the root -> there is a grandparent node
+			TextAnchorNode grandparentNode = parentNode.parent;
+			TextAnchorNode uncleNode = Sibling(parentNode);
+			if (uncleNode != null && uncleNode.color == RED) {
+				parentNode.color = BLACK;
+				uncleNode.color = BLACK;
+				grandparentNode.color = RED;
+				FixTreeOnInsert(grandparentNode);
+				return;
+			}
+			// now we know: parent is red but uncle is black
+			// First rotation:
+			if (node == parentNode.right && parentNode == grandparentNode.left) {
+				RotateLeft(parentNode);
+				node = node.left;
+			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
+				RotateRight(parentNode);
+				node = node.right;
+			}
+			// because node might have changed, reassign variables:
+			parentNode = node.parent;
+			grandparentNode = parentNode.parent;
+			
+			// Now recolor a bit:
+			parentNode.color = BLACK;
+			grandparentNode.color = RED;
+			// Second rotation:
+			if (node == parentNode.left && parentNode == grandparentNode.left) {
+				RotateRight(grandparentNode);
+			} else {
+				// because of the first rotation, this is guaranteed:
+				Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
+				RotateLeft(grandparentNode);
+			}
+		}
+		
+		void RemoveNode(TextAnchorNode removedNode)
+		{
+			if (removedNode.left != null && removedNode.right != null) {
+				// replace removedNode with it's in-order successor
+				
+				TextAnchorNode leftMost = removedNode.right.LeftMost;
+				RemoveNode(leftMost); // remove leftMost from its current location
+				
+				// and overwrite the removedNode with it
+				ReplaceNode(removedNode, leftMost);
+				leftMost.left = removedNode.left;
+				if (leftMost.left != null) leftMost.left.parent = leftMost;
+				leftMost.right = removedNode.right;
+				if (leftMost.right != null) leftMost.right.parent = leftMost;
+				leftMost.color = removedNode.color;
+				
+				UpdateAugmentedData(leftMost);
+				if (leftMost.parent != null) UpdateAugmentedData(leftMost.parent);
+				return;
+			}
+			
+			// now either removedNode.left or removedNode.right is null
+			// get the remaining child
+			TextAnchorNode parentNode = removedNode.parent;
+			TextAnchorNode childNode = removedNode.left ?? removedNode.right;
+			ReplaceNode(removedNode, childNode);
+			if (parentNode != null) UpdateAugmentedData(parentNode);
+			if (removedNode.color == BLACK) {
+				if (childNode != null && childNode.color == RED) {
+					childNode.color = BLACK;
+				} else {
+					FixTreeOnDelete(childNode, parentNode);
+				}
+			}
+		}
+		
+		void FixTreeOnDelete(TextAnchorNode node, TextAnchorNode parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (parentNode == null)
+				return;
+			
+			// warning: node may be null
+			TextAnchorNode sibling = Sibling(node, parentNode);
+			if (sibling.color == RED) {
+				parentNode.color = RED;
+				sibling.color = BLACK;
+				if (node == parentNode.left) {
+					RotateLeft(parentNode);
+				} else {
+					RotateRight(parentNode);
+				}
+				
+				sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			}
+			
+			if (parentNode.color == BLACK
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				FixTreeOnDelete(parentNode, parentNode.parent);
+				return;
+			}
+			
+			if (parentNode.color == RED
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				parentNode.color = BLACK;
+				return;
+			}
+			
+			if (node == parentNode.left &&
+			    sibling.color == BLACK &&
+			    GetColor(sibling.left) == RED &&
+			    GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.left.color = BLACK;
+				RotateRight(sibling);
+			}
+			else if (node == parentNode.right &&
+			         sibling.color == BLACK &&
+			         GetColor(sibling.right) == RED &&
+			         GetColor(sibling.left) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.right.color = BLACK;
+				RotateLeft(sibling);
+			}
+			sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			
+			sibling.color = parentNode.color;
+			parentNode.color = BLACK;
+			if (node == parentNode.left) {
+				if (sibling.right != null) {
+					Debug.Assert(sibling.right.color == RED);
+					sibling.right.color = BLACK;
+				}
+				RotateLeft(parentNode);
+			} else {
+				if (sibling.left != null) {
+					Debug.Assert(sibling.left.color == RED);
+					sibling.left.color = BLACK;
+				}
+				RotateRight(parentNode);
+			}
+		}
+		
+		void ReplaceNode(TextAnchorNode replacedNode, TextAnchorNode newNode)
+		{
+			if (replacedNode.parent == null) {
+				Debug.Assert(replacedNode == root);
+				root = newNode;
+			} else {
+				if (replacedNode.parent.left == replacedNode)
+					replacedNode.parent.left = newNode;
+				else
+					replacedNode.parent.right = newNode;
+			}
+			if (newNode != null) {
+				newNode.parent = replacedNode.parent;
+			}
+			replacedNode.parent = null;
+		}
+		
+		void RotateLeft(TextAnchorNode p)
+		{
+			// let q be p's right child
+			TextAnchorNode q = p.right;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's right child to be q's left child
+			p.right = q.left;
+			if (p.right != null) p.right.parent = p;
+			// set q's left child to be p
+			q.left = p;
+			p.parent = q;
+			UpdateAugmentedData(p);
+			UpdateAugmentedData(q);
+		}
+		
+		void RotateRight(TextAnchorNode p)
+		{
+			// let q be p's left child
+			TextAnchorNode q = p.left;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's left child to be q's right child
+			p.left = q.right;
+			if (p.left != null) p.left.parent = p;
+			// set q's right child to be p
+			q.right = p;
+			p.parent = q;
+			UpdateAugmentedData(p);
+			UpdateAugmentedData(q);
+		}
+		
+		static TextAnchorNode Sibling(TextAnchorNode node)
+		{
+			if (node == node.parent.left)
+				return node.parent.right;
+			else
+				return node.parent.left;
+		}
+		
+		static TextAnchorNode Sibling(TextAnchorNode node, TextAnchorNode parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (node == parentNode.left)
+				return parentNode.right;
+			else
+				return parentNode.left;
+		}
+		
+		static bool GetColor(TextAnchorNode node)
+		{
+			return node != null ? node.color : BLACK;
+		}
+		#endregion
+		
+		#region CheckProperties
+		[Conditional("DATACONSISTENCYTEST")]
+		internal void CheckProperties()
+		{
+			#if DEBUG
+			if (root != null) {
+				CheckProperties(root);
+				
+				// check red-black property:
+				int blackCount = -1;
+				CheckNodeProperties(root, null, RED, 0, ref blackCount);
+			}
+			#endif
+		}
+		
+		#if DEBUG
+		void CheckProperties(TextAnchorNode node)
+		{
+			int totalLength = node.length;
+			if (node.left != null) {
+				CheckProperties(node.left);
+				totalLength += node.left.totalLength;
+			}
+			if (node.right != null) {
+				CheckProperties(node.right);
+				totalLength += node.right.totalLength;
+			}
+			Debug.Assert(node.totalLength == totalLength);
+		}
+		
+		/*
+		1. A node is either red or black.
+		2. The root is black.
+		3. All leaves are black. (The leaves are the NIL children.)
+		4. Both children of every red node are black. (So every red node must have a black parent.)
+		5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
+		 */
+		void CheckNodeProperties(TextAnchorNode node, TextAnchorNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
+		{
+			if (node == null) return;
+			
+			Debug.Assert(node.parent == parentNode);
+			
+			if (parentColor == RED) {
+				Debug.Assert(node.color == BLACK);
+			}
+			if (node.color == BLACK) {
+				blackCount++;
+			}
+			if (node.left == null && node.right == null) {
+				// node is a leaf node:
+				if (expectedBlackCount == -1)
+					expectedBlackCount = blackCount;
+				else
+					Debug.Assert(expectedBlackCount == blackCount);
+			}
+			CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
+			CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
+		}
+		#endif
+		#endregion
+		
+		#region GetTreeAsString
+		#if DEBUG
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+		public string GetTreeAsString()
+		{
+			if (root == null)
+				return "<empty tree>";
+			StringBuilder b = new StringBuilder();
+			AppendTreeToString(root, b, 0);
+			return b.ToString();
+		}
+		
+		static void AppendTreeToString(TextAnchorNode node, StringBuilder b, int indent)
+		{
+			if (node.color == RED)
+				b.Append("RED   ");
+			else
+				b.Append("BLACK ");
+			b.AppendLine(node.ToString());
+			indent += 2;
+			if (node.left != null) {
+				b.Append(' ', indent);
+				b.Append("L: ");
+				AppendTreeToString(node.left, b, indent);
+			}
+			if (node.right != null) {
+				b.Append(' ', indent);
+				b.Append("R: ");
+				AppendTreeToString(node.right, b, indent);
+			}
+		}
+		#endif
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextDocument.cs	(revision 11807)
@@ -0,0 +1,1151 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ComponentModel.Design;
+using System.Diagnostics;
+using System.Globalization;
+using System.Threading;
+using ICSharpCode.AvalonEdit.Utils;
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
+	/// </summary>
+	/// <remarks>
+	/// <b>Thread safety:</b>
+	/// <inheritdoc cref="VerifyAccess"/>
+	/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
+	/// </remarks>
+	public sealed class TextDocument : IDocument, INotifyPropertyChanged
+	{
+		#region Thread ownership
+		readonly object lockObject = new object();
+		Thread owner = Thread.CurrentThread;
+		
+		/// <summary>
+		/// Verifies that the current thread is the documents owner thread.
+		/// Throws an <see cref="InvalidOperationException"/> if the wrong thread accesses the TextDocument.
+		/// </summary>
+		/// <remarks>
+		/// <para>The TextDocument class is not thread-safe. A document instance expects to have a single owner thread
+		/// and will throw an <see cref="InvalidOperationException"/> when accessed from another thread.
+		/// It is possible to change the owner thread using the <see cref="SetOwnerThread"/> method.</para>
+		/// </remarks>
+		public void VerifyAccess()
+		{
+			if (Thread.CurrentThread != owner)
+				throw new InvalidOperationException("TextDocument can be accessed only from the thread that owns it.");
+		}
+		
+		/// <summary>
+		/// Transfers ownership of the document to another thread. This method can be used to load
+		/// a file into a TextDocument on a background thread and then transfer ownership to the UI thread
+		/// for displaying the document.
+		/// </summary>
+		/// <remarks>
+		/// <inheritdoc cref="VerifyAccess"/>
+		/// <para>
+		/// The owner can be set to null, which means that no thread can access the document. But, if the document
+		/// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>.
+		/// </para>
+		/// </remarks>
+		public void SetOwnerThread(Thread newOwner)
+		{
+			// We need to lock here to ensure that in the null owner case,
+			// only one thread succeeds in taking ownership.
+			lock (lockObject) {
+				if (owner != null) {
+					VerifyAccess();
+				}
+				owner = newOwner;
+			}
+		}
+		#endregion
+		
+		#region Fields + Constructor
+		readonly Rope<char> rope;
+		readonly DocumentLineTree lineTree;
+		readonly LineManager lineManager;
+		readonly TextAnchorTree anchorTree;
+		readonly TextSourceVersionProvider versionProvider = new TextSourceVersionProvider();
+		
+		/// <summary>
+		/// Create an empty text document.
+		/// </summary>
+		public TextDocument()
+			: this(string.Empty)
+		{
+		}
+		
+		/// <summary>
+		/// Create a new text document with the specified initial text.
+		/// </summary>
+		public TextDocument(IEnumerable<char> initialText)
+		{
+			if (initialText == null)
+				throw new ArgumentNullException("initialText");
+			rope = new Rope<char>(initialText);
+			lineTree = new DocumentLineTree(this);
+			lineManager = new LineManager(lineTree, this);
+			lineTrackers.CollectionChanged += delegate {
+				lineManager.UpdateListOfLineTrackers();
+			};
+			
+			anchorTree = new TextAnchorTree(this);
+			undoStack = new UndoStack();
+			FireChangeEvents();
+		}
+		
+		/// <summary>
+		/// Create a new text document with the specified initial text.
+		/// </summary>
+		public TextDocument(ITextSource initialText)
+			: this(GetTextFromTextSource(initialText))
+		{
+		}
+		
+		// gets the text from a text source, directly retrieving the underlying rope where possible
+		static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			
+			#if NREFACTORY
+			if (textSource is ReadOnlyDocument)
+				textSource = textSource.CreateSnapshot(); // retrieve underlying text source, which might be a RopeTextSource
+			#endif
+			
+			RopeTextSource rts = textSource as RopeTextSource;
+			if (rts != null)
+				return rts.GetRope();
+			
+			TextDocument doc = textSource as TextDocument;
+			if (doc != null)
+				return doc.rope;
+			
+			return textSource.Text;
+		}
+		#endregion
+		
+		#region Text
+		void ThrowIfRangeInvalid(int offset, int length)
+		{
+			if (offset < 0 || offset > rope.Length) {
+				throw new ArgumentOutOfRangeException("offset", offset, "0 <= offset <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			if (length < 0 || offset + length > rope.Length) {
+				throw new ArgumentOutOfRangeException("length", length, "0 <= length, offset(" + offset + ")+length <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
+			}
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(int offset, int length)
+		{
+			VerifyAccess();
+			return rope.ToString(offset, length);
+		}
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the document.
+		/// </summary>
+		public string GetText(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return GetText(segment.Offset, segment.Length);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(char c, int startIndex, int count)
+		{
+			DebugVerifyAccess();
+			return rope.IndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(char c, int startIndex, int count)
+		{
+			DebugVerifyAccess();
+			return rope.LastIndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOfAny(char[] anyOf, int startIndex, int count)
+		{
+			DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
+			return rope.IndexOfAny(anyOf, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			DebugVerifyAccess();
+			return rope.IndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			DebugVerifyAccess();
+			return rope.LastIndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public char GetCharAt(int offset)
+		{
+			DebugVerifyAccess(); // frequently called, so must be fast in release builds
+			return rope[offset];
+		}
+		
+		WeakReference cachedText;
+		
+		/// <summary>
+		/// Gets/Sets the text of the whole document.
+		/// </summary>
+		public string Text {
+			get {
+				VerifyAccess();
+				string completeText = cachedText != null ? (cachedText.Target as string) : null;
+				if (completeText == null) {
+					completeText = rope.ToString();
+					cachedText = new WeakReference(completeText);
+				}
+				return completeText;
+			}
+			set {
+				VerifyAccess();
+				if (value == null)
+					throw new ArgumentNullException("value");
+				Replace(0, rope.Length, value);
+			}
+		}
+		
+		/// <inheritdoc/>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public event EventHandler TextChanged;
+		
+		event EventHandler IDocument.ChangeCompleted {
+			add { this.TextChanged += value; }
+			remove { this.TextChanged -= value; }
+		}
+		
+		/// <inheritdoc/>
+		public int TextLength {
+			get {
+				VerifyAccess();
+				return rope.Length;
+			}
+		}
+		
+		/// <summary>
+		/// Is raised when the TextLength property changes.
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		[Obsolete("This event will be removed in a future version; use the PropertyChanged event instead")]
+		public event EventHandler TextLengthChanged;
+		
+		/// <summary>
+		/// Is raised when one of the properties <see cref="Text"/>, <see cref="TextLength"/>, <see cref="LineCount"/>,
+		/// <see cref="UndoStack"/> changes.
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public event PropertyChangedEventHandler PropertyChanged;
+		
+		/// <summary>
+		/// Is raised before the document changes.
+		/// </summary>
+		/// <remarks>
+		/// <para>Here is the order in which events are raised during a document update:</para>
+		/// <list type="bullet">
+		/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
+		///   <list type="bullet">
+		///   <item><description>Start of change group (on undo stack)</description></item>
+		///   <item><description><see cref="UpdateStarted"/> event is raised</description></item>
+		///   </list></item>
+		/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
+		///   <list type="bullet">
+		///   <item><description><see cref="Changing"/> event is raised</description></item>
+		///   <item><description>The document is changed</description></item>
+		///   <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
+		///     in the deleted text portion</description></item>
+		///   <item><description><see cref="Changed"/> event is raised</description></item>
+		///   </list></item>
+		/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
+		///   <list type="bullet">
+		///   <item><description><see cref="TextChanged"/> event is raised</description></item>
+		///   <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
+		///   <item><description>End of change group (on undo stack)</description></item>
+		///   <item><description><see cref="UpdateFinished"/> event is raised</description></item>
+		///   </list></item>
+		/// </list>
+		/// <para>
+		/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
+		/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
+		/// </para><para>
+		/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
+		/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
+		/// </para><para>
+		/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
+		/// </para>
+		/// </remarks>
+		public event EventHandler<DocumentChangeEventArgs> Changing;
+		
+		// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
+		private event EventHandler<TextChangeEventArgs> textChanging;
+		
+		event EventHandler<TextChangeEventArgs> IDocument.TextChanging {
+			add { textChanging += value; }
+			remove { textChanging -= value; }
+		}
+		
+		/// <summary>
+		/// Is raised after the document has changed.
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public event EventHandler<DocumentChangeEventArgs> Changed;
+		
+		private event EventHandler<TextChangeEventArgs> textChanged;
+		
+		event EventHandler<TextChangeEventArgs> IDocument.TextChanged {
+			add { textChanged += value; }
+			remove { textChanged -= value; }
+		}
+		
+		/// <summary>
+		/// Creates a snapshot of the current text.
+		/// </summary>
+		/// <remarks>
+		/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
+		/// the document's owner thread is concurrently modifying the document.
+		/// </para><para>
+		/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
+		/// classes implementing ITextSource.CreateSnapshot().
+		/// </para><para>
+		/// </para>
+		/// </remarks>
+		public ITextSource CreateSnapshot()
+		{
+			lock (lockObject) {
+				return new RopeTextSource(rope, versionProvider.CurrentVersion);
+			}
+		}
+		
+		/// <summary>
+		/// Creates a snapshot of a part of the current text.
+		/// </summary>
+		/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
+		public ITextSource CreateSnapshot(int offset, int length)
+		{
+			lock (lockObject) {
+				return new RopeTextSource(rope.GetRange(offset, length));
+			}
+		}
+		
+		#if NREFACTORY
+		/// <inheritdoc/>
+		public IDocument CreateDocumentSnapshot()
+		{
+			return new ReadOnlyDocument(this, fileName);
+		}
+		#endif
+		
+		/// <inheritdoc/>
+		public ITextSourceVersion Version {
+			get { return versionProvider.CurrentVersion; }
+		}
+		
+		/// <inheritdoc/>
+		public System.IO.TextReader CreateReader()
+		{
+			lock (lockObject) {
+				return new RopeTextReader(rope);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public System.IO.TextReader CreateReader(int offset, int length)
+		{
+			lock (lockObject) {
+				return new RopeTextReader(rope.GetRange(offset, length));
+			}
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(System.IO.TextWriter writer)
+		{
+			VerifyAccess();
+			rope.WriteTo(writer, 0, rope.Length);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(System.IO.TextWriter writer, int offset, int length)
+		{
+			VerifyAccess();
+			rope.WriteTo(writer, offset, length);
+		}
+		#endregion
+		
+		#region BeginUpdate / EndUpdate
+		int beginUpdateCount;
+		
+		/// <summary>
+		/// Gets if an update is running.
+		/// </summary>
+		/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
+		public bool IsInUpdate {
+			get {
+				VerifyAccess();
+				return beginUpdateCount > 0;
+			}
+		}
+		
+		/// <summary>
+		/// Immediately calls <see cref="BeginUpdate()"/>,
+		/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
+		/// </summary>
+		/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
+		public IDisposable RunUpdate()
+		{
+			BeginUpdate();
+			return new CallbackOnDispose(EndUpdate);
+		}
+		
+		/// <summary>
+		/// <para>Begins a group of document changes.</para>
+		/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
+		/// group all changes into a single action.</para>
+		/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
+		/// of EndUpdate calls the events resume their work.</para>
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public void BeginUpdate()
+		{
+			VerifyAccess();
+			if (inDocumentChanging)
+				throw new InvalidOperationException("Cannot change document within another document change.");
+			beginUpdateCount++;
+			if (beginUpdateCount == 1) {
+				undoStack.StartUndoGroup();
+				if (UpdateStarted != null)
+					UpdateStarted(this, EventArgs.Empty);
+			}
+		}
+		
+		/// <summary>
+		/// Ends a group of document changes.
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public void EndUpdate()
+		{
+			VerifyAccess();
+			if (inDocumentChanging)
+				throw new InvalidOperationException("Cannot end update within document change.");
+			if (beginUpdateCount == 0)
+				throw new InvalidOperationException("No update is active.");
+			if (beginUpdateCount == 1) {
+				// fire change events inside the change group - event handlers might add additional
+				// document changes to the change group
+				FireChangeEvents();
+				undoStack.EndUndoGroup();
+				beginUpdateCount = 0;
+				if (UpdateFinished != null)
+					UpdateFinished(this, EventArgs.Empty);
+			} else {
+				beginUpdateCount -= 1;
+			}
+		}
+		
+		/// <summary>
+		/// Occurs when a document change starts.
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public event EventHandler UpdateStarted;
+		
+		/// <summary>
+		/// Occurs when a document change is finished.
+		/// </summary>
+		/// <remarks><inheritdoc cref="Changing"/></remarks>
+		public event EventHandler UpdateFinished;
+		
+		void IDocument.StartUndoableAction()
+		{
+			BeginUpdate();
+		}
+		
+		void IDocument.EndUndoableAction()
+		{
+			EndUpdate();
+		}
+		
+		IDisposable IDocument.OpenUndoGroup()
+		{
+			return RunUpdate();
+		}
+		#endregion
+		
+		#region Fire events after update
+		int oldTextLength;
+		int oldLineCount;
+		bool fireTextChanged;
+		
+		/// <summary>
+		/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
+		/// </summary>
+		internal void FireChangeEvents()
+		{
+			// it may be necessary to fire the event multiple times if the document is changed
+			// from inside the event handlers
+			while (fireTextChanged) {
+				fireTextChanged = false;
+				if (TextChanged != null)
+					TextChanged(this, EventArgs.Empty);
+				OnPropertyChanged("Text");
+				
+				int textLength = rope.Length;
+				if (textLength != oldTextLength) {
+					oldTextLength = textLength;
+					if (TextLengthChanged != null)
+						TextLengthChanged(this, EventArgs.Empty);
+					OnPropertyChanged("TextLength");
+				}
+				int lineCount = lineTree.LineCount;
+				if (lineCount != oldLineCount) {
+					oldLineCount = lineCount;
+					if (LineCountChanged != null)
+						LineCountChanged(this, EventArgs.Empty);
+					OnPropertyChanged("LineCount");
+				}
+			}
+		}
+		
+		void OnPropertyChanged(string propertyName)
+		{
+			if (PropertyChanged != null)
+				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
+		}
+		#endregion
+		
+		#region Insert / Remove  / Replace
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <remarks>
+		/// Anchors positioned exactly at the insertion offset will move according to their movement type.
+		/// For AnchorMovementType.Default, they will move behind the inserted text.
+		/// The caret will also move behind the inserted text.
+		/// </remarks>
+		public void Insert(int offset, string text)
+		{
+			Replace(offset, 0, new StringTextSource(text), null);
+		}
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <remarks>
+		/// Anchors positioned exactly at the insertion offset will move according to their movement type.
+		/// For AnchorMovementType.Default, they will move behind the inserted text.
+		/// The caret will also move behind the inserted text.
+		/// </remarks>
+		public void Insert(int offset, ITextSource text)
+		{
+			Replace(offset, 0, text, null);
+		}
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="defaultAnchorMovementType">
+		/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
+		/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
+		/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
+		/// </param>
+		public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
+		{
+			if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) {
+				Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
+			} else {
+				Replace(offset, 0, new StringTextSource(text), null);
+			}
+		}
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="defaultAnchorMovementType">
+		/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
+		/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
+		/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
+		/// </param>
+		public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
+		{
+			if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) {
+				Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
+			} else {
+				Replace(offset, 0, text, null);
+			}
+		}
+		
+		/// <summary>
+		/// Removes text.
+		/// </summary>
+		public void Remove(ISegment segment)
+		{
+			Replace(segment, string.Empty);
+		}
+		
+		/// <summary>
+		/// Removes text.
+		/// </summary>
+		/// <param name="offset">Starting offset of the text to be removed.</param>
+		/// <param name="length">Length of the text to be removed.</param>
+		public void Remove(int offset, int length)
+		{
+			Replace(offset, length, StringTextSource.Empty);
+		}
+		
+		internal bool inDocumentChanging;
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		public void Replace(ISegment segment, string text)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		public void Replace(ISegment segment, ITextSource text)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			Replace(segment.Offset, segment.Length, text, null);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="text">The new text.</param>
+		public void Replace(int offset, int length, string text)
+		{
+			Replace(offset, length, new StringTextSource(text), null);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="text">The new text.</param>
+		public void Replace(int offset, int length, ITextSource text)
+		{
+			Replace(offset, length, text, null);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
+		/// This affects how the anchors and segments inside the replaced region behave.</param>
+		public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
+		{
+			Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
+		/// This affects how the anchors and segments inside the replaced region behave.</param>
+		public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			// Please see OffsetChangeMappingType XML comments for details on how these modes work.
+			switch (offsetChangeMappingType) {
+				case OffsetChangeMappingType.Normal:
+					Replace(offset, length, text, null);
+					break;
+				case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
+					Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
+						new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
+					break;
+				case OffsetChangeMappingType.RemoveAndInsert:
+					if (length == 0 || text.TextLength == 0) {
+						// only insertion or only removal?
+						// OffsetChangeMappingType doesn't matter, just use Normal.
+						Replace(offset, length, text, null);
+					} else {
+						OffsetChangeMap map = new OffsetChangeMap(2);
+						map.Add(new OffsetChangeMapEntry(offset, length, 0));
+						map.Add(new OffsetChangeMapEntry(offset, 0, text.TextLength));
+						map.Freeze();
+						Replace(offset, length, text, map);
+					}
+					break;
+				case OffsetChangeMappingType.CharacterReplace:
+					if (length == 0 || text.TextLength == 0) {
+						// only insertion or only removal?
+						// OffsetChangeMappingType doesn't matter, just use Normal.
+						Replace(offset, length, text, null);
+					} else if (text.TextLength > length) {
+						// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
+						// the last character
+						OffsetChangeMapEntry entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
+						Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
+					} else if (text.TextLength < length) {
+						OffsetChangeMapEntry entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
+						Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
+					} else {
+						Replace(offset, length, text, OffsetChangeMap.Empty);
+					}
+					break;
+				default:
+					throw new ArgumentOutOfRangeException("offsetChangeMappingType", offsetChangeMappingType, "Invalid enum value");
+			}
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
+		/// This affects how the anchors and segments inside the replaced region behave.
+		/// If you pass null (the default when using one of the other overloads), the offsets are changed as
+		/// in OffsetChangeMappingType.Normal mode.
+		/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
+		/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
+		/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
+		/// DocumentChangeEventArgs instance.
+		/// </param>
+		public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
+		{
+			Replace(offset, length, new StringTextSource(text), offsetChangeMap);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
+		/// This affects how the anchors and segments inside the replaced region behave.
+		/// If you pass null (the default when using one of the other overloads), the offsets are changed as
+		/// in OffsetChangeMappingType.Normal mode.
+		/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
+		/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
+		/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
+		/// DocumentChangeEventArgs instance.
+		/// </param>
+		public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			text = text.CreateSnapshot();
+			if (offsetChangeMap != null)
+				offsetChangeMap.Freeze();
+			
+			// Ensure that all changes take place inside an update group.
+			// Will also take care of throwing an exception if inDocumentChanging is set.
+			BeginUpdate();
+			try {
+				// protect document change against corruption by other changes inside the event handlers
+				inDocumentChanging = true;
+				try {
+					// The range verification must wait until after the BeginUpdate() call because the document
+					// might be modified inside the UpdateStarted event.
+					ThrowIfRangeInvalid(offset, length);
+					
+					DoReplace(offset, length, text, offsetChangeMap);
+				} finally {
+					inDocumentChanging = false;
+				}
+			} finally {
+				EndUpdate();
+			}
+		}
+		
+		void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
+		{
+			if (length == 0 && newText.TextLength == 0)
+				return;
+			
+			// trying to replace a single character in 'Normal' mode?
+			// for single characters, 'CharacterReplace' mode is equivalent, but more performant
+			// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
+			if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
+				offsetChangeMap = OffsetChangeMap.Empty;
+			
+			ITextSource removedText;
+			if (length == 0) {
+				removedText = StringTextSource.Empty;
+			} else if (length < 100) {
+				removedText = new StringTextSource(rope.ToString(offset, length));
+			} else {
+				// use a rope if the removed string is long
+				removedText = new RopeTextSource(rope.GetRange(offset, length));
+			}
+			DocumentChangeEventArgs args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
+			
+			// fire DocumentChanging event
+			if (Changing != null)
+				Changing(this, args);
+			if (textChanging != null)
+				textChanging(this, args);
+			
+			undoStack.Push(this, args);
+			
+			cachedText = null; // reset cache of complete document text
+			fireTextChanged = true;
+			DelayedEvents delayedEvents = new DelayedEvents();
+			
+			lock (lockObject) {
+				// create linked list of checkpoints
+				versionProvider.AppendChange(args);
+				
+				// now update the textBuffer and lineTree
+				if (offset == 0 && length == rope.Length) {
+					// optimize replacing the whole document
+					rope.Clear();
+					var newRopeTextSource = newText as RopeTextSource;
+					if (newRopeTextSource != null)
+						rope.InsertRange(0, newRopeTextSource.GetRope());
+					else
+						rope.InsertText(0, newText.Text);
+					lineManager.Rebuild();
+				} else {
+					rope.RemoveRange(offset, length);
+					lineManager.Remove(offset, length);
+					#if DEBUG
+					lineTree.CheckProperties();
+					#endif
+					var newRopeTextSource = newText as RopeTextSource;
+					if (newRopeTextSource != null)
+						rope.InsertRange(offset, newRopeTextSource.GetRope());
+					else
+						rope.InsertText(offset, newText.Text);
+					lineManager.Insert(offset, newText);
+					#if DEBUG
+					lineTree.CheckProperties();
+					#endif
+				}
+			}
+			
+			// update text anchors
+			if (offsetChangeMap == null) {
+				anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
+			} else {
+				foreach (OffsetChangeMapEntry entry in offsetChangeMap) {
+					anchorTree.HandleTextChange(entry, delayedEvents);
+				}
+			}
+			
+			lineManager.ChangeComplete(args);
+			
+			// raise delayed events after our data structures are consistent again
+			delayedEvents.RaiseEvents();
+			
+			// fire DocumentChanged event
+			if (Changed != null)
+				Changed(this, args);
+			if (textChanged != null)
+				textChanged(this, args);
+		}
+		#endregion
+		
+		#region GetLineBy...
+		/// <summary>
+		/// Gets a read-only list of lines.
+		/// </summary>
+		/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
+		public IList<DocumentLine> Lines {
+			get { return lineTree; }
+		}
+		
+		/// <summary>
+		/// Gets a line by the line number: O(log n)
+		/// </summary>
+		public DocumentLine GetLineByNumber(int number)
+		{
+			VerifyAccess();
+			if (number < 1 || number > lineTree.LineCount)
+				throw new ArgumentOutOfRangeException("number", number, "Value must be between 1 and " + lineTree.LineCount);
+			return lineTree.GetByNumber(number);
+		}
+		
+		IDocumentLine IDocument.GetLineByNumber(int lineNumber)
+		{
+			return GetLineByNumber(lineNumber);
+		}
+		
+		/// <summary>
+		/// Gets a document lines by offset.
+		/// Runtime: O(log n)
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
+		public DocumentLine GetLineByOffset(int offset)
+		{
+			VerifyAccess();
+			if (offset < 0 || offset > rope.Length) {
+				throw new ArgumentOutOfRangeException("offset", offset, "0 <= offset <= " + rope.Length.ToString());
+			}
+			return lineTree.GetByOffset(offset);
+		}
+		
+		IDocumentLine IDocument.GetLineByOffset(int offset)
+		{
+			return GetLineByOffset(offset);
+		}
+		#endregion
+		
+		#region GetOffset / GetLocation
+		/// <summary>
+		/// Gets the offset from a text location.
+		/// </summary>
+		/// <seealso cref="GetLocation"/>
+		public int GetOffset(TextLocation location)
+		{
+			return GetOffset(location.Line, location.Column);
+		}
+		
+		/// <summary>
+		/// Gets the offset from a text location.
+		/// </summary>
+		/// <seealso cref="GetLocation"/>
+		public int GetOffset(int line, int column)
+		{
+			DocumentLine docLine = GetLineByNumber(line);
+			if (column <= 0)
+				return docLine.Offset;
+			if (column > docLine.Length)
+				return docLine.EndOffset;
+			return docLine.Offset + column - 1;
+		}
+		
+		/// <summary>
+		/// Gets the location from an offset.
+		/// </summary>
+		/// <seealso cref="GetOffset(TextLocation)"/>
+		public TextLocation GetLocation(int offset)
+		{
+			DocumentLine line = GetLineByOffset(offset);
+			return new TextLocation(line.LineNumber, offset - line.Offset + 1);
+		}
+		#endregion
+		
+		#region Line Trackers
+		readonly ObservableCollection<ILineTracker> lineTrackers = new ObservableCollection<ILineTracker>();
+		
+		/// <summary>
+		/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
+		/// You can add custom line trackers to this list.
+		/// </summary>
+		public IList<ILineTracker> LineTrackers {
+			get {
+				VerifyAccess();
+				return lineTrackers;
+			}
+		}
+		#endregion
+		
+		#region UndoStack
+		UndoStack undoStack;
+		
+		/// <summary>
+		/// Gets the <see cref="UndoStack"/> of the document.
+		/// </summary>
+		/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
+		public UndoStack UndoStack {
+			get { return undoStack; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				if (value != undoStack) {
+					undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
+					// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
+					undoStack = value;
+					OnPropertyChanged("UndoStack");
+				}
+			}
+		}
+		#endregion
+		
+		#region CreateAnchor
+		/// <summary>
+		/// Creates a new <see cref="TextAnchor"/> at the specified offset.
+		/// </summary>
+		/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
+		public TextAnchor CreateAnchor(int offset)
+		{
+			VerifyAccess();
+			if (offset < 0 || offset > rope.Length) {
+				throw new ArgumentOutOfRangeException("offset", offset, "0 <= offset <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			return anchorTree.CreateAnchor(offset);
+		}
+		
+		ITextAnchor IDocument.CreateAnchor(int offset)
+		{
+			return CreateAnchor(offset);
+		}
+		#endregion
+		
+		#region LineCount
+		/// <summary>
+		/// Gets the total number of lines in the document.
+		/// Runtime: O(1).
+		/// </summary>
+		public int LineCount {
+			get {
+				VerifyAccess();
+				return lineTree.LineCount;
+			}
+		}
+		
+		/// <summary>
+		/// Is raised when the LineCount property changes.
+		/// </summary>
+		[Obsolete("This event will be removed in a future version; use the PropertyChanged event instead")]
+		public event EventHandler LineCountChanged;
+		#endregion
+		
+		#region Debugging
+		[Conditional("DEBUG")]
+		internal void DebugVerifyAccess()
+		{
+			VerifyAccess();
+		}
+		
+		/// <summary>
+		/// Gets the document lines tree in string form.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
+		internal string GetLineTreeAsString()
+		{
+			#if DEBUG
+			return lineTree.GetTreeAsString();
+			#else
+			return "Not available in release build.";
+			#endif
+		}
+		
+		/// <summary>
+		/// Gets the text anchor tree in string form.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
+		internal string GetTextAnchorTreeAsString()
+		{
+			#if DEBUG
+			return anchorTree.GetTreeAsString();
+			#else
+			return "Not available in release build.";
+			#endif
+		}
+		#endregion
+		
+		#region Service Provider
+		IServiceProvider serviceProvider;
+		
+		/// <summary>
+		/// Gets/Sets the service provider associated with this document.
+		/// By default, every TextDocument has its own ServiceContainer; and has the document itself
+		/// registered as <see cref="IDocument"/> and <see cref="TextDocument"/>.
+		/// </summary>
+		public IServiceProvider ServiceProvider {
+			get {
+				VerifyAccess();
+				if (serviceProvider == null) {
+					var container = new ServiceContainer();
+					container.AddService(typeof(IDocument), this);
+					container.AddService(typeof(TextDocument), this);
+					serviceProvider = container;
+				}
+				return serviceProvider;
+			}
+			set {
+				VerifyAccess();
+				if (value == null)
+					throw new ArgumentNullException();
+				serviceProvider = value;
+			}
+		}
+		
+		object IServiceProvider.GetService(Type serviceType)
+		{
+			return this.ServiceProvider.GetService(serviceType);
+		}
+		#endregion
+		
+		#region FileName
+		string fileName;
+		
+		/// <inheritdoc/>
+		public event EventHandler FileNameChanged;
+		
+		void OnFileNameChanged(EventArgs e)
+		{
+			EventHandler handler = this.FileNameChanged;
+			if (handler != null)
+				handler(this, e);
+		}
+		
+		/// <inheritdoc/>
+		public string FileName {
+			get { return fileName; }
+			set {
+				if (fileName != value) {
+					fileName = value;
+					OnFileNameChanged(EventArgs.Empty);
+				}
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextDocumentWeakEventManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextDocumentWeakEventManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextDocumentWeakEventManager.cs	(revision 11807)
@@ -0,0 +1,167 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Contains weak event managers for the TextDocument events.
+	/// </summary>
+	public static class TextDocumentWeakEventManager
+	{
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.UpdateStarted"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class UpdateStarted : WeakEventManagerBase<UpdateStarted, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.UpdateStarted += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.UpdateStarted -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.UpdateFinished"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class UpdateFinished : WeakEventManagerBase<UpdateFinished, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.UpdateFinished += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.UpdateFinished -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.Changing"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class Changing : WeakEventManagerBase<Changing, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.Changing += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.Changing -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.Changed"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class Changed : WeakEventManagerBase<Changed, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.Changed += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.Changed -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.LineCountChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		[Obsolete("The TextDocument.LineCountChanged event will be removed in a future version. Use PropertyChangedEventManager instead.")]
+		public sealed class LineCountChanged : WeakEventManagerBase<LineCountChanged, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.LineCountChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.LineCountChanged -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.TextLengthChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		[Obsolete("The TextDocument.TextLengthChanged event will be removed in a future version. Use PropertyChangedEventManager instead.")]
+		public sealed class TextLengthChanged : WeakEventManagerBase<TextLengthChanged, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.TextLengthChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.TextLengthChanged -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextDocument.TextChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class TextChanged : WeakEventManagerBase<TextChanged, TextDocument>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextDocument source)
+			{
+				source.TextChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextDocument source)
+			{
+				source.TextChanged -= DeliverEvent;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextLocation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextLocation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextLocation.cs	(revision 11807)
@@ -0,0 +1,271 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Globalization;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	#if !NREFACTORY
+	/// <summary>
+	/// A line/column position.
+	/// Text editor lines/columns are counted started from one.
+	/// </summary>
+	/// <remarks>
+	/// The document provides the methods <see cref="IDocument.GetLocation"/> and
+	/// <see cref="IDocument.GetOffset(TextLocation)"/> to convert between offsets and TextLocations.
+	/// </remarks>
+	[Serializable]
+	[TypeConverter(typeof(TextLocationConverter))]
+	public struct TextLocation : IComparable<TextLocation>, IEquatable<TextLocation>
+	{
+		/// <summary>
+		/// Represents no text location (0, 0).
+		/// </summary>
+		public static readonly TextLocation Empty = new TextLocation(0, 0);
+		
+		/// <summary>
+		/// Creates a TextLocation instance.
+		/// </summary>
+		public TextLocation(int line, int column)
+		{
+			this.line = line;
+			this.column = column;
+		}
+		
+		readonly int column, line;
+		
+		/// <summary>
+		/// Gets the line number.
+		/// </summary>
+		public int Line {
+			get { return line; }
+		}
+		
+		/// <summary>
+		/// Gets the column number.
+		/// </summary>
+		public int Column {
+			get { return column; }
+		}
+		
+		/// <summary>
+		/// Gets whether the TextLocation instance is empty.
+		/// </summary>
+		public bool IsEmpty {
+			get {
+				return column <= 0 && line <= 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets a string representation for debugging purposes.
+		/// </summary>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "(Line {1}, Col {0})", this.column, this.line);
+		}
+		
+		/// <summary>
+		/// Gets a hash code.
+		/// </summary>
+		public override int GetHashCode()
+		{
+			return unchecked (191 * column.GetHashCode() ^ line.GetHashCode());
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public override bool Equals(object obj)
+		{
+			if (!(obj is TextLocation)) return false;
+			return (TextLocation)obj == this;
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public bool Equals(TextLocation other)
+		{
+			return this == other;
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public static bool operator ==(TextLocation left, TextLocation right)
+		{
+			return left.column == right.column && left.line == right.line;
+		}
+		
+		/// <summary>
+		/// Inequality test.
+		/// </summary>
+		public static bool operator !=(TextLocation left, TextLocation right)
+		{
+			return left.column != right.column || left.line != right.line;
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator <(TextLocation left, TextLocation right)
+		{
+			if (left.line < right.line)
+				return true;
+			else if (left.line == right.line)
+				return left.column < right.column;
+			else
+				return false;
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator >(TextLocation left, TextLocation right)
+		{
+			if (left.line > right.line)
+				return true;
+			else if (left.line == right.line)
+				return left.column > right.column;
+			else
+				return false;
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator <=(TextLocation left, TextLocation right)
+		{
+			return !(left > right);
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator >=(TextLocation left, TextLocation right)
+		{
+			return !(left < right);
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public int CompareTo(TextLocation other)
+		{
+			if (this == other)
+				return 0;
+			if (this < other)
+				return -1;
+			else
+				return 1;
+		}
+	}
+	
+	/// <summary>
+	/// Converts strings of the form '0+[;,]0+' to a <see cref="TextLocation"/>.
+	/// </summary>
+	public class TextLocationConverter : TypeConverter
+	{
+		/// <inheritdoc/>
+		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
+		{
+			return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
+		}
+		
+		/// <inheritdoc/>
+		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
+		{
+			return destinationType == typeof(TextLocation) || base.CanConvertTo(context, destinationType);
+		}
+		
+		/// <inheritdoc/>
+		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
+		{
+			if (value is string) {
+				string[] parts = ((string)value).Split(';', ',');
+				if (parts.Length == 2) {
+					return new TextLocation(int.Parse(parts[0], culture), int.Parse(parts[1], culture));
+				}
+			}
+			return base.ConvertFrom(context, culture, value);
+		}
+		
+		/// <inheritdoc/>
+		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
+		{
+			if (value is TextLocation && destinationType == typeof(string)) {
+				var loc = (TextLocation)value;
+				return loc.Line.ToString(culture) + ";" + loc.Column.ToString(culture);
+			}
+			return base.ConvertTo(context, culture, value, destinationType);
+		}
+	}
+	
+	/// <summary>
+	/// An (Offset,Length)-pair.
+	/// </summary>
+	public interface ISegment
+	{
+		/// <summary>
+		/// Gets the start offset of the segment.
+		/// </summary>
+		int Offset { get; }
+		
+		/// <summary>
+		/// Gets the length of the segment.
+		/// </summary>
+		/// <remarks>For line segments (IDocumentLine), the length does not include the line delimeter.</remarks>
+		int Length { get; }
+		
+		/// <summary>
+		/// Gets the end offset of the segment.
+		/// </summary>
+		/// <remarks>EndOffset = Offset + Length;</remarks>
+		int EndOffset { get; }
+	}
+	
+	/// <summary>
+	/// Extension methods for <see cref="ISegment"/>.
+	/// </summary>
+	public static class ISegmentExtensions
+	{
+		/// <summary>
+		/// Gets whether <paramref name="segment"/> fully contains the specified segment.
+		/// </summary>
+		/// <remarks>
+		/// Use <c>segment.Contains(offset, 0)</c> to detect whether a segment (end inclusive) contains offset;
+		/// use <c>segment.Contains(offset, 1)</c> to detect whether a segment (end exclusive) contains offset.
+		/// </remarks>
+		public static bool Contains (this ISegment segment, int offset, int length)
+		{
+			return segment.Offset <= offset && offset + length <= segment.EndOffset;
+		}
+		
+		/// <summary>
+		/// Gets whether <paramref name="thisSegment"/> fully contains the specified segment.
+		/// </summary>
+		public static bool Contains (this ISegment thisSegment, ISegment segment)
+		{
+			return segment != null && thisSegment.Offset <= segment.Offset && segment.EndOffset <= thisSegment.EndOffset;
+		}
+	}
+	#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSegment.cs	(revision 11807)
@@ -0,0 +1,266 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// A segment that can be put into a <see cref="TextSegmentCollection{T}"/>.
+	/// </summary>
+	/// <remarks>
+	/// <para>
+	/// A <see cref="TextSegment"/> can be stand-alone or part of a <see cref="TextSegmentCollection{T}"/>.
+	/// If the segment is stored inside a TextSegmentCollection, its Offset and Length will be updated by that collection.
+	/// </para>
+	/// <para>
+	/// When the document changes, the offsets of all text segments in the TextSegmentCollection will be adjusted accordingly.
+	/// Start offsets move like <see cref="AnchorMovementType">AnchorMovementType.AfterInsertion</see>,
+	/// end offsets move like <see cref="AnchorMovementType">AnchorMovementType.BeforeInsertion</see>
+	/// (i.e. the segment will always stay as small as possible).</para>
+	/// <para>
+	/// If a document change causes a segment to be deleted completely, it will be reduced to length 0, but segments are
+	/// never automatically removed from the collection.
+	/// Segments with length 0 will never expand due to document changes, and they move as <c>AfterInsertion</c>.
+	/// </para>
+	/// <para>
+	/// Thread-safety: a TextSegmentCollection that is connected to a <see cref="TextDocument"/> may only be used on that document's owner thread.
+	/// A disconnected TextSegmentCollection is safe for concurrent reads, but concurrent access is not safe when there are writes.
+	/// Keep in mind that reading the Offset properties of a text segment inside the collection is a read access on the
+	/// collection; and setting an Offset property of a text segment is a write access on the collection.
+	/// </para>
+	/// </remarks>
+	/// <seealso cref="ISegment"/>
+	/// <seealso cref="AnchorSegment"/>
+	/// <seealso cref="TextSegmentCollection{T}"/>
+	public class TextSegment : ISegment
+	{
+		internal ISegmentTree ownerTree;
+		internal TextSegment left, right, parent;
+		
+		/// <summary>
+		/// The color of the segment in the red/black tree.
+		/// </summary>
+		internal bool color;
+		
+		/// <summary>
+		/// The "length" of the node (distance to previous node)
+		/// </summary>
+		internal int nodeLength;
+		
+		/// <summary>
+		/// The total "length" of this subtree.
+		/// </summary>
+		internal int totalNodeLength; // totalNodeLength = nodeLength + left.totalNodeLength + right.totalNodeLength
+		
+		/// <summary>
+		/// The length of the segment (do not confuse with nodeLength).
+		/// </summary>
+		internal int segmentLength;
+		
+		/// <summary>
+		/// distanceToMaxEnd = Max(segmentLength,
+		///                        left.distanceToMaxEnd + left.Offset - Offset,
+		///                        left.distanceToMaxEnd + right.Offset - Offset)
+		/// </summary>
+		internal int distanceToMaxEnd;
+		
+		int ISegment.Offset {
+			get { return StartOffset; }
+		}
+		
+		/// <summary>
+		/// Gets whether this segment is connected to a TextSegmentCollection and will automatically
+		/// update its offsets.
+		/// </summary>
+		protected bool IsConnectedToCollection {
+			get {
+				return ownerTree != null;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the start offset of the segment.
+		/// </summary>
+		/// <remarks>
+		/// When setting the start offset, the end offset will change, too: the Length of the segment will stay constant.
+		/// </remarks>
+		public int StartOffset {
+			get {
+				// If the segment is not connected to a tree, we store the offset in "nodeLength".
+				// Otherwise, "nodeLength" contains the distance to the start offset of the previous node
+				Debug.Assert(!(ownerTree == null && parent != null));
+				Debug.Assert(!(ownerTree == null && left != null));
+				
+				TextSegment n = this;
+				int offset = n.nodeLength;
+				if (n.left != null)
+					offset += n.left.totalNodeLength;
+				while (n.parent != null) {
+					if (n == n.parent.right) {
+						if (n.parent.left != null)
+							offset += n.parent.left.totalNodeLength;
+						offset += n.parent.nodeLength;
+					}
+					n = n.parent;
+				}
+				return offset;
+			}
+			set {
+				if (value < 0)
+					throw new ArgumentOutOfRangeException("value", "Offset must not be negative");
+				if (this.StartOffset != value) {
+					// need a copy of the variable because ownerTree.Remove() sets this.ownerTree to null
+					ISegmentTree ownerTree = this.ownerTree;
+					if (ownerTree != null) {
+						ownerTree.Remove(this);
+						nodeLength = value;
+						ownerTree.Add(this);
+					} else {
+						nodeLength = value;
+					}
+					OnSegmentChanged();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the end offset of the segment.
+		/// </summary>
+		/// <remarks>
+		/// Setting the end offset will change the length, the start offset will stay constant.
+		/// </remarks>
+		public int EndOffset {
+			get {
+				return StartOffset + Length;
+			}
+			set {
+				int newLength = value - StartOffset;
+				if (newLength < 0)
+					throw new ArgumentOutOfRangeException("value", "EndOffset must be greater or equal to StartOffset");
+				Length = newLength;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the length of the segment.
+		/// </summary>
+		/// <remarks>
+		/// Setting the length will change the end offset, the start offset will stay constant.
+		/// </remarks>
+		public int Length {
+			get {
+				return segmentLength;
+			}
+			set {
+				if (value < 0)
+					throw new ArgumentOutOfRangeException("value", "Length must not be negative");
+				if (segmentLength != value) {
+					segmentLength = value;
+					if (ownerTree != null)
+						ownerTree.UpdateAugmentedData(this);
+					OnSegmentChanged();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// This method gets called when the StartOffset/Length/EndOffset properties are set.
+		/// It is not called when StartOffset/Length/EndOffset change due to document changes
+		/// </summary>
+		protected virtual void OnSegmentChanged()
+		{
+		}
+		
+		internal TextSegment LeftMost {
+			get {
+				TextSegment node = this;
+				while (node.left != null)
+					node = node.left;
+				return node;
+			}
+		}
+		
+		internal TextSegment RightMost {
+			get {
+				TextSegment node = this;
+				while (node.right != null)
+					node = node.right;
+				return node;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the inorder successor of the node.
+		/// </summary>
+		internal TextSegment Successor {
+			get {
+				if (right != null) {
+					return right.LeftMost;
+				} else {
+					TextSegment node = this;
+					TextSegment oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// go up until we are coming out of a left subtree
+					} while (node != null && node.right == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the inorder predecessor of the node.
+		/// </summary>
+		internal TextSegment Predecessor {
+			get {
+				if (left != null) {
+					return left.RightMost;
+				} else {
+					TextSegment node = this;
+					TextSegment oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// go up until we are coming out of a right subtree
+					} while (node != null && node.left == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		#if DEBUG
+		internal string ToDebugString()
+		{
+			return "[nodeLength=" + nodeLength + " totalNodeLength=" + totalNodeLength
+				+ " distanceToMaxEnd=" + distanceToMaxEnd + " MaxEndOffset=" + (StartOffset + distanceToMaxEnd) + "]";
+		}
+		#endif
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " Offset=" + StartOffset + " Length=" + Length + " EndOffset=" + EndOffset + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSegmentCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSegmentCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSegmentCollection.cs	(revision 11807)
@@ -0,0 +1,989 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Windows;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Interface to allow TextSegments to access the TextSegmentCollection - we cannot use a direct reference
+	/// because TextSegmentCollection is generic.
+	/// </summary>
+	interface ISegmentTree
+	{
+		void Add(TextSegment s);
+		void Remove(TextSegment s);
+		void UpdateAugmentedData(TextSegment s);
+	}
+	
+	/// <summary>
+	/// <para>
+	/// A collection of text segments that supports efficient lookup of segments
+	/// intersecting with another segment.
+	/// </para>
+	/// </summary>
+	/// <remarks><inheritdoc cref="TextSegment"/></remarks>
+	/// <see cref="TextSegment"/>
+	public sealed class TextSegmentCollection<T> : ICollection<T>, ISegmentTree, IWeakEventListener where T : TextSegment
+	{
+		// Implementation: this is basically a mixture of an augmented interval tree
+		// and the TextAnchorTree.
+		
+		// WARNING: you need to understand interval trees (the version with the augmented 'high'/'max' field)
+		// and how the TextAnchorTree works before you have any chance of understanding this code.
+		
+		// This means that every node holds two "segments":
+		// one like the segments in the text anchor tree to support efficient offset changes
+		// and another that is the interval as seen by the user
+		
+		// So basically, the tree contains a list of contiguous node segments of the first kind,
+		// with interval segments starting at the end of every node segment.
+		
+		// Performance:
+		// Add is O(lg n)
+		// Remove is O(lg n)
+		// DocumentChanged is O(m * lg n), with m the number of segments that intersect with the changed document section
+		// FindFirstSegmentWithStartAfter is O(m + lg n) with m being the number of segments at the same offset as the result segment
+		// FindIntersectingSegments is O(m + lg n) with m being the number of intersecting segments.
+		
+		int count;
+		TextSegment root;
+		bool isConnectedToDocument;
+		
+		#region Constructor
+		/// <summary>
+		/// Creates a new TextSegmentCollection that needs manual calls to <see cref="UpdateOffsets(DocumentChangeEventArgs)"/>.
+		/// </summary>
+		public TextSegmentCollection()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new TextSegmentCollection that updates the offsets automatically.
+		/// </summary>
+		/// <param name="textDocument">The document to which the text segments
+		/// that will be added to the tree belong. When the document changes, the
+		/// position of the text segments will be updated accordingly.</param>
+		public TextSegmentCollection(TextDocument textDocument)
+		{
+			if (textDocument == null)
+				throw new ArgumentNullException("textDocument");
+			
+			textDocument.VerifyAccess();
+			isConnectedToDocument = true;
+			TextDocumentWeakEventManager.Changed.AddListener(textDocument, this);
+		}
+		#endregion
+		
+		#region OnDocumentChanged / UpdateOffsets
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
+				OnDocumentChanged((DocumentChangeEventArgs)e);
+				return true;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Updates the start and end offsets of all segments stored in this collection.
+		/// </summary>
+		/// <param name="e">DocumentChangeEventArgs instance describing the change to the document.</param>
+		public void UpdateOffsets(DocumentChangeEventArgs e)
+		{
+			if (e == null)
+				throw new ArgumentNullException("e");
+			if (isConnectedToDocument)
+				throw new InvalidOperationException("This TextSegmentCollection will automatically update offsets; do not call UpdateOffsets manually!");
+			OnDocumentChanged(e);
+			CheckProperties();
+		}
+		
+		void OnDocumentChanged(DocumentChangeEventArgs e)
+		{
+			OffsetChangeMap map = e.OffsetChangeMapOrNull;
+			if (map != null) {
+				foreach (OffsetChangeMapEntry entry in map) {
+					UpdateOffsetsInternal(entry);
+				}
+			} else {
+				UpdateOffsetsInternal(e.CreateSingleChangeMapEntry());
+			}
+		}
+		
+		/// <summary>
+		/// Updates the start and end offsets of all segments stored in this collection.
+		/// </summary>
+		/// <param name="change">OffsetChangeMapEntry instance describing the change to the document.</param>
+		public void UpdateOffsets(OffsetChangeMapEntry change)
+		{
+			if (isConnectedToDocument)
+				throw new InvalidOperationException("This TextSegmentCollection will automatically update offsets; do not call UpdateOffsets manually!");
+			UpdateOffsetsInternal(change);
+			CheckProperties();
+		}
+		#endregion
+		
+		#region UpdateOffsets (implementation)
+		void UpdateOffsetsInternal(OffsetChangeMapEntry change)
+		{
+			// Special case pure insertions, because they don't always cause a text segment to increase in size when the replaced region
+			// is inside a segment (when offset is at start or end of a text semgent).
+			if (change.RemovalLength == 0) {
+				InsertText(change.Offset, change.InsertionLength);
+			} else {
+				ReplaceText(change);
+			}
+		}
+		
+		void InsertText(int offset, int length)
+		{
+			if (length == 0)
+				return;
+			
+			// enlarge segments that contain offset (excluding those that have offset as endpoint)
+			foreach (TextSegment segment in FindSegmentsContaining(offset)) {
+				if (segment.StartOffset < offset && offset < segment.EndOffset) {
+					segment.Length += length;
+				}
+			}
+			
+			// move start offsets of all segments >= offset
+			TextSegment node = FindFirstSegmentWithStartAfter(offset);
+			if (node != null) {
+				node.nodeLength += length;
+				UpdateAugmentedData(node);
+			}
+		}
+		
+		void ReplaceText(OffsetChangeMapEntry change)
+		{
+			Debug.Assert(change.RemovalLength > 0);
+			int offset = change.Offset;
+			foreach (TextSegment segment in FindOverlappingSegments(offset, change.RemovalLength)) {
+				if (segment.StartOffset <= offset) {
+					if (segment.EndOffset >= offset + change.RemovalLength) {
+						// Replacement inside segment: adjust segment length
+						segment.Length += change.InsertionLength - change.RemovalLength;
+					} else {
+						// Replacement starting inside segment and ending after segment end: set segment end to removal position
+						//segment.EndOffset = offset;
+						segment.Length = offset - segment.StartOffset;
+					}
+				} else {
+					// Replacement starting in front of text segment and running into segment.
+					// Keep segment.EndOffset constant and move segment.StartOffset to the end of the replacement
+					int remainingLength = segment.EndOffset - (offset + change.RemovalLength);
+					RemoveSegment(segment);
+					segment.StartOffset = offset + change.RemovalLength;
+					segment.Length = Math.Max(0, remainingLength);
+					AddSegment(segment);
+				}
+			}
+			// move start offsets of all segments > offset
+			TextSegment node = FindFirstSegmentWithStartAfter(offset + 1);
+			if (node != null) {
+				Debug.Assert(node.nodeLength >= change.RemovalLength);
+				node.nodeLength += change.InsertionLength - change.RemovalLength;
+				UpdateAugmentedData(node);
+			}
+		}
+		#endregion
+		
+		#region Add
+		/// <summary>
+		/// Adds the specified segment to the tree. This will cause the segment to update when the
+		/// document changes.
+		/// </summary>
+		public void Add(T item)
+		{
+			if (item == null)
+				throw new ArgumentNullException("item");
+			if (item.ownerTree != null)
+				throw new ArgumentException("The segment is already added to a SegmentCollection.");
+			AddSegment(item);
+		}
+		
+		void ISegmentTree.Add(TextSegment s)
+		{
+			AddSegment(s);
+		}
+		
+		void AddSegment(TextSegment node)
+		{
+			int insertionOffset = node.StartOffset;
+			node.distanceToMaxEnd = node.segmentLength;
+			if (root == null) {
+				root = node;
+				node.totalNodeLength = node.nodeLength;
+			} else if (insertionOffset >= root.totalNodeLength) {
+				// append segment at end of tree
+				node.nodeLength = node.totalNodeLength = insertionOffset - root.totalNodeLength;
+				InsertAsRight(root.RightMost, node);
+			} else {
+				// insert in middle of tree
+				TextSegment n = FindNode(ref insertionOffset);
+				Debug.Assert(insertionOffset < n.nodeLength);
+				// split node segment 'n' at offset
+				node.totalNodeLength = node.nodeLength = insertionOffset;
+				n.nodeLength -= insertionOffset;
+				InsertBefore(n, node);
+			}
+			node.ownerTree = this;
+			count++;
+			CheckProperties();
+		}
+		
+		void InsertBefore(TextSegment node, TextSegment newNode)
+		{
+			if (node.left == null) {
+				InsertAsLeft(node, newNode);
+			} else {
+				InsertAsRight(node.left.RightMost, newNode);
+			}
+		}
+		#endregion
+		
+		#region GetNextSegment / GetPreviousSegment
+		/// <summary>
+		/// Gets the next segment after the specified segment.
+		/// Segments are sorted by their start offset.
+		/// Returns null if segment is the last segment.
+		/// </summary>
+		public T GetNextSegment(T segment)
+		{
+			if (!Contains(segment))
+				throw new ArgumentException("segment is not inside the segment tree");
+			return (T)segment.Successor;
+		}
+		
+		/// <summary>
+		/// Gets the previous segment before the specified segment.
+		/// Segments are sorted by their start offset.
+		/// Returns null if segment is the first segment.
+		/// </summary>
+		public T GetPreviousSegment(T segment)
+		{
+			if (!Contains(segment))
+				throw new ArgumentException("segment is not inside the segment tree");
+			return (T)segment.Predecessor;
+		}
+		#endregion
+		
+		#region FirstSegment/LastSegment
+		/// <summary>
+		/// Returns the first segment in the collection or null, if the collection is empty.
+		/// </summary>
+		public T FirstSegment {
+			get {
+				return root == null ? null : (T)root.LeftMost;
+			}
+		}
+		
+		/// <summary>
+		/// Returns the last segment in the collection or null, if the collection is empty.
+		/// </summary>
+		public T LastSegment {
+			get {
+				return root == null ? null : (T)root.RightMost;
+			}
+		}
+		#endregion
+		
+		#region FindFirstSegmentWithStartAfter
+		/// <summary>
+		/// Gets the first segment with a start offset greater or equal to <paramref name="startOffset"/>.
+		/// Returns null if no such segment is found.
+		/// </summary>
+		public T FindFirstSegmentWithStartAfter(int startOffset)
+		{
+			if (root == null)
+				return null;
+			if (startOffset <= 0)
+				return (T)root.LeftMost;
+			TextSegment s = FindNode(ref startOffset);
+			// startOffset means that the previous segment is starting at the offset we were looking for
+			while (startOffset == 0) {
+				TextSegment p = (s == null) ? root.RightMost : s.Predecessor;
+				// There must always be a predecessor: if we were looking for the first node, we would have already
+				// returned it as root.LeftMost above.
+				Debug.Assert(p != null);
+				startOffset += p.nodeLength;
+				s = p;
+			}
+			return (T)s;
+		}
+		
+		/// <summary>
+		/// Finds the node at the specified offset.
+		/// After the method has run, offset is relative to the beginning of the returned node.
+		/// </summary>
+		TextSegment FindNode(ref int offset)
+		{
+			TextSegment n = root;
+			while (true) {
+				if (n.left != null) {
+					if (offset < n.left.totalNodeLength) {
+						n = n.left; // descend into left subtree
+						continue;
+					} else {
+						offset -= n.left.totalNodeLength; // skip left subtree
+					}
+				}
+				if (offset < n.nodeLength) {
+					return n; // found correct node
+				} else {
+					offset -= n.nodeLength; // skip this node
+				}
+				if (n.right != null) {
+					n = n.right; // descend into right subtree
+				} else {
+					// didn't find any node containing the offset
+					return null;
+				}
+			}
+		}
+		#endregion
+		
+		#region FindOverlappingSegments
+		/// <summary>
+		/// Finds all segments that contain the given offset.
+		/// (StartOffset &lt;= offset &lt;= EndOffset)
+		/// Segments are returned in the order given by GetNextSegment/GetPreviousSegment.
+		/// </summary>
+		/// <returns>Returns a new collection containing the results of the query.
+		/// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
+		public ReadOnlyCollection<T> FindSegmentsContaining(int offset)
+		{
+			return FindOverlappingSegments(offset, 0);
+		}
+		
+		/// <summary>
+		/// Finds all segments that overlap with the given segment (including touching segments).
+		/// </summary>
+		/// <returns>Returns a new collection containing the results of the query.
+		/// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
+		public ReadOnlyCollection<T> FindOverlappingSegments(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return FindOverlappingSegments(segment.Offset, segment.Length);
+		}
+		
+		/// <summary>
+		/// Finds all segments that overlap with the given segment (including touching segments).
+		/// Segments are returned in the order given by GetNextSegment/GetPreviousSegment.
+		/// </summary>
+		/// <returns>Returns a new collection containing the results of the query.
+		/// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
+		public ReadOnlyCollection<T> FindOverlappingSegments(int offset, int length)
+		{
+			ThrowUtil.CheckNotNegative(length, "length");
+			List<T> results = new List<T>();
+			if (root != null) {
+				FindOverlappingSegments(results, root, offset, offset + length);
+			}
+			return results.AsReadOnly();
+		}
+		
+		void FindOverlappingSegments(List<T> results, TextSegment node, int low, int high)
+		{
+			// low and high are relative to node.LeftMost startpos (not node.LeftMost.Offset)
+			if (high < 0) {
+				// node is irrelevant for search because all intervals in node are after high
+				return;
+			}
+			
+			// find values relative to node.Offset
+			int nodeLow = low - node.nodeLength;
+			int nodeHigh = high - node.nodeLength;
+			if (node.left != null) {
+				nodeLow -= node.left.totalNodeLength;
+				nodeHigh -= node.left.totalNodeLength;
+			}
+			
+			if (node.distanceToMaxEnd < nodeLow) {
+				// node is irrelevant for search because all intervals in node are before low
+				return;
+			}
+			
+			if (node.left != null)
+				FindOverlappingSegments(results, node.left, low, high);
+			
+			if (nodeHigh < 0) {
+				// node and everything in node.right is before low
+				return;
+			}
+			
+			if (nodeLow <= node.segmentLength) {
+				results.Add((T)node);
+			}
+			
+			if (node.right != null)
+				FindOverlappingSegments(results, node.right, nodeLow, nodeHigh);
+		}
+		#endregion
+		
+		#region UpdateAugmentedData
+		void UpdateAugmentedData(TextSegment node)
+		{
+			int totalLength = node.nodeLength;
+			int distanceToMaxEnd = node.segmentLength;
+			if (node.left != null) {
+				totalLength += node.left.totalNodeLength;
+				
+				int leftDTME = node.left.distanceToMaxEnd;
+				// dtme is relative, so convert it to the coordinates of node:
+				if (node.left.right != null)
+					leftDTME -= node.left.right.totalNodeLength;
+				leftDTME -= node.nodeLength;
+				if (leftDTME > distanceToMaxEnd)
+					distanceToMaxEnd = leftDTME;
+			}
+			if (node.right != null) {
+				totalLength += node.right.totalNodeLength;
+				
+				int rightDTME = node.right.distanceToMaxEnd;
+				// dtme is relative, so convert it to the coordinates of node:
+				rightDTME += node.right.nodeLength;
+				if (node.right.left != null)
+					rightDTME += node.right.left.totalNodeLength;
+				if (rightDTME > distanceToMaxEnd)
+					distanceToMaxEnd = rightDTME;
+			}
+			if (node.totalNodeLength != totalLength
+			    || node.distanceToMaxEnd != distanceToMaxEnd)
+			{
+				node.totalNodeLength = totalLength;
+				node.distanceToMaxEnd = distanceToMaxEnd;
+				if (node.parent != null)
+					UpdateAugmentedData(node.parent);
+			}
+		}
+		
+		void ISegmentTree.UpdateAugmentedData(TextSegment node)
+		{
+			UpdateAugmentedData(node);
+		}
+		#endregion
+		
+		#region Remove
+		/// <summary>
+		/// Removes the specified segment from the tree. This will cause the segment to not update
+		/// anymore when the document changes.
+		/// </summary>
+		public bool Remove(T item)
+		{
+			if (!Contains(item))
+				return false;
+			RemoveSegment(item);
+			return true;
+		}
+		
+		void ISegmentTree.Remove(TextSegment s)
+		{
+			RemoveSegment(s);
+		}
+		
+		void RemoveSegment(TextSegment s)
+		{
+			int oldOffset = s.StartOffset;
+			TextSegment successor = s.Successor;
+			if (successor != null)
+				successor.nodeLength += s.nodeLength;
+			RemoveNode(s);
+			if (successor != null)
+				UpdateAugmentedData(successor);
+			Disconnect(s, oldOffset);
+			CheckProperties();
+		}
+		
+		void Disconnect(TextSegment s, int offset)
+		{
+			s.left = s.right = s.parent = null;
+			s.ownerTree = null;
+			s.nodeLength = offset;
+			count--;
+		}
+		
+		/// <summary>
+		/// Removes all segments from the tree.
+		/// </summary>
+		public void Clear()
+		{
+			T[] segments = this.ToArray();
+			root = null;
+			int offset = 0;
+			foreach (TextSegment s in segments) {
+				offset += s.nodeLength;
+				Disconnect(s, offset);
+			}
+			CheckProperties();
+		}
+		#endregion
+		
+		#region CheckProperties
+		[Conditional("DATACONSISTENCYTEST")]
+		internal void CheckProperties()
+		{
+			#if DEBUG
+			if (root != null) {
+				CheckProperties(root);
+				
+				// check red-black property:
+				int blackCount = -1;
+				CheckNodeProperties(root, null, RED, 0, ref blackCount);
+			}
+			
+			int expectedCount = 0;
+			// we cannot trust LINQ not to call ICollection.Count, so we need this loop
+			// to count the elements in the tree
+			using (IEnumerator<T> en = GetEnumerator()) {
+				while (en.MoveNext()) expectedCount++;
+			}
+			Debug.Assert(count == expectedCount);
+			#endif
+		}
+		
+		#if DEBUG
+		void CheckProperties(TextSegment node)
+		{
+			int totalLength = node.nodeLength;
+			int distanceToMaxEnd = node.segmentLength;
+			if (node.left != null) {
+				CheckProperties(node.left);
+				totalLength += node.left.totalNodeLength;
+				distanceToMaxEnd = Math.Max(distanceToMaxEnd,
+				                            node.left.distanceToMaxEnd + node.left.StartOffset - node.StartOffset);
+			}
+			if (node.right != null) {
+				CheckProperties(node.right);
+				totalLength += node.right.totalNodeLength;
+				distanceToMaxEnd = Math.Max(distanceToMaxEnd,
+				                            node.right.distanceToMaxEnd + node.right.StartOffset - node.StartOffset);
+			}
+			Debug.Assert(node.totalNodeLength == totalLength);
+			Debug.Assert(node.distanceToMaxEnd == distanceToMaxEnd);
+		}
+		
+		/*
+		1. A node is either red or black.
+		2. The root is black.
+		3. All leaves are black. (The leaves are the NIL children.)
+		4. Both children of every red node are black. (So every red node must have a black parent.)
+		5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
+		 */
+		void CheckNodeProperties(TextSegment node, TextSegment parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
+		{
+			if (node == null) return;
+			
+			Debug.Assert(node.parent == parentNode);
+			
+			if (parentColor == RED) {
+				Debug.Assert(node.color == BLACK);
+			}
+			if (node.color == BLACK) {
+				blackCount++;
+			}
+			if (node.left == null && node.right == null) {
+				// node is a leaf node:
+				if (expectedBlackCount == -1)
+					expectedBlackCount = blackCount;
+				else
+					Debug.Assert(expectedBlackCount == blackCount);
+			}
+			CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
+			CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
+		}
+		
+		static void AppendTreeToString(TextSegment node, StringBuilder b, int indent)
+		{
+			if (node.color == RED)
+				b.Append("RED   ");
+			else
+				b.Append("BLACK ");
+			b.AppendLine(node.ToString() + node.ToDebugString());
+			indent += 2;
+			if (node.left != null) {
+				b.Append(' ', indent);
+				b.Append("L: ");
+				AppendTreeToString(node.left, b, indent);
+			}
+			if (node.right != null) {
+				b.Append(' ', indent);
+				b.Append("R: ");
+				AppendTreeToString(node.right, b, indent);
+			}
+		}
+		#endif
+		
+		internal string GetTreeAsString()
+		{
+			#if DEBUG
+			StringBuilder b = new StringBuilder();
+			if (root != null)
+				AppendTreeToString(root, b, 0);
+			return b.ToString();
+			#else
+			return "Not available in release build.";
+			#endif
+		}
+		#endregion
+		
+		#region Red/Black Tree
+		internal const bool RED = true;
+		internal const bool BLACK = false;
+		
+		void InsertAsLeft(TextSegment parentNode, TextSegment newNode)
+		{
+			Debug.Assert(parentNode.left == null);
+			parentNode.left = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAugmentedData(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void InsertAsRight(TextSegment parentNode, TextSegment newNode)
+		{
+			Debug.Assert(parentNode.right == null);
+			parentNode.right = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAugmentedData(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void FixTreeOnInsert(TextSegment node)
+		{
+			Debug.Assert(node != null);
+			Debug.Assert(node.color == RED);
+			Debug.Assert(node.left == null || node.left.color == BLACK);
+			Debug.Assert(node.right == null || node.right.color == BLACK);
+			
+			TextSegment parentNode = node.parent;
+			if (parentNode == null) {
+				// we inserted in the root -> the node must be black
+				// since this is a root node, making the node black increments the number of black nodes
+				// on all paths by one, so it is still the same for all paths.
+				node.color = BLACK;
+				return;
+			}
+			if (parentNode.color == BLACK) {
+				// if the parent node where we inserted was black, our red node is placed correctly.
+				// since we inserted a red node, the number of black nodes on each path is unchanged
+				// -> the tree is still balanced
+				return;
+			}
+			// parentNode is red, so there is a conflict here!
+			
+			// because the root is black, parentNode is not the root -> there is a grandparent node
+			TextSegment grandparentNode = parentNode.parent;
+			TextSegment uncleNode = Sibling(parentNode);
+			if (uncleNode != null && uncleNode.color == RED) {
+				parentNode.color = BLACK;
+				uncleNode.color = BLACK;
+				grandparentNode.color = RED;
+				FixTreeOnInsert(grandparentNode);
+				return;
+			}
+			// now we know: parent is red but uncle is black
+			// First rotation:
+			if (node == parentNode.right && parentNode == grandparentNode.left) {
+				RotateLeft(parentNode);
+				node = node.left;
+			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
+				RotateRight(parentNode);
+				node = node.right;
+			}
+			// because node might have changed, reassign variables:
+			parentNode = node.parent;
+			grandparentNode = parentNode.parent;
+			
+			// Now recolor a bit:
+			parentNode.color = BLACK;
+			grandparentNode.color = RED;
+			// Second rotation:
+			if (node == parentNode.left && parentNode == grandparentNode.left) {
+				RotateRight(grandparentNode);
+			} else {
+				// because of the first rotation, this is guaranteed:
+				Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
+				RotateLeft(grandparentNode);
+			}
+		}
+		
+		void RemoveNode(TextSegment removedNode)
+		{
+			if (removedNode.left != null && removedNode.right != null) {
+				// replace removedNode with it's in-order successor
+				
+				TextSegment leftMost = removedNode.right.LeftMost;
+				RemoveNode(leftMost); // remove leftMost from its current location
+				
+				// and overwrite the removedNode with it
+				ReplaceNode(removedNode, leftMost);
+				leftMost.left = removedNode.left;
+				if (leftMost.left != null) leftMost.left.parent = leftMost;
+				leftMost.right = removedNode.right;
+				if (leftMost.right != null) leftMost.right.parent = leftMost;
+				leftMost.color = removedNode.color;
+				
+				UpdateAugmentedData(leftMost);
+				if (leftMost.parent != null) UpdateAugmentedData(leftMost.parent);
+				return;
+			}
+			
+			// now either removedNode.left or removedNode.right is null
+			// get the remaining child
+			TextSegment parentNode = removedNode.parent;
+			TextSegment childNode = removedNode.left ?? removedNode.right;
+			ReplaceNode(removedNode, childNode);
+			if (parentNode != null) UpdateAugmentedData(parentNode);
+			if (removedNode.color == BLACK) {
+				if (childNode != null && childNode.color == RED) {
+					childNode.color = BLACK;
+				} else {
+					FixTreeOnDelete(childNode, parentNode);
+				}
+			}
+		}
+		
+		void FixTreeOnDelete(TextSegment node, TextSegment parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (parentNode == null)
+				return;
+			
+			// warning: node may be null
+			TextSegment sibling = Sibling(node, parentNode);
+			if (sibling.color == RED) {
+				parentNode.color = RED;
+				sibling.color = BLACK;
+				if (node == parentNode.left) {
+					RotateLeft(parentNode);
+				} else {
+					RotateRight(parentNode);
+				}
+				
+				sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			}
+			
+			if (parentNode.color == BLACK
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				FixTreeOnDelete(parentNode, parentNode.parent);
+				return;
+			}
+			
+			if (parentNode.color == RED
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				parentNode.color = BLACK;
+				return;
+			}
+			
+			if (node == parentNode.left &&
+			    sibling.color == BLACK &&
+			    GetColor(sibling.left) == RED &&
+			    GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.left.color = BLACK;
+				RotateRight(sibling);
+			}
+			else if (node == parentNode.right &&
+			         sibling.color == BLACK &&
+			         GetColor(sibling.right) == RED &&
+			         GetColor(sibling.left) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.right.color = BLACK;
+				RotateLeft(sibling);
+			}
+			sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			
+			sibling.color = parentNode.color;
+			parentNode.color = BLACK;
+			if (node == parentNode.left) {
+				if (sibling.right != null) {
+					Debug.Assert(sibling.right.color == RED);
+					sibling.right.color = BLACK;
+				}
+				RotateLeft(parentNode);
+			} else {
+				if (sibling.left != null) {
+					Debug.Assert(sibling.left.color == RED);
+					sibling.left.color = BLACK;
+				}
+				RotateRight(parentNode);
+			}
+		}
+		
+		void ReplaceNode(TextSegment replacedNode, TextSegment newNode)
+		{
+			if (replacedNode.parent == null) {
+				Debug.Assert(replacedNode == root);
+				root = newNode;
+			} else {
+				if (replacedNode.parent.left == replacedNode)
+					replacedNode.parent.left = newNode;
+				else
+					replacedNode.parent.right = newNode;
+			}
+			if (newNode != null) {
+				newNode.parent = replacedNode.parent;
+			}
+			replacedNode.parent = null;
+		}
+		
+		void RotateLeft(TextSegment p)
+		{
+			// let q be p's right child
+			TextSegment q = p.right;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's right child to be q's left child
+			p.right = q.left;
+			if (p.right != null) p.right.parent = p;
+			// set q's left child to be p
+			q.left = p;
+			p.parent = q;
+			UpdateAugmentedData(p);
+			UpdateAugmentedData(q);
+		}
+		
+		void RotateRight(TextSegment p)
+		{
+			// let q be p's left child
+			TextSegment q = p.left;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's left child to be q's right child
+			p.left = q.right;
+			if (p.left != null) p.left.parent = p;
+			// set q's right child to be p
+			q.right = p;
+			p.parent = q;
+			UpdateAugmentedData(p);
+			UpdateAugmentedData(q);
+		}
+		
+		static TextSegment Sibling(TextSegment node)
+		{
+			if (node == node.parent.left)
+				return node.parent.right;
+			else
+				return node.parent.left;
+		}
+		
+		static TextSegment Sibling(TextSegment node, TextSegment parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (node == parentNode.left)
+				return parentNode.right;
+			else
+				return parentNode.left;
+		}
+		
+		static bool GetColor(TextSegment node)
+		{
+			return node != null ? node.color : BLACK;
+		}
+		#endregion
+		
+		#region ICollection<T> implementation
+		/// <summary>
+		/// Gets the number of segments in the tree.
+		/// </summary>
+		public int Count {
+			get { return count; }
+		}
+		
+		bool ICollection<T>.IsReadOnly {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether this tree contains the specified item.
+		/// </summary>
+		public bool Contains(T item)
+		{
+			return item != null && item.ownerTree == this;
+		}
+		
+		/// <summary>
+		/// Copies all segments in this SegmentTree to the specified array.
+		/// </summary>
+		public void CopyTo(T[] array, int arrayIndex)
+		{
+			if (array == null)
+				throw new ArgumentNullException("array");
+			if (array.Length < this.Count)
+				throw new ArgumentException("The array is too small", "array");
+			if (arrayIndex < 0 || arrayIndex + count > array.Length)
+				throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "Value must be between 0 and " + (array.Length - count));
+			foreach (T s in this) {
+				array[arrayIndex++] = s;
+			}
+		}
+		
+		/// <summary>
+		/// Gets an enumerator to enumerate the segments.
+		/// </summary>
+		public IEnumerator<T> GetEnumerator()
+		{
+			if (root != null) {
+				TextSegment current = root.LeftMost;
+				while (current != null) {
+					yield return (T)current;
+					// TODO: check if collection was modified during enumeration
+					current = current.Successor;
+				}
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.GetEnumerator();
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSourceVersionProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSourceVersionProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextSourceVersionProvider.cs	(revision 11807)
@@ -0,0 +1,136 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	#if !NREFACTORY
+	/// <summary>
+	/// Provides ITextSourceVersion instances.
+	/// </summary>
+	public class TextSourceVersionProvider
+	{
+		Version currentVersion;
+		
+		/// <summary>
+		/// Creates a new TextSourceVersionProvider instance.
+		/// </summary>
+		public TextSourceVersionProvider()
+		{
+			this.currentVersion = new Version(this);
+		}
+		
+		/// <summary>
+		/// Gets the current version.
+		/// </summary>
+		public ITextSourceVersion CurrentVersion {
+			get { return currentVersion; }
+		}
+		
+		/// <summary>
+		/// Replaces the current version with a new version.
+		/// </summary>
+		/// <param name="change">Change from current version to new version</param>
+		public void AppendChange(TextChangeEventArgs change)
+		{
+			if (change == null)
+				throw new ArgumentNullException("change");
+			currentVersion.change = change;
+			currentVersion.next = new Version(currentVersion);
+			currentVersion = currentVersion.next;
+		}
+		
+		[DebuggerDisplay("Version #{id}")]
+		sealed class Version : ITextSourceVersion
+		{
+			// Reference back to the provider.
+			// Used to determine if two checkpoints belong to the same document.
+			readonly TextSourceVersionProvider provider;
+			// ID used for CompareAge()
+			readonly int id;
+			
+			// the change from this version to the next version
+			internal TextChangeEventArgs change;
+			internal Version next;
+			
+			internal Version(TextSourceVersionProvider provider)
+			{
+				this.provider = provider;
+			}
+			
+			internal Version(Version prev)
+			{
+				this.provider = prev.provider;
+				this.id = unchecked( prev.id + 1 );
+			}
+			
+			public bool BelongsToSameDocumentAs(ITextSourceVersion other)
+			{
+				Version o = other as Version;
+				return o != null && provider == o.provider;
+			}
+			
+			public int CompareAge(ITextSourceVersion other)
+			{
+				if (other == null)
+					throw new ArgumentNullException("other");
+				Version o = other as Version;
+				if (o == null || provider != o.provider)
+					throw new ArgumentException("Versions do not belong to the same document.");
+				// We will allow overflows, but assume that the maximum distance between checkpoints is 2^31-1.
+				// This is guaranteed on x86 because so many checkpoints don't fit into memory.
+				return Math.Sign(unchecked( this.id - o.id ));
+			}
+			
+			public IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other)
+			{
+				int result = CompareAge(other);
+				Version o = (Version)other;
+				if (result < 0)
+					return GetForwardChanges(o);
+				else if (result > 0)
+					return o.GetForwardChanges(this).Reverse().Select(change => change.Invert());
+				else
+					return Empty<TextChangeEventArgs>.Array;
+			}
+			
+			IEnumerable<TextChangeEventArgs> GetForwardChanges(Version other)
+			{
+				// Return changes from this(inclusive) to other(exclusive).
+				for (Version node = this; node != other; node = node.next) {
+					yield return node.change;
+				}
+			}
+			
+			public int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement)
+			{
+				int offset = oldOffset;
+				foreach (var e in GetChangesTo(other)) {
+					offset = e.GetNewOffset(offset, movement);
+				}
+				return offset;
+			}
+		}
+	}
+	#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextUtilities.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextUtilities.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/TextUtilities.cs	(revision 11807)
@@ -0,0 +1,422 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.Windows.Documents;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Specifies the mode for getting the next caret position.
+	/// </summary>
+	public enum CaretPositioningMode
+	{
+		/// <summary>
+		/// Normal positioning (stop after every grapheme)
+		/// </summary>
+		Normal,
+		/// <summary>
+		/// Stop only on word borders.
+		/// </summary>
+		WordBorder,
+		/// <summary>
+		/// Stop only at the beginning of words. This is used for Ctrl+Left/Ctrl+Right.
+		/// </summary>
+		WordStart,
+		/// <summary>
+		/// Stop only at the beginning of words, and anywhere in the middle of symbols.
+		/// </summary>
+		WordStartOrSymbol,
+		/// <summary>
+		/// Stop only on word borders, and anywhere in the middle of symbols.
+		/// </summary>
+		WordBorderOrSymbol,
+		/// <summary>
+		/// Stop between every Unicode codepoint, even within the same grapheme.
+		/// This is used to implement deleting the previous grapheme when Backspace is pressed.
+		/// </summary>
+		EveryCodepoint
+	}
+	
+	/// <summary>
+	/// Static helper methods for working with text.
+	/// </summary>
+	public static partial class TextUtilities
+	{
+		#region GetControlCharacterName
+		// the names of the first 32 ASCII characters = Unicode C0 block
+		static readonly string[] c0Table = {
+			"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT",
+			"LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3",
+			"DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS",
+			"RS", "US"
+		};
+		
+		// DEL (ASCII 127) and
+		// the names of the control characters in the C1 block (Unicode 128 to 159)
+		static readonly string[] delAndC1Table = {
+			"DEL",
+			"PAD", "HOP", "BPH", "NBH", "IND", "NEL", "SSA", "ESA", "HTS", "HTJ",
+			"VTS", "PLD", "PLU", "RI", "SS2", "SS3", "DCS", "PU1", "PU2", "STS",
+			"CCH", "MW", "SPA", "EPA", "SOS", "SGCI", "SCI", "CSI", "ST", "OSC",
+			"PM", "APC"
+		};
+		
+		/// <summary>
+		/// Gets the name of the control character.
+		/// For unknown characters, the unicode codepoint is returned as 4-digit hexadecimal value.
+		/// </summary>
+		public static string GetControlCharacterName(char controlCharacter)
+		{
+			int num = (int)controlCharacter;
+			if (num < c0Table.Length)
+				return c0Table[num];
+			else if (num >= 127 && num <= 159)
+				return delAndC1Table[num - 127];
+			else
+				return num.ToString("x4", CultureInfo.InvariantCulture);
+		}
+		#endregion
+		
+		#region GetWhitespace
+		/// <summary>
+		/// Gets all whitespace (' ' and '\t', but no newlines) after offset.
+		/// </summary>
+		/// <param name="textSource">The text source.</param>
+		/// <param name="offset">The offset where the whitespace starts.</param>
+		/// <returns>The segment containing the whitespace.</returns>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		public static ISegment GetWhitespaceAfter(ITextSource textSource, int offset)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			int pos;
+			for (pos = offset; pos < textSource.TextLength; pos++) {
+				char c = textSource.GetCharAt(pos);
+				if (c != ' ' && c != '\t')
+					break;
+			}
+			return new SimpleSegment(offset, pos - offset);
+		}
+		
+		/// <summary>
+		/// Gets all whitespace (' ' and '\t', but no newlines) before offset.
+		/// </summary>
+		/// <param name="textSource">The text source.</param>
+		/// <param name="offset">The offset where the whitespace ends.</param>
+		/// <returns>The segment containing the whitespace.</returns>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		public static ISegment GetWhitespaceBefore(ITextSource textSource, int offset)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			int pos;
+			for (pos = offset - 1; pos >= 0; pos--) {
+				char c = textSource.GetCharAt(pos);
+				if (c != ' ' && c != '\t')
+					break;
+			}
+			pos++; // go back the one character that isn't whitespace
+			return new SimpleSegment(pos, offset - pos);
+		}
+		
+		/// <summary>
+		/// Gets the leading whitespace segment on the document line.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
+		                                                 Justification = "Parameter cannot be ITextSource because it must belong to the DocumentLine")]
+		public static ISegment GetLeadingWhitespace(TextDocument document, DocumentLine documentLine)
+		{
+			if (documentLine == null)
+				throw new ArgumentNullException("documentLine");
+			return GetWhitespaceAfter(document, documentLine.Offset);
+		}
+		
+		/// <summary>
+		/// Gets the trailing whitespace segment on the document line.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters",
+		                                                 Justification = "Parameter cannot be ITextSource because it must belong to the DocumentLine")]
+		public static ISegment GetTrailingWhitespace(TextDocument document, DocumentLine documentLine)
+		{
+			if (documentLine == null)
+				throw new ArgumentNullException("documentLine");
+			ISegment segment = GetWhitespaceBefore(document, documentLine.EndOffset);
+			// If the whole line consists of whitespace, we consider all of it as leading whitespace,
+			// so return an empty segment as trailing whitespace.
+			if (segment.Offset == documentLine.Offset)
+				return new SimpleSegment(documentLine.EndOffset, 0);
+			else
+				return segment;
+		}
+		#endregion
+		
+		#region GetSingleIndentationSegment
+		/// <summary>
+		/// Gets a single indentation segment starting at <paramref name="offset"/> - at most one tab
+		/// or <paramref name="indentationSize"/> spaces.
+		/// </summary>
+		/// <param name="textSource">The text source.</param>
+		/// <param name="offset">The offset where the indentation segment starts.</param>
+		/// <param name="indentationSize">The size of an indentation unit. See <see cref="TextEditorOptions.IndentationSize"/>.</param>
+		/// <returns>The indentation segment.
+		/// If there is no indentation character at the specified <paramref name="offset"/>,
+		/// an empty segment is returned.</returns>
+		public static ISegment GetSingleIndentationSegment(ITextSource textSource, int offset, int indentationSize)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			int pos = offset;
+			while (pos < textSource.TextLength) {
+				char c = textSource.GetCharAt(pos);
+				if (c == '\t') {
+					if (pos == offset)
+						return new SimpleSegment(offset, 1);
+					else
+						break;
+				} else if (c == ' ') {
+					if (pos - offset >= indentationSize)
+						break;
+				} else {
+					break;
+				}
+				// continue only if c==' ' and (pos-offset)<tabSize
+				pos++;
+			}
+			return new SimpleSegment(offset, pos - offset);
+		}
+		#endregion
+		
+		#region GetCharacterClass
+		/// <summary>
+		/// Gets whether the character is whitespace, part of an identifier, or line terminator.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "c")]
+		public static CharacterClass GetCharacterClass(char c)
+		{
+			if (c == '\r' || c == '\n')
+				return CharacterClass.LineTerminator;
+			if (c == '_')
+				return CharacterClass.IdentifierPart;
+			return GetCharacterClass(char.GetUnicodeCategory(c));
+		}
+		
+		static CharacterClass GetCharacterClass(char highSurrogate, char lowSurrogate)
+		{
+			if (char.IsSurrogatePair(highSurrogate, lowSurrogate)) {
+				return GetCharacterClass(char.GetUnicodeCategory(highSurrogate.ToString() + lowSurrogate.ToString(), 0));
+			} else {
+				// malformed surrogate pair
+				return CharacterClass.Other;
+			}
+		}
+		
+		static CharacterClass GetCharacterClass(UnicodeCategory c)
+		{
+			switch (c) {
+				case UnicodeCategory.SpaceSeparator:
+				case UnicodeCategory.LineSeparator:
+				case UnicodeCategory.ParagraphSeparator:
+				case UnicodeCategory.Control:
+					return CharacterClass.Whitespace;
+				case UnicodeCategory.UppercaseLetter:
+				case UnicodeCategory.LowercaseLetter:
+				case UnicodeCategory.TitlecaseLetter:
+				case UnicodeCategory.ModifierLetter:
+				case UnicodeCategory.OtherLetter:
+				case UnicodeCategory.DecimalDigitNumber:
+					return CharacterClass.IdentifierPart;
+				case UnicodeCategory.NonSpacingMark:
+				case UnicodeCategory.SpacingCombiningMark:
+				case UnicodeCategory.EnclosingMark:
+					return CharacterClass.CombiningMark;
+				default:
+					return CharacterClass.Other;
+			}
+		}
+		#endregion
+		
+		#region GetNextCaretPosition
+		/// <summary>
+		/// Gets the next caret position.
+		/// </summary>
+		/// <param name="textSource">The text source.</param>
+		/// <param name="offset">The start offset inside the text source.</param>
+		/// <param name="direction">The search direction (forwards or backwards).</param>
+		/// <param name="mode">The mode for caret positioning.</param>
+		/// <returns>The offset of the next caret position, or -1 if there is no further caret position
+		/// in the text source.</returns>
+		/// <remarks>
+		/// This method is NOT equivalent to the actual caret movement when using VisualLine.GetNextCaretPosition.
+		/// In real caret movement, there are additional caret stops at line starts and ends. This method
+		/// treats linefeeds as simple whitespace.
+		/// </remarks>
+		public static int GetNextCaretPosition(ITextSource textSource, int offset, LogicalDirection direction, CaretPositioningMode mode)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			switch (mode) {
+				case CaretPositioningMode.Normal:
+				case CaretPositioningMode.EveryCodepoint:
+				case CaretPositioningMode.WordBorder:
+				case CaretPositioningMode.WordBorderOrSymbol:
+				case CaretPositioningMode.WordStart:
+				case CaretPositioningMode.WordStartOrSymbol:
+					break; // OK
+				default:
+					throw new ArgumentException("Unsupported CaretPositioningMode: " + mode, "mode");
+			}
+			if (direction != LogicalDirection.Backward
+			    && direction != LogicalDirection.Forward)
+			{
+				throw new ArgumentException("Invalid LogicalDirection: " + direction, "direction");
+			}
+			int textLength = textSource.TextLength;
+			if (textLength <= 0) {
+				// empty document? has a normal caret position at 0, though no word borders
+				if (IsNormal(mode)) {
+					if (offset > 0 && direction == LogicalDirection.Backward) return 0;
+					if (offset < 0 && direction == LogicalDirection.Forward) return 0;
+				}
+				return -1;
+			}
+			while (true) {
+				int nextPos = (direction == LogicalDirection.Backward) ? offset - 1 : offset + 1;
+				
+				// return -1 if there is no further caret position in the text source
+				// we also need this to handle offset values outside the valid range
+				if (nextPos < 0 || nextPos > textLength)
+					return -1;
+				
+				// check if we've run against the textSource borders.
+				// a 'textSource' usually isn't the whole document, but a single VisualLineElement.
+				if (nextPos == 0) {
+					// at the document start, there's only a word border
+					// if the first character is not whitespace
+					if (IsNormal(mode) || !char.IsWhiteSpace(textSource.GetCharAt(0)))
+						return nextPos;
+				} else if (nextPos == textLength) {
+					// at the document end, there's never a word start
+					if (mode != CaretPositioningMode.WordStart && mode != CaretPositioningMode.WordStartOrSymbol) {
+						// at the document end, there's only a word border
+						// if the last character is not whitespace
+						if (IsNormal(mode) || !char.IsWhiteSpace(textSource.GetCharAt(textLength - 1)))
+							return nextPos;
+					}
+				} else {
+					char charBefore = textSource.GetCharAt(nextPos - 1);
+					char charAfter = textSource.GetCharAt(nextPos);
+					// Don't stop in the middle of a surrogate pair
+					if (!char.IsSurrogatePair(charBefore, charAfter)) {
+						CharacterClass classBefore = GetCharacterClass(charBefore);
+						CharacterClass classAfter = GetCharacterClass(charAfter);
+						// get correct class for characters outside BMP:
+						if (char.IsLowSurrogate(charBefore) && nextPos >= 2) {
+							classBefore = GetCharacterClass(textSource.GetCharAt(nextPos - 2), charBefore);
+						}
+						if (char.IsHighSurrogate(charAfter) && nextPos + 1 < textLength) {
+							classAfter = GetCharacterClass(charAfter, textSource.GetCharAt(nextPos + 1));
+						}
+						if (StopBetweenCharacters(mode, classBefore, classAfter)) {
+							return nextPos;
+						}
+					}
+				}
+				// we'll have to continue searching...
+				offset = nextPos;
+			}
+		}
+		
+		static bool IsNormal(CaretPositioningMode mode)
+		{
+			return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
+		}
+		
+		static bool StopBetweenCharacters(CaretPositioningMode mode, CharacterClass charBefore, CharacterClass charAfter)
+		{
+			if (mode == CaretPositioningMode.EveryCodepoint)
+				return true;
+			// Don't stop in the middle of a grapheme
+			if (charAfter == CharacterClass.CombiningMark)
+				return false;
+			// Stop after every grapheme in normal mode
+			if (mode == CaretPositioningMode.Normal)
+				return true;
+			if (charBefore == charAfter) {
+				if (charBefore == CharacterClass.Other &&
+				    (mode == CaretPositioningMode.WordBorderOrSymbol || mode == CaretPositioningMode.WordStartOrSymbol))
+				{
+					// With the "OrSymbol" modes, there's a word border and start between any two unknown characters
+					return true;
+				}
+			} else {
+				// this looks like a possible border
+				
+				// if we're looking for word starts, check that this is a word start (and not a word end)
+				// if we're just checking for word borders, accept unconditionally
+				if (!((mode == CaretPositioningMode.WordStart || mode == CaretPositioningMode.WordStartOrSymbol)
+				      && (charAfter == CharacterClass.Whitespace || charAfter == CharacterClass.LineTerminator)))
+				{
+					return true;
+				}
+			}
+			return false;
+		}
+		#endregion
+	}
+	
+	/// <summary>
+	/// Classifies a character as whitespace, line terminator, part of an identifier, or other.
+	/// </summary>
+	public enum CharacterClass
+	{
+		/// <summary>
+		/// The character is not whitespace, line terminator or part of an identifier.
+		/// </summary>
+		Other,
+		/// <summary>
+		/// The character is whitespace (but not line terminator).
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "WPF uses 'Whitespace'")]
+		Whitespace,
+		/// <summary>
+		/// The character can be part of an identifier (Letter, digit or underscore).
+		/// </summary>
+		IdentifierPart,
+		/// <summary>
+		/// The character is line terminator (\r or \n).
+		/// </summary>
+		LineTerminator,
+		/// <summary>
+		/// The character is a unicode combining mark that modifies the previous character.
+		/// Corresponds to the Unicode designations "Mn", "Mc" and "Me".
+		/// </summary>
+		CombiningMark
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/UndoOperationGroup.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/UndoOperationGroup.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/UndoOperationGroup.cs	(revision 11807)
@@ -0,0 +1,76 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// This class stacks the last x operations from the undostack and makes
+	/// one undo/redo operation from it.
+	/// </summary>
+	sealed class UndoOperationGroup : IUndoableOperationWithContext
+	{
+		IUndoableOperation[] undolist;
+		
+		public UndoOperationGroup(Deque<IUndoableOperation> stack, int numops)
+		{
+			if (stack == null)  {
+				throw new ArgumentNullException("stack");
+			}
+			
+			Debug.Assert(numops > 0 , "UndoOperationGroup : numops should be > 0");
+			Debug.Assert(numops <= stack.Count);
+			
+			undolist = new IUndoableOperation[numops];
+			for (int i = 0; i < numops; ++i) {
+				undolist[i] = stack.PopBack();
+			}
+		}
+		
+		public void Undo()
+		{
+			for (int i = 0; i < undolist.Length; ++i) {
+				undolist[i].Undo();
+			}
+		}
+		
+		public void Undo(UndoStack stack)
+		{
+			for (int i = 0; i < undolist.Length; ++i) {
+				stack.RunUndo(undolist[i]);
+			}
+		}
+		
+		public void Redo()
+		{
+			for (int i = undolist.Length - 1; i >= 0; --i) {
+				undolist[i].Redo();
+			}
+		}
+		
+		public void Redo(UndoStack stack)
+		{
+			for (int i = undolist.Length - 1; i >= 0; --i) {
+				stack.RunRedo(undolist[i]);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/UndoStack.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/UndoStack.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/UndoStack.cs	(revision 11807)
@@ -0,0 +1,458 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Undo stack implementation.
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
+	public sealed class UndoStack : INotifyPropertyChanged
+	{
+		/// undo stack is listening for changes
+		internal const int StateListen = 0;
+		/// undo stack is reverting/repeating a set of changes
+		internal const int StatePlayback = 1;
+		// undo stack is reverting/repeating a set of changes and modifies the document to do this
+		internal const int StatePlaybackModifyDocument = 2;
+		/// state is used for checking that noone but the UndoStack performs changes
+		/// during Undo events
+		internal int state = StateListen;
+		
+		Deque<IUndoableOperation> undostack = new Deque<IUndoableOperation>();
+		Deque<IUndoableOperation> redostack = new Deque<IUndoableOperation>();
+		int sizeLimit = int.MaxValue;
+		
+		int undoGroupDepth;
+		int actionCountInUndoGroup;
+		int optionalActionCount;
+		object lastGroupDescriptor;
+		bool allowContinue;
+		
+		#region IsOriginalFile implementation
+		// implements feature request SD2-784 - File still considered dirty after undoing all changes
+		
+		/// <summary>
+		/// Number of times undo must be executed until the original state is reached.
+		/// Negative: number of times redo must be executed until the original state is reached.
+		/// Special case: int.MinValue == original state is unreachable
+		/// </summary>
+		int elementsOnUndoUntilOriginalFile;
+		
+		bool isOriginalFile = true;
+		
+		/// <summary>
+		/// Gets whether the document is currently in its original state (no modifications).
+		/// </summary>
+		public bool IsOriginalFile {
+			get { return isOriginalFile; }
+		}
+		
+		void RecalcIsOriginalFile()
+		{
+			bool newIsOriginalFile = (elementsOnUndoUntilOriginalFile == 0);
+			if (newIsOriginalFile != isOriginalFile) {
+				isOriginalFile = newIsOriginalFile;
+				NotifyPropertyChanged("IsOriginalFile");
+			}
+		}
+		
+		/// <summary>
+		/// Marks the current state as original. Discards any previous "original" markers.
+		/// </summary>
+		public void MarkAsOriginalFile()
+		{
+			elementsOnUndoUntilOriginalFile = 0;
+			RecalcIsOriginalFile();
+		}
+		
+		/// <summary>
+		/// Discards the current "original" marker.
+		/// </summary>
+		public void DiscardOriginalFileMarker()
+		{
+			elementsOnUndoUntilOriginalFile = int.MinValue;
+			RecalcIsOriginalFile();
+		}
+		
+		void FileModified(int newElementsOnUndoStack)
+		{
+			if (elementsOnUndoUntilOriginalFile == int.MinValue)
+				return;
+			
+			elementsOnUndoUntilOriginalFile += newElementsOnUndoStack;
+			if (elementsOnUndoUntilOriginalFile > undostack.Count)
+				elementsOnUndoUntilOriginalFile = int.MinValue;
+			
+			// don't call RecalcIsOriginalFile(): wait until end of undo group
+		}
+		#endregion
+		
+		/// <summary>
+		/// Gets if the undo stack currently accepts changes.
+		/// Is false while an undo action is running.
+		/// </summary>
+		public bool AcceptChanges {
+			get { return state == StateListen; }
+		}
+		
+		/// <summary>
+		/// Gets if there are actions on the undo stack.
+		/// Use the PropertyChanged event to listen to changes of this property.
+		/// </summary>
+		public bool CanUndo {
+			get { return undostack.Count > 0; }
+		}
+		
+		/// <summary>
+		/// Gets if there are actions on the redo stack.
+		/// Use the PropertyChanged event to listen to changes of this property.
+		/// </summary>
+		public bool CanRedo {
+			get { return redostack.Count > 0; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the limit on the number of items on the undo stack.
+		/// </summary>
+		/// <remarks>The size limit is enforced only on the number of stored top-level undo groups.
+		/// Elements within undo groups do not count towards the size limit.</remarks>
+		public int SizeLimit {
+			get { return sizeLimit; }
+			set {
+				if (value < 0)
+					ThrowUtil.CheckNotNegative(value, "value");
+				if (sizeLimit != value) {
+					sizeLimit = value;
+					NotifyPropertyChanged("SizeLimit");
+					if (undoGroupDepth == 0)
+						EnforceSizeLimit();
+				}
+			}
+		}
+		
+		void EnforceSizeLimit()
+		{
+			Debug.Assert(undoGroupDepth == 0);
+			while (undostack.Count > sizeLimit)
+				undostack.PopFront();
+			while (redostack.Count > sizeLimit)
+				redostack.PopFront();
+		}
+		
+		/// <summary>
+		/// If an undo group is open, gets the group descriptor of the current top-level
+		/// undo group.
+		/// If no undo group is open, gets the group descriptor from the previous undo group.
+		/// </summary>
+		/// <remarks>The group descriptor can be used to join adjacent undo groups:
+		/// use a group descriptor to mark your changes, and on the second action,
+		/// compare LastGroupDescriptor and use <see cref="StartContinuedUndoGroup"/> if you
+		/// want to join the undo groups.</remarks>
+		public object LastGroupDescriptor {
+			get { return lastGroupDescriptor; }
+		}
+		
+		/// <summary>
+		/// Starts grouping changes.
+		/// Maintains a counter so that nested calls are possible.
+		/// </summary>
+		public void StartUndoGroup()
+		{
+			StartUndoGroup(null);
+		}
+		
+		/// <summary>
+		/// Starts grouping changes.
+		/// Maintains a counter so that nested calls are possible.
+		/// </summary>
+		/// <param name="groupDescriptor">An object that is stored with the undo group.
+		/// If this is not a top-level undo group, the parameter is ignored.</param>
+		public void StartUndoGroup(object groupDescriptor)
+		{
+			if (undoGroupDepth == 0) {
+				actionCountInUndoGroup = 0;
+				optionalActionCount = 0;
+				lastGroupDescriptor = groupDescriptor;
+			}
+			undoGroupDepth++;
+			//Util.LoggingService.Debug("Open undo group (new depth=" + undoGroupDepth + ")");
+		}
+		
+		/// <summary>
+		/// Starts grouping changes, continuing with the previously closed undo group if possible.
+		/// Maintains a counter so that nested calls are possible.
+		/// If the call to StartContinuedUndoGroup is a nested call, it behaves exactly
+		/// as <see cref="StartUndoGroup()"/>, only top-level calls can continue existing undo groups.
+		/// </summary>
+		/// <param name="groupDescriptor">An object that is stored with the undo group.
+		/// If this is not a top-level undo group, the parameter is ignored.</param>
+		public void StartContinuedUndoGroup(object groupDescriptor = null)
+		{
+			if (undoGroupDepth == 0) {
+				actionCountInUndoGroup = (allowContinue && undostack.Count > 0) ? 1 : 0;
+				optionalActionCount = 0;
+				lastGroupDescriptor = groupDescriptor;
+			}
+			undoGroupDepth++;
+			//Util.LoggingService.Debug("Continue undo group (new depth=" + undoGroupDepth + ")");
+		}
+		
+		/// <summary>
+		/// Stops grouping changes.
+		/// </summary>
+		public void EndUndoGroup()
+		{
+			if (undoGroupDepth == 0) throw new InvalidOperationException("There are no open undo groups");
+			undoGroupDepth--;
+			//Util.LoggingService.Debug("Close undo group (new depth=" + undoGroupDepth + ")");
+			if (undoGroupDepth == 0) {
+				Debug.Assert(state == StateListen || actionCountInUndoGroup == 0);
+				allowContinue = true;
+				if (actionCountInUndoGroup == optionalActionCount) {
+					// only optional actions: don't store them
+					for (int i = 0; i < optionalActionCount; i++) {
+						undostack.PopBack();
+					}
+					allowContinue = false;
+				} else if (actionCountInUndoGroup > 1) {
+					// combine all actions within the group into a single grouped action
+					undostack.PushBack(new UndoOperationGroup(undostack, actionCountInUndoGroup));
+					FileModified(-actionCountInUndoGroup + 1 + optionalActionCount);
+				}
+				//if (state == StateListen) {
+				EnforceSizeLimit();
+				RecalcIsOriginalFile(); // can raise event
+				//}
+			}
+		}
+		
+		/// <summary>
+		/// Throws an InvalidOperationException if an undo group is current open.
+		/// </summary>
+		void ThrowIfUndoGroupOpen()
+		{
+			if (undoGroupDepth != 0) {
+				undoGroupDepth = 0;
+				throw new InvalidOperationException("No undo group should be open at this point");
+			}
+			if (state != StateListen) {
+				throw new InvalidOperationException("This method cannot be called while an undo operation is being performed");
+			}
+		}
+		
+		List<TextDocument> affectedDocuments;
+		
+		internal void RegisterAffectedDocument(TextDocument document)
+		{
+			if (affectedDocuments == null)
+				affectedDocuments = new List<TextDocument>();
+			if (!affectedDocuments.Contains(document)) {
+				affectedDocuments.Add(document);
+				document.BeginUpdate();
+			}
+		}
+		
+		void CallEndUpdateOnAffectedDocuments()
+		{
+			if (affectedDocuments != null) {
+				foreach (TextDocument doc in affectedDocuments) {
+					doc.EndUpdate();
+				}
+				affectedDocuments = null;
+			}
+		}
+		
+		/// <summary>
+		/// Call this method to undo the last operation on the stack
+		/// </summary>
+		public void Undo()
+		{
+			ThrowIfUndoGroupOpen();
+			if (undostack.Count > 0) {
+				// disallow continuing undo groups after undo operation
+				lastGroupDescriptor = null; allowContinue = false;
+				// fetch operation to undo and move it to redo stack
+				IUndoableOperation uedit = undostack.PopBack();
+				redostack.PushBack(uedit);
+				state = StatePlayback;
+				try {
+					RunUndo(uedit);
+				} finally {
+					state = StateListen;
+					FileModified(-1);
+					CallEndUpdateOnAffectedDocuments();
+				}
+				RecalcIsOriginalFile();
+				if (undostack.Count == 0)
+					NotifyPropertyChanged("CanUndo");
+				if (redostack.Count == 1)
+					NotifyPropertyChanged("CanRedo");
+			}
+		}
+		
+		internal void RunUndo(IUndoableOperation op)
+		{
+			IUndoableOperationWithContext opWithCtx = op as IUndoableOperationWithContext;
+			if (opWithCtx != null)
+				opWithCtx.Undo(this);
+			else
+				op.Undo();
+		}
+		
+		/// <summary>
+		/// Call this method to redo the last undone operation
+		/// </summary>
+		public void Redo()
+		{
+			ThrowIfUndoGroupOpen();
+			if (redostack.Count > 0) {
+				lastGroupDescriptor = null; allowContinue = false;
+				IUndoableOperation uedit = redostack.PopBack();
+				undostack.PushBack(uedit);
+				state = StatePlayback;
+				try {
+					RunRedo(uedit);
+				} finally {
+					state = StateListen;
+					FileModified(1);
+					CallEndUpdateOnAffectedDocuments();
+				}
+				RecalcIsOriginalFile();
+				if (redostack.Count == 0)
+					NotifyPropertyChanged("CanRedo");
+				if (undostack.Count == 1)
+					NotifyPropertyChanged("CanUndo");
+			}
+		}
+		
+		internal void RunRedo(IUndoableOperation op)
+		{
+			IUndoableOperationWithContext opWithCtx = op as IUndoableOperationWithContext;
+			if (opWithCtx != null)
+				opWithCtx.Redo(this);
+			else
+				op.Redo();
+		}
+		
+		/// <summary>
+		/// Call this method to push an UndoableOperation on the undostack.
+		/// The redostack will be cleared if you use this method.
+		/// </summary>
+		public void Push(IUndoableOperation operation)
+		{
+			Push(operation, false);
+		}
+		
+		/// <summary>
+		/// Call this method to push an UndoableOperation on the undostack.
+		/// However, the operation will be only stored if the undo group contains a
+		/// non-optional operation.
+		/// Use this method to store the caret position/selection on the undo stack to
+		/// prevent having only actions that affect only the caret and not the document.
+		/// </summary>
+		public void PushOptional(IUndoableOperation operation)
+		{
+			if (undoGroupDepth == 0)
+				throw new InvalidOperationException("Cannot use PushOptional outside of undo group");
+			Push(operation, true);
+		}
+		
+		void Push(IUndoableOperation operation, bool isOptional)
+		{
+			if (operation == null) {
+				throw new ArgumentNullException("operation");
+			}
+			
+			if (state == StateListen && sizeLimit > 0) {
+				bool wasEmpty = undostack.Count == 0;
+				
+				bool needsUndoGroup = undoGroupDepth == 0;
+				if (needsUndoGroup) StartUndoGroup();
+				undostack.PushBack(operation);
+				actionCountInUndoGroup++;
+				if (isOptional)
+					optionalActionCount++;
+				else
+					FileModified(1);
+				if (needsUndoGroup) EndUndoGroup();
+				if (wasEmpty)
+					NotifyPropertyChanged("CanUndo");
+				ClearRedoStack();
+			}
+		}
+		
+		/// <summary>
+		/// Call this method, if you want to clear the redo stack
+		/// </summary>
+		public void ClearRedoStack()
+		{
+			if (redostack.Count != 0) {
+				redostack.Clear();
+				NotifyPropertyChanged("CanRedo");
+				// if the "original file" marker is on the redo stack: remove it
+				if (elementsOnUndoUntilOriginalFile < 0)
+					elementsOnUndoUntilOriginalFile = int.MinValue;
+			}
+		}
+		
+		/// <summary>
+		/// Clears both the undo and redo stack.
+		/// </summary>
+		public void ClearAll()
+		{
+			ThrowIfUndoGroupOpen();
+			actionCountInUndoGroup = 0;
+			optionalActionCount = 0;
+			if (undostack.Count != 0) {
+				lastGroupDescriptor = null;
+				allowContinue = false;
+				undostack.Clear();
+				NotifyPropertyChanged("CanUndo");
+			}
+			ClearRedoStack();
+		}
+		
+		internal void Push(TextDocument document, DocumentChangeEventArgs e)
+		{
+			if (state == StatePlayback)
+				throw new InvalidOperationException("Document changes during undo/redo operations are not allowed.");
+			if (state == StatePlaybackModifyDocument)
+				state = StatePlayback; // allow only 1 change per expected modification
+			else
+				Push(new DocumentChangeOperation(document, e));
+		}
+		
+		/// <summary>
+		/// Is raised when a property (CanUndo, CanRedo) changed.
+		/// </summary>
+		public event PropertyChangedEventHandler PropertyChanged;
+		
+		void NotifyPropertyChanged(string propertyName)
+		{
+			if (PropertyChanged != null)
+				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/WeakLineTracker.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/WeakLineTracker.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Document/WeakLineTracker.cs	(revision 11807)
@@ -0,0 +1,109 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Document
+{
+	/// <summary>
+	/// Allows registering a line tracker on a TextDocument using a weak reference from the document to the line tracker.
+	/// </summary>
+	public sealed class WeakLineTracker : ILineTracker
+	{
+		TextDocument textDocument;
+		WeakReference targetObject;
+		
+		private WeakLineTracker(TextDocument textDocument, ILineTracker targetTracker)
+		{
+			this.textDocument = textDocument;
+			this.targetObject = new WeakReference(targetTracker);
+		}
+		
+		/// <summary>
+		/// Registers the <paramref name="targetTracker"/> as line tracker for the <paramref name="textDocument"/>.
+		/// A weak reference to the target tracker will be used, and the WeakLineTracker will deregister itself
+		/// when the target tracker is garbage collected.
+		/// </summary>
+		public static WeakLineTracker Register(TextDocument textDocument, ILineTracker targetTracker)
+		{
+			if (textDocument == null)
+				throw new ArgumentNullException("textDocument");
+			if (targetTracker == null)
+				throw new ArgumentNullException("targetTracker");
+			WeakLineTracker wlt = new WeakLineTracker(textDocument, targetTracker);
+			textDocument.LineTrackers.Add(wlt);
+			return wlt;
+		}
+		
+		/// <summary>
+		/// Deregisters the weak line tracker.
+		/// </summary>
+		public void Deregister()
+		{
+			if (textDocument != null) {
+				textDocument.LineTrackers.Remove(this);
+				textDocument = null;
+			}
+		}
+		
+		void ILineTracker.BeforeRemoveLine(DocumentLine line)
+		{
+			ILineTracker targetTracker = targetObject.Target as ILineTracker;
+			if (targetTracker != null)
+				targetTracker.BeforeRemoveLine(line);
+			else
+				Deregister();
+		}
+		
+		void ILineTracker.SetLineLength(DocumentLine line, int newTotalLength)
+		{
+			ILineTracker targetTracker = targetObject.Target as ILineTracker;
+			if (targetTracker != null)
+				targetTracker.SetLineLength(line, newTotalLength);
+			else
+				Deregister();
+		}
+		
+		void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
+		{
+			ILineTracker targetTracker = targetObject.Target as ILineTracker;
+			if (targetTracker != null)
+				targetTracker.LineInserted(insertionPos, newLine);
+			else
+				Deregister();
+		}
+		
+		void ILineTracker.RebuildDocument()
+		{
+			ILineTracker targetTracker = targetObject.Target as ILineTracker;
+			if (targetTracker != null)
+				targetTracker.RebuildDocument();
+			else
+				Deregister();
+		}
+		
+		void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
+		{
+			ILineTracker targetTracker = targetObject.Target as ILineTracker;
+			if (targetTracker != null)
+				targetTracker.ChangeComplete(e);
+			else
+				Deregister();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/AbstractMargin.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/AbstractMargin.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/AbstractMargin.cs	(revision 11807)
@@ -0,0 +1,117 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Base class for margins.
+	/// Margins don't have to derive from this class, it just helps maintaining a reference to the TextView
+	/// and the TextDocument.
+	/// AbstractMargin derives from FrameworkElement, so if you don't want to handle visual children and rendering
+	/// on your own, choose another base class for your margin!
+	/// </summary>
+	public abstract class AbstractMargin : FrameworkElement, ITextViewConnect
+	{
+		/// <summary>
+		/// TextView property.
+		/// </summary>
+		public static readonly DependencyProperty TextViewProperty =
+			DependencyProperty.Register("TextView", typeof(TextView), typeof(AbstractMargin),
+			                            new FrameworkPropertyMetadata(OnTextViewChanged));
+		
+		/// <summary>
+		/// Gets/sets the text view for which line numbers are displayed.
+		/// </summary>
+		/// <remarks>Adding a margin to <see cref="TextArea.LeftMargins"/> will automatically set this property to the text area's TextView.</remarks>
+		public TextView TextView {
+			get { return (TextView)GetValue(TextViewProperty); }
+			set { SetValue(TextViewProperty, value); }
+		}
+		
+		static void OnTextViewChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			AbstractMargin margin = (AbstractMargin)dp;
+			margin.wasAutoAddedToTextView = false;
+			margin.OnTextViewChanged((TextView)e.OldValue, (TextView)e.NewValue);
+		}
+		
+		// automatically set/unset TextView property using ITextViewConnect
+		bool wasAutoAddedToTextView;
+		
+		void ITextViewConnect.AddToTextView(TextView textView)
+		{
+			if (this.TextView == null) {
+				this.TextView = textView;
+				wasAutoAddedToTextView = true;
+			} else if (this.TextView != textView) {
+				throw new InvalidOperationException("This margin belongs to a different TextView.");
+			}
+		}
+		
+		void ITextViewConnect.RemoveFromTextView(TextView textView)
+		{
+			if (wasAutoAddedToTextView && this.TextView == textView) {
+				this.TextView = null;
+				Debug.Assert(!wasAutoAddedToTextView); // setting this.TextView should have unset this flag
+			}
+		}
+		
+		TextDocument document;
+		
+		/// <summary>
+		/// Gets the document associated with the margin.
+		/// </summary>
+		public TextDocument Document {
+			get { return document; }
+		}
+		
+		/// <summary>
+		/// Called when the <see cref="TextView"/> is changing.
+		/// </summary>
+		protected virtual void OnTextViewChanged(TextView oldTextView, TextView newTextView)
+		{
+			if (oldTextView != null) {
+				oldTextView.DocumentChanged -= TextViewDocumentChanged;
+			}
+			if (newTextView != null) {
+				newTextView.DocumentChanged += TextViewDocumentChanged;
+			}
+			TextViewDocumentChanged(null, null);
+		}
+		
+		void TextViewDocumentChanged(object sender, EventArgs e)
+		{
+			OnDocumentChanged(document, TextView != null ? TextView.Document : null);
+		}
+		
+		/// <summary>
+		/// Called when the <see cref="Document"/> is changing.
+		/// </summary>
+		protected virtual void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
+		{
+			document = newDocument;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/Caret.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/Caret.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/Caret.cs	(revision 11807)
@@ -0,0 +1,538 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Helper class with caret-related methods.
+	/// </summary>
+	public sealed class Caret
+	{
+		readonly TextArea textArea;
+		readonly TextView textView;
+		readonly CaretLayer caretAdorner;
+		bool visible;
+		
+		internal Caret(TextArea textArea)
+		{
+			this.textArea = textArea;
+			this.textView = textArea.TextView;
+			position = new TextViewPosition(1, 1, 0);
+			
+			caretAdorner = new CaretLayer(textArea);
+			textView.InsertLayer(caretAdorner, KnownLayer.Caret, LayerInsertionPosition.Replace);
+			textView.VisualLinesChanged += TextView_VisualLinesChanged;
+			textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged;
+		}
+		
+		internal void UpdateIfVisible()
+		{
+			if (visible) {
+				Show();
+			}
+		}
+		
+		void TextView_VisualLinesChanged(object sender, EventArgs e)
+		{
+			if (visible) {
+				Show();
+			}
+			// required because the visual columns might have changed if the
+			// element generators did something differently than on the last run
+			// (e.g. a FoldingSection was collapsed)
+			InvalidateVisualColumn();
+		}
+		
+		void TextView_ScrollOffsetChanged(object sender, EventArgs e)
+		{
+			if (caretAdorner != null) {
+				caretAdorner.InvalidateVisual();
+			}
+		}
+		
+		double desiredXPos = double.NaN;
+		TextViewPosition position;
+		
+		/// <summary>
+		/// Gets/Sets the position of the caret.
+		/// Retrieving this property will validate the visual column (which can be expensive).
+		/// Use the <see cref="Location"/> property instead if you don't need the visual column.
+		/// </summary>
+		public TextViewPosition Position {
+			get {
+				ValidateVisualColumn();
+				return position;
+			}
+			set {
+				if (position != value) {
+					position = value;
+					
+					storedCaretOffset = -1;
+					
+					//Debug.WriteLine("Caret position changing to " + value);
+					
+					ValidatePosition();
+					InvalidateVisualColumn();
+					RaisePositionChanged();
+					Log("Caret position changed to " + value);
+					if (visible)
+						Show();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the caret position without validating it.
+		/// </summary>
+		internal TextViewPosition NonValidatedPosition {
+			get {
+				return position;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the location of the caret.
+		/// The getter of this property is faster than <see cref="Position"/> because it doesn't have
+		/// to validate the visual column.
+		/// </summary>
+		public TextLocation Location {
+			get {
+				return position.Location;
+			}
+			set {
+				this.Position = new TextViewPosition(value);
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the caret line.
+		/// </summary>
+		public int Line {
+			get { return position.Line; }
+			set {
+				this.Position = new TextViewPosition(value, position.Column);
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the caret column.
+		/// </summary>
+		public int Column {
+			get { return position.Column; }
+			set {
+				this.Position = new TextViewPosition(position.Line, value);
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the caret visual column.
+		/// </summary>
+		public int VisualColumn {
+			get {
+				ValidateVisualColumn();
+				return position.VisualColumn;
+			}
+			set {
+				this.Position = new TextViewPosition(position.Line, position.Column, value);
+			}
+		}
+		
+		bool isInVirtualSpace;
+		
+		/// <summary>
+		/// Gets whether the caret is in virtual space.
+		/// </summary>
+		public bool IsInVirtualSpace {
+			get {
+				ValidateVisualColumn();
+				return isInVirtualSpace;
+			}
+		}
+		
+		int storedCaretOffset;
+		
+		internal void OnDocumentChanging()
+		{
+			storedCaretOffset = this.Offset;
+			InvalidateVisualColumn();
+		}
+		
+		internal void OnDocumentChanged(DocumentChangeEventArgs e)
+		{
+			InvalidateVisualColumn();
+			if (storedCaretOffset >= 0) {
+				// If the caret is at the end of a selection, we don't expand the selection if something
+				// is inserted at the end. Thus we also need to keep the caret in front of the insertion.
+				AnchorMovementType caretMovementType;
+				if (!textArea.Selection.IsEmpty && storedCaretOffset == textArea.Selection.SurroundingSegment.EndOffset)
+					caretMovementType = AnchorMovementType.BeforeInsertion;
+				else
+					caretMovementType = AnchorMovementType.Default;
+				int newCaretOffset = e.GetNewOffset(storedCaretOffset, caretMovementType);
+				TextDocument document = textArea.Document;
+				if (document != null) {
+					// keep visual column
+					this.Position = new TextViewPosition(document.GetLocation(newCaretOffset), position.VisualColumn);
+				}
+			}
+			storedCaretOffset = -1;
+		}
+		
+		/// <summary>
+		/// Gets/Sets the caret offset.
+		/// Setting the caret offset has the side effect of setting the <see cref="DesiredXPos"/> to NaN.
+		/// </summary>
+		public int Offset {
+			get {
+				TextDocument document = textArea.Document;
+				if (document == null) {
+					return 0;
+				} else {
+					return document.GetOffset(position.Location);
+				}
+			}
+			set {
+				TextDocument document = textArea.Document;
+				if (document != null) {
+					this.Position = new TextViewPosition(document.GetLocation(value));
+					this.DesiredXPos = double.NaN;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the desired x-position of the caret, in device-independent pixels.
+		/// This property is NaN if the caret has no desired position.
+		/// </summary>
+		public double DesiredXPos {
+			get { return desiredXPos; }
+			set { desiredXPos = value; }
+		}
+		
+		void ValidatePosition()
+		{
+			if (position.Line < 1)
+				position.Line = 1;
+			if (position.Column < 1)
+				position.Column = 1;
+			if (position.VisualColumn < -1)
+				position.VisualColumn = -1;
+			TextDocument document = textArea.Document;
+			if (document != null) {
+				if (position.Line > document.LineCount) {
+					position.Line = document.LineCount;
+					position.Column = document.GetLineByNumber(position.Line).Length + 1;
+					position.VisualColumn = -1;
+				} else {
+					DocumentLine line = document.GetLineByNumber(position.Line);
+					if (position.Column > line.Length + 1) {
+						position.Column = line.Length + 1;
+						position.VisualColumn = -1;
+					}
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Event raised when the caret position has changed.
+		/// If the caret position is changed inside a document update (between BeginUpdate/EndUpdate calls),
+		/// the PositionChanged event is raised only once at the end of the document update.
+		/// </summary>
+		public event EventHandler PositionChanged;
+		
+		bool raisePositionChangedOnUpdateFinished;
+		
+		void RaisePositionChanged()
+		{
+			if (textArea.Document != null && textArea.Document.IsInUpdate) {
+				raisePositionChangedOnUpdateFinished = true;
+			} else {
+				if (PositionChanged != null) {
+					PositionChanged(this, EventArgs.Empty);
+				}
+			}
+		}
+		
+		internal void OnDocumentUpdateFinished()
+		{
+			if (raisePositionChangedOnUpdateFinished) {
+				if (PositionChanged != null) {
+					PositionChanged(this, EventArgs.Empty);
+				}
+			}
+		}
+		
+		bool visualColumnValid;
+		
+		void ValidateVisualColumn()
+		{
+			if (!visualColumnValid) {
+				TextDocument document = textArea.Document;
+				if (document != null) {
+					Debug.WriteLine("Explicit validation of caret column");
+					var documentLine = document.GetLineByNumber(position.Line);
+					RevalidateVisualColumn(textView.GetOrConstructVisualLine(documentLine));
+				}
+			}
+		}
+		
+		void InvalidateVisualColumn()
+		{
+			visualColumnValid = false;
+		}
+		
+		/// <summary>
+		/// Validates the visual column of the caret using the specified visual line.
+		/// The visual line must contain the caret offset.
+		/// </summary>
+		void RevalidateVisualColumn(VisualLine visualLine)
+		{
+			if (visualLine == null)
+				throw new ArgumentNullException("visualLine");
+			
+			// mark column as validated
+			visualColumnValid = true;
+			
+			int caretOffset = textView.Document.GetOffset(position.Location);
+			int firstDocumentLineOffset = visualLine.FirstDocumentLine.Offset;
+			position.VisualColumn = visualLine.ValidateVisualColumn(position, textArea.Selection.EnableVirtualSpace);
+			
+			// search possible caret positions
+			int newVisualColumnForwards = visualLine.GetNextCaretPosition(position.VisualColumn - 1, LogicalDirection.Forward, CaretPositioningMode.Normal, textArea.Selection.EnableVirtualSpace);
+			// If position.VisualColumn was valid, we're done with validation.
+			if (newVisualColumnForwards != position.VisualColumn) {
+				// also search backwards so that we can pick the better match
+				int newVisualColumnBackwards = visualLine.GetNextCaretPosition(position.VisualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.Normal, textArea.Selection.EnableVirtualSpace);
+				
+				if (newVisualColumnForwards < 0 && newVisualColumnBackwards < 0)
+					throw ThrowUtil.NoValidCaretPosition();
+				
+				// determine offsets for new visual column positions
+				int newOffsetForwards;
+				if (newVisualColumnForwards >= 0)
+					newOffsetForwards = visualLine.GetRelativeOffset(newVisualColumnForwards) + firstDocumentLineOffset;
+				else
+					newOffsetForwards = -1;
+				int newOffsetBackwards;
+				if (newVisualColumnBackwards >= 0)
+					newOffsetBackwards = visualLine.GetRelativeOffset(newVisualColumnBackwards) + firstDocumentLineOffset;
+				else
+					newOffsetBackwards = -1;
+				
+				int newVisualColumn, newOffset;
+				// if there's only one valid position, use it
+				if (newVisualColumnForwards < 0) {
+					newVisualColumn = newVisualColumnBackwards;
+					newOffset = newOffsetBackwards;
+				} else if (newVisualColumnBackwards < 0) {
+					newVisualColumn = newVisualColumnForwards;
+					newOffset = newOffsetForwards;
+				} else {
+					// two valid positions: find the better match
+					if (Math.Abs(newOffsetBackwards - caretOffset) < Math.Abs(newOffsetForwards - caretOffset)) {
+						// backwards is better
+						newVisualColumn = newVisualColumnBackwards;
+						newOffset = newOffsetBackwards;
+					} else {
+						// forwards is better
+						newVisualColumn = newVisualColumnForwards;
+						newOffset = newOffsetForwards;
+					}
+				}
+				this.Position = new TextViewPosition(textView.Document.GetLocation(newOffset), newVisualColumn);
+			}
+			isInVirtualSpace = (position.VisualColumn > visualLine.VisualLength);
+		}
+		
+		Rect CalcCaretRectangle(VisualLine visualLine)
+		{
+			if (!visualColumnValid) {
+				RevalidateVisualColumn(visualLine);
+			}
+			
+			TextLine textLine = visualLine.GetTextLine(position.VisualColumn, position.IsAtEndOfLine);
+			double xPos = visualLine.GetTextLineVisualXPosition(textLine, position.VisualColumn);
+			double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop);
+			double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom);
+			
+			return new Rect(xPos,
+			                lineTop,
+			                SystemParameters.CaretWidth,
+			                lineBottom - lineTop);
+		}
+		
+		Rect CalcCaretOverstrikeRectangle(VisualLine visualLine)
+		{
+			if (!visualColumnValid) {
+				RevalidateVisualColumn(visualLine);
+			}
+			
+			int currentPos = position.VisualColumn;
+			// The text being overwritten in overstrike mode is everything up to the next normal caret stop
+			int nextPos = visualLine.GetNextCaretPosition(currentPos, LogicalDirection.Forward, CaretPositioningMode.Normal, true);
+			TextLine textLine = visualLine.GetTextLine(currentPos);
+			
+			Rect r;
+			if (currentPos < visualLine.VisualLength) {
+				// If the caret is within the text, use GetTextBounds() for the text being overwritten.
+				// This is necessary to ensure the rectangle is calculated correctly in bidirectional text.
+				var textBounds = textLine.GetTextBounds(currentPos, nextPos - currentPos)[0];
+				r = textBounds.Rectangle;
+				r.Y += visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineTop);
+			} else {
+				// If the caret is at the end of the line (or in virtual space),
+				// use the visual X position of currentPos and nextPos (one or more of which will be in virtual space)
+				double xPos = visualLine.GetTextLineVisualXPosition(textLine, currentPos);
+				double xPos2 = visualLine.GetTextLineVisualXPosition(textLine, nextPos);
+				double lineTop = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextTop);
+				double lineBottom = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextBottom);
+				r = new Rect(xPos, lineTop, xPos2 - xPos, lineBottom - lineTop);
+			}
+			// If the caret is too small (e.g. in front of zero-width character), ensure it's still visible
+			if (r.Width < SystemParameters.CaretWidth)
+				r.Width = SystemParameters.CaretWidth;
+			return r;
+		}
+		
+		/// <summary>
+		/// Returns the caret rectangle. The coordinate system is in device-independent pixels from the top of the document.
+		/// </summary>
+		public Rect CalculateCaretRectangle()
+		{
+			if (textView != null && textView.Document != null) {
+				VisualLine visualLine = textView.GetOrConstructVisualLine(textView.Document.GetLineByNumber(position.Line));
+				return textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine);
+			} else {
+				return Rect.Empty;
+			}
+		}
+		
+		/// <summary>
+		/// Minimum distance of the caret to the view border.
+		/// </summary>
+		internal const double MinimumDistanceToViewBorder = 30;
+		
+		/// <summary>
+		/// Scrolls the text view so that the caret is visible.
+		/// </summary>
+		public void BringCaretToView()
+		{
+			BringCaretToView(MinimumDistanceToViewBorder);
+		}
+		
+		internal void BringCaretToView(double border)
+		{
+			Rect caretRectangle = CalculateCaretRectangle();
+			if (!caretRectangle.IsEmpty) {
+				caretRectangle.Inflate(border, border);
+				textView.MakeVisible(caretRectangle);
+			}
+		}
+		
+		/// <summary>
+		/// Makes the caret visible and updates its on-screen position.
+		/// </summary>
+		public void Show()
+		{
+			Log("Caret.Show()");
+			visible = true;
+			if (!showScheduled) {
+				showScheduled = true;
+				textArea.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(ShowInternal));
+			}
+		}
+		
+		bool showScheduled;
+		bool hasWin32Caret;
+		
+		void ShowInternal()
+		{
+			showScheduled = false;
+			
+			// if show was scheduled but caret hidden in the meantime
+			if (!visible)
+				return;
+			
+			if (caretAdorner != null && textView != null) {
+				VisualLine visualLine = textView.GetVisualLine(position.Line);
+				if (visualLine != null) {
+					Rect caretRect = this.textArea.OverstrikeMode ? CalcCaretOverstrikeRectangle(visualLine) : CalcCaretRectangle(visualLine);
+					// Create Win32 caret so that Windows knows where our managed caret is. This is necessary for
+					// features like 'Follow text editing' in the Windows Magnifier.
+					if (!hasWin32Caret) {
+						hasWin32Caret = Win32.CreateCaret(textView, caretRect.Size);
+					}
+					if (hasWin32Caret) {
+						Win32.SetCaretPosition(textView, caretRect.Location - textView.ScrollOffset);
+					}
+					caretAdorner.Show(caretRect);
+					textArea.ime.UpdateCompositionWindow();
+				} else {
+					caretAdorner.Hide();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Makes the caret invisible.
+		/// </summary>
+		public void Hide()
+		{
+			Log("Caret.Hide()");
+			visible = false;
+			if (hasWin32Caret) {
+				Win32.DestroyCaret();
+				hasWin32Caret = false;
+			}
+			if (caretAdorner != null) {
+				caretAdorner.Hide();
+			}
+		}
+		
+		[Conditional("DEBUG")]
+		static void Log(string text)
+		{
+			// commented out to make debug output less noisy - add back if there are any problems with the caret
+			//Debug.WriteLine(text);
+		}
+		
+		/// <summary>
+		/// Gets/Sets the color of the caret.
+		/// </summary>
+		public Brush CaretBrush {
+			get { return caretAdorner.CaretBrush; }
+			set { caretAdorner.CaretBrush = value; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretLayer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretLayer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretLayer.cs	(revision 11807)
@@ -0,0 +1,115 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Threading;
+
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	sealed class CaretLayer : Layer
+	{
+		TextArea textArea;
+		
+		bool isVisible;
+		Rect caretRectangle;
+		
+		DispatcherTimer caretBlinkTimer = new DispatcherTimer();
+		bool blink;
+		
+		public CaretLayer(TextArea textArea) : base(textArea.TextView, KnownLayer.Caret)
+		{
+			this.textArea = textArea;
+			this.IsHitTestVisible = false;
+			caretBlinkTimer.Tick += new EventHandler(caretBlinkTimer_Tick);
+		}
+
+		void caretBlinkTimer_Tick(object sender, EventArgs e)
+		{
+			blink = !blink;
+			InvalidateVisual();
+		}
+		
+		public void Show(Rect caretRectangle)
+		{
+			this.caretRectangle = caretRectangle;
+			this.isVisible = true;
+			StartBlinkAnimation();
+			InvalidateVisual();
+		}
+		
+		public void Hide()
+		{
+			if (isVisible) {
+				isVisible = false;
+				StopBlinkAnimation();
+				InvalidateVisual();
+			}
+		}
+		
+		void StartBlinkAnimation()
+		{
+			TimeSpan blinkTime = Win32.CaretBlinkTime;
+			blink = true; // the caret should visible initially
+			// This is important if blinking is disabled (system reports a negative blinkTime)
+			if (blinkTime.TotalMilliseconds > 0) {
+				caretBlinkTimer.Interval = blinkTime;
+				caretBlinkTimer.Start();
+			}
+		}
+		
+		void StopBlinkAnimation()
+		{
+			caretBlinkTimer.Stop();
+		}
+		
+		internal Brush CaretBrush;
+		
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			base.OnRender(drawingContext);
+			if (isVisible && blink) {
+				Brush caretBrush = this.CaretBrush;
+				if (caretBrush == null)
+					caretBrush = (Brush)textView.GetValue(TextBlock.ForegroundProperty);
+				
+				if (this.textArea.OverstrikeMode) {
+					SolidColorBrush scBrush = caretBrush as SolidColorBrush;
+					if (scBrush != null) {
+						Color brushColor = scBrush.Color;
+						Color newColor = Color.FromArgb(100, brushColor.R, brushColor.G, brushColor.B);
+						caretBrush = new SolidColorBrush(newColor);
+						caretBrush.Freeze();
+					}
+				}
+				
+				Rect r = new Rect(caretRectangle.X - textView.HorizontalOffset,
+				                  caretRectangle.Y - textView.VerticalOffset,
+				                  caretRectangle.Width,
+				                  caretRectangle.Height);
+				drawingContext.DrawRectangle(caretBrush, null, PixelSnapHelpers.Round(r, PixelSnapHelpers.GetPixelSize(this)));
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretNavigationCommandHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretNavigationCommandHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretNavigationCommandHandler.cs	(revision 11807)
@@ -0,0 +1,392 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	enum CaretMovementType
+	{
+		None,
+		CharLeft,
+		CharRight,
+		Backspace,
+		WordLeft,
+		WordRight,
+		LineUp,
+		LineDown,
+		PageUp,
+		PageDown,
+		LineStart,
+		LineEnd,
+		DocumentStart,
+		DocumentEnd
+	}
+	
+	static class CaretNavigationCommandHandler
+	{
+		/// <summary>
+		/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
+		/// </summary>
+		public static TextAreaInputHandler Create(TextArea textArea)
+		{
+			TextAreaInputHandler handler = new TextAreaInputHandler(textArea);
+			handler.CommandBindings.AddRange(CommandBindings);
+			handler.InputBindings.AddRange(InputBindings);
+			return handler;
+		}
+		
+		static readonly List<CommandBinding> CommandBindings = new List<CommandBinding>();
+		static readonly List<InputBinding> InputBindings = new List<InputBinding>();
+		
+		static void AddBinding(ICommand command, ModifierKeys modifiers, Key key, ExecutedRoutedEventHandler handler)
+		{
+			CommandBindings.Add(new CommandBinding(command, handler));
+			InputBindings.Add(TextAreaDefaultInputHandler.CreateFrozenKeyBinding(command, modifiers, key));
+		}
+		
+		static CaretNavigationCommandHandler()
+		{
+			const ModifierKeys None = ModifierKeys.None;
+			const ModifierKeys Ctrl = ModifierKeys.Control;
+			const ModifierKeys Shift = ModifierKeys.Shift;
+			const ModifierKeys Alt = ModifierKeys.Alt;
+			
+			AddBinding(EditingCommands.MoveLeftByCharacter, None, Key.Left, OnMoveCaret(CaretMovementType.CharLeft));
+			AddBinding(EditingCommands.SelectLeftByCharacter, Shift, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.CharLeft));
+			AddBinding(RectangleSelection.BoxSelectLeftByCharacter, Alt | Shift, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.CharLeft));
+			AddBinding(EditingCommands.MoveRightByCharacter, None, Key.Right, OnMoveCaret(CaretMovementType.CharRight));
+			AddBinding(EditingCommands.SelectRightByCharacter, Shift, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.CharRight));
+			AddBinding(RectangleSelection.BoxSelectRightByCharacter, Alt | Shift, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.CharRight));
+			
+			AddBinding(EditingCommands.MoveLeftByWord, Ctrl, Key.Left, OnMoveCaret(CaretMovementType.WordLeft));
+			AddBinding(EditingCommands.SelectLeftByWord, Ctrl | Shift, Key.Left, OnMoveCaretExtendSelection(CaretMovementType.WordLeft));
+			AddBinding(RectangleSelection.BoxSelectLeftByWord, Ctrl | Alt | Shift, Key.Left, OnMoveCaretBoxSelection(CaretMovementType.WordLeft));
+			AddBinding(EditingCommands.MoveRightByWord, Ctrl, Key.Right, OnMoveCaret(CaretMovementType.WordRight));
+			AddBinding(EditingCommands.SelectRightByWord, Ctrl | Shift, Key.Right, OnMoveCaretExtendSelection(CaretMovementType.WordRight));
+			AddBinding(RectangleSelection.BoxSelectRightByWord, Ctrl | Alt | Shift, Key.Right, OnMoveCaretBoxSelection(CaretMovementType.WordRight));
+			
+			AddBinding(EditingCommands.MoveUpByLine, None, Key.Up, OnMoveCaret(CaretMovementType.LineUp));
+			AddBinding(EditingCommands.SelectUpByLine, Shift, Key.Up, OnMoveCaretExtendSelection(CaretMovementType.LineUp));
+			AddBinding(RectangleSelection.BoxSelectUpByLine, Alt | Shift, Key.Up, OnMoveCaretBoxSelection(CaretMovementType.LineUp));
+			AddBinding(EditingCommands.MoveDownByLine, None, Key.Down, OnMoveCaret(CaretMovementType.LineDown));
+			AddBinding(EditingCommands.SelectDownByLine, Shift, Key.Down, OnMoveCaretExtendSelection(CaretMovementType.LineDown));
+			AddBinding(RectangleSelection.BoxSelectDownByLine, Alt | Shift, Key.Down, OnMoveCaretBoxSelection(CaretMovementType.LineDown));
+			
+			AddBinding(EditingCommands.MoveDownByPage, None, Key.PageDown, OnMoveCaret(CaretMovementType.PageDown));
+			AddBinding(EditingCommands.SelectDownByPage, Shift, Key.PageDown, OnMoveCaretExtendSelection(CaretMovementType.PageDown));
+			AddBinding(EditingCommands.MoveUpByPage, None, Key.PageUp, OnMoveCaret(CaretMovementType.PageUp));
+			AddBinding(EditingCommands.SelectUpByPage, Shift, Key.PageUp, OnMoveCaretExtendSelection(CaretMovementType.PageUp));
+			
+			AddBinding(EditingCommands.MoveToLineStart, None, Key.Home, OnMoveCaret(CaretMovementType.LineStart));
+			AddBinding(EditingCommands.SelectToLineStart, Shift, Key.Home, OnMoveCaretExtendSelection(CaretMovementType.LineStart));
+			AddBinding(RectangleSelection.BoxSelectToLineStart, Alt | Shift, Key.Home, OnMoveCaretBoxSelection(CaretMovementType.LineStart));
+			AddBinding(EditingCommands.MoveToLineEnd, None, Key.End, OnMoveCaret(CaretMovementType.LineEnd));
+			AddBinding(EditingCommands.SelectToLineEnd, Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.LineEnd));
+			AddBinding(RectangleSelection.BoxSelectToLineEnd, Alt | Shift, Key.End, OnMoveCaretBoxSelection(CaretMovementType.LineEnd));
+			
+			AddBinding(EditingCommands.MoveToDocumentStart, Ctrl, Key.Home, OnMoveCaret(CaretMovementType.DocumentStart));
+			AddBinding(EditingCommands.SelectToDocumentStart, Ctrl | Shift, Key.Home, OnMoveCaretExtendSelection(CaretMovementType.DocumentStart));
+			AddBinding(EditingCommands.MoveToDocumentEnd, Ctrl, Key.End, OnMoveCaret(CaretMovementType.DocumentEnd));
+			AddBinding(EditingCommands.SelectToDocumentEnd, Ctrl | Shift, Key.End, OnMoveCaretExtendSelection(CaretMovementType.DocumentEnd));
+			
+			CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, OnSelectAll));
+			
+			TextAreaDefaultInputHandler.WorkaroundWPFMemoryLeak(InputBindings);
+		}
+		
+		static void OnSelectAll(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				args.Handled = true;
+				textArea.Caret.Offset = textArea.Document.TextLength;
+				textArea.Selection = SimpleSelection.Create(textArea, 0, textArea.Document.TextLength);
+			}
+		}
+		
+		static TextArea GetTextArea(object target)
+		{
+			return target as TextArea;
+		}
+		
+		static ExecutedRoutedEventHandler OnMoveCaret(CaretMovementType direction)
+		{
+			return (target, args) => {
+				TextArea textArea = GetTextArea(target);
+				if (textArea != null && textArea.Document != null) {
+					args.Handled = true;
+					textArea.ClearSelection();
+					MoveCaret(textArea, direction);
+					textArea.Caret.BringCaretToView();
+				}
+			};
+		}
+		
+		static ExecutedRoutedEventHandler OnMoveCaretExtendSelection(CaretMovementType direction)
+		{
+			return (target, args) => {
+				TextArea textArea = GetTextArea(target);
+				if (textArea != null && textArea.Document != null) {
+					args.Handled = true;
+					TextViewPosition oldPosition = textArea.Caret.Position;
+					MoveCaret(textArea, direction);
+					textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
+					textArea.Caret.BringCaretToView();
+				}
+			};
+		}
+		
+		static ExecutedRoutedEventHandler OnMoveCaretBoxSelection(CaretMovementType direction)
+		{
+			return (target, args) => {
+				TextArea textArea = GetTextArea(target);
+				if (textArea != null && textArea.Document != null) {
+					args.Handled = true;
+					// First, convert the selection into a rectangle selection
+					// (this is required so that virtual space gets enabled for the caret movement)
+					if (textArea.Options.EnableRectangularSelection && !(textArea.Selection is RectangleSelection)) {
+						if (textArea.Selection.IsEmpty) {
+							textArea.Selection = new RectangleSelection(textArea, textArea.Caret.Position, textArea.Caret.Position);
+						} else {
+							// Convert normal selection to rectangle selection
+							textArea.Selection = new RectangleSelection(textArea, textArea.Selection.StartPosition, textArea.Caret.Position);
+						}
+					}
+					// Now move the caret and extend the selection
+					TextViewPosition oldPosition = textArea.Caret.Position;
+					MoveCaret(textArea, direction);
+					textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
+					textArea.Caret.BringCaretToView();
+				}
+			};
+		}
+		
+		#region Caret movement
+		internal static void MoveCaret(TextArea textArea, CaretMovementType direction)
+		{
+			double desiredXPos = textArea.Caret.DesiredXPos;
+			textArea.Caret.Position = GetNewCaretPosition(textArea.TextView, textArea.Caret.Position, direction, textArea.Selection.EnableVirtualSpace, ref desiredXPos);
+			textArea.Caret.DesiredXPos = desiredXPos;
+		}
+		
+		internal static TextViewPosition GetNewCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, bool enableVirtualSpace, ref double desiredXPos)
+		{
+			switch (direction) {
+				case CaretMovementType.None:
+					return caretPosition;
+				case CaretMovementType.DocumentStart:
+					desiredXPos = double.NaN;
+					return new TextViewPosition(0, 0);
+				case CaretMovementType.DocumentEnd:
+					desiredXPos = double.NaN;
+					return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
+			}
+			DocumentLine caretLine = textView.Document.GetLineByNumber(caretPosition.Line);
+			VisualLine visualLine = textView.GetOrConstructVisualLine(caretLine);
+			TextLine textLine = visualLine.GetTextLine(caretPosition.VisualColumn, caretPosition.IsAtEndOfLine);
+			switch (direction) {
+				case CaretMovementType.CharLeft:
+					desiredXPos = double.NaN;
+					return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
+				case CaretMovementType.Backspace:
+					desiredXPos = double.NaN;
+					return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.EveryCodepoint, enableVirtualSpace);
+				case CaretMovementType.CharRight:
+					desiredXPos = double.NaN;
+					return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.Normal, enableVirtualSpace);
+				case CaretMovementType.WordLeft:
+					desiredXPos = double.NaN;
+					return GetPrevCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
+				case CaretMovementType.WordRight:
+					desiredXPos = double.NaN;
+					return GetNextCaretPosition(textView, caretPosition, visualLine, CaretPositioningMode.WordStart, enableVirtualSpace);
+				case CaretMovementType.LineUp:
+				case CaretMovementType.LineDown:
+				case CaretMovementType.PageUp:
+				case CaretMovementType.PageDown:
+					return GetUpDownCaretPosition(textView, caretPosition, direction, visualLine, textLine, enableVirtualSpace, ref desiredXPos);
+				case CaretMovementType.LineStart:
+					desiredXPos = double.NaN;
+					return GetStartOfLineCaretPosition(caretPosition.VisualColumn, visualLine, textLine, enableVirtualSpace);
+				case CaretMovementType.LineEnd:
+					desiredXPos = double.NaN;
+					return GetEndOfLineCaretPosition(visualLine, textLine);
+				default:
+					throw new NotSupportedException(direction.ToString());
+			}
+		}
+		#endregion
+		
+		#region Home/End
+		static TextViewPosition GetStartOfLineCaretPosition(int oldVC, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace)
+		{
+			int newVC = visualLine.GetTextLineVisualStartColumn(textLine);
+			if (newVC == 0)
+				newVC = visualLine.GetNextCaretPosition(newVC - 1, LogicalDirection.Forward, CaretPositioningMode.WordStart, enableVirtualSpace);
+			if (newVC < 0)
+				throw ThrowUtil.NoValidCaretPosition();
+			// when the caret is already at the start of the text, jump to start before whitespace
+			if (newVC == oldVC)
+				newVC = 0;
+			return visualLine.GetTextViewPosition(newVC);
+		}
+		
+		static TextViewPosition GetEndOfLineCaretPosition(VisualLine visualLine, TextLine textLine)
+		{
+			int newVC = visualLine.GetTextLineVisualStartColumn(textLine) + textLine.Length - textLine.TrailingWhitespaceLength;
+			TextViewPosition pos = visualLine.GetTextViewPosition(newVC);
+			pos.IsAtEndOfLine = true;
+			return pos;
+		}
+		#endregion
+		
+		#region By-character / By-word movement
+		static TextViewPosition GetNextCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
+		{
+			int pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Forward, mode, enableVirtualSpace);
+			if (pos >= 0) {
+				return visualLine.GetTextViewPosition(pos);
+			} else {
+				// move to start of next line
+				DocumentLine nextDocumentLine = visualLine.LastDocumentLine.NextLine;
+				if (nextDocumentLine != null) {
+					VisualLine nextLine = textView.GetOrConstructVisualLine(nextDocumentLine);
+					pos = nextLine.GetNextCaretPosition(-1, LogicalDirection.Forward, mode, enableVirtualSpace);
+					if (pos < 0)
+						throw ThrowUtil.NoValidCaretPosition();
+					return nextLine.GetTextViewPosition(pos);
+				} else {
+					// at end of document
+					Debug.Assert(visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength == textView.Document.TextLength);
+					return new TextViewPosition(textView.Document.GetLocation(textView.Document.TextLength));
+				}
+			}
+		}
+		
+		static TextViewPosition GetPrevCaretPosition(TextView textView, TextViewPosition caretPosition, VisualLine visualLine, CaretPositioningMode mode, bool enableVirtualSpace)
+		{
+			int pos = visualLine.GetNextCaretPosition(caretPosition.VisualColumn, LogicalDirection.Backward, mode, enableVirtualSpace);
+			if (pos >= 0) {
+				return visualLine.GetTextViewPosition(pos);
+			} else {
+				// move to end of previous line
+				DocumentLine previousDocumentLine = visualLine.FirstDocumentLine.PreviousLine;
+				if (previousDocumentLine != null) {
+					VisualLine previousLine = textView.GetOrConstructVisualLine(previousDocumentLine);
+					pos = previousLine.GetNextCaretPosition(previousLine.VisualLength + 1, LogicalDirection.Backward, mode, enableVirtualSpace);
+					if (pos < 0)
+						throw ThrowUtil.NoValidCaretPosition();
+					return previousLine.GetTextViewPosition(pos);
+				} else {
+					// at start of document
+					Debug.Assert(visualLine.FirstDocumentLine.Offset == 0);
+					return new TextViewPosition(0, 0);
+				}
+			}
+		}
+		#endregion
+
+		#region Line+Page up/down
+		static TextViewPosition GetUpDownCaretPosition(TextView textView, TextViewPosition caretPosition, CaretMovementType direction, VisualLine visualLine, TextLine textLine, bool enableVirtualSpace, ref double xPos)
+		{
+			// moving up/down happens using the desired visual X position
+			if (double.IsNaN(xPos))
+				xPos = visualLine.GetTextLineVisualXPosition(textLine, caretPosition.VisualColumn);
+			// now find the TextLine+VisualLine where the caret will end up in
+			VisualLine targetVisualLine = visualLine;
+			TextLine targetLine;
+			int textLineIndex = visualLine.TextLines.IndexOf(textLine);
+			switch (direction) {
+				case CaretMovementType.LineUp:
+					{
+						// Move up: move to the previous TextLine in the same visual line
+						// or move to the last TextLine of the previous visual line
+						int prevLineNumber = visualLine.FirstDocumentLine.LineNumber - 1;
+						if (textLineIndex > 0) {
+							targetLine = visualLine.TextLines[textLineIndex - 1];
+						} else if (prevLineNumber >= 1) {
+							DocumentLine prevLine = textView.Document.GetLineByNumber(prevLineNumber);
+							targetVisualLine = textView.GetOrConstructVisualLine(prevLine);
+							targetLine = targetVisualLine.TextLines[targetVisualLine.TextLines.Count - 1];
+						} else {
+							targetLine = null;
+						}
+						break;
+					}
+				case CaretMovementType.LineDown:
+					{
+						// Move down: move to the next TextLine in the same visual line
+						// or move to the first TextLine of the next visual line
+						int nextLineNumber = visualLine.LastDocumentLine.LineNumber + 1;
+						if (textLineIndex < visualLine.TextLines.Count - 1) {
+							targetLine = visualLine.TextLines[textLineIndex + 1];
+						} else if (nextLineNumber <= textView.Document.LineCount) {
+							DocumentLine nextLine = textView.Document.GetLineByNumber(nextLineNumber);
+							targetVisualLine = textView.GetOrConstructVisualLine(nextLine);
+							targetLine = targetVisualLine.TextLines[0];
+						} else {
+							targetLine = null;
+						}
+						break;
+					}
+				case CaretMovementType.PageUp:
+				case CaretMovementType.PageDown:
+					{
+						// Page up/down: find the target line using its visual position
+						double yPos = visualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.LineMiddle);
+						if (direction == CaretMovementType.PageUp)
+							yPos -= textView.RenderSize.Height;
+						else
+							yPos += textView.RenderSize.Height;
+						DocumentLine newLine = textView.GetDocumentLineByVisualTop(yPos);
+						targetVisualLine = textView.GetOrConstructVisualLine(newLine);
+						targetLine = targetVisualLine.GetTextLineByVisualYPosition(yPos);
+						break;
+					}
+				default:
+					throw new NotSupportedException(direction.ToString());
+			}
+			if (targetLine != null) {
+				double yPos = targetVisualLine.GetTextLineVisualYPosition(targetLine, VisualYPosition.LineMiddle);
+				int newVisualColumn = targetVisualLine.GetVisualColumn(new Point(xPos, yPos), enableVirtualSpace);
+				
+				// prevent wrapping to the next line; TODO: could 'IsAtEnd' help here?
+				int targetLineStartCol = targetVisualLine.GetTextLineVisualStartColumn(targetLine);
+				if (newVisualColumn >= targetLineStartCol + targetLine.Length) {
+					if (newVisualColumn <= targetVisualLine.VisualLength)
+						newVisualColumn = targetLineStartCol + targetLine.Length - 1;
+				}
+				return targetVisualLine.GetTextViewPosition(newVisualColumn);
+			} else {
+				return caretPosition;
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretWeakEventHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretWeakEventHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/CaretWeakEventHandler.cs	(revision 11807)
@@ -0,0 +1,48 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using ICSharpCode.AvalonEdit.Utils;
+using System;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Contains classes for handling weak events on the Caret class.
+	/// </summary>
+	public static class CaretWeakEventManager
+	{
+		/// <summary>
+		/// Handles the Caret.PositionChanged event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class PositionChanged : WeakEventManagerBase<PositionChanged, Caret>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(Caret source)
+			{
+				source.PositionChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(Caret source)
+			{
+				source.PositionChanged -= DeliverEvent;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/DottedLineMargin.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/DottedLineMargin.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/DottedLineMargin.cs	(revision 11807)
@@ -0,0 +1,78 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Media;
+using System.Windows.Shapes;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Margin for use with the text area.
+	/// A vertical dotted line to separate the line numbers from the text view.
+	/// </summary>
+	public static class DottedLineMargin
+	{
+		static readonly object tag = new object();
+		
+		/// <summary>
+		/// Creates a vertical dotted line to separate the line numbers from the text view.
+		/// </summary>
+		public static UIElement Create()
+		{
+			Line line = new Line {
+				X1 = 0, Y1 = 0, X2 = 0, Y2 = 1,
+				StrokeDashArray = { 0, 2 },
+				Stretch = Stretch.Fill,
+				StrokeThickness = 1,
+				StrokeDashCap = PenLineCap.Round,
+				Margin = new Thickness(2, 0, 2, 0),
+				Tag = tag
+			};
+			
+			return line;
+		}
+		
+		/// <summary>
+		/// Creates a vertical dotted line to separate the line numbers from the text view.
+		/// </summary>
+		[Obsolete("This method got published accidentally; and will be removed again in a future version. Use the parameterless overload instead.")]
+		public static UIElement Create(TextEditor editor)
+		{
+			Line line = (Line)Create();
+			
+			line.SetBinding(
+				Line.StrokeProperty,
+				new Binding("LineNumbersForeground") { Source = editor }
+			);
+			
+			return line;
+		}
+		
+		/// <summary>
+		/// Gets whether the specified UIElement is the result of a DottedLineMargin.Create call.
+		/// </summary>
+		public static bool IsDottedLineMargin(UIElement element)
+		{
+			Line l = element as Line;
+			return l != null && l.Tag == tag;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/DragDropException.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/DragDropException.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/DragDropException.cs	(revision 11807)
@@ -0,0 +1,61 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.Serialization;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Wraps exceptions that occur during drag'n'drop.
+	/// Exceptions during drag'n'drop might
+	/// get swallowed by WPF/COM, so AvalonEdit catches them and re-throws them later
+	/// wrapped in a DragDropException.
+	/// </summary>
+	[Serializable()]
+	public class DragDropException : Exception
+	{
+		/// <summary>
+		/// Creates a new DragDropException.
+		/// </summary>
+		public DragDropException() : base()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new DragDropException.
+		/// </summary>
+		public DragDropException(string message) : base(message)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new DragDropException.
+		/// </summary>
+		public DragDropException(string message, Exception innerException) : base(message, innerException)
+		{
+		}
+		
+		/// <summary>
+		/// Deserializes a DragDropException.
+		/// </summary>
+		protected DragDropException(SerializationInfo info, StreamingContext context) : base(info, context)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/EditingCommandHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/EditingCommandHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/EditingCommandHandler.cs	(revision 11807)
@@ -0,0 +1,644 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Input;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Highlighting;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
+	/// so this class is static.
+	/// </summary>
+	static class EditingCommandHandler
+	{
+		/// <summary>
+		/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
+		/// </summary>
+		public static TextAreaInputHandler Create(TextArea textArea)
+		{
+			TextAreaInputHandler handler = new TextAreaInputHandler(textArea);
+			handler.CommandBindings.AddRange(CommandBindings);
+			handler.InputBindings.AddRange(InputBindings);
+			return handler;
+		}
+		
+		static readonly List<CommandBinding> CommandBindings = new List<CommandBinding>();
+		static readonly List<InputBinding> InputBindings = new List<InputBinding>();
+		
+		static void AddBinding(ICommand command, ModifierKeys modifiers, Key key, ExecutedRoutedEventHandler handler)
+		{
+			CommandBindings.Add(new CommandBinding(command, handler));
+			InputBindings.Add(TextAreaDefaultInputHandler.CreateFrozenKeyBinding(command, modifiers, key));
+		}
+		
+		static EditingCommandHandler()
+		{
+			CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete));
+			AddBinding(EditingCommands.Delete, ModifierKeys.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
+			AddBinding(EditingCommands.DeleteNextWord, ModifierKeys.Control, Key.Delete, OnDelete(CaretMovementType.WordRight));
+			AddBinding(EditingCommands.Backspace, ModifierKeys.None, Key.Back, OnDelete(CaretMovementType.Backspace));
+			InputBindings.Add(TextAreaDefaultInputHandler.CreateFrozenKeyBinding(EditingCommands.Backspace, ModifierKeys.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace
+			AddBinding(EditingCommands.DeletePreviousWord, ModifierKeys.Control, Key.Back, OnDelete(CaretMovementType.WordLeft));
+			AddBinding(EditingCommands.EnterParagraphBreak, ModifierKeys.None, Key.Enter, OnEnter);
+			AddBinding(EditingCommands.EnterLineBreak, ModifierKeys.Shift, Key.Enter, OnEnter);
+			AddBinding(EditingCommands.TabForward, ModifierKeys.None, Key.Tab, OnTab);
+			AddBinding(EditingCommands.TabBackward, ModifierKeys.Shift, Key.Tab, OnShiftTab);
+			
+			CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, OnCopy, CanCutOrCopy));
+			CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, OnCut, CanCutOrCopy));
+			CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, OnPaste, CanPaste));
+			
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.DeleteLine, OnDeleteLine));
+			
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertToUppercase, OnConvertToUpperCase));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertToLowercase, OnConvertToLowerCase));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertToTitleCase, OnConvertToTitleCase));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.InvertCase, OnInvertCase));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs));
+			CommandBindings.Add(new CommandBinding(AvalonEditCommands.IndentSelection, OnIndentSelection));
+			
+			TextAreaDefaultInputHandler.WorkaroundWPFMemoryLeak(InputBindings);
+		}
+		
+		static TextArea GetTextArea(object target)
+		{
+			return target as TextArea;
+		}
+		
+		#region Text Transformation Helpers
+		enum DefaultSegmentType
+		{
+			None,
+			WholeDocument,
+			CurrentLine
+		}
+		
+		/// <summary>
+		/// Calls transformLine on all lines in the selected range.
+		/// transformLine needs to handle read-only segments!
+		/// </summary>
+		static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				using (textArea.Document.RunUpdate()) {
+					DocumentLine start, end;
+					if (textArea.Selection.IsEmpty) {
+						if (defaultSegmentType == DefaultSegmentType.CurrentLine) {
+							start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
+						} else if (defaultSegmentType == DefaultSegmentType.WholeDocument) {
+							start = textArea.Document.Lines.First();
+							end = textArea.Document.Lines.Last();
+						} else {
+							start = end = null;
+						}
+					} else {
+						ISegment segment = textArea.Selection.SurroundingSegment;
+						start = textArea.Document.GetLineByOffset(segment.Offset);
+						end = textArea.Document.GetLineByOffset(segment.EndOffset);
+						// don't include the last line if no characters on it are selected
+						if (start != end && end.Offset == segment.EndOffset)
+							end = end.PreviousLine;
+					}
+					if (start != null) {
+						transformLine(textArea, start);
+						while (start != end) {
+							start = start.NextLine;
+							transformLine(textArea, start);
+						}
+					}
+				}
+				textArea.Caret.BringCaretToView();
+				args.Handled = true;
+			}
+		}
+		
+		/// <summary>
+		/// Calls transformLine on all writable segment in the selected range.
+		/// </summary>
+		static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				using (textArea.Document.RunUpdate()) {
+					IEnumerable<ISegment> segments;
+					if (textArea.Selection.IsEmpty) {
+						if (defaultSegmentType == DefaultSegmentType.CurrentLine) {
+							segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
+						} else if (defaultSegmentType == DefaultSegmentType.WholeDocument) {
+							segments = textArea.Document.Lines.Cast<ISegment>();
+						} else {
+							segments = null;
+						}
+					} else {
+						segments = textArea.Selection.Segments.Cast<ISegment>();
+					}
+					if (segments != null) {
+						foreach (ISegment segment in segments.Reverse()) {
+							foreach (ISegment writableSegment in textArea.GetDeletableSegments(segment).Reverse()) {
+								transformSegment(textArea, writableSegment);
+							}
+						}
+					}
+				}
+				textArea.Caret.BringCaretToView();
+				args.Handled = true;
+			}
+		}
+		#endregion
+		
+		#region EnterLineBreak
+		static void OnEnter(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.IsKeyboardFocused) {
+				textArea.PerformTextInput("\n");
+				args.Handled = true;
+			}
+		}
+		#endregion
+		
+		#region Tab
+		static void OnTab(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				using (textArea.Document.RunUpdate()) {
+					if (textArea.Selection.IsMultiline) {
+						var segment = textArea.Selection.SurroundingSegment;
+						DocumentLine start = textArea.Document.GetLineByOffset(segment.Offset);
+						DocumentLine end = textArea.Document.GetLineByOffset(segment.EndOffset);
+						// don't include the last line if no characters on it are selected
+						if (start != end && end.Offset == segment.EndOffset)
+							end = end.PreviousLine;
+						DocumentLine current = start;
+						while (true) {
+							int offset = current.Offset;
+							if (textArea.ReadOnlySectionProvider.CanInsert(offset))
+								textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
+							if (current == end)
+								break;
+							current = current.NextLine;
+						}
+					} else {
+						string indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
+						textArea.ReplaceSelectionWithText(indentationString);
+					}
+				}
+				textArea.Caret.BringCaretToView();
+				args.Handled = true;
+			}
+		}
+		
+		static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedLines(
+				delegate (TextArea textArea, DocumentLine line) {
+					int offset = line.Offset;
+					ISegment s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize);
+					if (s.Length > 0) {
+						s = textArea.GetDeletableSegments(s).FirstOrDefault();
+						if (s != null && s.Length > 0) {
+							textArea.Document.Remove(s.Offset, s.Length);
+						}
+					}
+				}, target, args, DefaultSegmentType.CurrentLine);
+		}
+		#endregion
+		
+		#region Delete
+		static ExecutedRoutedEventHandler OnDelete(CaretMovementType caretMovement)
+		{
+			return (target, args) => {
+				TextArea textArea = GetTextArea(target);
+				if (textArea != null && textArea.Document != null) {
+					if (textArea.Selection.IsEmpty) {
+						TextViewPosition startPos = textArea.Caret.Position;
+						bool enableVirtualSpace = textArea.Options.EnableVirtualSpace;
+						// When pressing delete; don't move the caret further into virtual space - instead delete the newline
+						if (caretMovement == CaretMovementType.CharRight)
+							enableVirtualSpace = false;
+						double desiredXPos = textArea.Caret.DesiredXPos;
+						TextViewPosition endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
+							textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
+						// GetNewCaretPosition may return (0,0) as new position,
+						// thus we need to validate endPos before using it in the selection.
+						if (endPos.Line < 1 || endPos.Column < 1)
+							endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
+						// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
+						var sel = new SimpleSelection(textArea, startPos, endPos);
+						sel.ReplaceSelectionWithText(string.Empty);
+					} else {
+						textArea.RemoveSelectedText();
+					}
+					textArea.Caret.BringCaretToView();
+					args.Handled = true;
+				}
+			};
+		}
+		
+		static void CanDelete(object target, CanExecuteRoutedEventArgs args)
+		{
+			// HasSomethingSelected for delete command
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				args.CanExecute = !textArea.Selection.IsEmpty;
+				args.Handled = true;
+			}
+		}
+		#endregion
+		
+		#region Clipboard commands
+		static void CanCutOrCopy(object target, CanExecuteRoutedEventArgs args)
+		{
+			// HasSomethingSelected for copy and cut commands
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
+				args.Handled = true;
+			}
+		}
+		
+		static void OnCopy(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) {
+					DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
+					CopyWholeLine(textArea, currentLine);
+				} else {
+					CopySelectedText(textArea);
+				}
+				args.Handled = true;
+			}
+		}
+		
+		static void OnCut(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) {
+					DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
+					if (CopyWholeLine(textArea, currentLine)) {
+						ISegment[] segmentsToDelete = textArea.GetDeletableSegments(new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
+						for (int i = segmentsToDelete.Length - 1; i >= 0; i--) {
+							textArea.Document.Remove(segmentsToDelete[i]);
+						}
+					}
+				} else {
+					if (CopySelectedText(textArea))
+						textArea.RemoveSelectedText();
+				}
+				textArea.Caret.BringCaretToView();
+				args.Handled = true;
+			}
+		}
+		
+		static bool CopySelectedText(TextArea textArea)
+		{
+			var data = textArea.Selection.CreateDataObject(textArea);
+			var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
+			textArea.RaiseEvent(copyingEventArgs);
+			if (copyingEventArgs.CommandCancelled)
+				return false;
+			
+			try {
+				Clipboard.SetDataObject(data, true);
+			} catch (ExternalException) {
+				// Apparently this exception sometimes happens randomly.
+				// The MS controls just ignore it, so we'll do the same.
+				return false;
+			}
+			
+			string text = textArea.Selection.GetText();
+			text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
+			textArea.OnTextCopied(new TextEventArgs(text));
+			return true;
+		}
+		
+		const string LineSelectedType = "MSDEVLineSelect";  // This is the type VS 2003 and 2005 use for flagging a whole line copy
+		
+		public static bool ConfirmDataFormat(TextArea textArea, DataObject dataObject, string format)
+		{
+			var e = new DataObjectSettingDataEventArgs(dataObject, format);
+			textArea.RaiseEvent(e);
+			return !e.CommandCancelled;
+		}
+		
+		static bool CopyWholeLine(TextArea textArea, DocumentLine line)
+		{
+			ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
+			string text = textArea.Document.GetText(wholeLine);
+			// Ensure we use the appropriate newline sequence for the OS
+			text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
+			DataObject data = new DataObject();
+			if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
+				data.SetText(text);
+			
+			// Also copy text in HTML format to clipboard - good for pasting text into Word
+			// or to the SharpDevelop forums.
+			if (ConfirmDataFormat(textArea, data, DataFormats.Html)) {
+				IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
+				HtmlClipboard.SetHtml(data, HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, new HtmlOptions(textArea.Options)));
+			}
+			
+			if (ConfirmDataFormat(textArea, data, LineSelectedType)) {
+				MemoryStream lineSelected = new MemoryStream(1);
+				lineSelected.WriteByte(1);
+				data.SetData(LineSelectedType, lineSelected, false);
+			}
+			
+			var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
+			textArea.RaiseEvent(copyingEventArgs);
+			if (copyingEventArgs.CommandCancelled)
+				return false;
+			
+			try {
+				Clipboard.SetDataObject(data, true);
+			} catch (ExternalException) {
+				// Apparently this exception sometimes happens randomly.
+				// The MS controls just ignore it, so we'll do the same.
+				return false;
+			}
+			textArea.OnTextCopied(new TextEventArgs(text));
+			return true;
+		}
+		
+		static void CanPaste(object target, CanExecuteRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)
+					&& Clipboard.ContainsText();
+				// WPF Clipboard.ContainsText() is safe to call without catching ExternalExceptions
+				// because it doesn't try to lock the clipboard - it just peeks inside with IsClipboardFormatAvailable().
+				args.Handled = true;
+			}
+		}
+		
+		static void OnPaste(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				IDataObject dataObject;
+				try {
+					dataObject = Clipboard.GetDataObject();
+				} catch (ExternalException) {
+					return;
+				}
+				if (dataObject == null)
+					return;
+				Debug.WriteLine(dataObject.GetData(DataFormats.Html) as string);
+				
+				// convert text back to correct newlines for this document
+				string newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
+				string text;
+				try {
+					text = (string)dataObject.GetData(DataFormats.UnicodeText);
+					text = TextUtilities.NormalizeNewLines(text, newLine);
+				} catch (OutOfMemoryException) {
+					return;
+				}
+				
+				if (!string.IsNullOrEmpty(text)) {
+					bool fullLine = textArea.Options.CutCopyWholeLine && dataObject.GetDataPresent(LineSelectedType);
+					bool rectangular = dataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
+					
+					string pasteFormat;
+					// fill the suggested DataFormat used for the paste action:
+					if (fullLine)
+						pasteFormat = LineSelectedType;
+					else if (rectangular && textArea.Selection.IsEmpty && !(textArea.Selection is RectangleSelection))
+						pasteFormat = RectangleSelection.RectangularSelectionDataType;
+					else
+						pasteFormat = DataFormats.UnicodeText;
+					
+					var pastingEventArgs = new DataObjectPastingEventArgs(dataObject, false, pasteFormat);
+					textArea.RaiseEvent(pastingEventArgs);
+					if (pastingEventArgs.CommandCancelled)
+						return;
+					
+					// DataObject.PastingEvent handlers might have changed the format to apply.
+					pasteFormat = pastingEventArgs.FormatToApply;
+					
+					fullLine = pasteFormat == LineSelectedType;
+					rectangular = pasteFormat == RectangleSelection.RectangularSelectionDataType;
+					
+					if (fullLine) {
+						DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
+						if (textArea.ReadOnlySectionProvider.CanInsert(currentLine.Offset)) {
+							textArea.Document.Insert(currentLine.Offset, text);
+						}
+					} else if (rectangular && textArea.Selection.IsEmpty && !(textArea.Selection is RectangleSelection)) {
+						if (!RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, false))
+							textArea.ReplaceSelectionWithText(text);
+					} else {
+						textArea.ReplaceSelectionWithText(text);
+					}
+				}
+				textArea.Caret.BringCaretToView();
+				args.Handled = true;
+			}
+		}
+		#endregion
+		
+		#region DeleteLine
+		static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				int firstLineIndex, lastLineIndex;
+				if (textArea.Selection.Length == 0) {
+					// There is no selection, simply delete current line
+					firstLineIndex = lastLineIndex = textArea.Caret.Line;
+				} else {
+					// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
+					firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line);
+					lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line);
+				}
+				DocumentLine startLine = textArea.Document.GetLineByNumber(firstLineIndex);
+				DocumentLine endLine = textArea.Document.GetLineByNumber(lastLineIndex);
+				textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength);
+				textArea.RemoveSelectedText();
+				args.Handled = true;
+			}
+		}
+		#endregion
+		
+		#region Remove..Whitespace / Convert Tabs-Spaces
+		static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedLines(
+				delegate (TextArea textArea, DocumentLine line) {
+					textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
+				}, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedLines(
+				delegate (TextArea textArea, DocumentLine line) {
+					textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
+				}, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedLines(
+				delegate (TextArea textArea, DocumentLine line) {
+					ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
+				}, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
+		{
+			TextDocument document = textArea.Document;
+			int endOffset = segment.EndOffset;
+			string indentationString = new string(' ', textArea.Options.IndentationSize);
+			for (int offset = segment.Offset; offset < endOffset; offset++) {
+				if (document.GetCharAt(offset) == '\t') {
+					document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
+					endOffset += indentationString.Length - 1;
+				}
+			}
+		}
+		
+		static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedLines(
+				delegate (TextArea textArea, DocumentLine line) {
+					ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
+				}, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
+		{
+			TextDocument document = textArea.Document;
+			int endOffset = segment.EndOffset;
+			int indentationSize = textArea.Options.IndentationSize;
+			int spacesCount = 0;
+			for (int offset = segment.Offset; offset < endOffset; offset++) {
+				if (document.GetCharAt(offset) == ' ') {
+					spacesCount++;
+					if (spacesCount == indentationSize) {
+						document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace);
+						spacesCount = 0;
+						offset -= indentationSize - 1;
+						endOffset -= indentationSize - 1;
+					}
+				} else {
+					spacesCount = 0;
+				}
+			}
+		}
+		#endregion
+		
+		#region Convert...Case
+		static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
+		{
+			TransformSelectedSegments(
+				delegate (TextArea textArea, ISegment segment) {
+					string oldText = textArea.Document.GetText(segment);
+					string newText = transformText(oldText);
+					textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace);
+				}, target, args, DefaultSegmentType.WholeDocument);
+		}
+		
+		static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
+		{
+			ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
+		}
+		
+		static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
+		{
+			ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
+		}
+		
+		static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
+		{
+			ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
+		}
+		
+		static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
+		{
+			ConvertCase(InvertCase, target, args);
+		}
+		
+		static string InvertCase(string text)
+		{
+			CultureInfo culture = CultureInfo.CurrentCulture;
+			char[] buffer = text.ToCharArray();
+			for (int i = 0; i < buffer.Length; ++i) {
+				char c = buffer[i];
+				buffer[i] = char.IsUpper(c) ? char.ToLower(c, culture) : char.ToUpper(c, culture);
+			}
+			return new string(buffer);
+		}
+		#endregion
+		
+		static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
+		{
+			TextArea textArea = GetTextArea(target);
+			if (textArea != null && textArea.Document != null) {
+				using (textArea.Document.RunUpdate()) {
+					int start, end;
+					if (textArea.Selection.IsEmpty) {
+						start = 1;
+						end = textArea.Document.LineCount;
+					} else {
+						start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset).LineNumber;
+						end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset).LineNumber;
+					}
+					textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
+				}
+				textArea.Caret.BringCaretToView();
+				args.Handled = true;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/EmptySelection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/EmptySelection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/EmptySelection.cs	(revision 11807)
@@ -0,0 +1,105 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	sealed class EmptySelection : Selection
+	{
+		public EmptySelection(TextArea textArea) : base(textArea)
+		{
+		}
+		
+		public override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
+		{
+			return this;
+		}
+		
+		public override TextViewPosition StartPosition {
+			get { return new TextViewPosition(TextLocation.Empty); }
+		}
+		
+		public override TextViewPosition EndPosition {
+			get { return new TextViewPosition(TextLocation.Empty); }
+		}
+		
+		public override ISegment SurroundingSegment {
+			get { return null; }
+		}
+		
+		public override Selection SetEndpoint(TextViewPosition endPosition)
+		{
+			throw new NotSupportedException();
+		}
+		
+		public override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
+		{
+			var document = textArea.Document;
+			if (document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			return Create(textArea, startPosition, endPosition);
+		}
+		
+		public override IEnumerable<SelectionSegment> Segments {
+			get { return Empty<SelectionSegment>.Array; }
+		}
+		
+		public override string GetText()
+		{
+			return string.Empty;
+		}
+		
+		public override void ReplaceSelectionWithText(string newText)
+		{
+			if (newText == null)
+				throw new ArgumentNullException("newText");
+			newText = AddSpacesIfRequired(newText, textArea.Caret.Position, textArea.Caret.Position);
+			if (newText.Length > 0) {
+				if (textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)) {
+					textArea.Document.Insert(textArea.Caret.Offset, newText);
+				}
+			}
+			textArea.Caret.VisualColumn = -1;
+		}
+		
+		public override int Length {
+			get { return 0; }
+		}
+		
+		// Use reference equality because there's only one EmptySelection per text area.
+		public override int GetHashCode()
+		{
+			return RuntimeHelpers.GetHashCode(this);
+		}
+		
+		public override bool Equals(object obj)
+		{
+			return this == obj;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/IReadOnlySectionProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/IReadOnlySectionProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/IReadOnlySectionProvider.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Determines whether the document can be modified.
+	/// </summary>
+	public interface IReadOnlySectionProvider
+	{
+		/// <summary>
+		/// Gets whether insertion is possible at the specified offset.
+		/// </summary>
+		bool CanInsert(int offset);
+		
+		/// <summary>
+		/// Gets the deletable segments inside the given segment.
+		/// </summary>
+		/// <remarks>
+		/// All segments in the result must be within the given segment, and they must be returned in order
+		/// (e.g. if two segments are returned, EndOffset of first segment must be less than StartOffset of second segment).
+		/// 
+		/// For replacements, the last segment being returned will be replaced with the new text. If an empty list is returned,
+		/// no replacement will be done.
+		/// </remarks>
+		IEnumerable<ISegment> GetDeletableSegments(ISegment segment);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/ImeNativeWrapper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/ImeNativeWrapper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/ImeNativeWrapper.cs	(revision 11807)
@@ -0,0 +1,221 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Windows;
+using System.Windows.Input;
+using System.Windows.Interop;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+using Draw = System.Drawing;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Native API required for IME support.
+	/// </summary>
+	static class ImeNativeWrapper
+	{
+		[StructLayout(LayoutKind.Sequential)]
+		struct CompositionForm
+		{
+			public int dwStyle;
+			public POINT ptCurrentPos;
+			public RECT rcArea;
+		}
+		
+		[StructLayout(LayoutKind.Sequential)]
+		struct POINT
+		{
+			public int x;
+			public int y;
+		}
+		
+		[StructLayout(LayoutKind.Sequential)]
+		struct RECT
+		{
+			public int left;
+			public int top;
+			public int right;
+			public int bottom;
+		}
+		
+		[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+		struct LOGFONT
+		{
+			public int lfHeight;
+			public int lfWidth;
+			public int lfEscapement;
+			public int lfOrientation;
+			public int lfWeight;
+			public byte lfItalic;
+			public byte lfUnderline;
+			public byte lfStrikeOut;
+			public byte lfCharSet;
+			public byte lfOutPrecision;
+			public byte lfClipPrecision;
+			public byte lfQuality;
+			public byte lfPitchAndFamily;
+			[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string lfFaceName;
+		}
+		
+		const int CPS_CANCEL = 0x4;
+		const int NI_COMPOSITIONSTR = 0x15;
+		const int GCS_COMPSTR = 0x0008;
+		
+		public const int WM_IME_COMPOSITION = 0x10F;
+		public const int WM_IME_SETCONTEXT = 0x281;
+		public const int WM_INPUTLANGCHANGE = 0x51;
+		
+		[DllImport("imm32.dll")]
+		public static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
+		[DllImport("imm32.dll")]
+		internal static extern IntPtr ImmGetContext(IntPtr hWnd);
+		[DllImport("imm32.dll")]
+		internal static extern IntPtr ImmGetDefaultIMEWnd(IntPtr hWnd);
+		[DllImport("imm32.dll")]
+		[return: MarshalAs(UnmanagedType.Bool)]
+		internal static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hIMC);
+		[DllImport("imm32.dll")]
+		[return: MarshalAs(UnmanagedType.Bool)]
+		static extern bool ImmNotifyIME(IntPtr hIMC, int dwAction, int dwIndex, int dwValue = 0);
+		[DllImport("imm32.dll")]
+		[return: MarshalAs(UnmanagedType.Bool)]
+		static extern bool ImmSetCompositionWindow(IntPtr hIMC, ref CompositionForm form);
+		[DllImport("imm32.dll", CharSet = CharSet.Unicode)]
+		[return: MarshalAs(UnmanagedType.Bool)]
+		static extern bool ImmSetCompositionFont(IntPtr hIMC, ref LOGFONT font);
+		[DllImport("imm32.dll")]
+		[return: MarshalAs(UnmanagedType.Bool)]
+		static extern bool ImmGetCompositionFont(IntPtr hIMC, out LOGFONT font);
+		
+		[DllImport("msctf.dll")]
+		static extern int TF_CreateThreadMgr(out ITfThreadMgr threadMgr);
+		
+		[ThreadStatic] static bool textFrameworkThreadMgrInitialized;
+		[ThreadStatic] static ITfThreadMgr textFrameworkThreadMgr;
+		
+		public static ITfThreadMgr GetTextFrameworkThreadManager()
+		{
+			if (!textFrameworkThreadMgrInitialized) {
+				textFrameworkThreadMgrInitialized = true;
+				TF_CreateThreadMgr(out textFrameworkThreadMgr);
+			}
+			return textFrameworkThreadMgr;
+		}
+		
+		public static bool NotifyIme(IntPtr hIMC)
+		{
+			return ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL);
+		}
+		
+		public static bool SetCompositionWindow(HwndSource source, IntPtr hIMC, TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			Rect textViewBounds = textArea.TextView.GetBounds(source);
+			Rect characterBounds = textArea.TextView.GetCharacterBounds(textArea.Caret.Position, source);
+			CompositionForm form = new CompositionForm();
+			form.dwStyle = 0x0020;
+			form.ptCurrentPos.x = (int)Math.Max(characterBounds.Left, textViewBounds.Left);
+			form.ptCurrentPos.y = (int)Math.Max(characterBounds.Top, textViewBounds.Top);
+			form.rcArea.left = (int)textViewBounds.Left;
+			form.rcArea.top = (int)textViewBounds.Top;
+			form.rcArea.right = (int)textViewBounds.Right;
+			form.rcArea.bottom = (int)textViewBounds.Bottom;
+			return ImmSetCompositionWindow(hIMC, ref form);
+		}
+		
+		public static bool SetCompositionFont(HwndSource source, IntPtr hIMC, TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			LOGFONT lf = new LOGFONT();
+			Rect characterBounds = textArea.TextView.GetCharacterBounds(textArea.Caret.Position, source);
+			lf.lfFaceName = textArea.FontFamily.Source;
+			lf.lfHeight = (int)characterBounds.Height;
+			return ImmSetCompositionFont(hIMC, ref lf);
+		}
+		
+		static Rect GetBounds(this TextView textView, HwndSource source)
+		{
+			// this may happen during layout changes in AvalonDock, so we just return an empty rectangle
+			// in those cases. It should be refreshed immediately.
+			if (source.RootVisual == null || !source.RootVisual.IsAncestorOf(textView))
+				return EMPTY_RECT;
+			Rect displayRect = new Rect(0, 0, textView.ActualWidth, textView.ActualHeight);
+			return textView
+				.TransformToAncestor(source.RootVisual).TransformBounds(displayRect) // rect on root visual
+				.TransformToDevice(source.RootVisual); // rect on HWND
+		}
+		
+		static readonly Rect EMPTY_RECT = new Rect(0, 0, 0, 0);
+		
+		static Rect GetCharacterBounds(this TextView textView, TextViewPosition pos, HwndSource source)
+		{
+			VisualLine vl = textView.GetVisualLine(pos.Line);
+			if (vl == null)
+				return EMPTY_RECT;
+			// this may happen during layout changes in AvalonDock, so we just return an empty rectangle
+			// in those cases. It should be refreshed immediately.
+			if (source.RootVisual == null || !source.RootVisual.IsAncestorOf(textView))
+				return EMPTY_RECT;
+			TextLine line = vl.GetTextLine(pos.VisualColumn, pos.IsAtEndOfLine);
+			Rect displayRect;
+			// calculate the display rect for the current character
+			if (pos.VisualColumn < vl.VisualLengthWithEndOfLineMarker) {
+				displayRect = line.GetTextBounds(pos.VisualColumn, 1).First().Rectangle;
+				displayRect.Offset(0, vl.GetTextLineVisualYPosition(line, VisualYPosition.LineTop));
+			} else {
+				// if we are in virtual space, we just use one wide-space as character width
+				displayRect = new Rect(vl.GetVisualPosition(pos.VisualColumn, VisualYPosition.TextTop),
+				                       new Size(textView.WideSpaceWidth, textView.DefaultLineHeight));
+			}
+			// adjust to current scrolling
+			displayRect.Offset(-textView.ScrollOffset);
+			return textView
+				.TransformToAncestor(source.RootVisual).TransformBounds(displayRect) // rect on root visual
+				.TransformToDevice(source.RootVisual); // rect on HWND
+		}
+	}
+	
+	[ComImport, Guid("aa80e801-2021-11d2-93e0-0060b067b86e"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+	interface ITfThreadMgr
+	{
+		void Activate(out int clientId);
+		void Deactivate();
+		void CreateDocumentMgr(out IntPtr docMgr);
+		void EnumDocumentMgrs(out IntPtr enumDocMgrs);
+		void GetFocus(out IntPtr docMgr);
+		void SetFocus(IntPtr docMgr);
+		void AssociateFocus(IntPtr hwnd, IntPtr newDocMgr, out IntPtr prevDocMgr);
+		void IsThreadFocus([MarshalAs(UnmanagedType.Bool)] out bool isFocus);
+		void GetFunctionProvider(ref Guid classId, out IntPtr funcProvider);
+		void EnumFunctionProviders(out IntPtr enumProviders);
+		void GetGlobalCompartment(out IntPtr compartmentMgr);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/ImeSupport.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/ImeSupport.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/ImeSupport.cs	(revision 11807)
@@ -0,0 +1,165 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Interop;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	class ImeSupport
+	{
+		readonly TextArea textArea;
+		IntPtr currentContext;
+		IntPtr previousContext;
+		IntPtr defaultImeWnd;
+		HwndSource hwndSource;
+		EventHandler requerySuggestedHandler; // we need to keep the event handler instance alive because CommandManager.RequerySuggested uses weak references
+		bool isReadOnly;
+		
+		public ImeSupport(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+			InputMethod.SetIsInputMethodSuspended(this.textArea, textArea.Options.EnableImeSupport);
+			// We listen to CommandManager.RequerySuggested for both caret offset changes and changes to the set of read-only sections.
+			// This is because there's no dedicated event for read-only section changes; but RequerySuggested needs to be raised anyways
+			// to invalidate the Paste command.
+			requerySuggestedHandler = OnRequerySuggested;
+			CommandManager.RequerySuggested += requerySuggestedHandler;
+			textArea.OptionChanged += TextAreaOptionChanged;
+		}
+
+		void OnRequerySuggested(object sender, EventArgs e)
+		{
+			UpdateImeEnabled();
+		}
+		
+		void TextAreaOptionChanged(object sender, PropertyChangedEventArgs e)
+		{
+			if (e.PropertyName == "EnableImeSupport") {
+				InputMethod.SetIsInputMethodSuspended(this.textArea, textArea.Options.EnableImeSupport);
+				UpdateImeEnabled();
+			}
+		}
+		
+		public void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
+		{
+			UpdateImeEnabled();
+		}
+		
+		public void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
+		{
+			if (e.OldFocus == textArea && currentContext != IntPtr.Zero)
+				ImeNativeWrapper.NotifyIme(currentContext);
+			ClearContext();
+		}
+		
+		void UpdateImeEnabled()
+		{
+			if (textArea.Options.EnableImeSupport && textArea.IsKeyboardFocused) {
+				bool newReadOnly = !textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
+				if (hwndSource == null || isReadOnly != newReadOnly) {
+					ClearContext(); // clear existing context (on read-only change)
+					isReadOnly = newReadOnly;
+					CreateContext();
+				}
+			} else {
+				ClearContext();
+			}
+		}
+		
+		void ClearContext()
+		{
+			if (hwndSource != null) {
+				ImeNativeWrapper.ImmAssociateContext(hwndSource.Handle, previousContext);
+				ImeNativeWrapper.ImmReleaseContext(defaultImeWnd, currentContext);
+				currentContext = IntPtr.Zero;
+				defaultImeWnd = IntPtr.Zero;
+				hwndSource.RemoveHook(WndProc);
+				hwndSource = null;
+			}
+		}
+		
+		void CreateContext()
+		{
+			hwndSource = (HwndSource)PresentationSource.FromVisual(this.textArea);
+			if (hwndSource != null) {
+				if (isReadOnly) {
+					defaultImeWnd = IntPtr.Zero;
+					currentContext = IntPtr.Zero;
+				} else {
+					defaultImeWnd = ImeNativeWrapper.ImmGetDefaultIMEWnd(IntPtr.Zero);
+					currentContext = ImeNativeWrapper.ImmGetContext(defaultImeWnd);
+				}
+				previousContext = ImeNativeWrapper.ImmAssociateContext(hwndSource.Handle, currentContext);
+				hwndSource.AddHook(WndProc);
+				// UpdateCompositionWindow() will be called by the caret becoming visible
+				
+				var threadMgr = ImeNativeWrapper.GetTextFrameworkThreadManager();
+				if (threadMgr != null) {
+					// Even though the docu says passing null is invalid, this seems to help
+					// activating the IME on the default input context that is shared with WPF
+					threadMgr.SetFocus(IntPtr.Zero);
+				}
+			}
+		}
+		
+		IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+		{
+			switch (msg) {
+				case ImeNativeWrapper.WM_INPUTLANGCHANGE:
+					// Don't mark the message as handled; other windows
+					// might want to handle it as well.
+					
+					// If we have a context, recreate it
+					if (hwndSource != null) {
+						ClearContext();
+						CreateContext();
+					}
+					break;
+				case ImeNativeWrapper.WM_IME_COMPOSITION:
+					UpdateCompositionWindow();
+					break;
+			}
+			return IntPtr.Zero;
+		}
+		
+		public void UpdateCompositionWindow()
+		{
+			if (currentContext != IntPtr.Zero) {
+				ImeNativeWrapper.SetCompositionFont(hwndSource, currentContext, textArea);
+				ImeNativeWrapper.SetCompositionWindow(hwndSource, currentContext, textArea);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/LineNumberMargin.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/LineNumberMargin.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/LineNumberMargin.cs	(revision 11807)
@@ -0,0 +1,260 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Margin showing line numbers.
+	/// </summary>
+	public class LineNumberMargin : AbstractMargin, IWeakEventListener
+	{
+		static LineNumberMargin()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(LineNumberMargin),
+			                                         new FrameworkPropertyMetadata(typeof(LineNumberMargin)));
+		}
+		
+		TextArea textArea;
+		
+		/// <summary>
+		/// The typeface used for rendering the line number margin.
+		/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
+		/// </summary>
+		protected Typeface typeface;
+		
+		/// <summary>
+		/// The font size used for rendering the line number margin.
+		/// This field is calculated in MeasureOverride() based on the FontFamily etc. properties.
+		/// </summary>
+		protected double emSize;
+		
+		/// <inheritdoc/>
+		protected override Size MeasureOverride(Size availableSize)
+		{
+			typeface = this.CreateTypeface();
+			emSize = (double)GetValue(TextBlock.FontSizeProperty);
+			
+			FormattedText text = TextFormatterFactory.CreateFormattedText(
+				this,
+				new string('9', maxLineNumberLength),
+				typeface,
+				emSize,
+				(Brush)GetValue(Control.ForegroundProperty)
+			);
+			return new Size(text.Width, 0);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			TextView textView = this.TextView;
+			Size renderSize = this.RenderSize;
+			if (textView != null && textView.VisualLinesValid) {
+				var foreground = (Brush)GetValue(Control.ForegroundProperty);
+				foreach (VisualLine line in textView.VisualLines) {
+					int lineNumber = line.FirstDocumentLine.LineNumber;
+					FormattedText text = TextFormatterFactory.CreateFormattedText(
+						this,
+						lineNumber.ToString(CultureInfo.CurrentCulture),
+						typeface, emSize, foreground
+					);
+					double y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
+					drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
+				}
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView)
+		{
+			if (oldTextView != null) {
+				oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
+			}
+			base.OnTextViewChanged(oldTextView, newTextView);
+			if (newTextView != null) {
+				newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
+				
+				// find the text area belonging to the new text view
+				textArea = newTextView.GetService(typeof(TextArea)) as TextArea;
+			} else {
+				textArea = null;
+			}
+			InvalidateVisual();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
+		{
+			if (oldDocument != null) {
+				PropertyChangedEventManager.RemoveListener(oldDocument, this, "LineCount");
+			}
+			base.OnDocumentChanged(oldDocument, newDocument);
+			if (newDocument != null) {
+				PropertyChangedEventManager.AddListener(newDocument, this, "LineCount");
+			}
+			OnDocumentLineCountChanged();
+		}
+		
+		/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
+		protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(PropertyChangedEventManager)) {
+				OnDocumentLineCountChanged();
+				return true;
+			}
+			return false;
+		}
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			return ReceiveWeakEvent(managerType, sender, e);
+		}
+		
+		/// <summary>
+		/// Maximum length of a line number, in characters
+		/// </summary>
+		protected int maxLineNumberLength = 1;
+		
+		void OnDocumentLineCountChanged()
+		{
+			int documentLineCount = Document != null ? Document.LineCount : 1;
+			int newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;
+			
+			// The margin looks too small when there is only one digit, so always reserve space for
+			// at least two digits
+			if (newLength < 2)
+				newLength = 2;
+			
+			if (newLength != maxLineNumberLength) {
+				maxLineNumberLength = newLength;
+				InvalidateMeasure();
+			}
+		}
+		
+		void TextViewVisualLinesChanged(object sender, EventArgs e)
+		{
+			InvalidateVisual();
+		}
+		
+		AnchorSegment selectionStart;
+		bool selecting;
+		
+		/// <inheritdoc/>
+		protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
+		{
+			base.OnMouseLeftButtonDown(e);
+			if (!e.Handled && TextView != null && textArea != null) {
+				e.Handled = true;
+				textArea.Focus();
+				
+				SimpleSegment currentSeg = GetTextLineSegment(e);
+				if (currentSeg == SimpleSegment.Invalid)
+					return;
+				textArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
+				if (CaptureMouse()) {
+					selecting = true;
+					selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
+					if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) {
+						SimpleSelection simpleSelection = textArea.Selection as SimpleSelection;
+						if (simpleSelection != null)
+							selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment);
+					}
+					textArea.Selection = Selection.Create(textArea, selectionStart);
+					if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) {
+						ExtendSelection(currentSeg);
+					}
+				}
+			}
+		}
+		
+		SimpleSegment GetTextLineSegment(MouseEventArgs e)
+		{
+			Point pos = e.GetPosition(TextView);
+			pos.X = 0;
+			pos.Y += TextView.VerticalOffset;
+			VisualLine vl = TextView.GetVisualLineFromVisualTop(pos.Y);
+			if (vl == null)
+				return SimpleSegment.Invalid;
+			TextLine tl = vl.GetTextLineByVisualYPosition(pos.Y);
+			int visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
+			int visualEndColumn = visualStartColumn + tl.Length;
+			int relStart = vl.FirstDocumentLine.Offset;
+			int startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
+			int endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
+			if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
+				endOffset += vl.LastDocumentLine.DelimiterLength;
+			return new SimpleSegment(startOffset, endOffset - startOffset);
+		}
+		
+		void ExtendSelection(SimpleSegment currentSeg)
+		{
+			if (currentSeg.Offset < selectionStart.Offset) {
+				textArea.Caret.Offset = currentSeg.Offset;
+				textArea.Selection = Selection.Create(textArea, currentSeg.Offset, selectionStart.Offset + selectionStart.Length);
+			} else {
+				textArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
+				textArea.Selection = Selection.Create(textArea, selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnMouseMove(MouseEventArgs e)
+		{
+			if (selecting && textArea != null && TextView != null) {
+				e.Handled = true;
+				SimpleSegment currentSeg = GetTextLineSegment(e);
+				if (currentSeg == SimpleSegment.Invalid)
+					return;
+				ExtendSelection(currentSeg);
+			}
+			base.OnMouseMove(e);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
+		{
+			if (selecting) {
+				selecting = false;
+				selectionStart = null;
+				ReleaseMouseCapture();
+				e.Handled = true;
+			}
+			base.OnMouseLeftButtonUp(e);
+		}
+		
+		/// <inheritdoc/>
+		protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
+		{
+			// accept clicks even when clicking on the background
+			return new PointHitTestResult(this, hitTestParameters.HitPoint);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/NoReadOnlySections.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/NoReadOnlySections.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/NoReadOnlySections.cs	(revision 11807)
@@ -0,0 +1,66 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// <see cref="IReadOnlySectionProvider"/> that has no read-only sections; all text is editable.
+	/// </summary>
+	sealed class NoReadOnlySections : IReadOnlySectionProvider
+	{
+		public static readonly NoReadOnlySections Instance = new NoReadOnlySections();
+		
+		public bool CanInsert(int offset)
+		{
+			return true;
+		}
+		
+		public IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			// the segment is always deletable
+			return ExtensionMethods.Sequence(segment);
+		}
+	}
+	
+	/// <summary>
+	/// <see cref="IReadOnlySectionProvider"/> that completely disables editing.
+	/// </summary>
+	sealed class ReadOnlySectionDocument : IReadOnlySectionProvider
+	{
+		public static readonly ReadOnlySectionDocument Instance = new ReadOnlySectionDocument();
+		
+		public bool CanInsert(int offset)
+		{
+			return false;
+		}
+		
+		public IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
+		{
+			return Enumerable.Empty<ISegment>();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/RectangleSelection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/RectangleSelection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/RectangleSelection.cs	(revision 11807)
@@ -0,0 +1,417 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Rectangular selection ("box selection").
+	/// </summary>
+	public sealed class RectangleSelection : Selection
+	{
+		#region Commands
+		/// <summary>
+		/// Expands the selection left by one character, creating a rectangular selection.
+		/// Key gesture: Alt+Shift+Left
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectLeftByCharacter = Command("BoxSelectLeftByCharacter");
+		
+		/// <summary>
+		/// Expands the selection right by one character, creating a rectangular selection.
+		/// Key gesture: Alt+Shift+Right
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectRightByCharacter = Command("BoxSelectRightByCharacter");
+		
+		/// <summary>
+		/// Expands the selection left by one word, creating a rectangular selection.
+		/// Key gesture: Ctrl+Alt+Shift+Left
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectLeftByWord = Command("BoxSelectLeftByWord");
+		
+		/// <summary>
+		/// Expands the selection left by one word, creating a rectangular selection.
+		/// Key gesture: Ctrl+Alt+Shift+Right
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectRightByWord = Command("BoxSelectRightByWord");
+		
+		/// <summary>
+		/// Expands the selection up by one line, creating a rectangular selection.
+		/// Key gesture: Alt+Shift+Up
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectUpByLine = Command("BoxSelectUpByLine");
+		
+		/// <summary>
+		/// Expands the selection up by one line, creating a rectangular selection.
+		/// Key gesture: Alt+Shift+Down
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectDownByLine = Command("BoxSelectDownByLine");
+		
+		/// <summary>
+		/// Expands the selection to the start of the line, creating a rectangular selection.
+		/// Key gesture: Alt+Shift+Home
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectToLineStart = Command("BoxSelectToLineStart");
+		
+		/// <summary>
+		/// Expands the selection to the end of the line, creating a rectangular selection.
+		/// Key gesture: Alt+Shift+End
+		/// </summary>
+		public static readonly RoutedUICommand BoxSelectToLineEnd = Command("BoxSelectToLineEnd");
+		
+		static RoutedUICommand Command(string name)
+		{
+			return new RoutedUICommand(name, name, typeof(RectangleSelection));
+		}
+		#endregion
+		
+		TextDocument document;
+		readonly int startLine, endLine;
+		readonly double startXPos, endXPos;
+		readonly int topLeftOffset, bottomRightOffset;
+		readonly TextViewPosition start, end;
+		
+		readonly List<SelectionSegment> segments = new List<SelectionSegment>();
+		
+		#region Constructors
+		/// <summary>
+		/// Creates a new rectangular selection.
+		/// </summary>
+		public RectangleSelection(TextArea textArea, TextViewPosition start, TextViewPosition end)
+			: base(textArea)
+		{
+			InitDocument();
+			this.startLine = start.Line;
+			this.endLine = end.Line;
+			this.startXPos = GetXPos(textArea, start);
+			this.endXPos = GetXPos(textArea, end);
+			CalculateSegments();
+			this.topLeftOffset = this.segments.First().StartOffset;
+			this.bottomRightOffset = this.segments.Last().EndOffset;
+			
+			this.start = start;
+			this.end = end;
+		}
+		
+		private RectangleSelection(TextArea textArea, int startLine, double startXPos, TextViewPosition end)
+			: base(textArea)
+		{
+			InitDocument();
+			this.startLine = startLine;
+			this.endLine = end.Line;
+			this.startXPos = startXPos;
+			this.endXPos = GetXPos(textArea, end);
+			CalculateSegments();
+			this.topLeftOffset = this.segments.First().StartOffset;
+			this.bottomRightOffset = this.segments.Last().EndOffset;
+			
+			this.start = GetStart();
+			this.end = end;
+		}
+		
+		private RectangleSelection(TextArea textArea, TextViewPosition start, int endLine, double endXPos)
+			: base(textArea)
+		{
+			InitDocument();
+			this.startLine = start.Line;
+			this.endLine = endLine;
+			this.startXPos = GetXPos(textArea, start);
+			this.endXPos = endXPos;
+			CalculateSegments();
+			this.topLeftOffset = this.segments.First().StartOffset;
+			this.bottomRightOffset = this.segments.Last().EndOffset;
+			
+			this.start = start;
+			this.end = GetEnd();
+		}
+		
+		void InitDocument()
+		{
+			document = textArea.Document;
+			if (document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+		}
+		
+		static double GetXPos(TextArea textArea, TextViewPosition pos)
+		{
+			DocumentLine documentLine = textArea.Document.GetLineByNumber(pos.Line);
+			VisualLine visualLine = textArea.TextView.GetOrConstructVisualLine(documentLine);
+			int vc = visualLine.ValidateVisualColumn(pos, true);
+			TextLine textLine = visualLine.GetTextLine(vc, pos.IsAtEndOfLine);
+			return visualLine.GetTextLineVisualXPosition(textLine, vc);
+		}
+		
+		void CalculateSegments()
+		{
+			DocumentLine nextLine = document.GetLineByNumber(Math.Min(startLine, endLine));
+			do {
+				VisualLine vl = textArea.TextView.GetOrConstructVisualLine(nextLine);
+				int startVC = vl.GetVisualColumn(new Point(startXPos, 0), true);
+				int endVC = vl.GetVisualColumn(new Point(endXPos, 0), true);
+				
+				int baseOffset = vl.FirstDocumentLine.Offset;
+				int startOffset = baseOffset + vl.GetRelativeOffset(startVC);
+				int endOffset = baseOffset + vl.GetRelativeOffset(endVC);
+				segments.Add(new SelectionSegment(startOffset, startVC, endOffset, endVC));
+				
+				nextLine = vl.LastDocumentLine.NextLine;
+			} while (nextLine != null && nextLine.LineNumber <= Math.Max(startLine, endLine));
+		}
+		
+		TextViewPosition GetStart()
+		{
+			SelectionSegment segment = (startLine < endLine ? segments.First() : segments.Last());
+			if (startXPos < endXPos) {
+				return new TextViewPosition(document.GetLocation(segment.StartOffset), segment.StartVisualColumn);
+			} else {
+				return new TextViewPosition(document.GetLocation(segment.EndOffset), segment.EndVisualColumn);
+			}
+		}
+		
+		TextViewPosition GetEnd()
+		{
+			SelectionSegment segment = (startLine < endLine ? segments.Last() : segments.First());
+			if (startXPos < endXPos) {
+				return new TextViewPosition(document.GetLocation(segment.EndOffset), segment.EndVisualColumn);
+			} else {
+				return new TextViewPosition(document.GetLocation(segment.StartOffset), segment.StartVisualColumn);
+			}
+		}
+		#endregion
+		
+		/// <inheritdoc/>
+		public override string GetText()
+		{
+			StringBuilder b = new StringBuilder();
+			foreach (ISegment s in this.Segments) {
+				if (b.Length > 0)
+					b.AppendLine();
+				b.Append(document.GetText(s));
+			}
+			return b.ToString();
+		}
+		
+		/// <inheritdoc/>
+		public override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
+		{
+			return SetEndpoint(endPosition);
+		}
+		
+		/// <inheritdoc/>
+		public override int Length {
+			get {
+				return this.Segments.Sum(s => s.Length);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override bool EnableVirtualSpace {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override ISegment SurroundingSegment {
+			get {
+				return new SimpleSegment(topLeftOffset, bottomRightOffset - topLeftOffset);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override IEnumerable<SelectionSegment> Segments {
+			get { return segments; }
+		}
+		
+		/// <inheritdoc/>
+		public override TextViewPosition StartPosition {
+			get { return start; }
+		}
+		
+		/// <inheritdoc/>
+		public override TextViewPosition EndPosition {
+			get { return end; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			RectangleSelection r = obj as RectangleSelection;
+			return r != null && r.textArea == this.textArea
+				&& r.topLeftOffset == this.topLeftOffset && r.bottomRightOffset == this.bottomRightOffset
+				&& r.startLine == this.startLine && r.endLine == this.endLine
+				&& r.startXPos == this.startXPos && r.endXPos == this.endXPos;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			return topLeftOffset ^ bottomRightOffset;
+		}
+		
+		/// <inheritdoc/>
+		public override Selection SetEndpoint(TextViewPosition endPosition)
+		{
+			return new RectangleSelection(textArea, startLine, startXPos, endPosition);
+		}
+		
+		int GetVisualColumnFromXPos(int line, double xPos)
+		{
+			var vl = textArea.TextView.GetOrConstructVisualLine(textArea.Document.GetLineByNumber(line));
+			return vl.GetVisualColumn(new Point(xPos, 0), true);
+		}
+		
+		/// <inheritdoc/>
+		public override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
+		{
+			TextLocation newStartLocation = textArea.Document.GetLocation(e.GetNewOffset(topLeftOffset, AnchorMovementType.AfterInsertion));
+			TextLocation newEndLocation = textArea.Document.GetLocation(e.GetNewOffset(bottomRightOffset, AnchorMovementType.BeforeInsertion));
+			
+			return new RectangleSelection(textArea,
+			                              new TextViewPosition(newStartLocation, GetVisualColumnFromXPos(newStartLocation.Line, startXPos)),
+			                              new TextViewPosition(newEndLocation, GetVisualColumnFromXPos(newEndLocation.Line, endXPos)));
+		}
+		
+		/// <inheritdoc/>
+		public override void ReplaceSelectionWithText(string newText)
+		{
+			if (newText == null)
+				throw new ArgumentNullException("newText");
+			using (textArea.Document.RunUpdate()) {
+				TextViewPosition start = new TextViewPosition(document.GetLocation(topLeftOffset), GetVisualColumnFromXPos(startLine, startXPos));
+				TextViewPosition end = new TextViewPosition(document.GetLocation(bottomRightOffset), GetVisualColumnFromXPos(endLine, endXPos));
+				int insertionLength;
+				int totalInsertionLength = 0;
+				int firstInsertionLength = 0;
+				int editOffset = Math.Min(topLeftOffset, bottomRightOffset);
+				TextViewPosition pos;
+				if (NewLineFinder.NextNewLine(newText, 0) == SimpleSegment.Invalid) {
+					// insert same text into every line
+					foreach (SelectionSegment lineSegment in this.Segments.Reverse()) {
+						ReplaceSingleLineText(textArea, lineSegment, newText, out insertionLength);
+						totalInsertionLength += insertionLength;
+						firstInsertionLength = insertionLength;
+					}
+					
+					int newEndOffset = editOffset + totalInsertionLength;
+					pos = new TextViewPosition(document.GetLocation(editOffset + firstInsertionLength));
+					
+					textArea.Selection = new RectangleSelection(textArea, pos, Math.Max(startLine, endLine), GetXPos(textArea, pos));
+				} else {
+					string[] lines = newText.Split(NewLineFinder.NewlineStrings, segments.Count, StringSplitOptions.None);
+					int line = Math.Min(startLine, endLine);
+					for (int i = lines.Length - 1; i >= 0; i--) {
+						ReplaceSingleLineText(textArea, segments[i], lines[i], out insertionLength);
+						firstInsertionLength = insertionLength;
+					}
+					pos = new TextViewPosition(document.GetLocation(editOffset + firstInsertionLength));
+					textArea.ClearSelection();
+				}
+				textArea.Caret.Position = textArea.TextView.GetPosition(new Point(GetXPos(textArea, pos), textArea.TextView.GetVisualTopByDocumentLine(Math.Max(startLine, endLine)))).GetValueOrDefault();
+			}
+		}
+		
+		void ReplaceSingleLineText(TextArea textArea, SelectionSegment lineSegment, string newText, out int insertionLength)
+		{
+			if (lineSegment.Length == 0) {
+				if (newText.Length > 0 && textArea.ReadOnlySectionProvider.CanInsert(lineSegment.StartOffset)) {
+					newText = AddSpacesIfRequired(newText, new TextViewPosition(document.GetLocation(lineSegment.StartOffset), lineSegment.StartVisualColumn), new TextViewPosition(document.GetLocation(lineSegment.EndOffset), lineSegment.EndVisualColumn));
+					textArea.Document.Insert(lineSegment.StartOffset, newText);
+				}
+			} else {
+				ISegment[] segmentsToDelete = textArea.GetDeletableSegments(lineSegment);
+				for (int i = segmentsToDelete.Length - 1; i >= 0; i--) {
+					if (i == segmentsToDelete.Length - 1) {
+						if (segmentsToDelete[i].Offset == SurroundingSegment.Offset && segmentsToDelete[i].Length == SurroundingSegment.Length) {
+							newText = AddSpacesIfRequired(newText, new TextViewPosition(document.GetLocation(lineSegment.StartOffset), lineSegment.StartVisualColumn), new TextViewPosition(document.GetLocation(lineSegment.EndOffset), lineSegment.EndVisualColumn));
+						}
+						textArea.Document.Replace(segmentsToDelete[i], newText);
+					} else {
+						textArea.Document.Remove(segmentsToDelete[i]);
+					}
+				}
+			}
+			insertionLength = newText.Length;
+		}
+		
+		/// <summary>
+		/// Performs a rectangular paste operation.
+		/// </summary>
+		public static bool PerformRectangularPaste(TextArea textArea, TextViewPosition startPosition, string text, bool selectInsertedText)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			if (text == null)
+				throw new ArgumentNullException("text");
+			int newLineCount = text.Count(c => c == '\n'); // TODO might not work in all cases, but single \r line endings are really rare today.
+			TextLocation endLocation = new TextLocation(startPosition.Line + newLineCount, startPosition.Column);
+			if (endLocation.Line <= textArea.Document.LineCount) {
+				int endOffset = textArea.Document.GetOffset(endLocation);
+				if (textArea.Selection.EnableVirtualSpace || textArea.Document.GetLocation(endOffset) == endLocation) {
+					RectangleSelection rsel = new RectangleSelection(textArea, startPosition, endLocation.Line, GetXPos(textArea, startPosition));
+					rsel.ReplaceSelectionWithText(text);
+					if (selectInsertedText && textArea.Selection is RectangleSelection) {
+						RectangleSelection sel = (RectangleSelection)textArea.Selection;
+						textArea.Selection = new RectangleSelection(textArea, startPosition, sel.endLine, sel.endXPos);
+					}
+					return true;
+				}
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Gets the name of the entry in the DataObject that signals rectangle selections.
+		/// </summary>
+		public const string RectangularSelectionDataType = "AvalonEditRectangularSelection";
+		
+		/// <inheritdoc/>
+		public override System.Windows.DataObject CreateDataObject(TextArea textArea)
+		{
+			var data = base.CreateDataObject(textArea);
+			
+			if (EditingCommandHandler.ConfirmDataFormat(textArea, data, RectangularSelectionDataType)) {
+				MemoryStream isRectangle = new MemoryStream(1);
+				isRectangle.WriteByte(1);
+				data.SetData(RectangularSelectionDataType, isRectangle, false);
+			}
+			return data;
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			// It's possible that ToString() gets called on old (invalid) selections, e.g. for "change from... to..." debug message
+			// make sure we don't crash even when the desired locations don't exist anymore.
+			return string.Format("[RectangleSelection {0} {1} {2} to {3} {4} {5}]", startLine, topLeftOffset, startXPos, endLine, bottomRightOffset, endXPos);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/Selection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/Selection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/Selection.cs	(revision 11807)
@@ -0,0 +1,302 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Windows;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Highlighting;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Base class for selections.
+	/// </summary>
+	public abstract class Selection
+	{
+		/// <summary>
+		/// Creates a new simple selection that selects the text from startOffset to endOffset.
+		/// </summary>
+		public static Selection Create(TextArea textArea, int startOffset, int endOffset)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			if (startOffset == endOffset)
+				return textArea.emptySelection;
+			else
+				return new SimpleSelection(textArea,
+				                           new TextViewPosition(textArea.Document.GetLocation(startOffset)),
+				                           new TextViewPosition(textArea.Document.GetLocation(endOffset)));
+		}
+		
+		internal static Selection Create(TextArea textArea, TextViewPosition start, TextViewPosition end)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			if (textArea.Document.GetOffset(start.Location) == textArea.Document.GetOffset(end.Location) && start.VisualColumn == end.VisualColumn)
+				return textArea.emptySelection;
+			else
+				return new SimpleSelection(textArea, start, end);
+		}
+		
+		/// <summary>
+		/// Creates a new simple selection that selects the text in the specified segment.
+		/// </summary>
+		public static Selection Create(TextArea textArea, ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return Create(textArea, segment.Offset, segment.EndOffset);
+		}
+		
+		internal readonly TextArea textArea;
+		
+		/// <summary>
+		/// Constructor for Selection.
+		/// </summary>
+		protected Selection(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+		}
+		
+		/// <summary>
+		/// Gets the start position of the selection.
+		/// </summary>
+		public abstract TextViewPosition StartPosition { get; }
+		
+		/// <summary>
+		/// Gets the end position of the selection.
+		/// </summary>
+		public abstract TextViewPosition EndPosition { get; }
+		
+		/// <summary>
+		/// Gets the selected text segments.
+		/// </summary>
+		public abstract IEnumerable<SelectionSegment> Segments { get; }
+		
+		/// <summary>
+		/// Gets the smallest segment that contains all segments in this selection.
+		/// May return null if the selection is empty.
+		/// </summary>
+		public abstract ISegment SurroundingSegment { get; }
+		
+		/// <summary>
+		/// Replaces the selection with the specified text.
+		/// </summary>
+		public abstract void ReplaceSelectionWithText(string newText);
+		
+		internal string AddSpacesIfRequired(string newText, TextViewPosition start, TextViewPosition end)
+		{
+			if (EnableVirtualSpace && InsertVirtualSpaces(newText, start, end)) {
+				var line = textArea.Document.GetLineByNumber(start.Line);
+				string lineText = textArea.Document.GetText(line);
+				var vLine = textArea.TextView.GetOrConstructVisualLine(line);
+				int colDiff = start.VisualColumn - vLine.VisualLengthWithEndOfLineMarker;
+				if (colDiff > 0) {
+					string additionalSpaces = "";
+					if (!textArea.Options.ConvertTabsToSpaces && lineText.Trim('\t').Length == 0) {
+						int tabCount = (int)(colDiff / textArea.Options.IndentationSize);
+						additionalSpaces = new string('\t', tabCount);
+						colDiff -= tabCount * textArea.Options.IndentationSize;
+					}
+					additionalSpaces += new string(' ', colDiff);
+					return additionalSpaces + newText;
+				}
+			}
+			return newText;
+		}
+		
+		bool InsertVirtualSpaces(string newText, TextViewPosition start, TextViewPosition end)
+		{
+			return (!string.IsNullOrEmpty(newText) || !(IsInVirtualSpace(start) && IsInVirtualSpace(end)))
+				&& newText != "\r\n"
+				&& newText != "\n"
+				&& newText != "\r";
+		}
+		
+		bool IsInVirtualSpace(TextViewPosition pos)
+		{
+			return pos.VisualColumn > textArea.TextView.GetOrConstructVisualLine(textArea.Document.GetLineByNumber(pos.Line)).VisualLength;
+		}
+		
+		/// <summary>
+		/// Updates the selection when the document changes.
+		/// </summary>
+		public abstract Selection UpdateOnDocumentChange(DocumentChangeEventArgs e);
+		
+		/// <summary>
+		/// Gets whether the selection is empty.
+		/// </summary>
+		public virtual bool IsEmpty {
+			get { return Length == 0; }
+		}
+		
+		/// <summary>
+		/// Gets whether virtual space is enabled for this selection.
+		/// </summary>
+		public virtual bool EnableVirtualSpace {
+			get { return textArea.Options.EnableVirtualSpace; }
+		}
+		
+		/// <summary>
+		/// Gets the selection length.
+		/// </summary>
+		public abstract int Length { get; }
+		
+		/// <summary>
+		/// Returns a new selection with the changed end point.
+		/// </summary>
+		/// <exception cref="NotSupportedException">Cannot set endpoint for empty selection</exception>
+		public abstract Selection SetEndpoint(TextViewPosition endPosition);
+		
+		/// <summary>
+		/// If this selection is empty, starts a new selection from <paramref name="startPosition"/> to
+		/// <paramref name="endPosition"/>, otherwise, changes the endpoint of this selection.
+		/// </summary>
+		public abstract Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition);
+		
+		/// <summary>
+		/// Gets whether the selection is multi-line.
+		/// </summary>
+		public virtual bool IsMultiline {
+			get {
+				ISegment surroundingSegment = this.SurroundingSegment;
+				if (surroundingSegment == null)
+					return false;
+				int start = surroundingSegment.Offset;
+				int end = start + surroundingSegment.Length;
+				var document = textArea.Document;
+				if (document == null)
+					throw ThrowUtil.NoDocumentAssigned();
+				return document.GetLineByOffset(start) != document.GetLineByOffset(end);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the selected text.
+		/// </summary>
+		public virtual string GetText()
+		{
+			var document = textArea.Document;
+			if (document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			StringBuilder b = null;
+			string text = null;
+			foreach (ISegment s in Segments) {
+				if (text != null) {
+					if (b == null)
+						b = new StringBuilder(text);
+					else
+						b.Append(text);
+				}
+				text = document.GetText(s);
+			}
+			if (b != null) {
+				if (text != null) b.Append(text);
+				return b.ToString();
+			} else {
+				return text ?? string.Empty;
+			}
+		}
+		
+		/// <summary>
+		/// Creates a HTML fragment for the selected text.
+		/// </summary>
+		public string CreateHtmlFragment(HtmlOptions options)
+		{
+			if (options == null)
+				throw new ArgumentNullException("options");
+			IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
+			StringBuilder html = new StringBuilder();
+			bool first = true;
+			foreach (ISegment selectedSegment in this.Segments) {
+				if (first)
+					first = false;
+				else
+					html.AppendLine("<br>");
+				html.Append(HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, selectedSegment, options));
+			}
+			return html.ToString();
+		}
+		
+		/// <inheritdoc/>
+		public abstract override bool Equals(object obj);
+		
+		/// <inheritdoc/>
+		public abstract override int GetHashCode();
+		
+		/// <summary>
+		/// Gets whether the specified offset is included in the selection.
+		/// </summary>
+		/// <returns>True, if the selection contains the offset (selection borders inclusive);
+		/// otherwise, false.</returns>
+		public virtual bool Contains(int offset)
+		{
+			if (this.IsEmpty)
+				return false;
+			if (this.SurroundingSegment.Contains(offset, 0)) {
+				foreach (ISegment s in this.Segments) {
+					if (s.Contains(offset, 0)) {
+						return true;
+					}
+				}
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Creates a data object containing the selection's text.
+		/// </summary>
+		public virtual DataObject CreateDataObject(TextArea textArea)
+		{
+			DataObject data = new DataObject();
+			
+			// Ensure we use the appropriate newline sequence for the OS
+			string text = TextUtilities.NormalizeNewLines(GetText(), Environment.NewLine);
+			
+			// Enable drag/drop to Word, Notepad++ and others
+			if (EditingCommandHandler.ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) {
+				data.SetText(text);
+			}
+			
+			// Enable drag/drop to SciTe:
+			// We cannot use SetText, thus we need to use typeof(string).FullName as data format.
+			// new DataObject(object) calls SetData(object), which in turn calls SetData(Type, data),
+			// which then uses Type.FullName as format.
+			// We immitate that behavior here as well:
+			if (EditingCommandHandler.ConfirmDataFormat(textArea, data, typeof(string).FullName)) {
+				data.SetData(typeof(string).FullName, text);
+			}
+			
+			// Also copy text in HTML format to clipboard - good for pasting text into Word
+			// or to the SharpDevelop forums.
+			if (EditingCommandHandler.ConfirmDataFormat(textArea, data, DataFormats.Html)) {
+				HtmlClipboard.SetHtml(data, CreateHtmlFragment(new HtmlOptions(textArea.Options)));
+			}
+			return data;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionColorizer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionColorizer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionColorizer.cs	(revision 11807)
@@ -0,0 +1,74 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Rendering;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	sealed class SelectionColorizer : ColorizingTransformer
+	{
+		TextArea textArea;
+		
+		public SelectionColorizer(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+		}
+		
+		protected override void Colorize(ITextRunConstructionContext context)
+		{
+			// if SelectionForeground is null, keep the existing foreground color
+			if (textArea.SelectionForeground == null)
+				return;
+			
+			int lineStartOffset = context.VisualLine.FirstDocumentLine.Offset;
+			int lineEndOffset = context.VisualLine.LastDocumentLine.Offset + context.VisualLine.LastDocumentLine.TotalLength;
+			
+			foreach (SelectionSegment segment in textArea.Selection.Segments) {
+				int segmentStart = segment.StartOffset;
+				int segmentEnd = segment.EndOffset;
+				if (segmentEnd <= lineStartOffset)
+					continue;
+				if (segmentStart >= lineEndOffset)
+					continue;
+				int startColumn;
+				if (segmentStart < lineStartOffset)
+					startColumn = 0;
+				else
+					startColumn = context.VisualLine.ValidateVisualColumn(segment.StartOffset, segment.StartVisualColumn, textArea.Selection.EnableVirtualSpace);
+				
+				int endColumn;
+				if (segmentEnd > lineEndOffset)
+					endColumn = textArea.Selection.EnableVirtualSpace ? int.MaxValue : context.VisualLine.VisualLengthWithEndOfLineMarker;
+				else
+					endColumn = context.VisualLine.ValidateVisualColumn(segment.EndOffset, segment.EndVisualColumn, textArea.Selection.EnableVirtualSpace);
+				
+				ChangeVisualElements(
+					startColumn, endColumn,
+					element => {
+						element.TextRunProperties.SetForegroundBrush(textArea.SelectionForeground);
+					});
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionLayer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionLayer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionLayer.cs	(revision 11807)
@@ -0,0 +1,68 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media;
+
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	sealed class SelectionLayer : Layer, IWeakEventListener
+	{
+		readonly TextArea textArea;
+		
+		public SelectionLayer(TextArea textArea) : base(textArea.TextView, KnownLayer.Selection)
+		{
+			this.IsHitTestVisible = false;
+			
+			this.textArea = textArea;
+			TextViewWeakEventManager.VisualLinesChanged.AddListener(textView, this);
+			TextViewWeakEventManager.ScrollOffsetChanged.AddListener(textView, this);
+		}
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextViewWeakEventManager.VisualLinesChanged)
+			    || managerType == typeof(TextViewWeakEventManager.ScrollOffsetChanged))
+			{
+				InvalidateVisual();
+				return true;
+			}
+			return false;
+		}
+		
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			base.OnRender(drawingContext);
+			
+			BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder();
+			geoBuilder.AlignToMiddleOfPixels = true;
+			geoBuilder.ExtendToFullWidthAtLineEnd = textArea.Selection.EnableVirtualSpace;
+			geoBuilder.CornerRadius = textArea.SelectionCornerRadius;
+			foreach (var segment in textArea.Selection.Segments) {
+				geoBuilder.AddSegment(textView, segment);
+			}
+			Geometry geometry = geoBuilder.CreateGeometry();
+			if (geometry != null) {
+				drawingContext.DrawGeometry(textArea.SelectionBrush, textArea.SelectionBorder, geometry);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionMouseHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionMouseHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionMouseHandler.cs	(revision 11807)
@@ -0,0 +1,676 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Handles selection of text using the mouse.
+	/// </summary>
+	sealed class SelectionMouseHandler : ITextAreaInputHandler
+	{
+		#region enum SelectionMode
+		enum SelectionMode
+		{
+			/// <summary>
+			/// no selection (no mouse button down)
+			/// </summary>
+			None,
+			/// <summary>
+			/// left mouse button down on selection, might be normal click
+			/// or might be drag'n'drop
+			/// </summary>
+			PossibleDragStart,
+			/// <summary>
+			/// dragging text
+			/// </summary>
+			Drag,
+			/// <summary>
+			/// normal selection (click+drag)
+			/// </summary>
+			Normal,
+			/// <summary>
+			/// whole-word selection (double click+drag or ctrl+click+drag)
+			/// </summary>
+			WholeWord,
+			/// <summary>
+			/// whole-line selection (triple click+drag)
+			/// </summary>
+			WholeLine,
+			/// <summary>
+			/// rectangular selection (alt+click+drag)
+			/// </summary>
+			Rectangular
+		}
+		#endregion
+		
+		readonly TextArea textArea;
+		
+		SelectionMode mode;
+		AnchorSegment startWord;
+		Point possibleDragStartMousePos;
+		
+		#region Constructor + Attach + Detach
+		public SelectionMouseHandler(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+		}
+		
+		public TextArea TextArea {
+			get { return textArea; }
+		}
+		
+		public void Attach()
+		{
+			textArea.MouseLeftButtonDown += textArea_MouseLeftButtonDown;
+			textArea.MouseMove += textArea_MouseMove;
+			textArea.MouseLeftButtonUp += textArea_MouseLeftButtonUp;
+			textArea.QueryCursor += textArea_QueryCursor;
+			textArea.OptionChanged += textArea_OptionChanged;
+			
+			enableTextDragDrop = textArea.Options.EnableTextDragDrop;
+			if (enableTextDragDrop) {
+				AttachDragDrop();
+			}
+		}
+		
+		public void Detach()
+		{
+			mode = SelectionMode.None;
+			textArea.MouseLeftButtonDown -= textArea_MouseLeftButtonDown;
+			textArea.MouseMove -= textArea_MouseMove;
+			textArea.MouseLeftButtonUp -= textArea_MouseLeftButtonUp;
+			textArea.QueryCursor -= textArea_QueryCursor;
+			textArea.OptionChanged -= textArea_OptionChanged;
+			if (enableTextDragDrop) {
+				DetachDragDrop();
+			}
+		}
+		
+		void AttachDragDrop()
+		{
+			textArea.AllowDrop = true;
+			textArea.GiveFeedback += textArea_GiveFeedback;
+			textArea.QueryContinueDrag += textArea_QueryContinueDrag;
+			textArea.DragEnter += textArea_DragEnter;
+			textArea.DragOver += textArea_DragOver;
+			textArea.DragLeave += textArea_DragLeave;
+			textArea.Drop += textArea_Drop;
+		}
+		
+		void DetachDragDrop()
+		{
+			textArea.AllowDrop = false;
+			textArea.GiveFeedback -= textArea_GiveFeedback;
+			textArea.QueryContinueDrag -= textArea_QueryContinueDrag;
+			textArea.DragEnter -= textArea_DragEnter;
+			textArea.DragOver -= textArea_DragOver;
+			textArea.DragLeave -= textArea_DragLeave;
+			textArea.Drop -= textArea_Drop;
+		}
+		
+		bool enableTextDragDrop;
+		
+		void textArea_OptionChanged(object sender, PropertyChangedEventArgs e)
+		{
+			bool newEnableTextDragDrop = textArea.Options.EnableTextDragDrop;
+			if (newEnableTextDragDrop != enableTextDragDrop) {
+				enableTextDragDrop = newEnableTextDragDrop;
+				if (newEnableTextDragDrop)
+					AttachDragDrop();
+				else
+					DetachDragDrop();
+			}
+		}
+		#endregion
+		
+		#region Dropping text
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
+		void textArea_DragEnter(object sender, DragEventArgs e)
+		{
+			try {
+				e.Effects = GetEffect(e);
+				textArea.Caret.Show();
+			} catch (Exception ex) {
+				OnDragException(ex);
+			}
+		}
+
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
+		void textArea_DragOver(object sender, DragEventArgs e)
+		{
+			try {
+				e.Effects = GetEffect(e);
+			} catch (Exception ex) {
+				OnDragException(ex);
+			}
+		}
+		
+		DragDropEffects GetEffect(DragEventArgs e)
+		{
+			if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) {
+				e.Handled = true;
+				int visualColumn;
+				bool isAtEndOfLine;
+				int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
+				if (offset >= 0) {
+					textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
+					textArea.Caret.DesiredXPos = double.NaN;
+					if (textArea.ReadOnlySectionProvider.CanInsert(offset)) {
+						if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move
+						    && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey)
+						{
+							return DragDropEffects.Move;
+						} else {
+							return e.AllowedEffects & DragDropEffects.Copy;
+						}
+					}
+				}
+			}
+			return DragDropEffects.None;
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
+		void textArea_DragLeave(object sender, DragEventArgs e)
+		{
+			try {
+				e.Handled = true;
+				if (!textArea.IsKeyboardFocusWithin)
+					textArea.Caret.Hide();
+			} catch (Exception ex) {
+				OnDragException(ex);
+			}
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
+		void textArea_Drop(object sender, DragEventArgs e)
+		{
+			try {
+				DragDropEffects effect = GetEffect(e);
+				e.Effects = effect;
+				if (effect != DragDropEffects.None) {
+					string text = e.Data.GetData(DataFormats.UnicodeText, true) as string;
+					if (text != null) {
+						int start = textArea.Caret.Offset;
+						if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) {
+							Debug.WriteLine("Drop: did not drop: drop target is inside selection");
+							e.Effects = DragDropEffects.None;
+						} else {
+							Debug.WriteLine("Drop: insert at " + start);
+							
+							bool rectangular = e.Data.GetDataPresent(RectangleSelection.RectangularSelectionDataType);
+							
+							string newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
+							text = TextUtilities.NormalizeNewLines(text, newLine);
+							
+							string pasteFormat;
+							// fill the suggested DataFormat used for the paste action:
+							if (rectangular)
+								pasteFormat = RectangleSelection.RectangularSelectionDataType;
+							else
+								pasteFormat = DataFormats.UnicodeText;
+							
+							var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, pasteFormat);
+							textArea.RaiseEvent(pastingEventArgs);
+							if (pastingEventArgs.CommandCancelled)
+								return;
+							
+							// DataObject.PastingEvent handlers might have changed the format to apply.
+							rectangular = pastingEventArgs.FormatToApply == RectangleSelection.RectangularSelectionDataType;
+							
+							// Mark the undo group with the currentDragDescriptor, if the drag
+							// is originating from the same control. This allows combining
+							// the undo groups when text is moved.
+							textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor);
+							try {
+								if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {
+									
+								} else {
+									textArea.Document.Insert(start, text);
+									textArea.Selection = Selection.Create(textArea, start, start + text.Length);
+								}
+							} finally {
+								textArea.Document.UndoStack.EndUndoGroup();
+							}
+						}
+						e.Handled = true;
+					}
+				}
+			} catch (Exception ex) {
+				OnDragException(ex);
+			}
+		}
+		
+		void OnDragException(Exception ex)
+		{
+			// WPF swallows exceptions during drag'n'drop or reports them incorrectly, so
+			// we re-throw them later to allow the application's unhandled exception handler
+			// to catch them
+			textArea.Dispatcher.BeginInvoke(
+				DispatcherPriority.Send,
+				new Action(delegate {
+				           	throw new DragDropException("Exception during drag'n'drop", ex);
+				           }));
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
+		void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e)
+		{
+			try {
+				e.UseDefaultCursors = true;
+				e.Handled = true;
+			} catch (Exception ex) {
+				OnDragException(ex);
+			}
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
+		void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
+		{
+			try {
+				if (e.EscapePressed) {
+					e.Action = DragAction.Cancel;
+				} else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) {
+					e.Action = DragAction.Drop;
+				} else {
+					e.Action = DragAction.Continue;
+				}
+				e.Handled = true;
+			} catch (Exception ex) {
+				OnDragException(ex);
+			}
+		}
+		#endregion
+		
+		#region Start Drag
+		object currentDragDescriptor;
+		
+		void StartDrag()
+		{
+			// prevent nested StartDrag calls
+			mode = SelectionMode.Drag;
+			
+			// mouse capture and Drag'n'Drop doesn't mix
+			textArea.ReleaseMouseCapture();
+			
+			DataObject dataObject = textArea.Selection.CreateDataObject(textArea);
+			
+			DragDropEffects allowedEffects = DragDropEffects.All;
+			var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList();
+			foreach (ISegment s in deleteOnMove) {
+				ISegment[] result = textArea.GetDeletableSegments(s);
+				if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
+					allowedEffects &= ~DragDropEffects.Move;
+				}
+			}
+			
+			var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
+			textArea.RaiseEvent(copyingEventArgs);
+			if (copyingEventArgs.CommandCancelled)
+				return;
+			
+			object dragDescriptor = new object();
+			this.currentDragDescriptor = dragDescriptor;
+			
+			DragDropEffects resultEffect;
+			using (textArea.AllowCaretOutsideSelection()) {
+				var oldCaretPosition = textArea.Caret.Position;
+				try {
+					Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
+					resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
+					Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
+				} catch (COMException ex) {
+					// ignore COM errors - don't crash on badly implemented drop targets
+					Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
+					return;
+				}
+				if (resultEffect == DragDropEffects.None) {
+					// reset caret if drag was aborted
+					textArea.Caret.Position = oldCaretPosition;
+				}
+			}
+			
+			this.currentDragDescriptor = null;
+			
+			if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
+				bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor);
+				if (draggedInsideSingleDocument)
+					textArea.Document.UndoStack.StartContinuedUndoGroup(null);
+				textArea.Document.BeginUpdate();
+				try {
+					foreach (ISegment s in deleteOnMove) {
+						textArea.Document.Remove(s.Offset, s.Length);
+					}
+				} finally {
+					textArea.Document.EndUpdate();
+					if (draggedInsideSingleDocument)
+						textArea.Document.UndoStack.EndUndoGroup();
+				}
+			}
+		}
+		#endregion
+		
+		#region QueryCursor
+		// provide the IBeam Cursor for the text area
+		void textArea_QueryCursor(object sender, QueryCursorEventArgs e)
+		{
+			if (!e.Handled) {
+				if (mode != SelectionMode.None || !enableTextDragDrop) {
+					e.Cursor = Cursors.IBeam;
+					e.Handled = true;
+				} else if (textArea.TextView.VisualLinesValid) {
+					// Only query the cursor if the visual lines are valid.
+					// If they are invalid, the cursor will get re-queried when the visual lines
+					// get refreshed.
+					Point p = e.GetPosition(textArea.TextView);
+					if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) {
+						int visualColumn;
+						bool isAtEndOfLine;
+						int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
+						if (textArea.Selection.Contains(offset))
+							e.Cursor = Cursors.Arrow;
+						else
+							e.Cursor = Cursors.IBeam;
+						e.Handled = true;
+					}
+				}
+			}
+		}
+		#endregion
+		
+		#region LeftButtonDown
+		void textArea_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+		{
+			mode = SelectionMode.None;
+			if (!e.Handled && e.ChangedButton == MouseButton.Left) {
+				ModifierKeys modifiers = Keyboard.Modifiers;
+				bool shift = (modifiers & ModifierKeys.Shift) == ModifierKeys.Shift;
+				if (enableTextDragDrop && e.ClickCount == 1 && !shift) {
+					int visualColumn;
+					bool isAtEndOfLine;
+					int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
+					if (textArea.Selection.Contains(offset)) {
+						if (textArea.CaptureMouse()) {
+							mode = SelectionMode.PossibleDragStart;
+							possibleDragStartMousePos = e.GetPosition(textArea);
+						}
+						e.Handled = true;
+						return;
+					}
+				}
+				
+				var oldPosition = textArea.Caret.Position;
+				SetCaretOffsetToMousePosition(e);
+				
+				
+				if (!shift) {
+					textArea.ClearSelection();
+				}
+				if (textArea.CaptureMouse()) {
+					if ((modifiers & ModifierKeys.Alt) == ModifierKeys.Alt && textArea.Options.EnableRectangularSelection) {
+						mode = SelectionMode.Rectangular;
+						if (shift && textArea.Selection is RectangleSelection) {
+							textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
+						}
+					} else if (e.ClickCount == 1 && ((modifiers & ModifierKeys.Control) == 0)) {
+						mode = SelectionMode.Normal;
+						if (shift && !(textArea.Selection is RectangleSelection)) {
+							textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
+						}
+					} else {
+						SimpleSegment startWord;
+						if (e.ClickCount == 3) {
+							mode = SelectionMode.WholeLine;
+							startWord = GetLineAtMousePosition(e);
+						} else {
+							mode = SelectionMode.WholeWord;
+							startWord = GetWordAtMousePosition(e);
+						}
+						if (startWord == SimpleSegment.Invalid) {
+							mode = SelectionMode.None;
+							textArea.ReleaseMouseCapture();
+							return;
+						}
+						if (shift && !textArea.Selection.IsEmpty) {
+							if (startWord.Offset < textArea.Selection.SurroundingSegment.Offset) {
+								textArea.Selection = textArea.Selection.SetEndpoint(new TextViewPosition(textArea.Document.GetLocation(startWord.Offset)));
+							} else if (startWord.EndOffset > textArea.Selection.SurroundingSegment.EndOffset) {
+								textArea.Selection = textArea.Selection.SetEndpoint(new TextViewPosition(textArea.Document.GetLocation(startWord.EndOffset)));
+							}
+							this.startWord = new AnchorSegment(textArea.Document, textArea.Selection.SurroundingSegment);
+						} else {
+							textArea.Selection = Selection.Create(textArea, startWord.Offset, startWord.EndOffset);
+							this.startWord = new AnchorSegment(textArea.Document, startWord.Offset, startWord.Length);
+						}
+					}
+				}
+			}
+			e.Handled = true;
+		}
+		#endregion
+		
+		#region Mouse Position <-> Text coordinates
+		SimpleSegment GetWordAtMousePosition(MouseEventArgs e)
+		{
+			TextView textView = textArea.TextView;
+			if (textView == null) return SimpleSegment.Invalid;
+			Point pos = e.GetPosition(textView);
+			if (pos.Y < 0)
+				pos.Y = 0;
+			if (pos.Y > textView.ActualHeight)
+				pos.Y = textView.ActualHeight;
+			pos += textView.ScrollOffset;
+			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
+			if (line != null) {
+				int visualColumn = line.GetVisualColumn(pos, textArea.Selection.EnableVirtualSpace);
+				int wordStartVC = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, textArea.Selection.EnableVirtualSpace);
+				if (wordStartVC == -1)
+					wordStartVC = 0;
+				int wordEndVC = line.GetNextCaretPosition(wordStartVC, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, textArea.Selection.EnableVirtualSpace);
+				if (wordEndVC == -1)
+					wordEndVC = line.VisualLength;
+				int relOffset = line.FirstDocumentLine.Offset;
+				int wordStartOffset = line.GetRelativeOffset(wordStartVC) + relOffset;
+				int wordEndOffset = line.GetRelativeOffset(wordEndVC) + relOffset;
+				return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset);
+			} else {
+				return SimpleSegment.Invalid;
+			}
+		}
+		
+		SimpleSegment GetLineAtMousePosition(MouseEventArgs e)
+		{
+			TextView textView = textArea.TextView;
+			if (textView == null) return SimpleSegment.Invalid;
+			Point pos = e.GetPosition(textView);
+			if (pos.Y < 0)
+				pos.Y = 0;
+			if (pos.Y > textView.ActualHeight)
+				pos.Y = textView.ActualHeight;
+			pos += textView.ScrollOffset;
+			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
+			if (line != null) {
+				return new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset);
+			} else {
+				return SimpleSegment.Invalid;
+			}
+		}
+		
+		int GetOffsetFromMousePosition(MouseEventArgs e, out int visualColumn, out bool isAtEndOfLine)
+		{
+			return GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine);
+		}
+		
+		int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine)
+		{
+			visualColumn = 0;
+			TextView textView = textArea.TextView;
+			Point pos = positionRelativeToTextView;
+			if (pos.Y < 0)
+				pos.Y = 0;
+			if (pos.Y > textView.ActualHeight)
+				pos.Y = textView.ActualHeight;
+			pos += textView.ScrollOffset;
+			if (pos.Y > textView.DocumentHeight)
+				pos.Y = textView.DocumentHeight - ExtensionMethods.Epsilon;
+			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
+			if (line != null) {
+				visualColumn = line.GetVisualColumn(pos, textArea.Selection.EnableVirtualSpace, out isAtEndOfLine);
+				return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
+			}
+			isAtEndOfLine = false;
+			return -1;
+		}
+		
+		int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn)
+		{
+			visualColumn = 0;
+			TextView textView = textArea.TextView;
+			Point pos = positionRelativeToTextView;
+			if (pos.Y < 0)
+				pos.Y = 0;
+			if (pos.Y > textView.ActualHeight)
+				pos.Y = textView.ActualHeight;
+			pos += textView.ScrollOffset;
+			if (pos.Y > textView.DocumentHeight)
+				pos.Y = textView.DocumentHeight - ExtensionMethods.Epsilon;
+			VisualLine line = textView.GetVisualLineFromVisualTop(pos.Y);
+			if (line != null) {
+				visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, textArea.Selection.EnableVirtualSpace);
+				return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset;
+			}
+			return -1;
+		}
+		#endregion
+		
+		#region MouseMove
+		void textArea_MouseMove(object sender, MouseEventArgs e)
+		{
+			if (e.Handled)
+				return;
+			if (mode == SelectionMode.Normal || mode == SelectionMode.WholeWord || mode == SelectionMode.WholeLine || mode == SelectionMode.Rectangular) {
+				e.Handled = true;
+				if (textArea.TextView.VisualLinesValid) {
+					// If the visual lines are not valid, don't extend the selection.
+					// Extending the selection forces a VisualLine refresh, and it is sufficient
+					// to do that on MouseUp, we don't have to do it every MouseMove.
+					ExtendSelectionToMouse(e);
+				}
+			} else if (mode == SelectionMode.PossibleDragStart) {
+				e.Handled = true;
+				Vector mouseMovement = e.GetPosition(textArea) - possibleDragStartMousePos;
+				if (Math.Abs(mouseMovement.X) > SystemParameters.MinimumHorizontalDragDistance
+				    || Math.Abs(mouseMovement.Y) > SystemParameters.MinimumVerticalDragDistance)
+				{
+					StartDrag();
+				}
+			}
+		}
+		#endregion
+		
+		#region ExtendSelection
+		void SetCaretOffsetToMousePosition(MouseEventArgs e)
+		{
+			SetCaretOffsetToMousePosition(e, null);
+		}
+		
+		void SetCaretOffsetToMousePosition(MouseEventArgs e, ISegment allowedSegment)
+		{
+			int visualColumn;
+			bool isAtEndOfLine;
+			int offset;
+			if (mode == SelectionMode.Rectangular) {
+				offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(textArea.TextView), out visualColumn);
+				isAtEndOfLine = true;
+			} else {
+				offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine);
+			}
+			if (allowedSegment != null) {
+				offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset);
+			}
+			if (offset >= 0) {
+				textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine };
+				textArea.Caret.DesiredXPos = double.NaN;
+			}
+		}
+		
+		void ExtendSelectionToMouse(MouseEventArgs e)
+		{
+			TextViewPosition oldPosition = textArea.Caret.Position;
+			if (mode == SelectionMode.Normal || mode == SelectionMode.Rectangular) {
+				SetCaretOffsetToMousePosition(e);
+				if (mode == SelectionMode.Normal && textArea.Selection is RectangleSelection)
+					textArea.Selection = new SimpleSelection(textArea, oldPosition, textArea.Caret.Position);
+				else if (mode == SelectionMode.Rectangular && !(textArea.Selection is RectangleSelection))
+					textArea.Selection = new RectangleSelection(textArea, oldPosition, textArea.Caret.Position);
+				else
+					textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
+			} else if (mode == SelectionMode.WholeWord || mode == SelectionMode.WholeLine) {
+				var newWord = (mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
+				if (newWord != SimpleSegment.Invalid) {
+					textArea.Selection = Selection.Create(textArea,
+					                                      Math.Min(newWord.Offset, startWord.Offset),
+					                                      Math.Max(newWord.EndOffset, startWord.EndOffset));
+					// Set caret offset, but limit the caret to stay inside the selection.
+					// in whole-word selection, it's otherwise possible that we get the caret outside the
+					// selection - but the TextArea doesn't like that and will reset the selection, causing
+					// flickering.
+					SetCaretOffsetToMousePosition(e, textArea.Selection.SurroundingSegment);
+				}
+			}
+			textArea.Caret.BringCaretToView(5.0);
+		}
+		#endregion
+		
+		#region MouseLeftButtonUp
+		void textArea_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+		{
+			if (mode == SelectionMode.None || e.Handled)
+				return;
+			e.Handled = true;
+			if (mode == SelectionMode.PossibleDragStart) {
+				// -> this was not a drag start (mouse didn't move after mousedown)
+				SetCaretOffsetToMousePosition(e);
+				textArea.ClearSelection();
+			} else if (mode == SelectionMode.Normal || mode == SelectionMode.WholeWord || mode == SelectionMode.WholeLine || mode == SelectionMode.Rectangular) {
+				ExtendSelectionToMouse(e);
+			}
+			mode = SelectionMode.None;
+			textArea.ReleaseMouseCapture();
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SelectionSegment.cs	(revision 11807)
@@ -0,0 +1,108 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Represents a selected segment.
+	/// </summary>
+	public class SelectionSegment : ISegment
+	{
+		readonly int startOffset, endOffset;
+		readonly int startVC, endVC;
+		
+		/// <summary>
+		/// Creates a SelectionSegment from two offsets.
+		/// </summary>
+		public SelectionSegment(int startOffset, int endOffset)
+		{
+			this.startOffset = Math.Min(startOffset, endOffset);
+			this.endOffset = Math.Max(startOffset, endOffset);
+			this.startVC = this.endVC = -1;
+		}
+		
+		/// <summary>
+		/// Creates a SelectionSegment from two offsets and visual columns.
+		/// </summary>
+		public SelectionSegment(int startOffset, int startVC, int endOffset, int endVC)
+		{
+			if (startOffset < endOffset || (startOffset == endOffset && startVC <= endVC)) {
+				this.startOffset = startOffset;
+				this.startVC = startVC;
+				this.endOffset = endOffset;
+				this.endVC = endVC;
+			} else {
+				this.startOffset = endOffset;
+				this.startVC = endVC;
+				this.endOffset = startOffset;
+				this.endVC = startVC;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the start offset.
+		/// </summary>
+		public int StartOffset {
+			get { return startOffset; }
+		}
+		
+		/// <summary>
+		/// Gets the end offset.
+		/// </summary>
+		public int EndOffset {
+			get { return endOffset; }
+		}
+		
+		/// <summary>
+		/// Gets the start visual column.
+		/// </summary>
+		public int StartVisualColumn {
+			get { return startVC; }
+		}
+		
+		/// <summary>
+		/// Gets the end visual column.
+		/// </summary>
+		public int EndVisualColumn {
+			get { return endVC; }
+		}
+		
+		/// <inheritdoc/>
+		int ISegment.Offset {
+			get { return startOffset; }
+		}
+		
+		/// <inheritdoc/>
+		public int Length {
+			get { return endOffset - startOffset; }
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format("[SelectionSegment StartOffset={0}, EndOffset={1}, StartVC={2}, EndVC={3}]", startOffset, endOffset, startVC, endVC);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SimpleSelection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SimpleSelection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/SimpleSelection.cs	(revision 11807)
@@ -0,0 +1,174 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// A simple selection.
+	/// </summary>
+	public sealed class SimpleSelection : Selection
+	{
+		readonly TextViewPosition start, end;
+		readonly int startOffset, endOffset;
+		
+		/// <summary>
+		/// Creates a new SimpleSelection instance.
+		/// </summary>
+		public SimpleSelection(TextArea textArea, TextViewPosition start, TextViewPosition end)
+			: base(textArea)
+		{
+			this.start = start;
+			this.end = end;
+			this.startOffset = textArea.Document.GetOffset(start.Location);
+			this.endOffset = textArea.Document.GetOffset(end.Location);
+		}
+		
+		/// <inheritdoc/>
+		public override IEnumerable<SelectionSegment> Segments {
+			get {
+				return ExtensionMethods.Sequence<SelectionSegment>(new SelectionSegment(startOffset, start.VisualColumn, endOffset, end.VisualColumn));
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override ISegment SurroundingSegment {
+			get {
+				return new SelectionSegment(startOffset, endOffset);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void ReplaceSelectionWithText(string newText)
+		{
+			if (newText == null)
+				throw new ArgumentNullException("newText");
+			using (textArea.Document.RunUpdate()) {
+				ISegment[] segmentsToDelete = textArea.GetDeletableSegments(this.SurroundingSegment);
+				for (int i = segmentsToDelete.Length - 1; i >= 0; i--) {
+					if (i == segmentsToDelete.Length - 1) {
+						if (segmentsToDelete[i].Offset == SurroundingSegment.Offset && segmentsToDelete[i].Length == SurroundingSegment.Length) {
+							newText = AddSpacesIfRequired(newText, start, end);
+						}
+						if (string.IsNullOrEmpty(newText)) {
+							// place caret at the beginning of the selection
+							if (start.CompareTo(end) <= 0)
+								textArea.Caret.Position = start;
+							else
+								textArea.Caret.Position = end;
+						} else {
+							// place caret so that it ends up behind the new text
+							textArea.Caret.Offset = segmentsToDelete[i].EndOffset;
+						}
+						textArea.Document.Replace(segmentsToDelete[i], newText);
+					} else {
+						textArea.Document.Remove(segmentsToDelete[i]);
+					}
+				}
+				if (segmentsToDelete.Length != 0) {
+					textArea.ClearSelection();
+				}
+			}
+		}
+		
+		public override TextViewPosition StartPosition {
+			get { return start; }
+		}
+		
+		public override TextViewPosition EndPosition {
+			get { return end; }
+		}
+		
+		/// <inheritdoc/>
+		public override Selection UpdateOnDocumentChange(DocumentChangeEventArgs e)
+		{
+			if (e == null)
+				throw new ArgumentNullException("e");
+			int newStartOffset, newEndOffset;
+			if (startOffset <= endOffset) {
+				newStartOffset = e.GetNewOffset(startOffset, AnchorMovementType.Default);
+				newEndOffset = Math.Max(newStartOffset, e.GetNewOffset(endOffset, AnchorMovementType.BeforeInsertion));
+			} else {
+				newEndOffset = e.GetNewOffset(endOffset, AnchorMovementType.Default);
+				newStartOffset = Math.Max(newEndOffset, e.GetNewOffset(startOffset, AnchorMovementType.BeforeInsertion));
+			}
+			return Selection.Create(
+				textArea,
+				new TextViewPosition(textArea.Document.GetLocation(newStartOffset), start.VisualColumn),
+				new TextViewPosition(textArea.Document.GetLocation(newEndOffset), end.VisualColumn)
+			);
+		}
+		
+		/// <inheritdoc/>
+		public override bool IsEmpty {
+			get { return startOffset == endOffset && start.VisualColumn == end.VisualColumn; }
+		}
+		
+		/// <inheritdoc/>
+		public override int Length {
+			get {
+				return Math.Abs(endOffset - startOffset);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override Selection SetEndpoint(TextViewPosition endPosition)
+		{
+			return Create(textArea, start, endPosition);
+		}
+		
+		public override Selection StartSelectionOrSetEndpoint(TextViewPosition startPosition, TextViewPosition endPosition)
+		{
+			var document = textArea.Document;
+			if (document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			return Create(textArea, start, endPosition);
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			unchecked {
+				return startOffset * 27811 + endOffset + textArea.GetHashCode();
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			SimpleSelection other = obj as SimpleSelection;
+			if (other == null) return false;
+			return this.start.Equals(other.start) && this.end.Equals(other.end)
+				&& this.startOffset == other.startOffset && this.endOffset == other.endOffset
+				&& this.textArea == other.textArea;
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[SimpleSelection Start=" + start + " End=" + end + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextArea.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextArea.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextArea.cs	(revision 11807)
@@ -0,0 +1,1138 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Indentation;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+using ICSharpCode.NRefactory;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Control that wraps a TextView and adds support for user input and the caret.
+	/// </summary>
+	public class TextArea : Control, IScrollInfo, IWeakEventListener, ITextEditorComponent, IServiceProvider
+	{
+		internal readonly ImeSupport ime;
+		
+		#region Constructor
+		static TextArea()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(TextArea),
+			                                         new FrameworkPropertyMetadata(typeof(TextArea)));
+			KeyboardNavigation.IsTabStopProperty.OverrideMetadata(
+				typeof(TextArea), new FrameworkPropertyMetadata(Boxes.True));
+			KeyboardNavigation.TabNavigationProperty.OverrideMetadata(
+				typeof(TextArea), new FrameworkPropertyMetadata(KeyboardNavigationMode.None));
+			FocusableProperty.OverrideMetadata(
+				typeof(TextArea), new FrameworkPropertyMetadata(Boxes.True));
+		}
+		
+		/// <summary>
+		/// Creates a new TextArea instance.
+		/// </summary>
+		public TextArea() : this(new TextView())
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new TextArea instance.
+		/// </summary>
+		protected TextArea(TextView textView)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			this.textView = textView;
+			this.Options = textView.Options;
+			
+			selection = emptySelection = new EmptySelection(this);
+			
+			textView.Services.AddService(typeof(TextArea), this);
+			
+			textView.LineTransformers.Add(new SelectionColorizer(this));
+			textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
+			
+			caret = new Caret(this);
+			caret.PositionChanged += (sender, e) => RequestSelectionValidation();
+			caret.PositionChanged += CaretPositionChanged;
+			AttachTypingEvents();
+			ime = new ImeSupport(this);
+			
+			leftMargins.CollectionChanged += leftMargins_CollectionChanged;
+			
+			this.DefaultInputHandler = new TextAreaDefaultInputHandler(this);
+			this.ActiveInputHandler = this.DefaultInputHandler;
+		}
+		#endregion
+		
+		#region InputHandler management
+		/// <summary>
+		/// Gets the default input handler.
+		/// </summary>
+		/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
+		public TextAreaDefaultInputHandler DefaultInputHandler { get; private set; }
+		
+		ITextAreaInputHandler activeInputHandler;
+		bool isChangingInputHandler;
+		
+		/// <summary>
+		/// Gets/Sets the active input handler.
+		/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
+		/// </summary>
+		/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
+		public ITextAreaInputHandler ActiveInputHandler {
+			get { return activeInputHandler; }
+			set {
+				if (value != null && value.TextArea != this)
+					throw new ArgumentException("The input handler was created for a different text area than this one.");
+				if (isChangingInputHandler)
+					throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
+				if (activeInputHandler != value) {
+					isChangingInputHandler = true;
+					try {
+						// pop the whole stack
+						PopStackedInputHandler(stackedInputHandlers.LastOrDefault());
+						Debug.Assert(stackedInputHandlers.IsEmpty);
+						
+						if (activeInputHandler != null)
+							activeInputHandler.Detach();
+						activeInputHandler = value;
+						if (value != null)
+							value.Attach();
+					} finally {
+						isChangingInputHandler = false;
+					}
+					if (ActiveInputHandlerChanged != null)
+						ActiveInputHandlerChanged(this, EventArgs.Empty);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Occurs when the ActiveInputHandler property changes.
+		/// </summary>
+		public event EventHandler ActiveInputHandlerChanged;
+		
+		ImmutableStack<TextAreaStackedInputHandler> stackedInputHandlers = ImmutableStack<TextAreaStackedInputHandler>.Empty;
+		
+		/// <summary>
+		/// Gets the list of currently active stacked input handlers.
+		/// </summary>
+		/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
+		public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers {
+			get { return stackedInputHandlers; }
+		}
+		
+		/// <summary>
+		/// Pushes an input handler onto the list of stacked input handlers.
+		/// </summary>
+		/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
+		public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
+		{
+			if (inputHandler == null)
+				throw new ArgumentNullException("inputHandler");
+			stackedInputHandlers = stackedInputHandlers.Push(inputHandler);
+			inputHandler.Attach();
+		}
+		
+		/// <summary>
+		/// Pops the stacked input handler (and all input handlers above it).
+		/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
+		/// does nothing.
+		/// </summary>
+		/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
+		public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
+		{
+			if (stackedInputHandlers.Any(i => i == inputHandler)) {
+				ITextAreaInputHandler oldHandler;
+				do {
+					oldHandler = stackedInputHandlers.Peek();
+					stackedInputHandlers = stackedInputHandlers.Pop();
+					oldHandler.Detach();
+				} while (oldHandler != inputHandler);
+			}
+		}
+		#endregion
+		
+		#region Document property
+		/// <summary>
+		/// Document property.
+		/// </summary>
+		public static readonly DependencyProperty DocumentProperty
+			= TextView.DocumentProperty.AddOwner(typeof(TextArea), new FrameworkPropertyMetadata(OnDocumentChanged));
+		
+		/// <summary>
+		/// Gets/Sets the document displayed by the text editor.
+		/// </summary>
+		public TextDocument Document {
+			get { return (TextDocument)GetValue(DocumentProperty); }
+			set { SetValue(DocumentProperty, value); }
+		}
+		
+		/// <inheritdoc/>
+		public event EventHandler DocumentChanged;
+		
+		static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			((TextArea)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
+		}
+		
+		void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
+		{
+			if (oldValue != null) {
+				TextDocumentWeakEventManager.Changing.RemoveListener(oldValue, this);
+				TextDocumentWeakEventManager.Changed.RemoveListener(oldValue, this);
+				TextDocumentWeakEventManager.UpdateStarted.RemoveListener(oldValue, this);
+				TextDocumentWeakEventManager.UpdateFinished.RemoveListener(oldValue, this);
+			}
+			textView.Document = newValue;
+			if (newValue != null) {
+				TextDocumentWeakEventManager.Changing.AddListener(newValue, this);
+				TextDocumentWeakEventManager.Changed.AddListener(newValue, this);
+				TextDocumentWeakEventManager.UpdateStarted.AddListener(newValue, this);
+				TextDocumentWeakEventManager.UpdateFinished.AddListener(newValue, this);
+			}
+			// Reset caret location and selection: this is necessary because the caret/selection might be invalid
+			// in the new document (e.g. if new document is shorter than the old document).
+			caret.Location = new TextLocation(1, 1);
+			this.ClearSelection();
+			if (DocumentChanged != null)
+				DocumentChanged(this, EventArgs.Empty);
+			CommandManager.InvalidateRequerySuggested();
+		}
+		#endregion
+		
+		#region Options property
+		/// <summary>
+		/// Options property.
+		/// </summary>
+		public static readonly DependencyProperty OptionsProperty
+			= TextView.OptionsProperty.AddOwner(typeof(TextArea), new FrameworkPropertyMetadata(OnOptionsChanged));
+		
+		/// <summary>
+		/// Gets/Sets the document displayed by the text editor.
+		/// </summary>
+		public TextEditorOptions Options {
+			get { return (TextEditorOptions)GetValue(OptionsProperty); }
+			set { SetValue(OptionsProperty, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when a text editor option has changed.
+		/// </summary>
+		public event PropertyChangedEventHandler OptionChanged;
+		
+		/// <summary>
+		/// Raises the <see cref="OptionChanged"/> event.
+		/// </summary>
+		protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
+		{
+			if (OptionChanged != null) {
+				OptionChanged(this, e);
+			}
+		}
+		
+		static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			((TextArea)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
+		}
+		
+		void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
+		{
+			if (oldValue != null) {
+				PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
+			}
+			textView.Options = newValue;
+			if (newValue != null) {
+				PropertyChangedWeakEventManager.AddListener(newValue, this);
+			}
+			OnOptionChanged(new PropertyChangedEventArgs(null));
+		}
+		#endregion
+		
+		#region ReceiveWeakEvent
+		/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
+		protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextDocumentWeakEventManager.Changing)) {
+				OnDocumentChanging();
+				return true;
+			} else if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
+				OnDocumentChanged((DocumentChangeEventArgs)e);
+				return true;
+			} else if (managerType == typeof(TextDocumentWeakEventManager.UpdateStarted)) {
+				OnUpdateStarted();
+				return true;
+			} else if (managerType == typeof(TextDocumentWeakEventManager.UpdateFinished)) {
+				OnUpdateFinished();
+				return true;
+			} else if (managerType == typeof(PropertyChangedWeakEventManager)) {
+				OnOptionChanged((PropertyChangedEventArgs)e);
+				return true;
+			}
+			return false;
+		}
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			return ReceiveWeakEvent(managerType, sender, e);
+		}
+		#endregion
+		
+		#region Caret handling on document changes
+		void OnDocumentChanging()
+		{
+			caret.OnDocumentChanging();
+		}
+		
+		void OnDocumentChanged(DocumentChangeEventArgs e)
+		{
+			caret.OnDocumentChanged(e);
+			this.Selection = selection.UpdateOnDocumentChange(e);
+		}
+		
+		void OnUpdateStarted()
+		{
+			Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
+		}
+		
+		void OnUpdateFinished()
+		{
+			caret.OnDocumentUpdateFinished();
+		}
+		
+		sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
+		{
+			// keep textarea in weak reference because the IUndoableOperation is stored with the document
+			WeakReference textAreaReference;
+			TextViewPosition caretPosition;
+			Selection selection;
+			
+			public RestoreCaretAndSelectionUndoAction(TextArea textArea)
+			{
+				this.textAreaReference = new WeakReference(textArea);
+				// Just save the old caret position, no need to validate here.
+				// If we restore it, we'll validate it anyways.
+				this.caretPosition = textArea.Caret.NonValidatedPosition;
+				this.selection = textArea.Selection;
+			}
+			
+			public void Undo()
+			{
+				TextArea textArea = (TextArea)textAreaReference.Target;
+				if (textArea != null) {
+					textArea.Caret.Position = caretPosition;
+					textArea.Selection = selection;
+				}
+			}
+			
+			public void Redo()
+			{
+				// redo=undo: we just restore the caret/selection state
+				Undo();
+			}
+		}
+		#endregion
+		
+		#region TextView property
+		readonly TextView textView;
+		IScrollInfo scrollInfo;
+
+		/// <summary>
+		/// Gets the text view used to display text in this text area.
+		/// </summary>
+		public TextView TextView {
+			get {
+				return textView;
+			}
+		}
+		/// <inheritdoc/>
+		public override void OnApplyTemplate()
+		{
+			base.OnApplyTemplate();
+			scrollInfo = textView;
+			ApplyScrollInfo();
+		}
+		#endregion
+		
+		#region Selection property
+		internal readonly Selection emptySelection;
+		Selection selection;
+		
+		/// <summary>
+		/// Occurs when the selection has changed.
+		/// </summary>
+		public event EventHandler SelectionChanged;
+		
+		/// <summary>
+		/// Gets/Sets the selection in this text area.
+		/// </summary>
+		
+		public Selection Selection {
+			get { return selection; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				if (value.textArea != this)
+					throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
+				if (!object.Equals(selection, value)) {
+//					Debug.WriteLine("Selection change from " + selection + " to " + value);
+					if (textView != null) {
+						ISegment oldSegment = selection.SurroundingSegment;
+						ISegment newSegment = value.SurroundingSegment;
+						if (!Selection.EnableVirtualSpace && (selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) {
+							// perf optimization:
+							// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
+							int oldSegmentOffset = oldSegment.Offset;
+							int newSegmentOffset = newSegment.Offset;
+							if (oldSegmentOffset != newSegmentOffset) {
+								textView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
+								                Math.Abs(oldSegmentOffset - newSegmentOffset),
+								                DispatcherPriority.Background);
+							}
+							int oldSegmentEndOffset = oldSegment.EndOffset;
+							int newSegmentEndOffset = newSegment.EndOffset;
+							if (oldSegmentEndOffset != newSegmentEndOffset) {
+								textView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
+								                Math.Abs(oldSegmentEndOffset - newSegmentEndOffset),
+								                DispatcherPriority.Background);
+							}
+						} else {
+							textView.Redraw(oldSegment, DispatcherPriority.Background);
+							textView.Redraw(newSegment, DispatcherPriority.Background);
+						}
+					}
+					selection = value;
+					if (SelectionChanged != null)
+						SelectionChanged(this, EventArgs.Empty);
+					// a selection change causes commands like copy/paste/etc. to change status
+					CommandManager.InvalidateRequerySuggested();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Clears the current selection.
+		/// </summary>
+		public void ClearSelection()
+		{
+			this.Selection = emptySelection;
+		}
+		
+		/// <summary>
+		/// The <see cref="SelectionBrush"/> property.
+		/// </summary>
+		public static readonly DependencyProperty SelectionBrushProperty =
+			DependencyProperty.Register("SelectionBrush", typeof(Brush), typeof(TextArea));
+		
+		/// <summary>
+		/// Gets/Sets the background brush used for the selection.
+		/// </summary>
+		public Brush SelectionBrush {
+			get { return (Brush)GetValue(SelectionBrushProperty); }
+			set { SetValue(SelectionBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// The <see cref="SelectionForeground"/> property.
+		/// </summary>
+		public static readonly DependencyProperty SelectionForegroundProperty =
+			DependencyProperty.Register("SelectionForeground", typeof(Brush), typeof(TextArea));
+		
+		/// <summary>
+		/// Gets/Sets the foreground brush used selected text.
+		/// </summary>
+		public Brush SelectionForeground {
+			get { return (Brush)GetValue(SelectionForegroundProperty); }
+			set { SetValue(SelectionForegroundProperty, value); }
+		}
+		
+		/// <summary>
+		/// The <see cref="SelectionBorder"/> property.
+		/// </summary>
+		public static readonly DependencyProperty SelectionBorderProperty =
+			DependencyProperty.Register("SelectionBorder", typeof(Pen), typeof(TextArea));
+		
+		/// <summary>
+		/// Gets/Sets the background brush used for the selection.
+		/// </summary>
+		public Pen SelectionBorder {
+			get { return (Pen)GetValue(SelectionBorderProperty); }
+			set { SetValue(SelectionBorderProperty, value); }
+		}
+		
+		/// <summary>
+		/// The <see cref="SelectionCornerRadius"/> property.
+		/// </summary>
+		public static readonly DependencyProperty SelectionCornerRadiusProperty =
+			DependencyProperty.Register("SelectionCornerRadius", typeof(double), typeof(TextArea),
+			                            new FrameworkPropertyMetadata(3.0));
+		
+		/// <summary>
+		/// Gets/Sets the corner radius of the selection.
+		/// </summary>
+		public double SelectionCornerRadius {
+			get { return (double)GetValue(SelectionCornerRadiusProperty); }
+			set { SetValue(SelectionCornerRadiusProperty, value); }
+		}
+		#endregion
+		
+		#region Force caret to stay inside selection
+		bool ensureSelectionValidRequested;
+		int allowCaretOutsideSelection;
+		
+		void RequestSelectionValidation()
+		{
+			if (!ensureSelectionValidRequested && allowCaretOutsideSelection == 0) {
+				ensureSelectionValidRequested = true;
+				Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(EnsureSelectionValid));
+			}
+		}
+		
+		/// <summary>
+		/// Code that updates only the caret but not the selection can cause confusion when
+		/// keys like 'Delete' delete the (possibly invisible) selected text and not the
+		/// text around the caret.
+		/// 
+		/// So we'll ensure that the caret is inside the selection.
+		/// (when the caret is not in the selection, we'll clear the selection)
+		/// 
+		/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
+		/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
+		/// it's sufficient to fix it after any event handlers have run.
+		/// </summary>
+		void EnsureSelectionValid()
+		{
+			ensureSelectionValidRequested = false;
+			if (allowCaretOutsideSelection == 0) {
+				if (!selection.IsEmpty && !selection.Contains(caret.Offset)) {
+					Debug.WriteLine("Resetting selection because caret is outside");
+					this.ClearSelection();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Temporarily allows positioning the caret outside the selection.
+		/// Dispose the returned IDisposable to revert the allowance.
+		/// </summary>
+		/// <remarks>
+		/// The text area only forces the caret to be inside the selection when other events
+		/// have finished running (using the dispatcher), so you don't have to use this method
+		/// for temporarily positioning the caret in event handlers.
+		/// This method is only necessary if you want to run the WPF dispatcher, e.g. if you
+		/// perform a drag'n'drop operation.
+		/// </remarks>
+		public IDisposable AllowCaretOutsideSelection()
+		{
+			VerifyAccess();
+			allowCaretOutsideSelection++;
+			return new CallbackOnDispose(
+				delegate {
+					VerifyAccess();
+					allowCaretOutsideSelection--;
+					RequestSelectionValidation();
+				});
+		}
+		#endregion
+		
+		#region Properties
+		readonly Caret caret;
+		
+		/// <summary>
+		/// Gets the Caret used for this text area.
+		/// </summary>
+		public Caret Caret {
+			get { return caret; }
+		}
+		
+		void CaretPositionChanged(object sender, EventArgs e)
+		{
+			if (textView == null)
+				return;
+			
+			this.textView.HighlightedLine = this.Caret.Line;
+		}
+		
+		ObservableCollection<UIElement> leftMargins = new ObservableCollection<UIElement>();
+		
+		/// <summary>
+		/// Gets the collection of margins displayed to the left of the text view.
+		/// </summary>
+		public ObservableCollection<UIElement> LeftMargins {
+			get {
+				return leftMargins;
+			}
+		}
+		
+		void leftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
+		{
+			if (e.OldItems != null) {
+				foreach (ITextViewConnect c in e.OldItems.OfType<ITextViewConnect>()) {
+					c.RemoveFromTextView(textView);
+				}
+			}
+			if (e.NewItems != null) {
+				foreach (ITextViewConnect c in e.NewItems.OfType<ITextViewConnect>()) {
+					c.AddToTextView(textView);
+				}
+			}
+		}
+		
+		IReadOnlySectionProvider readOnlySectionProvider = NoReadOnlySections.Instance;
+		
+		/// <summary>
+		/// Gets/Sets an object that provides read-only sections for the text area.
+		/// </summary>
+		public IReadOnlySectionProvider ReadOnlySectionProvider {
+			get { return readOnlySectionProvider; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				readOnlySectionProvider = value;
+				CommandManager.InvalidateRequerySuggested(); // the read-only status effects Paste.CanExecute and the IME
+			}
+		}
+		#endregion
+		
+		#region IScrollInfo implementation
+		ScrollViewer scrollOwner;
+		bool canVerticallyScroll, canHorizontallyScroll;
+		
+		void ApplyScrollInfo()
+		{
+			if (scrollInfo != null) {
+				scrollInfo.ScrollOwner = scrollOwner;
+				scrollInfo.CanVerticallyScroll = canVerticallyScroll;
+				scrollInfo.CanHorizontallyScroll = canHorizontallyScroll;
+				scrollOwner = null;
+			}
+		}
+		
+		bool IScrollInfo.CanVerticallyScroll {
+			get { return scrollInfo != null ? scrollInfo.CanVerticallyScroll : false; }
+			set {
+				canVerticallyScroll = value;
+				if (scrollInfo != null)
+					scrollInfo.CanVerticallyScroll = value;
+			}
+		}
+		
+		bool IScrollInfo.CanHorizontallyScroll {
+			get { return scrollInfo != null ? scrollInfo.CanHorizontallyScroll : false; }
+			set {
+				canHorizontallyScroll = value;
+				if (scrollInfo != null)
+					scrollInfo.CanHorizontallyScroll = value;
+			}
+		}
+		
+		double IScrollInfo.ExtentWidth {
+			get { return scrollInfo != null ? scrollInfo.ExtentWidth : 0; }
+		}
+		
+		double IScrollInfo.ExtentHeight {
+			get { return scrollInfo != null ? scrollInfo.ExtentHeight : 0; }
+		}
+		
+		double IScrollInfo.ViewportWidth {
+			get { return scrollInfo != null ? scrollInfo.ViewportWidth : 0; }
+		}
+		
+		double IScrollInfo.ViewportHeight {
+			get { return scrollInfo != null ? scrollInfo.ViewportHeight : 0; }
+		}
+		
+		double IScrollInfo.HorizontalOffset {
+			get { return scrollInfo != null ? scrollInfo.HorizontalOffset : 0; }
+		}
+		
+		double IScrollInfo.VerticalOffset {
+			get { return scrollInfo != null ? scrollInfo.VerticalOffset : 0; }
+		}
+		
+		ScrollViewer IScrollInfo.ScrollOwner {
+			get { return scrollInfo != null ? scrollInfo.ScrollOwner : null; }
+			set {
+				if (scrollInfo != null)
+					scrollInfo.ScrollOwner = value;
+				else
+					scrollOwner = value;
+			}
+		}
+		
+		void IScrollInfo.LineUp()
+		{
+			if (scrollInfo != null) scrollInfo.LineUp();
+		}
+		
+		void IScrollInfo.LineDown()
+		{
+			if (scrollInfo != null) scrollInfo.LineDown();
+		}
+		
+		void IScrollInfo.LineLeft()
+		{
+			if (scrollInfo != null) scrollInfo.LineLeft();
+		}
+		
+		void IScrollInfo.LineRight()
+		{
+			if (scrollInfo != null) scrollInfo.LineRight();
+		}
+		
+		void IScrollInfo.PageUp()
+		{
+			if (scrollInfo != null) scrollInfo.PageUp();
+		}
+		
+		void IScrollInfo.PageDown()
+		{
+			if (scrollInfo != null) scrollInfo.PageDown();
+		}
+		
+		void IScrollInfo.PageLeft()
+		{
+			if (scrollInfo != null) scrollInfo.PageLeft();
+		}
+		
+		void IScrollInfo.PageRight()
+		{
+			if (scrollInfo != null) scrollInfo.PageRight();
+		}
+		
+		void IScrollInfo.MouseWheelUp()
+		{
+			if (scrollInfo != null) scrollInfo.MouseWheelUp();
+		}
+		
+		void IScrollInfo.MouseWheelDown()
+		{
+			if (scrollInfo != null) scrollInfo.MouseWheelDown();
+		}
+		
+		void IScrollInfo.MouseWheelLeft()
+		{
+			if (scrollInfo != null) scrollInfo.MouseWheelLeft();
+		}
+		
+		void IScrollInfo.MouseWheelRight()
+		{
+			if (scrollInfo != null) scrollInfo.MouseWheelRight();
+		}
+		
+		void IScrollInfo.SetHorizontalOffset(double offset)
+		{
+			if (scrollInfo != null) scrollInfo.SetHorizontalOffset(offset);
+		}
+		
+		void IScrollInfo.SetVerticalOffset(double offset)
+		{
+			if (scrollInfo != null) scrollInfo.SetVerticalOffset(offset);
+		}
+		
+		Rect IScrollInfo.MakeVisible(System.Windows.Media.Visual visual, Rect rectangle)
+		{
+			if (scrollInfo != null)
+				return scrollInfo.MakeVisible(visual, rectangle);
+			else
+				return Rect.Empty;
+		}
+		#endregion
+		
+		#region Focus Handling (Show/Hide Caret)
+		/// <inheritdoc/>
+		protected override void OnMouseDown(MouseButtonEventArgs e)
+		{
+			base.OnMouseDown(e);
+			Focus();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
+		{
+			base.OnGotKeyboardFocus(e);
+			// First activate IME, then show caret
+			ime.OnGotKeyboardFocus(e);
+			caret.Show();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
+		{
+			base.OnLostKeyboardFocus(e);
+			caret.Hide();
+			ime.OnLostKeyboardFocus(e);
+		}
+		#endregion
+		
+		#region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText
+		/// <summary>
+		/// Occurs when the TextArea receives text input.
+		/// This is like the <see cref="UIElement.TextInput"/> event,
+		/// but occurs immediately before the TextArea handles the TextInput event.
+		/// </summary>
+		public event TextCompositionEventHandler TextEntering;
+		
+		/// <summary>
+		/// Occurs when the TextArea receives text input.
+		/// This is like the <see cref="UIElement.TextInput"/> event,
+		/// but occurs immediately after the TextArea handles the TextInput event.
+		/// </summary>
+		public event TextCompositionEventHandler TextEntered;
+		
+		/// <summary>
+		/// Raises the TextEntering event.
+		/// </summary>
+		protected virtual void OnTextEntering(TextCompositionEventArgs e)
+		{
+			if (TextEntering != null) {
+				TextEntering(this, e);
+			}
+		}
+		
+		/// <summary>
+		/// Raises the TextEntered event.
+		/// </summary>
+		protected virtual void OnTextEntered(TextCompositionEventArgs e)
+		{
+			if (TextEntered != null) {
+				TextEntered(this, e);
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnTextInput(TextCompositionEventArgs e)
+		{
+			//Debug.WriteLine("TextInput: Text='" + e.Text + "' SystemText='" + e.SystemText + "' ControlText='" + e.ControlText + "'");
+			base.OnTextInput(e);
+			if (!e.Handled && this.Document != null) {
+				if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b") {
+					// ASCII 0x1b = ESC.
+					// WPF produces a TextInput event with that old ASCII control char
+					// when Escape is pressed. We'll just ignore it.
+					
+					// A deadkey followed by backspace causes a textinput event for the BS character.
+					
+					// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
+					// We have to ignore those (not handle them) to keep the shortcut working.
+					return;
+				}
+				HideMouseCursor();
+				PerformTextInput(e);
+				e.Handled = true;
+			}
+		}
+		
+		/// <summary>
+		/// Performs text input.
+		/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
+		/// and then raises the <see cref="TextEntered"/> event.
+		/// </summary>
+		public void PerformTextInput(string text)
+		{
+			TextComposition textComposition = new TextComposition(InputManager.Current, this, text);
+			TextCompositionEventArgs e = new TextCompositionEventArgs(Keyboard.PrimaryDevice, textComposition);
+			e.RoutedEvent = TextInputEvent;
+			PerformTextInput(e);
+		}
+		
+		/// <summary>
+		/// Performs text input.
+		/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
+		/// and then raises the <see cref="TextEntered"/> event.
+		/// </summary>
+		public void PerformTextInput(TextCompositionEventArgs e)
+		{
+			if (e == null)
+				throw new ArgumentNullException("e");
+			if (this.Document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			OnTextEntering(e);
+			if (!e.Handled) {
+				if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
+					ReplaceSelectionWithNewLine();
+				else {
+					if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
+						EditingCommands.SelectRightByCharacter.Execute(null, this);
+					ReplaceSelectionWithText(e.Text);
+				}
+				OnTextEntered(e);
+				caret.BringCaretToView();
+			}
+		}
+		
+		void ReplaceSelectionWithNewLine()
+		{
+			string newLine = TextUtilities.GetNewLineFromDocument(this.Document, this.Caret.Line);
+			using (this.Document.RunUpdate()) {
+				ReplaceSelectionWithText(newLine);
+				if (this.IndentationStrategy != null) {
+					DocumentLine line = this.Document.GetLineByNumber(this.Caret.Line);
+					ISegment[] deletable = GetDeletableSegments(line);
+					if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) {
+						// use indentation strategy only if the line is not read-only
+						this.IndentationStrategy.IndentLine(this.Document, line);
+					}
+				}
+			}
+		}
+		
+		internal void RemoveSelectedText()
+		{
+			if (this.Document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			selection.ReplaceSelectionWithText(string.Empty);
+			#if DEBUG
+			if (!selection.IsEmpty) {
+				foreach (ISegment s in selection.Segments) {
+					Debug.Assert(this.ReadOnlySectionProvider.GetDeletableSegments(s).Count() == 0);
+				}
+			}
+			#endif
+		}
+		
+		internal void ReplaceSelectionWithText(string newText)
+		{
+			if (newText == null)
+				throw new ArgumentNullException("newText");
+			if (this.Document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			selection.ReplaceSelectionWithText(newText);
+		}
+		
+		internal ISegment[] GetDeletableSegments(ISegment segment)
+		{
+			var deletableSegments = this.ReadOnlySectionProvider.GetDeletableSegments(segment);
+			if (deletableSegments == null)
+				throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
+			var array = deletableSegments.ToArray();
+			int lastIndex = segment.Offset;
+			for (int i = 0; i < array.Length; i++) {
+				if (array[i].Offset < lastIndex)
+					throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
+				lastIndex = array[i].EndOffset;
+			}
+			if (lastIndex > segment.EndOffset)
+				throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
+			return array;
+		}
+		#endregion
+		
+		#region IndentationStrategy property
+		/// <summary>
+		/// IndentationStrategy property.
+		/// </summary>
+		public static readonly DependencyProperty IndentationStrategyProperty =
+			DependencyProperty.Register("IndentationStrategy", typeof(IIndentationStrategy), typeof(TextArea),
+			                            new FrameworkPropertyMetadata(new DefaultIndentationStrategy()));
+		
+		/// <summary>
+		/// Gets/Sets the indentation strategy used when inserting new lines.
+		/// </summary>
+		public IIndentationStrategy IndentationStrategy {
+			get { return (IIndentationStrategy)GetValue(IndentationStrategyProperty); }
+			set { SetValue(IndentationStrategyProperty, value); }
+		}
+		#endregion
+		
+		#region OnKeyDown/OnKeyUp
+		/// <inheritdoc/>
+		protected override void OnPreviewKeyDown(KeyEventArgs e)
+		{
+			base.OnPreviewKeyDown(e);
+			
+			if (!e.Handled && e.Key == Key.Insert && this.Options.AllowToggleOverstrikeMode) {
+				this.OverstrikeMode = !this.OverstrikeMode;
+				e.Handled = true;
+				return;
+			}
+			
+			foreach (TextAreaStackedInputHandler h in stackedInputHandlers) {
+				if (e.Handled)
+					break;
+				h.OnPreviewKeyDown(e);
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnPreviewKeyUp(KeyEventArgs e)
+		{
+			base.OnPreviewKeyUp(e);
+			foreach (TextAreaStackedInputHandler h in stackedInputHandlers) {
+				if (e.Handled)
+					break;
+				h.OnPreviewKeyUp(e);
+			}
+		}
+		
+		// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
+		/// <inheritdoc/>
+		protected override void OnKeyDown(KeyEventArgs e)
+		{
+			base.OnKeyDown(e);
+			TextView.InvalidateCursorIfMouseWithinTextView();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnKeyUp(KeyEventArgs e)
+		{
+			base.OnKeyUp(e);
+			TextView.InvalidateCursorIfMouseWithinTextView();
+		}
+		#endregion
+		
+		#region Hide Mouse Cursor While Typing
+		
+		bool isMouseCursorHidden;
+		
+		void AttachTypingEvents()
+		{
+			// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
+			this.MouseEnter += delegate { ShowMouseCursor(); };
+			this.MouseLeave += delegate { ShowMouseCursor(); };
+			this.PreviewMouseMove += delegate { ShowMouseCursor(); };
+			#if DOTNET4
+			this.TouchEnter += delegate { ShowMouseCursor(); };
+			this.TouchLeave += delegate { ShowMouseCursor(); };
+			this.PreviewTouchMove += delegate { ShowMouseCursor(); };
+			#endif
+		}
+		
+		void ShowMouseCursor()
+		{
+			if (this.isMouseCursorHidden) {
+				System.Windows.Forms.Cursor.Show();
+				this.isMouseCursorHidden = false;
+			}
+		}
+		
+		void HideMouseCursor() {
+			if (Options.HideCursorWhileTyping && !this.isMouseCursorHidden && this.IsMouseOver) {
+				this.isMouseCursorHidden = true;
+				System.Windows.Forms.Cursor.Hide();
+			}
+		}
+		
+		#endregion
+		
+		#region Overstrike mode
+		
+		/// <summary>
+		/// The <see cref="OverstrikeMode"/> dependency property.
+		/// </summary>
+		public static readonly DependencyProperty OverstrikeModeProperty =
+			DependencyProperty.Register("OverstrikeMode", typeof(bool), typeof(TextArea),
+			                            new FrameworkPropertyMetadata(Boxes.False));
+		
+		/// <summary>
+		/// Gets/Sets whether overstrike mode is active.
+		/// </summary>
+		public bool OverstrikeMode {
+			get { return (bool)GetValue(OverstrikeModeProperty); }
+			set { SetValue(OverstrikeModeProperty, value); }
+		}
+		
+		#endregion
+		
+		/// <inheritdoc/>
+		protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
+		{
+			// accept clicks even where the text area draws no background
+			return new PointHitTestResult(this, hitTestParameters.HitPoint);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
+		{
+			base.OnPropertyChanged(e);
+			if (e.Property == SelectionBrushProperty
+			    || e.Property == SelectionBorderProperty
+			    || e.Property == SelectionForegroundProperty
+			    || e.Property == SelectionCornerRadiusProperty)
+			{
+				textView.Redraw();
+			} else if (e.Property == OverstrikeModeProperty) {
+				caret.UpdateIfVisible();
+			}
+		}
+		
+		/// <summary>
+		/// Gets the requested service.
+		/// </summary>
+		/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
+		public virtual object GetService(Type serviceType)
+		{
+			return textView.GetService(serviceType);
+		}
+		
+		/// <summary>
+		/// Occurs when text inside the TextArea was copied.
+		/// </summary>
+		public event EventHandler<TextEventArgs> TextCopied;
+		
+		internal void OnTextCopied(TextEventArgs e)
+		{
+			if (TextCopied != null)
+				TextCopied(this, e);
+		}
+	}
+	
+	/// <summary>
+	/// EventArgs with text.
+	/// </summary>
+	[Serializable]
+	public class TextEventArgs : EventArgs
+	{
+		string text;
+		
+		/// <summary>
+		/// Gets the text.
+		/// </summary>
+		public string Text {
+			get {
+				return text;
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new TextEventArgs instance.
+		/// </summary>
+		public TextEventArgs(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextAreaDefaultInputHandlers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextAreaDefaultInputHandlers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextAreaDefaultInputHandlers.cs	(revision 11807)
@@ -0,0 +1,135 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using System.Windows.Input;
+
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Contains the predefined input handlers.
+	/// </summary>
+	public class TextAreaDefaultInputHandler : TextAreaInputHandler
+	{
+		/// <summary>
+		/// Gets the caret navigation input handler.
+		/// </summary>
+		public TextAreaInputHandler CaretNavigation { get; private set; }
+		
+		/// <summary>
+		/// Gets the editing input handler.
+		/// </summary>
+		public TextAreaInputHandler Editing { get; private set; }
+		
+		/// <summary>
+		/// Gets the mouse selection input handler.
+		/// </summary>
+		public ITextAreaInputHandler MouseSelection { get; private set; }
+		
+		/// <summary>
+		/// Creates a new TextAreaDefaultInputHandler instance.
+		/// </summary>
+		public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
+		{
+			this.NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
+			this.NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
+			this.NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
+			
+			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo));
+			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo));
+		}
+		
+		internal static KeyBinding CreateFrozenKeyBinding(ICommand command, ModifierKeys modifiers, Key key)
+		{
+			KeyBinding kb = new KeyBinding(command, key, modifiers);
+			// Mark KeyBindings as frozen because they're shared between multiple editor instances.
+			// KeyBinding derives from Freezable only in .NET 4, so we have to use this little trick:
+			Freezable f = ((object)kb) as Freezable;
+			if (f != null)
+				f.Freeze();
+			return kb;
+		}
+		
+		internal static void WorkaroundWPFMemoryLeak(List<InputBinding> inputBindings)
+		{
+			// Work around WPF memory leak:
+			// KeyBinding retains a reference to whichever UIElement it is used in first.
+			// Using a dummy element for this purpose ensures that we don't leak
+			// a real text editor (with a potentially large document).
+			UIElement dummyElement = new UIElement();
+			dummyElement.InputBindings.AddRange(inputBindings);
+		}
+		
+		#region Undo / Redo
+		UndoStack GetUndoStack()
+		{
+			TextDocument document = this.TextArea.Document;
+			if (document != null)
+				return document.UndoStack;
+			else
+				return null;
+		}
+		
+		void ExecuteUndo(object sender, ExecutedRoutedEventArgs e)
+		{
+			var undoStack = GetUndoStack();
+			if (undoStack != null) {
+				if (undoStack.CanUndo) {
+					undoStack.Undo();
+					this.TextArea.Caret.BringCaretToView();
+				}
+				e.Handled = true;
+			}
+		}
+		
+		void CanExecuteUndo(object sender, CanExecuteRoutedEventArgs e)
+		{
+			var undoStack = GetUndoStack();
+			if (undoStack != null) {
+				e.Handled = true;
+				e.CanExecute = undoStack.CanUndo;
+			}
+		}
+		
+		void ExecuteRedo(object sender, ExecutedRoutedEventArgs e)
+		{
+			var undoStack = GetUndoStack();
+			if (undoStack != null) {
+				if (undoStack.CanRedo) {
+					undoStack.Redo();
+					this.TextArea.Caret.BringCaretToView();
+				}
+				e.Handled = true;
+			}
+		}
+		
+		void CanExecuteRedo(object sender, CanExecuteRoutedEventArgs e)
+		{
+			var undoStack = GetUndoStack();
+			if (undoStack != null) {
+				e.Handled = true;
+				e.CanExecute = undoStack.CanRedo;
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextAreaInputHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextAreaInputHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextAreaInputHandler.cs	(revision 11807)
@@ -0,0 +1,257 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using ICSharpCode.AvalonEdit.Utils;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Windows.Input;
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// A set of input bindings and event handlers for the text area.
+	/// </summary>
+	/// <remarks>
+	/// <para>
+	/// There is one active input handler per text area (<see cref="Editing.TextArea.ActiveInputHandler"/>), plus
+	/// a number of active stacked input handlers.
+	/// </para>
+	/// <para>
+	/// The text area also stores a reference to a default input handler, but that is not necessarily active.
+	/// </para>
+	/// <para>
+	/// Stacked input handlers work in addition to the set of currently active handlers (without detaching them).
+	/// They are detached in the reverse order of being attached.
+	/// </para>
+	/// </remarks>
+	public interface ITextAreaInputHandler
+	{
+		/// <summary>
+		/// Gets the text area that the input handler belongs to.
+		/// </summary>
+		TextArea TextArea {
+			get;
+		}
+		
+		/// <summary>
+		/// Attaches an input handler to the text area.
+		/// </summary>
+		void Attach();
+		
+		/// <summary>
+		/// Detaches the input handler from the text area.
+		/// </summary>
+		void Detach();
+	}
+	
+	/// <summary>
+	/// Stacked input handler.
+	/// Uses OnEvent-methods instead of registering event handlers to ensure that the events are handled in the correct order.
+	/// </summary>
+	public abstract class TextAreaStackedInputHandler : ITextAreaInputHandler
+	{
+		readonly TextArea textArea;
+		
+		/// <inheritdoc/>
+		public TextArea TextArea {
+			get { return textArea; }
+		}
+		
+		/// <summary>
+		/// Creates a new TextAreaInputHandler.
+		/// </summary>
+		protected TextAreaStackedInputHandler(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+		}
+		
+		/// <inheritdoc/>
+		public virtual void Attach()
+		{
+		}
+		
+		/// <inheritdoc/>
+		public virtual void Detach()
+		{
+		}
+		
+		/// <summary>
+		/// Called for the PreviewKeyDown event.
+		/// </summary>
+		public virtual void OnPreviewKeyDown(KeyEventArgs e)
+		{
+		}
+		
+		/// <summary>
+		/// Called for the PreviewKeyUp event.
+		/// </summary>
+		public virtual void OnPreviewKeyUp(KeyEventArgs e)
+		{
+		}
+	}
+	
+	/// <summary>
+	/// Default-implementation of <see cref="ITextAreaInputHandler"/>.
+	/// </summary>
+	/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
+	public class TextAreaInputHandler : ITextAreaInputHandler
+	{
+		readonly ObserveAddRemoveCollection<CommandBinding> commandBindings;
+		readonly ObserveAddRemoveCollection<InputBinding> inputBindings;
+		readonly ObserveAddRemoveCollection<ITextAreaInputHandler> nestedInputHandlers;
+		readonly TextArea textArea;
+		bool isAttached;
+		
+		/// <summary>
+		/// Creates a new TextAreaInputHandler.
+		/// </summary>
+		public TextAreaInputHandler(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+			commandBindings = new ObserveAddRemoveCollection<CommandBinding>(CommandBinding_Added, CommandBinding_Removed);
+			inputBindings = new ObserveAddRemoveCollection<InputBinding>(InputBinding_Added, InputBinding_Removed);
+			nestedInputHandlers = new ObserveAddRemoveCollection<ITextAreaInputHandler>(NestedInputHandler_Added, NestedInputHandler_Removed);
+		}
+		
+		/// <inheritdoc/>
+		public TextArea TextArea {
+			get { return textArea; }
+		}
+		
+		/// <summary>
+		/// Gets whether the input handler is currently attached to the text area.
+		/// </summary>
+		public bool IsAttached {
+			get { return isAttached; }
+		}
+		
+		#region CommandBindings / InputBindings
+		/// <summary>
+		/// Gets the command bindings of this input handler.
+		/// </summary>
+		public ICollection<CommandBinding> CommandBindings {
+			get { return commandBindings; }
+		}
+		
+		void CommandBinding_Added(CommandBinding commandBinding)
+		{
+			if (isAttached)
+				textArea.CommandBindings.Add(commandBinding);
+		}
+		
+		void CommandBinding_Removed(CommandBinding commandBinding)
+		{
+			if (isAttached)
+				textArea.CommandBindings.Remove(commandBinding);
+		}
+		
+		/// <summary>
+		/// Gets the input bindings of this input handler.
+		/// </summary>
+		public ICollection<InputBinding> InputBindings {
+			get { return inputBindings; }
+		}
+		
+		void InputBinding_Added(InputBinding inputBinding)
+		{
+			if (isAttached)
+				textArea.InputBindings.Add(inputBinding);
+		}
+		
+		void InputBinding_Removed(InputBinding inputBinding)
+		{
+			if (isAttached)
+				textArea.InputBindings.Remove(inputBinding);
+		}
+		
+		/// <summary>
+		/// Adds a command and input binding.
+		/// </summary>
+		/// <param name="command">The command ID.</param>
+		/// <param name="modifiers">The modifiers of the keyboard shortcut.</param>
+		/// <param name="key">The key of the keyboard shortcut.</param>
+		/// <param name="handler">The event handler to run when the command is executed.</param>
+		public void AddBinding(ICommand command, ModifierKeys modifiers, Key key, ExecutedRoutedEventHandler handler)
+		{
+			this.CommandBindings.Add(new CommandBinding(command, handler));
+			this.InputBindings.Add(new KeyBinding(command, key, modifiers));
+		}
+		#endregion
+		
+		#region NestedInputHandlers
+		/// <summary>
+		/// Gets the collection of nested input handlers. NestedInputHandlers are activated and deactivated
+		/// together with this input handler.
+		/// </summary>
+		public ICollection<ITextAreaInputHandler> NestedInputHandlers {
+			get { return nestedInputHandlers; }
+		}
+		
+		void NestedInputHandler_Added(ITextAreaInputHandler handler)
+		{
+			if (handler == null)
+				throw new ArgumentNullException("handler");
+			if (handler.TextArea != textArea)
+				throw new ArgumentException("The nested handler must be working for the same text area!");
+			if (isAttached)
+				handler.Attach();
+		}
+		
+		void NestedInputHandler_Removed(ITextAreaInputHandler handler)
+		{
+			if (isAttached)
+				handler.Detach();
+		}
+		#endregion
+		
+		#region Attach/Detach
+		/// <inheritdoc/>
+		public virtual void Attach()
+		{
+			if (isAttached)
+				throw new InvalidOperationException("Input handler is already attached");
+			isAttached = true;
+			
+			textArea.CommandBindings.AddRange(commandBindings);
+			textArea.InputBindings.AddRange(inputBindings);
+			foreach (ITextAreaInputHandler handler in nestedInputHandlers)
+				handler.Attach();
+		}
+		
+		/// <inheritdoc/>
+		public virtual void Detach()
+		{
+			if (!isAttached)
+				throw new InvalidOperationException("Input handler is not attached");
+			isAttached = false;
+			
+			foreach (CommandBinding b in commandBindings)
+				textArea.CommandBindings.Remove(b);
+			foreach (InputBinding b in inputBindings)
+				textArea.InputBindings.Remove(b);
+			foreach (ITextAreaInputHandler handler in nestedInputHandlers)
+				handler.Detach();
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextSegmentReadOnlySectionProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextSegmentReadOnlySectionProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Editing/TextSegmentReadOnlySectionProvider.cs	(revision 11807)
@@ -0,0 +1,103 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Document;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Editing
+{
+	/// <summary>
+	/// Implementation for <see cref="IReadOnlySectionProvider"/> that stores the segments
+	/// in a <see cref="TextSegmentCollection{T}"/>.
+	/// </summary>
+	public class TextSegmentReadOnlySectionProvider<T> : IReadOnlySectionProvider where T : TextSegment
+	{
+		readonly TextSegmentCollection<T> segments;
+		
+		/// <summary>
+		/// Gets the collection storing the read-only segments.
+		/// </summary>
+		public TextSegmentCollection<T> Segments {
+			get { return segments; }
+		}
+		
+		/// <summary>
+		/// Creates a new TextSegmentReadOnlySectionProvider instance for the specified document.
+		/// </summary>
+		public TextSegmentReadOnlySectionProvider(TextDocument textDocument)
+		{
+			segments = new TextSegmentCollection<T>(textDocument);
+		}
+		
+		/// <summary>
+		/// Creates a new TextSegmentReadOnlySectionProvider instance using the specified TextSegmentCollection.
+		/// </summary>
+		public TextSegmentReadOnlySectionProvider(TextSegmentCollection<T> segments)
+		{
+			if (segments == null)
+				throw new ArgumentNullException("segments");
+			this.segments = segments;
+		}
+		
+		/// <summary>
+		/// Gets whether insertion is possible at the specified offset.
+		/// </summary>
+		public virtual bool CanInsert(int offset)
+		{
+			foreach (TextSegment segment in segments.FindSegmentsContaining(offset)) {
+				if (segment.StartOffset < offset && offset < segment.EndOffset)
+					return false;
+			}
+			return true;
+		}
+		
+		/// <summary>
+		/// Gets the deletable segments inside the given segment.
+		/// </summary>
+		public virtual IEnumerable<ISegment> GetDeletableSegments(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			
+			if (segment.Length == 0 && CanInsert(segment.Offset)) {
+				yield return segment;
+				yield break;
+			}
+			
+			int readonlyUntil = segment.Offset;
+			foreach (TextSegment ts in segments.FindOverlappingSegments(segment)) {
+				int start = ts.StartOffset;
+				int end = start + ts.Length;
+				if (start > readonlyUntil) {
+					yield return new SimpleSegment(readonlyUntil, start - readonlyUntil);
+				}
+				if (end > readonlyUntil) {
+					readonlyUntil = end;
+				}
+			}
+			int endOffset = segment.EndOffset;
+			if (readonlyUntil < endOffset) {
+				yield return new SimpleSegment(readonlyUntil, endOffset - readonlyUntil);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingElementGenerator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingElementGenerator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingElementGenerator.cs	(revision 11807)
@@ -0,0 +1,210 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	/// <summary>
+	/// A <see cref="VisualLineElementGenerator"/> that produces line elements for folded <see cref="FoldingSection"/>s.
+	/// </summary>
+	public sealed class FoldingElementGenerator : VisualLineElementGenerator, ITextViewConnect
+	{
+		readonly List<TextView> textViews = new List<TextView>();
+		FoldingManager foldingManager;
+		
+		#region FoldingManager property / connecting with TextView
+		/// <summary>
+		/// Gets/Sets the folding manager from which the foldings should be shown.
+		/// </summary>
+		public FoldingManager FoldingManager {
+			get {
+				return foldingManager;
+			}
+			set {
+				if (foldingManager != value) {
+					if (foldingManager != null) {
+						foreach (TextView v in textViews)
+							foldingManager.RemoveFromTextView(v);
+					}
+					foldingManager = value;
+					if (foldingManager != null) {
+						foreach (TextView v in textViews)
+							foldingManager.AddToTextView(v);
+					}
+				}
+			}
+		}
+		
+		void ITextViewConnect.AddToTextView(TextView textView)
+		{
+			textViews.Add(textView);
+			if (foldingManager != null)
+				foldingManager.AddToTextView(textView);
+		}
+		
+		void ITextViewConnect.RemoveFromTextView(TextView textView)
+		{
+			textViews.Remove(textView);
+			if (foldingManager != null)
+				foldingManager.RemoveFromTextView(textView);
+		}
+		#endregion
+		
+		/// <inheritdoc/>
+		public override void StartGeneration(ITextRunConstructionContext context)
+		{
+			base.StartGeneration(context);
+			if (foldingManager != null) {
+				if (!foldingManager.textViews.Contains(context.TextView))
+					throw new ArgumentException("Invalid TextView");
+				if (context.Document != foldingManager.document)
+					throw new ArgumentException("Invalid document");
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override int GetFirstInterestedOffset(int startOffset)
+		{
+			if (foldingManager != null) {
+				foreach (FoldingSection fs in foldingManager.GetFoldingsContaining(startOffset)) {
+					// Test whether we're currently within a folded folding (that didn't just end).
+					// If so, create the fold marker immediately.
+					// This is necessary if the actual beginning of the fold marker got skipped due to another VisualElementGenerator.
+					if (fs.IsFolded && fs.EndOffset > startOffset) {
+						//return startOffset;
+					}
+				}
+				return foldingManager.GetNextFoldedFoldingStart(startOffset);
+			} else {
+				return -1;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override VisualLineElement ConstructElement(int offset)
+		{
+			if (foldingManager == null)
+				return null;
+			int foldedUntil = -1;
+			FoldingSection foldingSection = null;
+			foreach (FoldingSection fs in foldingManager.GetFoldingsContaining(offset)) {
+				if (fs.IsFolded) {
+					if (fs.EndOffset > foldedUntil) {
+						foldedUntil = fs.EndOffset;
+						foldingSection = fs;
+					}
+				}
+			}
+			if (foldedUntil > offset && foldingSection != null) {
+				// Handle overlapping foldings: if there's another folded folding
+				// (starting within the foldingSection) that continues after the end of the folded section,
+				// then we'll extend our fold element to cover that overlapping folding.
+				bool foundOverlappingFolding;
+				do {
+					foundOverlappingFolding = false;
+					foreach (FoldingSection fs in FoldingManager.GetFoldingsContaining(foldedUntil)) {
+						if (fs.IsFolded && fs.EndOffset > foldedUntil) {
+							foldedUntil = fs.EndOffset;
+							foundOverlappingFolding = true;
+						}
+					}
+				} while (foundOverlappingFolding);
+				
+				string title = foldingSection.Title;
+				if (string.IsNullOrEmpty(title))
+					title = "...";
+				var p = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
+				p.SetForegroundBrush(textBrush);
+				var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
+				var text = FormattedTextElement.PrepareText(textFormatter, title, p);
+				return new FoldingLineElement(foldingSection, text, foldedUntil - offset) { textBrush = textBrush };
+			} else {
+				return null;
+			}
+		}
+		
+		sealed class FoldingLineElement : FormattedTextElement
+		{
+			readonly FoldingSection fs;
+			
+			internal Brush textBrush;
+			
+			public FoldingLineElement(FoldingSection fs, TextLine text, int documentLength) : base(text, documentLength)
+			{
+				this.fs = fs;
+			}
+			
+			public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+			{
+				return new FoldingLineTextRun(this, this.TextRunProperties) { textBrush = textBrush };
+			}
+			
+			protected internal override void OnMouseDown(MouseButtonEventArgs e)
+			{
+				if (e.ClickCount == 2 && e.ChangedButton == MouseButton.Left) {
+					fs.IsFolded = false;
+					e.Handled = true;
+				} else {
+					base.OnMouseDown(e);
+				}
+			}
+		}
+		
+		sealed class FoldingLineTextRun : FormattedTextRun
+		{
+			internal Brush textBrush;
+			
+			public FoldingLineTextRun(FormattedTextElement element, TextRunProperties properties)
+				: base(element, properties)
+			{
+			}
+			
+			public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways)
+			{
+				var metrics = Format(double.PositiveInfinity);
+				Rect r = new Rect(origin.X, origin.Y - metrics.Baseline, metrics.Width, metrics.Height);
+				drawingContext.DrawRectangle(null, new Pen(textBrush, 1), r);
+				base.Draw(drawingContext, origin, rightToLeft, sideways);
+			}
+		}
+		
+		/// <summary>
+		/// Default brush for folding element text. Value: Brushes.Gray
+		/// </summary>
+		public static readonly Brush DefaultTextBrush = Brushes.Gray;
+		
+		static Brush textBrush = DefaultTextBrush;
+		
+		/// <summary>
+		/// Gets/sets the brush used for folding element text.
+		/// </summary>
+		public static Brush TextBrush {
+			get { return textBrush; }
+			set { textBrush = value; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingManager.cs	(revision 11807)
@@ -0,0 +1,397 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Windows;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	/// <summary>
+	/// Stores a list of foldings for a specific TextView and TextDocument.
+	/// </summary>
+	public class FoldingManager : IWeakEventListener
+	{
+		internal readonly TextDocument document;
+		
+		internal readonly List<TextView> textViews = new List<TextView>();
+		readonly TextSegmentCollection<FoldingSection> foldings;
+		bool isFirstUpdate = true;
+		
+		#region Constructor
+		/// <summary>
+		/// Creates a new FoldingManager instance.
+		/// </summary>
+		public FoldingManager(TextDocument document)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			this.document = document;
+			this.foldings = new TextSegmentCollection<FoldingSection>();
+			document.VerifyAccess();
+			TextDocumentWeakEventManager.Changed.AddListener(document, this);
+		}
+		#endregion
+		
+		#region ReceiveWeakEvent
+		/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
+		protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
+				OnDocumentChanged((DocumentChangeEventArgs)e);
+				return true;
+			}
+			return false;
+		}
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			return ReceiveWeakEvent(managerType, sender, e);
+		}
+		
+		void OnDocumentChanged(DocumentChangeEventArgs e)
+		{
+			foldings.UpdateOffsets(e);
+			int newEndOffset = e.Offset + e.InsertionLength;
+			// extend end offset to the end of the line (including delimiter)
+			var endLine = document.GetLineByOffset(newEndOffset);
+			newEndOffset = endLine.Offset + endLine.TotalLength;
+			foreach (var affectedFolding in foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) {
+				if (affectedFolding.Length == 0) {
+					RemoveFolding(affectedFolding);
+				} else {
+					affectedFolding.ValidateCollapsedLineSections();
+				}
+			}
+		}
+		#endregion
+		
+		#region Manage TextViews
+		internal void AddToTextView(TextView textView)
+		{
+			if (textView == null || textViews.Contains(textView))
+				throw new ArgumentException();
+			textViews.Add(textView);
+			foreach (FoldingSection fs in foldings) {
+				if (fs.collapsedSections != null) {
+					Array.Resize(ref fs.collapsedSections, textViews.Count);
+					fs.ValidateCollapsedLineSections();
+				}
+			}
+		}
+		
+		internal void RemoveFromTextView(TextView textView)
+		{
+			int pos = textViews.IndexOf(textView);
+			if (pos < 0)
+				throw new ArgumentException();
+			textViews.RemoveAt(pos);
+			foreach (FoldingSection fs in foldings) {
+				if (fs.collapsedSections != null) {
+					var c = new CollapsedLineSection[textViews.Count];
+					Array.Copy(fs.collapsedSections, 0, c, 0, pos);
+					fs.collapsedSections[pos].Uncollapse();
+					Array.Copy(fs.collapsedSections, pos + 1, c, pos, c.Length - pos);
+					fs.collapsedSections = c;
+				}
+			}
+		}
+		
+		internal void Redraw()
+		{
+			foreach (TextView textView in textViews)
+				textView.Redraw();
+		}
+		
+		internal void Redraw(FoldingSection fs)
+		{
+			foreach (TextView textView in textViews)
+				textView.Redraw(fs);
+		}
+		#endregion
+		
+		#region Create / Remove / Clear
+		/// <summary>
+		/// Creates a folding for the specified text section.
+		/// </summary>
+		public FoldingSection CreateFolding(int startOffset, int endOffset)
+		{
+			if (startOffset >= endOffset)
+				throw new ArgumentException("startOffset must be less than endOffset");
+			if (startOffset < 0 || endOffset > document.TextLength)
+				throw new ArgumentException("Folding must be within document boundary");
+			FoldingSection fs = new FoldingSection(this, startOffset, endOffset);
+			foldings.Add(fs);
+			Redraw(fs);
+			return fs;
+		}
+		
+		/// <summary>
+		/// Removes a folding section from this manager.
+		/// </summary>
+		public void RemoveFolding(FoldingSection fs)
+		{
+			if (fs == null)
+				throw new ArgumentNullException("fs");
+			fs.IsFolded = false;
+			foldings.Remove(fs);
+			Redraw(fs);
+		}
+		
+		/// <summary>
+		/// Removes all folding sections.
+		/// </summary>
+		public void Clear()
+		{
+			document.VerifyAccess();
+			foreach (FoldingSection s in foldings)
+				s.IsFolded = false;
+			foldings.Clear();
+			Redraw();
+		}
+		#endregion
+		
+		#region Get...Folding
+		/// <summary>
+		/// Gets all foldings in this manager.
+		/// The foldings are returned sorted by start offset;
+		/// for multiple foldings at the same offset the order is undefined.
+		/// </summary>
+		public IEnumerable<FoldingSection> AllFoldings {
+			get { return foldings; }
+		}
+		
+		/// <summary>
+		/// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts.
+		/// Returns -1 if there are no foldings after <paramref name="startOffset"/>.
+		/// </summary>
+		public int GetNextFoldedFoldingStart(int startOffset)
+		{
+			FoldingSection fs = foldings.FindFirstSegmentWithStartAfter(startOffset);
+			while (fs != null && !fs.IsFolded)
+				fs = foldings.GetNextSegment(fs);
+			return fs != null ? fs.StartOffset : -1;
+		}
+		
+		/// <summary>
+		/// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to
+		/// <paramref name="startOffset"/>.
+		/// Returns null if there are no foldings after <paramref name="startOffset"/>.
+		/// </summary>
+		public FoldingSection GetNextFolding(int startOffset)
+		{
+			// TODO: returns the longest folding instead of any folding at the first position after startOffset
+			return foldings.FindFirstSegmentWithStartAfter(startOffset);
+		}
+		
+		/// <summary>
+		/// Gets all foldings that start exactly at <paramref name="startOffset"/>.
+		/// </summary>
+		public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset)
+		{
+			List<FoldingSection> result = new List<FoldingSection>();
+			FoldingSection fs = foldings.FindFirstSegmentWithStartAfter(startOffset);
+			while (fs != null && fs.StartOffset == startOffset) {
+				result.Add(fs);
+				fs = foldings.GetNextSegment(fs);
+			}
+			return result.AsReadOnly();
+		}
+		
+		/// <summary>
+		/// Gets all foldings that contain <paramref name="offset" />.
+		/// </summary>
+		public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset)
+		{
+			return foldings.FindSegmentsContaining(offset);
+		}
+		#endregion
+		
+		#region UpdateFoldings
+		/// <summary>
+		/// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings.
+		/// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state
+		/// (<see cref="FoldingSection.IsFolded"/>) for existing foldings.
+		/// </summary>
+		/// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param>
+		/// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after
+		/// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>.
+		/// Use -1 for this parameter if there were no parse errors.</param>
+		public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset)
+		{
+			if (newFoldings == null)
+				throw new ArgumentNullException("newFoldings");
+			
+			if (firstErrorOffset < 0)
+				firstErrorOffset = int.MaxValue;
+			
+			var oldFoldings = this.AllFoldings.ToArray();
+			int oldFoldingIndex = 0;
+			int previousStartOffset = 0;
+			// merge new foldings into old foldings so that sections keep being collapsed
+			// both oldFoldings and newFoldings are sorted by start offset
+			foreach (NewFolding newFolding in newFoldings) {
+				// ensure newFoldings are sorted correctly
+				if (newFolding.StartOffset < previousStartOffset)
+					throw new ArgumentException("newFoldings must be sorted by start offset");
+				previousStartOffset = newFolding.StartOffset;
+				
+				int startOffset = newFolding.StartOffset.CoerceValue(0, document.TextLength);
+				int endOffset = newFolding.EndOffset.CoerceValue(0, document.TextLength);
+				
+				if (newFolding.StartOffset == newFolding.EndOffset)
+					continue; // ignore zero-length foldings
+				
+				// remove old foldings that were skipped
+				while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) {
+					this.RemoveFolding(oldFoldings[oldFoldingIndex++]);
+				}
+				FoldingSection section;
+				// reuse current folding if its matching:
+				if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) {
+					section = oldFoldings[oldFoldingIndex++];
+					section.Length = newFolding.EndOffset - newFolding.StartOffset;
+				} else {
+					// no matching current folding; create a new one:
+					section = this.CreateFolding(newFolding.StartOffset, newFolding.EndOffset);
+					// auto-close #regions only when opening the document
+					if (isFirstUpdate) {
+						section.IsFolded = newFolding.DefaultClosed;
+						isFirstUpdate = false;
+					}
+					section.Tag = newFolding;
+				}
+				section.Title = newFolding.Name;
+			}
+			// remove all outstanding old foldings:
+			while (oldFoldingIndex < oldFoldings.Length) {
+				FoldingSection oldSection = oldFoldings[oldFoldingIndex++];
+				if (oldSection.StartOffset >= firstErrorOffset)
+					break;
+				this.RemoveFolding(oldSection);
+			}
+		}
+		#endregion
+		
+		#region Install
+		/// <summary>
+		/// Adds Folding support to the specified text area.
+		/// Warning: The folding manager is only valid for the text area's current document. The folding manager
+		/// must be uninstalled before the text area is bound to a different document.
+		/// </summary>
+		/// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns>
+		public static FoldingManager Install(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			return new FoldingManagerInstallation(textArea);
+		}
+		
+		/// <summary>
+		/// Uninstalls the folding manager.
+		/// </summary>
+		/// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception>
+		public static void Uninstall(FoldingManager manager)
+		{
+			if (manager == null)
+				throw new ArgumentNullException("manager");
+			FoldingManagerInstallation installation = manager as FoldingManagerInstallation;
+			if (installation != null) {
+				installation.Uninstall();
+			} else {
+				throw new ArgumentException("FoldingManager was not created using FoldingManager.Install");
+			}
+		}
+		
+		sealed class FoldingManagerInstallation : FoldingManager
+		{
+			TextArea textArea;
+			FoldingMargin margin;
+			FoldingElementGenerator generator;
+			
+			public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document)
+			{
+				this.textArea = textArea;
+				margin = new FoldingMargin() { FoldingManager = this };
+				generator = new FoldingElementGenerator() { FoldingManager = this };
+				textArea.LeftMargins.Add(margin);
+				textArea.TextView.Services.AddService(typeof(FoldingManager), this);
+				// HACK: folding only works correctly when it has highest priority
+				textArea.TextView.ElementGenerators.Insert(0, generator);
+				textArea.Caret.PositionChanged += textArea_Caret_PositionChanged;
+			}
+			
+			/*
+			void DemoMode()
+			{
+				foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm };
+				foldingMargin = new FoldingMargin { FoldingManager = fm };
+				foldingMarginBorder = new Border {
+					Child = foldingMargin,
+					Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0)
+				};
+				foldingMarginBorder.SizeChanged += UpdateTextViewClip;
+				textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator);
+				textEditor.TextArea.LeftMargins.Add(foldingMarginBorder);
+			}
+			
+			void UpdateTextViewClip(object sender, SizeChangedEventArgs e)
+			{
+				textEditor.TextArea.TextView.Clip = new RectangleGeometry(
+					new Rect(-foldingMarginBorder.ActualWidth,
+					         0,
+					         textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth,
+					         textEditor.TextArea.TextView.ActualHeight));
+			}
+			 */
+			
+			public void Uninstall()
+			{
+				Clear();
+				if (textArea != null) {
+					textArea.Caret.PositionChanged -= textArea_Caret_PositionChanged;
+					textArea.LeftMargins.Remove(margin);
+					textArea.TextView.ElementGenerators.Remove(generator);
+					textArea.TextView.Services.RemoveService(typeof(FoldingManager));
+					margin = null;
+					generator = null;
+					textArea = null;
+				}
+			}
+			
+			void textArea_Caret_PositionChanged(object sender, EventArgs e)
+			{
+				// Expand Foldings when Caret is moved into them.
+				int caretOffset = textArea.Caret.Offset;
+				foreach (FoldingSection s in GetFoldingsContaining(caretOffset)) {
+					if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) {
+						s.IsFolded = false;
+					}
+				}
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingMargin.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingMargin.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingMargin.cs	(revision 11807)
@@ -0,0 +1,350 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	/// <summary>
+	/// A margin that shows markers for foldings and allows to expand/collapse the foldings.
+	/// </summary>
+	public class FoldingMargin : AbstractMargin
+	{
+		/// <summary>
+		/// Gets/Sets the folding manager from which the foldings should be shown.
+		/// </summary>
+		public FoldingManager FoldingManager { get; set; }
+		
+		internal const double SizeFactor = Constants.PixelPerPoint;
+		
+		#region Brushes
+		/// <summary>
+		/// FoldingMarkerBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty FoldingMarkerBrushProperty =
+			DependencyProperty.RegisterAttached("FoldingMarkerBrush", typeof(Brush), typeof(FoldingMargin),
+			                                    new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying the lines of folding markers.
+		/// </summary>
+		public Brush FoldingMarkerBrush {
+			get { return (Brush)GetValue(FoldingMarkerBrushProperty); }
+			set { SetValue(FoldingMarkerBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// FoldingMarkerBackgroundBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty FoldingMarkerBackgroundBrushProperty =
+			DependencyProperty.RegisterAttached("FoldingMarkerBackgroundBrush", typeof(Brush), typeof(FoldingMargin),
+			                                    new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying the background of folding markers.
+		/// </summary>
+		public Brush FoldingMarkerBackgroundBrush {
+			get { return (Brush)GetValue(FoldingMarkerBackgroundBrushProperty); }
+			set { SetValue(FoldingMarkerBackgroundBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// SelectedFoldingMarkerBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty SelectedFoldingMarkerBrushProperty =
+			DependencyProperty.RegisterAttached("SelectedFoldingMarkerBrush",
+			                                    typeof(Brush), typeof(FoldingMargin),
+			                                    new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying the lines of selected folding markers.
+		/// </summary>
+		public Brush SelectedFoldingMarkerBrush {
+			get { return (Brush)GetValue(SelectedFoldingMarkerBrushProperty); }
+			set { SetValue(SelectedFoldingMarkerBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// SelectedFoldingMarkerBackgroundBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty SelectedFoldingMarkerBackgroundBrushProperty =
+			DependencyProperty.RegisterAttached("SelectedFoldingMarkerBackgroundBrush",
+			                                    typeof(Brush), typeof(FoldingMargin),
+			                                    new FrameworkPropertyMetadata(Brushes.White, FrameworkPropertyMetadataOptions.Inherits, OnUpdateBrushes));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying the background of selected folding markers.
+		/// </summary>
+		public Brush SelectedFoldingMarkerBackgroundBrush {
+			get { return (Brush)GetValue(SelectedFoldingMarkerBackgroundBrushProperty); }
+			set { SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); }
+		}
+		
+		static void OnUpdateBrushes(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			FoldingMargin m = null;
+			if (d is FoldingMargin)
+				m = (FoldingMargin)d;
+			else if (d is TextEditor)
+				m = ((TextEditor)d).TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin;
+			if (m == null) return;
+			if (e.Property.Name == FoldingMarkerBrushProperty.Name)
+				m.foldingControlPen = MakeFrozenPen((Brush)e.NewValue);
+			if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name)
+				m.selectedFoldingControlPen = MakeFrozenPen((Brush)e.NewValue);
+		}
+		#endregion
+		
+		/// <inheritdoc/>
+		protected override Size MeasureOverride(Size availableSize)
+		{
+			foreach (FoldingMarginMarker m in markers) {
+				m.Measure(availableSize);
+			}
+			double width = SizeFactor * (double)GetValue(TextBlock.FontSizeProperty);
+			return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0);
+		}
+		
+		/// <inheritdoc/>
+		protected override Size ArrangeOverride(Size finalSize)
+		{
+			Size pixelSize = PixelSnapHelpers.GetPixelSize(this);
+			foreach (FoldingMarginMarker m in markers) {
+				int visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset);
+				TextLine textLine = m.VisualLine.GetTextLine(visualColumn);
+				double yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset;
+				yPos -= m.DesiredSize.Height / 2;
+				double xPos = (finalSize.Width - m.DesiredSize.Width) / 2;
+				m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize));
+			}
+			return base.ArrangeOverride(finalSize);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView)
+		{
+			if (oldTextView != null) {
+				oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
+			}
+			base.OnTextViewChanged(oldTextView, newTextView);
+			if (newTextView != null) {
+				newTextView.VisualLinesChanged += TextViewVisualLinesChanged;
+			}
+			TextViewVisualLinesChanged(null, null);
+		}
+		
+		List<FoldingMarginMarker> markers = new List<FoldingMarginMarker>();
+		
+		void TextViewVisualLinesChanged(object sender, EventArgs e)
+		{
+			foreach (FoldingMarginMarker m in markers) {
+				RemoveVisualChild(m);
+			}
+			markers.Clear();
+			InvalidateVisual();
+			if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) {
+				foreach (VisualLine line in TextView.VisualLines) {
+					FoldingSection fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset);
+					if (fs == null)
+						continue;
+					if (fs.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) {
+						FoldingMarginMarker m = new FoldingMarginMarker {
+							IsExpanded = !fs.IsFolded,
+							VisualLine = line,
+							FoldingSection = fs
+						};
+						
+						markers.Add(m);
+						AddVisualChild(m);
+						
+						m.IsMouseDirectlyOverChanged += delegate { InvalidateVisual(); };
+						
+						InvalidateMeasure();
+						continue;
+					}
+				}
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override int VisualChildrenCount {
+			get { return markers.Count; }
+		}
+		
+		/// <inheritdoc/>
+		protected override Visual GetVisualChild(int index)
+		{
+			return markers[index];
+		}
+		
+		Pen foldingControlPen = MakeFrozenPen((Brush)FoldingMarkerBrushProperty.DefaultMetadata.DefaultValue);
+		Pen selectedFoldingControlPen = MakeFrozenPen((Brush)SelectedFoldingMarkerBrushProperty.DefaultMetadata.DefaultValue);
+		
+		static Pen MakeFrozenPen(Brush brush)
+		{
+			Pen pen = new Pen(brush, 1);
+			pen.Freeze();
+			return pen;
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			if (TextView == null || !TextView.VisualLinesValid)
+				return;
+			if (TextView.VisualLines.Count == 0 || FoldingManager == null)
+				return;
+			
+			var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList();
+			Pen[] colors = new Pen[allTextLines.Count + 1];
+			Pen[] endMarker = new Pen[allTextLines.Count];
+			
+			CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker);
+			CalculateFoldLinesForMarkers(allTextLines, colors, endMarker);
+			DrawFoldLines(drawingContext, colors, endMarker);
+			
+			base.OnRender(drawingContext);
+		}
+
+		/// <summary>
+		/// Calculates fold lines for all folding sections that start in front of the current view
+		/// and run into the current view.
+		/// </summary>
+		void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker)
+		{
+			int viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset;
+			int viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset;
+			var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset);
+			int maxEndOffset = 0;
+			foreach (FoldingSection fs in foldings) {
+				int end = fs.EndOffset;
+				if (end <= viewEndOffset && !fs.IsFolded) {
+					int textLineNr = GetTextLineIndexFromOffset(allTextLines, end);
+					if (textLineNr >= 0) {
+						endMarker[textLineNr] = foldingControlPen;
+					}
+				}
+				if (end > maxEndOffset && fs.StartOffset < viewStartOffset) {
+					maxEndOffset = end;
+				}
+			}
+			if (maxEndOffset > 0) {
+				if (maxEndOffset > viewEndOffset) {
+					for (int i = 0; i < colors.Length; i++) {
+						colors[i] = foldingControlPen;
+					}
+				} else {
+					int maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset);
+					for (int i = 0; i <= maxTextLine; i++) {
+						colors[i] = foldingControlPen;
+					}
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Calculates fold lines for all folding sections that start inside the current view
+		/// </summary>
+		void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker)
+		{
+			foreach (FoldingMarginMarker marker in markers) {
+				int end = marker.FoldingSection.EndOffset;
+				int endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end);
+				if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) {
+					if (marker.IsMouseDirectlyOver)
+						endMarker[endTextLineNr] = selectedFoldingControlPen;
+					else if (endMarker[endTextLineNr] == null)
+						endMarker[endTextLineNr] = foldingControlPen;
+				}
+				int startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset);
+				if (startTextLineNr >= 0) {
+					for (int i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) {
+						if (marker.IsMouseDirectlyOver)
+							colors[i] = selectedFoldingControlPen;
+						else if (colors[i] == null)
+							colors[i] = foldingControlPen;
+					}
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker')
+		/// Each entry in the input arrays corresponds to one TextLine.
+		/// </summary>
+		void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker)
+		{
+			// Because we are using PenLineCap.Flat (the default), for vertical lines,
+			// Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the
+			// middle of a pixel. (and the other way round for horizontal lines)
+			Size pixelSize = PixelSnapHelpers.GetPixelSize(this);
+			double markerXPos = PixelSnapHelpers.PixelAlign(RenderSize.Width / 2, pixelSize.Width);
+			double startY = 0;
+			Pen currentPen = colors[0];
+			int tlNumber = 0;
+			foreach (VisualLine vl in TextView.VisualLines) {
+				foreach (TextLine tl in vl.TextLines) {
+					if (endMarker[tlNumber] != null) {
+						double visualPos = GetVisualPos(vl, tl, pixelSize.Height);
+						drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(RenderSize.Width, visualPos));
+					}
+					if (colors[tlNumber + 1] != currentPen) {
+						double visualPos = GetVisualPos(vl, tl, pixelSize.Height);
+						if (currentPen != null) {
+							drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2));
+						}
+						currentPen = colors[tlNumber + 1];
+						startY = visualPos;
+					}
+					tlNumber++;
+				}
+			}
+			if (currentPen != null) {
+				drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, RenderSize.Height));
+			}
+		}
+		
+		double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight)
+		{
+			double pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset;
+			return PixelSnapHelpers.PixelAlign(pos, pixelHeight);
+		}
+		
+		int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset)
+		{
+			int lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber;
+			VisualLine vl = TextView.GetVisualLine(lineNumber);
+			if (vl != null) {
+				int relOffset = offset - vl.FirstDocumentLine.Offset;
+				TextLine line = vl.GetTextLine(vl.GetVisualColumn(relOffset));
+				return textLines.IndexOf(line);
+			}
+			return -1;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingMarginMarker.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingMarginMarker.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingMarginMarker.cs	(revision 11807)
@@ -0,0 +1,103 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	sealed class FoldingMarginMarker : UIElement
+	{
+		internal VisualLine VisualLine;
+		internal FoldingSection FoldingSection;
+		
+		bool isExpanded;
+		
+		public bool IsExpanded {
+			get { return isExpanded; }
+			set {
+				if (isExpanded != value) {
+					isExpanded = value;
+					InvalidateVisual();
+				}
+				if (FoldingSection != null)
+					FoldingSection.IsFolded = !value;
+			}
+		}
+		
+		protected override void OnMouseDown(MouseButtonEventArgs e)
+		{
+			base.OnMouseDown(e);
+			if (!e.Handled) {
+				if (e.ChangedButton == MouseButton.Left) {
+					IsExpanded = !IsExpanded;
+					e.Handled = true;
+				}
+			}
+		}
+		
+		const double MarginSizeFactor = 0.7;
+		
+		protected override Size MeasureCore(Size availableSize)
+		{
+			double size = MarginSizeFactor * FoldingMargin.SizeFactor * (double)GetValue(TextBlock.FontSizeProperty);
+			size = PixelSnapHelpers.RoundToOdd(size, PixelSnapHelpers.GetPixelSize(this).Width);
+			return new Size(size, size);
+		}
+		
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			FoldingMargin margin = VisualParent as FoldingMargin;
+			Pen activePen = new Pen(margin.SelectedFoldingMarkerBrush, 1);
+			Pen inactivePen = new Pen(margin.FoldingMarkerBrush, 1);
+			activePen.StartLineCap = inactivePen.StartLineCap = PenLineCap.Square;
+			activePen.EndLineCap = inactivePen.EndLineCap = PenLineCap.Square;
+			Size pixelSize = PixelSnapHelpers.GetPixelSize(this);
+			Rect rect = new Rect(pixelSize.Width / 2,
+			                     pixelSize.Height / 2,
+			                     this.RenderSize.Width - pixelSize.Width,
+			                     this.RenderSize.Height - pixelSize.Height);
+			drawingContext.DrawRectangle(
+				IsMouseDirectlyOver ? margin.SelectedFoldingMarkerBackgroundBrush : margin.FoldingMarkerBackgroundBrush,
+				IsMouseDirectlyOver ? activePen : inactivePen, rect);
+			double middleX = rect.Left + rect.Width / 2;
+			double middleY = rect.Top + rect.Height / 2;
+			double space = PixelSnapHelpers.Round(rect.Width / 8, pixelSize.Width) + pixelSize.Width;
+			drawingContext.DrawLine(activePen,
+			                        new Point(rect.Left + space, middleY),
+			                        new Point(rect.Right - space, middleY));
+			if (!isExpanded) {
+				drawingContext.DrawLine(activePen,
+				                        new Point(middleX, rect.Top + space),
+				                        new Point(middleX, rect.Bottom - space));
+			}
+		}
+		
+		protected override void OnIsMouseDirectlyOverChanged(DependencyPropertyChangedEventArgs e)
+		{
+			base.OnIsMouseDirectlyOverChanged(e);
+			InvalidateVisual();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingSection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingSection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/FoldingSection.cs	(revision 11807)
@@ -0,0 +1,203 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Text;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#endif
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	/// <summary>
+	/// A section that can be folded.
+	/// </summary>
+	public sealed class FoldingSection : TextSegment
+	{
+		readonly FoldingManager manager;
+		bool isFolded;
+		internal CollapsedLineSection[] collapsedSections;
+		string title;
+		
+		/// <summary>
+		/// Gets/sets if the section is folded.
+		/// </summary>
+		public bool IsFolded {
+			get { return isFolded; }
+			set {
+				if (isFolded != value) {
+					isFolded = value;
+					ValidateCollapsedLineSections(); // create/destroy CollapsedLineSection
+						manager.Redraw(this);
+				}
+			}
+		}
+		
+		internal void ValidateCollapsedLineSections()
+		{
+			if (!isFolded) {
+				RemoveCollapsedLineSection();
+				return;
+			}
+			// It is possible that StartOffset/EndOffset get set to invalid values via the property setters in TextSegment,
+			// so we coerce those values into the valid range.
+			DocumentLine startLine = manager.document.GetLineByOffset(StartOffset.CoerceValue(0, manager.document.TextLength));
+			DocumentLine endLine = manager.document.GetLineByOffset(EndOffset.CoerceValue(0, manager.document.TextLength));
+			if (startLine == endLine) {
+				RemoveCollapsedLineSection();
+			} else {
+				if (collapsedSections == null)
+					collapsedSections = new CollapsedLineSection[manager.textViews.Count];
+				// Validate collapsed line sections
+				DocumentLine startLinePlusOne = startLine.NextLine;
+				for (int i = 0; i < collapsedSections.Length; i++) {
+					var collapsedSection = collapsedSections[i];
+					if (collapsedSection == null || collapsedSection.Start != startLinePlusOne || collapsedSection.End != endLine) {
+						// recreate this collapsed section
+						if (collapsedSection != null) {
+							Debug.WriteLine("CollapsedLineSection validation - recreate collapsed section from " + startLinePlusOne + " to " + endLine);
+							collapsedSection.Uncollapse();
+						}
+						collapsedSections[i] = manager.textViews[i].CollapseLines(startLinePlusOne, endLine);
+					}
+				}
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnSegmentChanged()
+		{
+			ValidateCollapsedLineSections();
+			base.OnSegmentChanged();
+			// don't redraw if the FoldingSection wasn't added to the FoldingManager's collection yet
+			if (IsConnectedToCollection)
+				manager.Redraw(this);
+		}
+		
+		/// <summary>
+		/// Gets/Sets the text used to display the collapsed version of the folding section.
+		/// </summary>
+		public string Title {
+			get {
+				return title;
+			}
+			set {
+				if (title != value) {
+					title = value;
+					if (this.IsFolded)
+						manager.Redraw(this);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the content of the collapsed lines as text.
+		/// </summary>
+		public string TextContent {
+			get {
+				return manager.document.GetText(StartOffset, EndOffset - StartOffset);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the content of the collapsed lines as tooltip text.
+		/// </summary>
+		[Obsolete]
+		public string TooltipText {
+			get {
+				// This fixes SD-1394:
+				// Each line is checked for leading indentation whitespaces. If
+				// a line has the same or more indentation than the first line,
+				// it is reduced. If a line is less indented than the first line
+				// the indentation is removed completely.
+				//
+				// See the following example:
+				// 	line 1
+				// 		line 2
+				// 			line 3
+				//  line 4
+				//
+				// is reduced to:
+				// line 1
+				// 	line 2
+				// 		line 3
+				// line 4
+				
+				var startLine = manager.document.GetLineByOffset(StartOffset);
+				var endLine = manager.document.GetLineByOffset(EndOffset);
+				var builder = new StringBuilder();
+				
+				var current = startLine;
+				ISegment startIndent = TextUtilities.GetLeadingWhitespace(manager.document, startLine);
+				
+				while (current != endLine.NextLine) {
+					ISegment currentIndent = TextUtilities.GetLeadingWhitespace(manager.document, current);
+					
+					if (current == startLine && current == endLine)
+						builder.Append(manager.document.GetText(StartOffset, EndOffset - StartOffset));
+					else if (current == startLine) {
+						if (current.EndOffset - StartOffset > 0)
+							builder.AppendLine(manager.document.GetText(StartOffset, current.EndOffset - StartOffset).TrimStart());
+					} else if (current == endLine) {
+						if (startIndent.Length <= currentIndent.Length)
+							builder.Append(manager.document.GetText(current.Offset + startIndent.Length, EndOffset - current.Offset - startIndent.Length));
+						else
+							builder.Append(manager.document.GetText(current.Offset + currentIndent.Length, EndOffset - current.Offset - currentIndent.Length));
+					} else {
+						if (startIndent.Length <= currentIndent.Length)
+							builder.AppendLine(manager.document.GetText(current.Offset + startIndent.Length, current.Length - startIndent.Length));
+						else
+							builder.AppendLine(manager.document.GetText(current.Offset + currentIndent.Length, current.Length - currentIndent.Length));
+					}
+					
+					current = current.NextLine;
+				}
+				
+				return builder.ToString();
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets an additional object associated with this folding section.
+		/// </summary>
+		public object Tag { get; set; }
+		
+		internal FoldingSection(FoldingManager manager, int startOffset, int endOffset)
+		{
+			Debug.Assert(manager != null);
+			this.manager = manager;
+			this.StartOffset = startOffset;
+			this.Length = endOffset - startOffset;
+		}
+		
+		void RemoveCollapsedLineSection()
+		{
+			if (collapsedSections != null) {
+				foreach (var collapsedSection in collapsedSections) {
+					if (collapsedSection != null && collapsedSection.Start != null)
+						collapsedSection.Uncollapse();
+				}
+				collapsedSections = null;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/NewFolding.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/NewFolding.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/NewFolding.cs	(revision 11807)
@@ -0,0 +1,87 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	/// <summary>
+	/// Helper class used for <see cref="FoldingManager.UpdateFoldings"/>.
+	/// </summary>
+	public class NewFolding : ISegment
+	{
+		/// <summary>
+		/// Gets/Sets the start offset.
+		/// </summary>
+		public int StartOffset { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the end offset.
+		/// </summary>
+		public int EndOffset { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the name displayed for the folding.
+		/// </summary>
+		public string Name { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether the folding is closed by default.
+		/// </summary>
+		public bool DefaultClosed { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether the folding is considered to be a definition.
+		/// This has an effect on the 'Show Definitions only' command.
+		/// </summary>
+		public bool IsDefinition { get; set; }
+		
+		/// <summary>
+		/// Creates a new NewFolding instance.
+		/// </summary>
+		public NewFolding()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new NewFolding instance.
+		/// </summary>
+		public NewFolding(int start, int end)
+		{
+			if (!(start <= end))
+				throw new ArgumentException("'start' must be less than 'end'");
+			this.StartOffset = start;
+			this.EndOffset = end;
+			this.Name = null;
+			this.DefaultClosed = false;
+		}
+		
+		int ISegment.Offset {
+			get { return this.StartOffset; }
+		}
+		
+		int ISegment.Length {
+			get { return this.EndOffset - this.StartOffset; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/XmlFoldingStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/XmlFoldingStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Folding/XmlFoldingStrategy.cs	(revision 11807)
@@ -0,0 +1,240 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Xml;
+
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Folding
+{
+	/// <summary>
+	/// Holds information about the start of a fold in an xml string.
+	/// </summary>
+	sealed class XmlFoldStart : NewFolding
+	{
+		internal int StartLine;
+	}
+	
+	/// <summary>
+	/// Determines folds for an xml string in the editor.
+	/// </summary>
+	public class XmlFoldingStrategy
+	{
+		/// <summary>
+		/// Flag indicating whether attributes should be displayed on folded
+		/// elements.
+		/// </summary>
+		public bool ShowAttributesWhenFolded { get; set; }
+		
+		/// <summary>
+		/// Create <see cref="NewFolding"/>s for the specified document and updates the folding manager with them.
+		/// </summary>
+		public void UpdateFoldings(FoldingManager manager, TextDocument document)
+		{
+			int firstErrorOffset;
+			IEnumerable<NewFolding> foldings = CreateNewFoldings(document, out firstErrorOffset);
+			manager.UpdateFoldings(foldings, firstErrorOffset);
+		}
+		
+		/// <summary>
+		/// Create <see cref="NewFolding"/>s for the specified document.
+		/// </summary>
+		public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
+		{
+			try {
+				XmlTextReader reader = new XmlTextReader(document.CreateReader());
+				reader.XmlResolver = null; // don't resolve DTDs
+				return CreateNewFoldings(document, reader, out firstErrorOffset);
+			} catch (XmlException) {
+				firstErrorOffset = 0;
+				return Enumerable.Empty<NewFolding>();
+			}
+		}
+		
+		/// <summary>
+		/// Create <see cref="NewFolding"/>s for the specified document.
+		/// </summary>
+		public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, XmlReader reader, out int firstErrorOffset)
+		{
+			Stack<XmlFoldStart> stack = new Stack<XmlFoldStart>();
+			List<NewFolding> foldMarkers = new List<NewFolding>();
+			try {
+				while (reader.Read()) {
+					switch (reader.NodeType) {
+						case XmlNodeType.Element:
+							if (!reader.IsEmptyElement) {
+								XmlFoldStart newFoldStart = CreateElementFoldStart(document, reader);
+								stack.Push(newFoldStart);
+							}
+							break;
+							
+						case XmlNodeType.EndElement:
+							XmlFoldStart foldStart = stack.Pop();
+							CreateElementFold(document, foldMarkers, reader, foldStart);
+							break;
+							
+						case XmlNodeType.Comment:
+							CreateCommentFold(document, foldMarkers, reader);
+							break;
+					}
+				}
+				firstErrorOffset = -1;
+			} catch (XmlException ex) {
+				// ignore errors at invalid positions (prevent ArgumentOutOfRangeException)
+				if (ex.LineNumber >= 1 && ex.LineNumber <= document.LineCount)
+					firstErrorOffset = document.GetOffset(ex.LineNumber, ex.LinePosition);
+				else
+					firstErrorOffset = 0;
+			}
+			foldMarkers.Sort((a,b) => a.StartOffset.CompareTo(b.StartOffset));
+			return foldMarkers;
+		}
+		
+		static int GetOffset(TextDocument document, XmlReader reader)
+		{
+			IXmlLineInfo info = reader as IXmlLineInfo;
+			if (info != null && info.HasLineInfo()) {
+				return document.GetOffset(info.LineNumber, info.LinePosition);
+			} else {
+				throw new ArgumentException("XmlReader does not have positioning information.");
+			}
+		}
+		
+		/// <summary>
+		/// Creates a comment fold if the comment spans more than one line.
+		/// </summary>
+		/// <remarks>The text displayed when the comment is folded is the first
+		/// line of the comment.</remarks>
+		static void CreateCommentFold(TextDocument document, List<NewFolding> foldMarkers, XmlReader reader)
+		{
+			string comment = reader.Value;
+			if (comment != null) {
+				int firstNewLine = comment.IndexOf('\n');
+				if (firstNewLine >= 0) {
+					
+					// Take off 4 chars to get the actual comment start (takes
+					// into account the <!-- chars.
+					
+					int startOffset = GetOffset(document, reader) - 4;
+					int endOffset = startOffset + comment.Length + 7;
+					
+					string foldText = String.Concat("<!--", comment.Substring(0, firstNewLine).TrimEnd('\r') , "-->");
+					foldMarkers.Add(new NewFolding(startOffset, endOffset) { Name = foldText } );
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Creates an XmlFoldStart for the start tag of an element.
+		/// </summary>
+		XmlFoldStart CreateElementFoldStart(TextDocument document, XmlReader reader)
+		{
+			// Take off 1 from the offset returned
+			// from the xml since it points to the start
+			// of the element name and not the beginning
+			// tag.
+			//XmlFoldStart newFoldStart = new XmlFoldStart(reader.Prefix, reader.LocalName, reader.LineNumber - 1, reader.LinePosition - 2);
+			XmlFoldStart newFoldStart = new XmlFoldStart();
+			
+			IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
+			newFoldStart.StartLine = lineInfo.LineNumber;
+			newFoldStart.StartOffset = document.GetOffset(newFoldStart.StartLine, lineInfo.LinePosition - 1);
+			
+			if (this.ShowAttributesWhenFolded && reader.HasAttributes) {
+				newFoldStart.Name = String.Concat("<", reader.Name, " ", GetAttributeFoldText(reader), ">");
+			} else {
+				newFoldStart.Name = String.Concat("<", reader.Name, ">");
+			}
+			
+			return newFoldStart;
+		}
+		
+		/// <summary>
+		/// Create an element fold if the start and end tag are on
+		/// different lines.
+		/// </summary>
+		static void CreateElementFold(TextDocument document, List<NewFolding> foldMarkers, XmlReader reader, XmlFoldStart foldStart)
+		{
+			IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
+			int endLine = lineInfo.LineNumber;
+			if (endLine > foldStart.StartLine) {
+				int endCol = lineInfo.LinePosition + reader.Name.Length + 1;
+				foldStart.EndOffset = document.GetOffset(endLine, endCol);
+				foldMarkers.Add(foldStart);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the element's attributes as a string on one line that will
+		/// be displayed when the element is folded.
+		/// </summary>
+		/// <remarks>
+		/// Currently this puts all attributes from an element on the same
+		/// line of the start tag.  It does not cater for elements where attributes
+		/// are not on the same line as the start tag.
+		/// </remarks>
+		static string GetAttributeFoldText(XmlReader reader)
+		{
+			StringBuilder text = new StringBuilder();
+			
+			for (int i = 0; i < reader.AttributeCount; ++i) {
+				reader.MoveToAttribute(i);
+				
+				text.Append(reader.Name);
+				text.Append("=");
+				text.Append(reader.QuoteChar.ToString());
+				text.Append(XmlEncodeAttributeValue(reader.Value, reader.QuoteChar));
+				text.Append(reader.QuoteChar.ToString());
+				
+				// Append a space if this is not the
+				// last attribute.
+				if (i < reader.AttributeCount - 1) {
+					text.Append(" ");
+				}
+			}
+			
+			return text.ToString();
+		}
+		
+		/// <summary>
+		/// Xml encode the attribute string since the string returned from
+		/// the XmlTextReader is the plain unencoded string and .NET
+		/// does not provide us with an xml encode method.
+		/// </summary>
+		static string XmlEncodeAttributeValue(string attributeValue, char quoteChar)
+		{
+			StringBuilder encodedValue = new StringBuilder(attributeValue);
+			
+			encodedValue.Replace("&", "&amp;");
+			encodedValue.Replace("<", "&lt;");
+			encodedValue.Replace(">", "&gt;");
+			
+			if (quoteChar == '"') {
+				encodedValue.Replace("\"", "&quot;");
+			} else {
+				encodedValue.Replace("'", "&apos;");
+			}
+			
+			return encodedValue.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/DocumentHighlighter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/DocumentHighlighter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/DocumentHighlighter.cs	(revision 11807)
@@ -0,0 +1,348 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+using SpanStack = ICSharpCode.AvalonEdit.Utils.ImmutableStack<ICSharpCode.AvalonEdit.Highlighting.HighlightingSpan>;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// This class can syntax-highlight a document.
+	/// It automatically manages invalidating the highlighting when the document changes.
+	/// </summary>
+	public class DocumentHighlighter : ILineTracker, IHighlighter
+	{
+		/// <summary>
+		/// Stores the span state at the end of each line.
+		/// storedSpanStacks[0] = state at beginning of document
+		/// storedSpanStacks[i] = state after line i
+		/// </summary>
+		readonly CompressingTreeList<SpanStack> storedSpanStacks = new CompressingTreeList<SpanStack>(object.ReferenceEquals);
+		readonly CompressingTreeList<bool> isValid = new CompressingTreeList<bool>((a, b) => a == b);
+		readonly IDocument document;
+		readonly IHighlightingDefinition definition;
+		readonly HighlightingEngine engine;
+		readonly WeakLineTracker weakLineTracker;
+		bool isHighlighting;
+		bool isInHighlightingGroup;
+		bool isDisposed;
+		
+		/// <summary>
+		/// Gets the document that this DocumentHighlighter is highlighting.
+		/// </summary>
+		public IDocument Document {
+			get { return document; }
+		}
+		
+		/// <summary>
+		/// Creates a new DocumentHighlighter instance.
+		/// </summary>
+		public DocumentHighlighter(TextDocument document, IHighlightingDefinition definition)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (definition == null)
+				throw new ArgumentNullException("definition");
+			this.document = document;
+			this.definition = definition;
+			this.engine = new HighlightingEngine(definition.MainRuleSet);
+			document.VerifyAccess();
+			weakLineTracker = WeakLineTracker.Register(document, this);
+			InvalidateHighlighting();
+		}
+		
+		#if NREFACTORY
+		/// <summary>
+		/// Creates a new DocumentHighlighter instance.
+		/// </summary>
+		public DocumentHighlighter(ReadOnlyDocument document, IHighlightingDefinition definition)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (definition == null)
+				throw new ArgumentNullException("definition");
+			this.document = document;
+			this.definition = definition;
+			this.engine = new HighlightingEngine(definition.MainRuleSet);
+			InvalidateHighlighting();
+		}
+		#endif
+		
+		/// <summary>
+		/// Disposes the document highlighter.
+		/// </summary>
+		public void Dispose()
+		{
+			if (weakLineTracker != null)
+				weakLineTracker.Deregister();
+			isDisposed = true;
+		}
+		
+		void ILineTracker.BeforeRemoveLine(DocumentLine line)
+		{
+			CheckIsHighlighting();
+			int number = line.LineNumber;
+			storedSpanStacks.RemoveAt(number);
+			isValid.RemoveAt(number);
+			if (number < isValid.Count) {
+				isValid[number] = false;
+				if (number < firstInvalidLine)
+					firstInvalidLine = number;
+			}
+		}
+		
+		void ILineTracker.SetLineLength(DocumentLine line, int newTotalLength)
+		{
+			CheckIsHighlighting();
+			int number = line.LineNumber;
+			isValid[number] = false;
+			if (number < firstInvalidLine)
+				firstInvalidLine = number;
+		}
+		
+		void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
+		{
+			CheckIsHighlighting();
+			Debug.Assert(insertionPos.LineNumber + 1 == newLine.LineNumber);
+			int lineNumber = newLine.LineNumber;
+			storedSpanStacks.Insert(lineNumber, null);
+			isValid.Insert(lineNumber, false);
+			if (lineNumber < firstInvalidLine)
+				firstInvalidLine = lineNumber;
+		}
+		
+		void ILineTracker.RebuildDocument()
+		{
+			InvalidateHighlighting();
+		}
+		
+		void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
+		{
+		}
+		
+		ImmutableStack<HighlightingSpan> initialSpanStack = SpanStack.Empty;
+		
+		/// <summary>
+		/// Gets/sets the the initial span stack of the document. Default value is <see cref="SpanStack.Empty" />.
+		/// </summary>
+		public ImmutableStack<HighlightingSpan> InitialSpanStack {
+			get { return initialSpanStack; }
+			set {
+				initialSpanStack = value ?? SpanStack.Empty;
+				InvalidateHighlighting();
+			}
+		}
+		
+		/// <summary>
+		/// Invalidates all stored highlighting info.
+		/// When the document changes, the highlighting is invalidated automatically, this method
+		/// needs to be called only when there are changes to the highlighting rule set.
+		/// </summary>
+		public void InvalidateHighlighting()
+		{
+			CheckIsHighlighting();
+			storedSpanStacks.Clear();
+			storedSpanStacks.Add(initialSpanStack);
+			storedSpanStacks.InsertRange(1, document.LineCount, null);
+			isValid.Clear();
+			isValid.Add(true);
+			isValid.InsertRange(1, document.LineCount, false);
+			firstInvalidLine = 1;
+		}
+		
+		int firstInvalidLine;
+		
+		/// <inheritdoc/>
+		public HighlightedLine HighlightLine(int lineNumber)
+		{
+			ThrowUtil.CheckInRangeInclusive(lineNumber, "lineNumber", 1, document.LineCount);
+			CheckIsHighlighting();
+			isHighlighting = true;
+			try {
+				HighlightUpTo(lineNumber - 1);
+				IDocumentLine line = document.GetLineByNumber(lineNumber);
+				HighlightedLine result = engine.HighlightLine(document, line);
+				UpdateTreeList(lineNumber);
+				return result;
+			} finally {
+				isHighlighting = false;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the span stack at the end of the specified line.
+		/// -> GetSpanStack(1) returns the spans at the start of the second line.
+		/// </summary>
+		/// <remarks>
+		/// GetSpanStack(0) is valid and will return <see cref="InitialSpanStack"/>.
+		/// The elements are returned in inside-out order (first element of result enumerable is the color of the innermost span).
+		/// </remarks>
+		public SpanStack GetSpanStack(int lineNumber)
+		{
+			ThrowUtil.CheckInRangeInclusive(lineNumber, "lineNumber", 0, document.LineCount);
+			if (firstInvalidLine <= lineNumber) {
+				UpdateHighlightingState(lineNumber);
+			}
+			return storedSpanStacks[lineNumber];
+		}
+		
+		/// <inheritdoc/>
+		public IEnumerable<HighlightingColor> GetColorStack(int lineNumber)
+		{
+			return GetSpanStack(lineNumber).Select(s => s.SpanColor).Where(s => s != null);
+		}
+		
+		void CheckIsHighlighting()
+		{
+			if (isDisposed) {
+				throw new ObjectDisposedException("DocumentHighlighter");
+			}
+			if (isHighlighting) {
+				throw new InvalidOperationException("Invalid call - a highlighting operation is currently running.");
+			}
+		}
+		
+		/// <inheritdoc/>
+		public void UpdateHighlightingState(int lineNumber)
+		{
+			CheckIsHighlighting();
+			isHighlighting = true;
+			try {
+				HighlightUpTo(lineNumber);
+			} finally {
+				isHighlighting = false;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the engine's CurrentSpanStack to the end of the target line.
+		/// Updates the span stack for all lines up to (and including) the target line, if necessary.
+		/// </summary>
+		void HighlightUpTo(int targetLineNumber)
+		{
+			for (int currentLine = 0; currentLine <= targetLineNumber; currentLine++) {
+				if (firstInvalidLine > currentLine) {
+					// (this branch is always taken on the first loop iteration, as firstInvalidLine > 0)
+					
+					if (firstInvalidLine <= targetLineNumber) {
+						// Skip valid lines to next invalid line:
+						engine.CurrentSpanStack = storedSpanStacks[firstInvalidLine - 1];
+						currentLine = firstInvalidLine;
+					} else {
+						// Skip valid lines to target line:
+						engine.CurrentSpanStack = storedSpanStacks[targetLineNumber];
+						break;
+					}
+				}
+				Debug.Assert(EqualSpanStacks(engine.CurrentSpanStack, storedSpanStacks[currentLine - 1]));
+				engine.ScanLine(document, document.GetLineByNumber(currentLine));
+				UpdateTreeList(currentLine);
+			}
+			Debug.Assert(EqualSpanStacks(engine.CurrentSpanStack, storedSpanStacks[targetLineNumber]));
+		}
+		
+		void UpdateTreeList(int lineNumber)
+		{
+			if (!EqualSpanStacks(engine.CurrentSpanStack, storedSpanStacks[lineNumber])) {
+				isValid[lineNumber] = true;
+				//Debug.WriteLine("Span stack in line " + lineNumber + " changed from " + storedSpanStacks[lineNumber] + " to " + spanStack);
+				storedSpanStacks[lineNumber] = engine.CurrentSpanStack;
+				if (lineNumber + 1 < isValid.Count) {
+					isValid[lineNumber + 1] = false;
+					firstInvalidLine = lineNumber + 1;
+				} else {
+					firstInvalidLine = int.MaxValue;
+				}
+				if (lineNumber + 1 < document.LineCount)
+					OnHighlightStateChanged(lineNumber + 1, lineNumber + 1);
+			} else if (firstInvalidLine == lineNumber) {
+				isValid[lineNumber] = true;
+				firstInvalidLine = isValid.IndexOf(false);
+				if (firstInvalidLine < 0)
+					firstInvalidLine = int.MaxValue;
+			}
+		}
+		
+		static bool EqualSpanStacks(SpanStack a, SpanStack b)
+		{
+			// We must use value equality between the stacks because HighlightingColorizer.OnHighlightStateChanged
+			// depends on the fact that equal input state + unchanged line contents produce equal output state.
+			if (a == b)
+				return true;
+			if (a == null || b == null)
+				return false;
+			while (!a.IsEmpty && !b.IsEmpty) {
+				if (a.Peek() != b.Peek())
+					return false;
+				a = a.Pop();
+				b = b.Pop();
+				if (a == b)
+					return true;
+			}
+			return a.IsEmpty && b.IsEmpty;
+		}
+		
+		/// <inheritdoc/>
+		public event HighlightingStateChangedEventHandler HighlightingStateChanged;
+		
+		/// <summary>
+		/// Is called when the highlighting state at the end of the specified line has changed.
+		/// </summary>
+		/// <remarks>This callback must not call HighlightLine or InvalidateHighlighting.
+		/// It may call GetSpanStack, but only for the changed line and lines above.
+		/// This method must not modify the document.</remarks>
+		protected virtual void OnHighlightStateChanged(int fromLineNumber, int toLineNumber)
+		{
+			if (HighlightingStateChanged != null)
+				HighlightingStateChanged(fromLineNumber, toLineNumber);
+		}
+		
+		/// <inheritdoc/>
+		public HighlightingColor DefaultTextColor {
+			get { return null; }
+		}
+		
+		/// <inheritdoc/>
+		public void BeginHighlighting()
+		{
+			if (isInHighlightingGroup)
+				throw new InvalidOperationException("Highlighting group is already open");
+			isInHighlightingGroup = true;
+		}
+		
+		/// <inheritdoc/>
+		public void EndHighlighting()
+		{
+			if (!isInHighlightingGroup)
+				throw new InvalidOperationException("Highlighting group is not open");
+			isInHighlightingGroup = false;
+		}
+		
+		/// <inheritdoc/>
+		public HighlightingColor GetNamedColor(string name)
+		{
+			return definition.GetNamedColor(name);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedInlineBuilder.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedInlineBuilder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedInlineBuilder.cs	(revision 11807)
@@ -0,0 +1,205 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Takes a series of highlighting commands and stores them.
+	/// Later, it can build inline objects (for use with WPF TextBlock) from the commands.
+	/// </summary>
+	/// <remarks>
+	/// This class is not used in AvalonEdit - but it is useful for someone who wants to put a HighlightedLine
+	/// into a TextBlock.
+	/// In SharpDevelop, we use it to provide syntax highlighting inside the search results pad.
+	/// </remarks>
+	[Obsolete("Use RichText / RichTextModel instead")]
+	public sealed class HighlightedInlineBuilder
+	{
+		static HighlightingBrush MakeBrush(Brush b)
+		{
+			SolidColorBrush scb = b as SolidColorBrush;
+			if (scb != null)
+				return new SimpleHighlightingBrush(scb);
+			else
+				return null;
+		}
+		
+		readonly string text;
+		List<int> stateChangeOffsets = new List<int>();
+		List<HighlightingColor> stateChanges = new List<HighlightingColor>();
+		
+		int GetIndexForOffset(int offset)
+		{
+			if (offset < 0 || offset > text.Length)
+				throw new ArgumentOutOfRangeException("offset");
+			int index = stateChangeOffsets.BinarySearch(offset);
+			if (index < 0) {
+				index = ~index;
+				if (offset < text.Length) {
+					stateChanges.Insert(index, stateChanges[index - 1].Clone());
+					stateChangeOffsets.Insert(index, offset);
+				}
+			}
+			return index;
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightedInlineBuilder instance.
+		/// </summary>
+		public HighlightedInlineBuilder(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+			stateChangeOffsets.Add(0);
+			stateChanges.Add(new HighlightingColor());
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightedInlineBuilder instance.
+		/// </summary>
+		public HighlightedInlineBuilder(RichText text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text.Text;
+			stateChangeOffsets.AddRange(text.stateChangeOffsets);
+			stateChanges.AddRange(text.stateChanges);
+		}
+		
+		HighlightedInlineBuilder(string text, List<int> offsets, List<HighlightingColor> states)
+		{
+			this.text = text;
+			stateChangeOffsets = offsets;
+			stateChanges = states;
+		}
+		
+		/// <summary>
+		/// Gets the text.
+		/// </summary>
+		public string Text {
+			get { return text; }
+		}
+		
+		/// <summary>
+		/// Applies the properties from the HighlightingColor to the specified text segment.
+		/// </summary>
+		public void SetHighlighting(int offset, int length, HighlightingColor color)
+		{
+			if (color == null)
+				throw new ArgumentNullException("color");
+			if (color.Foreground == null && color.Background == null && color.FontStyle == null && color.FontWeight == null) {
+				// Optimization: don't split the HighlightingState when we're not changing
+				// any property. For example, the "Punctuation" color in C# is
+				// empty by default.
+				return;
+			}
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].MergeWith(color);
+			}
+		}
+		
+		/// <summary>
+		/// Sets the foreground brush on the specified text segment.
+		/// </summary>
+		public void SetForeground(int offset, int length, Brush brush)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			var hbrush = MakeBrush(brush);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].Foreground = hbrush;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the background brush on the specified text segment.
+		/// </summary>
+		public void SetBackground(int offset, int length, Brush brush)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			var hbrush = MakeBrush(brush);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].Background = hbrush;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the font weight on the specified text segment.
+		/// </summary>
+		public void SetFontWeight(int offset, int length, FontWeight weight)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].FontWeight = weight;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the font style on the specified text segment.
+		/// </summary>
+		public void SetFontStyle(int offset, int length, FontStyle style)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].FontStyle = style;
+			}
+		}
+		
+		/// <summary>
+		/// Creates WPF Run instances that can be used for TextBlock.Inlines.
+		/// </summary>
+		public Run[] CreateRuns()
+		{
+			return ToRichText().CreateRuns();
+		}
+		
+		/// <summary>
+		/// Creates a RichText instance.
+		/// </summary>
+		public RichText ToRichText()
+		{
+			return new RichText(text, stateChangeOffsets.ToArray(), stateChanges.Select(FreezableHelper.GetFrozenClone).ToArray());
+		}
+		
+		/// <summary>
+		/// Clones this HighlightedInlineBuilder.
+		/// </summary>
+		public HighlightedInlineBuilder Clone()
+		{
+			return new HighlightedInlineBuilder(this.text,
+			                                    stateChangeOffsets.ToList(),
+			                                    stateChanges.Select(sc => sc.Clone()).ToList());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedLine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedLine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedLine.cs	(revision 11807)
@@ -0,0 +1,335 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Represents a highlighted document line.
+	/// </summary>
+	public class HighlightedLine
+	{
+		/// <summary>
+		/// Creates a new HighlightedLine instance.
+		/// </summary>
+		public HighlightedLine(IDocument document, IDocumentLine documentLine)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			//if (!document.Lines.Contains(documentLine))
+			//	throw new ArgumentException("Line is null or not part of document");
+			this.Document = document;
+			this.DocumentLine = documentLine;
+			this.Sections = new NullSafeCollection<HighlightedSection>();
+		}
+		
+		/// <summary>
+		/// Gets the document associated with this HighlightedLine.
+		/// </summary>
+		public IDocument Document { get; private set; }
+		
+		/// <summary>
+		/// Gets the document line associated with this HighlightedLine.
+		/// </summary>
+		public IDocumentLine DocumentLine { get; private set; }
+		
+		/// <summary>
+		/// Gets the highlighted sections.
+		/// The sections are not overlapping, but they may be nested.
+		/// In that case, outer sections come in the list before inner sections.
+		/// The sections are sorted by start offset.
+		/// </summary>
+		public IList<HighlightedSection> Sections { get; private set; }
+		
+		/// <summary>
+		/// Validates that the sections are sorted correctly, and that they are not overlapping.
+		/// </summary>
+		/// <seealso cref="Sections"/>
+		public void ValidateInvariants()
+		{
+			var line = this;
+			int lineStartOffset = line.DocumentLine.Offset;
+			int lineEndOffset = line.DocumentLine.EndOffset;
+			for (int i = 0; i < line.Sections.Count; i++) {
+				HighlightedSection s1 = line.Sections[i];
+				if (s1.Offset < lineStartOffset || s1.Length < 0 || s1.Offset + s1.Length > lineEndOffset)
+					throw new InvalidOperationException("Section is outside line bounds");
+				for (int j = i + 1; j < line.Sections.Count; j++) {
+					HighlightedSection s2 = line.Sections[j];
+					if (s2.Offset >= s1.Offset + s1.Length) {
+						// s2 is after s1
+					} else if (s2.Offset >= s1.Offset && s2.Offset + s2.Length <= s1.Offset + s1.Length) {
+						// s2 is nested within s1
+					} else {
+						throw new InvalidOperationException("Sections are overlapping or incorrectly sorted.");
+					}
+				}
+			}
+		}
+		
+		#region Merge
+		/// <summary>
+		/// Merges the additional line into this line.
+		/// </summary>
+		public void MergeWith(HighlightedLine additionalLine)
+		{
+			if (additionalLine == null)
+				return;
+			#if DEBUG
+			ValidateInvariants();
+			additionalLine.ValidateInvariants();
+			#endif
+			
+			int pos = 0;
+			Stack<int> activeSectionEndOffsets = new Stack<int>();
+			int lineEndOffset = this.DocumentLine.EndOffset;
+			activeSectionEndOffsets.Push(lineEndOffset);
+			foreach (HighlightedSection newSection in additionalLine.Sections) {
+				int newSectionStart = newSection.Offset;
+				// Track the existing sections using the stack, up to the point where
+				// we need to insert the first part of the newSection
+				while (pos < this.Sections.Count) {
+					HighlightedSection s = this.Sections[pos];
+					if (newSection.Offset < s.Offset)
+						break;
+					while (s.Offset > activeSectionEndOffsets.Peek()) {
+						activeSectionEndOffsets.Pop();
+					}
+					activeSectionEndOffsets.Push(s.Offset + s.Length);
+					pos++;
+				}
+				// Now insert the new section
+				// Create a copy of the stack so that we can track the sections we traverse
+				// during the insertion process:
+				Stack<int> insertionStack = new Stack<int>(activeSectionEndOffsets.Reverse());
+				// The stack enumerator reverses the order of the elements, so we call Reverse() to restore
+				// the original order.
+				int i;
+				for (i = pos; i < this.Sections.Count; i++) {
+					HighlightedSection s = this.Sections[i];
+					if (newSection.Offset + newSection.Length <= s.Offset)
+						break;
+					// Insert a segment in front of s:
+					Insert(ref i, ref newSectionStart, s.Offset, newSection.Color, insertionStack);
+					
+					while (s.Offset > insertionStack.Peek()) {
+						insertionStack.Pop();
+					}
+					insertionStack.Push(s.Offset + s.Length);
+				}
+				Insert(ref i, ref newSectionStart, newSection.Offset + newSection.Length, newSection.Color, insertionStack);
+			}
+			
+			#if DEBUG
+			ValidateInvariants();
+			#endif
+		}
+		
+		void Insert(ref int pos, ref int newSectionStart, int insertionEndPos, HighlightingColor color, Stack<int> insertionStack)
+		{
+			if (newSectionStart >= insertionEndPos) {
+				// nothing to insert here
+				return;
+			}
+			
+			while (insertionStack.Peek() <= newSectionStart) {
+				insertionStack.Pop();
+			}
+			while (insertionStack.Peek() < insertionEndPos) {
+				int end = insertionStack.Pop();
+				// insert the portion from newSectionStart to end
+				if (end > newSectionStart) {
+					this.Sections.Insert(pos++, new HighlightedSection {
+					                     	Offset = newSectionStart,
+					                     	Length = end - newSectionStart,
+					                     	Color = color
+					                     });
+					newSectionStart = end;
+				}
+			}
+			if (insertionEndPos > newSectionStart) {
+				this.Sections.Insert(pos++, new HighlightedSection {
+				                     	Offset = newSectionStart,
+				                     	Length = insertionEndPos - newSectionStart,
+				                     	Color = color
+				                     });
+				newSectionStart = insertionEndPos;
+			}
+		}
+		#endregion
+		
+		#region WriteTo / ToHtml
+		sealed class HtmlElement : IComparable<HtmlElement>
+		{
+			internal readonly int Offset;
+			internal readonly int Nesting;
+			internal readonly bool IsEnd;
+			internal readonly HighlightingColor Color;
+			
+			public HtmlElement(int offset, int nesting, bool isEnd, HighlightingColor color)
+			{
+				this.Offset = offset;
+				this.Nesting = nesting;
+				this.IsEnd = isEnd;
+				this.Color = color;
+			}
+			
+			public int CompareTo(HtmlElement other)
+			{
+				int r = Offset.CompareTo(other.Offset);
+				if (r != 0)
+					return r;
+				if (IsEnd != other.IsEnd) {
+					if (IsEnd)
+						return -1;
+					else
+						return 1;
+				} else {
+					if (IsEnd)
+						return other.Nesting.CompareTo(Nesting);
+					else
+						return Nesting.CompareTo(other.Nesting);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Writes the highlighted line to the RichTextWriter.
+		/// </summary>
+		internal void WriteTo(RichTextWriter writer)
+		{
+			int startOffset = this.DocumentLine.Offset;
+			WriteTo(writer, startOffset, startOffset + this.DocumentLine.Length);
+		}
+		
+		/// <summary>
+		/// Writes a part of the highlighted line to the RichTextWriter.
+		/// </summary>
+		internal void WriteTo(RichTextWriter writer, int startOffset, int endOffset)
+		{
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			int documentLineStartOffset = this.DocumentLine.Offset;
+			int documentLineEndOffset = documentLineStartOffset + this.DocumentLine.Length;
+			if (startOffset < documentLineStartOffset || startOffset > documentLineEndOffset)
+				throw new ArgumentOutOfRangeException("startOffset", startOffset, "Value must be between " + documentLineStartOffset + " and " + documentLineEndOffset);
+			if (endOffset < startOffset || endOffset > documentLineEndOffset)
+				throw new ArgumentOutOfRangeException("endOffset", endOffset, "Value must be between startOffset and " + documentLineEndOffset);
+			ISegment requestedSegment = new SimpleSegment(startOffset, endOffset - startOffset);
+			
+			List<HtmlElement> elements = new List<HtmlElement>();
+			for (int i = 0; i < this.Sections.Count; i++) {
+				HighlightedSection s = this.Sections[i];
+				if (SimpleSegment.GetOverlap(s, requestedSegment).Length > 0) {
+					elements.Add(new HtmlElement(s.Offset, i, false, s.Color));
+					elements.Add(new HtmlElement(s.Offset + s.Length, i, true, s.Color));
+				}
+			}
+			elements.Sort();
+			
+			IDocument document = this.Document;
+			int textOffset = startOffset;
+			foreach (HtmlElement e in elements) {
+				int newOffset = Math.Min(e.Offset, endOffset);
+				if (newOffset > startOffset) {
+					document.WriteTextTo(writer, textOffset, newOffset - textOffset);
+				}
+				textOffset = Math.Max(textOffset, newOffset);
+				if (e.IsEnd)
+					writer.EndSpan();
+				else
+					writer.BeginSpan(e.Color);
+			}
+			document.WriteTextTo(writer, textOffset, endOffset - textOffset);
+		}
+		
+		/// <summary>
+		/// Produces HTML code for the line, with &lt;span class="colorName"&gt; tags.
+		/// </summary>
+		public string ToHtml(HtmlOptions options = null)
+		{
+			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
+			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
+				WriteTo(htmlWriter);
+			}
+			return stringWriter.ToString();
+		}
+		
+		/// <summary>
+		/// Produces HTML code for a section of the line, with &lt;span class="colorName"&gt; tags.
+		/// </summary>
+		public string ToHtml(int startOffset, int endOffset, HtmlOptions options = null)
+		{
+			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
+			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
+				WriteTo(htmlWriter, startOffset, endOffset);
+			}
+			return stringWriter.ToString();
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " " + ToHtml() + "]";
+		}
+		#endregion
+		
+		/// <summary>
+		/// Creates a <see cref="HighlightedInlineBuilder"/> that stores the text and highlighting of this line.
+		/// </summary>
+		[Obsolete("Use ToRichText() instead")]
+		public HighlightedInlineBuilder ToInlineBuilder()
+		{
+			HighlightedInlineBuilder builder = new HighlightedInlineBuilder(Document.GetText(DocumentLine));
+			int startOffset = DocumentLine.Offset;
+			foreach (HighlightedSection section in Sections) {
+				builder.SetHighlighting(section.Offset - startOffset, section.Length, section.Color);
+			}
+			return builder;
+		}
+		
+		/// <summary>
+		/// Creates a <see cref="RichTextModel"/> that stores the highlighting of this line.
+		/// </summary>
+		public RichTextModel ToRichTextModel()
+		{
+			var builder = new RichTextModel();
+			int startOffset = DocumentLine.Offset;
+			foreach (HighlightedSection section in Sections) {
+				builder.ApplyHighlighting(section.Offset - startOffset, section.Length, section.Color);
+			}
+			return builder;
+		}
+		
+		/// <summary>
+		/// Creates a <see cref="RichText"/> that stores the text and highlighting of this line.
+		/// </summary>
+		public RichText ToRichText()
+		{
+			return new RichText(Document.GetText(DocumentLine), ToRichTextModel());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedSection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedSection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightedSection.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A text section with syntax highlighting information.
+	/// </summary>
+	public class HighlightedSection : ISegment
+	{
+		/// <summary>
+		/// Gets/sets the document offset of the section.
+		/// </summary>
+		public int Offset { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the length of the section.
+		/// </summary>
+		public int Length { get; set; }
+		
+		int ISegment.EndOffset {
+			get { return this.Offset + this.Length; }
+		}
+		
+		/// <summary>
+		/// Gets the highlighting color associated with the highlighted section.
+		/// </summary>
+		public HighlightingColor Color { get; set; }
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format("[HighlightedSection ({0}-{1})={2}]", Offset, Offset + Length, Color);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingBrush.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingBrush.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingBrush.cs	(revision 11807)
@@ -0,0 +1,163 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using System.Reflection;
+using System.Runtime.Serialization;
+using System.Windows;
+using System.Windows.Media;
+
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A brush used for syntax highlighting. Can retrieve a real brush on-demand.
+	/// </summary>
+	[Serializable]
+	public abstract class HighlightingBrush
+	{
+		/// <summary>
+		/// Gets the real brush.
+		/// </summary>
+		/// <param name="context">The construction context. context can be null!</param>
+		public abstract Brush GetBrush(ITextRunConstructionContext context);
+		
+		/// <summary>
+		/// Gets the color of the brush.
+		/// </summary>
+		/// <param name="context">The construction context. context can be null!</param>
+		public virtual Color? GetColor(ITextRunConstructionContext context)
+		{
+			SolidColorBrush scb = GetBrush(context) as SolidColorBrush;
+			if (scb != null)
+				return scb.Color;
+			else
+				return null;
+		}
+	}
+	
+	/// <summary>
+	/// Highlighting brush implementation that takes a frozen brush.
+	/// </summary>
+	[Serializable]
+	public sealed class SimpleHighlightingBrush : HighlightingBrush, ISerializable
+	{
+		readonly SolidColorBrush brush;
+		
+		internal SimpleHighlightingBrush(SolidColorBrush brush)
+		{
+			brush.Freeze();
+			this.brush = brush;
+		}
+		
+		/// <inheritdoc/>
+		public SimpleHighlightingBrush(Color color) : this(new SolidColorBrush(color)) {}
+		
+		/// <inheritdoc/>
+		public override Brush GetBrush(ITextRunConstructionContext context)
+		{
+			return brush;
+		}
+
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return brush.ToString();
+		}
+		
+		SimpleHighlightingBrush(SerializationInfo info, StreamingContext context)
+		{
+			this.brush = new SolidColorBrush((Color)ColorConverter.ConvertFromString(info.GetString("color")));
+			brush.Freeze();
+		}
+		
+		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+		{
+			info.AddValue("color", brush.Color.ToString(CultureInfo.InvariantCulture));
+		}
+		
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			SimpleHighlightingBrush other = obj as SimpleHighlightingBrush;
+			if (other == null)
+				return false;
+			return this.brush.Color.Equals(other.brush.Color);
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			return brush.Color.GetHashCode();
+		}
+	}
+	
+	/// <summary>
+	/// HighlightingBrush implementation that finds a brush using a resource.
+	/// </summary>
+	[Serializable]
+	sealed class SystemColorHighlightingBrush : HighlightingBrush, ISerializable
+	{
+		readonly PropertyInfo property;
+		
+		public SystemColorHighlightingBrush(PropertyInfo property)
+		{
+			Debug.Assert(property.ReflectedType == typeof(SystemColors));
+			Debug.Assert(typeof(Brush).IsAssignableFrom(property.PropertyType));
+			this.property = property;
+		}
+		
+		public override Brush GetBrush(ITextRunConstructionContext context)
+		{
+			return (Brush)property.GetValue(null, null);
+		}
+		
+		public override string ToString()
+		{
+			return property.Name;
+		}
+		
+		SystemColorHighlightingBrush(SerializationInfo info, StreamingContext context)
+		{
+			property = typeof(SystemColors).GetProperty(info.GetString("propertyName"));
+			if (property == null)
+				throw new ArgumentException("Error deserializing SystemColorHighlightingBrush");
+		}
+		
+		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+		{
+			info.AddValue("propertyName", property.Name);
+		}
+		
+		public override bool Equals(object obj)
+		{
+			SystemColorHighlightingBrush other = obj as SystemColorHighlightingBrush;
+			if (other == null)
+				return false;
+			return object.Equals(this.property, other.property);
+		}
+		
+		public override int GetHashCode()
+		{
+			return property.GetHashCode();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingColor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingColor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingColor.cs	(revision 11807)
@@ -0,0 +1,278 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Security.Permissions;
+using System.Text;
+using System.Windows;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A highlighting color is a set of font properties and foreground and background color.
+	/// </summary>
+	[Serializable]
+	public class HighlightingColor : ISerializable, IFreezable, ICloneable, IEquatable<HighlightingColor>
+	{
+		internal static readonly HighlightingColor Empty = FreezableHelper.FreezeAndReturn(new HighlightingColor());
+		
+		string name;
+		FontWeight? fontWeight;
+		FontStyle? fontStyle;
+		HighlightingBrush foreground;
+		HighlightingBrush background;
+		bool frozen;
+		
+		/// <summary>
+		/// Gets/Sets the name of the color.
+		/// </summary>
+		public string Name {
+			get {
+				return name;
+			}
+			set {
+				if (frozen)
+					throw new InvalidOperationException();
+				name = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the font weight. Null if the highlighting color does not change the font weight.
+		/// </summary>
+		public FontWeight? FontWeight {
+			get {
+				return fontWeight;
+			}
+			set {
+				if (frozen)
+					throw new InvalidOperationException();
+				fontWeight = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the font style. Null if the highlighting color does not change the font style.
+		/// </summary>
+		public FontStyle? FontStyle {
+			get {
+				return fontStyle;
+			}
+			set {
+				if (frozen)
+					throw new InvalidOperationException();
+				fontStyle = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the foreground color applied by the highlighting.
+		/// </summary>
+		public HighlightingBrush Foreground {
+			get {
+				return foreground;
+			}
+			set {
+				if (frozen)
+					throw new InvalidOperationException();
+				foreground = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the background color applied by the highlighting.
+		/// </summary>
+		public HighlightingBrush Background {
+			get {
+				return background;
+			}
+			set {
+				if (frozen)
+					throw new InvalidOperationException();
+				background = value;
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightingColor instance.
+		/// </summary>
+		public HighlightingColor()
+		{
+		}
+		
+		/// <summary>
+		/// Deserializes a HighlightingColor.
+		/// </summary>
+		protected HighlightingColor(SerializationInfo info, StreamingContext context)
+		{
+			if (info == null)
+				throw new ArgumentNullException("info");
+			this.Name = info.GetString("Name");
+			if (info.GetBoolean("HasWeight"))
+				this.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(info.GetInt32("Weight"));
+			if (info.GetBoolean("HasStyle"))
+				this.FontStyle = (FontStyle?)new FontStyleConverter().ConvertFromInvariantString(info.GetString("Style"));
+			this.Foreground = (HighlightingBrush)info.GetValue("Foreground", typeof(HighlightingBrush));
+			this.Background = (HighlightingBrush)info.GetValue("Background", typeof(HighlightingBrush));
+		}
+		
+		/// <summary>
+		/// Serializes this HighlightingColor instance.
+		/// </summary>
+		#if DOTNET4
+		[System.Security.SecurityCritical]
+		#else
+		[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
+		#endif
+		public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+		{
+			if (info == null)
+				throw new ArgumentNullException("info");
+			info.AddValue("Name", this.Name);
+			info.AddValue("HasWeight", this.FontWeight.HasValue);
+			if (this.FontWeight.HasValue)
+				info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
+			info.AddValue("HasStyle", this.FontStyle.HasValue);
+			if (this.FontStyle.HasValue)
+				info.AddValue("Style", this.FontStyle.Value.ToString());
+			info.AddValue("Foreground", this.Foreground);
+			info.AddValue("Background", this.Background);
+		}
+		
+		/// <summary>
+		/// Gets CSS code for the color.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
+		public virtual string ToCss()
+		{
+			StringBuilder b = new StringBuilder();
+			if (Foreground != null) {
+				Color? c = Foreground.GetColor(null);
+				if (c != null) {
+					b.AppendFormat(CultureInfo.InvariantCulture, "color: #{0:x2}{1:x2}{2:x2}; ", c.Value.R, c.Value.G, c.Value.B);
+				}
+			}
+			if (FontWeight != null) {
+				b.Append("font-weight: ");
+				b.Append(FontWeight.Value.ToString().ToLowerInvariant());
+				b.Append("; ");
+			}
+			if (FontStyle != null) {
+				b.Append("font-style: ");
+				b.Append(FontStyle.Value.ToString().ToLowerInvariant());
+				b.Append("; ");
+			}
+			return b.ToString();
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " " + (string.IsNullOrEmpty(this.Name) ? ToCss() : this.Name) + "]";
+		}
+		
+		/// <summary>
+		/// Prevent further changes to this highlighting color.
+		/// </summary>
+		public virtual void Freeze()
+		{
+			frozen = true;
+		}
+		
+		/// <summary>
+		/// Gets whether this HighlightingColor instance is frozen.
+		/// </summary>
+		public bool IsFrozen {
+			get { return frozen; }
+		}
+		
+		/// <summary>
+		/// Clones this highlighting color.
+		/// If this color is frozen, the clone will be unfrozen.
+		/// </summary>
+		public virtual HighlightingColor Clone()
+		{
+			HighlightingColor c = (HighlightingColor)MemberwiseClone();
+			c.frozen = false;
+			return c;
+		}
+		
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+		
+		/// <inheritdoc/>
+		public override sealed bool Equals(object obj)
+		{
+			return Equals(obj as HighlightingColor);
+		}
+		
+		/// <inheritdoc/>
+		public virtual bool Equals(HighlightingColor other)
+		{
+			if (other == null)
+				return false;
+			return this.name == other.name && this.fontWeight == other.fontWeight && this.fontStyle == other.fontStyle && object.Equals(this.foreground, other.foreground) && object.Equals(this.background, other.background);
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			int hashCode = 0;
+			unchecked {
+				if (name != null)
+					hashCode += 1000000007 * name.GetHashCode();
+				hashCode += 1000000009 * fontWeight.GetHashCode();
+				hashCode += 1000000021 * fontStyle.GetHashCode();
+				if (foreground != null)
+					hashCode += 1000000033 * foreground.GetHashCode();
+				if (background != null)
+					hashCode += 1000000087 * background.GetHashCode();
+			}
+			return hashCode;
+		}
+		
+		/// <summary>
+		/// Overwrites the properties in this HighlightingColor with those from the given color;
+		/// but maintains the current values where the properties of the given color return <c>null</c>.
+		/// </summary>
+		public void MergeWith(HighlightingColor color)
+		{
+			FreezableHelper.ThrowIfFrozen(this);
+			if (color.fontWeight != null)
+				this.fontWeight = color.fontWeight;
+			if (color.fontStyle != null)
+				this.fontStyle = color.fontStyle;
+			if (color.foreground != null)
+				this.foreground = color.foreground;
+			if (color.background != null)
+				this.background = color.background;
+		}
+		
+		internal bool IsEmptyForMerge {
+			get {
+				return fontWeight == null && fontStyle == null && foreground == null && background == null;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingColorizer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingColorizer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingColorizer.cs	(revision 11807)
@@ -0,0 +1,359 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A colorizes that interprets a highlighting rule set and colors the document accordingly.
+	/// </summary>
+	public class HighlightingColorizer : DocumentColorizingTransformer
+	{
+		readonly IHighlightingDefinition definition;
+		TextView textView;
+		IHighlighter highlighter;
+		bool isFixedHighlighter;
+		
+		/// <summary>
+		/// Creates a new HighlightingColorizer instance.
+		/// </summary>
+		/// <param name="definition">The highlighting definition.</param>
+		public HighlightingColorizer(IHighlightingDefinition definition)
+		{
+			if (definition == null)
+				throw new ArgumentNullException("definition");
+			this.definition = definition;
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightingColorizer instance that uses a fixed highlighter instance.
+		/// The colorizer can only be used with text views that show the document for which
+		/// the highlighter was created.
+		/// </summary>
+		/// <param name="highlighter">The highlighter to be used.</param>
+		public HighlightingColorizer(IHighlighter highlighter)
+		{
+			if (highlighter == null)
+				throw new ArgumentNullException("highlighter");
+			this.highlighter = highlighter;
+			this.isFixedHighlighter = true;
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightingColorizer instance.
+		/// Derived classes using this constructor must override the <see cref="CreateHighlighter"/> method.
+		/// </summary>
+		protected HighlightingColorizer()
+		{
+		}
+		
+		void textView_DocumentChanged(object sender, EventArgs e)
+		{
+			TextView textView = (TextView)sender;
+			DeregisterServices(textView);
+			RegisterServices(textView);
+		}
+		
+		/// <summary>
+		/// This method is called when a text view is removed from this HighlightingColorizer,
+		/// and also when the TextDocument on any associated text view changes.
+		/// </summary>
+		protected virtual void DeregisterServices(TextView textView)
+		{
+			if (highlighter != null) {
+				if (isInHighlightingGroup) {
+					highlighter.EndHighlighting();
+					isInHighlightingGroup = false;
+				}
+				highlighter.HighlightingStateChanged -= OnHighlightStateChanged;
+				// remove highlighter if it is registered
+				if (textView.Services.GetService(typeof(IHighlighter)) == highlighter)
+					textView.Services.RemoveService(typeof(IHighlighter));
+				if (!isFixedHighlighter) {
+					if (highlighter != null)
+						highlighter.Dispose();
+					highlighter = null;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// This method is called when a new text view is added to this HighlightingColorizer,
+		/// and also when the TextDocument on any associated text view changes.
+		/// </summary>
+		protected virtual void RegisterServices(TextView textView)
+		{
+			if (textView.Document != null) {
+				if (!isFixedHighlighter)
+					highlighter = textView.Document != null ? CreateHighlighter(textView, textView.Document) : null;
+				if (highlighter != null && highlighter.Document == textView.Document) {
+					// add service only if it doesn't already exist
+					if (textView.Services.GetService(typeof(IHighlighter)) == null) {
+						textView.Services.AddService(typeof(IHighlighter), highlighter);
+					}
+					highlighter.HighlightingStateChanged += OnHighlightStateChanged;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Creates the IHighlighter instance for the specified text document.
+		/// </summary>
+		protected virtual IHighlighter CreateHighlighter(TextView textView, TextDocument document)
+		{
+			if (definition != null)
+				return new DocumentHighlighter(document, definition);
+			else
+				throw new NotSupportedException("Cannot create a highlighter because no IHighlightingDefinition was specified, and the CreateHighlighter() method was not overridden.");
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnAddToTextView(TextView textView)
+		{
+			if (this.textView != null) {
+				throw new InvalidOperationException("Cannot use a HighlightingColorizer instance in multiple text views. Please create a separate instance for each text view.");
+			}
+			base.OnAddToTextView(textView);
+			this.textView = textView;
+			textView.DocumentChanged += textView_DocumentChanged;
+			textView.VisualLineConstructionStarting += textView_VisualLineConstructionStarting;
+			textView.VisualLinesChanged += textView_VisualLinesChanged;
+			RegisterServices(textView);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnRemoveFromTextView(TextView textView)
+		{
+			DeregisterServices(textView);
+			textView.DocumentChanged -= textView_DocumentChanged;
+			textView.VisualLineConstructionStarting -= textView_VisualLineConstructionStarting;
+			textView.VisualLinesChanged -= textView_VisualLinesChanged;
+			base.OnRemoveFromTextView(textView);
+			this.textView = null;
+		}
+		
+		bool isInHighlightingGroup;
+		
+		void textView_VisualLineConstructionStarting(object sender, VisualLineConstructionStartEventArgs e)
+		{
+			if (highlighter != null) {
+				// Force update of highlighting state up to the position where we start generating visual lines.
+				// This is necessary in case the document gets modified above the FirstLineInView so that the highlighting state changes.
+				// We need to detect this case and issue a redraw (through OnHighlightStateChanged)
+				// before the visual line construction reuses existing lines that were built using the invalid highlighting state.
+				lineNumberBeingColorized = e.FirstLineInView.LineNumber - 1;
+				if (!isInHighlightingGroup) {
+					// avoid opening group twice if there was an exception during the previous visual line construction
+					// (not ideal, but better than throwing InvalidOperationException "group already open"
+					// without any way of recovering)
+					highlighter.BeginHighlighting();
+					isInHighlightingGroup = true;
+				}
+				highlighter.UpdateHighlightingState(lineNumberBeingColorized);
+				lineNumberBeingColorized = 0;
+			}
+		}
+		
+		void textView_VisualLinesChanged(object sender, EventArgs e)
+		{
+			if (highlighter != null && isInHighlightingGroup) {
+				highlighter.EndHighlighting();
+				isInHighlightingGroup = false;
+			}
+		}
+		
+		DocumentLine lastColorizedLine;
+		
+		/// <inheritdoc/>
+		protected override void Colorize(ITextRunConstructionContext context)
+		{
+			this.lastColorizedLine = null;
+			base.Colorize(context);
+			if (this.lastColorizedLine != context.VisualLine.LastDocumentLine) {
+				if (highlighter != null) {
+					// In some cases, it is possible that we didn't highlight the last document line within the visual line
+					// (e.g. when the line ends with a fold marker).
+					// But even if we didn't highlight it, we'll have to update the highlighting state for it so that the
+					// proof inside TextViewDocumentHighlighter.OnHighlightStateChanged holds.
+					lineNumberBeingColorized = context.VisualLine.LastDocumentLine.LineNumber;
+					highlighter.UpdateHighlightingState(lineNumberBeingColorized);
+					lineNumberBeingColorized = 0;
+				}
+			}
+			this.lastColorizedLine = null;
+		}
+		
+		int lineNumberBeingColorized;
+		
+		/// <inheritdoc/>
+		protected override void ColorizeLine(DocumentLine line)
+		{
+			if (highlighter != null) {
+				lineNumberBeingColorized = line.LineNumber;
+				HighlightedLine hl = highlighter.HighlightLine(lineNumberBeingColorized);
+				lineNumberBeingColorized = 0;
+				foreach (HighlightedSection section in hl.Sections) {
+					if (IsEmptyColor(section.Color))
+						continue;
+					ChangeLinePart(section.Offset, section.Offset + section.Length,
+					               visualLineElement => ApplyColorToElement(visualLineElement, section.Color));
+				}
+			}
+			this.lastColorizedLine = line;
+		}
+		
+		/// <summary>
+		/// Gets whether the color is empty (has no effect on a VisualLineTextElement).
+		/// For example, the C# "Punctuation" is an empty color.
+		/// </summary>
+		internal static bool IsEmptyColor(HighlightingColor color)
+		{
+			if (color == null)
+				return true;
+			return color.Background == null && color.Foreground == null
+				&& color.FontStyle == null && color.FontWeight == null;
+		}
+		
+		/// <summary>
+		/// Applies a highlighting color to a visual line element.
+		/// </summary>
+		protected virtual void ApplyColorToElement(VisualLineElement element, HighlightingColor color)
+		{
+			ApplyColorToElement(element, color, CurrentContext);
+		}
+		
+		internal static void ApplyColorToElement(VisualLineElement element, HighlightingColor color, ITextRunConstructionContext context)
+		{
+			if (color.Foreground != null) {
+				Brush b = color.Foreground.GetBrush(context);
+				if (b != null)
+					element.TextRunProperties.SetForegroundBrush(b);
+			}
+			if (color.Background != null) {
+				Brush b = color.Background.GetBrush(context);
+				if (b != null)
+					element.BackgroundBrush = b;
+			}
+			if (color.FontStyle != null || color.FontWeight != null) {
+				Typeface tf = element.TextRunProperties.Typeface;
+				element.TextRunProperties.SetTypeface(new Typeface(
+					tf.FontFamily,
+					color.FontStyle ?? tf.Style,
+					color.FontWeight ?? tf.Weight,
+					tf.Stretch
+				));
+			}
+		}
+		
+		/// <summary>
+		/// This method is responsible for telling the TextView to redraw lines when the highlighting state has changed.
+		/// </summary>
+		/// <remarks>
+		/// Creation of a VisualLine triggers the syntax highlighter (which works on-demand), so it says:
+		/// Hey, the user typed "/*". Don't just recreate that line, but also the next one
+		/// because my highlighting state (at end of line) changed!
+		/// </remarks>
+		void OnHighlightStateChanged(int fromLineNumber, int toLineNumber)
+		{
+			if (lineNumberBeingColorized != 0) {
+				// Ignore notifications for any line except the one we're interested in.
+				// This improves the performance as Redraw() can take quite some time when called repeatedly
+				// while scanning the document (above the visible area) for highlighting changes.
+				if (toLineNumber <= lineNumberBeingColorized) {
+					return;
+				}
+			}
+			
+			// The user may have inserted "/*" into the current line, and so far only that line got redrawn.
+			// So when the highlighting state is changed, we issue a redraw for the line immediately below.
+			// If the highlighting state change applies to the lines below, too, the construction of each line
+			// will invalidate the next line, and the construction pass will regenerate all lines.
+			
+			Debug.WriteLine(string.Format("OnHighlightStateChanged forces redraw of lines {0} to {1}", fromLineNumber, toLineNumber));
+			
+			// If the VisualLine construction is in progress, we have to avoid sending redraw commands for
+			// anything above the line currently being constructed.
+			// It takes some explanation to see why this cannot happen.
+			// VisualLines always get constructed from top to bottom.
+			// Each VisualLine construction calls into the highlighter and thus forces an update of the
+			// highlighting state for all lines up to the one being constructed.
+			
+			// To guarantee that we don't redraw lines we just constructed, we need to show that when
+			// a VisualLine is being reused, the highlighting state at that location is still up-to-date.
+			
+			// This isn't exactly trivial and the initial implementation was incorrect in the presence of external document changes
+			// (e.g. split view).
+			
+			// For the first line in the view, the TextView.VisualLineConstructionStarting event is used to check that the
+			// highlighting state is up-to-date. If it isn't, this method will be executed, and it'll mark the first line
+			// in the view as requiring a redraw. This is safely possible because that event occurs before any lines are reused.
+			
+			// Once we take care of the first visual line, we won't get in trouble with other lines due to the top-to-bottom
+			// construction process.
+			
+			// We'll prove that: if line N is being reused, then the highlighting state is up-to-date until (end of) line N-1.
+			
+			// Start of induction: the first line in view is reused only if the highlighting state was up-to-date
+			// until line N-1 (no change detected in VisualLineConstructionStarting event).
+			
+			// Induction step:
+			// If another line N+1 is being reused, then either
+			//     a) the previous line (the visual line containing document line N) was newly constructed
+			// or  b) the previous line was reused
+			// In case a, the construction updated the highlighting state. This means the stack at end of line N is up-to-date.
+			// In case b, the highlighting state at N-1 was up-to-date, and the text of line N was not changed.
+			//   (if the text was changed, the line could not have been reused).
+			// From this follows that the highlighting state at N is still up-to-date.
+			
+			// The above proof holds even in the presence of folding: folding only ever hides text in the middle of a visual line.
+			// Our Colorize-override ensures that the highlighting state is always updated for the LastDocumentLine,
+			// so it will always invalidate the next visual line when a folded line is constructed
+			// and the highlighting stack has changed.
+			
+			if (fromLineNumber == toLineNumber) {
+				textView.Redraw(textView.Document.GetLineByNumber(fromLineNumber));
+			} else {
+				// If there are multiple lines marked as changed; only the first one really matters
+				// for the highlighting during rendering.
+				// However this callback is also called outside of the rendering process, e.g. when a highlighter
+				// decides to re-highlight some section based on external feedback (e.g. semantic highlighting).
+				var fromLine = textView.Document.GetLineByNumber(fromLineNumber);
+				var toLine = textView.Document.GetLineByNumber(toLineNumber);
+				int startOffset = fromLine.Offset;
+				textView.Redraw(startOffset, toLine.EndOffset - startOffset);
+			}
+			
+			/*
+			 * Meta-comment: "why does this have to be so complicated?"
+			 * 
+			 * The problem is that I want to re-highlight only on-demand and incrementally;
+			 * and at the same time only repaint changed lines.
+			 * So the highlighter and the VisualLine construction both have to run in a single pass.
+			 * The highlighter must take care that it never touches already constructed visual lines;
+			 * if it detects that something must be redrawn because the highlighting state changed,
+			 * it must do so early enough in the construction process.
+			 * But doing it too early means it doesn't have the information necessary to re-highlight and redraw only the desired parts.
+			 */
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingDefinitionInvalidException.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingDefinitionInvalidException.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingDefinitionInvalidException.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.Serialization;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Indicates that the highlighting definition that was tried to load was invalid.
+	/// </summary>
+	[Serializable()]
+	public class HighlightingDefinitionInvalidException : Exception
+	{
+		/// <summary>
+		/// Creates a new HighlightingDefinitionInvalidException instance.
+		/// </summary>
+		public HighlightingDefinitionInvalidException() : base()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightingDefinitionInvalidException instance.
+		/// </summary>
+		public HighlightingDefinitionInvalidException(string message) : base(message)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightingDefinitionInvalidException instance.
+		/// </summary>
+		public HighlightingDefinitionInvalidException(string message, Exception innerException) : base(message, innerException)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new HighlightingDefinitionInvalidException instance.
+		/// </summary>
+		protected HighlightingDefinitionInvalidException(SerializationInfo info, StreamingContext context) : base(info, context)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingDefinitionTypeConverter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingDefinitionTypeConverter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingDefinitionTypeConverter.cs	(revision 11807)
@@ -0,0 +1,69 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Globalization;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Converts between strings and <see cref="IHighlightingDefinition"/> by treating the string as the definition name
+	/// and calling <c>HighlightingManager.Instance.<see cref="HighlightingManager.GetDefinition">GetDefinition</see>(name)</c>.
+	/// </summary>
+	public sealed class HighlightingDefinitionTypeConverter : TypeConverter
+	{
+		/// <inheritdoc/>
+		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
+		{
+			if (sourceType == typeof(string))
+				return true;
+			else
+				return base.CanConvertFrom(context, sourceType);
+		}
+		
+		/// <inheritdoc/>
+		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
+		{
+			string definitionName = value as string;
+			if (definitionName != null)
+				return HighlightingManager.Instance.GetDefinition(definitionName);
+			else
+				return base.ConvertFrom(context, culture, value);
+		}
+		
+		/// <inheritdoc/>
+		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
+		{
+			if (destinationType == typeof(string))
+				return true;
+			else
+				return base.CanConvertTo(context, destinationType);
+		}
+		
+		/// <inheritdoc/>
+		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
+		{
+			IHighlightingDefinition definition = value as IHighlightingDefinition;
+			if (definition != null && destinationType == typeof(string))
+				return definition.Name;
+			else
+				return base.ConvertTo(context, culture, value, destinationType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingEngine.cs	(revision 11807)
@@ -0,0 +1,325 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text.RegularExpressions;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+using ICSharpCode.AvalonEdit.Utils;
+using SpanStack = ICSharpCode.AvalonEdit.Utils.ImmutableStack<ICSharpCode.AvalonEdit.Highlighting.HighlightingSpan>;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Regex-based highlighting engine.
+	/// </summary>
+	public class HighlightingEngine
+	{
+		readonly HighlightingRuleSet mainRuleSet;
+		SpanStack spanStack = SpanStack.Empty;
+		
+		/// <summary>
+		/// Creates a new HighlightingEngine instance.
+		/// </summary>
+		public HighlightingEngine(HighlightingRuleSet mainRuleSet)
+		{
+			if (mainRuleSet == null)
+				throw new ArgumentNullException("mainRuleSet");
+			this.mainRuleSet = mainRuleSet;
+		}
+		
+		/// <summary>
+		/// Gets/sets the current span stack.
+		/// </summary>
+		public SpanStack CurrentSpanStack {
+			get { return spanStack; }
+			set {
+				spanStack = value ?? SpanStack.Empty;
+			}
+		}
+		
+		#region Highlighting Engine
+		
+		// local variables from HighlightLineInternal (are member because they are accessed by HighlighLine helper methods)
+		string lineText;
+		int lineStartOffset;
+		int position;
+		
+		/// <summary>
+		/// the HighlightedLine where highlighting output is being written to.
+		/// if this variable is null, nothing is highlighted and only the span state is updated
+		/// </summary>
+		HighlightedLine highlightedLine;
+		
+		/// <summary>
+		/// Highlights the specified line in the specified document.
+		/// 
+		/// Before calling this method, <see cref="CurrentSpanStack"/> must be set to the proper
+		/// state for the beginning of this line. After highlighting has completed,
+		/// <see cref="CurrentSpanStack"/> will be updated to represent the state after the line.
+		/// </summary>
+		public HighlightedLine HighlightLine(IDocument document, IDocumentLine line)
+		{
+			this.lineStartOffset = line.Offset;
+			this.lineText = document.GetText(line);
+			try {
+				this.highlightedLine = new HighlightedLine(document, line);
+				HighlightLineInternal();
+				return this.highlightedLine;
+			} finally {
+				this.highlightedLine = null;
+				this.lineText = null;
+				this.lineStartOffset = 0;
+			}
+		}
+		
+		/// <summary>
+		/// Updates <see cref="CurrentSpanStack"/> for the specified line in the specified document.
+		/// 
+		/// Before calling this method, <see cref="CurrentSpanStack"/> must be set to the proper
+		/// state for the beginning of this line. After highlighting has completed,
+		/// <see cref="CurrentSpanStack"/> will be updated to represent the state after the line.
+		/// </summary>
+		public void ScanLine(IDocument document, IDocumentLine line)
+		{
+			//this.lineStartOffset = line.Offset; not necessary for scanning
+			this.lineText = document.GetText(line);
+			try {
+				Debug.Assert(highlightedLine == null);
+				HighlightLineInternal();
+			} finally {
+				this.lineText = null;
+			}
+		}
+		
+		void HighlightLineInternal()
+		{
+			position = 0;
+			ResetColorStack();
+			HighlightingRuleSet currentRuleSet = this.CurrentRuleSet;
+			Stack<Match[]> storedMatchArrays = new Stack<Match[]>();
+			Match[] matches = AllocateMatchArray(currentRuleSet.Spans.Count);
+			Match endSpanMatch = null;
+			
+			while (true) {
+				for (int i = 0; i < matches.Length; i++) {
+					if (matches[i] == null || (matches[i].Success && matches[i].Index < position))
+						matches[i] = currentRuleSet.Spans[i].StartExpression.Match(lineText, position);
+				}
+				if (endSpanMatch == null && !spanStack.IsEmpty)
+					endSpanMatch = spanStack.Peek().EndExpression.Match(lineText, position);
+				
+				Match firstMatch = Minimum(matches, endSpanMatch);
+				if (firstMatch == null)
+					break;
+				
+				HighlightNonSpans(firstMatch.Index);
+				
+				Debug.Assert(position == firstMatch.Index);
+				
+				if (firstMatch == endSpanMatch) {
+					HighlightingSpan poppedSpan = spanStack.Peek();
+					if (!poppedSpan.SpanColorIncludesEnd)
+						PopColor(); // pop SpanColor
+					PushColor(poppedSpan.EndColor);
+					position = firstMatch.Index + firstMatch.Length;
+					PopColor(); // pop EndColor
+					if (poppedSpan.SpanColorIncludesEnd)
+						PopColor(); // pop SpanColor
+					spanStack = spanStack.Pop();
+					currentRuleSet = this.CurrentRuleSet;
+					//FreeMatchArray(matches);
+					if (storedMatchArrays.Count > 0) {
+						matches = storedMatchArrays.Pop();
+						int index = currentRuleSet.Spans.IndexOf(poppedSpan);
+						Debug.Assert(index >= 0 && index < matches.Length);
+						if (matches[index].Index == position) {
+							throw new InvalidOperationException(
+								"A highlighting span matched 0 characters, which would cause an endless loop.\n" +
+								"Change the highlighting definition so that either the start or the end regex matches at least one character.\n" +
+								"Start regex: " + poppedSpan.StartExpression + "\n" +
+								"End regex: " + poppedSpan.EndExpression);
+						}
+					} else {
+						matches = AllocateMatchArray(currentRuleSet.Spans.Count);
+					}
+				} else {
+					int index = Array.IndexOf(matches, firstMatch);
+					Debug.Assert(index >= 0);
+					HighlightingSpan newSpan = currentRuleSet.Spans[index];
+					spanStack = spanStack.Push(newSpan);
+					currentRuleSet = this.CurrentRuleSet;
+					storedMatchArrays.Push(matches);
+					matches = AllocateMatchArray(currentRuleSet.Spans.Count);
+					if (newSpan.SpanColorIncludesStart)
+						PushColor(newSpan.SpanColor);
+					PushColor(newSpan.StartColor);
+					position = firstMatch.Index + firstMatch.Length;
+					PopColor();
+					if (!newSpan.SpanColorIncludesStart)
+						PushColor(newSpan.SpanColor);
+				}
+				endSpanMatch = null;
+			}
+			HighlightNonSpans(lineText.Length);
+			
+			PopAllColors();
+		}
+		
+		void HighlightNonSpans(int until)
+		{
+			Debug.Assert(position <= until);
+			if (position == until)
+				return;
+			if (highlightedLine != null) {
+				IList<HighlightingRule> rules = CurrentRuleSet.Rules;
+				Match[] matches = AllocateMatchArray(rules.Count);
+				while (true) {
+					for (int i = 0; i < matches.Length; i++) {
+						if (matches[i] == null || (matches[i].Success && matches[i].Index < position))
+							matches[i] = rules[i].Regex.Match(lineText, position, until - position);
+					}
+					Match firstMatch = Minimum(matches, null);
+					if (firstMatch == null)
+						break;
+					
+					position = firstMatch.Index;
+					int ruleIndex = Array.IndexOf(matches, firstMatch);
+					if (firstMatch.Length == 0) {
+						throw new InvalidOperationException(
+							"A highlighting rule matched 0 characters, which would cause an endless loop.\n" +
+							"Change the highlighting definition so that the rule matches at least one character.\n" +
+							"Regex: " + rules[ruleIndex].Regex);
+					}
+					PushColor(rules[ruleIndex].Color);
+					position = firstMatch.Index + firstMatch.Length;
+					PopColor();
+				}
+				//FreeMatchArray(matches);
+			}
+			position = until;
+		}
+		
+		static readonly HighlightingRuleSet emptyRuleSet = new HighlightingRuleSet() { Name = "EmptyRuleSet" };
+		
+		HighlightingRuleSet CurrentRuleSet {
+			get {
+				if (spanStack.IsEmpty)
+					return mainRuleSet;
+				else
+					return spanStack.Peek().RuleSet ?? emptyRuleSet;
+			}
+		}
+		#endregion
+		
+		#region Color Stack Management
+		Stack<HighlightedSection> highlightedSectionStack;
+		HighlightedSection lastPoppedSection;
+		
+		void ResetColorStack()
+		{
+			Debug.Assert(position == 0);
+			lastPoppedSection = null;
+			if (highlightedLine == null) {
+				highlightedSectionStack = null;
+			} else {
+				highlightedSectionStack = new Stack<HighlightedSection>();
+				foreach (HighlightingSpan span in spanStack.Reverse()) {
+					PushColor(span.SpanColor);
+				}
+			}
+		}
+		
+		void PushColor(HighlightingColor color)
+		{
+			if (highlightedLine == null)
+				return;
+			if (color == null) {
+				highlightedSectionStack.Push(null);
+			} else if (lastPoppedSection != null && lastPoppedSection.Color == color
+			           && lastPoppedSection.Offset + lastPoppedSection.Length == position + lineStartOffset)
+			{
+				highlightedSectionStack.Push(lastPoppedSection);
+				lastPoppedSection = null;
+			} else {
+				HighlightedSection hs = new HighlightedSection {
+					Offset = position + lineStartOffset,
+					Color = color
+				};
+				highlightedLine.Sections.Add(hs);
+				highlightedSectionStack.Push(hs);
+				lastPoppedSection = null;
+			}
+		}
+		
+		void PopColor()
+		{
+			if (highlightedLine == null)
+				return;
+			HighlightedSection s = highlightedSectionStack.Pop();
+			if (s != null) {
+				s.Length = (position + lineStartOffset) - s.Offset;
+				if (s.Length == 0)
+					highlightedLine.Sections.Remove(s);
+				else
+					lastPoppedSection = s;
+			}
+		}
+		
+		void PopAllColors()
+		{
+			if (highlightedSectionStack != null) {
+				while (highlightedSectionStack.Count > 0)
+					PopColor();
+			}
+		}
+		#endregion
+		
+		#region Match helpers
+		/// <summary>
+		/// Returns the first match from the array or endSpanMatch.
+		/// </summary>
+		static Match Minimum(Match[] arr, Match endSpanMatch)
+		{
+			Match min = null;
+			foreach (Match v in arr) {
+				if (v.Success && (min == null || v.Index < min.Index))
+					min = v;
+			}
+			if (endSpanMatch != null && endSpanMatch.Success && (min == null || endSpanMatch.Index < min.Index))
+				return endSpanMatch;
+			else
+				return min;
+		}
+		
+		static Match[] AllocateMatchArray(int count)
+		{
+			if (count == 0)
+				return Empty<Match>.Array;
+			else
+				return new Match[count];
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingManager.cs	(revision 11807)
@@ -0,0 +1,289 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.IO;
+using System.Xml;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Manages a list of syntax highlighting definitions.
+	/// </summary>
+	/// <remarks>
+	/// All memers on this class (including instance members) are thread-safe.
+	/// </remarks>
+	public class HighlightingManager : IHighlightingDefinitionReferenceResolver
+	{
+		sealed class DelayLoadedHighlightingDefinition : IHighlightingDefinition
+		{
+			readonly object lockObj = new object();
+			readonly string name;
+			Func<IHighlightingDefinition> lazyLoadingFunction;
+			IHighlightingDefinition definition;
+			Exception storedException;
+			
+			public DelayLoadedHighlightingDefinition(string name, Func<IHighlightingDefinition> lazyLoadingFunction)
+			{
+				this.name = name;
+				this.lazyLoadingFunction = lazyLoadingFunction;
+			}
+			
+			public string Name {
+				get {
+					if (name != null)
+						return name;
+					else
+						return GetDefinition().Name;
+				}
+			}
+			
+			[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
+			                                                 Justification = "The exception will be rethrown")]
+			IHighlightingDefinition GetDefinition()
+			{
+				Func<IHighlightingDefinition> func;
+				lock (lockObj) {
+					if (this.definition != null)
+						return this.definition;
+					func = this.lazyLoadingFunction;
+				}
+				Exception exception = null;
+				IHighlightingDefinition def = null;
+				try {
+					using (var busyLock = BusyManager.Enter(this)) {
+						if (!busyLock.Success)
+							throw new InvalidOperationException("Tried to create delay-loaded highlighting definition recursively. Make sure the are no cyclic references between the highlighting definitions.");
+						def = func();
+					}
+					if (def == null)
+						throw new InvalidOperationException("Function for delay-loading highlighting definition returned null");
+				} catch (Exception ex) {
+					exception = ex;
+				}
+				lock (lockObj) {
+					this.lazyLoadingFunction = null;
+					if (this.definition == null && this.storedException == null) {
+						this.definition = def;
+						this.storedException = exception;
+					}
+					if (this.storedException != null)
+						throw new HighlightingDefinitionInvalidException("Error delay-loading highlighting definition", this.storedException);
+					return this.definition;
+				}
+			}
+			
+			public HighlightingRuleSet MainRuleSet {
+				get {
+					return GetDefinition().MainRuleSet;
+				}
+			}
+			
+			public HighlightingRuleSet GetNamedRuleSet(string name)
+			{
+				return GetDefinition().GetNamedRuleSet(name);
+			}
+			
+			public HighlightingColor GetNamedColor(string name)
+			{
+				return GetDefinition().GetNamedColor(name);
+			}
+			
+			public IEnumerable<HighlightingColor> NamedHighlightingColors {
+				get {
+					return GetDefinition().NamedHighlightingColors;
+				}
+			}
+			
+			public override string ToString()
+			{
+				return this.Name;
+			}
+			
+			public IDictionary<string, string> Properties {
+				get {
+					return GetDefinition().Properties;
+				}
+			}
+		}
+		
+		readonly object lockObj = new object();
+		Dictionary<string, IHighlightingDefinition> highlightingsByName = new Dictionary<string, IHighlightingDefinition>();
+		Dictionary<string, IHighlightingDefinition> highlightingsByExtension = new Dictionary<string, IHighlightingDefinition>(StringComparer.OrdinalIgnoreCase);
+		List<IHighlightingDefinition> allHighlightings = new List<IHighlightingDefinition>();
+		
+		/// <summary>
+		/// Gets a highlighting definition by name.
+		/// Returns null if the definition is not found.
+		/// </summary>
+		public IHighlightingDefinition GetDefinition(string name)
+		{
+			lock (lockObj) {
+				IHighlightingDefinition rh;
+				if (highlightingsByName.TryGetValue(name, out rh))
+					return rh;
+				else
+					return null;
+			}
+		}
+		
+		/// <summary>
+		/// Gets a copy of all highlightings.
+		/// </summary>
+		public ReadOnlyCollection<IHighlightingDefinition> HighlightingDefinitions {
+			get {
+				lock (lockObj) {
+					return Array.AsReadOnly(allHighlightings.ToArray());
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets a highlighting definition by extension.
+		/// Returns null if the definition is not found.
+		/// </summary>
+		public IHighlightingDefinition GetDefinitionByExtension(string extension)
+		{
+			lock (lockObj) {
+				IHighlightingDefinition rh;
+				if (highlightingsByExtension.TryGetValue(extension, out rh))
+					return rh;
+				else
+					return null;
+			}
+		}
+		
+		/// <summary>
+		/// Registers a highlighting definition.
+		/// </summary>
+		/// <param name="name">The name to register the definition with.</param>
+		/// <param name="extensions">The file extensions to register the definition for.</param>
+		/// <param name="highlighting">The highlighting definition.</param>
+		public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting)
+		{
+			if (highlighting == null)
+				throw new ArgumentNullException("highlighting");
+			
+			lock (lockObj) {
+				allHighlightings.Add(highlighting);
+				if (name != null) {
+					highlightingsByName[name] = highlighting;
+				}
+				if (extensions != null) {
+					foreach (string ext in extensions) {
+						highlightingsByExtension[ext] = highlighting;
+					}
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Registers a highlighting definition.
+		/// </summary>
+		/// <param name="name">The name to register the definition with.</param>
+		/// <param name="extensions">The file extensions to register the definition for.</param>
+		/// <param name="lazyLoadedHighlighting">A function that loads the highlighting definition.</param>
+		public void RegisterHighlighting(string name, string[] extensions, Func<IHighlightingDefinition> lazyLoadedHighlighting)
+		{
+			if (lazyLoadedHighlighting == null)
+				throw new ArgumentNullException("lazyLoadedHighlighting");
+			RegisterHighlighting(name, extensions, new DelayLoadedHighlightingDefinition(name, lazyLoadedHighlighting));
+		}
+		
+		/// <summary>
+		/// Gets the default HighlightingManager instance.
+		/// The default HighlightingManager comes with built-in highlightings.
+		/// </summary>
+		public static HighlightingManager Instance {
+			get {
+				return DefaultHighlightingManager.Instance;
+			}
+		}
+		
+		internal sealed class DefaultHighlightingManager : HighlightingManager
+		{
+			public new static readonly DefaultHighlightingManager Instance = new DefaultHighlightingManager();
+			
+			public DefaultHighlightingManager()
+			{
+				Resources.RegisterBuiltInHighlightings(this);
+			}
+			
+			// Registering a built-in highlighting
+			internal void RegisterHighlighting(string name, string[] extensions, string resourceName)
+			{
+				try {
+					#if DEBUG
+					// don't use lazy-loading in debug builds, show errors immediately
+					Xshd.XshdSyntaxDefinition xshd;
+					using (Stream s = Resources.OpenStream(resourceName)) {
+						using (XmlTextReader reader = new XmlTextReader(s)) {
+							xshd = Xshd.HighlightingLoader.LoadXshd(reader, false);
+						}
+					}
+					Debug.Assert(name == xshd.Name);
+					if (extensions != null)
+						Debug.Assert(System.Linq.Enumerable.SequenceEqual(extensions, xshd.Extensions));
+					else
+						Debug.Assert(xshd.Extensions.Count == 0);
+					
+					// round-trip xshd:
+//					string resourceFileName = Path.Combine(Path.GetTempPath(), resourceName);
+//					using (XmlTextWriter writer = new XmlTextWriter(resourceFileName, System.Text.Encoding.UTF8)) {
+//						writer.Formatting = Formatting.Indented;
+//						new Xshd.SaveXshdVisitor(writer).WriteDefinition(xshd);
+//					}
+//					using (FileStream fs = File.Create(resourceFileName + ".bin")) {
+//						new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(fs, xshd);
+//					}
+//					using (FileStream fs = File.Create(resourceFileName + ".compiled")) {
+//						new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(fs, Xshd.HighlightingLoader.Load(xshd, this));
+//					}
+					
+					RegisterHighlighting(name, extensions, Xshd.HighlightingLoader.Load(xshd, this));
+					#else
+					RegisterHighlighting(name, extensions, LoadHighlighting(resourceName));
+					#endif
+				} catch (HighlightingDefinitionInvalidException ex) {
+					throw new InvalidOperationException("The built-in highlighting '" + name + "' is invalid.", ex);
+				}
+			}
+			
+			[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode",
+			                                                 Justification = "LoadHighlighting is used only in release builds")]
+			Func<IHighlightingDefinition> LoadHighlighting(string resourceName)
+			{
+				Func<IHighlightingDefinition> func = delegate {
+					Xshd.XshdSyntaxDefinition xshd;
+					using (Stream s = Resources.OpenStream(resourceName)) {
+						using (XmlTextReader reader = new XmlTextReader(s)) {
+							// in release builds, skip validating the built-in highlightings
+							xshd = Xshd.HighlightingLoader.LoadXshd(reader, true);
+						}
+					}
+					return Xshd.HighlightingLoader.Load(xshd, this);
+				};
+				return func;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingRule.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingRule.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingRule.cs	(revision 11807)
@@ -0,0 +1,46 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text.RegularExpressions;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A highlighting rule.
+	/// </summary>
+	[Serializable]
+	public class HighlightingRule
+	{
+		/// <summary>
+		/// Gets/Sets the regular expression for the rule.
+		/// </summary>
+		public Regex Regex { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the highlighting color.
+		/// </summary>
+		public HighlightingColor Color { get; set; }
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " " + Regex + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingRuleSet.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingRuleSet.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingRuleSet.cs	(revision 11807)
@@ -0,0 +1,61 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A highlighting rule set describes a set of spans that are valid at a given code location.
+	/// </summary>
+	[Serializable]
+	public class HighlightingRuleSet
+	{
+		/// <summary>
+		/// Creates a new RuleSet instance.
+		/// </summary>
+		public HighlightingRuleSet()
+		{
+			this.Spans = new NullSafeCollection<HighlightingSpan>();
+			this.Rules = new NullSafeCollection<HighlightingRule>();
+		}
+		
+		/// <summary>
+		/// Gets/Sets the name of the rule set.
+		/// </summary>
+		public string Name { get; set; }
+		
+		/// <summary>
+		/// Gets the list of spans.
+		/// </summary>
+		public IList<HighlightingSpan> Spans { get; private set; }
+		
+		/// <summary>
+		/// Gets the list of rules.
+		/// </summary>
+		public IList<HighlightingRule> Rules { get; private set; }
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " " + Name + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingSpan.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingSpan.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HighlightingSpan.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text.RegularExpressions;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A highlighting span is a region with start+end expression that has a different RuleSet inside
+	/// and colors the region.
+	/// </summary>
+	[Serializable]
+	public class HighlightingSpan
+	{
+		/// <summary>
+		/// Gets/Sets the start expression.
+		/// </summary>
+		public Regex StartExpression { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the end expression.
+		/// </summary>
+		public Regex EndExpression { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the rule set that applies inside this span.
+		/// </summary>
+		public HighlightingRuleSet RuleSet { get; set; }
+		
+		/// <summary>
+		/// Gets the color used for the text matching the start expression.
+		/// </summary>
+		public HighlightingColor StartColor { get; set; }
+		
+		/// <summary>
+		/// Gets the color used for the text between start and end.
+		/// </summary>
+		public HighlightingColor SpanColor { get; set; }
+		
+		/// <summary>
+		/// Gets the color used for the text matching the end expression.
+		/// </summary>
+		public HighlightingColor EndColor { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether the span color includes the start.
+		/// The default is <c>false</c>.
+		/// </summary>
+		public bool SpanColorIncludesStart { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether the span color includes the end.
+		/// The default is <c>false</c>.
+		/// </summary>
+		public bool SpanColorIncludesEnd { get; set; }
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " Start=" + StartExpression + ", End=" + EndExpression + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlClipboard.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlClipboard.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlClipboard.cs	(revision 11807)
@@ -0,0 +1,112 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using System.Text;
+using System.Windows;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Allows copying HTML text to the clipboard.
+	/// </summary>
+	public static class HtmlClipboard
+	{
+		/// <summary>
+		/// Builds a header for the CF_HTML clipboard format.
+		/// </summary>
+		static string BuildHeader(int startHTML, int endHTML, int startFragment, int endFragment)
+		{
+			StringBuilder b = new StringBuilder();
+			b.AppendLine("Version:0.9");
+			b.AppendLine("StartHTML:" + startHTML.ToString("d8", CultureInfo.InvariantCulture));
+			b.AppendLine("EndHTML:" + endHTML.ToString("d8", CultureInfo.InvariantCulture));
+			b.AppendLine("StartFragment:" + startFragment.ToString("d8", CultureInfo.InvariantCulture));
+			b.AppendLine("EndFragment:" + endFragment.ToString("d8", CultureInfo.InvariantCulture));
+			return b.ToString();
+		}
+		
+		/// <summary>
+		/// Sets the TextDataFormat.Html on the data object to the specified html fragment.
+		/// This helper methods takes care of creating the necessary CF_HTML header.
+		/// </summary>
+		public static void SetHtml(DataObject dataObject, string htmlFragment)
+		{
+			if (dataObject == null)
+				throw new ArgumentNullException("dataObject");
+			if (htmlFragment == null)
+				throw new ArgumentNullException("htmlFragment");
+			
+			string htmlStart = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">" + Environment.NewLine
+				+ "<HTML>" + Environment.NewLine
+				+ "<BODY>" + Environment.NewLine
+				+ "<!--StartFragment-->" + Environment.NewLine;
+			string htmlEnd = "<!--EndFragment-->" + Environment.NewLine + "</BODY>" + Environment.NewLine + "</HTML>" + Environment.NewLine;
+			string dummyHeader = BuildHeader(0, 0, 0, 0);
+			// the offsets are stored as UTF-8 bytes (see CF_HTML documentation)
+			int startHTML = dummyHeader.Length;
+			int startFragment = startHTML + htmlStart.Length;
+			int endFragment = startFragment + Encoding.UTF8.GetByteCount(htmlFragment);
+			int endHTML = endFragment + htmlEnd.Length;
+			string cf_html = BuildHeader(startHTML, endHTML, startFragment, endFragment) + htmlStart + htmlFragment + htmlEnd;
+			Debug.WriteLine(cf_html);
+			dataObject.SetText(cf_html, TextDataFormat.Html);
+		}
+		
+		/// <summary>
+		/// Creates a HTML fragment from a part of a document.
+		/// </summary>
+		/// <param name="document">The document to create HTML from.</param>
+		/// <param name="highlighter">The highlighter used to highlight the document. <c>null</c> is valid and will create HTML without any highlighting.</param>
+		/// <param name="segment">The part of the document to create HTML for. You can pass <c>null</c> to create HTML for the whole document.</param>
+		/// <param name="options">The options for the HTML creation.</param>
+		/// <returns>HTML code for the document part.</returns>
+		public static string CreateHtmlFragment(IDocument document, IHighlighter highlighter, ISegment segment, HtmlOptions options)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (options == null)
+				throw new ArgumentNullException("options");
+			if (highlighter != null && highlighter.Document != document)
+				throw new ArgumentException("Highlighter does not belong to the specified document.");
+			if (segment == null)
+				segment = new SimpleSegment(0, document.TextLength);
+			
+			StringBuilder html = new StringBuilder();
+			int segmentEndOffset = segment.EndOffset;
+			IDocumentLine line = document.GetLineByOffset(segment.Offset);
+			while (line != null && line.Offset < segmentEndOffset) {
+				HighlightedLine highlightedLine;
+				if (highlighter != null)
+					highlightedLine = highlighter.HighlightLine(line.LineNumber);
+				else
+					highlightedLine = new HighlightedLine(document, line);
+				SimpleSegment s = SimpleSegment.GetOverlap(segment, line);
+				if (html.Length > 0)
+					html.AppendLine("<br>");
+				html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options));
+				line = line.NextLine;
+			}
+			return html.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlOptions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlOptions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlOptions.cs	(revision 11807)
@@ -0,0 +1,85 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+#if DOTNET4
+using System.Net;
+#else
+using System.Web;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Holds options for converting text to HTML.
+	/// </summary>
+	public class HtmlOptions
+	{
+		/// <summary>
+		/// Creates a default HtmlOptions instance.
+		/// </summary>
+		public HtmlOptions()
+		{
+			this.TabSize = 4;
+		}
+		
+		/// <summary>
+		/// Creates a new HtmlOptions instance that copies applicable options from the <see cref="TextEditorOptions"/>.
+		/// </summary>
+		public HtmlOptions(TextEditorOptions options) : this()
+		{
+			if (options == null)
+				throw new ArgumentNullException("options");
+			this.TabSize = options.IndentationSize;
+		}
+		
+		/// <summary>
+		/// The amount of spaces a tab gets converted to.
+		/// </summary>
+		public int TabSize { get; set; }
+		
+		/// <summary>
+		/// Writes the HTML attribute for the style to the text writer.
+		/// </summary>
+		public virtual void WriteStyleAttributeForColor(TextWriter writer, HighlightingColor color)
+		{
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			if (color == null)
+				throw new ArgumentNullException("color");
+			writer.Write(" style=\"");
+			#if DOTNET4
+			WebUtility.HtmlEncode(color.ToCss(), writer);
+			#else
+			HttpUtility.HtmlEncode(color.ToCss(), writer);
+			#endif
+			writer.Write('"');
+		}
+		
+		/// <summary>
+		/// Gets whether the color needs to be written out to HTML.
+		/// </summary>
+		public virtual bool ColorNeedsSpanForStyling(HighlightingColor color)
+		{
+			if (color == null)
+				throw new ArgumentNullException("color");
+			return !string.IsNullOrEmpty(color.ToCss());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlRichTextWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlRichTextWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/HtmlRichTextWriter.cs	(revision 11807)
@@ -0,0 +1,268 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+#if DOTNET4
+using System.Net;
+#else
+using System.Web;
+#endif
+using System.Text;
+using System.Windows;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// RichTextWriter implementation that produces HTML.
+	/// </summary>
+	class HtmlRichTextWriter : RichTextWriter
+	{
+		readonly TextWriter htmlWriter;
+		readonly HtmlOptions options;
+		Stack<string> endTagStack = new Stack<string>();
+		bool spaceNeedsEscaping = true;
+		bool hasSpace;
+		bool needIndentation = true;
+		int indentationLevel;
+		
+		/// <summary>
+		/// Creates a new HtmlRichTextWriter instance.
+		/// </summary>
+		/// <param name="htmlWriter">
+		/// The text writer where the raw HTML is written to.
+		/// The HtmlRichTextWriter does not take ownership of the htmlWriter;
+		/// disposing the HtmlRichTextWriter will not dispose the underlying htmlWriter!
+		/// </param>
+		/// <param name="options">Options that control the HTML output.</param>
+		public HtmlRichTextWriter(TextWriter htmlWriter, HtmlOptions options = null)
+		{
+			if (htmlWriter == null)
+				throw new ArgumentNullException("htmlWriter");
+			this.htmlWriter = htmlWriter;
+			this.options = options ?? new HtmlOptions();
+		}
+		
+		/// <inheritdoc/>
+		public override Encoding Encoding {
+			get { return htmlWriter.Encoding; }
+		}
+		
+		/// <inheritdoc/>
+		public override void Flush()
+		{
+			FlushSpace(true); // next char potentially might be whitespace
+			htmlWriter.Flush();
+		}
+		
+		/// <inheritdoc/>
+		protected override void Dispose(bool disposing)
+		{
+			if (disposing) {
+				FlushSpace(true);
+			}
+			base.Dispose(disposing);
+		}
+		
+		void FlushSpace(bool nextIsWhitespace)
+		{
+			if (hasSpace) {
+				if (spaceNeedsEscaping || nextIsWhitespace)
+					htmlWriter.Write("&nbsp;");
+				else
+					htmlWriter.Write(' ');
+				hasSpace = false;
+				spaceNeedsEscaping = true;
+			}
+		}
+		
+		void WriteIndentation()
+		{
+			if (needIndentation) {
+				for (int i = 0; i < indentationLevel; i++) {
+					WriteChar('\t');
+				}
+				needIndentation = false;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void Write(char value)
+		{
+			WriteIndentation();
+			WriteChar(value);
+		}
+		
+		static readonly char[] specialChars = { ' ', '\t', '\r', '\n' };
+		
+		void WriteChar(char c)
+		{
+			bool isWhitespace = char.IsWhiteSpace(c);
+			FlushSpace(isWhitespace);
+			switch (c) {
+				case ' ':
+					if (spaceNeedsEscaping)
+						htmlWriter.Write("&nbsp;");
+					else
+						hasSpace = true;
+					break;
+				case '\t':
+					for (int i = 0; i < options.TabSize; i++) {
+						htmlWriter.Write("&nbsp;");
+					}
+					break;
+				case '\r':
+					break; // ignore; we'll write the <br/> with the following \n
+				case '\n':
+					htmlWriter.Write("<br/>");
+					needIndentation = true;
+					break;
+				default:
+					#if DOTNET4
+					WebUtility.HtmlEncode(c.ToString(), htmlWriter);
+					#else
+					HttpUtility.HtmlEncode(c.ToString(), htmlWriter);
+					#endif
+					break;
+			}
+			// If we just handled a space by setting hasSpace = true,
+			// we mustn't set spaceNeedsEscaping as doing so would affect our own space,
+			// not just the following spaces.
+			if (c != ' ') {
+				// Following spaces must be escaped if c was a newline/tab;
+				// and they don't need escaping if c was a normal character.
+				spaceNeedsEscaping = isWhitespace;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void Write(string value)
+		{
+			int pos = 0;
+			do {
+				int endPos = value.IndexOfAny(specialChars, pos);
+				if (endPos < 0) {
+					WriteSimpleString(value.Substring(pos));
+					return; // reached end of string
+				}
+				if (endPos > pos)
+					WriteSimpleString(value.Substring(pos, endPos - pos));
+				WriteChar(value[pos]);
+				pos = endPos + 1;
+			} while (pos < value.Length);
+		}
+		
+		void WriteIndentationAndSpace()
+		{
+			WriteIndentation();
+			FlushSpace(false);
+		}
+		
+		void WriteSimpleString(string value)
+		{
+			if (value.Length == 0)
+				return;
+			WriteIndentationAndSpace();
+			#if DOTNET4
+			WebUtility.HtmlEncode(value, htmlWriter);
+			#else
+			HttpUtility.HtmlEncode(value, htmlWriter);
+			#endif
+		}
+		
+		/// <inheritdoc/>
+		public override void Indent()
+		{
+			indentationLevel++;
+		}
+		
+		/// <inheritdoc/>
+		public override void Unindent()
+		{
+			if (indentationLevel == 0)
+				throw new NotSupportedException();
+			indentationLevel--;
+		}
+		
+		/// <inheritdoc/>
+		protected override void BeginUnhandledSpan()
+		{
+			endTagStack.Push(null);
+		}
+		
+		/// <inheritdoc/>
+		public override void EndSpan()
+		{
+			htmlWriter.Write(endTagStack.Pop());
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(Color foregroundColor)
+		{
+			BeginSpan(new HighlightingColor { Foreground = new SimpleHighlightingBrush(foregroundColor) });
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(FontFamily fontFamily)
+		{
+			BeginUnhandledSpan(); // TODO
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(FontStyle fontStyle)
+		{
+			BeginSpan(new HighlightingColor { FontStyle = fontStyle });
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(FontWeight fontWeight)
+		{
+			BeginSpan(new HighlightingColor { FontWeight = fontWeight });
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(HighlightingColor highlightingColor)
+		{
+			WriteIndentationAndSpace();
+			if (options.ColorNeedsSpanForStyling(highlightingColor)) {
+				htmlWriter.Write("<span");
+				options.WriteStyleAttributeForColor(htmlWriter, highlightingColor);
+				htmlWriter.Write('>');
+				endTagStack.Push("</span>");
+			} else {
+				endTagStack.Push(null);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginHyperlinkSpan(Uri uri)
+		{
+			WriteIndentationAndSpace();
+			#if DOTNET4
+			string link = WebUtility.HtmlEncode(uri.ToString());
+			#else
+			string link = HttpUtility.HtmlEncode(uri.ToString());
+			#endif
+			htmlWriter.Write("<a href=\"" + link + "\">");
+			endTagStack.Push("</a>");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlighter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlighter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlighter.cs	(revision 11807)
@@ -0,0 +1,126 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+#if NREFACTORY
+using ICSharpCode.NRefactory.Editor;
+#else
+using ICSharpCode.AvalonEdit.Document;
+#endif
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Represents a highlighted document.
+	/// </summary>
+	/// <remarks>This interface is used by the <see cref="HighlightingColorizer"/> to register the highlighter as a TextView service.</remarks>
+	public interface IHighlighter : IDisposable
+	{
+		/// <summary>
+		/// Gets the underlying text document.
+		/// </summary>
+		IDocument Document { get; }
+		
+		/// <summary>
+		/// Gets the stack of active colors (the colors associated with the active spans) at the end of the specified line.
+		/// -> GetColorStack(1) returns the colors at the start of the second line.
+		/// </summary>
+		/// <remarks>
+		/// GetColorStack(0) is valid and will return the empty stack.
+		/// The elements are returned in inside-out order (first element of result enumerable is the color of the innermost span).
+		/// </remarks>
+		IEnumerable<HighlightingColor> GetColorStack(int lineNumber);
+		
+		// Starting with SD 5.0, this interface exports GetColorStack() instead of GetSpanStack().
+		// This was done because custom highlighter implementations might not use the HighlightingSpan class (AST-based highlighting).
+		
+		/// <summary>
+		/// Highlights the specified document line.
+		/// </summary>
+		/// <param name="lineNumber">The line to highlight.</param>
+		/// <returns>A <see cref="HighlightedLine"/> line object that represents the highlighted sections.</returns>
+		HighlightedLine HighlightLine(int lineNumber);
+		
+		/// <summary>
+		/// Enforces a highlighting state update (triggering the HighlightingStateChanged event if necessary)
+		/// for all lines up to (and inclusive) the specified line number.
+		/// </summary>
+		void UpdateHighlightingState(int lineNumber);
+		
+		/// <summary>
+		/// Notification when the highlighter detects that the highlighting state at the
+		/// <b>beginning</b> of the specified lines has changed.
+		/// <c>fromLineNumber</c> and <c>toLineNumber</c> are both inclusive;
+		/// the common case of a single-line change is represented by <c>fromLineNumber == toLineNumber</c>.
+		/// 
+		/// During highlighting, the highlighting of line X will cause this event to be raised
+		/// for line X+1 if the highlighting state at the end of line X has changed from its previous state.
+		/// This event may also be raised outside of the highlighting process to signalize that
+		/// changes to external data (not the document text; but e.g. semantic information)
+		/// require a re-highlighting of the specified lines.
+		/// </summary>
+		/// <remarks>
+		/// For implementers: there is the requirement that, during highlighting,
+		/// if there was no state changed reported for the beginning of line X,
+		/// and there were no document changes between the start of line X and the start of line Y (with Y > X),
+		/// then this event must not be raised for any line between X and Y (inclusive).
+		/// 
+		/// Equal input state + unchanged line = Equal output state.
+		/// 
+		/// See the comment in the HighlightingColorizer.OnHighlightStateChanged implementation
+		/// for details about the requirements for a correct custom IHighlighter.
+		/// 
+		/// Outside of the highlighting process, this event can be raised without such restrictions.
+		/// </remarks>
+		event HighlightingStateChangedEventHandler HighlightingStateChanged;
+		
+		/// <summary>
+		/// Opens a group of <see cref="HighlightLine"/> calls.
+		/// It is not necessary to call this method before calling <see cref="HighlightLine"/>,
+		/// however, doing so can make the highlighting much more performant in some cases
+		/// (e.g. the C# semantic highlighter in SharpDevelop will re-use the resolver within a highlighting group).
+		/// </summary>
+		/// <remarks>
+		/// The group is closed by either a <see cref="EndHighlighting"/> or a <see cref="IDisposable.Dispose"/> call.
+		/// Nested groups are not allowed.
+		/// </remarks>
+		void BeginHighlighting();
+		
+		/// <summary>
+		/// Closes the currently opened group of <see cref="HighlightLine"/> calls.
+		/// </summary>
+		/// <seealso cref="BeginHighlighting"/>.
+		void EndHighlighting();
+		
+		/// <summary>
+		/// Retrieves the HighlightingColor with the specified name. Returns null if no color matching the name is found.
+		/// </summary>
+		HighlightingColor GetNamedColor(string name);
+		
+		/// <summary>
+		/// Gets the default text color.
+		/// </summary>
+		HighlightingColor DefaultTextColor { get; }
+	}
+	
+	/// <summary>
+	/// Event handler for <see cref="IHighlighter.HighlightingStateChanged"/>
+	/// </summary>
+	public delegate void HighlightingStateChangedEventHandler(int fromLineNumber, int toLineNumber);
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlightingDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlightingDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlightingDefinition.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A highlighting definition.
+	/// </summary>
+	[TypeConverter(typeof(HighlightingDefinitionTypeConverter))]
+	public interface IHighlightingDefinition
+	{
+		/// <summary>
+		/// Gets the name of the highlighting definition.
+		/// </summary>
+		string Name { get; }
+		
+		/// <summary>
+		/// Gets the main rule set.
+		/// </summary>
+		HighlightingRuleSet MainRuleSet { get; }
+		
+		/// <summary>
+		/// Gets a rule set by name.
+		/// </summary>
+		/// <returns>The rule set, or null if it is not found.</returns>
+		HighlightingRuleSet GetNamedRuleSet(string name);
+		
+		/// <summary>
+		/// Gets a named highlighting color.
+		/// </summary>
+		/// <returns>The highlighting color, or null if it is not found.</returns>
+		HighlightingColor GetNamedColor(string name);
+		
+		/// <summary>
+		/// Gets the list of named highlighting colors.
+		/// </summary>
+		IEnumerable<HighlightingColor> NamedHighlightingColors { get; }
+		
+		/// <summary>
+		/// Gets the list of properties.
+		/// </summary>
+		IDictionary<string, string> Properties { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlightingDefinitionReferenceResolver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlightingDefinitionReferenceResolver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/IHighlightingDefinitionReferenceResolver.cs	(revision 11807)
@@ -0,0 +1,33 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Interface for resolvers that can solve cross-definition references.
+	/// </summary>
+	public interface IHighlightingDefinitionReferenceResolver
+	{
+		/// <summary>
+		/// Gets the highlighting definition by name, or null if it is not found.
+		/// </summary>
+		IHighlightingDefinition GetDefinition(string name);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ASPX.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ASPX.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ASPX.xshd	(revision 11807)
@@ -0,0 +1,16 @@
+<?xml version="1.0"?>
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name="ASP/XHTML" extensions=".asp;.aspx;.asax;.asmx;.ascx;.master" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="ASPSectionStartEndTags" foreground="Black" background="Yellow" exampleText="&lt;% System.Console.WriteLine(&quot;Hello World!&quot;); %&gt;" /> 
+	<Color name="ASPSection" foreground="Black" background="#FFF7F2E3" exampleText="&lt;% System.Console.WriteLine(&quot;Hello World!&quot;); %&gt;" />
+	<RuleSet ignoreCase="true">
+		<Span ruleSet="ASP" multiline="true">
+			<Begin color="ASPSectionStartEndTags">&lt;%</Begin>
+			<End color="ASPSectionStartEndTags">%&gt;</End>
+		</Span>
+		<Import ruleSet="HTML/" />
+	</RuleSet>
+	<RuleSet name="ASP">
+		<Import ruleSet="C#/" />
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Boo.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Boo.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Boo.xshd	(revision 11807)
@@ -0,0 +1,212 @@
+﻿<SyntaxDefinition name="Boo" extensions=".boo" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="Green" />
+	<Color name="String" foreground="Blue" />
+	<Color name="Regex" foreground="#FFFF6600" />
+	<RuleSet>
+		<Span color="Comment" multiline="true">
+			<Begin>"""</Begin>
+			<End>"""</End>
+		</Span>
+		<Span foreground="Gray">
+			<Begin>\#</Begin>
+		</Span>
+		<Span foreground="#FF999999">
+			<Begin>//</Begin>
+		</Span>
+		<Span color="Comment" ruleSet="comments set" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<Span begin="\\" end="." />
+				<Span foreground="#FF993366" ruleSet="">
+					<!-- ruleSet="" reference this file's main ruleset, allowing normal boo code inside ${} -->
+					<Begin>\$\{</Begin>
+					<End>}</End>
+				</Span>
+			</RuleSet>
+		</Span>
+		<Span color="String">
+			<Begin>'</Begin>
+			<End>'</End>
+			<RuleSet>
+				<Span begin="\\" end="." />
+			</RuleSet>
+		</Span>
+		<Span color="Regex" multiline="true">
+			<Begin>@/</Begin>
+			<End>/</End>
+		</Span>
+		<Span color="Regex">
+			<!-- this is a span (not a rule) because " within a regex doesn't start a string literal -->
+			<Begin>/\S+/</Begin>
+			<End></End> <!-- end immediately after Begin -->
+		</Span>
+		<Keywords foreground="Black" fontWeight="bold">
+			<Word>self</Word>
+			<Word>super</Word>
+		</Keywords>
+		<Keywords foreground="DarkCyan" fontWeight="bold">
+			<Word>is</Word>
+			<Word>isa</Word>
+			<Word>and</Word>
+			<Word>or</Word>
+			<Word>not</Word>
+		</Keywords>
+		<Keywords foreground="Blue" fontWeight="bold">
+			<Word>else</Word>
+			<Word>elif</Word>
+			<Word>if</Word>
+			<Word>match</Word>
+			<Word>case</Word>
+			<Word>unless</Word>
+			<Word>otherwise</Word>
+			<Word>for</Word>
+			<Word>in</Word>
+			<Word>while</Word>
+		</Keywords>
+		<Keywords foreground="Navy">
+			<Word>break</Word>
+			<Word>continue</Word>
+			<Word>return</Word>
+			<Word>yield</Word>
+			<Word>goto</Word>
+		</Keywords>
+		<Keywords foreground="Teal" fontWeight="bold">
+			<Word>try</Word>
+			<Word>raise</Word>
+			<Word>ensure</Word>
+			<Word>except</Word>
+			<Word>retry</Word>
+			<Word>success</Word>
+		</Keywords>
+		<Keywords foreground="Olive">
+			<Word>fixed</Word>
+			<Word>unsafe</Word>
+		</Keywords>
+		<Keywords foreground="Purple" fontWeight="bold">
+			<Word>bool</Word>
+			<Word>double</Word>
+			<Word>single</Word>
+			<Word>byte</Word>
+			<Word>sbyte</Word>
+			<Word>short</Word>
+			<Word>ushort</Word>
+			<Word>int</Word>
+			<Word>uint</Word>
+			<Word>long</Word>
+			<Word>ulong</Word>
+			<Word>date</Word>
+			<Word>timespan</Word>
+			<Word>decimal</Word>
+			<Word>char</Word>
+			<Word>object</Word>
+			<Word>duck</Word>
+			<Word>string</Word>
+			<Word>regex</Word>
+		</Keywords>
+		<Keywords foreground="Red">
+			<Word>void</Word>
+		</Keywords>
+		<Keywords foreground="Blue" fontWeight="bold">
+			<Word>cast</Word>
+			<Word>as</Word>
+		</Keywords>
+		<Keywords foreground="Brown">
+			<Word>override</Word>
+			<Word>static</Word>
+			<Word>virtual</Word>
+			<Word>abstract</Word>
+			<Word>final</Word>
+			<Word>transient</Word>
+			<Word>partial</Word>
+		</Keywords>
+		<Keywords foreground="Blue" fontWeight="bold">
+			<Word>public</Word>
+			<Word>protected</Word>
+			<Word>private</Word>
+			<Word>internal</Word>
+		</Keywords>
+		<Keywords foreground="Green" fontWeight="bold">
+			<Word>namespace</Word>
+			<Word>import</Word>
+			<Word>from</Word>
+		</Keywords>
+		<Keywords foreground="SaddleBrown">
+			<Word>get</Word>
+			<Word>set</Word>
+		</Keywords>
+		<Keywords foreground="Black" fontWeight="bold">
+			<Word>null</Word>
+			<Word>value</Word>
+			<Word>true</Word>
+			<Word>false</Word>
+			<Word>ast</Word>
+		</Keywords>
+		<Keywords foreground="Maroon">
+			<Word>using</Word>
+			<Word>unchecked</Word>
+			<Word>checked</Word>
+			<Word>lock</Word>
+			<Word>getter</Word>
+			<Word>required</Word>
+			<Word>rawArrayIndexing</Word>
+			<Word>normalArrayIndexing</Word>
+			<Word>yieldAll</Word>
+		</Keywords>
+		<Keywords foreground="Purple">
+			<Word>assert</Word>
+			<Word>array</Word>
+			<Word>matrix</Word>
+			<Word>print</Word>
+			<Word>gets</Word>
+			<Word>prompt</Word>
+			<Word>enumerate</Word>
+			<Word>zip</Word>
+			<Word>filter</Word>
+			<Word>map</Word>
+			<Word>cat</Word>
+			<Word>__eval__</Word>
+			<Word>__switch__</Word>
+		</Keywords>
+		<Keywords foreground="Blue" fontWeight="bold">
+			<Word>constructor</Word>
+			<Word>destructor</Word>
+			<Word>def</Word>
+			<Word>include</Word>
+			<Word>event</Word>
+			<Word>ref</Word>
+		</Keywords>
+		<Keywords foreground="Gray">
+			<Word>pass</Word>
+		</Keywords>
+		<Keywords foreground="Blue" fontWeight="bold">
+			<Word>enum</Word>
+			<Word>class</Word>
+			<Word>struct</Word>
+			<Word>interface</Word>
+			<Word>mixin</Word>
+			<Word>callable</Word>
+			<Word>do</Word>
+			<Word>of</Word>
+		</Keywords>
+		<Rule foreground="MidnightBlue">[\d\w_]+(?=(\s*\())</Rule>
+		<Rule foreground="DarkBlue">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="comments set">
+		<!-- allows nested /**/ comments, coloring them Green/Teal alternately -->
+		<Span foreground="Teal" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+			<RuleSet>
+				<Span color="Comment" ruleSet="comments set" multiline="true">
+					<Begin>/\*</Begin>
+					<End>\*/</End>
+				</Span>
+			</RuleSet>
+		</Span>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CPP-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CPP-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CPP-Mode.xshd	(revision 11807)
@@ -0,0 +1,195 @@
+<?xml version="1.0"?>
+<!-- syntaxdefinition for C/C++ 2001 by Andrea Paatz and Mike Krueger -->
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name="C++" extensions=".c;.h;.cc;.cpp;.hpp" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="Green" />
+	<Color name="Character" foreground="Fuchsia" />
+	<Color name="String" foreground="Fuchsia" />
+	<Color name="Preprocessor" foreground="Green" />
+	<Color name="Punctuation" foreground="DarkGreen" />
+	<Color name="MethodName" foreground="MidnightBlue" fontWeight="bold" />
+	<Color name="Digits" foreground="DarkBlue" />
+	<Color name="CompoundKeywords" foreground="Black" fontWeight="bold" />
+	<Color name="This" foreground="Black" fontWeight="bold" />
+	<Color name="Operators" foreground="#FF008B8B" fontWeight="bold" />
+	<Color name="Namespace" foreground="#FF008000" fontWeight="bold" />
+	<Color name="Friend" foreground="#FFA52A2A" />
+	<Color name="Modifiers" foreground="#FF0000FF" fontWeight="bold" />
+	<Color name="TypeKeywords" foreground="#FFFF0000" />
+	<Color name="BooleanConstants" foreground="#FF000000" fontWeight="bold" />
+	<Color name="Keywords" foreground="#FF0000FF" fontWeight="bold" />
+	<Color name="LoopKeywords" foreground="#FF0000FF" fontWeight="bold" />
+	<Color name="JumpKeywords" foreground="#FF000080" />
+	<Color name="ExceptionHandling" foreground="#FF008080" fontWeight="bold" />
+	<Color name="ControlFlow" foreground="#FF0000FF" fontWeight="bold" />
+	<RuleSet ignoreCase="false">
+		<Rule color="Punctuation">
+		[?,.;()\[\]{}+\-/%*&lt;&gt;^=~!&amp;]+
+		</Rule>
+		<Keywords color="CompoundKeywords">
+			<Word>__abstract</Word>
+			<Word>__box</Word>
+			<Word>__delegate</Word>
+			<Word>__gc</Word>
+			<Word>__identifier</Word>
+			<Word>__nogc</Word>
+			<Word>__pin</Word>
+			<Word>__property</Word>
+			<Word>__sealed</Word>
+			<Word>__try_cast</Word>
+			<Word>__typeof</Word>
+			<Word>__value</Word>
+			<Word>__event</Word>
+			<Word>__hook</Word>
+			<Word>__raise</Word>
+			<Word>__unhook</Word>
+			<Word>__interface</Word>
+			<Word>ref class</Word>
+			<Word>ref struct</Word>
+			<Word>value class</Word>
+			<Word>value struct</Word>
+			<Word>interface class</Word>
+			<Word>interface struct</Word>
+			<Word>enum class</Word>
+			<Word>enum struct</Word>
+			<Word>delegate</Word>
+			<Word>event</Word>
+			<Word>property</Word>
+			<Word>abstract</Word>
+			<Word>override</Word>
+			<Word>sealed</Word>
+			<Word>generic</Word>
+			<Word>where</Word>
+			<Word>finally</Word>
+			<Word>for each</Word>
+			<Word>gcnew</Word>
+			<Word>in</Word>
+			<Word>initonly</Word>
+			<Word>literal</Word>
+			<Word>nullptr</Word>
+		</Keywords>
+		<Keywords color="This">
+			<Word>this</Word>
+		</Keywords>
+		<Keywords color="Operators">
+			<Word>and</Word>
+			<Word>and_eq</Word>
+			<Word>bitand</Word>
+			<Word>bitor</Word>
+			<Word>new</Word>
+			<Word>not</Word>
+			<Word>not_eq</Word>
+			<Word>or</Word>
+			<Word>or_eq</Word>
+			<Word>xor</Word>
+			<Word>xor_eq</Word>
+		</Keywords>
+		<Keywords color="Namespace">
+			<Word>using</Word>
+			<Word>namespace</Word>
+		</Keywords>
+		<Keywords color="Friend">
+			<Word>friend</Word>
+		</Keywords>
+		<Keywords color="Modifiers">
+			<Word>private</Word>
+			<Word>protected</Word>
+			<Word>public</Word>
+			<Word>const</Word>
+			<Word>volatile</Word>
+			<Word>static</Word>
+		</Keywords>
+		<Keywords color="TypeKeywords">
+			<Word>bool</Word>
+			<Word>char</Word>
+			<Word>unsigned</Word>
+			<Word>union</Word>
+			<Word>virtual</Word>
+			<Word>double</Word>
+			<Word>float</Word>
+			<Word>short</Word>
+			<Word>signed</Word>
+			<Word>void</Word>
+			<Word>class</Word>
+			<Word>enum</Word>
+			<Word>struct</Word>
+		</Keywords>
+		<Keywords color="BooleanConstants">
+			<Word>false</Word>
+			<Word>true</Word>
+		</Keywords>
+		<Keywords color="LoopKeywords">
+			<Word>do</Word>
+			<Word>for</Word>
+			<Word>while</Word>
+		</Keywords>
+		<Keywords color="JumpKeywords">
+			<Word>break</Word>
+			<Word>continue</Word>
+			<Word>goto</Word>
+			<Word>return</Word>
+		</Keywords>
+		<Keywords color="ExceptionHandling">
+			<Word>catch</Word>
+			<Word>throw</Word>
+			<Word>try</Word>
+		</Keywords>
+		<Keywords color="ControlFlow">
+			<Word>case</Word>
+			<Word>else</Word>
+			<Word>if</Word>
+			<Word>switch</Word>
+			<Word>default</Word>
+		</Keywords>
+		<Keywords color="Keywords">
+			<Word>asm</Word>
+			<Word>auto</Word>
+			<Word>compl</Word>
+			<Word>mutable</Word>
+			<Word>const_cast</Word>
+			<Word>delete</Word>
+			<Word>dynamic_cast</Word>
+			<Word>explicit</Word>
+			<Word>export</Word>
+			<Word>extern</Word>
+			<Word>inline</Word>
+			<Word>int</Word>
+			<Word>long</Word>
+			<Word>operator</Word>
+			<Word>register</Word>
+			<Word>reinterpret_cast</Word>
+			<Word>sizeof</Word>
+			<Word>static_cast</Word>
+			<Word>template</Word>
+			<Word>typedef</Word>
+			<Word>typeid</Word>
+			<Word>typename</Word>
+		</Keywords>
+		<Span color="Preprocessor">
+			<Begin>\#</Begin>
+		</Span>
+		<Span color="Comment">
+			<Begin>//</Begin>
+		</Span>
+		<Span color="Comment" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<Span begin="\\" end="." />
+			</RuleSet>
+		</Span>
+		<Span color="Character">
+			<Begin>'</Begin>
+			<End>'</End>
+			<RuleSet>
+				<Span begin="\\" end="." />
+			</RuleSet>
+		</Span>
+		<Rule color="MethodName">[\d\w_]+(?=(\s*\())</Rule>
+		<Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CSS-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CSS-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CSS-Mode.xshd	(revision 11807)
@@ -0,0 +1,56 @@
+﻿<SyntaxDefinition name="CSS" extensions=".css" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="Gray" exampleText="/* comment */" />
+	<Color name="String" foreground="Green" exampleText="body { background: url(&quot;image.png&quot;) }" />
+	<Color name="Selector" foreground="DarkBlue" fontWeight="bold" exampleText="div p" />
+	<Color name="Class" foreground="DarkMagenta" exampleText="#para" />
+	<Color name="Property" foreground="Red" exampleText="p { color: red; }" />
+	<Color name="Value" foreground="Blue" exampleText="p { color: red; }" />
+	<Color name="CurlyBraces" foreground="Black" exampleText="{ }" />
+	<Color name="Colon" foreground="Black" exampleText=":" />
+	<RuleSet ignoreCase="true">
+		<Span color="Comment" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		<Span
+			color="Property"
+			multiline="true"
+			ruleSet="CSSBlock">
+			<Begin color="CurlyBraces">\{</Begin>
+			<End color="CurlyBraces">\}</End>
+		</Span>
+		<Span color="Class">
+			<Begin>\#</Begin>
+			<End>\s</End>
+		</Span>
+		<Rule color="Selector">[\d\w]</Rule>
+	</RuleSet>
+
+	<RuleSet name="CSSBlock">
+		<Span color="Comment" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		<Span color="Value" multiline="true">
+			<Begin color="Colon">\:</Begin>
+			<End color="CurlyBraces">\;|(?=\})</End>
+			<RuleSet>
+				<Span color="String" multiline="true">
+					<Begin>"</Begin>
+					<End>"</End>
+					<RuleSet>
+						<Span begin="\\" end="." />
+					</RuleSet>
+				</Span>
+				<Span color="String" multiline="true">
+					<Begin>'</Begin>
+					<End>'</End>
+					<RuleSet>
+						<Span begin="\\" end="." />
+					</RuleSet>
+				</Span>
+			</RuleSet>
+		</Span>
+	</RuleSet>
+</SyntaxDefinition>
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CSharp-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CSharp-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/CSharp-Mode.xshd	(revision 11807)
@@ -0,0 +1,292 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="C#" extensions=".cs" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
+	<Color name="Comment" foreground="Green" exampleText="// comment" />
+	<Color name="String" foreground="Blue" exampleText="string text = &quot;Hello, World!&quot;"/>
+	<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
+	<Color name="Preprocessor" foreground="Green" exampleText="#region Title" />
+	<Color name="Punctuation" exampleText="a(b.c);" />
+	<Color name="ValueTypeKeywords" fontWeight="bold" foreground="Red" exampleText="bool b = true;" />
+	<Color name="ReferenceTypeKeywords" foreground="Red" exampleText="object o;" />
+	<Color name="MethodCall" foreground="MidnightBlue" fontWeight="bold" exampleText="o.ToString();"/>
+	<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
+	<Color name="ThisOrBaseReference" fontWeight="bold" exampleText="this.Do(); base.Do();"/>
+	<Color name="NullOrValueKeywords" fontWeight="bold" exampleText="if (value == null)"/>
+	<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a) {} else {}"/>
+	<Color name="GotoKeywords" foreground="Navy" exampleText="continue; return null;"/>
+	<Color name="ContextKeywords" foreground="Navy" exampleText="var a = from x in y select z;"/>
+	<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" exampleText="try {} catch {} finally {}"/>
+	<Color name="CheckedKeyword" fontWeight="bold" foreground="DarkGray" exampleText="checked {}"/>
+	<Color name="UnsafeKeywords" foreground="Olive" exampleText="unsafe { fixed (..) {} }"/>
+	<Color name="OperatorKeywords" fontWeight="bold" foreground="Pink" exampleText="public static implicit operator..."/>
+	<Color name="ParameterModifiers" fontWeight="bold" foreground="DeepPink" exampleText="(ref int a, params int[] b)"/>
+	<Color name="Modifiers" foreground="Brown" exampleText="static readonly int a;"/>
+	<Color name="Visibility" fontWeight="bold" foreground="Blue" exampleText="public override void ToString();"/>
+	<Color name="NamespaceKeywords" fontWeight="bold" foreground="Green" exampleText="namespace A.B { using System; }"/>
+	<Color name="GetSetAddRemove" foreground="SaddleBrown" exampleText="int Prop { get; set; }"/>
+	<Color name="TrueFalse" fontWeight="bold" foreground="DarkCyan" exampleText="b = false; a = true;" />
+	<Color name="TypeKeywords" fontWeight="bold" foreground="DarkCyan" exampleText="if (x is int) { a = x as int; type = typeof(int); size = sizeof(int); c = new object(); }"/>
+	
+	<Property name="DocCommentMarker" value="///" />
+	
+	<RuleSet name="CommentMarkerSet">
+		<Keywords fontWeight="bold" foreground="Red">
+			<Word>TODO</Word>
+			<Word>FIXME</Word>
+		</Keywords>
+		<Keywords fontWeight="bold" foreground="#E0E000">
+			<Word>HACK</Word>
+			<Word>UNDONE</Word>
+		</Keywords>
+	</RuleSet>
+	
+	<!-- This is the main ruleset. -->
+	<RuleSet>
+		<Span color="Preprocessor">
+			<Begin>\#</Begin>
+			<RuleSet name="PreprocessorSet">
+				<Span> <!-- preprocessor directives that allows comments -->
+					<Begin fontWeight="bold">
+						(define|undef|if|elif|else|endif|line)\b
+					</Begin>
+					<RuleSet>
+						<Span color="Comment" ruleSet="CommentMarkerSet">
+							<Begin>//</Begin>
+						</Span>
+					</RuleSet>
+				</Span>
+				<Span> <!-- preprocessor directives that don't allow comments -->
+					<Begin fontWeight="bold">
+						(region|endregion|error|warning|pragma)\b
+					</Begin>
+				</Span>
+			</RuleSet>
+		</Span>
+		
+		<Span color="Comment">
+			<Begin color="XmlDoc/DocComment">///(?!/)</Begin>
+			<RuleSet>
+				<Import ruleSet="XmlDoc/DocCommentSet"/>
+				<Import ruleSet="CommentMarkerSet"/>
+			</RuleSet>
+		</Span>
+		
+		<Span color="Comment" ruleSet="CommentMarkerSet">
+			<Begin>//</Begin>
+		</Span>
+		
+		<Span color="Comment" ruleSet="CommentMarkerSet" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin="\\" end="."/>
+			</RuleSet>
+		</Span>
+		
+		<Span color="Char">
+			<Begin>'</Begin>
+			<End>'</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin="\\" end="."/>
+			</RuleSet>
+		</Span>
+		
+		<Span color="String" multiline="true">
+			<Begin>@"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin='""' end=""/>
+			</RuleSet>
+		</Span>
+		
+		<!-- don't highlight "@int" as keyword -->
+		<Rule>
+			@[\w\d_]+
+		</Rule>
+		
+		<Keywords color="ThisOrBaseReference">
+			<Word>this</Word>
+			<Word>base</Word>
+		</Keywords>
+		
+		<Keywords color="TypeKeywords">
+			<Word>as</Word>
+			<Word>is</Word>
+			<Word>new</Word>
+			<Word>sizeof</Word>
+			<Word>typeof</Word>
+			<Word>stackalloc</Word>
+		</Keywords>
+		
+		<Keywords color="TrueFalse">
+			<Word>true</Word>
+			<Word>false</Word>
+		</Keywords>
+		
+		<Keywords color="Keywords">
+			<Word>else</Word>
+			<Word>if</Word>
+			<Word>switch</Word>
+			<Word>case</Word>
+			<Word>default</Word>
+			<Word>do</Word>
+			<Word>for</Word>
+			<Word>foreach</Word>
+			<Word>in</Word>
+			<Word>while</Word>
+			<Word>lock</Word>
+		</Keywords>
+		
+		<Keywords color="GotoKeywords">
+			<Word>break</Word>
+			<Word>continue</Word>
+			<Word>goto</Word>
+			<Word>return</Word>
+		</Keywords>
+		
+		<Keywords color="ContextKeywords">
+			<Word>yield</Word>
+			<Word>partial</Word>
+			<Word>global</Word>
+			<Word>where</Word>
+			<Word>select</Word>
+			<Word>group</Word>
+			<Word>by</Word>
+			<Word>into</Word>
+			<Word>from</Word>
+			<Word>ascending</Word>
+			<Word>descending</Word>
+			<Word>orderby</Word>
+			<Word>let</Word>
+			<Word>join</Word>
+			<Word>on</Word>
+			<Word>equals</Word>
+			<Word>var</Word>
+			<Word>dynamic</Word>
+			<Word>await</Word>
+		</Keywords>
+		
+		<Keywords color="ExceptionKeywords">
+			<Word>try</Word>
+			<Word>throw</Word>
+			<Word>catch</Word>
+			<Word>finally</Word>
+		</Keywords>
+		
+		<Keywords color="CheckedKeyword">
+			<Word>checked</Word>
+			<Word>unchecked</Word>
+		</Keywords>
+		
+		<Keywords color="UnsafeKeywords">
+			<Word>fixed</Word>
+			<Word>unsafe</Word>
+		</Keywords>
+		
+		<Keywords color="ValueTypeKeywords">
+			<Word>bool</Word>
+			<Word>byte</Word>
+			<Word>char</Word>
+			<Word>decimal</Word>
+			<Word>double</Word>
+			<Word>enum</Word>
+			<Word>float</Word>
+			<Word>int</Word>
+			<Word>long</Word>
+			<Word>sbyte</Word>
+			<Word>short</Word>
+			<Word>struct</Word>
+			<Word>uint</Word>
+			<Word>ushort</Word>
+			<Word>ulong</Word>
+		</Keywords>
+		
+		<Keywords color="ReferenceTypeKeywords">
+			<Word>class</Word>
+			<Word>interface</Word>
+			<Word>delegate</Word>
+			<Word>object</Word>
+			<Word>string</Word>
+			<Word>void</Word>
+		</Keywords>
+		
+		<Keywords color="OperatorKeywords">
+			<Word>explicit</Word>
+			<Word>implicit</Word>
+			<Word>operator</Word>
+		</Keywords>
+		
+		<Keywords color="ParameterModifiers">
+			<Word>params</Word>
+			<Word>ref</Word>
+			<Word>out</Word>
+		</Keywords>
+		
+		<Keywords color="Modifiers">
+			<Word>abstract</Word>
+			<Word>const</Word>
+			<Word>event</Word>
+			<Word>extern</Word>
+			<Word>override</Word>
+			<Word>readonly</Word>
+			<Word>sealed</Word>
+			<Word>static</Word>
+			<Word>virtual</Word>
+			<Word>volatile</Word>
+			<Word>async</Word>
+		</Keywords>
+		
+		<Keywords color="Visibility">
+			<Word>public</Word>
+			<Word>protected</Word>
+			<Word>private</Word>
+			<Word>internal</Word>
+		</Keywords>
+		
+		<Keywords color="NamespaceKeywords">
+			<Word>namespace</Word>
+			<Word>using</Word>
+		</Keywords>
+		
+		<Keywords color="GetSetAddRemove">
+			<Word>get</Word>
+			<Word>set</Word>
+			<Word>add</Word>
+			<Word>remove</Word>
+		</Keywords>
+		
+		<Keywords color="NullOrValueKeywords">
+			<Word>null</Word>
+			<Word>value</Word>
+		</Keywords>
+		
+		<!-- Mark previous rule-->
+		<Rule color="MethodCall">
+		\b
+		[\d\w_]+  # an identifier
+		(?=\s*\() # followed by (
+		</Rule>
+		
+		<!-- Digits -->
+		<Rule color="NumberLiteral">
+			\b0[xX][0-9a-fA-F]+  # hex number
+		|	
+			(	\b\d+(\.[0-9]+)?   #number with optional floating point
+			|	\.[0-9]+           #or just starting with floating point
+			)
+			([eE][+-]?[0-9]+)? # optional exponent
+		</Rule>
+		
+		<Rule color="Punctuation">
+			[?,.;()\[\]{}+\-/%*&lt;&gt;^+~!|&amp;]+
+		</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Coco-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Coco-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Coco-Mode.xshd	(revision 11807)
@@ -0,0 +1,74 @@
+<?xml version="1.0" ?>
+<!-- syntaxdefinition for Coco/R 2003 by Mike Krueger -->
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name="Coco" extensions=".atg" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="#FF808080" fontStyle="italic" />
+	<Color name="Punctuation" foreground="#FF000000" fontWeight="bold" />
+	<Color name="Keywords" foreground="#FF0000FF" fontWeight="bold" />
+	<Color name="String" foreground="#FF006400" />
+	<RuleSet ignoreCase="false">
+		<Rule color="Punctuation">
+			[{}\(\)\[\]|+\-=\.]+
+		</Rule>
+		<Keywords color="Keywords">
+			<Word>ANY</Word>
+			<Word>CHARACTERS</Word>
+			<Word>COMMENTS</Word>
+			<Word>COMPILER</Word>
+			<Word>CONTEXT</Word>
+			<Word>END</Word>
+			<Word>FROM</Word>
+			<Word>IF</Word>
+			<Word>IGNORE</Word>
+			<Word>NAMESPACE</Word>
+			<Word>NESTED</Word>
+			<Word>PRAGMAS</Word>
+			<Word>PRODUCTIONS</Word>
+			<Word>SYNC</Word>
+			<Word>TO</Word>
+			<Word>TOKENS</Word>
+			<Word>TOKENNAMES</Word>
+			<Word>WEAK</Word>
+			<Word>using</Word>
+		</Keywords>
+		<Span color="Comment">
+			<Begin>//</Begin>
+		</Span>
+		<Span color="Comment" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		<Span foreground="Black" ruleSet="CSharp" multiline="true">
+			<Begin color="Keywords">COMPILER</Begin>
+			<End color="Keywords">TOKENNAMES</End>
+		</Span>
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+		</Span>
+		<Span color="String">
+			<Begin>'</Begin>
+			<End>'</End>
+		</Span>
+		<Span foreground="#FF000000" ruleSet="ParamList">
+			<Begin foreground="#FF000000" fontWeight="bold">&lt;</Begin>
+			<End foreground="#FF000000" fontWeight="bold">&gt;</End>
+		</Span>
+		<Span foreground="#FF2F4F4F" fontWeight="normal" fontStyle="normal" ruleSet="CSharp" multiline="true">
+			<Begin foreground="#FF008000" fontWeight="bold" fontStyle="italic">\(\.</Begin>
+			<End foreground="#FF008000" fontWeight="bold" fontStyle="italic">\.\)</End>
+		</Span>
+		<Rule foreground="#FF00008B" fontWeight="normal" fontStyle="normal">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="CSharp" ignoreCase="false">
+		<Import ruleSet="C#/" />
+		<Rule foreground="#FF00008B" fontWeight="normal" fontStyle="normal">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="ParamList" ignoreCase="false">
+		<Import ruleSet="C#/" />
+		<Rule foreground="#FF00008B" fontWeight="normal" fontStyle="normal">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="RuleDefinition" ignoreCase="false">
+		<Rule foreground="#FF00008B" fontWeight="normal" fontStyle="normal">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/HTML-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/HTML-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/HTML-Mode.xshd	(revision 11807)
@@ -0,0 +1,388 @@
+<?xml version="1.0"?>
+<!-- syntaxdefinition for HTML 2000 by Mike Krueger -->
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name="HTML" extensions=".htm;.html" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="DarkSlateGray" exampleText="&lt;!-- comment --&gt;" />
+	<Color name="Digits" foreground="DarkBlue" exampleText="&lt;digits&gt;0123456789&lt;/digits&gt;" />
+	<Color name="ScriptTag" foreground="#FF8B008B" exampleText="&lt;script&gt;alert('Hello World!');&lt;/script&gt;" />
+	<Color name="JavaScriptTag" foreground="#FF8B008B" exampleText="&lt;script lang=&quot;JavaScript&quot;&gt;alert('Hello World!');&lt;/script&gt;" />
+	<Color name="JScriptTag" foreground="#FF8B008B" exampleText="&lt;script lang=&quot;JScript&quot;&gt;Response.Write(&quot;Hello World!&quot;);&lt;/script&gt;" />
+	<Color name="VBScriptTag" foreground="#FF8B008B" exampleText="&lt;script lang=&quot;VBScript&quot;&gt;Response.Write(&quot;Hello World!&quot;)&lt;/script&gt;" />
+	<Color name="UnknownScriptTag" foreground="#FF8B008B" exampleText="&lt;script la&gt;alert('Hello World!');&lt;/script&gt;" />
+	<Color name="HtmlTag" foreground="#FF8B008B" exampleText="&lt;html&gt;Hello World!/html&gt;" />
+	<Color name="Tags" foreground="#FF8B008B" exampleText="&lt;html&gt;Hello World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="Attributes" foreground="Red" exampleText="&lt;html background='green'&gt;Hello World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="Slash" foreground="DarkMagenta" exampleText="&lt;html background='green'&gt;Hello World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="Assignment" foreground="Blue" exampleText="&lt;html background='green'&gt;Hello World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="String" foreground="Blue" exampleText="&lt;html background='green'&gt;Hello World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="EntityReference" foreground="Blue" exampleText="&lt;html background='green'&gt;Hello&amp;nbsp;World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="Entities" foreground="#FF008000" exampleText="&lt;html background='green'&gt;Hello&amp;nbsp;World! &lt;test /&gt;&lt;/html&gt;" />
+	<Color name="UnknownAttribute" foreground="Blue" exampleText="&lt;html foo='bar' background='green'&gt;Hello&amp;nbsp;World! &lt;test /&gt;&lt;/html&gt;" />
+	<RuleSet ignoreCase="true">
+		<Span color="Comment" multiline="true">
+			<Begin>&lt;!--</Begin>
+			<End>--&gt;</End>
+		</Span>
+		<Span ruleSet="JavaScriptSet" multiline="true">
+			<Begin color="JavaScriptTag">&lt;script\ lang="JavaScript"&gt;</Begin>
+			<End color="JavaScriptTag">&lt;/script&gt;</End>
+		</Span>
+		<Span ruleSet="JavaScriptSet" multiline="true">
+			<Begin color="JavaScriptTag">&lt;script\s.*?text/javascript.*?&gt;</Begin>
+			<End color="JavaScriptTag">&lt;/script&gt;</End>
+		</Span>
+		<Span multiline="true">
+			<Begin color="JScriptTag">&lt;script\ lang="JScript"&gt;</Begin>
+			<End color="JScriptTag">&lt;/script&gt;</End>
+		</Span>
+		<Span multiline="true">
+			<Begin color="VBScriptTag">&lt;script\ lang="VBScript"&gt;</Begin>
+			<End color="VBScriptTag">&lt;/script&gt;</End>
+		</Span>
+		<Span ruleSet="JavaScriptSet" multiline="true">
+			<Begin color="ScriptTag">&lt;script&gt;</Begin>
+			<End color="ScriptTag">&lt;/script&gt;</End>
+		</Span>
+		<Span multiline="true">
+			<Begin color="UnknownScriptTag">&lt;script[^\w\d_]</Begin>
+			<End color="UnknownScriptTag">&lt;/script&gt;</End>
+		</Span>
+		<Span color="HtmlTag" ruleSet="HtmlTagSet" multiline="true">
+			<Begin>&lt;</Begin>
+			<End>&gt;</End>
+		</Span>
+		<Span color="EntityReference" ruleSet="EntityReferenceSet">
+			<Begin>&amp;</Begin>
+			<End>;</End>
+		</Span>
+		<Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="JavaScriptSet">
+		<Import ruleSet="JavaScript/" />
+		<Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="EntityReferenceSet" ignoreCase="false">
+		<Keywords color="Entities">
+			<Word>aacute</Word>
+			<Word>agrave</Word>
+			<Word>acirc</Word>
+			<Word>amp</Word>
+			<Word>atilde</Word>
+			<Word>aring</Word>
+			<Word>auml</Word>
+			<Word>aelig</Word>
+			<Word>ccedil</Word>
+			<Word>copy</Word>
+			<Word>eacute</Word>
+			<Word>egrave</Word>
+			<Word>ecirc</Word>
+			<Word>euml</Word>
+			<Word>iacute</Word>
+			<Word>igrave</Word>
+			<Word>icirc</Word>
+			<Word>iuml</Word>
+			<Word>eth</Word>
+			<Word>gt</Word>
+			<Word>lt</Word>
+			<Word>nbsp</Word>
+			<Word>ntilde</Word>
+			<Word>oacute</Word>
+			<Word>ograve</Word>
+			<Word>ocirc</Word>
+			<Word>otilde</Word>
+			<Word>ouml</Word>
+			<Word>oslash</Word>
+			<Word>quot</Word>
+			<Word>reg</Word>
+			<Word>szlig</Word>
+			<Word>uacute</Word>
+			<Word>ugrave</Word>
+			<Word>ucirc</Word>
+			<Word>uuml</Word>
+			<Word>yacute</Word>
+			<Word>thorn</Word>
+			<Word>trade</Word>
+			<Word>yuml</Word>
+		</Keywords>
+		<Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+	<RuleSet name="HtmlTagSet" ignoreCase="false">
+		<Keywords color="Slash">
+			<Word>/</Word>
+		</Keywords>
+		<Keywords color="Assignment">
+			<Word>=</Word>
+		</Keywords>
+		<Keywords color="Tags">
+			<Word>!DOCTYPE</Word>
+			<Word>A</Word>
+			<Word>ABBR</Word>
+			<Word>ACRONYM</Word>
+			<Word>ADDRESS</Word>
+			<Word>APPLET</Word>
+			<Word>AREA</Word>
+			<Word>B</Word>
+			<Word>BASE</Word>
+			<Word>BASEFONT</Word>
+			<Word>BGSOUND</Word>
+			<Word>BDO</Word>
+			<Word>BIG</Word>
+			<Word>BLINK</Word>
+			<Word>BLOCKQUOTE</Word>
+			<Word>BODY</Word>
+			<Word>BR</Word>
+			<Word>BUTTON</Word>
+			<Word>CAPTION</Word>
+			<Word>CENTER</Word>
+			<Word>CITE</Word>
+			<Word>CODE</Word>
+			<Word>COL</Word>
+			<Word>COLGROUP</Word>
+			<Word>COMMENT</Word>
+			<Word>DD</Word>
+			<Word>DEL</Word>
+			<Word>DFN</Word>
+			<Word>DIR</Word>
+			<Word>DIV</Word>
+			<Word>DL</Word>
+			<Word>DT</Word>
+			<Word>EM</Word>
+			<Word>EMBED</Word>
+			<Word>FIELDSET</Word>
+			<Word>FONT</Word>
+			<Word>FORM</Word>
+			<Word>FRAME</Word>
+			<Word>FRAMESET</Word>
+			<Word>H</Word>
+			<Word>H1</Word>
+			<Word>H2</Word>
+			<Word>H3</Word>
+			<Word>H4</Word>
+			<Word>H5</Word>
+			<Word>H6</Word>
+			<Word>HEAD</Word>
+			<Word>HR</Word>
+			<Word>HTA:APPLICATION</Word>
+			<Word>HTML</Word>
+			<Word>I</Word>
+			<Word>IFRAME</Word>
+			<Word>IMG</Word>
+			<Word>INPUT</Word>
+			<Word>INS</Word>
+			<Word>ISINDEX</Word>
+			<Word>KBD</Word>
+			<Word>LABEL</Word>
+			<Word>LEGEnd</Word>
+			<Word>LI</Word>
+			<Word>LINK</Word>
+			<Word>LISTING</Word>
+			<Word>MAP</Word>
+			<Word>MARQUEE</Word>
+			<Word>MENU</Word>
+			<Word>META</Word>
+			<Word>MULTICOL</Word>
+			<Word>NEXTID</Word>
+			<Word>NOBR</Word>
+			<Word>NOFRAMES</Word>
+			<Word>NOSCRIPT</Word>
+			<Word>OBJECT</Word>
+			<Word>OL</Word>
+			<Word>OPTGROUP</Word>
+			<Word>OPTION</Word>
+			<Word>P</Word>
+			<Word>PARAM</Word>
+			<Word>PLAINTEXT</Word>
+			<Word>PRE</Word>
+			<Word>Q</Word>
+			<Word>S</Word>
+			<Word>SAMP</Word>
+			<Word>SCRIPT</Word>
+			<Word>SELECT</Word>
+			<Word>SERVER</Word>
+			<Word>SMALL</Word>
+			<Word>SOUND</Word>
+			<Word>SPACER</Word>
+			<Word>Span</Word>
+			<Word>STRONG</Word>
+			<Word>STYLE</Word>
+			<Word>SUB</Word>
+			<Word>SUP</Word>
+			<Word>TABLE</Word>
+			<Word>TBODY</Word>
+			<Word>TD</Word>
+			<Word>TEXTAREA</Word>
+			<Word>TEXTFLOW</Word>
+			<Word>TFOOT</Word>
+			<Word>TH</Word>
+			<Word>THEAD</Word>
+			<Word>TITLE</Word>
+			<Word>TR</Word>
+			<Word>TT</Word>
+			<Word>U</Word>
+			<Word>VAR</Word>
+			<Word>WBR</Word>
+			<Word>XMP</Word>
+		</Keywords>
+		<Keywords color="Attributes">
+			<Word>abbr</Word>
+			<Word>accept-charset</Word>
+			<Word>accept</Word>
+			<Word>accesskey</Word>
+			<Word>action</Word>
+			<Word>align</Word>
+			<Word>alink</Word>
+			<Word>alt</Word>
+			<Word>applicationname</Word>
+			<Word>archive</Word>
+			<Word>axis</Word>
+			<Word>background</Word>
+			<Word>behavior</Word>
+			<Word>bgcolor</Word>
+			<Word>bgproperties</Word>
+			<Word>border</Word>
+			<Word>bordercolor</Word>
+			<Word>bordercolordark</Word>
+			<Word>bordercolorligh</Word>
+			<Word>borderstyle</Word>
+			<Word>caption</Word>
+			<Word>cellpadding</Word>
+			<Word>cellspacing</Word>
+			<Word>char</Word>
+			<Word>charoff</Word>
+			<Word>charset</Word>
+			<Word>checked</Word>
+			<Word>cite</Word>
+			<Word>class</Word>
+			<Word>classid</Word>
+			<Word>clear</Word>
+			<Word>code</Word>
+			<Word>codetype</Word>
+			<Word>color</Word>
+			<Word>cols</Word>
+			<Word>colspan</Word>
+			<Word>compact</Word>
+			<Word>content</Word>
+			<Word>coords</Word>
+			<Word>data</Word>
+			<Word>datetime</Word>
+			<Word>declare</Word>
+			<Word>defer</Word>
+			<Word>dir</Word>
+			<Word>direction</Word>
+			<Word>disabled</Word>
+			<Word>dynsrc</Word>
+			<Word>enctype</Word>
+			<Word>face</Word>
+			<Word>for</Word>
+			<Word>frame</Word>
+			<Word>frameborder</Word>
+			<Word>framespacing</Word>
+			<Word>gutter</Word>
+			<Word>headers</Word>
+			<Word>height</Word>
+			<Word>href</Word>
+			<Word>hreflang</Word>
+			<Word>hspace</Word>
+			<Word>http-equiv</Word>
+			<Word>icon</Word>
+			<Word>id</Word>
+			<Word>ismap</Word>
+			<Word>label</Word>
+			<Word>language</Word>
+			<Word>leftmargin</Word>
+			<Word>link</Word>
+			<Word>longdesc</Word>
+			<Word>loop</Word>
+			<Word>lowsrc</Word>
+			<Word>marginheight</Word>
+			<Word>marginwidth</Word>
+			<Word>maximizebutton</Word>
+			<Word>maxlength</Word>
+			<Word>media</Word>
+			<Word>method</Word>
+			<Word>methods</Word>
+			<Word>minimizebutton</Word>
+			<Word>multiple</Word>
+			<Word>name</Word>
+			<Word>nohref</Word>
+			<Word>noresize</Word>
+			<Word>noshade</Word>
+			<Word>nowrap</Word>
+			<Word>object</Word>
+			<Word>onabort</Word>
+			<Word>onblur</Word>
+			<Word>onchange</Word>
+			<Word>onclick</Word>
+			<Word>ondblclick</Word>
+			<Word>onerror</Word>
+			<Word>onfocus</Word>
+			<Word>onkeydown</Word>
+			<Word>onkeypress</Word>
+			<Word>onkeyup</Word>
+			<Word>onload</Word>
+			<Word>onmousedown</Word>
+			<Word>onmousemove</Word>
+			<Word>onmouseout</Word>
+			<Word>onmouseover</Word>
+			<Word>onmouseup</Word>
+			<Word>onreset</Word>
+			<Word>onselect</Word>
+			<Word>onsubmit</Word>
+			<Word>onunload</Word>
+			<Word>profile</Word>
+			<Word>prompt</Word>
+			<Word>readonly</Word>
+			<Word>rel</Word>
+			<Word>rev</Word>
+			<Word>rows</Word>
+			<Word>rowspan</Word>
+			<Word>rules</Word>
+			<Word>runat</Word>
+			<Word>scheme</Word>
+			<Word>scope</Word>
+			<Word>scrollamount</Word>
+			<Word>scrolldelay</Word>
+			<Word>scrolling</Word>
+			<Word>selected</Word>
+			<Word>shape</Word>
+			<Word>showintaskbar</Word>
+			<Word>singleinstance</Word>
+			<Word>size</Word>
+			<Word>span</Word>
+			<Word>src</Word>
+			<Word>standby</Word>
+			<Word>start</Word>
+			<Word>style</Word>
+			<Word>summary</Word>
+			<Word>sysmenu</Word>
+			<Word>tabindex</Word>
+			<Word>target</Word>
+			<Word>text</Word>
+			<Word>title</Word>
+			<Word>topmargin</Word>
+			<Word>type</Word>
+			<Word>urn</Word>
+			<Word>usemap</Word>
+			<Word>valign</Word>
+			<Word>value</Word>
+			<Word>valuetype</Word>
+			<Word>version</Word>
+			<Word>vlink</Word>
+			<Word>vrml</Word>
+			<Word>vspace</Word>
+			<Word>width</Word>
+			<Word>windowstate</Word>
+			<Word>wrap</Word>
+		</Keywords>
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+		</Span>
+		<Span color="String">
+			<Begin>'</Begin>
+			<End>'</End>
+		</Span>
+		<Rule color="UnknownAttribute">[\d\w_]+(?=(\s*=))</Rule>
+		<Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Java-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Java-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Java-Mode.xshd	(revision 11807)
@@ -0,0 +1,152 @@
+<?xml version="1.0"?>
+<!-- syntaxdefinition for Java 2001 by Jonathan Pierce & Mike Krueger -->
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name="Java" extensions=".java" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+  <Color name="MethodName" foreground="DarkBlue" />
+  <Color name="Digits" foreground="DarkBlue" fontStyle="italic" />
+  <Color name="String" foreground="Magenta"  />
+  <Color name="Character" foreground="Magenta"  />
+  <Color name="Comment" foreground="SlateGray" />
+  <Color name="Punctuation" foreground="DarkGreen" />
+  <Color name="AccessKeywords" foreground="Black" fontWeight="bold" />
+  <Color name="OperatorKeywords" foreground="DarkCyan" fontWeight="bold" />
+  <Color name="SelectionStatements" foreground="Blue" fontWeight="bold" />
+  <Color name="IterationStatements" foreground="Blue" fontWeight="bold" />
+  <Color name="ExceptionHandlingStatements" foreground="Teal" fontWeight="bold" />
+  <Color name="ValueTypes" foreground="Red" fontWeight="bold" />
+  <Color name="ReferenceTypes" foreground="Red" />
+  <Color name="Void" foreground="Red" />
+  <Color name="JumpStatements" foreground="Navy" />
+  <Color name="Modifiers" foreground="Brown" />
+  <Color name="AccessModifiers" foreground="Blue" fontWeight="bold" />
+  <Color name="Package" foreground="Green" fontWeight="bold" />
+  <Color name="Literals" foreground="Black" fontWeight="bold" />
+  <Color name="CommentTags" foreground="Red" fontWeight="bold" fontStyle="italic" />
+  <Color name="JavaDocTags" foreground="DarkGray" fontWeight="bold" fontStyle="italic" />
+  <RuleSet ignoreCase="false">
+    <Rule color="Punctuation">
+      [?,.()\[\]{}+\-/%*&lt;&gt;^!|]+
+    </Rule>
+    <Keywords color="AccessKeywords">
+      <Word>this</Word>
+      <Word>super</Word>
+    </Keywords>
+    <Keywords color="OperatorKeywords">
+      <Word>new</Word>
+      <Word>instanceof</Word>
+      <Word>true</Word>
+      <Word>false</Word>
+    </Keywords>
+    <Keywords color="SelectionStatements">
+      <Word>else</Word>
+      <Word>if</Word>
+      <Word>switch</Word>
+      <Word>case</Word>
+    </Keywords>
+    <Keywords color="IterationStatements">
+      <Word>do</Word>
+      <Word>for</Word>
+      <Word>while</Word>
+    </Keywords>
+    <Keywords color="JumpStatements">
+      <Word>break</Word>
+      <Word>continue</Word>
+      <Word>default</Word>
+      <Word>goto</Word>
+      <Word>return</Word>
+    </Keywords>
+    <Keywords color="ExceptionHandlingStatements">
+      <Word>try</Word>
+      <Word>throw</Word>
+      <Word>catch</Word>
+      <Word>finally</Word>
+    </Keywords>
+    <Keywords color="ValueTypes">
+      <Word>boolean</Word>
+      <Word>double</Word>
+      <Word>int</Word>
+      <Word>short</Word>
+      <Word>long</Word>
+      <Word>float</Word>
+      <Word>byte</Word>
+      <Word>char</Word>
+    </Keywords>
+    <Keywords color="ReferenceTypes">
+      <Word>class</Word>
+      <Word>interface</Word>
+      <Word>object</Word>
+    </Keywords>
+    <Keywords color="Void">
+      <Word>void</Word>
+    </Keywords>
+    <Keywords color="Modifiers">
+      <Word>abstract</Word>
+      <Word>const</Word>
+      <Word>static</Word>
+      <Word>final</Word>
+      <Word>native</Word>
+      <Word>extends</Word>
+      <Word>implements</Word>
+      <Word>volatile</Word>
+      <Word>transient</Word>
+      <Word>throws</Word>
+      <Word>strictfp</Word>
+      <Word>synchronized</Word>
+    </Keywords>
+    <Keywords color="AccessModifiers">
+      <Word>public</Word>
+      <Word>protected</Word>
+      <Word>private</Word>
+    </Keywords>
+    <Keywords color="Package">
+      <Word>package</Word>
+      <Word>import</Word>
+    </Keywords>
+    <Keywords color="Literals">
+      <Word>null</Word>
+    </Keywords>
+    <Span color="Comment" ruleSet="TestSet">
+      <Begin>//</Begin>
+    </Span>
+    <Span color="Comment" ruleSet="TestSet" multiline="true">
+      <Begin>/\*</Begin>
+      <End>\*/</End>
+    </Span>
+    <Span color="String">
+      <Begin>"</Begin>
+      <End>"</End>
+      <RuleSet>
+        <Span begin="\\" end="." />
+      </RuleSet>
+    </Span>
+    <Span color="Character">
+      <Begin>'</Begin>
+      <End>'</End>
+      <RuleSet>
+        <Span begin="\\" end="." />
+      </RuleSet>
+    </Span>
+    <Rule color="MethodName">[\d\w_]+(?=(\s*\())</Rule>
+    <Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+  </RuleSet>
+  <RuleSet name="TestSet" ignoreCase="true">
+    <Keywords color="CommentTags">
+      <Word>TODO</Word>
+    </Keywords>
+    <Keywords color="JavaDocTags">
+      <Word>@author</Word>
+      <Word>@version</Word>
+      <Word>@param</Word>
+      <Word>@return</Word>
+      <Word>@exception</Word>
+      <Word>@throws</Word>
+      <Word>@see</Word>
+      <Word>@since</Word>
+      <Word>@serial</Word>
+      <Word>@serialField</Word>
+      <Word>@serialData</Word>
+      <Word>@deprecated</Word>
+    </Keywords>
+    <Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+  </RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/JavaScript-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/JavaScript-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/JavaScript-Mode.xshd	(revision 11807)
@@ -0,0 +1,132 @@
+<?xml version="1.0"?>
+<!-- syntaxdefinition for JavaScript 2.0 by Svante Lidman -->
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name="JavaScript" extensions=".js" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Digits" foreground="DarkBlue" exampleText="3.14" />
+	<Color name="Comment" foreground="Green" exampleText="// comment" />
+	<Color name="String" foreground="Sienna" exampleText="var text = &quot;Hello, World!&quot;;" />
+	<Color name="Character" foreground="Sienna" exampleText="var char = 'a';" />
+	<Color name="Regex" foreground="Sienna" exampleText="/abc/m" />
+	<Color name="JavaScriptKeyWords" foreground="Blue" exampleText="return myVariable;" />
+	<Color name="JavaScriptIntrinsics" foreground="Blue" exampleText="Math.random()" />
+	<Color name="JavaScriptLiterals" foreground="Blue" exampleText="return false;" />
+	<Color name="JavaScriptGlobalFunctions" foreground="Blue" exampleText="escape(myString);" />
+	<RuleSet ignoreCase="false">
+		<Keywords color="JavaScriptKeyWords">
+			<Word>break</Word>
+			<Word>continue</Word>
+			<Word>delete</Word>
+			<Word>else</Word>
+			<Word>for</Word>
+			<Word>function</Word>
+			<Word>if</Word>
+			<Word>in</Word>
+			<Word>new</Word>
+			<Word>return</Word>
+			<Word>this</Word>
+			<Word>typeof</Word>
+			<Word>var</Word>
+			<Word>void</Word>
+			<Word>while</Word>
+			<Word>with</Word>
+			<Word>abstract</Word>
+			<Word>boolean</Word>
+			<Word>byte</Word>
+			<Word>case</Word>
+			<Word>catch</Word>
+			<Word>char</Word>
+			<Word>class</Word>
+			<Word>const</Word>
+			<Word>debugger</Word>
+			<Word>default</Word>
+			<Word>do</Word>
+			<Word>double</Word>
+			<Word>enum</Word>
+			<Word>export</Word>
+			<Word>extends</Word>
+			<Word>final</Word>
+			<Word>finally</Word>
+			<Word>float</Word>
+			<Word>goto</Word>
+			<Word>implements</Word>
+			<Word>import</Word>
+			<Word>instanceof</Word>
+			<Word>int</Word>
+			<Word>interface</Word>
+			<Word>long</Word>
+			<Word>native</Word>
+			<Word>package</Word>
+			<Word>private</Word>
+			<Word>protected</Word>
+			<Word>public</Word>
+			<Word>short</Word>
+			<Word>static</Word>
+			<Word>super</Word>
+			<Word>switch</Word>
+			<Word>synchronized</Word>
+			<Word>throw</Word>
+			<Word>throws</Word>
+			<Word>transient</Word>
+			<Word>try</Word>
+			<Word>volatile</Word>
+		</Keywords>
+		<Keywords color="JavaScriptIntrinsics">
+			<Word>Array</Word>
+			<Word>Boolean</Word>
+			<Word>Date</Word>
+			<Word>Function</Word>
+			<Word>Global</Word>
+			<Word>Math</Word>
+			<Word>Number</Word>
+			<Word>Object</Word>
+			<Word>RegExp</Word>
+			<Word>String</Word>
+		</Keywords>
+		<Keywords color="JavaScriptLiterals">
+			<Word>false</Word>
+			<Word>null</Word>
+			<Word>true</Word>
+			<Word>NaN</Word>
+			<Word>Infinity</Word>
+		</Keywords>
+		<Keywords color="JavaScriptGlobalFunctions">
+			<Word>eval</Word>
+			<Word>parseInt</Word>
+			<Word>parseFloat</Word>
+			<Word>escape</Word>
+			<Word>unescape</Word>
+			<Word>isNaN</Word>
+			<Word>isFinite</Word>
+		</Keywords>
+		<Span color="Comment">
+			<Begin>//</Begin>
+		</Span>
+		<Span color="Comment" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		<!--<Rule color="Regex">/.*/</Rule>-->
+		<Span color="Regex">
+			<Begin>/</Begin>
+			<End>/</End>
+			<RuleSet>
+				<Span begin="\\/" end="." />
+			</RuleSet>
+		</Span>
+		<Span color="String" multiline="true">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<Span begin="\\" end="." />
+			</RuleSet>
+		</Span>
+		<Span color="Character">
+			<Begin>'</Begin>
+			<End>'</End>
+			<RuleSet>
+				<Span begin="\\" end="." />
+			</RuleSet>
+		</Span>
+		<Rule color="Digits">\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/MarkDown-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/MarkDown-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/MarkDown-Mode.xshd	(revision 11807)
@@ -0,0 +1,56 @@
+﻿<?xml version="1.0"?>
+<SyntaxDefinition name="MarkDown" extensions=".md" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Heading" foreground="Maroon" exampleText="# Title #" />
+	<Color name="Emphasis" fontStyle="italic" exampleText="*this* is important!" />
+	<Color name="StrongEmphasis" fontWeight="bold" exampleText="**this** is more important!" />
+	<Color name="Code" exampleText="this is `int.GetHashCode()`" />
+	<Color name="BlockQuote" foreground="DarkBlue" exampleText="&gt; This is a\r\n&gt; quote." />
+	<Color name="Link" foreground="Blue" exampleText="[text](http://example.com)" />
+	<Color name="Image" foreground="Green" exampleText="[text][http://example.com/test.png]" />
+	<Color name="LineBreak" background="LightGray" exampleText="end of line      \r\n2nd line   " />
+	
+	<RuleSet ignoreCase="true">
+		<Rule color="Heading">
+			^\#.*
+		</Rule>
+		<Rule color="StrongEmphasis">
+			\*\*.*\*\*
+		</Rule>
+		<Rule color="StrongEmphasis">
+			__.*__
+		</Rule>
+		<Rule color="Emphasis">
+			\*(?![ ]).*\*
+		</Rule>
+		<Rule color="Emphasis">
+			_.*_
+		</Rule>
+		<Rule color="Code">
+			`.*`
+		</Rule>
+		<Span color="Code" ruleSet="C#/" multiline="true">
+			<Begin>^\t</Begin>
+			<End>^(?!\t)</End>
+		</Span>
+		<Span color="Code" ruleSet="C#/" multiline="true">
+			<Begin>^[ ]{4}</Begin>
+			<End>^(?![ ]{4})</End>
+		</Span>
+		<Span color="BlockQuote" multiline="true">
+			<Begin>^&gt;</Begin>
+			<End>^(?!&gt;)</End>
+		</Span>
+		<Rule color="Image">
+			\!\[.*\]\[.*\]
+		</Rule>
+		<Rule color="Link">
+			\[.*\]\(.*\)
+		</Rule>
+		<Rule color="Link">
+			\[.*\]\[.*\]
+		</Rule>
+		<Rule color="LineBreak">
+			[ ]{2}$
+		</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ModeV1.xsd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ModeV1.xsd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ModeV1.xsd	(revision 11807)
@@ -0,0 +1,296 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
+	<xsd:annotation>
+		<xsd:documentation>
+		This schema defines the syntax for mode definitions in SharpDevelop.
+		The schema can be simplified quite a bit but it does the job as is.
+		
+		
+		If you are using this file as a reference it is probably easiest to scroll to
+		the botton to find the definition of the root element called SyntaxDefinition and
+		then unwind the different type definitions and refernces.
+		
+		Note on coloring:
+		Many tags define how some symbol should be colored. If a specific symbol
+		can not be matched onto either a Span definition, Keyword, or a Digit/Number it
+		will be rendered in the current default color. Which is the default color of the
+		current span or the default color of the mode as a whole if no span has been entered.
+		</xsd:documentation>
+	</xsd:annotation>
+	
+	<!-- Defines the default rendering of the mode -->
+	<xsd:complexType name="EnvironmentEntry">
+		<xsd:attribute name="bold" type="xsd:boolean" />
+		<xsd:attribute name="italic" type="xsd:boolean" />
+		<xsd:attribute name="color" type="xsd:string" />
+		<xsd:attribute name="bgcolor" type="xsd:string" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="CustomEnvironmentEntry">
+		<xsd:attribute name="name" type="xsd:string" use="required" />
+		<xsd:attribute name="bold" type="xsd:boolean" />
+		<xsd:attribute name="italic" type="xsd:boolean" />
+		<xsd:attribute name="color" type="xsd:string" />
+		<xsd:attribute name="bgcolor" type="xsd:string" />
+	</xsd:complexType>
+	
+	<!-- The environment tag defines the coloring of various attributes in SharpDevelop -->
+	<xsd:complexType name="Environment">
+		
+		<xsd:choice minOccurs="0" maxOccurs="unbounded">
+			<xsd:element name="Default" type="EnvironmentEntry" minOccurs="0" maxOccurs="1" />
+			<xsd:element name="Selection" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="VRuler" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="InvalidLines" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="CaretMarker" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="CaretLine" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			
+			<xsd:element name="LineNumbers" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			
+			<xsd:element name="FoldLine" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="FoldMarker" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="SelectedFoldLine" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			
+			<xsd:element name="EOLMarkers" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="SpaceMarkers" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			<xsd:element name="TabMarkers" type="EnvironmentEntry" minOccurs="0" maxOccurs="1"/>
+			
+			<xsd:element name="Custom" type="CustomEnvironmentEntry" minOccurs="0" maxOccurs="unbounded"/>
+		</xsd:choice>
+	</xsd:complexType>
+	
+	<xsd:complexType name="Properties">
+		<xsd:sequence>
+			<xsd:element name="Property" type="Property" minOccurs="0" maxOccurs="unbounded"/>
+		</xsd:sequence>
+	</xsd:complexType>
+	
+	<xsd:complexType name="Property">
+		<!-- The actual KeyWord, typically reserved words or symbols in a programming language -->
+		<xsd:attribute name="name" type="xsd:string" />
+		<xsd:attribute name="value" type="xsd:string" />
+	</xsd:complexType>
+	
+	<!-- The Digits tag defines the color for rendering Digits-->
+	<xsd:complexType name="Digits">
+		<xsd:attribute name="name" type="xsd:string" />
+		<xsd:attribute name="bold" type="xsd:boolean" />
+		<xsd:attribute name="italic" type="xsd:boolean" />
+		<xsd:attribute name="color" type="xsd:string" />
+		<xsd:attribute name="bgcolor" type="xsd:string" />
+	</xsd:complexType>
+	
+	<!-- Defines the delimiting characters of the syntax, e.g., the characters that, "break up" a line
+    into separate symbols, typically key words. It is not necessary, or desirable to include the
+    characters that denot the start or end of a span. Space and Tab are implicitly defined as delimeters
+    and they don't need to be includeded explicitly (this will probably be changed at some future time).-->
+	<xsd:complexType name="Delimiters">
+		<xsd:simpleContent>
+			<xsd:extension base="xsd:string">
+			</xsd:extension>
+		</xsd:simpleContent>
+	</xsd:complexType>
+	
+	<!-- The beginning symbol of a Span -->
+	<xsd:complexType name="Begin">
+		<xsd:simpleContent>
+			<xsd:extension base="xsd:string">
+				<xsd:attribute name="singleword" type="xsd:boolean" />
+				<xsd:attribute name="startofline" type="xsd:boolean" />
+				<!-- The default rendering style for the Begin symbol. If not specified
+					 the defaul rendering style for the span will be used. -->
+				<xsd:attribute name="bold" type="xsd:boolean" />
+				<xsd:attribute name="italic" type="xsd:boolean" />
+				<xsd:attribute name="color" type="xsd:string" />
+				<xsd:attribute name="bgcolor" type="xsd:string" />
+			</xsd:extension>
+		</xsd:simpleContent>
+	</xsd:complexType>
+	
+	<!-- The end symbol of a Span -->
+	<xsd:complexType name="End">
+		<xsd:simpleContent>
+			<xsd:extension base="xsd:string">
+				<xsd:attribute name="singleword" type="xsd:boolean" />
+				<!-- The default rendering style for the End symbol. If not specified
+					 the defaul rendering style for the span will be used. -->
+				<xsd:attribute name="bold" type="xsd:boolean" />
+				<xsd:attribute name="italic" type="xsd:boolean" />
+				<xsd:attribute name="color" type="xsd:string" />
+				<xsd:attribute name="bgcolor" type="xsd:string" />
+			</xsd:extension>
+		</xsd:simpleContent>
+	</xsd:complexType>
+	
+	<xsd:complexType name="Span">
+		<xsd:sequence>
+			<!-- Defines the symbol that indicates the beginning of the span. -->
+			<xsd:element name="Begin" type="Begin" />
+			<!-- Defines the symbol that indicates the end of the span. May be omitted for
+				 one-line spans. -->
+			<xsd:element name="End" minOccurs="0" type="End" />
+		</xsd:sequence>
+		<!-- The name of the span definition -->
+		<xsd:attribute name="name" type="xsd:string" use="required" />
+		<!-- Defines the rule set that is applicable in the Span. May be omitted. -->
+		<xsd:attribute name="rule" type="xsd:string" />
+		<!-- Defines wether the Span should terminate automatically at the end of line. Typical examples
+       		 include one-line comments such as // in C++ or REM in Windows .Bat files. -->
+		<xsd:attribute name="stopateol" type="xsd:boolean" />
+		
+		<!-- OBSOLUTE: Defines whether C-style escape sequences using \ are applicable or not in the span. -->
+		<xsd:attribute name="noescapesequences" type="xsd:boolean" />
+		
+		<!-- defines the escape character -->
+		<xsd:attribute name="escapecharacter" type="xsd:string" />
+		
+		<!-- The default rendering style for the span -->
+		<xsd:attribute name="bold" type="xsd:boolean" />
+		<xsd:attribute name="italic" type="xsd:boolean" />
+		<xsd:attribute name="color" type="xsd:string" />
+		<xsd:attribute name="bgcolor" type="xsd:string" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="MarkPrevious">
+		<xsd:simpleContent>
+			<xsd:extension base="xsd:string">
+				<!-- Svante Lidman, looking in the code it is a bit unclear what the intent is here... -->
+				<xsd:attribute name="markmarker" type="xsd:boolean" />
+				<!-- The rendering style to be used -->
+				<xsd:attribute name="bold" type="xsd:boolean" />
+				<xsd:attribute name="italic" type="xsd:boolean" />
+				<xsd:attribute name="color" type="xsd:string" />
+				<xsd:attribute name="bgcolor" type="xsd:string" />
+			</xsd:extension>
+		</xsd:simpleContent>
+	</xsd:complexType>
+	
+	<!-- Allows you to define the coloring of the symbol that follows a specified symbol -->
+	<xsd:complexType name="MarkFollowing">
+		<xsd:simpleContent>
+			<xsd:extension base="xsd:string">
+				<!-- Svante Lidman, looking in the code it is a bit unclear what the intent is here... -->
+				<xsd:attribute name="markmarker" type="xsd:boolean" />
+				<!-- The rendering style to be used -->
+				<xsd:attribute name="bold" type="xsd:boolean" />
+				<xsd:attribute name="italic" type="xsd:boolean" />
+				<xsd:attribute name="color" type="xsd:string" />
+				<xsd:attribute name="bgcolor" type="xsd:string" />
+			</xsd:extension>
+		</xsd:simpleContent>
+	</xsd:complexType>
+	
+	<xsd:complexType name="Key">
+		<!-- The actual KeyWord, typically reserved words or symbols in a programming language -->
+		<xsd:attribute name="word" type="xsd:string" />
+	</xsd:complexType>
+	
+	
+	<!-- A grouping of keywords that sholuld be colored the same way -->
+	<xsd:complexType name="KeyWords">
+		<xsd:sequence>
+			<!-- allow groups with 0 keywords: this simplifies the syntax highlighting editor -->
+			<!-- A KeyWord -->
+			<xsd:element name="Key" type="Key" minOccurs="0" maxOccurs="unbounded">
+			</xsd:element>
+		</xsd:sequence>
+		<!-- The name of the KeyWord group -->
+		<xsd:attribute name="name" type="xsd:string" />
+		<!-- The rendering style of the  KeyWord group -->
+		<xsd:attribute name="bold" type="xsd:boolean" />
+		<xsd:attribute name="italic" type="xsd:boolean" />
+		<xsd:attribute name="color" type="xsd:string" />
+		<xsd:attribute name="bgcolor" type="xsd:string" />
+	</xsd:complexType>
+	
+	<xsd:complexType name="RuleSet">
+		<xsd:sequence>
+			<!-- Defines the delimiting characters of the syntax, e.g., the characters that, "break up" a line
+        		 into separate symbols, typically key words. It is not necessary, or desirable to include the
+        		 characters that denot the start or end of a span. Space and Tab are implicitly defined as delimeters
+        		 and they don't need to be includeded explicitly (this will probably be changed at some future time).-->
+			<xsd:element name="Delimiters" type="Delimiters" minOccurs="0" maxOccurs="1">
+			</xsd:element>
+			<!-- A Span tag defines a scope, or what can be seen as a separate parsing context where a different set of
+            	 highlighting rules are applicable compared to the text where the span is found. 
+            	 Examples of spans include:
+            	 - A string in a language as C
+            	 - A <script> tag in Html
+            	 - The internals of a tag in XML (between < and >).
+            	 A span can have a rule set associated with it that defines the highlighting rules that are applicable
+            	 in the span. -->
+			<xsd:element name="Span" type="Span" minOccurs="0" maxOccurs="unbounded">
+			</xsd:element>
+			<!-- The MarkPrevious tag allows you to define the coloring of the item that preceeds a specific
+            	 symbol. An example of where this comes in handy is when coloring the contents of an XML-tag,
+            	 in particular the attributes and attribute names. The following definition:
+            	 <MarkPrevious bold="false" italic="false" color="Red">=</MarkPrevious>
+				 will make teh highlighter color words that are followed by an = to be colored in Red.
+				 You can see this in this file if you view it with the default XML-mode in SharpDevelop. -->
+			<xsd:element name="MarkPrevious" type="MarkPrevious" minOccurs="0" maxOccurs="unbounded">
+			</xsd:element>
+			<!-- The MarkFollowing tag works similarly as the MarkPrevious tag but relates to the coloring
+            of the symbol that follows the specified symbol. -->
+			<xsd:element name="MarkFollowing" type="MarkFollowing" minOccurs="0" maxOccurs="unbounded">
+			</xsd:element>
+			<!-- Defines a group of keywords that should be colored the same way -->
+			<xsd:element name="KeyWords" type="KeyWords" minOccurs="0" maxOccurs="unbounded">
+			</xsd:element>
+		</xsd:sequence>
+		<!-- The name of the RuleSet. Used when you refer to the RuleSet in the rule attribute of a Span tag.
+        	 Each mode file should have a rule definition without a defined name. This denotes the default rule
+        	 set for the mode. -->
+		<xsd:attribute name="name" type="xsd:string" />
+		<!-- Allows you to use another mode, defined in another file as a RuleSet. For an example see the
+        	 use of the JavaScript mode from the HTML-mode. -->
+		<xsd:attribute name="reference" type="xsd:string" />
+		<!-- Defines whether case is significant for matching keywords in the mode. -->
+		<xsd:attribute name="ignorecase" type="xsd:boolean" />
+		<!-- OBSOLETE: noescapesequences -->
+		<xsd:attribute name="noescapesequences" type="xsd:boolean" />
+		<!-- defines the escape character -->
+		<xsd:attribute name="escapecharacter" type="xsd:string" />
+	</xsd:complexType>
+	
+	<!-- The RuleSets tag is just a grouping of the set of RuleSets for a mode. -->
+	<xsd:complexType name="RuleSets">
+		<xsd:sequence minOccurs="0" maxOccurs="unbounded">
+			<!-- Any number of RuleSet tag can be defined in a mode -->
+			<xsd:element name="RuleSet" type="RuleSet" minOccurs="1" maxOccurs="unbounded">
+			</xsd:element>
+		</xsd:sequence>
+	</xsd:complexType>
+	
+	<!-- SyntaxDefinition is the root-element in a mode definition file -->
+	<xsd:element name="SyntaxDefinition">
+		<xsd:complexType>
+			<xsd:sequence>
+				<!-- The Environment tag defines colors, for various standard elements in the SharpDevelop GUI, if
+				     not given the default values are used. -->
+				<xsd:element name="Environment" type="Environment" minOccurs="0" maxOccurs="1"/>
+				
+				<!-- The Properties section defines properties which are bound to the highlighting -->
+				<xsd:element name="Properties" type="Properties" minOccurs="0" maxOccurs="1" />
+				
+				<!-- The Digits tag defines the color for rendering Digits-->
+				<xsd:element name="Digits" type="Digits" minOccurs="0" maxOccurs="1"/>
+				
+				<!-- The RuleSets tag defines the rule sets that are used in the mode. Note that all modes are defined in
+					 a flat structture even if they are used recursively. For an example of a mode that uses
+					 multiple rule sets see the XML-mode. There is a top level rule-set and and another rule-set
+					 that handles highligting within a tag, i.e., between < and >. -->
+				<xsd:element name="RuleSets" type="RuleSets" />
+			</xsd:sequence>
+			<!-- The name of the mode. This is used when you, in the defintion of a RuleSet refers to another
+				 mode. I.e., one that is defined in an external file. For an example of this see the HTML-Mode that
+				 uses the JavaScript-mode this way. -->
+			<xsd:attribute name="name" type="xsd:string" />
+			<!-- The file extensions that the mode is applicable for. Extensions must be written with lower case and
+				 should include the ., as in .txt. If several extensions are applicable they should be separeated with | -->
+			<xsd:attribute name="extensions" type="xsd:string" />
+			<!-- Name of a syntax mode where rulesets, spans, keywords and other settings are imported from -->
+			<xsd:attribute name="extends" type="xsd:string" />
+		</xsd:complexType>
+	</xsd:element>
+
+</xsd:schema>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ModeV2.xsd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ModeV2.xsd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/ModeV2.xsd	(revision 11807)
@@ -0,0 +1,167 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xsd:schema version="2" elementFormDefault="qualified" targetNamespace="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+	<!-- Font Weight -->
+	<xsd:simpleType name="FontWeight">
+		<xsd:union>
+			<xsd:simpleType>
+				<xsd:restriction base="xsd:integer">
+					<xsd:minInclusive value="1"/>
+					<xsd:maxInclusive value="999"/>
+				</xsd:restriction>
+			</xsd:simpleType>
+			<xsd:simpleType>
+				<xsd:restriction base="xsd:string">
+					<xsd:enumeration value="bold"/>
+					<xsd:enumeration value="normal"/>
+					<xsd:enumeration value="regular"/>
+					<!-- should we support other font weight names? -->
+				</xsd:restriction>
+			</xsd:simpleType>
+		</xsd:union>
+	</xsd:simpleType>
+	
+	<!-- Font Style -->
+	<xsd:simpleType name="FontStyle">
+		<xsd:restriction base="xsd:string">
+			<xsd:enumeration value="italic"/>
+			<xsd:enumeration value="normal"/>
+			<xsd:enumeration value="oblique"/>
+		</xsd:restriction>
+	</xsd:simpleType>
+	
+	<!-- Color -->
+	<xsd:attributeGroup name="ColorAttributes">
+		<xsd:attribute name="foreground" type="xsd:string" use="optional" />
+		<xsd:attribute name="background" type="xsd:string" use="optional" />
+		<xsd:attribute name="fontWeight" type="FontWeight" use="optional" />
+		<xsd:attribute name="fontStyle" type="FontStyle" use="optional" />
+		<xsd:anyAttribute namespace="##other" processContents="lax" />
+	</xsd:attributeGroup>
+	
+	<xsd:attributeGroup name="ColorReferenceAttributes">
+		<xsd:attributeGroup ref="ColorAttributes" />
+		<xsd:attribute name="color" type="xsd:string" use="optional" />
+	</xsd:attributeGroup>
+	
+	<xsd:element name="Color">
+		<xsd:complexType>
+			<xsd:attribute name="name" type="xsd:string" use="required" />
+			<xsd:attribute name="exampleText" type="xsd:string" use="optional" />
+			<xsd:attributeGroup ref="ColorAttributes"/>
+		</xsd:complexType>
+	</xsd:element>
+	
+	<xsd:element name="Property">
+		<xsd:complexType>
+			<xsd:attribute name="name" type="xsd:string" use="required" />
+			<xsd:attribute name="value" type="xsd:string" use="required" />
+			<xsd:anyAttribute namespace="##other" processContents="lax" />
+		</xsd:complexType>
+	</xsd:element>
+	
+	<!-- Regular expression -->
+	<xsd:simpleType name="regex">
+		<xsd:restriction base="xsd:string"/>
+	</xsd:simpleType>
+	
+	<xsd:simpleType name="regexIgnorePatternWhitespace">
+		<xsd:restriction base="xsd:string"/>
+	</xsd:simpleType>
+	
+	<!-- Keywords -->
+	<xsd:element name="Keywords">
+		<xsd:complexType>
+			<xsd:sequence>
+				<xsd:element ref="Word" minOccurs="1" maxOccurs="unbounded"/>
+			</xsd:sequence>
+			<xsd:attributeGroup ref="ColorReferenceAttributes"/>
+		</xsd:complexType>
+	</xsd:element>
+	
+	<xsd:element name="Word">
+		<xsd:complexType>
+			<xsd:simpleContent>
+				<xsd:extension base="xsd:string">
+					<xsd:anyAttribute namespace="##other" processContents="lax" />
+				</xsd:extension>
+			</xsd:simpleContent>
+		</xsd:complexType>
+	</xsd:element>
+	
+	<!-- Spans -->
+	<xsd:element name="Span">
+		<xsd:complexType>
+			<xsd:sequence>
+				<xsd:element ref="Begin" minOccurs="0" maxOccurs="1"/>
+				<xsd:element ref="End" minOccurs="0" maxOccurs="1"/>
+				<xsd:element ref="RuleSet" minOccurs="0" maxOccurs="1"/>
+			</xsd:sequence>
+			
+			<xsd:attributeGroup ref="ColorReferenceAttributes"/>
+			<xsd:attribute name="multiline" type="xsd:boolean" use="optional"/>
+			<xsd:attribute name="ruleSet" type="xsd:string" use="optional"/>
+			<xsd:attribute name="begin" type="regex" use="optional"/>
+			<xsd:attribute name="end" type="regex" use="optional"/>
+		</xsd:complexType>
+	</xsd:element>
+	
+	<xsd:complexType name="SpanBeginEnd">
+		<xsd:simpleContent>
+			<xsd:extension base="regexIgnorePatternWhitespace">
+				<xsd:attributeGroup ref="ColorReferenceAttributes"/>
+			</xsd:extension>
+		</xsd:simpleContent>
+	</xsd:complexType>
+	
+	<xsd:element name="Begin" type="SpanBeginEnd"/>
+	<xsd:element name="End" type="SpanBeginEnd"/>
+	
+	<!-- Imports -->
+	<xsd:element name="Import">
+		<xsd:complexType>
+			<xsd:attribute name="ruleSet" type="xsd:string" use="required"/>
+		</xsd:complexType>
+	</xsd:element>
+	
+	<!-- Rules -->
+	<xsd:element name="Rule">
+		<xsd:complexType>
+			<xsd:simpleContent>
+				<xsd:extension base="regexIgnorePatternWhitespace">
+					<xsd:attributeGroup ref="ColorReferenceAttributes"/>
+				</xsd:extension>
+			</xsd:simpleContent>
+		</xsd:complexType>
+	</xsd:element>
+	
+	<!-- Rule set -->
+	<xsd:element name="RuleSet">
+		<xsd:complexType>
+			<xsd:choice minOccurs="0" maxOccurs="unbounded">
+				<xsd:element ref="Keywords"/>
+				<xsd:element ref="Span"/>
+				<xsd:element ref="Import"/>
+				<xsd:element ref="Rule"/>
+				<xsd:any namespace="##other" processContents="lax" />
+			</xsd:choice>
+			<xsd:attribute name="name" type="xsd:string" use="optional" />
+			<xsd:attribute name="ignoreCase" type="xsd:boolean" use="optional" />
+			<xsd:anyAttribute namespace="##other" processContents="lax" />
+		</xsd:complexType>
+	</xsd:element>
+	
+	<!-- Main syntax definition -->
+	<xsd:element name="SyntaxDefinition">
+		<xsd:complexType>
+			<xsd:choice minOccurs="1" maxOccurs="unbounded">
+				<xsd:element ref="Property"/>
+				<xsd:element ref="Color"/>
+				<xsd:element ref="RuleSet"/>
+				<xsd:any namespace="##other" processContents="lax" />
+			</xsd:choice>
+			<xsd:attribute name="name" type="xsd:string" use="optional" />
+			<xsd:attribute name="extensions" type="xsd:string" use="optional" />
+			<xsd:anyAttribute namespace="##other" processContents="lax" />
+		</xsd:complexType>
+	</xsd:element>
+</xsd:schema>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/PHP-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/PHP-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/PHP-Mode.xshd	(revision 11807)
@@ -0,0 +1,158 @@
+<?xml version="1.0"?>
+<!-- syntaxdefinition for PHP 2001 by Chad Smith & Mike Krueger -->
+<!-- converted to AvalonEdit format by Siegfried Pammer in 2010 -->
+<SyntaxDefinition name ="PHP" extensions = ".php" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="Green" exampleText="// comment" />
+	<Color name="String" foreground="Blue" exampleText="$text = &quot;Hello, World!&quot;" />
+	<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415" />
+	<Color name="Punctuation" foreground="DarkGreen" exampleText="a(b + c)" />
+	<Color name="FunctionCall" foreground="MidnightBlue" fontWeight="bold" exampleText="abs(num);"/>
+	<Color name="AccessKeywords" foreground="Black" fontWeight="bold" exampleText="global $database;" />
+	<Color name="OperatorKeywords" foreground="DarkCyan" fontWeight="bold" exampleText="if (x === false and y === false) { }" />
+	<Color name="SelectionStatements" foreground="Blue" fontWeight="bold" exampleText="if (true) { } else { }" />
+	<Color name="IterationStatements" foreground="Blue" fontWeight="bold" exampleText="while (true) { }" />
+	<Color name="JumpStatements" foreground="Navy" fontWeight="bold" exampleText="if (x == 5) continue;" />
+	<Color name="ControlStatements" foreground="Teal" fontWeight="bold" exampleText="include(&quot;test.php&quot;);" />
+	<Color name="ValueTypes" foreground="Red" fontWeight="bold" exampleText="int test = 5;" />
+	<Color name="OtherTypes" foreground="Red" exampleText="object test = null;" />
+	<Color name="AccessModifiers" foreground="Blue" fontWeight="bold" exampleText="public function test() {}" />
+	<RuleSet>
+		<Span color="Comment">
+			<Begin>\#</Begin>
+		</Span>
+		
+		<Span color="Comment">
+			<Begin>//</Begin>
+		</Span>
+		
+		<Span color="Comment" multiline="true">
+			<Begin>/\*</Begin>
+			<End>\*/</End>
+		</Span>
+		
+		<!-- Digits -->
+		<Rule color="NumberLiteral">
+			\b0[xX][0-9a-fA-F]+  # hex number
+		|
+			\b0[0-9]+ # octal number
+		|
+			(	\b\d+(\.[0-9]+)?   #number with optional floating point
+			|	\.[0-9]+           #or just starting with floating point
+			)
+			([eE][+-]?[0-9]+)? # optional exponent
+		</Rule>
+		
+		<Rule color="Punctuation">
+			[?,.:;()\[\]{}+\-/%*&lt;&gt;&amp;^!|~@]+
+		</Rule>
+		
+		<!-- Mark previous rule-->
+		<Rule color="FunctionCall">
+		\b
+		[\d\w_]+  # an identifier
+		(?=\s*\() # followed by (
+		</Rule>
+		
+		<Span color="String" multiline="true">
+			<Begin>'</Begin>
+			<End>'</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin="\\" end="."/>
+			</RuleSet>
+		</Span>
+		
+		<Span color="String" multiline="true">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin="\\" end="."/>
+			</RuleSet>
+		</Span>
+		
+		<!-- heredoc syntax -->
+		<Span color="String" multiline="true">
+			<Begin>&lt;&lt;&lt;\"?[\d\w_]+\"?$</Begin>
+		 	<End>^[\d\w_]+;</End>
+		</Span>
+	
+		<!-- nowdoc syntax -->
+		<Span color="String" multiline="true">
+			<Begin>&lt;&lt;&lt;\'[\d\w_]+\'$</Begin>
+			<End>^[\d\w_]+;</End>
+		</Span>
+	
+		<Keywords color="AccessKeywords">
+			<Word>global</Word>
+			<Word>my</Word>
+			<Word>var</Word>
+		</Keywords>
+		
+		<Keywords color="OperatorKeywords">
+			<Word>and</Word>
+			<Word>or</Word>
+			<Word>new</Word>
+			<Word>clone</Word>
+			<Word>instanceof</Word>
+			<Word>xor</Word>
+			<Word>true</Word>
+			<Word>false</Word>
+		</Keywords>
+	
+		<Keywords color="SelectionStatements">
+			<Word>else</Word>
+			<Word>else</Word>
+			<Word>switch</Word>
+			<Word>case</Word>
+			<Word>endif</Word>
+			<Word>elseif</Word>
+		</Keywords>
+	
+		<Keywords color="IterationStatements">
+			<Word>do</Word>
+			<Word>for</Word>
+			<Word>foreach</Word>
+			<Word>while</Word>
+			<Word>endwhile</Word>
+			<Word>exit</Word>
+		</Keywords>
+	
+		<Keywords color="JumpStatements">
+			<Word>break</Word>
+			<Word>continue</Word>
+			<Word>default</Word>
+			<Word>goto</Word>
+			<Word>return</Word>
+		</Keywords>
+	
+		<Keywords color="ControlStatements">
+			<Word>require</Word>
+			<Word>include</Word>
+			<Word>require</Word>
+			<Word>include</Word>
+			<Word>function</Word>
+		</Keywords>
+	
+		<Keywords color="ValueTypes">
+			<Word>int</Word>
+			<Word>integer</Word>
+			<Word>real</Word>
+			<Word>double</Word>
+			<Word>float</Word>
+			<Word>string</Word>
+			<Word>array</Word>
+			<Word>object</Word>
+		</Keywords>
+	
+		<Keywords color="OtherTypes">
+			<Word>class</Word>
+			<Word>void</Word>
+		</Keywords>
+	
+		<Keywords color="AccessModifiers">
+			<Word>public</Word>
+			<Word>private</Word>
+		</Keywords>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Patch-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Patch-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Patch-Mode.xshd	(revision 11807)
@@ -0,0 +1,35 @@
+﻿<?xml version="1.0"?>
+<SyntaxDefinition name="Patch" extensions=".patch;.diff" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="AddedText" foreground="Navy" exampleText="+added" />
+	<Color name="RemovedText" foreground="#FF339966" exampleText="-removed" />
+	<Color name="UnchangedText" exampleText=" unchanged" />
+	<Color name="Position" foreground="Navy" exampleText="@@ -186,6 +186,12 @@" />
+	<Color name="Header" foreground="DarkRed" exampleText="--- (oldversion)&#10;+++ (newversion)" />
+	<Color name="FileName" foreground="Green" fontWeight="bold" exampleText="Index: path/to/file" />
+	<RuleSet>
+		<Span color="FileName">
+			<Begin>Index:\s</Begin>
+		</Span>
+		<Span color="Header">
+			<Begin>==</Begin>
+		</Span>
+		<Span color="Header">
+			<Begin>---</Begin>
+		</Span>
+		<Span color="Header">
+			<Begin>\+\+\+</Begin>
+		</Span>
+		<Span foreground="Purple">
+			<Begin>@@</Begin>
+		</Span>
+		<Span color="RemovedText">
+			<Begin>-</Begin>
+		</Span>
+		<Span color="AddedText">
+			<Begin>\+</Begin>
+		</Span>
+		<Span color="UnchangedText">
+			<Begin>\s</Begin>
+		</Span>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/PowerShell.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/PowerShell.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/PowerShell.xshd	(revision 11807)
@@ -0,0 +1,146 @@
+﻿<?xml version="1.0"?>
+<SyntaxDefinition name="PowerShell" extensions=".ps1;.psm1;.psd1" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="Green" exampleText="// comment" />
+	<Color name="String" foreground="Blue" exampleText="string text = &quot;Hello, World!&quot;"/>
+	<Color name="Char" foreground="Magenta" exampleText="char linefeed = '\n';"/>
+	<Color name="Punctuation" exampleText="a(b.c);" />
+	<Color name="NumberLiteral" foreground="DarkBlue" exampleText="3.1415f"/>
+	<Color name="Keywords" fontWeight="bold" foreground="Blue" exampleText="if (a)"/>
+	<Color name="Variable" foreground="Maroon" exampleText="$param = 1" />
+	<Color name="ExceptionKeywords" fontWeight="bold" foreground="Teal" />
+	<Color name="GotoKeywords" foreground="Navy" />
+	<Color name="ReferenceTypes" foreground="Red" />
+	<Color name="Command" fontWeight="bold" foreground="MidnightBlue" />
+	<Color name="Operators" foreground="#FF8515EA" exampleText="-eq"/>
+	
+	<RuleSet ignoreCase="true">
+		<Span color="Comment">
+			<Begin>\#</Begin>
+		</Span>
+		
+		<Span color="Comment" multiline="true">
+			<Begin>&lt;\#</Begin>
+			<End>\#&gt;</End>
+		</Span>
+		
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin="\\" end="."/>
+			</RuleSet>
+		</Span>
+		
+		<Span color="Char">
+			<Begin>'</Begin>
+			<End>'</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin="\\" end="."/>
+			</RuleSet>
+		</Span>
+		
+		<Span color="String" multiline="true">
+			<Begin color="String">@"</Begin>
+			<End>"@</End>
+			<RuleSet>
+				<!-- span for escape sequences -->
+				<Span begin='""' end=""/>
+			</RuleSet>
+		</Span>
+				
+		<Keywords color="Keywords">
+			<Word>while</Word>
+			<Word>param</Word>
+			<Word>end</Word>
+			<Word>define</Word>
+			<Word>else</Word>
+			<Word>from</Word>
+			<Word>foreach</Word>
+			<Word>var</Word>
+			<Word>dynamicparam</Word>
+			<Word>filter</Word>
+			<Word>dp</Word>
+			<Word>until</Word>
+			<Word>for</Word>
+			<Word>exit</Word>
+			<Word>switch</Word>
+			<Word>process</Word>
+			<Word>begin</Word>
+			<Word>elseif</Word>
+			<Word>if</Word>
+			<Word>in</Word>
+			<Word>data</Word>
+			<Word>class</Word>
+			<Word>using</Word>
+			<Word>function</Word>
+		</Keywords>
+		
+		<Keywords color="ExceptionKeywords">
+			<Word>catch</Word>
+			<Word>finally</Word>
+			<Word>throw</Word>
+			<Word>trap</Word>
+			<Word>try</Word>
+		</Keywords>
+		
+		<Keywords color="GotoKeywords">
+			<Word>break</Word>
+			<Word>continue</Word>
+			<Word>return</Word>
+		</Keywords>
+		
+		<Keywords color="ReferenceTypes">
+			<Word>class</Word>
+		</Keywords>
+		
+		<Keywords color="Operators">
+			<Word>-not</Word>
+			<Word>-band</Word>
+			<Word>-bor</Word>
+			<Word>-replace</Word>
+			<Word>-ireplace</Word>
+			<Word>-creplace</Word>
+			<Word>-and</Word>
+			<Word>-or</Word>
+			<Word>-is</Word>
+			<Word>-isnot</Word>
+			<Word>-as</Word>
+			<Word>-lt</Word>
+			<Word>-le</Word>
+			<Word>-gt</Word>
+			<Word>-ge</Word>
+			<Word>-eq</Word>
+			<Word>-ne</Word>
+			<Word>-contains</Word>
+			<Word>-notcontains</Word>
+			<Word>-like</Word>
+			<Word>-notlike</Word>
+			<Word>-match</Word>
+			<Word>-notmatch</Word>
+		</Keywords>
+		
+		<Rule color="Variable">
+			\$[\d\w_]+
+		</Rule>
+		
+		<Rule color="Command">
+		[\w]+-[\w]+
+		</Rule>
+		
+		<!-- Digits -->
+		<Rule color="NumberLiteral">
+			\b0[xX][0-9a-fA-F]+  # hex number
+		|	
+			(	\b\d+(\.[0-9]+)?   #number with optional floating point
+			|	\.[0-9]+           #or just starting with floating point
+			)
+			([eE][+-]?[0-9]+)? # optional exponent
+		</Rule>
+		
+		<Rule color="Punctuation">
+			[?,.;()\[\]{}+\-/%*&lt;&gt;^+~!|&amp;]+
+		</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Resources.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Resources.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Resources.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	static class Resources
+	{
+		static readonly string Prefix = typeof(Resources).FullName + ".";
+		
+		public static Stream OpenStream(string name)
+		{
+			Stream s = typeof(Resources).Assembly.GetManifestResourceStream(Prefix + name);
+			if (s == null)
+				throw new FileNotFoundException("The resource file '" + name + "' was not found.");
+			return s;
+		}
+		
+		internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm)
+		{
+			hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd");
+			hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd");
+			
+			hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd");
+			hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd");
+			hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd");
+			
+			hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd");
+			hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd");
+			hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd");
+			hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp" , ".hpp" }, "CPP-Mode.xshd");
+			hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd");
+			hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd");
+			hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd");
+			hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd");
+			hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd");
+			hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd");
+			hlm.RegisterHighlighting("XML", (".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;" +
+			                                 ".xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;" +
+			                                 ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" +
+			                                 ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'),
+			                         "XML-Mode.xshd");
+			hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Tex-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Tex-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/Tex-Mode.xshd	(revision 11807)
@@ -0,0 +1,108 @@
+<?xml version="1.0"?>
+<!-- syntaxdefinition for TeX document 2001 by Mike Krueger (gleaned from Jedit) -->
+
+<SyntaxDefinition name = "TeX" extensions = ".tex">
+	
+	<Digits   name = "Digits" bold = "false" italic = "false" color = "Black"/>
+	
+	<RuleSets>
+		<RuleSet ignorecase = "false">
+		  	<Delimiters>&amp;~!@%^*()-+=|\#/{}[]:;"'&lt;&gt; , .?</Delimiters>
+			
+			<Span name = "LineComment" bold = "false" italic = "true" color = "SlateGray" stopateol = "true">
+				<Begin>%</Begin>
+			</Span>
+			
+			<Span name = "MathMode" rule = "MathMode" bold = "false" italic = "false" color = "Black" stopateol = "false">
+				<Begin>$$</Begin>
+				<End>$$</End>
+			</Span>
+			<Span name = "LatexMathMode" rule = "MathMode" bold = "false" italic = "false" color = "Black" stopateol = "false">
+				<Begin>\[</Begin>
+				<End>\]</End>
+			</Span>
+			
+			<!-- \... commands -->
+			<MarkFollowing markmarker ="true" bold = "true" italic = "false" color = "MidnightBlue">\</MarkFollowing>
+			
+			<!-- some commands must be handled specially -->
+			<KeyWords name = "Keyword1" bold = "false" italic = "false" color = "Blue">
+				<Key word = "\$" />
+				<Key word = "\\" />
+				<Key word = "\%" />
+		  	</KeyWords>
+		  
+		 	<KeyWords name = "KeyWords2" bold="true" italic="false" color="Green">
+				    <Key word = ")" />
+				    <Key word = ")" />
+				    <Key word = "{" />
+				    <Key word = "}" />
+				    <Key word = "[" />
+				    <Key word = "]" />
+				    <Key word = "=" />
+				    <Key word = "!" />
+				    <Key word = "+" />
+				    <Key word = "-" />
+				    <Key word = "/" />
+				    <Key word = "*" />
+				    <Key word = "&gt;" />
+				    <Key word = "&lt;" />
+				    <Key word = "&amp;" />
+				    <Key word = "|" />
+				    <Key word = "^" />
+				    <Key word = "~" />
+				    <Key word = "." />
+				    <Key word = "," />
+				    <Key word = ";" />
+				    <Key word = "?" />
+				    <Key word = ":" />
+				    <Key word = "'" />
+	<!--			    <Key word = """ />-->
+				    <Key word = "`" />
+	 	 	</KeyWords>
+		</RuleSet>
+		
+		<RuleSet name = "MathMode" ignorecase = "false">
+		  	<Delimiters>&amp;~!@%^*()-+=|\#/{}[]:;"'&lt;&gt; , .?</Delimiters>
+			
+			
+			<Span name = "LineComment" bold = "false" italic = "true" color = "SlateGray" stopateol = "true">
+				<Begin>%</Begin>
+			</Span>
+		 	
+			<!-- \... commands -->
+			<MarkFollowing markmarker ="true" bold = "true" italic = "false" color = "MidnightBlue">\</MarkFollowing>
+
+			<KeyWords name = "KeyWords2" bold="true" italic="false" color="Green">
+				    <Key word = ")" />
+				    <Key word = ")" />
+				    <Key word = "{" />
+				    <Key word = "}" />
+				    <Key word = "[" />
+				    <Key word = "]" />
+				    <Key word = "=" />
+				    <Key word = "!" />
+				    <Key word = "+" />
+				    <Key word = "-" />
+				    <Key word = "/" />
+				    <Key word = "*" />
+				    <Key word = "&gt;" />
+				    <Key word = "&lt;" />
+				    <Key word = "&amp;" />
+				    <Key word = "|" />
+				    <Key word = "^" />
+				    <Key word = "~" />
+				    <Key word = "." />
+				    <Key word = "," />
+				    <Key word = ";" />
+				    <Key word = "?" />
+				    <Key word = ":" />
+				    <Key word = "'" />
+	<!--			    <Key word = """ />-->
+				    <Key word = "`" />
+	 	 	</KeyWords>
+		</RuleSet>
+	</RuleSets>
+	
+</SyntaxDefinition>
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/VB-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/VB-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/VB-Mode.xshd	(revision 11807)
@@ -0,0 +1,256 @@
+<?xml version="1.0"?>
+
+<!-- Syntaxdefinition for VB.NET, v0.1 Rev 1 by Christian Holm -->
+<!-- Updated 2005 by Daniel Grunwald for VB.NET 2.0 -->
+<!-- Converted to AvalonEdit format by Daniel Grunwald in 2010 -->
+<!-- Updated 2010 by Siegfried Oleg Pammer for VB.NET 9 and 10 -->
+<!-- Updated 2011 by Siegfried Oleg Pammer for VB 11 CTP -->
+<SyntaxDefinition name="VB" extensions=".vb" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="Comment" foreground="Green" exampleText="' comment" />
+	<Color name="String" exampleText="text = &quot;Hello, World!&quot;" />
+	
+	<Color name="DateLiteral" foreground="Blue" exampleText="endOfWorld = #2012-12-21#" />
+	<Color name="Preprocessor" foreground="Maroon" exampleText="#Region &quot;Title&quot;" />
+	<Color name="DataTypes" foreground="#FF6F002F" exampleText="Dim b As Boolean = True" />
+	<Color name="Operators" foreground="#FF8515EA" exampleText="If a OrElse b Then"/>
+	<Color name="Constants" foreground="Blue" exampleText="b = False" />
+	<Color name="Keywords" foreground="Blue" exampleText="If a OrElse b Then" />
+	<Color name="FunctionKeywords" foreground="Blue" exampleText="CInt(a)" />
+	<Color name="ContextKeywords" foreground="Blue" exampleText="Declare Unicode Sub SomeMethod" />
+	
+	<Property name="DocCommentMarker" value="'''" />
+	
+	<RuleSet ignoreCase="true">
+		<Span color="String">
+			<Begin>"</Begin>
+			<End>"</End>
+			<RuleSet>
+				<Span begin="&quot;&quot;" end="" />
+			</RuleSet>
+		</Span>
+		<Span color="Preprocessor" ruleSet="PreprocessorSet">
+			<Begin>(?&lt;=(^\s*))\#</Begin>
+		</Span>
+		<Span color="DateLiteral">
+			<Begin>(?&lt;!(^\s*))\#</Begin>
+			<End>\#</End>
+		</Span>
+		<Span color="Comment" ruleSet="XmlDoc/DocCommentSet">
+			<Begin color="XmlDoc/DocComment">'''</Begin>
+		</Span>
+		<Span color="Comment">
+			<Begin>'</Begin>
+		</Span>
+		<Span color="Comment">
+			<Begin>\bREM\b</Begin>
+		</Span>
+		<Keywords color="DataTypes">
+			<Word>Boolean</Word>
+			<Word>Byte</Word>
+			<Word>Char</Word>
+			<Word>Date</Word>
+			<Word>Decimal</Word>
+			<Word>Double</Word>
+			<Word>Integer</Word>
+			<Word>Long</Word>
+			<Word>Object</Word>
+			<Word>SByte</Word>
+			<Word>Short</Word>
+			<Word>Single</Word>
+			<Word>String</Word>
+			<Word>UInteger</Word>
+			<Word>ULong</Word>
+			<Word>UShort</Word>
+			<Word>Variant</Word>
+		</Keywords>
+		<Keywords color="Operators">
+			<Word>AddressOf</Word>
+			<Word>And</Word>
+			<Word>AndAlso</Word>
+			<Word>Await</Word>
+			<Word>Is</Word>
+			<Word>IsNot</Word>
+			<Word>Like</Word>
+			<Word>Mod</Word>
+			<Word>New</Word>
+			<Word>Not</Word>
+			<Word>Or</Word>
+			<Word>OrElse</Word>
+			<Word>Xor</Word>
+		</Keywords>
+		<Keywords color="Constants">
+			<Word>False</Word>
+			<Word>Me</Word>
+			<Word>MyBase</Word>
+			<Word>MyClass</Word>
+			<Word>Nothing</Word>
+			<Word>True</Word>
+		</Keywords>
+		<Keywords color="FunctionKeywords">
+			<Word>CBool</Word>
+			<Word>CByte</Word>
+			<Word>CChar</Word>
+			<Word>CDate</Word>
+			<Word>CDbl</Word>
+			<Word>CDec</Word>
+			<Word>CInt</Word>
+			<Word>CLng</Word>
+			<Word>CObj</Word>
+			<Word>CSByte</Word>
+			<Word>CShort</Word>
+			<Word>CSng</Word>
+			<Word>CStr</Word>
+			<Word>CType</Word>
+			<Word>CUInt</Word>
+			<Word>CULng</Word>
+			<Word>CUShort</Word>
+			<Word>DirectCast</Word>
+			<Word>GetType</Word>
+			<Word>GetXmlNamespace</Word>
+			<Word>IIf</Word>
+			<Word>TryCast</Word>
+			<Word>TypeOf</Word>
+		</Keywords>
+		<Keywords color="Keywords">
+			<Word>AddHandler</Word>
+			<Word>Alias</Word>
+			<Word>As</Word>
+			<Word>ByRef</Word>
+			<Word>ByVal</Word>
+			<Word>Call</Word>
+			<Word>Case</Word>
+			<Word>Catch</Word>
+			<Word>Class</Word>
+			<Word>Const</Word>
+			<Word>Continue</Word>
+			<Word>Declare</Word>
+			<Word>Default</Word>
+			<Word>Delegate</Word>
+			<Word>Dim</Word>
+			<Word>Do</Word>
+			<Word>Each</Word>
+			<Word>Else</Word>
+			<Word>ElseIf</Word>
+			<Word>End</Word>
+			<Word>EndIf</Word>
+			<Word>Enum</Word>
+			<Word>Erase</Word>
+			<Word>Error</Word>
+			<Word>Event</Word>
+			<Word>Exit</Word>
+			<Word>Finally</Word>
+			<Word>For</Word>
+			<Word>Friend</Word>
+			<Word>Function</Word>
+			<Word>Get</Word>
+			<Word>Global</Word>
+			<Word>GoSub</Word>
+			<Word>GoTo</Word>
+			<Word>Handles</Word>
+			<Word>If</Word>
+			<Word>Implements</Word>
+			<Word>Imports</Word>
+			<Word>In</Word>
+			<Word>Inherits</Word>
+			<Word>Interface</Word>
+			<Word>Let</Word>
+			<Word>Lib</Word>
+			<Word>Loop</Word>
+			<Word>Module</Word>
+			<Word>MustInherit</Word>
+			<Word>MustOverride</Word>
+			<Word>Namespace</Word>
+			<Word>Narrowing</Word>
+			<Word>New</Word>
+			<Word>Next</Word>
+			<Word>NotInheritable</Word>
+			<Word>NotOverridable</Word>
+			<Word>Of</Word>
+			<Word>On</Word>
+			<Word>Operator</Word>
+			<Word>Option</Word>
+			<Word>Optional</Word>
+			<Word>Overloads</Word>
+			<Word>Overridable</Word>
+			<Word>Overrides</Word>
+			<Word>ParamArray</Word>
+			<Word>Partial</Word>
+			<Word>Private</Word>
+			<Word>Property</Word>
+			<Word>Protected</Word>
+			<Word>Public</Word>
+			<Word>RaiseEvent</Word>
+			<Word>ReadOnly</Word>
+			<Word>ReDim</Word>
+			<Word>RemoveHandler</Word>
+			<Word>Resume</Word>
+			<Word>Return</Word>
+			<Word>Select</Word>
+			<Word>Set</Word>
+			<Word>Shadows</Word>
+			<Word>Shared</Word>
+			<Word>Static</Word>
+			<Word>Step</Word>
+			<Word>Stop</Word>
+			<Word>Structure</Word>
+			<Word>Sub</Word>
+			<Word>SyncLock</Word>
+			<Word>Then</Word>
+			<Word>Throw</Word>
+			<Word>To</Word>
+			<Word>Try</Word>
+			<Word>Using</Word>
+			<Word>Wend</Word>
+			<Word>When</Word>
+			<Word>While</Word>
+			<Word>Widening</Word>
+			<Word>With</Word>
+			<Word>WithEvents</Word>
+			<Word>WriteOnly</Word>
+		</Keywords>
+		<Keywords color="ContextKeywords">
+			<Word>Aggregate</Word>
+			<Word>Ansi</Word>
+			<Word>Ascending</Word>
+			<Word>Async</Word>
+			<Word>Auto</Word>
+			<Word>Binary</Word>
+			<Word>By</Word>
+			<Word>Compare</Word>
+			<Word>Custom</Word>
+			<Word>Descending</Word>
+			<Word>Distinct</Word>
+			<Word>Equals</Word>
+			<Word>Explicit</Word>
+			<Word>From</Word>
+			<Word>Group</Word>
+			<Word>Infer</Word>
+			<Word>Into</Word>
+			<Word>Iterator</Word>
+			<Word>Join</Word>
+			<Word>Key</Word>
+			<Word>Off</Word>
+			<Word>Preserve</Word>
+			<Word>Skip</Word>
+			<Word>Strict</Word>
+			<Word>Take</Word>
+			<Word>Text</Word>
+			<Word>Unicode</Word>
+			<Word>Until</Word>
+			<Word>Where</Word>
+			<Word>Yield</Word>
+		</Keywords>
+	</RuleSet>
+	<RuleSet name="PreprocessorSet" ignoreCase="true">
+		<Keywords fontWeight="bold">
+			<Word>Const</Word>
+			<Word>Else</Word>
+			<Word>ElseIf</Word>
+			<Word>End</Word>
+			<Word>ExternalChecksum</Word>
+			<Word>ExternalSource</Word>
+			<Word>If</Word>
+			<Word>Region</Word>
+		</Keywords>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/XML-Mode.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/XML-Mode.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/XML-Mode.xshd	(revision 11807)
@@ -0,0 +1,63 @@
+<SyntaxDefinition name="XML" extensions=".xml;.xsl;.xslt;.xsd;.manifest;.config;.addin;.xshd;.wxs;.wxi;.wxl;.proj;.csproj;.vbproj;.ilproj;.booproj;.build;.xfrm;.targets;.xaml;.xpt;.xft;.map;.wsdl;.disco;.ps1xml;.nuspec" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color foreground="Green" name="Comment" exampleText="&lt;!-- comment --&gt;" />
+	<Color foreground="Blue" name="CData" exampleText="&lt;![CDATA[data]]&gt;" />
+	<Color foreground="Blue" name="DocType" exampleText="&lt;!DOCTYPE rootElement&gt;" />
+	<Color foreground="Blue" name="XmlDeclaration" exampleText='&lt;?xml version="1.0"?&gt;' />
+	<Color foreground="DarkMagenta" name="XmlTag" exampleText='&lt;tag attribute="value" /&gt;' />
+	<Color foreground="Red" name="AttributeName" exampleText='&lt;tag attribute="value" /&gt;' />
+	<Color foreground="Blue" name="AttributeValue" exampleText='&lt;tag attribute="value" /&gt;' />
+	<Color foreground="Teal" name="Entity" exampleText="index.aspx?a=1&amp;amp;b=2" />
+	<Color foreground="Olive" name="BrokenEntity" exampleText="index.aspx?a=1&amp;b=2" />
+	
+	<RuleSet>
+		<Span color="Comment" multiline="true">
+			<Begin>&lt;!--</Begin>
+			<End>--&gt;</End>
+		</Span>
+		<Span color="CData" multiline="true">
+			<Begin>&lt;!\[CDATA\[</Begin>
+			<End>]]&gt;</End>
+		</Span>
+		<Span color="DocType" multiline="true">
+			<Begin>&lt;!DOCTYPE</Begin>
+			<End>&gt;</End>
+		</Span>
+		<Span color="XmlDeclaration" multiline="true">
+			<Begin>&lt;\?</Begin>
+			<End>\?&gt;</End>
+		</Span>
+		<Span color="XmlTag" multiline="true">
+			<Begin>&lt;</Begin>
+			<End>&gt;</End>
+			<RuleSet>
+				<!-- Treat the position before '<' as end, as that's not a valid character
+				     in attribute names and indicates the user forgot a closing quote. -->
+				<Span color="AttributeValue" multiline="true" ruleSet="EntitySet">
+					<Begin>"</Begin>
+					<End>"|(?=&lt;)</End>
+				</Span>
+				<Span color="AttributeValue" multiline="true" ruleSet="EntitySet">
+					<Begin>'</Begin>
+					<End>'|(?=&lt;)</End>
+				</Span>
+				<Rule color="AttributeName">[\d\w_\-\.]+(?=(\s*=))</Rule>
+				<Rule color="AttributeValue">=</Rule>
+			</RuleSet>
+		</Span>
+		<Import ruleSet="EntitySet"/>
+	</RuleSet>
+	
+	<RuleSet name="EntitySet">
+		<Rule color="Entity">
+			&amp;
+			[\w\d\#]+
+			;
+		</Rule>
+
+		<Rule color="BrokenEntity">
+			&amp;
+			[\w\d\#]*
+			#missing ;
+		</Rule>
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/XmlDoc.xshd
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/XmlDoc.xshd	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Resources/XmlDoc.xshd	(revision 11807)
@@ -0,0 +1,57 @@
+<?xml version="1.0"?>
+<SyntaxDefinition name="XmlDoc" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
+	<Color name="XmlString" foreground="Silver" fontWeight="bold" exampleText="${DocCommentMarker} &lt;exception cref=&quot;System.Exception&quot; /&gt;" />
+	<Color name="DocComment" foreground="Gray" exampleText="${DocCommentMarker} &lt;exception cref=&quot;System.Exception&quot; /&gt;" />
+	<Color name="XmlPunctuation" fontWeight="bold" exampleText="${DocCommentMarker} &lt;exception cref=&quot;System.Exception&quot; /&gt;" />
+	<Color name="KnownDocTags" fontWeight="bold" exampleText="${DocCommentMarker} &lt;exception cref=&quot;System.Exception&quot; /&gt;" />
+	
+	<RuleSet name="DocCommentSet">
+		<Span color="DocComment">
+			<Begin>&lt;</Begin>
+			<End>&gt;</End>
+			<RuleSet>
+				<Span color="XmlString">
+					<Begin>"</Begin>
+					<End>"</End>
+				</Span>
+				<Keywords color="XmlPunctuation">
+					<Word>/</Word>
+					<Word>|</Word>
+					<Word>=</Word>
+				</Keywords>
+				<Keywords color="KnownDocTags">
+					<Word>c</Word>
+					<Word>code</Word>
+					<Word>example</Word>
+					<Word>exception</Word>
+					<Word>list</Word>
+					<Word>para</Word>
+					<Word>param</Word>
+					<Word>paramref</Word>
+					<Word>permission</Word>
+					<Word>remarks</Word>
+					<Word>returns</Word>
+					<Word>see</Word>
+					<Word>seealso</Word>
+					<Word>summary</Word>
+					<Word>value</Word>
+					
+					<Word>type</Word>
+					<Word>name</Word>
+					<Word>cref</Word>
+					<Word>item</Word>
+					<Word>term</Word>
+					<Word>description</Word>
+					<Word>listheader</Word>
+					<Word>typeparam</Word>
+					<Word>typeparamref</Word>
+				</Keywords>
+			</RuleSet>
+		</Span>
+	</RuleSet>
+	
+	<!-- root ruleset = DocCommentSet -->
+	<RuleSet>
+		<Import ruleSet="DocCommentSet" />
+	</RuleSet>
+</SyntaxDefinition>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichText.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichText.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichText.cs	(revision 11807)
@@ -0,0 +1,272 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Windows.Documents;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Represents a immutable piece text with highlighting information.
+	/// </summary>
+	public class RichText
+	{
+		/// <summary>
+		/// The empty string without any formatting information.
+		/// </summary>
+		public static readonly RichText Empty = new RichText(string.Empty);
+		
+		readonly string text;
+		internal readonly int[] stateChangeOffsets;
+		internal readonly HighlightingColor[] stateChanges;
+		
+		/// <summary>
+		/// Creates a RichText instance with the given text and RichTextModel.
+		/// </summary>
+		/// <param name="text">
+		/// The text to use in this RichText instance.
+		/// </param>
+		/// <param name="model">
+		/// The model that contains the formatting to use for this RichText instance.
+		/// <c>model.DocumentLength</c> should correspond to <c>text.Length</c>.
+		/// This parameter may be null, in which case the RichText instance just holds plain text.
+		/// </param>
+		public RichText(string text, RichTextModel model = null)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+			if (model != null) {
+				var sections = model.GetHighlightedSections(0, text.Length).ToArray();
+				stateChangeOffsets = new int[sections.Length];
+				stateChanges = new HighlightingColor[sections.Length];
+				for (int i = 0; i < sections.Length; i++) {
+					stateChangeOffsets[i] = sections[i].Offset;
+					stateChanges[i] = sections[i].Color;
+				}
+			} else {
+				stateChangeOffsets = new int[] { 0 };
+				stateChanges = new HighlightingColor[] { HighlightingColor.Empty };
+			}
+		}
+		
+		internal RichText(string text, int[] offsets, HighlightingColor[] states)
+		{
+			this.text = text;
+			Debug.Assert(offsets[0] == 0);
+			Debug.Assert(offsets.Last() <= text.Length);
+			this.stateChangeOffsets = offsets;
+			this.stateChanges = states;
+		}
+		
+		/// <summary>
+		/// Gets the text.
+		/// </summary>
+		public string Text {
+			get { return text; }
+		}
+		
+		/// <summary>
+		/// Gets the text length.
+		/// </summary>
+		public int Length {
+			get { return text.Length; }
+		}
+		
+		int GetIndexForOffset(int offset)
+		{
+			if (offset < 0 || offset > text.Length)
+				throw new ArgumentOutOfRangeException("offset");
+			int index = Array.BinarySearch(stateChangeOffsets, offset);
+			if (index < 0) {
+				// If no color change exists directly at offset,
+				// return the index of the color segment that contains offset.
+				index = ~index - 1;
+			}
+			return index;
+		}
+		
+		int GetEnd(int index)
+		{
+			// Gets the end of the color segment no. index.
+			if (index + 1 < stateChangeOffsets.Length)
+				return stateChangeOffsets[index + 1];
+			else
+				return text.Length;
+		}
+		
+		/// <summary>
+		/// Gets the HighlightingColor for the specified offset.
+		/// </summary>
+		public HighlightingColor GetHighlightingAt(int offset)
+		{
+			return stateChanges[GetIndexForOffset(offset)];
+		}
+		
+		/// <summary>
+		/// Retrieves the highlighted sections in the specified range.
+		/// The highlighted sections will be sorted by offset, and there will not be any nested or overlapping sections.
+		/// </summary>
+		public IEnumerable<HighlightedSection> GetHighlightedSections(int offset, int length)
+		{
+			int index = GetIndexForOffset(offset);
+			int pos = offset;
+			int endOffset = offset + length;
+			while (pos < endOffset) {
+				int endPos = Math.Min(endOffset, GetEnd(index));
+				yield return new HighlightedSection {
+					Offset = pos,
+					Length = endPos - pos,
+					Color = stateChanges[index]
+				};
+				pos = endPos;
+				index++;
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new RichTextModel with the formatting from this RichText.
+		/// </summary>
+		public RichTextModel ToRichTextModel()
+		{
+			return new RichTextModel(stateChangeOffsets, stateChanges.Select(ch => ch.Clone()).ToArray());
+		}
+		
+		/// <summary>
+		/// Gets the text.
+		/// </summary>
+		public override string ToString()
+		{
+			return text;
+		}
+		
+		/// <summary>
+		/// Creates WPF Run instances that can be used for TextBlock.Inlines.
+		/// </summary>
+		public Run[] CreateRuns()
+		{
+			Run[] runs = new Run[stateChanges.Length];
+			for (int i = 0; i < runs.Length; i++) {
+				int startOffset = stateChangeOffsets[i];
+				int endOffset = i + 1 < stateChangeOffsets.Length ? stateChangeOffsets[i + 1] : text.Length;
+				Run r = new Run(text.Substring(startOffset, endOffset - startOffset));
+				HighlightingColor state = stateChanges[i];
+				ApplyColorToTextElement(r, state);
+				runs[i] = r;
+			}
+			return runs;
+		}
+
+		internal static void ApplyColorToTextElement(TextElement r, HighlightingColor state)
+		{
+			if (state.Foreground != null)
+				r.Foreground = state.Foreground.GetBrush(null);
+			if (state.Background != null)
+				r.Background = state.Background.GetBrush(null);
+			if (state.FontWeight != null)
+				r.FontWeight = state.FontWeight.Value;
+			if (state.FontStyle != null)
+				r.FontStyle = state.FontStyle.Value;
+		}
+		
+		/// <summary>
+		/// Produces HTML code for the line, with &lt;span style="..."&gt; tags.
+		/// </summary>
+		public string ToHtml(HtmlOptions options = null)
+		{
+			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
+			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
+				htmlWriter.Write(this);
+			}
+			return stringWriter.ToString();
+		}
+		
+		/// <summary>
+		/// Produces HTML code for a section of the line, with &lt;span style="..."&gt; tags.
+		/// </summary>
+		public string ToHtml(int offset, int length, HtmlOptions options = null)
+		{
+			StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
+			using (var htmlWriter = new HtmlRichTextWriter(stringWriter, options)) {
+				htmlWriter.Write(this, offset, length);
+			}
+			return stringWriter.ToString();
+		}
+		
+		/// <summary>
+		/// Creates a substring of this rich text.
+		/// </summary>
+		public RichText Substring(int offset, int length)
+		{
+			if (offset == 0 && length == this.Length)
+				return this;
+			string newText = text.Substring(offset, length);
+			RichTextModel model = ToRichTextModel();
+			OffsetChangeMap map = new OffsetChangeMap(2);
+			map.Add(new OffsetChangeMapEntry(offset + length, text.Length - offset - length, 0));
+			map.Add(new OffsetChangeMapEntry(0, offset, 0));
+			model.UpdateOffsets(map);
+			return new RichText(newText, model);
+		}
+		
+		/// <summary>
+		/// Concatenates the specified rich texts.
+		/// </summary>
+		public static RichText Concat(params RichText[] texts)
+		{
+			if (texts == null || texts.Length == 0)
+				return Empty;
+			else if (texts.Length == 1)
+				return texts[0];
+			string newText = string.Concat(texts.Select(txt => txt.text));
+			RichTextModel model = texts[0].ToRichTextModel();
+			int offset = texts[0].Length;
+			for (int i = 1; i < texts.Length; i++) {
+				model.Append(offset, texts[i].stateChangeOffsets, texts[i].stateChanges);
+				offset += texts[i].Length;
+			}
+			return new RichText(newText, model);
+		}
+		
+		/// <summary>
+		/// Concatenates the specified rich texts.
+		/// </summary>
+		public static RichText operator +(RichText a, RichText b)
+		{
+			return RichText.Concat(a, b);
+		}
+		
+		/// <summary>
+		/// Implicit conversion from string to RichText.
+		/// </summary>
+		public static implicit operator RichText(string text)
+		{
+			if (text != null)
+				return new RichText(text);
+			else
+				return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextColorizer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextColorizer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextColorizer.cs	(revision 11807)
@@ -0,0 +1,54 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A colorizer that applies the highlighting from a <see cref="RichTextModel"/> to the editor.
+	/// </summary>
+	public class RichTextColorizer : DocumentColorizingTransformer
+	{
+		readonly RichTextModel richTextModel;
+		
+		/// <summary>
+		/// Creates a new RichTextColorizer instance.
+		/// </summary>
+		public RichTextColorizer(RichTextModel richTextModel)
+		{
+			if (richTextModel == null)
+				throw new ArgumentNullException("richTextModel");
+			this.richTextModel = richTextModel;
+		}
+		
+		/// <inheritdoc/>
+		protected override void ColorizeLine(DocumentLine line)
+		{
+			var sections = richTextModel.GetHighlightedSections(line.Offset, line.Length);
+			foreach (HighlightedSection section in sections) {
+				if (HighlightingColorizer.IsEmptyColor(section.Color))
+					continue;
+				ChangeLinePart(section.Offset, section.Offset + section.Length,
+				               visualLineElement => HighlightingColorizer.ApplyColorToElement(visualLineElement, section.Color, CurrentContext));
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextModel.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextModel.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextModel.cs	(revision 11807)
@@ -0,0 +1,298 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Windows;
+using System.Windows.Documents;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// Stores rich-text formatting.
+	/// </summary>
+	public sealed class RichTextModel
+	{
+		List<int> stateChangeOffsets = new List<int>();
+		List<HighlightingColor> stateChanges = new List<HighlightingColor>();
+		
+		int GetIndexForOffset(int offset)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset");
+			int index = stateChangeOffsets.BinarySearch(offset);
+			if (index < 0) {
+				// If no color change exists directly at offset,
+				// create a new one.
+				index = ~index;
+				stateChanges.Insert(index, stateChanges[index - 1].Clone());
+				stateChangeOffsets.Insert(index, offset);
+			}
+			return index;
+		}
+		
+		int GetIndexForOffsetUseExistingSegment(int offset)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset");
+			int index = stateChangeOffsets.BinarySearch(offset);
+			if (index < 0) {
+				// If no color change exists directly at offset,
+				// return the index of the color segment that contains offset.
+				index = ~index - 1;
+			}
+			return index;
+		}
+		
+		int GetEnd(int index)
+		{
+			// Gets the end of the color segment no. index.
+			if (index + 1 < stateChangeOffsets.Count)
+				return stateChangeOffsets[index + 1];
+			else
+				return int.MaxValue;
+		}
+		
+		/// <summary>
+		/// Creates a new RichTextModel.
+		/// </summary>
+		public RichTextModel()
+		{
+			stateChangeOffsets.Add(0);
+			stateChanges.Add(new HighlightingColor());
+		}
+		
+		/// <summary>
+		/// Creates a RichTextModel from a CONTIGUOUS list of HighlightedSections.
+		/// </summary>
+		internal RichTextModel(int[] stateChangeOffsets, HighlightingColor[] stateChanges)
+		{
+			Debug.Assert(stateChangeOffsets[0] == 0);
+			this.stateChangeOffsets.AddRange(stateChangeOffsets);
+			this.stateChanges.AddRange(stateChanges);
+		}
+		
+		#region UpdateOffsets
+		/// <summary>
+		/// Updates the start and end offsets of all segments stored in this collection.
+		/// </summary>
+		/// <param name="e">TextChangeEventArgs instance describing the change to the document.</param>
+		public void UpdateOffsets(TextChangeEventArgs e)
+		{
+			if (e == null)
+				throw new ArgumentNullException("e");
+			UpdateOffsets(e.GetNewOffset);
+		}
+		
+		/// <summary>
+		/// Updates the start and end offsets of all segments stored in this collection.
+		/// </summary>
+		/// <param name="change">OffsetChangeMap instance describing the change to the document.</param>
+		public void UpdateOffsets(OffsetChangeMap change)
+		{
+			if (change == null)
+				throw new ArgumentNullException("change");
+			UpdateOffsets(change.GetNewOffset);
+		}
+		
+		/// <summary>
+		/// Updates the start and end offsets of all segments stored in this collection.
+		/// </summary>
+		/// <param name="change">OffsetChangeMapEntry instance describing the change to the document.</param>
+		public void UpdateOffsets(OffsetChangeMapEntry change)
+		{
+			UpdateOffsets(change.GetNewOffset);
+		}
+		
+		void UpdateOffsets(Func<int, AnchorMovementType, int> updateOffset)
+		{
+			int readPos = 1;
+			int writePos = 1;
+			while (readPos < stateChangeOffsets.Count) {
+				Debug.Assert(writePos <= readPos);
+				int newOffset = updateOffset(stateChangeOffsets[readPos], AnchorMovementType.Default);
+				if (newOffset == stateChangeOffsets[writePos - 1]) {
+					// offset moved to same position as previous offset
+					// -> previous segment has length 0 and gets overwritten with this segment
+					stateChanges[writePos - 1] = stateChanges[readPos];
+				} else {
+					stateChangeOffsets[writePos] = newOffset;
+					stateChanges[writePos] = stateChanges[readPos];
+					writePos++;
+				}
+				readPos++;
+			}
+			// Delete all entries that were not written to
+			stateChangeOffsets.RemoveRange(writePos, stateChangeOffsets.Count - writePos);
+			stateChanges.RemoveRange(writePos, stateChanges.Count - writePos);
+		}
+		#endregion
+		
+		/// <summary>
+		/// Appends another RichTextModel after this one.
+		/// </summary>
+		internal void Append(int offset, int[] newOffsets, HighlightingColor[] newColors)
+		{
+			Debug.Assert(newOffsets.Length == newColors.Length);
+			Debug.Assert(newOffsets[0] == 0);
+			// remove everything before offset:
+			while (stateChangeOffsets.Count > 0 && stateChangeOffsets.Last() <= offset) {
+				stateChangeOffsets.RemoveAt(stateChangeOffsets.Count - 1);
+				stateChanges.RemoveAt(stateChanges.Count - 1);
+			}
+			// Append the new segments
+			for (int i = 0; i < newOffsets.Length; i++) {
+				stateChangeOffsets.Add(offset + newOffsets[i]);
+				stateChanges.Add(newColors[i]);
+			}
+		}
+		
+		/// <summary>
+		/// Gets a copy of the HighlightingColor for the specified offset.
+		/// </summary>
+		public HighlightingColor GetHighlightingAt(int offset)
+		{
+			return stateChanges[GetIndexForOffsetUseExistingSegment(offset)].Clone();
+		}
+		
+		/// <summary>
+		/// Applies the HighlightingColor to the specified range of text.
+		/// If the color specifies <c>null</c> for some properties, existing highlighting is preserved.
+		/// </summary>
+		public void ApplyHighlighting(int offset, int length, HighlightingColor color)
+		{
+			if (color == null || color.IsEmptyForMerge) {
+				// Optimization: don't split the HighlightingState when we're not changing
+				// any property. For example, the "Punctuation" color in C# is
+				// empty by default.
+				return;
+			}
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].MergeWith(color);
+			}
+		}
+		
+		/// <summary>
+		/// Sets the HighlightingColor for the specified range of text,
+		/// completely replacing the existing highlighting in that area.
+		/// </summary>
+		public void SetHighlighting(int offset, int length, HighlightingColor color)
+		{
+			if (length <= 0)
+				return;
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			stateChanges[startIndex] = color != null ? color.Clone() : new HighlightingColor();
+			stateChanges.RemoveRange(startIndex + 1, endIndex - (startIndex + 1));
+			stateChangeOffsets.RemoveRange(startIndex + 1, endIndex - (startIndex + 1));
+		}
+		
+		/// <summary>
+		/// Sets the foreground brush on the specified text segment.
+		/// </summary>
+		public void SetForeground(int offset, int length, HighlightingBrush brush)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].Foreground = brush;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the background brush on the specified text segment.
+		/// </summary>
+		public void SetBackground(int offset, int length, HighlightingBrush brush)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].Background = brush;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the font weight on the specified text segment.
+		/// </summary>
+		public void SetFontWeight(int offset, int length, FontWeight weight)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].FontWeight = weight;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the font style on the specified text segment.
+		/// </summary>
+		public void SetFontStyle(int offset, int length, FontStyle style)
+		{
+			int startIndex = GetIndexForOffset(offset);
+			int endIndex = GetIndexForOffset(offset + length);
+			for (int i = startIndex; i < endIndex; i++) {
+				stateChanges[i].FontStyle = style;
+			}
+		}
+		
+		/// <summary>
+		/// Retrieves the highlighted sections in the specified range.
+		/// The highlighted sections will be sorted by offset, and there will not be any nested or overlapping sections.
+		/// </summary>
+		public IEnumerable<HighlightedSection> GetHighlightedSections(int offset, int length)
+		{
+			int index = GetIndexForOffsetUseExistingSegment(offset);
+			int pos = offset;
+			int endOffset = offset + length;
+			while (pos < endOffset) {
+				int endPos = Math.Min(endOffset, GetEnd(index));
+				yield return new HighlightedSection {
+					Offset = pos,
+					Length = endPos - pos,
+					Color = stateChanges[index].Clone()
+				};
+				pos = endPos;
+				index++;
+			}
+		}
+		
+		/// <summary>
+		/// Creates WPF Run instances that can be used for TextBlock.Inlines.
+		/// </summary>
+		/// <param name="textSource">The text source that holds the text for this RichTextModel.</param>
+		public Run[] CreateRuns(ITextSource textSource)
+		{
+			Run[] runs = new Run[stateChanges.Count];
+			for (int i = 0; i < runs.Length; i++) {
+				int startOffset = stateChangeOffsets[i];
+				int endOffset = i + 1 < stateChangeOffsets.Count ? stateChangeOffsets[i + 1] : textSource.TextLength;
+				Run r = new Run(textSource.GetText(startOffset, endOffset - startOffset));
+				HighlightingColor state = stateChanges[i];
+				RichText.ApplyColorToTextElement(r, state);
+				runs[i] = r;
+			}
+			return runs;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextModelWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextModelWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/RichTextModelWriter.cs	(revision 11807)
@@ -0,0 +1,128 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using System.Windows.Media;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting
+{
+	/// <summary>
+	/// A RichTextWriter that writes into a document and RichTextModel.
+	/// </summary>
+	class RichTextModelWriter : PlainRichTextWriter
+	{
+		readonly RichTextModel richTextModel;
+		readonly DocumentTextWriter documentTextWriter;
+		readonly Stack<HighlightingColor> colorStack = new Stack<HighlightingColor>();
+		HighlightingColor currentColor;
+		int currentColorBegin = -1;
+		
+		/// <summary>
+		/// Creates a new RichTextModelWriter that inserts into document, starting at insertionOffset.
+		/// </summary>
+		public RichTextModelWriter(RichTextModel richTextModel, IDocument document, int insertionOffset)
+			: base(new DocumentTextWriter(document, insertionOffset))
+		{
+			if (richTextModel == null)
+				throw new ArgumentNullException("richTextModel");
+			this.richTextModel = richTextModel;
+			this.documentTextWriter = (DocumentTextWriter)base.textWriter;
+			currentColor = richTextModel.GetHighlightingAt(Math.Max(0, insertionOffset - 1));
+		}
+		
+		/// <summary>
+		/// Gets/Sets the current insertion offset.
+		/// </summary>
+		public int InsertionOffset {
+			get { return documentTextWriter.InsertionOffset; }
+			set { documentTextWriter.InsertionOffset = value; }
+		}
+		
+		
+		/// <inheritdoc/>
+		protected override void BeginUnhandledSpan()
+		{
+			colorStack.Push(currentColor);
+		}
+		
+		void BeginColorSpan()
+		{
+			WriteIndentationIfNecessary();
+			colorStack.Push(currentColor);
+			currentColor = currentColor.Clone();
+			currentColorBegin = documentTextWriter.InsertionOffset;
+		}
+		
+		/// <inheritdoc/>
+		public override void EndSpan()
+		{
+			currentColor = colorStack.Pop();
+			currentColorBegin = documentTextWriter.InsertionOffset;
+		}
+		
+		/// <inheritdoc/>
+		protected override void AfterWrite()
+		{
+			base.AfterWrite();
+			richTextModel.SetHighlighting(currentColorBegin, documentTextWriter.InsertionOffset - currentColorBegin, currentColor);
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(Color foregroundColor)
+		{
+			BeginColorSpan();
+			currentColor.Foreground = new SimpleHighlightingBrush(foregroundColor);
+			currentColor.Freeze();
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(FontFamily fontFamily)
+		{
+			BeginUnhandledSpan(); // TODO
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(FontStyle fontStyle)
+		{
+			BeginColorSpan();
+			currentColor.FontStyle = fontStyle;
+			currentColor.Freeze();
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(FontWeight fontWeight)
+		{
+			BeginColorSpan();
+			currentColor.FontWeight = fontWeight;
+			currentColor.Freeze();
+		}
+		
+		/// <inheritdoc/>
+		public override void BeginSpan(HighlightingColor highlightingColor)
+		{
+			BeginColorSpan();
+			currentColor.MergeWith(highlightingColor);
+			currentColor.Freeze();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/HighlightingLoader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/HighlightingLoader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/HighlightingLoader.cs	(revision 11807)
@@ -0,0 +1,114 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Xml;
+using System.Xml.Schema;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// Static class with helper methods to load XSHD highlighting files.
+	/// </summary>
+	public static class HighlightingLoader
+	{
+		#region XSHD loading
+		/// <summary>
+		/// Lodas a syntax definition from the xml reader.
+		/// </summary>
+		public static XshdSyntaxDefinition LoadXshd(XmlReader reader)
+		{
+			return LoadXshd(reader, false);
+		}
+		
+		internal static XshdSyntaxDefinition LoadXshd(XmlReader reader, bool skipValidation)
+		{
+			if (reader == null)
+				throw new ArgumentNullException("reader");
+			try {
+				reader.MoveToContent();
+				if (reader.NamespaceURI == V2Loader.Namespace) {
+					return V2Loader.LoadDefinition(reader, skipValidation);
+				} else {
+					return V1Loader.LoadDefinition(reader, skipValidation);
+				}
+			} catch (XmlSchemaException ex) {
+				throw WrapException(ex, ex.LineNumber, ex.LinePosition);
+			} catch (XmlException ex) {
+				throw WrapException(ex, ex.LineNumber, ex.LinePosition);
+			}
+		}
+		
+		static Exception WrapException(Exception ex, int lineNumber, int linePosition)
+		{
+			return new HighlightingDefinitionInvalidException(FormatExceptionMessage(ex.Message, lineNumber, linePosition), ex);
+		}
+		
+		internal static string FormatExceptionMessage(string message, int lineNumber, int linePosition)
+		{
+			if (lineNumber <= 0)
+				return message;
+			else
+				return "Error at position (line " + lineNumber + ", column " + linePosition + "):\n" + message;
+		}
+		
+		internal static XmlReader GetValidatingReader(XmlReader input, bool ignoreWhitespace, XmlSchemaSet schemaSet)
+		{
+			XmlReaderSettings settings = new XmlReaderSettings();
+			settings.CloseInput = true;
+			settings.IgnoreComments = true;
+			settings.IgnoreWhitespace = ignoreWhitespace;
+			if (schemaSet != null) {
+				settings.Schemas = schemaSet;
+				settings.ValidationType = ValidationType.Schema;
+			}
+			return XmlReader.Create(input, settings);
+		}
+		
+		internal static XmlSchemaSet LoadSchemaSet(XmlReader schemaInput)
+		{
+			XmlSchemaSet schemaSet = new XmlSchemaSet();
+			schemaSet.Add(null, schemaInput);
+			schemaSet.ValidationEventHandler += delegate(object sender, ValidationEventArgs args) {
+				throw new HighlightingDefinitionInvalidException(args.Message);
+			};
+			return schemaSet;
+		}
+		#endregion
+		
+		#region Load Highlighting from XSHD
+		/// <summary>
+		/// Creates a highlighting definition from the XSHD file.
+		/// </summary>
+		public static IHighlightingDefinition Load(XshdSyntaxDefinition syntaxDefinition, IHighlightingDefinitionReferenceResolver resolver)
+		{
+			if (syntaxDefinition == null)
+				throw new ArgumentNullException("syntaxDefinition");
+			return new XmlHighlightingDefinition(syntaxDefinition, resolver);
+		}
+		
+		/// <summary>
+		/// Creates a highlighting definition from the XSHD file.
+		/// </summary>
+		public static IHighlightingDefinition Load(XmlReader reader, IHighlightingDefinitionReferenceResolver resolver)
+		{
+			return Load(LoadXshd(reader), resolver);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/IXshdVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/IXshdVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/IXshdVisitor.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A visitor over the XSHD element tree.
+	/// </summary>
+	public interface IXshdVisitor
+	{
+		/// <summary/>
+		object VisitRuleSet(XshdRuleSet ruleSet);
+		
+		/// <summary/>
+		object VisitColor(XshdColor color);
+		
+		/// <summary/>
+		object VisitKeywords(XshdKeywords keywords);
+		
+		/// <summary/>
+		object VisitSpan(XshdSpan span);
+		
+		/// <summary/>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", Justification = "A VB programmer implementing a visitor?")]
+		object VisitImport(XshdImport import);
+		
+		/// <summary/>
+		object VisitRule(XshdRule rule);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/SaveXshdVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/SaveXshdVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/SaveXshdVisitor.cs	(revision 11807)
@@ -0,0 +1,197 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Xml;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// Xshd visitor implementation that saves an .xshd file as XML.
+	/// </summary>
+	public sealed class SaveXshdVisitor : IXshdVisitor
+	{
+		/// <summary>
+		/// XML namespace for XSHD.
+		/// </summary>
+		public const string Namespace = V2Loader.Namespace;
+		
+		XmlWriter writer;
+		
+		/// <summary>
+		/// Creates a new SaveXshdVisitor instance.
+		/// </summary>
+		public SaveXshdVisitor(XmlWriter writer)
+		{
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			this.writer = writer;
+		}
+		
+		/// <summary>
+		/// Writes the specified syntax definition.
+		/// </summary>
+		public void WriteDefinition(XshdSyntaxDefinition definition)
+		{
+			if (definition == null)
+				throw new ArgumentNullException("definition");
+			writer.WriteStartElement("SyntaxDefinition", Namespace);
+			if (definition.Name != null)
+				writer.WriteAttributeString("name", definition.Name);
+			if (definition.Extensions != null)
+				writer.WriteAttributeString("extensions", string.Join(";", definition.Extensions.ToArray()));
+			
+			definition.AcceptElements(this);
+			
+			writer.WriteEndElement();
+		}
+		
+		object IXshdVisitor.VisitRuleSet(XshdRuleSet ruleSet)
+		{
+			writer.WriteStartElement("RuleSet", Namespace);
+			
+			if (ruleSet.Name != null)
+				writer.WriteAttributeString("name", ruleSet.Name);
+			WriteBoolAttribute("ignoreCase", ruleSet.IgnoreCase);
+			
+			ruleSet.AcceptElements(this);
+			
+			writer.WriteEndElement();
+			return null;
+		}
+		
+		void WriteBoolAttribute(string attributeName, bool? value)
+		{
+			if (value != null) {
+				writer.WriteAttributeString(attributeName, value.Value ? "true" : "false");
+			}
+		}
+		
+		void WriteRuleSetReference(XshdReference<XshdRuleSet> ruleSetReference)
+		{
+			if (ruleSetReference.ReferencedElement != null) {
+				if (ruleSetReference.ReferencedDefinition != null)
+					writer.WriteAttributeString("ruleSet", ruleSetReference.ReferencedDefinition + "/" + ruleSetReference.ReferencedElement);
+				else
+					writer.WriteAttributeString("ruleSet", ruleSetReference.ReferencedElement);
+			}
+		}
+		
+		void WriteColorReference(XshdReference<XshdColor> color)
+		{
+			if (color.InlineElement != null) {
+				WriteColorAttributes(color.InlineElement);
+			} else if (color.ReferencedElement != null) {
+				if (color.ReferencedDefinition != null)
+					writer.WriteAttributeString("color", color.ReferencedDefinition + "/" + color.ReferencedElement);
+				else
+					writer.WriteAttributeString("color", color.ReferencedElement);
+			}
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "The file format requires lowercase, and all possible values are English-only")]
+		void WriteColorAttributes(XshdColor color)
+		{
+			if (color.Foreground != null)
+				writer.WriteAttributeString("foreground", color.Foreground.ToString());
+			if (color.Background != null)
+				writer.WriteAttributeString("background", color.Background.ToString());
+			if (color.FontWeight != null)
+				writer.WriteAttributeString("fontWeight", V2Loader.FontWeightConverter.ConvertToInvariantString(color.FontWeight.Value).ToLowerInvariant());
+			if (color.FontStyle != null)
+				writer.WriteAttributeString("fontStyle", V2Loader.FontStyleConverter.ConvertToInvariantString(color.FontStyle.Value).ToLowerInvariant());
+		}
+		
+		object IXshdVisitor.VisitColor(XshdColor color)
+		{
+			writer.WriteStartElement("Color", Namespace);
+			if (color.Name != null)
+				writer.WriteAttributeString("name", color.Name);
+			WriteColorAttributes(color);
+			if (color.ExampleText != null)
+				writer.WriteAttributeString("exampleText", color.ExampleText);
+			writer.WriteEndElement();
+			return null;
+		}
+		
+		object IXshdVisitor.VisitKeywords(XshdKeywords keywords)
+		{
+			writer.WriteStartElement("Keywords", Namespace);
+			WriteColorReference(keywords.ColorReference);
+			foreach (string word in keywords.Words) {
+				writer.WriteElementString("Word", Namespace, word);
+			}
+			writer.WriteEndElement();
+			return null;
+		}
+		
+		object IXshdVisitor.VisitSpan(XshdSpan span)
+		{
+			writer.WriteStartElement("Span", Namespace);
+			WriteColorReference(span.SpanColorReference);
+			if (span.BeginRegexType == XshdRegexType.Default && span.BeginRegex != null)
+				writer.WriteAttributeString("begin", span.BeginRegex);
+			if (span.EndRegexType == XshdRegexType.Default && span.EndRegex != null)
+				writer.WriteAttributeString("end", span.EndRegex);
+			WriteRuleSetReference(span.RuleSetReference);
+			if (span.Multiline)
+				writer.WriteAttributeString("multiline", "true");
+			
+			if (span.BeginRegexType == XshdRegexType.IgnorePatternWhitespace)
+				WriteBeginEndElement("Begin", span.BeginRegex, span.BeginColorReference);
+			if (span.EndRegexType == XshdRegexType.IgnorePatternWhitespace)
+				WriteBeginEndElement("End", span.EndRegex, span.EndColorReference);
+			
+			if (span.RuleSetReference.InlineElement != null)
+				span.RuleSetReference.InlineElement.AcceptVisitor(this);
+			
+			writer.WriteEndElement();
+			return null;
+		}
+		
+		void WriteBeginEndElement(string elementName, string regex, XshdReference<XshdColor> colorReference)
+		{
+			if (regex != null) {
+				writer.WriteStartElement(elementName, Namespace);
+				WriteColorReference(colorReference);
+				writer.WriteString(regex);
+				writer.WriteEndElement();
+			}
+		}
+		
+		object IXshdVisitor.VisitImport(XshdImport import)
+		{
+			writer.WriteStartElement("Import", Namespace);
+			WriteRuleSetReference(import.RuleSetReference);
+			writer.WriteEndElement();
+			return null;
+		}
+		
+		object IXshdVisitor.VisitRule(XshdRule rule)
+		{
+			writer.WriteStartElement("Rule", Namespace);
+			WriteColorReference(rule.ColorReference);
+			
+			writer.WriteString(rule.Regex);
+			
+			writer.WriteEndElement();
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/V1Loader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/V1Loader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/V1Loader.cs	(revision 11807)
@@ -0,0 +1,340 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Windows;
+using System.Windows.Media;
+using System.Xml;
+using System.Xml.Schema;
+
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// Loads .xshd files, version 1.0.
+	/// </summary>
+	sealed class V1Loader
+	{
+		static XmlSchemaSet schemaSet;
+		
+		static XmlSchemaSet SchemaSet {
+			get {
+				if (schemaSet == null) {
+					schemaSet = HighlightingLoader.LoadSchemaSet(new XmlTextReader(
+						Resources.OpenStream("ModeV1.xsd")));
+				}
+				return schemaSet;
+			}
+		}
+		
+		public static XshdSyntaxDefinition LoadDefinition(XmlReader reader, bool skipValidation)
+		{
+			reader = HighlightingLoader.GetValidatingReader(reader, false, skipValidation ? null : SchemaSet);
+			XmlDocument document = new XmlDocument();
+			document.Load(reader);
+			V1Loader loader = new V1Loader();
+			return loader.ParseDefinition(document.DocumentElement);
+		}
+		
+		XshdSyntaxDefinition ParseDefinition(XmlElement syntaxDefinition)
+		{
+			XshdSyntaxDefinition def = new XshdSyntaxDefinition();
+			def.Name = syntaxDefinition.GetAttributeOrNull("name");
+			if (syntaxDefinition.HasAttribute("extensions")) {
+				def.Extensions.AddRange(syntaxDefinition.GetAttribute("extensions").Split(';', '|'));
+			}
+			
+			XshdRuleSet mainRuleSetElement = null;
+			foreach (XmlElement element in syntaxDefinition.GetElementsByTagName("RuleSet")) {
+				XshdRuleSet ruleSet = ImportRuleSet(element);
+				def.Elements.Add(ruleSet);
+				if (ruleSet.Name == null)
+					mainRuleSetElement = ruleSet;
+				
+				if (syntaxDefinition["Digits"] != null) {
+					// create digit highlighting rule
+					
+					const string optionalExponent = @"([eE][+-]?[0-9]+)?";
+					const string floatingPoint = @"\.[0-9]+";
+					ruleSet.Elements.Add(
+						new XshdRule {
+							ColorReference = GetColorReference(syntaxDefinition["Digits"]),
+							RegexType = XshdRegexType.IgnorePatternWhitespace,
+							Regex = @"\b0[xX][0-9a-fA-F]+"
+								+ @"|"
+								+ @"(\b\d+(" + floatingPoint + ")?"
+								+ @"|" + floatingPoint + ")"
+								+ optionalExponent
+						});
+				}
+			}
+			
+			if (syntaxDefinition.HasAttribute("extends") && mainRuleSetElement != null) {
+				// convert 'extends="HTML"' to '<Import ruleSet="HTML/" />' in main rule set.
+				mainRuleSetElement.Elements.Add(
+					new XshdImport { RuleSetReference = new XshdReference<XshdRuleSet>(
+						syntaxDefinition.GetAttribute("extends"), string.Empty
+					) });
+			}
+			return def;
+		}
+		
+		static XshdColor GetColorFromElement(XmlElement element)
+		{
+			if (!element.HasAttribute("bold") && !element.HasAttribute("italic") && !element.HasAttribute("color") && !element.HasAttribute("bgcolor"))
+				return null;
+			XshdColor color = new XshdColor();
+			if (element.HasAttribute("bold"))
+				color.FontWeight = XmlConvert.ToBoolean(element.GetAttribute("bold")) ? FontWeights.Bold : FontWeights.Normal;
+			if (element.HasAttribute("italic"))
+				color.FontStyle = XmlConvert.ToBoolean(element.GetAttribute("italic")) ? FontStyles.Italic : FontStyles.Normal;
+			if (element.HasAttribute("color"))
+				color.Foreground = ParseColor(element.GetAttribute("color"));
+			if (element.HasAttribute("bgcolor"))
+				color.Background = ParseColor(element.GetAttribute("bgcolor"));
+			return color;
+		}
+		
+		static XshdReference<XshdColor> GetColorReference(XmlElement element)
+		{
+			XshdColor color = GetColorFromElement(element);
+			if (color != null)
+				return new XshdReference<XshdColor>(color);
+			else
+				return new XshdReference<XshdColor>();
+		}
+		
+		static HighlightingBrush ParseColor(string c)
+		{
+			if (c.StartsWith("#", StringComparison.Ordinal)) {
+				int a = 255;
+				int offset = 0;
+				if (c.Length > 7) {
+					offset = 2;
+					a = Int32.Parse(c.Substring(1,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+				}
+				
+				int r = Int32.Parse(c.Substring(1 + offset,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+				int g = Int32.Parse(c.Substring(3 + offset,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+				int b = Int32.Parse(c.Substring(5 + offset,2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+				return new SimpleHighlightingBrush(Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b));
+			} else if (c.StartsWith("SystemColors.", StringComparison.Ordinal)) {
+				return V2Loader.GetSystemColorBrush(null, c);
+			} else {
+				return new SimpleHighlightingBrush((Color)V2Loader.ColorConverter.ConvertFromInvariantString(c));
+			}
+		}
+		
+		char ruleSetEscapeCharacter;
+		
+		XshdRuleSet ImportRuleSet(XmlElement element)
+		{
+			XshdRuleSet ruleSet = new XshdRuleSet();
+			ruleSet.Name = element.GetAttributeOrNull("name");
+			
+			if (element.HasAttribute("escapecharacter")) {
+				ruleSetEscapeCharacter = element.GetAttribute("escapecharacter")[0];
+			} else {
+				ruleSetEscapeCharacter = '\0';
+			}
+			
+			if (element.HasAttribute("reference")) {
+				ruleSet.Elements.Add(
+					new XshdImport { RuleSetReference = new XshdReference<XshdRuleSet>(
+						element.GetAttribute("reference"), string.Empty
+					) });
+			}
+			ruleSet.IgnoreCase = element.GetBoolAttribute("ignorecase");
+			
+			foreach (XmlElement el in element.GetElementsByTagName("KeyWords")) {
+				XshdKeywords keywords = new XshdKeywords();
+				keywords.ColorReference = GetColorReference(el);
+				// we have to handle old syntax highlighting definitions that contain
+				// empty keywords or empty keyword groups
+				foreach (XmlElement node in el.GetElementsByTagName("Key")) {
+					string word = node.GetAttribute("word");
+					if (!string.IsNullOrEmpty(word))
+						keywords.Words.Add(word);
+				}
+				if (keywords.Words.Count > 0) {
+					ruleSet.Elements.Add(keywords);
+				}
+			}
+			
+			foreach (XmlElement el in element.GetElementsByTagName("Span")) {
+				ruleSet.Elements.Add(ImportSpan(el));
+			}
+			
+			foreach (XmlElement el in element.GetElementsByTagName("MarkPrevious")) {
+				ruleSet.Elements.Add(ImportMarkPrevNext(el, false));
+			}
+			foreach (XmlElement el in element.GetElementsByTagName("MarkFollowing")) {
+				ruleSet.Elements.Add(ImportMarkPrevNext(el, true));
+			}
+			
+			return ruleSet;
+		}
+		
+		static XshdRule ImportMarkPrevNext(XmlElement el, bool markFollowing)
+		{
+			bool markMarker = el.GetBoolAttribute("markmarker") ?? false;
+			string what = Regex.Escape(el.InnerText);
+			const string identifier = @"[\d\w_]+";
+			const string whitespace = @"\s*";
+			
+			string regex;
+			if (markFollowing) {
+				if (markMarker) {
+					regex = what + whitespace + identifier;
+				} else {
+					regex = "(?<=(" + what + whitespace + "))" + identifier;
+				}
+			} else {
+				if (markMarker) {
+					regex = identifier + whitespace + what;
+				} else {
+					regex = identifier + "(?=(" + whitespace + what + "))";
+				}
+			}
+			return new XshdRule {
+				ColorReference = GetColorReference(el),
+				Regex = regex,
+				RegexType = XshdRegexType.IgnorePatternWhitespace
+			};
+		}
+		
+		XshdSpan ImportSpan(XmlElement element)
+		{
+			XshdSpan span = new XshdSpan();
+			if (element.HasAttribute("rule")) {
+				span.RuleSetReference = new XshdReference<XshdRuleSet>(null, element.GetAttribute("rule"));
+			}
+			char escapeCharacter = ruleSetEscapeCharacter;
+			if (element.HasAttribute("escapecharacter")) {
+				escapeCharacter = element.GetAttribute("escapecharacter")[0];
+			}
+			span.Multiline = !(element.GetBoolAttribute("stopateol") ?? false);
+			
+			span.SpanColorReference = GetColorReference(element);
+			
+			span.BeginRegexType = XshdRegexType.IgnorePatternWhitespace;
+			span.BeginRegex = ImportRegex(element["Begin"].InnerText,
+			                              element["Begin"].GetBoolAttribute("singleword") ?? false,
+			                              element["Begin"].GetBoolAttribute("startofline"));
+			span.BeginColorReference = GetColorReference(element["Begin"]);
+			
+			string endElementText = string.Empty;
+			if (element["End"] != null) {
+				span.EndRegexType = XshdRegexType.IgnorePatternWhitespace;
+				endElementText = element["End"].InnerText;
+				span.EndRegex = ImportRegex(endElementText,
+				                            element["End"].GetBoolAttribute("singleword") ?? false,
+				                            null);
+				span.EndColorReference = GetColorReference(element["End"]);
+			}
+			
+			if (escapeCharacter != '\0') {
+				XshdRuleSet ruleSet = new XshdRuleSet();
+				if (endElementText.Length == 1 && endElementText[0] == escapeCharacter) {
+					// ""-style escape
+					ruleSet.Elements.Add(new XshdSpan {
+					                     	BeginRegex = Regex.Escape(endElementText + endElementText),
+					                     	EndRegex = ""
+					                     });
+				} else {
+					// \"-style escape
+					ruleSet.Elements.Add(new XshdSpan {
+					                     	BeginRegex = Regex.Escape(escapeCharacter.ToString()),
+					                     	EndRegex = "."
+					                     });
+				}
+				if (span.RuleSetReference.ReferencedElement != null) {
+					ruleSet.Elements.Add(new XshdImport { RuleSetReference = span.RuleSetReference });
+				}
+				span.RuleSetReference = new XshdReference<XshdRuleSet>(ruleSet);
+			}
+			return span;
+		}
+		
+		static string ImportRegex(string expr, bool singleWord, bool? startOfLine)
+		{
+			StringBuilder b = new StringBuilder();
+			if (startOfLine != null) {
+				if (startOfLine.Value) {
+					b.Append(@"(?<=(^\s*))");
+				} else {
+					b.Append(@"(?<!(^\s*))");
+				}
+			} else {
+				if (singleWord)
+					b.Append(@"\b");
+			}
+			for (int i = 0; i < expr.Length; i++) {
+				char c = expr[i];
+				if (c == '@') {
+					++i;
+					if (i == expr.Length)
+						throw new HighlightingDefinitionInvalidException("Unexpected end of @ sequence, use @@ to look for a single @.");
+					switch (expr[i]) {
+						case 'C': // match whitespace or punctuation
+							b.Append(@"[^\w\d_]");
+							break;
+						case '!': // negative lookahead
+							{
+								StringBuilder whatmatch = new StringBuilder();
+								++i;
+								while (i < expr.Length && expr[i] != '@') {
+									whatmatch.Append(expr[i++]);
+								}
+								b.Append("(?!(");
+								b.Append(Regex.Escape(whatmatch.ToString()));
+								b.Append("))");
+							}
+							break;
+						case '-': // negative lookbehind
+							{
+								StringBuilder whatmatch = new StringBuilder();
+								++i;
+								while (i < expr.Length && expr[i] != '@') {
+									whatmatch.Append(expr[i++]);
+								}
+								b.Append("(?<!(");
+								b.Append(Regex.Escape(whatmatch.ToString()));
+								b.Append("))");
+							}
+							break;
+						case '@':
+							b.Append("@");
+							break;
+						default:
+							throw new HighlightingDefinitionInvalidException("Unknown character in @ sequence.");
+					}
+				} else {
+					b.Append(Regex.Escape(c.ToString()));
+				}
+			}
+			if (singleWord)
+				b.Append(@"\b");
+			return b.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/V2Loader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/V2Loader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/V2Loader.cs	(revision 11807)
@@ -0,0 +1,349 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Media;
+using System.Xml;
+using System.Xml.Schema;
+
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// Loads .xshd files, version 2.0.
+	/// Version 2.0 files are recognized by the namespace.
+	/// </summary>
+	static class V2Loader
+	{
+		public const string Namespace = "http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008";
+		
+		static XmlSchemaSet schemaSet;
+		
+		static XmlSchemaSet SchemaSet {
+			get {
+				if (schemaSet == null) {
+					schemaSet = HighlightingLoader.LoadSchemaSet(new XmlTextReader(
+						Resources.OpenStream("ModeV2.xsd")));
+				}
+				return schemaSet;
+			}
+		}
+		
+		public static XshdSyntaxDefinition LoadDefinition(XmlReader reader, bool skipValidation)
+		{
+			reader = HighlightingLoader.GetValidatingReader(reader, true, skipValidation ? null : SchemaSet);
+			reader.Read();
+			return ParseDefinition(reader);
+		}
+		
+		static XshdSyntaxDefinition ParseDefinition(XmlReader reader)
+		{
+			Debug.Assert(reader.LocalName == "SyntaxDefinition");
+			XshdSyntaxDefinition def = new XshdSyntaxDefinition();
+			def.Name = reader.GetAttribute("name");
+			string extensions = reader.GetAttribute("extensions");
+			if (extensions != null)
+				def.Extensions.AddRange(extensions.Split(';'));
+			ParseElements(def.Elements, reader);
+			Debug.Assert(reader.NodeType == XmlNodeType.EndElement);
+			Debug.Assert(reader.LocalName == "SyntaxDefinition");
+			return def;
+		}
+		
+		static void ParseElements(ICollection<XshdElement> c, XmlReader reader)
+		{
+			if (reader.IsEmptyElement)
+				return;
+			while (reader.Read() && reader.NodeType != XmlNodeType.EndElement) {
+				Debug.Assert(reader.NodeType == XmlNodeType.Element);
+				if (reader.NamespaceURI != Namespace) {
+					if (!reader.IsEmptyElement)
+						reader.Skip();
+					continue;
+				}
+				switch (reader.Name) {
+					case "RuleSet":
+						c.Add(ParseRuleSet(reader));
+						break;
+					case "Property":
+						c.Add(ParseProperty(reader));
+						break;
+					case "Color":
+						c.Add(ParseNamedColor(reader));
+						break;
+					case "Keywords":
+						c.Add(ParseKeywords(reader));
+						break;
+					case "Span":
+						c.Add(ParseSpan(reader));
+						break;
+					case "Import":
+						c.Add(ParseImport(reader));
+						break;
+					case "Rule":
+						c.Add(ParseRule(reader));
+						break;
+					default:
+						throw new NotSupportedException("Unknown element " + reader.Name);
+				}
+			}
+		}
+		
+		static XshdElement ParseProperty(XmlReader reader)
+		{
+			XshdProperty property = new XshdProperty();
+			SetPosition(property, reader);
+			property.Name = reader.GetAttribute("name");
+			property.Value = reader.GetAttribute("value");
+			return property;
+		}
+		
+		static XshdRuleSet ParseRuleSet(XmlReader reader)
+		{
+			XshdRuleSet ruleSet = new XshdRuleSet();
+			SetPosition(ruleSet, reader);
+			ruleSet.Name = reader.GetAttribute("name");
+			ruleSet.IgnoreCase = reader.GetBoolAttribute("ignoreCase");
+			
+			CheckElementName(reader, ruleSet.Name);
+			ParseElements(ruleSet.Elements, reader);
+			return ruleSet;
+		}
+		
+		static XshdRule ParseRule(XmlReader reader)
+		{
+			XshdRule rule = new XshdRule();
+			SetPosition(rule, reader);
+			rule.ColorReference = ParseColorReference(reader);
+			if (!reader.IsEmptyElement) {
+				reader.Read();
+				if (reader.NodeType == XmlNodeType.Text) {
+					rule.Regex = reader.ReadContentAsString();
+					rule.RegexType = XshdRegexType.IgnorePatternWhitespace;
+				}
+			}
+			return rule;
+		}
+		
+		static XshdKeywords ParseKeywords(XmlReader reader)
+		{
+			XshdKeywords keywords = new XshdKeywords();
+			SetPosition(keywords, reader);
+			keywords.ColorReference = ParseColorReference(reader);
+			reader.Read();
+			while (reader.NodeType != XmlNodeType.EndElement) {
+				Debug.Assert(reader.NodeType == XmlNodeType.Element);
+				keywords.Words.Add(reader.ReadElementString());
+			}
+			return keywords;
+		}
+		
+		static XshdImport ParseImport(XmlReader reader)
+		{
+			XshdImport import = new XshdImport();
+			SetPosition(import, reader);
+			import.RuleSetReference = ParseRuleSetReference(reader);
+			if (!reader.IsEmptyElement)
+				reader.Skip();
+			return import;
+		}
+		
+		static XshdSpan ParseSpan(XmlReader reader)
+		{
+			XshdSpan span = new XshdSpan();
+			SetPosition(span, reader);
+			span.BeginRegex = reader.GetAttribute("begin");
+			span.EndRegex = reader.GetAttribute("end");
+			span.Multiline = reader.GetBoolAttribute("multiline") ?? false;
+			span.SpanColorReference = ParseColorReference(reader);
+			span.RuleSetReference = ParseRuleSetReference(reader);
+			if (!reader.IsEmptyElement) {
+				reader.Read();
+				while (reader.NodeType != XmlNodeType.EndElement) {
+					Debug.Assert(reader.NodeType == XmlNodeType.Element);
+					switch (reader.Name) {
+						case "Begin":
+							if (span.BeginRegex != null)
+								throw Error(reader, "Duplicate Begin regex");
+							span.BeginColorReference = ParseColorReference(reader);
+							span.BeginRegex = reader.ReadElementString();
+							span.BeginRegexType = XshdRegexType.IgnorePatternWhitespace;
+							break;
+						case "End":
+							if (span.EndRegex != null)
+								throw Error(reader, "Duplicate End regex");
+							span.EndColorReference = ParseColorReference(reader);
+							span.EndRegex = reader.ReadElementString();
+							span.EndRegexType = XshdRegexType.IgnorePatternWhitespace;
+							break;
+						case "RuleSet":
+							if (span.RuleSetReference.ReferencedElement != null)
+								throw Error(reader, "Cannot specify both inline RuleSet and RuleSet reference");
+							span.RuleSetReference = new XshdReference<XshdRuleSet>(ParseRuleSet(reader));
+							reader.Read();
+							break;
+						default:
+							throw new NotSupportedException("Unknown element " + reader.Name);
+					}
+				}
+			}
+			return span;
+		}
+		
+		static Exception Error(XmlReader reader, string message)
+		{
+			return Error(reader as IXmlLineInfo, message);
+		}
+		
+		static Exception Error(IXmlLineInfo lineInfo, string message)
+		{
+			if (lineInfo != null)
+				return new HighlightingDefinitionInvalidException(HighlightingLoader.FormatExceptionMessage(message, lineInfo.LineNumber, lineInfo.LinePosition));
+			else
+				return new HighlightingDefinitionInvalidException(message);
+		}
+		
+		/// <summary>
+		/// Sets the element's position to the XmlReader's position.
+		/// </summary>
+		static void SetPosition(XshdElement element, XmlReader reader)
+		{
+			IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+			if (lineInfo != null) {
+				element.LineNumber = lineInfo.LineNumber;
+				element.ColumnNumber = lineInfo.LinePosition;
+			}
+		}
+		
+		static XshdReference<XshdRuleSet> ParseRuleSetReference(XmlReader reader)
+		{
+			string ruleSet = reader.GetAttribute("ruleSet");
+			if (ruleSet != null) {
+				// '/' is valid in highlighting definition names, so we need the last occurence
+				int pos = ruleSet.LastIndexOf('/');
+				if (pos >= 0) {
+					return new XshdReference<XshdRuleSet>(ruleSet.Substring(0, pos), ruleSet.Substring(pos + 1));
+				} else {
+					return new XshdReference<XshdRuleSet>(null, ruleSet);
+				}
+			} else {
+				return new XshdReference<XshdRuleSet>();
+			}
+		}
+		
+		static void CheckElementName(XmlReader reader, string name)
+		{
+			if (name != null) {
+				if (name.Length == 0)
+					throw Error(reader, "The empty string is not a valid name.");
+				if (name.IndexOf('/') >= 0)
+					throw Error(reader, "Element names must not contain a slash.");
+			}
+		}
+		
+		#region ParseColor
+		static XshdColor ParseNamedColor(XmlReader reader)
+		{
+			XshdColor color = ParseColorAttributes(reader);
+			// check removed: invisible named colors may be useful now that apps can read highlighting data
+			//if (color.Foreground == null && color.FontWeight == null && color.FontStyle == null)
+			//	throw Error(reader, "A named color must have at least one element.");
+			color.Name = reader.GetAttribute("name");
+			CheckElementName(reader, color.Name);
+			color.ExampleText = reader.GetAttribute("exampleText");
+			return color;
+		}
+		
+		static XshdReference<XshdColor> ParseColorReference(XmlReader reader)
+		{
+			string color = reader.GetAttribute("color");
+			if (color != null) {
+				int pos = color.LastIndexOf('/');
+				if (pos >= 0) {
+					return new XshdReference<XshdColor>(color.Substring(0, pos), color.Substring(pos + 1));
+				} else {
+					return new XshdReference<XshdColor>(null, color);
+				}
+			} else {
+				return new XshdReference<XshdColor>(ParseColorAttributes(reader));
+			}
+		}
+		
+		static XshdColor ParseColorAttributes(XmlReader reader)
+		{
+			XshdColor color = new XshdColor();
+			SetPosition(color, reader);
+			IXmlLineInfo position = reader as IXmlLineInfo;
+			color.Foreground = ParseColor(position, reader.GetAttribute("foreground"));
+			color.Background = ParseColor(position, reader.GetAttribute("background"));
+			color.FontWeight = ParseFontWeight(reader.GetAttribute("fontWeight"));
+			color.FontStyle = ParseFontStyle(reader.GetAttribute("fontStyle"));
+			return color;
+		}
+		
+		internal readonly static ColorConverter ColorConverter = new ColorConverter();
+		internal readonly static FontWeightConverter FontWeightConverter = new FontWeightConverter();
+		internal readonly static FontStyleConverter FontStyleConverter = new FontStyleConverter();
+		
+		static HighlightingBrush ParseColor(IXmlLineInfo lineInfo, string color)
+		{
+			if (string.IsNullOrEmpty(color))
+				return null;
+			if (color.StartsWith("SystemColors.", StringComparison.Ordinal))
+				return GetSystemColorBrush(lineInfo, color);
+			else
+				return FixedColorHighlightingBrush((Color?)ColorConverter.ConvertFromInvariantString(color));
+		}
+		
+		internal static SystemColorHighlightingBrush GetSystemColorBrush(IXmlLineInfo lineInfo, string name)
+		{
+			Debug.Assert(name.StartsWith("SystemColors.", StringComparison.Ordinal));
+			string shortName = name.Substring(13);
+			var property = typeof(SystemColors).GetProperty(shortName + "Brush");
+			if (property == null)
+				throw Error(lineInfo, "Cannot find '" + name + "'.");
+			return new SystemColorHighlightingBrush(property);
+		}
+		
+		static HighlightingBrush FixedColorHighlightingBrush(Color? color)
+		{
+			if (color == null)
+				return null;
+			return new SimpleHighlightingBrush(color.Value);
+		}
+		
+		static FontWeight? ParseFontWeight(string fontWeight)
+		{
+			if (string.IsNullOrEmpty(fontWeight))
+				return null;
+			return (FontWeight?)FontWeightConverter.ConvertFromInvariantString(fontWeight);
+		}
+		
+		static FontStyle? ParseFontStyle(string fontStyle)
+		{
+			if (string.IsNullOrEmpty(fontStyle))
+				return null;
+			return (FontStyle?)FontStyleConverter.ConvertFromInvariantString(fontStyle);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XmlHighlightingDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XmlHighlightingDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XmlHighlightingDefinition.cs	(revision 11807)
@@ -0,0 +1,421 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Text.RegularExpressions;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	[Serializable]
+	sealed class XmlHighlightingDefinition : IHighlightingDefinition
+	{
+		public string Name { get; private set; }
+		
+		public XmlHighlightingDefinition(XshdSyntaxDefinition xshd, IHighlightingDefinitionReferenceResolver resolver)
+		{
+			this.Name = xshd.Name;
+			// Create HighlightingRuleSet instances
+			var rnev = new RegisterNamedElementsVisitor(this);
+			xshd.AcceptElements(rnev);
+			// Assign MainRuleSet so that references can be resolved
+			foreach (XshdElement element in xshd.Elements) {
+				XshdRuleSet xrs = element as XshdRuleSet;
+				if (xrs != null && xrs.Name == null) {
+					if (MainRuleSet != null)
+						throw Error(element, "Duplicate main RuleSet. There must be only one nameless RuleSet!");
+					else
+						MainRuleSet = rnev.ruleSets[xrs];
+				}
+			}
+			if (MainRuleSet == null)
+				throw new HighlightingDefinitionInvalidException("Could not find main RuleSet.");
+			// Translate elements within the rulesets (resolving references and processing imports)
+			xshd.AcceptElements(new TranslateElementVisitor(this, rnev.ruleSets, resolver));
+			
+			foreach (var p in xshd.Elements.OfType<XshdProperty>())
+				propDict.Add(p.Name, p.Value);
+		}
+		
+		#region RegisterNamedElements
+		sealed class RegisterNamedElementsVisitor : IXshdVisitor
+		{
+			XmlHighlightingDefinition def;
+			internal readonly Dictionary<XshdRuleSet, HighlightingRuleSet> ruleSets
+				= new Dictionary<XshdRuleSet, HighlightingRuleSet>();
+			
+			public RegisterNamedElementsVisitor(XmlHighlightingDefinition def)
+			{
+				this.def = def;
+			}
+			
+			public object VisitRuleSet(XshdRuleSet ruleSet)
+			{
+				HighlightingRuleSet hrs = new HighlightingRuleSet();
+				ruleSets.Add(ruleSet, hrs);
+				if (ruleSet.Name != null) {
+					if (ruleSet.Name.Length == 0)
+						throw Error(ruleSet, "Name must not be the empty string");
+					if (def.ruleSetDict.ContainsKey(ruleSet.Name))
+						throw Error(ruleSet, "Duplicate rule set name '" + ruleSet.Name + "'.");
+					
+					def.ruleSetDict.Add(ruleSet.Name, hrs);
+				}
+				ruleSet.AcceptElements(this);
+				return null;
+			}
+			
+			public object VisitColor(XshdColor color)
+			{
+				if (color.Name != null) {
+					if (color.Name.Length == 0)
+						throw Error(color, "Name must not be the empty string");
+					if (def.colorDict.ContainsKey(color.Name))
+						throw Error(color, "Duplicate color name '" + color.Name + "'.");
+					
+					def.colorDict.Add(color.Name, new HighlightingColor());
+				}
+				return null;
+			}
+			
+			public object VisitKeywords(XshdKeywords keywords)
+			{
+				return keywords.ColorReference.AcceptVisitor(this);
+			}
+			
+			public object VisitSpan(XshdSpan span)
+			{
+				span.BeginColorReference.AcceptVisitor(this);
+				span.SpanColorReference.AcceptVisitor(this);
+				span.EndColorReference.AcceptVisitor(this);
+				return span.RuleSetReference.AcceptVisitor(this);
+			}
+			
+			public object VisitImport(XshdImport import)
+			{
+				return import.RuleSetReference.AcceptVisitor(this);
+			}
+			
+			public object VisitRule(XshdRule rule)
+			{
+				return rule.ColorReference.AcceptVisitor(this);
+			}
+		}
+		#endregion
+		
+		#region TranslateElements
+		sealed class TranslateElementVisitor : IXshdVisitor
+		{
+			readonly XmlHighlightingDefinition def;
+			readonly Dictionary<XshdRuleSet, HighlightingRuleSet> ruleSetDict;
+			readonly Dictionary<HighlightingRuleSet, XshdRuleSet> reverseRuleSetDict;
+			readonly IHighlightingDefinitionReferenceResolver resolver;
+			HashSet<XshdRuleSet> processingStartedRuleSets = new HashSet<XshdRuleSet>();
+			HashSet<XshdRuleSet> processedRuleSets = new HashSet<XshdRuleSet>();
+			bool ignoreCase;
+			
+			public TranslateElementVisitor(XmlHighlightingDefinition def, Dictionary<XshdRuleSet, HighlightingRuleSet> ruleSetDict, IHighlightingDefinitionReferenceResolver resolver)
+			{
+				Debug.Assert(def != null);
+				Debug.Assert(ruleSetDict != null);
+				this.def = def;
+				this.ruleSetDict = ruleSetDict;
+				this.resolver = resolver;
+				reverseRuleSetDict = new Dictionary<HighlightingRuleSet, XshdRuleSet>();
+				foreach (var pair in ruleSetDict) {
+					reverseRuleSetDict.Add(pair.Value, pair.Key);
+				}
+			}
+			
+			public object VisitRuleSet(XshdRuleSet ruleSet)
+			{
+				HighlightingRuleSet rs = ruleSetDict[ruleSet];
+				if (processedRuleSets.Contains(ruleSet))
+					return rs;
+				if (!processingStartedRuleSets.Add(ruleSet))
+					throw Error(ruleSet, "RuleSet cannot be processed because it contains cyclic <Import>");
+				
+				bool oldIgnoreCase = ignoreCase;
+				if (ruleSet.IgnoreCase != null)
+					ignoreCase = ruleSet.IgnoreCase.Value;
+				
+				rs.Name = ruleSet.Name;
+				
+				foreach (XshdElement element in ruleSet.Elements) {
+					object o = element.AcceptVisitor(this);
+					HighlightingRuleSet elementRuleSet = o as HighlightingRuleSet;
+					if (elementRuleSet != null) {
+						Merge(rs, elementRuleSet);
+					} else {
+						HighlightingSpan span = o as HighlightingSpan;
+						if (span != null) {
+							rs.Spans.Add(span);
+						} else {
+							HighlightingRule elementRule = o as HighlightingRule;
+							if (elementRule != null) {
+								rs.Rules.Add(elementRule);
+							}
+						}
+					}
+				}
+				
+				ignoreCase = oldIgnoreCase;
+				processedRuleSets.Add(ruleSet);
+				
+				return rs;
+			}
+			
+			static void Merge(HighlightingRuleSet target, HighlightingRuleSet source)
+			{
+				target.Rules.AddRange(source.Rules);
+				target.Spans.AddRange(source.Spans);
+			}
+			
+			public object VisitColor(XshdColor color)
+			{
+				HighlightingColor c;
+				if (color.Name != null)
+					c = def.colorDict[color.Name];
+				else if (color.Foreground == null && color.FontStyle == null && color.FontWeight == null)
+					return null;
+				else
+					c = new HighlightingColor();
+				
+				c.Name = color.Name;
+				c.Foreground = color.Foreground;
+				c.Background = color.Background;
+				c.FontStyle = color.FontStyle;
+				c.FontWeight = color.FontWeight;
+				return c;
+			}
+			
+			public object VisitKeywords(XshdKeywords keywords)
+			{
+				if (keywords.Words.Count == 0)
+					return Error(keywords, "Keyword group must not be empty.");
+				foreach (string keyword in keywords.Words) {
+					if (string.IsNullOrEmpty(keyword))
+						throw Error(keywords, "Cannot use empty string as keyword");
+				}
+				StringBuilder keyWordRegex = new StringBuilder();
+				// We can use "\b" only where the keyword starts/ends with a letter or digit, otherwise we don't
+				// highlight correctly. (example: ILAsm-Mode.xshd with ".maxstack" keyword)
+				if (keywords.Words.All(IsSimpleWord)) {
+					keyWordRegex.Append(@"\b(?>");
+					// (?> = atomic group
+					// atomic groups increase matching performance, but we
+					// must ensure that the keywords are sorted correctly.
+					// "\b(?>in|int)\b" does not match "int" because the atomic group captures "in".
+					// To solve this, we are sorting the keywords by descending length.
+					int i = 0;
+					foreach (string keyword in keywords.Words.OrderByDescending(w=>w.Length)) {
+						if (i++ > 0)
+							keyWordRegex.Append('|');
+						keyWordRegex.Append(Regex.Escape(keyword));
+					}
+					keyWordRegex.Append(@")\b");
+				} else {
+					keyWordRegex.Append('(');
+					int i = 0;
+					foreach (string keyword in keywords.Words) {
+						if (i++ > 0)
+							keyWordRegex.Append('|');
+						if (char.IsLetterOrDigit(keyword[0]))
+							keyWordRegex.Append(@"\b");
+						keyWordRegex.Append(Regex.Escape(keyword));
+						if (char.IsLetterOrDigit(keyword[keyword.Length - 1]))
+							keyWordRegex.Append(@"\b");
+					}
+					keyWordRegex.Append(')');
+				}
+				return new HighlightingRule {
+					Color = GetColor(keywords, keywords.ColorReference),
+					Regex = CreateRegex(keywords, keyWordRegex.ToString(), XshdRegexType.Default)
+				};
+			}
+			
+			static bool IsSimpleWord(string word)
+			{
+				return char.IsLetterOrDigit(word[0]) && char.IsLetterOrDigit(word, word.Length - 1);
+			}
+			
+			Regex CreateRegex(XshdElement position, string regex, XshdRegexType regexType)
+			{
+				if (regex == null)
+					throw Error(position, "Regex missing");
+				RegexOptions options = RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture;
+				if (regexType == XshdRegexType.IgnorePatternWhitespace)
+					options |= RegexOptions.IgnorePatternWhitespace;
+				if (ignoreCase)
+					options |= RegexOptions.IgnoreCase;
+				try {
+					return new Regex(regex, options);
+				} catch (ArgumentException ex) {
+					throw Error(position, ex.Message);
+				}
+			}
+			
+			HighlightingColor GetColor(XshdElement position, XshdReference<XshdColor> colorReference)
+			{
+				if (colorReference.InlineElement != null) {
+					return (HighlightingColor)colorReference.InlineElement.AcceptVisitor(this);
+				} else if (colorReference.ReferencedElement != null) {
+					IHighlightingDefinition definition = GetDefinition(position, colorReference.ReferencedDefinition);
+					HighlightingColor color = definition.GetNamedColor(colorReference.ReferencedElement);
+					if (color == null)
+						throw Error(position, "Could not find color named '" + colorReference.ReferencedElement + "'.");
+					return color;
+				} else {
+					return null;
+				}
+			}
+			
+			IHighlightingDefinition GetDefinition(XshdElement position, string definitionName)
+			{
+				if (definitionName == null)
+					return def;
+				if (resolver == null)
+					throw Error(position, "Resolving references to other syntax definitions is not possible because the IHighlightingDefinitionReferenceResolver is null.");
+				IHighlightingDefinition d = resolver.GetDefinition(definitionName);
+				if (d == null)
+					throw Error(position, "Could not find definition with name '" + definitionName + "'.");
+				return d;
+			}
+			
+			HighlightingRuleSet GetRuleSet(XshdElement position, XshdReference<XshdRuleSet> ruleSetReference)
+			{
+				if (ruleSetReference.InlineElement != null) {
+					return (HighlightingRuleSet)ruleSetReference.InlineElement.AcceptVisitor(this);
+				} else if (ruleSetReference.ReferencedElement != null) {
+					IHighlightingDefinition definition = GetDefinition(position, ruleSetReference.ReferencedDefinition);
+					HighlightingRuleSet ruleSet = definition.GetNamedRuleSet(ruleSetReference.ReferencedElement);
+					if (ruleSet == null)
+						throw Error(position, "Could not find rule set named '" + ruleSetReference.ReferencedElement + "'.");
+					return ruleSet;
+				} else {
+					return null;
+				}
+			}
+			
+			public object VisitSpan(XshdSpan span)
+			{
+				string endRegex = span.EndRegex;
+				if (string.IsNullOrEmpty(span.BeginRegex) && string.IsNullOrEmpty(span.EndRegex))
+					throw Error(span, "Span has no start/end regex.");
+				if (!span.Multiline) {
+					if (endRegex == null)
+						endRegex = "$";
+					else if (span.EndRegexType == XshdRegexType.IgnorePatternWhitespace)
+						endRegex = "($|" + endRegex + "\n)";
+					else
+						endRegex = "($|" + endRegex + ")";
+				}
+				HighlightingColor wholeSpanColor = GetColor(span, span.SpanColorReference);
+				return new HighlightingSpan {
+					StartExpression = CreateRegex(span, span.BeginRegex, span.BeginRegexType),
+					EndExpression = CreateRegex(span, endRegex, span.EndRegexType),
+					RuleSet = GetRuleSet(span, span.RuleSetReference),
+					StartColor = GetColor(span, span.BeginColorReference),
+					SpanColor = wholeSpanColor,
+					EndColor = GetColor(span, span.EndColorReference),
+					SpanColorIncludesStart = true,
+					SpanColorIncludesEnd = true
+				};
+			}
+			
+			public object VisitImport(XshdImport import)
+			{
+				HighlightingRuleSet hrs = GetRuleSet(import, import.RuleSetReference);
+				XshdRuleSet inputRuleSet;
+				if (reverseRuleSetDict.TryGetValue(hrs, out inputRuleSet)) {
+					// ensure the ruleset is processed before importing its members
+					if (VisitRuleSet(inputRuleSet) != hrs)
+						Debug.Fail("this shouldn't happen");
+				}
+				return hrs;
+			}
+			
+			public object VisitRule(XshdRule rule)
+			{
+				return new HighlightingRule {
+					Color = GetColor(rule, rule.ColorReference),
+					Regex = CreateRegex(rule, rule.Regex, rule.RegexType)
+				};
+			}
+		}
+		#endregion
+		
+		static Exception Error(XshdElement element, string message)
+		{
+			if (element.LineNumber > 0)
+				return new HighlightingDefinitionInvalidException(
+					"Error at line " + element.LineNumber + ":\n" + message);
+			else
+				return new HighlightingDefinitionInvalidException(message);
+		}
+		
+		Dictionary<string, HighlightingRuleSet> ruleSetDict = new Dictionary<string, HighlightingRuleSet>();
+		Dictionary<string, HighlightingColor> colorDict = new Dictionary<string, HighlightingColor>();
+		[OptionalField]
+		Dictionary<string, string> propDict = new Dictionary<string, string>();
+		
+		public HighlightingRuleSet MainRuleSet { get; private set; }
+		
+		public HighlightingRuleSet GetNamedRuleSet(string name)
+		{
+			if (string.IsNullOrEmpty(name))
+				return MainRuleSet;
+			HighlightingRuleSet r;
+			if (ruleSetDict.TryGetValue(name, out r))
+				return r;
+			else
+				return null;
+		}
+		
+		public HighlightingColor GetNamedColor(string name)
+		{
+			HighlightingColor c;
+			if (colorDict.TryGetValue(name, out c))
+				return c;
+			else
+				return null;
+		}
+		
+		public IEnumerable<HighlightingColor> NamedHighlightingColors {
+			get {
+				return colorDict.Values;
+			}
+		}
+		
+		public override string ToString()
+		{
+			return this.Name;
+		}
+		
+		public IDictionary<string, string> Properties {
+			get {
+				return propDict;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdColor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdColor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdColor.cs	(revision 11807)
@@ -0,0 +1,116 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.Serialization;
+using System.Security.Permissions;
+using System.Windows;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A color in an Xshd file.
+	/// </summary>
+	[Serializable]
+	public class XshdColor : XshdElement, ISerializable
+	{
+		/// <summary>
+		/// Gets/sets the name.
+		/// </summary>
+		public string Name { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the foreground brush.
+		/// </summary>
+		public HighlightingBrush Foreground { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the background brush.
+		/// </summary>
+		public HighlightingBrush Background { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the font weight.
+		/// </summary>
+		public FontWeight? FontWeight { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the font style.
+		/// </summary>
+		public FontStyle? FontStyle { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the example text that demonstrates where the color is used.
+		/// </summary>
+		public string ExampleText { get; set; }
+		
+		/// <summary>
+		/// Creates a new XshdColor instance.
+		/// </summary>
+		public XshdColor()
+		{
+		}
+		
+		/// <summary>
+		/// Deserializes an XshdColor.
+		/// </summary>
+		protected XshdColor(SerializationInfo info, StreamingContext context)
+		{
+			if (info == null)
+				throw new ArgumentNullException("info");
+			this.Name = info.GetString("Name");
+			this.Foreground = (HighlightingBrush)info.GetValue("Foreground", typeof(HighlightingBrush));
+			this.Background = (HighlightingBrush)info.GetValue("Background", typeof(HighlightingBrush));
+			if (info.GetBoolean("HasWeight"))
+				this.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(info.GetInt32("Weight"));
+			if (info.GetBoolean("HasStyle"))
+				this.FontStyle = (FontStyle?)new FontStyleConverter().ConvertFromInvariantString(info.GetString("Style"));
+			this.ExampleText = info.GetString("ExampleText");
+		}
+		
+		/// <summary>
+		/// Serializes this XshdColor instance.
+		/// </summary>
+		#if DOTNET4
+		[System.Security.SecurityCritical]
+		#else
+		[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
+		#endif
+		public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+		{
+			if (info == null)
+				throw new ArgumentNullException("info");
+			info.AddValue("Name", this.Name);
+			info.AddValue("Foreground", this.Foreground);
+			info.AddValue("Background", this.Background);
+			info.AddValue("HasWeight", this.FontWeight.HasValue);
+			if (this.FontWeight.HasValue)
+				info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
+			info.AddValue("HasStyle", this.FontStyle.HasValue);
+			if (this.FontStyle.HasValue)
+				info.AddValue("Style", this.FontStyle.Value.ToString());
+			info.AddValue("ExampleText", this.ExampleText);
+		}
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return visitor.VisitColor(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdElement.cs	(revision 11807)
@@ -0,0 +1,44 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// An element in a XSHD rule set.
+	/// </summary>
+	[Serializable]
+	public abstract class XshdElement
+	{
+		/// <summary>
+		/// Gets the line number in the .xshd file.
+		/// </summary>
+		public int LineNumber { get; set; }
+		
+		/// <summary>
+		/// Gets the column number in the .xshd file.
+		/// </summary>
+		public int ColumnNumber { get; set; }
+		
+		/// <summary>
+		/// Applies the visitor to this element.
+		/// </summary>
+		public abstract object AcceptVisitor(IXshdVisitor visitor);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdImport.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdImport.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdImport.cs	(revision 11807)
@@ -0,0 +1,40 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// &lt;Import&gt; element.
+	/// </summary>
+	[Serializable]
+	public class XshdImport : XshdElement
+	{
+		/// <summary>
+		/// Gets/sets the referenced rule set.
+		/// </summary>
+		public XshdReference<XshdRuleSet> RuleSetReference { get; set; }
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return visitor.VisitImport(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdKeywords.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdKeywords.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdKeywords.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A list of keywords.
+	/// </summary>
+	[Serializable]
+	public class XshdKeywords : XshdElement
+	{
+		/// <summary>
+		/// The color.
+		/// </summary>
+		public XshdReference<XshdColor> ColorReference { get; set; }
+		
+		readonly NullSafeCollection<string> words = new NullSafeCollection<string>();
+		
+		/// <summary>
+		/// Gets the list of key words.
+		/// </summary>
+		public IList<string> Words {
+			get { return words; }
+		}
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return visitor.VisitKeywords(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdProperty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdProperty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdProperty.cs	(revision 11807)
@@ -0,0 +1,53 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A property in an Xshd file.
+	/// </summary>
+	[Serializable]
+	public class XshdProperty : XshdElement
+	{
+		/// <summary>
+		/// Gets/sets the name.
+		/// </summary>
+		public string Name { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the value.
+		/// </summary>
+		public string Value { get; set; }
+		
+		/// <summary>
+		/// Creates a new XshdColor instance.
+		/// </summary>
+		public XshdProperty()
+		{
+		}
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return null;
+//			return visitor.VisitProperty(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdReference.cs	(revision 11807)
@@ -0,0 +1,142 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A reference to an xshd color, or an inline xshd color.
+	/// </summary>
+	[Serializable]
+	public struct XshdReference<T> : IEquatable<XshdReference<T>> where T : XshdElement
+	{
+		string referencedDefinition;
+		string referencedElement;
+		T inlineElement;
+		
+		/// <summary>
+		/// Gets the reference.
+		/// </summary>
+		public string ReferencedDefinition {
+			get { return referencedDefinition; }
+		}
+		
+		/// <summary>
+		/// Gets the reference.
+		/// </summary>
+		public string ReferencedElement {
+			get { return referencedElement; }
+		}
+		
+		/// <summary>
+		/// Gets the inline element.
+		/// </summary>
+		public T InlineElement {
+			get { return inlineElement; }
+		}
+		
+		/// <summary>
+		/// Creates a new XshdReference instance.
+		/// </summary>
+		public XshdReference(string referencedDefinition, string referencedElement)
+		{
+			if (referencedElement == null)
+				throw new ArgumentNullException("referencedElement");
+			this.referencedDefinition = referencedDefinition;
+			this.referencedElement = referencedElement;
+			this.inlineElement = null;
+		}
+		
+		/// <summary>
+		/// Creates a new XshdReference instance.
+		/// </summary>
+		public XshdReference(T inlineElement)
+		{
+			if (inlineElement == null)
+				throw new ArgumentNullException("inlineElement");
+			this.referencedDefinition = null;
+			this.referencedElement = null;
+			this.inlineElement = inlineElement;
+		}
+		
+		/// <summary>
+		/// Applies the visitor to the inline element, if there is any.
+		/// </summary>
+		public object AcceptVisitor(IXshdVisitor visitor)
+		{
+			if (inlineElement != null)
+				return inlineElement.AcceptVisitor(visitor);
+			else
+				return null;
+		}
+		
+		#region Equals and GetHashCode implementation
+		// The code in this region is useful if you want to use this structure in collections.
+		// If you don't need it, you can just remove the region and the ": IEquatable<XshdColorReference>" declaration.
+		
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			if (obj is XshdReference<T>)
+				return Equals((XshdReference<T>)obj); // use Equals method below
+			else
+				return false;
+		}
+		
+		/// <summary>
+		/// Equality operator.
+		/// </summary>
+		public bool Equals(XshdReference<T> other)
+		{
+			// add comparisions for all members here
+			return this.referencedDefinition == other.referencedDefinition
+				&& this.referencedElement == other.referencedElement
+				&& this.inlineElement == other.inlineElement;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			// combine the hash codes of all members here (e.g. with XOR operator ^)
+			return GetHashCode(referencedDefinition) ^ GetHashCode(referencedElement) ^ GetHashCode(inlineElement);
+		}
+		
+		static int GetHashCode(object o)
+		{
+			return o != null ? o.GetHashCode() : 0;
+		}
+		
+		/// <summary>
+		/// Equality operator.
+		/// </summary>
+		public static bool operator ==(XshdReference<T> left, XshdReference<T> right)
+		{
+			return left.Equals(right);
+		}
+		
+		/// <summary>
+		/// Inequality operator.
+		/// </summary>
+		public static bool operator !=(XshdReference<T> left, XshdReference<T> right)
+		{
+			return !left.Equals(right);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdRule.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdRule.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdRule.cs	(revision 11807)
@@ -0,0 +1,50 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// &lt;Rule&gt; element.
+	/// </summary>
+	[Serializable]
+	public class XshdRule : XshdElement
+	{
+		/// <summary>
+		/// Gets/sets the rule regex.
+		/// </summary>
+		public string Regex { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the rule regex type.
+		/// </summary>
+		public XshdRegexType RegexType { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the color reference.
+		/// </summary>
+		public XshdReference<XshdColor> ColorReference { get; set; }
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return visitor.VisitRule(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdRuleSet.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdRuleSet.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdRuleSet.cs	(revision 11807)
@@ -0,0 +1,66 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A rule set in a XSHD file.
+	/// </summary>
+	[Serializable]
+	public class XshdRuleSet : XshdElement
+	{
+		/// <summary>
+		/// Gets/Sets the name of the rule set.
+		/// </summary>
+		public string Name { get; set; }
+		
+		/// <summary>
+		/// Gets/sets whether the case is ignored in expressions inside this rule set.
+		/// </summary>
+		public bool? IgnoreCase { get; set; }
+		
+		readonly NullSafeCollection<XshdElement> elements = new NullSafeCollection<XshdElement>();
+		
+		/// <summary>
+		/// Gets the collection of elements.
+		/// </summary>
+		public IList<XshdElement> Elements {
+			get { return elements; }
+		}
+		
+		/// <summary>
+		/// Applies the visitor to all elements.
+		/// </summary>
+		public void AcceptElements(IXshdVisitor visitor)
+		{
+			foreach (XshdElement element in Elements) {
+				element.AcceptVisitor(visitor);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return visitor.VisitRuleSet(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdSpan.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdSpan.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdSpan.cs	(revision 11807)
@@ -0,0 +1,97 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// Specifies the type of the regex.
+	/// </summary>
+	public enum XshdRegexType
+	{
+		/// <summary>
+		/// Normal regex. Used when the regex was specified as attribute.
+		/// </summary>
+		Default,
+		/// <summary>
+		/// Ignore pattern whitespace / allow regex comments. Used when the regex was specified as text element.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly",
+		                                                 Justification = "Using the same case as the RegexOption")]
+		IgnorePatternWhitespace
+	}
+	
+	/// <summary>
+	/// &lt;Span&gt; element.
+	/// </summary>
+	[Serializable]
+	public class XshdSpan : XshdElement
+	{
+		/// <summary>
+		/// Gets/sets the begin regex.
+		/// </summary>
+		public string BeginRegex { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the begin regex type.
+		/// </summary>
+		public XshdRegexType BeginRegexType { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the end regex.
+		/// </summary>
+		public string EndRegex { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the end regex type.
+		/// </summary>
+		public XshdRegexType EndRegexType { get; set; }
+		
+		/// <summary>
+		/// Gets/sets whether the span is multiline.
+		/// </summary>
+		public bool Multiline { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the rule set reference.
+		/// </summary>
+		public XshdReference<XshdRuleSet> RuleSetReference { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the span color.
+		/// </summary>
+		public XshdReference<XshdColor> SpanColorReference { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the span begin color.
+		/// </summary>
+		public XshdReference<XshdColor> BeginColorReference { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the span end color.
+		/// </summary>
+		public XshdReference<XshdColor> EndColorReference { get; set; }
+		
+		/// <inheritdoc/>
+		public override object AcceptVisitor(IXshdVisitor visitor)
+		{
+			return visitor.VisitSpan(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdSyntaxDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdSyntaxDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Highlighting/Xshd/XshdSyntaxDefinition.cs	(revision 11807)
@@ -0,0 +1,65 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Highlighting.Xshd
+{
+	/// <summary>
+	/// A &lt;SyntaxDefinition&gt; element.
+	/// </summary>
+	[Serializable]
+	public class XshdSyntaxDefinition
+	{
+		/// <summary>
+		/// Creates a new XshdSyntaxDefinition object.
+		/// </summary>
+		public XshdSyntaxDefinition()
+		{
+			this.Elements = new NullSafeCollection<XshdElement>();
+			this.Extensions = new NullSafeCollection<string>();
+		}
+		
+		/// <summary>
+		/// Gets/sets the definition name
+		/// </summary>
+		public string Name { get; set; }
+		
+		/// <summary>
+		/// Gets the associated extensions.
+		/// </summary>
+		public IList<string> Extensions { get; private set; }
+		
+		/// <summary>
+		/// Gets the collection of elements.
+		/// </summary>
+		public IList<XshdElement> Elements { get; private set; }
+		
+		/// <summary>
+		/// Applies the visitor to all elements.
+		/// </summary>
+		public void AcceptElements(IXshdVisitor visitor)
+		{
+			foreach (XshdElement element in Elements) {
+				element.AcceptVisitor(visitor);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit License-5.0.1.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit License-5.0.1.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit License-5.0.1.txt	(revision 11807)
@@ -0,0 +1,19 @@
+The MIT License (MIT)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit-5.0.1.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit-5.0.1.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit-5.0.1.csproj	(revision 11807)
@@ -0,0 +1,449 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;DOTNET4;NREFACTORY</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DOTNET4;NREFACTORY</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;DOTNET4;NREFACTORY</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DOTNET4;NREFACTORY</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;DOTNET4;NREFACTORY</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DOTNET4;NREFACTORY</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+    <ProjectGuid>{255C7DEB-3C98-4BC2-92D4-B683F82A7E52}</ProjectGuid>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <PropertyGroup>
+    <RootNamespace>ICSharpCode.AvalonEdit</RootNamespace>
+  </PropertyGroup>
+  <PropertyGroup>
+    <OutputType>Library</OutputType>
+  </PropertyGroup>
+  <PropertyGroup>
+    <StartupObject />
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyName>ICSharpCode.AvalonEdit</AssemblyName>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="PresentationCore" />
+    <Reference Include="PresentationFramework" />
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Drawing" />
+    <Reference Include="System.Windows.Forms" />
+    <Reference Include="System.Xaml" />
+    <Reference Include="System.Xml" />
+    <Reference Include="UIAutomationProvider" />
+    <Reference Include="UIAutomationTypes" />
+    <Reference Include="WindowsBase" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="AvalonEditCommands.cs" />
+    <Compile Include="CodeCompletion\CompletionList.cs" />
+    <Compile Include="CodeCompletion\CompletionListBox.cs" />
+    <Compile Include="CodeCompletion\CompletionWindow.cs" />
+    <Compile Include="CodeCompletion\CompletionWindowBase.cs" />
+    <Compile Include="CodeCompletion\ICompletionData.cs" />
+    <Compile Include="CodeCompletion\InsightWindow.cs" />
+    <Compile Include="CodeCompletion\IOverloadProvider.cs" />
+    <Compile Include="CodeCompletion\OverloadInsightWindow.cs" />
+    <Compile Include="CodeCompletion\OverloadViewer.cs" />
+    <Compile Include="Document\DocumentChangeEventArgs.cs" />
+    <Compile Include="Document\DocumentChangeOperation.cs">
+      <DependentUpon>UndoStack.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\DocumentLine.cs" />
+    <Compile Include="Document\DocumentLineTree.cs">
+      <DependentUpon>DocumentLine.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\DocumentTextWriter.cs" />
+    <Compile Include="Document\GapTextBuffer.cs">
+      <DependentUpon>TextDocument.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\IDocument.cs" />
+    <Compile Include="Document\ILineTracker.cs" />
+    <Compile Include="Document\ITextAnchor.cs" />
+    <Compile Include="Document\ITextSource.cs" />
+    <Compile Include="Document\IUndoableOperation.cs">
+      <DependentUpon>UndoStack.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\LineManager.cs">
+      <DependentUpon>TextDocument.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\LineNode.cs">
+      <DependentUpon>DocumentLine.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\NewLineFinder.cs" />
+    <Compile Include="Document\OffsetChangeMap.cs" />
+    <Compile Include="Document\RopeTextSource.cs" />
+    <Compile Include="Document\SimpleSegment.cs" />
+    <Compile Include="Document\TextAnchor.cs" />
+    <Compile Include="Document\TextAnchorNode.cs">
+      <DependentUpon>TextAnchor.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\TextAnchorTree.cs">
+      <DependentUpon>TextAnchor.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\TextDocument.cs" />
+    <Compile Include="Document\TextDocumentWeakEventManager.cs">
+      <DependentUpon>TextDocument.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\TextLocation.cs" />
+    <Compile Include="Document\TextSegment.cs" />
+    <Compile Include="Document\TextSegmentCollection.cs" />
+    <Compile Include="Document\TextSourceVersionProvider.cs" />
+    <Compile Include="Document\TextUtilities.cs" />
+    <Compile Include="Document\UndoOperationGroup.cs">
+      <DependentUpon>UndoStack.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Document\UndoStack.cs" />
+    <Compile Include="Document\WeakLineTracker.cs">
+      <DependentUpon>ILineTracker.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\AbstractMargin.cs" />
+    <Compile Include="Editing\Caret.cs" />
+    <Compile Include="Editing\CaretLayer.cs" />
+    <Compile Include="Editing\CaretNavigationCommandHandler.cs" />
+    <Compile Include="Editing\CaretWeakEventHandler.cs" />
+    <Compile Include="Editing\DottedLineMargin.cs" />
+    <Compile Include="Editing\DragDropException.cs" />
+    <Compile Include="Editing\EditingCommandHandler.cs" />
+    <Compile Include="Editing\EmptySelection.cs">
+      <DependentUpon>Selection.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\ImeNativeWrapper.cs" />
+    <Compile Include="Editing\ImeSupport.cs" />
+    <Compile Include="Editing\IReadOnlySectionProvider.cs" />
+    <Compile Include="Editing\LineNumberMargin.cs" />
+    <Compile Include="Editing\NoReadOnlySections.cs">
+      <DependentUpon>IReadOnlySectionProvider.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\RectangleSelection.cs">
+      <DependentUpon>Selection.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\Selection.cs" />
+    <Compile Include="Editing\SelectionColorizer.cs">
+      <DependentUpon>Selection.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\SelectionLayer.cs">
+      <DependentUpon>Selection.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\SelectionMouseHandler.cs">
+      <DependentUpon>Selection.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\SelectionSegment.cs" />
+    <Compile Include="Editing\SimpleSelection.cs">
+      <DependentUpon>Selection.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Editing\TextArea.cs" />
+    <Compile Include="Editing\TextAreaDefaultInputHandlers.cs" />
+    <Compile Include="Editing\TextAreaInputHandler.cs" />
+    <Compile Include="Editing\TextSegmentReadOnlySectionProvider.cs">
+      <DependentUpon>IReadOnlySectionProvider.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Folding\FoldingElementGenerator.cs" />
+    <Compile Include="Folding\FoldingManager.cs" />
+    <Compile Include="Folding\FoldingMargin.cs" />
+    <Compile Include="Folding\FoldingMarginMarker.cs" />
+    <Compile Include="Folding\FoldingSection.cs" />
+    <Compile Include="Folding\NewFolding.cs" />
+    <Compile Include="Folding\XmlFoldingStrategy.cs" />
+    <Compile Include="Highlighting\DocumentHighlighter.cs" />
+    <Compile Include="Highlighting\HighlightedInlineBuilder.cs" />
+    <Compile Include="Highlighting\HighlightedLine.cs" />
+    <Compile Include="Highlighting\HighlightedSection.cs" />
+    <Compile Include="Highlighting\HighlightingBrush.cs" />
+    <Compile Include="Highlighting\HighlightingColor.cs" />
+    <Compile Include="Highlighting\HighlightingColorizer.cs" />
+    <Compile Include="Highlighting\HighlightingDefinitionInvalidException.cs" />
+    <Compile Include="Highlighting\HighlightingDefinitionTypeConverter.cs" />
+    <Compile Include="Highlighting\HighlightingEngine.cs" />
+    <Compile Include="Highlighting\HighlightingManager.cs" />
+    <Compile Include="Highlighting\HighlightingRule.cs" />
+    <Compile Include="Highlighting\HighlightingRuleSet.cs" />
+    <Compile Include="Highlighting\HighlightingSpan.cs" />
+    <Compile Include="Highlighting\HtmlClipboard.cs" />
+    <Compile Include="Highlighting\HtmlOptions.cs" />
+    <Compile Include="Highlighting\HtmlRichTextWriter.cs" />
+    <Compile Include="Highlighting\IHighlighter.cs" />
+    <Compile Include="Highlighting\IHighlightingDefinition.cs" />
+    <Compile Include="Highlighting\IHighlightingDefinitionReferenceResolver.cs" />
+    <Compile Include="Highlighting\Resources\Resources.cs" />
+    <Compile Include="Highlighting\RichText.cs" />
+    <Compile Include="Highlighting\RichTextColorizer.cs" />
+    <Compile Include="Highlighting\RichTextModel.cs" />
+    <Compile Include="Highlighting\RichTextModelWriter.cs" />
+    <Compile Include="Highlighting\Xshd\HighlightingLoader.cs" />
+    <Compile Include="Highlighting\Xshd\IXshdVisitor.cs" />
+    <Compile Include="Highlighting\Xshd\SaveXshdVisitor.cs" />
+    <Compile Include="Highlighting\Xshd\V1Loader.cs" />
+    <Compile Include="Highlighting\Xshd\V2Loader.cs" />
+    <Compile Include="Highlighting\Xshd\XmlHighlightingDefinition.cs" />
+    <Compile Include="Highlighting\Xshd\XshdColor.cs" />
+    <Compile Include="Highlighting\Xshd\XshdElement.cs" />
+    <Compile Include="Highlighting\Xshd\XshdImport.cs" />
+    <Compile Include="Highlighting\Xshd\XshdKeywords.cs" />
+    <Compile Include="Highlighting\Xshd\XshdProperty.cs" />
+    <Compile Include="Highlighting\Xshd\XshdReference.cs" />
+    <Compile Include="Highlighting\Xshd\XshdRule.cs" />
+    <Compile Include="Highlighting\Xshd\XshdRuleSet.cs" />
+    <Compile Include="Highlighting\Xshd\XshdSpan.cs" />
+    <Compile Include="Highlighting\Xshd\XshdSyntaxDefinition.cs" />
+    <Compile Include="Indentation\CSharp\CSharpIndentationStrategy.cs" />
+    <Compile Include="Indentation\CSharp\DocumentAccessor.cs" />
+    <Compile Include="Indentation\CSharp\IndentationReformatter.cs" />
+    <Compile Include="Indentation\DefaultIndentationStrategy.cs" />
+    <Compile Include="Indentation\IIndentationStrategy.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Rendering\BackgroundGeometryBuilder.cs">
+      <DependentUpon>IBackgroundRenderer.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\CollapsedLineSection.cs">
+      <DependentUpon>HeightTree.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\ColorizingTransformer.cs">
+      <DependentUpon>IVisualLineTransformer.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\ColumnRulerRenderer.cs" />
+    <Compile Include="Rendering\CurrentLineHighlightRenderer.cs" />
+    <Compile Include="Rendering\DefaultTextRunTypographyProperties.cs" />
+    <Compile Include="Rendering\DocumentColorizingTransformer.cs">
+      <DependentUpon>IVisualLineTransformer.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\FormattedTextElement.cs" />
+    <Compile Include="Rendering\GlobalTextRunProperties.cs">
+      <DependentUpon>TextView.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\HeightTree.cs" />
+    <Compile Include="Rendering\HeightTreeLineNode.cs">
+      <DependentUpon>HeightTree.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\HeightTreeNode.cs">
+      <DependentUpon>HeightTree.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\IBackgroundRenderer.cs" />
+    <Compile Include="Rendering\InlineObjectRun.cs" />
+    <Compile Include="Rendering\ITextRunConstructionContext.cs">
+      <DependentUpon>VisualLineElementGenerator.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\ITextViewConnect.cs">
+      <DependentUpon>TextView.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\IVisualLineTransformer.cs" />
+    <Compile Include="Rendering\Layer.cs">
+      <DependentUpon>TextView.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\LayerPosition.cs">
+      <DependentUpon>TextView.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\LinkElementGenerator.cs" />
+    <Compile Include="Rendering\MouseHoverLogic.cs" />
+    <Compile Include="Rendering\SimpleTextSource.cs">
+      <DependentUpon>FormattedTextElement.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\SingleCharacterElementGenerator.cs" />
+    <Compile Include="Rendering\TextLayer.cs">
+      <DependentUpon>TextView.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\TextView.cs" />
+    <Compile Include="Rendering\TextViewCachedElements.cs" />
+    <Compile Include="Rendering\TextViewWeakEventManager.cs">
+      <DependentUpon>TextView.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\VisualLine.cs" />
+    <Compile Include="Rendering\VisualLineConstructionStartEventArgs.cs" />
+    <Compile Include="Rendering\VisualLineElement.cs" />
+    <Compile Include="Rendering\VisualLineElementGenerator.cs" />
+    <Compile Include="Rendering\VisualLineElementTextRunProperties.cs">
+      <DependentUpon>VisualLine.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\VisualLineLinkText.cs" />
+    <Compile Include="Rendering\VisualLinesInvalidException.cs" />
+    <Compile Include="Rendering\VisualLineText.cs" />
+    <Compile Include="Rendering\VisualLineTextParagraphProperties.cs">
+      <DependentUpon>VisualLine.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\VisualLineTextSource.cs">
+      <DependentUpon>VisualLineElementGenerator.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Rendering\VisualYPosition.cs">
+      <DependentUpon>VisualLine.cs</DependentUpon>
+    </Compile>
+    <Compile Include="Search\DropDownButton.cs" />
+    <Compile Include="Search\ISearchStrategy.cs" />
+    <Compile Include="Search\Localization.cs" />
+    <Compile Include="Search\RegexSearchStrategy.cs" />
+    <Compile Include="Search\SearchCommands.cs" />
+    <Compile Include="Search\SearchPanel.cs">
+      <SubType>Code</SubType>
+    </Compile>
+    <Compile Include="Search\SearchResultBackgroundRenderer.cs" />
+    <Compile Include="Search\SearchStrategyFactory.cs" />
+    <Compile Include="Snippets\IActiveElement.cs" />
+    <Compile Include="Snippets\InsertionContext.cs" />
+    <Compile Include="Snippets\Snippet.cs" />
+    <Compile Include="Snippets\SnippetAnchorElement.cs" />
+    <Compile Include="Snippets\SnippetBoundElement.cs" />
+    <Compile Include="Snippets\SnippetCaretElement.cs" />
+    <Compile Include="Snippets\SnippetContainerElement.cs" />
+    <Compile Include="Snippets\SnippetElement.cs" />
+    <Compile Include="Snippets\SnippetEventArgs.cs" />
+    <Compile Include="Snippets\SnippetInputHandler.cs" />
+    <Compile Include="Snippets\SnippetReplaceableTextElement.cs" />
+    <Compile Include="Snippets\SnippetSelectionElement.cs" />
+    <Compile Include="Snippets\SnippetTextElement.cs" />
+    <Compile Include="TextEditor.cs" />
+    <Compile Include="TextEditorAutomationPeer.cs" />
+    <Compile Include="TextEditorComponent.cs" />
+    <Compile Include="TextEditorOptions.cs" />
+    <Compile Include="TextEditorWeakEventManager.cs">
+      <DependentUpon>TextEditor.cs</DependentUpon>
+    </Compile>
+    <Compile Include="TextViewPosition.cs" />
+    <Compile Include="Utils\Boxes.cs" />
+    <Compile Include="Utils\CallbackOnDispose.cs" />
+    <Compile Include="Utils\CharRope.cs" />
+    <Compile Include="Utils\CompressingTreeList.cs" />
+    <Compile Include="Utils\Constants.cs" />
+    <Compile Include="Utils\DelayedEvents.cs" />
+    <Compile Include="Utils\Deque.cs" />
+    <Compile Include="Utils\DocumentPrinter.cs" />
+    <Compile Include="Utils\Empty.cs" />
+    <Compile Include="Utils\ExtensionMethods.cs" />
+    <Compile Include="Utils\FileReader.cs" />
+    <Compile Include="Utils\IFreezable.cs" />
+    <Compile Include="Utils\ImmutableStack.cs" />
+    <Compile Include="Utils\NullSafeCollection.cs" />
+    <Compile Include="Utils\ObserveAddRemoveCollection.cs" />
+    <Compile Include="Utils\PixelSnapHelpers.cs" />
+    <Compile Include="Utils\PlainRichTextWriter.cs" />
+    <Compile Include="Utils\PropertyChangedWeakEventManager.cs" />
+    <Compile Include="Utils\RichTextWriter.cs" />
+    <Compile Include="Utils\Rope.cs" />
+    <Compile Include="Utils\RopeNode.cs" />
+    <Compile Include="Utils\RopeTextReader.cs" />
+    <Compile Include="Utils\StringSegment.cs" />
+    <Compile Include="Utils\TextFormatterFactory.cs" />
+    <Compile Include="Utils\ThrowUtil.cs" />
+    <Compile Include="Utils\WeakEventManagerBase.cs" />
+    <Compile Include="Utils\Win32.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+    <EmbeddedResource Include="Highlighting\Resources\ASPX.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\Boo.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\Coco-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\CPP-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\CSharp-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\CSS-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\HTML-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\Java-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\JavaScript-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\MarkDown-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\ModeV1.xsd">
+      <SubType>Designer</SubType>
+    </EmbeddedResource>
+    <EmbeddedResource Include="Highlighting\Resources\ModeV2.xsd">
+      <SubType>Designer</SubType>
+    </EmbeddedResource>
+    <EmbeddedResource Include="Highlighting\Resources\Patch-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\PHP-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\PowerShell.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\Tex-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\VB-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\XML-Mode.xshd" />
+    <EmbeddedResource Include="Highlighting\Resources\XmlDoc.xshd" />
+  </ItemGroup>
+  <ItemGroup>
+    <Page Include="CodeCompletion\CompletionList.xaml" />
+    <Page Include="CodeCompletion\InsightWindow.xaml" />
+    <Page Include="Search\DropDownButton.xaml">
+      <DependentUpon>DropDownButton.cs</DependentUpon>
+    </Page>
+    <Page Include="Search\SearchPanel.xaml">
+      <DependentUpon>SearchPanel.cs</DependentUpon>
+    </Page>
+    <Page Include="TextEditor.xaml" />
+    <Page Include="themes\generic.xaml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="ICSharpCode.AvalonEdit License-5.0.1.txt" />
+    <Resource Include="Search\next.png" />
+    <Resource Include="Search\prev.png" />
+    <Resource Include="themes\RightArrow.cur" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\..\HeuristicLab.NRefactory\5.5.0\NRefactory-5.5.0\ICSharpCode.NRefactory-5.5.0.csproj">
+      <Project>{1022483b-7cf4-4162-827f-984b64eaf8b3}</Project>
+      <Name>ICSharpCode.NRefactory-5.5.0</Name>
+      <Private>False</Private>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit-5.0.1.csproj.user
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit-5.0.1.csproj.user	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/ICSharpCode.AvalonEdit-5.0.1.csproj.user	(revision 11807)
@@ -0,0 +1,6 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <ProjectView>ProjectFiles</ProjectView>
+  </PropertyGroup>
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/CSharpIndentationStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/CSharpIndentationStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/CSharpIndentationStrategy.cs	(revision 11807)
@@ -0,0 +1,95 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Indentation.CSharp
+{
+	/// <summary>
+	/// Smart indentation for C#.
+	/// </summary>
+	public class CSharpIndentationStrategy : DefaultIndentationStrategy
+	{
+		/// <summary>
+		/// Creates a new CSharpIndentationStrategy.
+		/// </summary>
+		public CSharpIndentationStrategy()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new CSharpIndentationStrategy and initializes the settings using the text editor options.
+		/// </summary>
+		public CSharpIndentationStrategy(TextEditorOptions options)
+		{
+			this.IndentationString = options.IndentationString;
+		}
+		
+		string indentationString = "\t";
+		
+		/// <summary>
+		/// Gets/Sets the indentation string.
+		/// </summary>
+		public string IndentationString {
+			get { return indentationString; }
+			set {
+				if (string.IsNullOrEmpty(value))
+					throw new ArgumentException("Indentation string must not be null or empty");
+				indentationString = value;
+			}
+		}
+		
+		/// <summary>
+		/// Performs indentation using the specified document accessor.
+		/// </summary>
+		/// <param name="document">Object used for accessing the document line-by-line</param>
+		/// <param name="keepEmptyLines">Specifies whether empty lines should be kept</param>
+		public void Indent(IDocumentAccessor document, bool keepEmptyLines)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			IndentationSettings settings = new IndentationSettings();
+			settings.IndentString = this.IndentationString;
+			settings.LeaveEmptyLines = keepEmptyLines;
+			
+			IndentationReformatter r = new IndentationReformatter();
+			r.Reformat(document, settings);
+		}
+		
+		/// <inheritdoc cref="IIndentationStrategy.IndentLine"/>
+		public override void IndentLine(TextDocument document, DocumentLine line)
+		{
+			int lineNr = line.LineNumber;
+			TextDocumentAccessor acc = new TextDocumentAccessor(document, lineNr, lineNr);
+			Indent(acc, false);
+			
+			string t = acc.Text;
+			if (t.Length == 0) {
+				// use AutoIndentation for new lines in comments / verbatim strings.
+				base.IndentLine(document, line);
+			}
+		}
+		
+		/// <inheritdoc cref="IIndentationStrategy.IndentLines"/>
+		public override void IndentLines(TextDocument document, int beginLine, int endLine)
+		{
+			Indent(new TextDocumentAccessor(document, beginLine, endLine), true);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/DocumentAccessor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/DocumentAccessor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/DocumentAccessor.cs	(revision 11807)
@@ -0,0 +1,122 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Indentation.CSharp
+{
+	/// <summary>
+	/// Interface used for the indentation class to access the document.
+	/// </summary>
+	public interface IDocumentAccessor
+	{
+		/// <summary>Gets if the current line is read only (because it is not in the
+		/// selected text region)</summary>
+		bool IsReadOnly { get; }
+		/// <summary>Gets the number of the current line.</summary>
+		int LineNumber { get; }
+		/// <summary>Gets/Sets the text of the current line.</summary>
+		string Text { get; set; }
+		/// <summary>Advances to the next line.</summary>
+		bool MoveNext();
+	}
+	
+	#region TextDocumentAccessor
+	/// <summary>
+	/// Adapter IDocumentAccessor -> TextDocument
+	/// </summary>
+	public sealed class TextDocumentAccessor : IDocumentAccessor
+	{
+		readonly TextDocument doc;
+		readonly int minLine;
+		readonly int maxLine;
+		
+		/// <summary>
+		/// Creates a new TextDocumentAccessor.
+		/// </summary>
+		public TextDocumentAccessor(TextDocument document)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			doc = document;
+			this.minLine = 1;
+			this.maxLine = doc.LineCount;
+		}
+		
+		/// <summary>
+		/// Creates a new TextDocumentAccessor that indents only a part of the document.
+		/// </summary>
+		public TextDocumentAccessor(TextDocument document, int minLine, int maxLine)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			doc = document;
+			this.minLine = minLine;
+			this.maxLine = maxLine;
+		}
+		
+		int num;
+		string text;
+		DocumentLine line;
+		
+		/// <inheritdoc/>
+		public bool IsReadOnly {
+			get {
+				return num < minLine;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public int LineNumber {
+			get {
+				return num;
+			}
+		}
+		
+		bool lineDirty;
+		
+		/// <inheritdoc/>
+		public string Text {
+			get { return text; }
+			set {
+				if (num < minLine) return;
+				text = value;
+				lineDirty = true;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public bool MoveNext()
+		{
+			if (lineDirty) {
+				doc.Replace(line, text);
+				lineDirty = false;
+			}
+			++num;
+			if (num > maxLine) return false;
+			line = doc.GetLineByNumber(num);
+			text = doc.GetText(line);
+			return true;
+		}
+	}
+	#endregion
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/IndentationReformatter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/IndentationReformatter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/CSharp/IndentationReformatter.cs	(revision 11807)
@@ -0,0 +1,489 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Indentation.CSharp
+{
+	sealed class IndentationSettings
+	{
+		public string IndentString = "\t";
+		/// <summary>Leave empty lines empty.</summary>
+		public bool LeaveEmptyLines = true;
+	}
+	
+	sealed class IndentationReformatter
+	{
+		/// <summary>
+		/// An indentation block. Tracks the state of the indentation.
+		/// </summary>
+		struct Block
+		{
+			/// <summary>
+			/// The indentation outside of the block.
+			/// </summary>
+			public string OuterIndent;
+			
+			/// <summary>
+			/// The indentation inside the block.
+			/// </summary>
+			public string InnerIndent;
+			
+			/// <summary>
+			/// The last word that was seen inside this block.
+			/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
+			/// this property can be used to identify the type of block statement (if, while, switch)
+			/// at the position of the '{'.
+			/// </summary>
+			public string LastWord;
+			
+			/// <summary>
+			/// The type of bracket that opened this block (, [ or {
+			/// </summary>
+			public char Bracket;
+			
+			/// <summary>
+			/// Gets whether there's currently a line continuation going on inside this block.
+			/// </summary>
+			public bool Continuation;
+			
+			/// <summary>
+			/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
+			/// with if statements that don't use '{}'. They are not represented by a Block instance on
+			/// the stack, but are instead handled similar to line continuations.
+			/// This property is an integer because there might be multiple nested one-line-blocks.
+			/// As soon as there is a finished statement, OneLineBlock is reset to 0.
+			/// </summary>
+			public int OneLineBlock;
+			
+			/// <summary>
+			/// The previous value of one-line-block before it was reset.
+			/// Used to restore the indentation of 'else' to the correct level.
+			/// </summary>
+			public int PreviousOneLineBlock;
+			
+			public void ResetOneLineBlock()
+			{
+				PreviousOneLineBlock = OneLineBlock;
+				OneLineBlock = 0;
+			}
+			
+			/// <summary>
+			/// Gets the line number where this block started.
+			/// </summary>
+			public int StartLine;
+			
+			public void Indent(IndentationSettings set)
+			{
+				Indent(set.IndentString);
+			}
+			
+			public void Indent(string indentationString)
+			{
+				OuterIndent = InnerIndent;
+				InnerIndent += indentationString;
+				Continuation = false;
+				ResetOneLineBlock();
+				LastWord = "";
+			}
+			
+			public override string ToString()
+			{
+				return string.Format(
+					CultureInfo.InvariantCulture,
+					"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
+					this.StartLine, this.LastWord, this.Continuation, this.OneLineBlock, this.PreviousOneLineBlock);
+			}
+		}
+		
+		StringBuilder wordBuilder;
+		Stack<Block> blocks; // blocks contains all blocks outside of the current
+		Block block;  // block is the current block
+		
+		bool inString;
+		bool inChar;
+		bool verbatim;
+		bool escape;
+		
+		bool lineComment;
+		bool blockComment;
+		
+		char lastRealChar; // last non-comment char
+		
+		public void Reformat(IDocumentAccessor doc, IndentationSettings set)
+		{
+			Init();
+			
+			while (doc.MoveNext()) {
+				Step(doc, set);
+			}
+		}
+		
+		public void Init()
+		{
+			wordBuilder = new StringBuilder();
+			blocks = new Stack<Block>();
+			block = new Block();
+			block.InnerIndent = "";
+			block.OuterIndent = "";
+			block.Bracket = '{';
+			block.Continuation = false;
+			block.LastWord = "";
+			block.OneLineBlock = 0;
+			block.PreviousOneLineBlock = 0;
+			block.StartLine = 0;
+			
+			inString = false;
+			inChar   = false;
+			verbatim = false;
+			escape   = false;
+			
+			lineComment  = false;
+			blockComment = false;
+			
+			lastRealChar = ' '; // last non-comment char
+		}
+		
+		public void Step(IDocumentAccessor doc, IndentationSettings set)
+		{
+			string line = doc.Text;
+			if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
+			line = line.TrimStart();
+			
+			StringBuilder indent = new StringBuilder();
+			if (line.Length == 0) {
+				// Special treatment for empty lines:
+				if (blockComment || (inString && verbatim))
+					return;
+				indent.Append(block.InnerIndent);
+				indent.Append(Repeat(set.IndentString, block.OneLineBlock));
+				if (block.Continuation)
+					indent.Append(set.IndentString);
+				if (doc.Text != indent.ToString())
+					doc.Text = indent.ToString();
+				return;
+			}
+			
+			if (TrimEnd(doc))
+				line = doc.Text.TrimStart();
+			
+			Block oldBlock = block;
+			bool startInComment = blockComment;
+			bool startInString = (inString && verbatim);
+			
+			#region Parse char by char
+			lineComment = false;
+			inChar = false;
+			escape = false;
+			if (!verbatim) inString = false;
+			
+			lastRealChar = '\n';
+			
+			char lastchar = ' ';
+			char c = ' ';
+			char nextchar = line[0];
+			for (int i = 0; i < line.Length; i++) {
+				if (lineComment) break; // cancel parsing current line
+				
+				lastchar = c;
+				c = nextchar;
+				if (i + 1 < line.Length)
+					nextchar = line[i + 1];
+				else
+					nextchar = '\n';
+				
+				if (escape) {
+					escape = false;
+					continue;
+				}
+				
+				#region Check for comment/string chars
+				switch (c) {
+					case '/':
+						if (blockComment && lastchar == '*')
+							blockComment = false;
+						if (!inString && !inChar) {
+							if (!blockComment && nextchar == '/')
+								lineComment = true;
+							if (!lineComment && nextchar == '*')
+								blockComment = true;
+						}
+						break;
+					case '#':
+						if (!(inChar || blockComment || inString))
+							lineComment = true;
+						break;
+					case '"':
+						if (!(inChar || lineComment || blockComment)) {
+							inString = !inString;
+							if (!inString && verbatim) {
+								if (nextchar == '"') {
+									escape = true; // skip escaped quote
+									inString = true;
+								} else {
+									verbatim = false;
+								}
+							} else if (inString && lastchar == '@') {
+								verbatim = true;
+							}
+						}
+						break;
+					case '\'':
+						if (!(inString || lineComment || blockComment)) {
+							inChar = !inChar;
+						}
+						break;
+					case '\\':
+						if ((inString && !verbatim) || inChar)
+							escape = true; // skip next character
+						break;
+				}
+				#endregion
+				
+				if (lineComment || blockComment || inString || inChar) {
+					if (wordBuilder.Length > 0)
+						block.LastWord = wordBuilder.ToString();
+					wordBuilder.Length = 0;
+					continue;
+				}
+				
+				if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
+					if (block.Bracket == '{')
+						block.Continuation = true;
+				}
+				
+				if (Char.IsLetterOrDigit(c)) {
+					wordBuilder.Append(c);
+				} else {
+					if (wordBuilder.Length > 0)
+						block.LastWord = wordBuilder.ToString();
+					wordBuilder.Length = 0;
+				}
+				
+				#region Push/Pop the blocks
+				switch (c) {
+					case '{':
+						block.ResetOneLineBlock();
+						blocks.Push(block);
+						block.StartLine = doc.LineNumber;
+						if (block.LastWord == "switch") {
+							block.Indent(set.IndentString + set.IndentString);
+							/* oldBlock refers to the previous line, not the previous block
+							 * The block we want is not available anymore because it was never pushed.
+							 * } else if (oldBlock.OneLineBlock) {
+							// Inside a one-line-block is another statement
+							// with a full block: indent the inner full block
+							// by one additional level
+							block.Indent(set, set.IndentString + set.IndentString);
+							block.OuterIndent += set.IndentString;
+							// Indent current line if it starts with the '{' character
+							if (i == 0) {
+								oldBlock.InnerIndent += set.IndentString;
+							}*/
+						} else {
+							block.Indent(set);
+						}
+						block.Bracket = '{';
+						break;
+					case '}':
+						while (block.Bracket != '{') {
+							if (blocks.Count == 0) break;
+							block = blocks.Pop();
+						}
+						if (blocks.Count == 0) break;
+						block = blocks.Pop();
+						block.Continuation = false;
+						block.ResetOneLineBlock();
+						break;
+					case '(':
+					case '[':
+						blocks.Push(block);
+						if (block.StartLine == doc.LineNumber)
+							block.InnerIndent = block.OuterIndent;
+						else
+							block.StartLine = doc.LineNumber;
+						block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
+						             (oldBlock.Continuation ? set.IndentString : "") +
+						             (i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
+						block.Bracket = c;
+						break;
+					case ')':
+						if (blocks.Count == 0) break;
+						if (block.Bracket == '(') {
+							block = blocks.Pop();
+							if (IsSingleStatementKeyword(block.LastWord))
+								block.Continuation = false;
+						}
+						break;
+					case ']':
+						if (blocks.Count == 0) break;
+						if (block.Bracket == '[')
+							block = blocks.Pop();
+						break;
+					case ';':
+					case ',':
+						block.Continuation = false;
+						block.ResetOneLineBlock();
+						break;
+					case ':':
+						if (block.LastWord == "case" 
+						    || line.StartsWith("case ", StringComparison.Ordinal) 
+						    || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) 
+						{
+							block.Continuation = false;
+							block.ResetOneLineBlock();
+						}
+						break;
+				}
+				
+				if (!Char.IsWhiteSpace(c)) {
+					// register this char as last char
+					lastRealChar = c;
+				}
+				#endregion
+			}
+			#endregion
+			
+			if (wordBuilder.Length > 0)
+				block.LastWord = wordBuilder.ToString();
+			wordBuilder.Length = 0;
+			
+			if (startInString) return;
+			if (startInComment && line[0] != '*') return;
+			if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
+				return;
+			
+			if (line[0] == '}') {
+				indent.Append(oldBlock.OuterIndent);
+				oldBlock.ResetOneLineBlock();
+				oldBlock.Continuation = false;
+			} else {
+				indent.Append(oldBlock.InnerIndent);
+			}
+			
+			if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
+				indent.Remove(indent.Length - 1, 1);
+			} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
+				indent.Remove(indent.Length - 1, 1);
+			}
+			
+			if (line[0] == ':') {
+				oldBlock.Continuation = true;
+			} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
+				if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
+					indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
+			} else if (lastRealChar == ')') {
+				if (IsSingleStatementKeyword(block.LastWord)) {
+					block.OneLineBlock++;
+				}
+			} else if (lastRealChar == 'e' && block.LastWord == "else") {
+				block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
+				block.Continuation = false;
+				oldBlock.OneLineBlock = block.OneLineBlock - 1;
+			}
+			
+			if (doc.IsReadOnly) {
+				// We can't change the current line, but we should accept the existing
+				// indentation if possible (=if the current statement is not a multiline
+				// statement).
+				if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
+				    oldBlock.StartLine == block.StartLine &&
+				    block.StartLine < doc.LineNumber && lastRealChar != ':')
+				{
+					// use indent StringBuilder to get the indentation of the current line
+					indent.Length = 0;
+					line = doc.Text; // get untrimmed line
+					for (int i = 0; i < line.Length; ++i) {
+						if (!Char.IsWhiteSpace(line[i]))
+							break;
+						indent.Append(line[i]);
+					}
+					// /* */ multiline comments have an extra space - do not count it
+					// for the block's indentation.
+					if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
+						indent.Length -= 1;
+					}
+					block.InnerIndent = indent.ToString();
+				}
+				return;
+			}
+			
+			if (line[0] != '{') {
+				if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
+					indent.Append(set.IndentString);
+				indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
+			}
+			
+			// this is only for blockcomment lines starting with *,
+			// all others keep their old indentation
+			if (startInComment)
+				indent.Append(' ');
+			
+			if (indent.Length != (doc.Text.Length - line.Length) ||
+			    !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
+			    Char.IsWhiteSpace(doc.Text[indent.Length]))
+			{
+				doc.Text = indent.ToString() + line;
+			}
+		}
+		
+		static string Repeat(string text, int count)
+		{
+			if (count == 0)
+				return string.Empty;
+			if (count == 1)
+				return text;
+			StringBuilder b = new StringBuilder(text.Length * count);
+			for (int i = 0; i < count; i++)
+				b.Append(text);
+			return b.ToString();
+		}
+		
+		static bool IsSingleStatementKeyword(string keyword)
+		{
+			switch (keyword) {
+				case "if":
+				case "for":
+				case "while":
+				case "do":
+				case "foreach":
+				case "using":
+				case "lock":
+					return true;
+				default:
+					return false;
+			}
+		}
+		
+		static bool TrimEnd(IDocumentAccessor doc)
+		{
+			string line = doc.Text;
+			if (!Char.IsWhiteSpace(line[line.Length - 1])) return false;
+			
+			// one space after an empty comment is allowed
+			if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
+				return false;
+			
+			doc.Text = line.TrimEnd();
+			return true;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/DefaultIndentationStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/DefaultIndentationStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/DefaultIndentationStrategy.cs	(revision 11807)
@@ -0,0 +1,55 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Indentation
+{
+	/// <summary>
+	/// Handles indentation by copying the indentation from the previous line.
+	/// Does not support indenting multiple lines.
+	/// </summary>
+	public class DefaultIndentationStrategy : IIndentationStrategy
+	{
+		/// <inheritdoc/>
+		public virtual void IndentLine(TextDocument document, DocumentLine line)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (line == null)
+				throw new ArgumentNullException("line");
+			DocumentLine previousLine = line.PreviousLine;
+			if (previousLine != null) {
+				ISegment indentationSegment = TextUtilities.GetWhitespaceAfter(document, previousLine.Offset);
+				string indentation = document.GetText(indentationSegment);
+				// copy indentation to line
+				indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset);
+				document.Replace(indentationSegment, indentation);
+			}
+		}
+		
+		/// <summary>
+		/// Does nothing: indenting multiple lines is useless without a smart indentation strategy.
+		/// </summary>
+		public virtual void IndentLines(TextDocument document, int beginLine, int endLine)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/IIndentationStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/IIndentationStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Indentation/IIndentationStrategy.cs	(revision 11807)
@@ -0,0 +1,40 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using ICSharpCode.AvalonEdit.Document;
+using System;
+
+namespace ICSharpCode.AvalonEdit.Indentation
+{
+	/// <summary>
+	/// Strategy how the text editor handles indentation when new lines are inserted.
+	/// </summary>
+	public interface IIndentationStrategy
+	{
+		/// <summary>
+		/// Sets the indentation for the specified line.
+		/// Usually this is constructed from the indentation of the previous line.
+		/// </summary>
+		void IndentLine(TextDocument document, DocumentLine line);
+		
+		/// <summary>
+		/// Reindents a set of lines.
+		/// </summary>
+		void IndentLines(TextDocument document, int beginLine, int endLine);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿using System;
+using System.Reflection;
+using System.Resources;
+using System.Runtime.InteropServices;
+using System.Windows;
+using System.Windows.Markup;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ICSharpCode.AvalonEdit")]
+[assembly: AssemblyDescription("WPF-based extensible text editor")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("ic#code")]
+[assembly: AssemblyProduct("SharpDevelop")]
+[assembly: AssemblyCopyright("2000-2014 AlphaSierraPapa for the SharpDevelop Team")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+[assembly: CLSCompliant(true)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("5d2fbf08-c059-4fa7-98ef-a56916bd007b")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.0.1")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
+
+[assembly: NeutralResourcesLanguage("en-US")]
+
+[assembly: ThemeInfo(
+  ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
+  //(used if a resource is not found in the page,
+  // or application resource dictionaries)
+  ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
+  //(used if a resource is not found in the page,
+  // app, or any theme specific resource dictionaries)
+)]
+
+[assembly: XmlnsPrefix("http://icsharpcode.net/sharpdevelop/avalonedit", "avalonedit")]
+
+[assembly: XmlnsDefinition("http://icsharpcode.net/sharpdevelop/avalonedit", "ICSharpCode.AvalonEdit")]
+[assembly: XmlnsDefinition("http://icsharpcode.net/sharpdevelop/avalonedit", "ICSharpCode.AvalonEdit.Editing")]
+[assembly: XmlnsDefinition("http://icsharpcode.net/sharpdevelop/avalonedit", "ICSharpCode.AvalonEdit.Rendering")]
+[assembly: XmlnsDefinition("http://icsharpcode.net/sharpdevelop/avalonedit", "ICSharpCode.AvalonEdit.Highlighting")]
+[assembly: XmlnsDefinition("http://icsharpcode.net/sharpdevelop/avalonedit", "ICSharpCode.AvalonEdit.Search")]
+
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly",
+  Justification = "AssemblyInformationalVersion does not need to be a parsable version")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/BackgroundGeometryBuilder.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/BackgroundGeometryBuilder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/BackgroundGeometryBuilder.cs	(revision 11807)
@@ -0,0 +1,358 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls.Primitives;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Helper for creating a PathGeometry.
+	/// </summary>
+	public sealed class BackgroundGeometryBuilder
+	{
+		double cornerRadius;
+		
+		/// <summary>
+		/// Gets/sets the radius of the rounded corners.
+		/// </summary>
+		public double CornerRadius {
+			get { return cornerRadius; }
+			set { cornerRadius = value; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets whether to align the geometry to whole pixels.
+		/// </summary>
+		public bool AlignToWholePixels { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether to align the geometry to the middle of pixels.
+		/// </summary>
+		public bool AlignToMiddleOfPixels { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether to extend the rectangles to full width at line end.
+		/// </summary>
+		public bool ExtendToFullWidthAtLineEnd { get; set; }
+		
+		/// <summary>
+		/// Creates a new BackgroundGeometryBuilder instance.
+		/// </summary>
+		public BackgroundGeometryBuilder()
+		{
+		}
+		
+		/// <summary>
+		/// Adds the specified segment to the geometry.
+		/// </summary>
+		public void AddSegment(TextView textView, ISegment segment)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			Size pixelSize = PixelSnapHelpers.GetPixelSize(textView);
+			foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) {
+				AddRectangle(pixelSize, r);
+			}
+		}
+		
+		/// <summary>
+		/// Adds a rectangle to the geometry.
+		/// </summary>
+		/// <remarks>
+		/// This overload will align the coordinates according to
+		/// <see cref="AlignToWholePixels"/> or <see cref="AlignToMiddleOfPixels"/>.
+		/// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned.
+		/// </remarks>
+		public void AddRectangle(TextView textView, Rect rectangle)
+		{
+			AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle);
+		}
+
+		void AddRectangle(Size pixelSize, Rect r)
+		{
+			if (AlignToWholePixels) {
+				AddRectangle(PixelSnapHelpers.Round(r.Left, pixelSize.Width),
+				             PixelSnapHelpers.Round(r.Top + 1, pixelSize.Height),
+				             PixelSnapHelpers.Round(r.Right, pixelSize.Width),
+				             PixelSnapHelpers.Round(r.Bottom + 1, pixelSize.Height));
+			} else if (AlignToMiddleOfPixels) {
+				AddRectangle(PixelSnapHelpers.PixelAlign(r.Left, pixelSize.Width),
+				             PixelSnapHelpers.PixelAlign(r.Top + 1, pixelSize.Height),
+				             PixelSnapHelpers.PixelAlign(r.Right, pixelSize.Width),
+				             PixelSnapHelpers.PixelAlign(r.Bottom + 1, pixelSize.Height));
+			} else {
+				AddRectangle(r.Left, r.Top + 1, r.Right, r.Bottom + 1);
+			}
+		}
+		
+		/// <summary>
+		/// Calculates the list of rectangle where the segment in shown.
+		/// This method usually returns one rectangle for each line inside the segment
+		/// (but potentially more, e.g. when bidirectional text is involved).
+		/// </summary>
+		public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd);
+		}
+		
+		static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd)
+		{
+			int segmentStart = segment.Offset;
+			int segmentEnd = segment.Offset + segment.Length;
+			
+			segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength);
+			segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength);
+			
+			TextViewPosition start;
+			TextViewPosition end;
+			
+			if (segment is SelectionSegment) {
+				SelectionSegment sel = (SelectionSegment)segment;
+				start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn);
+				end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn);
+			} else {
+				start = new TextViewPosition(textView.Document.GetLocation(segmentStart));
+				end = new TextViewPosition(textView.Document.GetLocation(segmentEnd));
+			}
+			
+			foreach (VisualLine vl in textView.VisualLines) {
+				int vlStartOffset = vl.FirstDocumentLine.Offset;
+				if (vlStartOffset > segmentEnd)
+					break;
+				int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length;
+				if (vlEndOffset < segmentStart)
+					continue;
+				
+				int segmentStartVC;
+				if (segmentStart < vlStartOffset)
+					segmentStartVC = 0;
+				else
+					segmentStartVC = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd);
+				
+				int segmentEndVC;
+				if (segmentEnd > vlEndOffset)
+					segmentEndVC = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker;
+				else
+					segmentEndVC = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd);
+				
+				foreach (var rect in ProcessTextLines(textView, vl, segmentStartVC, segmentEndVC))
+					yield return rect;
+			}
+		}
+		
+		/// <summary>
+		/// Calculates the rectangles for the visual column segment.
+		/// This returns one rectangle for each line inside the segment.
+		/// </summary>
+		public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVC, int endVC)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			if (line == null)
+				throw new ArgumentNullException("line");
+			return ProcessTextLines(textView, line, startVC, endVC);
+		}
+
+		static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVC, int segmentEndVC)
+		{
+			TextLine lastTextLine = visualLine.TextLines.Last();
+			Vector scrollOffset = textView.ScrollOffset;
+			
+			for (int i = 0; i < visualLine.TextLines.Count; i++) {
+				TextLine line = visualLine.TextLines[i];
+				double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop);
+				int visualStartCol = visualLine.GetTextLineVisualStartColumn(line);
+				int visualEndCol = visualStartCol + line.Length;
+				if (line != lastTextLine)
+					visualEndCol -= line.TrailingWhitespaceLength;
+				
+				if (segmentEndVC < visualStartCol)
+					break;
+				if (lastTextLine != line && segmentStartVC > visualEndCol)
+					continue;
+				int segmentStartVCInLine = Math.Max(segmentStartVC, visualStartCol);
+				int segmentEndVCInLine = Math.Min(segmentEndVC, visualEndCol);
+				y -= scrollOffset.Y;
+				if (segmentStartVCInLine == segmentEndVCInLine) {
+					// GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit
+					// We need to return a rectangle to ensure empty lines are still visible
+					double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVCInLine);
+					pos -= scrollOffset.X;
+					// The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active.
+					// If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace.
+					// Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace.
+					if (segmentEndVCInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVC > segmentEndVCInLine && line.TrailingWhitespaceLength == 0)
+						continue;
+					if (segmentStartVCInLine == visualStartCol && i > 0 && segmentStartVC < segmentStartVCInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0)
+						continue;
+					yield return new Rect(pos, y, 1, line.Height);
+				} else {
+					Rect lastRect = Rect.Empty;
+					if (segmentStartVCInLine <= visualEndCol) {
+						foreach (TextBounds b in line.GetTextBounds(segmentStartVCInLine, segmentEndVCInLine - segmentStartVCInLine)) {
+							double left = b.Rectangle.Left - scrollOffset.X;
+							double right = b.Rectangle.Right - scrollOffset.X;
+							if (!lastRect.IsEmpty)
+								yield return lastRect;
+							// left>right is possible in RTL languages
+							lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
+						}
+					}
+					if (segmentEndVC >= visualLine.VisualLengthWithEndOfLineMarker) {
+						double left = (segmentStartVC > visualLine.VisualLengthWithEndOfLineMarker ? visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVC) : line.Width) - scrollOffset.X;
+						double right = ((segmentEndVC == int.MaxValue || line != lastTextLine) ? Math.Max(((IScrollInfo)textView).ExtentWidth, ((IScrollInfo)textView).ViewportWidth) : visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVC)) - scrollOffset.X;
+						Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height);
+						if (!lastRect.IsEmpty) {
+							if (extendSelection.IntersectsWith(lastRect)) {
+								lastRect.Union(extendSelection);
+								yield return lastRect;
+							} else {
+								yield return lastRect;
+								yield return extendSelection;
+							}
+						} else
+							yield return extendSelection;
+					} else
+						yield return lastRect;
+				}
+			}
+		}
+		
+		PathFigureCollection figures = new PathFigureCollection();
+		PathFigure figure;
+		int insertionIndex;
+		double lastTop, lastBottom;
+		double lastLeft, lastRight;
+		
+		/// <summary>
+		/// Adds a rectangle to the geometry.
+		/// </summary>
+		/// <remarks>
+		/// This overload assumes that the coordinates are aligned properly
+		/// (see <see cref="AlignToWholePixels"/>, <see cref="AlignToMiddleOfPixels"/>).
+		/// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned.
+		/// </remarks>
+		public void AddRectangle(double left, double top, double right, double bottom)
+		{
+			if (!top.IsClose(lastBottom)) {
+				CloseFigure();
+			}
+			if (figure == null) {
+				figure = new PathFigure();
+				figure.StartPoint = new Point(left, top + cornerRadius);
+				if (Math.Abs(left - right) > cornerRadius) {
+					figure.Segments.Add(MakeArc(left + cornerRadius, top, SweepDirection.Clockwise));
+					figure.Segments.Add(MakeLineSegment(right - cornerRadius, top));
+					figure.Segments.Add(MakeArc(right, top + cornerRadius, SweepDirection.Clockwise));
+				}
+				figure.Segments.Add(MakeLineSegment(right, bottom - cornerRadius));
+				insertionIndex = figure.Segments.Count;
+				//figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise));
+			} else {
+				if (!lastRight.IsClose(right)) {
+					double cr = right < lastRight ? -cornerRadius : cornerRadius;
+					SweepDirection dir1 = right < lastRight ? SweepDirection.Clockwise : SweepDirection.Counterclockwise;
+					SweepDirection dir2 = right < lastRight ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
+					figure.Segments.Insert(insertionIndex++, MakeArc(lastRight + cr, lastBottom, dir1));
+					figure.Segments.Insert(insertionIndex++, MakeLineSegment(right - cr, top));
+					figure.Segments.Insert(insertionIndex++, MakeArc(right, top + cornerRadius, dir2));
+				}
+				figure.Segments.Insert(insertionIndex++, MakeLineSegment(right, bottom - cornerRadius));
+				figure.Segments.Insert(insertionIndex, MakeLineSegment(lastLeft, lastTop + cornerRadius));
+				if (!lastLeft.IsClose(left)) {
+					double cr = left < lastLeft ? cornerRadius : -cornerRadius;
+					SweepDirection dir1 = left < lastLeft ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
+					SweepDirection dir2 = left < lastLeft ? SweepDirection.Clockwise : SweepDirection.Counterclockwise;
+					figure.Segments.Insert(insertionIndex, MakeArc(lastLeft, lastBottom - cornerRadius, dir1));
+					figure.Segments.Insert(insertionIndex, MakeLineSegment(lastLeft - cr, lastBottom));
+					figure.Segments.Insert(insertionIndex, MakeArc(left + cr, lastBottom, dir2));
+				}
+			}
+			this.lastTop = top;
+			this.lastBottom = bottom;
+			this.lastLeft = left;
+			this.lastRight = right;
+		}
+		
+		ArcSegment MakeArc(double x, double y, SweepDirection dir)
+		{
+			ArcSegment arc = new ArcSegment(
+				new Point(x, y),
+				new Size(cornerRadius, cornerRadius),
+				0, false, dir, true);
+			arc.Freeze();
+			return arc;
+		}
+		
+		static LineSegment MakeLineSegment(double x, double y)
+		{
+			LineSegment ls = new LineSegment(new Point(x, y), true);
+			ls.Freeze();
+			return ls;
+		}
+		
+		/// <summary>
+		/// Closes the current figure.
+		/// </summary>
+		public void CloseFigure()
+		{
+			if (figure != null) {
+				figure.Segments.Insert(insertionIndex, MakeLineSegment(lastLeft, lastTop + cornerRadius));
+				if (Math.Abs(lastLeft - lastRight) > cornerRadius) {
+					figure.Segments.Insert(insertionIndex, MakeArc(lastLeft, lastBottom - cornerRadius, SweepDirection.Clockwise));
+					figure.Segments.Insert(insertionIndex, MakeLineSegment(lastLeft + cornerRadius, lastBottom));
+					figure.Segments.Insert(insertionIndex, MakeArc(lastRight - cornerRadius, lastBottom, SweepDirection.Clockwise));
+				}
+				
+				figure.IsClosed = true;
+				figures.Add(figure);
+				figure = null;
+			}
+		}
+		
+		/// <summary>
+		/// Creates the geometry.
+		/// Returns null when the geometry is empty!
+		/// </summary>
+		public Geometry CreateGeometry()
+		{
+			CloseFigure();
+			if (figures.Count != 0) {
+				PathGeometry g = new PathGeometry(figures);
+				g.Freeze();
+				return g;
+			} else {
+				return null;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/CollapsedLineSection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/CollapsedLineSection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/CollapsedLineSection.cs	(revision 11807)
@@ -0,0 +1,110 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Represents a collapsed line section.
+	/// Use the Uncollapse() method to uncollapse the section.
+	/// </summary>
+	public sealed class CollapsedLineSection
+	{
+		DocumentLine start, end;
+		HeightTree heightTree;
+		
+		#if DEBUG
+		internal string ID;
+		static int nextId;
+		#else
+		const string ID = "";
+		#endif
+		
+		internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
+		{
+			this.heightTree = heightTree;
+			this.start = start;
+			this.end = end;
+			#if DEBUG
+			unchecked {
+				this.ID = " #" + (nextId++);
+			}
+			#endif
+		}
+		
+		/// <summary>
+		/// Gets if the document line is collapsed.
+		/// This property initially is true and turns to false when uncollapsing the section.
+		/// </summary>
+		public bool IsCollapsed {
+			get { return start != null; }
+		}
+		
+		/// <summary>
+		/// Gets the start line of the section.
+		/// When the section is uncollapsed or the text containing it is deleted,
+		/// this property returns null.
+		/// </summary>
+		public DocumentLine Start {
+			get { return start; }
+			internal set { start = value; }
+		}
+		
+		/// <summary>
+		/// Gets the end line of the section.
+		/// When the section is uncollapsed or the text containing it is deleted,
+		/// this property returns null.
+		/// </summary>
+		public DocumentLine End {
+			get { return end; }
+			internal set { end = value; }
+		}
+		
+		/// <summary>
+		/// Uncollapses the section.
+		/// This causes the Start and End properties to be set to null!
+		/// Does nothing if the section is already uncollapsed.
+		/// </summary>
+		public void Uncollapse()
+		{
+			if (start == null)
+				return;
+			
+			heightTree.Uncollapse(this);
+			#if DEBUG
+			heightTree.CheckProperties();
+			#endif
+			
+			start = null;
+			end = null;
+		}
+		
+		/// <summary>
+		/// Gets a string representation of the collapsed section.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
+		public override string ToString()
+		{
+			return "[CollapsedSection" + ID + " Start=" + (start != null ? start.LineNumber.ToString() : "null")
+				+ " End=" + (end != null ? end.LineNumber.ToString() : "null") + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ColorizingTransformer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ColorizingTransformer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ColorizingTransformer.cs	(revision 11807)
@@ -0,0 +1,123 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Base class for <see cref="IVisualLineTransformer"/> that helps
+	/// splitting visual elements so that colors (and other text properties) can be easily assigned
+	/// to individual words/characters.
+	/// </summary>
+	public abstract class ColorizingTransformer : IVisualLineTransformer, ITextViewConnect
+	{
+		/// <summary>
+		/// Gets the list of elements currently being transformed.
+		/// </summary>
+		protected IList<VisualLineElement> CurrentElements { get; private set; }
+		
+		/// <summary>
+		/// <see cref="IVisualLineTransformer.Transform"/> implementation.
+		/// Sets <see cref="CurrentElements"/> and calls <see cref="Colorize"/>.
+		/// </summary>
+		public void Transform(ITextRunConstructionContext context, IList<VisualLineElement> elements)
+		{
+			if (elements == null)
+				throw new ArgumentNullException("elements");
+			if (this.CurrentElements != null)
+				throw new InvalidOperationException("Recursive Transform() call");
+			this.CurrentElements = elements;
+			try {
+				Colorize(context);
+			} finally {
+				this.CurrentElements = null;
+			}
+		}
+		
+		/// <summary>
+		/// Performs the colorization.
+		/// </summary>
+		protected abstract void Colorize(ITextRunConstructionContext context);
+		
+		/// <summary>
+		/// Changes visual element properties.
+		/// This method accesses <see cref="CurrentElements"/>, so it must be called only during
+		/// a <see cref="Transform"/> call.
+		/// This method splits <see cref="VisualLineElement"/>s as necessary to ensure that the region
+		/// can be colored by setting the <see cref="VisualLineElement.TextRunProperties"/> of whole elements,
+		/// and then calls the <paramref name="action"/> on all elements in the region.
+		/// </summary>
+		/// <param name="visualStartColumn">Start visual column of the region to change</param>
+		/// <param name="visualEndColumn">End visual column of the region to change</param>
+		/// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param>
+		protected void ChangeVisualElements(int visualStartColumn, int visualEndColumn, Action<VisualLineElement> action)
+		{
+			if (action == null)
+				throw new ArgumentNullException("action");
+			for (int i = 0; i < CurrentElements.Count; i++) {
+				VisualLineElement e = CurrentElements[i];
+				if (e.VisualColumn > visualEndColumn)
+					break;
+				if (e.VisualColumn < visualStartColumn &&
+				    e.VisualColumn + e.VisualLength > visualStartColumn)
+				{
+					if (e.CanSplit) {
+						e.Split(visualStartColumn, CurrentElements, i--);
+						continue;
+					}
+				}
+				if (e.VisualColumn >= visualStartColumn && e.VisualColumn < visualEndColumn) {
+					if (e.VisualColumn + e.VisualLength > visualEndColumn) {
+						if (e.CanSplit) {
+							e.Split(visualEndColumn, CurrentElements, i--);
+							continue;
+						}
+					} else {
+						action(e);
+					}
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Called when added to a text view.
+		/// </summary>
+		protected virtual void OnAddToTextView(TextView textView)
+		{
+		}
+		
+		/// <summary>
+		/// Called when removed from a text view.
+		/// </summary>
+		protected virtual void OnRemoveFromTextView(TextView textView)
+		{
+		}
+		
+		void ITextViewConnect.AddToTextView(TextView textView)
+		{
+			OnAddToTextView(textView);
+		}
+		
+		void ITextViewConnect.RemoveFromTextView(TextView textView)
+		{
+			OnRemoveFromTextView(textView);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ColumnRulerRenderer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ColumnRulerRenderer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ColumnRulerRenderer.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media;
+
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Renders a ruler at a certain column.
+	/// </summary>
+	sealed class ColumnRulerRenderer : IBackgroundRenderer
+	{
+		Pen pen;
+		int column;
+		TextView textView;
+		
+		public static readonly Color DefaultForeground = Colors.LightGray;
+		
+		public ColumnRulerRenderer(TextView textView)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			
+			this.pen = new Pen(new SolidColorBrush(DefaultForeground), 1);
+			this.pen.Freeze();
+			this.textView = textView;
+			this.textView.BackgroundRenderers.Add(this);
+		}
+		
+		public KnownLayer Layer {
+			get { return KnownLayer.Background; }
+		}
+		
+		public void SetRuler(int column, Pen pen)
+		{
+			if (this.column != column) {
+				this.column = column;
+				textView.InvalidateLayer(this.Layer);
+			}
+			if (this.pen != pen) {
+				this.pen = pen;
+				textView.InvalidateLayer(this.Layer);
+			}
+		}
+		
+		public void Draw(TextView textView, System.Windows.Media.DrawingContext drawingContext)
+		{
+			if (column < 1) return;
+			double offset = textView.WideSpaceWidth * column;
+			Size pixelSize = PixelSnapHelpers.GetPixelSize(textView);
+			double markerXPos = PixelSnapHelpers.PixelAlign(offset, pixelSize.Width);
+			markerXPos -= textView.ScrollOffset.X;
+			Point start = new Point(markerXPos, 0);
+			Point end = new Point(markerXPos, Math.Max(textView.DocumentHeight, textView.ActualHeight));
+			
+			drawingContext.DrawLine(pen, start, end);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/CurrentLineHighlightRenderer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/CurrentLineHighlightRenderer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/CurrentLineHighlightRenderer.cs	(revision 11807)
@@ -0,0 +1,88 @@
+﻿// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
+// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
+
+using System;
+using System.Windows;
+using System.Windows.Media;
+
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	sealed class CurrentLineHighlightRenderer : IBackgroundRenderer
+	{
+		#region Fields
+		
+		int line;
+		TextView textView;
+		
+		public static readonly Color DefaultBackground = Color.FromArgb(22, 20, 220, 224);
+		public static readonly Color DefaultBorder = Color.FromArgb(52, 0, 255, 110);
+		
+		#endregion
+
+		#region Properties
+		
+		public int Line {
+			get { return this.Line; } 
+			set {
+				if (this.line != value) {
+					this.line = value;
+					this.textView.InvalidateLayer(this.Layer);
+				}
+			}
+		}
+		
+		public KnownLayer Layer
+		{
+			get { return KnownLayer.Selection; }
+		}
+		
+		public Brush BackgroundBrush {
+			get; set;
+		}
+		
+		public Pen BorderPen {
+			get; set;
+		}
+		
+		#endregion		
+		
+		public CurrentLineHighlightRenderer(TextView textView)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			
+			this.BorderPen = new Pen(new SolidColorBrush(DefaultBorder), 1);
+			this.BorderPen.Freeze();
+			
+			this.BackgroundBrush = new SolidColorBrush(DefaultBackground);
+			this.BackgroundBrush.Freeze();
+			
+			this.textView = textView;
+			this.textView.BackgroundRenderers.Add(this);
+			
+			this.line = 0;
+		}
+		
+		public void Draw(TextView textView, DrawingContext drawingContext)
+		{
+			if(!this.textView.Options.HighlightCurrentLine)
+				return;
+			
+			BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder();
+			
+			var visualLine = this.textView.GetVisualLine(line);
+			if (visualLine == null) return;
+			
+			var linePosY = visualLine.VisualTop - this.textView.ScrollOffset.Y;
+			
+			builder.AddRectangle(textView, new Rect(0, linePosY, textView.ActualWidth, visualLine.Height));
+			
+			Geometry geometry = builder.CreateGeometry();
+			if (geometry != null) {
+				drawingContext.DrawGeometry(this.BackgroundBrush, this.BorderPen, geometry);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/DefaultTextRunTypographyProperties.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/DefaultTextRunTypographyProperties.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/DefaultTextRunTypographyProperties.cs	(revision 11807)
@@ -0,0 +1,186 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media.TextFormatting;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Default implementation for TextRunTypographyProperties.
+	/// </summary>
+	public class DefaultTextRunTypographyProperties : TextRunTypographyProperties
+	{
+		/// <inheritdoc/>
+		public override FontVariants Variants {
+			get { return FontVariants.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool StylisticSet1 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet2 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet3 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet4 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet5 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet6 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet7 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet8 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet9 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet10 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet11 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet12 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet13 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet14 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet15 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet16 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet17 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet18 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet19 { get { return false; } }
+		/// <inheritdoc/>
+		public override bool StylisticSet20 { get { return false; } }
+		
+		/// <inheritdoc/>
+		public override int StylisticAlternates {
+			get { return 0; }
+		}
+		
+		/// <inheritdoc/>
+		public override int StandardSwashes {
+			get { return 0; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool StandardLigatures {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool SlashedZero {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override FontNumeralStyle NumeralStyle {
+			get { return FontNumeralStyle.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override FontNumeralAlignment NumeralAlignment {
+			get { return FontNumeralAlignment.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool MathematicalGreek {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool Kerning {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool HistoricalLigatures {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool HistoricalForms {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override FontFraction Fraction {
+			get { return FontFraction.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override FontEastAsianWidths EastAsianWidths {
+			get { return FontEastAsianWidths.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override FontEastAsianLanguage EastAsianLanguage {
+			get { return FontEastAsianLanguage.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool EastAsianExpertForms {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool DiscretionaryLigatures {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override int ContextualSwashes {
+			get { return 0; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool ContextualLigatures {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool ContextualAlternates {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool CaseSensitiveForms {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool CapitalSpacing {
+			get { return false; }
+		}
+		
+		/// <inheritdoc/>
+		public override FontCapitals Capitals {
+			get { return FontCapitals.Normal; }
+		}
+		
+		/// <inheritdoc/>
+		public override int AnnotationAlternates {
+			get { return 0; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/DocumentColorizingTransformer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/DocumentColorizingTransformer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/DocumentColorizingTransformer.cs	(revision 11807)
@@ -0,0 +1,98 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Base class for <see cref="IVisualLineTransformer"/> that helps
+	/// colorizing the document. Derived classes can work with document lines
+	/// and text offsets and this class takes care of the visual lines and visual columns.
+	/// </summary>
+	public abstract class DocumentColorizingTransformer : ColorizingTransformer
+	{
+		DocumentLine currentDocumentLine;
+		int firstLineStart;
+		int currentDocumentLineStartOffset, currentDocumentLineEndOffset;
+		
+		/// <summary>
+		/// Gets the current ITextRunConstructionContext.
+		/// </summary>
+		protected ITextRunConstructionContext CurrentContext { get; private set; }
+		
+		/// <inheritdoc/>
+		protected override void Colorize(ITextRunConstructionContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			this.CurrentContext = context;
+			
+			currentDocumentLine = context.VisualLine.FirstDocumentLine;
+			firstLineStart = currentDocumentLineStartOffset = currentDocumentLine.Offset;
+			currentDocumentLineEndOffset = currentDocumentLineStartOffset + currentDocumentLine.Length;
+			int currentDocumentLineTotalEndOffset = currentDocumentLineStartOffset + currentDocumentLine.TotalLength;
+			
+			if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) {
+				ColorizeLine(currentDocumentLine);
+			} else {
+				ColorizeLine(currentDocumentLine);
+				// ColorizeLine modifies the visual line elements, loop through a copy of the line elements
+				foreach (VisualLineElement e in context.VisualLine.Elements.ToArray()) {
+					int elementOffset = firstLineStart + e.RelativeTextOffset;
+					if (elementOffset >= currentDocumentLineTotalEndOffset) {
+						currentDocumentLine = context.Document.GetLineByOffset(elementOffset);
+						currentDocumentLineStartOffset = currentDocumentLine.Offset;
+						currentDocumentLineEndOffset = currentDocumentLineStartOffset + currentDocumentLine.Length;
+						currentDocumentLineTotalEndOffset = currentDocumentLineStartOffset + currentDocumentLine.TotalLength;
+						ColorizeLine(currentDocumentLine);
+					}
+				}
+			}
+			currentDocumentLine = null;
+			this.CurrentContext = null;
+		}
+		
+		/// <summary>
+		/// Override this method to colorize an individual document line.
+		/// </summary>
+		protected abstract void ColorizeLine(DocumentLine line);
+		
+		/// <summary>
+		/// Changes a part of the current document line.
+		/// </summary>
+		/// <param name="startOffset">Start offset of the region to change</param>
+		/// <param name="endOffset">End offset of the region to change</param>
+		/// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param>
+		protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action)
+		{
+			if (startOffset < currentDocumentLineStartOffset || startOffset > currentDocumentLineEndOffset)
+				throw new ArgumentOutOfRangeException("startOffset", startOffset, "Value must be between " + currentDocumentLineStartOffset + " and " + currentDocumentLineEndOffset);
+			if (endOffset < startOffset || endOffset > currentDocumentLineEndOffset)
+				throw new ArgumentOutOfRangeException("endOffset", endOffset, "Value must be between " + startOffset + " and " + currentDocumentLineEndOffset);
+			VisualLine vl = this.CurrentContext.VisualLine;
+			int visualStart = vl.GetVisualColumn(startOffset - firstLineStart);
+			int visualEnd = vl.GetVisualColumn(endOffset - firstLineStart);
+			if (visualStart < visualEnd) {
+				ChangeVisualElements(visualStart, visualEnd, action);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/FormattedTextElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/FormattedTextElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/FormattedTextElement.cs	(revision 11807)
@@ -0,0 +1,222 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Formatted text (not normal document text).
+	/// This is used as base class for various VisualLineElements that are displayed using a
+	/// FormattedText, for example newline markers or collapsed folding sections.
+	/// </summary>
+	public class FormattedTextElement : VisualLineElement
+	{
+		internal readonly FormattedText formattedText;
+		internal string text;
+		internal TextLine textLine;
+		
+		/// <summary>
+		/// Creates a new FormattedTextElement that displays the specified text
+		/// and occupies the specified length in the document.
+		/// </summary>
+		public FormattedTextElement(string text, int documentLength) : base(1, documentLength)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+			this.BreakBefore = LineBreakCondition.BreakPossible;
+			this.BreakAfter = LineBreakCondition.BreakPossible;
+		}
+		
+		/// <summary>
+		/// Creates a new FormattedTextElement that displays the specified text
+		/// and occupies the specified length in the document.
+		/// </summary>
+		public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.textLine = text;
+			this.BreakBefore = LineBreakCondition.BreakPossible;
+			this.BreakAfter = LineBreakCondition.BreakPossible;
+		}
+		
+		/// <summary>
+		/// Creates a new FormattedTextElement that displays the specified text
+		/// and occupies the specified length in the document.
+		/// </summary>
+		public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.formattedText = text;
+			this.BreakBefore = LineBreakCondition.BreakPossible;
+			this.BreakAfter = LineBreakCondition.BreakPossible;
+		}
+		
+		/// <summary>
+		/// Gets/sets the line break condition before the element.
+		/// The default is 'BreakPossible'.
+		/// </summary>
+		public LineBreakCondition BreakBefore { get; set; }
+		
+		/// <summary>
+		/// Gets/sets the line break condition after the element.
+		/// The default is 'BreakPossible'.
+		/// </summary>
+		public LineBreakCondition BreakAfter { get; set; }
+		
+		/// <inheritdoc/>
+		public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+		{
+			if (textLine == null) {
+				var formatter = TextFormatterFactory.Create(context.TextView);
+				textLine = PrepareText(formatter, this.text, this.TextRunProperties);
+				this.text = null;
+			}
+			return new FormattedTextRun(this, this.TextRunProperties);
+		}
+		
+		/// <summary>
+		/// Constructs a TextLine from a simple text.
+		/// </summary>
+		public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties)
+		{
+			if (formatter == null)
+				throw new ArgumentNullException("formatter");
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (properties == null)
+				throw new ArgumentNullException("properties");
+			return formatter.FormatLine(
+				new SimpleTextSource(text, properties),
+				0,
+				32000,
+				new VisualLineTextParagraphProperties {
+					defaultTextRunProperties = properties,
+					textWrapping = TextWrapping.NoWrap,
+					tabSize = 40
+				},
+				null);
+		}
+	}
+	
+	/// <summary>
+	/// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class.
+	/// </summary>
+	public class FormattedTextRun : TextEmbeddedObject
+	{
+		readonly FormattedTextElement element;
+		TextRunProperties properties;
+		
+		/// <summary>
+		/// Creates a new FormattedTextRun.
+		/// </summary>
+		public FormattedTextRun(FormattedTextElement element, TextRunProperties properties)
+		{
+			if (element == null)
+				throw new ArgumentNullException("element");
+			if (properties == null)
+				throw new ArgumentNullException("properties");
+			this.properties = properties;
+			this.element = element;
+		}
+		
+		/// <summary>
+		/// Gets the element for which the FormattedTextRun was created.
+		/// </summary>
+		public FormattedTextElement Element {
+			get { return element; }
+		}
+		
+		/// <inheritdoc/>
+		public override LineBreakCondition BreakBefore {
+			get { return element.BreakBefore; }
+		}
+		
+		/// <inheritdoc/>
+		public override LineBreakCondition BreakAfter {
+			get { return element.BreakAfter; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool HasFixedSize {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override CharacterBufferReference CharacterBufferReference {
+			get { return new CharacterBufferReference(); }
+		}
+		
+		/// <inheritdoc/>
+		public override int Length {
+			get { return element.VisualLength; }
+		}
+		
+		/// <inheritdoc/>
+		public override TextRunProperties Properties {
+			get { return properties; }
+		}
+		
+		/// <inheritdoc/>
+		public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth)
+		{
+			var formattedText = element.formattedText;
+			if (formattedText != null) {
+				return new TextEmbeddedObjectMetrics(formattedText.WidthIncludingTrailingWhitespace,
+				                                     formattedText.Height,
+				                                     formattedText.Baseline);
+			} else {
+				var text = element.textLine;
+				return new TextEmbeddedObjectMetrics(text.WidthIncludingTrailingWhitespace,
+				                                     text.Height,
+				                                     text.Baseline);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways)
+		{
+			var formattedText = element.formattedText;
+			if (formattedText != null) {
+				return new Rect(0, 0, formattedText.WidthIncludingTrailingWhitespace, formattedText.Height);
+			} else {
+				var text = element.textLine;
+				return new Rect(0, 0, text.WidthIncludingTrailingWhitespace, text.Height);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways)
+		{
+			if (element.formattedText != null) {
+				origin.Y -= element.formattedText.Baseline;
+				drawingContext.DrawText(element.formattedText, origin);
+			} else {
+				origin.Y -= element.textLine.Baseline;
+				element.textLine.Draw(drawingContext, origin, InvertAxes.None);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/GlobalTextRunProperties.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/GlobalTextRunProperties.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/GlobalTextRunProperties.cs	(revision 11807)
@@ -0,0 +1,43 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	sealed class GlobalTextRunProperties : TextRunProperties
+	{
+		internal Typeface typeface;
+		internal double fontRenderingEmSize;
+		internal Brush foregroundBrush;
+		internal Brush backgroundBrush;
+		internal System.Globalization.CultureInfo cultureInfo;
+		
+		public override Typeface Typeface { get { return typeface; } }
+		public override double FontRenderingEmSize { get { return fontRenderingEmSize; } }
+		public override double FontHintingEmSize { get { return fontRenderingEmSize; } }
+		public override TextDecorationCollection TextDecorations { get { return null; } }
+		public override Brush ForegroundBrush { get { return foregroundBrush; } }
+		public override Brush BackgroundBrush { get { return backgroundBrush; } }
+		public override System.Globalization.CultureInfo CultureInfo { get { return cultureInfo; } }
+		public override TextEffectCollection TextEffects { get { return null; } }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTree.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTree.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTree.cs	(revision 11807)
@@ -0,0 +1,1111 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
+	/// </summary>
+	sealed class HeightTree : ILineTracker, IDisposable
+	{
+		// TODO: Optimize this. This tree takes alot of memory.
+		// (56 bytes for HeightTreeNode
+		// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
+		// And we might do much better by compressing lines with the same height into a single node.
+		// That would also improve load times because we would always start with just a single node.
+		
+		/* Idea:
+		 class NewHeightTreeNode {
+			int totalCount; // =count+left.count+right.count
+			int count; // one node can represent multiple lines
+			double height; // height of each line in this node
+			double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
+			List<CollapsedSection> collapsedSections; // sections holding this line collapsed
+			// no "nodeCollapsedSections"/"totalCollapsedSections":
+			NewHeightTreeNode left, right, parent;
+			bool color;
+		}
+		totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
+		 collapsing/uncollapsing, especially when compression reduces the n.
+		 */
+		
+		#region Constructor
+		readonly TextDocument document;
+		HeightTreeNode root;
+		WeakLineTracker weakLineTracker;
+		
+		public HeightTree(TextDocument document, double defaultLineHeight)
+		{
+			this.document = document;
+			weakLineTracker = WeakLineTracker.Register(document, this);
+			this.DefaultLineHeight = defaultLineHeight;
+			RebuildDocument();
+		}
+		
+		public void Dispose()
+		{
+			if (weakLineTracker != null)
+				weakLineTracker.Deregister();
+			this.root = null;
+			this.weakLineTracker = null;
+		}
+		
+		double defaultLineHeight;
+		
+		public double DefaultLineHeight {
+			get { return defaultLineHeight; }
+			set {
+				double oldValue = defaultLineHeight;
+				if (oldValue == value)
+					return;
+				defaultLineHeight = value;
+				// update the stored value in all nodes:
+				foreach (var node in AllNodes) {
+					if (node.lineNode.height == oldValue) {
+						node.lineNode.height = value;
+						UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
+					}
+				}
+			}
+		}
+		
+		HeightTreeNode GetNode(DocumentLine ls)
+		{
+			return GetNodeByIndex(ls.LineNumber - 1);
+		}
+		#endregion
+		
+		#region RebuildDocument
+		void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
+		{
+		}
+		
+		void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
+		{
+		}
+		
+		/// <summary>
+		/// Rebuild the tree, in O(n).
+		/// </summary>
+		public void RebuildDocument()
+		{
+			foreach (CollapsedLineSection s in GetAllCollapsedSections()) {
+				s.Start = null;
+				s.End = null;
+			}
+			
+			HeightTreeNode[] nodes = new HeightTreeNode[document.LineCount];
+			int lineNumber = 0;
+			foreach (DocumentLine ls in document.Lines) {
+				nodes[lineNumber++] = new HeightTreeNode(ls, defaultLineHeight);
+			}
+			Debug.Assert(nodes.Length > 0);
+			// now build the corresponding balanced tree
+			int height = DocumentLineTree.GetTreeHeight(nodes.Length);
+			Debug.WriteLine("HeightTree will have height: " + height);
+			root = BuildTree(nodes, 0, nodes.Length, height);
+			root.color = BLACK;
+			#if DEBUG
+			CheckProperties();
+			#endif
+		}
+		
+		/// <summary>
+		/// build a tree from a list of nodes
+		/// </summary>
+		HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
+		{
+			Debug.Assert(start <= end);
+			if (start == end) {
+				return null;
+			}
+			int middle = (start + end) / 2;
+			HeightTreeNode node = nodes[middle];
+			node.left = BuildTree(nodes, start, middle, subtreeHeight - 1);
+			node.right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
+			if (node.left != null) node.left.parent = node;
+			if (node.right != null) node.right.parent = node;
+			if (subtreeHeight == 1)
+				node.color = RED;
+			UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
+			return node;
+		}
+		#endregion
+		
+		#region Insert/Remove lines
+		void ILineTracker.BeforeRemoveLine(DocumentLine line)
+		{
+			HeightTreeNode node = GetNode(line);
+			if (node.lineNode.collapsedSections != null) {
+				foreach (CollapsedLineSection cs in node.lineNode.collapsedSections.ToArray()) {
+					if (cs.Start == line && cs.End == line) {
+						cs.Start = null;
+						cs.End = null;
+					} else if (cs.Start == line) {
+						Uncollapse(cs);
+						cs.Start = line.NextLine;
+						AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
+					} else if (cs.End == line) {
+						Uncollapse(cs);
+						cs.End = line.PreviousLine;
+						AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
+					}
+				}
+			}
+			BeginRemoval();
+			RemoveNode(node);
+			// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
+			node.lineNode.collapsedSections = null;
+			EndRemoval();
+		}
+		
+//		void ILineTracker.AfterRemoveLine(DocumentLine line)
+//		{
+//
+//		}
+		
+		void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
+		{
+			InsertAfter(GetNode(insertionPos), newLine);
+			#if DEBUG
+			CheckProperties();
+			#endif
+		}
+		
+		HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
+		{
+			HeightTreeNode newNode = new HeightTreeNode(newLine, defaultLineHeight);
+			if (node.right == null) {
+				if (node.lineNode.collapsedSections != null) {
+					// we are inserting directly after node - so copy all collapsedSections
+					// that do not end at node.
+					foreach (CollapsedLineSection cs in node.lineNode.collapsedSections) {
+						if (cs.End != node.documentLine)
+							newNode.AddDirectlyCollapsed(cs);
+					}
+				}
+				InsertAsRight(node, newNode);
+			} else {
+				node = node.right.LeftMost;
+				if (node.lineNode.collapsedSections != null) {
+					// we are inserting directly before node - so copy all collapsedSections
+					// that do not start at node.
+					foreach (CollapsedLineSection cs in node.lineNode.collapsedSections) {
+						if (cs.Start != node.documentLine)
+							newNode.AddDirectlyCollapsed(cs);
+					}
+				}
+				InsertAsLeft(node, newNode);
+			}
+			return newNode;
+		}
+		#endregion
+		
+		#region Rotation callbacks
+		enum UpdateAfterChildrenChangeRecursionMode
+		{
+			None,
+			IfRequired,
+			WholeBranch
+		}
+		
+		static void UpdateAfterChildrenChange(HeightTreeNode node)
+		{
+			UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
+		}
+		
+		static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
+		{
+			int totalCount = 1;
+			double totalHeight = node.lineNode.TotalHeight;
+			if (node.left != null) {
+				totalCount += node.left.totalCount;
+				totalHeight += node.left.totalHeight;
+			}
+			if (node.right != null) {
+				totalCount += node.right.totalCount;
+				totalHeight += node.right.totalHeight;
+			}
+			if (node.IsDirectlyCollapsed)
+				totalHeight = 0;
+			if (totalCount != node.totalCount
+			    || !totalHeight.IsClose(node.totalHeight)
+			    || mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
+			{
+				node.totalCount = totalCount;
+				node.totalHeight = totalHeight;
+				if (node.parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
+					UpdateAugmentedData(node.parent, mode);
+			}
+		}
+		
+		void UpdateAfterRotateLeft(HeightTreeNode node)
+		{
+			// node = old parent
+			// node.parent = pivot, new parent
+			var collapsedP = node.parent.collapsedSections;
+			var collapsedQ = node.collapsedSections;
+			// move collapsedSections from old parent to new parent
+			node.parent.collapsedSections = collapsedQ;
+			node.collapsedSections = null;
+			// split the collapsedSections from the new parent into its old children:
+			if (collapsedP != null) {
+				foreach (CollapsedLineSection cs in collapsedP) {
+					if (node.parent.right != null)
+						node.parent.right.AddDirectlyCollapsed(cs);
+					node.parent.lineNode.AddDirectlyCollapsed(cs);
+					if (node.right != null)
+						node.right.AddDirectlyCollapsed(cs);
+				}
+			}
+			MergeCollapsedSectionsIfPossible(node);
+			
+			UpdateAfterChildrenChange(node);
+			
+			// not required: rotations only happen on insertions/deletions
+			// -> totalCount changes -> the parent is always updated
+			//UpdateAfterChildrenChange(node.parent);
+		}
+		
+		void UpdateAfterRotateRight(HeightTreeNode node)
+		{
+			// node = old parent
+			// node.parent = pivot, new parent
+			var collapsedP = node.parent.collapsedSections;
+			var collapsedQ = node.collapsedSections;
+			// move collapsedSections from old parent to new parent
+			node.parent.collapsedSections = collapsedQ;
+			node.collapsedSections = null;
+			// split the collapsedSections from the new parent into its old children:
+			if (collapsedP != null) {
+				foreach (CollapsedLineSection cs in collapsedP) {
+					if (node.parent.left != null)
+						node.parent.left.AddDirectlyCollapsed(cs);
+					node.parent.lineNode.AddDirectlyCollapsed(cs);
+					if (node.left != null)
+						node.left.AddDirectlyCollapsed(cs);
+				}
+			}
+			MergeCollapsedSectionsIfPossible(node);
+			
+			UpdateAfterChildrenChange(node);
+			
+			// not required: rotations only happen on insertions/deletions
+			// -> totalCount changes -> the parent is always updated
+			//UpdateAfterChildrenChange(node.parent);
+		}
+		
+		// node removal:
+		// a node in the middle of the tree is removed as following:
+		//  its successor is removed
+		//  it is replaced with its successor
+		
+		void BeforeNodeRemove(HeightTreeNode removedNode)
+		{
+			Debug.Assert(removedNode.left == null || removedNode.right == null);
+			
+			var collapsed = removedNode.collapsedSections;
+			if (collapsed != null) {
+				HeightTreeNode childNode = removedNode.left ?? removedNode.right;
+				if (childNode != null) {
+					foreach (CollapsedLineSection cs in collapsed)
+						childNode.AddDirectlyCollapsed(cs);
+				}
+			}
+			if (removedNode.parent != null)
+				MergeCollapsedSectionsIfPossible(removedNode.parent);
+		}
+		
+		void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
+		{
+			Debug.Assert(removedNode != null);
+			Debug.Assert(newNode != null);
+			while (newNodeOldParent != removedNode) {
+				if (newNodeOldParent.collapsedSections != null) {
+					foreach (CollapsedLineSection cs in newNodeOldParent.collapsedSections) {
+						newNode.lineNode.AddDirectlyCollapsed(cs);
+					}
+				}
+				newNodeOldParent = newNodeOldParent.parent;
+			}
+			if (newNode.collapsedSections != null) {
+				foreach (CollapsedLineSection cs in newNode.collapsedSections) {
+					newNode.lineNode.AddDirectlyCollapsed(cs);
+				}
+			}
+			newNode.collapsedSections = removedNode.collapsedSections;
+			MergeCollapsedSectionsIfPossible(newNode);
+		}
+		
+		bool inRemoval;
+		List<HeightTreeNode> nodesToCheckForMerging;
+		
+		void BeginRemoval()
+		{
+			Debug.Assert(!inRemoval);
+			if (nodesToCheckForMerging == null) {
+				nodesToCheckForMerging = new List<HeightTreeNode>();
+			}
+			inRemoval = true;
+		}
+		
+		void EndRemoval()
+		{
+			Debug.Assert(inRemoval);
+			inRemoval = false;
+			foreach (HeightTreeNode node in nodesToCheckForMerging) {
+				MergeCollapsedSectionsIfPossible(node);
+			}
+			nodesToCheckForMerging.Clear();
+		}
+		
+		void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
+		{
+			Debug.Assert(node != null);
+			if (inRemoval) {
+				nodesToCheckForMerging.Add(node);
+				return;
+			}
+			// now check if we need to merge collapsedSections together
+			bool merged = false;
+			var collapsedL = node.lineNode.collapsedSections;
+			if (collapsedL != null) {
+				for (int i = collapsedL.Count - 1; i >= 0; i--) {
+					CollapsedLineSection cs = collapsedL[i];
+					if (cs.Start == node.documentLine || cs.End == node.documentLine)
+						continue;
+					if (node.left == null
+					    || (node.left.collapsedSections != null && node.left.collapsedSections.Contains(cs)))
+					{
+						if (node.right == null
+						    || (node.right.collapsedSections != null && node.right.collapsedSections.Contains(cs)))
+						{
+							// all children of node contain cs: -> merge!
+							if (node.left != null) node.left.RemoveDirectlyCollapsed(cs);
+							if (node.right != null) node.right.RemoveDirectlyCollapsed(cs);
+							collapsedL.RemoveAt(i);
+							node.AddDirectlyCollapsed(cs);
+							merged = true;
+						}
+					}
+				}
+				if (collapsedL.Count == 0)
+					node.lineNode.collapsedSections = null;
+			}
+			if (merged && node.parent != null) {
+				MergeCollapsedSectionsIfPossible(node.parent);
+			}
+		}
+		#endregion
+		
+		#region GetNodeBy... / Get...FromNode
+		HeightTreeNode GetNodeByIndex(int index)
+		{
+			Debug.Assert(index >= 0);
+			Debug.Assert(index < root.totalCount);
+			HeightTreeNode node = root;
+			while (true) {
+				if (node.left != null && index < node.left.totalCount) {
+					node = node.left;
+				} else {
+					if (node.left != null) {
+						index -= node.left.totalCount;
+					}
+					if (index == 0)
+						return node;
+					index--;
+					node = node.right;
+				}
+			}
+		}
+		
+		HeightTreeNode GetNodeByVisualPosition(double position)
+		{
+			HeightTreeNode node = root;
+			while (true) {
+				double positionAfterLeft = position;
+				if (node.left != null) {
+					positionAfterLeft -= node.left.totalHeight;
+					if (positionAfterLeft < 0) {
+						// Descend into left
+						node = node.left;
+						continue;
+					}
+				}
+				double positionBeforeRight = positionAfterLeft - node.lineNode.TotalHeight;
+				if (positionBeforeRight < 0) {
+					// Found the correct node
+					return node;
+				}
+				if (node.right == null || node.right.totalHeight == 0) {
+					// Can happen when position>node.totalHeight,
+					// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
+					
+					// If node.lineNode isn't collapsed, return that.
+					// Also return node.lineNode if there is no previous node that we could return instead.
+					if (node.lineNode.TotalHeight > 0 || node.left == null)
+						return node;
+					// Otherwise, descend into left (find the last non-collapsed node)
+					node = node.left;
+				} else {
+					// Descend into right
+					position = positionBeforeRight;
+					node = node.right;
+				}
+			}
+		}
+		
+		static double GetVisualPositionFromNode(HeightTreeNode node)
+		{
+			double position = (node.left != null) ? node.left.totalHeight : 0;
+			while (node.parent != null) {
+				if (node.IsDirectlyCollapsed)
+					position = 0;
+				if (node == node.parent.right) {
+					if (node.parent.left != null)
+						position += node.parent.left.totalHeight;
+					position += node.parent.lineNode.TotalHeight;
+				}
+				node = node.parent;
+			}
+			return position;
+		}
+		#endregion
+		
+		#region Public methods
+		public DocumentLine GetLineByNumber(int number)
+		{
+			return GetNodeByIndex(number - 1).documentLine;
+		}
+		
+		public DocumentLine GetLineByVisualPosition(double position)
+		{
+			return GetNodeByVisualPosition(position).documentLine;
+		}
+		
+		public double GetVisualPosition(DocumentLine line)
+		{
+			return GetVisualPositionFromNode(GetNode(line));
+		}
+		
+		public double GetHeight(DocumentLine line)
+		{
+			return GetNode(line).lineNode.height;
+		}
+		
+		public void SetHeight(DocumentLine line, double val)
+		{
+			var node = GetNode(line);
+			node.lineNode.height = val;
+			UpdateAfterChildrenChange(node);
+		}
+		
+		public bool GetIsCollapsed(int lineNumber)
+		{
+			var node = GetNodeByIndex(lineNumber - 1);
+			return node.lineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
+		}
+		
+		/// <summary>
+		/// Collapses the specified text section.
+		/// Runtime: O(log n)
+		/// </summary>
+		public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
+		{
+			if (!document.Lines.Contains(start))
+				throw new ArgumentException("Line is not part of this document", "start");
+			if (!document.Lines.Contains(end))
+				throw new ArgumentException("Line is not part of this document", "end");
+			int length = end.LineNumber - start.LineNumber + 1;
+			if (length < 0)
+				throw new ArgumentException("start must be a line before end");
+			CollapsedLineSection section = new CollapsedLineSection(this, start, end);
+			AddCollapsedSection(section, length);
+			#if DEBUG
+			CheckProperties();
+			#endif
+			return section;
+		}
+		#endregion
+		
+		#region LineCount & TotalHeight
+		public int LineCount {
+			get {
+				return root.totalCount;
+			}
+		}
+		
+		public double TotalHeight {
+			get {
+				return root.totalHeight;
+			}
+		}
+		#endregion
+		
+		#region GetAllCollapsedSections
+		IEnumerable<HeightTreeNode> AllNodes {
+			get {
+				if (root != null) {
+					HeightTreeNode node = root.LeftMost;
+					while (node != null) {
+						yield return node;
+						node = node.Successor;
+					}
+				}
+			}
+		}
+		
+		internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
+		{
+			List<CollapsedLineSection> emptyCSList = new List<CollapsedLineSection>();
+			return System.Linq.Enumerable.Distinct(
+				System.Linq.Enumerable.SelectMany(
+					AllNodes, node => System.Linq.Enumerable.Concat(node.lineNode.collapsedSections ?? emptyCSList,
+					                                                node.collapsedSections ?? emptyCSList)
+				));
+		}
+		#endregion
+		
+		#region CheckProperties
+		#if DEBUG
+		[Conditional("DATACONSISTENCYTEST")]
+		internal void CheckProperties()
+		{
+			CheckProperties(root);
+			
+			foreach (CollapsedLineSection cs in GetAllCollapsedSections()) {
+				Debug.Assert(GetNode(cs.Start).lineNode.collapsedSections.Contains(cs));
+				Debug.Assert(GetNode(cs.End).lineNode.collapsedSections.Contains(cs));
+				int endLine = cs.End.LineNumber;
+				for (int i = cs.Start.LineNumber; i <= endLine; i++) {
+					CheckIsInSection(cs, GetLineByNumber(i));
+				}
+			}
+			
+			// check red-black property:
+			int blackCount = -1;
+			CheckNodeProperties(root, null, RED, 0, ref blackCount);
+		}
+		
+		void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
+		{
+			HeightTreeNode node = GetNode(line);
+			if (node.lineNode.collapsedSections != null && node.lineNode.collapsedSections.Contains(cs))
+				return;
+			while (node != null) {
+				if (node.collapsedSections != null && node.collapsedSections.Contains(cs))
+					return;
+				node = node.parent;
+			}
+			throw new InvalidOperationException(cs + " not found for line " + line);
+		}
+		
+		void CheckProperties(HeightTreeNode node)
+		{
+			int totalCount = 1;
+			double totalHeight = node.lineNode.TotalHeight;
+			if (node.lineNode.IsDirectlyCollapsed)
+				Debug.Assert(node.lineNode.collapsedSections.Count > 0);
+			if (node.left != null) {
+				CheckProperties(node.left);
+				totalCount += node.left.totalCount;
+				totalHeight += node.left.totalHeight;
+				
+				CheckAllContainedIn(node.left.collapsedSections, node.lineNode.collapsedSections);
+			}
+			if (node.right != null) {
+				CheckProperties(node.right);
+				totalCount += node.right.totalCount;
+				totalHeight += node.right.totalHeight;
+				
+				CheckAllContainedIn(node.right.collapsedSections, node.lineNode.collapsedSections);
+			}
+			if (node.left != null && node.right != null) {
+				if (node.left.collapsedSections != null && node.right.collapsedSections != null) {
+					var intersection = System.Linq.Enumerable.Intersect(node.left.collapsedSections, node.right.collapsedSections);
+					Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
+				}
+			}
+			if (node.IsDirectlyCollapsed) {
+				Debug.Assert(node.collapsedSections.Count > 0);
+				totalHeight = 0;
+			}
+			Debug.Assert(node.totalCount == totalCount);
+			Debug.Assert(node.totalHeight.IsClose(totalHeight));
+		}
+		
+		/// <summary>
+		/// Checks that all elements in list1 are contained in list2.
+		/// </summary>
+		static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
+		{
+			if (list1 == null) list1 = new List<CollapsedLineSection>();
+			if (list2 == null) list2 = new List<CollapsedLineSection>();
+			foreach (CollapsedLineSection cs in list1) {
+				Debug.Assert(list2.Contains(cs));
+			}
+		}
+		
+		/*
+		1. A node is either red or black.
+		2. The root is black.
+		3. All leaves are black. (The leaves are the NIL children.)
+		4. Both children of every red node are black. (So every red node must have a black parent.)
+		5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
+		 */
+		void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
+		{
+			if (node == null) return;
+			
+			Debug.Assert(node.parent == parentNode);
+			
+			if (parentColor == RED) {
+				Debug.Assert(node.color == BLACK);
+			}
+			if (node.color == BLACK) {
+				blackCount++;
+			}
+			if (node.left == null && node.right == null) {
+				// node is a leaf node:
+				if (expectedBlackCount == -1)
+					expectedBlackCount = blackCount;
+				else
+					Debug.Assert(expectedBlackCount == blackCount);
+			}
+			CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
+			CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+		public string GetTreeAsString()
+		{
+			StringBuilder b = new StringBuilder();
+			AppendTreeToString(root, b, 0);
+			return b.ToString();
+		}
+		
+		static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
+		{
+			if (node.color == RED)
+				b.Append("RED   ");
+			else
+				b.Append("BLACK ");
+			b.AppendLine(node.ToString());
+			indent += 2;
+			if (node.left != null) {
+				b.Append(' ', indent);
+				b.Append("L: ");
+				AppendTreeToString(node.left, b, indent);
+			}
+			if (node.right != null) {
+				b.Append(' ', indent);
+				b.Append("R: ");
+				AppendTreeToString(node.right, b, indent);
+			}
+		}
+		#endif
+		#endregion
+		
+		#region Red/Black Tree
+		const bool RED = true;
+		const bool BLACK = false;
+		
+		void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
+		{
+			Debug.Assert(parentNode.left == null);
+			parentNode.left = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAfterChildrenChange(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
+		{
+			Debug.Assert(parentNode.right == null);
+			parentNode.right = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAfterChildrenChange(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void FixTreeOnInsert(HeightTreeNode node)
+		{
+			Debug.Assert(node != null);
+			Debug.Assert(node.color == RED);
+			Debug.Assert(node.left == null || node.left.color == BLACK);
+			Debug.Assert(node.right == null || node.right.color == BLACK);
+			
+			HeightTreeNode parentNode = node.parent;
+			if (parentNode == null) {
+				// we inserted in the root -> the node must be black
+				// since this is a root node, making the node black increments the number of black nodes
+				// on all paths by one, so it is still the same for all paths.
+				node.color = BLACK;
+				return;
+			}
+			if (parentNode.color == BLACK) {
+				// if the parent node where we inserted was black, our red node is placed correctly.
+				// since we inserted a red node, the number of black nodes on each path is unchanged
+				// -> the tree is still balanced
+				return;
+			}
+			// parentNode is red, so there is a conflict here!
+			
+			// because the root is black, parentNode is not the root -> there is a grandparent node
+			HeightTreeNode grandparentNode = parentNode.parent;
+			HeightTreeNode uncleNode = Sibling(parentNode);
+			if (uncleNode != null && uncleNode.color == RED) {
+				parentNode.color = BLACK;
+				uncleNode.color = BLACK;
+				grandparentNode.color = RED;
+				FixTreeOnInsert(grandparentNode);
+				return;
+			}
+			// now we know: parent is red but uncle is black
+			// First rotation:
+			if (node == parentNode.right && parentNode == grandparentNode.left) {
+				RotateLeft(parentNode);
+				node = node.left;
+			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
+				RotateRight(parentNode);
+				node = node.right;
+			}
+			// because node might have changed, reassign variables:
+			parentNode = node.parent;
+			grandparentNode = parentNode.parent;
+			
+			// Now recolor a bit:
+			parentNode.color = BLACK;
+			grandparentNode.color = RED;
+			// Second rotation:
+			if (node == parentNode.left && parentNode == grandparentNode.left) {
+				RotateRight(grandparentNode);
+			} else {
+				// because of the first rotation, this is guaranteed:
+				Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
+				RotateLeft(grandparentNode);
+			}
+		}
+		
+		void RemoveNode(HeightTreeNode removedNode)
+		{
+			if (removedNode.left != null && removedNode.right != null) {
+				// replace removedNode with it's in-order successor
+				
+				HeightTreeNode leftMost = removedNode.right.LeftMost;
+				HeightTreeNode parentOfLeftMost = leftMost.parent;
+				RemoveNode(leftMost); // remove leftMost from its current location
+				
+				BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
+				// and overwrite the removedNode with it
+				ReplaceNode(removedNode, leftMost);
+				leftMost.left = removedNode.left;
+				if (leftMost.left != null) leftMost.left.parent = leftMost;
+				leftMost.right = removedNode.right;
+				if (leftMost.right != null) leftMost.right.parent = leftMost;
+				leftMost.color = removedNode.color;
+				
+				UpdateAfterChildrenChange(leftMost);
+				if (leftMost.parent != null) UpdateAfterChildrenChange(leftMost.parent);
+				return;
+			}
+			
+			// now either removedNode.left or removedNode.right is null
+			// get the remaining child
+			HeightTreeNode parentNode = removedNode.parent;
+			HeightTreeNode childNode = removedNode.left ?? removedNode.right;
+			BeforeNodeRemove(removedNode);
+			ReplaceNode(removedNode, childNode);
+			if (parentNode != null) UpdateAfterChildrenChange(parentNode);
+			if (removedNode.color == BLACK) {
+				if (childNode != null && childNode.color == RED) {
+					childNode.color = BLACK;
+				} else {
+					FixTreeOnDelete(childNode, parentNode);
+				}
+			}
+		}
+		
+		void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (parentNode == null)
+				return;
+			
+			// warning: node may be null
+			HeightTreeNode sibling = Sibling(node, parentNode);
+			if (sibling.color == RED) {
+				parentNode.color = RED;
+				sibling.color = BLACK;
+				if (node == parentNode.left) {
+					RotateLeft(parentNode);
+				} else {
+					RotateRight(parentNode);
+				}
+				
+				sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			}
+			
+			if (parentNode.color == BLACK
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				FixTreeOnDelete(parentNode, parentNode.parent);
+				return;
+			}
+			
+			if (parentNode.color == RED
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				parentNode.color = BLACK;
+				return;
+			}
+			
+			if (node == parentNode.left &&
+			    sibling.color == BLACK &&
+			    GetColor(sibling.left) == RED &&
+			    GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.left.color = BLACK;
+				RotateRight(sibling);
+			}
+			else if (node == parentNode.right &&
+			         sibling.color == BLACK &&
+			         GetColor(sibling.right) == RED &&
+			         GetColor(sibling.left) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.right.color = BLACK;
+				RotateLeft(sibling);
+			}
+			sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			
+			sibling.color = parentNode.color;
+			parentNode.color = BLACK;
+			if (node == parentNode.left) {
+				if (sibling.right != null) {
+					Debug.Assert(sibling.right.color == RED);
+					sibling.right.color = BLACK;
+				}
+				RotateLeft(parentNode);
+			} else {
+				if (sibling.left != null) {
+					Debug.Assert(sibling.left.color == RED);
+					sibling.left.color = BLACK;
+				}
+				RotateRight(parentNode);
+			}
+		}
+		
+		void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
+		{
+			if (replacedNode.parent == null) {
+				Debug.Assert(replacedNode == root);
+				root = newNode;
+			} else {
+				if (replacedNode.parent.left == replacedNode)
+					replacedNode.parent.left = newNode;
+				else
+					replacedNode.parent.right = newNode;
+			}
+			if (newNode != null) {
+				newNode.parent = replacedNode.parent;
+			}
+			replacedNode.parent = null;
+		}
+		
+		void RotateLeft(HeightTreeNode p)
+		{
+			// let q be p's right child
+			HeightTreeNode q = p.right;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's right child to be q's left child
+			p.right = q.left;
+			if (p.right != null) p.right.parent = p;
+			// set q's left child to be p
+			q.left = p;
+			p.parent = q;
+			UpdateAfterRotateLeft(p);
+		}
+		
+		void RotateRight(HeightTreeNode p)
+		{
+			// let q be p's left child
+			HeightTreeNode q = p.left;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's left child to be q's right child
+			p.left = q.right;
+			if (p.left != null) p.left.parent = p;
+			// set q's right child to be p
+			q.right = p;
+			p.parent = q;
+			UpdateAfterRotateRight(p);
+		}
+		
+		static HeightTreeNode Sibling(HeightTreeNode node)
+		{
+			if (node == node.parent.left)
+				return node.parent.right;
+			else
+				return node.parent.left;
+		}
+		
+		static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (node == parentNode.left)
+				return parentNode.right;
+			else
+				return parentNode.left;
+		}
+		
+		static bool GetColor(HeightTreeNode node)
+		{
+			return node != null ? node.color : BLACK;
+		}
+		#endregion
+		
+		#region Collapsing support
+		static bool GetIsCollapedFromNode(HeightTreeNode node)
+		{
+			while (node != null) {
+				if (node.IsDirectlyCollapsed)
+					return true;
+				node = node.parent;
+			}
+			return false;
+		}
+		
+		internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
+		{
+			AddRemoveCollapsedSection(section, sectionLength, true);
+		}
+		
+		void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
+		{
+			Debug.Assert(sectionLength > 0);
+			
+			HeightTreeNode node = GetNode(section.Start);
+			// Go up in the tree.
+			while (true) {
+				// Mark all middle nodes as collapsed
+				if (add)
+					node.lineNode.AddDirectlyCollapsed(section);
+				else
+					node.lineNode.RemoveDirectlyCollapsed(section);
+				sectionLength -= 1;
+				if (sectionLength == 0) {
+					// we are done!
+					Debug.Assert(node.documentLine == section.End);
+					break;
+				}
+				// Mark all right subtrees as collapsed.
+				if (node.right != null) {
+					if (node.right.totalCount < sectionLength) {
+						if (add)
+							node.right.AddDirectlyCollapsed(section);
+						else
+							node.right.RemoveDirectlyCollapsed(section);
+						sectionLength -= node.right.totalCount;
+					} else {
+						// mark partially into the right subtree: go down the right subtree.
+						AddRemoveCollapsedSectionDown(section, node.right, sectionLength, add);
+						break;
+					}
+				}
+				// go up to the next node
+				HeightTreeNode parentNode = node.parent;
+				Debug.Assert(parentNode != null);
+				while (parentNode.right == node) {
+					node = parentNode;
+					parentNode = node.parent;
+					Debug.Assert(parentNode != null);
+				}
+				node = parentNode;
+			}
+			UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
+			UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
+		}
+		
+		static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
+		{
+			while (true) {
+				if (node.left != null) {
+					if (node.left.totalCount < sectionLength) {
+						// mark left subtree
+						if (add)
+							node.left.AddDirectlyCollapsed(section);
+						else
+							node.left.RemoveDirectlyCollapsed(section);
+						sectionLength -= node.left.totalCount;
+					} else {
+						// mark only inside the left subtree
+						node = node.left;
+						Debug.Assert(node != null);
+						continue;
+					}
+				}
+				if (add)
+					node.lineNode.AddDirectlyCollapsed(section);
+				else
+					node.lineNode.RemoveDirectlyCollapsed(section);
+				sectionLength -= 1;
+				if (sectionLength == 0) {
+					// done!
+					Debug.Assert(node.documentLine == section.End);
+					break;
+				}
+				// mark inside right subtree:
+				node = node.right;
+				Debug.Assert(node != null);
+			}
+		}
+		
+		public void Uncollapse(CollapsedLineSection section)
+		{
+			int sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
+			AddRemoveCollapsedSection(section, sectionLength, false);
+			// do not call CheckProperties() in here - Uncollapse is also called during line removals
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTreeLineNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTreeLineNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTreeLineNode.cs	(revision 11807)
@@ -0,0 +1,64 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	struct HeightTreeLineNode
+	{
+		internal HeightTreeLineNode(double height)
+		{
+			this.collapsedSections = null;
+			this.height = height;
+		}
+		
+		internal double height;
+		internal List<CollapsedLineSection> collapsedSections;
+		
+		internal bool IsDirectlyCollapsed {
+			get { return collapsedSections != null; }
+		}
+		
+		internal void AddDirectlyCollapsed(CollapsedLineSection section)
+		{
+			if (collapsedSections == null)
+				collapsedSections = new List<CollapsedLineSection>();
+			collapsedSections.Add(section);
+		}
+		
+		internal void RemoveDirectlyCollapsed(CollapsedLineSection section)
+		{
+			Debug.Assert(collapsedSections.Contains(section));
+			collapsedSections.Remove(section);
+			if (collapsedSections.Count == 0)
+				collapsedSections = null;
+		}
+		
+		/// <summary>
+		/// Returns 0 if the line is directly collapsed, otherwise, returns <see cref="height"/>.
+		/// </summary>
+		internal double TotalHeight {
+			get {
+				return IsDirectlyCollapsed ? 0 : height;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTreeNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTreeNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/HeightTreeNode.cs	(revision 11807)
@@ -0,0 +1,170 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// A node in the text view's height tree.
+	/// </summary>
+	sealed class HeightTreeNode
+	{
+		internal readonly DocumentLine documentLine;
+		internal HeightTreeLineNode lineNode;
+		
+		internal HeightTreeNode left, right, parent;
+		internal bool color;
+		
+		internal HeightTreeNode()
+		{
+		}
+		
+		internal HeightTreeNode(DocumentLine documentLine, double height)
+		{
+			this.documentLine = documentLine;
+			this.totalCount = 1;
+			this.lineNode = new HeightTreeLineNode(height);
+			this.totalHeight = height;
+		}
+		
+		internal HeightTreeNode LeftMost {
+			get {
+				HeightTreeNode node = this;
+				while (node.left != null)
+					node = node.left;
+				return node;
+			}
+		}
+		
+		internal HeightTreeNode RightMost {
+			get {
+				HeightTreeNode node = this;
+				while (node.right != null)
+					node = node.right;
+				return node;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the inorder successor of the node.
+		/// </summary>
+		internal HeightTreeNode Successor {
+			get {
+				if (right != null) {
+					return right.LeftMost;
+				} else {
+					HeightTreeNode node = this;
+					HeightTreeNode oldNode;
+					do {
+						oldNode = node;
+						node = node.parent;
+						// go up until we are coming out of a left subtree
+					} while (node != null && node.right == oldNode);
+					return node;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// The number of lines in this node and its child nodes.
+		/// Invariant:
+		///   totalCount = 1 + left.totalCount + right.totalCount
+		/// </summary>
+		internal int totalCount;
+		
+		/// <summary>
+		/// The total height of this node and its child nodes, excluding directly collapsed nodes.
+		/// Invariant:
+		///   totalHeight = left.IsDirectlyCollapsed ? 0 : left.totalHeight
+		///               + lineNode.IsDirectlyCollapsed ? 0 : lineNode.Height
+		///               + right.IsDirectlyCollapsed ? 0 : right.totalHeight
+		/// </summary>
+		internal double totalHeight;
+		
+		/// <summary>
+		/// List of the sections that hold this node collapsed.
+		/// Invariant 1:
+		///   For each document line in the range described by a CollapsedSection, exactly one ancestor
+		///   contains that CollapsedSection.
+		/// Invariant 2:
+		///   A CollapsedSection is contained either in left+middle or middle+right or just middle.
+		/// Invariant 3:
+		///   Start and end of a CollapsedSection always contain the collapsedSection in their
+		///   documentLine (middle node).
+		/// </summary>
+		internal List<CollapsedLineSection> collapsedSections;
+		
+		internal bool IsDirectlyCollapsed {
+			get {
+				return collapsedSections != null;
+			}
+		}
+		
+		internal void AddDirectlyCollapsed(CollapsedLineSection section)
+		{
+			if (collapsedSections == null) {
+				collapsedSections = new List<CollapsedLineSection>();
+				totalHeight = 0;
+			}
+			Debug.Assert(!collapsedSections.Contains(section));
+			collapsedSections.Add(section);
+		}
+		
+		
+		internal void RemoveDirectlyCollapsed(CollapsedLineSection section)
+		{
+			Debug.Assert(collapsedSections.Contains(section));
+			collapsedSections.Remove(section);
+			if (collapsedSections.Count == 0) {
+				collapsedSections = null;
+				totalHeight = lineNode.TotalHeight;
+				if (left != null)
+					totalHeight += left.totalHeight;
+				if (right != null)
+					totalHeight += right.totalHeight;
+			}
+		}
+		
+		#if DEBUG
+		public override string ToString()
+		{
+			return "[HeightTreeNode "
+				+ documentLine.LineNumber + " CS=" + GetCollapsedSections(collapsedSections)
+				+ " Line.CS=" + GetCollapsedSections(lineNode.collapsedSections)
+				+ " Line.Height=" + lineNode.height
+				+ " TotalHeight=" + totalHeight
+				+ "]";
+		}
+		
+		static string GetCollapsedSections(List<CollapsedLineSection> list)
+		{
+			if (list == null)
+				return "{}";
+			return "{" +
+				string.Join(",",
+				            list.ConvertAll(cs=>cs.ID).ToArray())
+				+ "}";
+		}
+		#endif
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/IBackgroundRenderer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/IBackgroundRenderer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/IBackgroundRenderer.cs	(revision 11807)
@@ -0,0 +1,41 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Media;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Background renderers draw in the background of a known layer.
+	/// You can use background renderers to draw non-interactive elements on the TextView
+	/// without introducing new UIElements.
+	/// </summary>
+	public interface IBackgroundRenderer
+	{
+		/// <summary>
+		/// Gets the layer on which this background renderer should draw.
+		/// </summary>
+		KnownLayer Layer { get; }
+		
+		/// <summary>
+		/// Causes the background renderer to draw.
+		/// </summary>
+		void Draw(TextView textView, DrawingContext drawingContext);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ITextRunConstructionContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ITextRunConstructionContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ITextRunConstructionContext.cs	(revision 11807)
@@ -0,0 +1,62 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Contains information relevant for text run creation.
+	/// </summary>
+	public interface ITextRunConstructionContext
+	{
+		/// <summary>
+		/// Gets the text document.
+		/// </summary>
+		TextDocument Document { get; }
+		
+		/// <summary>
+		/// Gets the text view for which the construction runs.
+		/// </summary>
+		TextView TextView { get; }
+		
+		/// <summary>
+		/// Gets the visual line that is currently being constructed.
+		/// </summary>
+		VisualLine VisualLine { get; }
+		
+		/// <summary>
+		/// Gets the global text run properties.
+		/// </summary>
+		TextRunProperties GlobalTextRunProperties { get; }
+		
+		/// <summary>
+		/// Gets a piece of text from the document.
+		/// </summary>
+		/// <remarks>
+		/// This method is allowed to return a larger string than requested.
+		/// It does this by returning a <see cref="StringSegment"/> that describes the requested segment within the returned string.
+		/// This method should be the preferred text access method in the text transformation pipeline, as it can avoid repeatedly allocating string instances
+		/// for text within the same line.
+		/// </remarks>
+		StringSegment GetText(int offset, int length);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ITextViewConnect.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ITextViewConnect.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/ITextViewConnect.cs	(revision 11807)
@@ -0,0 +1,39 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Allows <see cref="VisualLineElementGenerator"/>s, <see cref="IVisualLineTransformer"/>s and
+	/// <see cref="IBackgroundRenderer"/>s to be notified when they are added or removed from a text view.
+	/// </summary>
+	public interface ITextViewConnect
+	{
+		/// <summary>
+		/// Called when added to a text view.
+		/// </summary>
+		void AddToTextView(TextView textView);
+		
+		/// <summary>
+		/// Called when removed from a text view.
+		/// </summary>
+		void RemoveFromTextView(TextView textView);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/IVisualLineTransformer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/IVisualLineTransformer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/IVisualLineTransformer.cs	(revision 11807)
@@ -0,0 +1,34 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Allows transforming visual line elements.
+	/// </summary>
+	public interface IVisualLineTransformer
+	{
+		/// <summary>
+		/// Applies the transformation to the specified list of visual line elements.
+		/// </summary>
+		void Transform(ITextRunConstructionContext context, IList<VisualLineElement> elements);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/InlineObjectRun.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/InlineObjectRun.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/InlineObjectRun.cs	(revision 11807)
@@ -0,0 +1,160 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// A inline UIElement in the document.
+	/// </summary>
+	public class InlineObjectElement : VisualLineElement
+	{
+		/// <summary>
+		/// Gets the inline element that is displayed.
+		/// </summary>
+		public UIElement Element { get; private set; }
+		
+		/// <summary>
+		/// Creates a new InlineObjectElement.
+		/// </summary>
+		/// <param name="documentLength">The length of the element in the document. Must be non-negative.</param>
+		/// <param name="element">The element to display.</param>
+		public InlineObjectElement(int documentLength, UIElement element)
+			: base(1, documentLength)
+		{
+			if (element == null)
+				throw new ArgumentNullException("element");
+			this.Element = element;
+		}
+		
+		/// <inheritdoc/>
+		public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			
+			return new InlineObjectRun(1, this.TextRunProperties, this.Element);
+		}
+	}
+	
+	/// <summary>
+	/// A text run with an embedded UIElement.
+	/// </summary>
+	public class InlineObjectRun : TextEmbeddedObject
+	{
+		UIElement element;
+		int length;
+		TextRunProperties properties;
+		internal Size desiredSize;
+		
+		/// <summary>
+		/// Creates a new InlineObjectRun instance.
+		/// </summary>
+		/// <param name="length">The length of the TextRun.</param>
+		/// <param name="properties">The <see cref="TextRunProperties"/> to use.</param>
+		/// <param name="element">The <see cref="UIElement"/> to display.</param>
+		public InlineObjectRun(int length, TextRunProperties properties, UIElement element)
+		{
+			if (length <= 0)
+				throw new ArgumentOutOfRangeException("length", length, "Value must be positive");
+			if (properties == null)
+				throw new ArgumentNullException("properties");
+			if (element == null)
+				throw new ArgumentNullException("element");
+			
+			this.length = length;
+			this.properties = properties;
+			this.element = element;
+		}
+		
+		/// <summary>
+		/// Gets the element displayed by the InlineObjectRun.
+		/// </summary>
+		public UIElement Element {
+			get { return element; }
+		}
+		
+		/// <summary>
+		/// Gets the VisualLine that contains this object. This property is only available after the object
+		/// was added to the text view.
+		/// </summary>
+		public VisualLine VisualLine { get; internal set; }
+		
+		/// <inheritdoc/>
+		public override LineBreakCondition BreakBefore {
+			get { return LineBreakCondition.BreakDesired; }
+		}
+		
+		/// <inheritdoc/>
+		public override LineBreakCondition BreakAfter {
+			get { return LineBreakCondition.BreakDesired; }
+		}
+		
+		/// <inheritdoc/>
+		public override bool HasFixedSize {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override CharacterBufferReference CharacterBufferReference {
+			get { return new CharacterBufferReference(); }
+		}
+		
+		/// <inheritdoc/>
+		public override int Length {
+			get { return length; }
+		}
+		
+		/// <inheritdoc/>
+		public override TextRunProperties Properties {
+			get { return properties; }
+		}
+		
+		/// <inheritdoc/>
+		public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth)
+		{
+			double baseline = TextBlock.GetBaselineOffset(element);
+			if (double.IsNaN(baseline))
+				baseline = desiredSize.Height;
+			return new TextEmbeddedObjectMetrics(desiredSize.Width, desiredSize.Height, baseline);
+		}
+		
+		/// <inheritdoc/>
+		public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways)
+		{
+			if (this.element.IsArrangeValid) {
+				double baseline = TextBlock.GetBaselineOffset(element);
+				if (double.IsNaN(baseline))
+					baseline = desiredSize.Height;
+				return new Rect(new Point(0, -baseline), desiredSize);
+			} else {
+				return Rect.Empty;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/Layer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/Layer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/Layer.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Media;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Base class for known layers.
+	/// </summary>
+	class Layer : UIElement
+	{
+		protected readonly TextView textView;
+		protected readonly KnownLayer knownLayer;
+		
+		public Layer(TextView textView, KnownLayer knownLayer)
+		{
+			Debug.Assert(textView != null);
+			this.textView = textView;
+			this.knownLayer = knownLayer;
+			this.Focusable = false;
+		}
+		
+		protected override GeometryHitTestResult HitTestCore(GeometryHitTestParameters hitTestParameters)
+		{
+			return null;
+		}
+		
+		protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
+		{
+			return null;
+		}
+		
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			base.OnRender(drawingContext);
+			textView.RenderBackground(drawingContext, knownLayer);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/LayerPosition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/LayerPosition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/LayerPosition.cs	(revision 11807)
@@ -0,0 +1,106 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// An enumeration of well-known layers.
+	/// </summary>
+	public enum KnownLayer
+	{
+		/// <summary>
+		/// This layer is in the background.
+		/// There is no UIElement to represent this layer, it is directly drawn in the TextView.
+		/// It is not possible to replace the background layer or insert new layers below it.
+		/// </summary>
+		/// <remarks>This layer is below the Selection layer.</remarks>
+		Background,
+		/// <summary>
+		/// This layer contains the selection rectangle.
+		/// </summary>
+		/// <remarks>This layer is between the Background and the Text layers.</remarks>
+		Selection,
+		/// <summary>
+		/// This layer contains the text and inline UI elements.
+		/// </summary>
+		/// <remarks>This layer is between the Selection and the Caret layers.</remarks>
+		Text,
+		/// <summary>
+		/// This layer contains the blinking caret.
+		/// </summary>
+		/// <remarks>This layer is above the Text layer.</remarks>
+		Caret
+	}
+	
+	/// <summary>
+	/// Specifies where a new layer is inserted, in relation to an old layer.
+	/// </summary>
+	public enum LayerInsertionPosition
+	{
+		/// <summary>
+		/// The new layer is inserted below the specified layer.
+		/// </summary>
+		Below,
+		/// <summary>
+		/// The new layer replaces the specified layer. The old layer is removed
+		/// from the <see cref="TextView.Layers"/> collection.
+		/// </summary>
+		Replace,
+		/// <summary>
+		/// The new layer is inserted above the specified layer.
+		/// </summary>
+		Above
+	}
+	
+	sealed class LayerPosition : IComparable<LayerPosition>
+	{
+		internal static readonly DependencyProperty LayerPositionProperty =
+			DependencyProperty.RegisterAttached("LayerPosition", typeof(LayerPosition), typeof(LayerPosition));
+		
+		public static void SetLayerPosition(UIElement layer, LayerPosition value)
+		{
+			layer.SetValue(LayerPositionProperty, value);
+		}
+		
+		public static LayerPosition GetLayerPosition(UIElement layer)
+		{
+			return (LayerPosition)layer.GetValue(LayerPositionProperty);
+		}
+		
+		internal readonly KnownLayer KnownLayer;
+		internal readonly LayerInsertionPosition Position;
+		
+		public LayerPosition(KnownLayer knownLayer, LayerInsertionPosition position)
+		{
+			this.KnownLayer = knownLayer;
+			this.Position = position;
+		}
+		
+		public int CompareTo(LayerPosition other)
+		{
+			int r = this.KnownLayer.CompareTo(other.KnownLayer);
+			if (r != 0)
+				return r;
+			else
+				return this.Position.CompareTo(other.Position);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/LinkElementGenerator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/LinkElementGenerator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/LinkElementGenerator.cs	(revision 11807)
@@ -0,0 +1,159 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text.RegularExpressions;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	// This class is public because it can be used as a base class for custom links.
+	
+	/// <summary>
+	/// Detects hyperlinks and makes them clickable.
+	/// </summary>
+	/// <remarks>
+	/// This element generator can be easily enabled and configured using the
+	/// <see cref="TextEditorOptions"/>.
+	/// </remarks>
+	public class LinkElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
+	{
+		// a link starts with a protocol (or just with www), followed by 0 or more 'link characters', followed by a link end character
+		// (this allows accepting punctuation inside links but not at the end)
+		internal readonly static Regex defaultLinkRegex = new Regex(@"\b(https?://|ftp://|www\.)[\w\d\._/\-~%@()+:?&=#!]*[\w\d/]");
+		
+		// try to detect email addresses
+		internal readonly static Regex defaultMailRegex = new Regex(@"\b[\w\d\.\-]+\@[\w\d\.\-]+\.[a-z]{2,6}\b");
+		
+		readonly Regex linkRegex;
+		
+		/// <summary>
+		/// Gets/Sets whether the user needs to press Control to click the link.
+		/// The default value is true.
+		/// </summary>
+		public bool RequireControlModifierForClick { get; set; }
+		
+		/// <summary>
+		/// Creates a new LinkElementGenerator.
+		/// </summary>
+		public LinkElementGenerator()
+		{
+			this.linkRegex = defaultLinkRegex;
+			this.RequireControlModifierForClick = true;
+		}
+		
+		/// <summary>
+		/// Creates a new LinkElementGenerator using the specified regex.
+		/// </summary>
+		protected LinkElementGenerator(Regex regex) : this()
+		{
+			if (regex == null)
+				throw new ArgumentNullException("regex");
+			this.linkRegex = regex;
+		}
+		
+		void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
+		{
+			this.RequireControlModifierForClick = options.RequireControlModifierForHyperlinkClick;
+		}
+		
+		Match GetMatch(int startOffset, out int matchOffset)
+		{
+			int endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;
+			StringSegment relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
+			Match m = linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
+			matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
+			return m;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetFirstInterestedOffset(int startOffset)
+		{
+			int matchOffset;
+			GetMatch(startOffset, out matchOffset);
+			return matchOffset;
+		}
+		
+		/// <inheritdoc/>
+		public override VisualLineElement ConstructElement(int offset)
+		{
+			int matchOffset;
+			Match m = GetMatch(offset, out matchOffset);
+			if (m.Success && matchOffset == offset) {
+				return ConstructElementFromMatch(m);
+			} else {
+				return null;
+			}
+		}
+		
+		/// <summary>
+		/// Constructs a VisualLineElement that replaces the matched text.
+		/// The default implementation will create a <see cref="VisualLineLinkText"/>
+		/// based on the URI provided by <see cref="GetUriFromMatch"/>.
+		/// </summary>
+		protected virtual VisualLineElement ConstructElementFromMatch(Match m)
+		{
+			Uri uri = GetUriFromMatch(m);
+			if (uri == null)
+				return null;
+			VisualLineLinkText linkText = new VisualLineLinkText(CurrentContext.VisualLine, m.Length);
+			linkText.NavigateUri = uri;
+			linkText.RequireControlModifierForClick = this.RequireControlModifierForClick;
+			return linkText;
+		}
+		
+		/// <summary>
+		/// Fetches the URI from the regex match. Returns null if the URI format is invalid.
+		/// </summary>
+		protected virtual Uri GetUriFromMatch(Match match)
+		{
+			string targetUrl = match.Value;
+			if (targetUrl.StartsWith("www.", StringComparison.Ordinal))
+				targetUrl = "http://" + targetUrl;
+			if (Uri.IsWellFormedUriString(targetUrl, UriKind.Absolute))
+				return new Uri(targetUrl);
+			
+			return null;
+		}
+	}
+	
+	// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
+	
+	/// <summary>
+	/// Detects e-mail addresses and makes them clickable.
+	/// </summary>
+	/// <remarks>
+	/// This element generator can be easily enabled and configured using the
+	/// <see cref="TextEditorOptions"/>.
+	/// </remarks>
+	sealed class MailLinkElementGenerator : LinkElementGenerator
+	{
+		/// <summary>
+		/// Creates a new MailLinkElementGenerator.
+		/// </summary>
+		public MailLinkElementGenerator()
+			: base(defaultMailRegex)
+		{
+		}
+		
+		protected override Uri GetUriFromMatch(Match match)
+		{
+			return new Uri("mailto:" + match.Value);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/MouseHoverLogic.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/MouseHoverLogic.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/MouseHoverLogic.cs	(revision 11807)
@@ -0,0 +1,149 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Input;
+using System.Windows.Threading;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Encapsulates and adds MouseHover support to UIElements.
+	/// </summary>
+	public class MouseHoverLogic : IDisposable
+	{
+		UIElement target;
+		
+		DispatcherTimer mouseHoverTimer;
+		Point mouseHoverStartPoint;
+		MouseEventArgs mouseHoverLastEventArgs;
+		bool mouseHovering;
+		
+		/// <summary>
+		/// Creates a new instance and attaches itself to the <paramref name="target" /> UIElement.
+		/// </summary>
+		public MouseHoverLogic(UIElement target)
+		{
+			if (target == null)
+				throw new ArgumentNullException("target");
+			this.target = target;
+			this.target.MouseLeave += MouseHoverLogicMouseLeave;
+			this.target.MouseMove += MouseHoverLogicMouseMove;
+			this.target.MouseEnter += MouseHoverLogicMouseEnter;
+		}
+		
+		void MouseHoverLogicMouseMove(object sender, MouseEventArgs e)
+		{
+			Vector mouseMovement = mouseHoverStartPoint - e.GetPosition(this.target);
+			if (Math.Abs(mouseMovement.X) > SystemParameters.MouseHoverWidth
+			    || Math.Abs(mouseMovement.Y) > SystemParameters.MouseHoverHeight)
+			{
+				StartHovering(e);
+			}
+			// do not set e.Handled - allow others to also handle MouseMove
+		}
+		
+		void MouseHoverLogicMouseEnter(object sender, MouseEventArgs e)
+		{
+			StartHovering(e);
+			// do not set e.Handled - allow others to also handle MouseEnter
+		}
+		
+		void StartHovering(MouseEventArgs e)
+		{
+			StopHovering();
+			mouseHoverStartPoint = e.GetPosition(this.target);
+			mouseHoverLastEventArgs = e;
+			mouseHoverTimer = new DispatcherTimer(SystemParameters.MouseHoverTime, DispatcherPriority.Background, OnMouseHoverTimerElapsed, this.target.Dispatcher);
+			mouseHoverTimer.Start();
+		}
+		
+		void MouseHoverLogicMouseLeave(object sender, MouseEventArgs e)
+		{
+			StopHovering();
+			// do not set e.Handled - allow others to also handle MouseLeave
+		}
+		
+		void StopHovering()
+		{
+			if (mouseHoverTimer != null) {
+				mouseHoverTimer.Stop();
+				mouseHoverTimer = null;
+			}
+			if (mouseHovering) {
+				mouseHovering = false;
+				OnMouseHoverStopped(mouseHoverLastEventArgs);
+			}
+		}
+		
+		void OnMouseHoverTimerElapsed(object sender, EventArgs e)
+		{
+			mouseHoverTimer.Stop();
+			mouseHoverTimer = null;
+			
+			mouseHovering = true;
+			OnMouseHover(mouseHoverLastEventArgs);
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse starts hovering over a certain location.
+		/// </summary>
+		public event EventHandler<MouseEventArgs> MouseHover;
+		
+		/// <summary>
+		/// Raises the <see cref="MouseHover"/> event.
+		/// </summary>
+		protected virtual void OnMouseHover(MouseEventArgs e)
+		{
+			if (MouseHover != null) {
+				MouseHover(this, e);
+			}
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse stops hovering over a certain location.
+		/// </summary>
+		public event EventHandler<MouseEventArgs> MouseHoverStopped;
+		
+		/// <summary>
+		/// Raises the <see cref="MouseHoverStopped"/> event.
+		/// </summary>
+		protected virtual void OnMouseHoverStopped(MouseEventArgs e)
+		{
+			if (MouseHoverStopped != null) {
+				MouseHoverStopped(this, e);
+			}
+		}
+		
+		bool disposed;
+		
+		/// <summary>
+		/// Removes the MouseHover support from the target UIElement.
+		/// </summary>
+		public void Dispose()
+		{
+			if (!disposed) {
+				this.target.MouseLeave -= MouseHoverLogicMouseLeave;
+				this.target.MouseMove -= MouseHoverLogicMouseMove;
+				this.target.MouseEnter -= MouseHoverLogicMouseEnter;
+			}
+			disposed = true;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/SimpleTextSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/SimpleTextSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/SimpleTextSource.cs	(revision 11807)
@@ -0,0 +1,54 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows.Media.TextFormatting;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	sealed class SimpleTextSource : TextSource
+	{
+		readonly string text;
+		readonly TextRunProperties properties;
+		
+		public SimpleTextSource(string text, TextRunProperties properties)
+		{
+			this.text = text;
+			this.properties = properties;
+		}
+		
+		public override TextRun GetTextRun(int textSourceCharacterIndex)
+		{
+			if (textSourceCharacterIndex < text.Length)
+				return new TextCharacters(text, textSourceCharacterIndex, text.Length - textSourceCharacterIndex, properties);
+			else
+				return new TextEndOfParagraph(1);
+		}
+		
+		public override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int textSourceCharacterIndex)
+		{
+			throw new NotImplementedException();
+		}
+		
+		public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int textSourceCharacterIndexLimit)
+		{
+			throw new NotImplementedException();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/SingleCharacterElementGenerator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/SingleCharacterElementGenerator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/SingleCharacterElementGenerator.cs	(revision 11807)
@@ -0,0 +1,283 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
+	
+	/// <summary>
+	/// Element generator that displays · for spaces and » for tabs and a box for control characters.
+	/// </summary>
+	/// <remarks>
+	/// This element generator is present in every TextView by default; the enabled features can be configured using the
+	/// <see cref="TextEditorOptions"/>.
+	/// </remarks>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
+	sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
+	{
+		/// <summary>
+		/// Gets/Sets whether to show · for spaces.
+		/// </summary>
+		public bool ShowSpaces { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether to show » for tabs.
+		/// </summary>
+		public bool ShowTabs { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether to show a box with the hex code for control characters.
+		/// </summary>
+		public bool ShowBoxForControlCharacters { get; set; }
+		
+		/// <summary>
+		/// Creates a new SingleCharacterElementGenerator instance.
+		/// </summary>
+		public SingleCharacterElementGenerator()
+		{
+			this.ShowSpaces = true;
+			this.ShowTabs = true;
+			this.ShowBoxForControlCharacters = true;
+		}
+		
+		void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
+		{
+			this.ShowSpaces = options.ShowSpaces;
+			this.ShowTabs = options.ShowTabs;
+			this.ShowBoxForControlCharacters = options.ShowBoxForControlCharacters;
+		}
+		
+		public override int GetFirstInterestedOffset(int startOffset)
+		{
+			DocumentLine endLine = CurrentContext.VisualLine.LastDocumentLine;
+			StringSegment relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset);
+			
+			for (int i = 0; i < relevantText.Count; i++) {
+				char c = relevantText.Text[relevantText.Offset + i];
+				switch (c) {
+					case ' ':
+						if (ShowSpaces)
+							return startOffset + i;
+						break;
+					case '\t':
+						if (ShowTabs)
+							return startOffset + i;
+						break;
+					default:
+						if (ShowBoxForControlCharacters && char.IsControl(c)) {
+							return startOffset + i;
+						}
+						break;
+				}
+			}
+			return -1;
+		}
+		
+		public override VisualLineElement ConstructElement(int offset)
+		{
+			char c = CurrentContext.Document.GetCharAt(offset);
+			if (ShowSpaces && c == ' ') {
+				return new SpaceTextElement(CurrentContext.TextView.cachedElements.GetTextForNonPrintableCharacter("\u00B7", CurrentContext));
+			} else if (ShowTabs && c == '\t') {
+				return new TabTextElement(CurrentContext.TextView.cachedElements.GetTextForNonPrintableCharacter("\u00BB", CurrentContext));
+			} else if (ShowBoxForControlCharacters && char.IsControl(c)) {
+				var p = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
+				p.SetForegroundBrush(Brushes.White);
+				var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
+				var text = FormattedTextElement.PrepareText(textFormatter,
+				                                            TextUtilities.GetControlCharacterName(c), p);
+				return new SpecialCharacterBoxElement(text);
+			} else {
+				return null;
+			}
+		}
+		
+		sealed class SpaceTextElement : FormattedTextElement
+		{
+			public SpaceTextElement(TextLine textLine) : base(textLine, 1)
+			{
+				BreakBefore = LineBreakCondition.BreakPossible;
+				BreakAfter = LineBreakCondition.BreakDesired;
+			}
+			
+			public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
+			{
+				if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
+					return base.GetNextCaretPosition(visualColumn, direction, mode);
+				else
+					return -1;
+			}
+			
+			public override bool IsWhitespace(int visualColumn)
+			{
+				return true;
+			}
+		}
+		
+		sealed class TabTextElement : VisualLineElement
+		{
+			internal readonly TextLine text;
+			
+			public TabTextElement(TextLine text) : base(2, 1)
+			{
+				this.text = text;
+			}
+			
+			public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+			{
+				// the TabTextElement consists of two TextRuns:
+				// first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation
+				if (startVisualColumn == this.VisualColumn)
+					return new TabGlyphRun(this, this.TextRunProperties);
+				else if (startVisualColumn == this.VisualColumn + 1)
+					return new TextCharacters("\t", 0, 1, this.TextRunProperties);
+				else
+					throw new ArgumentOutOfRangeException("startVisualColumn");
+			}
+			
+			public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
+			{
+				if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
+					return base.GetNextCaretPosition(visualColumn, direction, mode);
+				else
+					return -1;
+			}
+			
+			public override bool IsWhitespace(int visualColumn)
+			{
+				return true;
+			}
+		}
+		
+		sealed class TabGlyphRun : TextEmbeddedObject
+		{
+			readonly TabTextElement element;
+			TextRunProperties properties;
+			
+			public TabGlyphRun(TabTextElement element, TextRunProperties properties)
+			{
+				if (properties == null)
+					throw new ArgumentNullException("properties");
+				this.properties = properties;
+				this.element = element;
+			}
+			
+			public override LineBreakCondition BreakBefore {
+				get { return LineBreakCondition.BreakPossible; }
+			}
+			
+			public override LineBreakCondition BreakAfter {
+				get { return LineBreakCondition.BreakRestrained; }
+			}
+			
+			public override bool HasFixedSize {
+				get { return true; }
+			}
+			
+			public override CharacterBufferReference CharacterBufferReference {
+				get { return new CharacterBufferReference(); }
+			}
+			
+			public override int Length {
+				get { return 1; }
+			}
+			
+			public override TextRunProperties Properties {
+				get { return properties; }
+			}
+			
+			public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth)
+			{
+				double width = Math.Min(0, element.text.WidthIncludingTrailingWhitespace - 1);
+				return new TextEmbeddedObjectMetrics(width, element.text.Height, element.text.Baseline);
+			}
+			
+			public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways)
+			{
+				double width = Math.Min(0, element.text.WidthIncludingTrailingWhitespace - 1);
+				return new Rect(0, 0, width, element.text.Height);
+			}
+			
+			public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways)
+			{
+				origin.Y -= element.text.Baseline;
+				element.text.Draw(drawingContext, origin, InvertAxes.None);
+			}
+		}
+		
+		sealed class SpecialCharacterBoxElement : FormattedTextElement
+		{
+			public SpecialCharacterBoxElement(TextLine text) : base(text, 1)
+			{
+			}
+			
+			public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+			{
+				return new SpecialCharacterTextRun(this, this.TextRunProperties);
+			}
+		}
+		
+		sealed class SpecialCharacterTextRun : FormattedTextRun
+		{
+			static readonly SolidColorBrush darkGrayBrush;
+			
+			static SpecialCharacterTextRun()
+			{
+				darkGrayBrush = new SolidColorBrush(Color.FromArgb(200, 128, 128, 128));
+				darkGrayBrush.Freeze();
+			}
+			
+			public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
+				: base(element, properties)
+			{
+			}
+			
+			public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways)
+			{
+				Point newOrigin = new Point(origin.X + 1.5, origin.Y);
+				var metrics = base.Format(double.PositiveInfinity);
+				Rect r = new Rect(newOrigin.X - 0.5, newOrigin.Y - metrics.Baseline, metrics.Width + 2, metrics.Height);
+				drawingContext.DrawRoundedRectangle(darkGrayBrush, null, r, 2.5, 2.5);
+				base.Draw(drawingContext, newOrigin, rightToLeft, sideways);
+			}
+			
+			public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth)
+			{
+				TextEmbeddedObjectMetrics metrics = base.Format(remainingParagraphWidth);
+				return new TextEmbeddedObjectMetrics(metrics.Width + 3,
+				                                     metrics.Height, metrics.Baseline);
+			}
+			
+			public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways)
+			{
+				Rect r = base.ComputeBoundingBox(rightToLeft, sideways);
+				r.Width += 3;
+				return r;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextLayer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextLayer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextLayer.cs	(revision 11807)
@@ -0,0 +1,85 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using System.Windows.Input;
+using System.Windows.Media;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// The control that contains the text.
+	/// 
+	/// This control is used to allow other UIElements to be placed inside the TextView but
+	/// behind the text.
+	/// The text rendering process (VisualLine creation) is controlled by the TextView, this
+	/// class simply displays the created Visual Lines.
+	/// </summary>
+	/// <remarks>
+	/// This class does not contain any input handling and is invisible to hit testing. Input
+	/// is handled by the TextView.
+	/// This allows UIElements that are displayed behind the text, but still can react to mouse input.
+	/// </remarks>
+	sealed class TextLayer : Layer
+	{
+		/// <summary>
+		/// the index of the text layer in the layers collection
+		/// </summary>
+		internal int index;
+		
+		public TextLayer(TextView textView) : base(textView, KnownLayer.Text)
+		{
+		}
+		
+		List<VisualLineDrawingVisual> visuals = new List<VisualLineDrawingVisual>();
+		
+		internal void SetVisualLines(ICollection<VisualLine> visualLines)
+		{
+			foreach (VisualLineDrawingVisual v in visuals) {
+				if (v.VisualLine.IsDisposed)
+					RemoveVisualChild(v);
+			}
+			visuals.Clear();
+			foreach (VisualLine newLine in visualLines) {
+				VisualLineDrawingVisual v = newLine.Render();
+				if (!v.IsAdded) {
+					AddVisualChild(v);
+					v.IsAdded = true;
+				}
+				visuals.Add(v);
+			}
+			InvalidateArrange();
+		}
+		
+		protected override int VisualChildrenCount {
+			get { return visuals.Count; }
+		}
+		
+		protected override Visual GetVisualChild(int index)
+		{
+			return visuals[index];
+		}
+		
+		protected override void ArrangeCore(Rect finalRect)
+		{
+			textView.ArrangeTextLayer(visuals);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextView.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextView.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextView.cs	(revision 11807)
@@ -0,0 +1,2081 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ComponentModel.Design;
+using System.Diagnostics;
+using System.Globalization;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Threading;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
+	/// 
+	/// This is the heart of the text editor, this class controls the text rendering process.
+	/// 
+	/// Taken as a standalone control, it's a text viewer without any editing capability.
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
+	                                                 Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
+	public class TextView : FrameworkElement, IScrollInfo, IWeakEventListener, ITextEditorComponent, IServiceProvider
+	{
+		#region Constructor
+		static TextView()
+		{
+			ClipToBoundsProperty.OverrideMetadata(typeof(TextView), new FrameworkPropertyMetadata(Boxes.True));
+			FocusableProperty.OverrideMetadata(typeof(TextView), new FrameworkPropertyMetadata(Boxes.False));
+		}
+		
+		ColumnRulerRenderer columnRulerRenderer;
+		CurrentLineHighlightRenderer currentLineHighlighRenderer;
+		
+		/// <summary>
+		/// Creates a new TextView instance.
+		/// </summary>
+		public TextView()
+		{
+			services.AddService(typeof(TextView), this);
+			textLayer = new TextLayer(this);
+			elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
+			lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
+			backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
+			columnRulerRenderer = new ColumnRulerRenderer(this);
+			currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
+			this.Options = new TextEditorOptions();
+			
+			Debug.Assert(singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
+			
+			layers = new LayerCollection(this);
+			InsertLayer(textLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
+			
+			this.hoverLogic = new MouseHoverLogic(this);
+			this.hoverLogic.MouseHover += (sender, e) => RaiseHoverEventPair(e, PreviewMouseHoverEvent, MouseHoverEvent);
+			this.hoverLogic.MouseHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewMouseHoverStoppedEvent, MouseHoverStoppedEvent);
+		}
+
+		#endregion
+		
+		#region Document Property
+		/// <summary>
+		/// Document property.
+		/// </summary>
+		public static readonly DependencyProperty DocumentProperty =
+			DependencyProperty.Register("Document", typeof(TextDocument), typeof(TextView),
+			                            new FrameworkPropertyMetadata(OnDocumentChanged));
+		
+		TextDocument document;
+		HeightTree heightTree;
+		
+		/// <summary>
+		/// Gets/Sets the document displayed by the text editor.
+		/// </summary>
+		public TextDocument Document {
+			get { return (TextDocument)GetValue(DocumentProperty); }
+			set { SetValue(DocumentProperty, value); }
+		}
+		
+		static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			((TextView)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
+		}
+		
+		internal double FontSize {
+			get {
+				return (double)GetValue(TextBlock.FontSizeProperty);
+			}
+		}
+		
+		/// <summary>
+		/// Occurs when the document property has changed.
+		/// </summary>
+		public event EventHandler DocumentChanged;
+		
+		void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
+		{
+			if (oldValue != null) {
+				heightTree.Dispose();
+				heightTree = null;
+				formatter.Dispose();
+				formatter = null;
+				cachedElements.Dispose();
+				cachedElements = null;
+				TextDocumentWeakEventManager.Changing.RemoveListener(oldValue, this);
+			}
+			this.document = newValue;
+			ClearScrollData();
+			ClearVisualLines();
+			if (newValue != null) {
+				TextDocumentWeakEventManager.Changing.AddListener(newValue, this);
+				formatter = TextFormatterFactory.Create(this);
+				InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
+				heightTree = new HeightTree(newValue, DefaultLineHeight);
+				cachedElements = new TextViewCachedElements();
+			}
+			InvalidateMeasure(DispatcherPriority.Normal);
+			if (DocumentChanged != null)
+				DocumentChanged(this, EventArgs.Empty);
+		}
+		
+		/// <summary>
+		/// Recreates the text formatter that is used internally
+		/// by calling <see cref="TextFormatterFactory.Create"/>.
+		/// </summary>
+		void RecreateTextFormatter()
+		{
+			if (formatter != null) {
+				formatter.Dispose();
+				formatter = TextFormatterFactory.Create(this);
+				Redraw();
+			}
+		}
+		
+		void RecreateCachedElements()
+		{
+			if (cachedElements != null) {
+				cachedElements.Dispose();
+				cachedElements = new TextViewCachedElements();
+			}
+		}
+		
+		/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
+		protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextDocumentWeakEventManager.Changing)) {
+				// TODO: put redraw into background so that other input events can be handled before the redraw.
+				// Unfortunately the "easy" approach (just use DispatcherPriority.Background) here makes the editor twice as slow because
+				// the caret position change forces an immediate redraw, and the text input then forces a background redraw.
+				// When fixing this, make sure performance on the SharpDevelop "type text in C# comment" stress test doesn't get significantly worse.
+				DocumentChangeEventArgs change = (DocumentChangeEventArgs)e;
+				Redraw(change.Offset, change.RemovalLength, DispatcherPriority.Normal);
+				return true;
+			} else if (managerType == typeof(PropertyChangedWeakEventManager)) {
+				OnOptionChanged((PropertyChangedEventArgs)e);
+				return true;
+			}
+			return false;
+		}
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			return ReceiveWeakEvent(managerType, sender, e);
+		}
+		#endregion
+		
+		#region Options property
+		/// <summary>
+		/// Options property.
+		/// </summary>
+		public static readonly DependencyProperty OptionsProperty =
+			DependencyProperty.Register("Options", typeof(TextEditorOptions), typeof(TextView),
+			                            new FrameworkPropertyMetadata(OnOptionsChanged));
+		
+		/// <summary>
+		/// Gets/Sets the options used by the text editor.
+		/// </summary>
+		public TextEditorOptions Options {
+			get { return (TextEditorOptions)GetValue(OptionsProperty); }
+			set { SetValue(OptionsProperty, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when a text editor option has changed.
+		/// </summary>
+		public event PropertyChangedEventHandler OptionChanged;
+		
+		/// <summary>
+		/// Raises the <see cref="OptionChanged"/> event.
+		/// </summary>
+		protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
+		{
+			if (OptionChanged != null) {
+				OptionChanged(this, e);
+			}
+			
+			if (Options.ShowColumnRuler)
+				columnRulerRenderer.SetRuler(Options.ColumnRulerPosition, ColumnRulerPen);
+			else
+				columnRulerRenderer.SetRuler(-1, ColumnRulerPen);
+			
+			UpdateBuiltinElementGeneratorsFromOptions();
+			Redraw();
+		}
+		
+		static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			((TextView)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
+		}
+		
+		void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
+		{
+			if (oldValue != null) {
+				PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
+			}
+			if (newValue != null) {
+				PropertyChangedWeakEventManager.AddListener(newValue, this);
+			}
+			OnOptionChanged(new PropertyChangedEventArgs(null));
+		}
+		#endregion
+		
+		#region ElementGenerators+LineTransformers Properties
+		readonly ObserveAddRemoveCollection<VisualLineElementGenerator> elementGenerators;
+		
+		/// <summary>
+		/// Gets a collection where element generators can be registered.
+		/// </summary>
+		public IList<VisualLineElementGenerator> ElementGenerators {
+			get { return elementGenerators; }
+		}
+		
+		void ElementGenerator_Added(VisualLineElementGenerator generator)
+		{
+			ConnectToTextView(generator);
+			Redraw();
+		}
+		
+		void ElementGenerator_Removed(VisualLineElementGenerator generator)
+		{
+			DisconnectFromTextView(generator);
+			Redraw();
+		}
+		
+		readonly ObserveAddRemoveCollection<IVisualLineTransformer> lineTransformers;
+		
+		/// <summary>
+		/// Gets a collection where line transformers can be registered.
+		/// </summary>
+		public IList<IVisualLineTransformer> LineTransformers {
+			get { return lineTransformers; }
+		}
+		
+		void LineTransformer_Added(IVisualLineTransformer lineTransformer)
+		{
+			ConnectToTextView(lineTransformer);
+			Redraw();
+		}
+		
+		void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
+		{
+			DisconnectFromTextView(lineTransformer);
+			Redraw();
+		}
+		#endregion
+		
+		#region Builtin ElementGenerators
+//		NewLineElementGenerator newLineElementGenerator;
+		SingleCharacterElementGenerator singleCharacterElementGenerator;
+		LinkElementGenerator linkElementGenerator;
+		MailLinkElementGenerator mailLinkElementGenerator;
+		
+		void UpdateBuiltinElementGeneratorsFromOptions()
+		{
+			TextEditorOptions options = this.Options;
+			
+//			AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
+			AddRemoveDefaultElementGeneratorOnDemand(ref singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
+			AddRemoveDefaultElementGeneratorOnDemand(ref linkElementGenerator, options.EnableHyperlinks);
+			AddRemoveDefaultElementGeneratorOnDemand(ref mailLinkElementGenerator, options.EnableEmailHyperlinks);
+		}
+		
+		void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
+			where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
+		{
+			bool hasGenerator = generator != null;
+			if (hasGenerator != demand) {
+				if (demand) {
+					generator = new T();
+					this.ElementGenerators.Add(generator);
+				} else {
+					this.ElementGenerators.Remove(generator);
+					generator = null;
+				}
+			}
+			if (generator != null)
+				generator.FetchOptions(this.Options);
+		}
+		#endregion
+		
+		#region Layers
+		internal readonly TextLayer textLayer;
+		readonly LayerCollection layers;
+		
+		/// <summary>
+		/// Gets the list of layers displayed in the text view.
+		/// </summary>
+		public UIElementCollection Layers {
+			get { return layers; }
+		}
+		
+		sealed class LayerCollection : UIElementCollection
+		{
+			readonly TextView textView;
+			
+			public LayerCollection(TextView textView)
+				: base(textView, textView)
+			{
+				this.textView = textView;
+			}
+			
+			public override void Clear()
+			{
+				base.Clear();
+				textView.LayersChanged();
+			}
+			
+			public override int Add(UIElement element)
+			{
+				int r = base.Add(element);
+				textView.LayersChanged();
+				return r;
+			}
+			
+			public override void RemoveAt(int index)
+			{
+				base.RemoveAt(index);
+				textView.LayersChanged();
+			}
+			
+			public override void RemoveRange(int index, int count)
+			{
+				base.RemoveRange(index, count);
+				textView.LayersChanged();
+			}
+		}
+		
+		void LayersChanged()
+		{
+			textLayer.index = layers.IndexOf(textLayer);
+		}
+		
+		/// <summary>
+		/// Inserts a new layer at a position specified relative to an existing layer.
+		/// </summary>
+		/// <param name="layer">The new layer to insert.</param>
+		/// <param name="referencedLayer">The existing layer</param>
+		/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
+		public void InsertLayer(UIElement layer, KnownLayer referencedLayer, LayerInsertionPosition position)
+		{
+			if (layer == null)
+				throw new ArgumentNullException("layer");
+			if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
+				throw new InvalidEnumArgumentException("referencedLayer", (int)referencedLayer, typeof(KnownLayer));
+			if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
+				throw new InvalidEnumArgumentException("position", (int)position, typeof(LayerInsertionPosition));
+			if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
+				throw new InvalidOperationException("Cannot replace or insert below the background layer.");
+			
+			LayerPosition newPosition = new LayerPosition(referencedLayer, position);
+			LayerPosition.SetLayerPosition(layer, newPosition);
+			for (int i = 0; i < layers.Count; i++) {
+				LayerPosition p = LayerPosition.GetLayerPosition(layers[i]);
+				if (p != null) {
+					if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) {
+						// found the referenced layer
+						switch (position) {
+							case LayerInsertionPosition.Below:
+								layers.Insert(i, layer);
+								return;
+							case LayerInsertionPosition.Above:
+								layers.Insert(i + 1, layer);
+								return;
+							case LayerInsertionPosition.Replace:
+								layers[i] = layer;
+								return;
+						}
+					} else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
+					           || p.KnownLayer > referencedLayer) {
+						// we skipped the insertion position (referenced layer does not exist?)
+						layers.Insert(i, layer);
+						return;
+					}
+				}
+			}
+			// inserting after all existing layers:
+			layers.Add(layer);
+		}
+		
+		/// <inheritdoc/>
+		protected override int VisualChildrenCount {
+			get { return layers.Count + inlineObjects.Count; }
+		}
+		
+		/// <inheritdoc/>
+		protected override Visual GetVisualChild(int index)
+		{
+			int cut = textLayer.index + 1;
+			if (index < cut)
+				return layers[index];
+			else if (index < cut + inlineObjects.Count)
+				return inlineObjects[index - cut].Element;
+			else
+				return layers[index - inlineObjects.Count];
+		}
+		
+		/// <inheritdoc/>
+		protected override System.Collections.IEnumerator LogicalChildren {
+			get {
+				return inlineObjects.Select(io => io.Element).Concat(layers.Cast<UIElement>()).GetEnumerator();
+			}
+		}
+		#endregion
+		
+		#region Inline object handling
+		List<InlineObjectRun> inlineObjects = new List<InlineObjectRun>();
+		
+		/// <summary>
+		/// Adds a new inline object.
+		/// </summary>
+		internal void AddInlineObject(InlineObjectRun inlineObject)
+		{
+			Debug.Assert(inlineObject.VisualLine != null);
+			
+			// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
+			bool alreadyAdded = false;
+			for (int i = 0; i < inlineObjects.Count; i++) {
+				if (inlineObjects[i].Element == inlineObject.Element) {
+					RemoveInlineObjectRun(inlineObjects[i], true);
+					inlineObjects.RemoveAt(i);
+					alreadyAdded = true;
+					break;
+				}
+			}
+			
+			inlineObjects.Add(inlineObject);
+			if (!alreadyAdded) {
+				AddVisualChild(inlineObject.Element);
+			}
+			inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
+			inlineObject.desiredSize = inlineObject.Element.DesiredSize;
+		}
+		
+		void MeasureInlineObjects()
+		{
+			// As part of MeasureOverride(), re-measure the inline objects
+			foreach (InlineObjectRun inlineObject in inlineObjects) {
+				if (inlineObject.VisualLine.IsDisposed) {
+					// Don't re-measure inline objects that are going to be removed anyways.
+					// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
+					continue;
+				}
+				inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
+				if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.desiredSize)) {
+					// the element changed size -> recreate its parent visual line
+					inlineObject.desiredSize = inlineObject.Element.DesiredSize;
+					if (allVisualLines.Remove(inlineObject.VisualLine)) {
+						DisposeVisualLine(inlineObject.VisualLine);
+					}
+				}
+			}
+		}
+		
+		List<VisualLine> visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
+		
+		void RemoveInlineObjects(VisualLine visualLine)
+		{
+			// Delay removing inline objects:
+			// A document change immediately invalidates affected visual lines, but it does not
+			// cause an immediate redraw.
+			// To prevent inline objects from flickering when they are recreated, we delay removing
+			// inline objects until the next redraw.
+			if (visualLine.hasInlineObjects) {
+				visualLinesWithOutstandingInlineObjects.Add(visualLine);
+			}
+		}
+		
+		/// <summary>
+		/// Remove the inline objects that were marked for removal.
+		/// </summary>
+		void RemoveInlineObjectsNow()
+		{
+			if (visualLinesWithOutstandingInlineObjects.Count == 0)
+				return;
+			inlineObjects.RemoveAll(
+				ior => {
+					if (visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) {
+						RemoveInlineObjectRun(ior, false);
+						return true;
+					}
+					return false;
+				});
+			visualLinesWithOutstandingInlineObjects.Clear();
+		}
+
+		// Remove InlineObjectRun.Element from TextLayer.
+		// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
+		void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
+		{
+			if (!keepElement && ior.Element.IsKeyboardFocusWithin) {
+				// When the inline element that has the focus is removed, WPF will reset the
+				// focus to the main window without raising appropriate LostKeyboardFocus events.
+				// To work around this, we manually set focus to the next focusable parent.
+				UIElement element = this;
+				while (element != null && !element.Focusable) {
+					element = VisualTreeHelper.GetParent(element) as UIElement;
+				}
+				if (element != null)
+					Keyboard.Focus(element);
+			}
+			ior.VisualLine = null;
+			if (!keepElement)
+				RemoveVisualChild(ior.Element);
+		}
+		#endregion
+		
+		#region Brushes
+		/// <summary>
+		/// NonPrintableCharacterBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty NonPrintableCharacterBrushProperty =
+			DependencyProperty.Register("NonPrintableCharacterBrush", typeof(Brush), typeof(TextView),
+			                            new FrameworkPropertyMetadata(Brushes.LightGray));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying non-printable characters.
+		/// </summary>
+		public Brush NonPrintableCharacterBrush {
+			get { return (Brush)GetValue(NonPrintableCharacterBrushProperty); }
+			set { SetValue(NonPrintableCharacterBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// LinkTextForegroundBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty LinkTextForegroundBrushProperty =
+			DependencyProperty.Register("LinkTextForegroundBrush", typeof(Brush), typeof(TextView),
+			                            new FrameworkPropertyMetadata(Brushes.Blue));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying link texts.
+		/// </summary>
+		public Brush LinkTextForegroundBrush {
+			get { return (Brush)GetValue(LinkTextForegroundBrushProperty); }
+			set { SetValue(LinkTextForegroundBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// LinkTextBackgroundBrush dependency property.
+		/// </summary>
+		public static readonly DependencyProperty LinkTextBackgroundBrushProperty =
+			DependencyProperty.Register("LinkTextBackgroundBrush", typeof(Brush), typeof(TextView),
+			                            new FrameworkPropertyMetadata(Brushes.Transparent));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for the background of link texts.
+		/// </summary>
+		public Brush LinkTextBackgroundBrush {
+			get { return (Brush)GetValue(LinkTextBackgroundBrushProperty); }
+			set { SetValue(LinkTextBackgroundBrushProperty, value); }
+		}
+		#endregion
+		
+		#region Redraw methods / VisualLine invalidation
+		/// <summary>
+		/// Causes the text editor to regenerate all visual lines.
+		/// </summary>
+		public void Redraw()
+		{
+			Redraw(DispatcherPriority.Normal);
+		}
+		
+		/// <summary>
+		/// Causes the text editor to regenerate all visual lines.
+		/// </summary>
+		public void Redraw(DispatcherPriority redrawPriority)
+		{
+			VerifyAccess();
+			ClearVisualLines();
+			InvalidateMeasure(redrawPriority);
+		}
+		
+		/// <summary>
+		/// Causes the text editor to regenerate the specified visual line.
+		/// </summary>
+		public void Redraw(VisualLine visualLine, DispatcherPriority redrawPriority = DispatcherPriority.Normal)
+		{
+			VerifyAccess();
+			if (allVisualLines.Remove(visualLine)) {
+				DisposeVisualLine(visualLine);
+				InvalidateMeasure(redrawPriority);
+			}
+		}
+		
+		/// <summary>
+		/// Causes the text editor to redraw all lines overlapping with the specified segment.
+		/// </summary>
+		public void Redraw(int offset, int length, DispatcherPriority redrawPriority = DispatcherPriority.Normal)
+		{
+			VerifyAccess();
+			bool changedSomethingBeforeOrInLine = false;
+			for (int i = 0; i < allVisualLines.Count; i++) {
+				VisualLine visualLine = allVisualLines[i];
+				int lineStart = visualLine.FirstDocumentLine.Offset;
+				int lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
+				if (offset <= lineEnd) {
+					changedSomethingBeforeOrInLine = true;
+					if (offset + length >= lineStart) {
+						allVisualLines.RemoveAt(i--);
+						DisposeVisualLine(visualLine);
+					}
+				}
+			}
+			if (changedSomethingBeforeOrInLine) {
+				// Repaint not only when something in visible area was changed, but also when anything in front of it
+				// was changed. We might have to redraw the line number margin. Or the highlighting changed.
+				// However, we'll try to reuse the existing VisualLines.
+				InvalidateMeasure(redrawPriority);
+			}
+		}
+		
+		/// <summary>
+		/// Causes a known layer to redraw.
+		/// This method does not invalidate visual lines;
+		/// use the <see cref="Redraw()"/> method to do that.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
+		                                                 Justification="This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
+		public void InvalidateLayer(KnownLayer knownLayer)
+		{
+			InvalidateMeasure(DispatcherPriority.Normal);
+		}
+		
+		/// <summary>
+		/// Causes a known layer to redraw.
+		/// This method does not invalidate visual lines;
+		/// use the <see cref="Redraw()"/> method to do that.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
+		                                                 Justification="This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
+		public void InvalidateLayer(KnownLayer knownLayer, DispatcherPriority priority)
+		{
+			InvalidateMeasure(priority);
+		}
+		
+		/// <summary>
+		/// Causes the text editor to redraw all lines overlapping with the specified segment.
+		/// Does nothing if segment is null.
+		/// </summary>
+		public void Redraw(ISegment segment, DispatcherPriority redrawPriority = DispatcherPriority.Normal)
+		{
+			if (segment != null) {
+				Redraw(segment.Offset, segment.Length, redrawPriority);
+			}
+		}
+		
+		/// <summary>
+		/// Invalidates all visual lines.
+		/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
+		/// that the visual lines will be recreated.
+		/// </summary>
+		void ClearVisualLines()
+		{
+			visibleVisualLines = null;
+			if (allVisualLines.Count != 0) {
+				foreach (VisualLine visualLine in allVisualLines) {
+					DisposeVisualLine(visualLine);
+				}
+				allVisualLines.Clear();
+			}
+		}
+		
+		void DisposeVisualLine(VisualLine visualLine)
+		{
+			if (newVisualLines != null && newVisualLines.Contains(visualLine)) {
+				throw new ArgumentException("Cannot dispose visual line because it is in construction!");
+			}
+			visibleVisualLines = null;
+			visualLine.Dispose();
+			RemoveInlineObjects(visualLine);
+		}
+		#endregion
+		
+		#region InvalidateMeasure(DispatcherPriority)
+		DispatcherOperation invalidateMeasureOperation;
+		
+		void InvalidateMeasure(DispatcherPriority priority)
+		{
+			if (priority >= DispatcherPriority.Render) {
+				if (invalidateMeasureOperation != null) {
+					invalidateMeasureOperation.Abort();
+					invalidateMeasureOperation = null;
+				}
+				base.InvalidateMeasure();
+			} else {
+				if (invalidateMeasureOperation != null) {
+					invalidateMeasureOperation.Priority = priority;
+				} else {
+					invalidateMeasureOperation = Dispatcher.BeginInvoke(
+						priority,
+						new Action(
+							delegate {
+								invalidateMeasureOperation = null;
+								base.InvalidateMeasure();
+							}
+						)
+					);
+				}
+			}
+		}
+		#endregion
+		
+		#region Get(OrConstruct)VisualLine
+		/// <summary>
+		/// Gets the visual line that contains the document line with the specified number.
+		/// Returns null if the document line is outside the visible range.
+		/// </summary>
+		public VisualLine GetVisualLine(int documentLineNumber)
+		{
+			// TODO: EnsureVisualLines() ?
+			foreach (VisualLine visualLine in allVisualLines) {
+				Debug.Assert(visualLine.IsDisposed == false);
+				int start = visualLine.FirstDocumentLine.LineNumber;
+				int end = visualLine.LastDocumentLine.LineNumber;
+				if (documentLineNumber >= start && documentLineNumber <= end)
+					return visualLine;
+			}
+			return null;
+		}
+		
+		/// <summary>
+		/// Gets the visual line that contains the document line with the specified number.
+		/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
+		/// </summary>
+		public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
+		{
+			if (documentLine == null)
+				throw new ArgumentNullException("documentLine");
+			if (!this.Document.Lines.Contains(documentLine))
+				throw new InvalidOperationException("Line belongs to wrong document");
+			VerifyAccess();
+			
+			VisualLine l = GetVisualLine(documentLine.LineNumber);
+			if (l == null) {
+				TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
+				VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
+				
+				while (heightTree.GetIsCollapsed(documentLine.LineNumber)) {
+					documentLine = documentLine.PreviousLine;
+				}
+				
+				l = BuildVisualLine(documentLine,
+				                    globalTextRunProperties, paragraphProperties,
+				                    elementGenerators.ToArray(), lineTransformers.ToArray(),
+				                    lastAvailableSize);
+				allVisualLines.Add(l);
+				// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
+				foreach (var line in allVisualLines) {
+					line.VisualTop = heightTree.GetVisualPosition(line.FirstDocumentLine);
+				}
+			}
+			return l;
+		}
+		#endregion
+		
+		#region Visual Lines (fields and properties)
+		List<VisualLine> allVisualLines = new List<VisualLine>();
+		ReadOnlyCollection<VisualLine> visibleVisualLines;
+		double clippedPixelsOnTop;
+		List<VisualLine> newVisualLines;
+		
+		/// <summary>
+		/// Gets the currently visible visual lines.
+		/// </summary>
+		/// <exception cref="VisualLinesInvalidException">
+		/// Gets thrown if there are invalid visual lines when this property is accessed.
+		/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
+		/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
+		/// when they are invalid.
+		/// </exception>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
+		public ReadOnlyCollection<VisualLine> VisualLines {
+			get {
+				if (visibleVisualLines == null)
+					throw new VisualLinesInvalidException();
+				return visibleVisualLines;
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether the visual lines are valid.
+		/// Will return false after a call to Redraw().
+		/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
+		/// if this property is <c>false</c>.
+		/// </summary>
+		public bool VisualLinesValid {
+			get { return visibleVisualLines != null; }
+		}
+		
+		/// <summary>
+		/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
+		/// This event may be used to mark visual lines as invalid that would otherwise be reused.
+		/// </summary>
+		public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
+		
+		/// <summary>
+		/// Occurs when the TextView was measured and changed its visual lines.
+		/// </summary>
+		public event EventHandler VisualLinesChanged;
+		
+		/// <summary>
+		/// If the visual lines are invalid, creates new visual lines for the visible part
+		/// of the document.
+		/// If all visual lines are valid, this method does nothing.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The visual line build process is already running.
+		/// It is not allowed to call this method during the construction of a visual line.</exception>
+		public void EnsureVisualLines()
+		{
+			Dispatcher.VerifyAccess();
+			if (inMeasure)
+				throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
+			if (!VisualLinesValid) {
+				// increase priority for re-measure
+				InvalidateMeasure(DispatcherPriority.Normal);
+				// force immediate re-measure
+				UpdateLayout();
+			}
+			// Sometimes we still have invalid lines after UpdateLayout - work around the problem
+			// by calling MeasureOverride directly.
+			if (!VisualLinesValid) {
+				Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
+				MeasureOverride(lastAvailableSize);
+			}
+			if (!VisualLinesValid)
+				throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
+		}
+		#endregion
+		
+		#region Measure
+		/// <summary>
+		/// Additonal amount that allows horizontal scrolling past the end of the longest line.
+		/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
+		/// </summary>
+		const double AdditionalHorizontalScrollAmount = 3;
+		
+		Size lastAvailableSize;
+		bool inMeasure;
+		
+		/// <inheritdoc/>
+		protected override Size MeasureOverride(Size availableSize)
+		{
+			// We don't support infinite available width, so we'll limit it to 32000 pixels.
+			if (availableSize.Width > 32000)
+				availableSize.Width = 32000;
+			
+			if (!canHorizontallyScroll && !availableSize.Width.IsClose(lastAvailableSize.Width))
+				ClearVisualLines();
+			lastAvailableSize = availableSize;
+			
+			foreach (UIElement layer in layers) {
+				layer.Measure(availableSize);
+			}
+			MeasureInlineObjects();
+			
+			InvalidateVisual(); // = InvalidateArrange+InvalidateRender
+			
+			double maxWidth;
+			if (document == null) {
+				// no document -> create empty list of lines
+				allVisualLines = new List<VisualLine>();
+				visibleVisualLines = allVisualLines.AsReadOnly();
+				maxWidth = 0;
+			} else {
+				inMeasure = true;
+				try {
+					maxWidth = CreateAndMeasureVisualLines(availableSize);
+				} finally {
+					inMeasure = false;
+				}
+			}
+			
+			// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
+			RemoveInlineObjectsNow();
+			
+			maxWidth += AdditionalHorizontalScrollAmount;
+			double heightTreeHeight = this.DocumentHeight;
+			TextEditorOptions options = this.Options;
+			if (options.AllowScrollBelowDocument) {
+				if (!double.IsInfinity(scrollViewport.Height)) {
+					heightTreeHeight = Math.Max(heightTreeHeight, Math.Min(heightTreeHeight - 50, scrollOffset.Y) + scrollViewport.Height);
+				}
+			}
+			
+			textLayer.SetVisualLines(visibleVisualLines);
+			
+			SetScrollData(availableSize,
+			              new Size(maxWidth, heightTreeHeight),
+			              scrollOffset);
+			if (VisualLinesChanged != null)
+				VisualLinesChanged(this, EventArgs.Empty);
+			
+			return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight));
+		}
+		
+		/// <summary>
+		/// Build all VisualLines in the visible range.
+		/// </summary>
+		/// <returns>Width the longest line</returns>
+		double CreateAndMeasureVisualLines(Size availableSize)
+		{
+			TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
+			VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
+			
+			Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + scrollOffset);
+			var firstLineInView = heightTree.GetLineByVisualPosition(scrollOffset.Y);
+			
+			// number of pixels clipped from the first visual line(s)
+			clippedPixelsOnTop = scrollOffset.Y - heightTree.GetVisualPosition(firstLineInView);
+			// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
+			Debug.Assert(clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
+			
+			newVisualLines = new List<VisualLine>();
+			
+			if (VisualLineConstructionStarting != null)
+				VisualLineConstructionStarting(this, new VisualLineConstructionStartEventArgs(firstLineInView));
+			
+			var elementGeneratorsArray = elementGenerators.ToArray();
+			var lineTransformersArray = lineTransformers.ToArray();
+			var nextLine = firstLineInView;
+			double maxWidth = 0;
+			double yPos = -clippedPixelsOnTop;
+			while (yPos < availableSize.Height && nextLine != null) {
+				VisualLine visualLine = GetVisualLine(nextLine.LineNumber);
+				if (visualLine == null) {
+					visualLine = BuildVisualLine(nextLine,
+					                             globalTextRunProperties, paragraphProperties,
+					                             elementGeneratorsArray, lineTransformersArray,
+					                             availableSize);
+				}
+				
+				visualLine.VisualTop = scrollOffset.Y + yPos;
+				
+				nextLine = visualLine.LastDocumentLine.NextLine;
+				
+				yPos += visualLine.Height;
+				
+				foreach (TextLine textLine in visualLine.TextLines) {
+					if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
+						maxWidth = textLine.WidthIncludingTrailingWhitespace;
+				}
+				
+				newVisualLines.Add(visualLine);
+			}
+			
+			foreach (VisualLine line in allVisualLines) {
+				Debug.Assert(line.IsDisposed == false);
+				if (!newVisualLines.Contains(line))
+					DisposeVisualLine(line);
+			}
+			
+			allVisualLines = newVisualLines;
+			// visibleVisualLines = readonly copy of visual lines
+			visibleVisualLines = new ReadOnlyCollection<VisualLine>(newVisualLines.ToArray());
+			newVisualLines = null;
+			
+			if (allVisualLines.Any(line => line.IsDisposed)) {
+				throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
+				                                    "This can happen when Redraw() is called during measure for lines " +
+				                                    "that are already constructed.");
+			}
+			return maxWidth;
+		}
+		#endregion
+		
+		#region BuildVisualLine
+		TextFormatter formatter;
+		internal TextViewCachedElements cachedElements;
+		
+		TextRunProperties CreateGlobalTextRunProperties()
+		{
+			var p = new GlobalTextRunProperties();
+			p.typeface = this.CreateTypeface();
+			p.fontRenderingEmSize = FontSize;
+			p.foregroundBrush = (Brush)GetValue(Control.ForegroundProperty);
+			ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
+			p.cultureInfo = CultureInfo.CurrentCulture;
+			return p;
+		}
+		
+		VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
+		{
+			return new VisualLineTextParagraphProperties {
+				defaultTextRunProperties = defaultTextRunProperties,
+				textWrapping = canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
+				tabSize = Options.IndentationSize * WideSpaceWidth
+			};
+		}
+		
+		VisualLine BuildVisualLine(DocumentLine documentLine,
+		                           TextRunProperties globalTextRunProperties,
+		                           VisualLineTextParagraphProperties paragraphProperties,
+		                           VisualLineElementGenerator[] elementGeneratorsArray,
+		                           IVisualLineTransformer[] lineTransformersArray,
+		                           Size availableSize)
+		{
+			if (heightTree.GetIsCollapsed(documentLine.LineNumber))
+				throw new InvalidOperationException("Trying to build visual line from collapsed line");
+			
+			//Debug.WriteLine("Building line " + documentLine.LineNumber);
+			
+			VisualLine visualLine = new VisualLine(this, documentLine);
+			VisualLineTextSource textSource = new VisualLineTextSource(visualLine) {
+				Document = document,
+				GlobalTextRunProperties = globalTextRunProperties,
+				TextView = this
+			};
+			
+			visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
+			
+			if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) {
+				// Check whether the lines are collapsed correctly:
+				double firstLinePos = heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
+				double lastLinePos = heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
+				if (!firstLinePos.IsClose(lastLinePos)) {
+					for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) {
+						if (!heightTree.GetIsCollapsed(i))
+							throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
+					}
+					throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
+				}
+			}
+			
+			visualLine.RunTransformers(textSource, lineTransformersArray);
+			
+			// now construct textLines:
+			int textOffset = 0;
+			TextLineBreak lastLineBreak = null;
+			var textLines = new List<TextLine>();
+			paragraphProperties.indent = 0;
+			paragraphProperties.firstLineInParagraph = true;
+			while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) {
+				TextLine textLine = formatter.FormatLine(
+					textSource,
+					textOffset,
+					availableSize.Width,
+					paragraphProperties,
+					lastLineBreak
+				);
+				textLines.Add(textLine);
+				textOffset += textLine.Length;
+				
+				// exit loop so that we don't do the indentation calculation if there's only a single line
+				if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
+					break;
+				
+				if (paragraphProperties.firstLineInParagraph) {
+					paragraphProperties.firstLineInParagraph = false;
+					
+					TextEditorOptions options = this.Options;
+					double indentation = 0;
+					if (options.InheritWordWrapIndentation) {
+						// determine indentation for next line:
+						int indentVisualColumn = GetIndentationVisualColumn(visualLine);
+						if (indentVisualColumn > 0 && indentVisualColumn < textOffset) {
+							indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
+						}
+					}
+					indentation += options.WordWrapIndentation;
+					// apply the calculated indentation unless it's more than half of the text editor size:
+					if (indentation > 0 && indentation * 2 < availableSize.Width)
+						paragraphProperties.indent = indentation;
+				}
+				lastLineBreak = textLine.GetTextLineBreak();
+			}
+			visualLine.SetTextLines(textLines);
+			heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
+			return visualLine;
+		}
+		
+		static int GetIndentationVisualColumn(VisualLine visualLine)
+		{
+			if (visualLine.Elements.Count == 0)
+				return 0;
+			int column = 0;
+			int elementIndex = 0;
+			VisualLineElement element = visualLine.Elements[elementIndex];
+			while (element.IsWhitespace(column)) {
+				column++;
+				if (column == element.VisualColumn + element.VisualLength) {
+					elementIndex++;
+					if (elementIndex == visualLine.Elements.Count)
+						break;
+					element = visualLine.Elements[elementIndex];
+				}
+			}
+			return column;
+		}
+		#endregion
+		
+		#region Arrange
+		/// <summary>
+		/// Arrange implementation.
+		/// </summary>
+		protected override Size ArrangeOverride(Size finalSize)
+		{
+			EnsureVisualLines();
+			
+			foreach (UIElement layer in layers) {
+				layer.Arrange(new Rect(new Point(0, 0), finalSize));
+			}
+			
+			if (document == null || allVisualLines.Count == 0)
+				return finalSize;
+			
+			// validate scroll position
+			Vector newScrollOffset = scrollOffset;
+			if (scrollOffset.X + finalSize.Width > scrollExtent.Width) {
+				newScrollOffset.X = Math.Max(0, scrollExtent.Width - finalSize.Width);
+			}
+			if (scrollOffset.Y + finalSize.Height > scrollExtent.Height) {
+				newScrollOffset.Y = Math.Max(0, scrollExtent.Height - finalSize.Height);
+			}
+			if (SetScrollData(scrollViewport, scrollExtent, newScrollOffset))
+				InvalidateMeasure(DispatcherPriority.Normal);
+			
+			//Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + scrollOffset);
+			
+//			double maxWidth = 0;
+			
+			if (visibleVisualLines != null) {
+				Point pos = new Point(-scrollOffset.X, -clippedPixelsOnTop);
+				foreach (VisualLine visualLine in visibleVisualLines) {
+					int offset = 0;
+					foreach (TextLine textLine in visualLine.TextLines) {
+						foreach (var span in textLine.GetTextRunSpans()) {
+							InlineObjectRun inline = span.Value as InlineObjectRun;
+							if (inline != null && inline.VisualLine != null) {
+								Debug.Assert(inlineObjects.Contains(inline));
+								double distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset, 0));
+								inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize));
+							}
+							offset += span.Length;
+						}
+						pos.Y += textLine.Height;
+					}
+				}
+			}
+			InvalidateCursorIfMouseWithinTextView();
+			
+			return finalSize;
+		}
+		#endregion
+		
+		#region Render
+		readonly ObserveAddRemoveCollection<IBackgroundRenderer> backgroundRenderers;
+		
+		/// <summary>
+		/// Gets the list of background renderers.
+		/// </summary>
+		public IList<IBackgroundRenderer> BackgroundRenderers {
+			get { return backgroundRenderers; }
+		}
+		
+		void BackgroundRenderer_Added(IBackgroundRenderer renderer)
+		{
+			ConnectToTextView(renderer);
+			InvalidateLayer(renderer.Layer);
+		}
+		
+		void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
+		{
+			DisconnectFromTextView(renderer);
+			InvalidateLayer(renderer.Layer);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnRender(DrawingContext drawingContext)
+		{
+			RenderBackground(drawingContext, KnownLayer.Background);
+			foreach (var line in visibleVisualLines) {
+				Brush currentBrush = null;
+				int startVC = 0;
+				int length = 0;
+				foreach (var element in line.Elements) {
+					if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) {
+						if (currentBrush != null) {
+							BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder();
+							builder.AlignToWholePixels = true;
+							builder.CornerRadius = 3;
+							foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVC, startVC + length))
+								builder.AddRectangle(this, rect);
+							Geometry geometry = builder.CreateGeometry();
+							if (geometry != null) {
+								drawingContext.DrawGeometry(currentBrush, null, geometry);
+							}
+						}
+						startVC = element.VisualColumn;
+						length = element.DocumentLength;
+						currentBrush = element.BackgroundBrush;
+					} else {
+						length += element.VisualLength;
+					}
+				}
+				if (currentBrush != null) {
+					BackgroundGeometryBuilder builder = new BackgroundGeometryBuilder();
+					builder.AlignToWholePixels = true;
+					builder.CornerRadius = 3;
+					foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVC, startVC + length))
+						builder.AddRectangle(this, rect);
+					Geometry geometry = builder.CreateGeometry();
+					if (geometry != null) {
+						drawingContext.DrawGeometry(currentBrush, null, geometry);
+					}
+				}
+			}
+		}
+		
+		internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
+		{
+			foreach (IBackgroundRenderer bg in backgroundRenderers) {
+				if (bg.Layer == layer) {
+					bg.Draw(this, drawingContext);
+				}
+			}
+		}
+		
+		internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
+		{
+			Point pos = new Point(-scrollOffset.X, -clippedPixelsOnTop);
+			foreach (VisualLineDrawingVisual visual in visuals) {
+				TranslateTransform t = visual.Transform as TranslateTransform;
+				if (t == null || t.X != pos.X || t.Y != pos.Y) {
+					visual.Transform = new TranslateTransform(pos.X, pos.Y);
+					visual.Transform.Freeze();
+				}
+				pos.Y += visual.Height;
+			}
+		}
+		#endregion
+		
+		#region IScrollInfo implementation
+		/// <summary>
+		/// Size of the document, in pixels.
+		/// </summary>
+		Size scrollExtent;
+		
+		/// <summary>
+		/// Offset of the scroll position.
+		/// </summary>
+		Vector scrollOffset;
+		
+		/// <summary>
+		/// Size of the viewport.
+		/// </summary>
+		Size scrollViewport;
+		
+		void ClearScrollData()
+		{
+			SetScrollData(new Size(), new Size(), new Vector());
+		}
+		
+		bool SetScrollData(Size viewport, Size extent, Vector offset)
+		{
+			if (!(viewport.IsClose(this.scrollViewport)
+			      && extent.IsClose(this.scrollExtent)
+			      && offset.IsClose(this.scrollOffset)))
+			{
+				this.scrollViewport = viewport;
+				this.scrollExtent = extent;
+				SetScrollOffset(offset);
+				this.OnScrollChange();
+				return true;
+			}
+			return false;
+		}
+		
+		void OnScrollChange()
+		{
+			ScrollViewer scrollOwner = ((IScrollInfo)this).ScrollOwner;
+			if (scrollOwner != null) {
+				scrollOwner.InvalidateScrollInfo();
+			}
+		}
+		
+		bool canVerticallyScroll;
+		bool IScrollInfo.CanVerticallyScroll {
+			get { return canVerticallyScroll; }
+			set {
+				if (canVerticallyScroll != value) {
+					canVerticallyScroll = value;
+					InvalidateMeasure(DispatcherPriority.Normal);
+				}
+			}
+		}
+		bool canHorizontallyScroll;
+		bool IScrollInfo.CanHorizontallyScroll {
+			get { return canHorizontallyScroll; }
+			set {
+				if (canHorizontallyScroll != value) {
+					canHorizontallyScroll = value;
+					ClearVisualLines();
+					InvalidateMeasure(DispatcherPriority.Normal);
+				}
+			}
+		}
+		
+		double IScrollInfo.ExtentWidth {
+			get { return scrollExtent.Width; }
+		}
+		
+		double IScrollInfo.ExtentHeight {
+			get { return scrollExtent.Height; }
+		}
+		
+		double IScrollInfo.ViewportWidth {
+			get { return scrollViewport.Width; }
+		}
+		
+		double IScrollInfo.ViewportHeight {
+			get { return scrollViewport.Height; }
+		}
+		
+		/// <summary>
+		/// Gets the horizontal scroll offset.
+		/// </summary>
+		public double HorizontalOffset {
+			get { return scrollOffset.X; }
+		}
+		
+		/// <summary>
+		/// Gets the vertical scroll offset.
+		/// </summary>
+		public double VerticalOffset {
+			get { return scrollOffset.Y; }
+		}
+		
+		/// <summary>
+		/// Gets the scroll offset;
+		/// </summary>
+		public Vector ScrollOffset {
+			get { return scrollOffset; }
+		}
+		
+		/// <summary>
+		/// Occurs when the scroll offset has changed.
+		/// </summary>
+		public event EventHandler ScrollOffsetChanged;
+		
+		void SetScrollOffset(Vector vector)
+		{
+			if (!canHorizontallyScroll)
+				vector.X = 0;
+			if (!canVerticallyScroll)
+				vector.Y = 0;
+			
+			if (!scrollOffset.IsClose(vector)) {
+				scrollOffset = vector;
+				if (ScrollOffsetChanged != null)
+					ScrollOffsetChanged(this, EventArgs.Empty);
+			}
+		}
+		
+		ScrollViewer IScrollInfo.ScrollOwner { get; set; }
+		
+		void IScrollInfo.LineUp()
+		{
+			((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y - DefaultLineHeight);
+		}
+		
+		void IScrollInfo.LineDown()
+		{
+			((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y + DefaultLineHeight);
+		}
+		
+		void IScrollInfo.LineLeft()
+		{
+			((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X - WideSpaceWidth);
+		}
+		
+		void IScrollInfo.LineRight()
+		{
+			((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X + WideSpaceWidth);
+		}
+		
+		void IScrollInfo.PageUp()
+		{
+			((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y - scrollViewport.Height);
+		}
+		
+		void IScrollInfo.PageDown()
+		{
+			((IScrollInfo)this).SetVerticalOffset(scrollOffset.Y + scrollViewport.Height);
+		}
+		
+		void IScrollInfo.PageLeft()
+		{
+			((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X - scrollViewport.Width);
+		}
+		
+		void IScrollInfo.PageRight()
+		{
+			((IScrollInfo)this).SetHorizontalOffset(scrollOffset.X + scrollViewport.Width);
+		}
+		
+		void IScrollInfo.MouseWheelUp()
+		{
+			((IScrollInfo)this).SetVerticalOffset(
+				scrollOffset.Y - (SystemParameters.WheelScrollLines * DefaultLineHeight));
+			OnScrollChange();
+		}
+		
+		void IScrollInfo.MouseWheelDown()
+		{
+			((IScrollInfo)this).SetVerticalOffset(
+				scrollOffset.Y + (SystemParameters.WheelScrollLines * DefaultLineHeight));
+			OnScrollChange();
+		}
+		
+		void IScrollInfo.MouseWheelLeft()
+		{
+			((IScrollInfo)this).SetHorizontalOffset(
+				scrollOffset.X - (SystemParameters.WheelScrollLines * WideSpaceWidth));
+			OnScrollChange();
+		}
+		
+		void IScrollInfo.MouseWheelRight()
+		{
+			((IScrollInfo)this).SetHorizontalOffset(
+				scrollOffset.X + (SystemParameters.WheelScrollLines * WideSpaceWidth));
+			OnScrollChange();
+		}
+		
+		bool defaultTextMetricsValid;
+		double wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
+		double defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
+		double defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
+		
+		/// <summary>
+		/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
+		/// </summary>
+		/// <remarks>
+		/// This is the width of an 'x' in the current font.
+		/// We do not measure the width of an actual space as that would lead to tiny tabs in
+		/// some proportional fonts.
+		/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
+		/// </remarks>
+		public double WideSpaceWidth {
+			get {
+				CalculateDefaultTextMetrics();
+				return wideSpaceWidth;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the default line height. This is the height of an empty line or a line containing regular text.
+		/// Lines that include formatted text or custom UI elements may have a different line height.
+		/// </summary>
+		public double DefaultLineHeight {
+			get {
+				CalculateDefaultTextMetrics();
+				return defaultLineHeight;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
+		/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
+		/// Lines that include formatted text or custom UI elements may have a different baseline.
+		/// </summary>
+		public double DefaultBaseline {
+			get {
+				CalculateDefaultTextMetrics();
+				return defaultBaseline;
+			}
+		}
+		
+		void InvalidateDefaultTextMetrics()
+		{
+			defaultTextMetricsValid = false;
+			if (heightTree != null) {
+				// calculate immediately so that height tree gets updated
+				CalculateDefaultTextMetrics();
+			}
+		}
+		
+		void CalculateDefaultTextMetrics()
+		{
+			if (defaultTextMetricsValid)
+				return;
+			defaultTextMetricsValid = true;
+			if (formatter != null) {
+				var textRunProperties = CreateGlobalTextRunProperties();
+				using (var line = formatter.FormatLine(
+					new SimpleTextSource("x", textRunProperties),
+					0, 32000,
+					new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
+					null))
+				{
+					wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
+					defaultBaseline = Math.Max(1, line.Baseline);
+					defaultLineHeight = Math.Max(1, line.Height);
+				}
+			} else {
+				wideSpaceWidth = FontSize / 2;
+				defaultBaseline = FontSize;
+				defaultLineHeight = FontSize + 3;
+			}
+			// Update heightTree.DefaultLineHeight, if a document is loaded.
+			if (heightTree != null)
+				heightTree.DefaultLineHeight = defaultLineHeight;
+		}
+		
+		static double ValidateVisualOffset(double offset)
+		{
+			if (double.IsNaN(offset))
+				throw new ArgumentException("offset must not be NaN");
+			if (offset < 0)
+				return 0;
+			else
+				return offset;
+		}
+		
+		void IScrollInfo.SetHorizontalOffset(double offset)
+		{
+			offset = ValidateVisualOffset(offset);
+			if (!scrollOffset.X.IsClose(offset)) {
+				SetScrollOffset(new Vector(offset, scrollOffset.Y));
+				InvalidateVisual();
+				textLayer.InvalidateVisual();
+			}
+		}
+		
+		void IScrollInfo.SetVerticalOffset(double offset)
+		{
+			offset = ValidateVisualOffset(offset);
+			if (!scrollOffset.Y.IsClose(offset)) {
+				SetScrollOffset(new Vector(scrollOffset.X, offset));
+				InvalidateMeasure(DispatcherPriority.Normal);
+			}
+		}
+		
+		Rect IScrollInfo.MakeVisible(Visual visual, Rect rectangle)
+		{
+			if (rectangle.IsEmpty || visual == null || visual == this || !this.IsAncestorOf(visual)) {
+				return Rect.Empty;
+			}
+			// Convert rectangle into our coordinate space.
+			GeneralTransform childTransform = visual.TransformToAncestor(this);
+			rectangle = childTransform.TransformBounds(rectangle);
+			
+			MakeVisible(Rect.Offset(rectangle, scrollOffset));
+			
+			return rectangle;
+		}
+		
+		/// <summary>
+		/// Scrolls the text view so that the specified rectangle gets visible.
+		/// </summary>
+		public void MakeVisible(Rect rectangle)
+		{
+			Rect visibleRectangle = new Rect(scrollOffset.X, scrollOffset.Y,
+			                                 scrollViewport.Width, scrollViewport.Height);
+			Vector newScrollOffset = scrollOffset;
+			if (rectangle.Left < visibleRectangle.Left) {
+				if (rectangle.Right > visibleRectangle.Right) {
+					newScrollOffset.X = rectangle.Left + rectangle.Width / 2;
+				} else {
+					newScrollOffset.X = rectangle.Left;
+				}
+			} else if (rectangle.Right > visibleRectangle.Right) {
+				newScrollOffset.X = rectangle.Right - scrollViewport.Width;
+			}
+			if (rectangle.Top < visibleRectangle.Top) {
+				if (rectangle.Bottom > visibleRectangle.Bottom) {
+					newScrollOffset.Y = rectangle.Top + rectangle.Height / 2;
+				} else {
+					newScrollOffset.Y = rectangle.Top;
+				}
+			} else if (rectangle.Bottom > visibleRectangle.Bottom) {
+				newScrollOffset.Y = rectangle.Bottom - scrollViewport.Height;
+			}
+			newScrollOffset.X = ValidateVisualOffset(newScrollOffset.X);
+			newScrollOffset.Y = ValidateVisualOffset(newScrollOffset.Y);
+			if (!scrollOffset.IsClose(newScrollOffset)) {
+				SetScrollOffset(newScrollOffset);
+				this.OnScrollChange();
+				InvalidateMeasure(DispatcherPriority.Normal);
+			}
+		}
+		#endregion
+		
+		#region Visual element mouse handling
+		/// <inheritdoc/>
+		protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
+		{
+			// accept clicks even where the text area draws no background
+			return new PointHitTestResult(this, hitTestParameters.HitPoint);
+		}
+		
+		[ThreadStatic] static bool invalidCursor;
+		
+		/// <summary>
+		/// Updates the mouse cursor by calling <see cref="Mouse.UpdateCursor"/>, but with background priority.
+		/// </summary>
+		public static void InvalidateCursor()
+		{
+			if (!invalidCursor) {
+				invalidCursor = true;
+				Dispatcher.CurrentDispatcher.BeginInvoke(
+					DispatcherPriority.Background, // fixes issue #288
+					new Action(
+						delegate {
+							invalidCursor = false;
+							Mouse.UpdateCursor();
+						}));
+			}
+		}
+		
+		internal void InvalidateCursorIfMouseWithinTextView()
+		{
+			// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
+			// Unnecessary updates may cause the mouse pointer to flicker
+			// (e.g. if it is over a window border, it blinks between Resize and Normal)
+			if (this.IsMouseOver)
+				InvalidateCursor();
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnQueryCursor(QueryCursorEventArgs e)
+		{
+			VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset);
+			if (element != null) {
+				element.OnQueryCursor(e);
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnMouseDown(MouseButtonEventArgs e)
+		{
+			base.OnMouseDown(e);
+			if (!e.Handled) {
+				EnsureVisualLines();
+				VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset);
+				if (element != null) {
+					element.OnMouseDown(e);
+				}
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnMouseUp(MouseButtonEventArgs e)
+		{
+			base.OnMouseUp(e);
+			if (!e.Handled) {
+				EnsureVisualLines();
+				VisualLineElement element = GetVisualLineElementFromPosition(e.GetPosition(this) + scrollOffset);
+				if (element != null) {
+					element.OnMouseUp(e);
+				}
+			}
+		}
+		#endregion
+		
+		#region Getting elements from Visual Position
+		/// <summary>
+		/// Gets the visual line at the specified document position (relative to start of document).
+		/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
+		/// text area).
+		/// </summary>
+		public VisualLine GetVisualLineFromVisualTop(double visualTop)
+		{
+			// TODO: change this method to also work outside the visible range -
+			// required to make GetPosition work as expected!
+			EnsureVisualLines();
+			foreach (VisualLine vl in this.VisualLines) {
+				if (visualTop < vl.VisualTop)
+					continue;
+				if (visualTop < vl.VisualTop + vl.Height)
+					return vl;
+			}
+			return null;
+		}
+		
+		/// <summary>
+		/// Gets the visual top position (relative to start of document) from a document line number.
+		/// </summary>
+		public double GetVisualTopByDocumentLine(int line)
+		{
+			VerifyAccess();
+			if (heightTree == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			return heightTree.GetVisualPosition(heightTree.GetLineByNumber(line));
+		}
+		
+		VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
+		{
+			VisualLine vl = GetVisualLineFromVisualTop(visualPosition.Y);
+			if (vl != null) {
+				int column = vl.GetVisualColumnFloor(visualPosition);
+//				Debug.WriteLine(vl.FirstDocumentLine.LineNumber + " vc " + column);
+				foreach (VisualLineElement element in vl.Elements) {
+					if (element.VisualColumn + element.VisualLength <= column)
+						continue;
+					return element;
+				}
+			}
+			return null;
+		}
+		#endregion
+		
+		#region Visual Position <-> TextViewPosition
+		/// <summary>
+		/// Gets the visual position from a text view position.
+		/// </summary>
+		/// <param name="position">The text view position.</param>
+		/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
+		/// <returns>The position in WPF device-independent pixels relative
+		/// to the top left corner of the document.</returns>
+		public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
+		{
+			VerifyAccess();
+			if (this.Document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			DocumentLine documentLine = this.Document.GetLineByNumber(position.Line);
+			VisualLine visualLine = GetOrConstructVisualLine(documentLine);
+			int visualColumn = position.VisualColumn;
+			if (visualColumn < 0) {
+				int offset = documentLine.Offset + position.Column - 1;
+				visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
+			}
+			return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
+		}
+		
+		/// <summary>
+		/// Gets the text view position from the specified visual position.
+		/// If the position is within a character, it is rounded to the next character boundary.
+		/// </summary>
+		/// <param name="visualPosition">The position in WPF device-independent pixels relative
+		/// to the top left corner of the document.</param>
+		/// <returns>The logical position, or null if the position is outside the document.</returns>
+		public TextViewPosition? GetPosition(Point visualPosition)
+		{
+			VerifyAccess();
+			if (this.Document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			VisualLine line = GetVisualLineFromVisualTop(visualPosition.Y);
+			if (line == null)
+				return null;
+			return line.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
+		}
+		
+		/// <summary>
+		/// Gets the text view position from the specified visual position.
+		/// If the position is inside a character, the position in front of the character is returned.
+		/// </summary>
+		/// <param name="visualPosition">The position in WPF device-independent pixels relative
+		/// to the top left corner of the document.</param>
+		/// <returns>The logical position, or null if the position is outside the document.</returns>
+		public TextViewPosition? GetPositionFloor(Point visualPosition)
+		{
+			VerifyAccess();
+			if (this.Document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			VisualLine line = GetVisualLineFromVisualTop(visualPosition.Y);
+			if (line == null)
+				return null;
+			return line.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
+		}
+		#endregion
+		
+		#region Service Provider
+		readonly ServiceContainer services = new ServiceContainer();
+		
+		/// <summary>
+		/// Gets a service container used to associate services with the text view.
+		/// </summary>
+		/// <remarks>
+		/// This container does not provide document services -
+		/// use <c>TextView.GetService()</c> instead of <c>TextView.Services.GetService()</c> to ensure
+		/// that document services can be found as well.
+		/// </remarks>
+		public ServiceContainer Services {
+			get { return services; }
+		}
+		
+		/// <summary>
+		/// Retrieves a service from the text view.
+		/// If the service is not found in the <see cref="Services"/> container,
+		/// this method will also look for it in the current document's service provider.
+		/// </summary>
+		public virtual object GetService(Type serviceType)
+		{
+			object instance = services.GetService(serviceType);
+			if (instance == null && document != null) {
+				instance = document.ServiceProvider.GetService(serviceType);
+			}
+			return instance;
+		}
+		
+		void ConnectToTextView(object obj)
+		{
+			ITextViewConnect c = obj as ITextViewConnect;
+			if (c != null)
+				c.AddToTextView(this);
+		}
+		
+		void DisconnectFromTextView(object obj)
+		{
+			ITextViewConnect c = obj as ITextViewConnect;
+			if (c != null)
+				c.RemoveFromTextView(this);
+		}
+		#endregion
+		
+		#region MouseHover
+		/// <summary>
+		/// The PreviewMouseHover event.
+		/// </summary>
+		public static readonly RoutedEvent PreviewMouseHoverEvent =
+			EventManager.RegisterRoutedEvent("PreviewMouseHover", RoutingStrategy.Tunnel,
+			                                 typeof(MouseEventHandler), typeof(TextView));
+		/// <summary>
+		/// The MouseHover event.
+		/// </summary>
+		public static readonly RoutedEvent MouseHoverEvent =
+			EventManager.RegisterRoutedEvent("MouseHover", RoutingStrategy.Bubble,
+			                                 typeof(MouseEventHandler), typeof(TextView));
+		
+		/// <summary>
+		/// The PreviewMouseHoverStopped event.
+		/// </summary>
+		public static readonly RoutedEvent PreviewMouseHoverStoppedEvent =
+			EventManager.RegisterRoutedEvent("PreviewMouseHoverStopped", RoutingStrategy.Tunnel,
+			                                 typeof(MouseEventHandler), typeof(TextView));
+		/// <summary>
+		/// The MouseHoverStopped event.
+		/// </summary>
+		public static readonly RoutedEvent MouseHoverStoppedEvent =
+			EventManager.RegisterRoutedEvent("MouseHoverStopped", RoutingStrategy.Bubble,
+			                                 typeof(MouseEventHandler), typeof(TextView));
+		
+		
+		/// <summary>
+		/// Occurs when the mouse has hovered over a fixed location for some time.
+		/// </summary>
+		public event MouseEventHandler PreviewMouseHover {
+			add { AddHandler(PreviewMouseHoverEvent, value); }
+			remove { RemoveHandler(PreviewMouseHoverEvent, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse has hovered over a fixed location for some time.
+		/// </summary>
+		public event MouseEventHandler MouseHover {
+			add { AddHandler(MouseHoverEvent, value); }
+			remove { RemoveHandler(MouseHoverEvent, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse had previously hovered but now started moving again.
+		/// </summary>
+		public event MouseEventHandler PreviewMouseHoverStopped {
+			add { AddHandler(PreviewMouseHoverStoppedEvent, value); }
+			remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse had previously hovered but now started moving again.
+		/// </summary>
+		public event MouseEventHandler MouseHoverStopped {
+			add { AddHandler(MouseHoverStoppedEvent, value); }
+			remove { RemoveHandler(MouseHoverStoppedEvent, value); }
+		}
+		
+		MouseHoverLogic hoverLogic;
+		
+		void RaiseHoverEventPair(MouseEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
+		{
+			var mouseDevice = e.MouseDevice;
+			var stylusDevice = e.StylusDevice;
+			int inputTime = Environment.TickCount;
+			var args1 = new MouseEventArgs(mouseDevice, inputTime, stylusDevice) {
+				RoutedEvent = tunnelingEvent,
+				Source = this
+			};
+			RaiseEvent(args1);
+			var args2 = new MouseEventArgs(mouseDevice, inputTime, stylusDevice) {
+				RoutedEvent = bubblingEvent,
+				Source = this,
+				Handled = args1.Handled
+			};
+			RaiseEvent(args2);
+		}
+		#endregion
+		
+		/// <summary>
+		/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
+		/// and not used to start the generation of a <see cref="VisualLine"/>.
+		/// </summary>
+		/// <remarks>
+		/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
+		/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
+		/// <see cref="VisualLineElementGenerator"/>.
+		/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
+		/// 
+		/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
+		/// N+1 to M. Do not collapse line N itself.
+		/// 
+		/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
+		/// <see cref="CollapsedLineSection"/> returned from this method.
+		/// </remarks>
+		public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
+		{
+			VerifyAccess();
+			if (heightTree == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			return heightTree.CollapseText(start, end);
+		}
+		
+		/// <summary>
+		/// Gets the height of the document.
+		/// </summary>
+		public double DocumentHeight {
+			get {
+				// return 0 if there is no document = no heightTree
+				return heightTree != null ? heightTree.TotalHeight : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the document line at the specified visual position.
+		/// </summary>
+		public DocumentLine GetDocumentLineByVisualTop(double visualTop)
+		{
+			VerifyAccess();
+			if (heightTree == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			return heightTree.GetLineByVisualPosition(visualTop);
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
+		{
+			base.OnPropertyChanged(e);
+			if (TextFormatterFactory.PropertyChangeAffectsTextFormatter(e.Property)) {
+				// first, create the new text formatter:
+				RecreateTextFormatter();
+				// changing text formatter requires recreating the cached elements
+				RecreateCachedElements();
+				// and we need to re-measure the font metrics:
+				InvalidateDefaultTextMetrics();
+			} else if (e.Property == Control.ForegroundProperty
+			           || e.Property == TextView.NonPrintableCharacterBrushProperty
+			           || e.Property == TextView.LinkTextBackgroundBrushProperty
+			           || e.Property == TextView.LinkTextForegroundBrushProperty)
+			{
+				// changing brushes requires recreating the cached elements
+				RecreateCachedElements();
+				Redraw();
+			}
+			if (e.Property == Control.FontFamilyProperty
+			    || e.Property == Control.FontSizeProperty
+			    || e.Property == Control.FontStretchProperty
+			    || e.Property == Control.FontStyleProperty
+			    || e.Property == Control.FontWeightProperty)
+			{
+				// changing font properties requires recreating cached elements
+				RecreateCachedElements();
+				// and we need to re-measure the font metrics:
+				InvalidateDefaultTextMetrics();
+				Redraw();
+			}
+			if (e.Property == ColumnRulerPenProperty) {
+				columnRulerRenderer.SetRuler(this.Options.ColumnRulerPosition, this.ColumnRulerPen);
+			}
+			if (e.Property == CurrentLineBorderProperty) {
+				currentLineHighlighRenderer.BorderPen = this.CurrentLineBorder;
+			}
+			if (e.Property == CurrentLineBackgroundProperty) {
+				currentLineHighlighRenderer.BackgroundBrush = this.CurrentLineBackground;
+			}
+		}
+		
+		/// <summary>
+		/// The pen used to draw the column ruler.
+		/// <seealso cref="TextEditorOptions.ShowColumnRuler"/>
+		/// </summary>
+		public static readonly DependencyProperty ColumnRulerPenProperty =
+			DependencyProperty.Register("ColumnRulerBrush", typeof(Pen), typeof(TextView),
+			                            new FrameworkPropertyMetadata(CreateFrozenPen(Brushes.LightGray)));
+		
+		static Pen CreateFrozenPen(SolidColorBrush brush)
+		{
+			Pen pen = new Pen(brush, 1);
+			pen.Freeze();
+			return pen;
+		}
+		
+		/// <summary>
+		/// Gets/Sets the pen used to draw the column ruler.
+		/// <seealso cref="TextEditorOptions.ShowColumnRuler"/>
+		/// </summary>
+		public Pen ColumnRulerPen {
+			get { return (Pen)GetValue(ColumnRulerPenProperty); }
+			set { SetValue(ColumnRulerPenProperty, value); }
+		}
+		
+		/// <summary>
+		/// The <see cref="CurrentLineBackground"/> property.
+		/// </summary>
+		public static readonly DependencyProperty CurrentLineBackgroundProperty =
+			DependencyProperty.Register("CurrentLineBackground", typeof(Brush), typeof(TextView));
+		
+		/// <summary>
+		/// Gets/Sets the background brush used by current line highlighter.
+		/// </summary>
+		public Brush CurrentLineBackground {
+			get { return (Brush)GetValue(CurrentLineBackgroundProperty); }
+			set { SetValue(CurrentLineBackgroundProperty, value); }
+		}
+		
+		/// <summary>
+		/// The <see cref="CurrentLineBorder"/> property.
+		/// </summary>
+		public static readonly DependencyProperty CurrentLineBorderProperty =
+			DependencyProperty.Register("CurrentLineBorder", typeof(Pen), typeof(TextView));
+		
+		/// <summary>
+		/// Gets/Sets the background brush used for the current line.
+		/// </summary>
+		public Pen CurrentLineBorder {
+			get { return (Pen)GetValue(CurrentLineBorderProperty); }
+			set { SetValue(CurrentLineBorderProperty, value); }
+		}
+		
+		/// <summary>
+		/// Gets/Sets highlighted line number.
+		/// </summary>
+		public int HighlightedLine {
+			get { return this.currentLineHighlighRenderer.Line; }
+			set { this.currentLineHighlighRenderer.Line = value; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextViewCachedElements.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextViewCachedElements.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextViewCachedElements.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	sealed class TextViewCachedElements : IDisposable
+	{
+		TextFormatter formatter;
+		Dictionary<string, TextLine> nonPrintableCharacterTexts;
+		
+		public TextLine GetTextForNonPrintableCharacter(string text, ITextRunConstructionContext context)
+		{
+			if (nonPrintableCharacterTexts == null)
+				nonPrintableCharacterTexts = new Dictionary<string, TextLine>();
+			TextLine textLine;
+			if (!nonPrintableCharacterTexts.TryGetValue(text, out textLine)) {
+				var p = new VisualLineElementTextRunProperties(context.GlobalTextRunProperties);
+				p.SetForegroundBrush(context.TextView.NonPrintableCharacterBrush);
+				if (formatter == null)
+					formatter = TextFormatterFactory.Create(context.TextView);
+				textLine = FormattedTextElement.PrepareText(formatter, text, p);
+				nonPrintableCharacterTexts[text] = textLine;
+			}
+			return textLine;
+		}
+		
+		public void Dispose()
+		{
+			if (nonPrintableCharacterTexts != null) {
+				foreach (TextLine line in nonPrintableCharacterTexts.Values)
+					line.Dispose();
+			}
+			if (formatter != null)
+				formatter.Dispose();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextViewWeakEventManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextViewWeakEventManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/TextViewWeakEventManager.cs	(revision 11807)
@@ -0,0 +1,86 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Contains weak event managers for the TextView events.
+	/// </summary>
+	public static class TextViewWeakEventManager
+	{
+		/// <summary>
+		/// Weak event manager for the <see cref="TextView.DocumentChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class DocumentChanged : WeakEventManagerBase<DocumentChanged, TextView>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextView source)
+			{
+				source.DocumentChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextView source)
+			{
+				source.DocumentChanged -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextView.VisualLinesChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class VisualLinesChanged : WeakEventManagerBase<VisualLinesChanged, TextView>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextView source)
+			{
+				source.VisualLinesChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextView source)
+			{
+				source.VisualLinesChanged -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="TextView.ScrollOffsetChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class ScrollOffsetChanged : WeakEventManagerBase<ScrollOffsetChanged, TextView>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(TextView source)
+			{
+				source.ScrollOffsetChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(TextView source)
+			{
+				source.ScrollOffsetChanged -= DeliverEvent;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLine.cs	(revision 11807)
@@ -0,0 +1,772 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System.Linq;
+using System.Windows.Controls;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Utils;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Represents a visual line in the document.
+	/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
+	/// all but the first are collapsed.
+	/// </summary>
+	public sealed class VisualLine
+	{
+		enum LifetimePhase : byte
+		{
+			Generating,
+			Transforming,
+			Live,
+			Disposed
+		}
+		
+		TextView textView;
+		List<VisualLineElement> elements;
+		internal bool hasInlineObjects;
+		LifetimePhase phase;
+		
+		/// <summary>
+		/// Gets the document to which this VisualLine belongs.
+		/// </summary>
+		public TextDocument Document { get; private set; }
+		
+		/// <summary>
+		/// Gets the first document line displayed by this visual line.
+		/// </summary>
+		public DocumentLine FirstDocumentLine { get; private set; }
+		
+		/// <summary>
+		/// Gets the last document line displayed by this visual line.
+		/// </summary>
+		public DocumentLine LastDocumentLine { get; private set; }
+		
+		/// <summary>
+		/// Gets a read-only collection of line elements.
+		/// </summary>
+		public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
+		
+		ReadOnlyCollection<TextLine> textLines;
+		
+		/// <summary>
+		/// Gets a read-only collection of text lines.
+		/// </summary>
+		public ReadOnlyCollection<TextLine> TextLines {
+			get {
+				if (phase < LifetimePhase.Live)
+					throw new InvalidOperationException();
+				return textLines;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the start offset of the VisualLine inside the document.
+		/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
+		/// </summary>
+		public int StartOffset {
+			get {
+				return FirstDocumentLine.Offset;
+			}
+		}
+		
+		/// <summary>
+		/// Length in visual line coordinates.
+		/// </summary>
+		public int VisualLength { get; private set; }
+		
+		/// <summary>
+		/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
+		/// </summary>
+		public int VisualLengthWithEndOfLineMarker {
+			get {
+				int length = VisualLength;
+				if (textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
+				return length;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the height of the visual line in device-independent pixels.
+		/// </summary>
+		public double Height { get; private set; }
+		
+		/// <summary>
+		/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
+		/// </summary>
+		public double VisualTop { get; internal set; }
+		
+		internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
+		{
+			Debug.Assert(textView != null);
+			Debug.Assert(firstDocumentLine != null);
+			this.textView = textView;
+			this.Document = textView.Document;
+			this.FirstDocumentLine = firstDocumentLine;
+		}
+		
+		internal void ConstructVisualElements(ITextRunConstructionContext context, VisualLineElementGenerator[] generators)
+		{
+			Debug.Assert(phase == LifetimePhase.Generating);
+			foreach (VisualLineElementGenerator g in generators) {
+				g.StartGeneration(context);
+			}
+			elements = new List<VisualLineElement>();
+			PerformVisualElementConstruction(generators);
+			foreach (VisualLineElementGenerator g in generators) {
+				g.FinishGeneration();
+			}
+			
+			var globalTextRunProperties = context.GlobalTextRunProperties;
+			foreach (var element in elements) {
+				element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
+			}
+			this.Elements = elements.AsReadOnly();
+			CalculateOffsets();
+			phase = LifetimePhase.Transforming;
+		}
+		
+		void PerformVisualElementConstruction(VisualLineElementGenerator[] generators)
+		{
+			TextDocument document = this.Document;
+			int offset = FirstDocumentLine.Offset;
+			int currentLineEnd = offset + FirstDocumentLine.Length;
+			LastDocumentLine = FirstDocumentLine;
+			int askInterestOffset = 0; // 0 or 1
+			while (offset + askInterestOffset <= currentLineEnd) {
+				int textPieceEndOffset = currentLineEnd;
+				foreach (VisualLineElementGenerator g in generators) {
+					g.cachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
+					if (g.cachedInterest != -1) {
+						if (g.cachedInterest < offset)
+							throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
+							                                      g.cachedInterest,
+							                                      "GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
+						if (g.cachedInterest < textPieceEndOffset)
+							textPieceEndOffset = g.cachedInterest;
+					}
+				}
+				Debug.Assert(textPieceEndOffset >= offset);
+				if (textPieceEndOffset > offset) {
+					int textPieceLength = textPieceEndOffset - offset;
+					elements.Add(new VisualLineText(this, textPieceLength));
+					offset = textPieceEndOffset;
+				}
+				// If no elements constructed / only zero-length elements constructed:
+				// do not asking the generators again for the same location (would cause endless loop)
+				askInterestOffset = 1;
+				foreach (VisualLineElementGenerator g in generators) {
+					if (g.cachedInterest == offset) {
+						VisualLineElement element = g.ConstructElement(offset);
+						if (element != null) {
+							elements.Add(element);
+							if (element.DocumentLength > 0) {
+								// a non-zero-length element was constructed
+								askInterestOffset = 0;
+								offset += element.DocumentLength;
+								if (offset > currentLineEnd) {
+									DocumentLine newEndLine = document.GetLineByOffset(offset);
+									currentLineEnd = newEndLine.Offset + newEndLine.Length;
+									this.LastDocumentLine = newEndLine;
+									if (currentLineEnd < offset) {
+										throw new InvalidOperationException(
+											"The VisualLineElementGenerator " + g.GetType().Name +
+											" produced an element which ends within the line delimiter");
+									}
+								}
+								break;
+							}
+						}
+					}
+				}
+			}
+		}
+		
+		void CalculateOffsets()
+		{
+			int visualOffset = 0;
+			int textOffset = 0;
+			foreach (VisualLineElement element in elements) {
+				element.VisualColumn = visualOffset;
+				element.RelativeTextOffset = textOffset;
+				visualOffset += element.VisualLength;
+				textOffset += element.DocumentLength;
+			}
+			VisualLength = visualOffset;
+			Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
+		}
+		
+		internal void RunTransformers(ITextRunConstructionContext context, IVisualLineTransformer[] transformers)
+		{
+			Debug.Assert(phase == LifetimePhase.Transforming);
+			foreach (IVisualLineTransformer transformer in transformers) {
+				transformer.Transform(context, elements);
+			}
+			// For some strange reason, WPF requires that either all or none of the typography properties are set.
+			if (elements.Any(e => e.TextRunProperties.TypographyProperties != null)) {
+				// Fix typographic properties
+				foreach (VisualLineElement element in elements) {
+					if (element.TextRunProperties.TypographyProperties == null) {
+						element.TextRunProperties.SetTypographyProperties(new DefaultTextRunTypographyProperties());
+					}
+				}
+			}
+			phase = LifetimePhase.Live;
+		}
+		
+		/// <summary>
+		/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
+		/// The replacement operation must preserve the document length, but may change the visual length.
+		/// </summary>
+		/// <remarks>
+		/// This method may only be called by line transformers.
+		/// </remarks>
+		public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
+		{
+			ReplaceElement(elementIndex, 1, newElements);
+		}
+		
+		/// <summary>
+		/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
+		/// The replacement operation must preserve the document length, but may change the visual length.
+		/// </summary>
+		/// <remarks>
+		/// This method may only be called by line transformers.
+		/// </remarks>
+		public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
+		{
+			if (phase != LifetimePhase.Transforming)
+				throw new InvalidOperationException("This method may only be called by line transformers.");
+			int oldDocumentLength = 0;
+			for (int i = elementIndex; i < elementIndex + count; i++) {
+				oldDocumentLength += elements[i].DocumentLength;
+			}
+			int newDocumentLength = 0;
+			foreach (var newElement in newElements) {
+				newDocumentLength += newElement.DocumentLength;
+			}
+			if (oldDocumentLength != newDocumentLength)
+				throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
+			elements.RemoveRange(elementIndex, count);
+			elements.InsertRange(elementIndex, newElements);
+			CalculateOffsets();
+		}
+		
+		internal void SetTextLines(List<TextLine> textLines)
+		{
+			this.textLines = textLines.AsReadOnly();
+			Height = 0;
+			foreach (TextLine line in textLines)
+				Height += line.Height;
+		}
+		
+		/// <summary>
+		/// Gets the visual column from a document offset relative to the first line start.
+		/// </summary>
+		public int GetVisualColumn(int relativeTextOffset)
+		{
+			ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
+			foreach (VisualLineElement element in elements) {
+				if (element.RelativeTextOffset <= relativeTextOffset
+				    && element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
+				{
+					return element.GetVisualColumn(relativeTextOffset);
+				}
+			}
+			return VisualLength;
+		}
+		
+		/// <summary>
+		/// Gets the document offset (relative to the first line start) from a visual column.
+		/// </summary>
+		public int GetRelativeOffset(int visualColumn)
+		{
+			ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
+			int documentLength = 0;
+			foreach (VisualLineElement element in elements) {
+				if (element.VisualColumn <= visualColumn
+				    && element.VisualColumn + element.VisualLength > visualColumn)
+				{
+					return element.GetRelativeOffset(visualColumn);
+				}
+				documentLength += element.DocumentLength;
+			}
+			return documentLength;
+		}
+		
+		/// <summary>
+		/// Gets the text line containing the specified visual column.
+		/// </summary>
+		public TextLine GetTextLine(int visualColumn)
+		{
+			return GetTextLine(visualColumn, false);
+		}
+		
+		/// <summary>
+		/// Gets the text line containing the specified visual column.
+		/// </summary>
+		public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
+		{
+			if (visualColumn < 0)
+				throw new ArgumentOutOfRangeException("visualColumn");
+			if (visualColumn >= VisualLengthWithEndOfLineMarker)
+				return TextLines[TextLines.Count - 1];
+			foreach (TextLine line in TextLines) {
+				if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
+					return line;
+				else
+					visualColumn -= line.Length;
+			}
+			throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
+		}
+		
+		/// <summary>
+		/// Gets the visual top from the specified text line.
+		/// </summary>
+		/// <returns>Distance in device-independent pixels
+		/// from the top of the document to the top of the specified text line.</returns>
+		public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
+		{
+			if (textLine == null)
+				throw new ArgumentNullException("textLine");
+			double pos = VisualTop;
+			foreach (TextLine tl in TextLines) {
+				if (tl == textLine) {
+					switch (yPositionMode) {
+						case VisualYPosition.LineTop:
+							return pos;
+						case VisualYPosition.LineMiddle:
+							return pos + tl.Height / 2;
+						case VisualYPosition.LineBottom:
+							return pos + tl.Height;
+						case VisualYPosition.TextTop:
+							return pos + tl.Baseline - textView.DefaultBaseline;
+						case VisualYPosition.TextBottom:
+							return pos + tl.Baseline - textView.DefaultBaseline + textView.DefaultLineHeight;
+						case VisualYPosition.TextMiddle:
+							return pos + tl.Baseline - textView.DefaultBaseline + textView.DefaultLineHeight / 2;
+						case VisualYPosition.Baseline:
+							return pos + tl.Baseline;
+						default:
+							throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
+					}
+				} else {
+					pos += tl.Height;
+				}
+			}
+			throw new ArgumentException("textLine is not a line in this VisualLine");
+		}
+		
+		/// <summary>
+		/// Gets the start visual column from the specified text line.
+		/// </summary>
+		public int GetTextLineVisualStartColumn(TextLine textLine)
+		{
+			if (!TextLines.Contains(textLine))
+				throw new ArgumentException("textLine is not a line in this VisualLine");
+			int col = 0;
+			foreach (TextLine tl in TextLines) {
+				if (tl == textLine)
+					break;
+				else
+					col += tl.Length;
+			}
+			return col;
+		}
+		
+		/// <summary>
+		/// Gets a TextLine by the visual position.
+		/// </summary>
+		public TextLine GetTextLineByVisualYPosition(double visualTop)
+		{
+			const double epsilon = 0.0001;
+			double pos = this.VisualTop;
+			foreach (TextLine tl in TextLines) {
+				pos += tl.Height;
+				if (visualTop + epsilon < pos)
+					return tl;
+			}
+			return TextLines[TextLines.Count - 1];
+		}
+		
+		/// <summary>
+		/// Gets the visual position from the specified visualColumn.
+		/// </summary>
+		/// <returns>Position in device-independent pixels
+		/// relative to the top left of the document.</returns>
+		public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
+		{
+			TextLine textLine = GetTextLine(visualColumn);
+			double xPos = GetTextLineVisualXPosition(textLine, visualColumn);
+			double yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
+			return new Point(xPos, yPos);
+		}
+		
+		internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
+		{
+			TextLine textLine = GetTextLine(visualColumn, isAtEndOfLine);
+			double xPos = GetTextLineVisualXPosition(textLine, visualColumn);
+			double yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
+			return new Point(xPos, yPos);
+		}
+		
+		/// <summary>
+		/// Gets the distance to the left border of the text area of the specified visual column.
+		/// The visual column must belong to the specified text line.
+		/// </summary>
+		public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
+		{
+			if (textLine == null)
+				throw new ArgumentNullException("textLine");
+			double xPos = textLine.GetDistanceFromCharacterHit(
+				new CharacterHit(Math.Min(visualColumn, VisualLengthWithEndOfLineMarker), 0));
+			if (visualColumn > VisualLengthWithEndOfLineMarker) {
+				xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * textView.WideSpaceWidth;
+			}
+			return xPos;
+		}
+		
+		/// <summary>
+		/// Gets the visual column from a document position (relative to top left of the document).
+		/// If the user clicks between two visual columns, rounds to the nearest column.
+		/// </summary>
+		public int GetVisualColumn(Point point)
+		{
+			return GetVisualColumn(point, textView.Options.EnableVirtualSpace);
+		}
+		
+		/// <summary>
+		/// Gets the visual column from a document position (relative to top left of the document).
+		/// If the user clicks between two visual columns, rounds to the nearest column.
+		/// </summary>
+		public int GetVisualColumn(Point point, bool allowVirtualSpace)
+		{
+			return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
+		}
+		
+		internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
+		{
+			var textLine = GetTextLineByVisualYPosition(point.Y);
+			int vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
+			isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
+			return vc;
+		}
+		
+		/// <summary>
+		/// Gets the visual column from a document position (relative to top left of the document).
+		/// If the user clicks between two visual columns, rounds to the nearest column.
+		/// </summary>
+		public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
+		{
+			if (xPos > textLine.WidthIncludingTrailingWhitespace) {
+				if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) {
+					int virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / textView.WideSpaceWidth);
+					return VisualLengthWithEndOfLineMarker + virtualX;
+				}
+			}
+			CharacterHit ch = textLine.GetCharacterHitFromDistance(xPos);
+			return ch.FirstCharacterIndex + ch.TrailingLength;
+		}
+		
+		/// <summary>
+		/// Validates the visual column and returns the correct one.
+		/// </summary>
+		public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
+		{
+			return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
+		}
+		
+		/// <summary>
+		/// Validates the visual column and returns the correct one.
+		/// </summary>
+		public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
+		{
+			int firstDocumentLineOffset = this.FirstDocumentLine.Offset;
+			if (visualColumn < 0) {
+				return GetVisualColumn(offset - firstDocumentLineOffset);
+			} else {
+				int offsetFromVisualColumn = GetRelativeOffset(visualColumn);
+				offsetFromVisualColumn += firstDocumentLineOffset;
+				if (offsetFromVisualColumn != offset) {
+					return GetVisualColumn(offset - firstDocumentLineOffset);
+				} else {
+					if (visualColumn > VisualLength && !allowVirtualSpace) {
+						return VisualLength;
+					}
+				}
+			}
+			return visualColumn;
+		}
+		
+		/// <summary>
+		/// Gets the visual column from a document position (relative to top left of the document).
+		/// If the user clicks between two visual columns, returns the first of those columns.
+		/// </summary>
+		public int GetVisualColumnFloor(Point point)
+		{
+			return GetVisualColumnFloor(point, textView.Options.EnableVirtualSpace);
+		}
+		
+		/// <summary>
+		/// Gets the visual column from a document position (relative to top left of the document).
+		/// If the user clicks between two visual columns, returns the first of those columns.
+		/// </summary>
+		public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
+		{
+			bool tmp;
+			return GetVisualColumnFloor(point, allowVirtualSpace, out tmp);
+		}
+		
+		internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
+		{
+			TextLine textLine = GetTextLineByVisualYPosition(point.Y);
+			if (point.X > textLine.WidthIncludingTrailingWhitespace) {
+				isAtEndOfLine = true;
+				if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1]) {
+					// clicking virtual space in the last line
+					int virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / textView.WideSpaceWidth);
+					return VisualLengthWithEndOfLineMarker + virtualX;
+				} else {
+					// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
+					// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
+					// specially and return the line's end column instead.
+					return GetTextLineVisualStartColumn(textLine) + textLine.Length;
+				}
+			} else {
+				isAtEndOfLine = false;
+			}
+			CharacterHit ch = textLine.GetCharacterHitFromDistance(point.X);
+			return ch.FirstCharacterIndex;
+		}
+		
+		/// <summary>
+		/// Gets the text view position from the specified visual column.
+		/// </summary>
+		public TextViewPosition GetTextViewPosition(int visualColumn)
+		{
+			int documentOffset = GetRelativeOffset(visualColumn) + this.FirstDocumentLine.Offset;
+			return new TextViewPosition(this.Document.GetLocation(documentOffset), visualColumn);
+		}
+		
+		/// <summary>
+		/// Gets the text view position from the specified visual position.
+		/// If the position is within a character, it is rounded to the next character boundary.
+		/// </summary>
+		/// <param name="visualPosition">The position in WPF device-independent pixels relative
+		/// to the top left corner of the document.</param>
+		/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
+		public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
+		{
+			bool isAtEndOfLine;
+			int visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out isAtEndOfLine);
+			int documentOffset = GetRelativeOffset(visualColumn) + this.FirstDocumentLine.Offset;
+			TextViewPosition pos = new TextViewPosition(this.Document.GetLocation(documentOffset), visualColumn);
+			pos.IsAtEndOfLine = isAtEndOfLine;
+			return pos;
+		}
+		
+		/// <summary>
+		/// Gets the text view position from the specified visual position.
+		/// If the position is inside a character, the position in front of the character is returned.
+		/// </summary>
+		/// <param name="visualPosition">The position in WPF device-independent pixels relative
+		/// to the top left corner of the document.</param>
+		/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
+		public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
+		{
+			bool isAtEndOfLine;
+			int visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out isAtEndOfLine);
+			int documentOffset = GetRelativeOffset(visualColumn) + this.FirstDocumentLine.Offset;
+			TextViewPosition pos = new TextViewPosition(this.Document.GetLocation(documentOffset), visualColumn);
+			pos.IsAtEndOfLine = isAtEndOfLine;
+			return pos;
+		}
+		
+		/// <summary>
+		/// Gets whether the visual line was disposed.
+		/// </summary>
+		public bool IsDisposed {
+			get { return phase == LifetimePhase.Disposed; }
+		}
+		
+		internal void Dispose()
+		{
+			if (phase == LifetimePhase.Disposed)
+				return;
+			Debug.Assert(phase == LifetimePhase.Live);
+			phase = LifetimePhase.Disposed;
+			foreach (TextLine textLine in TextLines) {
+				textLine.Dispose();
+			}
+		}
+		
+		/// <summary>
+		/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
+		/// </summary>
+		public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
+		{
+			if (!HasStopsInVirtualSpace(mode))
+				allowVirtualSpace = false;
+			
+			if (elements.Count == 0) {
+				// special handling for empty visual lines:
+				if (allowVirtualSpace) {
+					if (direction == LogicalDirection.Forward)
+						return Math.Max(0, visualColumn + 1);
+					else if (visualColumn > 0)
+						return visualColumn - 1;
+					else
+						return -1;
+				} else {
+					// even though we don't have any elements,
+					// there's a single caret stop at visualColumn 0
+					if (visualColumn < 0 && direction == LogicalDirection.Forward)
+						return 0;
+					else if (visualColumn > 0 && direction == LogicalDirection.Backward)
+						return 0;
+					else
+						return -1;
+				}
+			}
+			
+			int i;
+			if (direction == LogicalDirection.Backward) {
+				// Search Backwards:
+				// If the last element doesn't handle line borders, return the line end as caret stop
+				
+				if (visualColumn > this.VisualLength && !elements[elements.Count-1].HandlesLineBorders && HasImplicitStopAtLineEnd(mode)) {
+					if (allowVirtualSpace)
+						return visualColumn - 1;
+					else
+						return this.VisualLength;
+				}
+				// skip elements that start after or at visualColumn
+				for (i = elements.Count - 1; i >= 0; i--) {
+					if (elements[i].VisualColumn < visualColumn)
+						break;
+				}
+				// search last element that has a caret stop
+				for (; i >= 0; i--) {
+					int pos = elements[i].GetNextCaretPosition(
+						Math.Min(visualColumn, elements[i].VisualColumn + elements[i].VisualLength + 1),
+						direction, mode);
+					if (pos >= 0)
+						return pos;
+				}
+				// If we've found nothing, and the first element doesn't handle line borders,
+				// return the line start as normal caret stop.
+				if (visualColumn > 0 && !elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
+					return 0;
+			} else {
+				// Search Forwards:
+				// If the first element doesn't handle line borders, return the line start as caret stop
+				if (visualColumn < 0 && !elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
+					return 0;
+				// skip elements that end before or at visualColumn
+				for (i = 0; i < elements.Count; i++) {
+					if (elements[i].VisualColumn + elements[i].VisualLength > visualColumn)
+						break;
+				}
+				// search first element that has a caret stop
+				for (; i < elements.Count; i++) {
+					int pos = elements[i].GetNextCaretPosition(
+						Math.Max(visualColumn, elements[i].VisualColumn - 1),
+						direction, mode);
+					if (pos >= 0)
+						return pos;
+				}
+				// if we've found nothing, and the last element doesn't handle line borders,
+				// return the line end as caret stop
+				if ((allowVirtualSpace || !elements[elements.Count-1].HandlesLineBorders) && HasImplicitStopAtLineEnd(mode)) {
+					if (visualColumn < this.VisualLength)
+						return this.VisualLength;
+					else if (allowVirtualSpace)
+						return visualColumn + 1;
+				}
+			}
+			// we've found nothing, return -1 and let the caret search continue in the next line
+			return -1;
+		}
+		
+		static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
+		{
+			return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
+		}
+		
+		static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
+		{
+			return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "mode",
+		                                                 Justification = "make method consistent with HasImplicitStopAtLineStart; might depend on mode in the future")]
+		static bool HasImplicitStopAtLineEnd(CaretPositioningMode mode)
+		{
+			return true;
+		}
+		
+		VisualLineDrawingVisual visual;
+		
+		internal VisualLineDrawingVisual Render()
+		{
+			Debug.Assert(phase == LifetimePhase.Live);
+			if (visual == null)
+				visual = new VisualLineDrawingVisual(this);
+			return visual;
+		}
+	}
+	
+	sealed class VisualLineDrawingVisual : DrawingVisual
+	{
+		public readonly VisualLine VisualLine;
+		public readonly double Height;
+		internal bool IsAdded;
+		
+		public VisualLineDrawingVisual(VisualLine visualLine)
+		{
+			this.VisualLine = visualLine;
+			var drawingContext = RenderOpen();
+			double pos = 0;
+			foreach (TextLine textLine in visualLine.TextLines) {
+				textLine.Draw(drawingContext, new Point(0, pos), InvertAxes.None);
+				pos += textLine.Height;
+			}
+			this.Height = pos;
+			drawingContext.Close();
+		}
+		
+		protected override GeometryHitTestResult HitTestCore(GeometryHitTestParameters hitTestParameters)
+		{
+			return null;
+		}
+		
+		protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
+		{
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineConstructionStartEventArgs.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineConstructionStartEventArgs.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineConstructionStartEventArgs.cs	(revision 11807)
@@ -0,0 +1,44 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// EventArgs for the <see cref="TextView.VisualLineConstructionStarting"/> event.
+	/// </summary>
+	public class VisualLineConstructionStartEventArgs : EventArgs
+	{
+		/// <summary>
+		/// Gets/Sets the first line that is visible in the TextView.
+		/// </summary>
+		public DocumentLine FirstLineInView { get; private set; }
+		
+		/// <summary>
+		/// Creates a new VisualLineConstructionStartEventArgs instance.
+		/// </summary>
+		public VisualLineConstructionStartEventArgs(DocumentLine firstLineInView)
+		{
+			if (firstLineInView == null)
+				throw new ArgumentNullException("firstLineInView");
+			this.FirstLineInView = firstLineInView;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElement.cs	(revision 11807)
@@ -0,0 +1,264 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Represents a visual element in the document.
+	/// </summary>
+	public abstract class VisualLineElement
+	{
+		/// <summary>
+		/// Creates a new VisualLineElement.
+		/// </summary>
+		/// <param name="visualLength">The length of the element in VisualLine coordinates. Must be positive.</param>
+		/// <param name="documentLength">The length of the element in the document. Must be non-negative.</param>
+		protected VisualLineElement(int visualLength, int documentLength)
+		{
+			if (visualLength < 1)
+				throw new ArgumentOutOfRangeException("visualLength", visualLength, "Value must be at least 1");
+			if (documentLength < 0)
+				throw new ArgumentOutOfRangeException("documentLength", documentLength, "Value must be at least 0");
+			this.VisualLength = visualLength;
+			this.DocumentLength = documentLength;
+		}
+		
+		/// <summary>
+		/// Gets the length of this element in visual columns.
+		/// </summary>
+		public int VisualLength { get; private set; }
+		
+		/// <summary>
+		/// Gets the length of this element in the text document.
+		/// </summary>
+		public int DocumentLength { get; private set; }
+		
+		/// <summary>
+		/// Gets the visual column where this element starts.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods",
+		                                                 Justification = "This property holds the start visual column, use GetVisualColumn to get inner visual columns.")]
+		public int VisualColumn { get; internal set; }
+		
+		/// <summary>
+		/// Gets the text offset where this element starts, relative to the start text offset of the visual line.
+		/// </summary>
+		public int RelativeTextOffset { get; internal set; }
+		
+		/// <summary>
+		/// Gets the text run properties.
+		/// A unique <see cref="VisualLineElementTextRunProperties"/> instance is used for each
+		/// <see cref="VisualLineElement"/>; colorizing code may assume that modifying the
+		/// <see cref="VisualLineElementTextRunProperties"/> will affect only this
+		/// <see cref="VisualLineElement"/>.
+		/// </summary>
+		public VisualLineElementTextRunProperties TextRunProperties { get; private set; }
+		
+		/// <summary>
+		/// Gets/sets the brush used for the background of this <see cref="VisualLineElement" />.
+		/// </summary>
+		public Brush BackgroundBrush { get; set; }
+		
+		internal void SetTextRunProperties(VisualLineElementTextRunProperties p)
+		{
+			this.TextRunProperties = p;
+		}
+		
+		/// <summary>
+		/// Creates the TextRun for this line element.
+		/// </summary>
+		/// <param name="startVisualColumn">
+		/// The visual column from which the run should be constructed.
+		/// Normally the same value as the <see cref="VisualColumn"/> property is used to construct the full run;
+		/// but when word-wrapping is active, partial runs might be created.
+		/// </param>
+		/// <param name="context">
+		/// Context object that contains information relevant for text run creation.
+		/// </param>
+		public abstract TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context);
+		
+		/// <summary>
+		/// Retrieves the text span immediately before the visual column.
+		/// </summary>
+		/// <remarks>This method is used for word-wrapping in bidirectional text.</remarks>
+		public virtual TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context)
+		{
+			return null;
+		}
+		
+		/// <summary>
+		/// Gets if this VisualLineElement can be split.
+		/// </summary>
+		public virtual bool CanSplit {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Splits the element.
+		/// </summary>
+		/// <param name="splitVisualColumn">Position inside this element at which it should be broken</param>
+		/// <param name="elements">The collection of line elements</param>
+		/// <param name="elementIndex">The index at which this element is in the elements list.</param>
+		public virtual void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex)
+		{
+			throw new NotSupportedException();
+		}
+		
+		/// <summary>
+		/// Helper method for splitting this line element into two, correctly updating the
+		/// <see cref="VisualLength"/>, <see cref="DocumentLength"/>, <see cref="VisualColumn"/>
+		/// and <see cref="RelativeTextOffset"/> properties.
+		/// </summary>
+		/// <param name="firstPart">The element before the split position.</param>
+		/// <param name="secondPart">The element after the split position.</param>
+		/// <param name="splitVisualColumn">The split position as visual column.</param>
+		/// <param name="splitRelativeTextOffset">The split position as text offset.</param>
+		protected void SplitHelper(VisualLineElement firstPart, VisualLineElement secondPart, int splitVisualColumn, int splitRelativeTextOffset)
+		{
+			if (firstPart == null)
+				throw new ArgumentNullException("firstPart");
+			if (secondPart == null)
+				throw new ArgumentNullException("secondPart");
+			int relativeSplitVisualColumn = splitVisualColumn - VisualColumn;
+			int relativeSplitRelativeTextOffset = splitRelativeTextOffset - RelativeTextOffset;
+			
+			if (relativeSplitVisualColumn <= 0 || relativeSplitVisualColumn >= VisualLength)
+				throw new ArgumentOutOfRangeException("splitVisualColumn", splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1));
+			if (relativeSplitRelativeTextOffset < 0 || relativeSplitRelativeTextOffset > DocumentLength)
+				throw new ArgumentOutOfRangeException("splitRelativeTextOffset", splitRelativeTextOffset, "Value must be between " + (RelativeTextOffset) + " and " + (RelativeTextOffset + DocumentLength));
+			int oldVisualLength = VisualLength;
+			int oldDocumentLength = DocumentLength;
+			int oldVisualColumn = VisualColumn;
+			int oldRelativeTextOffset = RelativeTextOffset;
+			firstPart.VisualColumn = oldVisualColumn;
+			secondPart.VisualColumn = oldVisualColumn + relativeSplitVisualColumn;
+			firstPart.RelativeTextOffset = oldRelativeTextOffset;
+			secondPart.RelativeTextOffset = oldRelativeTextOffset + relativeSplitRelativeTextOffset;
+			firstPart.VisualLength = relativeSplitVisualColumn;
+			secondPart.VisualLength = oldVisualLength - relativeSplitVisualColumn;
+			firstPart.DocumentLength = relativeSplitRelativeTextOffset;
+			secondPart.DocumentLength = oldDocumentLength - relativeSplitRelativeTextOffset;
+			if (firstPart.TextRunProperties == null)
+				firstPart.TextRunProperties = TextRunProperties.Clone();
+			if (secondPart.TextRunProperties == null)
+				secondPart.TextRunProperties = TextRunProperties.Clone();
+		}
+		
+		/// <summary>
+		/// Gets the visual column of a text location inside this element.
+		/// The text offset is given relative to the visual line start.
+		/// </summary>
+		public virtual int GetVisualColumn(int relativeTextOffset)
+		{
+			if (relativeTextOffset >= this.RelativeTextOffset + DocumentLength)
+				return VisualColumn + VisualLength;
+			else
+				return VisualColumn;
+		}
+		
+		/// <summary>
+		/// Gets the text offset of a visual column inside this element.
+		/// </summary>
+		/// <returns>A text offset relative to the visual line start.</returns>
+		public virtual int GetRelativeOffset(int visualColumn)
+		{
+			if (visualColumn >= this.VisualColumn + VisualLength)
+				return RelativeTextOffset + DocumentLength;
+			else
+				return RelativeTextOffset;
+		}
+		
+		/// <summary>
+		/// Gets the next caret position inside this element.
+		/// </summary>
+		/// <param name="visualColumn">The visual column from which the search should be started.</param>
+		/// <param name="direction">The search direction (forwards or backwards).</param>
+		/// <param name="mode">Whether to stop only at word borders.</param>
+		/// <returns>The visual column of the next caret position, or -1 if there is no next caret position.</returns>
+		/// <remarks>
+		/// In the space between two line elements, it is sufficient that one of them contains a caret position;
+		/// though in many cases, both of them contain one.
+		/// </remarks>
+		public virtual int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
+		{
+			int stop1 = this.VisualColumn;
+			int stop2 = this.VisualColumn + this.VisualLength;
+			if (direction == LogicalDirection.Backward) {
+				if (visualColumn > stop2 && mode != CaretPositioningMode.WordStart && mode != CaretPositioningMode.WordStartOrSymbol)
+					return stop2;
+				else if (visualColumn > stop1)
+					return stop1;
+			} else {
+				if (visualColumn < stop1)
+					return stop1;
+				else if (visualColumn < stop2 && mode != CaretPositioningMode.WordStart && mode != CaretPositioningMode.WordStartOrSymbol)
+					return stop2;
+			}
+			return -1;
+		}
+		
+		/// <summary>
+		/// Gets whether the specified offset in this element is considered whitespace.
+		/// </summary>
+		public virtual bool IsWhitespace(int visualColumn)
+		{
+			return false;
+		}
+		
+		/// <summary>
+		/// Gets whether the <see cref="GetNextCaretPosition"/> implementation handles line borders.
+		/// If this property returns false, the caller of GetNextCaretPosition should handle the line
+		/// borders (i.e. place caret stops at the start and end of the line).
+		/// This property has an effect only for VisualLineElements that are at the start or end of a
+		/// <see cref="VisualLine"/>.
+		/// </summary>
+		public virtual bool HandlesLineBorders {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Queries the cursor over the visual line element.
+		/// </summary>
+		protected internal virtual void OnQueryCursor(QueryCursorEventArgs e)
+		{
+		}
+		
+		/// <summary>
+		/// Allows the visual line element to handle a mouse event.
+		/// </summary>
+		protected internal virtual void OnMouseDown(MouseButtonEventArgs e)
+		{
+		}
+		
+		/// <summary>
+		/// Allows the visual line element to handle a mouse event.
+		/// </summary>
+		protected internal virtual void OnMouseUp(MouseButtonEventArgs e)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElementGenerator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElementGenerator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElementGenerator.cs	(revision 11807)
@@ -0,0 +1,78 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// Abstract base class for generators that produce new visual line elements.
+	/// </summary>
+	public abstract class VisualLineElementGenerator
+	{
+		/// <summary>
+		/// Gets the text run construction context.
+		/// </summary>
+		protected ITextRunConstructionContext CurrentContext { get; private set; }
+		
+		/// <summary>
+		/// Initializes the generator for the <see cref="ITextRunConstructionContext"/>
+		/// </summary>
+		public virtual void StartGeneration(ITextRunConstructionContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			this.CurrentContext = context;
+		}
+		
+		/// <summary>
+		/// De-initializes the generator.
+		/// </summary>
+		public virtual void FinishGeneration()
+		{
+			this.CurrentContext = null;
+		}
+		
+		/// <summary>
+		/// Should only be used by VisualLine.ConstructVisualElements.
+		/// </summary>
+		internal int cachedInterest;
+		
+		/// <summary>
+		/// Gets the first offset >= startOffset where the generator wants to construct an element.
+		/// Return -1 to signal no interest.
+		/// </summary>
+		public abstract int GetFirstInterestedOffset(int startOffset);
+		
+		/// <summary>
+		/// Constructs an element at the specified offset.
+		/// May return null if no element should be constructed.
+		/// </summary>
+		/// <remarks>
+		/// Avoid signalling interest and then building no element by returning null - doing so
+		/// causes the generated <see cref="VisualLineText"/> elements to be unnecessarily split
+		/// at the position where you signalled interest.
+		/// </remarks>
+		public abstract VisualLineElement ConstructElement(int offset);
+	}
+	
+	internal interface IBuiltinElementGenerator
+	{
+		void FetchOptions(TextEditorOptions options);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElementTextRunProperties.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElementTextRunProperties.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineElementTextRunProperties.cs	(revision 11807)
@@ -0,0 +1,256 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.Windows;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// <see cref="TextRunProperties"/> implementation that allows changing the properties.
+	/// A <see cref="VisualLineElementTextRunProperties"/> instance usually is assigned to a single
+	/// <see cref="VisualLineElement"/>.
+	/// </summary>
+	public class VisualLineElementTextRunProperties : TextRunProperties, ICloneable
+	{
+		Brush backgroundBrush;
+		BaselineAlignment baselineAlignment;
+		CultureInfo cultureInfo;
+		double fontHintingEmSize;
+		double fontRenderingEmSize;
+		Brush foregroundBrush;
+		Typeface typeface;
+		TextDecorationCollection textDecorations;
+		TextEffectCollection textEffects;
+		TextRunTypographyProperties typographyProperties;
+		NumberSubstitution numberSubstitution;
+		
+		/// <summary>
+		/// Creates a new VisualLineElementTextRunProperties instance that copies its values
+		/// from the specified <paramref name="textRunProperties"/>.
+		/// For the <see cref="TextDecorations"/> and <see cref="TextEffects"/> collections, deep copies
+		/// are created if those collections are not frozen.
+		/// </summary>
+		public VisualLineElementTextRunProperties(TextRunProperties textRunProperties)
+		{
+			if (textRunProperties == null)
+				throw new ArgumentNullException("textRunProperties");
+			backgroundBrush = textRunProperties.BackgroundBrush;
+			baselineAlignment = textRunProperties.BaselineAlignment;
+			cultureInfo = textRunProperties.CultureInfo;
+			fontHintingEmSize = textRunProperties.FontHintingEmSize;
+			fontRenderingEmSize = textRunProperties.FontRenderingEmSize;
+			foregroundBrush = textRunProperties.ForegroundBrush;
+			typeface = textRunProperties.Typeface;
+			textDecorations = textRunProperties.TextDecorations;
+			if (textDecorations != null && !textDecorations.IsFrozen) {
+				textDecorations = textDecorations.Clone();
+			}
+			textEffects = textRunProperties.TextEffects;
+			if (textEffects != null && !textEffects.IsFrozen) {
+				textEffects = textEffects.Clone();
+			}
+			typographyProperties = textRunProperties.TypographyProperties;
+			numberSubstitution = textRunProperties.NumberSubstitution;
+		}
+		
+		/// <summary>
+		/// Creates a copy of this instance.
+		/// </summary>
+		public virtual VisualLineElementTextRunProperties Clone()
+		{
+			return new VisualLineElementTextRunProperties(this);
+		}
+		
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+		
+		/// <inheritdoc/>
+		public override Brush BackgroundBrush {
+			get { return backgroundBrush; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="BackgroundBrush"/>.
+		/// </summary>
+		public void SetBackgroundBrush(Brush value)
+		{
+			ExtensionMethods.CheckIsFrozen(value);
+			backgroundBrush = value;
+		}
+		
+		/// <inheritdoc/>
+		public override BaselineAlignment BaselineAlignment {
+			get { return baselineAlignment; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="BaselineAlignment"/>.
+		/// </summary>
+		public void SetBaselineAlignment(BaselineAlignment value)
+		{
+			baselineAlignment = value;
+		}
+		
+		/// <inheritdoc/>
+		public override CultureInfo CultureInfo {
+			get { return cultureInfo; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="CultureInfo"/>.
+		/// </summary>
+		public void SetCultureInfo(CultureInfo value)
+		{
+			if (value == null)
+				throw new ArgumentNullException("value");
+			cultureInfo = value;
+		}
+		
+		/// <inheritdoc/>
+		public override double FontHintingEmSize {
+			get { return fontHintingEmSize; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="FontHintingEmSize"/>.
+		/// </summary>
+		public void SetFontHintingEmSize(double value)
+		{
+			fontHintingEmSize = value;
+		}
+		
+		/// <inheritdoc/>
+		public override double FontRenderingEmSize {
+			get { return fontRenderingEmSize; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="FontRenderingEmSize"/>.
+		/// </summary>
+		public void SetFontRenderingEmSize(double value)
+		{
+			fontRenderingEmSize = value;
+		}
+		
+		/// <inheritdoc/>
+		public override Brush ForegroundBrush {
+			get { return foregroundBrush; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="ForegroundBrush"/>.
+		/// </summary>
+		public void SetForegroundBrush(Brush value)
+		{
+			ExtensionMethods.CheckIsFrozen(value);
+			foregroundBrush = value;
+		}
+		
+		/// <inheritdoc/>
+		public override Typeface Typeface {
+			get { return typeface; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="Typeface"/>.
+		/// </summary>
+		public void SetTypeface(Typeface value)
+		{
+			if (value == null)
+				throw new ArgumentNullException("value");
+			typeface = value;
+		}
+		
+		/// <summary>
+		/// Gets the text decorations. The value may be null, a frozen <see cref="TextDecorationCollection"/>
+		/// or an unfrozen <see cref="TextDecorationCollection"/>.
+		/// If the value is an unfrozen <see cref="TextDecorationCollection"/>, you may assume that the
+		/// collection instance is only used for this <see cref="TextRunProperties"/> instance and it is safe
+		/// to add <see cref="TextDecoration"/>s.
+		/// </summary>
+		public override TextDecorationCollection TextDecorations {
+			get { return textDecorations; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="TextDecorations"/>.
+		/// </summary>
+		public void SetTextDecorations(TextDecorationCollection value)
+		{
+			ExtensionMethods.CheckIsFrozen(value);
+			textDecorations = value;
+		}
+		
+		/// <summary>
+		/// Gets the text effects. The value may be null, a frozen <see cref="TextEffectCollection"/>
+		/// or an unfrozen <see cref="TextEffectCollection"/>.
+		/// If the value is an unfrozen <see cref="TextEffectCollection"/>, you may assume that the
+		/// collection instance is only used for this <see cref="TextRunProperties"/> instance and it is safe
+		/// to add <see cref="TextEffect"/>s.
+		/// </summary>
+		public override TextEffectCollection TextEffects {
+			get { return textEffects; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="TextEffects"/>.
+		/// </summary>
+		public void SetTextEffects(TextEffectCollection value)
+		{
+			ExtensionMethods.CheckIsFrozen(value);
+			textEffects = value;
+		}
+		
+		/// <summary>
+		/// Gets the typography properties for the text run.
+		/// </summary>
+		public override TextRunTypographyProperties TypographyProperties {
+			get { return typographyProperties; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="TypographyProperties"/>.
+		/// </summary>
+		public void SetTypographyProperties(TextRunTypographyProperties value)
+		{
+			typographyProperties = value;
+		}
+		
+		/// <summary>
+		/// Gets the number substitution settings for the text run.
+		/// </summary>
+		public override NumberSubstitution NumberSubstitution {
+			get { return numberSubstitution; }
+		}
+		
+		/// <summary>
+		/// Sets the <see cref="NumberSubstitution"/>.
+		/// </summary>
+		public void SetNumberSubstitution(NumberSubstitution value)
+		{
+			numberSubstitution = value;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineLinkText.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineLinkText.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineLinkText.cs	(revision 11807)
@@ -0,0 +1,129 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Navigation;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// VisualLineElement that represents a piece of text and is a clickable link.
+	/// </summary>
+	public class VisualLineLinkText : VisualLineText
+	{
+		/// <summary>
+		/// Gets/Sets the URL that is navigated to when the link is clicked.
+		/// </summary>
+		public Uri NavigateUri { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the window name where the URL will be opened.
+		/// </summary>
+		public string TargetName { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether the user needs to press Control to click the link.
+		/// The default value is true.
+		/// </summary>
+		public bool RequireControlModifierForClick { get; set; }
+		
+		/// <summary>
+		/// Creates a visual line text element with the specified length.
+		/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
+		/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
+		/// </summary>
+		public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
+		{
+			this.RequireControlModifierForClick = true;
+		}
+		
+		/// <inheritdoc/>
+		public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+		{
+			this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
+			this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
+			this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
+			return base.CreateTextRun(startVisualColumn, context);
+		}
+		
+		/// <summary>
+		/// Gets whether the link is currently clickable.
+		/// </summary>
+		/// <remarks>Returns true when control is pressed; or when
+		/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
+		protected bool LinkIsClickable()
+		{
+			if (NavigateUri == null)
+				return false;
+			if (RequireControlModifierForClick)
+				return (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control;
+			else
+				return true;
+		}
+		
+		/// <inheritdoc/>
+		protected internal override void OnQueryCursor(QueryCursorEventArgs e)
+		{
+			if (LinkIsClickable()) {
+				e.Handled = true;
+				e.Cursor = Cursors.Hand;
+			}
+		}
+		
+		/// <inheritdoc/>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
+		                                                 Justification = "I've seen Process.Start throw undocumented exceptions when the mail client / web browser is installed incorrectly")]
+		protected internal override void OnMouseDown(MouseButtonEventArgs e)
+		{
+			if (e.ChangedButton == MouseButton.Left && !e.Handled && LinkIsClickable()) {
+				RequestNavigateEventArgs args = new RequestNavigateEventArgs(this.NavigateUri, this.TargetName);
+				args.RoutedEvent = Hyperlink.RequestNavigateEvent;
+				FrameworkElement element = e.Source as FrameworkElement;
+				if (element != null) {
+					// allow user code to handle the navigation request
+					element.RaiseEvent(args);
+				}
+				if (!args.Handled) {
+					try {
+						Process.Start(this.NavigateUri.ToString());
+					} catch {
+						// ignore all kinds of errors during web browser start
+					}
+				}
+				e.Handled = true;
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override VisualLineText CreateInstance(int length)
+		{
+			return new VisualLineLinkText(ParentVisualLine, length) {
+				NavigateUri = this.NavigateUri,
+				TargetName = this.TargetName,
+				RequireControlModifierForClick = this.RequireControlModifierForClick
+			};
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineText.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineText.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineText.cs	(revision 11807)
@@ -0,0 +1,137 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows.Documents;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// VisualLineElement that represents a piece of text.
+	/// </summary>
+	public class VisualLineText : VisualLineElement
+	{
+		VisualLine parentVisualLine;
+		
+		/// <summary>
+		/// Gets the parent visual line.
+		/// </summary>
+		public VisualLine ParentVisualLine {
+			get { return parentVisualLine; }
+		}
+		
+		/// <summary>
+		/// Creates a visual line text element with the specified length.
+		/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
+		/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
+		/// </summary>
+		public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length)
+		{
+			if (parentVisualLine == null)
+				throw new ArgumentNullException("parentVisualLine");
+			this.parentVisualLine = parentVisualLine;
+		}
+		
+		/// <summary>
+		/// Override this method to control the type of new VisualLineText instances when
+		/// the visual line is split due to syntax highlighting.
+		/// </summary>
+		protected virtual VisualLineText CreateInstance(int length)
+		{
+			return new VisualLineText(parentVisualLine, length);
+		}
+		
+		/// <inheritdoc/>
+		public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			
+			int relativeOffset = startVisualColumn - VisualColumn;
+			StringSegment text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset + relativeOffset, DocumentLength - relativeOffset);
+			return new TextCharacters(text.Text, text.Offset, text.Count, this.TextRunProperties);
+		}
+		
+		/// <inheritdoc/>
+		public override bool IsWhitespace(int visualColumn)
+		{
+			int offset = visualColumn - this.VisualColumn + parentVisualLine.FirstDocumentLine.Offset + this.RelativeTextOffset;
+			return char.IsWhiteSpace(parentVisualLine.Document.GetCharAt(offset));
+		}
+		
+		/// <inheritdoc/>
+		public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			
+			int relativeOffset = visualColumnLimit - VisualColumn;
+			StringSegment text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset);
+			CharacterBufferRange range = new CharacterBufferRange(text.Text, text.Offset, text.Count);
+			return new TextSpan<CultureSpecificCharacterBufferRange>(range.Length, new CultureSpecificCharacterBufferRange(this.TextRunProperties.CultureInfo, range));
+		}
+		
+		/// <inheritdoc/>
+		public override bool CanSplit {
+			get { return true; }
+		}
+		
+		/// <inheritdoc/>
+		public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex)
+		{
+			if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength)
+				throw new ArgumentOutOfRangeException("splitVisualColumn", splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1));
+			if (elements == null)
+				throw new ArgumentNullException("elements");
+			if (elements[elementIndex] != this)
+				throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index");
+			int relativeSplitPos = splitVisualColumn - VisualColumn;
+			VisualLineText splitPart = CreateInstance(DocumentLength - relativeSplitPos);
+			SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset);
+			elements.Insert(elementIndex + 1, splitPart);
+		}
+		
+		/// <inheritdoc/>
+		public override int GetRelativeOffset(int visualColumn)
+		{
+			return this.RelativeTextOffset + visualColumn - this.VisualColumn;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetVisualColumn(int relativeTextOffset)
+		{
+			return this.VisualColumn + relativeTextOffset - this.RelativeTextOffset;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
+		{
+			int textOffset = parentVisualLine.StartOffset + this.RelativeTextOffset;
+			int pos = TextUtilities.GetNextCaretPosition(parentVisualLine.Document, textOffset + visualColumn - this.VisualColumn, direction, mode);
+			if (pos < textOffset || pos > textOffset + this.DocumentLength)
+				return -1;
+			else
+				return this.VisualColumn + pos - textOffset;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineTextParagraphProperties.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineTextParagraphProperties.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineTextParagraphProperties.cs	(revision 11807)
@@ -0,0 +1,46 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media.TextFormatting;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	sealed class VisualLineTextParagraphProperties : TextParagraphProperties
+	{
+		internal TextRunProperties defaultTextRunProperties;
+		internal TextWrapping textWrapping;
+		internal double tabSize;
+		internal double indent;
+		internal bool firstLineInParagraph;
+		
+		public override double DefaultIncrementalTab {
+			get { return tabSize; }
+		}
+		
+		public override FlowDirection FlowDirection { get { return FlowDirection.LeftToRight; } }
+		public override TextAlignment TextAlignment { get { return TextAlignment.Left; } }
+		public override double LineHeight { get { return double.NaN; } }
+		public override bool FirstLineInParagraph { get { return firstLineInParagraph; } }
+		public override TextRunProperties DefaultTextRunProperties { get { return defaultTextRunProperties; } }
+		public override TextWrapping TextWrapping { get { return textWrapping; } }
+		public override TextMarkerProperties TextMarkerProperties { get { return null; } }
+		public override double Indent { get { return indent; } }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineTextSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineTextSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLineTextSource.cs	(revision 11807)
@@ -0,0 +1,138 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows.Media.TextFormatting;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// WPF TextSource implementation that creates TextRuns for a VisualLine.
+	/// </summary>
+	sealed class VisualLineTextSource : TextSource, ITextRunConstructionContext
+	{
+		public VisualLineTextSource(VisualLine visualLine)
+		{
+			this.VisualLine = visualLine;
+		}
+		
+		public VisualLine VisualLine { get; private set; }
+		public TextView TextView { get; set; }
+		public TextDocument Document { get; set; }
+		public TextRunProperties GlobalTextRunProperties { get; set; }
+		
+		public override TextRun GetTextRun(int textSourceCharacterIndex)
+		{
+			try {
+				foreach (VisualLineElement element in VisualLine.Elements) {
+					if (textSourceCharacterIndex >= element.VisualColumn
+					    && textSourceCharacterIndex < element.VisualColumn + element.VisualLength)
+					{
+						int relativeOffset = textSourceCharacterIndex - element.VisualColumn;
+						TextRun run = element.CreateTextRun(textSourceCharacterIndex, this);
+						if (run == null)
+							throw new ArgumentNullException(element.GetType().Name + ".CreateTextRun");
+						if (run.Length == 0)
+							throw new ArgumentException("The returned TextRun must not have length 0.", element.GetType().Name + ".Length");
+						if (relativeOffset + run.Length > element.VisualLength)
+							throw new ArgumentException("The returned TextRun is too long.", element.GetType().Name + ".CreateTextRun");
+						InlineObjectRun inlineRun = run as InlineObjectRun;
+						if (inlineRun != null) {
+							inlineRun.VisualLine = VisualLine;
+							VisualLine.hasInlineObjects = true;
+							TextView.AddInlineObject(inlineRun);
+						}
+						return run;
+					}
+				}
+				if (TextView.Options.ShowEndOfLine && textSourceCharacterIndex == VisualLine.VisualLength) {
+					return CreateTextRunForNewLine();
+				}
+				return new TextEndOfParagraph(1);
+			} catch (Exception ex) {
+				Debug.WriteLine(ex.ToString());
+				throw;
+			}
+		}
+
+		TextRun CreateTextRunForNewLine()
+		{
+			string newlineText = "";
+			DocumentLine lastDocumentLine = VisualLine.LastDocumentLine;
+			if (lastDocumentLine.DelimiterLength == 2) {
+				newlineText = "¶";
+			} else if (lastDocumentLine.DelimiterLength == 1) {
+				char newlineChar = Document.GetCharAt(lastDocumentLine.Offset + lastDocumentLine.Length);
+				if (newlineChar == '\r')
+					newlineText = "\\r";
+				else if (newlineChar == '\n')
+					newlineText = "\\n";
+				else
+					newlineText = "?";
+			}
+			return new FormattedTextRun(new FormattedTextElement(TextView.cachedElements.GetTextForNonPrintableCharacter(newlineText, this), 0), GlobalTextRunProperties);
+		}
+		
+		public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int textSourceCharacterIndexLimit)
+		{
+			try {
+				foreach (VisualLineElement element in VisualLine.Elements) {
+					if (textSourceCharacterIndexLimit > element.VisualColumn
+					    && textSourceCharacterIndexLimit <= element.VisualColumn + element.VisualLength)
+					{
+						TextSpan<CultureSpecificCharacterBufferRange> span = element.GetPrecedingText(textSourceCharacterIndexLimit, this);
+						if (span == null)
+							break;
+						int relativeOffset = textSourceCharacterIndexLimit - element.VisualColumn;
+						if (span.Length > relativeOffset)
+							throw new ArgumentException("The returned TextSpan is too long.", element.GetType().Name + ".GetPrecedingText");
+						return span;
+					}
+				}
+				CharacterBufferRange empty = CharacterBufferRange.Empty;
+				return new TextSpan<CultureSpecificCharacterBufferRange>(empty.Length, new CultureSpecificCharacterBufferRange(null, empty));
+			} catch (Exception ex) {
+				Debug.WriteLine(ex.ToString());
+				throw;
+			}
+		}
+		
+		public override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int textSourceCharacterIndex)
+		{
+			throw new NotSupportedException();
+		}
+		
+		string cachedString;
+		int cachedStringOffset;
+		
+		public StringSegment GetText(int offset, int length)
+		{
+			if (cachedString != null) {
+				if (offset >= cachedStringOffset && offset + length <= cachedStringOffset + cachedString.Length) {
+					return new StringSegment(cachedString, offset - cachedStringOffset, length);
+				}
+			}
+			cachedStringOffset = offset;
+			return new StringSegment(cachedString = this.Document.GetText(offset, length));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLinesInvalidException.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLinesInvalidException.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualLinesInvalidException.cs	(revision 11807)
@@ -0,0 +1,59 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.Serialization;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// A VisualLinesInvalidException indicates that you accessed the <see cref="TextView.VisualLines"/> property
+	/// of the <see cref="TextView"/> while the visual lines were invalid.
+	/// </summary>
+	[Serializable]
+	public class VisualLinesInvalidException  : Exception
+	{
+		/// <summary>
+		/// Creates a new VisualLinesInvalidException instance.
+		/// </summary>
+		public VisualLinesInvalidException() : base()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new VisualLinesInvalidException instance.
+		/// </summary>
+		public VisualLinesInvalidException(string message) : base(message)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new VisualLinesInvalidException instance.
+		/// </summary>
+		public VisualLinesInvalidException(string message, Exception innerException) : base(message, innerException)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new VisualLinesInvalidException instance.
+		/// </summary>
+		protected VisualLinesInvalidException(SerializationInfo info, StreamingContext context) : base(info, context)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualYPosition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualYPosition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Rendering/VisualYPosition.cs	(revision 11807)
@@ -0,0 +1,61 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Rendering
+{
+	/// <summary>
+	/// An enum that specifies the possible Y positions that can be returned by VisualLine.GetVisualPosition.
+	/// </summary>
+	public enum VisualYPosition
+	{
+		/// <summary>
+		/// Returns the top of the TextLine.
+		/// </summary>
+		LineTop,
+		/// <summary>
+		/// Returns the top of the text.
+		/// If the line contains inline UI elements larger than the text, TextTop may be below LineTop.
+		/// For a line containing regular text (all in the editor's main font), this will be equal to LineTop.
+		/// </summary>
+		TextTop,
+		/// <summary>
+		/// Returns the bottom of the TextLine.
+		/// </summary>
+		LineBottom,
+		/// <summary>
+		/// The middle between LineTop and LineBottom.
+		/// </summary>
+		LineMiddle,
+		/// <summary>
+		/// Returns the bottom of the text. 
+		/// If the line contains inline UI elements larger than the text, TextBottom might be above LineBottom.
+		/// For a line containing regular text (all in the editor's main font), this will be equal to LineBottom.
+		/// </summary>
+		TextBottom,
+		/// <summary>
+		/// The middle between TextTop and TextBottom.
+		/// </summary>
+		TextMiddle,
+		/// <summary>
+		/// Returns the baseline of the text.
+		/// </summary>
+		Baseline
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/DropDownButton.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/DropDownButton.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/DropDownButton.cs	(revision 11807)
@@ -0,0 +1,89 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Controls.Primitives;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	/// <summary>
+	/// A button that opens a drop-down menu when clicked.
+	/// </summary>
+	public class DropDownButton : ButtonBase
+	{
+		/// <summary>
+		/// Identifies the <see cref="DropDownContentProperty" /> dependency property.
+		/// </summary>
+		public static readonly DependencyProperty DropDownContentProperty
+		= DependencyProperty.Register("DropDownContent", typeof(Popup),
+			typeof(DropDownButton), new FrameworkPropertyMetadata(null));
+		
+		/// <summary>
+		/// The key that identifies the <see cref="IsDropDownContentOpenProperty" /> dependency property.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
+		protected static readonly DependencyPropertyKey IsDropDownContentOpenPropertyKey
+		= DependencyProperty.RegisterReadOnly("IsDropDownContentOpen", typeof(bool),
+			typeof(DropDownButton), new FrameworkPropertyMetadata(false));
+		
+		/// <summary>
+		/// Identifies the <see cref="IsDropDownContentOpenProperty" /> dependency property.
+		/// </summary>
+		public static readonly DependencyProperty IsDropDownContentOpenProperty = IsDropDownContentOpenPropertyKey.DependencyProperty;
+		
+		static DropDownButton()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(DropDownButton), new FrameworkPropertyMetadata(typeof(DropDownButton)));
+		}
+		
+		/// <summary>
+		/// Gets/Sets the popup that is used as drop-down content.
+		/// </summary>
+		public Popup DropDownContent {
+			get { return (Popup)GetValue(DropDownContentProperty); }
+			set { SetValue(DropDownContentProperty, value); }
+		}
+		
+		/// <summary>
+		/// Gets whether the drop-down is opened.
+		/// </summary>
+		public bool IsDropDownContentOpen {
+			get { return (bool)GetValue(IsDropDownContentOpenProperty); }
+			protected set { SetValue(IsDropDownContentOpenPropertyKey, value); }
+		}
+		
+		/// <inheritdoc/>
+		protected override void OnClick()
+		{
+			if (DropDownContent != null && !IsDropDownContentOpen) {
+				DropDownContent.Placement = PlacementMode.Bottom;
+				DropDownContent.PlacementTarget = this;
+				DropDownContent.IsOpen = true;
+				DropDownContent.Closed += DropDownContent_Closed;
+				this.IsDropDownContentOpen = true;
+			}
+		}
+		
+		void DropDownContent_Closed(object sender, EventArgs e)
+		{
+			((Popup)sender).Closed -= DropDownContent_Closed;
+			this.IsDropDownContentOpen = false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/DropDownButton.xaml
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/DropDownButton.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/DropDownButton.xaml	(revision 11807)
@@ -0,0 +1,71 @@
+﻿<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+	xmlns:local="clr-namespace:ICSharpCode.AvalonEdit.Search"
+>
+	<!-- Colors for DropDownButton and SplitButton -->
+	<SolidColorBrush x:Key="{ComponentResourceKey {x:Type local:DropDownButton}, ActiveBorder}" Color="#FF0A246A"/>
+	<SolidColorBrush x:Key="{ComponentResourceKey {x:Type local:DropDownButton}, ActiveBackground}" Color="#FFB6BDD2"/>
+	
+	<!-- Style and Template for DropDownButton -->
+	<Style TargetType="{x:Type local:DropDownButton}">
+		<Setter Property="TextElement.Foreground" Value = "{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
+		<Setter Property="Control.Padding" Value="2,2,2,2"/>
+		<Setter Property="Border.BorderThickness" Value="1,1,1,1"/>
+		<Setter Property="Panel.Background" Value="Transparent"/>
+		<Setter Property="Border.BorderBrush" Value="Transparent"/>
+		<Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
+		<Setter Property="FrameworkElement.VerticalAlignment" Value="Center"/>
+		<Setter Property="Control.HorizontalContentAlignment" Value="Center"/>
+		<Setter Property="Control.VerticalContentAlignment" Value="Center"/>
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="local:DropDownButton"
+				                 xmlns:s="clr-namespace:System;assembly=mscorlib">
+					<Border
+						BorderThickness="{TemplateBinding Border.BorderThickness}"
+						BorderBrush="{TemplateBinding Border.BorderBrush}"
+						Background="{TemplateBinding Panel.Background}"
+						Name="OuterBorder"
+						SnapsToDevicePixels="True"
+					>
+						<StackPanel Orientation="Horizontal">
+							<ContentPresenter
+								Margin="{TemplateBinding Control.Padding}"
+								Content="{TemplateBinding ContentControl.Content}"
+								ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
+								ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
+								HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
+								VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
+								SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
+							<Path Margin="0,2,2,2"
+							      Data = "M0,0 L1,0 0.5,1 z"
+							      Fill = "{TemplateBinding TextElement.Foreground}"
+							      Width = "7"
+							      Height = "3.5"
+							      Stretch = "Fill"/>
+						</StackPanel>
+					</Border>
+					<ControlTemplate.Triggers>
+						<Trigger Property="UIElement.IsMouseOver" Value="True">
+							<Setter Property="Border.BorderBrush" TargetName="OuterBorder" Value="{DynamicResource {ComponentResourceKey {x:Type local:DropDownButton}, ActiveBorder}}" />
+							<Setter Property="Panel.Background" TargetName="OuterBorder" Value="{DynamicResource {ComponentResourceKey {x:Type local:DropDownButton}, ActiveBackground}}"/>
+						</Trigger>
+						<Trigger Property="UIElement.IsKeyboardFocused" Value="True">
+							<Setter Property="Border.BorderBrush" TargetName="OuterBorder" Value="{DynamicResource {ComponentResourceKey {x:Type local:DropDownButton}, ActiveBorder}}"/>
+							<Setter Property="Panel.Background" TargetName="OuterBorder" Value="{DynamicResource {ComponentResourceKey {x:Type local:DropDownButton}, ActiveBackground}}"/>
+						</Trigger>
+						<Trigger Property="UIElement.IsEnabled" Value="False">
+							<Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
+						</Trigger>
+						<Trigger Property="local:DropDownButton.IsDropDownContentOpen" Value="True">
+							<Setter Property="Border.BorderBrush" TargetName="OuterBorder" Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" />
+							<Setter Property="Border.BorderThickness" TargetName="OuterBorder" Value="1,1,1,0" />
+							<Setter Property="Border.Padding" TargetName="OuterBorder" Value="0,0,0,1" />
+							<Setter Property="Panel.Background" TargetName="OuterBorder" Value="Transparent"/>
+						</Trigger>
+					</ControlTemplate.Triggers>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+</ResourceDictionary>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/ISearchStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/ISearchStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/ISearchStrategy.cs	(revision 11807)
@@ -0,0 +1,103 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	/// <summary>
+	/// Basic interface for search algorithms.
+	/// </summary>
+	public interface ISearchStrategy : IEquatable<ISearchStrategy>
+	{
+		/// <summary>
+		/// Finds all matches in the given ITextSource and the given range.
+		/// </summary>
+		/// <remarks>
+		/// This method must be implemented thread-safe.
+		/// All segments in the result must be within the given range, and they must be returned in order
+		/// (e.g. if two results are returned, EndOffset of first result must be less than or equal StartOffset of second result).
+		/// </remarks>
+		IEnumerable<ISearchResult> FindAll(ITextSource document, int offset, int length);
+		
+		/// <summary>
+		/// Finds the next match in the given ITextSource and the given range.
+		/// </summary>
+		/// <remarks>This method must be implemented thread-safe.</remarks>
+		ISearchResult FindNext(ITextSource document, int offset, int length);
+	}
+	
+	/// <summary>
+	/// Represents a search result.
+	/// </summary>
+	public interface ISearchResult : ISegment
+	{
+		/// <summary>
+		/// Replaces parts of the replacement string with parts from the match. (e.g. $1)
+		/// </summary>
+		string ReplaceWith(string replacement);
+	}
+	
+	/// <summary>
+	/// Defines supported search modes.
+	/// </summary>
+	public enum SearchMode
+	{
+		/// <summary>
+		/// Standard search
+		/// </summary>
+		Normal,
+		/// <summary>
+		/// RegEx search
+		/// </summary>
+		RegEx,
+		/// <summary>
+		/// Wildcard search
+		/// </summary>
+		Wildcard
+	}
+	
+	/// <inheritdoc/>
+	public class SearchPatternException : Exception, ISerializable
+	{
+		/// <inheritdoc/>
+		public SearchPatternException()
+		{
+		}
+		
+		/// <inheritdoc/>
+		public SearchPatternException(string message) : base(message)
+		{
+		}
+		
+		/// <inheritdoc/>
+		public SearchPatternException(string message, Exception innerException) : base(message, innerException)
+		{
+		}
+
+		// This constructor is needed for serialization.
+		/// <inheritdoc/>
+		protected SearchPatternException(SerializationInfo info, StreamingContext context) : base(info, context)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/Localization.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/Localization.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/Localization.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	/// <summary>
+	/// Holds default texts for buttons and labels in the SearchPanel. Override properties to add other languages.
+	/// </summary>
+	public class Localization
+	{
+		/// <summary>
+		/// Default: 'Match case'
+		/// </summary>
+		public virtual string MatchCaseText {
+			get { return "Match case"; }
+		}
+		
+		/// <summary>
+		/// Default: 'Match whole words'
+		/// </summary>
+		public virtual string MatchWholeWordsText {
+			get { return "Match whole words"; }
+		}
+		
+		
+		/// <summary>
+		/// Default: 'Use regular expressions'
+		/// </summary>
+		public virtual string UseRegexText {
+			get { return "Use regular expressions"; }
+		}
+		
+		/// <summary>
+		/// Default: 'Find next (F3)'
+		/// </summary>
+		public virtual string FindNextText {
+			get { return "Find next (F3)"; }
+		}
+		
+		/// <summary>
+		/// Default: 'Find previous (Shift+F3)'
+		/// </summary>
+		public virtual string FindPreviousText {
+			get { return "Find previous (Shift+F3)"; }
+		}
+		
+		/// <summary>
+		/// Default: 'Error: '
+		/// </summary>
+		public virtual string ErrorText {
+			get { return "Error: "; }
+		}
+		
+		/// <summary>
+		/// Default: 'No matches found!'
+		/// </summary>
+		public virtual string NoMatchesFoundText {
+			get { return "No matches found!"; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/RegexSearchStrategy.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/RegexSearchStrategy.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/RegexSearchStrategy.cs	(revision 11807)
@@ -0,0 +1,85 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Windows.Documents;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	class RegexSearchStrategy : ISearchStrategy
+	{
+		readonly Regex searchPattern;
+		readonly bool matchWholeWords;
+		
+		public RegexSearchStrategy(Regex searchPattern, bool matchWholeWords)
+		{
+			if (searchPattern == null)
+				throw new ArgumentNullException("searchPattern");
+			this.searchPattern = searchPattern;
+			this.matchWholeWords = matchWholeWords;
+		}
+		
+		public IEnumerable<ISearchResult> FindAll(ITextSource document, int offset, int length)
+		{
+			int endOffset = offset + length;
+			foreach (Match result in searchPattern.Matches(document.Text)) {
+				int resultEndOffset = result.Length + result.Index;
+				if (offset > result.Index || endOffset < resultEndOffset)
+					continue;
+				if (matchWholeWords && (!IsWordBorder(document, result.Index) || !IsWordBorder(document, resultEndOffset)))
+					continue;
+				yield return new SearchResult { StartOffset = result.Index, Length = result.Length, Data = result };
+			}
+		}
+		
+		static bool IsWordBorder(ITextSource document, int offset)
+		{
+			return TextUtilities.GetNextCaretPosition(document, offset - 1, LogicalDirection.Forward, CaretPositioningMode.WordBorder) == offset;
+		}
+		
+		public ISearchResult FindNext(ITextSource document, int offset, int length)
+		{
+			return FindAll(document, offset, length).FirstOrDefault();
+		}
+		
+		public bool Equals(ISearchStrategy other)
+		{
+			var strategy = other as RegexSearchStrategy;
+			return strategy != null &&
+				strategy.searchPattern.ToString() == searchPattern.ToString() &&
+				strategy.searchPattern.Options == searchPattern.Options &&
+				strategy.searchPattern.RightToLeft == searchPattern.RightToLeft;
+		}
+	}
+	
+	class SearchResult : TextSegment, ISearchResult
+	{
+		public Match Data { get; set; }
+		
+		public string ReplaceWith(string replacement)
+		{
+			return Data.Result(replacement);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchCommands.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchCommands.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchCommands.cs	(revision 11807)
@@ -0,0 +1,148 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	/// <summary>
+	/// Search commands for AvalonEdit.
+	/// </summary>
+	public static class SearchCommands
+	{
+		/// <summary>
+		/// Finds the next occurrence in the file.
+		/// </summary>
+		public static readonly RoutedCommand FindNext = new RoutedCommand(
+			"FindNext", typeof(SearchPanel),
+			new InputGestureCollection { new KeyGesture(Key.F3) }
+		);
+		
+		/// <summary>
+		/// Finds the previous occurrence in the file.
+		/// </summary>
+		public static readonly RoutedCommand FindPrevious = new RoutedCommand(
+			"FindPrevious", typeof(SearchPanel),
+			new InputGestureCollection { new KeyGesture(Key.F3, ModifierKeys.Shift) }
+		);
+		
+		/// <summary>
+		/// Closes the SearchPanel.
+		/// </summary>
+		public static readonly RoutedCommand CloseSearchPanel = new RoutedCommand(
+			"CloseSearchPanel", typeof(SearchPanel),
+			new InputGestureCollection { new KeyGesture(Key.Escape) }
+		);
+	}
+	
+	/// <summary>
+	/// TextAreaInputHandler that registers all search-related commands.
+	/// </summary>
+	public class SearchInputHandler : TextAreaInputHandler
+	{
+		/// <summary>
+		/// Creates a new SearchInputHandler and registers the search-related commands.
+		/// </summary>
+		[Obsolete("Use SearchPanel.Install instead")]
+		public SearchInputHandler(TextArea textArea)
+			: base(textArea)
+		{
+			RegisterCommands(this.CommandBindings);
+			panel = SearchPanel.Install(textArea);
+		}
+		
+		internal SearchInputHandler(TextArea textArea, SearchPanel panel)
+			: base(textArea)
+		{
+			RegisterCommands(this.CommandBindings);
+			this.panel = panel;
+		}
+		
+		void RegisterCommands(ICollection<CommandBinding> commandBindings)
+		{
+			commandBindings.Add(new CommandBinding(ApplicationCommands.Find, ExecuteFind));
+			commandBindings.Add(new CommandBinding(SearchCommands.FindNext, ExecuteFindNext, CanExecuteWithOpenSearchPanel));
+			commandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious, CanExecuteWithOpenSearchPanel));
+			commandBindings.Add(new CommandBinding(SearchCommands.CloseSearchPanel, ExecuteCloseSearchPanel, CanExecuteWithOpenSearchPanel));
+		}
+		
+		SearchPanel panel;
+		
+		void ExecuteFind(object sender, ExecutedRoutedEventArgs e)
+		{
+			panel.Open();
+			if (!(TextArea.Selection.IsEmpty || TextArea.Selection.IsMultiline))
+				panel.SearchPattern = TextArea.Selection.GetText();
+			Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Input, (Action)delegate { panel.Reactivate(); });
+		}
+
+		void CanExecuteWithOpenSearchPanel(object sender, CanExecuteRoutedEventArgs e)
+		{
+			if (panel.IsClosed) {
+				e.CanExecute = false;
+				// Continue routing so that the key gesture can be consumed by another component.
+				e.ContinueRouting = true;
+			} else {
+				e.CanExecute = true;
+				e.Handled = true;
+			}
+		}
+		
+		void ExecuteFindNext(object sender, ExecutedRoutedEventArgs e)
+		{
+			if (!panel.IsClosed) {
+				panel.FindNext();
+				e.Handled = true;
+			}
+		}
+		
+		void ExecuteFindPrevious(object sender, ExecutedRoutedEventArgs e)
+		{
+			if (!panel.IsClosed) {
+				panel.FindPrevious();
+				e.Handled = true;
+			}
+		}
+		
+		void ExecuteCloseSearchPanel(object sender, ExecutedRoutedEventArgs e)
+		{
+			if (!panel.IsClosed) {
+				panel.Close();
+				e.Handled = true;
+			}
+		}
+		
+		/// <summary>
+		/// Fired when SearchOptions are modified inside the SearchPanel.
+		/// </summary>
+		public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged {
+			add { panel.SearchOptionsChanged += value; }
+			remove { panel.SearchOptionsChanged -= value; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchPanel.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchPanel.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchPanel.cs	(revision 11807)
@@ -0,0 +1,526 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Threading;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Folding;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	/// <summary>
+	/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
+	/// </summary>
+	public class SearchPanel : Control
+	{
+		TextArea textArea;
+		SearchInputHandler handler;
+		TextDocument currentDocument;
+		SearchResultBackgroundRenderer renderer;
+		TextBox searchTextBox;
+		SearchPanelAdorner adorner;
+		
+		#region DependencyProperties
+		/// <summary>
+		/// Dependency property for <see cref="UseRegex"/>.
+		/// </summary>
+		public static readonly DependencyProperty UseRegexProperty =
+			DependencyProperty.Register("UseRegex", typeof(bool), typeof(SearchPanel),
+			                            new FrameworkPropertyMetadata(false, SearchPatternChangedCallback));
+		
+		/// <summary>
+		/// Gets/sets whether the search pattern should be interpreted as regular expression.
+		/// </summary>
+		public bool UseRegex {
+			get { return (bool)GetValue(UseRegexProperty); }
+			set { SetValue(UseRegexProperty, value); }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="MatchCase"/>.
+		/// </summary>
+		public static readonly DependencyProperty MatchCaseProperty =
+			DependencyProperty.Register("MatchCase", typeof(bool), typeof(SearchPanel),
+			                            new FrameworkPropertyMetadata(false, SearchPatternChangedCallback));
+		
+		/// <summary>
+		/// Gets/sets whether the search pattern should be interpreted case-sensitive.
+		/// </summary>
+		public bool MatchCase {
+			get { return (bool)GetValue(MatchCaseProperty); }
+			set { SetValue(MatchCaseProperty, value); }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="WholeWords"/>.
+		/// </summary>
+		public static readonly DependencyProperty WholeWordsProperty =
+			DependencyProperty.Register("WholeWords", typeof(bool), typeof(SearchPanel),
+			                            new FrameworkPropertyMetadata(false, SearchPatternChangedCallback));
+		
+		/// <summary>
+		/// Gets/sets whether the search pattern should only match whole words.
+		/// </summary>
+		public bool WholeWords {
+			get { return (bool)GetValue(WholeWordsProperty); }
+			set { SetValue(WholeWordsProperty, value); }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="SearchPattern"/>.
+		/// </summary>
+		public static readonly DependencyProperty SearchPatternProperty =
+			DependencyProperty.Register("SearchPattern", typeof(string), typeof(SearchPanel),
+			                            new FrameworkPropertyMetadata("", SearchPatternChangedCallback));
+		
+		/// <summary>
+		/// Gets/sets the search pattern.
+		/// </summary>
+		public string SearchPattern {
+			get { return (string)GetValue(SearchPatternProperty); }
+			set { SetValue(SearchPatternProperty, value); }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="MarkerBrush"/>.
+		/// </summary>
+		public static readonly DependencyProperty MarkerBrushProperty =
+			DependencyProperty.Register("MarkerBrush", typeof(Brush), typeof(SearchPanel),
+			                            new FrameworkPropertyMetadata(Brushes.LightGreen, MarkerBrushChangedCallback));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for marking search results in the TextView.
+		/// </summary>
+		public Brush MarkerBrush {
+			get { return (Brush)GetValue(MarkerBrushProperty); }
+			set { SetValue(MarkerBrushProperty, value); }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="Localization"/>.
+		/// </summary>
+		public static readonly DependencyProperty LocalizationProperty =
+			DependencyProperty.Register("Localization", typeof(Localization), typeof(SearchPanel),
+			                            new FrameworkPropertyMetadata(new Localization()));
+		
+		/// <summary>
+		/// Gets/sets the localization for the SearchPanel.
+		/// </summary>
+		public Localization Localization {
+			get { return (Localization)GetValue(LocalizationProperty); }
+			set { SetValue(LocalizationProperty, value); }
+		}
+		#endregion
+		
+		static void MarkerBrushChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			SearchPanel panel = d as SearchPanel;
+			if (panel != null) {
+				panel.renderer.MarkerBrush = (Brush)e.NewValue;
+			}
+		}
+		
+		static SearchPanel()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(SearchPanel), new FrameworkPropertyMetadata(typeof(SearchPanel)));
+		}
+		
+		ISearchStrategy strategy;
+		
+		static void SearchPatternChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			SearchPanel panel = d as SearchPanel;
+			if (panel != null) {
+				panel.ValidateSearchText();
+				panel.UpdateSearch();
+			}
+		}
+
+		void UpdateSearch()
+		{
+			// only reset as long as there are results
+			// if no results are found, the "no matches found" message should not flicker.
+			// if results are found by the next run, the message will be hidden inside DoSearch ...
+			if (renderer.CurrentResults.Any())
+				messageView.IsOpen = false;
+			strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
+			OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
+			DoSearch(true);
+		}
+		
+		/// <summary>
+		/// Creates a new SearchPanel.
+		/// </summary>
+		[Obsolete("Use the Install method instead")]
+		public SearchPanel()
+		{
+		}
+		
+		/// <summary>
+		/// Attaches this SearchPanel to a TextArea instance.
+		/// </summary>
+		[Obsolete("Use the Install method instead")]
+		public void Attach(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			AttachInternal(textArea);
+		}
+		
+		/// <summary>
+		/// Creates a SearchPanel and installs it to the TextEditor's TextArea.
+		/// </summary>
+		/// <remarks>This is a convenience wrapper.</remarks>
+		public static SearchPanel Install(TextEditor editor)
+		{
+			if (editor == null)
+				throw new ArgumentNullException("editor");
+			return Install(editor.TextArea);
+		}
+		
+		/// <summary>
+		/// Creates a SearchPanel and installs it to the TextArea.
+		/// </summary>
+		public static SearchPanel Install(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			#pragma warning disable 618
+			SearchPanel panel = new SearchPanel();
+			panel.AttachInternal(textArea);
+			panel.handler = new SearchInputHandler(textArea, panel);
+			textArea.DefaultInputHandler.NestedInputHandlers.Add(panel.handler);
+			return panel;
+		}
+		
+		/// <summary>
+		/// Removes the SearchPanel from the TextArea.
+		/// </summary>
+		public void Uninstall()
+		{
+			CloseAndRemove();
+			textArea.DefaultInputHandler.NestedInputHandlers.Remove(handler);
+		}
+		
+		void AttachInternal(TextArea textArea)
+		{
+			this.textArea = textArea;
+			adorner = new SearchPanelAdorner(textArea, this);
+			DataContext = this;
+			
+			renderer = new SearchResultBackgroundRenderer();
+			currentDocument = textArea.Document;
+			if (currentDocument != null)
+				currentDocument.TextChanged += textArea_Document_TextChanged;
+			textArea.DocumentChanged += textArea_DocumentChanged;
+			KeyDown += SearchLayerKeyDown;
+			
+			this.CommandBindings.Add(new CommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
+			this.CommandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
+			this.CommandBindings.Add(new CommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
+			IsClosed = true;
+		}
+
+		void textArea_DocumentChanged(object sender, EventArgs e)
+		{
+			if (currentDocument != null)
+				currentDocument.TextChanged -= textArea_Document_TextChanged;
+			currentDocument = textArea.Document;
+			if (currentDocument != null) {
+				currentDocument.TextChanged += textArea_Document_TextChanged;
+				DoSearch(false);
+			}
+		}
+
+		void textArea_Document_TextChanged(object sender, EventArgs e)
+		{
+			DoSearch(false);
+		}
+		
+		/// <inheritdoc/>
+		public override void OnApplyTemplate()
+		{
+			base.OnApplyTemplate();
+			searchTextBox = Template.FindName("PART_searchTextBox", this) as TextBox;
+		}
+		
+		void ValidateSearchText()
+		{
+			if (searchTextBox == null)
+				return;
+			var be = searchTextBox.GetBindingExpression(TextBox.TextProperty);
+			try {
+				Validation.ClearInvalid(be);
+				UpdateSearch();
+			} catch (SearchPatternException ex) {
+				var ve = new ValidationError(be.ParentBinding.ValidationRules[0], be, ex.Message, ex);
+				Validation.MarkInvalid(be, ve);
+			}
+		}
+		
+		/// <summary>
+		/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
+		/// </summary>
+		public void Reactivate()
+		{
+			if (searchTextBox == null)
+				return;
+			searchTextBox.Focus();
+			searchTextBox.SelectAll();
+		}
+		
+		/// <summary>
+		/// Moves to the next occurrence in the file.
+		/// </summary>
+		public void FindNext()
+		{
+			SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset + 1);
+			if (result == null)
+				result = renderer.CurrentResults.FirstSegment;
+			if (result != null) {
+				SelectResult(result);
+			}
+		}
+
+		/// <summary>
+		/// Moves to the previous occurrence in the file.
+		/// </summary>
+		public void FindPrevious()
+		{
+			SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset);
+			if (result != null)
+				result = renderer.CurrentResults.GetPreviousSegment(result);
+			if (result == null)
+				result = renderer.CurrentResults.LastSegment;
+			if (result != null) {
+				SelectResult(result);
+			}
+		}
+		
+		ToolTip messageView = new ToolTip { Placement = PlacementMode.Bottom, StaysOpen = false };
+
+		void DoSearch(bool changeSelection)
+		{
+			if (IsClosed)
+				return;
+			renderer.CurrentResults.Clear();
+			
+			if (!string.IsNullOrEmpty(SearchPattern)) {
+				int offset = textArea.Caret.Offset;
+				if (changeSelection) {
+					textArea.ClearSelection();
+				}
+				// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
+				foreach (SearchResult result in strategy.FindAll(textArea.Document, 0, textArea.Document.TextLength)) {
+					if (changeSelection && result.StartOffset >= offset) {
+						SelectResult(result);
+						changeSelection = false;
+					}
+					renderer.CurrentResults.Add(result);
+				}
+				if (!renderer.CurrentResults.Any()) {
+					messageView.IsOpen = true;
+					messageView.Content = Localization.NoMatchesFoundText;
+					messageView.PlacementTarget = searchTextBox;
+				} else
+					messageView.IsOpen = false;
+			}
+			textArea.TextView.InvalidateLayer(KnownLayer.Selection);
+		}
+
+		void SelectResult(SearchResult result)
+		{
+			textArea.Caret.Offset = result.StartOffset;
+			textArea.Selection = Selection.Create(textArea, result.StartOffset, result.EndOffset);
+			textArea.Caret.BringCaretToView();
+			// show caret even if the editor does not have the Keyboard Focus
+			textArea.Caret.Show();
+		}
+		
+		void SearchLayerKeyDown(object sender, KeyEventArgs e)
+		{
+			switch (e.Key) {
+				case Key.Enter:
+					e.Handled = true;
+					messageView.IsOpen = false;
+					if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
+						FindPrevious();
+					else
+						FindNext();
+					if (searchTextBox != null) {
+						var error = Validation.GetErrors(searchTextBox).FirstOrDefault();
+						if (error != null) {
+							messageView.Content = Localization.ErrorText + " " + error.ErrorContent;
+							messageView.PlacementTarget = searchTextBox;
+							messageView.IsOpen = true;
+						}
+					}
+					break;
+				case Key.Escape:
+					e.Handled = true;
+					Close();
+					break;
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether the Panel is already closed.
+		/// </summary>
+		public bool IsClosed { get; private set; }
+		
+		/// <summary>
+		/// Closes the SearchPanel.
+		/// </summary>
+		public void Close()
+		{
+			bool hasFocus = this.IsKeyboardFocusWithin;
+			
+			var layer = AdornerLayer.GetAdornerLayer(textArea);
+			if (layer != null)
+				layer.Remove(adorner);
+			messageView.IsOpen = false;
+			textArea.TextView.BackgroundRenderers.Remove(renderer);
+			if (hasFocus)
+				textArea.Focus();
+			IsClosed = true;
+			
+			// Clear existing search results so that the segments don't have to be maintained
+			renderer.CurrentResults.Clear();
+		}
+		
+		/// <summary>
+		/// Closes the SearchPanel and removes it.
+		/// </summary>
+		[Obsolete("Use the Uninstall method instead!")]
+		public void CloseAndRemove()
+		{
+			Close();
+			textArea.DocumentChanged -= textArea_DocumentChanged;
+			if (currentDocument != null)
+				currentDocument.TextChanged -= textArea_Document_TextChanged;
+		}
+		
+		/// <summary>
+		/// Opens the an existing search panel.
+		/// </summary>
+		public void Open()
+		{
+			if (!IsClosed) return;
+			var layer = AdornerLayer.GetAdornerLayer(textArea);
+			if (layer != null)
+				layer.Add(adorner);
+			textArea.TextView.BackgroundRenderers.Add(renderer);
+			IsClosed = false;
+			DoSearch(false);
+		}
+		
+		/// <summary>
+		/// Fired when SearchOptions are changed inside the SearchPanel.
+		/// </summary>
+		public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
+		
+		/// <summary>
+		/// Raises the <see cref="SearchPanel.SearchOptionsChanged" /> event.
+		/// </summary>
+		protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
+		{
+			if (SearchOptionsChanged != null) {
+				SearchOptionsChanged(this, e);
+			}
+		}
+	}
+	
+	/// <summary>
+	/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
+	/// </summary>
+	public class SearchOptionsChangedEventArgs : EventArgs
+	{
+		/// <summary>
+		/// Gets the search pattern.
+		/// </summary>
+		public string SearchPattern { get; private set; }
+		
+		/// <summary>
+		/// Gets whether the search pattern should be interpreted case-sensitive.
+		/// </summary>
+		public bool MatchCase { get; private set; }
+		
+		/// <summary>
+		/// Gets whether the search pattern should be interpreted as regular expression.
+		/// </summary>
+		public bool UseRegex { get; private set; }
+		
+		/// <summary>
+		/// Gets whether the search pattern should only match whole words.
+		/// </summary>
+		public bool WholeWords { get; private set; }
+		
+		/// <summary>
+		/// Creates a new SearchOptionsChangedEventArgs instance.
+		/// </summary>
+		public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
+		{
+			this.SearchPattern = searchPattern;
+			this.MatchCase = matchCase;
+			this.UseRegex = useRegex;
+			this.WholeWords = wholeWords;
+		}
+	}
+	
+	class SearchPanelAdorner : Adorner
+	{
+		SearchPanel panel;
+		
+		public SearchPanelAdorner(TextArea textArea, SearchPanel panel)
+			: base(textArea)
+		{
+			this.panel = panel;
+			AddVisualChild(panel);
+		}
+		
+		protected override int VisualChildrenCount {
+			get { return 1; }
+		}
+
+		protected override Visual GetVisualChild(int index)
+		{
+			if (index != 0)
+				throw new ArgumentOutOfRangeException();
+			return panel;
+		}
+		
+		protected override Size ArrangeOverride(Size finalSize)
+		{
+			panel.Arrange(new Rect(new Point(0, 0), finalSize));
+			return new Size(panel.ActualWidth, panel.ActualHeight);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchPanel.xaml
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchPanel.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchPanel.xaml	(revision 11807)
@@ -0,0 +1,47 @@
+﻿<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:search="clr-namespace:ICSharpCode.AvalonEdit.Search">
+	<Style TargetType="search:SearchPanel">
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type search:SearchPanel}">
+					<Border Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" BorderBrush="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" BorderThickness="1" HorizontalAlignment="Right" VerticalAlignment="Top" Cursor="Arrow">
+						<StackPanel Orientation="Horizontal">
+							<TextBox Name="PART_searchTextBox" Focusable="True" Width="150" Height="24" Margin="3,3,3,0">
+								<TextBox.Text>
+									<Binding Path="SearchPattern" RelativeSource="{RelativeSource TemplatedParent}" UpdateSourceTrigger="PropertyChanged">
+										<Binding.ValidationRules>
+											<ExceptionValidationRule />
+										</Binding.ValidationRules>
+									</Binding>
+								</TextBox.Text>
+							</TextBox>
+							<search:DropDownButton Height="24">
+								<search:DropDownButton.DropDownContent>
+									<Popup StaysOpen="False">
+										<Border Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" BorderBrush="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" BorderThickness="1">
+											<StackPanel Orientation="Vertical">
+												<CheckBox IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" Content="{Binding Localization.MatchCaseText, RelativeSource={RelativeSource TemplatedParent}}" Margin="3" />
+												<CheckBox IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" Content="{Binding Localization.MatchWholeWordsText, RelativeSource={RelativeSource TemplatedParent}}" Margin="3" />
+												<CheckBox IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" Content="{Binding Localization.UseRegexText, RelativeSource={RelativeSource TemplatedParent}}" Margin="3" />
+											</StackPanel>
+										</Border>
+									</Popup>
+								</search:DropDownButton.DropDownContent>
+							</search:DropDownButton>
+							<Button Margin="3" Height="24" Width="24" Command="search:SearchCommands.FindPrevious" ToolTip="{Binding Localization.FindPreviousText, RelativeSource={RelativeSource TemplatedParent}}">
+								<Image Width="16" Height="16" Stretch="Fill" Source="prev.png" />
+							</Button>
+							<Button Margin="3" Height="24" Width="24" Command="search:SearchCommands.FindNext" ToolTip="{Binding Localization.FindNextText, RelativeSource={RelativeSource TemplatedParent}}">
+								<Image Width="16" Height="16" Stretch="Fill" Source="next.png" />
+							</Button>
+							<Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="search:SearchCommands.CloseSearchPanel"
+							        VerticalContentAlignment="Center" HorizontalContentAlignment="Center">
+								<Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" />
+							</Button>
+						</StackPanel>
+					</Border>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+</ResourceDictionary>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchResultBackgroundRenderer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchResultBackgroundRenderer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchResultBackgroundRenderer.cs	(revision 11807)
@@ -0,0 +1,93 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	class SearchResultBackgroundRenderer : IBackgroundRenderer
+	{
+		TextSegmentCollection<SearchResult> currentResults = new TextSegmentCollection<SearchResult>();
+		
+		public TextSegmentCollection<SearchResult> CurrentResults {
+			get { return currentResults; }
+		}
+		
+		public KnownLayer Layer {
+			get {
+				// draw behind selection
+				return KnownLayer.Selection;
+			}
+		}
+		
+		public SearchResultBackgroundRenderer()
+		{
+			markerBrush = Brushes.LightGreen;
+			markerPen = new Pen(markerBrush, 1);
+		}
+		
+		Brush markerBrush;
+		Pen markerPen;
+		
+		public Brush MarkerBrush {
+			get { return markerBrush; }
+			set {
+				this.markerBrush = value;
+				markerPen = new Pen(markerBrush, 1);
+			}
+		}
+		
+		public void Draw(TextView textView, DrawingContext drawingContext)
+		{
+			if (textView == null)
+				throw new ArgumentNullException("textView");
+			if (drawingContext == null)
+				throw new ArgumentNullException("drawingContext");
+			
+			if (currentResults == null || !textView.VisualLinesValid)
+				return;
+			
+			var visualLines = textView.VisualLines;
+			if (visualLines.Count == 0)
+				return;
+			
+			int viewStart = visualLines.First().FirstDocumentLine.Offset;
+			int viewEnd = visualLines.Last().LastDocumentLine.EndOffset;
+			
+			foreach (SearchResult result in currentResults.FindOverlappingSegments(viewStart, viewEnd - viewStart)) {
+				BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder();
+				geoBuilder.AlignToMiddleOfPixels = true;
+				geoBuilder.CornerRadius = 3;
+				geoBuilder.AddSegment(textView, result);
+				Geometry geometry = geoBuilder.CreateGeometry();
+				if (geometry != null) {
+					drawingContext.DrawGeometry(markerBrush, markerPen, geometry);
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchStrategyFactory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchStrategyFactory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Search/SearchStrategyFactory.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Windows.Controls;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Search
+{
+	/// <summary>
+	/// Provides factory methods for ISearchStrategies.
+	/// </summary>
+	public static class SearchStrategyFactory
+	{
+		/// <summary>
+		/// Creates a default ISearchStrategy with the given parameters.
+		/// </summary>
+		public static ISearchStrategy Create(string searchPattern, bool ignoreCase, bool matchWholeWords, SearchMode mode)
+		{
+			if (searchPattern == null)
+				throw new ArgumentNullException("searchPattern");
+			RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline;
+			if (ignoreCase)
+				options |= RegexOptions.IgnoreCase;
+			
+			switch (mode) {
+				case SearchMode.Normal:
+					searchPattern = Regex.Escape(searchPattern);
+					break;
+				case SearchMode.Wildcard:
+					searchPattern = ConvertWildcardsToRegex(searchPattern);
+					break;
+			}
+			try {
+				Regex pattern = new Regex(searchPattern, options);
+				return new RegexSearchStrategy(pattern, matchWholeWords);
+			} catch (ArgumentException ex) {
+				throw new SearchPatternException(ex.Message, ex);
+			}
+		}
+		
+		static string ConvertWildcardsToRegex(string searchPattern)
+		{
+			if (string.IsNullOrEmpty(searchPattern))
+				return "";
+			
+			StringBuilder builder = new StringBuilder();
+			
+			foreach (char ch in searchPattern) {
+				switch (ch) {
+					case '?':
+						builder.Append(".");
+						break;
+					case '*':
+						builder.Append(".*");
+						break;
+					default:
+						builder.Append(Regex.Escape(ch.ToString()));
+						break;
+				}
+			}
+			
+			return builder.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/IActiveElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/IActiveElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/IActiveElement.cs	(revision 11807)
@@ -0,0 +1,50 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Represents an active element that allows the snippet to stay interactive after insertion.
+	/// </summary>
+	public interface IActiveElement
+	{
+		/// <summary>
+		/// Called when the all snippet elements have been inserted.
+		/// </summary>
+		void OnInsertionCompleted();
+		
+		/// <summary>
+		/// Called when the interactive mode is deactivated.
+		/// </summary>
+		void Deactivate(SnippetEventArgs e);
+		
+		/// <summary>
+		/// Gets whether this element is editable (the user will be able to select it with Tab).
+		/// </summary>
+		bool IsEditable { get; }
+		
+		/// <summary>
+		/// Gets the segment associated with this element. May be null.
+		/// </summary>
+		ISegment Segment { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/InsertionContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/InsertionContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/InsertionContext.cs	(revision 11807)
@@ -0,0 +1,302 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Represents the context of a snippet insertion.
+	/// </summary>
+	public class InsertionContext : IWeakEventListener
+	{
+		enum Status
+		{
+			Insertion,
+			RaisingInsertionCompleted,
+			Interactive,
+			RaisingDeactivated,
+			Deactivated
+		}
+		
+		Status currentStatus = Status.Insertion;
+		
+		/// <summary>
+		/// Creates a new InsertionContext instance.
+		/// </summary>
+		public InsertionContext(TextArea textArea, int insertionPosition)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.TextArea = textArea;
+			this.Document = textArea.Document;
+			this.SelectedText = textArea.Selection.GetText();
+			this.InsertionPosition = insertionPosition;
+			this.startPosition = insertionPosition;
+			
+			DocumentLine startLine = this.Document.GetLineByOffset(insertionPosition);
+			ISegment indentation = TextUtilities.GetWhitespaceAfter(this.Document, startLine.Offset);
+			this.Indentation = Document.GetText(indentation.Offset, Math.Min(indentation.EndOffset, insertionPosition) - indentation.Offset);
+			this.Tab = textArea.Options.IndentationString;
+			
+			this.LineTerminator = TextUtilities.GetNewLineFromDocument(this.Document, startLine.LineNumber);
+		}
+		
+		/// <summary>
+		/// Gets the text area.
+		/// </summary>
+		public TextArea TextArea { get; private set; }
+		
+		/// <summary>
+		/// Gets the text document.
+		/// </summary>
+		public ICSharpCode.AvalonEdit.Document.TextDocument Document { get; private set; }
+		
+		/// <summary>
+		/// Gets the text that was selected before the insertion of the snippet.
+		/// </summary>
+		public string SelectedText { get; private set; }
+		
+		/// <summary>
+		/// Gets the indentation at the insertion position.
+		/// </summary>
+		public string Indentation { get; private set; }
+		
+		/// <summary>
+		/// Gets the indentation string for a single indentation level.
+		/// </summary>
+		public string Tab { get; private set; }
+		
+		/// <summary>
+		/// Gets the line terminator at the insertion position.
+		/// </summary>
+		public string LineTerminator { get; private set; }
+		
+		/// <summary>
+		/// Gets/Sets the insertion position.
+		/// </summary>
+		public int InsertionPosition { get; set; }
+		
+		readonly int startPosition;
+		ICSharpCode.AvalonEdit.Document.AnchorSegment wholeSnippetAnchor;
+		bool deactivateIfSnippetEmpty;
+		
+		/// <summary>
+		/// Gets the start position of the snippet insertion.
+		/// </summary>
+		public int StartPosition {
+			get {
+				if (wholeSnippetAnchor != null)
+					return wholeSnippetAnchor.Offset;
+				else
+					return startPosition;
+			}
+		}
+		
+		/// <summary>
+		/// Inserts text at the insertion position and advances the insertion position.
+		/// This method will add the current indentation to every line in <paramref name="text"/> and will
+		/// replace newlines with the expected newline for the document.
+		/// </summary>
+		public void InsertText(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (currentStatus != Status.Insertion)
+				throw new InvalidOperationException();
+			
+			text = text.Replace("\t", this.Tab);
+			
+			using (this.Document.RunUpdate()) {
+				int textOffset = 0;
+				SimpleSegment segment;
+				while ((segment = NewLineFinder.NextNewLine(text, textOffset)) != SimpleSegment.Invalid) {
+					string insertString = text.Substring(textOffset, segment.Offset - textOffset)
+						+ this.LineTerminator + this.Indentation;
+					this.Document.Insert(InsertionPosition, insertString);
+					this.InsertionPosition += insertString.Length;
+					textOffset = segment.EndOffset;
+				}
+				string remainingInsertString = text.Substring(textOffset);
+				this.Document.Insert(InsertionPosition, remainingInsertString);
+				this.InsertionPosition += remainingInsertString.Length;
+			}
+		}
+		
+		Dictionary<SnippetElement, IActiveElement> elementMap = new Dictionary<SnippetElement, IActiveElement>();
+		List<IActiveElement> registeredElements = new List<IActiveElement>();
+		
+		/// <summary>
+		/// Registers an active element. Elements should be registered during insertion and will be called back
+		/// when insertion has completed.
+		/// </summary>
+		/// <param name="owner">The snippet element that created the active element.</param>
+		/// <param name="element">The active element.</param>
+		public void RegisterActiveElement(SnippetElement owner, IActiveElement element)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			if (element == null)
+				throw new ArgumentNullException("element");
+			if (currentStatus != Status.Insertion)
+				throw new InvalidOperationException();
+			elementMap.Add(owner, element);
+			registeredElements.Add(element);
+		}
+		
+		/// <summary>
+		/// Returns the active element belonging to the specified snippet element, or null if no such active element is found.
+		/// </summary>
+		public IActiveElement GetActiveElement(SnippetElement owner)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			IActiveElement element;
+			if (elementMap.TryGetValue(owner, out element))
+				return element;
+			else
+				return null;
+		}
+		
+		/// <summary>
+		/// Gets the list of active elements.
+		/// </summary>
+		public IEnumerable<IActiveElement> ActiveElements {
+			get { return registeredElements; }
+		}
+		
+		/// <summary>
+		/// Calls the <see cref="IActiveElement.OnInsertionCompleted"/> method on all registered active elements
+		/// and raises the <see cref="InsertionCompleted"/> event.
+		/// </summary>
+		/// <param name="e">The EventArgs to use</param>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate",
+		                                                 Justification="There is an event and this method is raising it.")]
+		public void RaiseInsertionCompleted(EventArgs e)
+		{
+			if (currentStatus != Status.Insertion)
+				throw new InvalidOperationException();
+			if (e == null)
+				e = EventArgs.Empty;
+			
+			currentStatus = Status.RaisingInsertionCompleted;
+			int endPosition = this.InsertionPosition;
+			this.wholeSnippetAnchor = new AnchorSegment(Document, startPosition, endPosition - startPosition);
+			TextDocumentWeakEventManager.UpdateFinished.AddListener(Document, this);
+			deactivateIfSnippetEmpty = (endPosition != startPosition);
+			
+			foreach (IActiveElement element in registeredElements) {
+				element.OnInsertionCompleted();
+			}
+			if (InsertionCompleted != null)
+				InsertionCompleted(this, e);
+			currentStatus = Status.Interactive;
+			if (registeredElements.Count == 0) {
+				// deactivate immediately if there are no interactive elements
+				Deactivate(new SnippetEventArgs(DeactivateReason.NoActiveElements));
+			} else {
+				myInputHandler = new SnippetInputHandler(this);
+				// disable existing snippet input handlers - there can be only 1 active snippet
+				foreach (TextAreaStackedInputHandler h in TextArea.StackedInputHandlers) {
+					if (h is SnippetInputHandler)
+						TextArea.PopStackedInputHandler(h);
+				}
+				TextArea.PushStackedInputHandler(myInputHandler);
+			}
+		}
+		
+		SnippetInputHandler myInputHandler;
+		
+		/// <summary>
+		/// Occurs when the all snippet elements have been inserted.
+		/// </summary>
+		public event EventHandler InsertionCompleted;
+		
+		/// <summary>
+		/// Calls the <see cref="IActiveElement.Deactivate"/> method on all registered active elements.
+		/// </summary>
+		/// <param name="e">The EventArgs to use</param>
+		public void Deactivate(SnippetEventArgs e)
+		{
+			if (currentStatus == Status.Deactivated || currentStatus == Status.RaisingDeactivated)
+				return;
+			if (currentStatus != Status.Interactive)
+				throw new InvalidOperationException("Cannot call Deactivate() until RaiseInsertionCompleted() has finished.");
+			if (e == null)
+				e = new SnippetEventArgs(DeactivateReason.Unknown);
+			
+			TextDocumentWeakEventManager.UpdateFinished.RemoveListener(Document, this);
+			currentStatus = Status.RaisingDeactivated;
+			TextArea.PopStackedInputHandler(myInputHandler);
+			foreach (IActiveElement element in registeredElements) {
+				element.Deactivate(e);
+			}
+			if (Deactivated != null)
+				Deactivated(this, e);
+			currentStatus = Status.Deactivated;
+		}
+		
+		/// <summary>
+		/// Occurs when the interactive mode is deactivated.
+		/// </summary>
+		public event EventHandler<SnippetEventArgs> Deactivated;
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			return ReceiveWeakEvent(managerType, sender, e);
+		}
+		
+		/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
+		protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextDocumentWeakEventManager.UpdateFinished)) {
+				// Deactivate if snippet is deleted. This is necessary for correctly leaving interactive
+				// mode if Undo is pressed after a snippet insertion.
+				if (wholeSnippetAnchor.Length == 0 && deactivateIfSnippetEmpty)
+					Deactivate(new SnippetEventArgs(DeactivateReason.Deleted));
+				return true;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Adds existing segments as snippet elements.
+		/// </summary>
+		public void Link(ISegment mainElement, ISegment[] boundElements)
+		{
+			var main = new SnippetReplaceableTextElement { Text = Document.GetText(mainElement) };
+			RegisterActiveElement(main, new ReplaceableActiveElement(this, mainElement.Offset, mainElement.EndOffset));
+			foreach (var boundElement in boundElements) {
+				var bound = new SnippetBoundElement { TargetElement = main };
+				var start = Document.CreateAnchor(boundElement.Offset);
+				start.MovementType = AnchorMovementType.BeforeInsertion;
+				start.SurviveDeletion = true;
+				var end = Document.CreateAnchor(boundElement.EndOffset);
+				end.MovementType = AnchorMovementType.BeforeInsertion;
+				end.SurviveDeletion = true;
+				
+				RegisterActiveElement(bound, new BoundActiveElement(this, main, bound, new AnchorSegment(start, end)));
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/Snippet.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/Snippet.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/Snippet.cs	(revision 11807)
@@ -0,0 +1,59 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// A code snippet that can be inserted into the text editor.
+	/// </summary>
+	[Serializable]
+	public class Snippet : SnippetContainerElement
+	{
+		/// <summary>
+		/// Inserts the snippet into the text area.
+		/// </summary>
+		public void Insert(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			
+			ISegment selection = textArea.Selection.SurroundingSegment;
+			int insertionPosition = textArea.Caret.Offset;
+			
+			if (selection != null) // if something is selected
+				// use selection start instead of caret position,
+				// because caret could be at end of selection or anywhere inside.
+				// Removal of the selected text causes the caret position to be invalid.
+				insertionPosition = selection.Offset + TextUtilities.GetWhitespaceAfter(textArea.Document, selection.Offset).Length;
+			
+			InsertionContext context = new InsertionContext(textArea, insertionPosition);
+			
+			using (context.Document.RunUpdate()) {
+				if (selection != null)
+					textArea.Document.Remove(insertionPosition, selection.EndOffset - insertionPosition);
+				Insert(context);
+				context.RaiseInsertionCompleted(EventArgs.Empty);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetAnchorElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetAnchorElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetAnchorElement.cs	(revision 11807)
@@ -0,0 +1,113 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Creates a named anchor that can be accessed by other SnippetElements.
+	/// </summary>
+	public sealed class SnippetAnchorElement : SnippetElement
+	{
+		/// <summary>
+		/// Gets or sets the name of the anchor.
+		/// </summary>
+		public string Name { get; private set; }
+		
+		/// <summary>
+		/// Creates a SnippetAnchorElement with the supplied name.
+		/// </summary>
+		public SnippetAnchorElement(string name)
+		{
+			this.Name = name;
+		}
+		
+		/// <inheritdoc />
+		public override void Insert(InsertionContext context)
+		{
+			TextAnchor start = context.Document.CreateAnchor(context.InsertionPosition);
+			start.MovementType = AnchorMovementType.BeforeInsertion;
+			start.SurviveDeletion = true;
+			AnchorSegment segment = new AnchorSegment(start, start);
+			context.RegisterActiveElement(this, new AnchorElement(segment, Name, context));
+		}
+	}
+	
+	/// <summary>
+	/// AnchorElement created by SnippetAnchorElement.
+	/// </summary>
+	public sealed class AnchorElement : IActiveElement
+	{
+		/// <inheritdoc />
+		public bool IsEditable {
+			get { return false; }
+		}
+		
+		AnchorSegment segment;
+		InsertionContext context;
+		
+		/// <inheritdoc />
+		public ISegment Segment {
+			get { return segment; }
+		}
+		
+		/// <summary>
+		/// Creates a new AnchorElement.
+		/// </summary>
+		public AnchorElement(AnchorSegment segment, string name, InsertionContext context)
+		{
+			this.segment = segment;
+			this.context = context;
+			this.Name = name;
+		}
+		
+		/// <summary>
+		/// Gets or sets the text at the anchor.
+		/// </summary>
+		public string Text {
+			get { return context.Document.GetText(segment); }
+			set {
+				int offset = segment.Offset;
+				int length = segment.Length;
+				context.Document.Replace(offset, length, value);
+				if (length == 0) {
+					// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
+					segment = new AnchorSegment(context.Document, offset, value.Length);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets or sets the name of the anchor.
+		/// </summary>
+		public string Name { get; private set; }
+		
+		/// <inheritdoc />
+		public void OnInsertionCompleted()
+		{
+		}
+		
+		/// <inheritdoc />
+		public void Deactivate(SnippetEventArgs e)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetBoundElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetBoundElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetBoundElement.cs	(revision 11807)
@@ -0,0 +1,138 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Documents;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text.
+	/// </summary>
+	[Serializable]
+	public class SnippetBoundElement : SnippetElement
+	{
+		SnippetReplaceableTextElement targetElement;
+		
+		/// <summary>
+		/// Gets/Sets the target element.
+		/// </summary>
+		public SnippetReplaceableTextElement TargetElement {
+			get { return targetElement; }
+			set { targetElement = value; }
+		}
+		
+		/// <summary>
+		/// Converts the text before copying it.
+		/// </summary>
+		public virtual string ConvertText(string input)
+		{
+			return input;
+		}
+		
+		/// <inheritdoc/>
+		public override void Insert(InsertionContext context)
+		{
+			if (targetElement != null) {
+				TextAnchor start = context.Document.CreateAnchor(context.InsertionPosition);
+				start.MovementType = AnchorMovementType.BeforeInsertion;
+				start.SurviveDeletion = true;
+				string inputText = targetElement.Text;
+				if (inputText != null) {
+					context.InsertText(ConvertText(inputText));
+				}
+				TextAnchor end = context.Document.CreateAnchor(context.InsertionPosition);
+				end.MovementType = AnchorMovementType.BeforeInsertion;
+				end.SurviveDeletion = true;
+				AnchorSegment segment = new AnchorSegment(start, end);
+				context.RegisterActiveElement(this, new BoundActiveElement(context, targetElement, this, segment));
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override Inline ToTextRun()
+		{
+			if (targetElement != null) {
+				string inputText = targetElement.Text;
+				if (inputText != null) {
+					return new Italic(new Run(ConvertText(inputText)));
+				}
+			}
+			return base.ToTextRun();
+		}
+	}
+	
+	sealed class BoundActiveElement : IActiveElement
+	{
+		InsertionContext context;
+		SnippetReplaceableTextElement targetSnippetElement;
+		SnippetBoundElement boundElement;
+		internal IReplaceableActiveElement targetElement;
+		AnchorSegment segment;
+		
+		public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment)
+		{
+			this.context = context;
+			this.targetSnippetElement = targetSnippetElement;
+			this.boundElement = boundElement;
+			this.segment = segment;
+		}
+		
+		public void OnInsertionCompleted()
+		{
+			targetElement = context.GetActiveElement(targetSnippetElement) as IReplaceableActiveElement;
+			if (targetElement != null) {
+				targetElement.TextChanged += targetElement_TextChanged;
+			}
+		}
+		
+		void targetElement_TextChanged(object sender, EventArgs e)
+		{
+			// Don't copy text if the segments overlap (we would get an endless loop).
+			// This can happen if the user deletes the text between the replaceable element and the bound element.
+			if (SimpleSegment.GetOverlap(segment, targetElement.Segment) == SimpleSegment.Invalid) {
+				int offset = segment.Offset;
+				int length = segment.Length;
+				string text = boundElement.ConvertText(targetElement.Text);
+				if (length != text.Length || text != context.Document.GetText(offset, length)) {
+					// Call replace only if we're actually changing something.
+					// Without this check, we would generate an empty undo group when the user pressed undo.
+					context.Document.Replace(offset, length, text);
+					if (length == 0) {
+						// replacing an empty anchor segment with text won't enlarge it, so we have to recreate it
+						segment = new AnchorSegment(context.Document, offset, text.Length);
+					}
+				}
+			}
+		}
+		
+		public void Deactivate(SnippetEventArgs e)
+		{
+		}
+		
+		public bool IsEditable {
+			get { return false; }
+		}
+		
+		public ISegment Segment {
+			get { return segment; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetCaretElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetCaretElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetCaretElement.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.Serialization;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Sets the caret position after interactive mode has finished.
+	/// </summary>
+	[Serializable]
+	public class SnippetCaretElement : SnippetElement
+	{
+		[OptionalField]
+		bool setCaretOnlyIfTextIsSelected;
+		
+		/// <summary>
+		/// Creates a new SnippetCaretElement.
+		/// </summary>
+		public SnippetCaretElement()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new SnippetCaretElement.
+		/// </summary>
+		/// <param name="setCaretOnlyIfTextIsSelected">
+		/// If set to true, the caret is set only when some text was selected.
+		/// This is useful when both SnippetCaretElement and SnippetSelectionElement are used in the same snippet.
+		/// </param>
+		public SnippetCaretElement(bool setCaretOnlyIfTextIsSelected)
+		{
+			this.setCaretOnlyIfTextIsSelected = setCaretOnlyIfTextIsSelected;
+		}
+		
+		/// <inheritdoc/>
+		public override void Insert(InsertionContext context)
+		{
+			if (!setCaretOnlyIfTextIsSelected || !string.IsNullOrEmpty(context.SelectedText))
+				SetCaret(context);
+		}
+		
+		internal static void SetCaret(InsertionContext context)
+		{
+			TextAnchor pos = context.Document.CreateAnchor(context.InsertionPosition);
+			pos.MovementType = AnchorMovementType.BeforeInsertion;
+			pos.SurviveDeletion = true;
+			context.Deactivated += (sender, e) => {
+				if (e.Reason == DeactivateReason.ReturnPressed || e.Reason == DeactivateReason.NoActiveElements) {
+					context.TextArea.Caret.Offset = pos.Offset;
+				}
+			};
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetContainerElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetContainerElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetContainerElement.cs	(revision 11807)
@@ -0,0 +1,62 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows.Documents;
+
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// A snippet element that has sub-elements.
+	/// </summary>
+	[Serializable]
+	public class SnippetContainerElement : SnippetElement
+	{
+		NullSafeCollection<SnippetElement> elements = new NullSafeCollection<SnippetElement>();
+		
+		/// <summary>
+		/// Gets the list of child elements.
+		/// </summary>
+		public IList<SnippetElement> Elements {
+			get { return elements; }
+		}
+		
+		/// <inheritdoc/>
+		public override void Insert(InsertionContext context)
+		{
+			foreach (SnippetElement e in this.Elements) {
+				e.Insert(context);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override Inline ToTextRun()
+		{
+			Span span = new Span();
+			foreach (SnippetElement e in this.Elements) {
+				Inline r = e.ToTextRun();
+				if (r != null)
+					span.Inlines.Add(r);
+			}
+			return span;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetElement.cs	(revision 11807)
@@ -0,0 +1,43 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Documents;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// An element inside a snippet.
+	/// </summary>
+	[Serializable]
+	public abstract class SnippetElement
+	{
+		/// <summary>
+		/// Performs insertion of the snippet.
+		/// </summary>
+		public abstract void Insert(InsertionContext context);
+		
+		/// <summary>
+		/// Converts the snippet to text, with replaceable fields in italic.
+		/// </summary>
+		public virtual Inline ToTextRun()
+		{
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetEventArgs.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetEventArgs.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetEventArgs.cs	(revision 11807)
@@ -0,0 +1,72 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Provides information about the event that occured during use of snippets.
+	/// </summary>
+	public class SnippetEventArgs : EventArgs
+	{
+		/// <summary>
+		/// Gets the reason for deactivation.
+		/// </summary>
+		public DeactivateReason Reason { get; private set; }
+		
+		/// <summary>
+		/// Creates a new SnippetEventArgs object, with a DeactivateReason.
+		/// </summary>
+		public SnippetEventArgs(DeactivateReason reason)
+		{
+			this.Reason = reason;
+		}
+	}
+	
+	/// <summary>
+	/// Describes the reason for deactivation of a <see cref="SnippetElement" />.
+	/// </summary>
+	public enum DeactivateReason
+	{
+		/// <summary>
+		/// Unknown reason.
+		/// </summary>
+		Unknown,
+		/// <summary>
+		/// Snippet was deleted.
+		/// </summary>
+		Deleted,
+		/// <summary>
+		/// There are no active elements in the snippet.
+		/// </summary>
+		NoActiveElements,
+		/// <summary>
+		/// The SnippetInputHandler was detached.
+		/// </summary>
+		InputHandlerDetached,
+		/// <summary>
+		/// Return was pressed by the user.
+		/// </summary>
+		ReturnPressed,
+		/// <summary>
+		/// Escape was pressed by the user.
+		/// </summary>
+		EscapePressed
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetInputHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetInputHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetInputHandler.cs	(revision 11807)
@@ -0,0 +1,93 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Windows.Input;
+
+using ICSharpCode.AvalonEdit.Editing;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	sealed class SnippetInputHandler : TextAreaStackedInputHandler
+	{
+		readonly InsertionContext context;
+		
+		public SnippetInputHandler(InsertionContext context)
+			: base(context.TextArea)
+		{
+			this.context = context;
+		}
+		
+		public override void Attach()
+		{
+			base.Attach();
+			
+			SelectElement(FindNextEditableElement(-1, false));
+		}
+		
+		public override void Detach()
+		{
+			base.Detach();
+			context.Deactivate(new SnippetEventArgs(DeactivateReason.InputHandlerDetached));
+		}
+		
+		public override void OnPreviewKeyDown(KeyEventArgs e)
+		{
+			base.OnPreviewKeyDown(e);
+			if (e.Key == Key.Escape) {
+				context.Deactivate(new SnippetEventArgs(DeactivateReason.EscapePressed));
+				e.Handled = true;
+			} else if (e.Key == Key.Return) {
+				context.Deactivate(new SnippetEventArgs(DeactivateReason.ReturnPressed));
+				e.Handled = true;
+			} else if (e.Key == Key.Tab) {
+				bool backwards = e.KeyboardDevice.Modifiers == ModifierKeys.Shift;
+				SelectElement(FindNextEditableElement(TextArea.Caret.Offset, backwards));
+				e.Handled = true;
+			}
+		}
+		
+		void SelectElement(IActiveElement element)
+		{
+			if (element != null) {
+				TextArea.Selection = Selection.Create(TextArea, element.Segment);
+				TextArea.Caret.Offset = element.Segment.EndOffset;
+			}
+		}
+		
+		IActiveElement FindNextEditableElement(int offset, bool backwards)
+		{
+			IEnumerable<IActiveElement> elements = context.ActiveElements.Where(e => e.IsEditable && e.Segment != null);
+			if (backwards) {
+				elements = elements.Reverse();
+				foreach (IActiveElement element in elements) {
+					if (offset > element.Segment.EndOffset)
+						return element;
+				}
+			} else {
+				foreach (IActiveElement element in elements) {
+					if (offset < element.Segment.Offset)
+						return element;
+				}
+			}
+			return elements.FirstOrDefault();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetReplaceableTextElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetReplaceableTextElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetReplaceableTextElement.cs	(revision 11807)
@@ -0,0 +1,227 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Windows;
+using System.Windows.Documents;
+using System.Windows.Media;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Text element that is supposed to be replaced by the user.
+	/// Will register an <see cref="IReplaceableActiveElement"/>.
+	/// </summary>
+	[Serializable]
+	public class SnippetReplaceableTextElement : SnippetTextElement
+	{
+		/// <inheritdoc/>
+		public override void Insert(InsertionContext context)
+		{
+			int start = context.InsertionPosition;
+			base.Insert(context);
+			int end = context.InsertionPosition;
+			context.RegisterActiveElement(this, new ReplaceableActiveElement(context, start, end));
+		}
+		
+		/// <inheritdoc/>
+		public override Inline ToTextRun()
+		{
+			return new Italic(base.ToTextRun());
+		}
+	}
+	
+	/// <summary>
+	/// Interface for active element registered by <see cref="SnippetReplaceableTextElement"/>.
+	/// </summary>
+	public interface IReplaceableActiveElement : IActiveElement
+	{
+		/// <summary>
+		/// Gets the current text inside the element.
+		/// </summary>
+		string Text { get; }
+		
+		/// <summary>
+		/// Occurs when the text inside the element changes.
+		/// </summary>
+		event EventHandler TextChanged;
+	}
+	
+	sealed class ReplaceableActiveElement : IReplaceableActiveElement, IWeakEventListener
+	{
+		readonly InsertionContext context;
+		readonly int startOffset, endOffset;
+		TextAnchor start, end;
+		
+		public ReplaceableActiveElement(InsertionContext context, int startOffset, int endOffset)
+		{
+			this.context = context;
+			this.startOffset = startOffset;
+			this.endOffset = endOffset;
+		}
+		
+		void AnchorDeleted(object sender, EventArgs e)
+		{
+			context.Deactivate(new SnippetEventArgs(DeactivateReason.Deleted));
+		}
+		
+		public void OnInsertionCompleted()
+		{
+			// anchors must be created in OnInsertionCompleted because they should move only
+			// due to user insertions, not due to insertions of other snippet parts
+			start = context.Document.CreateAnchor(startOffset);
+			start.MovementType = AnchorMovementType.BeforeInsertion;
+			end = context.Document.CreateAnchor(endOffset);
+			end.MovementType = AnchorMovementType.AfterInsertion;
+			start.Deleted += AnchorDeleted;
+			end.Deleted += AnchorDeleted;
+			
+			// Be careful with references from the document to the editing/snippet layer - use weak events
+			// to prevent memory leaks when the text area control gets dropped from the UI while the snippet is active.
+			// The InsertionContext will keep us alive as long as the snippet is in interactive mode.
+			TextDocumentWeakEventManager.TextChanged.AddListener(context.Document, this);
+			
+			background = new Renderer { Layer = KnownLayer.Background, element = this };
+			foreground = new Renderer { Layer = KnownLayer.Text, element = this };
+			context.TextArea.TextView.BackgroundRenderers.Add(background);
+			context.TextArea.TextView.BackgroundRenderers.Add(foreground);
+			context.TextArea.Caret.PositionChanged += Caret_PositionChanged;
+			Caret_PositionChanged(null, null);
+			
+			this.Text = GetText();
+		}
+
+		public void Deactivate(SnippetEventArgs e)
+		{
+			TextDocumentWeakEventManager.TextChanged.RemoveListener(context.Document, this);
+			context.TextArea.TextView.BackgroundRenderers.Remove(background);
+			context.TextArea.TextView.BackgroundRenderers.Remove(foreground);
+			context.TextArea.Caret.PositionChanged -= Caret_PositionChanged;
+		}
+		
+		bool isCaretInside;
+		
+		void Caret_PositionChanged(object sender, EventArgs e)
+		{
+			ISegment s = this.Segment;
+			if (s != null) {
+				bool newIsCaretInside = s.Contains(context.TextArea.Caret.Offset, 0);
+				if (newIsCaretInside != isCaretInside) {
+					isCaretInside = newIsCaretInside;
+					context.TextArea.TextView.InvalidateLayer(foreground.Layer);
+				}
+			}
+		}
+		
+		Renderer background, foreground;
+		
+		public string Text { get; private set; }
+		
+		string GetText()
+		{
+			if (start.IsDeleted || end.IsDeleted)
+				return string.Empty;
+			else
+				return context.Document.GetText(start.Offset, Math.Max(0, end.Offset - start.Offset));
+		}
+		
+		public event EventHandler TextChanged;
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(TextDocumentWeakEventManager.TextChanged)) {
+				string newText = GetText();
+				if (this.Text != newText) {
+					this.Text = newText;
+					if (TextChanged != null)
+						TextChanged(this, e);
+				}
+				return true;
+			}
+			return false;
+		}
+		
+		public bool IsEditable {
+			get { return true; }
+		}
+		
+		public ISegment Segment {
+			get {
+				if (start.IsDeleted || end.IsDeleted)
+					return null;
+				else
+					return new SimpleSegment(start.Offset, Math.Max(0, end.Offset - start.Offset));
+			}
+		}
+		
+		sealed class Renderer : IBackgroundRenderer
+		{
+			static readonly Brush backgroundBrush = CreateBackgroundBrush();
+			static readonly Pen activeBorderPen = CreateBorderPen();
+			
+			static Brush CreateBackgroundBrush()
+			{
+				SolidColorBrush b = new SolidColorBrush(Colors.LimeGreen);
+				b.Opacity = 0.4;
+				b.Freeze();
+				return b;
+			}
+			
+			static Pen CreateBorderPen()
+			{
+				Pen p = new Pen(Brushes.Black, 1);
+				p.DashStyle = DashStyles.Dot;
+				p.Freeze();
+				return p;
+			}
+			
+			internal ReplaceableActiveElement element;
+			
+			public KnownLayer Layer { get; set; }
+			
+			public void Draw(TextView textView, System.Windows.Media.DrawingContext drawingContext)
+			{
+				ISegment s = element.Segment;
+				if (s != null) {
+					BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder();
+					geoBuilder.AlignToMiddleOfPixels = true;
+					if (Layer == KnownLayer.Background) {
+						geoBuilder.AddSegment(textView, s);
+						drawingContext.DrawGeometry(backgroundBrush, null, geoBuilder.CreateGeometry());
+					} else {
+						// draw foreground only if active
+						if (element.isCaretInside) {
+							geoBuilder.AddSegment(textView, s);
+							foreach (BoundActiveElement boundElement in element.context.ActiveElements.OfType<BoundActiveElement>()) {
+								if (boundElement.targetElement == element) {
+									geoBuilder.AddSegment(textView, boundElement.Segment);
+									geoBuilder.CloseFigure();
+								}
+							}
+							drawingContext.DrawGeometry(null, activeBorderPen, geoBuilder.CreateGeometry());
+						}
+					}
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetSelectionElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetSelectionElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetSelectionElement.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Inserts the previously selected text at the selection marker.
+	/// </summary>
+	[Serializable]
+	public class SnippetSelectionElement : SnippetElement
+	{
+		/// <summary>
+		/// Gets/Sets the new indentation of the selected text.
+		/// </summary>
+		public int Indentation { get; set; }
+		
+		/// <inheritdoc/>
+		public override void Insert(InsertionContext context)
+		{
+			StringBuilder tabString = new StringBuilder();
+			
+			for (int i = 0; i < Indentation; i++) {
+				tabString.Append(context.Tab);
+			}
+			
+			string indent = tabString.ToString();
+			
+			string text = context.SelectedText.TrimStart(' ', '\t');
+			
+			text = text.Replace(context.LineTerminator,
+			                             context.LineTerminator + indent);
+			
+			context.Document.Insert(context.InsertionPosition, text);
+			context.InsertionPosition += text.Length;
+			
+			if (string.IsNullOrEmpty(context.SelectedText))
+				SnippetCaretElement.SetCaret(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetTextElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetTextElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Snippets/SnippetTextElement.cs	(revision 11807)
@@ -0,0 +1,53 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows.Documents;
+
+namespace ICSharpCode.AvalonEdit.Snippets
+{
+	/// <summary>
+	/// Represents a text element in a snippet.
+	/// </summary>
+	[Serializable]
+	public class SnippetTextElement : SnippetElement
+	{
+		string text;
+		
+		/// <summary>
+		/// The text to be inserted.
+		/// </summary>
+		public string Text {
+			get { return text; }
+			set { text = value; }
+		}
+		
+		/// <inheritdoc/>
+		public override void Insert(InsertionContext context)
+		{
+			if (text != null)
+				context.InsertText(text);
+		}
+		
+		/// <inheritdoc/>
+		public override Inline ToTextRun()
+		{
+			return new Run(text ?? string.Empty);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditor.cs	(revision 11807)
@@ -0,0 +1,1182 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Data;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Media;
+using System.Windows.Shapes;
+using System.Windows.Threading;
+
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Highlighting;
+using ICSharpCode.AvalonEdit.Rendering;
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// The text editor control.
+	/// Contains a scrollable TextArea.
+	/// </summary>
+	[Localizability(LocalizationCategory.Text), ContentProperty("Text")]
+	public class TextEditor : Control, ITextEditorComponent, IServiceProvider, IWeakEventListener
+	{
+		#region Constructors
+		static TextEditor()
+		{
+			DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditor),
+			                                         new FrameworkPropertyMetadata(typeof(TextEditor)));
+			FocusableProperty.OverrideMetadata(typeof(TextEditor),
+			                                   new FrameworkPropertyMetadata(Boxes.True));
+		}
+		
+		/// <summary>
+		/// Creates a new TextEditor instance.
+		/// </summary>
+		public TextEditor() : this(new TextArea())
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new TextEditor instance.
+		/// </summary>
+		protected TextEditor(TextArea textArea)
+		{
+			if (textArea == null)
+				throw new ArgumentNullException("textArea");
+			this.textArea = textArea;
+			
+			textArea.TextView.Services.AddService(typeof(TextEditor), this);
+			
+			SetCurrentValue(OptionsProperty, textArea.Options);
+			SetCurrentValue(DocumentProperty, new TextDocument());
+		}
+		
+		#if !DOTNET4
+		void SetCurrentValue(DependencyProperty property, object value)
+		{
+			SetValue(property, value);
+		}
+		#endif
+		#endregion
+		
+		/// <inheritdoc/>
+		protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
+		{
+			return new TextEditorAutomationPeer(this);
+		}
+		
+		/// Forward focus to TextArea.
+		/// <inheritdoc/>
+		protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
+		{
+			base.OnGotKeyboardFocus(e);
+			if (e.NewFocus == this) {
+				Keyboard.Focus(this.TextArea);
+				e.Handled = true;
+			}
+		}
+		
+		#region Document property
+		/// <summary>
+		/// Document property.
+		/// </summary>
+		public static readonly DependencyProperty DocumentProperty
+			= TextView.DocumentProperty.AddOwner(
+				typeof(TextEditor), new FrameworkPropertyMetadata(OnDocumentChanged));
+		
+		/// <summary>
+		/// Gets/Sets the document displayed by the text editor.
+		/// This is a dependency property.
+		/// </summary>
+		public TextDocument Document {
+			get { return (TextDocument)GetValue(DocumentProperty); }
+			set { SetValue(DocumentProperty, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the document property has changed.
+		/// </summary>
+		public event EventHandler DocumentChanged;
+		
+		/// <summary>
+		/// Raises the <see cref="DocumentChanged"/> event.
+		/// </summary>
+		protected virtual void OnDocumentChanged(EventArgs e)
+		{
+			if (DocumentChanged != null) {
+				DocumentChanged(this, e);
+			}
+		}
+		
+		static void OnDocumentChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			((TextEditor)dp).OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
+		}
+		
+		void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
+		{
+			if (oldValue != null) {
+				TextDocumentWeakEventManager.TextChanged.RemoveListener(oldValue, this);
+				PropertyChangedEventManager.RemoveListener(oldValue.UndoStack, this, "IsOriginalFile");
+			}
+			textArea.Document = newValue;
+			if (newValue != null) {
+				TextDocumentWeakEventManager.TextChanged.AddListener(newValue, this);
+				PropertyChangedEventManager.AddListener(newValue.UndoStack, this, "IsOriginalFile");
+			}
+			OnDocumentChanged(EventArgs.Empty);
+			OnTextChanged(EventArgs.Empty);
+		}
+		#endregion
+		
+		#region Options property
+		/// <summary>
+		/// Options property.
+		/// </summary>
+		public static readonly DependencyProperty OptionsProperty
+			= TextView.OptionsProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(OnOptionsChanged));
+		
+		/// <summary>
+		/// Gets/Sets the options currently used by the text editor.
+		/// </summary>
+		public TextEditorOptions Options {
+			get { return (TextEditorOptions)GetValue(OptionsProperty); }
+			set { SetValue(OptionsProperty, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when a text editor option has changed.
+		/// </summary>
+		public event PropertyChangedEventHandler OptionChanged;
+		
+		/// <summary>
+		/// Raises the <see cref="OptionChanged"/> event.
+		/// </summary>
+		protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
+		{
+			if (OptionChanged != null) {
+				OptionChanged(this, e);
+			}
+		}
+		
+		static void OnOptionsChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
+		{
+			((TextEditor)dp).OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
+		}
+		
+		void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
+		{
+			if (oldValue != null) {
+				PropertyChangedWeakEventManager.RemoveListener(oldValue, this);
+			}
+			textArea.Options = newValue;
+			if (newValue != null) {
+				PropertyChangedWeakEventManager.AddListener(newValue, this);
+			}
+			OnOptionChanged(new PropertyChangedEventArgs(null));
+		}
+		
+		/// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
+		protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			if (managerType == typeof(PropertyChangedWeakEventManager)) {
+				OnOptionChanged((PropertyChangedEventArgs)e);
+				return true;
+			} else if (managerType == typeof(TextDocumentWeakEventManager.TextChanged)) {
+				OnTextChanged(e);
+				return true;
+			} else if (managerType == typeof(PropertyChangedEventManager)) {
+				return HandleIsOriginalChanged((PropertyChangedEventArgs)e);
+			}
+			return false;
+		}
+		
+		bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
+		{
+			return ReceiveWeakEvent(managerType, sender, e);
+		}
+		#endregion
+		
+		#region Text property
+		/// <summary>
+		/// Gets/Sets the text of the current document.
+		/// </summary>
+		[Localizability(LocalizationCategory.Text), DefaultValue("")]
+		public string Text {
+			get {
+				TextDocument document = this.Document;
+				return document != null ? document.Text : string.Empty;
+			}
+			set {
+				TextDocument document = GetDocument();
+				document.Text = value ?? string.Empty;
+				// after replacing the full text, the caret is positioned at the end of the document
+				// - reset it to the beginning.
+				this.CaretOffset = 0;
+				document.UndoStack.ClearAll();
+			}
+		}
+		
+		TextDocument GetDocument()
+		{
+			TextDocument document = this.Document;
+			if (document == null)
+				throw ThrowUtil.NoDocumentAssigned();
+			return document;
+		}
+		
+		/// <summary>
+		/// Occurs when the Text property changes.
+		/// </summary>
+		public event EventHandler TextChanged;
+		
+		/// <summary>
+		/// Raises the <see cref="TextChanged"/> event.
+		/// </summary>
+		protected virtual void OnTextChanged(EventArgs e)
+		{
+			if (TextChanged != null) {
+				TextChanged(this, e);
+			}
+		}
+		#endregion
+		
+		#region TextArea / ScrollViewer properties
+		readonly TextArea textArea;
+		ScrollViewer scrollViewer;
+		
+		/// <summary>
+		/// Is called after the template was applied.
+		/// </summary>
+		public override void OnApplyTemplate()
+		{
+			base.OnApplyTemplate();
+			scrollViewer = (ScrollViewer)Template.FindName("PART_ScrollViewer", this);
+		}
+		
+		/// <summary>
+		/// Gets the text area.
+		/// </summary>
+		public TextArea TextArea {
+			get {
+				return textArea;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the scroll viewer used by the text editor.
+		/// This property can return null if the template has not been applied / does not contain a scroll viewer.
+		/// </summary>
+		internal ScrollViewer ScrollViewer {
+			get { return scrollViewer; }
+		}
+		
+		bool CanExecute(RoutedUICommand command)
+		{
+			TextArea textArea = this.TextArea;
+			if (textArea == null)
+				return false;
+			else
+				return command.CanExecute(null, textArea);
+		}
+		
+		void Execute(RoutedUICommand command)
+		{
+			TextArea textArea = this.TextArea;
+			if (textArea != null)
+				command.Execute(null, textArea);
+		}
+		#endregion
+		
+		#region Syntax highlighting
+		/// <summary>
+		/// The <see cref="SyntaxHighlighting"/> property.
+		/// </summary>
+		public static readonly DependencyProperty SyntaxHighlightingProperty =
+			DependencyProperty.Register("SyntaxHighlighting", typeof(IHighlightingDefinition), typeof(TextEditor),
+			                            new FrameworkPropertyMetadata(OnSyntaxHighlightingChanged));
+		
+		
+		/// <summary>
+		/// Gets/sets the syntax highlighting definition used to colorize the text.
+		/// </summary>
+		public IHighlightingDefinition SyntaxHighlighting {
+			get { return (IHighlightingDefinition)GetValue(SyntaxHighlightingProperty); }
+			set { SetValue(SyntaxHighlightingProperty, value); }
+		}
+		
+		IVisualLineTransformer colorizer;
+		
+		static void OnSyntaxHighlightingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			((TextEditor)d).OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
+		}
+		
+		void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
+		{
+			if (colorizer != null) {
+				this.TextArea.TextView.LineTransformers.Remove(colorizer);
+				colorizer = null;
+			}
+			if (newValue != null) {
+				colorizer = CreateColorizer(newValue);
+				if (colorizer != null)
+					this.TextArea.TextView.LineTransformers.Insert(0, colorizer);
+			}
+		}
+		
+		/// <summary>
+		/// Creates the highlighting colorizer for the specified highlighting definition.
+		/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
+		/// </summary>
+		/// <returns></returns>
+		protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
+		{
+			if (highlightingDefinition == null)
+				throw new ArgumentNullException("highlightingDefinition");
+			return new HighlightingColorizer(highlightingDefinition);
+		}
+		#endregion
+		
+		#region WordWrap
+		/// <summary>
+		/// Word wrap dependency property.
+		/// </summary>
+		public static readonly DependencyProperty WordWrapProperty =
+			DependencyProperty.Register("WordWrap", typeof(bool), typeof(TextEditor),
+			                            new FrameworkPropertyMetadata(Boxes.False));
+		
+		/// <summary>
+		/// Specifies whether the text editor uses word wrapping.
+		/// </summary>
+		/// <remarks>
+		/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
+		/// HorizontalScrollBarVisibility setting.
+		/// </remarks>
+		public bool WordWrap {
+			get { return (bool)GetValue(WordWrapProperty); }
+			set { SetValue(WordWrapProperty, Boxes.Box(value)); }
+		}
+		#endregion
+		
+		#region IsReadOnly
+		/// <summary>
+		/// IsReadOnly dependency property.
+		/// </summary>
+		public static readonly DependencyProperty IsReadOnlyProperty =
+			DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(TextEditor),
+			                            new FrameworkPropertyMetadata(Boxes.False, OnIsReadOnlyChanged));
+		
+		/// <summary>
+		/// Specifies whether the user can change the text editor content.
+		/// Setting this property will replace the
+		/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
+		/// </summary>
+		public bool IsReadOnly {
+			get { return (bool)GetValue(IsReadOnlyProperty); }
+			set { SetValue(IsReadOnlyProperty, Boxes.Box(value)); }
+		}
+		
+		static void OnIsReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			TextEditor editor = d as TextEditor;
+			if (editor != null) {
+				if ((bool)e.NewValue)
+					editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
+				else
+					editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
+				
+				TextEditorAutomationPeer peer = TextEditorAutomationPeer.FromElement(editor) as TextEditorAutomationPeer;
+				if (peer != null) {
+					peer.RaiseIsReadOnlyChanged((bool)e.OldValue, (bool)e.NewValue);
+				}
+			}
+		}
+		#endregion
+		
+		#region IsModified
+		/// <summary>
+		/// Dependency property for <see cref="IsModified"/>
+		/// </summary>
+		public static readonly DependencyProperty IsModifiedProperty =
+			DependencyProperty.Register("IsModified", typeof(bool), typeof(TextEditor),
+			                            new FrameworkPropertyMetadata(Boxes.False, OnIsModifiedChanged));
+		
+		/// <summary>
+		/// Gets/Sets the 'modified' flag.
+		/// </summary>
+		public bool IsModified {
+			get { return (bool)GetValue(IsModifiedProperty); }
+			set { SetValue(IsModifiedProperty, Boxes.Box(value)); }
+		}
+		
+		static void OnIsModifiedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			TextEditor editor = d as TextEditor;
+			if (editor != null) {
+				TextDocument document = editor.Document;
+				if (document != null) {
+					UndoStack undoStack = document.UndoStack;
+					if ((bool)e.NewValue) {
+						if (undoStack.IsOriginalFile)
+							undoStack.DiscardOriginalFileMarker();
+					} else {
+						undoStack.MarkAsOriginalFile();
+					}
+				}
+			}
+		}
+		
+		bool HandleIsOriginalChanged(PropertyChangedEventArgs e)
+		{
+			if (e.PropertyName == "IsOriginalFile") {
+				TextDocument document = this.Document;
+				if (document != null) {
+					SetCurrentValue(IsModifiedProperty, Boxes.Box(!document.UndoStack.IsOriginalFile));
+				}
+				return true;
+			} else {
+				return false;
+			}
+		}
+		#endregion
+		
+		#region ShowLineNumbers
+		/// <summary>
+		/// ShowLineNumbers dependency property.
+		/// </summary>
+		public static readonly DependencyProperty ShowLineNumbersProperty =
+			DependencyProperty.Register("ShowLineNumbers", typeof(bool), typeof(TextEditor),
+			                            new FrameworkPropertyMetadata(Boxes.False, OnShowLineNumbersChanged));
+		
+		/// <summary>
+		/// Specifies whether line numbers are shown on the left to the text view.
+		/// </summary>
+		public bool ShowLineNumbers {
+			get { return (bool)GetValue(ShowLineNumbersProperty); }
+			set { SetValue(ShowLineNumbersProperty, Boxes.Box(value)); }
+		}
+		
+		static void OnShowLineNumbersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			TextEditor editor = (TextEditor)d;
+			var leftMargins = editor.TextArea.LeftMargins;
+			if ((bool)e.NewValue) {
+				LineNumberMargin lineNumbers = new LineNumberMargin();
+				Line line = (Line)DottedLineMargin.Create();
+				leftMargins.Insert(0, lineNumbers);
+				leftMargins.Insert(1, line);
+				var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
+				line.SetBinding(Line.StrokeProperty, lineNumbersForeground);
+				lineNumbers.SetBinding(Control.ForegroundProperty, lineNumbersForeground);
+			} else {
+				for (int i = 0; i < leftMargins.Count; i++) {
+					if (leftMargins[i] is LineNumberMargin) {
+						leftMargins.RemoveAt(i);
+						if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) {
+							leftMargins.RemoveAt(i);
+						}
+						break;
+					}
+				}
+			}
+		}
+		#endregion
+		
+		#region LineNumbersForeground
+		/// <summary>
+		/// LineNumbersForeground dependency property.
+		/// </summary>
+		public static readonly DependencyProperty LineNumbersForegroundProperty =
+			DependencyProperty.Register("LineNumbersForeground", typeof(Brush), typeof(TextEditor),
+			                            new FrameworkPropertyMetadata(Brushes.Gray, OnLineNumbersForegroundChanged));
+		
+		/// <summary>
+		/// Gets/sets the Brush used for displaying the foreground color of line numbers.
+		/// </summary>
+		public Brush LineNumbersForeground {
+			get { return (Brush)GetValue(LineNumbersForegroundProperty); }
+			set { SetValue(LineNumbersForegroundProperty, value); }
+		}
+		
+		static void OnLineNumbersForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
+		{
+			TextEditor editor = (TextEditor)d;
+			var lineNumberMargin = editor.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;;
+			
+			if (lineNumberMargin != null) {
+				lineNumberMargin.SetValue(Control.ForegroundProperty, e.NewValue);
+			}
+		}
+		#endregion
+		
+		#region TextBoxBase-like methods
+		/// <summary>
+		/// Appends text to the end of the document.
+		/// </summary>
+		public void AppendText(string textData)
+		{
+			var document = GetDocument();
+			document.Insert(document.TextLength, textData);
+		}
+		
+		/// <summary>
+		/// Begins a group of document changes.
+		/// </summary>
+		public void BeginChange()
+		{
+			GetDocument().BeginUpdate();
+		}
+		
+		/// <summary>
+		/// Copies the current selection to the clipboard.
+		/// </summary>
+		public void Copy()
+		{
+			Execute(ApplicationCommands.Copy);
+		}
+		
+		/// <summary>
+		/// Removes the current selection and copies it to the clipboard.
+		/// </summary>
+		public void Cut()
+		{
+			Execute(ApplicationCommands.Cut);
+		}
+		
+		/// <summary>
+		/// Begins a group of document changes and returns an object that ends the group of document
+		/// changes when it is disposed.
+		/// </summary>
+		public IDisposable DeclareChangeBlock()
+		{
+			return GetDocument().RunUpdate();
+		}
+		
+		/// <summary>
+		/// Ends the current group of document changes.
+		/// </summary>
+		public void EndChange()
+		{
+			GetDocument().EndUpdate();
+		}
+		
+		/// <summary>
+		/// Scrolls one line down.
+		/// </summary>
+		public void LineDown()
+		{
+			if (scrollViewer != null)
+				scrollViewer.LineDown();
+		}
+		
+		/// <summary>
+		/// Scrolls to the left.
+		/// </summary>
+		public void LineLeft()
+		{
+			if (scrollViewer != null)
+				scrollViewer.LineLeft();
+		}
+		
+		/// <summary>
+		/// Scrolls to the right.
+		/// </summary>
+		public void LineRight()
+		{
+			if (scrollViewer != null)
+				scrollViewer.LineRight();
+		}
+		
+		/// <summary>
+		/// Scrolls one line up.
+		/// </summary>
+		public void LineUp()
+		{
+			if (scrollViewer != null)
+				scrollViewer.LineUp();
+		}
+		
+		/// <summary>
+		/// Scrolls one page down.
+		/// </summary>
+		public void PageDown()
+		{
+			if (scrollViewer != null)
+				scrollViewer.PageDown();
+		}
+		
+		/// <summary>
+		/// Scrolls one page up.
+		/// </summary>
+		public void PageUp()
+		{
+			if (scrollViewer != null)
+				scrollViewer.PageUp();
+		}
+		
+		/// <summary>
+		/// Scrolls one page left.
+		/// </summary>
+		public void PageLeft()
+		{
+			if (scrollViewer != null)
+				scrollViewer.PageLeft();
+		}
+		
+		/// <summary>
+		/// Scrolls one page right.
+		/// </summary>
+		public void PageRight()
+		{
+			if (scrollViewer != null)
+				scrollViewer.PageRight();
+		}
+		
+		/// <summary>
+		/// Pastes the clipboard content.
+		/// </summary>
+		public void Paste()
+		{
+			Execute(ApplicationCommands.Paste);
+		}
+		
+		/// <summary>
+		/// Redoes the most recent undone command.
+		/// </summary>
+		/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
+		public bool Redo()
+		{
+			if (CanExecute(ApplicationCommands.Redo)) {
+				Execute(ApplicationCommands.Redo);
+				return true;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Scrolls to the end of the document.
+		/// </summary>
+		public void ScrollToEnd()
+		{
+			ApplyTemplate(); // ensure scrollViewer is created
+			if (scrollViewer != null)
+				scrollViewer.ScrollToEnd();
+		}
+		
+		/// <summary>
+		/// Scrolls to the start of the document.
+		/// </summary>
+		public void ScrollToHome()
+		{
+			ApplyTemplate(); // ensure scrollViewer is created
+			if (scrollViewer != null)
+				scrollViewer.ScrollToHome();
+		}
+		
+		/// <summary>
+		/// Scrolls to the specified position in the document.
+		/// </summary>
+		public void ScrollToHorizontalOffset(double offset)
+		{
+			ApplyTemplate(); // ensure scrollViewer is created
+			if (scrollViewer != null)
+				scrollViewer.ScrollToHorizontalOffset(offset);
+		}
+		
+		/// <summary>
+		/// Scrolls to the specified position in the document.
+		/// </summary>
+		public void ScrollToVerticalOffset(double offset)
+		{
+			ApplyTemplate(); // ensure scrollViewer is created
+			if (scrollViewer != null)
+				scrollViewer.ScrollToVerticalOffset(offset);
+		}
+		
+		/// <summary>
+		/// Selects the entire text.
+		/// </summary>
+		public void SelectAll()
+		{
+			Execute(ApplicationCommands.SelectAll);
+		}
+		
+		/// <summary>
+		/// Undoes the most recent command.
+		/// </summary>
+		/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
+		public bool Undo()
+		{
+			if (CanExecute(ApplicationCommands.Undo)) {
+				Execute(ApplicationCommands.Undo);
+				return true;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Gets if the most recent undone command can be redone.
+		/// </summary>
+		public bool CanRedo {
+			get { return CanExecute(ApplicationCommands.Redo); }
+		}
+		
+		/// <summary>
+		/// Gets if the most recent command can be undone.
+		/// </summary>
+		public bool CanUndo {
+			get { return CanExecute(ApplicationCommands.Undo); }
+		}
+		
+		/// <summary>
+		/// Gets the vertical size of the document.
+		/// </summary>
+		public double ExtentHeight {
+			get {
+				return scrollViewer != null ? scrollViewer.ExtentHeight : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the horizontal size of the current document region.
+		/// </summary>
+		public double ExtentWidth {
+			get {
+				return scrollViewer != null ? scrollViewer.ExtentWidth : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the horizontal size of the viewport.
+		/// </summary>
+		public double ViewportHeight {
+			get {
+				return scrollViewer != null ? scrollViewer.ViewportHeight : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the horizontal size of the viewport.
+		/// </summary>
+		public double ViewportWidth {
+			get {
+				return scrollViewer != null ? scrollViewer.ViewportWidth : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the vertical scroll position.
+		/// </summary>
+		public double VerticalOffset {
+			get {
+				return scrollViewer != null ? scrollViewer.VerticalOffset : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the horizontal scroll position.
+		/// </summary>
+		public double HorizontalOffset {
+			get {
+				return scrollViewer != null ? scrollViewer.HorizontalOffset : 0;
+			}
+		}
+		#endregion
+		
+		#region TextBox methods
+		/// <summary>
+		/// Gets/Sets the selected text.
+		/// </summary>
+		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+		public string SelectedText {
+			get {
+				TextArea textArea = this.TextArea;
+				// We'll get the text from the whole surrounding segment.
+				// This is done to ensure that SelectedText.Length == SelectionLength.
+				if (textArea != null && textArea.Document != null && !textArea.Selection.IsEmpty)
+					return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
+				else
+					return string.Empty;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				TextArea textArea = this.TextArea;
+				if (textArea != null && textArea.Document != null) {
+					int offset = this.SelectionStart;
+					int length = this.SelectionLength;
+					textArea.Document.Replace(offset, length, value);
+					// keep inserted text selected
+					textArea.Selection = SimpleSelection.Create(textArea, offset, offset + value.Length);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the caret position.
+		/// </summary>
+		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+		public int CaretOffset {
+			get {
+				TextArea textArea = this.TextArea;
+				if (textArea != null)
+					return textArea.Caret.Offset;
+				else
+					return 0;
+			}
+			set {
+				TextArea textArea = this.TextArea;
+				if (textArea != null)
+					textArea.Caret.Offset = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the start position of the selection.
+		/// </summary>
+		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+		public int SelectionStart {
+			get {
+				TextArea textArea = this.TextArea;
+				if (textArea != null) {
+					if (textArea.Selection.IsEmpty)
+						return textArea.Caret.Offset;
+					else
+						return textArea.Selection.SurroundingSegment.Offset;
+				} else {
+					return 0;
+				}
+			}
+			set {
+				Select(value, SelectionLength);
+			}
+		}
+		
+		/// <summary>
+		/// Gets/sets the length of the selection.
+		/// </summary>
+		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+		public int SelectionLength {
+			get {
+				TextArea textArea = this.TextArea;
+				if (textArea != null && !textArea.Selection.IsEmpty)
+					return textArea.Selection.SurroundingSegment.Length;
+				else
+					return 0;
+			}
+			set {
+				Select(SelectionStart, value);
+			}
+		}
+		
+		/// <summary>
+		/// Selects the specified text section.
+		/// </summary>
+		public void Select(int start, int length)
+		{
+			int documentLength = Document != null ? Document.TextLength : 0;
+			if (start < 0 || start > documentLength)
+				throw new ArgumentOutOfRangeException("start", start, "Value must be between 0 and " + documentLength);
+			if (length < 0 || start + length > documentLength)
+				throw new ArgumentOutOfRangeException("length", length, "Value must be between 0 and " + (documentLength - start));
+			textArea.Selection = SimpleSelection.Create(textArea, start, start + length);
+			textArea.Caret.Offset = start + length;
+		}
+		
+		/// <summary>
+		/// Gets the number of lines in the document.
+		/// </summary>
+		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+		public int LineCount {
+			get {
+				TextDocument document = this.Document;
+				if (document != null)
+					return document.LineCount;
+				else
+					return 1;
+			}
+		}
+		
+		/// <summary>
+		/// Clears the text.
+		/// </summary>
+		public void Clear()
+		{
+			this.Text = string.Empty;
+		}
+		#endregion
+		
+		#region Loading from stream
+		/// <summary>
+		/// Loads the text from the stream, auto-detecting the encoding.
+		/// </summary>
+		/// <remarks>
+		/// This method sets <see cref="IsModified"/> to false.
+		/// </remarks>
+		public void Load(Stream stream)
+		{
+			using (StreamReader reader = FileReader.OpenStream(stream, this.Encoding ?? Encoding.UTF8)) {
+				this.Text = reader.ReadToEnd();
+				SetCurrentValue(EncodingProperty, reader.CurrentEncoding); // assign encoding after ReadToEnd() so that the StreamReader can autodetect the encoding
+			}
+			SetCurrentValue(IsModifiedProperty, Boxes.False);
+		}
+		
+		/// <summary>
+		/// Loads the text from the stream, auto-detecting the encoding.
+		/// </summary>
+		public void Load(string fileName)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException("fileName");
+			using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
+				Load(fs);
+			}
+		}
+		
+		/// <summary>
+		/// Encoding dependency property.
+		/// </summary>
+		public static readonly DependencyProperty EncodingProperty =
+			DependencyProperty.Register("Encoding", typeof(Encoding), typeof(TextEditor));
+		
+		/// <summary>
+		/// Gets/sets the encoding used when the file is saved.
+		/// </summary>
+		/// <remarks>
+		/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
+		/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
+		/// </remarks>
+		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
+		public Encoding Encoding {
+			get { return (Encoding)GetValue(EncodingProperty); }
+			set { SetValue(EncodingProperty, value); }
+		}
+		
+		/// <summary>
+		/// Saves the text to the stream.
+		/// </summary>
+		/// <remarks>
+		/// This method sets <see cref="IsModified"/> to false.
+		/// </remarks>
+		public void Save(Stream stream)
+		{
+			if (stream == null)
+				throw new ArgumentNullException("stream");
+			var encoding = this.Encoding;
+			var document = this.Document;
+			StreamWriter writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
+			if (document != null)
+				document.WriteTextTo(writer);
+			writer.Flush();
+			// do not close the stream
+			SetCurrentValue(IsModifiedProperty, Boxes.False);
+		}
+		
+		/// <summary>
+		/// Saves the text to the file.
+		/// </summary>
+		public void Save(string fileName)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException("fileName");
+			using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
+				Save(fs);
+			}
+		}
+		#endregion
+		
+		#region MouseHover events
+		/// <summary>
+		/// The PreviewMouseHover event.
+		/// </summary>
+		public static readonly RoutedEvent PreviewMouseHoverEvent =
+			TextView.PreviewMouseHoverEvent.AddOwner(typeof(TextEditor));
+		
+		/// <summary>
+		/// The MouseHover event.
+		/// </summary>
+		public static readonly RoutedEvent MouseHoverEvent =
+			TextView.MouseHoverEvent.AddOwner(typeof(TextEditor));
+		
+		
+		/// <summary>
+		/// The PreviewMouseHoverStopped event.
+		/// </summary>
+		public static readonly RoutedEvent PreviewMouseHoverStoppedEvent =
+			TextView.PreviewMouseHoverStoppedEvent.AddOwner(typeof(TextEditor));
+		
+		/// <summary>
+		/// The MouseHoverStopped event.
+		/// </summary>
+		public static readonly RoutedEvent MouseHoverStoppedEvent =
+			TextView.MouseHoverStoppedEvent.AddOwner(typeof(TextEditor));
+		
+		
+		/// <summary>
+		/// Occurs when the mouse has hovered over a fixed location for some time.
+		/// </summary>
+		public event MouseEventHandler PreviewMouseHover {
+			add { AddHandler(PreviewMouseHoverEvent, value); }
+			remove { RemoveHandler(PreviewMouseHoverEvent, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse has hovered over a fixed location for some time.
+		/// </summary>
+		public event MouseEventHandler MouseHover {
+			add { AddHandler(MouseHoverEvent, value); }
+			remove { RemoveHandler(MouseHoverEvent, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse had previously hovered but now started moving again.
+		/// </summary>
+		public event MouseEventHandler PreviewMouseHoverStopped {
+			add { AddHandler(PreviewMouseHoverStoppedEvent, value); }
+			remove { RemoveHandler(PreviewMouseHoverStoppedEvent, value); }
+		}
+		
+		/// <summary>
+		/// Occurs when the mouse had previously hovered but now started moving again.
+		/// </summary>
+		public event MouseEventHandler MouseHoverStopped {
+			add { AddHandler(MouseHoverStoppedEvent, value); }
+			remove { RemoveHandler(MouseHoverStoppedEvent, value); }
+		}
+		#endregion
+		
+		#region ScrollBarVisibility
+		/// <summary>
+		/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
+		/// </summary>
+		public static readonly DependencyProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(ScrollBarVisibility.Visible));
+		
+		/// <summary>
+		/// Gets/Sets the horizontal scroll bar visibility.
+		/// </summary>
+		public ScrollBarVisibility HorizontalScrollBarVisibility {
+			get { return (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); }
+			set { SetValue(HorizontalScrollBarVisibilityProperty, value); }
+		}
+		
+		/// <summary>
+		/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
+		/// </summary>
+		public static readonly DependencyProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner(typeof(TextEditor), new FrameworkPropertyMetadata(ScrollBarVisibility.Visible));
+		
+		/// <summary>
+		/// Gets/Sets the vertical scroll bar visibility.
+		/// </summary>
+		public ScrollBarVisibility VerticalScrollBarVisibility {
+			get { return (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); }
+			set { SetValue(VerticalScrollBarVisibilityProperty, value); }
+		}
+		#endregion
+		
+		object IServiceProvider.GetService(Type serviceType)
+		{
+			return textArea.GetService(serviceType);
+		}
+		
+		/// <summary>
+		/// Gets the text view position from a point inside the editor.
+		/// </summary>
+		/// <param name="point">The position, relative to top left
+		/// corner of TextEditor control</param>
+		/// <returns>The text view position, or null if the point is outside the document.</returns>
+		public TextViewPosition? GetPositionFromPoint(Point point)
+		{
+			if (this.Document == null)
+				return null;
+			TextView textView = this.TextArea.TextView;
+			return textView.GetPosition(TranslatePoint(point, textView) + textView.ScrollOffset);
+		}
+		
+		/// <summary>
+		/// Scrolls to the specified line.
+		/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
+		/// </summary>
+		public void ScrollToLine(int line)
+		{
+			ScrollTo(line, -1);
+		}
+		
+		/// <summary>
+		/// Scrolls to the specified line/column.
+		/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
+		/// </summary>
+		public void ScrollTo(int line, int column)
+		{
+			const double MinimumScrollPercentage = 0.3;
+			
+			TextView textView = textArea.TextView;
+			TextDocument document = textView.Document;
+			if (scrollViewer != null && document != null) {
+				if (line < 1)
+					line = 1;
+				if (line > document.LineCount)
+					line = document.LineCount;
+				
+				IScrollInfo scrollInfo = textView;
+				if (!scrollInfo.CanHorizontallyScroll) {
+					// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
+					// to the correct position.
+					// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
+					VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
+					double remainingHeight = scrollViewer.ViewportHeight / 2;
+					while (remainingHeight > 0) {
+						DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
+						if (prevLine == null)
+							break;
+						vl = textView.GetOrConstructVisualLine(prevLine);
+						remainingHeight -= vl.Height;
+					}
+				}
+				
+				Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), VisualYPosition.LineMiddle);
+				double verticalPos = p.Y - scrollViewer.ViewportHeight / 2;
+				if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > MinimumScrollPercentage * scrollViewer.ViewportHeight) {
+					scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos));
+				}
+				if (column > 0) {
+					if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) {
+						double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2);
+						if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > MinimumScrollPercentage * scrollViewer.ViewportWidth) {
+							scrollViewer.ScrollToHorizontalOffset(horizontalPos);
+						}
+					} else {
+						scrollViewer.ScrollToHorizontalOffset(0);
+					}
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditor.xaml
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditor.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditor.xaml	(revision 11807)
@@ -0,0 +1,78 @@
+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+	xmlns:AvalonEdit="clr-namespace:ICSharpCode.AvalonEdit"
+	xmlns:editing="clr-namespace:ICSharpCode.AvalonEdit.Editing"
+>
+	<Style TargetType="{x:Type AvalonEdit:TextEditor}">
+		<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" />
+		<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}" />
+		<Setter Property="FlowDirection" Value="LeftToRight"/> <!-- AvalonEdit does not support RTL, so ensure we use LTR by default -->
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type AvalonEdit:TextEditor}">
+					<ScrollViewer
+						Focusable="False"
+						Name="PART_ScrollViewer"
+						CanContentScroll="True"
+						VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}"
+						HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}"
+						Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TextArea}"
+						VerticalContentAlignment="Top"
+						HorizontalContentAlignment="Left"
+						Background="{TemplateBinding Background}"
+						Padding="{TemplateBinding Padding}"
+						BorderBrush="{TemplateBinding BorderBrush}"
+						BorderThickness="{TemplateBinding BorderThickness}"
+					/>
+					<ControlTemplate.Triggers>
+						<Trigger Property="WordWrap"
+						         Value="True">
+							<Setter TargetName="PART_ScrollViewer"
+							        Property="HorizontalScrollBarVisibility"
+							        Value="Disabled" />
+						</Trigger>
+					</ControlTemplate.Triggers>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+	
+	<Style TargetType="{x:Type editing:TextArea}" x:Shared="False">
+		<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
+		<Setter Property="SelectionBrush">
+			<Setter.Value>
+				<SolidColorBrush
+					Color="{DynamicResource {x:Static SystemColors.HighlightColorKey}}"
+					Opacity="0.7"/>
+			</Setter.Value>
+		</Setter>
+		<Setter Property="SelectionBorder">
+			<Setter.Value>
+				<Pen Brush="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
+				     Thickness="1"/>
+			</Setter.Value>
+		</Setter>
+		<Setter Property="SelectionForeground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
+		<Setter Property="Template">
+			<Setter.Value>
+				<ControlTemplate TargetType="{x:Type editing:TextArea}">
+					<DockPanel Focusable="False">
+						<ItemsControl DockPanel.Dock="Left"
+						              Focusable="False"
+						              ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=LeftMargins}">
+							<ItemsControl.ItemsPanel>
+								<ItemsPanelTemplate>
+									<StackPanel Orientation="Horizontal" />
+								</ItemsPanelTemplate>
+							</ItemsControl.ItemsPanel>
+						</ItemsControl>
+						<ContentPresenter
+							Panel.ZIndex="-1"
+							Focusable="False"
+							Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TextView}"/>
+					</DockPanel>
+				</ControlTemplate>
+			</Setter.Value>
+		</Setter>
+	</Style>
+</ResourceDictionary>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorAutomationPeer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorAutomationPeer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorAutomationPeer.cs	(revision 11807)
@@ -0,0 +1,80 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows.Automation;
+using System.Windows.Automation.Peers;
+using System.Windows.Automation.Provider;
+using System.Windows.Controls;
+
+using ICSharpCode.AvalonEdit.Utils;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// Exposes <see cref="TextEditor"/> to automation.
+	/// </summary>
+	public class TextEditorAutomationPeer : FrameworkElementAutomationPeer, IValueProvider
+	{
+		/// <summary>
+		/// Creates a new TextEditorAutomationPeer instance.
+		/// </summary>
+		public TextEditorAutomationPeer(TextEditor owner) : base(owner)
+		{
+			Debug.WriteLine("TextEditorAutomationPeer was created");
+		}
+		
+		private TextEditor TextEditor {
+			get { return (TextEditor)base.Owner; }
+		}
+		
+		void IValueProvider.SetValue(string value)
+		{
+			this.TextEditor.Text = value;
+		}
+		
+		string IValueProvider.Value {
+			get { return this.TextEditor.Text; }
+		}
+		
+		bool IValueProvider.IsReadOnly {
+			get { return this.TextEditor.IsReadOnly; }
+		}
+		
+		/// <inheritdoc/>
+		public override object GetPattern(PatternInterface patternInterface)
+		{
+			if (patternInterface == PatternInterface.Value)
+				return this;
+			
+			if (patternInterface == PatternInterface.Scroll) {
+				ScrollViewer scrollViewer = this.TextEditor.ScrollViewer;
+				if (scrollViewer != null)
+					return UIElementAutomationPeer.CreatePeerForElement(scrollViewer);
+			}
+			
+			return base.GetPattern(patternInterface);
+		}
+		
+		internal void RaiseIsReadOnlyChanged(bool oldValue, bool newValue)
+		{
+			RaisePropertyChangedEvent(ValuePatternIdentifiers.IsReadOnlyProperty, Boxes.Box(oldValue), Boxes.Box(newValue));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorComponent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorComponent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorComponent.cs	(revision 11807)
@@ -0,0 +1,55 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Editing;
+using ICSharpCode.AvalonEdit.Rendering;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// Represents a text editor control (<see cref="TextEditor"/>, <see cref="TextArea"/>
+	/// or <see cref="TextView"/>).
+	/// </summary>
+	public interface ITextEditorComponent : IServiceProvider
+	{
+		/// <summary>
+		/// Gets the document being edited.
+		/// </summary>
+		TextDocument Document { get; }
+		
+		/// <summary>
+		/// Occurs when the Document property changes (when the text editor is connected to another
+		/// document - not when the document content changes).
+		/// </summary>
+		event EventHandler DocumentChanged;
+		
+		/// <summary>
+		/// Gets the options of the text editor.
+		/// </summary>
+		TextEditorOptions Options { get; }
+		
+		/// <summary>
+		/// Occurs when the Options property changes, or when an option inside the current option list
+		/// changes.
+		/// </summary>
+		event PropertyChangedEventHandler OptionChanged;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorOptions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorOptions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorOptions.cs	(revision 11807)
@@ -0,0 +1,497 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Reflection;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// A container for the text editor options.
+	/// </summary>
+	[Serializable]
+	public class TextEditorOptions : INotifyPropertyChanged
+	{
+		#region ctor
+		/// <summary>
+		/// Initializes an empty instance of TextEditorOptions.
+		/// </summary>
+		public TextEditorOptions()
+		{
+		}
+		
+		/// <summary>
+		/// Initializes a new instance of TextEditorOptions by copying all values
+		/// from <paramref name="options"/> to the new instance.
+		/// </summary>
+		public TextEditorOptions(TextEditorOptions options)
+		{
+			// get all the fields in the class
+			FieldInfo[] fields = typeof(TextEditorOptions).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
+			
+			// copy each value over to 'this'
+			foreach(FieldInfo fi in fields) {
+				if (!fi.IsNotSerialized)
+					fi.SetValue(this, fi.GetValue(options));
+			}
+		}
+		#endregion
+		
+		#region PropertyChanged handling
+		/// <inheritdoc/>
+		[field: NonSerialized]
+		public event PropertyChangedEventHandler PropertyChanged;
+		
+		/// <summary>
+		/// Raises the PropertyChanged event.
+		/// </summary>
+		/// <param name="propertyName">The name of the changed property.</param>
+		protected void OnPropertyChanged(string propertyName)
+		{
+			OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
+		}
+		
+		/// <summary>
+		/// Raises the PropertyChanged event.
+		/// </summary>
+		protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
+		{
+			if (PropertyChanged != null) {
+				PropertyChanged(this, e);
+			}
+		}
+		#endregion
+		
+		#region ShowSpaces / ShowTabs / ShowEndOfLine / ShowBoxForControlCharacters
+		bool showSpaces;
+		
+		/// <summary>
+		/// Gets/Sets whether to show · for spaces.
+		/// </summary>
+		/// <remarks>The default value is <c>false</c>.</remarks>
+		[DefaultValue(false)]
+		public virtual bool ShowSpaces {
+			get { return showSpaces; }
+			set {
+				if (showSpaces != value) {
+					showSpaces = value;
+					OnPropertyChanged("ShowSpaces");
+				}
+			}
+		}
+		
+		bool showTabs;
+		
+		/// <summary>
+		/// Gets/Sets whether to show » for tabs.
+		/// </summary>
+		/// <remarks>The default value is <c>false</c>.</remarks>
+		[DefaultValue(false)]
+		public virtual bool ShowTabs {
+			get { return showTabs; }
+			set {
+				if (showTabs != value) {
+					showTabs = value;
+					OnPropertyChanged("ShowTabs");
+				}
+			}
+		}
+		
+		bool showEndOfLine;
+		
+		/// <summary>
+		/// Gets/Sets whether to show ¶ at the end of lines.
+		/// </summary>
+		/// <remarks>The default value is <c>false</c>.</remarks>
+		[DefaultValue(false)]
+		public virtual bool ShowEndOfLine {
+			get { return showEndOfLine; }
+			set {
+				if (showEndOfLine != value) {
+					showEndOfLine = value;
+					OnPropertyChanged("ShowEndOfLine");
+				}
+			}
+		}
+		
+		bool showBoxForControlCharacters = true;
+		
+		/// <summary>
+		/// Gets/Sets whether to show a box with the hex code for control characters.
+		/// </summary>
+		/// <remarks>The default value is <c>true</c>.</remarks>
+		[DefaultValue(true)]
+		public virtual bool ShowBoxForControlCharacters {
+			get { return showBoxForControlCharacters; }
+			set {
+				if (showBoxForControlCharacters != value) {
+					showBoxForControlCharacters = value;
+					OnPropertyChanged("ShowBoxForControlCharacters");
+				}
+			}
+		}
+		#endregion
+		
+		#region EnableHyperlinks
+		bool enableHyperlinks = true;
+		
+		/// <summary>
+		/// Gets/Sets whether to enable clickable hyperlinks in the editor.
+		/// </summary>
+		/// <remarks>The default value is <c>true</c>.</remarks>
+		[DefaultValue(true)]
+		public virtual bool EnableHyperlinks {
+			get { return enableHyperlinks; }
+			set {
+				if (enableHyperlinks != value) {
+					enableHyperlinks = value;
+					OnPropertyChanged("EnableHyperlinks");
+				}
+			}
+		}
+		
+		bool enableEmailHyperlinks = true;
+		
+		/// <summary>
+		/// Gets/Sets whether to enable clickable hyperlinks for e-mail addresses in the editor.
+		/// </summary>
+		/// <remarks>The default value is <c>true</c>.</remarks>
+		[DefaultValue(true)]
+		public virtual bool EnableEmailHyperlinks {
+			get { return enableEmailHyperlinks; }
+			set {
+				if (enableEmailHyperlinks != value) {
+					enableEmailHyperlinks = value;
+					OnPropertyChanged("EnableEMailHyperlinks");
+				}
+			}
+		}
+		
+		bool requireControlModifierForHyperlinkClick = true;
+		
+		/// <summary>
+		/// Gets/Sets whether the user needs to press Control to click hyperlinks.
+		/// The default value is true.
+		/// </summary>
+		/// <remarks>The default value is <c>true</c>.</remarks>
+		[DefaultValue(true)]
+		public virtual bool RequireControlModifierForHyperlinkClick {
+			get { return requireControlModifierForHyperlinkClick; }
+			set {
+				if (requireControlModifierForHyperlinkClick != value) {
+					requireControlModifierForHyperlinkClick = value;
+					OnPropertyChanged("RequireControlModifierForHyperlinkClick");
+				}
+			}
+		}
+		#endregion
+		
+		#region TabSize / IndentationSize / ConvertTabsToSpaces / GetIndentationString
+		// I'm using '_' prefixes for the fields here to avoid confusion with the local variables
+		// in the methods below.
+		// The fields should be accessed only by their property - the fields might not be used
+		// if someone overrides the property.
+		
+		int indentationSize = 4;
+		
+		/// <summary>
+		/// Gets/Sets the width of one indentation unit.
+		/// </summary>
+		/// <remarks>The default value is 4.</remarks>
+		[DefaultValue(4)]
+		public virtual int IndentationSize {
+			get { return indentationSize; }
+			set {
+				if (value < 1)
+					throw new ArgumentOutOfRangeException("value", value, "value must be positive");
+				// sanity check; a too large value might cause WPF to crash internally much later
+				// (it only crashed in the hundred thousands for me; but might crash earlier with larger fonts)
+				if (value > 1000)
+					throw new ArgumentOutOfRangeException("value", value, "indentation size is too large");
+				if (indentationSize != value) {
+					indentationSize = value;
+					OnPropertyChanged("IndentationSize");
+					OnPropertyChanged("IndentationString");
+				}
+			}
+		}
+		
+		bool convertTabsToSpaces;
+		
+		/// <summary>
+		/// Gets/Sets whether to use spaces for indentation instead of tabs.
+		/// </summary>
+		/// <remarks>The default value is <c>false</c>.</remarks>
+		[DefaultValue(false)]
+		public virtual bool ConvertTabsToSpaces {
+			get { return convertTabsToSpaces; }
+			set {
+				if (convertTabsToSpaces != value) {
+					convertTabsToSpaces = value;
+					OnPropertyChanged("ConvertTabsToSpaces");
+					OnPropertyChanged("IndentationString");
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the text used for indentation.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
+		[Browsable(false)]
+		public string IndentationString {
+			get { return GetIndentationString(1); }
+		}
+		
+		/// <summary>
+		/// Gets text required to indent from the specified <paramref name="column"/> to the next indentation level.
+		/// </summary>
+		public virtual string GetIndentationString(int column)
+		{
+			if (column < 1)
+				throw new ArgumentOutOfRangeException("column", column, "Value must be at least 1.");
+			int indentationSize = this.IndentationSize;
+			if (ConvertTabsToSpaces) {
+				return new string(' ', indentationSize - ((column - 1) % indentationSize));
+			} else {
+				return "\t";
+			}
+		}
+		#endregion
+		
+		bool cutCopyWholeLine = true;
+		
+		/// <summary>
+		/// Gets/Sets whether copying without a selection copies the whole current line.
+		/// </summary>
+		[DefaultValue(true)]
+		public virtual bool CutCopyWholeLine {
+			get { return cutCopyWholeLine; }
+			set {
+				if (cutCopyWholeLine != value) {
+					cutCopyWholeLine = value;
+					OnPropertyChanged("CutCopyWholeLine");
+				}
+			}
+		}
+		
+		bool allowScrollBelowDocument;
+		
+		/// <summary>
+		/// Gets/Sets whether the user can scroll below the bottom of the document.
+		/// The default value is false; but it a good idea to set this property to true when using folding.
+		/// </summary>
+		[DefaultValue(false)]
+		public virtual bool AllowScrollBelowDocument {
+			get { return allowScrollBelowDocument; }
+			set {
+				if (allowScrollBelowDocument != value) {
+					allowScrollBelowDocument = value;
+					OnPropertyChanged("AllowScrollBelowDocument");
+				}
+			}
+		}
+		
+		double wordWrapIndentation = 0;
+		
+		/// <summary>
+		/// Gets/Sets the indentation used for all lines except the first when word-wrapping.
+		/// The default value is 0.
+		/// </summary>
+		[DefaultValue(0.0)]
+		public virtual double WordWrapIndentation {
+			get { return wordWrapIndentation; }
+			set {
+				if (double.IsNaN(value) || double.IsInfinity(value))
+					throw new ArgumentOutOfRangeException("value", value, "value must not be NaN/infinity");
+				if (value != wordWrapIndentation) {
+					wordWrapIndentation = value;
+					OnPropertyChanged("WordWrapIndentation");
+				}
+			}
+		}
+		
+		bool inheritWordWrapIndentation = true;
+		
+		/// <summary>
+		/// Gets/Sets whether the indentation is inherited from the first line when word-wrapping.
+		/// The default value is true.
+		/// </summary>
+		/// <remarks>When combined with <see cref="WordWrapIndentation"/>, the inherited indentation is added to the word wrap indentation.</remarks>
+		[DefaultValue(true)]
+		public virtual bool InheritWordWrapIndentation {
+			get { return inheritWordWrapIndentation; }
+			set {
+				if (value != inheritWordWrapIndentation) {
+					inheritWordWrapIndentation = value;
+					OnPropertyChanged("InheritWordWrapIndentation");
+				}
+			}
+		}
+		
+		bool enableRectangularSelection = true;
+		
+		/// <summary>
+		/// Enables rectangular selection (press ALT and select a rectangle)
+		/// </summary>
+		[DefaultValue(true)]
+		public bool EnableRectangularSelection {
+			get { return enableRectangularSelection; }
+			set {
+				if (enableRectangularSelection != value) {
+					enableRectangularSelection = value;
+					OnPropertyChanged("EnableRectangularSelection");
+				}
+			}
+		}
+		
+		bool enableTextDragDrop = true;
+		
+		/// <summary>
+		/// Enable dragging text within the text area.
+		/// </summary>
+		[DefaultValue(true)]
+		public bool EnableTextDragDrop {
+			get { return enableTextDragDrop; }
+			set {
+				if (enableTextDragDrop != value) {
+					enableTextDragDrop = value;
+					OnPropertyChanged("EnableTextDragDrop");
+				}
+			}
+		}
+		
+		bool enableVirtualSpace;
+		
+		/// <summary>
+		/// Gets/Sets whether the user can set the caret behind the line ending
+		/// (into "virtual space").
+		/// Note that virtual space is always used (independent from this setting)
+		/// when doing rectangle selections.
+		/// </summary>
+		[DefaultValue(false)]
+		public virtual bool EnableVirtualSpace {
+			get { return enableVirtualSpace; }
+			set {
+				if (enableVirtualSpace != value) {
+					enableVirtualSpace = value;
+					OnPropertyChanged("EnableVirtualSpace");
+				}
+			}
+		}
+		
+		bool enableImeSupport = true;
+		
+		/// <summary>
+		/// Gets/Sets whether the support for Input Method Editors (IME)
+		/// for non-alphanumeric scripts (Chinese, Japanese, Korean, ...) is enabled.
+		/// </summary>
+		[DefaultValue(true)]
+		public virtual bool EnableImeSupport {
+			get { return enableImeSupport; }
+			set {
+				if (enableImeSupport != value) {
+					enableImeSupport = value;
+					OnPropertyChanged("EnableImeSupport");
+				}
+			}
+		}
+		
+		bool showColumnRuler = false;
+		
+		/// <summary>
+		/// Gets/Sets whether the column ruler should be shown.
+		/// </summary>
+		[DefaultValue(false)]
+		public virtual bool ShowColumnRuler {
+			get { return showColumnRuler; }
+			set {
+				if (showColumnRuler != value) {
+					showColumnRuler = value;
+					OnPropertyChanged("ShowColumnRuler");
+				}
+			}
+		}
+		
+		int columnRulerPosition = 80;
+		
+		/// <summary>
+		/// Gets/Sets where the column ruler should be shown.
+		/// </summary>
+		[DefaultValue(80)]
+		public virtual int ColumnRulerPosition {
+			get { return columnRulerPosition; }
+			set {
+				if (columnRulerPosition != value) {
+					columnRulerPosition = value;
+					OnPropertyChanged("ColumnRulerPosition");
+				}
+			}
+		}
+		
+		bool highlightCurrentLine = false;
+		
+		/// <summary>
+		/// Gets/Sets if current line should be shown.
+		/// </summary>
+		[DefaultValue(false)]
+		public virtual bool HighlightCurrentLine {
+			get { return highlightCurrentLine; }
+			set {
+				if (highlightCurrentLine != value) {
+					highlightCurrentLine = value;
+					OnPropertyChanged("HighlightCurrentLine");
+				}
+			}
+		}
+		
+		bool hideCursorWhileTyping = true;
+		
+		/// <summary>
+		/// Gets/Sets if mouse cursor should be hidden while user is typing.
+		/// </summary>
+		[DefaultValue(true)]
+		public bool HideCursorWhileTyping {
+			get { return hideCursorWhileTyping; }
+			set {
+				if (hideCursorWhileTyping != value) {
+					hideCursorWhileTyping = value;
+					OnPropertyChanged("HideCursorWhileTyping");
+				}
+			}
+		}
+		
+		bool allowToggleOverstrikeMode = false;
+		
+		/// <summary>
+		/// Gets/Sets if the user is allowed to enable/disable overstrike mode.
+		/// </summary>
+		[DefaultValue(false)]
+		public bool AllowToggleOverstrikeMode {
+			get { return allowToggleOverstrikeMode; }
+			set {
+				if (allowToggleOverstrikeMode != value) {
+					allowToggleOverstrikeMode = value;
+					OnPropertyChanged("AllowToggleOverstrikeMode");
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorWeakEventManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorWeakEventManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextEditorWeakEventManager.cs	(revision 11807)
@@ -0,0 +1,67 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using ICSharpCode.AvalonEdit.Utils;
+using System;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// Contains weak event managers for <see cref="ITextEditorComponent"/>.
+	/// </summary>
+	public static class TextEditorWeakEventManager
+	{
+		/// <summary>
+		/// Weak event manager for the <see cref="ITextEditorComponent.DocumentChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class DocumentChanged : WeakEventManagerBase<DocumentChanged, ITextEditorComponent>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(ITextEditorComponent source)
+			{
+				source.DocumentChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(ITextEditorComponent source)
+			{
+				source.DocumentChanged -= DeliverEvent;
+			}
+		}
+		
+		/// <summary>
+		/// Weak event manager for the <see cref="ITextEditorComponent.OptionChanged"/> event.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
+		public sealed class OptionChanged : WeakEventManagerBase<OptionChanged, ITextEditorComponent>
+		{
+			/// <inheritdoc/>
+			protected override void StartListening(ITextEditorComponent source)
+			{
+				source.OptionChanged += DeliverEvent;
+			}
+			
+			/// <inheritdoc/>
+			protected override void StopListening(ITextEditorComponent source)
+			{
+				source.OptionChanged -= DeliverEvent;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextViewPosition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextViewPosition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/TextViewPosition.cs	(revision 11807)
@@ -0,0 +1,199 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using ICSharpCode.NRefactory;
+using ICSharpCode.AvalonEdit.Document;
+
+namespace ICSharpCode.AvalonEdit
+{
+	/// <summary>
+	/// Represents a text location with a visual column.
+	/// </summary>
+	public struct TextViewPosition : IEquatable<TextViewPosition>, IComparable<TextViewPosition>
+	{
+		int line, column, visualColumn;
+		bool isAtEndOfLine;
+		
+		/// <summary>
+		/// Gets/Sets Location.
+		/// </summary>
+		public TextLocation Location {
+			get {
+				return new TextLocation(line, column);
+			}
+			set {
+				line = value.Line;
+				column = value.Column;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the line number.
+		/// </summary>
+		public int Line {
+			get { return line; }
+			set { line = value; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the (text) column number.
+		/// </summary>
+		public int Column {
+			get { return column; }
+			set { column = value; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the visual column number.
+		/// Can be -1 (meaning unknown visual column).
+		/// </summary>
+		public int VisualColumn {
+			get { return visualColumn; }
+			set { visualColumn = value; }
+		}
+		
+		/// <summary>
+		/// When word-wrap is enabled and a line is wrapped at a position where there is no space character;
+		/// then both the end of the first TextLine and the beginning of the second TextLine
+		/// refer to the same position in the document, and also have the same visual column.
+		/// In this case, the IsAtEndOfLine property is used to distinguish between the two cases:
+		/// the value <c>true</c> indicates that the position refers to the end of the previous TextLine;
+		/// the value <c>false</c> indicates that the position refers to the beginning of the next TextLine.
+		/// 
+		/// If this position is not at such a wrapping position, the value of this property has no effect.
+		/// </summary>
+		public bool IsAtEndOfLine {
+			get { return isAtEndOfLine; }
+			set { isAtEndOfLine = value; }
+		}
+		
+		/// <summary>
+		/// Creates a new TextViewPosition instance.
+		/// </summary>
+		public TextViewPosition(int line, int column, int visualColumn)
+		{
+			this.line = line;
+			this.column = column;
+			this.visualColumn = visualColumn;
+			this.isAtEndOfLine = false;
+		}
+		
+		/// <summary>
+		/// Creates a new TextViewPosition instance.
+		/// </summary>
+		public TextViewPosition(int line, int column)
+			: this(line, column, -1)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new TextViewPosition instance.
+		/// </summary>
+		public TextViewPosition(TextLocation location, int visualColumn)
+		{
+			this.line = location.Line;
+			this.column = location.Column;
+			this.visualColumn = visualColumn;
+			this.isAtEndOfLine = false;
+		}
+		
+		/// <summary>
+		/// Creates a new TextViewPosition instance.
+		/// </summary>
+		public TextViewPosition(TextLocation location)
+			: this(location, -1)
+		{
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture,
+			                     "[TextViewPosition Line={0} Column={1} VisualColumn={2} IsAtEndOfLine={3}]",
+			                     this.line, this.column, this.visualColumn, this.isAtEndOfLine);
+		}
+		
+		#region Equals and GetHashCode implementation
+		// The code in this region is useful if you want to use this structure in collections.
+		// If you don't need it, you can just remove the region and the ": IEquatable<Struct1>" declaration.
+		
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			if (obj is TextViewPosition)
+				return Equals((TextViewPosition)obj); // use Equals method below
+			else
+				return false;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			int hashCode = isAtEndOfLine ? 115817 : 0;
+			unchecked {
+				hashCode += 1000000007 * Line.GetHashCode();
+				hashCode += 1000000009 * Column.GetHashCode();
+				hashCode += 1000000021 * VisualColumn.GetHashCode();
+			}
+			return hashCode;
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public bool Equals(TextViewPosition other)
+		{
+			return this.Line == other.Line && this.Column == other.Column && this.VisualColumn == other.VisualColumn && this.IsAtEndOfLine == other.IsAtEndOfLine;
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public static bool operator ==(TextViewPosition left, TextViewPosition right)
+		{
+			return left.Equals(right);
+		}
+		
+		/// <summary>
+		/// Inequality test.
+		/// </summary>
+		public static bool operator !=(TextViewPosition left, TextViewPosition right)
+		{
+			return !(left.Equals(right)); // use operator == and negate result
+		}
+		#endregion
+		
+		/// <inheritdoc/>
+		public int CompareTo(TextViewPosition other)
+		{
+			int r = this.Location.CompareTo(other.Location);
+			if (r != 0)
+				return r;
+			r = this.visualColumn.CompareTo(other.visualColumn);
+			if (r != 0)
+				return r;
+			if (isAtEndOfLine && !other.isAtEndOfLine)
+				return -1;
+			else if (!isAtEndOfLine && other.isAtEndOfLine)
+				return 1;
+			return 0;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Boxes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Boxes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Boxes.cs	(revision 11807)
@@ -0,0 +1,36 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Reuse the same instances for boxed booleans.
+	/// </summary>
+	static class Boxes
+	{
+		public static readonly object True = true;
+		public static readonly object False = false;
+		
+		public static object Box(bool value)
+		{
+			return value ? True : False;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CallbackOnDispose.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CallbackOnDispose.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CallbackOnDispose.cs	(revision 11807)
@@ -0,0 +1,101 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Invokes an action when it is disposed.
+	/// </summary>
+	/// <remarks>
+	/// This class ensures the callback is invoked at most once,
+	/// even when Dispose is called on multiple threads.
+	/// </remarks>
+	sealed class CallbackOnDispose : IDisposable
+	{
+		Action action;
+		
+		public CallbackOnDispose(Action action)
+		{
+			if (action == null)
+				throw new ArgumentNullException("action");
+			this.action = action;
+		}
+		
+		public void Dispose()
+		{
+			Action a = Interlocked.Exchange(ref action, null);
+			if (a != null) {
+				a();
+			}
+		}
+	}
+	
+	/// <summary>
+	/// This class is used to prevent stack overflows by representing a 'busy' flag
+	/// that prevents reentrance when another call is running.
+	/// However, using a simple 'bool busy' is not thread-safe, so we use a
+	/// thread-static BusyManager.
+	/// </summary>
+	static class BusyManager
+	{
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible",
+			Justification = "Should always be used with 'var'")]
+		public struct BusyLock : IDisposable
+		{
+			public static readonly BusyLock Failed = new BusyLock(null);
+			
+			readonly List<object> objectList;
+			
+			internal BusyLock(List<object> objectList)
+			{
+				this.objectList = objectList;
+			}
+			
+			public bool Success {
+				get { return objectList != null; }
+			}
+			
+			public void Dispose()
+			{
+				if (objectList != null) {
+					objectList.RemoveAt(objectList.Count - 1);
+				}
+			}
+		}
+		
+		[ThreadStatic] static List<object> _activeObjects;
+		
+		public static BusyLock Enter(object obj)
+		{
+			List<object> activeObjects = _activeObjects;
+			if (activeObjects == null)
+				activeObjects = _activeObjects = new List<object>();
+			for (int i = 0; i < activeObjects.Count; i++) {
+				if (activeObjects[i] == obj)
+					return BusyLock.Failed;
+			}
+			activeObjects.Add(obj);
+			return new BusyLock(activeObjects);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CharRope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CharRope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CharRope.cs	(revision 11807)
@@ -0,0 +1,226 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Poor man's template specialization: extension methods for Rope&lt;char&gt;.
+	/// </summary>
+	public static class CharRope
+	{
+		/// <summary>
+		/// Creates a new rope from the specified text.
+		/// </summary>
+		public static Rope<char> Create(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			return new Rope<char>(InitFromString(text));
+		}
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the rope.
+		/// Runs in O(lg N + M), where M=<paramref name="length"/>.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public static string ToString(this Rope<char> rope, int startIndex, int length)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			#if DEBUG
+			if (length < 0)
+				throw new ArgumentOutOfRangeException("length", length, "Value must be >= 0");
+			#endif
+			if (length == 0)
+				return string.Empty;
+			char[] buffer = new char[length];
+			rope.CopyTo(startIndex, buffer, 0, length);
+			return new string(buffer);
+		}
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the rope and writes it to the specified text writer.
+		/// Runs in O(lg N + M), where M=<paramref name="length"/>.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public static void WriteTo(this Rope<char> rope, TextWriter output, int startIndex, int length)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			if (output == null)
+				throw new ArgumentNullException("output");
+			rope.VerifyRange(startIndex, length);
+			rope.root.WriteTo(startIndex, output, length);
+		}
+		
+		/// <summary>
+		/// Appends text to this rope.
+		/// Runs in O(lg N + M).
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		public static void AddText(this Rope<char> rope, string text)
+		{
+			InsertText(rope, rope.Length, text);
+		}
+		
+		/// <summary>
+		/// Inserts text into this rope.
+		/// Runs in O(lg N + M).
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
+		public static void InsertText(this Rope<char> rope, int index, string text)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			rope.InsertRange(index, text.ToCharArray(), 0, text.Length);
+			/*if (index < 0 || index > rope.Length) {
+				throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + rope.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (text.Length == 0)
+				return;
+			rope.root = rope.root.Insert(index, text);
+			rope.OnChanged();*/
+		}
+		
+		internal static RopeNode<char> InitFromString(string text)
+		{
+			if (text.Length == 0) {
+				return RopeNode<char>.emptyRopeNode;
+			}
+			RopeNode<char> node = RopeNode<char>.CreateNodes(text.Length);
+			FillNode(node, text, 0);
+			return node;
+		}
+		
+		static void FillNode(RopeNode<char> node, string text, int start)
+		{
+			if (node.contents != null) {
+				text.CopyTo(start, node.contents, 0, node.length);
+			} else {
+				FillNode(node.left, text, start);
+				FillNode(node.right, text, start + node.left.length);
+			}
+		}
+		
+		internal static void WriteTo(this RopeNode<char> node, int index, TextWriter output, int count)
+		{
+			if (node.height == 0) {
+				if (node.contents == null) {
+					// function node
+					node.GetContentNode().WriteTo(index, output, count);
+				} else {
+					// leaf node: append data
+					output.Write(node.contents, index, count);
+				}
+			} else {
+				// concat node: do recursive calls
+				if (index + count <= node.left.length) {
+					node.left.WriteTo(index, output, count);
+				} else if (index >= node.left.length) {
+					node.right.WriteTo(index - node.left.length, output, count);
+				} else {
+					int amountInLeft = node.left.length - index;
+					node.left.WriteTo(index, output, amountInLeft);
+					node.right.WriteTo(0, output, count - amountInLeft);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of any element in the specified array.
+		/// </summary>
+		/// <param name="rope">The target rope.</param>
+		/// <param name="anyOf">Array of characters being searched.</param>
+		/// <param name="startIndex">Start index of the search.</param>
+		/// <param name="length">Length of the area to search.</param>
+		/// <returns>The first index where any character was found; or -1 if no occurrence was found.</returns>
+		public static int IndexOfAny(this Rope<char> rope, char[] anyOf, int startIndex, int length)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			if (anyOf == null)
+				throw new ArgumentNullException("anyOf");
+			rope.VerifyRange(startIndex, length);
+			
+			while (length > 0) {
+				var entry = rope.FindNodeUsingCache(startIndex).PeekOrDefault();
+				char[] contents = entry.node.contents;
+				int startWithinNode = startIndex - entry.nodeStartIndex;
+				int nodeLength = Math.Min(entry.node.length, startWithinNode + length);
+				for (int i = startIndex - entry.nodeStartIndex; i < nodeLength; i++) {
+					char element = contents[i];
+					foreach (char needle in anyOf) {
+						if (element == needle)
+							return entry.nodeStartIndex + i;
+					}
+				}
+				length -= nodeLength - startWithinNode;
+				startIndex = entry.nodeStartIndex + nodeLength;
+			}
+			return -1;
+		}
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of the search text.
+		/// </summary>
+		public static int IndexOf(this Rope<char> rope, string searchText, int startIndex, int length, StringComparison comparisonType)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			if (searchText == null)
+				throw new ArgumentNullException("searchText");
+			rope.VerifyRange(startIndex, length);
+			int pos = rope.ToString(startIndex, length).IndexOf(searchText, comparisonType);
+			if (pos < 0)
+				return -1;
+			else
+				return pos + startIndex;
+		}
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the search text.
+		/// </summary>
+		public static int LastIndexOf(this Rope<char> rope, string searchText, int startIndex, int length, StringComparison comparisonType)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			if (searchText == null)
+				throw new ArgumentNullException("searchText");
+			rope.VerifyRange(startIndex, length);
+			int pos = rope.ToString(startIndex, length).LastIndexOf(searchText, comparisonType);
+			if (pos < 0)
+				return -1;
+			else
+				return pos + startIndex;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CompressingTreeList.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CompressingTreeList.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/CompressingTreeList.cs	(revision 11807)
@@ -0,0 +1,927 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// A IList{T} implementation that has efficient insertion and removal (in O(lg n) time)
+	/// and that saves memory by allocating only one node when a value is repeated in adjacent indices.
+	/// Based on this "compression", it also supports efficient InsertRange/SetRange/RemoveRange operations.
+	/// </summary>
+	/// <remarks>
+	/// Current memory usage: 5*IntPtr.Size + 12 + sizeof(T) per node.
+	/// Use this class only if lots of adjacent values are identical (can share one node).
+	/// </remarks>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
+	                                                 Justification = "It's an IList<T> implementation")]
+	public sealed class CompressingTreeList<T> : IList<T>
+	{
+		// Further memory optimization: this tree could work without parent pointers. But that
+		// requires changing most of tree manipulating logic.
+		// Also possible is to remove the count field and calculate it as totalCount-left.totalCount-right.totalCount
+		// - but that would make tree manipulations more difficult to handle.
+		
+		#region Node definition
+		sealed class Node
+		{
+			internal Node left, right, parent;
+			internal bool color;
+			internal int count, totalCount;
+			internal T value;
+			
+			public Node(T value, int count)
+			{
+				this.value = value;
+				this.count = count;
+				this.totalCount = count;
+			}
+			
+			internal Node LeftMost {
+				get {
+					Node node = this;
+					while (node.left != null)
+						node = node.left;
+					return node;
+				}
+			}
+			
+			internal Node RightMost {
+				get {
+					Node node = this;
+					while (node.right != null)
+						node = node.right;
+					return node;
+				}
+			}
+			
+			/// <summary>
+			/// Gets the inorder predecessor of the node.
+			/// </summary>
+			internal Node Predecessor {
+				get {
+					if (left != null) {
+						return left.RightMost;
+					} else {
+						Node node = this;
+						Node oldNode;
+						do {
+							oldNode = node;
+							node = node.parent;
+							// go up until we are coming out of a right subtree
+						} while (node != null && node.left == oldNode);
+						return node;
+					}
+				}
+			}
+			
+			/// <summary>
+			/// Gets the inorder successor of the node.
+			/// </summary>
+			internal Node Successor {
+				get {
+					if (right != null) {
+						return right.LeftMost;
+					} else {
+						Node node = this;
+						Node oldNode;
+						do {
+							oldNode = node;
+							node = node.parent;
+							// go up until we are coming out of a left subtree
+						} while (node != null && node.right == oldNode);
+						return node;
+					}
+				}
+			}
+			
+			public override string ToString()
+			{
+				return "[TotalCount=" + totalCount + " Count=" + count + " Value=" + value + "]";
+			}
+		}
+		#endregion
+		
+		#region Fields and Constructor
+		readonly Func<T, T, bool> comparisonFunc;
+		Node root;
+		
+		/// <summary>
+		/// Creates a new CompressingTreeList instance.
+		/// </summary>
+		/// <param name="equalityComparer">The equality comparer used for comparing consequtive values.
+		/// A single node may be used to store the multiple values that are considered equal.</param>
+		public CompressingTreeList(IEqualityComparer<T> equalityComparer)
+		{
+			if (equalityComparer == null)
+				throw new ArgumentNullException("equalityComparer");
+			this.comparisonFunc = equalityComparer.Equals;
+		}
+		
+		/// <summary>
+		/// Creates a new CompressingTreeList instance.
+		/// </summary>
+		/// <param name="comparisonFunc">A function that checks two values for equality. If this
+		/// function returns true, a single node may be used to store the two values.</param>
+		public CompressingTreeList(Func<T, T, bool> comparisonFunc)
+		{
+			if (comparisonFunc == null)
+				throw new ArgumentNullException("comparisonFunc");
+			this.comparisonFunc = comparisonFunc;
+		}
+		#endregion
+		
+		#region InsertRange
+		/// <summary>
+		/// Inserts <paramref name="item"/> <paramref name="count"/> times at position
+		/// <paramref name="index"/>.
+		/// </summary>
+		public void InsertRange(int index, int count, T item)
+		{
+			if (index < 0 || index > this.Count)
+				throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + this.Count);
+			if (count < 0)
+				throw new ArgumentOutOfRangeException("count", count, "Value must not be negative");
+			if (count == 0)
+				return;
+			unchecked {
+				if (this.Count + count < 0)
+					throw new OverflowException("Cannot insert elements: total number of elements must not exceed int.MaxValue.");
+			}
+			
+			if (root == null) {
+				root = new Node(item, count);
+			} else {
+				Node n = GetNode(ref index);
+				// check if we can put the value into the node n:
+				if (comparisonFunc(n.value, item)) {
+					n.count += count;
+					UpdateAugmentedData(n);
+				} else if (index == n.count) {
+					// this can only happen when appending at the end
+					Debug.Assert(n == root.RightMost);
+					InsertAsRight(n, new Node(item, count));
+				} else if (index == 0) {
+					// insert before:
+					// maybe we can put the value in the previous node?
+					Node p = n.Predecessor;
+					if (p != null && comparisonFunc(p.value, item)) {
+						p.count += count;
+						UpdateAugmentedData(p);
+					} else {
+						InsertBefore(n, new Node(item, count));
+					}
+				} else {
+					Debug.Assert(index > 0 && index < n.count);
+					// insert in the middle:
+					// split n into a new node and n
+					n.count -= index;
+					InsertBefore(n, new Node(n.value, index));
+					// then insert the new item in between
+					InsertBefore(n, new Node(item, count));
+					UpdateAugmentedData(n);
+				}
+			}
+			CheckProperties();
+		}
+		
+		void InsertBefore(Node node, Node newNode)
+		{
+			if (node.left == null) {
+				InsertAsLeft(node, newNode);
+			} else {
+				InsertAsRight(node.left.RightMost, newNode);
+			}
+		}
+		#endregion
+		
+		#region RemoveRange
+		/// <summary>
+		/// Removes <paramref name="count"/> items starting at position
+		/// <paramref name="index"/>.
+		/// </summary>
+		public void RemoveRange(int index, int count)
+		{
+			if (index < 0 || index > this.Count)
+				throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + this.Count);
+			if (count < 0 || index + count > this.Count)
+				throw new ArgumentOutOfRangeException("count", count, "0 <= length, index(" + index + ")+count <= " + this.Count);
+			if (count == 0)
+				return;
+			
+			Node n = GetNode(ref index);
+			if (index + count < n.count) {
+				// just remove inside a single node
+				n.count -= count;
+				UpdateAugmentedData(n);
+			} else {
+				// keep only the part of n from 0 to index
+				Node firstNodeBeforeDeletedRange;
+				if (index > 0) {
+					count -= (n.count - index);
+					n.count = index;
+					UpdateAugmentedData(n);
+					firstNodeBeforeDeletedRange = n;
+					n = n.Successor;
+				} else {
+					Debug.Assert(index == 0);
+					firstNodeBeforeDeletedRange = n.Predecessor;
+				}
+				while (n != null && count >= n.count) {
+					count -= n.count;
+					Node s = n.Successor;
+					RemoveNode(n);
+					n = s;
+				}
+				if (count > 0) {
+					Debug.Assert(n != null && count < n.count);
+					n.count -= count;
+					UpdateAugmentedData(n);
+				}
+				if (n != null) {
+					Debug.Assert(n.Predecessor == firstNodeBeforeDeletedRange);
+					if (firstNodeBeforeDeletedRange != null && comparisonFunc(firstNodeBeforeDeletedRange.value, n.value)) {
+						firstNodeBeforeDeletedRange.count += n.count;
+						RemoveNode(n);
+						UpdateAugmentedData(firstNodeBeforeDeletedRange);
+					}
+				}
+			}
+			
+			CheckProperties();
+		}
+		#endregion
+		
+		#region SetRange
+		/// <summary>
+		/// Sets <paramref name="count"/> indices starting at <paramref name="index"/> to
+		/// <paramref name="item"/>
+		/// </summary>
+		public void SetRange(int index, int count, T item)
+		{
+			RemoveRange(index, count);
+			InsertRange(index, count, item);
+		}
+		#endregion
+		
+		#region GetNode
+		Node GetNode(ref int index)
+		{
+			Node node = root;
+			while (true) {
+				if (node.left != null && index < node.left.totalCount) {
+					node = node.left;
+				} else {
+					if (node.left != null) {
+						index -= node.left.totalCount;
+					}
+					if (index < node.count || node.right == null)
+						return node;
+					index -= node.count;
+					node = node.right;
+				}
+			}
+		}
+		#endregion
+		
+		#region UpdateAugmentedData
+		void UpdateAugmentedData(Node node)
+		{
+			int totalCount = node.count;
+			if (node.left != null) totalCount += node.left.totalCount;
+			if (node.right != null) totalCount += node.right.totalCount;
+			if (node.totalCount != totalCount) {
+				node.totalCount = totalCount;
+				if (node.parent != null)
+					UpdateAugmentedData(node.parent);
+			}
+		}
+		#endregion
+		
+		#region IList<T> implementation
+		/// <summary>
+		/// Gets or sets an item by index.
+		/// </summary>
+		public T this[int index] {
+			get {
+				if (index < 0 || index >= this.Count)
+					throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + (this.Count - 1));
+				return GetNode(ref index).value;
+			}
+			set {
+				RemoveAt(index);
+				Insert(index, value);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the number of items in the list.
+		/// </summary>
+		public int Count {
+			get {
+				if (root != null)
+					return root.totalCount;
+				else
+					return 0;
+			}
+		}
+		
+		bool ICollection<T>.IsReadOnly {
+			get {
+				return false;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the index of the specified <paramref name="item"/>.
+		/// </summary>
+		public int IndexOf(T item)
+		{
+			int index = 0;
+			if (root != null) {
+				Node n = root.LeftMost;
+				while (n != null) {
+					if (comparisonFunc(n.value, item))
+						return index;
+					index += n.count;
+					n = n.Successor;
+				}
+			}
+			Debug.Assert(index == this.Count);
+			return -1;
+		}
+		
+		/// <summary>
+		/// Gets the the first index so that all values from the result index to <paramref name="index"/>
+		/// are equal.
+		/// </summary>
+		public int GetStartOfRun(int index)
+		{
+			if (index < 0 || index >= this.Count)
+				throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + (this.Count - 1));
+			int indexInRun = index;
+			GetNode(ref indexInRun);
+			return index - indexInRun;
+		}
+
+		/// <summary>
+		/// Gets the first index after <paramref name="index"/> so that the value at the result index is not
+		/// equal to the value at <paramref name="index"/>.
+		/// That is, this method returns the exclusive end index of the run of equal values.
+		/// </summary>
+		public int GetEndOfRun(int index)
+		{
+			if (index < 0 || index >= this.Count)
+				throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + (this.Count - 1));
+			int indexInRun = index;
+			int runLength = GetNode(ref indexInRun).count;
+			return index - indexInRun + runLength;
+		}
+
+		/// <summary>
+		/// Gets the number of elements after <paramref name="index"/> that have the same value as each other.
+		/// </summary>
+		[Obsolete("This method may be confusing as it returns only the remaining run length after index. " +
+		          "Use GetStartOfRun/GetEndOfRun instead.")]
+		public int GetRunLength(int index)
+		{
+			if (index < 0 || index >= this.Count)
+				throw new ArgumentOutOfRangeException("index", index, "Value must be between 0 and " + (this.Count - 1));
+			return GetNode(ref index).count - index;
+		}
+		
+		/// <summary>
+		/// Applies the conversion function to all elements in this CompressingTreeList.
+		/// </summary>
+		public void Transform(Func<T, T> converter)
+		{
+			if (root == null)
+				return;
+			Node prevNode = null;
+			for (Node n = root.LeftMost; n != null; n = n.Successor) {
+				n.value = converter(n.value);
+				if (prevNode != null && comparisonFunc(prevNode.value, n.value)) {
+					n.count += prevNode.count;
+					UpdateAugmentedData(n);
+					RemoveNode(prevNode);
+				}
+				prevNode = n;
+			}
+			CheckProperties();
+		}
+		
+		/// <summary>
+		/// Applies the conversion function to the elements in the specified range.
+		/// </summary>
+		public void TransformRange(int index, int length, Func<T, T> converter)
+		{
+			if (root == null)
+				return;
+			int endIndex = index + length;
+			int pos = index;
+			while (pos < endIndex) {
+				int endPos = Math.Min(endIndex, GetEndOfRun(pos));
+				T oldValue = this[pos];
+				T newValue = converter(oldValue);
+				SetRange(pos, endPos - pos, newValue);
+				pos = endPos;
+			}
+		}
+		
+		/// <summary>
+		/// Inserts the specified <paramref name="item"/> at <paramref name="index"/>
+		/// </summary>
+		public void Insert(int index, T item)
+		{
+			InsertRange(index, 1, item);
+		}
+		
+		/// <summary>
+		/// Removes one item at <paramref name="index"/>
+		/// </summary>
+		public void RemoveAt(int index)
+		{
+			RemoveRange(index, 1);
+		}
+		
+		/// <summary>
+		/// Adds the specified <paramref name="item"/> to the end of the list.
+		/// </summary>
+		public void Add(T item)
+		{
+			InsertRange(this.Count, 1, item);
+		}
+		
+		/// <summary>
+		/// Removes all items from this list.
+		/// </summary>
+		public void Clear()
+		{
+			root = null;
+		}
+		
+		/// <summary>
+		/// Gets whether this list contains the specified item.
+		/// </summary>
+		public bool Contains(T item)
+		{
+			return IndexOf(item) >= 0;
+		}
+		
+		/// <summary>
+		/// Copies all items in this list to the specified array.
+		/// </summary>
+		public void CopyTo(T[] array, int arrayIndex)
+		{
+			if (array == null)
+				throw new ArgumentNullException("array");
+			if (array.Length < this.Count)
+				throw new ArgumentException("The array is too small", "array");
+			if (arrayIndex < 0 || arrayIndex + this.Count > array.Length)
+				throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "Value must be between 0 and " + (array.Length - this.Count));
+			foreach (T v in this) {
+				array[arrayIndex++] = v;
+			}
+		}
+		
+		/// <summary>
+		/// Removes the specified item from this list.
+		/// </summary>
+		public bool Remove(T item)
+		{
+			int index = IndexOf(item);
+			if (index >= 0) {
+				RemoveAt(index);
+				return true;
+			} else {
+				return false;
+			}
+		}
+		#endregion
+		
+		#region IEnumerable<T>
+		/// <summary>
+		/// Gets an enumerator for this list.
+		/// </summary>
+		public IEnumerator<T> GetEnumerator()
+		{
+			if (root != null) {
+				Node n = root.LeftMost;
+				while (n != null) {
+					for (int i = 0; i < n.count; i++) {
+						yield return n.value;
+					}
+					n = n.Successor;
+				}
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return GetEnumerator();
+		}
+		#endregion
+		
+		#region Red/Black Tree
+		internal const bool RED = true;
+		internal const bool BLACK = false;
+		
+		void InsertAsLeft(Node parentNode, Node newNode)
+		{
+			Debug.Assert(parentNode.left == null);
+			parentNode.left = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAugmentedData(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void InsertAsRight(Node parentNode, Node newNode)
+		{
+			Debug.Assert(parentNode.right == null);
+			parentNode.right = newNode;
+			newNode.parent = parentNode;
+			newNode.color = RED;
+			UpdateAugmentedData(parentNode);
+			FixTreeOnInsert(newNode);
+		}
+		
+		void FixTreeOnInsert(Node node)
+		{
+			Debug.Assert(node != null);
+			Debug.Assert(node.color == RED);
+			Debug.Assert(node.left == null || node.left.color == BLACK);
+			Debug.Assert(node.right == null || node.right.color == BLACK);
+			
+			Node parentNode = node.parent;
+			if (parentNode == null) {
+				// we inserted in the root -> the node must be black
+				// since this is a root node, making the node black increments the number of black nodes
+				// on all paths by one, so it is still the same for all paths.
+				node.color = BLACK;
+				return;
+			}
+			if (parentNode.color == BLACK) {
+				// if the parent node where we inserted was black, our red node is placed correctly.
+				// since we inserted a red node, the number of black nodes on each path is unchanged
+				// -> the tree is still balanced
+				return;
+			}
+			// parentNode is red, so there is a conflict here!
+			
+			// because the root is black, parentNode is not the root -> there is a grandparent node
+			Node grandparentNode = parentNode.parent;
+			Node uncleNode = Sibling(parentNode);
+			if (uncleNode != null && uncleNode.color == RED) {
+				parentNode.color = BLACK;
+				uncleNode.color = BLACK;
+				grandparentNode.color = RED;
+				FixTreeOnInsert(grandparentNode);
+				return;
+			}
+			// now we know: parent is red but uncle is black
+			// First rotation:
+			if (node == parentNode.right && parentNode == grandparentNode.left) {
+				RotateLeft(parentNode);
+				node = node.left;
+			} else if (node == parentNode.left && parentNode == grandparentNode.right) {
+				RotateRight(parentNode);
+				node = node.right;
+			}
+			// because node might have changed, reassign variables:
+			parentNode = node.parent;
+			grandparentNode = parentNode.parent;
+			
+			// Now recolor a bit:
+			parentNode.color = BLACK;
+			grandparentNode.color = RED;
+			// Second rotation:
+			if (node == parentNode.left && parentNode == grandparentNode.left) {
+				RotateRight(grandparentNode);
+			} else {
+				// because of the first rotation, this is guaranteed:
+				Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
+				RotateLeft(grandparentNode);
+			}
+		}
+		
+		void RemoveNode(Node removedNode)
+		{
+			if (removedNode.left != null && removedNode.right != null) {
+				// replace removedNode with it's in-order successor
+				
+				Node leftMost = removedNode.right.LeftMost;
+				RemoveNode(leftMost); // remove leftMost from its current location
+				
+				// and overwrite the removedNode with it
+				ReplaceNode(removedNode, leftMost);
+				leftMost.left = removedNode.left;
+				if (leftMost.left != null) leftMost.left.parent = leftMost;
+				leftMost.right = removedNode.right;
+				if (leftMost.right != null) leftMost.right.parent = leftMost;
+				leftMost.color = removedNode.color;
+				
+				UpdateAugmentedData(leftMost);
+				if (leftMost.parent != null) UpdateAugmentedData(leftMost.parent);
+				return;
+			}
+			
+			// now either removedNode.left or removedNode.right is null
+			// get the remaining child
+			Node parentNode = removedNode.parent;
+			Node childNode = removedNode.left ?? removedNode.right;
+			ReplaceNode(removedNode, childNode);
+			if (parentNode != null) UpdateAugmentedData(parentNode);
+			if (removedNode.color == BLACK) {
+				if (childNode != null && childNode.color == RED) {
+					childNode.color = BLACK;
+				} else {
+					FixTreeOnDelete(childNode, parentNode);
+				}
+			}
+		}
+		
+		void FixTreeOnDelete(Node node, Node parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (parentNode == null)
+				return;
+			
+			// warning: node may be null
+			Node sibling = Sibling(node, parentNode);
+			if (sibling.color == RED) {
+				parentNode.color = RED;
+				sibling.color = BLACK;
+				if (node == parentNode.left) {
+					RotateLeft(parentNode);
+				} else {
+					RotateRight(parentNode);
+				}
+				
+				sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			}
+			
+			if (parentNode.color == BLACK
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				FixTreeOnDelete(parentNode, parentNode.parent);
+				return;
+			}
+			
+			if (parentNode.color == RED
+			    && sibling.color == BLACK
+			    && GetColor(sibling.left) == BLACK
+			    && GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				parentNode.color = BLACK;
+				return;
+			}
+			
+			if (node == parentNode.left &&
+			    sibling.color == BLACK &&
+			    GetColor(sibling.left) == RED &&
+			    GetColor(sibling.right) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.left.color = BLACK;
+				RotateRight(sibling);
+			}
+			else if (node == parentNode.right &&
+			         sibling.color == BLACK &&
+			         GetColor(sibling.right) == RED &&
+			         GetColor(sibling.left) == BLACK)
+			{
+				sibling.color = RED;
+				sibling.right.color = BLACK;
+				RotateLeft(sibling);
+			}
+			sibling = Sibling(node, parentNode); // update value of sibling after rotation
+			
+			sibling.color = parentNode.color;
+			parentNode.color = BLACK;
+			if (node == parentNode.left) {
+				if (sibling.right != null) {
+					Debug.Assert(sibling.right.color == RED);
+					sibling.right.color = BLACK;
+				}
+				RotateLeft(parentNode);
+			} else {
+				if (sibling.left != null) {
+					Debug.Assert(sibling.left.color == RED);
+					sibling.left.color = BLACK;
+				}
+				RotateRight(parentNode);
+			}
+		}
+		
+		void ReplaceNode(Node replacedNode, Node newNode)
+		{
+			if (replacedNode.parent == null) {
+				Debug.Assert(replacedNode == root);
+				root = newNode;
+			} else {
+				if (replacedNode.parent.left == replacedNode)
+					replacedNode.parent.left = newNode;
+				else
+					replacedNode.parent.right = newNode;
+			}
+			if (newNode != null) {
+				newNode.parent = replacedNode.parent;
+			}
+			replacedNode.parent = null;
+		}
+		
+		void RotateLeft(Node p)
+		{
+			// let q be p's right child
+			Node q = p.right;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's right child to be q's left child
+			p.right = q.left;
+			if (p.right != null) p.right.parent = p;
+			// set q's left child to be p
+			q.left = p;
+			p.parent = q;
+			UpdateAugmentedData(p);
+			UpdateAugmentedData(q);
+		}
+		
+		void RotateRight(Node p)
+		{
+			// let q be p's left child
+			Node q = p.left;
+			Debug.Assert(q != null);
+			Debug.Assert(q.parent == p);
+			// set q to be the new root
+			ReplaceNode(p, q);
+			
+			// set p's left child to be q's right child
+			p.left = q.right;
+			if (p.left != null) p.left.parent = p;
+			// set q's right child to be p
+			q.right = p;
+			p.parent = q;
+			UpdateAugmentedData(p);
+			UpdateAugmentedData(q);
+		}
+		
+		static Node Sibling(Node node)
+		{
+			if (node == node.parent.left)
+				return node.parent.right;
+			else
+				return node.parent.left;
+		}
+		
+		static Node Sibling(Node node, Node parentNode)
+		{
+			Debug.Assert(node == null || node.parent == parentNode);
+			if (node == parentNode.left)
+				return parentNode.right;
+			else
+				return parentNode.left;
+		}
+		
+		static bool GetColor(Node node)
+		{
+			return node != null ? node.color : BLACK;
+		}
+		#endregion
+		
+		#region CheckProperties
+		[Conditional("DATACONSISTENCYTEST")]
+		internal void CheckProperties()
+		{
+			#if DEBUG
+			if (root != null) {
+				CheckProperties(root);
+				
+				// check red-black property:
+				int blackCount = -1;
+				CheckNodeProperties(root, null, RED, 0, ref blackCount);
+				
+				// ensure that the tree is compressed:
+				Node p = root.LeftMost;
+				Node n = p.Successor;
+				while (n != null) {
+					Debug.Assert(!comparisonFunc(p.value, n.value));
+					p = n;
+					n = p.Successor;
+				}
+			}
+			#endif
+		}
+		
+		#if DEBUG
+		void CheckProperties(Node node)
+		{
+			Debug.Assert(node.count > 0);
+			int totalCount = node.count;
+			if (node.left != null) {
+				CheckProperties(node.left);
+				totalCount += node.left.totalCount;
+			}
+			if (node.right != null) {
+				CheckProperties(node.right);
+				totalCount += node.right.totalCount;
+			}
+			Debug.Assert(node.totalCount == totalCount);
+		}
+		
+		/*
+		1. A node is either red or black.
+		2. The root is black.
+		3. All leaves are black. (The leaves are the NIL children.)
+		4. Both children of every red node are black. (So every red node must have a black parent.)
+		5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
+		 */
+		void CheckNodeProperties(Node node, Node parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
+		{
+			if (node == null) return;
+			
+			Debug.Assert(node.parent == parentNode);
+			
+			if (parentColor == RED) {
+				Debug.Assert(node.color == BLACK);
+			}
+			if (node.color == BLACK) {
+				blackCount++;
+			}
+			if (node.left == null && node.right == null) {
+				// node is a leaf node:
+				if (expectedBlackCount == -1)
+					expectedBlackCount = blackCount;
+				else
+					Debug.Assert(expectedBlackCount == blackCount);
+			}
+			CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
+			CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
+		}
+		#endif
+		#endregion
+		
+		#region GetTreeAsString
+		internal string GetTreeAsString()
+		{
+			#if DEBUG
+			if (root == null)
+				return "<empty tree>";
+			StringBuilder b = new StringBuilder();
+			AppendTreeToString(root, b, 0);
+			return b.ToString();
+			#else
+			return "Not available in release build.";
+			#endif
+		}
+		
+		#if DEBUG
+		static void AppendTreeToString(Node node, StringBuilder b, int indent)
+		{
+			if (node.color == RED)
+				b.Append("RED   ");
+			else
+				b.Append("BLACK ");
+			b.AppendLine(node.ToString());
+			indent += 2;
+			if (node.left != null) {
+				b.Append(' ', indent);
+				b.Append("L: ");
+				AppendTreeToString(node.left, b, indent);
+			}
+			if (node.right != null) {
+				b.Append(' ', indent);
+				b.Append("R: ");
+				AppendTreeToString(node.right, b, indent);
+			}
+		}
+		#endif
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Constants.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Constants.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Constants.cs	(revision 11807)
@@ -0,0 +1,30 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	static class Constants
+	{
+		/// <summary>
+		/// Multiply with this constant to convert from points to device-independent pixels.
+		/// </summary>
+		public const double PixelPerPoint = 4 / 3.0;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/DelayedEvents.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/DelayedEvents.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/DelayedEvents.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Maintains a list of delayed events to raise.
+	/// </summary>
+	sealed class DelayedEvents
+	{
+		struct EventCall
+		{
+			EventHandler handler;
+			object sender;
+			EventArgs e;
+			
+			public EventCall(EventHandler handler, object sender, EventArgs e)
+			{
+				this.handler = handler;
+				this.sender = sender;
+				this.e = e;
+			}
+			
+			public void Call()
+			{
+				handler(sender, e);
+			}
+		}
+		
+		Queue<EventCall> eventCalls = new Queue<EventCall>();
+		
+		public void DelayedRaise(EventHandler handler, object sender, EventArgs e)
+		{
+			if (handler != null) {
+				eventCalls.Enqueue(new EventCall(handler, sender, e));
+			}
+		}
+		
+		public void RaiseEvents()
+		{
+			while (eventCalls.Count > 0)
+				eventCalls.Dequeue().Call();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Deque.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Deque.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Deque.cs	(revision 11807)
@@ -0,0 +1,189 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Double-ended queue.
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
+	[Serializable]
+	public sealed class Deque<T> : ICollection<T>
+	{
+		T[] arr = Empty<T>.Array;
+		int size, head, tail;
+		
+		/// <inheritdoc/>
+		public int Count {
+			get { return size; }
+		}
+		
+		/// <inheritdoc/>
+		public void Clear()
+		{
+			arr = Empty<T>.Array;
+			size = 0;
+			head = 0;
+			tail = 0;
+		}
+		
+		/// <summary>
+		/// Gets/Sets an element inside the deque.
+		/// </summary>
+		public T this[int index] {
+			get {
+				ThrowUtil.CheckInRangeInclusive(index, "index", 0, size - 1);
+				return arr[(head + index) % arr.Length];
+			}
+			set {
+				ThrowUtil.CheckInRangeInclusive(index, "index", 0, size - 1);
+				arr[(head + index) % arr.Length] = value;
+			}
+		}
+		
+		/// <summary>
+		/// Adds an element to the end of the deque.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "PushBack")]
+		public void PushBack(T item)
+		{
+			if (size == arr.Length)
+				SetCapacity(Math.Max(4, arr.Length * 2));
+			arr[tail++] = item;
+			if (tail == arr.Length) tail = 0;
+			size++;
+		}
+		
+		/// <summary>
+		/// Pops an element from the end of the deque.
+		/// </summary>
+		public T PopBack()
+		{
+			if (size == 0)
+				throw new InvalidOperationException();
+			if (tail == 0)
+				tail = arr.Length - 1;
+			else
+				tail--;
+			T val = arr[tail];
+			arr[tail] = default(T); // allow GC to collect the element
+			size--;
+			return val;
+		}
+		
+		/// <summary>
+		/// Adds an element to the front of the deque.
+		/// </summary>
+		public void PushFront(T item)
+		{
+			if (size == arr.Length)
+				SetCapacity(Math.Max(4, arr.Length * 2));
+			if (head == 0)
+				head = arr.Length - 1;
+			else
+				head--;
+			arr[head] = item;
+			size++;
+		}
+		
+		/// <summary>
+		/// Pops an element from the end of the deque.
+		/// </summary>
+		public T PopFront()
+		{
+			if (size == 0)
+				throw new InvalidOperationException();
+			T val = arr[head];
+			arr[head] = default(T); // allow GC to collect the element
+			head++;
+			if (head == arr.Length) head = 0;
+			size--;
+			return val;
+		}
+		
+		void SetCapacity(int capacity)
+		{
+			T[] newArr = new T[capacity];
+			CopyTo(newArr, 0);
+			head = 0;
+			tail = (size == capacity) ? 0 : size;
+			arr = newArr;
+		}
+		
+		/// <inheritdoc/>
+		public IEnumerator<T> GetEnumerator()
+		{
+			if (head < tail) {
+				for (int i = head; i < tail; i++)
+					yield return arr[i];
+			} else {
+				for (int i = head; i < arr.Length; i++)
+					yield return arr[i];
+				for (int i = 0; i < tail; i++)
+					yield return arr[i];
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.GetEnumerator();
+		}
+		
+		bool ICollection<T>.IsReadOnly {
+			get { return false; }
+		}
+		
+		void ICollection<T>.Add(T item)
+		{
+			PushBack(item);
+		}
+		
+		/// <inheritdoc/>
+		public bool Contains(T item)
+		{
+			EqualityComparer<T> comparer = EqualityComparer<T>.Default;
+			foreach (T element in this)
+				if (comparer.Equals(item, element))
+					return true;
+			return false;
+		}
+		
+		/// <inheritdoc/>
+		public void CopyTo(T[] array, int arrayIndex)
+		{
+			if (array == null)
+				throw new ArgumentNullException("array");
+			if (head < tail) {
+				Array.Copy(arr, head, array, arrayIndex, tail - head);
+			} else {
+				int num1 = arr.Length - head;
+				Array.Copy(arr, head, array, arrayIndex, num1);
+				Array.Copy(arr, 0, array, arrayIndex + num1, tail);
+			}
+		}
+		
+		bool ICollection<T>.Remove(T item)
+		{
+			throw new NotSupportedException();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/DocumentPrinter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/DocumentPrinter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/DocumentPrinter.cs	(revision 11807)
@@ -0,0 +1,122 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Windows;
+using System.Windows.Documents;
+
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.AvalonEdit.Document;
+using ICSharpCode.AvalonEdit.Highlighting;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Helps printing documents.
+	/// </summary>
+	public static class DocumentPrinter
+	{
+		#if NREFACTORY
+		/// <summary>
+		/// Converts a readonly TextDocument to a Block and applies the provided highlighting definition.
+		/// </summary>
+		public static Block ConvertTextDocumentToBlock(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
+		{
+			IHighlighter highlighter;
+			if (highlightingDefinition != null)
+				highlighter = new DocumentHighlighter(document, highlightingDefinition);
+			else
+				highlighter = null;
+			return ConvertTextDocumentToBlock(document, highlighter);
+		}
+		#endif
+		
+		/// <summary>
+		/// Converts an IDocument to a Block and applies the provided highlighter.
+		/// </summary>
+		public static Block ConvertTextDocumentToBlock(IDocument document, IHighlighter highlighter)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			Paragraph p = new Paragraph();
+			p.TextAlignment = TextAlignment.Left;
+			for (int lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) {
+				if (lineNumber > 1)
+					p.Inlines.Add(new LineBreak());
+				var line = document.GetLineByNumber(lineNumber);
+				if (highlighter != null) {
+					HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
+					p.Inlines.AddRange(highlightedLine.ToRichText().CreateRuns());
+				} else {
+					p.Inlines.Add(document.GetText(line));
+				}
+			}
+			return p;
+		}
+		
+		#if NREFACTORY
+		/// <summary>
+		/// Converts a readonly TextDocument to a RichText and applies the provided highlighting definition.
+		/// </summary>
+		public static RichText ConvertTextDocumentToRichText(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
+		{
+			IHighlighter highlighter;
+			if (highlightingDefinition != null)
+				highlighter = new DocumentHighlighter(document, highlightingDefinition);
+			else
+				highlighter = null;
+			return ConvertTextDocumentToRichText(document, highlighter);
+		}
+		#endif
+		
+		/// <summary>
+		/// Converts an IDocument to a RichText and applies the provided highlighter.
+		/// </summary>
+		public static RichText ConvertTextDocumentToRichText(IDocument document, IHighlighter highlighter)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			var texts = new List<RichText>();
+			for (int lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) {
+				var line = document.GetLineByNumber(lineNumber);
+				if (lineNumber > 1)
+					texts.Add(line.PreviousLine.DelimiterLength == 2 ? "\r\n" : "\n");
+				if (highlighter != null) {
+					HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
+					texts.Add(highlightedLine.ToRichText());
+				} else {
+					texts.Add(document.GetText(line));
+				}
+			}
+			return RichText.Concat(texts.ToArray());
+		}
+		
+		/// <summary>
+		/// Creates a flow document from the editor's contents.
+		/// </summary>
+		public static FlowDocument CreateFlowDocumentForEditor(TextEditor editor)
+		{
+			IHighlighter highlighter = editor.TextArea.GetService(typeof(IHighlighter)) as IHighlighter;
+			FlowDocument doc = new FlowDocument(ConvertTextDocumentToBlock(editor.Document, highlighter));
+			doc.FontFamily = editor.FontFamily;
+			doc.FontSize = editor.FontSize;
+			return doc;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Empty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Empty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Empty.cs	(revision 11807)
@@ -0,0 +1,32 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Provides immutable empty list instances.
+	/// </summary>
+	static class Empty<T>
+	{
+		public static readonly T[] Array = new T[0];
+		//public static readonly ReadOnlyCollection<T> ReadOnlyCollection = new ReadOnlyCollection<T>(Array);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ExtensionMethods.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ExtensionMethods.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ExtensionMethods.cs	(revision 11807)
@@ -0,0 +1,237 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Xml;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	static class ExtensionMethods
+	{
+		#region Epsilon / IsClose / CoerceValue
+		/// <summary>
+		/// Epsilon used for <c>IsClose()</c> implementations.
+		/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
+		/// and there's no need to be too accurate (we're dealing with pixels here),
+		/// so we will use the value 0.01.
+		/// Previosly we used 1e-8 but that was causing issues:
+		/// http://community.sharpdevelop.net/forums/t/16048.aspx
+		/// </summary>
+		public const double Epsilon = 0.01;
+		
+		/// <summary>
+		/// Returns true if the doubles are close (difference smaller than 0.01).
+		/// </summary>
+		public static bool IsClose(this double d1, double d2)
+		{
+			if (d1 == d2) // required for infinities
+				return true;
+			return Math.Abs(d1 - d2) < Epsilon;
+		}
+		
+		/// <summary>
+		/// Returns true if the doubles are close (difference smaller than 0.01).
+		/// </summary>
+		public static bool IsClose(this Size d1, Size d2)
+		{
+			return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
+		}
+		
+		/// <summary>
+		/// Returns true if the doubles are close (difference smaller than 0.01).
+		/// </summary>
+		public static bool IsClose(this Vector d1, Vector d2)
+		{
+			return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
+		}
+		
+		/// <summary>
+		/// Forces the value to stay between mininum and maximum.
+		/// </summary>
+		/// <returns>minimum, if value is less than minimum.
+		/// Maximum, if value is greater than maximum.
+		/// Otherwise, value.</returns>
+		public static double CoerceValue(this double value, double minimum, double maximum)
+		{
+			return Math.Max(Math.Min(value, maximum), minimum);
+		}
+		
+		/// <summary>
+		/// Forces the value to stay between mininum and maximum.
+		/// </summary>
+		/// <returns>minimum, if value is less than minimum.
+		/// Maximum, if value is greater than maximum.
+		/// Otherwise, value.</returns>
+		public static int CoerceValue(this int value, int minimum, int maximum)
+		{
+			return Math.Max(Math.Min(value, maximum), minimum);
+		}
+		#endregion
+		
+		#region CreateTypeface
+		/// <summary>
+		/// Creates typeface from the framework element.
+		/// </summary>
+		public static Typeface CreateTypeface(this FrameworkElement fe)
+		{
+			return new Typeface((FontFamily)fe.GetValue(TextBlock.FontFamilyProperty),
+			                    (FontStyle)fe.GetValue(TextBlock.FontStyleProperty),
+			                    (FontWeight)fe.GetValue(TextBlock.FontWeightProperty),
+			                    (FontStretch)fe.GetValue(TextBlock.FontStretchProperty));
+		}
+		#endregion
+		
+		#region AddRange / Sequence
+		public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
+		{
+			foreach (T e in elements)
+				collection.Add(e);
+		}
+		
+		/// <summary>
+		/// Creates an IEnumerable with a single value.
+		/// </summary>
+		public static IEnumerable<T> Sequence<T>(T value)
+		{
+			yield return value;
+		}
+		#endregion
+		
+		#region XML reading
+		/// <summary>
+		/// Gets the value of the attribute, or null if the attribute does not exist.
+		/// </summary>
+		public static string GetAttributeOrNull(this XmlElement element, string attributeName)
+		{
+			XmlAttribute attr = element.GetAttributeNode(attributeName);
+			return attr != null ? attr.Value : null;
+		}
+		
+		/// <summary>
+		/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
+		/// </summary>
+		public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
+		{
+			XmlAttribute attr = element.GetAttributeNode(attributeName);
+			return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
+		}
+		
+		/// <summary>
+		/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
+		/// </summary>
+		public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
+		{
+			string attributeValue = reader.GetAttribute(attributeName);
+			if (attributeValue == null)
+				return null;
+			else
+				return XmlConvert.ToBoolean(attributeValue);
+		}
+		#endregion
+		
+		#region DPI independence
+		public static Rect TransformToDevice(this Rect rect, Visual visual)
+		{
+			Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
+			return Rect.Transform(rect, matrix);
+		}
+		
+		public static Rect TransformFromDevice(this Rect rect, Visual visual)
+		{
+			Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
+			return Rect.Transform(rect, matrix);
+		}
+		
+		public static Size TransformToDevice(this Size size, Visual visual)
+		{
+			Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
+			return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
+		}
+		
+		public static Size TransformFromDevice(this Size size, Visual visual)
+		{
+			Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
+			return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
+		}
+		
+		public static Point TransformToDevice(this Point point, Visual visual)
+		{
+			Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
+			return new Point(point.X * matrix.M11, point.Y * matrix.M22);
+		}
+		
+		public static Point TransformFromDevice(this Point point, Visual visual)
+		{
+			Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
+			return new Point(point.X * matrix.M11, point.Y * matrix.M22);
+		}
+		#endregion
+		
+		#region System.Drawing <-> WPF conversions
+		public static System.Drawing.Point ToSystemDrawing(this Point p)
+		{
+			return new System.Drawing.Point((int)p.X, (int)p.Y);
+		}
+		
+		public static Point ToWpf(this System.Drawing.Point p)
+		{
+			return new Point(p.X, p.Y);
+		}
+		
+		public static Size ToWpf(this System.Drawing.Size s)
+		{
+			return new Size(s.Width, s.Height);
+		}
+		
+		public static Rect ToWpf(this System.Drawing.Rectangle rect)
+		{
+			return new Rect(rect.Location.ToWpf(), rect.Size.ToWpf());
+		}
+		#endregion
+		
+		public static IEnumerable<DependencyObject> VisualAncestorsAndSelf(this DependencyObject obj)
+		{
+			while (obj != null) {
+				yield return obj;
+				obj = VisualTreeHelper.GetParent(obj);
+			}
+		}
+		
+		[Conditional("DEBUG")]
+		public static void CheckIsFrozen(Freezable f)
+		{
+			if (f != null && !f.IsFrozen)
+				Debug.WriteLine("Performance warning: Not frozen: " + f.ToString());
+		}
+		
+		[Conditional("DEBUG")]
+		public static void Log(bool condition, string format, params object[] args)
+		{
+			if (condition) {
+				string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args) + Environment.NewLine + Environment.StackTrace;
+				Console.WriteLine(output);
+				Debug.WriteLine(output);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/FileReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/FileReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/FileReader.cs	(revision 11807)
@@ -0,0 +1,240 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Class that can open text files with auto-detection of the encoding.
+	/// </summary>
+	public static class FileReader
+	{
+		/// <summary>
+		/// Gets if the given encoding is a Unicode encoding (UTF).
+		/// </summary>
+		/// <remarks>
+		/// Returns true for UTF-7, UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE and UTF-32 BE.
+		/// Returns false for all other encodings.
+		/// </remarks>
+		public static bool IsUnicode(Encoding encoding)
+		{
+			if (encoding == null)
+				throw new ArgumentNullException("encoding");
+			switch (encoding.CodePage) {
+				case 65000: // UTF-7
+				case 65001: // UTF-8
+				case 1200: // UTF-16 LE
+				case 1201: // UTF-16 BE
+				case 12000: // UTF-32 LE
+				case 12001: // UTF-32 BE
+					return true;
+				default:
+					return false;
+			}
+		}
+		
+		static bool IsASCIICompatible(Encoding encoding)
+		{
+			byte[] bytes = encoding.GetBytes("Az");
+			return bytes.Length == 2 && bytes[0] == 'A' && bytes[1] == 'z';
+		}
+		
+		static Encoding RemoveBOM(Encoding encoding)
+		{
+			switch (encoding.CodePage) {
+				case 65001: // UTF-8
+					return UTF8NoBOM;
+				default:
+					return encoding;
+			}
+		}
+		
+		/// <summary>
+		/// Reads the content of the given stream.
+		/// </summary>
+		/// <param name="stream">The stream to read.
+		/// The stream must support seeking and must be positioned at its beginning.</param>
+		/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
+		/// <returns>The file content as string.</returns>
+		public static string ReadFileContent(Stream stream, Encoding defaultEncoding)
+		{
+			using (StreamReader reader = OpenStream(stream, defaultEncoding)) {
+				return reader.ReadToEnd();
+			}
+		}
+		
+		/// <summary>
+		/// Reads the content of the file.
+		/// </summary>
+		/// <param name="fileName">The file name.</param>
+		/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
+		/// <returns>The file content as string.</returns>
+		public static string ReadFileContent(string fileName, Encoding defaultEncoding)
+		{
+			using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
+				return ReadFileContent(fs, defaultEncoding);
+			}
+		}
+		
+		/// <summary>
+		/// Opens the specified file for reading.
+		/// </summary>
+		/// <param name="fileName">The file to open.</param>
+		/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
+		/// <returns>Returns a StreamReader that reads from the stream. Use
+		/// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns>
+		public static StreamReader OpenFile(string fileName, Encoding defaultEncoding)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException("fileName");
+			FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
+			try {
+				return OpenStream(fs, defaultEncoding);
+				// don't use finally: the stream must be kept open until the StreamReader closes it
+			} catch {
+				fs.Dispose();
+				throw;
+			}
+		}
+		
+		/// <summary>
+		/// Opens the specified stream for reading.
+		/// </summary>
+		/// <param name="stream">The stream to open.</param>
+		/// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param>
+		/// <returns>Returns a StreamReader that reads from the stream. Use
+		/// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns>
+		public static StreamReader OpenStream(Stream stream, Encoding defaultEncoding)
+		{
+			if (stream == null)
+				throw new ArgumentNullException("stream");
+			if (stream.Position != 0)
+				throw new ArgumentException("stream is not positioned at beginning.", "stream");
+			if (defaultEncoding == null)
+				throw new ArgumentNullException("defaultEncoding");
+			
+			if (stream.Length >= 2) {
+				// the autodetection of StreamReader is not capable of detecting the difference
+				// between ISO-8859-1 and UTF-8 without BOM.
+				int firstByte = stream.ReadByte();
+				int secondByte = stream.ReadByte();
+				switch ((firstByte << 8) | secondByte) {
+					case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader
+					case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE)
+					case 0xfeff: // UTF-16 BE BOM
+					case 0xefbb: // start of UTF-8 BOM
+						// StreamReader autodetection works
+						stream.Position = 0;
+						return new StreamReader(stream);
+					default:
+						return AutoDetect(stream, (byte)firstByte, (byte)secondByte, defaultEncoding);
+				}
+			} else {
+				if (defaultEncoding != null) {
+					return new StreamReader(stream, defaultEncoding);
+				} else {
+					return new StreamReader(stream);
+				}
+			}
+		}
+		
+		static readonly Encoding UTF8NoBOM = new UTF8Encoding(false);
+		
+		static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding)
+		{
+			int max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB
+			const int ASCII = 0;
+			const int Error = 1;
+			const int UTF8  = 2;
+			const int UTF8Sequence = 3;
+			int state = ASCII;
+			int sequenceLength = 0;
+			byte b;
+			for (int i = 0; i < max; i++) {
+				if (i == 0) {
+					b = firstByte;
+				} else if (i == 1) {
+					b = secondByte;
+				} else {
+					b = (byte)fs.ReadByte();
+				}
+				if (b < 0x80) {
+					// normal ASCII character
+					if (state == UTF8Sequence) {
+						state = Error;
+						break;
+					}
+				} else if (b < 0xc0) {
+					// 10xxxxxx : continues UTF8 byte sequence
+					if (state == UTF8Sequence) {
+						--sequenceLength;
+						if (sequenceLength < 0) {
+							state = Error;
+							break;
+						} else if (sequenceLength == 0) {
+							state = UTF8;
+						}
+					} else {
+						state = Error;
+						break;
+					}
+				} else if (b >= 0xc2 && b < 0xf5) {
+					// beginning of byte sequence
+					if (state == UTF8 || state == ASCII) {
+						state = UTF8Sequence;
+						if (b < 0xe0) {
+							sequenceLength = 1; // one more byte following
+						} else if (b < 0xf0) {
+							sequenceLength = 2; // two more bytes following
+						} else {
+							sequenceLength = 3; // three more bytes following
+						}
+					} else {
+						state = Error;
+						break;
+					}
+				} else {
+					// 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629)
+					state = Error;
+					break;
+				}
+			}
+			fs.Position = 0;
+			switch (state) {
+				case ASCII:
+					return new StreamReader(fs, IsASCIICompatible(defaultEncoding) ? RemoveBOM(defaultEncoding) : Encoding.ASCII);
+				case Error:
+					// When the file seems to be non-UTF8,
+					// we read it using the user-specified encoding so it is saved again
+					// using that encoding.
+					if (IsUnicode(defaultEncoding)) {
+						// the file is not Unicode, so don't read it using Unicode even if the
+						// user has choosen Unicode as the default encoding.
+						
+						defaultEncoding = Encoding.Default; // use system encoding instead
+					}
+					return new StreamReader(fs, RemoveBOM(defaultEncoding));
+				default:
+					return new StreamReader(fs, UTF8NoBOM);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/IFreezable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/IFreezable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/IFreezable.cs	(revision 11807)
@@ -0,0 +1,123 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	interface IFreezable
+	{
+		/// <summary>
+		/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
+		/// </summary>
+		bool IsFrozen { get; }
+		
+		/// <summary>
+		/// Freezes this instance.
+		/// </summary>
+		void Freeze();
+	}
+	
+	static class FreezableHelper
+	{
+		public static void ThrowIfFrozen(IFreezable freezable)
+		{
+			if (freezable.IsFrozen)
+				throw new InvalidOperationException("Cannot mutate frozen " + freezable.GetType().Name);
+		}
+		
+		public static IList<T> FreezeListAndElements<T>(IList<T> list)
+		{
+			if (list != null) {
+				foreach (T item in list)
+					Freeze(item);
+			}
+			return FreezeList(list);
+		}
+		
+		public static IList<T> FreezeList<T>(IList<T> list)
+		{
+			if (list == null || list.Count == 0)
+				return Empty<T>.Array;
+			if (list.IsReadOnly) {
+				// If the list is already read-only, return it directly.
+				// This is important, otherwise we might undo the effects of interning.
+				return list;
+			} else {
+				return new ReadOnlyCollection<T>(list.ToArray());
+			}
+		}
+		
+		public static void Freeze(object item)
+		{
+			IFreezable f = item as IFreezable;
+			if (f != null)
+				f.Freeze();
+		}
+		
+		public static T FreezeAndReturn<T>(T item) where T : IFreezable
+		{
+			item.Freeze();
+			return item;
+		}
+		
+		/// <summary>
+		/// If the item is not frozen, this method creates and returns a frozen clone.
+		/// If the item is already frozen, it is returned without creating a clone.
+		/// </summary>
+		public static T GetFrozenClone<T>(T item) where T : IFreezable, ICloneable
+		{
+			if (!item.IsFrozen) {
+				item = (T)item.Clone();
+				item.Freeze();
+			}
+			return item;
+		}
+	}
+
+	[Serializable]
+	abstract class AbstractFreezable : IFreezable
+	{
+		bool isFrozen;
+		
+		/// <summary>
+		/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
+		/// </summary>
+		public bool IsFrozen {
+			get { return isFrozen; }
+		}
+		
+		/// <summary>
+		/// Freezes this instance.
+		/// </summary>
+		public void Freeze()
+		{
+			if (!isFrozen) {
+				FreezeInternal();
+				isFrozen = true;
+			}
+		}
+		
+		protected virtual void FreezeInternal()
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ImmutableStack.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ImmutableStack.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ImmutableStack.cs	(revision 11807)
@@ -0,0 +1,132 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// An immutable stack.
+	/// 
+	/// Using 'foreach' on the stack will return the items from top to bottom (in the order they would be popped).
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
+	[Serializable]
+	public sealed class ImmutableStack<T> : IEnumerable<T>
+	{
+		/// <summary>
+		/// Gets the empty stack instance.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "ImmutableStack is immutable")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
+		public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
+		
+		readonly T value;
+		readonly ImmutableStack<T> next;
+		
+		private ImmutableStack()
+		{
+		}
+		
+		private ImmutableStack(T value, ImmutableStack<T> next)
+		{
+			this.value = value;
+			this.next = next;
+		}
+		
+		/// <summary>
+		/// Pushes an item on the stack. This does not modify the stack itself, but returns a new
+		/// one with the value pushed.
+		/// </summary>
+		public ImmutableStack<T> Push(T item)
+		{
+			return new ImmutableStack<T>(item, this);
+		}
+		
+		/// <summary>
+		/// Gets the item on the top of the stack.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The stack is empty.</exception>
+		public T Peek()
+		{
+			if (IsEmpty)
+				throw new InvalidOperationException("Operation not valid on empty stack.");
+			return value;
+		}
+		
+		/// <summary>
+		/// Gets the item on the top of the stack.
+		/// Returns <c>default(T)</c> if the stack is empty.
+		/// </summary>
+		public T PeekOrDefault()
+		{
+			return value;
+		}
+		
+		/// <summary>
+		/// Gets the stack with the top item removed.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The stack is empty.</exception>
+		public ImmutableStack<T> Pop()
+		{
+			if (IsEmpty)
+				throw new InvalidOperationException("Operation not valid on empty stack.");
+			return next;
+		}
+		
+		/// <summary>
+		/// Gets if this stack is empty.
+		/// </summary>
+		public bool IsEmpty {
+			get { return next == null; }
+		}
+		
+		/// <summary>
+		/// Gets an enumerator that iterates through the stack top-to-bottom.
+		/// </summary>
+		public IEnumerator<T> GetEnumerator()
+		{
+			ImmutableStack<T> t = this;
+			while (!t.IsEmpty) {
+				yield return t.value;
+				t = t.next;
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.GetEnumerator();
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[Stack");
+			foreach (T val in this) {
+				b.Append(' ');
+				b.Append(val);
+			}
+			b.Append(']');
+			return b.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/NullSafeCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/NullSafeCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/NullSafeCollection.cs	(revision 11807)
@@ -0,0 +1,46 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// A collection that cannot contain null values.
+	/// </summary>
+	[Serializable]
+	public class NullSafeCollection<T> : Collection<T> where T : class
+	{
+		/// <inheritdoc/>
+		protected override void InsertItem(int index, T item)
+		{
+			if (item == null)
+				throw new ArgumentNullException("item");
+			base.InsertItem(index, item);
+		}
+		
+		/// <inheritdoc/>
+		protected override void SetItem(int index, T item)
+		{
+			if (item == null)
+				throw new ArgumentNullException("item");
+			base.SetItem(index, item);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ObserveAddRemoveCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ObserveAddRemoveCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ObserveAddRemoveCollection.cs	(revision 11807)
@@ -0,0 +1,89 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// A collection where adding and removing items causes a callback.
+	/// It is valid for the onAdd callback to throw an exception - this will prevent the new item from
+	/// being added to the collection.
+	/// </summary>
+	sealed class ObserveAddRemoveCollection<T> : Collection<T>
+	{
+		readonly Action<T> onAdd, onRemove;
+		
+		/// <summary>
+		/// Creates a new ObserveAddRemoveCollection using the specified callbacks.
+		/// </summary>
+		public ObserveAddRemoveCollection(Action<T> onAdd, Action<T> onRemove)
+		{
+			if (onAdd == null)
+				throw new ArgumentNullException("onAdd");
+			if (onRemove == null)
+				throw new ArgumentNullException("onRemove");
+			this.onAdd = onAdd;
+			this.onRemove = onRemove;
+		}
+		
+		/// <inheritdoc/>
+		protected override void ClearItems()
+		{
+			if (onRemove != null) {
+				foreach (T val in this)
+					onRemove(val);
+			}
+			base.ClearItems();
+		}
+		
+		/// <inheritdoc/>
+		protected override void InsertItem(int index, T item)
+		{
+			if (onAdd != null)
+				onAdd(item);
+			base.InsertItem(index, item);
+		}
+		
+		/// <inheritdoc/>
+		protected override void RemoveItem(int index)
+		{
+			if (onRemove != null)
+				onRemove(this[index]);
+			base.RemoveItem(index);
+		}
+		
+		/// <inheritdoc/>
+		protected override void SetItem(int index, T item)
+		{
+			if (onRemove != null)
+				onRemove(this[index]);
+			try {
+				if (onAdd != null)
+					onAdd(item);
+			} catch {
+				// When adding the new item fails, just remove the old one
+				// (we cannot keep the old item since we already successfully called onRemove for it)
+				base.RemoveAt(index);
+				throw;
+			}
+			base.SetItem(index, item);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PixelSnapHelpers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PixelSnapHelpers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PixelSnapHelpers.cs	(revision 11807)
@@ -0,0 +1,107 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Windows;
+using System.Windows.Media;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Contains static helper methods for aligning stuff on a whole number of pixels.
+	/// </summary>
+	public static class PixelSnapHelpers
+	{
+		/// <summary>
+		/// Gets the pixel size on the screen containing visual.
+		/// This method does not take transforms on visual into account.
+		/// </summary>
+		public static Size GetPixelSize(Visual visual)
+		{
+			if (visual == null)
+				throw new ArgumentNullException("visual");
+			PresentationSource source = PresentationSource.FromVisual(visual);
+			if (source != null) {
+				Matrix matrix = source.CompositionTarget.TransformFromDevice;
+				return new Size(matrix.M11, matrix.M22);
+			} else {
+				return new Size(1, 1);
+			}
+		}
+		
+		/// <summary>
+		/// Aligns <paramref name="value"/> on the next middle of a pixel.
+		/// </summary>
+		/// <param name="value">The value that should be aligned</param>
+		/// <param name="pixelSize">The size of one pixel</param>
+		public static double PixelAlign(double value, double pixelSize)
+		{
+			// 0 -> 0.5
+			// 0.1 -> 0.5
+			// 0.5 -> 0.5
+			// 0.9 -> 0.5
+			// 1 -> 1.5
+			return pixelSize * (Math.Round((value / pixelSize) + 0.5) - 0.5);
+		}
+		
+		/// <summary>
+		/// Aligns the borders of rect on the middles of pixels.
+		/// </summary>
+		public static Rect PixelAlign(Rect rect, Size pixelSize)
+		{
+			rect.X = PixelAlign(rect.X, pixelSize.Width);
+			rect.Y = PixelAlign(rect.Y, pixelSize.Height);
+			rect.Width = Round(rect.Width, pixelSize.Width);
+			rect.Height = Round(rect.Height, pixelSize.Height);
+			return rect;
+		}
+		
+		/// <summary>
+		/// Rounds <paramref name="point"/> to whole number of pixels.
+		/// </summary>
+		public static Point Round(Point point, Size pixelSize)
+		{
+			return new Point(Round(point.X, pixelSize.Width), Round(point.Y, pixelSize.Height));
+		}
+		
+		/// <summary>
+		/// Rounds val to whole number of pixels.
+		/// </summary>
+		public static Rect Round(Rect rect, Size pixelSize)
+		{
+			return new Rect(Round(rect.X, pixelSize.Width), Round(rect.Y, pixelSize.Height),
+			                Round(rect.Width, pixelSize.Width), Round(rect.Height, pixelSize.Height));
+		}
+		
+		/// <summary>
+		/// Rounds <paramref name="value"/> to a whole number of pixels.
+		/// </summary>
+		public static double Round(double value, double pixelSize)
+		{
+			return pixelSize * Math.Round(value / pixelSize);
+		}
+		
+		/// <summary>
+		/// Rounds <paramref name="value"/> to an whole odd number of pixels.
+		/// </summary>
+		public static double RoundToOdd(double value, double pixelSize)
+		{
+			return Round(value - pixelSize, pixelSize * 2) + pixelSize;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PlainRichTextWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PlainRichTextWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PlainRichTextWriter.cs	(revision 11807)
@@ -0,0 +1,140 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// RichTextWriter implementation that writes plain text only
+	/// and ignores all formatted spans.
+	/// </summary>
+	class PlainRichTextWriter : RichTextWriter
+	{
+		/// <summary>
+		/// The text writer that was passed to the PlainRichTextWriter constructor.
+		/// </summary>
+		protected readonly TextWriter textWriter;
+		string indentationString = "\t";
+		int indentationLevel;
+		char prevChar;
+		
+		/// <summary>
+		/// Creates a new PlainRichTextWriter instance that writes the text to the specified text writer.
+		/// </summary>
+		public PlainRichTextWriter(TextWriter textWriter)
+		{
+			if (textWriter == null)
+				throw new ArgumentNullException("textWriter");
+			this.textWriter = textWriter;
+		}
+		
+		/// <summary>
+		/// Gets/Sets the string used to indent by one level.
+		/// </summary>
+		public string IndentationString {
+			get {
+				return indentationString;
+			}
+			set {
+				indentationString = value;
+			}
+		}
+		
+		/// <inheritdoc/>
+		protected override void BeginUnhandledSpan()
+		{
+		}
+		
+		/// <inheritdoc/>
+		public override void EndSpan()
+		{
+		}
+		
+		void WriteIndentation()
+		{
+			for (int i = 0; i < indentationLevel; i++) {
+				textWriter.Write(indentationString);
+			}
+		}
+		
+		/// <summary>
+		/// Writes the indentation, if necessary.
+		/// </summary>
+		protected void WriteIndentationIfNecessary()
+		{
+			if (prevChar == '\n') {
+				WriteIndentation();
+				prevChar = '\0';
+			}
+		}
+		
+		/// <summary>
+		/// Is called after a write operation.
+		/// </summary>
+		protected virtual void AfterWrite()
+		{
+		}
+		
+		/// <inheritdoc/>
+		public override void Write(char value)
+		{
+			if (prevChar == '\n')
+				WriteIndentation();
+			textWriter.Write(value);
+			prevChar = value;
+			AfterWrite();
+		}
+		
+		/// <inheritdoc/>
+		public override void Indent()
+		{
+			indentationLevel++;
+		}
+		
+		/// <inheritdoc/>
+		public override void Unindent()
+		{
+			if (indentationLevel == 0)
+				throw new NotSupportedException();
+			indentationLevel--;
+		}
+		
+		/// <inheritdoc/>
+		public override Encoding Encoding {
+			get { return textWriter.Encoding; }
+		}
+		
+		/// <inheritdoc/>
+		public override IFormatProvider FormatProvider {
+			get { return textWriter.FormatProvider; }
+		}
+		
+		/// <inheritdoc/>
+		public override string NewLine {
+			get {
+				return textWriter.NewLine;
+			}
+			set {
+				textWriter.NewLine = value;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PropertyChangedWeakEventManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PropertyChangedWeakEventManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/PropertyChangedWeakEventManager.cs	(revision 11807)
@@ -0,0 +1,41 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// WeakEventManager for INotifyPropertyChanged.PropertyChanged.
+	/// </summary>
+	public sealed class PropertyChangedWeakEventManager : WeakEventManagerBase<PropertyChangedWeakEventManager, INotifyPropertyChanged>
+	{
+		/// <inheritdoc/>
+		protected override void StartListening(INotifyPropertyChanged source)
+		{
+			source.PropertyChanged += DeliverEvent;
+		}
+		
+		/// <inheritdoc/>
+		protected override void StopListening(INotifyPropertyChanged source)
+		{
+			source.PropertyChanged -= DeliverEvent;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RichTextWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RichTextWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RichTextWriter.cs	(revision 11807)
@@ -0,0 +1,124 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using System.Windows;
+using System.Windows.Media;
+using ICSharpCode.AvalonEdit.Highlighting;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	// TODO: This class (and derived classes) is currently unused; decide whether to keep it.
+	// (until this is decided, keep the class internal)
+	
+	/// <summary>
+	/// A text writer that supports creating spans of highlighted text.
+	/// </summary>
+	abstract class RichTextWriter : TextWriter
+	{
+		/// <summary>
+		/// Gets called by the RichTextWriter base class when a BeginSpan() method
+		/// that is not overwritten gets called.
+		/// </summary>
+		protected abstract void BeginUnhandledSpan();
+		
+		/// <summary>
+		/// Writes the RichText instance.
+		/// </summary>
+		public void Write(RichText richText)
+		{
+			Write(richText, 0, richText.Length);
+		}
+		
+		/// <summary>
+		/// Writes the RichText instance.
+		/// </summary>
+		public virtual void Write(RichText richText, int offset, int length)
+		{
+			foreach (var section in richText.GetHighlightedSections(offset, length)) {
+				BeginSpan(section.Color);
+				Write(richText.Text.Substring(section.Offset, section.Length));
+				EndSpan();
+			}
+		}
+		
+		/// <summary>
+		/// Begin a colored span.
+		/// </summary>
+		public virtual void BeginSpan(Color foregroundColor)
+		{
+			BeginUnhandledSpan();
+		}
+		
+		/// <summary>
+		/// Begin a span with modified font weight.
+		/// </summary>
+		public virtual void BeginSpan(FontWeight fontWeight)
+		{
+			BeginUnhandledSpan();
+		}
+		
+		/// <summary>
+		/// Begin a span with modified font style.
+		/// </summary>
+		public virtual void BeginSpan(FontStyle fontStyle)
+		{
+			BeginUnhandledSpan();
+		}
+		
+		/// <summary>
+		/// Begin a span with modified font family.
+		/// </summary>
+		public virtual void BeginSpan(FontFamily fontFamily)
+		{
+			BeginUnhandledSpan();
+		}
+		
+		/// <summary>
+		/// Begin a highlighted span.
+		/// </summary>
+		public virtual void BeginSpan(Highlighting.HighlightingColor highlightingColor)
+		{
+			BeginUnhandledSpan();
+		}
+		
+		/// <summary>
+		/// Begin a span that links to the specified URI.
+		/// </summary>
+		public virtual void BeginHyperlinkSpan(Uri uri)
+		{
+			BeginUnhandledSpan();
+		}
+		
+		/// <summary>
+		/// Marks the end of the current span.
+		/// </summary>
+		public abstract void EndSpan();
+		
+		/// <summary>
+		/// Increases the indentation level.
+		/// </summary>
+		public abstract void Indent();
+		
+		/// <summary>
+		/// Decreases the indentation level.
+		/// </summary>
+		public abstract void Unindent();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Rope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Rope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Rope.cs	(revision 11807)
@@ -0,0 +1,854 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// A kind of List&lt;T&gt;, but more efficient for random insertions/removal.
+	/// Also has cheap Clone() and SubRope() implementations.
+	/// </summary>
+	/// <remarks>
+	/// This class is not thread-safe: multiple concurrent write operations or writes concurrent to reads have undefined behaviour.
+	/// Concurrent reads, however, are safe.
+	/// However, clones of a rope are safe to use on other threads even though they share data with the original rope.
+	/// </remarks>
+	[Serializable]
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
+	public sealed class Rope<T> : IList<T>, ICloneable
+	{
+		internal RopeNode<T> root;
+		
+		internal Rope(RopeNode<T> root)
+		{
+			this.root = root;
+			root.CheckInvariants();
+		}
+		
+		/// <summary>
+		/// Creates a new rope representing the empty string.
+		/// </summary>
+		public Rope()
+		{
+			// we'll construct the empty rope as a clone of an imaginary static empty rope
+			this.root = RopeNode<T>.emptyRopeNode;
+			root.CheckInvariants();
+		}
+		
+		/// <summary>
+		/// Creates a rope from the specified input.
+		/// This operation runs in O(N).
+		/// </summary>
+		/// <exception cref="ArgumentNullException">input is null.</exception>
+		public Rope(IEnumerable<T> input)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			Rope<T> inputRope = input as Rope<T>;
+			if (inputRope != null) {
+				// clone ropes instead of copying them
+				inputRope.root.Publish();
+				this.root = inputRope.root;
+			} else {
+				string text = input as string;
+				if (text != null) {
+					// if a string is IEnumerable<T>, then T must be char
+					((Rope<char>)(object)this).root = CharRope.InitFromString(text);
+				} else {
+					T[] arr = ToArray(input);
+					this.root = RopeNode<T>.CreateFromArray(arr, 0, arr.Length);
+				}
+			}
+			this.root.CheckInvariants();
+		}
+		
+		/// <summary>
+		/// Creates a rope from a part of the array.
+		/// This operation runs in O(N).
+		/// </summary>
+		/// <exception cref="ArgumentNullException">input is null.</exception>
+		public Rope(T[] array, int arrayIndex, int count)
+		{
+			VerifyArrayWithRange(array, arrayIndex, count);
+			this.root = RopeNode<T>.CreateFromArray(array, arrayIndex, count);
+			this.root.CheckInvariants();
+		}
+		
+		/// <summary>
+		/// Creates a new rope that lazily initalizes its content.
+		/// </summary>
+		/// <param name="length">The length of the rope that will be lazily loaded.</param>
+		/// <param name="initializer">
+		/// The callback that provides the content for this rope.
+		/// <paramref name="initializer"/> will be called exactly once when the content of this rope is first requested.
+		/// It must return a rope with the specified length.
+		/// Because the initializer function is not called when a rope is cloned, and such clones may be used on another threads,
+		/// it is possible for the initializer callback to occur on any thread.
+		/// </param>
+		/// <remarks>
+		/// Any modifications inside the rope will also cause the content to be initialized.
+		/// However, insertions at the beginning and the end, as well as inserting this rope into another or
+		/// using the <see cref="Concat(Rope{T},Rope{T})"/> method, allows constructions of larger ropes where parts are
+		/// lazily loaded.
+		/// However, even methods like Concat may sometimes cause the initializer function to be called, e.g. when
+		/// two short ropes are concatenated.
+		/// </remarks>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
+		public Rope(int length, Func<Rope<T>> initializer)
+		{
+			if (initializer == null)
+				throw new ArgumentNullException("initializer");
+			if (length < 0)
+				throw new ArgumentOutOfRangeException("length", length, "Length must not be negative");
+			if (length == 0) {
+				this.root = RopeNode<T>.emptyRopeNode;
+			} else {
+				this.root = new FunctionNode<T>(length, initializer);
+			}
+			this.root.CheckInvariants();
+		}
+		
+		static T[] ToArray(IEnumerable<T> input)
+		{
+			T[] arr = input as T[];
+			return arr ?? input.ToArray();
+		}
+		
+		/// <summary>
+		/// Clones the rope.
+		/// This operation runs in linear time to the number of rope nodes touched since the last clone was created.
+		/// If you count the per-node cost to the operation modifying the rope (doing this doesn't increase the complexity of the modification operations);
+		/// the remainder of Clone() runs in O(1).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public Rope<T> Clone()
+		{
+			// The Publish() call actually modifies this rope instance; but this modification is thread-safe
+			// as long as the tree structure doesn't change during the operation.
+			root.Publish();
+			return new Rope<T>(root);
+		}
+		
+		object ICloneable.Clone()
+		{
+			return this.Clone();
+		}
+		
+		/// <summary>
+		/// Resets the rope to an empty list.
+		/// Runs in O(1).
+		/// </summary>
+		public void Clear()
+		{
+			root = RopeNode<T>.emptyRopeNode;
+			OnChanged();
+		}
+		
+		/// <summary>
+		/// Gets the length of the rope.
+		/// Runs in O(1).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public int Length {
+			get { return root.length; }
+		}
+		
+		/// <summary>
+		/// Gets the length of the rope.
+		/// Runs in O(1).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public int Count {
+			get { return root.length; }
+		}
+		
+		/// <summary>
+		/// Inserts another rope into this rope.
+		/// Runs in O(lg N + lg M), plus a per-node cost as if <c>newElements.Clone()</c> was called.
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
+		public void InsertRange(int index, Rope<T> newElements)
+		{
+			if (index < 0 || index > this.Length) {
+				throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + this.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			if (newElements == null)
+				throw new ArgumentNullException("newElements");
+			newElements.root.Publish();
+			root = root.Insert(index, newElements.root);
+			OnChanged();
+		}
+		
+		/// <summary>
+		/// Inserts new elemetns into this rope.
+		/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
+		public void InsertRange(int index, IEnumerable<T> newElements)
+		{
+			if (newElements == null)
+				throw new ArgumentNullException("newElements");
+			Rope<T> newElementsRope = newElements as Rope<T>;
+			if (newElementsRope != null) {
+				InsertRange(index, newElementsRope);
+			} else {
+				T[] arr = ToArray(newElements);
+				InsertRange(index, arr, 0, arr.Length);
+			}
+		}
+		
+		/// <summary>
+		/// Inserts new elements into this rope.
+		/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		/// <exception cref="ArgumentOutOfRangeException">index or length is outside the valid range.</exception>
+		public void InsertRange(int index, T[] array, int arrayIndex, int count)
+		{
+			if (index < 0 || index > this.Length) {
+				throw new ArgumentOutOfRangeException("index", index, "0 <= index <= " + this.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			VerifyArrayWithRange(array, arrayIndex, count);
+			if (count > 0) {
+				root = root.Insert(index, array, arrayIndex, count);
+				OnChanged();
+			}
+		}
+		
+		/// <summary>
+		/// Appends multiple elements to the end of this rope.
+		/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		public void AddRange(IEnumerable<T> newElements)
+		{
+			InsertRange(this.Length, newElements);
+		}
+		
+		/// <summary>
+		/// Appends another rope to the end of this rope.
+		/// Runs in O(lg N + lg M), plus a per-node cost as if <c>newElements.Clone()</c> was called.
+		/// </summary>
+		/// <exception cref="ArgumentNullException">newElements is null.</exception>
+		public void AddRange(Rope<T> newElements)
+		{
+			InsertRange(this.Length, newElements);
+		}
+		
+		/// <summary>
+		/// Appends new elements to the end of this rope.
+		/// Runs in O(lg N + M), where N is the length of this rope and M is the number of new elements.
+		/// </summary>
+		/// <exception cref="ArgumentNullException">array is null.</exception>
+		public void AddRange(T[] array, int arrayIndex, int count)
+		{
+			InsertRange(this.Length, array, arrayIndex, count);
+		}
+		
+		/// <summary>
+		/// Removes a range of elements from the rope.
+		/// Runs in O(lg N).
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		public void RemoveRange(int index, int count)
+		{
+			VerifyRange(index, count);
+			if (count > 0) {
+				root = root.RemoveRange(index, count);
+				OnChanged();
+			}
+		}
+		
+		/// <summary>
+		/// Copies a range of the specified array into the rope, overwriting existing elements.
+		/// Runs in O(lg N + M).
+		/// </summary>
+		public void SetRange(int index, T[] array, int arrayIndex, int count)
+		{
+			VerifyRange(index, count);
+			VerifyArrayWithRange(array, arrayIndex, count);
+			if (count > 0) {
+				root = root.StoreElements(index, array, arrayIndex, count);
+				OnChanged();
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new rope and initializes it with a part of this rope.
+		/// Runs in O(lg N) plus a per-node cost as if <c>this.Clone()</c> was called.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public Rope<T> GetRange(int index, int count)
+		{
+			VerifyRange(index, count);
+			Rope<T> newRope = Clone();
+			int endIndex = index + count;
+			newRope.RemoveRange(endIndex, newRope.Length - endIndex);
+			newRope.RemoveRange(0, index);
+			return newRope;
+		}
+		
+		/*
+		#region Equality
+		/// <summary>
+		/// Gets whether the two ropes have the same content.
+		/// Runs in O(N + M).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public bool Equals(Rope other)
+		{
+			if (other == null)
+				return false;
+			// quick detection for ropes that are clones of each other:
+			if (other.root == this.root)
+				return true;
+			if (other.Length != this.Length)
+				return false;
+			using (RopeTextReader a = new RopeTextReader(this, false)) {
+				using (RopeTextReader b = new RopeTextReader(other, false)) {
+					int charA, charB;
+					do {
+						charA = a.Read();
+						charB = b.Read();
+						if (charA != charB)
+							return false;
+					} while (charA != -1);
+					return true;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether two ropes have the same content.
+		/// Runs in O(N + M).
+		/// </summary>
+		public override bool Equals(object obj)
+		{
+			return Equals(obj as Rope);
+		}
+		
+		/// <summary>
+		/// Calculates the hash code of the rope's content.
+		/// Runs in O(N).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public override int GetHashCode()
+		{
+			int hashcode = 0;
+			using (RopeTextReader reader = new RopeTextReader(this, false)) {
+				unchecked {
+					int val;
+					while ((val = reader.Read()) != -1) {
+						hashcode = hashcode * 31 + val;
+					}
+				}
+			}
+			return hashcode;
+		}
+		#endregion
+		 */
+		
+		/// <summary>
+		/// Concatenates two ropes. The input ropes are not modified.
+		/// Runs in O(lg N + lg M).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
+		public static Rope<T> Concat(Rope<T> left, Rope<T> right)
+		{
+			if (left == null)
+				throw new ArgumentNullException("left");
+			if (right == null)
+				throw new ArgumentNullException("right");
+			left.root.Publish();
+			right.root.Publish();
+			return new Rope<T>(RopeNode<T>.Concat(left.root, right.root));
+		}
+		
+		/// <summary>
+		/// Concatenates multiple ropes. The input ropes are not modified.
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
+		public static Rope<T> Concat(params Rope<T>[] ropes)
+		{
+			if (ropes == null)
+				throw new ArgumentNullException("ropes");
+			Rope<T> result = new Rope<T>();
+			foreach (Rope<T> r in ropes)
+				result.AddRange(r);
+			return result;
+		}
+		
+		#region Caches / Changed event
+		internal struct RopeCacheEntry
+		{
+			internal readonly RopeNode<T> node;
+			internal readonly int nodeStartIndex;
+			
+			internal RopeCacheEntry(RopeNode<T> node, int nodeStartOffset)
+			{
+				this.node = node;
+				this.nodeStartIndex = nodeStartOffset;
+			}
+			
+			internal bool IsInside(int offset)
+			{
+				return offset >= nodeStartIndex && offset < nodeStartIndex + node.length;
+			}
+		}
+		
+		// cached pointer to 'last used node', used to speed up accesses by index that are close together
+		[NonSerialized]
+		volatile ImmutableStack<RopeCacheEntry> lastUsedNodeStack;
+		
+		internal void OnChanged()
+		{
+			lastUsedNodeStack = null;
+			
+			root.CheckInvariants();
+		}
+		#endregion
+		
+		#region GetChar / SetChar
+		/// <summary>
+		/// Gets/Sets a single character.
+		/// Runs in O(lg N) for random access. Sequential read-only access benefits from a special optimization and runs in amortized O(1).
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">Offset is outside the valid range (0 to Length-1).</exception>
+		/// <remarks>
+		/// The getter counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public T this[int index] {
+			get {
+				// use unsigned integers - this way negative values for index overflow and can be tested for with the same check
+				if (unchecked((uint)index >= (uint)this.Length)) {
+					throw new ArgumentOutOfRangeException("index", index, "0 <= index < " + this.Length.ToString(CultureInfo.InvariantCulture));
+				}
+				RopeCacheEntry entry = FindNodeUsingCache(index).PeekOrDefault();
+				return entry.node.contents[index - entry.nodeStartIndex];
+			}
+			set {
+				if (index < 0 || index >= this.Length) {
+					throw new ArgumentOutOfRangeException("index", index, "0 <= index < " + this.Length.ToString(CultureInfo.InvariantCulture));
+				}
+				root = root.SetElement(index, value);
+				OnChanged();
+				/* Here's a try at implementing the setter using the cached node stack (UNTESTED code!).
+				 * However I don't use the code because it's complicated and doesn't integrate correctly with change notifications.
+				 * Instead, I'll use the much easier to understand recursive solution.
+				 * Oh, and it also doesn't work correctly with function nodes.
+				ImmutableStack<RopeCacheEntry> nodeStack = FindNodeUsingCache(offset);
+				RopeCacheEntry entry = nodeStack.Peek();
+				if (!entry.node.isShared) {
+					entry.node.contents[offset - entry.nodeStartOffset] = value;
+					// missing: clear the caches except for the node stack cache (e.g. ToString() cache?)
+				} else {
+					RopeNode oldNode = entry.node;
+					RopeNode newNode = oldNode.Clone();
+					newNode.contents[offset - entry.nodeStartOffset] = value;
+					for (nodeStack = nodeStack.Pop(); !nodeStack.IsEmpty; nodeStack = nodeStack.Pop()) {
+						RopeNode parentNode = nodeStack.Peek().node;
+						RopeNode newParentNode = parentNode.CloneIfShared();
+						if (newParentNode.left == oldNode) {
+							newParentNode.left = newNode;
+						} else {
+							Debug.Assert(newParentNode.right == oldNode);
+							newParentNode.right = newNode;
+						}
+						if (parentNode == newParentNode) {
+							// we were able to change the existing node (it was not shared);
+							// there's no reason to go further upwards
+							ClearCacheOnModification();
+							return;
+						} else {
+							oldNode = parentNode;
+							newNode = newParentNode;
+						}
+					}
+					// we reached the root of the rope.
+					Debug.Assert(root == oldNode);
+					root = newNode;
+					ClearCacheOnModification();
+				}*/
+			}
+		}
+		
+		internal ImmutableStack<RopeCacheEntry> FindNodeUsingCache(int index)
+		{
+			Debug.Assert(index >= 0 && index < this.Length);
+			
+			// thread safety: fetch stack into local variable
+			ImmutableStack<RopeCacheEntry> stack = lastUsedNodeStack;
+			ImmutableStack<RopeCacheEntry> oldStack = stack;
+			
+			if (stack == null) {
+				stack = ImmutableStack<RopeCacheEntry>.Empty.Push(new RopeCacheEntry(root, 0));
+			}
+			while (!stack.PeekOrDefault().IsInside(index))
+				stack = stack.Pop();
+			while (true) {
+				RopeCacheEntry entry = stack.PeekOrDefault();
+				// check if we've reached a leaf or function node
+				if (entry.node.height == 0) {
+					if (entry.node.contents == null) {
+						// this is a function node - go down into its subtree
+						entry = new RopeCacheEntry(entry.node.GetContentNode(), entry.nodeStartIndex);
+						// entry is now guaranteed NOT to be another function node
+					}
+					if (entry.node.contents != null) {
+						// this is a node containing actual content, so we're done
+						break;
+					}
+				}
+				// go down towards leaves
+				if (index - entry.nodeStartIndex >= entry.node.left.length)
+					stack = stack.Push(new RopeCacheEntry(entry.node.right, entry.nodeStartIndex + entry.node.left.length));
+				else
+					stack = stack.Push(new RopeCacheEntry(entry.node.left, entry.nodeStartIndex));
+			}
+			
+			// write back stack to volatile cache variable
+			// (in multithreaded access, it doesn't matter which of the threads wins - it's just a cache)
+			if (oldStack != stack) {
+				// no need to write when we the cache variable didn't change
+				lastUsedNodeStack = stack;
+			}
+			
+			// this method guarantees that it finds a leaf node
+			Debug.Assert(stack.Peek().node.contents != null);
+			return stack;
+		}
+		#endregion
+		
+		#region ToString / WriteTo
+		internal void VerifyRange(int startIndex, int length)
+		{
+			if (startIndex < 0 || startIndex > this.Length) {
+				throw new ArgumentOutOfRangeException("startIndex", startIndex, "0 <= startIndex <= " + this.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			if (length < 0 || startIndex + length > this.Length) {
+				throw new ArgumentOutOfRangeException("length", length, "0 <= length, startIndex(" + startIndex + ")+length <= " + this.Length.ToString(CultureInfo.InvariantCulture));
+			}
+		}
+		
+		internal static void VerifyArrayWithRange(T[] array, int arrayIndex, int count)
+		{
+			if (array == null)
+				throw new ArgumentNullException("array");
+			if (arrayIndex < 0 || arrayIndex > array.Length) {
+				throw new ArgumentOutOfRangeException("startIndex", arrayIndex, "0 <= arrayIndex <= " + array.Length.ToString(CultureInfo.InvariantCulture));
+			}
+			if (count < 0 || arrayIndex + count > array.Length) {
+				throw new ArgumentOutOfRangeException("count", count, "0 <= length, arrayIndex(" + arrayIndex + ")+count <= " + array.Length.ToString(CultureInfo.InvariantCulture));
+			}
+		}
+		
+		/// <summary>
+		/// Creates a string from the rope. Runs in O(N).
+		/// </summary>
+		/// <returns>A string consisting of all elements in the rope as comma-separated list in {}.
+		/// As a special case, Rope&lt;char&gt; will return its contents as string without any additional separators or braces,
+		/// so it can be used like StringBuilder.ToString().</returns>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public override string ToString()
+		{
+			Rope<char> charRope = this as Rope<char>;
+			if (charRope != null) {
+				return charRope.ToString(0, this.Length);
+			} else {
+				StringBuilder b = new StringBuilder();
+				foreach (T element in this) {
+					if (b.Length == 0)
+						b.Append('{');
+					else
+						b.Append(", ");
+					b.Append(element.ToString());
+				}
+				b.Append('}');
+				return b.ToString();
+			}
+		}
+		
+		internal string GetTreeAsString()
+		{
+			#if DEBUG
+			return root.GetTreeAsString();
+			#else
+			return "Not available in release build.";
+			#endif
+		}
+		#endregion
+		
+		bool ICollection<T>.IsReadOnly {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Finds the first occurance of item.
+		/// Runs in O(N).
+		/// </summary>
+		/// <returns>The index of the first occurance of item, or -1 if it cannot be found.</returns>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public int IndexOf(T item)
+		{
+			return IndexOf(item, 0, this.Length);
+		}
+		
+		/// <summary>
+		/// Gets the index of the first occurrence the specified item.
+		/// </summary>
+		/// <param name="item">Item to search for.</param>
+		/// <param name="startIndex">Start index of the search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The first index where the item was found; or -1 if no occurrence was found.</returns>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public int IndexOf(T item, int startIndex, int count)
+		{
+			VerifyRange(startIndex, count);
+			
+			while (count > 0) {
+				var entry = FindNodeUsingCache(startIndex).PeekOrDefault();
+				T[] contents = entry.node.contents;
+				int startWithinNode = startIndex - entry.nodeStartIndex;
+				int nodeLength = Math.Min(entry.node.length, startWithinNode + count);
+				int r = Array.IndexOf(contents, item, startWithinNode, nodeLength - startWithinNode);
+				if (r >= 0)
+					return entry.nodeStartIndex + r;
+				count -= nodeLength - startWithinNode;
+				startIndex = entry.nodeStartIndex + nodeLength;
+			}
+			return -1;
+		}
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the specified item in this rope.
+		/// </summary>
+		public int LastIndexOf(T item)
+		{
+			return LastIndexOf(item, 0, this.Length);
+		}
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the specified item in this rope.
+		/// </summary>
+		/// <param name="item">The search item</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The last index where the item was found; or -1 if no occurrence was found.</returns>
+		/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
+		/// This is different than the meaning of the parameters on Array.LastIndexOf!</remarks>
+		public int LastIndexOf(T item, int startIndex, int count)
+		{
+			VerifyRange(startIndex, count);
+			
+			var comparer = EqualityComparer<T>.Default;
+			for (int i = startIndex + count - 1; i >= startIndex; i--) {
+				if (comparer.Equals(this[i], item))
+					return i;
+			}
+			return -1;
+		}
+		
+		/// <summary>
+		/// Inserts the item at the specified index in the rope.
+		/// Runs in O(lg N).
+		/// </summary>
+		public void Insert(int index, T item)
+		{
+			InsertRange(index, new[] { item }, 0, 1);
+		}
+		
+		/// <summary>
+		/// Removes a single item from the rope.
+		/// Runs in O(lg N).
+		/// </summary>
+		public void RemoveAt(int index)
+		{
+			RemoveRange(index, 1);
+		}
+		
+		/// <summary>
+		/// Appends the item at the end of the rope.
+		/// Runs in O(lg N).
+		/// </summary>
+		public void Add(T item)
+		{
+			InsertRange(this.Length, new[] { item }, 0, 1);
+		}
+		
+		/// <summary>
+		/// Searches the item in the rope.
+		/// Runs in O(N).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public bool Contains(T item)
+		{
+			return IndexOf(item) >= 0;
+		}
+		
+		/// <summary>
+		/// Copies the whole content of the rope into the specified array.
+		/// Runs in O(N).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public void CopyTo(T[] array, int arrayIndex)
+		{
+			CopyTo(0, array, arrayIndex, this.Length);
+		}
+		
+		/// <summary>
+		/// Copies the a part of the rope into the specified array.
+		/// Runs in O(lg N + M).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public void CopyTo(int index, T[] array, int arrayIndex, int count)
+		{
+			VerifyRange(index, count);
+			VerifyArrayWithRange(array, arrayIndex, count);
+			this.root.CopyTo(index, array, arrayIndex, count);
+		}
+		
+		/// <summary>
+		/// Removes the first occurance of an item from the rope.
+		/// Runs in O(N).
+		/// </summary>
+		public bool Remove(T item)
+		{
+			int index = IndexOf(item);
+			if (index >= 0) {
+				RemoveAt(index);
+				return true;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Retrieves an enumerator to iterate through the rope.
+		/// The enumerator will reflect the state of the rope from the GetEnumerator() call, further modifications
+		/// to the rope will not be visible to the enumerator.
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public IEnumerator<T> GetEnumerator()
+		{
+			this.root.Publish();
+			return Enumerate(root);
+		}
+		
+		/// <summary>
+		/// Creates an array and copies the contents of the rope into it.
+		/// Runs in O(N).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public T[] ToArray()
+		{
+			T[] arr = new T[this.Length];
+			this.root.CopyTo(0, arr, 0, arr.Length);
+			return arr;
+		}
+		
+		/// <summary>
+		/// Creates an array and copies the contents of the rope into it.
+		/// Runs in O(N).
+		/// </summary>
+		/// <remarks>
+		/// This method counts as a read access and may be called concurrently to other read accesses.
+		/// </remarks>
+		public T[] ToArray(int startIndex, int count)
+		{
+			VerifyRange(startIndex, count);
+			T[] arr = new T[count];
+			CopyTo(startIndex, arr, 0, count);
+			return arr;
+		}
+		
+		static IEnumerator<T> Enumerate(RopeNode<T> node)
+		{
+			Stack<RopeNode<T>> stack = new Stack<RopeNode<T>>();
+			while (node != null) {
+				// go to leftmost node, pushing the right parts that we'll have to visit later
+				while (node.contents == null) {
+					if (node.height == 0) {
+						// go down into function nodes
+						node = node.GetContentNode();
+						continue;
+					}
+					Debug.Assert(node.right != null);
+					stack.Push(node.right);
+					node = node.left;
+				}
+				// yield contents of leaf node
+				for (int i = 0; i < node.length; i++) {
+					yield return node.contents[i];
+				}
+				// go up to the next node not visited yet
+				if (stack.Count > 0)
+					node = stack.Pop();
+				else
+					node = null;
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.GetEnumerator();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RopeNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RopeNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RopeNode.cs	(revision 11807)
@@ -0,0 +1,620 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Runtime.Serialization;
+
+using System.Text;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	// Class used to represent a node in the tree.
+	// There are three types of nodes:
+	// Concat nodes: height>0, left!=null, right!=null, contents==null
+	// Leaf nodes: height==0, left==null, right==null, contents!=null
+	// Function nodes: height==0, left==null, right==null, contents==null, are of type FunctionNode<T>
+	
+	[Serializable]
+	class RopeNode<T>
+	{
+		internal const int NodeSize = 256;
+		
+		internal static readonly RopeNode<T> emptyRopeNode = new RopeNode<T> { isShared = true, contents = new T[RopeNode<T>.NodeSize] };
+		
+		// Fields for pointers to sub-nodes. Only non-null for concat nodes (height>=1)
+		internal RopeNode<T> left, right;
+		internal volatile bool isShared; // specifies whether this node is shared between multiple ropes
+		// the total length of all text in this subtree
+		internal int length;
+		// the height of this subtree: 0 for leaf nodes; 1+max(left.height,right.height) for concat nodes
+		internal byte height;
+		
+		// The character data. Only non-null for leaf nodes (height=0) that aren't function nodes.
+		internal T[] contents;
+		
+		internal int Balance {
+			get { return right.height - left.height; }
+		}
+		
+		[Conditional("DATACONSISTENCYTEST")]
+		internal void CheckInvariants()
+		{
+			if (height == 0) {
+				Debug.Assert(left == null && right == null);
+				if (contents == null) {
+					Debug.Assert(this is FunctionNode<T>);
+					Debug.Assert(length > 0);
+					Debug.Assert(isShared);
+				} else {
+					Debug.Assert(contents != null && contents.Length == NodeSize);
+					Debug.Assert(length >= 0 && length <= NodeSize);
+				}
+			} else {
+				Debug.Assert(left != null && right != null);
+				Debug.Assert(contents == null);
+				Debug.Assert(length == left.length + right.length);
+				Debug.Assert(height == 1 + Math.Max(left.height, right.height));
+				Debug.Assert(Math.Abs(this.Balance) <= 1);
+				
+				// this is an additional invariant that forces the tree to combine small leafs to prevent excessive memory usage:
+				Debug.Assert(length > NodeSize);
+				// note that this invariant ensures that all nodes except for the empty rope's single node have at least length 1
+				
+				if (isShared)
+					Debug.Assert(left.isShared && right.isShared);
+				left.CheckInvariants();
+				right.CheckInvariants();
+			}
+		}
+		
+		internal RopeNode<T> Clone()
+		{
+			if (height == 0) {
+				// If a function node needs cloning, we'll evaluate it.
+				if (contents == null)
+					return GetContentNode().Clone();
+				T[] newContents = new T[NodeSize];
+				contents.CopyTo(newContents, 0);
+				return new RopeNode<T> {
+					length = this.length,
+					contents = newContents
+				};
+			} else {
+				return new RopeNode<T> {
+					left = this.left,
+					right = this.right,
+					length = this.length,
+					height = this.height
+				};
+			}
+		}
+		
+		internal RopeNode<T> CloneIfShared()
+		{
+			if (isShared)
+				return Clone();
+			else
+				return this;
+		}
+		
+		internal void Publish()
+		{
+			if (!isShared) {
+				if (left != null)
+					left.Publish();
+				if (right != null)
+					right.Publish();
+				// it's important that isShared=true is set at the end:
+				// Publish() must not return until the whole subtree is marked as shared, even when
+				// Publish() is called concurrently.
+				isShared = true;
+			}
+		}
+		
+		internal static RopeNode<T> CreateFromArray(T[] arr, int index, int length)
+		{
+			if (length == 0) {
+				return emptyRopeNode;
+			}
+			RopeNode<T> node = CreateNodes(length);
+			return node.StoreElements(0, arr, index, length);
+		}
+		
+		internal static RopeNode<T> CreateNodes(int totalLength)
+		{
+			int leafCount = (totalLength + NodeSize - 1) / NodeSize;
+			return CreateNodes(leafCount, totalLength);
+		}
+		
+		static RopeNode<T> CreateNodes(int leafCount, int totalLength)
+		{
+			Debug.Assert(leafCount > 0);
+			Debug.Assert(totalLength > 0);
+			RopeNode<T> result = new RopeNode<T>();
+			result.length = totalLength;
+			if (leafCount == 1) {
+				result.contents = new T[NodeSize];
+			} else {
+				int rightSide = leafCount / 2;
+				int leftSide = leafCount - rightSide;
+				int leftLength = leftSide * NodeSize;
+				result.left = CreateNodes(leftSide, leftLength);
+				result.right = CreateNodes(rightSide, totalLength - leftLength);
+				result.height = (byte)(1 + Math.Max(result.left.height, result.right.height));
+			}
+			return result;
+		}
+		
+		/// <summary>
+		/// Balances this node and recomputes the 'height' field.
+		/// This method assumes that the children of this node are already balanced and have an up-to-date 'height' value.
+		/// </summary>
+		internal void Rebalance()
+		{
+			// Rebalance() shouldn't be called on shared nodes - it's only called after modifications!
+			Debug.Assert(!isShared);
+			// leaf nodes are always balanced (we don't use 'height' to detect leaf nodes here
+			// because Balance is supposed to recompute the height).
+			if (left == null)
+				return;
+			
+			// ensure we didn't miss a MergeIfPossible step
+			Debug.Assert(this.length > NodeSize);
+			
+			// We need to loop until it's balanced. Rotations might cause two small leaves to combine to a larger one,
+			// which changes the height and might mean we need additional balancing steps.
+			while (Math.Abs(this.Balance) > 1) {
+				// AVL balancing
+				// note: because we don't care about the identity of concat nodes, this works a little different than usual
+				// tree rotations: in our implementation, the "this" node will stay at the top, only its children are rearranged
+				if (this.Balance > 1) {
+					if (right.Balance < 0) {
+						right = right.CloneIfShared();
+						right.RotateRight();
+					}
+					this.RotateLeft();
+					// If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the left node; so rebalance that.
+					this.left.Rebalance();
+				} else if (this.Balance < -1) {
+					if (left.Balance > 0) {
+						left = left.CloneIfShared();
+						left.RotateLeft();
+					}
+					this.RotateRight();
+					// If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the right node; so rebalance that.
+					this.right.Rebalance();
+				}
+			}
+			
+			Debug.Assert(Math.Abs(this.Balance) <= 1);
+			this.height = (byte)(1 + Math.Max(left.height, right.height));
+		}
+		
+		void RotateLeft()
+		{
+			Debug.Assert(!isShared);
+			
+			/* Rotate tree to the left
+			 * 
+			 *       this               this
+			 *       /  \               /  \
+			 *      A   right   ===>  left  C
+			 *           / \          / \
+			 *          B   C        A   B
+			 */
+			RopeNode<T> a = left;
+			RopeNode<T> b = right.left;
+			RopeNode<T> c = right.right;
+			// reuse right concat node, if possible
+			this.left = right.isShared ? new RopeNode<T>() : right;
+			this.left.left = a;
+			this.left.right = b;
+			this.left.length = a.length + b.length;
+			this.left.height = (byte)(1 + Math.Max(a.height, b.height));
+			this.right = c;
+			
+			this.left.MergeIfPossible();
+		}
+		
+		void RotateRight()
+		{
+			Debug.Assert(!isShared);
+			
+			/* Rotate tree to the right
+			 * 
+			 *       this             this
+			 *       /  \             /  \
+			 *     left  C   ===>    A  right
+			 *     / \                   /  \
+			 *    A   B                 B    C
+			 */
+			RopeNode<T> a = left.left;
+			RopeNode<T> b = left.right;
+			RopeNode<T> c = right;
+			// reuse left concat node, if possible
+			this.right = left.isShared ? new RopeNode<T>() : left;
+			this.right.left = b;
+			this.right.right = c;
+			this.right.length = b.length + c.length;
+			this.right.height = (byte)(1 + Math.Max(b.height, c.height));
+			this.left = a;
+			
+			this.right.MergeIfPossible();
+		}
+		
+		void MergeIfPossible()
+		{
+			Debug.Assert(!isShared);
+			
+			if (this.length <= NodeSize) {
+				// Convert this concat node to leaf node.
+				// We know left and right cannot be concat nodes (they would have merged already),
+				// but they could be function nodes.
+				this.height = 0;
+				int lengthOnLeftSide = this.left.length;
+				if (this.left.isShared) {
+					this.contents = new T[NodeSize];
+					left.CopyTo(0, this.contents, 0, lengthOnLeftSide);
+				} else {
+					// must be a leaf node: function nodes are always marked shared
+					Debug.Assert(this.left.contents != null);
+					// steal buffer from left side
+					this.contents = this.left.contents;
+					#if DEBUG
+					// In debug builds, explicitly mark left node as 'damaged' - but no one else should be using it
+					// because it's not shared.
+					this.left.contents = Empty<T>.Array;
+					#endif
+				}
+				this.left = null;
+				right.CopyTo(0, this.contents, lengthOnLeftSide, this.right.length);
+				this.right = null;
+			}
+		}
+		
+		/// <summary>
+		/// Copies from the array to this node.
+		/// </summary>
+		internal RopeNode<T> StoreElements(int index, T[] array, int arrayIndex, int count)
+		{
+			RopeNode<T> result = this.CloneIfShared();
+			// result cannot be function node after a call to Clone()
+			if (result.height == 0) {
+				// leaf node:
+				Array.Copy(array, arrayIndex, result.contents, index, count);
+			} else {
+				// concat node:
+				if (index + count <= result.left.length) {
+					result.left = result.left.StoreElements(index, array, arrayIndex, count);
+				} else if (index >= this.left.length) {
+					result.right = result.right.StoreElements(index - result.left.length, array, arrayIndex, count);
+				} else {
+					int amountInLeft = result.left.length - index;
+					result.left = result.left.StoreElements(index, array, arrayIndex, amountInLeft);
+					result.right = result.right.StoreElements(0, array, arrayIndex + amountInLeft, count - amountInLeft);
+				}
+				result.Rebalance(); // tree layout might have changed if function nodes were replaced with their content
+			}
+			return result;
+		}
+		
+		/// <summary>
+		/// Copies from this node to the array.
+		/// </summary>
+		internal void CopyTo(int index, T[] array, int arrayIndex, int count)
+		{
+			if (height == 0) {
+				if (this.contents == null) {
+					// function node
+					this.GetContentNode().CopyTo(index, array, arrayIndex, count);
+				} else {
+					// leaf node
+					Array.Copy(this.contents, index, array, arrayIndex, count);
+				}
+			} else {
+				// concat node
+				if (index + count <= this.left.length) {
+					this.left.CopyTo(index, array, arrayIndex, count);
+				} else if (index >= this.left.length) {
+					this.right.CopyTo(index - this.left.length, array, arrayIndex, count);
+				} else {
+					int amountInLeft = this.left.length - index;
+					this.left.CopyTo(index, array, arrayIndex, amountInLeft);
+					this.right.CopyTo(0, array, arrayIndex + amountInLeft, count - amountInLeft);
+				}
+			}
+		}
+		
+		internal RopeNode<T> SetElement(int offset, T value)
+		{
+			RopeNode<T> result = CloneIfShared();
+			// result of CloneIfShared() is leaf or concat node
+			if (result.height == 0) {
+				result.contents[offset] = value;
+			} else {
+				if (offset < result.left.length) {
+					result.left = result.left.SetElement(offset, value);
+				} else {
+					result.right = result.right.SetElement(offset - result.left.length, value);
+				}
+				result.Rebalance(); // tree layout might have changed if function nodes were replaced with their content
+			}
+			return result;
+		}
+		
+		internal static RopeNode<T> Concat(RopeNode<T> left, RopeNode<T> right)
+		{
+			if (left.length == 0)
+				return right;
+			if (right.length == 0)
+				return left;
+			
+			if (left.length + right.length <= NodeSize) {
+				left = left.CloneIfShared();
+				// left is guaranteed to be leaf node after cloning:
+				// - it cannot be function node (due to clone)
+				// - it cannot be concat node (too short)
+				right.CopyTo(0, left.contents, left.length, right.length);
+				left.length += right.length;
+				return left;
+			} else {
+				RopeNode<T> concatNode = new RopeNode<T>();
+				concatNode.left = left;
+				concatNode.right = right;
+				concatNode.length = left.length + right.length;
+				concatNode.Rebalance();
+				return concatNode;
+			}
+		}
+		
+		/// <summary>
+		/// Splits this leaf node at offset and returns a new node with the part of the text after offset.
+		/// </summary>
+		RopeNode<T> SplitAfter(int offset)
+		{
+			Debug.Assert(!isShared && height == 0 && contents != null);
+			RopeNode<T> newPart = new RopeNode<T>();
+			newPart.contents = new T[NodeSize];
+			newPart.length = this.length - offset;
+			Array.Copy(this.contents, offset, newPart.contents, 0, newPart.length);
+			this.length = offset;
+			return newPart;
+		}
+		
+		internal RopeNode<T> Insert(int offset, RopeNode<T> newElements)
+		{
+			if (offset == 0) {
+				return Concat(newElements, this);
+			} else if (offset == this.length) {
+				return Concat(this, newElements);
+			}
+			
+			// first clone this node (converts function nodes to leaf or concat nodes)
+			RopeNode<T> result = CloneIfShared();
+			if (result.height == 0) {
+				// leaf node: we'll need to split this node
+				RopeNode<T> left = result;
+				RopeNode<T> right = left.SplitAfter(offset);
+				return Concat(Concat(left, newElements), right);
+			} else {
+				// concat node
+				if (offset < result.left.length) {
+					result.left = result.left.Insert(offset, newElements);
+				} else {
+					result.right = result.right.Insert(offset - result.left.length, newElements);
+				}
+				result.length += newElements.length;
+				result.Rebalance();
+				return result;
+			}
+		}
+		
+		internal RopeNode<T> Insert(int offset, T[] array, int arrayIndex, int count)
+		{
+			Debug.Assert(count > 0);
+			
+			if (this.length + count < RopeNode<char>.NodeSize) {
+				RopeNode<T> result = CloneIfShared();
+				// result must be leaf node (Clone never returns function nodes, too short for concat node)
+				int lengthAfterOffset = result.length - offset;
+				T[] resultContents = result.contents;
+				for (int i = lengthAfterOffset; i >= 0; i--) {
+					resultContents[i + offset + count] = resultContents[i + offset];
+				}
+				Array.Copy(array, arrayIndex, resultContents, offset, count);
+				result.length += count;
+				return result;
+			} else if (height == 0) {
+				// TODO: implement this more efficiently?
+				return Insert(offset, CreateFromArray(array, arrayIndex, count));
+			} else {
+				// this is a concat node (both leafs and function nodes are handled by the case above)
+				RopeNode<T> result = CloneIfShared();
+				if (offset < result.left.length) {
+					result.left = result.left.Insert(offset, array, arrayIndex, count);
+				} else {
+					result.right = result.right.Insert(offset - result.left.length, array, arrayIndex, count);
+				}
+				result.length += count;
+				result.Rebalance();
+				return result;
+			}
+		}
+		
+		internal RopeNode<T> RemoveRange(int index, int count)
+		{
+			Debug.Assert(count > 0);
+			
+			// produce empty node when one node is deleted completely
+			if (index == 0 && count == this.length)
+				return emptyRopeNode;
+			
+			int endIndex = index + count;
+			RopeNode<T> result = CloneIfShared(); // convert function node to concat/leaf
+			if (result.height == 0) {
+				int remainingAfterEnd = result.length - endIndex;
+				for (int i = 0; i < remainingAfterEnd; i++) {
+					result.contents[index + i] = result.contents[endIndex + i];
+				}
+				result.length -= count;
+			} else {
+				if (endIndex <= result.left.length) {
+					// deletion is only within the left part
+					result.left = result.left.RemoveRange(index, count);
+				} else if (index >= result.left.length) {
+					// deletion is only within the right part
+					result.right = result.right.RemoveRange(index - result.left.length, count);
+				} else {
+					// deletion overlaps both parts
+					int deletionAmountOnLeftSide = result.left.length - index;
+					result.left = result.left.RemoveRange(index, deletionAmountOnLeftSide);
+					result.right = result.right.RemoveRange(0, count - deletionAmountOnLeftSide);
+				}
+				// The deletion might have introduced empty nodes. Those must be removed.
+				if (result.left.length == 0)
+					return result.right;
+				if (result.right.length == 0)
+					return result.left;
+				
+				result.length -= count;
+				result.MergeIfPossible();
+				result.Rebalance();
+			}
+			return result;
+		}
+		
+		#region Debug Output
+		#if DEBUG
+		internal virtual void AppendTreeToString(StringBuilder b, int indent)
+		{
+			b.AppendLine(ToString());
+			indent += 2;
+			if (left != null) {
+				b.Append(' ', indent);
+				b.Append("L: ");
+				left.AppendTreeToString(b, indent);
+			}
+			if (right != null) {
+				b.Append(' ', indent);
+				b.Append("R: ");
+				right.AppendTreeToString(b, indent);
+			}
+		}
+		
+		public override string ToString()
+		{
+			if (contents != null) {
+				char[] charContents = contents as char[];
+				if (charContents != null)
+					return "[Leaf length=" + length + ", isShared=" + isShared + ", text=\"" + new string(charContents, 0, length) + "\"]";
+				else
+					return "[Leaf length=" + length + ", isShared=" + isShared + "\"]";
+			} else {
+				return "[Concat length=" + length + ", isShared=" + isShared + ", height=" + height + ", Balance=" + this.Balance + "]";
+			}
+		}
+		
+		internal string GetTreeAsString()
+		{
+			StringBuilder b = new StringBuilder();
+			AppendTreeToString(b, 0);
+			return b.ToString();
+		}
+		#endif
+		#endregion
+		
+		/// <summary>
+		/// Gets the root node of the subtree from a lazily evaluated function node.
+		/// Such nodes are always marked as shared.
+		/// GetContentNode() will return either a Concat or Leaf node, never another FunctionNode.
+		/// </summary>
+		internal virtual RopeNode<T> GetContentNode()
+		{
+			throw new InvalidOperationException("Called GetContentNode() on non-FunctionNode.");
+		}
+	}
+	
+	sealed class FunctionNode<T> : RopeNode<T>
+	{
+		Func<Rope<T>> initializer;
+		RopeNode<T> cachedResults;
+		
+		public FunctionNode(int length, Func<Rope<T>> initializer)
+		{
+			Debug.Assert(length > 0);
+			Debug.Assert(initializer != null);
+			
+			this.length = length;
+			this.initializer = initializer;
+			// Function nodes are immediately shared, but cannot be cloned.
+			// This ensures we evaluate every initializer only once.
+			this.isShared = true;
+		}
+		
+		internal override RopeNode<T> GetContentNode()
+		{
+			lock (this) {
+				if (this.cachedResults == null) {
+					if (this.initializer == null)
+						throw new InvalidOperationException("Trying to load this node recursively; or: a previous call to a rope initializer failed.");
+					Func<Rope<T>> initializerCopy = this.initializer;
+					this.initializer = null;
+					Rope<T> resultRope = initializerCopy();
+					if (resultRope == null)
+						throw new InvalidOperationException("Rope initializer returned null.");
+					RopeNode<T> resultNode = resultRope.root;
+					resultNode.Publish(); // result is shared between returned rope and the rope containing this function node
+					if (resultNode.length != this.length)
+						throw new InvalidOperationException("Rope initializer returned rope with incorrect length.");
+					if (resultNode.height == 0 && resultNode.contents == null) {
+						// ResultNode is another function node.
+						// We want to guarantee that GetContentNode() never returns function nodes, so we have to
+						// go down further in the tree.
+						this.cachedResults = resultNode.GetContentNode();
+					} else {
+						this.cachedResults = resultNode;
+					}
+				}
+				return this.cachedResults;
+			}
+		}
+		
+		#if DEBUG
+		internal override void AppendTreeToString(StringBuilder b, int indent)
+		{
+			RopeNode<T> resultNode;
+			lock (this) {
+				b.AppendLine(ToString());
+				resultNode = cachedResults;
+			}
+			indent += 2;
+			if (resultNode != null) {
+				b.Append(' ', indent);
+				b.Append("C: ");
+				resultNode.AppendTreeToString(b, indent);
+			}
+		}
+		
+		public override string ToString()
+		{
+			return "[FunctionNode length=" + length + " initializerRan=" + (initializer == null) + "]";
+		}
+		#endif
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RopeTextReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RopeTextReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/RopeTextReader.cs	(revision 11807)
@@ -0,0 +1,120 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// TextReader implementation that reads text from a rope.
+	/// </summary>
+	public sealed class RopeTextReader : TextReader
+	{
+		Stack<RopeNode<char>> stack = new Stack<RopeNode<char>>();
+		RopeNode<char> currentNode;
+		int indexInsideNode;
+		
+		/// <summary>
+		/// Creates a new RopeTextReader.
+		/// Internally, this method creates a Clone of the rope; so the text reader will always read through the old
+		/// version of the rope if it is modified. <seealso cref="Rope{T}.Clone()"/>
+		/// </summary>
+		public RopeTextReader(Rope<char> rope)
+		{
+			if (rope == null)
+				throw new ArgumentNullException("rope");
+			
+			// We force the user to iterate through a clone of the rope to keep the API contract of RopeTextReader simple
+			// (what happens when a rope is modified while iterating through it?)
+			rope.root.Publish();
+			
+			// special case for the empty rope:
+			// leave currentNode initialized to null (RopeTextReader doesn't support empty nodes)
+			if (rope.Length != 0) {
+				currentNode = rope.root;
+				GoToLeftMostLeaf();
+			}
+		}
+		
+		void GoToLeftMostLeaf()
+		{
+			while (currentNode.contents == null) {
+				if (currentNode.height == 0) {
+					// this is a function node - move to its contained rope
+					currentNode = currentNode.GetContentNode();
+					continue;
+				}
+				Debug.Assert(currentNode.right != null);
+				stack.Push(currentNode.right);
+				currentNode = currentNode.left;
+			}
+			Debug.Assert(currentNode.height == 0);
+		}
+		
+		/// <inheritdoc/>
+		public override int Peek()
+		{
+			if (currentNode == null)
+				return -1;
+			return currentNode.contents[indexInsideNode];
+		}
+		
+		/// <inheritdoc/>
+		public override int Read()
+		{
+			if (currentNode == null)
+				return -1;
+			char result = currentNode.contents[indexInsideNode++];
+			if (indexInsideNode >= currentNode.length)
+				GoToNextNode();
+			return result;
+		}
+		
+		void GoToNextNode()
+		{
+			if (stack.Count == 0) {
+				currentNode = null;
+			} else {
+				indexInsideNode = 0;
+				currentNode = stack.Pop();
+				GoToLeftMostLeaf();
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override int Read(char[] buffer, int index, int count)
+		{
+			if (currentNode == null)
+				return 0;
+			int amountInCurrentNode = currentNode.length - indexInsideNode;
+			if (count < amountInCurrentNode) {
+				Array.Copy(currentNode.contents, indexInsideNode, buffer, index, count);
+				indexInsideNode += count;
+				return count;
+			} else {
+				// read to end of current node
+				Array.Copy(currentNode.contents, indexInsideNode, buffer, index, amountInCurrentNode);
+				GoToNextNode();
+				return amountInCurrentNode;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/StringSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/StringSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/StringSegment.cs	(revision 11807)
@@ -0,0 +1,122 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Represents a string with a segment.
+	/// Similar to System.ArraySegment&lt;T&gt;, but for strings instead of arrays.
+	/// </summary>
+	public struct StringSegment : IEquatable<StringSegment>
+	{
+		readonly string text;
+		readonly int offset;
+		readonly int count;
+		
+		/// <summary>
+		/// Creates a new StringSegment.
+		/// </summary>
+		public StringSegment(string text, int offset, int count)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (offset < 0 || offset > text.Length)
+				throw new ArgumentOutOfRangeException("offset");
+			if (offset + count > text.Length)
+				throw new ArgumentOutOfRangeException("count");
+			this.text = text;
+			this.offset = offset;
+			this.count = count;
+		}
+		
+		/// <summary>
+		/// Creates a new StringSegment.
+		/// </summary>
+		public StringSegment(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+			this.offset = 0;
+			this.count = text.Length;
+		}
+		
+		/// <summary>
+		/// Gets the string used for this segment.
+		/// </summary>
+		public string Text {
+			get { return text; }
+		}
+		
+		/// <summary>
+		/// Gets the start offset of the segment with the text.
+		/// </summary>
+		public int Offset {
+			get { return offset; }
+		}
+		
+		/// <summary>
+		/// Gets the length of the segment.
+		/// </summary>
+		public int Count {
+			get { return count; }
+		}
+		
+		#region Equals and GetHashCode implementation
+		/// <inheritdoc/>
+		public override bool Equals(object obj)
+		{
+			if (obj is StringSegment)
+				return Equals((StringSegment)obj); // use Equals method below
+			else
+				return false;
+		}
+		
+		/// <inheritdoc/>
+		public bool Equals(StringSegment other)
+		{
+			// add comparisions for all members here
+			return object.ReferenceEquals(this.text, other.text) && offset == other.offset && count == other.count;
+		}
+		
+		/// <inheritdoc/>
+		public override int GetHashCode()
+		{
+			return text.GetHashCode() ^ offset ^ count;
+		}
+		
+		/// <summary>
+		/// Equality operator.
+		/// </summary>
+		public static bool operator ==(StringSegment left, StringSegment right)
+		{
+			return left.Equals(right);
+		}
+		
+		/// <summary>
+		/// Inequality operator.
+		/// </summary>
+		public static bool operator !=(StringSegment left, StringSegment right)
+		{
+			return !left.Equals(right);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/TextFormatterFactory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/TextFormatterFactory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/TextFormatterFactory.cs	(revision 11807)
@@ -0,0 +1,143 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.Reflection;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Media;
+using System.Windows.Media.TextFormatting;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+	/// </summary>
+	static class TextFormatterFactory
+	{
+		#if !DOTNET4
+		readonly static DependencyProperty TextFormattingModeProperty;
+		
+		static TextFormatterFactory()
+		{
+			Assembly presentationFramework = typeof(FrameworkElement).Assembly;
+			Type textOptionsType = presentationFramework.GetType("System.Windows.Media.TextOptions", false);
+			if (textOptionsType != null) {
+				TextFormattingModeProperty = textOptionsType.GetField("TextFormattingModeProperty").GetValue(null) as DependencyProperty;
+			}
+		}
+		#endif
+		
+		/// <summary>
+		/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+		/// </summary>
+		public static TextFormatter Create(DependencyObject owner)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			#if DOTNET4
+			return TextFormatter.Create(TextOptions.GetTextFormattingMode(owner));
+			#else
+			if (TextFormattingModeProperty != null) {
+				object formattingMode = owner.GetValue(TextFormattingModeProperty);
+				return (TextFormatter)typeof(TextFormatter).InvokeMember(
+					"Create",
+					BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
+					null, null,
+					new object[] { formattingMode },
+					CultureInfo.InvariantCulture);
+			} else {
+				return TextFormatter.Create();
+			}
+			#endif
+		}
+		
+		/// <summary>
+		/// Returns whether the specified dependency property affects the text formatter creation.
+		/// Controls should re-create their text formatter for such property changes.
+		/// </summary>
+		public static bool PropertyChangeAffectsTextFormatter(DependencyProperty dp)
+		{
+			#if DOTNET4
+			return dp == TextOptions.TextFormattingModeProperty;
+			#else
+			return dp == TextFormattingModeProperty && TextFormattingModeProperty != null;
+			#endif
+		}
+		
+		/// <summary>
+		/// Creates formatted text.
+		/// </summary>
+		/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
+		/// <param name="text">The text.</param>
+		/// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param>
+		/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
+		/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
+		/// <returns>A FormattedText object using the specified settings.</returns>
+		public static FormattedText CreateFormattedText(FrameworkElement element, string text, Typeface typeface, double? emSize, Brush foreground)
+		{
+			if (element == null)
+				throw new ArgumentNullException("element");
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (typeface == null)
+				typeface = element.CreateTypeface();
+			if (emSize == null)
+				emSize = TextBlock.GetFontSize(element);
+			if (foreground == null)
+				foreground = TextBlock.GetForeground(element);
+			#if DOTNET4
+			return new FormattedText(
+				text,
+				CultureInfo.CurrentCulture,
+				FlowDirection.LeftToRight,
+				typeface,
+				emSize.Value,
+				foreground,
+				null,
+				TextOptions.GetTextFormattingMode(element)
+			);
+			#else
+			if (TextFormattingModeProperty != null) {
+				object formattingMode = element.GetValue(TextFormattingModeProperty);
+				return (FormattedText)Activator.CreateInstance(
+					typeof(FormattedText),
+					text,
+					CultureInfo.CurrentCulture,
+					FlowDirection.LeftToRight,
+					typeface,
+					emSize,
+					foreground,
+					null,
+					formattingMode
+				);
+			} else {
+				return new FormattedText(
+					text,
+					CultureInfo.CurrentCulture,
+					FlowDirection.LeftToRight,
+					typeface,
+					emSize.Value,
+					foreground
+				);
+			}
+			#endif
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ThrowUtil.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ThrowUtil.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/ThrowUtil.cs	(revision 11807)
@@ -0,0 +1,71 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Contains exception-throwing helper methods.
+	/// </summary>
+	static class ThrowUtil
+	{
+		/// <summary>
+		/// Throws an ArgumentNullException if <paramref name="val"/> is null; otherwise
+		/// returns val.
+		/// </summary>
+		/// <example>
+		/// Use this method to throw an ArgumentNullException when using parameters for base
+		/// constructor calls.
+		/// <code>
+		/// public VisualLineText(string text) : base(ThrowUtil.CheckNotNull(text, "text").Length)
+		/// </code>
+		/// </example>
+		public static T CheckNotNull<T>(T val, string parameterName) where T : class
+		{
+			if (val == null)
+				throw new ArgumentNullException(parameterName);
+			return val;
+		}
+		
+		public static int CheckNotNegative(int val, string parameterName)
+		{
+			if (val < 0)
+				throw new ArgumentOutOfRangeException(parameterName, val, "value must not be negative");
+			return val;
+		}
+		
+		public static int CheckInRangeInclusive(int val, string parameterName, int lower, int upper)
+		{
+			if (val < lower || val > upper)
+				throw new ArgumentOutOfRangeException(parameterName, val, "Expected: " + lower.ToString(CultureInfo.InvariantCulture) + " <= " + parameterName + " <= " + upper.ToString(CultureInfo.InvariantCulture));
+			return val;
+		}
+		
+		public static InvalidOperationException NoDocumentAssigned()
+		{
+			return new InvalidOperationException("Document is null");
+		}
+		
+		public static InvalidOperationException NoValidCaretPosition()
+		{
+			return new InvalidOperationException("Could not find a valid caret position in the line");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/WeakEventManagerBase.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/WeakEventManagerBase.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/WeakEventManagerBase.cs	(revision 11807)
@@ -0,0 +1,101 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// WeakEventManager with AddListener/RemoveListener and CurrentManager implementation.
+	/// Helps implementing the WeakEventManager pattern with less code.
+	/// </summary>
+	public abstract class WeakEventManagerBase<TManager, TEventSource> : WeakEventManager
+		where TManager : WeakEventManagerBase<TManager, TEventSource>, new()
+		where TEventSource : class
+	{
+		/// <summary>
+		/// Creates a new WeakEventManagerBase instance.
+		/// </summary>
+		protected WeakEventManagerBase()
+		{
+			Debug.Assert(GetType() == typeof(TManager));
+		}
+		
+		/// <summary>
+		/// Adds a weak event listener.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
+		public static void AddListener(TEventSource source, IWeakEventListener listener)
+		{
+			CurrentManager.ProtectedAddListener(source, listener);
+		}
+		
+		/// <summary>
+		/// Removes a weak event listener.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
+		public static void RemoveListener(TEventSource source, IWeakEventListener listener)
+		{
+			CurrentManager.ProtectedRemoveListener(source, listener);
+		}
+		
+		/// <inheritdoc/>
+		protected sealed override void StartListening(object source)
+		{
+			if (source == null)
+				throw new ArgumentNullException("source");
+			StartListening((TEventSource)source);
+		}
+		
+		/// <inheritdoc/>
+		protected sealed override void StopListening(object source)
+		{
+			if (source == null)
+				throw new ArgumentNullException("source");
+			StopListening((TEventSource)source);
+		}
+		
+		/// <summary>
+		/// Attaches the event handler.
+		/// </summary>
+		protected abstract void StartListening(TEventSource source);
+		
+		/// <summary>
+		/// Detaches the event handler.
+		/// </summary>
+		protected abstract void StopListening(TEventSource source);
+		
+		/// <summary>
+		/// Gets the current manager.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
+		protected static TManager CurrentManager {
+			get {
+				Type managerType = typeof(TManager);
+				TManager manager = (TManager)GetCurrentManager(managerType);
+				if (manager == null) {
+					manager = new TManager();
+					SetCurrentManager(managerType, manager);
+				}
+				return manager;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Win32.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Win32.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/Utils/Win32.cs	(revision 11807)
@@ -0,0 +1,100 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Windows;
+using System.Windows.Interop;
+using System.Windows.Media;
+
+namespace ICSharpCode.AvalonEdit.Utils
+{
+	/// <summary>
+	/// Wrapper around Win32 functions.
+	/// </summary>
+	static class Win32
+	{
+		/// <summary>
+		/// Gets the caret blink time.
+		/// </summary>
+		public static TimeSpan CaretBlinkTime {
+			get { return TimeSpan.FromMilliseconds(SafeNativeMethods.GetCaretBlinkTime()); }
+		}
+		
+		/// <summary>
+		/// Creates an invisible Win32 caret for the specified Visual with the specified size (coordinates local to the owner visual).
+		/// </summary>
+		public static bool CreateCaret(Visual owner, Size size)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			HwndSource source = PresentationSource.FromVisual(owner) as HwndSource;
+			if (source != null) {
+				Vector r = owner.PointToScreen(new Point(size.Width, size.Height)) - owner.PointToScreen(new Point(0, 0));
+				return SafeNativeMethods.CreateCaret(source.Handle, IntPtr.Zero, (int)Math.Ceiling(r.X), (int)Math.Ceiling(r.Y));
+			} else {
+				return false;
+			}
+		}
+		
+		/// <summary>
+		/// Sets the position of the caret previously created using <see cref="CreateCaret"/>. position is relative to the owner visual.
+		/// </summary>
+		public static bool SetCaretPosition(Visual owner, Point position)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			HwndSource source = PresentationSource.FromVisual(owner) as HwndSource;
+			if (source != null) {
+				Point pointOnRootVisual = owner.TransformToAncestor(source.RootVisual).Transform(position);
+				Point pointOnHwnd = pointOnRootVisual.TransformToDevice(source.RootVisual);
+				return SafeNativeMethods.SetCaretPos((int)pointOnHwnd.X, (int)pointOnHwnd.Y);
+			} else {
+				return false;
+			}
+		}
+		
+		/// <summary>
+		/// Destroys the caret previously created using <see cref="CreateCaret"/>.
+		/// </summary>
+		public static bool DestroyCaret()
+		{
+			return SafeNativeMethods.DestroyCaret();
+		}
+		
+		[SuppressUnmanagedCodeSecurity]
+		static class SafeNativeMethods
+		{
+			[DllImport("user32.dll")]
+			public static extern int GetCaretBlinkTime();
+			
+			[DllImport("user32.dll")]
+			[return: MarshalAs(UnmanagedType.Bool)]
+			public static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
+			
+			[DllImport("user32.dll")]
+			[return: MarshalAs(UnmanagedType.Bool)]
+			public static extern bool SetCaretPos(int x, int y);
+			
+			[DllImport("user32.dll")]
+			[return: MarshalAs(UnmanagedType.Bool)]
+			public static extern bool DestroyCaret();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/themes/generic.xaml
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/themes/generic.xaml	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/AvalonEdit-5.0.1/themes/generic.xaml	(revision 11807)
@@ -0,0 +1,15 @@
+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+	xmlns:editing="clr-namespace:ICSharpCode.AvalonEdit.Editing">
+	<ResourceDictionary.MergedDictionaries>
+		<ResourceDictionary Source="/ICSharpCode.AvalonEdit;component/TextEditor.xaml" />
+		<ResourceDictionary Source="/ICSharpCode.AvalonEdit;component/Search/DropDownButton.xaml" />
+		<ResourceDictionary Source="/ICSharpCode.AvalonEdit;component/Search/SearchPanel.xaml" />
+		<ResourceDictionary Source="/ICSharpCode.AvalonEdit;component/CodeCompletion/CompletionList.xaml" />
+		<ResourceDictionary Source="/ICSharpCode.AvalonEdit;component/CodeCompletion/InsightWindow.xaml" />
+	</ResourceDictionary.MergedDictionaries>
+	
+	<Style TargetType="{x:Type editing:LineNumberMargin}">
+		<Setter Property="Control.Cursor" Value="/ICSharpCode.AvalonEdit;component/themes/RightArrow.cur"/>
+	</Style>
+</ResourceDictionary>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/HeuristicLab.AvalonEdit-5.0.1.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/HeuristicLab.AvalonEdit-5.0.1.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/HeuristicLab.AvalonEdit-5.0.1.csproj	(revision 11807)
@@ -0,0 +1,128 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{644B1CCE-1B2A-4C61-B0E3-A2EDB89DF872}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.AvalonEdit</RootNamespace>
+    <AssemblyName>HeuristicLab.AvalonEdit-5.0.1</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="Plugin.cs.frame" />
+    <Compile Include="Plugin.cs" />
+    <None Include="Properties\AssemblyInfo.cs.frame" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\..\..\HeuristicLab.PluginInfrastructure\3.3\HeuristicLab.PluginInfrastructure-3.3.csproj">
+      <Project>{94186a6a-5176-4402-ae83-886557b53cca}</Project>
+      <Name>HeuristicLab.PluginInfrastructure-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\AvalonEdit-5.0.1\ICSharpCode.AvalonEdit-5.0.1.csproj">
+      <Project>{255c7deb-3c98-4bc2-92d4-b683f82a7e52}</Project>
+      <Name>ICSharpCode.AvalonEdit-5.0.1</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="ICSharpCode.AvalonEdit License-5.0.1.txt">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </Content>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd
+</PreBuildEvent>
+  </PropertyGroup>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/ICSharpCode.AvalonEdit License-5.0.1.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/ICSharpCode.AvalonEdit License-5.0.1.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/ICSharpCode.AvalonEdit License-5.0.1.txt	(revision 11807)
@@ -0,0 +1,19 @@
+The MIT License (MIT)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/Plugin.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/Plugin.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/Plugin.cs.frame	(revision 11807)
@@ -0,0 +1,31 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.AvalonEdit {
+  [Plugin("HeuristicLab.AvalonEdit", "HeuristicLab wrapper for AvalonEdit", "5.0.1.$WCREV$")]
+  [PluginFile("HeuristicLab.AvalonEdit-5.0.1.dll", PluginFileType.Assembly)]
+  [PluginFile("ICSharpCode.AvalonEdit.dll", PluginFileType.Assembly)]
+  [PluginFile("ICSharpCode.AvalonEdit License-5.0.1.txt", PluginFileType.License)]
+  public class HeuristicLabAvalonEditPlugin : PluginBase {
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/Properties/AssemblyInfo.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/Properties/AssemblyInfo.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.AvalonEdit/5.0.1/HeuristicLab.AvalonEdit-5.0.1/Properties/AssemblyInfo.cs.frame	(revision 11807)
@@ -0,0 +1,56 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.AvalonEdit")]
+[assembly: AssemblyDescription("HeuristicLab transport plugin for AvalonEdit")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2014 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("73562182-0875-4959-95d1-831d2b4cac13")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.0.1.0")]
+[assembly: AssemblyFileVersion("5.0.1.$WCREV$")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/HeuristicLab.Cecil-0.9.5.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/HeuristicLab.Cecil-0.9.5.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/HeuristicLab.Cecil-0.9.5.csproj	(revision 11807)
@@ -0,0 +1,128 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{03026CEF-4529-4F91-A8A3-761652CE14AD}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.Cecil</RootNamespace>
+    <AssemblyName>HeuristicLab.Cecil-0.9.5</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="Properties\AssemblyInfo.cs.frame" />
+    <None Include="Plugin.cs.frame" />
+    <Compile Include="Plugin.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="Mono.Cecil License-0.9.5.txt">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </Content>
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\..\..\HeuristicLab.PluginInfrastructure\3.3\HeuristicLab.PluginInfrastructure-3.3.csproj">
+      <Project>{94186a6a-5176-4402-ae83-886557b53cca}</Project>
+      <Name>HeuristicLab.PluginInfrastructure-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\Mono.Cecil-0.9.5\Mono.Cecil-0.9.5.csproj">
+      <Project>{ccf26bbc-5555-46ec-81f9-5b253cd24170}</Project>
+      <Name>Mono.Cecil-0.9.5</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd
+</PreBuildEvent>
+  </PropertyGroup>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Mono.Cecil License-0.9.5.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Mono.Cecil License-0.9.5.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Mono.Cecil License-0.9.5.txt	(revision 11807)
@@ -0,0 +1,20 @@
+Copyright (c) 2008 - 2014 Jb Evain
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Plugin.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Plugin.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Plugin.cs.frame	(revision 11807)
@@ -0,0 +1,31 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Cecil {
+  [Plugin("HeuristicLab.Cecil", "HeuristicLab wrapper for Cecil", "0.9.5.$WCREV$")]
+  [PluginFile("HeuristicLab.Cecil-0.9.5.dll", PluginFileType.Assembly)]
+  [PluginFile("Mono.Cecil-0.9.5.dll", PluginFileType.Assembly)]
+  [PluginFile("Mono.Cecil License-0.9.5.txt", PluginFileType.License)]
+  public class HeuristicLabCecilPlugin : PluginBase {
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Properties/AssemblyInfo.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Properties/AssemblyInfo.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/HeuristicLab.Cecil-0.9.5/Properties/AssemblyInfo.cs.frame	(revision 11807)
@@ -0,0 +1,56 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.Cecil")]
+[assembly: AssemblyDescription("HeuristicLab transport plugin for Cecil")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2014 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("669722a6-e857-4ede-9bca-236336742a79")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("0.9.5.0")]
+[assembly: AssemblyFileVersion("0.9.5.$WCREV$")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil License-0.9.5.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil License-0.9.5.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil License-0.9.5.txt	(revision 11807)
@@ -0,0 +1,20 @@
+Copyright (c) 2008 - 2014 Jb Evain
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil-0.9.5.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil-0.9.5.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil-0.9.5.csproj	(revision 11807)
@@ -0,0 +1,275 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{CCF26BBC-5555-46EC-81F9-5B253CD24170}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Mono.Cecil</RootNamespace>
+    <AssemblyName>Mono.Cecil-0.9.5</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;NET_4_0;CECIL</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <NoWarn>0649</NoWarn>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;NET_4_0;CECIL</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <NoWarn>0649</NoWarn>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;NET_4_0;CECIL</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <NoWarn>0649</NoWarn>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;NET_4_0;CECIL</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <NoWarn>0649</NoWarn>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;NET_4_0;CECIL</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <NoWarn>0649</NoWarn>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;NET_4_0;CECIL</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <NoWarn>0649</NoWarn>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\Code.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\CodeReader.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\CodeWriter.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\Document.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\ExceptionHandler.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\ILProcessor.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\Instruction.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\MethodBody.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\OpCode.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\OpCodes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\SequencePoint.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\Symbols.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\VariableDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Cil\VariableReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\BlobHeap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\Buffers.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\CodedIndex.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\ElementType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\GuidHeap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\Heap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\MetadataToken.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\Row.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\StringHeap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\TableHeap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\TokenType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\UserStringHeap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.Metadata\Utilities.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\BinaryStreamReader.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\BinaryStreamWriter.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\ByteBuffer.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\ByteBufferEqualityComparer.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\DataDirectory.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\Image.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\ImageReader.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\ImageWriter.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\Section.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil.PE\TextMap.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ArrayType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyFlags.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyHashAlgorithm.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyLinkedResource.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyNameDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyNameReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyReader.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\AssemblyWriter.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\BaseAssemblyResolver.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\CallSite.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\CustomAttribute.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\DefaultAssemblyResolver.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\EmbeddedResource.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\EventAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\EventDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\EventReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ExportedType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\FieldAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\FieldDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\FieldReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\FileAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\FunctionPointerType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\GenericInstanceMethod.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\GenericInstanceType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\GenericParameter.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\GenericParameterAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IConstantProvider.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ICustomAttributeProvider.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IGenericInstance.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IGenericParameterProvider.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IMarshalInfoProvider.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IMemberDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IMetadataScope.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IMetadataTokenProvider.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\IMethodSignature.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\Import.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\LinkedResource.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ManifestResourceAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MarshalInfo.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MemberDefinitionCollection.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MemberReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MetadataResolver.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MetadataSystem.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodCallingConvention.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodImplAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodReturnType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodSemanticsAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\MethodSpecification.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\Modifiers.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ModuleDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ModuleKind.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ModuleReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\NativeType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ParameterAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ParameterDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ParameterDefinitionCollection.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ParameterReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PinnedType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PInvokeAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PInvokeInfo.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PointerType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PropertyAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PropertyDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\PropertyReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\ReferenceType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\Resource.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\SecurityDeclaration.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\SentinelType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TargetRuntime.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeAttributes.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeDefinition.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeDefinitionCollection.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeParser.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeReference.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeSpecification.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\TypeSystem.cs" />
+    <Compile Include="Mono.Cecil\Mono.Cecil\VariantType.cs" />
+    <Compile Include="Mono.Cecil\Mono.Collections.Generic\Collection.cs" />
+    <Compile Include="Mono.Cecil\Mono.Collections.Generic\ReadOnlyCollection.cs" />
+    <Compile Include="Mono.Cecil\Mono.Security.Cryptography\CryptoConvert.cs" />
+    <Compile Include="Mono.Cecil\Mono.Security.Cryptography\CryptoService.cs" />
+    <Compile Include="Mono.Cecil\Mono\Actions.cs" />
+    <Compile Include="Mono.Cecil\Mono\Empty.cs" />
+    <Compile Include="Mono.Cecil\Mono\Funcs.cs" />
+    <Compile Include="Mono.Cecil\System.Runtime.CompilerServices\ExtensionAttribute.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Mdb\Mono.Cecil.Mdb\MdbReader.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Mdb\Mono.Cecil.Mdb\MdbWriter.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Mdb\Mono.CompilerServices.SymbolWriter\MonoSymbolFile.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Mdb\Mono.CompilerServices.SymbolWriter\MonoSymbolTable.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Mdb\Mono.CompilerServices.SymbolWriter\MonoSymbolWriter.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Mdb\Mono.CompilerServices.SymbolWriter\SymbolWriterImpl.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\BitAccess.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\BitSet.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\CvInfo.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\DataStream.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\DbiDbgHdr.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\DbiHeader.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\DbiModuleInfo.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\DbiSecCon.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\Interfaces.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\IntHashTable.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\MsfDirectory.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbConstant.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbDebugException.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbException.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbFile.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbFileHeader.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbFunction.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbLine.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbLines.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbReader.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbScope.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbSlot.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbSource.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\PdbWriter.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\SourceLocationProvider.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\ISymUnmanagedDocumentWriter.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\ISymUnmanagedWriter2.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\ModuleMetadata.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\PdbHelper.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\PdbReader.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\PdbWriter.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\SymDocumentWriter.cs" />
+    <Compile Include="Symbols\Mono.Cecil.Pdb\Mono.Cecil.Pdb\SymWriter.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+    <None Include="Symbols\Mono.Cecil.Pdb\Microsoft.Cci.Pdb\LICENSE" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="Mono.Cecil License-0.9.5.txt" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Code.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Code.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Code.cs	(revision 11807)
@@ -0,0 +1,252 @@
+//
+// Code.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public enum Code {
+		Nop,
+		Break,
+		Ldarg_0,
+		Ldarg_1,
+		Ldarg_2,
+		Ldarg_3,
+		Ldloc_0,
+		Ldloc_1,
+		Ldloc_2,
+		Ldloc_3,
+		Stloc_0,
+		Stloc_1,
+		Stloc_2,
+		Stloc_3,
+		Ldarg_S,
+		Ldarga_S,
+		Starg_S,
+		Ldloc_S,
+		Ldloca_S,
+		Stloc_S,
+		Ldnull,
+		Ldc_I4_M1,
+		Ldc_I4_0,
+		Ldc_I4_1,
+		Ldc_I4_2,
+		Ldc_I4_3,
+		Ldc_I4_4,
+		Ldc_I4_5,
+		Ldc_I4_6,
+		Ldc_I4_7,
+		Ldc_I4_8,
+		Ldc_I4_S,
+		Ldc_I4,
+		Ldc_I8,
+		Ldc_R4,
+		Ldc_R8,
+		Dup,
+		Pop,
+		Jmp,
+		Call,
+		Calli,
+		Ret,
+		Br_S,
+		Brfalse_S,
+		Brtrue_S,
+		Beq_S,
+		Bge_S,
+		Bgt_S,
+		Ble_S,
+		Blt_S,
+		Bne_Un_S,
+		Bge_Un_S,
+		Bgt_Un_S,
+		Ble_Un_S,
+		Blt_Un_S,
+		Br,
+		Brfalse,
+		Brtrue,
+		Beq,
+		Bge,
+		Bgt,
+		Ble,
+		Blt,
+		Bne_Un,
+		Bge_Un,
+		Bgt_Un,
+		Ble_Un,
+		Blt_Un,
+		Switch,
+		Ldind_I1,
+		Ldind_U1,
+		Ldind_I2,
+		Ldind_U2,
+		Ldind_I4,
+		Ldind_U4,
+		Ldind_I8,
+		Ldind_I,
+		Ldind_R4,
+		Ldind_R8,
+		Ldind_Ref,
+		Stind_Ref,
+		Stind_I1,
+		Stind_I2,
+		Stind_I4,
+		Stind_I8,
+		Stind_R4,
+		Stind_R8,
+		Add,
+		Sub,
+		Mul,
+		Div,
+		Div_Un,
+		Rem,
+		Rem_Un,
+		And,
+		Or,
+		Xor,
+		Shl,
+		Shr,
+		Shr_Un,
+		Neg,
+		Not,
+		Conv_I1,
+		Conv_I2,
+		Conv_I4,
+		Conv_I8,
+		Conv_R4,
+		Conv_R8,
+		Conv_U4,
+		Conv_U8,
+		Callvirt,
+		Cpobj,
+		Ldobj,
+		Ldstr,
+		Newobj,
+		Castclass,
+		Isinst,
+		Conv_R_Un,
+		Unbox,
+		Throw,
+		Ldfld,
+		Ldflda,
+		Stfld,
+		Ldsfld,
+		Ldsflda,
+		Stsfld,
+		Stobj,
+		Conv_Ovf_I1_Un,
+		Conv_Ovf_I2_Un,
+		Conv_Ovf_I4_Un,
+		Conv_Ovf_I8_Un,
+		Conv_Ovf_U1_Un,
+		Conv_Ovf_U2_Un,
+		Conv_Ovf_U4_Un,
+		Conv_Ovf_U8_Un,
+		Conv_Ovf_I_Un,
+		Conv_Ovf_U_Un,
+		Box,
+		Newarr,
+		Ldlen,
+		Ldelema,
+		Ldelem_I1,
+		Ldelem_U1,
+		Ldelem_I2,
+		Ldelem_U2,
+		Ldelem_I4,
+		Ldelem_U4,
+		Ldelem_I8,
+		Ldelem_I,
+		Ldelem_R4,
+		Ldelem_R8,
+		Ldelem_Ref,
+		Stelem_I,
+		Stelem_I1,
+		Stelem_I2,
+		Stelem_I4,
+		Stelem_I8,
+		Stelem_R4,
+		Stelem_R8,
+		Stelem_Ref,
+		Ldelem_Any,
+		Stelem_Any,
+		Unbox_Any,
+		Conv_Ovf_I1,
+		Conv_Ovf_U1,
+		Conv_Ovf_I2,
+		Conv_Ovf_U2,
+		Conv_Ovf_I4,
+		Conv_Ovf_U4,
+		Conv_Ovf_I8,
+		Conv_Ovf_U8,
+		Refanyval,
+		Ckfinite,
+		Mkrefany,
+		Ldtoken,
+		Conv_U2,
+		Conv_U1,
+		Conv_I,
+		Conv_Ovf_I,
+		Conv_Ovf_U,
+		Add_Ovf,
+		Add_Ovf_Un,
+		Mul_Ovf,
+		Mul_Ovf_Un,
+		Sub_Ovf,
+		Sub_Ovf_Un,
+		Endfinally,
+		Leave,
+		Leave_S,
+		Stind_I,
+		Conv_U,
+		Arglist,
+		Ceq,
+		Cgt,
+		Cgt_Un,
+		Clt,
+		Clt_Un,
+		Ldftn,
+		Ldvirtftn,
+		Ldarg,
+		Ldarga,
+		Starg,
+		Ldloc,
+		Ldloca,
+		Stloc,
+		Localloc,
+		Endfilter,
+		Unaligned,
+		Volatile,
+		Tail,
+		Initobj,
+		Constrained,
+		Cpblk,
+		Initblk,
+		No,
+		Rethrow,
+		Sizeof,
+		Refanytype,
+		Readonly,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/CodeReader.cs	(revision 11807)
@@ -0,0 +1,598 @@
+//
+// CodeReader.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.PE;
+using Mono.Collections.Generic;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.Cil {
+
+	sealed class CodeReader : ByteBuffer {
+
+		readonly internal MetadataReader reader;
+
+		int start;
+		Section code_section;
+
+		MethodDefinition method;
+		MethodBody body;
+
+		int Offset {
+			get { return base.position - start; }
+		}
+
+		public CodeReader (Section section, MetadataReader reader)
+			: base (section.Data)
+		{
+			this.code_section = section;
+			this.reader = reader;
+		}
+
+		public MethodBody ReadMethodBody (MethodDefinition method)
+		{
+			this.method = method;
+			this.body = new MethodBody (method);
+
+			reader.context = method;
+
+			ReadMethodBody ();
+
+			return this.body;
+		}
+
+		public void MoveTo (int rva)
+		{
+			if (!IsInSection (rva)) {
+				code_section = reader.image.GetSectionAtVirtualAddress ((uint) rva);
+				Reset (code_section.Data);
+			}
+
+			base.position = rva - (int) code_section.VirtualAddress;
+		}
+
+		bool IsInSection (int rva)
+		{
+			return code_section.VirtualAddress <= rva && rva < code_section.VirtualAddress + code_section.SizeOfRawData;
+		}
+
+		void ReadMethodBody ()
+		{
+			MoveTo (method.RVA);
+
+			var flags = ReadByte ();
+			switch (flags & 0x3) {
+			case 0x2: // tiny
+				body.code_size = flags >> 2;
+				body.MaxStackSize = 8;
+				ReadCode ();
+				break;
+			case 0x3: // fat
+				base.position--;
+				ReadFatMethod ();
+				break;
+			default:
+				throw new InvalidOperationException ();
+			}
+
+			var symbol_reader = reader.module.SymbolReader;
+
+			if (symbol_reader != null) {
+				var instructions = body.Instructions;
+				symbol_reader.Read (body, offset => GetInstruction (instructions, offset));
+			}
+		}
+
+		void ReadFatMethod ()
+		{
+			var flags = ReadUInt16 ();
+			body.max_stack_size = ReadUInt16 ();
+			body.code_size = (int) ReadUInt32 ();
+			body.local_var_token = new MetadataToken (ReadUInt32 ());
+			body.init_locals = (flags & 0x10) != 0;
+
+			if (body.local_var_token.RID != 0)
+				body.variables = ReadVariables (body.local_var_token);
+
+			ReadCode ();
+
+			if ((flags & 0x8) != 0)
+				ReadSection ();
+		}
+
+		public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token)
+		{
+			var position = reader.position;
+			var variables = reader.ReadVariables (local_var_token);
+			reader.position = position;
+
+			return variables;
+		}
+
+		void ReadCode ()
+		{
+			start = position;
+			var code_size = body.code_size;
+
+			if (code_size < 0 || buffer.Length <= (uint) (code_size + position))
+				code_size = 0;
+
+			var end = start + code_size;
+			var instructions = body.instructions = new InstructionCollection (code_size / 3);
+
+			while (position < end) {
+				var offset = base.position - start;
+				var opcode = ReadOpCode ();
+				var current = new Instruction (offset, opcode);
+
+				if (opcode.OperandType != OperandType.InlineNone)
+					current.operand = ReadOperand (current);
+
+				instructions.Add (current);
+			}
+
+			ResolveBranches (instructions);
+		}
+
+		OpCode ReadOpCode ()
+		{
+			var il_opcode = ReadByte ();
+			return il_opcode != 0xfe
+				? OpCodes.OneByteOpCode [il_opcode]
+				: OpCodes.TwoBytesOpCode [ReadByte ()];
+		}
+
+		object ReadOperand (Instruction instruction)
+		{
+			switch (instruction.opcode.OperandType) {
+			case OperandType.InlineSwitch:
+				var length = ReadInt32 ();
+				var base_offset = Offset + (4 * length);
+				var branches = new int [length];
+				for (int i = 0; i < length; i++)
+					branches [i] = base_offset + ReadInt32 ();
+				return branches;
+			case OperandType.ShortInlineBrTarget:
+				return ReadSByte () + Offset;
+			case OperandType.InlineBrTarget:
+				return ReadInt32 () + Offset;
+			case OperandType.ShortInlineI:
+				if (instruction.opcode == OpCodes.Ldc_I4_S)
+					return ReadSByte ();
+
+				return ReadByte ();
+			case OperandType.InlineI:
+				return ReadInt32 ();
+			case OperandType.ShortInlineR:
+				return ReadSingle ();
+			case OperandType.InlineR:
+				return ReadDouble ();
+			case OperandType.InlineI8:
+				return ReadInt64 ();
+			case OperandType.ShortInlineVar:
+				return GetVariable (ReadByte ());
+			case OperandType.InlineVar:
+				return GetVariable (ReadUInt16 ());
+			case OperandType.ShortInlineArg:
+				return GetParameter (ReadByte ());
+			case OperandType.InlineArg:
+				return GetParameter (ReadUInt16 ());
+			case OperandType.InlineSig:
+				return GetCallSite (ReadToken ());
+			case OperandType.InlineString:
+				return GetString (ReadToken ());
+			case OperandType.InlineTok:
+			case OperandType.InlineType:
+			case OperandType.InlineMethod:
+			case OperandType.InlineField:
+				return reader.LookupToken (ReadToken ());
+			default:
+				throw new NotSupportedException ();
+			}
+		}
+
+		public string GetString (MetadataToken token)
+		{
+			return reader.image.UserStringHeap.Read (token.RID);
+		}
+
+		public ParameterDefinition GetParameter (int index)
+		{
+			return body.GetParameter (index);
+		}
+
+		public VariableDefinition GetVariable (int index)
+		{
+			return body.GetVariable (index);
+		}
+
+		public CallSite GetCallSite (MetadataToken token)
+		{
+			return reader.ReadCallSite (token);
+		}
+
+		void ResolveBranches (Collection<Instruction> instructions)
+		{
+			var items = instructions.items;
+			var size = instructions.size;
+
+			for (int i = 0; i < size; i++) {
+				var instruction = items [i];
+				switch (instruction.opcode.OperandType) {
+				case OperandType.ShortInlineBrTarget:
+				case OperandType.InlineBrTarget:
+					instruction.operand = GetInstruction ((int) instruction.operand);
+					break;
+				case OperandType.InlineSwitch:
+					var offsets = (int []) instruction.operand;
+					var branches = new Instruction [offsets.Length];
+					for (int j = 0; j < offsets.Length; j++)
+						branches [j] = GetInstruction (offsets [j]);
+
+					instruction.operand = branches;
+					break;
+				}
+			}
+		}
+
+		Instruction GetInstruction (int offset)
+		{
+			return GetInstruction (body.Instructions, offset);
+		}
+
+		static Instruction GetInstruction (Collection<Instruction> instructions, int offset)
+		{
+			var size = instructions.size;
+			var items = instructions.items;
+			if (offset < 0 || offset > items [size - 1].offset)
+				return null;
+
+			int min = 0;
+			int max = size - 1;
+			while (min <= max) {
+				int mid = min + ((max - min) / 2);
+				var instruction = items [mid];
+				var instruction_offset = instruction.offset;
+
+				if (offset == instruction_offset)
+					return instruction;
+
+				if (offset < instruction_offset)
+					max = mid - 1;
+				else
+					min = mid + 1;
+			}
+
+			return null;
+		}
+
+		void ReadSection ()
+		{
+			Align (4);
+
+			const byte fat_format = 0x40;
+			const byte more_sects = 0x80;
+
+			var flags = ReadByte ();
+			if ((flags & fat_format) == 0)
+				ReadSmallSection ();
+			else
+				ReadFatSection ();
+
+			if ((flags & more_sects) != 0)
+				ReadSection ();
+		}
+
+		void ReadSmallSection ()
+		{
+			var count = ReadByte () / 12;
+			Advance (2);
+
+			ReadExceptionHandlers (
+				count,
+				() => (int) ReadUInt16 (),
+				() => (int) ReadByte ());
+		}
+
+		void ReadFatSection ()
+		{
+			position--;
+			var count = (ReadInt32 () >> 8) / 24;
+
+			ReadExceptionHandlers (
+				count,
+				ReadInt32,
+				ReadInt32);
+		}
+
+		// inline ?
+		void ReadExceptionHandlers (int count, Func<int> read_entry, Func<int> read_length)
+		{
+			for (int i = 0; i < count; i++) {
+				var handler = new ExceptionHandler (
+					(ExceptionHandlerType) (read_entry () & 0x7));
+
+				handler.TryStart = GetInstruction (read_entry ());
+				handler.TryEnd = GetInstruction (handler.TryStart.Offset + read_length ());
+
+				handler.HandlerStart = GetInstruction (read_entry ());
+				handler.HandlerEnd = GetInstruction (handler.HandlerStart.Offset + read_length ());
+
+				ReadExceptionHandlerSpecific (handler);
+
+				this.body.ExceptionHandlers.Add (handler);
+			}
+		}
+
+		void ReadExceptionHandlerSpecific (ExceptionHandler handler)
+		{
+			switch (handler.HandlerType) {
+			case ExceptionHandlerType.Catch:
+				handler.CatchType = (TypeReference) reader.LookupToken (ReadToken ());
+				break;
+			case ExceptionHandlerType.Filter:
+				handler.FilterStart = GetInstruction (ReadInt32 ());
+				break;
+			default:
+				Advance (4);
+				break;
+			}
+		}
+
+		void Align (int align)
+		{
+			align--;
+			Advance (((position + align) & ~align) - position);
+		}
+
+		public MetadataToken ReadToken ()
+		{
+			return new MetadataToken (ReadUInt32 ());
+		}
+
+#if !READ_ONLY
+
+		public ByteBuffer PatchRawMethodBody (MethodDefinition method, CodeWriter writer, out MethodSymbols symbols)
+		{
+			var buffer = new ByteBuffer ();
+			symbols = new MethodSymbols (method.Name);
+
+			this.method = method;
+			reader.context = method;
+
+			MoveTo (method.RVA);
+
+			var flags = ReadByte ();
+
+			MetadataToken local_var_token;
+
+			switch (flags & 0x3) {
+			case 0x2: // tiny
+				buffer.WriteByte (flags);
+				local_var_token = MetadataToken.Zero;
+				symbols.code_size = flags >> 2;
+				PatchRawCode (buffer, symbols.code_size, writer);
+				break;
+			case 0x3: // fat
+				base.position--;
+
+				PatchRawFatMethod (buffer, symbols, writer, out local_var_token);
+				break;
+			default:
+				throw new NotSupportedException ();
+			}
+
+			var symbol_reader = reader.module.SymbolReader;
+			if (symbol_reader != null && writer.metadata.write_symbols) {
+				symbols.method_token = GetOriginalToken (writer.metadata, method);
+				symbols.local_var_token = local_var_token;
+				symbol_reader.Read (symbols);
+			}
+
+			return buffer;
+		}
+
+		void PatchRawFatMethod (ByteBuffer buffer, MethodSymbols symbols, CodeWriter writer, out MetadataToken local_var_token)
+		{
+			var flags = ReadUInt16 ();
+			buffer.WriteUInt16 (flags);
+			buffer.WriteUInt16 (ReadUInt16 ());
+			symbols.code_size = ReadInt32 ();
+			buffer.WriteInt32 (symbols.code_size);
+			local_var_token = ReadToken ();
+
+			if (local_var_token.RID > 0) {
+				var variables = symbols.variables = ReadVariables (local_var_token);
+				buffer.WriteUInt32 (variables != null
+					? writer.GetStandAloneSignature (symbols.variables).ToUInt32 ()
+					: 0);
+			} else
+				buffer.WriteUInt32 (0);
+
+			PatchRawCode (buffer, symbols.code_size, writer);
+
+			if ((flags & 0x8) != 0)
+				PatchRawSection (buffer, writer.metadata);
+		}
+
+		static MetadataToken GetOriginalToken (MetadataBuilder metadata, MethodDefinition method)
+		{
+			MetadataToken original;
+			if (metadata.TryGetOriginalMethodToken (method.token, out original))
+				return original;
+
+			return MetadataToken.Zero;
+		}
+
+		void PatchRawCode (ByteBuffer buffer, int code_size, CodeWriter writer)
+		{
+			var metadata = writer.metadata;
+			buffer.WriteBytes (ReadBytes (code_size));
+			var end = buffer.position;
+			buffer.position -= code_size;
+
+			while (buffer.position < end) {
+				OpCode opcode;
+				var il_opcode = buffer.ReadByte ();
+				if (il_opcode != 0xfe) {
+					opcode = OpCodes.OneByteOpCode [il_opcode];
+				} else {
+					var il_opcode2 = buffer.ReadByte ();
+					opcode = OpCodes.TwoBytesOpCode [il_opcode2];
+				}
+
+				switch (opcode.OperandType) {
+				case OperandType.ShortInlineI:
+				case OperandType.ShortInlineBrTarget:
+				case OperandType.ShortInlineVar:
+				case OperandType.ShortInlineArg:
+					buffer.position += 1;
+					break;
+				case OperandType.InlineVar:
+				case OperandType.InlineArg:
+					buffer.position += 2;
+					break;
+				case OperandType.InlineBrTarget:
+				case OperandType.ShortInlineR:
+				case OperandType.InlineI:
+					buffer.position += 4;
+					break;
+				case OperandType.InlineI8:
+				case OperandType.InlineR:
+					buffer.position += 8;
+					break;
+				case OperandType.InlineSwitch:
+					var length = buffer.ReadInt32 ();
+					buffer.position += length * 4;
+					break;
+				case OperandType.InlineString:
+					var @string = GetString (new MetadataToken (buffer.ReadUInt32 ()));
+					buffer.position -= 4;
+					buffer.WriteUInt32 (
+						new MetadataToken (
+							TokenType.String,
+							metadata.user_string_heap.GetStringIndex (@string)).ToUInt32 ());
+					break;
+				case OperandType.InlineSig:
+					var call_site = GetCallSite (new MetadataToken (buffer.ReadUInt32 ()));
+					buffer.position -= 4;
+					buffer.WriteUInt32 (writer.GetStandAloneSignature (call_site).ToUInt32 ());
+					break;
+				case OperandType.InlineTok:
+				case OperandType.InlineType:
+				case OperandType.InlineMethod:
+				case OperandType.InlineField:
+					var provider = reader.LookupToken (new MetadataToken (buffer.ReadUInt32 ()));
+					buffer.position -= 4;
+					buffer.WriteUInt32 (metadata.LookupToken (provider).ToUInt32 ());
+					break;
+				}
+			}
+		}
+
+		void PatchRawSection (ByteBuffer buffer, MetadataBuilder metadata)
+		{
+			var position = base.position;
+			Align (4);
+			buffer.WriteBytes (base.position - position);
+
+			const byte fat_format = 0x40;
+			const byte more_sects = 0x80;
+
+			var flags = ReadByte ();
+			if ((flags & fat_format) == 0) {
+				buffer.WriteByte (flags);
+				PatchRawSmallSection (buffer, metadata);
+			} else
+				PatchRawFatSection (buffer, metadata);
+
+			if ((flags & more_sects) != 0)
+				PatchRawSection (buffer, metadata);
+		}
+
+		void PatchRawSmallSection (ByteBuffer buffer, MetadataBuilder metadata)
+		{
+			var length = ReadByte ();
+			buffer.WriteByte (length);
+			Advance (2);
+
+			buffer.WriteUInt16 (0);
+
+			var count = length / 12;
+
+			PatchRawExceptionHandlers (buffer, metadata, count, false);
+		}
+
+		void PatchRawFatSection (ByteBuffer buffer, MetadataBuilder metadata)
+		{
+			position--;
+			var length = ReadInt32 ();
+			buffer.WriteInt32 (length);
+
+			var count = (length >> 8) / 24;
+
+			PatchRawExceptionHandlers (buffer, metadata, count, true);
+		}
+
+		void PatchRawExceptionHandlers (ByteBuffer buffer, MetadataBuilder metadata, int count, bool fat_entry)
+		{
+			const int fat_entry_size = 16;
+			const int small_entry_size = 6;
+
+			for (int i = 0; i < count; i++) {
+				ExceptionHandlerType handler_type;
+				if (fat_entry) {
+					var type = ReadUInt32 ();
+					handler_type = (ExceptionHandlerType) (type & 0x7);
+					buffer.WriteUInt32 (type);
+				} else {
+					var type = ReadUInt16 ();
+					handler_type = (ExceptionHandlerType) (type & 0x7);
+					buffer.WriteUInt16 (type);
+				}
+
+				buffer.WriteBytes (ReadBytes (fat_entry ? fat_entry_size : small_entry_size));
+
+				switch (handler_type) {
+				case ExceptionHandlerType.Catch:
+					var exception = reader.LookupToken (ReadToken ());
+					buffer.WriteUInt32 (metadata.LookupToken (exception).ToUInt32 ());
+					break;
+				default:
+					buffer.WriteUInt32 (ReadUInt32 ());
+					break;
+				}
+			}
+		}
+
+#endif
+
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/CodeWriter.cs	(revision 11807)
@@ -0,0 +1,638 @@
+//
+// CodeWriter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+
+using Mono.Collections.Generic;
+
+using Mono.Cecil.Metadata;
+using Mono.Cecil.PE;
+
+using RVA = System.UInt32;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Cil {
+
+	sealed class CodeWriter : ByteBuffer {
+
+		readonly RVA code_base;
+		internal readonly MetadataBuilder metadata;
+		readonly Dictionary<uint, MetadataToken> standalone_signatures;
+
+		RVA current;
+		MethodBody body;
+
+		public CodeWriter (MetadataBuilder metadata)
+			: base (0)
+		{
+			this.code_base = metadata.text_map.GetNextRVA (TextSegment.CLIHeader);
+			this.current = code_base;
+			this.metadata = metadata;
+			this.standalone_signatures = new Dictionary<uint, MetadataToken> ();
+		}
+
+		public RVA WriteMethodBody (MethodDefinition method)
+		{
+			var rva = BeginMethod ();
+
+			if (IsUnresolved (method)) {
+				if (method.rva == 0)
+					return 0;
+
+				WriteUnresolvedMethodBody (method);
+			} else {
+				if (IsEmptyMethodBody (method.Body))
+					return 0;
+
+				WriteResolvedMethodBody (method);
+			}
+
+			Align (4);
+
+			EndMethod ();
+			return rva;
+		}
+
+		static bool IsEmptyMethodBody (MethodBody body)
+		{
+			return body.instructions.IsNullOrEmpty ()
+				&& body.variables.IsNullOrEmpty ();
+		}
+
+		static bool IsUnresolved (MethodDefinition method)
+		{
+			return method.HasBody && method.HasImage && method.body == null;
+		}
+
+		void WriteUnresolvedMethodBody (MethodDefinition method)
+		{
+			var code_reader = metadata.module.Read (method, (_, reader) => reader.code);
+
+			MethodSymbols symbols;
+			var buffer = code_reader.PatchRawMethodBody (method, this, out symbols);
+
+			WriteBytes (buffer);
+
+			if (symbols.instructions.IsNullOrEmpty ())
+				return;
+
+			symbols.method_token = method.token;
+			symbols.local_var_token = GetLocalVarToken (buffer, symbols);
+
+			var symbol_writer = metadata.symbol_writer;
+			if (symbol_writer != null)
+				symbol_writer.Write (symbols);
+		}
+
+		static MetadataToken GetLocalVarToken (ByteBuffer buffer, MethodSymbols symbols)
+		{
+			if (symbols.variables.IsNullOrEmpty ())
+				return MetadataToken.Zero;
+
+			buffer.position = 8;
+			return new MetadataToken (buffer.ReadUInt32 ());
+		}
+
+		void WriteResolvedMethodBody (MethodDefinition method)
+		{
+			body = method.Body;
+			ComputeHeader ();
+			if (RequiresFatHeader ())
+				WriteFatHeader ();
+			else
+				WriteByte ((byte) (0x2 | (body.CodeSize << 2))); // tiny
+
+			WriteInstructions ();
+
+			if (body.HasExceptionHandlers)
+				WriteExceptionHandlers ();
+
+			var symbol_writer = metadata.symbol_writer;
+			if (symbol_writer != null)
+				symbol_writer.Write (body);
+		}
+
+		void WriteFatHeader ()
+		{
+			var body = this.body;
+			byte flags = 0x3;	// fat
+			if (body.InitLocals)
+				flags |= 0x10;	// init locals
+			if (body.HasExceptionHandlers)
+				flags |= 0x8;	// more sections
+
+			WriteByte (flags);
+			WriteByte (0x30);
+			WriteInt16 ((short) body.max_stack_size);
+			WriteInt32 (body.code_size);
+			body.local_var_token = body.HasVariables
+				? GetStandAloneSignature (body.Variables)
+				: MetadataToken.Zero;
+			WriteMetadataToken (body.local_var_token);
+		}
+
+		void WriteInstructions ()
+		{
+			var instructions = body.Instructions;
+			var items = instructions.items;
+			var size = instructions.size;
+
+			for (int i = 0; i < size; i++) {
+				var instruction = items [i];
+				WriteOpCode (instruction.opcode);
+				WriteOperand (instruction);
+			}
+		}
+
+		void WriteOpCode (OpCode opcode)
+		{
+			if (opcode.Size == 1) {
+				WriteByte (opcode.Op2);
+			} else {
+				WriteByte (opcode.Op1);
+				WriteByte (opcode.Op2);
+			}
+		}
+
+		void WriteOperand (Instruction instruction)
+		{
+			var opcode = instruction.opcode;
+			var operand_type = opcode.OperandType;
+			if (operand_type == OperandType.InlineNone)
+				return;
+
+			var operand = instruction.operand;
+			if (operand == null)
+				throw new ArgumentException ();
+
+			switch (operand_type) {
+			case OperandType.InlineSwitch: {
+				var targets = (Instruction []) operand;
+				WriteInt32 (targets.Length);
+				var diff = instruction.Offset + opcode.Size + (4 * (targets.Length + 1));
+				for (int i = 0; i < targets.Length; i++)
+					WriteInt32 (GetTargetOffset (targets [i]) - diff);
+				break;
+			}
+			case OperandType.ShortInlineBrTarget: {
+				var target = (Instruction) operand;
+				WriteSByte ((sbyte) (GetTargetOffset (target) - (instruction.Offset + opcode.Size + 1)));
+				break;
+			}
+			case OperandType.InlineBrTarget: {
+				var target = (Instruction) operand;
+				WriteInt32 (GetTargetOffset (target) - (instruction.Offset + opcode.Size + 4));
+				break;
+			}
+			case OperandType.ShortInlineVar:
+				WriteByte ((byte) GetVariableIndex ((VariableDefinition) operand));
+				break;
+			case OperandType.ShortInlineArg:
+				WriteByte ((byte) GetParameterIndex ((ParameterDefinition) operand));
+				break;
+			case OperandType.InlineVar:
+				WriteInt16 ((short) GetVariableIndex ((VariableDefinition) operand));
+				break;
+			case OperandType.InlineArg:
+				WriteInt16 ((short) GetParameterIndex ((ParameterDefinition) operand));
+				break;
+			case OperandType.InlineSig:
+				WriteMetadataToken (GetStandAloneSignature ((CallSite) operand));
+				break;
+			case OperandType.ShortInlineI:
+				if (opcode == OpCodes.Ldc_I4_S)
+					WriteSByte ((sbyte) operand);
+				else
+					WriteByte ((byte) operand);
+				break;
+			case OperandType.InlineI:
+				WriteInt32 ((int) operand);
+				break;
+			case OperandType.InlineI8:
+				WriteInt64 ((long) operand);
+				break;
+			case OperandType.ShortInlineR:
+				WriteSingle ((float) operand);
+				break;
+			case OperandType.InlineR:
+				WriteDouble ((double) operand);
+				break;
+			case OperandType.InlineString:
+				WriteMetadataToken (
+					new MetadataToken (
+						TokenType.String,
+						GetUserStringIndex ((string) operand)));
+				break;
+			case OperandType.InlineType:
+			case OperandType.InlineField:
+			case OperandType.InlineMethod:
+			case OperandType.InlineTok:
+				WriteMetadataToken (metadata.LookupToken ((IMetadataTokenProvider) operand));
+				break;
+			default:
+				throw new ArgumentException ();
+			}
+		}
+
+		int GetTargetOffset (Instruction instruction)
+		{
+			if (instruction == null) {
+				var last = body.instructions [body.instructions.size - 1];
+				return last.offset + last.GetSize ();
+			}
+
+			return instruction.offset;
+		}
+
+		uint GetUserStringIndex (string @string)
+		{
+			if (@string == null)
+				return 0;
+
+			return metadata.user_string_heap.GetStringIndex (@string);
+		}
+
+		static int GetVariableIndex (VariableDefinition variable)
+		{
+			return variable.Index;
+		}
+
+		int GetParameterIndex (ParameterDefinition parameter)
+		{
+			if (body.method.HasThis) {
+				if (parameter == body.this_parameter)
+					return 0;
+
+				return parameter.Index + 1;
+			}
+
+			return parameter.Index;
+		}
+
+		bool RequiresFatHeader ()
+		{
+			var body = this.body;
+			return body.CodeSize >= 64
+				|| body.InitLocals
+				|| body.HasVariables
+				|| body.HasExceptionHandlers
+				|| body.MaxStackSize > 8;
+		}
+
+		void ComputeHeader ()
+		{
+			int offset = 0;
+			var instructions = body.instructions;
+			var items = instructions.items;
+			var count = instructions.size;
+			var stack_size = 0;
+			var max_stack = 0;
+			Dictionary<Instruction, int> stack_sizes = null;
+
+			if (body.HasExceptionHandlers)
+				ComputeExceptionHandlerStackSize (ref stack_sizes);
+
+			for (int i = 0; i < count; i++) {
+				var instruction = items [i];
+				instruction.offset = offset;
+				offset += instruction.GetSize ();
+
+				ComputeStackSize (instruction, ref stack_sizes, ref stack_size, ref max_stack);
+			}
+
+			body.code_size = offset;
+			body.max_stack_size = max_stack;
+		}
+
+		void ComputeExceptionHandlerStackSize (ref Dictionary<Instruction, int> stack_sizes)
+		{
+			var exception_handlers = body.ExceptionHandlers;
+
+			for (int i = 0; i < exception_handlers.Count; i++) {
+				var exception_handler = exception_handlers [i];
+
+				switch (exception_handler.HandlerType) {
+				case ExceptionHandlerType.Catch:
+					AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
+					break;
+				case ExceptionHandlerType.Filter:
+					AddExceptionStackSize (exception_handler.FilterStart, ref stack_sizes);
+					AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes);
+					break;
+				}
+			}
+		}
+
+		static void AddExceptionStackSize (Instruction handler_start, ref Dictionary<Instruction, int> stack_sizes)
+		{
+			if (handler_start == null)
+				return;
+
+			if (stack_sizes == null)
+				stack_sizes = new Dictionary<Instruction, int> ();
+
+			stack_sizes [handler_start] = 1;
+		}
+
+		static void ComputeStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, ref int stack_size, ref int max_stack)
+		{
+			int computed_size;
+			if (stack_sizes != null && stack_sizes.TryGetValue (instruction, out computed_size))
+				stack_size = computed_size;
+
+			max_stack = System.Math.Max (max_stack, stack_size);
+			ComputeStackDelta (instruction, ref stack_size);
+			max_stack = System.Math.Max (max_stack, stack_size);
+
+			CopyBranchStackSize (instruction, ref stack_sizes, stack_size);
+			ComputeStackSize (instruction, ref stack_size);
+		}
+
+		static void CopyBranchStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, int stack_size)
+		{
+			if (stack_size == 0)
+				return;
+
+			switch (instruction.opcode.OperandType) {
+			case OperandType.ShortInlineBrTarget:
+			case OperandType.InlineBrTarget:
+				CopyBranchStackSize (ref stack_sizes, (Instruction) instruction.operand, stack_size);
+				break;
+			case OperandType.InlineSwitch:
+				var targets = (Instruction[]) instruction.operand;
+				for (int i = 0; i < targets.Length; i++)
+					CopyBranchStackSize (ref stack_sizes, targets [i], stack_size);
+				break;
+			}
+		}
+
+		static void CopyBranchStackSize (ref Dictionary<Instruction, int> stack_sizes, Instruction target, int stack_size)
+		{
+			if (stack_sizes == null)
+				stack_sizes = new Dictionary<Instruction, int> ();
+
+			int branch_stack_size = stack_size;
+
+			int computed_size;
+			if (stack_sizes.TryGetValue (target, out computed_size))
+				branch_stack_size = System.Math.Max (branch_stack_size, computed_size);
+
+			stack_sizes [target] = branch_stack_size;
+		}
+
+		static void ComputeStackSize (Instruction instruction, ref int stack_size)
+		{
+			switch (instruction.opcode.FlowControl) {
+			case FlowControl.Branch:
+			case FlowControl.Break:
+			case FlowControl.Throw:
+			case FlowControl.Return:
+				stack_size = 0;
+				break;
+			}
+		}
+
+		static void ComputeStackDelta (Instruction instruction, ref int stack_size)
+		{
+			switch (instruction.opcode.FlowControl) {
+			case FlowControl.Call: {
+				var method = (IMethodSignature) instruction.operand;
+				stack_size -= (method.HasParameters ? method.Parameters.Count : 0)
+					+ (method.HasThis && instruction.opcode.Code != Code.Newobj ? 1 : 0);
+				stack_size += (method.ReturnType.etype == ElementType.Void ? 0 : 1)
+					+ (method.HasThis && instruction.opcode.Code == Code.Newobj ? 1 : 0);
+				break;
+			}
+			default:
+				ComputePopDelta (instruction.opcode.StackBehaviourPop, ref stack_size);
+				ComputePushDelta (instruction.opcode.StackBehaviourPush, ref stack_size);
+				break;
+			}
+		}
+
+		static void ComputePopDelta (StackBehaviour pop_behavior, ref int stack_size)
+		{
+			switch (pop_behavior) {
+			case StackBehaviour.Popi:
+			case StackBehaviour.Popref:
+			case StackBehaviour.Pop1:
+				stack_size--;
+				break;
+			case StackBehaviour.Pop1_pop1:
+			case StackBehaviour.Popi_pop1:
+			case StackBehaviour.Popi_popi:
+			case StackBehaviour.Popi_popi8:
+			case StackBehaviour.Popi_popr4:
+			case StackBehaviour.Popi_popr8:
+			case StackBehaviour.Popref_pop1:
+			case StackBehaviour.Popref_popi:
+				stack_size -= 2;
+				break;
+			case StackBehaviour.Popi_popi_popi:
+			case StackBehaviour.Popref_popi_popi:
+			case StackBehaviour.Popref_popi_popi8:
+			case StackBehaviour.Popref_popi_popr4:
+			case StackBehaviour.Popref_popi_popr8:
+			case StackBehaviour.Popref_popi_popref:
+				stack_size -= 3;
+				break;
+			case StackBehaviour.PopAll:
+				stack_size = 0;
+				break;
+			}
+		}
+
+		static void ComputePushDelta (StackBehaviour push_behaviour, ref int stack_size)
+		{
+			switch (push_behaviour) {
+			case StackBehaviour.Push1:
+			case StackBehaviour.Pushi:
+			case StackBehaviour.Pushi8:
+			case StackBehaviour.Pushr4:
+			case StackBehaviour.Pushr8:
+			case StackBehaviour.Pushref:
+				stack_size++;
+				break;
+			case StackBehaviour.Push1_push1:
+				stack_size += 2;
+				break;
+			}
+		}
+
+		void WriteExceptionHandlers ()
+		{
+			Align (4);
+
+			var handlers = body.ExceptionHandlers;
+
+			if (handlers.Count < 0x15 && !RequiresFatSection (handlers))
+				WriteSmallSection (handlers);
+			else
+				WriteFatSection (handlers);
+		}
+
+		static bool RequiresFatSection (Collection<ExceptionHandler> handlers)
+		{
+			for (int i = 0; i < handlers.Count; i++) {
+				var handler = handlers [i];
+
+				if (IsFatRange (handler.TryStart, handler.TryEnd))
+					return true;
+
+				if (IsFatRange (handler.HandlerStart, handler.HandlerEnd))
+					return true;
+
+				if (handler.HandlerType == ExceptionHandlerType.Filter
+					&& IsFatRange (handler.FilterStart, handler.HandlerStart))
+					return true;
+			}
+
+			return false;
+		}
+
+		static bool IsFatRange (Instruction start, Instruction end)
+		{
+			if (end == null)
+				return true;
+
+			return end.Offset - start.Offset > 255 || start.Offset > 65535;
+		}
+
+		void WriteSmallSection (Collection<ExceptionHandler> handlers)
+		{
+			const byte eh_table = 0x1;
+
+			WriteByte (eh_table);
+			WriteByte ((byte) (handlers.Count * 12 + 4));
+			WriteBytes (2);
+
+			WriteExceptionHandlers (
+				handlers,
+				i => WriteUInt16 ((ushort) i),
+				i => WriteByte ((byte) i));
+		}
+
+		void WriteFatSection (Collection<ExceptionHandler> handlers)
+		{
+			const byte eh_table = 0x1;
+			const byte fat_format = 0x40;
+
+			WriteByte (eh_table | fat_format);
+
+			int size = handlers.Count * 24 + 4;
+			WriteByte ((byte) (size & 0xff));
+			WriteByte ((byte) ((size >> 8) & 0xff));
+			WriteByte ((byte) ((size >> 16) & 0xff));
+
+			WriteExceptionHandlers (handlers, WriteInt32, WriteInt32);
+		}
+
+		void WriteExceptionHandlers (Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length)
+		{
+			for (int i = 0; i < handlers.Count; i++) {
+				var handler = handlers [i];
+
+				write_entry ((int) handler.HandlerType);
+
+				write_entry (handler.TryStart.Offset);
+				write_length (GetTargetOffset (handler.TryEnd) - handler.TryStart.Offset);
+
+				write_entry (handler.HandlerStart.Offset);
+				write_length (GetTargetOffset (handler.HandlerEnd) - handler.HandlerStart.Offset);
+
+				WriteExceptionHandlerSpecific (handler);
+			}
+		}
+
+		void WriteExceptionHandlerSpecific (ExceptionHandler handler)
+		{
+			switch (handler.HandlerType) {
+			case ExceptionHandlerType.Catch:
+				WriteMetadataToken (metadata.LookupToken (handler.CatchType));
+				break;
+			case ExceptionHandlerType.Filter:
+				WriteInt32 (handler.FilterStart.Offset);
+				break;
+			default:
+				WriteInt32 (0);
+				break;
+			}
+		}
+
+		public MetadataToken GetStandAloneSignature (Collection<VariableDefinition> variables)
+		{
+			var signature = metadata.GetLocalVariableBlobIndex (variables);
+
+			return GetStandAloneSignatureToken (signature);
+		}
+
+		public MetadataToken GetStandAloneSignature (CallSite call_site)
+		{
+			var signature = metadata.GetCallSiteBlobIndex (call_site);
+			var token = GetStandAloneSignatureToken (signature);
+			call_site.MetadataToken = token;
+			return token;
+		}
+
+		MetadataToken GetStandAloneSignatureToken (uint signature)
+		{
+			MetadataToken token;
+			if (standalone_signatures.TryGetValue (signature, out token))
+				return token;
+
+			token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature));
+			standalone_signatures.Add (signature, token);
+			return token;
+		}
+
+		RVA BeginMethod ()
+		{
+			return current;
+		}
+
+		void WriteMetadataToken (MetadataToken token)
+		{
+			WriteUInt32 (token.ToUInt32 ());
+		}
+
+		void Align (int align)
+		{
+			align--;
+			WriteBytes (((position + align) & ~align) - position);
+		}
+
+		void EndMethod ()
+		{
+			current = (RVA) (code_base + position);
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Document.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Document.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Document.cs	(revision 11807)
@@ -0,0 +1,111 @@
+//
+// Document.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil.Cil {
+
+	public enum DocumentType {
+		Other,
+		Text,
+	}
+
+	public enum DocumentHashAlgorithm {
+		None,
+		MD5,
+		SHA1,
+	}
+
+	public enum DocumentLanguage {
+		Other,
+		C,
+		Cpp,
+		CSharp,
+		Basic,
+		Java,
+		Cobol,
+		Pascal,
+		Cil,
+		JScript,
+		Smc,
+		MCpp,
+	}
+
+	public enum DocumentLanguageVendor {
+		Other,
+		Microsoft,
+	}
+
+	public sealed class Document {
+
+		string url;
+
+		byte type;
+		byte hash_algorithm;
+		byte language;
+		byte language_vendor;
+
+		byte [] hash;
+
+		public string Url {
+			get { return url; }
+			set { url = value; }
+		}
+
+		public DocumentType Type {
+			get { return (DocumentType) type; }
+			set { type = (byte) value; }
+		}
+
+		public DocumentHashAlgorithm HashAlgorithm {
+			get { return (DocumentHashAlgorithm) hash_algorithm; }
+			set { hash_algorithm = (byte) value; }
+		}
+
+		public DocumentLanguage Language {
+			get { return (DocumentLanguage) language; }
+			set { language = (byte) value; }
+		}
+
+		public DocumentLanguageVendor LanguageVendor {
+			get { return (DocumentLanguageVendor) language_vendor; }
+			set { language_vendor = (byte) value; }
+		}
+
+		public byte [] Hash {
+			get { return hash; }
+			set { hash = value; }
+		}
+
+		public Document (string url)
+		{
+			this.url = url;
+			this.hash = Empty<byte>.Array;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/ExceptionHandler.cs	(revision 11807)
@@ -0,0 +1,89 @@
+//
+// ExceptionHandler.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public enum ExceptionHandlerType {
+		Catch = 0,
+		Filter = 1,
+		Finally = 2,
+		Fault = 4,
+	}
+
+	public sealed class ExceptionHandler {
+
+		Instruction try_start;
+		Instruction try_end;
+		Instruction filter_start;
+		Instruction handler_start;
+		Instruction handler_end;
+
+		TypeReference catch_type;
+		ExceptionHandlerType handler_type;
+
+		public Instruction TryStart {
+			get { return try_start; }
+			set { try_start = value; }
+		}
+
+		public Instruction TryEnd {
+			get { return try_end; }
+			set { try_end = value; }
+		}
+
+		public Instruction FilterStart {
+			get { return filter_start; }
+			set { filter_start = value; }
+		}
+
+		public Instruction HandlerStart {
+			get { return handler_start; }
+			set { handler_start = value; }
+		}
+
+		public Instruction HandlerEnd {
+			get { return handler_end; }
+			set { handler_end = value; }
+		}
+
+		public TypeReference CatchType {
+			get { return catch_type; }
+			set { catch_type = value; }
+		}
+
+		public ExceptionHandlerType HandlerType {
+			get { return handler_type; }
+			set { handler_type = value; }
+		}
+
+		public ExceptionHandler (ExceptionHandlerType handlerType)
+		{
+			this.handler_type = handlerType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/ILProcessor.cs	(revision 11807)
@@ -0,0 +1,278 @@
+//
+// ILProcessor.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil.Cil {
+
+	public sealed class ILProcessor {
+
+		readonly MethodBody body;
+		readonly Collection<Instruction> instructions;
+
+		public MethodBody Body {
+			get { return body; }
+		}
+
+		internal ILProcessor (MethodBody body)
+		{
+			this.body = body;
+			this.instructions = body.Instructions;
+		}
+
+		public Instruction Create (OpCode opcode)
+		{
+			return Instruction.Create (opcode);
+		}
+
+		public Instruction Create (OpCode opcode, TypeReference type)
+		{
+			return Instruction.Create (opcode, type);
+		}
+
+		public Instruction Create (OpCode opcode, CallSite site)
+		{
+			return Instruction.Create (opcode, site);
+		}
+
+		public Instruction Create (OpCode opcode, MethodReference method)
+		{
+			return Instruction.Create (opcode, method);
+		}
+
+		public Instruction Create (OpCode opcode, FieldReference field)
+		{
+			return Instruction.Create (opcode, field);
+		}
+
+		public Instruction Create (OpCode opcode, string value)
+		{
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, sbyte value)
+		{
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, byte value)
+		{
+			if (opcode.OperandType == OperandType.ShortInlineVar)
+				return Instruction.Create (opcode, body.Variables [value]);
+
+			if (opcode.OperandType == OperandType.ShortInlineArg)
+				return Instruction.Create (opcode, body.GetParameter (value));
+
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, int value)
+		{
+			if (opcode.OperandType == OperandType.InlineVar)
+				return Instruction.Create (opcode, body.Variables [value]);
+
+			if (opcode.OperandType == OperandType.InlineArg)
+				return Instruction.Create (opcode, body.GetParameter (value));
+
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, long value)
+		{
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, float value)
+		{
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, double value)
+		{
+			return Instruction.Create (opcode, value);
+		}
+
+		public Instruction Create (OpCode opcode, Instruction target)
+		{
+			return Instruction.Create (opcode, target);
+		}
+
+		public Instruction Create (OpCode opcode, Instruction [] targets)
+		{
+			return Instruction.Create (opcode, targets);
+		}
+
+		public Instruction Create (OpCode opcode, VariableDefinition variable)
+		{
+			return Instruction.Create (opcode, variable);
+		}
+
+		public Instruction Create (OpCode opcode, ParameterDefinition parameter)
+		{
+			return Instruction.Create (opcode, parameter);
+		}
+
+		public void Emit (OpCode opcode)
+		{
+			Append (Create (opcode));
+		}
+
+		public void Emit (OpCode opcode, TypeReference type)
+		{
+			Append (Create (opcode, type));
+		}
+
+		public void Emit (OpCode opcode, MethodReference method)
+		{
+			Append (Create (opcode, method));
+		}
+
+		public void Emit (OpCode opcode, CallSite site)
+		{
+			Append (Create (opcode, site));
+		}
+
+		public void Emit (OpCode opcode, FieldReference field)
+		{
+			Append (Create (opcode, field));
+		}
+
+		public void Emit (OpCode opcode, string value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, byte value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, sbyte value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, int value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, long value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, float value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, double value)
+		{
+			Append (Create (opcode, value));
+		}
+
+		public void Emit (OpCode opcode, Instruction target)
+		{
+			Append (Create (opcode, target));
+		}
+
+		public void Emit (OpCode opcode, Instruction [] targets)
+		{
+			Append (Create (opcode, targets));
+		}
+
+		public void Emit (OpCode opcode, VariableDefinition variable)
+		{
+			Append (Create (opcode, variable));
+		}
+
+		public void Emit (OpCode opcode, ParameterDefinition parameter)
+		{
+			Append (Create (opcode, parameter));
+		}
+
+		public void InsertBefore (Instruction target, Instruction instruction)
+		{
+			if (target == null)
+				throw new ArgumentNullException ("target");
+			if (instruction == null)
+				throw new ArgumentNullException ("instruction");
+
+			var index = instructions.IndexOf (target);
+			if (index == -1)
+				throw new ArgumentOutOfRangeException ("target");
+
+			instructions.Insert (index, instruction);
+		}
+
+		public void InsertAfter (Instruction target, Instruction instruction)
+		{
+			if (target == null)
+				throw new ArgumentNullException ("target");
+			if (instruction == null)
+				throw new ArgumentNullException ("instruction");
+
+			var index = instructions.IndexOf (target);
+			if (index == -1)
+				throw new ArgumentOutOfRangeException ("target");
+
+			instructions.Insert (index + 1, instruction);
+		}
+
+		public void Append (Instruction instruction)
+		{
+			if (instruction == null)
+				throw new ArgumentNullException ("instruction");
+
+			instructions.Add (instruction);
+		}
+
+		public void Replace (Instruction target, Instruction instruction)
+		{
+			if (target == null)
+				throw new ArgumentNullException ("target");
+			if (instruction == null)
+				throw new ArgumentNullException ("instruction");
+
+			InsertAfter (target, instruction);
+			Remove (target);
+		}
+
+		public void Remove (Instruction instruction)
+		{
+			if (instruction == null)
+				throw new ArgumentNullException ("instruction");
+
+			if (!instructions.Remove (instruction))
+				throw new ArgumentOutOfRangeException ("instruction");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Instruction.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Instruction.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Instruction.cs	(revision 11807)
@@ -0,0 +1,321 @@
+//
+// Instruction.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+
+namespace Mono.Cecil.Cil {
+
+	public sealed class Instruction {
+
+		internal int offset;
+		internal OpCode opcode;
+		internal object operand;
+
+		internal Instruction previous;
+		internal Instruction next;
+
+		SequencePoint sequence_point;
+
+		public int Offset {
+			get { return offset; }
+			set { offset = value; }
+		}
+
+		public OpCode OpCode {
+			get { return opcode; }
+			set { opcode = value; }
+		}
+
+		public object Operand {
+			get { return operand; }
+			set { operand = value; }
+		}
+
+		public Instruction Previous {
+			get { return previous; }
+			set { previous = value; }
+		}
+
+		public Instruction Next {
+			get { return next; }
+			set { next = value; }
+		}
+
+		public SequencePoint SequencePoint {
+			get { return sequence_point; }
+			set { sequence_point = value; }
+		}
+
+		internal Instruction (int offset, OpCode opCode)
+		{
+			this.offset = offset;
+			this.opcode = opCode;
+		}
+
+		internal Instruction (OpCode opcode, object operand)
+		{
+			this.opcode = opcode;
+			this.operand = operand;
+		}
+
+		public int GetSize ()
+		{
+			int size = opcode.Size;
+
+			switch (opcode.OperandType) {
+			case OperandType.InlineSwitch:
+				return size + (1 + ((Instruction []) operand).Length) * 4;
+			case OperandType.InlineI8:
+			case OperandType.InlineR:
+				return size + 8;
+			case OperandType.InlineBrTarget:
+			case OperandType.InlineField:
+			case OperandType.InlineI:
+			case OperandType.InlineMethod:
+			case OperandType.InlineString:
+			case OperandType.InlineTok:
+			case OperandType.InlineType:
+			case OperandType.ShortInlineR:
+			case OperandType.InlineSig:
+				return size + 4;
+			case OperandType.InlineArg:
+			case OperandType.InlineVar:
+				return size + 2;
+			case OperandType.ShortInlineBrTarget:
+			case OperandType.ShortInlineI:
+			case OperandType.ShortInlineArg:
+			case OperandType.ShortInlineVar:
+				return size + 1;
+			default:
+				return size;
+			}
+		}
+
+		public override string ToString ()
+		{
+			var instruction = new StringBuilder ();
+
+			AppendLabel (instruction, this);
+			instruction.Append (':');
+			instruction.Append (' ');
+			instruction.Append (opcode.Name);
+
+			if (operand == null)
+				return instruction.ToString ();
+
+			instruction.Append (' ');
+
+			switch (opcode.OperandType) {
+			case OperandType.ShortInlineBrTarget:
+			case OperandType.InlineBrTarget:
+				AppendLabel (instruction, (Instruction) operand);
+				break;
+			case OperandType.InlineSwitch:
+				var labels = (Instruction []) operand;
+				for (int i = 0; i < labels.Length; i++) {
+					if (i > 0)
+						instruction.Append (',');
+
+					AppendLabel (instruction, labels [i]);
+				}
+				break;
+			case OperandType.InlineString:
+				instruction.Append ('\"');
+				instruction.Append (operand);
+				instruction.Append ('\"');
+				break;
+			default:
+				instruction.Append (operand);
+				break;
+			}
+
+			return instruction.ToString ();
+		}
+
+		static void AppendLabel (StringBuilder builder, Instruction instruction)
+		{
+			builder.Append ("IL_");
+			builder.Append (instruction.offset.ToString ("x4"));
+		}
+
+		public static Instruction Create (OpCode opcode)
+		{
+			if (opcode.OperandType != OperandType.InlineNone)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, null);
+		}
+
+		public static Instruction Create (OpCode opcode, TypeReference type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ("type");
+			if (opcode.OperandType != OperandType.InlineType &&
+				opcode.OperandType != OperandType.InlineTok)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, type);
+		}
+
+		public static Instruction Create (OpCode opcode, CallSite site)
+		{
+			if (site == null)
+				throw new ArgumentNullException ("site");
+			if (opcode.Code != Code.Calli)
+				throw new ArgumentException ("code");
+
+			return new Instruction (opcode, site);
+		}
+
+		public static Instruction Create (OpCode opcode, MethodReference method)
+		{
+			if (method == null)
+				throw new ArgumentNullException ("method");
+			if (opcode.OperandType != OperandType.InlineMethod &&
+				opcode.OperandType != OperandType.InlineTok)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, method);
+		}
+
+		public static Instruction Create (OpCode opcode, FieldReference field)
+		{
+			if (field == null)
+				throw new ArgumentNullException ("field");
+			if (opcode.OperandType != OperandType.InlineField &&
+				opcode.OperandType != OperandType.InlineTok)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, field);
+		}
+
+		public static Instruction Create (OpCode opcode, string value)
+		{
+			if (value == null)
+				throw new ArgumentNullException ("value");
+			if (opcode.OperandType != OperandType.InlineString)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, sbyte value)
+		{
+			if (opcode.OperandType != OperandType.ShortInlineI &&
+				opcode != OpCodes.Ldc_I4_S)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, byte value)
+		{
+			if (opcode.OperandType != OperandType.ShortInlineI ||
+				opcode == OpCodes.Ldc_I4_S)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, int value)
+		{
+			if (opcode.OperandType != OperandType.InlineI)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, long value)
+		{
+			if (opcode.OperandType != OperandType.InlineI8)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, float value)
+		{
+			if (opcode.OperandType != OperandType.ShortInlineR)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, double value)
+		{
+			if (opcode.OperandType != OperandType.InlineR)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, value);
+		}
+
+		public static Instruction Create (OpCode opcode, Instruction target)
+		{
+			if (target == null)
+				throw new ArgumentNullException ("target");
+			if (opcode.OperandType != OperandType.InlineBrTarget &&
+				opcode.OperandType != OperandType.ShortInlineBrTarget)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, target);
+		}
+
+		public static Instruction Create (OpCode opcode, Instruction [] targets)
+		{
+			if (targets == null)
+				throw new ArgumentNullException ("targets");
+			if (opcode.OperandType != OperandType.InlineSwitch)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, targets);
+		}
+
+		public static Instruction Create (OpCode opcode, VariableDefinition variable)
+		{
+			if (variable == null)
+				throw new ArgumentNullException ("variable");
+			if (opcode.OperandType != OperandType.ShortInlineVar &&
+				opcode.OperandType != OperandType.InlineVar)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, variable);
+		}
+
+		public static Instruction Create (OpCode opcode, ParameterDefinition parameter)
+		{
+			if (parameter == null)
+				throw new ArgumentNullException ("parameter");
+			if (opcode.OperandType != OperandType.ShortInlineArg &&
+				opcode.OperandType != OperandType.InlineArg)
+				throw new ArgumentException ("opcode");
+
+			return new Instruction (opcode, parameter);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/MethodBody.cs	(revision 11807)
@@ -0,0 +1,230 @@
+//
+// MethodBody.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil.Cil {
+
+	public sealed class MethodBody : IVariableDefinitionProvider {
+
+		readonly internal MethodDefinition method;
+
+		internal ParameterDefinition this_parameter;
+		internal int max_stack_size;
+		internal int code_size;
+		internal bool init_locals;
+		internal MetadataToken local_var_token;
+
+		internal Collection<Instruction> instructions;
+		internal Collection<ExceptionHandler> exceptions;
+		internal Collection<VariableDefinition> variables;
+		Scope scope;
+
+		public MethodDefinition Method {
+			get { return method; }
+		}
+
+		public int MaxStackSize {
+			get { return max_stack_size; }
+			set { max_stack_size = value; }
+		}
+
+		public int CodeSize {
+			get { return code_size; }
+		}
+
+		public bool InitLocals {
+			get { return init_locals; }
+			set { init_locals = value; }
+		}
+
+		public MetadataToken LocalVarToken {
+			get { return local_var_token; }
+			set { local_var_token = value; }
+		}
+
+		public Collection<Instruction> Instructions {
+			get { return instructions ?? (instructions = new InstructionCollection ()); }
+		}
+
+		public bool HasExceptionHandlers {
+			get { return !exceptions.IsNullOrEmpty (); }
+		}
+
+		public Collection<ExceptionHandler> ExceptionHandlers {
+			get { return exceptions ?? (exceptions = new Collection<ExceptionHandler> ()); }
+		}
+
+		public bool HasVariables {
+			get { return !variables.IsNullOrEmpty (); }
+		}
+
+		public Collection<VariableDefinition> Variables {
+			get { return variables ?? (variables = new VariableDefinitionCollection ()); }
+		}
+
+		public Scope Scope {
+			get { return scope; }
+			set { scope = value; }
+		}
+
+		public ParameterDefinition ThisParameter {
+			get {
+				if (method == null || method.DeclaringType == null)
+					throw new NotSupportedException ();
+
+				return this_parameter ?? (this_parameter = new ParameterDefinition ("0", ParameterAttributes.None, method.DeclaringType));
+			}
+		}
+
+		public MethodBody (MethodDefinition method)
+		{
+			this.method = method;
+		}
+
+		public ILProcessor GetILProcessor ()
+		{
+			return new ILProcessor (this);
+		}
+	}
+
+	public interface IVariableDefinitionProvider {
+		bool HasVariables { get; }
+		Collection<VariableDefinition> Variables { get; }
+	}
+
+	class VariableDefinitionCollection : Collection<VariableDefinition> {
+
+		internal VariableDefinitionCollection ()
+		{
+		}
+
+		internal VariableDefinitionCollection (int capacity)
+			: base (capacity)
+		{
+		}
+
+		protected override void OnAdd (VariableDefinition item, int index)
+		{
+			item.index = index;
+		}
+
+		protected override void OnInsert (VariableDefinition item, int index)
+		{
+			item.index = index;
+
+			for (int i = index; i < size; i++)
+				items [i].index = i + 1;
+		}
+
+		protected override void OnSet (VariableDefinition item, int index)
+		{
+			item.index = index;
+		}
+
+		protected override void OnRemove (VariableDefinition item, int index)
+		{
+			item.index = -1;
+
+			for (int i = index + 1; i < size; i++)
+				items [i].index = i - 1;
+		}
+	}
+
+	class InstructionCollection : Collection<Instruction> {
+
+		internal InstructionCollection ()
+		{
+		}
+
+		internal InstructionCollection (int capacity)
+			: base (capacity)
+		{
+		}
+
+		protected override void OnAdd (Instruction item, int index)
+		{
+			if (index == 0)
+				return;
+
+			var previous = items [index - 1];
+			previous.next = item;
+			item.previous = previous;
+		}
+
+		protected override void OnInsert (Instruction item, int index)
+		{
+			if (size == 0)
+				return;
+
+			var current = items [index];
+			if (current == null) {
+				var last = items [index - 1];
+				last.next = item;
+				item.previous = last;
+				return;
+			}
+
+			var previous = current.previous;
+			if (previous != null) {
+				previous.next = item;
+				item.previous = previous;
+			}
+
+			current.previous = item;
+			item.next = current;
+		}
+
+		protected override void OnSet (Instruction item, int index)
+		{
+			var current = items [index];
+
+			item.previous = current.previous;
+			item.next = current.next;
+
+			current.previous = null;
+			current.next = null;
+		}
+
+		protected override void OnRemove (Instruction item, int index)
+		{
+			var previous = item.previous;
+			if (previous != null)
+				previous.next = item.next;
+
+			var next = item.next;
+			if (next != null)
+				next.previous = item.previous;
+
+			item.previous = null;
+			item.next = null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/OpCode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/OpCode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/OpCode.cs	(revision 11807)
@@ -0,0 +1,455 @@
+//
+// OpCode.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public enum FlowControl {
+		Branch,
+		Break,
+		Call,
+		Cond_Branch,
+		Meta,
+		Next,
+		Phi,
+		Return,
+		Throw,
+	}
+
+	public enum OpCodeType {
+		Annotation,
+		Macro,
+		Nternal,
+		Objmodel,
+		Prefix,
+		Primitive,
+	}
+
+	public enum OperandType {
+		InlineBrTarget,
+		InlineField,
+		InlineI,
+		InlineI8,
+		InlineMethod,
+		InlineNone,
+		InlinePhi,
+		InlineR,
+		InlineSig,
+		InlineString,
+		InlineSwitch,
+		InlineTok,
+		InlineType,
+		InlineVar,
+		InlineArg,
+		ShortInlineBrTarget,
+		ShortInlineI,
+		ShortInlineR,
+		ShortInlineVar,
+		ShortInlineArg,
+	}
+
+	public enum StackBehaviour {
+		Pop0,
+		Pop1,
+		Pop1_pop1,
+		Popi,
+		Popi_pop1,
+		Popi_popi,
+		Popi_popi8,
+		Popi_popi_popi,
+		Popi_popr4,
+		Popi_popr8,
+		Popref,
+		Popref_pop1,
+		Popref_popi,
+		Popref_popi_popi,
+		Popref_popi_popi8,
+		Popref_popi_popr4,
+		Popref_popi_popr8,
+		Popref_popi_popref,
+		PopAll,
+		Push0,
+		Push1,
+		Push1_push1,
+		Pushi,
+		Pushi8,
+		Pushr4,
+		Pushr8,
+		Pushref,
+		Varpop,
+		Varpush,
+	}
+
+	public struct OpCode {
+
+		readonly byte op1;
+		readonly byte op2;
+		readonly byte code;
+		readonly byte flow_control;
+		readonly byte opcode_type;
+		readonly byte operand_type;
+		readonly byte stack_behavior_pop;
+		readonly byte stack_behavior_push;
+
+		public string Name {
+			get { return OpCodeNames.names [(int) Code]; }
+		}
+
+		public int Size {
+			get { return op1 == 0xff ? 1 : 2; }
+		}
+
+		public byte Op1 {
+			get { return op1; }
+		}
+
+		public byte Op2 {
+			get { return op2; }
+		}
+
+		public short Value {
+			get { return op1 == 0xff ? op2 : (short) ((op1 << 8) | op2); }
+		}
+
+		public Code Code {
+			get { return (Code) code; }
+		}
+
+		public FlowControl FlowControl {
+			get { return (FlowControl) flow_control; }
+		}
+
+		public OpCodeType OpCodeType {
+			get { return (OpCodeType) opcode_type; }
+		}
+
+		public OperandType OperandType {
+			get { return (OperandType) operand_type; }
+		}
+
+		public StackBehaviour StackBehaviourPop {
+			get { return (StackBehaviour) stack_behavior_pop; }
+		}
+
+		public StackBehaviour StackBehaviourPush {
+			get { return (StackBehaviour) stack_behavior_push; }
+		}
+
+		internal OpCode (int x, int y)
+		{
+			this.op1 = (byte) ((x >> 0) & 0xff);
+			this.op2 = (byte) ((x >> 8) & 0xff);
+			this.code = (byte) ((x >> 16) & 0xff);
+			this.flow_control = (byte) ((x >> 24) & 0xff);
+
+			this.opcode_type = (byte) ((y >> 0) & 0xff);
+			this.operand_type = (byte) ((y >> 8) & 0xff);
+			this.stack_behavior_pop = (byte) ((y >> 16) & 0xff);
+			this.stack_behavior_push = (byte) ((y >> 24) & 0xff);
+
+			if (op1 == 0xff)
+				OpCodes.OneByteOpCode [op2] = this;
+			else
+				OpCodes.TwoBytesOpCode [op2] = this;
+		}
+
+		public override int GetHashCode ()
+		{
+			return Value;
+		}
+
+		public override bool Equals (object obj)
+		{
+			if (!(obj is OpCode))
+				return false;
+
+			var opcode = (OpCode) obj;
+			return op1 == opcode.op1 && op2 == opcode.op2;
+		}
+
+		public bool Equals (OpCode opcode)
+		{
+			return op1 == opcode.op1 && op2 == opcode.op2;
+		}
+
+		public static bool operator == (OpCode one, OpCode other)
+		{
+			return one.op1 == other.op1 && one.op2 == other.op2;
+		}
+
+		public static bool operator != (OpCode one, OpCode other)
+		{
+			return one.op1 != other.op1 || one.op2 != other.op2;
+		}
+
+		public override string ToString ()
+		{
+			return Name;
+		}
+	}
+
+	static class OpCodeNames {
+
+		internal static readonly string [] names;
+
+		static OpCodeNames ()
+		{
+			var table = new byte [] {
+				3, 110, 111, 112,
+				5, 98, 114, 101, 97, 107,
+				7, 108, 100, 97, 114, 103, 46, 48,
+				7, 108, 100, 97, 114, 103, 46, 49,
+				7, 108, 100, 97, 114, 103, 46, 50,
+				7, 108, 100, 97, 114, 103, 46, 51,
+				7, 108, 100, 108, 111, 99, 46, 48,
+				7, 108, 100, 108, 111, 99, 46, 49,
+				7, 108, 100, 108, 111, 99, 46, 50,
+				7, 108, 100, 108, 111, 99, 46, 51,
+				7, 115, 116, 108, 111, 99, 46, 48,
+				7, 115, 116, 108, 111, 99, 46, 49,
+				7, 115, 116, 108, 111, 99, 46, 50,
+				7, 115, 116, 108, 111, 99, 46, 51,
+				7, 108, 100, 97, 114, 103, 46, 115,
+				8, 108, 100, 97, 114, 103, 97, 46, 115,
+				7, 115, 116, 97, 114, 103, 46, 115,
+				7, 108, 100, 108, 111, 99, 46, 115,
+				8, 108, 100, 108, 111, 99, 97, 46, 115,
+				7, 115, 116, 108, 111, 99, 46, 115,
+				6, 108, 100, 110, 117, 108, 108,
+				9, 108, 100, 99, 46, 105, 52, 46, 109, 49,
+				8, 108, 100, 99, 46, 105, 52, 46, 48,
+				8, 108, 100, 99, 46, 105, 52, 46, 49,
+				8, 108, 100, 99, 46, 105, 52, 46, 50,
+				8, 108, 100, 99, 46, 105, 52, 46, 51,
+				8, 108, 100, 99, 46, 105, 52, 46, 52,
+				8, 108, 100, 99, 46, 105, 52, 46, 53,
+				8, 108, 100, 99, 46, 105, 52, 46, 54,
+				8, 108, 100, 99, 46, 105, 52, 46, 55,
+				8, 108, 100, 99, 46, 105, 52, 46, 56,
+				8, 108, 100, 99, 46, 105, 52, 46, 115,
+				6, 108, 100, 99, 46, 105, 52,
+				6, 108, 100, 99, 46, 105, 56,
+				6, 108, 100, 99, 46, 114, 52,
+				6, 108, 100, 99, 46, 114, 56,
+				3, 100, 117, 112,
+				3, 112, 111, 112,
+				3, 106, 109, 112,
+				4, 99, 97, 108, 108,
+				5, 99, 97, 108, 108, 105,
+				3, 114, 101, 116,
+				4, 98, 114, 46, 115,
+				9, 98, 114, 102, 97, 108, 115, 101, 46, 115,
+				8, 98, 114, 116, 114, 117, 101, 46, 115,
+				5, 98, 101, 113, 46, 115,
+				5, 98, 103, 101, 46, 115,
+				5, 98, 103, 116, 46, 115,
+				5, 98, 108, 101, 46, 115,
+				5, 98, 108, 116, 46, 115,
+				8, 98, 110, 101, 46, 117, 110, 46, 115,
+				8, 98, 103, 101, 46, 117, 110, 46, 115,
+				8, 98, 103, 116, 46, 117, 110, 46, 115,
+				8, 98, 108, 101, 46, 117, 110, 46, 115,
+				8, 98, 108, 116, 46, 117, 110, 46, 115,
+				2, 98, 114,
+				7, 98, 114, 102, 97, 108, 115, 101,
+				6, 98, 114, 116, 114, 117, 101,
+				3, 98, 101, 113,
+				3, 98, 103, 101,
+				3, 98, 103, 116,
+				3, 98, 108, 101,
+				3, 98, 108, 116,
+				6, 98, 110, 101, 46, 117, 110,
+				6, 98, 103, 101, 46, 117, 110,
+				6, 98, 103, 116, 46, 117, 110,
+				6, 98, 108, 101, 46, 117, 110,
+				6, 98, 108, 116, 46, 117, 110,
+				6, 115, 119, 105, 116, 99, 104,
+				8, 108, 100, 105, 110, 100, 46, 105, 49,
+				8, 108, 100, 105, 110, 100, 46, 117, 49,
+				8, 108, 100, 105, 110, 100, 46, 105, 50,
+				8, 108, 100, 105, 110, 100, 46, 117, 50,
+				8, 108, 100, 105, 110, 100, 46, 105, 52,
+				8, 108, 100, 105, 110, 100, 46, 117, 52,
+				8, 108, 100, 105, 110, 100, 46, 105, 56,
+				7, 108, 100, 105, 110, 100, 46, 105,
+				8, 108, 100, 105, 110, 100, 46, 114, 52,
+				8, 108, 100, 105, 110, 100, 46, 114, 56,
+				9, 108, 100, 105, 110, 100, 46, 114, 101, 102,
+				9, 115, 116, 105, 110, 100, 46, 114, 101, 102,
+				8, 115, 116, 105, 110, 100, 46, 105, 49,
+				8, 115, 116, 105, 110, 100, 46, 105, 50,
+				8, 115, 116, 105, 110, 100, 46, 105, 52,
+				8, 115, 116, 105, 110, 100, 46, 105, 56,
+				8, 115, 116, 105, 110, 100, 46, 114, 52,
+				8, 115, 116, 105, 110, 100, 46, 114, 56,
+				3, 97, 100, 100,
+				3, 115, 117, 98,
+				3, 109, 117, 108,
+				3, 100, 105, 118,
+				6, 100, 105, 118, 46, 117, 110,
+				3, 114, 101, 109,
+				6, 114, 101, 109, 46, 117, 110,
+				3, 97, 110, 100,
+				2, 111, 114,
+				3, 120, 111, 114,
+				3, 115, 104, 108,
+				3, 115, 104, 114,
+				6, 115, 104, 114, 46, 117, 110,
+				3, 110, 101, 103,
+				3, 110, 111, 116,
+				7, 99, 111, 110, 118, 46, 105, 49,
+				7, 99, 111, 110, 118, 46, 105, 50,
+				7, 99, 111, 110, 118, 46, 105, 52,
+				7, 99, 111, 110, 118, 46, 105, 56,
+				7, 99, 111, 110, 118, 46, 114, 52,
+				7, 99, 111, 110, 118, 46, 114, 56,
+				7, 99, 111, 110, 118, 46, 117, 52,
+				7, 99, 111, 110, 118, 46, 117, 56,
+				8, 99, 97, 108, 108, 118, 105, 114, 116,
+				5, 99, 112, 111, 98, 106,
+				5, 108, 100, 111, 98, 106,
+				5, 108, 100, 115, 116, 114,
+				6, 110, 101, 119, 111, 98, 106,
+				9, 99, 97, 115, 116, 99, 108, 97, 115, 115,
+				6, 105, 115, 105, 110, 115, 116,
+				9, 99, 111, 110, 118, 46, 114, 46, 117, 110,
+				5, 117, 110, 98, 111, 120,
+				5, 116, 104, 114, 111, 119,
+				5, 108, 100, 102, 108, 100,
+				6, 108, 100, 102, 108, 100, 97,
+				5, 115, 116, 102, 108, 100,
+				6, 108, 100, 115, 102, 108, 100,
+				7, 108, 100, 115, 102, 108, 100, 97,
+				6, 115, 116, 115, 102, 108, 100,
+				5, 115, 116, 111, 98, 106,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52, 46, 117, 110,
+				14, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56, 46, 117, 110,
+				13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 46, 117, 110,
+				13, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 46, 117, 110,
+				3, 98, 111, 120,
+				6, 110, 101, 119, 97, 114, 114,
+				5, 108, 100, 108, 101, 110,
+				7, 108, 100, 101, 108, 101, 109, 97,
+				9, 108, 100, 101, 108, 101, 109, 46, 105, 49,
+				9, 108, 100, 101, 108, 101, 109, 46, 117, 49,
+				9, 108, 100, 101, 108, 101, 109, 46, 105, 50,
+				9, 108, 100, 101, 108, 101, 109, 46, 117, 50,
+				9, 108, 100, 101, 108, 101, 109, 46, 105, 52,
+				9, 108, 100, 101, 108, 101, 109, 46, 117, 52,
+				9, 108, 100, 101, 108, 101, 109, 46, 105, 56,
+				8, 108, 100, 101, 108, 101, 109, 46, 105,
+				9, 108, 100, 101, 108, 101, 109, 46, 114, 52,
+				9, 108, 100, 101, 108, 101, 109, 46, 114, 56,
+				10, 108, 100, 101, 108, 101, 109, 46, 114, 101, 102,
+				8, 115, 116, 101, 108, 101, 109, 46, 105,
+				9, 115, 116, 101, 108, 101, 109, 46, 105, 49,
+				9, 115, 116, 101, 108, 101, 109, 46, 105, 50,
+				9, 115, 116, 101, 108, 101, 109, 46, 105, 52,
+				9, 115, 116, 101, 108, 101, 109, 46, 105, 56,
+				9, 115, 116, 101, 108, 101, 109, 46, 114, 52,
+				9, 115, 116, 101, 108, 101, 109, 46, 114, 56,
+				10, 115, 116, 101, 108, 101, 109, 46, 114, 101, 102,
+				10, 108, 100, 101, 108, 101, 109, 46, 97, 110, 121,
+				10, 115, 116, 101, 108, 101, 109, 46, 97, 110, 121,
+				9, 117, 110, 98, 111, 120, 46, 97, 110, 121,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 49,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 49,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 50,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 50,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 52,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 52,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105, 56,
+				11, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117, 56,
+				9, 114, 101, 102, 97, 110, 121, 118, 97, 108,
+				8, 99, 107, 102, 105, 110, 105, 116, 101,
+				8, 109, 107, 114, 101, 102, 97, 110, 121,
+				7, 108, 100, 116, 111, 107, 101, 110,
+				7, 99, 111, 110, 118, 46, 117, 50,
+				7, 99, 111, 110, 118, 46, 117, 49,
+				6, 99, 111, 110, 118, 46, 105,
+				10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 105,
+				10, 99, 111, 110, 118, 46, 111, 118, 102, 46, 117,
+				7, 97, 100, 100, 46, 111, 118, 102,
+				10, 97, 100, 100, 46, 111, 118, 102, 46, 117, 110,
+				7, 109, 117, 108, 46, 111, 118, 102,
+				10, 109, 117, 108, 46, 111, 118, 102, 46, 117, 110,
+				7, 115, 117, 98, 46, 111, 118, 102,
+				10, 115, 117, 98, 46, 111, 118, 102, 46, 117, 110,
+				10, 101, 110, 100, 102, 105, 110, 97, 108, 108, 121,
+				5, 108, 101, 97, 118, 101,
+				7, 108, 101, 97, 118, 101, 46, 115,
+				7, 115, 116, 105, 110, 100, 46, 105,
+				6, 99, 111, 110, 118, 46, 117,
+				7, 97, 114, 103, 108, 105, 115, 116,
+				3, 99, 101, 113,
+				3, 99, 103, 116,
+				6, 99, 103, 116, 46, 117, 110,
+				3, 99, 108, 116,
+				6, 99, 108, 116, 46, 117, 110,
+				5, 108, 100, 102, 116, 110,
+				9, 108, 100, 118, 105, 114, 116, 102, 116, 110,
+				5, 108, 100, 97, 114, 103,
+				6, 108, 100, 97, 114, 103, 97,
+				5, 115, 116, 97, 114, 103,
+				5, 108, 100, 108, 111, 99,
+				6, 108, 100, 108, 111, 99, 97,
+				5, 115, 116, 108, 111, 99,
+				8, 108, 111, 99, 97, 108, 108, 111, 99,
+				9, 101, 110, 100, 102, 105, 108, 116, 101, 114,
+				10, 117, 110, 97, 108, 105, 103, 110, 101, 100, 46,
+				9, 118, 111, 108, 97, 116, 105, 108, 101, 46,
+				5, 116, 97, 105, 108, 46,
+				7, 105, 110, 105, 116, 111, 98, 106,
+				12, 99, 111, 110, 115, 116, 114, 97, 105, 110, 101, 100, 46,
+				5, 99, 112, 98, 108, 107,
+				7, 105, 110, 105, 116, 98, 108, 107,
+				3, 110, 111, 46,
+				7, 114, 101, 116, 104, 114, 111, 119,
+				6, 115, 105, 122, 101, 111, 102,
+				10, 114, 101, 102, 97, 110, 121, 116, 121, 112, 101,
+				9, 114, 101, 97, 100, 111, 110, 108, 121, 46,
+			};
+
+			names = new string [219];
+
+			for (int i = 0, p = 0; i < names.Length; i++) {
+				var buffer = new char [table [p++]];
+
+				for (int j = 0; j < buffer.Length; j++)
+					buffer [j] = (char) table [p++];
+
+				names [i] = new string (buffer);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/OpCodes.cs	(revision 11807)
@@ -0,0 +1,912 @@
+//
+// OpCodes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public static class OpCodes {
+
+		internal static readonly OpCode [] OneByteOpCode = new OpCode [0xe0 + 1];
+		internal static readonly OpCode [] TwoBytesOpCode = new OpCode [0x1e + 1];
+
+		public static readonly OpCode Nop = new OpCode (
+			0xff << 0 | 0x00 << 8 | (byte) Code.Nop << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Break = new OpCode (
+			0xff << 0 | 0x01 << 8 | (byte) Code.Break << 16 | (byte) FlowControl.Break << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldarg_0 = new OpCode (
+			0xff << 0 | 0x02 << 8 | (byte) Code.Ldarg_0 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldarg_1 = new OpCode (
+			0xff << 0 | 0x03 << 8 | (byte) Code.Ldarg_1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldarg_2 = new OpCode (
+			0xff << 0 | 0x04 << 8 | (byte) Code.Ldarg_2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldarg_3 = new OpCode (
+			0xff << 0 | 0x05 << 8 | (byte) Code.Ldarg_3 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldloc_0 = new OpCode (
+			0xff << 0 | 0x06 << 8 | (byte) Code.Ldloc_0 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldloc_1 = new OpCode (
+			0xff << 0 | 0x07 << 8 | (byte) Code.Ldloc_1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldloc_2 = new OpCode (
+			0xff << 0 | 0x08 << 8 | (byte) Code.Ldloc_2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldloc_3 = new OpCode (
+			0xff << 0 | 0x09 << 8 | (byte) Code.Ldloc_3 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Stloc_0 = new OpCode (
+			0xff << 0 | 0x0a << 8 | (byte) Code.Stloc_0 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stloc_1 = new OpCode (
+			0xff << 0 | 0x0b << 8 | (byte) Code.Stloc_1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stloc_2 = new OpCode (
+			0xff << 0 | 0x0c << 8 | (byte) Code.Stloc_2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stloc_3 = new OpCode (
+			0xff << 0 | 0x0d << 8 | (byte) Code.Stloc_3 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldarg_S = new OpCode (
+			0xff << 0 | 0x0e << 8 | (byte) Code.Ldarg_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldarga_S = new OpCode (
+			0xff << 0 | 0x0f << 8 | (byte) Code.Ldarga_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Starg_S = new OpCode (
+			0xff << 0 | 0x10 << 8 | (byte) Code.Starg_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineArg << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldloc_S = new OpCode (
+			0xff << 0 | 0x11 << 8 | (byte) Code.Ldloc_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldloca_S = new OpCode (
+			0xff << 0 | 0x12 << 8 | (byte) Code.Ldloca_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Stloc_S = new OpCode (
+			0xff << 0 | 0x13 << 8 | (byte) Code.Stloc_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineVar << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldnull = new OpCode (
+			0xff << 0 | 0x14 << 8 | (byte) Code.Ldnull << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Ldc_I4_M1 = new OpCode (
+			0xff << 0 | 0x15 << 8 | (byte) Code.Ldc_I4_M1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_0 = new OpCode (
+			0xff << 0 | 0x16 << 8 | (byte) Code.Ldc_I4_0 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_1 = new OpCode (
+			0xff << 0 | 0x17 << 8 | (byte) Code.Ldc_I4_1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_2 = new OpCode (
+			0xff << 0 | 0x18 << 8 | (byte) Code.Ldc_I4_2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_3 = new OpCode (
+			0xff << 0 | 0x19 << 8 | (byte) Code.Ldc_I4_3 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_4 = new OpCode (
+			0xff << 0 | 0x1a << 8 | (byte) Code.Ldc_I4_4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_5 = new OpCode (
+			0xff << 0 | 0x1b << 8 | (byte) Code.Ldc_I4_5 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_6 = new OpCode (
+			0xff << 0 | 0x1c << 8 | (byte) Code.Ldc_I4_6 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_7 = new OpCode (
+			0xff << 0 | 0x1d << 8 | (byte) Code.Ldc_I4_7 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_8 = new OpCode (
+			0xff << 0 | 0x1e << 8 | (byte) Code.Ldc_I4_8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4_S = new OpCode (
+			0xff << 0 | 0x1f << 8 | (byte) Code.Ldc_I4_S << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I4 = new OpCode (
+			0xff << 0 | 0x20 << 8 | (byte) Code.Ldc_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldc_I8 = new OpCode (
+			0xff << 0 | 0x21 << 8 | (byte) Code.Ldc_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineI8 << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Ldc_R4 = new OpCode (
+			0xff << 0 | 0x22 << 8 | (byte) Code.Ldc_R4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.ShortInlineR << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushr4 << 24);
+
+		public static readonly OpCode Ldc_R8 = new OpCode (
+			0xff << 0 | 0x23 << 8 | (byte) Code.Ldc_R8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineR << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushr8 << 24);
+
+		public static readonly OpCode Dup = new OpCode (
+			0xff << 0 | 0x25 << 8 | (byte) Code.Dup << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1_push1 << 24);
+
+		public static readonly OpCode Pop = new OpCode (
+			0xff << 0 | 0x26 << 8 | (byte) Code.Pop << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Jmp = new OpCode (
+			0xff << 0 | 0x27 << 8 | (byte) Code.Jmp << 16 | (byte) FlowControl.Call << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Call = new OpCode (
+			0xff << 0 | 0x28 << 8 | (byte) Code.Call << 16 | (byte) FlowControl.Call << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);
+
+		public static readonly OpCode Calli = new OpCode (
+			0xff << 0 | 0x29 << 8 | (byte) Code.Calli << 16 | (byte) FlowControl.Call << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineSig << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);
+
+		public static readonly OpCode Ret = new OpCode (
+			0xff << 0 | 0x2a << 8 | (byte) Code.Ret << 16 | (byte) FlowControl.Return << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Br_S = new OpCode (
+			0xff << 0 | 0x2b << 8 | (byte) Code.Br_S << 16 | (byte) FlowControl.Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Brfalse_S = new OpCode (
+			0xff << 0 | 0x2c << 8 | (byte) Code.Brfalse_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Brtrue_S = new OpCode (
+			0xff << 0 | 0x2d << 8 | (byte) Code.Brtrue_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Beq_S = new OpCode (
+			0xff << 0 | 0x2e << 8 | (byte) Code.Beq_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bge_S = new OpCode (
+			0xff << 0 | 0x2f << 8 | (byte) Code.Bge_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bgt_S = new OpCode (
+			0xff << 0 | 0x30 << 8 | (byte) Code.Bgt_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ble_S = new OpCode (
+			0xff << 0 | 0x31 << 8 | (byte) Code.Ble_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Blt_S = new OpCode (
+			0xff << 0 | 0x32 << 8 | (byte) Code.Blt_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bne_Un_S = new OpCode (
+			0xff << 0 | 0x33 << 8 | (byte) Code.Bne_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bge_Un_S = new OpCode (
+			0xff << 0 | 0x34 << 8 | (byte) Code.Bge_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bgt_Un_S = new OpCode (
+			0xff << 0 | 0x35 << 8 | (byte) Code.Bgt_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ble_Un_S = new OpCode (
+			0xff << 0 | 0x36 << 8 | (byte) Code.Ble_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Blt_Un_S = new OpCode (
+			0xff << 0 | 0x37 << 8 | (byte) Code.Blt_Un_S << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Br = new OpCode (
+			0xff << 0 | 0x38 << 8 | (byte) Code.Br << 16 | (byte) FlowControl.Branch << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Brfalse = new OpCode (
+			0xff << 0 | 0x39 << 8 | (byte) Code.Brfalse << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Brtrue = new OpCode (
+			0xff << 0 | 0x3a << 8 | (byte) Code.Brtrue << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Beq = new OpCode (
+			0xff << 0 | 0x3b << 8 | (byte) Code.Beq << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bge = new OpCode (
+			0xff << 0 | 0x3c << 8 | (byte) Code.Bge << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bgt = new OpCode (
+			0xff << 0 | 0x3d << 8 | (byte) Code.Bgt << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ble = new OpCode (
+			0xff << 0 | 0x3e << 8 | (byte) Code.Ble << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Blt = new OpCode (
+			0xff << 0 | 0x3f << 8 | (byte) Code.Blt << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bne_Un = new OpCode (
+			0xff << 0 | 0x40 << 8 | (byte) Code.Bne_Un << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bge_Un = new OpCode (
+			0xff << 0 | 0x41 << 8 | (byte) Code.Bge_Un << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Bgt_Un = new OpCode (
+			0xff << 0 | 0x42 << 8 | (byte) Code.Bgt_Un << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ble_Un = new OpCode (
+			0xff << 0 | 0x43 << 8 | (byte) Code.Ble_Un << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Blt_Un = new OpCode (
+			0xff << 0 | 0x44 << 8 | (byte) Code.Blt_Un << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Switch = new OpCode (
+			0xff << 0 | 0x45 << 8 | (byte) Code.Switch << 16 | (byte) FlowControl.Cond_Branch << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineSwitch << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldind_I1 = new OpCode (
+			0xff << 0 | 0x46 << 8 | (byte) Code.Ldind_I1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_U1 = new OpCode (
+			0xff << 0 | 0x47 << 8 | (byte) Code.Ldind_U1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_I2 = new OpCode (
+			0xff << 0 | 0x48 << 8 | (byte) Code.Ldind_I2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_U2 = new OpCode (
+			0xff << 0 | 0x49 << 8 | (byte) Code.Ldind_U2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_I4 = new OpCode (
+			0xff << 0 | 0x4a << 8 | (byte) Code.Ldind_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_U4 = new OpCode (
+			0xff << 0 | 0x4b << 8 | (byte) Code.Ldind_U4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_I8 = new OpCode (
+			0xff << 0 | 0x4c << 8 | (byte) Code.Ldind_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Ldind_I = new OpCode (
+			0xff << 0 | 0x4d << 8 | (byte) Code.Ldind_I << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldind_R4 = new OpCode (
+			0xff << 0 | 0x4e << 8 | (byte) Code.Ldind_R4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushr4 << 24);
+
+		public static readonly OpCode Ldind_R8 = new OpCode (
+			0xff << 0 | 0x4f << 8 | (byte) Code.Ldind_R8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushr8 << 24);
+
+		public static readonly OpCode Ldind_Ref = new OpCode (
+			0xff << 0 | 0x50 << 8 | (byte) Code.Ldind_Ref << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Stind_Ref = new OpCode (
+			0xff << 0 | 0x51 << 8 | (byte) Code.Stind_Ref << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_I1 = new OpCode (
+			0xff << 0 | 0x52 << 8 | (byte) Code.Stind_I1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_I2 = new OpCode (
+			0xff << 0 | 0x53 << 8 | (byte) Code.Stind_I2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_I4 = new OpCode (
+			0xff << 0 | 0x54 << 8 | (byte) Code.Stind_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_I8 = new OpCode (
+			0xff << 0 | 0x55 << 8 | (byte) Code.Stind_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi8 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_R4 = new OpCode (
+			0xff << 0 | 0x56 << 8 | (byte) Code.Stind_R4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popr4 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_R8 = new OpCode (
+			0xff << 0 | 0x57 << 8 | (byte) Code.Stind_R8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popr8 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Add = new OpCode (
+			0xff << 0 | 0x58 << 8 | (byte) Code.Add << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Sub = new OpCode (
+			0xff << 0 | 0x59 << 8 | (byte) Code.Sub << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Mul = new OpCode (
+			0xff << 0 | 0x5a << 8 | (byte) Code.Mul << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Div = new OpCode (
+			0xff << 0 | 0x5b << 8 | (byte) Code.Div << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Div_Un = new OpCode (
+			0xff << 0 | 0x5c << 8 | (byte) Code.Div_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Rem = new OpCode (
+			0xff << 0 | 0x5d << 8 | (byte) Code.Rem << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Rem_Un = new OpCode (
+			0xff << 0 | 0x5e << 8 | (byte) Code.Rem_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode And = new OpCode (
+			0xff << 0 | 0x5f << 8 | (byte) Code.And << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Or = new OpCode (
+			0xff << 0 | 0x60 << 8 | (byte) Code.Or << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Xor = new OpCode (
+			0xff << 0 | 0x61 << 8 | (byte) Code.Xor << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Shl = new OpCode (
+			0xff << 0 | 0x62 << 8 | (byte) Code.Shl << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Shr = new OpCode (
+			0xff << 0 | 0x63 << 8 | (byte) Code.Shr << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Shr_Un = new OpCode (
+			0xff << 0 | 0x64 << 8 | (byte) Code.Shr_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Neg = new OpCode (
+			0xff << 0 | 0x65 << 8 | (byte) Code.Neg << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Not = new OpCode (
+			0xff << 0 | 0x66 << 8 | (byte) Code.Not << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Conv_I1 = new OpCode (
+			0xff << 0 | 0x67 << 8 | (byte) Code.Conv_I1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_I2 = new OpCode (
+			0xff << 0 | 0x68 << 8 | (byte) Code.Conv_I2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_I4 = new OpCode (
+			0xff << 0 | 0x69 << 8 | (byte) Code.Conv_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_I8 = new OpCode (
+			0xff << 0 | 0x6a << 8 | (byte) Code.Conv_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Conv_R4 = new OpCode (
+			0xff << 0 | 0x6b << 8 | (byte) Code.Conv_R4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr4 << 24);
+
+		public static readonly OpCode Conv_R8 = new OpCode (
+			0xff << 0 | 0x6c << 8 | (byte) Code.Conv_R8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);
+
+		public static readonly OpCode Conv_U4 = new OpCode (
+			0xff << 0 | 0x6d << 8 | (byte) Code.Conv_U4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_U8 = new OpCode (
+			0xff << 0 | 0x6e << 8 | (byte) Code.Conv_U8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Callvirt = new OpCode (
+			0xff << 0 | 0x6f << 8 | (byte) Code.Callvirt << 16 | (byte) FlowControl.Call << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Varpush << 24);
+
+		public static readonly OpCode Cpobj = new OpCode (
+			0xff << 0 | 0x70 << 8 | (byte) Code.Cpobj << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldobj = new OpCode (
+			0xff << 0 | 0x71 << 8 | (byte) Code.Ldobj << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldstr = new OpCode (
+			0xff << 0 | 0x72 << 8 | (byte) Code.Ldstr << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineString << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Newobj = new OpCode (
+			0xff << 0 | 0x73 << 8 | (byte) Code.Newobj << 16 | (byte) FlowControl.Call << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Varpop << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Castclass = new OpCode (
+			0xff << 0 | 0x74 << 8 | (byte) Code.Castclass << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Isinst = new OpCode (
+			0xff << 0 | 0x75 << 8 | (byte) Code.Isinst << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_R_Un = new OpCode (
+			0xff << 0 | 0x76 << 8 | (byte) Code.Conv_R_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);
+
+		public static readonly OpCode Unbox = new OpCode (
+			0xff << 0 | 0x79 << 8 | (byte) Code.Unbox << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Throw = new OpCode (
+			0xff << 0 | 0x7a << 8 | (byte) Code.Throw << 16 | (byte) FlowControl.Throw << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldfld = new OpCode (
+			0xff << 0 | 0x7b << 8 | (byte) Code.Ldfld << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldflda = new OpCode (
+			0xff << 0 | 0x7c << 8 | (byte) Code.Ldflda << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Stfld = new OpCode (
+			0xff << 0 | 0x7d << 8 | (byte) Code.Stfld << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Popref_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldsfld = new OpCode (
+			0xff << 0 | 0x7e << 8 | (byte) Code.Ldsfld << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldsflda = new OpCode (
+			0xff << 0 | 0x7f << 8 | (byte) Code.Ldsflda << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Stsfld = new OpCode (
+			0xff << 0 | 0x80 << 8 | (byte) Code.Stsfld << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineField << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stobj = new OpCode (
+			0xff << 0 | 0x81 << 8 | (byte) Code.Stobj << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi_pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Conv_Ovf_I1_Un = new OpCode (
+			0xff << 0 | 0x82 << 8 | (byte) Code.Conv_Ovf_I1_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I2_Un = new OpCode (
+			0xff << 0 | 0x83 << 8 | (byte) Code.Conv_Ovf_I2_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I4_Un = new OpCode (
+			0xff << 0 | 0x84 << 8 | (byte) Code.Conv_Ovf_I4_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I8_Un = new OpCode (
+			0xff << 0 | 0x85 << 8 | (byte) Code.Conv_Ovf_I8_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Conv_Ovf_U1_Un = new OpCode (
+			0xff << 0 | 0x86 << 8 | (byte) Code.Conv_Ovf_U1_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U2_Un = new OpCode (
+			0xff << 0 | 0x87 << 8 | (byte) Code.Conv_Ovf_U2_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U4_Un = new OpCode (
+			0xff << 0 | 0x88 << 8 | (byte) Code.Conv_Ovf_U4_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U8_Un = new OpCode (
+			0xff << 0 | 0x89 << 8 | (byte) Code.Conv_Ovf_U8_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Conv_Ovf_I_Un = new OpCode (
+			0xff << 0 | 0x8a << 8 | (byte) Code.Conv_Ovf_I_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U_Un = new OpCode (
+			0xff << 0 | 0x8b << 8 | (byte) Code.Conv_Ovf_U_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Box = new OpCode (
+			0xff << 0 | 0x8c << 8 | (byte) Code.Box << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Newarr = new OpCode (
+			0xff << 0 | 0x8d << 8 | (byte) Code.Newarr << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Ldlen = new OpCode (
+			0xff << 0 | 0x8e << 8 | (byte) Code.Ldlen << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelema = new OpCode (
+			0xff << 0 | 0x8f << 8 | (byte) Code.Ldelema << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_I1 = new OpCode (
+			0xff << 0 | 0x90 << 8 | (byte) Code.Ldelem_I1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_U1 = new OpCode (
+			0xff << 0 | 0x91 << 8 | (byte) Code.Ldelem_U1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_I2 = new OpCode (
+			0xff << 0 | 0x92 << 8 | (byte) Code.Ldelem_I2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_U2 = new OpCode (
+			0xff << 0 | 0x93 << 8 | (byte) Code.Ldelem_U2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_I4 = new OpCode (
+			0xff << 0 | 0x94 << 8 | (byte) Code.Ldelem_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_U4 = new OpCode (
+			0xff << 0 | 0x95 << 8 | (byte) Code.Ldelem_U4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_I8 = new OpCode (
+			0xff << 0 | 0x96 << 8 | (byte) Code.Ldelem_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Ldelem_I = new OpCode (
+			0xff << 0 | 0x97 << 8 | (byte) Code.Ldelem_I << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldelem_R4 = new OpCode (
+			0xff << 0 | 0x98 << 8 | (byte) Code.Ldelem_R4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushr4 << 24);
+
+		public static readonly OpCode Ldelem_R8 = new OpCode (
+			0xff << 0 | 0x99 << 8 | (byte) Code.Ldelem_R8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushr8 << 24);
+
+		public static readonly OpCode Ldelem_Ref = new OpCode (
+			0xff << 0 | 0x9a << 8 | (byte) Code.Ldelem_Ref << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Pushref << 24);
+
+		public static readonly OpCode Stelem_I = new OpCode (
+			0xff << 0 | 0x9b << 8 | (byte) Code.Stelem_I << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_I1 = new OpCode (
+			0xff << 0 | 0x9c << 8 | (byte) Code.Stelem_I1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_I2 = new OpCode (
+			0xff << 0 | 0x9d << 8 | (byte) Code.Stelem_I2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_I4 = new OpCode (
+			0xff << 0 | 0x9e << 8 | (byte) Code.Stelem_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_I8 = new OpCode (
+			0xff << 0 | 0x9f << 8 | (byte) Code.Stelem_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popi8 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_R4 = new OpCode (
+			0xff << 0 | 0xa0 << 8 | (byte) Code.Stelem_R4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popr4 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_R8 = new OpCode (
+			0xff << 0 | 0xa1 << 8 | (byte) Code.Stelem_R8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popr8 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stelem_Ref = new OpCode (
+			0xff << 0 | 0xa2 << 8 | (byte) Code.Stelem_Ref << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popref_popi_popref << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldelem_Any = new OpCode (
+			0xff << 0 | 0xa3 << 8 | (byte) Code.Ldelem_Any << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Stelem_Any = new OpCode (
+			0xff << 0 | 0xa4 << 8 | (byte) Code.Stelem_Any << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref_popi_popref << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Unbox_Any = new OpCode (
+			0xff << 0 | 0xa5 << 8 | (byte) Code.Unbox_Any << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Conv_Ovf_I1 = new OpCode (
+			0xff << 0 | 0xb3 << 8 | (byte) Code.Conv_Ovf_I1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U1 = new OpCode (
+			0xff << 0 | 0xb4 << 8 | (byte) Code.Conv_Ovf_U1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I2 = new OpCode (
+			0xff << 0 | 0xb5 << 8 | (byte) Code.Conv_Ovf_I2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U2 = new OpCode (
+			0xff << 0 | 0xb6 << 8 | (byte) Code.Conv_Ovf_U2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I4 = new OpCode (
+			0xff << 0 | 0xb7 << 8 | (byte) Code.Conv_Ovf_I4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U4 = new OpCode (
+			0xff << 0 | 0xb8 << 8 | (byte) Code.Conv_Ovf_U4 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I8 = new OpCode (
+			0xff << 0 | 0xb9 << 8 | (byte) Code.Conv_Ovf_I8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Conv_Ovf_U8 = new OpCode (
+			0xff << 0 | 0xba << 8 | (byte) Code.Conv_Ovf_U8 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi8 << 24);
+
+		public static readonly OpCode Refanyval = new OpCode (
+			0xff << 0 | 0xc2 << 8 | (byte) Code.Refanyval << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ckfinite = new OpCode (
+			0xff << 0 | 0xc3 << 8 | (byte) Code.Ckfinite << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushr8 << 24);
+
+		public static readonly OpCode Mkrefany = new OpCode (
+			0xff << 0 | 0xc6 << 8 | (byte) Code.Mkrefany << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldtoken = new OpCode (
+			0xff << 0 | 0xd0 << 8 | (byte) Code.Ldtoken << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineTok << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_U2 = new OpCode (
+			0xff << 0 | 0xd1 << 8 | (byte) Code.Conv_U2 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_U1 = new OpCode (
+			0xff << 0 | 0xd2 << 8 | (byte) Code.Conv_U1 << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_I = new OpCode (
+			0xff << 0 | 0xd3 << 8 | (byte) Code.Conv_I << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_I = new OpCode (
+			0xff << 0 | 0xd4 << 8 | (byte) Code.Conv_Ovf_I << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Conv_Ovf_U = new OpCode (
+			0xff << 0 | 0xd5 << 8 | (byte) Code.Conv_Ovf_U << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Add_Ovf = new OpCode (
+			0xff << 0 | 0xd6 << 8 | (byte) Code.Add_Ovf << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Add_Ovf_Un = new OpCode (
+			0xff << 0 | 0xd7 << 8 | (byte) Code.Add_Ovf_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Mul_Ovf = new OpCode (
+			0xff << 0 | 0xd8 << 8 | (byte) Code.Mul_Ovf << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Mul_Ovf_Un = new OpCode (
+			0xff << 0 | 0xd9 << 8 | (byte) Code.Mul_Ovf_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Sub_Ovf = new OpCode (
+			0xff << 0 | 0xda << 8 | (byte) Code.Sub_Ovf << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Sub_Ovf_Un = new OpCode (
+			0xff << 0 | 0xdb << 8 | (byte) Code.Sub_Ovf_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Endfinally = new OpCode (
+			0xff << 0 | 0xdc << 8 | (byte) Code.Endfinally << 16 | (byte) FlowControl.Return << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Leave = new OpCode (
+			0xff << 0 | 0xdd << 8 | (byte) Code.Leave << 16 | (byte) FlowControl.Branch << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineBrTarget << 8 | (byte) StackBehaviour.PopAll << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Leave_S = new OpCode (
+			0xff << 0 | 0xde << 8 | (byte) Code.Leave_S << 16 | (byte) FlowControl.Branch << 24,
+			(byte) OpCodeType.Macro << 0 | (byte) OperandType.ShortInlineBrTarget << 8 | (byte) StackBehaviour.PopAll << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Stind_I = new OpCode (
+			0xff << 0 | 0xdf << 8 | (byte) Code.Stind_I << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Conv_U = new OpCode (
+			0xff << 0 | 0xe0 << 8 | (byte) Code.Conv_U << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Arglist = new OpCode (
+			0xfe << 0 | 0x00 << 8 | (byte) Code.Arglist << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ceq = new OpCode (
+			0xfe << 0 | 0x01 << 8 | (byte) Code.Ceq << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Cgt = new OpCode (
+			0xfe << 0 | 0x02 << 8 | (byte) Code.Cgt << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Cgt_Un = new OpCode (
+			0xfe << 0 | 0x03 << 8 | (byte) Code.Cgt_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Clt = new OpCode (
+			0xfe << 0 | 0x04 << 8 | (byte) Code.Clt << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Clt_Un = new OpCode (
+			0xfe << 0 | 0x05 << 8 | (byte) Code.Clt_Un << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1_pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldftn = new OpCode (
+			0xfe << 0 | 0x06 << 8 | (byte) Code.Ldftn << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldvirtftn = new OpCode (
+			0xfe << 0 | 0x07 << 8 | (byte) Code.Ldvirtftn << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineMethod << 8 | (byte) StackBehaviour.Popref << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Ldarg = new OpCode (
+			0xfe << 0 | 0x09 << 8 | (byte) Code.Ldarg << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldarga = new OpCode (
+			0xfe << 0 | 0x0a << 8 | (byte) Code.Ldarga << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Starg = new OpCode (
+			0xfe << 0 | 0x0b << 8 | (byte) Code.Starg << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineArg << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Ldloc = new OpCode (
+			0xfe << 0 | 0x0c << 8 | (byte) Code.Ldloc << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push1 << 24);
+
+		public static readonly OpCode Ldloca = new OpCode (
+			0xfe << 0 | 0x0d << 8 | (byte) Code.Ldloca << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Stloc = new OpCode (
+			0xfe << 0 | 0x0e << 8 | (byte) Code.Stloc << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineVar << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Localloc = new OpCode (
+			0xfe << 0 | 0x0f << 8 | (byte) Code.Localloc << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Endfilter = new OpCode (
+			0xfe << 0 | 0x11 << 8 | (byte) Code.Endfilter << 16 | (byte) FlowControl.Return << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Unaligned = new OpCode (
+			0xfe << 0 | 0x12 << 8 | (byte) Code.Unaligned << 16 | (byte) FlowControl.Meta << 24,
+			(byte) OpCodeType.Prefix << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Volatile = new OpCode (
+			0xfe << 0 | 0x13 << 8 | (byte) Code.Volatile << 16 | (byte) FlowControl.Meta << 24,
+			(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Tail = new OpCode (
+			0xfe << 0 | 0x14 << 8 | (byte) Code.Tail << 16 | (byte) FlowControl.Meta << 24,
+			(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Initobj = new OpCode (
+			0xfe << 0 | 0x15 << 8 | (byte) Code.Initobj << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Constrained = new OpCode (
+			0xfe << 0 | 0x16 << 8 | (byte) Code.Constrained << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Cpblk = new OpCode (
+			0xfe << 0 | 0x17 << 8 | (byte) Code.Cpblk << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Initblk = new OpCode (
+			0xfe << 0 | 0x18 << 8 | (byte) Code.Initblk << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Popi_popi_popi << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode No = new OpCode (
+			0xfe << 0 | 0x19 << 8 | (byte) Code.No << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Prefix << 0 | (byte) OperandType.ShortInlineI << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Rethrow = new OpCode (
+			0xfe << 0 | 0x1a << 8 | (byte) Code.Rethrow << 16 | (byte) FlowControl.Throw << 24,
+			(byte) OpCodeType.Objmodel << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+
+		public static readonly OpCode Sizeof = new OpCode (
+			0xfe << 0 | 0x1c << 8 | (byte) Code.Sizeof << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineType << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Refanytype = new OpCode (
+			0xfe << 0 | 0x1d << 8 | (byte) Code.Refanytype << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Primitive << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop1 << 16 | (byte) StackBehaviour.Pushi << 24);
+
+		public static readonly OpCode Readonly = new OpCode (
+			0xfe << 0 | 0x1e << 8 | (byte) Code.Readonly << 16 | (byte) FlowControl.Next << 24,
+			(byte) OpCodeType.Prefix << 0 | (byte) OperandType.InlineNone << 8 | (byte) StackBehaviour.Pop0 << 16 | (byte) StackBehaviour.Push0 << 24);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/SequencePoint.cs	(revision 11807)
@@ -0,0 +1,70 @@
+//
+// SequencePoint.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public sealed class SequencePoint {
+
+		Document document;
+
+		int start_line;
+		int start_column;
+		int end_line;
+		int end_column;
+
+		public int StartLine {
+			get { return start_line; }
+			set { start_line = value; }
+		}
+
+		public int StartColumn {
+			get { return start_column; }
+			set { start_column = value; }
+		}
+
+		public int EndLine {
+			get { return end_line; }
+			set { end_line = value; }
+		}
+
+		public int EndColumn {
+			get { return end_column; }
+			set { end_column = value; }
+		}
+
+		public Document Document {
+			get { return document; }
+			set { document = value; }
+		}
+
+		public SequencePoint (Document document)
+		{
+			this.document = document;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Symbols.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Symbols.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/Symbols.cs	(revision 11807)
@@ -0,0 +1,277 @@
+//
+// Symbols.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using SR = System.Reflection;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil.Cil {
+
+	[StructLayout (LayoutKind.Sequential)]
+	public struct ImageDebugDirectory {
+		public int Characteristics;
+		public int TimeDateStamp;
+		public short MajorVersion;
+		public short MinorVersion;
+		public int Type;
+		public int SizeOfData;
+		public int AddressOfRawData;
+		public int PointerToRawData;
+	}
+
+	public sealed class Scope : IVariableDefinitionProvider {
+
+		Instruction start;
+		Instruction end;
+
+		Collection<Scope> scopes;
+		Collection<VariableDefinition> variables;
+
+		public Instruction Start {
+			get { return start; }
+			set { start = value; }
+		}
+
+		public Instruction End {
+			get { return end; }
+			set { end = value; }
+		}
+
+		public bool HasScopes {
+			get { return !scopes.IsNullOrEmpty (); }
+		}
+
+		public Collection<Scope> Scopes {
+			get {
+				if (scopes == null)
+					scopes = new Collection<Scope> ();
+
+				return scopes;
+			}
+		}
+
+		public bool HasVariables {
+			get { return !variables.IsNullOrEmpty (); }
+		}
+
+		public Collection<VariableDefinition> Variables {
+			get {
+				if (variables == null)
+					variables = new Collection<VariableDefinition> ();
+
+				return variables;
+			}
+		}
+	}
+
+	public struct InstructionSymbol {
+
+		public readonly int Offset;
+		public readonly SequencePoint SequencePoint;
+
+		public InstructionSymbol (int offset, SequencePoint sequencePoint)
+		{
+			this.Offset = offset;
+			this.SequencePoint = sequencePoint;
+		}
+	}
+
+	public sealed class MethodSymbols {
+
+		internal int code_size;
+		internal string method_name;
+		internal MetadataToken method_token;
+		internal MetadataToken local_var_token;
+		internal Collection<VariableDefinition> variables;
+		internal Collection<InstructionSymbol> instructions;
+
+		public bool HasVariables {
+			get { return !variables.IsNullOrEmpty (); }
+		}
+
+		public Collection<VariableDefinition> Variables {
+			get {
+				if (variables == null)
+					variables = new Collection<VariableDefinition> ();
+
+				return variables;
+			}
+		}
+
+		public Collection<InstructionSymbol> Instructions {
+			get {
+				if (instructions == null)
+					instructions = new Collection<InstructionSymbol> ();
+
+				return instructions;
+			}
+		}
+
+		public int CodeSize {
+			get { return code_size; }
+		}
+
+		public string MethodName {
+			get { return method_name; }
+		}
+
+		public MetadataToken MethodToken {
+			get { return method_token; }
+		}
+
+		public MetadataToken LocalVarToken {
+			get { return local_var_token; }
+		}
+
+		internal MethodSymbols (string methodName)
+		{
+			this.method_name = methodName;
+		}
+
+		public MethodSymbols (MetadataToken methodToken)
+		{
+			this.method_token = methodToken;
+		}
+	}
+
+	public delegate Instruction InstructionMapper (int offset);
+
+	public interface ISymbolReader : IDisposable {
+
+		bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header);
+		void Read (MethodBody body, InstructionMapper mapper);
+		void Read (MethodSymbols symbols);
+	}
+
+	public interface ISymbolReaderProvider {
+
+		ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName);
+		ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream);
+	}
+
+	static class SymbolProvider {
+
+		static readonly string symbol_kind = Type.GetType ("Mono.Runtime") != null ? "Mdb" : "Pdb";
+
+		static SR.AssemblyName GetPlatformSymbolAssemblyName ()
+		{
+			var cecil_name = typeof (SymbolProvider).Assembly.GetName ();
+
+			var name = new SR.AssemblyName {
+				Name = "Mono.Cecil." + symbol_kind,
+				Version = cecil_name.Version,
+			};
+
+			name.SetPublicKeyToken (cecil_name.GetPublicKeyToken ());
+
+			return name;
+		}
+
+		static Type GetPlatformType (string fullname)
+		{
+			var type = Type.GetType (fullname);
+			if (type != null)
+				return type;
+
+			var assembly_name = GetPlatformSymbolAssemblyName ();
+
+			type = Type.GetType (fullname + ", " + assembly_name.FullName);
+			if (type != null)
+				return type;
+
+			try {
+				var assembly = SR.Assembly.Load (assembly_name);
+				if (assembly != null)
+					return assembly.GetType (fullname);
+			} catch (FileNotFoundException) {
+#if !CF
+			} catch (FileLoadException) {
+#endif
+			}
+
+			return null;
+		}
+
+		static ISymbolReaderProvider reader_provider;
+
+		public static ISymbolReaderProvider GetPlatformReaderProvider ()
+		{
+			if (reader_provider != null)
+				return reader_provider;
+
+			var type = GetPlatformType (GetProviderTypeName ("ReaderProvider"));
+			if (type == null)
+				return null;
+
+			return reader_provider = (ISymbolReaderProvider) Activator.CreateInstance (type);
+		}
+
+		static string GetProviderTypeName (string name)
+		{
+			return "Mono.Cecil." + symbol_kind + "." + symbol_kind + name;
+		}
+
+#if !READ_ONLY
+
+		static ISymbolWriterProvider writer_provider;
+
+		public static ISymbolWriterProvider GetPlatformWriterProvider ()
+		{
+			if (writer_provider != null)
+				return writer_provider;
+
+			var type = GetPlatformType (GetProviderTypeName ("WriterProvider"));
+			if (type == null)
+				return null;
+
+			return writer_provider = (ISymbolWriterProvider) Activator.CreateInstance (type);
+		}
+
+#endif
+	}
+
+#if !READ_ONLY
+
+	public interface ISymbolWriter : IDisposable {
+
+		bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header);
+		void Write (MethodBody body);
+		void Write (MethodSymbols symbols);
+	}
+
+	public interface ISymbolWriterProvider {
+
+		ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName);
+		ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream);
+	}
+
+#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/VariableDefinition.cs	(revision 11807)
@@ -0,0 +1,52 @@
+//
+// VariableDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public sealed class VariableDefinition : VariableReference {
+
+		public bool IsPinned {
+			get { return variable_type.IsPinned; }
+		}
+
+		public VariableDefinition (TypeReference variableType)
+			: base (variableType)
+		{
+		}
+
+		public VariableDefinition (string name, TypeReference variableType)
+			: base (name, variableType)
+		{
+		}
+
+		public override VariableDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Cil/VariableReference.cs	(revision 11807)
@@ -0,0 +1,75 @@
+//
+// VariableReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Cil {
+
+	public abstract class VariableReference {
+
+		string name;
+		internal int index = -1;
+		protected TypeReference variable_type;
+
+		public string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public TypeReference VariableType {
+			get { return variable_type; }
+			set { variable_type = value; }
+		}
+
+		public int Index {
+			get { return index; }
+		}
+
+		internal VariableReference (TypeReference variable_type)
+			: this (string.Empty, variable_type)
+		{
+		}
+
+		internal VariableReference (string name, TypeReference variable_type)
+		{
+			this.name = name;
+			this.variable_type = variable_type;
+		}
+
+		public abstract VariableDefinition Resolve ();
+
+		public override string ToString ()
+		{
+			if (!string.IsNullOrEmpty (name))
+				return name;
+
+			if (index >= 0)
+				return "V_" + index;
+
+			return string.Empty;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/BlobHeap.cs	(revision 11807)
@@ -0,0 +1,59 @@
+//
+// BlobHeap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil.Metadata {
+
+	sealed class BlobHeap : Heap {
+
+		public BlobHeap (Section section, uint start, uint size)
+			: base (section, start, size)
+		{
+		}
+
+		public byte [] Read (uint index)
+		{
+			if (index == 0 || index > Size - 1)
+				return Empty<byte>.Array;
+
+			var data = Section.Data;
+
+			int position = (int) (index + Offset);
+			int length = (int) data.ReadCompressedUInt32 (ref position);
+
+			var buffer = new byte [length];
+
+			Buffer.BlockCopy (data, position, buffer, 0, length);
+
+			return buffer;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Buffers.cs	(revision 11807)
@@ -0,0 +1,373 @@
+//
+// TableHeapBuffer.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+using Mono.Cecil.PE;
+
+using RVA = System.UInt32;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Metadata {
+
+	sealed class TableHeapBuffer : HeapBuffer {
+
+		readonly ModuleDefinition module;
+		readonly MetadataBuilder metadata;
+
+		internal MetadataTable [] tables = new MetadataTable [45];
+
+		bool large_string;
+		bool large_blob;
+		readonly int [] coded_index_sizes = new int [13];
+		readonly Func<Table, int> counter;
+
+		public override bool IsEmpty {
+			get { return false; }
+		}
+
+		public TableHeapBuffer (ModuleDefinition module, MetadataBuilder metadata)
+			: base (24)
+		{
+			this.module = module;
+			this.metadata = metadata;
+			this.counter = GetTableLength;
+		}
+
+		int GetTableLength (Table table)
+		{
+			var md_table = tables [(int) table];
+			return md_table != null ? md_table.Length : 0;
+		}
+
+		public TTable GetTable<TTable> (Table table) where TTable : MetadataTable, new ()
+		{
+			var md_table = (TTable) tables [(int) table];
+			if (md_table != null)
+				return md_table;
+
+			md_table = new TTable ();
+			tables [(int) table] = md_table;
+			return md_table;
+		}
+
+		public void WriteBySize (uint value, int size)
+		{
+			if (size == 4)
+				WriteUInt32 (value);
+			else
+				WriteUInt16 ((ushort) value);
+		}
+
+		public void WriteBySize (uint value, bool large)
+		{
+			if (large)
+				WriteUInt32 (value);
+			else
+				WriteUInt16 ((ushort) value);
+		}
+
+		public void WriteString (uint @string)
+		{
+			WriteBySize (@string, large_string);
+		}
+
+		public void WriteBlob (uint blob)
+		{
+			WriteBySize (blob, large_blob);
+		}
+
+		public void WriteRID (uint rid, Table table)
+		{
+			var md_table = tables [(int) table];
+			WriteBySize (rid, md_table == null ? false : md_table.IsLarge);
+		}
+
+		int GetCodedIndexSize (CodedIndex coded_index)
+		{
+			var index = (int) coded_index;
+			var size = coded_index_sizes [index];
+			if (size != 0)
+				return size;
+
+			return coded_index_sizes [index] = coded_index.GetSize (counter);
+		}
+
+		public void WriteCodedRID (uint rid, CodedIndex coded_index)
+		{
+			WriteBySize (rid, GetCodedIndexSize (coded_index));
+		}
+
+		public void WriteTableHeap ()
+		{
+			WriteUInt32 (0);					// Reserved
+			WriteByte (GetTableHeapVersion ());	// MajorVersion
+			WriteByte (0);						// MinorVersion
+			WriteByte (GetHeapSizes ());		// HeapSizes
+			WriteByte (10);						// Reserved2
+			WriteUInt64 (GetValid ());			// Valid
+			WriteUInt64 (0x0016003301fa00);		// Sorted
+
+			WriteRowCount ();
+			WriteTables ();
+		}
+
+		void WriteRowCount ()
+		{
+			for (int i = 0; i < tables.Length; i++) {
+				var table = tables [i];
+				if (table == null || table.Length == 0)
+					continue;
+
+				WriteUInt32 ((uint) table.Length);
+			}
+		}
+
+		void WriteTables ()
+		{
+			for (int i = 0; i < tables.Length; i++) {
+				var table = tables [i];
+				if (table == null || table.Length == 0)
+					continue;
+
+				table.Write (this);
+			}
+		}
+
+		ulong GetValid ()
+		{
+			ulong valid = 0;
+
+			for (int i = 0; i < tables.Length; i++) {
+				var table = tables [i];
+				if (table == null || table.Length == 0)
+					continue;
+
+				table.Sort ();
+				valid |= (1UL << i);
+			}
+
+			return valid;
+		}
+
+		byte GetHeapSizes ()
+		{
+			byte heap_sizes = 0;
+
+			if (metadata.string_heap.IsLarge) {
+				large_string = true;
+				heap_sizes |= 0x01;
+			}
+
+			if (metadata.blob_heap.IsLarge) {
+				large_blob = true;
+				heap_sizes |= 0x04;
+			}
+
+			return heap_sizes;
+		}
+
+		byte GetTableHeapVersion ()
+		{
+			switch (module.Runtime) {
+			case TargetRuntime.Net_1_0:
+			case TargetRuntime.Net_1_1:
+				return 1;
+			default:
+				return 2;
+			}
+		}
+
+		public void FixupData (RVA data_rva)
+		{
+			var table = GetTable<FieldRVATable> (Table.FieldRVA);
+			if (table.length == 0)
+				return;
+
+			var field_idx_size = GetTable<FieldTable> (Table.Field).IsLarge ? 4 : 2;
+			var previous = this.position;
+
+			base.position = table.position;
+			for (int i = 0; i < table.length; i++) {
+				var rva = ReadUInt32 ();
+				base.position -= 4;
+				WriteUInt32 (rva + data_rva);
+				base.position += field_idx_size;
+			}
+
+			base.position = previous;
+		}
+	}
+
+	sealed class ResourceBuffer : ByteBuffer {
+
+		public ResourceBuffer ()
+			: base (0)
+		{
+		}
+
+		public uint AddResource (byte [] resource)
+		{
+			var offset = (uint) this.position;
+			WriteInt32 (resource.Length);
+			WriteBytes (resource);
+			return offset;
+		}
+	}
+
+	sealed class DataBuffer : ByteBuffer {
+
+		public DataBuffer ()
+			: base (0)
+		{
+		}
+
+		public RVA AddData (byte [] data)
+		{
+			var rva = (RVA) position;
+			WriteBytes (data);
+			return rva;
+		}
+	}
+
+	abstract class HeapBuffer : ByteBuffer {
+
+		public bool IsLarge {
+			get { return base.length > 65535; }
+		}
+
+		public abstract bool IsEmpty { get; }
+
+		protected HeapBuffer (int length)
+			: base (length)
+		{
+		}
+	}
+
+	class StringHeapBuffer : HeapBuffer {
+
+		readonly Dictionary<string, uint> strings = new Dictionary<string, uint> ();
+
+		public sealed override bool IsEmpty {
+			get { return length <= 1; }
+		}
+
+		public StringHeapBuffer ()
+			: base (1)
+		{
+			WriteByte (0);
+		}
+
+		public uint GetStringIndex (string @string)
+		{
+			uint index;
+			if (strings.TryGetValue (@string, out index))
+				return index;
+
+			index = (uint) base.position;
+			WriteString (@string);
+			strings.Add (@string, index);
+			return index;
+		}
+
+		protected virtual void WriteString (string @string)
+		{
+			WriteBytes (Encoding.UTF8.GetBytes (@string));
+			WriteByte (0);
+		}
+	}
+
+	sealed class BlobHeapBuffer : HeapBuffer {
+
+		readonly Dictionary<ByteBuffer, uint> blobs = new Dictionary<ByteBuffer, uint> (new ByteBufferEqualityComparer ());
+
+		public override bool IsEmpty {
+			get { return length <= 1; }
+		}
+
+		public BlobHeapBuffer ()
+			: base (1)
+		{
+			WriteByte (0);
+		}
+
+		public uint GetBlobIndex (ByteBuffer blob)
+		{
+			uint index;
+			if (blobs.TryGetValue (blob, out index))
+				return index;
+
+			index = (uint) base.position;
+			WriteBlob (blob);
+			blobs.Add (blob, index);
+			return index;
+		}
+
+		void WriteBlob (ByteBuffer blob)
+		{
+			WriteCompressedUInt32 ((uint) blob.length);
+			WriteBytes (blob);
+		}
+	}
+
+	sealed class UserStringHeapBuffer : StringHeapBuffer {
+
+		protected override void WriteString (string @string)
+		{
+			WriteCompressedUInt32 ((uint) @string.Length * 2 + 1);
+
+			byte special = 0;
+
+			for (int i = 0; i < @string.Length; i++) {
+				var @char = @string [i];
+				WriteUInt16 (@char);
+
+				if (special == 1)
+					continue;
+
+				if (@char < 0x20 || @char > 0x7e) {
+					if (@char > 0x7e
+						|| (@char >= 0x01 && @char <= 0x08)
+						|| (@char >= 0x0e && @char <= 0x1f)
+						|| @char == 0x27
+						|| @char == 0x2d) {
+
+						special = 1;
+					}
+				}
+			}
+
+			WriteByte (special);
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/CodedIndex.cs	(revision 11807)
@@ -0,0 +1,46 @@
+//
+// CodedIndex.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Metadata {
+
+	enum CodedIndex {
+		TypeDefOrRef,
+		HasConstant,
+		HasCustomAttribute,
+		HasFieldMarshal,
+		HasDeclSecurity,
+		MemberRefParent,
+		HasSemantics,
+		MethodDefOrRef,
+		MemberForwarded,
+		Implementation,
+		CustomAttributeType,
+		ResolutionScope,
+		TypeOrMethodDef
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/ElementType.cs	(revision 11807)
@@ -0,0 +1,73 @@
+//
+// ElementType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil.Metadata {
+
+	enum ElementType : byte {
+		None = 0x00,
+		Void = 0x01,
+		Boolean = 0x02,
+		Char = 0x03,
+		I1 = 0x04,
+		U1 = 0x05,
+		I2 = 0x06,
+		U2 = 0x07,
+		I4 = 0x08,
+		U4 = 0x09,
+		I8 = 0x0a,
+		U8 = 0x0b,
+		R4 = 0x0c,
+		R8 = 0x0d,
+		String = 0x0e,
+		Ptr = 0x0f,   // Followed by <type> token
+		ByRef = 0x10,   // Followed by <type> token
+		ValueType = 0x11,   // Followed by <type> token
+		Class = 0x12,   // Followed by <type> token
+		Var = 0x13,   // Followed by generic parameter number
+		Array = 0x14,   // <type> <rank> <boundsCount> <bound1>  <loCount> <lo1>
+		GenericInst = 0x15,   // <type> <type-arg-count> <type-1> ... <type-n> */
+		TypedByRef = 0x16,
+		I = 0x18,   // System.IntPtr
+		U = 0x19,   // System.UIntPtr
+		FnPtr = 0x1b,   // Followed by full method signature
+		Object = 0x1c,   // System.Object
+		SzArray = 0x1d,   // Single-dim array with 0 lower bound
+		MVar = 0x1e,   // Followed by generic parameter number
+		CModReqD = 0x1f,   // Required modifier : followed by a TypeDef or TypeRef token
+		CModOpt = 0x20,   // Optional modifier : followed by a TypeDef or TypeRef token
+		Internal = 0x21,   // Implemented within the CLI
+		Modifier = 0x40,   // Or'd with following element types
+		Sentinel = 0x41,   // Sentinel for varargs method signature
+		Pinned = 0x45,   // Denotes a local variable that points at a pinned object
+
+		// special undocumented constants
+		Type = 0x50,
+		Boxed = 0x51,
+		Enum = 0x55
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/GuidHeap.cs	(revision 11807)
@@ -0,0 +1,59 @@
+//
+// GuidHeap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil.Metadata {
+
+	sealed class GuidHeap : Heap {
+
+		public GuidHeap (Section section, uint start, uint size)
+			: base (section, start, size)
+		{
+		}
+
+		public Guid Read (uint index)
+		{
+			if (index == 0)
+				return new Guid ();
+
+			const int guid_size = 16;
+
+			var buffer = new byte [guid_size];
+
+			index--;
+
+			Buffer.BlockCopy (Section.Data, (int) (Offset + index), buffer, 0, guid_size);
+
+			return new Guid (buffer);
+
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Heap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Heap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Heap.cs	(revision 11807)
@@ -0,0 +1,48 @@
+//
+// Heap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil.Metadata {
+
+	abstract class Heap {
+
+		public int IndexSize;
+
+		public readonly Section Section;
+		public readonly uint Offset;
+		public readonly uint Size;
+
+		protected Heap (Section section, uint offset, uint size)
+		{
+			this.Section = section;
+			this.Offset = offset;
+			this.Size = size;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/MetadataToken.cs	(revision 11807)
@@ -0,0 +1,105 @@
+//
+// MetadataToken.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public struct MetadataToken {
+
+		readonly uint token;
+
+		public uint RID	{
+			get { return token & 0x00ffffff; }
+		}
+
+		public TokenType TokenType {
+			get { return (TokenType) (token & 0xff000000); }
+		}
+
+		public static readonly MetadataToken Zero = new MetadataToken ((uint) 0);
+
+		public MetadataToken (uint token)
+		{
+			this.token = token;
+		}
+
+		public MetadataToken (TokenType type)
+			: this (type, 0)
+		{
+		}
+
+		public MetadataToken (TokenType type, uint rid)
+		{
+			token = (uint) type | rid;
+		}
+
+		public MetadataToken (TokenType type, int rid)
+		{
+			token = (uint) type | (uint) rid;
+		}
+
+		public int ToInt32 ()
+		{
+			return (int) token;
+		}
+
+		public uint ToUInt32 ()
+		{
+			return token;
+		}
+
+		public override int GetHashCode ()
+		{
+			return (int) token;
+		}
+
+		public override bool Equals (object obj)
+		{
+			if (obj is MetadataToken) {
+				var other = (MetadataToken) obj;
+				return other.token == token;
+			}
+
+			return false;
+		}
+
+		public static bool operator == (MetadataToken one, MetadataToken other)
+		{
+			return one.token == other.token;
+		}
+
+		public static bool operator != (MetadataToken one, MetadataToken other)
+		{
+			return one.token != other.token;
+		}
+
+		public override string ToString ()
+		{
+			return string.Format ("[{0}:0x{1}]", TokenType, RID.ToString ("x4"));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Row.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Row.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Row.cs	(revision 11807)
@@ -0,0 +1,170 @@
+//
+// Row.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Generic;
+
+namespace Mono.Cecil.Metadata {
+
+	struct Row<T1, T2> {
+		internal T1 Col1;
+		internal T2 Col2;
+
+		public Row (T1 col1, T2 col2)
+		{
+			Col1 = col1;
+			Col2 = col2;
+		}
+	}
+
+	struct Row<T1, T2, T3> {
+		internal T1 Col1;
+		internal T2 Col2;
+		internal T3 Col3;
+
+		public Row (T1 col1, T2 col2, T3 col3)
+		{
+			Col1 = col1;
+			Col2 = col2;
+			Col3 = col3;
+		}
+	}
+
+	struct Row<T1, T2, T3, T4> {
+		internal T1 Col1;
+		internal T2 Col2;
+		internal T3 Col3;
+		internal T4 Col4;
+
+		public Row (T1 col1, T2 col2, T3 col3, T4 col4)
+		{
+			Col1 = col1;
+			Col2 = col2;
+			Col3 = col3;
+			Col4 = col4;
+		}
+	}
+
+	struct Row<T1, T2, T3, T4, T5> {
+		internal T1 Col1;
+		internal T2 Col2;
+		internal T3 Col3;
+		internal T4 Col4;
+		internal T5 Col5;
+
+		public Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5)
+		{
+			Col1 = col1;
+			Col2 = col2;
+			Col3 = col3;
+			Col4 = col4;
+			Col5 = col5;
+		}
+	}
+
+	struct Row<T1, T2, T3, T4, T5, T6> {
+		internal T1 Col1;
+		internal T2 Col2;
+		internal T3 Col3;
+		internal T4 Col4;
+		internal T5 Col5;
+		internal T6 Col6;
+
+		public Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5, T6 col6)
+		{
+			Col1 = col1;
+			Col2 = col2;
+			Col3 = col3;
+			Col4 = col4;
+			Col5 = col5;
+			Col6 = col6;
+		}
+	}
+
+	struct Row<T1, T2, T3, T4, T5, T6, T7, T8, T9> {
+		internal T1 Col1;
+		internal T2 Col2;
+		internal T3 Col3;
+		internal T4 Col4;
+		internal T5 Col5;
+		internal T6 Col6;
+		internal T7 Col7;
+		internal T8 Col8;
+		internal T9 Col9;
+
+		public Row (T1 col1, T2 col2, T3 col3, T4 col4, T5 col5, T6 col6, T7 col7, T8 col8, T9 col9)
+		{
+			Col1 = col1;
+			Col2 = col2;
+			Col3 = col3;
+			Col4 = col4;
+			Col5 = col5;
+			Col6 = col6;
+			Col7 = col7;
+			Col8 = col8;
+			Col9 = col9;
+		}
+	}
+
+	sealed class RowEqualityComparer : IEqualityComparer<Row<string, string>>, IEqualityComparer<Row<uint, uint>>, IEqualityComparer<Row<uint, uint, uint>> {
+
+		public bool Equals (Row<string, string> x, Row<string, string> y)
+		{
+			return x.Col1 == y.Col1
+				&& x.Col2 == y.Col2;
+		}
+
+		public int GetHashCode (Row<string, string> obj)
+		{
+			string x = obj.Col1, y = obj.Col2;
+			return (x != null ? x.GetHashCode () : 0) ^ (y != null ? y.GetHashCode () : 0);
+		}
+
+		public bool Equals (Row<uint, uint> x, Row<uint, uint> y)
+		{
+			return x.Col1 == y.Col1
+				&& x.Col2 == y.Col2;
+		}
+
+		public int GetHashCode (Row<uint, uint> obj)
+		{
+			return (int) (obj.Col1 ^ obj.Col2);
+		}
+
+		public bool Equals (Row<uint, uint, uint> x, Row<uint, uint, uint> y)
+		{
+			return x.Col1 == y.Col1
+				&& x.Col2 == y.Col2
+				&& x.Col3 == y.Col3;
+		}
+
+		public int GetHashCode (Row<uint, uint, uint> obj)
+		{
+			return (int) (obj.Col1 ^ obj.Col2 ^ obj.Col3);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/StringHeap.cs	(revision 11807)
@@ -0,0 +1,81 @@
+//
+// StringHeap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil.Metadata {
+
+	class StringHeap : Heap {
+
+		readonly Dictionary<uint, string> strings = new Dictionary<uint, string> ();
+
+		public StringHeap (Section section, uint start, uint size)
+			: base (section, start, size)
+		{
+		}
+
+		public string Read (uint index)
+		{
+			if (index == 0)
+				return string.Empty;
+
+			string @string;
+			if (strings.TryGetValue (index, out @string))
+				return @string;
+
+			if (index > Size - 1)
+				return string.Empty;
+
+			@string = ReadStringAt (index);
+			if (@string.Length != 0)
+				strings.Add (index, @string);
+
+			return @string;
+		}
+
+		protected virtual string ReadStringAt (uint index)
+		{
+			int length = 0;
+			byte [] data = Section.Data;
+			int start = (int) (index + Offset);
+
+			for (int i = start; ; i++) {
+				if (data [i] == 0)
+					break;
+
+				length++;
+			}
+
+			return Encoding.UTF8.GetString (data, start, length);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/TableHeap.cs	(revision 11807)
@@ -0,0 +1,111 @@
+//
+// TableHeap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil.Metadata {
+
+	enum Table : byte {
+		Module = 0x00,
+		TypeRef = 0x01,
+		TypeDef = 0x02,
+		FieldPtr = 0x03,
+		Field = 0x04,
+		MethodPtr = 0x05,
+		Method = 0x06,
+		ParamPtr = 0x07,
+		Param = 0x08,
+		InterfaceImpl = 0x09,
+		MemberRef = 0x0a,
+		Constant = 0x0b,
+		CustomAttribute = 0x0c,
+		FieldMarshal = 0x0d,
+		DeclSecurity = 0x0e,
+		ClassLayout = 0x0f,
+		FieldLayout = 0x10,
+		StandAloneSig = 0x11,
+		EventMap = 0x12,
+		EventPtr = 0x13,
+		Event = 0x14,
+		PropertyMap = 0x15,
+		PropertyPtr = 0x16,
+		Property = 0x17,
+		MethodSemantics = 0x18,
+		MethodImpl = 0x19,
+		ModuleRef = 0x1a,
+		TypeSpec = 0x1b,
+		ImplMap = 0x1c,
+		FieldRVA = 0x1d,
+		EncLog = 0x1e,
+		EncMap = 0x1f,
+		Assembly = 0x20,
+		AssemblyProcessor = 0x21,
+		AssemblyOS = 0x22,
+		AssemblyRef = 0x23,
+		AssemblyRefProcessor = 0x24,
+		AssemblyRefOS = 0x25,
+		File = 0x26,
+		ExportedType = 0x27,
+		ManifestResource = 0x28,
+		NestedClass = 0x29,
+		GenericParam = 0x2a,
+		MethodSpec = 0x2b,
+		GenericParamConstraint = 0x2c,
+	}
+
+	struct TableInformation {
+		public uint Offset;
+		public uint Length;
+		public uint RowSize;
+	}
+
+	sealed class TableHeap : Heap {
+
+		public long Valid;
+		public long Sorted;
+
+		public const int TableCount = 45;
+
+		public readonly TableInformation [] Tables = new TableInformation [TableCount];
+
+		public TableInformation this [Table table] {
+			get { return Tables [(int) table]; }
+		}
+
+		public TableHeap (Section section, uint start, uint size)
+			: base (section, start, size)
+		{
+		}
+
+		public bool HasTable (Table table)
+		{
+			return (Valid & (1L << (int) table)) != 0;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/TokenType.cs	(revision 11807)
@@ -0,0 +1,56 @@
+//
+// TokenType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum TokenType : uint {
+		Module = 0x00000000,
+		TypeRef = 0x01000000,
+		TypeDef = 0x02000000,
+		Field = 0x04000000,
+		Method = 0x06000000,
+		Param = 0x08000000,
+		InterfaceImpl = 0x09000000,
+		MemberRef = 0x0a000000,
+		CustomAttribute = 0x0c000000,
+		Permission = 0x0e000000,
+		Signature = 0x11000000,
+		Event = 0x14000000,
+		Property = 0x17000000,
+		ModuleRef = 0x1a000000,
+		TypeSpec = 0x1b000000,
+		Assembly = 0x20000000,
+		AssemblyRef = 0x23000000,
+		File = 0x26000000,
+		ExportedType = 0x27000000,
+		ManifestResource = 0x28000000,
+		GenericParam = 0x2a000000,
+		MethodSpec = 0x2b000000,
+		String = 0x70000000,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/UserStringHeap.cs	(revision 11807)
@@ -0,0 +1,59 @@
+//
+// UserStringHeap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil.Metadata {
+
+	sealed class UserStringHeap : StringHeap {
+
+		public UserStringHeap (Section section, uint start, uint size)
+			: base (section, start, size)
+		{
+		}
+
+		protected override string ReadStringAt (uint index)
+		{
+			byte [] data = Section.Data;
+			int start = (int) (index + Offset);
+
+			uint length = (uint) (data.ReadCompressedUInt32 (ref start) & ~1);
+			if (length < 1)
+				return string.Empty;
+
+			var chars = new char [length / 2];
+
+			for (int i = start, j = 0; i < start + length; i += 2)
+				chars [j++] = (char) (data [i] | (data [i + 1] << 8));
+
+			return new string (chars);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs	(revision 11807)
@@ -0,0 +1,529 @@
+//
+// Utilities.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	static partial class Mixin {
+
+		public static uint ReadCompressedUInt32 (this byte [] data, ref int position)
+		{
+			uint integer;
+			if ((data [position] & 0x80) == 0) {
+				integer = data [position];
+				position++;
+			} else if ((data [position] & 0x40) == 0) {
+				integer = (uint) (data [position] & ~0x80) << 8;
+				integer |= data [position + 1];
+				position += 2;
+			} else {
+				integer = (uint) (data [position] & ~0xc0) << 24;
+				integer |= (uint) data [position + 1] << 16;
+				integer |= (uint) data [position + 2] << 8;
+				integer |= (uint) data [position + 3];
+				position += 4;
+			}
+			return integer;
+		}
+
+		public static MetadataToken GetMetadataToken (this CodedIndex self, uint data)
+		{
+			uint rid;
+			TokenType token_type;
+			switch (self) {
+			case CodedIndex.TypeDefOrRef:
+				rid = data >> 2;
+				switch (data & 3) {
+				case 0:
+					token_type = TokenType.TypeDef; goto ret;
+				case 1:
+					token_type = TokenType.TypeRef; goto ret;
+				case 2:
+					token_type = TokenType.TypeSpec; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasConstant:
+				rid = data >> 2;
+				switch (data & 3) {
+				case 0:
+					token_type = TokenType.Field; goto ret;
+				case 1:
+					token_type = TokenType.Param; goto ret;
+				case 2:
+					token_type = TokenType.Property; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasCustomAttribute:
+				rid = data >> 5;
+				switch (data & 31) {
+				case 0:
+					token_type = TokenType.Method; goto ret;
+				case 1:
+					token_type = TokenType.Field; goto ret;
+				case 2:
+					token_type = TokenType.TypeRef; goto ret;
+				case 3:
+					token_type = TokenType.TypeDef; goto ret;
+				case 4:
+					token_type = TokenType.Param; goto ret;
+				case 5:
+					token_type = TokenType.InterfaceImpl; goto ret;
+				case 6:
+					token_type = TokenType.MemberRef; goto ret;
+				case 7:
+					token_type = TokenType.Module; goto ret;
+				case 8:
+					token_type = TokenType.Permission; goto ret;
+				case 9:
+					token_type = TokenType.Property; goto ret;
+				case 10:
+					token_type = TokenType.Event; goto ret;
+				case 11:
+					token_type = TokenType.Signature; goto ret;
+				case 12:
+					token_type = TokenType.ModuleRef; goto ret;
+				case 13:
+					token_type = TokenType.TypeSpec; goto ret;
+				case 14:
+					token_type = TokenType.Assembly; goto ret;
+				case 15:
+					token_type = TokenType.AssemblyRef; goto ret;
+				case 16:
+					token_type = TokenType.File; goto ret;
+				case 17:
+					token_type = TokenType.ExportedType; goto ret;
+				case 18:
+					token_type = TokenType.ManifestResource; goto ret;
+				case 19:
+					token_type = TokenType.GenericParam; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasFieldMarshal:
+				rid = data >> 1;
+				switch (data & 1) {
+				case 0:
+					token_type = TokenType.Field; goto ret;
+				case 1:
+					token_type = TokenType.Param; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasDeclSecurity:
+				rid = data >> 2;
+				switch (data & 3) {
+				case 0:
+					token_type = TokenType.TypeDef; goto ret;
+				case 1:
+					token_type = TokenType.Method; goto ret;
+				case 2:
+					token_type = TokenType.Assembly; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.MemberRefParent:
+				rid = data >> 3;
+				switch (data & 7) {
+				case 0:
+					token_type = TokenType.TypeDef; goto ret;
+				case 1:
+					token_type = TokenType.TypeRef; goto ret;
+				case 2:
+					token_type = TokenType.ModuleRef; goto ret;
+				case 3:
+					token_type = TokenType.Method; goto ret;
+				case 4:
+					token_type = TokenType.TypeSpec; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasSemantics:
+				rid = data >> 1;
+				switch (data & 1) {
+				case 0:
+					token_type = TokenType.Event; goto ret;
+				case 1:
+					token_type = TokenType.Property; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.MethodDefOrRef:
+				rid = data >> 1;
+				switch (data & 1) {
+				case 0:
+					token_type = TokenType.Method; goto ret;
+				case 1:
+					token_type = TokenType.MemberRef; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.MemberForwarded:
+				rid = data >> 1;
+				switch (data & 1) {
+				case 0:
+					token_type = TokenType.Field; goto ret;
+				case 1:
+					token_type = TokenType.Method; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.Implementation:
+				rid = data >> 2;
+				switch (data & 3) {
+				case 0:
+					token_type = TokenType.File; goto ret;
+				case 1:
+					token_type = TokenType.AssemblyRef; goto ret;
+				case 2:
+					token_type = TokenType.ExportedType; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.CustomAttributeType:
+				rid = data >> 3;
+				switch (data & 7) {
+				case 2:
+					token_type = TokenType.Method; goto ret;
+				case 3:
+					token_type = TokenType.MemberRef; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.ResolutionScope:
+				rid = data >> 2;
+				switch (data & 3) {
+				case 0:
+					token_type = TokenType.Module; goto ret;
+				case 1:
+					token_type = TokenType.ModuleRef; goto ret;
+				case 2:
+					token_type = TokenType.AssemblyRef; goto ret;
+				case 3:
+					token_type = TokenType.TypeRef; goto ret;
+				default:
+					goto exit;
+				}
+			case CodedIndex.TypeOrMethodDef:
+				rid = data >> 1;
+				switch (data & 1) {
+				case 0:
+					token_type = TokenType.TypeDef; goto ret;
+				case 1:
+					token_type = TokenType.Method; goto ret;
+				default: goto exit;
+				}
+			default:
+				goto exit;
+			}
+		ret:
+			return new MetadataToken (token_type, rid);
+		exit:
+			return MetadataToken.Zero;
+		}
+
+#if !READ_ONLY
+		public static uint CompressMetadataToken (this CodedIndex self, MetadataToken token)
+		{
+			uint ret = 0;
+			if (token.RID == 0)
+				return ret;
+			switch (self) {
+			case CodedIndex.TypeDefOrRef:
+				ret = token.RID << 2;
+				switch (token.TokenType) {
+				case TokenType.TypeDef:
+					return ret | 0;
+				case TokenType.TypeRef:
+					return ret | 1;
+				case TokenType.TypeSpec:
+					return ret | 2;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasConstant:
+				ret = token.RID << 2;
+				switch (token.TokenType) {
+				case TokenType.Field:
+					return ret | 0;
+				case TokenType.Param:
+					return ret | 1;
+				case TokenType.Property:
+					return ret | 2;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasCustomAttribute:
+				ret = token.RID << 5;
+				switch (token.TokenType) {
+				case TokenType.Method:
+					return ret | 0;
+				case TokenType.Field:
+					return ret | 1;
+				case TokenType.TypeRef:
+					return ret | 2;
+				case TokenType.TypeDef:
+					return ret | 3;
+				case TokenType.Param:
+					return ret | 4;
+				case TokenType.InterfaceImpl:
+					return ret | 5;
+				case TokenType.MemberRef:
+					return ret | 6;
+				case TokenType.Module:
+					return ret | 7;
+				case TokenType.Permission:
+					return ret | 8;
+				case TokenType.Property:
+					return ret | 9;
+				case TokenType.Event:
+					return ret | 10;
+				case TokenType.Signature:
+					return ret | 11;
+				case TokenType.ModuleRef:
+					return ret | 12;
+				case TokenType.TypeSpec:
+					return ret | 13;
+				case TokenType.Assembly:
+					return ret | 14;
+				case TokenType.AssemblyRef:
+					return ret | 15;
+				case TokenType.File:
+					return ret | 16;
+				case TokenType.ExportedType:
+					return ret | 17;
+				case TokenType.ManifestResource:
+					return ret | 18;
+				case TokenType.GenericParam:
+					return ret | 19;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasFieldMarshal:
+				ret = token.RID << 1;
+				switch (token.TokenType) {
+				case TokenType.Field:
+					return ret | 0;
+				case TokenType.Param:
+					return ret | 1;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasDeclSecurity:
+				ret = token.RID << 2;
+				switch (token.TokenType) {
+				case TokenType.TypeDef:
+					return ret | 0;
+				case TokenType.Method:
+					return ret | 1;
+				case TokenType.Assembly:
+					return ret | 2;
+				default:
+					goto exit;
+				}
+			case CodedIndex.MemberRefParent:
+				ret = token.RID << 3;
+				switch (token.TokenType) {
+				case TokenType.TypeDef:
+					return ret | 0;
+				case TokenType.TypeRef:
+					return ret | 1;
+				case TokenType.ModuleRef:
+					return ret | 2;
+				case TokenType.Method:
+					return ret | 3;
+				case TokenType.TypeSpec:
+					return ret | 4;
+				default:
+					goto exit;
+				}
+			case CodedIndex.HasSemantics:
+				ret = token.RID << 1;
+				switch (token.TokenType) {
+				case TokenType.Event:
+					return ret | 0;
+				case TokenType.Property:
+					return ret | 1;
+				default:
+					goto exit;
+				}
+			case CodedIndex.MethodDefOrRef:
+				ret = token.RID << 1;
+				switch (token.TokenType) {
+				case TokenType.Method:
+					return ret | 0;
+				case TokenType.MemberRef:
+					return ret | 1;
+				default:
+					goto exit;
+				}
+			case CodedIndex.MemberForwarded:
+				ret = token.RID << 1;
+				switch (token.TokenType) {
+				case TokenType.Field:
+					return ret | 0;
+				case TokenType.Method:
+					return ret | 1;
+				default:
+					goto exit;
+				}
+			case CodedIndex.Implementation:
+				ret = token.RID << 2;
+				switch (token.TokenType) {
+				case TokenType.File:
+					return ret | 0;
+				case TokenType.AssemblyRef:
+					return ret | 1;
+				case TokenType.ExportedType:
+					return ret | 2;
+				default:
+					goto exit;
+				}
+			case CodedIndex.CustomAttributeType:
+				ret = token.RID << 3;
+				switch (token.TokenType) {
+				case TokenType.Method:
+					return ret | 2;
+				case TokenType.MemberRef:
+					return ret | 3;
+				default:
+					goto exit;
+				}
+			case CodedIndex.ResolutionScope:
+				ret = token.RID << 2;
+				switch (token.TokenType) {
+				case TokenType.Module:
+					return ret | 0;
+				case TokenType.ModuleRef:
+					return ret | 1;
+				case TokenType.AssemblyRef:
+					return ret | 2;
+				case TokenType.TypeRef:
+					return ret | 3;
+				default:
+					goto exit;
+				}
+			case CodedIndex.TypeOrMethodDef:
+				ret = token.RID << 1;
+				switch (token.TokenType) {
+				case TokenType.TypeDef:
+					return ret | 0;
+				case TokenType.Method:
+					return ret | 1;
+				default:
+					goto exit;
+				}
+			default:
+				goto exit;
+			}
+		exit:
+			throw new ArgumentException ();
+		}
+#endif
+
+		public static int GetSize (this CodedIndex self, Func<Table, int> counter)
+		{
+			int bits;
+			Table [] tables;
+
+			switch (self) {
+			case CodedIndex.TypeDefOrRef:
+				bits = 2;
+				tables = new [] { Table.TypeDef, Table.TypeRef, Table.TypeSpec };
+				break;
+			case CodedIndex.HasConstant:
+				bits = 2;
+				tables = new [] { Table.Field, Table.Param, Table.Property };
+				break;
+			case CodedIndex.HasCustomAttribute:
+				bits = 5;
+				tables = new [] {
+					Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,
+					Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,
+					Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,
+					Table.ManifestResource, Table.GenericParam
+				};
+				break;
+			case CodedIndex.HasFieldMarshal:
+				bits = 1;
+				tables = new [] { Table.Field, Table.Param };
+				break;
+			case CodedIndex.HasDeclSecurity:
+				bits = 2;
+				tables = new [] { Table.TypeDef, Table.Method, Table.Assembly };
+				break;
+			case CodedIndex.MemberRefParent:
+				bits = 3;
+				tables = new [] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec };
+				break;
+			case CodedIndex.HasSemantics:
+				bits = 1;
+				tables = new [] { Table.Event, Table.Property };
+				break;
+			case CodedIndex.MethodDefOrRef:
+				bits = 1;
+				tables = new [] { Table.Method, Table.MemberRef };
+				break;
+			case CodedIndex.MemberForwarded:
+				bits = 1;
+				tables = new [] { Table.Field, Table.Method };
+				break;
+			case CodedIndex.Implementation:
+				bits = 2;
+				tables = new [] { Table.File, Table.AssemblyRef, Table.ExportedType };
+				break;
+			case CodedIndex.CustomAttributeType:
+				bits = 3;
+				tables = new [] { Table.Method, Table.MemberRef };
+				break;
+			case CodedIndex.ResolutionScope:
+				bits = 2;
+				tables = new [] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef };
+				break;
+			case CodedIndex.TypeOrMethodDef:
+				bits = 1;
+				tables = new [] { Table.TypeDef, Table.Method };
+				break;
+			default:
+				throw new ArgumentException ();
+			}
+
+			int max = 0;
+
+			for (int i = 0; i < tables.Length; i++) {
+				max = System.Math.Max (counter (tables [i]), max);
+			}
+
+			return max < (1 << (16 - bits)) ? 2 : 4;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/BinaryStreamReader.cs	(revision 11807)
@@ -0,0 +1,51 @@
+//
+// BinaryStreamReader.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+
+namespace Mono.Cecil.PE {
+
+	class BinaryStreamReader : BinaryReader {
+
+		public BinaryStreamReader (Stream stream)
+			: base (stream)
+		{
+		}
+
+		protected void Advance (int bytes)
+		{
+			BaseStream.Seek (bytes, SeekOrigin.Current);
+		}
+
+		protected DataDirectory ReadDataDirectory ()
+		{
+			return new DataDirectory (ReadUInt32 (), ReadUInt32 ());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/BinaryStreamWriter.cs	(revision 11807)
@@ -0,0 +1,96 @@
+//
+// BinaryStreamWriter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.PE {
+
+	class BinaryStreamWriter : BinaryWriter {
+
+		public BinaryStreamWriter (Stream stream)
+			: base (stream)
+		{
+		}
+
+		public void WriteByte (byte value)
+		{
+			Write (value);
+		}
+
+		public void WriteUInt16 (ushort value)
+		{
+			Write (value);
+		}
+
+		public void WriteInt16 (short value)
+		{
+			Write (value);
+		}
+
+		public void WriteUInt32 (uint value)
+		{
+			Write (value);
+		}
+
+		public void WriteInt32 (int value)
+		{
+			Write (value);
+		}
+
+		public void WriteUInt64 (ulong value)
+		{
+			Write (value);
+		}
+
+		public void WriteBytes (byte [] bytes)
+		{
+			Write (bytes);
+		}
+
+		public void WriteDataDirectory (DataDirectory directory)
+		{
+			Write (directory.VirtualAddress);
+			Write (directory.Size);
+		}
+
+		public void WriteBuffer (ByteBuffer buffer)
+		{
+			Write (buffer.buffer, 0, buffer.length);
+		}
+
+		protected void Advance (int bytes)
+		{
+			BaseStream.Seek (bytes, SeekOrigin.Current);
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ByteBuffer.cs	(revision 11807)
@@ -0,0 +1,342 @@
+//
+// ByteBuffer.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil.PE {
+
+	class ByteBuffer {
+
+		internal byte [] buffer;
+		internal int length;
+		internal int position;
+
+		public ByteBuffer ()
+		{
+			this.buffer = Empty<byte>.Array;
+		}
+
+		public ByteBuffer (int length)
+		{
+			this.buffer = new byte [length];
+		}
+
+		public ByteBuffer (byte [] buffer)
+		{
+			this.buffer = buffer ?? Empty<byte>.Array;
+			this.length = this.buffer.Length;
+		}
+
+		public void Reset (byte [] buffer)
+		{
+			this.buffer = buffer ?? Empty<byte>.Array;
+			this.length = this.buffer.Length;
+		}
+
+		public void Advance (int length)
+		{
+			position += length;
+		}
+
+		public byte ReadByte ()
+		{
+			return buffer [position++];
+		}
+
+		public sbyte ReadSByte ()
+		{
+			return (sbyte) ReadByte ();
+		}
+
+		public byte [] ReadBytes (int length)
+		{
+			var bytes = new byte [length];
+			Buffer.BlockCopy (buffer, position, bytes, 0, length);
+			position += length;
+			return bytes;
+		}
+
+		public ushort ReadUInt16 ()
+		{
+			ushort value = (ushort) (buffer [position]
+				| (buffer [position + 1] << 8));
+			position += 2;
+			return value;
+		}
+
+		public short ReadInt16 ()
+		{
+			return (short) ReadUInt16 ();
+		}
+
+		public uint ReadUInt32 ()
+		{
+			uint value = (uint) (buffer [position]
+				| (buffer [position + 1] << 8)
+				| (buffer [position + 2] << 16)
+				| (buffer [position + 3] << 24));
+			position += 4;
+			return value;
+		}
+
+		public int ReadInt32 ()
+		{
+			return (int) ReadUInt32 ();
+		}
+
+		public ulong ReadUInt64 ()
+		{
+			uint low = ReadUInt32 ();
+			uint high = ReadUInt32 ();
+
+			return (((ulong) high) << 32) | low;
+		}
+
+		public long ReadInt64 ()
+		{
+			return (long) ReadUInt64 ();
+		}
+
+		public uint ReadCompressedUInt32 ()
+		{
+			byte first = ReadByte ();
+			if ((first & 0x80) == 0)
+				return first;
+
+			if ((first & 0x40) == 0)
+				return ((uint) (first & ~0x80) << 8)
+					| ReadByte ();
+
+			return ((uint) (first & ~0xc0) << 24)
+				| (uint) ReadByte () << 16
+				| (uint) ReadByte () << 8
+				| ReadByte ();
+		}
+
+		public int ReadCompressedInt32 ()
+		{
+			var value = (int) ReadCompressedUInt32 ();
+
+			return (value & 1) != 0
+				? -(value >> 1)
+				: value >> 1;
+		}
+
+		public float ReadSingle ()
+		{
+			if (!BitConverter.IsLittleEndian) {
+				var bytes = ReadBytes (4);
+				Array.Reverse (bytes);
+				return BitConverter.ToSingle (bytes, 0);
+			}
+
+			float value = BitConverter.ToSingle (buffer, position);
+			position += 4;
+			return value;
+		}
+
+		public double ReadDouble ()
+		{
+			if (!BitConverter.IsLittleEndian) {
+				var bytes = ReadBytes (8);
+				Array.Reverse (bytes);
+				return BitConverter.ToDouble (bytes, 0);
+			}
+
+			double value = BitConverter.ToDouble (buffer, position);
+			position += 8;
+			return value;
+		}
+
+#if !READ_ONLY
+
+		public void WriteByte (byte value)
+		{
+			if (position == buffer.Length)
+				Grow (1);
+
+			buffer [position++] = value;
+
+			if (position > length)
+				length = position;
+		}
+
+		public void WriteSByte (sbyte value)
+		{
+			WriteByte ((byte) value);
+		}
+
+		public void WriteUInt16 (ushort value)
+		{
+			if (position + 2 > buffer.Length)
+				Grow (2);
+
+			buffer [position++] = (byte) value;
+			buffer [position++] = (byte) (value >> 8);
+
+			if (position > length)
+				length = position;
+		}
+
+		public void WriteInt16 (short value)
+		{
+			WriteUInt16 ((ushort) value);
+		}
+
+		public void WriteUInt32 (uint value)
+		{
+			if (position + 4 > buffer.Length)
+				Grow (4);
+
+			buffer [position++] = (byte) value;
+			buffer [position++] = (byte) (value >> 8);
+			buffer [position++] = (byte) (value >> 16);
+			buffer [position++] = (byte) (value >> 24);
+
+			if (position > length)
+				length = position;
+		}
+
+		public void WriteInt32 (int value)
+		{
+			WriteUInt32 ((uint) value);
+		}
+
+		public void WriteUInt64 (ulong value)
+		{
+			if (position + 8 > buffer.Length)
+				Grow (8);
+
+			buffer [position++] = (byte) value;
+			buffer [position++] = (byte) (value >> 8);
+			buffer [position++] = (byte) (value >> 16);
+			buffer [position++] = (byte) (value >> 24);
+			buffer [position++] = (byte) (value >> 32);
+			buffer [position++] = (byte) (value >> 40);
+			buffer [position++] = (byte) (value >> 48);
+			buffer [position++] = (byte) (value >> 56);
+
+			if (position > length)
+				length = position;
+		}
+
+		public void WriteInt64 (long value)
+		{
+			WriteUInt64 ((ulong) value);
+		}
+
+		public void WriteCompressedUInt32 (uint value)
+		{
+			if (value < 0x80)
+				WriteByte ((byte) value);
+			else if (value < 0x4000) {
+				WriteByte ((byte) (0x80 | (value >> 8)));
+				WriteByte ((byte) (value & 0xff));
+			} else {
+				WriteByte ((byte) ((value >> 24) | 0xc0));
+				WriteByte ((byte) ((value >> 16) & 0xff));
+				WriteByte ((byte) ((value >> 8) & 0xff));
+				WriteByte ((byte) (value & 0xff));
+			}
+		}
+
+		public void WriteCompressedInt32 (int value)
+		{
+			WriteCompressedUInt32 ((uint) ((value < 0) ? ((-value) << 1) | 1 : value << 1));
+		}
+
+		public void WriteBytes (byte [] bytes)
+		{
+			var length = bytes.Length;
+			if (position + length > buffer.Length)
+				Grow (length);
+
+			Buffer.BlockCopy (bytes, 0, buffer, position, length);
+			position += length;
+
+			if (position > this.length)
+				this.length = position;
+		}
+
+		public void WriteBytes (int length)
+		{
+			if (position + length > buffer.Length)
+				Grow (length);
+
+			position += length;
+
+			if (position > this.length)
+				this.length = position;
+		}
+
+		public void WriteBytes (ByteBuffer buffer)
+		{
+			if (position + buffer.length > this.buffer.Length)
+				Grow (buffer.length);
+
+			Buffer.BlockCopy (buffer.buffer, 0, this.buffer, position, buffer.length);
+			position += buffer.length;
+
+			if (position > this.length)
+				this.length = position;
+		}
+
+		public void WriteSingle (float value)
+		{
+			var bytes = BitConverter.GetBytes (value);
+
+			if (!BitConverter.IsLittleEndian)
+				Array.Reverse (bytes);
+
+			WriteBytes (bytes);
+		}
+
+		public void WriteDouble (double value)
+		{
+			var bytes = BitConverter.GetBytes (value);
+
+			if (!BitConverter.IsLittleEndian)
+				Array.Reverse (bytes);
+
+			WriteBytes (bytes);
+		}
+
+		void Grow (int desired)
+		{
+			var current = this.buffer;
+			var current_length = current.Length;
+
+			var buffer = new byte [System.Math.Max (current_length + desired, current_length * 2)];
+			Buffer.BlockCopy (current, 0, buffer, 0, current_length);
+			this.buffer = buffer;
+		}
+
+#endif
+
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ByteBufferEqualityComparer.cs	(revision 11807)
@@ -0,0 +1,78 @@
+//
+// ByteBufferEqualityComparer.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+
+namespace Mono.Cecil.PE {
+
+	sealed class ByteBufferEqualityComparer : IEqualityComparer<ByteBuffer> {
+
+		public bool Equals (ByteBuffer x, ByteBuffer y)
+		{
+			if (x.length != y.length)
+				return false;
+
+			var x_buffer = x.buffer;
+			var y_buffer = y.buffer;
+
+			for (int i = 0; i < x.length; i++)
+				if (x_buffer [i] != y_buffer [i])
+					return false;
+
+			return true;
+		}
+
+		public int GetHashCode (ByteBuffer buffer)
+		{
+#if !BYTE_BUFFER_WELL_DISTRIBUTED_HASH
+			var hash = 0;
+			var bytes = buffer.buffer;
+			for (int i = 0; i < buffer.length; i++)
+				hash = (hash * 37) ^ bytes [i];
+
+			return hash;
+#else
+			const uint p = 16777619;
+			uint hash = 2166136261;
+
+			var bytes = buffer.buffer;
+			for (int i = 0; i < buffer.length; i++)
+			    hash = (hash ^ bytes [i]) * p;
+
+			hash += hash << 13;
+			hash ^= hash >> 7;
+			hash += hash << 3;
+			hash ^= hash >> 17;
+			hash += hash << 5;
+
+			return (int) hash;
+#endif
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/DataDirectory.cs	(revision 11807)
@@ -0,0 +1,50 @@
+//
+// DataDirectory.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.PE {
+
+	struct DataDirectory {
+
+		public readonly RVA VirtualAddress;
+		public readonly uint Size;
+
+		public bool IsZero {
+			get { return VirtualAddress == 0 && Size == 0; }
+		}
+
+		public DataDirectory (RVA rva, uint size)
+		{
+			this.VirtualAddress = rva;
+			this.Size = size;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/Image.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/Image.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/Image.cs	(revision 11807)
@@ -0,0 +1,159 @@
+//
+// Image.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono;
+using Mono.Cecil.Cil;
+using Mono.Cecil.Metadata;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.PE {
+
+	sealed class Image {
+
+		public ModuleKind Kind;
+		public TargetRuntime Runtime;
+		public TargetArchitecture Architecture;
+		public string FileName;
+
+		public Section [] Sections;
+
+		public Section MetadataSection;
+
+		public uint EntryPointToken;
+		public ModuleAttributes Attributes;
+
+		public DataDirectory Debug;
+		public DataDirectory Resources;
+
+		public StringHeap StringHeap;
+		public BlobHeap BlobHeap;
+		public UserStringHeap UserStringHeap;
+		public GuidHeap GuidHeap;
+		public TableHeap TableHeap;
+
+		readonly int [] coded_index_sizes = new int [13];
+
+		readonly Func<Table, int> counter;
+
+		public Image ()
+		{
+			counter = GetTableLength;
+		}
+
+		public bool HasTable (Table table)
+		{
+			return GetTableLength (table) > 0;
+		}
+
+		public int GetTableLength (Table table)
+		{
+			return (int) TableHeap [table].Length;
+		}
+
+		public int GetTableIndexSize (Table table)
+		{
+			return GetTableLength (table) < 65536 ? 2 : 4;
+		}
+
+		public int GetCodedIndexSize (CodedIndex coded_index)
+		{
+			var index = (int) coded_index;
+			var size = coded_index_sizes [index];
+			if (size != 0)
+				return size;
+
+			return coded_index_sizes [index] = coded_index.GetSize (counter);
+		}
+
+		public uint ResolveVirtualAddress (RVA rva)
+		{
+			var section = GetSectionAtVirtualAddress (rva);
+			if (section == null)
+				throw new ArgumentOutOfRangeException ();
+
+			return ResolveVirtualAddressInSection (rva, section);
+		}
+
+		public uint ResolveVirtualAddressInSection (RVA rva, Section section)
+		{
+			return rva + section.PointerToRawData - section.VirtualAddress;
+		}
+
+		public Section GetSection (string name)
+		{
+			var sections = this.Sections;
+			for (int i = 0; i < sections.Length; i++) {
+				var section = sections [i];
+				if (section.Name == name)
+					return section;
+			}
+
+			return null;
+		}
+
+		public Section GetSectionAtVirtualAddress (RVA rva)
+		{
+			var sections = this.Sections;
+			for (int i = 0; i < sections.Length; i++) {
+				var section = sections [i];
+				if (rva >= section.VirtualAddress && rva < section.VirtualAddress + section.SizeOfRawData)
+					return section;
+			}
+
+			return null;
+		}
+
+		public ImageDebugDirectory GetDebugHeader (out byte [] header)
+		{
+			var section = GetSectionAtVirtualAddress (Debug.VirtualAddress);
+			var buffer = new ByteBuffer (section.Data);
+			buffer.position = (int) (Debug.VirtualAddress - section.VirtualAddress);
+
+			var directory = new ImageDebugDirectory {
+				Characteristics = buffer.ReadInt32 (),
+				TimeDateStamp = buffer.ReadInt32 (),
+				MajorVersion = buffer.ReadInt16 (),
+				MinorVersion = buffer.ReadInt16 (),
+				Type = buffer.ReadInt32 (),
+				SizeOfData = buffer.ReadInt32 (),
+				AddressOfRawData = buffer.ReadInt32 (),
+				PointerToRawData = buffer.ReadInt32 (),
+			};
+
+			buffer.position = (int) (directory.PointerToRawData - section.PointerToRawData);
+
+			header = new byte [directory.SizeOfData];
+			Buffer.BlockCopy (buffer.buffer, buffer.position, header, 0, header.Length);
+
+			return directory;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ImageReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ImageReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ImageReader.cs	(revision 11807)
@@ -0,0 +1,679 @@
+//
+// ImageReader.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+
+using Mono.Cecil.Metadata;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.PE {
+
+	sealed class ImageReader : BinaryStreamReader {
+
+		readonly Image image;
+
+		DataDirectory cli;
+		DataDirectory metadata;
+
+		public ImageReader (Stream stream)
+			: base (stream)
+		{
+			image = new Image ();
+
+			image.FileName = stream.GetFullyQualifiedName ();
+		}
+
+		void MoveTo (DataDirectory directory)
+		{
+			BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress);
+		}
+
+		void MoveTo (uint position)
+		{
+			BaseStream.Position = position;
+		}
+
+		void ReadImage ()
+		{
+			if (BaseStream.Length < 128)
+				throw new BadImageFormatException ();
+
+			// - DOSHeader
+
+			// PE					2
+			// Start				58
+			// Lfanew				4
+			// End					64
+
+			if (ReadUInt16 () != 0x5a4d)
+				throw new BadImageFormatException ();
+
+			Advance (58);
+
+			MoveTo (ReadUInt32 ());
+
+			if (ReadUInt32 () != 0x00004550)
+				throw new BadImageFormatException ();
+
+			// - PEFileHeader
+
+			// Machine				2
+			image.Architecture = ReadArchitecture ();
+
+			// NumberOfSections		2
+			ushort sections = ReadUInt16 ();
+
+			// TimeDateStamp		4
+			// PointerToSymbolTable	4
+			// NumberOfSymbols		4
+			// OptionalHeaderSize	2
+			Advance (14);
+
+			// Characteristics		2
+			ushort characteristics = ReadUInt16 ();
+
+			ushort subsystem;
+			ReadOptionalHeaders (out subsystem);
+			ReadSections (sections);
+			ReadCLIHeader ();
+			ReadMetadata ();
+
+			image.Kind = GetModuleKind (characteristics, subsystem);
+		}
+
+		TargetArchitecture ReadArchitecture ()
+		{
+			var machine = ReadUInt16 ();
+			switch (machine) {
+			case 0x014c:
+				return TargetArchitecture.I386;
+			case 0x8664:
+				return TargetArchitecture.AMD64;
+			case 0x0200:
+				return TargetArchitecture.IA64;
+			}
+
+			throw new NotSupportedException ();
+		}
+
+		static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem)
+		{
+			if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll
+				return ModuleKind.Dll;
+
+			if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui
+				return ModuleKind.Windows;
+
+			return ModuleKind.Console;
+		}
+
+		void ReadOptionalHeaders (out ushort subsystem)
+		{
+			// - PEOptionalHeader
+			//   - StandardFieldsHeader
+
+			// Magic				2
+			bool pe64 = ReadUInt16 () == 0x20b;
+
+			//						pe32 || pe64
+
+			// LMajor				1
+			// LMinor				1
+			// CodeSize				4
+			// InitializedDataSize	4
+			// UninitializedDataSize4
+			// EntryPointRVA		4
+			// BaseOfCode			4
+			// BaseOfData			4 || 0
+
+			//   - NTSpecificFieldsHeader
+
+			// ImageBase			4 || 8
+			// SectionAlignment		4
+			// FileAlignement		4
+			// OSMajor				2
+			// OSMinor				2
+			// UserMajor			2
+			// UserMinor			2
+			// SubSysMajor			2
+			// SubSysMinor			2
+			// Reserved				4
+			// ImageSize			4
+			// HeaderSize			4
+			// FileChecksum			4
+			Advance (66);
+
+			// SubSystem			2
+			subsystem = ReadUInt16 ();
+
+			// DLLFlags				2
+			// StackReserveSize		4 || 8
+			// StackCommitSize		4 || 8
+			// HeapReserveSize		4 || 8
+			// HeapCommitSize		4 || 8
+			// LoaderFlags			4
+			// NumberOfDataDir		4
+
+			//   - DataDirectoriesHeader
+
+			// ExportTable			8
+			// ImportTable			8
+			// ResourceTable		8
+			// ExceptionTable		8
+			// CertificateTable		8
+			// BaseRelocationTable	8
+
+			Advance (pe64 ? 90 : 74);
+
+			// Debug				8
+			image.Debug = ReadDataDirectory ();
+
+			// Copyright			8
+			// GlobalPtr			8
+			// TLSTable				8
+			// LoadConfigTable		8
+			// BoundImport			8
+			// IAT					8
+			// DelayImportDescriptor8
+			Advance (56);
+
+			// CLIHeader			8
+			cli = ReadDataDirectory ();
+
+			if (cli.IsZero)
+				throw new BadImageFormatException ();
+
+			// Reserved				8
+			Advance (8);
+		}
+
+		string ReadAlignedString (int length)
+		{
+			int read = 0;
+			var buffer = new char [length];
+			while (read < length) {
+				var current = ReadByte ();
+				if (current == 0)
+					break;
+
+				buffer [read++] = (char) current;
+			}
+
+			Advance (-1 + ((read + 4) & ~3) - read);
+
+			return new string (buffer, 0, read);
+		}
+
+		string ReadZeroTerminatedString (int length)
+		{
+			int read = 0;
+			var buffer = new char [length];
+			var bytes = ReadBytes (length);
+			while (read < length) {
+				var current = bytes [read];
+				if (current == 0)
+					break;
+
+				buffer [read++] = (char) current;
+			}
+
+			return new string (buffer, 0, read);
+		}
+
+		void ReadSections (ushort count)
+		{
+			var sections = new Section [count];
+
+			for (int i = 0; i < count; i++) {
+				var section = new Section ();
+
+				// Name
+				section.Name = ReadZeroTerminatedString (8);
+
+				// VirtualSize		4
+				Advance (4);
+
+				// VirtualAddress	4
+				section.VirtualAddress = ReadUInt32 ();
+				// SizeOfRawData	4
+				section.SizeOfRawData = ReadUInt32 ();
+				// PointerToRawData	4
+				section.PointerToRawData = ReadUInt32 ();
+
+				// PointerToRelocations		4
+				// PointerToLineNumbers		4
+				// NumberOfRelocations		2
+				// NumberOfLineNumbers		2
+				// Characteristics			4
+				Advance (16);
+
+				sections [i] = section;
+
+				if (section.Name == ".reloc")
+					continue;
+
+				ReadSectionData (section);
+			}
+
+			image.Sections = sections;
+		}
+
+		void ReadSectionData (Section section)
+		{
+			var position = BaseStream.Position;
+
+			MoveTo (section.PointerToRawData);
+
+			var length = (int) section.SizeOfRawData;
+			var data = new byte [length];
+			int offset = 0, read;
+
+			while ((read = Read (data, offset, length - offset)) > 0)
+				offset += read;
+
+			section.Data = data;
+
+			BaseStream.Position = position;
+		}
+
+		void ReadCLIHeader ()
+		{
+			MoveTo (cli);
+
+			// - CLIHeader
+
+			// Cb						4
+			// MajorRuntimeVersion		2
+			// MinorRuntimeVersion		2
+			Advance (8);
+
+			// Metadata					8
+			metadata = ReadDataDirectory ();
+			// Flags					4
+			image.Attributes = (ModuleAttributes) ReadUInt32 ();
+			// EntryPointToken			4
+			image.EntryPointToken = ReadUInt32 ();
+			// Resources				8
+			image.Resources = ReadDataDirectory ();
+			// StrongNameSignature		8
+			// CodeManagerTable			8
+			// VTableFixups				8
+			// ExportAddressTableJumps	8
+			// ManagedNativeHeader		8
+		}
+
+		void ReadMetadata ()
+		{
+			MoveTo (metadata);
+
+			if (ReadUInt32 () != 0x424a5342)
+				throw new BadImageFormatException ();
+
+			// MajorVersion			2
+			// MinorVersion			2
+			// Reserved				4
+			Advance (8);
+
+			var version = ReadZeroTerminatedString (ReadInt32 ());
+			image.Runtime = version.ParseRuntime ();
+
+			// Flags		2
+			Advance (2);
+
+			var streams = ReadUInt16 ();
+
+			var section = image.GetSectionAtVirtualAddress (metadata.VirtualAddress);
+			if (section == null)
+				throw new BadImageFormatException ();
+
+			image.MetadataSection = section;
+
+			for (int i = 0; i < streams; i++)
+				ReadMetadataStream (section);
+
+			if (image.TableHeap != null)
+				ReadTableHeap ();
+		}
+
+		void ReadMetadataStream (Section section)
+		{
+			// Offset		4
+			uint start = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32 (); // relative to the section start
+
+			// Size			4
+			uint size = ReadUInt32 ();
+
+			var name = ReadAlignedString (16);
+			switch (name) {
+			case "#~":
+			case "#-":
+				image.TableHeap = new TableHeap (section, start, size);
+				break;
+			case "#Strings":
+				image.StringHeap = new StringHeap (section, start, size);
+				break;
+			case "#Blob":
+				image.BlobHeap = new BlobHeap (section, start, size);
+				break;
+			case "#GUID":
+				image.GuidHeap = new GuidHeap (section, start, size);
+				break;
+			case "#US":
+				image.UserStringHeap = new UserStringHeap (section, start, size);
+				break;
+			}
+		}
+
+		void ReadTableHeap ()
+		{
+			var heap = image.TableHeap;
+
+			uint start = heap.Section.PointerToRawData;
+
+			MoveTo (heap.Offset + start);
+
+			// Reserved			4
+			// MajorVersion		1
+			// MinorVersion		1
+			Advance (6);
+
+			// HeapSizes		1
+			var sizes = ReadByte ();
+
+			// Reserved2		1
+			Advance (1);
+
+			// Valid			8
+			heap.Valid = ReadInt64 ();
+
+			// Sorted			8
+			heap.Sorted = ReadInt64 ();
+
+			for (int i = 0; i < TableHeap.TableCount; i++) {
+				if (!heap.HasTable ((Table) i))
+					continue;
+
+				heap.Tables [i].Length = ReadUInt32 ();
+			}
+
+			SetIndexSize (image.StringHeap, sizes, 0x1);
+			SetIndexSize (image.GuidHeap, sizes, 0x2);
+			SetIndexSize (image.BlobHeap, sizes, 0x4);
+
+			ComputeTableInformations ();
+		}
+
+		static void SetIndexSize (Heap heap, uint sizes, byte flag)
+		{
+			if (heap == null)
+				return;
+
+			heap.IndexSize = (sizes & flag) > 0 ? 4 : 2;
+		}
+
+		int GetTableIndexSize (Table table)
+		{
+			return image.GetTableIndexSize (table);
+		}
+
+		int GetCodedIndexSize (CodedIndex index)
+		{
+			return image.GetCodedIndexSize (index);
+		}
+
+		void ComputeTableInformations ()
+		{
+			uint offset = (uint) BaseStream.Position - image.MetadataSection.PointerToRawData; // header
+
+			int stridx_size = image.StringHeap.IndexSize;
+			int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2;
+
+			var heap = image.TableHeap;
+			var tables = heap.Tables;
+
+			for (int i = 0; i < TableHeap.TableCount; i++) {
+				var table = (Table) i;
+				if (!heap.HasTable (table))
+					continue;
+
+				int size;
+				switch (table) {
+				case Table.Module:
+					size = 2	// Generation
+						+ stridx_size	// Name
+						+ (image.GuidHeap.IndexSize * 3);	// Mvid, EncId, EncBaseId
+					break;
+				case Table.TypeRef:
+					size = GetCodedIndexSize (CodedIndex.ResolutionScope)	// ResolutionScope
+						+ (stridx_size * 2);	// Name, Namespace
+					break;
+				case Table.TypeDef:
+					size = 4	// Flags
+						+ (stridx_size * 2)	// Name, Namespace
+						+ GetCodedIndexSize (CodedIndex.TypeDefOrRef)	// BaseType
+						+ GetTableIndexSize (Table.Field)	// FieldList
+						+ GetTableIndexSize (Table.Method);	// MethodList
+					break;
+				case Table.FieldPtr:
+					size = GetTableIndexSize (Table.Field);	// Field
+					break;
+				case Table.Field:
+					size = 2	// Flags
+						+ stridx_size	// Name
+						+ blobidx_size;	// Signature
+					break;
+				case Table.MethodPtr:
+					size = GetTableIndexSize (Table.Method);	// Method
+					break;
+				case Table.Method:
+					size = 8	// Rva 4, ImplFlags 2, Flags 2
+						+ stridx_size	// Name
+						+ blobidx_size	// Signature
+						+ GetTableIndexSize (Table.Param); // ParamList
+					break;
+				case Table.ParamPtr:
+					size = GetTableIndexSize (Table.Param); // Param
+					break;
+				case Table.Param:
+					size = 4	// Flags 2, Sequence 2
+						+ stridx_size;	// Name
+					break;
+				case Table.InterfaceImpl:
+					size = GetTableIndexSize (Table.TypeDef)	// Class
+						+ GetCodedIndexSize (CodedIndex.TypeDefOrRef);	// Interface
+					break;
+				case Table.MemberRef:
+					size = GetCodedIndexSize (CodedIndex.MemberRefParent)	// Class
+						+ stridx_size	// Name
+						+ blobidx_size;	// Signature
+					break;
+				case Table.Constant:
+					size = 2	// Type
+						+ GetCodedIndexSize (CodedIndex.HasConstant)	// Parent
+						+ blobidx_size;	// Value
+					break;
+				case Table.CustomAttribute:
+					size = GetCodedIndexSize (CodedIndex.HasCustomAttribute)	// Parent
+						+ GetCodedIndexSize (CodedIndex.CustomAttributeType)	// Type
+						+ blobidx_size;	// Value
+					break;
+				case Table.FieldMarshal:
+					size = GetCodedIndexSize (CodedIndex.HasFieldMarshal)	// Parent
+						+ blobidx_size;	// NativeType
+					break;
+				case Table.DeclSecurity:
+					size = 2	// Action
+						+ GetCodedIndexSize (CodedIndex.HasDeclSecurity)	// Parent
+						+ blobidx_size;	// PermissionSet
+					break;
+				case Table.ClassLayout:
+					size = 6	// PackingSize 2, ClassSize 4
+						+ GetTableIndexSize (Table.TypeDef);	// Parent
+					break;
+				case Table.FieldLayout:
+					size = 4	// Offset
+						+ GetTableIndexSize (Table.Field);	// Field
+					break;
+				case Table.StandAloneSig:
+					size = blobidx_size;	// Signature
+					break;
+				case Table.EventMap:
+					size = GetTableIndexSize (Table.TypeDef)	// Parent
+						+ GetTableIndexSize (Table.Event);	// EventList
+					break;
+				case Table.EventPtr:
+					size = GetTableIndexSize (Table.Event);	// Event
+					break;
+				case Table.Event:
+					size = 2	// Flags
+						+ stridx_size // Name
+						+ GetCodedIndexSize (CodedIndex.TypeDefOrRef);	// EventType
+					break;
+				case Table.PropertyMap:
+					size = GetTableIndexSize (Table.TypeDef)	// Parent
+						+ GetTableIndexSize (Table.Property);	// PropertyList
+					break;
+				case Table.PropertyPtr:
+					size = GetTableIndexSize (Table.Property);	// Property
+					break;
+				case Table.Property:
+					size = 2	// Flags
+						+ stridx_size	// Name
+						+ blobidx_size;	// Type
+					break;
+				case Table.MethodSemantics:
+					size = 2	// Semantics
+						+ GetTableIndexSize (Table.Method)	// Method
+						+ GetCodedIndexSize (CodedIndex.HasSemantics);	// Association
+					break;
+				case Table.MethodImpl:
+					size = GetTableIndexSize (Table.TypeDef)	// Class
+						+ GetCodedIndexSize (CodedIndex.MethodDefOrRef)	// MethodBody
+						+ GetCodedIndexSize (CodedIndex.MethodDefOrRef);	// MethodDeclaration
+					break;
+				case Table.ModuleRef:
+					size = stridx_size;	// Name
+					break;
+				case Table.TypeSpec:
+					size = blobidx_size;	// Signature
+					break;
+				case Table.ImplMap:
+					size = 2	// MappingFlags
+						+ GetCodedIndexSize (CodedIndex.MemberForwarded)	// MemberForwarded
+						+ stridx_size	// ImportName
+						+ GetTableIndexSize (Table.ModuleRef);	// ImportScope
+					break;
+				case Table.FieldRVA:
+					size = 4	// RVA
+						+ GetTableIndexSize (Table.Field);	// Field
+					break;
+				case Table.EncLog:
+				case Table.EncMap:
+					size = 4;
+					break;
+				case Table.Assembly:
+					size = 16 // HashAlgId 4, Version 4 * 2, Flags 4
+						+ blobidx_size	// PublicKey
+						+ (stridx_size * 2);	// Name, Culture
+					break;
+				case Table.AssemblyProcessor:
+					size = 4;	// Processor
+					break;
+				case Table.AssemblyOS:
+					size = 12;	// Platform 4, Version 2 * 4
+					break;
+				case Table.AssemblyRef:
+					size = 12	// Version 2 * 4 + Flags 4
+						+ (blobidx_size * 2)	// PublicKeyOrToken, HashValue
+						+ (stridx_size * 2);	// Name, Culture
+					break;
+				case Table.AssemblyRefProcessor:
+					size = 4	// Processor
+						+ GetTableIndexSize (Table.AssemblyRef);	// AssemblyRef
+					break;
+				case Table.AssemblyRefOS:
+					size = 12	// Platform 4, Version 2 * 4
+						+ GetTableIndexSize (Table.AssemblyRef);	// AssemblyRef
+					break;
+				case Table.File:
+					size = 4	// Flags
+						+ stridx_size	// Name
+						+ blobidx_size;	// HashValue
+					break;
+				case Table.ExportedType:
+					size = 8	// Flags 4, TypeDefId 4
+						+ (stridx_size * 2)	// Name, Namespace
+						+ GetCodedIndexSize (CodedIndex.Implementation);	// Implementation
+					break;
+				case Table.ManifestResource:
+					size = 8	// Offset, Flags
+						+ stridx_size	// Name
+						+ GetCodedIndexSize (CodedIndex.Implementation);	// Implementation
+					break;
+				case Table.NestedClass:
+					size = GetTableIndexSize (Table.TypeDef)	// NestedClass
+						+ GetTableIndexSize (Table.TypeDef);	// EnclosingClass
+					break;
+				case Table.GenericParam:
+					size = 4	// Number, Flags
+						+ GetCodedIndexSize (CodedIndex.TypeOrMethodDef)	// Owner
+						+ stridx_size;	// Name
+					break;
+				case Table.MethodSpec:
+					size = GetCodedIndexSize (CodedIndex.MethodDefOrRef)	// Method
+						+ blobidx_size;	// Instantiation
+					break;
+				case Table.GenericParamConstraint:
+					size = GetTableIndexSize (Table.GenericParam)	// Owner
+						+ GetCodedIndexSize (CodedIndex.TypeDefOrRef);	// Constraint
+					break;
+				default:
+					throw new NotSupportedException ();
+				}
+
+				tables [i].RowSize = (uint) size;
+				tables [i].Offset = offset;
+
+				offset += (uint) size * tables [i].Length;
+			}
+		}
+
+		public static Image ReadImageFrom (Stream stream)
+		{
+			try {
+				var reader = new ImageReader (stream);
+				reader.ReadImage ();
+				return reader.image;
+			} catch (EndOfStreamException e) {
+				throw new BadImageFormatException (stream.GetFullyQualifiedName (), e);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/ImageWriter.cs	(revision 11807)
@@ -0,0 +1,820 @@
+//
+// ImageWriter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+
+#if !READ_ONLY
+
+using Mono.Cecil.Cil;
+using Mono.Cecil.Metadata;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.PE {
+
+	sealed class ImageWriter : BinaryStreamWriter {
+
+		readonly ModuleDefinition module;
+		readonly MetadataBuilder metadata;
+		readonly TextMap text_map;
+
+		ImageDebugDirectory debug_directory;
+		byte [] debug_data;
+
+		ByteBuffer win32_resources;
+
+		const uint pe_header_size = 0x178u;
+		const uint section_header_size = 0x28u;
+		const uint file_alignment = 0x200;
+		const uint section_alignment = 0x2000;
+		const ulong image_base = 0x00400000;
+
+		internal const RVA text_rva = 0x2000;
+
+		readonly bool pe64;
+		readonly uint time_stamp;
+
+		internal Section text;
+		internal Section rsrc;
+		internal Section reloc;
+
+		ushort sections;
+
+		ImageWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
+			: base (stream)
+		{
+			this.module = module;
+			this.metadata = metadata;
+			this.GetDebugHeader ();
+			this.GetWin32Resources ();
+			this.text_map = BuildTextMap ();
+			this.sections = 2; // text + reloc
+			this.pe64 = module.Architecture != TargetArchitecture.I386;
+			this.time_stamp = (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds;
+		}
+
+		void GetDebugHeader ()
+		{
+			var symbol_writer = metadata.symbol_writer;
+			if (symbol_writer == null)
+				return;
+
+			if (!symbol_writer.GetDebugHeader (out debug_directory, out debug_data))
+				debug_data = Empty<byte>.Array;
+		}
+
+		void GetWin32Resources ()
+		{
+			var rsrc = GetImageResourceSection ();
+			if (rsrc == null)
+				return;
+
+			var raw_resources = new byte [rsrc.Data.Length];
+			Buffer.BlockCopy (rsrc.Data, 0, raw_resources, 0, rsrc.Data.Length);
+			win32_resources = new ByteBuffer (raw_resources);
+		}
+
+		Section GetImageResourceSection ()
+		{
+			if (!module.HasImage)
+				return null;
+
+			const string rsrc_section = ".rsrc";
+
+			return module.Image.GetSection (rsrc_section);
+		}
+
+		public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
+		{
+			var writer = new ImageWriter (module, metadata, stream);
+			writer.BuildSections ();
+			return writer;
+		}
+
+		void BuildSections ()
+		{
+			var has_win32_resources = win32_resources != null;
+			if (has_win32_resources)
+				sections++;
+
+			text = CreateSection (".text", text_map.GetLength (), null);
+			var previous = text;
+
+			if (has_win32_resources) {
+				rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous);
+
+				PatchWin32Resources (win32_resources);
+				previous = rsrc;
+			}
+
+			reloc = CreateSection (".reloc", 12u, previous);
+		}
+
+		Section CreateSection (string name, uint size, Section previous)
+		{
+			return new Section {
+				Name = name,
+				VirtualAddress = previous != null
+					? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment)
+					: text_rva,
+				VirtualSize = size,
+				PointerToRawData = previous != null
+					? previous.PointerToRawData + previous.SizeOfRawData
+					: Align (GetHeaderSize (), file_alignment),
+				SizeOfRawData = Align (size, file_alignment)
+			};
+		}
+
+		static uint Align (uint value, uint align)
+		{
+			align--;
+			return (value + align) & ~align;
+		}
+
+		void WriteDOSHeader ()
+		{
+			Write (new byte [] {
+				// dos header start
+				0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00,
+				0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff,
+				0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00, 0x00, 0x00, 0x00,
+				// lfanew
+				0x80, 0x00, 0x00, 0x00,
+				// dos header end
+				0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09,
+				0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21,
+				0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72,
+				0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63,
+				0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62,
+				0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
+				0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d,
+				0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
+				0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00
+			});
+		}
+
+		void WritePEFileHeader ()
+		{
+			WriteUInt32 (0x00004550);		// Magic
+			WriteUInt16 (GetMachine ());	// Machine
+			WriteUInt16 (sections);			// NumberOfSections
+			WriteUInt32 (time_stamp);
+			WriteUInt32 (0);	// PointerToSymbolTable
+			WriteUInt32 (0);	// NumberOfSymbols
+			WriteUInt16 ((ushort) (!pe64 ? 0xe0 : 0xf0));	// SizeOfOptionalHeader
+
+			// ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware)
+			var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020));
+			if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule)
+				characteristics |= 0x2000;
+			WriteUInt16 (characteristics);	// Characteristics
+		}
+
+		ushort GetMachine ()
+		{
+			switch (module.Architecture) {
+			case TargetArchitecture.I386:
+				return 0x014c;
+			case TargetArchitecture.AMD64:
+				return 0x8664;
+			case TargetArchitecture.IA64:
+				return 0x0200;
+			}
+
+			throw new NotSupportedException ();
+		}
+
+		void WriteOptionalHeaders ()
+		{
+			WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b));	// Magic
+			WriteByte (8);	// LMajor
+			WriteByte (0);	// LMinor
+			WriteUInt32 (text.SizeOfRawData);	// CodeSize
+			WriteUInt32 (reloc.SizeOfRawData
+				+ (rsrc != null ? rsrc.SizeOfRawData : 0));	// InitializedDataSize
+			WriteUInt32 (0);	// UninitializedDataSize
+
+			var entry_point_rva = text_map.GetRVA (TextSegment.StartupStub);
+			if (module.Architecture == TargetArchitecture.IA64)
+				entry_point_rva += 0x20;
+			WriteUInt32 (entry_point_rva); // EntryPointRVA
+			WriteUInt32 (text_rva);	// BaseOfCode
+
+			if (!pe64) {
+				WriteUInt32 (0);	// BaseOfData
+				WriteUInt32 ((uint) image_base);	// ImageBase
+			} else {
+				WriteUInt64 (image_base);	// ImageBase
+			}
+
+			WriteUInt32 (section_alignment);	// SectionAlignment
+			WriteUInt32 (file_alignment);		// FileAlignment
+
+			WriteUInt16 (4);	// OSMajor
+			WriteUInt16 (0);	// OSMinor
+			WriteUInt16 (0);	// UserMajor
+			WriteUInt16 (0);	// UserMinor
+			WriteUInt16 (4);	// SubSysMajor
+			WriteUInt16 (0);	// SubSysMinor
+			WriteUInt32 (0);	// Reserved
+
+			WriteUInt32 (reloc.VirtualAddress + Align (reloc.VirtualSize, section_alignment));	// ImageSize
+			WriteUInt32 (text.PointerToRawData);	// HeaderSize
+
+			WriteUInt32 (0);	// Checksum
+			WriteUInt16 (GetSubSystem ());	// SubSystem
+			WriteUInt16 (0x8540);	// DLLFlags
+
+			const ulong stack_reserve = 0x100000;
+			const ulong stack_commit = 0x1000;
+			const ulong heap_reserve = 0x100000;
+			const ulong heap_commit = 0x1000;
+
+			if (!pe64) {
+				WriteUInt32 ((uint) stack_reserve);
+				WriteUInt32 ((uint) stack_commit);
+				WriteUInt32 ((uint) heap_reserve);
+				WriteUInt32 ((uint) heap_commit);
+			} else {
+				WriteUInt64 (stack_reserve);
+				WriteUInt64 (stack_commit);
+				WriteUInt64 (heap_reserve);
+				WriteUInt64 (heap_commit);
+			}
+
+			WriteUInt32 (0);	// LoaderFlags
+			WriteUInt32 (16);	// NumberOfDataDir
+
+			WriteZeroDataDirectory ();	// ExportTable
+			WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory));	// ImportTable
+			if (rsrc != null) {							// ResourceTable
+				WriteUInt32 (rsrc.VirtualAddress);
+				WriteUInt32 (rsrc.VirtualSize);
+			} else
+				WriteZeroDataDirectory ();
+
+			WriteZeroDataDirectory ();	// ExceptionTable
+			WriteZeroDataDirectory ();	// CertificateTable
+			WriteUInt32 (reloc.VirtualAddress);			// BaseRelocationTable
+			WriteUInt32 (reloc.VirtualSize);
+
+			if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
+				WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory));
+				WriteUInt32 (28u);
+			} else
+				WriteZeroDataDirectory ();
+
+			WriteZeroDataDirectory ();	// Copyright
+			WriteZeroDataDirectory ();	// GlobalPtr
+			WriteZeroDataDirectory ();	// TLSTable
+			WriteZeroDataDirectory ();	// LoadConfigTable
+			WriteZeroDataDirectory ();	// BoundImport
+			WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable));	// IAT
+			WriteZeroDataDirectory ();	// DelayImportDesc
+			WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader));	// CLIHeader
+			WriteZeroDataDirectory ();	// Reserved
+		}
+
+		void WriteZeroDataDirectory ()
+		{
+			WriteUInt32 (0);
+			WriteUInt32 (0);
+		}
+
+		ushort GetSubSystem ()
+		{
+			switch (module.Kind) {
+			case ModuleKind.Console:
+			case ModuleKind.Dll:
+			case ModuleKind.NetModule:
+				return 0x3;
+			case ModuleKind.Windows:
+				return 0x2;
+			default:
+				throw new ArgumentOutOfRangeException ();
+			}
+		}
+
+		void WriteSectionHeaders ()
+		{
+			WriteSection (text, 0x60000020);
+
+			if (rsrc != null)
+				WriteSection (rsrc, 0x40000040);
+
+			WriteSection (reloc, 0x42000040);
+		}
+
+		void WriteSection (Section section, uint characteristics)
+		{
+			var name = new byte [8];
+			var sect_name = section.Name;
+			for (int i = 0; i < sect_name.Length; i++)
+				name [i] = (byte) sect_name [i];
+
+			WriteBytes (name);
+			WriteUInt32 (section.VirtualSize);
+			WriteUInt32 (section.VirtualAddress);
+			WriteUInt32 (section.SizeOfRawData);
+			WriteUInt32 (section.PointerToRawData);
+			WriteUInt32 (0);	// PointerToRelocations
+			WriteUInt32 (0);	// PointerToLineNumbers
+			WriteUInt16 (0);	// NumberOfRelocations
+			WriteUInt16 (0);	// NumberOfLineNumbers
+			WriteUInt32 (characteristics);
+		}
+
+		void MoveTo (uint pointer)
+		{
+			BaseStream.Seek (pointer, SeekOrigin.Begin);
+		}
+
+		void MoveToRVA (Section section, RVA rva)
+		{
+			BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin);
+		}
+
+		void MoveToRVA (TextSegment segment)
+		{
+			MoveToRVA (text, text_map.GetRVA (segment));
+		}
+
+		void WriteRVA (RVA rva)
+		{
+			if (!pe64)
+				WriteUInt32 (rva);
+			else
+				WriteUInt64 (rva);
+		}
+
+		void WriteText ()
+		{
+			MoveTo (text.PointerToRawData);
+
+			// ImportAddressTable
+
+			WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable));
+			WriteRVA (0);
+
+			// CLIHeader
+
+			WriteUInt32 (0x48);
+			WriteUInt16 (2);
+			WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5));
+
+			WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader));
+			WriteUInt32 (GetMetadataLength ());
+			WriteUInt32 ((uint) module.Attributes);
+			WriteUInt32 (metadata.entry_point.ToUInt32 ());
+			WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources));
+			WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature));
+			WriteZeroDataDirectory ();	// CodeManagerTable
+			WriteZeroDataDirectory ();	// VTableFixups
+			WriteZeroDataDirectory ();	// ExportAddressTableJumps
+			WriteZeroDataDirectory ();	// ManagedNativeHeader
+
+			// Code
+
+			MoveToRVA (TextSegment.Code);
+			WriteBuffer (metadata.code);
+
+			// Resources
+
+			MoveToRVA (TextSegment.Resources);
+			WriteBuffer (metadata.resources);
+
+			// Data
+
+			if (metadata.data.length > 0) {
+				MoveToRVA (TextSegment.Data);
+				WriteBuffer (metadata.data);
+			}
+
+			// StrongNameSignature
+			// stays blank
+
+			// MetadataHeader
+
+			MoveToRVA (TextSegment.MetadataHeader);
+			WriteMetadataHeader ();
+
+			WriteMetadata ();
+
+			// DebugDirectory
+			if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
+				MoveToRVA (TextSegment.DebugDirectory);
+				WriteDebugDirectory ();
+			}
+
+			// ImportDirectory
+			MoveToRVA (TextSegment.ImportDirectory);
+			WriteImportDirectory ();
+
+			// StartupStub
+			MoveToRVA (TextSegment.StartupStub);
+			WriteStartupStub ();
+		}
+
+		uint GetMetadataLength ()
+		{
+			return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader);
+		}
+
+		void WriteMetadataHeader ()
+		{
+			WriteUInt32 (0x424a5342);	// Signature
+			WriteUInt16 (1);	// MajorVersion
+			WriteUInt16 (1);	// MinorVersion
+			WriteUInt32 (0);	// Reserved
+
+			var version = GetZeroTerminatedString (GetVersion ());
+			WriteUInt32 ((uint) version.Length);
+			WriteBytes (version);
+			WriteUInt16 (0);	// Flags
+			WriteUInt16 (GetStreamCount ());
+
+			uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader);
+
+			WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~");
+			WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings");
+			WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US");
+			WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID");
+			WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob");
+		}
+
+		string GetVersion ()
+		{
+			switch (module.Runtime) {
+			case TargetRuntime.Net_1_0:
+				return "v1.0.3705";
+			case TargetRuntime.Net_1_1:
+				return "v1.1.4322";
+			case TargetRuntime.Net_2_0:
+				return "v2.0.50727";
+			case TargetRuntime.Net_4_0:
+			default:
+				return "v4.0.30319";
+			}
+		}
+
+		ushort GetStreamCount ()
+		{
+			return (ushort) (
+				1	// #~
+				+ 1	// #Strings
+				+ (metadata.user_string_heap.IsEmpty ? 0 : 1)	// #US
+				+ 1	// GUID
+				+ (metadata.blob_heap.IsEmpty ? 0 : 1));	// #Blob
+		}
+
+		void WriteStreamHeader (ref uint offset, TextSegment heap, string name)
+		{
+			var length = (uint) text_map.GetLength (heap);
+			if (length == 0)
+				return;
+
+			WriteUInt32 (offset);
+			WriteUInt32 (length);
+			WriteBytes (GetZeroTerminatedString (name));
+			offset += length;
+		}
+
+		static byte [] GetZeroTerminatedString (string @string)
+		{
+			return GetString (@string, (@string.Length + 1 + 3) & ~3);
+		}
+
+		static byte [] GetSimpleString (string @string)
+		{
+			return GetString (@string, @string.Length);
+		}
+
+		static byte [] GetString (string @string, int length)
+		{
+			var bytes = new byte [length];
+			for (int i = 0; i < @string.Length; i++)
+				bytes [i] = (byte) @string [i];
+
+			return bytes;
+		}
+
+		void WriteMetadata ()
+		{
+			WriteHeap (TextSegment.TableHeap, metadata.table_heap);
+			WriteHeap (TextSegment.StringHeap, metadata.string_heap);
+			WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap);
+			WriteGuidHeap ();
+			WriteHeap (TextSegment.BlobHeap, metadata.blob_heap);
+		}
+
+		void WriteHeap (TextSegment heap, HeapBuffer buffer)
+		{
+			if (buffer.IsEmpty)
+				return;
+
+			MoveToRVA (heap);
+			WriteBuffer (buffer);
+		}
+
+		void WriteGuidHeap ()
+		{
+			MoveToRVA (TextSegment.GuidHeap);
+			WriteBytes (module.Mvid.ToByteArray ());
+		}
+
+		void WriteDebugDirectory ()
+		{
+			WriteInt32 (debug_directory.Characteristics);
+			WriteUInt32 (time_stamp);
+			WriteInt16 (debug_directory.MajorVersion);
+			WriteInt16 (debug_directory.MinorVersion);
+			WriteInt32 (debug_directory.Type);
+			WriteInt32 (debug_directory.SizeOfData);
+			WriteInt32 (debug_directory.AddressOfRawData);
+			WriteInt32 ((int) BaseStream.Position + 4);
+
+			WriteBytes (debug_data);
+		}
+
+		void WriteImportDirectory ()
+		{
+			WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40);	// ImportLookupTable
+			WriteUInt32 (0);	// DateTimeStamp
+			WriteUInt32 (0);	// ForwarderChain
+			WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14);
+			WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable));
+			Advance (20);
+
+			// ImportLookupTable
+			WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable));
+
+			// ImportHintNameTable
+			MoveToRVA (TextSegment.ImportHintNameTable);
+
+			WriteUInt16 (0);	// Hint
+			WriteBytes (GetRuntimeMain ());
+			WriteByte (0);
+			WriteBytes (GetSimpleString ("mscoree.dll"));
+			WriteUInt16 (0);
+		}
+
+		byte [] GetRuntimeMain ()
+		{
+			return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule
+				? GetSimpleString ("_CorDllMain")
+				: GetSimpleString ("_CorExeMain");
+		}
+
+		void WriteStartupStub ()
+		{
+			switch (module.Architecture) {
+			case TargetArchitecture.I386:
+				WriteUInt16 (0x25ff);
+				WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
+				return;
+			case TargetArchitecture.AMD64:
+				WriteUInt16 (0xa148);
+				WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
+				WriteUInt16 (0xe0ff);
+				return;
+			case TargetArchitecture.IA64:
+				WriteBytes (new byte [] {
+					0x0b, 0x48, 0x00, 0x02, 0x18, 0x10, 0xa0, 0x40, 0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00,
+					0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50, 0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00
+				});
+				WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.StartupStub));
+				WriteUInt32 ((uint) image_base + text_rva);
+				return;
+			}
+		}
+
+		void WriteRsrc ()
+		{
+			MoveTo (rsrc.PointerToRawData);
+			WriteBuffer (win32_resources);
+		}
+
+		void WriteReloc ()
+		{
+			MoveTo (reloc.PointerToRawData);
+
+			var reloc_rva = text_map.GetRVA (TextSegment.StartupStub);
+			reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2;
+			var page_rva = reloc_rva & ~0xfffu;
+
+			WriteUInt32 (page_rva);	// PageRVA
+			WriteUInt32 (0x000c);	// Block Size
+
+			switch (module.Architecture) {
+			case TargetArchitecture.I386:
+				WriteUInt32 (0x3000 + reloc_rva - page_rva);
+				break;
+			case TargetArchitecture.AMD64:
+				WriteUInt32 (0xa000 + reloc_rva - page_rva);
+				break;
+			case TargetArchitecture.IA64:
+				WriteUInt16 ((ushort) (0xa000 + reloc_rva - page_rva));
+				WriteUInt16 ((ushort) (0xa000 + reloc_rva - page_rva + 8));
+				break;
+			}
+
+			WriteBytes (new byte [file_alignment - reloc.VirtualSize]);
+		}
+
+		public void WriteImage ()
+		{
+			WriteDOSHeader ();
+			WritePEFileHeader ();
+			WriteOptionalHeaders ();
+			WriteSectionHeaders ();
+			WriteText ();
+			if (rsrc != null)
+				WriteRsrc ();
+			WriteReloc ();
+		}
+
+		TextMap BuildTextMap ()
+		{
+			var map = metadata.text_map;
+
+			map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16);
+			map.AddMap (TextSegment.Resources, metadata.resources.length, 8);
+			map.AddMap (TextSegment.Data, metadata.data.length, 4);
+			if (metadata.data.length > 0)
+				metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data));
+			map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4);
+
+			map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength ());
+			map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4);
+			map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4);
+			map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4);
+			map.AddMap (TextSegment.GuidHeap, 16);
+			map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4);
+
+			int debug_dir_len = 0;
+			if (!debug_data.IsNullOrEmpty ()) {
+				const int debug_dir_header_len = 28;
+
+				debug_directory.AddressOfRawData = (int) map.GetNextRVA (TextSegment.BlobHeap) + debug_dir_header_len;
+				debug_dir_len = debug_data.Length + debug_dir_header_len;
+			}
+
+			map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4);
+
+			RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory);
+			RVA import_hnt_rva = import_dir_rva + (!pe64 ? 48u : 52u);
+			import_hnt_rva = (import_hnt_rva + 15u) & ~15u;
+			uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u;
+
+			RVA startup_stub_rva = import_dir_rva + import_dir_len;
+			startup_stub_rva = module.Architecture == TargetArchitecture.IA64
+				? (startup_stub_rva + 15u) & ~15u
+				: 2 + ((startup_stub_rva + 3u) & ~3u);
+
+			map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len));
+			map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0));
+			map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ()));
+
+			return map;
+		}
+
+		uint GetStartupStubLength ()
+		{
+			switch (module.Architecture) {
+			case TargetArchitecture.I386:
+				return 6;
+			case TargetArchitecture.AMD64:
+				return 12;
+			case TargetArchitecture.IA64:
+				return 48;
+			default:
+				throw new InvalidOperationException ();
+			}
+		}
+
+		int GetMetadataHeaderLength ()
+		{
+			return
+				// MetadataHeader
+				40
+				// #~ header
+				+ 12
+				// #Strings header
+				+ 20
+				// #US header
+				+ (metadata.user_string_heap.IsEmpty ? 0 : 12)
+				// #GUID header
+				+ 16
+				// #Blob header
+				+ (metadata.blob_heap.IsEmpty ? 0 : 16);
+		}
+
+		int GetStrongNameLength ()
+		{
+			if ((module.Attributes & ModuleAttributes.StrongNameSigned) == 0)
+				return 0;
+
+			if (module.Assembly == null)
+				throw new InvalidOperationException ();
+
+			var public_key = module.Assembly.Name.PublicKey;
+
+			if (public_key != null) {
+				// in fx 2.0 the key may be from 384 to 16384 bits
+				// so we must calculate the signature size based on
+				// the size of the public key (minus the 32 byte header)
+				int size = public_key.Length;
+				if (size > 32)
+					return size - 32;
+				// note: size == 16 for the ECMA "key" which is replaced
+				// by the runtime with a 1024 bits key (128 bytes)
+			}
+
+			return 128; // default strongname signature size
+		}
+
+		public DataDirectory GetStrongNameSignatureDirectory ()
+		{
+			return text_map.GetDataDirectory (TextSegment.StrongNameSignature);
+		}
+
+		public uint GetHeaderSize ()
+		{
+			return pe_header_size + (sections * section_header_size);
+		}
+
+		void PatchWin32Resources (ByteBuffer resources)
+		{
+			PatchResourceDirectoryTable (resources);
+		}
+
+		void PatchResourceDirectoryTable (ByteBuffer resources)
+		{
+			resources.Advance (12);
+
+			var entries = resources.ReadUInt16 () + resources.ReadUInt16 ();
+
+			for (int i = 0; i < entries; i++)
+				PatchResourceDirectoryEntry (resources);
+		}
+
+		void PatchResourceDirectoryEntry (ByteBuffer resources)
+		{
+			resources.Advance (4);
+			var child = resources.ReadUInt32 ();
+
+			var position = resources.position;
+			resources.position = (int) child & 0x7fffffff;
+
+			if ((child & 0x80000000) != 0)
+				PatchResourceDirectoryTable (resources);
+			else
+				PatchResourceDataEntry (resources);
+
+			resources.position = position;
+		}
+
+		void PatchResourceDataEntry (ByteBuffer resources)
+		{
+			var old_rsrc = GetImageResourceSection ();
+			var rva = resources.ReadUInt32 ();
+			resources.position -= 4;
+			resources.WriteUInt32 (rva - old_rsrc.VirtualAddress + rsrc.VirtualAddress);
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/Section.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/Section.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/Section.cs	(revision 11807)
@@ -0,0 +1,43 @@
+//
+// Section.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.PE {
+
+	sealed class Section {
+		public string Name;
+		public RVA VirtualAddress;
+		public uint VirtualSize;
+		public uint SizeOfRawData;
+		public uint PointerToRawData;
+		public byte [] Data;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/TextMap.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/TextMap.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil.PE/TextMap.cs	(revision 11807)
@@ -0,0 +1,129 @@
+//
+// TextMap.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+#if !READ_ONLY
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil.PE {
+
+	enum TextSegment {
+		ImportAddressTable,
+		CLIHeader,
+		Code,
+		Resources,
+		Data,
+		StrongNameSignature,
+
+		// Metadata
+		MetadataHeader,
+		TableHeap,
+		StringHeap,
+		UserStringHeap,
+		GuidHeap,
+		BlobHeap,
+		// End Metadata
+
+		DebugDirectory,
+		ImportDirectory,
+		ImportHintNameTable,
+		StartupStub,
+	}
+
+	sealed class TextMap {
+
+		readonly Range [] map = new Range [16 /*Enum.GetValues (typeof (TextSegment)).Length*/];
+
+		public void AddMap (TextSegment segment, int length)
+		{
+			map [(int) segment] = new Range (GetStart (segment), (uint) length);
+		}
+
+		public void AddMap (TextSegment segment, int length, int align)
+		{
+			align--;
+
+			AddMap (segment, (length + align) & ~align);
+		}
+
+		public void AddMap (TextSegment segment, Range range)
+		{
+			map [(int) segment] = range;
+		}
+
+		public Range GetRange (TextSegment segment)
+		{
+			return map [(int) segment];
+		}
+
+		public DataDirectory GetDataDirectory (TextSegment segment)
+		{
+			var range = map [(int) segment];
+
+			return new DataDirectory (range.Length == 0 ? 0 : range.Start, range.Length);
+		}
+
+		public RVA GetRVA (TextSegment segment)
+		{
+			return map [(int) segment].Start;
+		}
+
+		public RVA GetNextRVA (TextSegment segment)
+		{
+			var i = (int) segment;
+			return map [i].Start + map [i].Length;
+		}
+
+		public int GetLength (TextSegment segment)
+		{
+			return (int) map [(int) segment].Length;
+		}
+
+		RVA GetStart (TextSegment segment)
+		{
+			var index = (int) segment;
+			return index == 0 ? ImageWriter.text_rva : ComputeStart (index);
+		}
+
+		RVA ComputeStart (int index)
+		{
+			index--;
+			return map [index].Start + map [index].Length;
+		}
+
+		public uint GetLength ()
+		{
+			var range = map [(int) TextSegment.StartupStub];
+			return range.Start - ImageWriter.text_rva + range.Length;
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ArrayType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ArrayType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ArrayType.cs	(revision 11807)
@@ -0,0 +1,159 @@
+//
+// ArrayType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+using Mono.Collections.Generic;
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public struct ArrayDimension {
+
+		int? lower_bound;
+		int? upper_bound;
+
+		public int? LowerBound {
+			get { return lower_bound; }
+			set { lower_bound = value; }
+		}
+
+		public int? UpperBound {
+			get { return upper_bound; }
+			set { upper_bound = value; }
+		}
+
+		public bool IsSized {
+			get { return lower_bound.HasValue || upper_bound.HasValue; }
+		}
+
+		public ArrayDimension (int? lowerBound, int? upperBound)
+		{
+			this.lower_bound = lowerBound;
+			this.upper_bound = upperBound;
+		}
+
+		public override string ToString ()
+		{
+			return !IsSized
+				? string.Empty
+				: lower_bound + "..." + upper_bound;
+		}
+	}
+
+	public sealed class ArrayType : TypeSpecification {
+
+		Collection<ArrayDimension> dimensions;
+
+		public Collection<ArrayDimension> Dimensions {
+			get {
+				if (dimensions != null)
+					return dimensions;
+
+				dimensions = new Collection<ArrayDimension> ();
+				dimensions.Add (new ArrayDimension ());
+				return dimensions;
+			}
+		}
+
+		public int Rank {
+			get { return dimensions == null ? 1 : dimensions.Count; }
+		}
+
+		public bool IsVector {
+			get {
+				if (dimensions == null)
+					return true;
+
+				if (dimensions.Count > 1)
+					return false;
+
+				var dimension = dimensions [0];
+
+				return !dimension.IsSized;
+			}
+		}
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override string Name {
+			get { return base.Name + Suffix; }
+		}
+
+		public override string FullName {
+			get { return base.FullName + Suffix; }
+		}
+
+		string Suffix {
+			get {
+				if (IsVector)
+					return "[]";
+
+				var suffix = new StringBuilder ();
+				suffix.Append ("[");
+				for (int i = 0; i < dimensions.Count; i++) {
+					if (i > 0)
+						suffix.Append (",");
+
+					suffix.Append (dimensions [i].ToString ());
+				}
+				suffix.Append ("]");
+
+				return suffix.ToString ();
+			}
+		}
+
+		public override bool IsArray {
+			get { return true; }
+		}
+
+		public ArrayType (TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckType (type);
+			this.etype = MD.ElementType.Array;
+		}
+
+		public ArrayType (TypeReference type, int rank)
+			: this (type)
+		{
+			Mixin.CheckType (type);
+
+			if (rank == 1)
+				return;
+
+			dimensions = new Collection<ArrayDimension> (rank);
+			for (int i = 0; i < rank; i++)
+				dimensions.Add (new ArrayDimension ());
+			this.etype = MD.ElementType.Array;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyDefinition.cs	(revision 11807)
@@ -0,0 +1,189 @@
+//
+// AssemblyDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class AssemblyDefinition : ICustomAttributeProvider, ISecurityDeclarationProvider {
+
+		AssemblyNameDefinition name;
+
+		internal ModuleDefinition main_module;
+		Collection<ModuleDefinition> modules;
+		Collection<CustomAttribute> custom_attributes;
+		Collection<SecurityDeclaration> security_declarations;
+
+		public AssemblyNameDefinition Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public string FullName {
+			get { return name != null ? name.FullName : string.Empty; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return new MetadataToken (TokenType.Assembly, 1); }
+			set { }
+		}
+
+		public Collection<ModuleDefinition> Modules {
+			get {
+				if (modules != null)
+					return modules;
+
+				if (main_module.HasImage)
+					return modules = main_module.Read (this, (_, reader) => reader.ReadModules ());
+
+				return modules = new Collection<ModuleDefinition> (1) { main_module };
+			}
+		}
+
+		public ModuleDefinition MainModule {
+			get { return main_module; }
+		}
+
+		public MethodDefinition EntryPoint {
+			get { return main_module.EntryPoint; }
+			set { main_module.EntryPoint = value; }
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (main_module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (main_module)); }
+		}
+
+		public bool HasSecurityDeclarations {
+			get {
+				if (security_declarations != null)
+					return security_declarations.Count > 0;
+
+				return this.GetHasSecurityDeclarations (main_module);
+			}
+		}
+
+		public Collection<SecurityDeclaration> SecurityDeclarations {
+			get { return security_declarations ?? (security_declarations = this.GetSecurityDeclarations (main_module)); }
+		}
+
+		internal AssemblyDefinition ()
+		{
+		}
+
+#if !READ_ONLY
+		public static AssemblyDefinition CreateAssembly (AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind)
+		{
+			return CreateAssembly (assemblyName, moduleName, new ModuleParameters { Kind = kind });
+		}
+
+		public static AssemblyDefinition CreateAssembly (AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters)
+		{
+			if (assemblyName == null)
+				throw new ArgumentNullException ("assemblyName");
+			if (moduleName == null)
+				throw new ArgumentNullException ("moduleName");
+			Mixin.CheckParameters (parameters);
+			if (parameters.Kind == ModuleKind.NetModule)
+				throw new ArgumentException ("kind");
+
+			var assembly = ModuleDefinition.CreateModule (moduleName, parameters).Assembly;
+			assembly.Name = assemblyName;
+
+			return assembly;
+		}
+#endif
+
+		public static AssemblyDefinition ReadAssembly (string fileName)
+		{
+			return ReadAssembly (ModuleDefinition.ReadModule (fileName));
+		}
+
+		public static AssemblyDefinition ReadAssembly (string fileName, ReaderParameters parameters)
+		{
+			return ReadAssembly (ModuleDefinition.ReadModule (fileName, parameters));
+		}
+
+		public static AssemblyDefinition ReadAssembly (Stream stream)
+		{
+			return ReadAssembly (ModuleDefinition.ReadModule (stream));
+		}
+
+		public static AssemblyDefinition ReadAssembly (Stream stream, ReaderParameters parameters)
+		{
+			return ReadAssembly (ModuleDefinition.ReadModule (stream, parameters));
+		}
+
+		static AssemblyDefinition ReadAssembly (ModuleDefinition module)
+		{
+			var assembly = module.Assembly;
+			if (assembly == null)
+				throw new ArgumentException ();
+
+			return assembly;
+		}
+
+#if !READ_ONLY
+		public void Write (string fileName)
+		{
+			Write (fileName, new WriterParameters ());
+		}
+
+		public void Write (Stream stream)
+		{
+			Write (stream, new WriterParameters ());
+		}
+
+		public void Write (string fileName, WriterParameters parameters)
+		{
+			main_module.Write (fileName, parameters);
+		}
+
+		public void Write (Stream stream, WriterParameters parameters)
+		{
+			main_module.Write (stream, parameters);
+		}
+#endif
+
+		public override string ToString ()
+		{
+			return this.FullName;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyFlags.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyFlags.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyFlags.cs	(revision 11807)
@@ -0,0 +1,41 @@
+//
+// AssemblyFlags.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum AssemblyAttributes : uint {
+		PublicKey					 	= 0x0001,
+		SideBySideCompatible			= 0x0000,
+		Retargetable					= 0x0100,
+		DisableJITCompileOptimizer		= 0x4000,
+		EnableJITCompileTracking		= 0x8000,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyHashAlgorithm.cs	(revision 11807)
@@ -0,0 +1,36 @@
+//
+// AssemblyHashAlgorithm.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum AssemblyHashAlgorithm : uint {
+		None		= 0x0000,
+		Reserved	= 0x8003,	// MD5
+		SHA1		= 0x8004
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyLinkedResource.cs	(revision 11807)
@@ -0,0 +1,57 @@
+//
+// AssemblyLinkedResource.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public sealed class AssemblyLinkedResource : Resource {
+
+		AssemblyNameReference reference;
+
+		public AssemblyNameReference Assembly {
+			get { return reference; }
+			set { reference = value; }
+		}
+
+		public override ResourceType ResourceType {
+			get { return ResourceType.AssemblyLinked; }
+		}
+
+		public AssemblyLinkedResource (string name, ManifestResourceAttributes flags)
+			: base (name, flags)
+		{
+		}
+
+		public AssemblyLinkedResource (string name, ManifestResourceAttributes flags, AssemblyNameReference reference)
+			: base (name, flags)
+		{
+			this.reference = reference;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyNameDefinition.cs	(revision 11807)
@@ -0,0 +1,50 @@
+//
+// AssemblyNameDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public sealed class AssemblyNameDefinition : AssemblyNameReference {
+
+		public override byte [] Hash {
+			get { return Empty<byte>.Array; }
+		}
+
+		internal AssemblyNameDefinition ()
+		{
+			this.token = new MetadataToken (TokenType.Assembly, 1);
+		}
+
+		public AssemblyNameDefinition (string name, Version version)
+			: base (name, version)
+		{
+			this.token = new MetadataToken (TokenType.Assembly, 1);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyNameReference.cs	(revision 11807)
@@ -0,0 +1,263 @@
+//
+// AssemblyNameReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Mono.Cecil {
+
+	public class AssemblyNameReference : IMetadataScope {
+
+		string name;
+		string culture;
+		Version version;
+		uint attributes;
+		byte [] public_key;
+		byte [] public_key_token;
+		AssemblyHashAlgorithm hash_algorithm;
+		byte [] hash;
+
+		internal MetadataToken token;
+
+		string full_name;
+
+		public string Name {
+			get { return name; }
+			set {
+				name = value;
+				full_name = null;
+			}
+		}
+
+		public string Culture {
+			get { return culture; }
+			set {
+				culture = value;
+				full_name = null;
+			}
+		}
+
+		public Version Version {
+			get { return version; }
+			set {
+				 version = value;
+				 full_name = null;
+			}
+		}
+
+		public AssemblyAttributes Attributes {
+			get { return (AssemblyAttributes) attributes; }
+			set { attributes = (uint) value; }
+		}
+
+		public bool HasPublicKey {
+			get { return attributes.GetAttributes ((uint) AssemblyAttributes.PublicKey); }
+			set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.PublicKey, value); }
+		}
+
+		public bool IsSideBySideCompatible {
+			get { return attributes.GetAttributes ((uint) AssemblyAttributes.SideBySideCompatible); }
+			set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.SideBySideCompatible, value); }
+		}
+
+		public bool IsRetargetable {
+			get { return attributes.GetAttributes ((uint) AssemblyAttributes.Retargetable); }
+			set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.Retargetable, value); }
+		}
+
+		public byte [] PublicKey {
+			get { return public_key; }
+			set {
+				public_key = value;
+				HasPublicKey = !public_key.IsNullOrEmpty ();
+				public_key_token = Empty<byte>.Array;
+				full_name = null;
+			}
+		}
+
+		public byte [] PublicKeyToken {
+			get {
+				if (public_key_token.IsNullOrEmpty () && !public_key.IsNullOrEmpty ()) {
+					var hash = HashPublicKey ();
+					// we need the last 8 bytes in reverse order
+					public_key_token = new byte [8];
+					Array.Copy (hash, (hash.Length - 8), public_key_token, 0, 8);
+					Array.Reverse (public_key_token, 0, 8);
+				}
+				return public_key_token;
+			}
+			set {
+				public_key_token = value;
+				full_name = null;
+			}
+		}
+
+		byte [] HashPublicKey ()
+		{
+			HashAlgorithm algorithm;
+
+			switch (hash_algorithm) {
+			case AssemblyHashAlgorithm.Reserved:
+#if SILVERLIGHT
+				throw new NotSupportedException ();
+#else
+				algorithm = MD5.Create ();
+				break;
+#endif
+			default:
+				// None default to SHA1
+#if SILVERLIGHT
+				algorithm = new SHA1Managed ();
+				break;
+#else
+				algorithm = SHA1.Create ();
+				break;
+#endif
+			}
+
+			using (algorithm)
+				return algorithm.ComputeHash (public_key);
+		}
+
+		public virtual MetadataScopeType MetadataScopeType {
+			get { return MetadataScopeType.AssemblyNameReference; }
+		}
+
+		public string FullName {
+			get {
+				if (full_name != null)
+					return full_name;
+
+				const string sep = ", ";
+
+				var builder = new StringBuilder ();
+				builder.Append (name);
+				if (version != null) {
+					builder.Append (sep);
+					builder.Append ("Version=");
+					builder.Append (version.ToString ());
+				}
+				builder.Append (sep);
+				builder.Append ("Culture=");
+				builder.Append (string.IsNullOrEmpty (culture) ? "neutral" : culture);
+				builder.Append (sep);
+				builder.Append ("PublicKeyToken=");
+
+				if (this.PublicKeyToken != null && public_key_token.Length > 0) {
+					for (int i = 0 ; i < public_key_token.Length ; i++) {
+						builder.Append (public_key_token [i].ToString ("x2"));
+					}
+				} else
+					builder.Append ("null");
+
+				return full_name = builder.ToString ();
+			}
+		}
+
+		public static AssemblyNameReference Parse (string fullName)
+		{
+			if (fullName == null)
+				throw new ArgumentNullException ("fullName");
+			if (fullName.Length == 0)
+				throw new ArgumentException ("Name can not be empty");
+
+			var name = new AssemblyNameReference ();
+			var tokens = fullName.Split (',');
+			for (int i = 0; i < tokens.Length; i++) {
+				var token = tokens [i].Trim ();
+
+				if (i == 0) {
+					name.Name = token;
+					continue;
+				}
+
+				var parts = token.Split ('=');
+				if (parts.Length != 2)
+					throw new ArgumentException ("Malformed name");
+
+				switch (parts [0]) {
+				case "Version":
+					name.Version = new Version (parts [1]);
+					break;
+				case "Culture":
+					name.Culture = parts [1];
+					break;
+				case "PublicKeyToken":
+					string pk_token = parts [1];
+					if (pk_token == "null")
+						break;
+
+					name.PublicKeyToken = new byte [pk_token.Length / 2];
+					for (int j = 0; j < name.PublicKeyToken.Length; j++) {
+						name.PublicKeyToken [j] = Byte.Parse (pk_token.Substring (j * 2, 2), NumberStyles.HexNumber);
+					}
+					break;
+				}
+			}
+
+			return name;
+		}
+
+		public AssemblyHashAlgorithm HashAlgorithm {
+			get { return hash_algorithm; }
+			set { hash_algorithm = value; }
+		}
+
+		public virtual byte [] Hash {
+			get { return hash; }
+			set { hash = value; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return token; }
+			set { token = value; }
+		}
+
+		internal AssemblyNameReference ()
+		{
+		}
+
+		public AssemblyNameReference (string name, Version version)
+		{
+			if (name == null)
+				throw new ArgumentNullException ("name");
+
+			this.name = name;
+			this.version = version;
+			this.hash_algorithm = AssemblyHashAlgorithm.None;
+			this.token = new MetadataToken (TokenType.AssemblyRef);
+		}
+
+		public override string ToString ()
+		{
+			return this.FullName;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyReader.cs	(revision 11807)
@@ -0,0 +1,3147 @@
+//
+// AssemblyReader.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+using Mono.Collections.Generic;
+using Mono.Cecil.Cil;
+using Mono.Cecil.Metadata;
+using Mono.Cecil.PE;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil {
+
+	abstract class ModuleReader {
+
+		readonly protected Image image;
+		readonly protected ModuleDefinition module;
+
+		protected ModuleReader (Image image, ReadingMode mode)
+		{
+			this.image = image;
+			this.module = new ModuleDefinition (image);
+			this.module.ReadingMode = mode;
+		}
+
+		protected abstract void ReadModule ();
+
+		protected void ReadModuleManifest (MetadataReader reader)
+		{
+			reader.Populate (module);
+
+			ReadAssembly (reader);
+		}
+
+		void ReadAssembly (MetadataReader reader)
+		{
+			var name = reader.ReadAssemblyNameDefinition ();
+			if (name == null) {
+				module.kind = ModuleKind.NetModule;
+				return;
+			}
+
+			var assembly = new AssemblyDefinition ();
+			assembly.Name = name;
+
+			module.assembly = assembly;
+			assembly.main_module = module;
+		}
+
+		public static ModuleDefinition CreateModuleFrom (Image image, ReaderParameters parameters)
+		{
+			var module = ReadModule (image, parameters);
+
+			ReadSymbols (module, parameters);
+
+			if (parameters.AssemblyResolver != null)
+				module.assembly_resolver = parameters.AssemblyResolver;
+
+			return module;
+		}
+
+		static void ReadSymbols (ModuleDefinition module, ReaderParameters parameters)
+		{
+			var symbol_reader_provider = parameters.SymbolReaderProvider;
+
+			if (symbol_reader_provider == null && parameters.ReadSymbols)
+				symbol_reader_provider = SymbolProvider.GetPlatformReaderProvider ();
+
+			if (symbol_reader_provider != null) {
+				module.SymbolReaderProvider = symbol_reader_provider;
+
+				var reader = parameters.SymbolStream != null
+					? symbol_reader_provider.GetSymbolReader (module, parameters.SymbolStream)
+					: symbol_reader_provider.GetSymbolReader (module, module.FullyQualifiedName);
+
+				module.ReadSymbols (reader);
+			}
+		}
+
+		static ModuleDefinition ReadModule (Image image, ReaderParameters parameters)
+		{
+			var reader = CreateModuleReader (image, parameters.ReadingMode);
+			reader.ReadModule ();
+			return reader.module;
+		}
+
+		static ModuleReader CreateModuleReader (Image image, ReadingMode mode)
+		{
+			switch (mode) {
+			case ReadingMode.Immediate:
+				return new ImmediateModuleReader (image);
+			case ReadingMode.Deferred:
+				return new DeferredModuleReader (image);
+			default:
+				throw new ArgumentException ();
+			}
+		}
+	}
+
+	sealed class ImmediateModuleReader : ModuleReader {
+
+		public ImmediateModuleReader (Image image)
+			: base (image, ReadingMode.Immediate)
+		{
+		}
+
+		protected override void ReadModule ()
+		{
+			this.module.Read (this.module, (module, reader) => {
+				ReadModuleManifest (reader);
+				ReadModule (module);
+				return module;
+			});
+		}
+
+		public static void ReadModule (ModuleDefinition module)
+		{
+			if (module.HasAssemblyReferences)
+				Read (module.AssemblyReferences);
+			if (module.HasResources)
+				Read (module.Resources);
+			if (module.HasModuleReferences)
+				Read (module.ModuleReferences);
+			if (module.HasTypes)
+				ReadTypes (module.Types);
+			if (module.HasExportedTypes)
+				Read (module.ExportedTypes);
+			if (module.HasCustomAttributes)
+				Read (module.CustomAttributes);
+
+			var assembly = module.Assembly;
+			if (assembly == null)
+				return;
+
+			if (assembly.HasCustomAttributes)
+				Read (assembly.CustomAttributes);
+			if (assembly.HasSecurityDeclarations)
+				Read (assembly.SecurityDeclarations);
+		}
+
+		static void ReadTypes (Collection<TypeDefinition> types)
+		{
+			for (int i = 0; i < types.Count; i++)
+				ReadType (types [i]);
+		}
+
+		static void ReadType (TypeDefinition type)
+		{
+			ReadGenericParameters (type);
+
+			if (type.HasInterfaces)
+				Read (type.Interfaces);
+
+			if (type.HasNestedTypes)
+				ReadTypes (type.NestedTypes);
+
+			if (type.HasLayoutInfo)
+				Read (type.ClassSize);
+
+			if (type.HasFields)
+				ReadFields (type);
+
+			if (type.HasMethods)
+				ReadMethods (type);
+
+			if (type.HasProperties)
+				ReadProperties (type);
+
+			if (type.HasEvents)
+				ReadEvents (type);
+
+			ReadSecurityDeclarations (type);
+			ReadCustomAttributes (type);
+		}
+
+		static void ReadGenericParameters (IGenericParameterProvider provider)
+		{
+			if (!provider.HasGenericParameters)
+				return;
+
+			var parameters = provider.GenericParameters;
+
+			for (int i = 0; i < parameters.Count; i++) {
+				var parameter = parameters [i];
+
+				if (parameter.HasConstraints)
+					Read (parameter.Constraints);
+
+				if (parameter.HasCustomAttributes)
+					Read (parameter.CustomAttributes);
+			}
+		}
+
+		static void ReadSecurityDeclarations (ISecurityDeclarationProvider provider)
+		{
+			if (provider.HasSecurityDeclarations)
+				Read (provider.SecurityDeclarations);
+		}
+
+		static void ReadCustomAttributes (ICustomAttributeProvider provider)
+		{
+			if (provider.HasCustomAttributes)
+				Read (provider.CustomAttributes);
+		}
+
+		static void ReadFields (TypeDefinition type)
+		{
+			var fields = type.Fields;
+
+			for (int i = 0; i < fields.Count; i++) {
+				var field = fields [i];
+
+				if (field.HasConstant)
+					Read (field.Constant);
+
+				if (field.HasLayoutInfo)
+					Read (field.Offset);
+
+				if (field.RVA > 0)
+					Read (field.InitialValue);
+
+				if (field.HasMarshalInfo)
+					Read (field.MarshalInfo);
+
+				ReadCustomAttributes (field);
+			}
+		}
+
+		static void ReadMethods (TypeDefinition type)
+		{
+			var methods = type.Methods;
+
+			for (int i = 0; i < methods.Count; i++) {
+				var method = methods [i];
+
+				ReadGenericParameters (method);
+
+				if (method.HasParameters)
+					ReadParameters (method);
+
+				if (method.HasOverrides)
+					Read (method.Overrides);
+
+				if (method.IsPInvokeImpl)
+					Read (method.PInvokeInfo);
+
+				ReadSecurityDeclarations (method);
+				ReadCustomAttributes (method);
+
+				var return_type = method.MethodReturnType;
+				if (return_type.HasConstant)
+					Read (return_type.Constant);
+
+				if (return_type.HasMarshalInfo)
+					Read (return_type.MarshalInfo);
+
+				ReadCustomAttributes (return_type);
+			}
+		}
+
+		static void ReadParameters (MethodDefinition method)
+		{
+			var parameters = method.Parameters;
+
+			for (int i = 0; i < parameters.Count; i++) {
+				var parameter = parameters [i];
+
+				if (parameter.HasConstant)
+					Read (parameter.Constant);
+
+				if (parameter.HasMarshalInfo)
+					Read (parameter.MarshalInfo);
+
+				ReadCustomAttributes (parameter);
+			}
+		}
+
+		static void ReadProperties (TypeDefinition type)
+		{
+			var properties = type.Properties;
+
+			for (int i = 0; i < properties.Count; i++) {
+				var property = properties [i];
+
+				Read (property.GetMethod);
+
+				if (property.HasConstant)
+					Read (property.Constant);
+
+				ReadCustomAttributes (property);
+			}
+		}
+
+		static void ReadEvents (TypeDefinition type)
+		{
+			var events = type.Events;
+
+			for (int i = 0; i < events.Count; i++) {
+				var @event = events [i];
+
+				Read (@event.AddMethod);
+
+				ReadCustomAttributes (@event);
+			}
+		}
+
+		static void Read (object collection)
+		{
+		}
+	}
+
+	sealed class DeferredModuleReader : ModuleReader {
+
+		public DeferredModuleReader (Image image)
+			: base (image, ReadingMode.Deferred)
+		{
+		}
+
+		protected override void ReadModule ()
+		{
+			this.module.Read (this.module, (module, reader) => {
+				ReadModuleManifest (reader);
+				return module;
+			});
+		}
+	}
+
+	sealed class MetadataReader : ByteBuffer {
+
+		readonly internal Image image;
+		readonly internal ModuleDefinition module;
+		readonly internal MetadataSystem metadata;
+
+		internal IGenericContext context;
+		internal CodeReader code;
+
+		uint Position {
+			get { return (uint) base.position; }
+			set { base.position = (int) value; }
+		}
+
+		public MetadataReader (ModuleDefinition module)
+			: base (module.Image.MetadataSection.Data)
+		{
+			this.image = module.Image;
+			this.module = module;
+			this.metadata = module.MetadataSystem;
+			this.code = new CodeReader (image.MetadataSection, this);
+		}
+
+		int GetCodedIndexSize (CodedIndex index)
+		{
+			return image.GetCodedIndexSize (index);
+		}
+
+		uint ReadByIndexSize (int size)
+		{
+			if (size == 4)
+				return ReadUInt32 ();
+			else
+				return ReadUInt16 ();
+		}
+
+		byte [] ReadBlob ()
+		{
+			var blob_heap = image.BlobHeap;
+			if (blob_heap == null) {
+				position += 2;
+				return Empty<byte>.Array;
+			}
+
+			return blob_heap.Read (ReadBlobIndex ());
+		}
+
+		byte [] ReadBlob (uint signature)
+		{
+			var blob_heap = image.BlobHeap;
+			if (blob_heap == null)
+				return Empty<byte>.Array;
+
+			return blob_heap.Read (signature);
+		}
+
+		uint ReadBlobIndex ()
+		{
+			var blob_heap = image.BlobHeap;
+			return ReadByIndexSize (blob_heap != null ? blob_heap.IndexSize : 2);
+		}
+
+		string ReadString ()
+		{
+			return image.StringHeap.Read (ReadByIndexSize (image.StringHeap.IndexSize));
+		}
+
+		uint ReadStringIndex ()
+		{
+			return ReadByIndexSize (image.StringHeap.IndexSize);
+		}
+
+		uint ReadTableIndex (Table table)
+		{
+			return ReadByIndexSize (image.GetTableIndexSize (table));
+		}
+
+		MetadataToken ReadMetadataToken (CodedIndex index)
+		{
+			return index.GetMetadataToken (ReadByIndexSize (GetCodedIndexSize (index)));
+		}
+
+		int MoveTo (Table table)
+		{
+			var info = image.TableHeap [table];
+			if (info.Length != 0)
+				Position = info.Offset;
+
+			return (int) info.Length;
+		}
+
+		bool MoveTo (Table table, uint row)
+		{
+			var info = image.TableHeap [table];
+			var length = info.Length;
+			if (length == 0 || row > length)
+				return false;
+
+			Position = info.Offset + (info.RowSize * (row - 1));
+			return true;
+		}
+
+		public AssemblyNameDefinition ReadAssemblyNameDefinition ()
+		{
+			if (MoveTo (Table.Assembly) == 0)
+				return null;
+
+			var name = new AssemblyNameDefinition ();
+
+			name.HashAlgorithm = (AssemblyHashAlgorithm) ReadUInt32 ();
+
+			PopulateVersionAndFlags (name);
+
+			name.PublicKey = ReadBlob ();
+
+			PopulateNameAndCulture (name);
+
+			return name;
+		}
+
+		public ModuleDefinition Populate (ModuleDefinition module)
+		{
+			if (MoveTo (Table.Module) == 0)
+				return module;
+
+			Advance (2); // Generation
+
+			module.Name = ReadString ();
+			module.Mvid = image.GuidHeap.Read (ReadByIndexSize (image.GuidHeap.IndexSize));
+
+			return module;
+		}
+
+		void InitializeAssemblyReferences ()
+		{
+			if (metadata.AssemblyReferences != null)
+				return;
+
+			int length = MoveTo (Table.AssemblyRef);
+			var references = metadata.AssemblyReferences = new AssemblyNameReference [length];
+
+			for (uint i = 0; i < length; i++) {
+				var reference = new AssemblyNameReference ();
+				reference.token = new MetadataToken (TokenType.AssemblyRef, i + 1);
+
+				PopulateVersionAndFlags (reference);
+
+				var key_or_token = ReadBlob ();
+
+				if (reference.HasPublicKey)
+					reference.PublicKey = key_or_token;
+				else
+					reference.PublicKeyToken = key_or_token;
+
+				PopulateNameAndCulture (reference);
+
+				reference.Hash = ReadBlob ();
+
+				references [i] = reference;
+			}
+		}
+
+		public Collection<AssemblyNameReference> ReadAssemblyReferences ()
+		{
+			InitializeAssemblyReferences ();
+
+			return new Collection<AssemblyNameReference> (metadata.AssemblyReferences);
+		}
+
+		public MethodDefinition ReadEntryPoint ()
+		{
+			if (module.Kind != ModuleKind.Console && module.Kind != ModuleKind.Windows)
+				return null;
+
+			var token = new MetadataToken (module.Image.EntryPointToken);
+
+			return GetMethodDefinition (token.RID);
+		}
+
+		public Collection<ModuleDefinition> ReadModules ()
+		{
+			var modules = new Collection<ModuleDefinition> (1);
+			modules.Add (this.module);
+
+			int length = MoveTo (Table.File);
+			for (uint i = 1; i <= length; i++) {
+				var attributes = (FileAttributes) ReadUInt32 ();
+				var name = ReadString ();
+				ReadBlobIndex ();
+
+				if (attributes != FileAttributes.ContainsMetaData)
+					continue;
+
+				var parameters = new ReaderParameters {
+					ReadingMode = module.ReadingMode,
+					SymbolReaderProvider = module.SymbolReaderProvider,
+				};
+
+				modules.Add (ModuleDefinition.ReadModule (
+					GetModuleFileName (name), parameters));
+			}
+
+			return modules;
+		}
+
+		string GetModuleFileName (string name)
+		{
+			if (module.FullyQualifiedName == null)
+				throw new NotSupportedException ();
+
+			var path = Path.GetDirectoryName (module.FullyQualifiedName);
+			return Path.Combine (path, name);
+		}
+
+		void InitializeModuleReferences ()
+		{
+			if (metadata.ModuleReferences != null)
+				return;
+
+			int length = MoveTo (Table.ModuleRef);
+			var references = metadata.ModuleReferences = new ModuleReference [length];
+
+			for (uint i = 0; i < length; i++) {
+				var reference = new ModuleReference (ReadString ());
+				reference.token = new MetadataToken (TokenType.ModuleRef, i + 1);
+
+				references [i] = reference;
+			}
+		}
+
+		public Collection<ModuleReference> ReadModuleReferences ()
+		{
+			InitializeModuleReferences ();
+
+			return new Collection<ModuleReference> (metadata.ModuleReferences);
+		}
+
+		public bool HasFileResource ()
+		{
+			int length = MoveTo (Table.File);
+			if (length == 0)
+				return false;
+
+			for (uint i = 1; i <= length; i++)
+				if (ReadFileRecord (i).Col1 == FileAttributes.ContainsNoMetaData)
+					return true;
+
+			return false;
+		}
+
+		public Collection<Resource> ReadResources ()
+		{
+			int length = MoveTo (Table.ManifestResource);
+			var resources = new Collection<Resource> (length);
+
+			for (int i = 1; i <= length; i++) {
+				var offset = ReadUInt32 ();
+				var flags = (ManifestResourceAttributes) ReadUInt32 ();
+				var name = ReadString ();
+				var implementation = ReadMetadataToken (CodedIndex.Implementation);
+
+				Resource resource;
+
+				if (implementation.RID == 0) {
+					resource = new EmbeddedResource (name, flags, offset, this);
+				} else if (implementation.TokenType == TokenType.AssemblyRef) {
+					resource = new AssemblyLinkedResource (name, flags) {
+						Assembly = (AssemblyNameReference) GetTypeReferenceScope (implementation),
+					};
+				} else if (implementation.TokenType == TokenType.File) {
+					var file_record = ReadFileRecord (implementation.RID);
+
+					resource = new LinkedResource (name, flags) {
+						File = file_record.Col2,
+						hash = ReadBlob (file_record.Col3)
+					};
+				} else
+					throw new NotSupportedException ();
+
+				resources.Add (resource);
+			}
+
+			return resources;
+		}
+
+		Row<FileAttributes, string, uint> ReadFileRecord (uint rid)
+		{
+			var position = this.position;
+
+			if (!MoveTo (Table.File, rid))
+				throw new ArgumentException ();
+
+			var record = new Row<FileAttributes, string, uint> (
+				(FileAttributes) ReadUInt32 (),
+				ReadString (),
+				ReadBlobIndex ());
+
+			this.position = position;
+
+			return record;
+		}
+
+		public MemoryStream GetManagedResourceStream (uint offset)
+		{
+			var rva = image.Resources.VirtualAddress;
+			var section = image.GetSectionAtVirtualAddress (rva);
+			var position = (rva - section.VirtualAddress) + offset;
+			var buffer = section.Data;
+
+			var length = buffer [position]
+				| (buffer [position + 1] << 8)
+				| (buffer [position + 2] << 16)
+				| (buffer [position + 3] << 24);
+
+			return new MemoryStream (buffer, (int) position + 4, length);
+		}
+
+		void PopulateVersionAndFlags (AssemblyNameReference name)
+		{
+			name.Version = new Version (
+				ReadUInt16 (),
+				ReadUInt16 (),
+				ReadUInt16 (),
+				ReadUInt16 ());
+
+			name.Attributes = (AssemblyAttributes) ReadUInt32 ();
+		}
+
+		void PopulateNameAndCulture (AssemblyNameReference name)
+		{
+			name.Name = ReadString ();
+			name.Culture = ReadString ();
+		}
+
+		public TypeDefinitionCollection ReadTypes ()
+		{
+			InitializeTypeDefinitions ();
+			var mtypes = metadata.Types;
+			var type_count = mtypes.Length - metadata.NestedTypes.Count;
+			var types = new TypeDefinitionCollection (module, type_count);
+
+			for (int i = 0; i < mtypes.Length; i++) {
+				var type = mtypes [i];
+				if (IsNested (type.Attributes))
+					continue;
+
+				types.Add (type);
+			}
+
+			if (image.HasTable (Table.MethodPtr) || image.HasTable (Table.FieldPtr))
+				CompleteTypes ();
+
+			return types;
+		}
+
+		void CompleteTypes ()
+		{
+			var types = metadata.Types;
+
+			for (int i = 0; i < types.Length; i++) {
+				var type = types [i];
+
+				InitializeCollection (type.Fields);
+				InitializeCollection (type.Methods);
+			}
+		}
+
+		void InitializeTypeDefinitions ()
+		{
+			if (metadata.Types != null)
+				return;
+
+			InitializeNestedTypes ();
+			InitializeFields ();
+			InitializeMethods ();
+
+			int length = MoveTo (Table.TypeDef);
+			var types = metadata.Types = new TypeDefinition [length];
+
+			for (uint i = 0; i < length; i++) {
+				if (types [i] != null)
+					continue;
+
+				types [i] = ReadType (i + 1);
+			}
+		}
+
+		static bool IsNested (TypeAttributes attributes)
+		{
+			switch (attributes & TypeAttributes.VisibilityMask) {
+			case TypeAttributes.NestedAssembly:
+			case TypeAttributes.NestedFamANDAssem:
+			case TypeAttributes.NestedFamily:
+			case TypeAttributes.NestedFamORAssem:
+			case TypeAttributes.NestedPrivate:
+			case TypeAttributes.NestedPublic:
+				return true;
+			default:
+				return false;
+			}
+		}
+
+		public bool HasNestedTypes (TypeDefinition type)
+		{
+			uint [] mapping;
+			InitializeNestedTypes ();
+
+			if (!metadata.TryGetNestedTypeMapping (type, out mapping))
+				return false;
+
+			return mapping.Length > 0;
+		}
+
+		public Collection<TypeDefinition> ReadNestedTypes (TypeDefinition type)
+		{
+			InitializeNestedTypes ();
+			uint [] mapping;
+			if (!metadata.TryGetNestedTypeMapping (type, out mapping))
+				return new MemberDefinitionCollection<TypeDefinition> (type);
+
+			var nested_types = new MemberDefinitionCollection<TypeDefinition> (type, mapping.Length);
+
+			for (int i = 0; i < mapping.Length; i++)
+				nested_types.Add (GetTypeDefinition (mapping [i]));
+
+			metadata.RemoveNestedTypeMapping (type);
+
+			return nested_types;
+		}
+
+		void InitializeNestedTypes ()
+		{
+			if (metadata.NestedTypes != null)
+				return;
+
+			var length = MoveTo (Table.NestedClass);
+
+			metadata.NestedTypes = new Dictionary<uint, uint []> (length);
+			metadata.ReverseNestedTypes = new Dictionary<uint, uint> (length);
+
+			if (length == 0)
+				return;
+
+			for (int i = 1; i <= length; i++) {
+				var nested = ReadTableIndex (Table.TypeDef);
+				var declaring = ReadTableIndex (Table.TypeDef);
+
+				AddNestedMapping (declaring, nested);
+			}
+		}
+
+		void AddNestedMapping (uint declaring, uint nested)
+		{
+			metadata.SetNestedTypeMapping (declaring, AddMapping (metadata.NestedTypes, declaring, nested));
+			metadata.SetReverseNestedTypeMapping (nested, declaring);
+		}
+
+		static TValue [] AddMapping<TKey, TValue> (Dictionary<TKey, TValue []> cache, TKey key, TValue value)
+		{
+			TValue [] mapped;
+			if (!cache.TryGetValue (key, out mapped)) {
+				mapped = new [] { value };
+				return mapped;
+			}
+
+			var new_mapped = new TValue [mapped.Length + 1];
+			Array.Copy (mapped, new_mapped, mapped.Length);
+			new_mapped [mapped.Length] = value;
+			return new_mapped;
+		}
+
+		TypeDefinition ReadType (uint rid)
+		{
+			if (!MoveTo (Table.TypeDef, rid))
+				return null;
+
+			var attributes = (TypeAttributes) ReadUInt32 ();
+			var name = ReadString ();
+			var @namespace = ReadString ();
+			var type = new TypeDefinition (@namespace, name, attributes);
+			type.token = new MetadataToken (TokenType.TypeDef, rid);
+			type.scope = module;
+			type.module = module;
+
+			metadata.AddTypeDefinition (type);
+
+			this.context = type;
+
+			type.BaseType = GetTypeDefOrRef (ReadMetadataToken (CodedIndex.TypeDefOrRef));
+
+			type.fields_range = ReadFieldsRange (rid);
+			type.methods_range = ReadMethodsRange (rid);
+
+			if (IsNested (attributes))
+				type.DeclaringType = GetNestedTypeDeclaringType (type);
+
+			return type;
+		}
+
+		TypeDefinition GetNestedTypeDeclaringType (TypeDefinition type)
+		{
+			uint declaring_rid;
+			if (!metadata.TryGetReverseNestedTypeMapping (type, out declaring_rid))
+				return null;
+
+			metadata.RemoveReverseNestedTypeMapping (type);
+			return GetTypeDefinition (declaring_rid);
+		}
+
+		Range ReadFieldsRange (uint type_index)
+		{
+			return ReadListRange (type_index, Table.TypeDef, Table.Field);
+		}
+
+		Range ReadMethodsRange (uint type_index)
+		{
+			return ReadListRange (type_index, Table.TypeDef, Table.Method);
+		}
+
+		Range ReadListRange (uint current_index, Table current, Table target)
+		{
+			var list = new Range ();
+
+			list.Start = ReadTableIndex (target);
+
+			uint next_index;
+			var current_table = image.TableHeap [current];
+
+			if (current_index == current_table.Length)
+				next_index = image.TableHeap [target].Length + 1;
+			else {
+				var position = Position;
+				Position += (uint) (current_table.RowSize - image.GetTableIndexSize (target));
+				next_index = ReadTableIndex (target);
+				Position = position;
+			}
+
+			list.Length = next_index - list.Start;
+
+			return list;
+		}
+
+		public Row<short, int> ReadTypeLayout (TypeDefinition type)
+		{
+			InitializeTypeLayouts ();
+			Row<ushort, uint> class_layout;
+			var rid = type.token.RID;
+			if (!metadata.ClassLayouts.TryGetValue (rid, out class_layout))
+				return new Row<short, int> (Mixin.NoDataMarker, Mixin.NoDataMarker);
+
+			type.PackingSize = (short) class_layout.Col1;
+			type.ClassSize = (int) class_layout.Col2;
+
+			metadata.ClassLayouts.Remove (rid);
+
+			return new Row<short, int> ((short) class_layout.Col1, (int) class_layout.Col2);
+		}
+
+		void InitializeTypeLayouts ()
+		{
+			if (metadata.ClassLayouts != null)
+				return;
+
+			int length = MoveTo (Table.ClassLayout);
+
+			var class_layouts = metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>> (length);
+
+			for (uint i = 0; i < length; i++) {
+				var packing_size = ReadUInt16 ();
+				var class_size = ReadUInt32 ();
+
+				var parent = ReadTableIndex (Table.TypeDef);
+
+				class_layouts.Add (parent, new Row<ushort, uint> (packing_size, class_size));
+			}
+		}
+
+		public TypeReference GetTypeDefOrRef (MetadataToken token)
+		{
+			return (TypeReference) LookupToken (token);
+		}
+
+		public TypeDefinition GetTypeDefinition (uint rid)
+		{
+			InitializeTypeDefinitions ();
+
+			var type = metadata.GetTypeDefinition (rid);
+			if (type != null)
+				return type;
+
+			return ReadTypeDefinition (rid);
+		}
+
+		TypeDefinition ReadTypeDefinition (uint rid)
+		{
+			if (!MoveTo (Table.TypeDef, rid))
+				return null;
+
+			return ReadType (rid);
+		}
+
+		void InitializeTypeReferences ()
+		{
+			if (metadata.TypeReferences != null)
+				return;
+
+			metadata.TypeReferences = new TypeReference [image.GetTableLength (Table.TypeRef)];
+		}
+
+		public TypeReference GetTypeReference (string scope, string full_name)
+		{
+			InitializeTypeReferences ();
+
+			var length = metadata.TypeReferences.Length;
+
+			for (uint i = 1; i <= length; i++) {
+				var type = GetTypeReference (i);
+
+				if (type.FullName != full_name)
+					continue;
+
+				if (string.IsNullOrEmpty (scope))
+					return type;
+
+				if (type.Scope.Name == scope)
+					return type;
+			}
+
+			return null;
+		}
+
+		TypeReference GetTypeReference (uint rid)
+		{
+			InitializeTypeReferences ();
+
+			var type = metadata.GetTypeReference (rid);
+			if (type != null)
+				return type;
+
+			return ReadTypeReference (rid);
+		}
+
+		TypeReference ReadTypeReference (uint rid)
+		{
+			if (!MoveTo (Table.TypeRef, rid))
+				return null;
+
+			TypeReference declaring_type = null;
+			IMetadataScope scope;
+
+			var scope_token = ReadMetadataToken (CodedIndex.ResolutionScope);
+
+			var name = ReadString ();
+			var @namespace = ReadString ();
+
+			var type = new TypeReference (
+				@namespace,
+				name,
+				module,
+				null);
+
+			type.token = new MetadataToken (TokenType.TypeRef, rid);
+
+			metadata.AddTypeReference (type);
+
+			if (scope_token.TokenType == TokenType.TypeRef) {
+				declaring_type = GetTypeDefOrRef (scope_token);
+
+				scope = declaring_type != null
+					? declaring_type.Scope
+					: module;
+			} else
+				scope = GetTypeReferenceScope (scope_token);
+
+			type.scope = scope;
+			type.DeclaringType = declaring_type;
+
+			MetadataSystem.TryProcessPrimitiveType (type);
+
+			return type;
+		}
+
+		IMetadataScope GetTypeReferenceScope (MetadataToken scope)
+		{
+			switch (scope.TokenType) {
+			case TokenType.AssemblyRef:
+				InitializeAssemblyReferences ();
+				return metadata.AssemblyReferences [(int) scope.RID - 1];
+			case TokenType.ModuleRef:
+				InitializeModuleReferences ();
+				return metadata.ModuleReferences [(int) scope.RID - 1];
+			case TokenType.Module:
+				return module;
+			default:
+				throw new NotSupportedException ();
+			}
+		}
+
+		public IEnumerable<TypeReference> GetTypeReferences ()
+		{
+			InitializeTypeReferences ();
+
+			var length = image.GetTableLength (Table.TypeRef);
+
+			var type_references = new TypeReference [length];
+
+			for (uint i = 1; i <= length; i++)
+				type_references [i - 1] = GetTypeReference (i);
+
+			return type_references;
+		}
+
+		TypeReference GetTypeSpecification (uint rid)
+		{
+			if (!MoveTo (Table.TypeSpec, rid))
+				return null;
+
+			var reader = ReadSignature (ReadBlobIndex ());
+			var type = reader.ReadTypeSignature ();
+			if (type.token.RID == 0)
+				type.token = new MetadataToken (TokenType.TypeSpec, rid);
+
+			return type;
+		}
+
+		SignatureReader ReadSignature (uint signature)
+		{
+			return new SignatureReader (signature, this);
+		}
+
+		public bool HasInterfaces (TypeDefinition type)
+		{
+			InitializeInterfaces ();
+			MetadataToken [] mapping;
+
+			return metadata.TryGetInterfaceMapping (type, out mapping);
+		}
+
+		public Collection<TypeReference> ReadInterfaces (TypeDefinition type)
+		{
+			InitializeInterfaces ();
+			MetadataToken [] mapping;
+
+			if (!metadata.TryGetInterfaceMapping (type, out mapping))
+				return new Collection<TypeReference> ();
+
+			var interfaces = new Collection<TypeReference> (mapping.Length);
+
+			this.context = type;
+
+			for (int i = 0; i < mapping.Length; i++)
+				interfaces.Add (GetTypeDefOrRef (mapping [i]));
+
+			metadata.RemoveInterfaceMapping (type);
+
+			return interfaces;
+		}
+
+		void InitializeInterfaces ()
+		{
+			if (metadata.Interfaces != null)
+				return;
+
+			int length = MoveTo (Table.InterfaceImpl);
+
+			metadata.Interfaces = new Dictionary<uint, MetadataToken []> (length);
+
+			for (int i = 0; i < length; i++) {
+				var type = ReadTableIndex (Table.TypeDef);
+				var @interface = ReadMetadataToken (CodedIndex.TypeDefOrRef);
+
+				AddInterfaceMapping (type, @interface);
+			}
+		}
+
+		void AddInterfaceMapping (uint type, MetadataToken @interface)
+		{
+			metadata.SetInterfaceMapping (type, AddMapping (metadata.Interfaces, type, @interface));
+		}
+
+		public Collection<FieldDefinition> ReadFields (TypeDefinition type)
+		{
+			var fields_range = type.fields_range;
+			if (fields_range.Length == 0)
+				return new MemberDefinitionCollection<FieldDefinition> (type);
+
+			var fields = new MemberDefinitionCollection<FieldDefinition> (type, (int) fields_range.Length);
+			this.context = type;
+
+			if (!MoveTo (Table.FieldPtr, fields_range.Start)) {
+				if (!MoveTo (Table.Field, fields_range.Start))
+					return fields;
+
+				for (uint i = 0; i < fields_range.Length; i++)
+					ReadField (fields_range.Start + i, fields);
+			} else
+				ReadPointers (Table.FieldPtr, Table.Field, fields_range, fields, ReadField);
+
+			return fields;
+		}
+
+		void ReadField (uint field_rid, Collection<FieldDefinition> fields)
+		{
+			var attributes = (FieldAttributes) ReadUInt16 ();
+			var name = ReadString ();
+			var signature = ReadBlobIndex ();
+
+			var field = new FieldDefinition (name, attributes, ReadFieldType (signature));
+			field.token = new MetadataToken (TokenType.Field, field_rid);
+			metadata.AddFieldDefinition (field);
+
+			if (IsDeleted (field))
+				return;
+
+			fields.Add (field);
+		}
+
+		void InitializeFields ()
+		{
+			if (metadata.Fields != null)
+				return;
+
+			metadata.Fields = new FieldDefinition [image.GetTableLength (Table.Field)];
+		}
+
+		TypeReference ReadFieldType (uint signature)
+		{
+			var reader = ReadSignature (signature);
+
+			const byte field_sig = 0x6;
+
+			if (reader.ReadByte () != field_sig)
+				throw new NotSupportedException ();
+
+			return reader.ReadTypeSignature ();
+		}
+
+		public int ReadFieldRVA (FieldDefinition field)
+		{
+			InitializeFieldRVAs ();
+			var rid = field.token.RID;
+
+			RVA rva;
+			if (!metadata.FieldRVAs.TryGetValue (rid, out rva))
+				return 0;
+
+			var size = GetFieldTypeSize (field.FieldType);
+
+			if (size == 0 || rva == 0)
+				return 0;
+
+			metadata.FieldRVAs.Remove (rid);
+
+			field.InitialValue = GetFieldInitializeValue (size, rva);
+
+			return (int) rva;
+		}
+
+		byte [] GetFieldInitializeValue (int size, RVA rva)
+		{
+			var section = image.GetSectionAtVirtualAddress (rva);
+			if (section == null)
+				return Empty<byte>.Array;
+
+			var value = new byte [size];
+			Buffer.BlockCopy (section.Data, (int) (rva - section.VirtualAddress), value, 0, size);
+			return value;
+		}
+
+		static int GetFieldTypeSize (TypeReference type)
+		{
+			int size = 0;
+
+			switch (type.etype) {
+			case ElementType.Boolean:
+			case ElementType.U1:
+			case ElementType.I1:
+				size = 1;
+				break;
+			case ElementType.U2:
+			case ElementType.I2:
+			case ElementType.Char:
+				size = 2;
+				break;
+			case ElementType.U4:
+			case ElementType.I4:
+			case ElementType.R4:
+				size = 4;
+				break;
+			case ElementType.U8:
+			case ElementType.I8:
+			case ElementType.R8:
+				size = 8;
+				break;
+			case ElementType.Ptr:
+			case ElementType.FnPtr:
+				size = IntPtr.Size;
+				break;
+			case ElementType.CModOpt:
+			case ElementType.CModReqD:
+				return GetFieldTypeSize (((IModifierType) type).ElementType);
+			default:
+				var field_type = type.CheckedResolve ();
+				if (field_type.HasLayoutInfo)
+					size = field_type.ClassSize;
+
+				break;
+			}
+
+			return size;
+		}
+
+		void InitializeFieldRVAs ()
+		{
+			if (metadata.FieldRVAs != null)
+				return;
+
+			int length = MoveTo (Table.FieldRVA);
+
+			var field_rvas = metadata.FieldRVAs = new Dictionary<uint, uint> (length);
+
+			for (int i = 0; i < length; i++) {
+				var rva = ReadUInt32 ();
+				var field = ReadTableIndex (Table.Field);
+
+				field_rvas.Add (field, rva);
+			}
+		}
+
+		public int ReadFieldLayout (FieldDefinition field)
+		{
+			InitializeFieldLayouts ();
+			var rid = field.token.RID;
+			uint offset;
+			if (!metadata.FieldLayouts.TryGetValue (rid, out offset))
+				return Mixin.NoDataMarker;
+
+			metadata.FieldLayouts.Remove (rid);
+
+			return (int) offset;
+		}
+
+		void InitializeFieldLayouts ()
+		{
+			if (metadata.FieldLayouts != null)
+				return;
+
+			int length = MoveTo (Table.FieldLayout);
+
+			var field_layouts = metadata.FieldLayouts = new Dictionary<uint, uint> (length);
+
+			for (int i = 0; i < length; i++) {
+				var offset = ReadUInt32 ();
+				var field = ReadTableIndex (Table.Field);
+
+				field_layouts.Add (field, offset);
+			}
+		}
+
+		public bool HasEvents (TypeDefinition type)
+		{
+			InitializeEvents ();
+
+			Range range;
+			if (!metadata.TryGetEventsRange (type, out range))
+				return false;
+
+			return range.Length > 0;
+		}
+
+		public Collection<EventDefinition> ReadEvents (TypeDefinition type)
+		{
+			InitializeEvents ();
+			Range range;
+
+			if (!metadata.TryGetEventsRange (type, out range))
+				return new MemberDefinitionCollection<EventDefinition> (type);
+
+			var events = new MemberDefinitionCollection<EventDefinition> (type, (int) range.Length);
+
+			metadata.RemoveEventsRange (type);
+
+			if (range.Length == 0)
+				return events;
+
+			this.context = type;
+
+			if (!MoveTo (Table.EventPtr, range.Start)) {
+				if (!MoveTo (Table.Event, range.Start))
+					return events;
+
+				for (uint i = 0; i < range.Length; i++)
+					ReadEvent (range.Start + i, events);
+			} else
+				ReadPointers (Table.EventPtr, Table.Event, range, events, ReadEvent);
+
+			return events;
+		}
+
+		void ReadEvent (uint event_rid, Collection<EventDefinition> events)
+		{
+			var attributes = (EventAttributes) ReadUInt16 ();
+			var name = ReadString ();
+			var event_type = GetTypeDefOrRef (ReadMetadataToken (CodedIndex.TypeDefOrRef));
+
+			var @event = new EventDefinition (name, attributes, event_type);
+			@event.token = new MetadataToken (TokenType.Event, event_rid);
+
+			if (IsDeleted (@event))
+				return;
+
+			events.Add (@event);
+		}
+
+		void InitializeEvents ()
+		{
+			if (metadata.Events != null)
+				return;
+
+			int length = MoveTo (Table.EventMap);
+
+			metadata.Events = new Dictionary<uint, Range> (length);
+
+			for (uint i = 1; i <= length; i++) {
+				var type_rid = ReadTableIndex (Table.TypeDef);
+				Range events_range = ReadEventsRange (i);
+				metadata.AddEventsRange (type_rid, events_range);
+			}
+		}
+
+		Range ReadEventsRange (uint rid)
+		{
+			return ReadListRange (rid, Table.EventMap, Table.Event);
+		}
+
+		public bool HasProperties (TypeDefinition type)
+		{
+			InitializeProperties ();
+
+			Range range;
+			if (!metadata.TryGetPropertiesRange (type, out range))
+				return false;
+
+			return range.Length > 0;
+		}
+
+		public Collection<PropertyDefinition> ReadProperties (TypeDefinition type)
+		{
+			InitializeProperties ();
+
+			Range range;
+
+			if (!metadata.TryGetPropertiesRange (type, out range))
+				return new MemberDefinitionCollection<PropertyDefinition> (type);
+
+			metadata.RemovePropertiesRange (type);
+
+			var properties = new MemberDefinitionCollection<PropertyDefinition> (type, (int) range.Length);
+
+			if (range.Length == 0)
+				return properties;
+
+			this.context = type;
+
+			if (!MoveTo (Table.PropertyPtr, range.Start)) {
+				if (!MoveTo (Table.Property, range.Start))
+					return properties;
+				for (uint i = 0; i < range.Length; i++)
+					ReadProperty (range.Start + i, properties);
+			} else
+				ReadPointers (Table.PropertyPtr, Table.Property, range, properties, ReadProperty);
+
+			return properties;
+		}
+
+		void ReadProperty (uint property_rid, Collection<PropertyDefinition> properties)
+		{
+			var attributes = (PropertyAttributes) ReadUInt16 ();
+			var name = ReadString ();
+			var signature = ReadBlobIndex ();
+
+			var reader = ReadSignature (signature);
+			const byte property_signature = 0x8;
+
+			var calling_convention = reader.ReadByte ();
+
+			if ((calling_convention & property_signature) == 0)
+				throw new NotSupportedException ();
+
+			var has_this = (calling_convention & 0x20) != 0;
+
+			reader.ReadCompressedUInt32 (); // count
+
+			var property = new PropertyDefinition (name, attributes, reader.ReadTypeSignature ());
+			property.HasThis = has_this;
+			property.token = new MetadataToken (TokenType.Property, property_rid);
+
+			if (IsDeleted (property))
+				return;
+
+			properties.Add (property);
+		}
+
+		void InitializeProperties ()
+		{
+			if (metadata.Properties != null)
+				return;
+
+			int length = MoveTo (Table.PropertyMap);
+
+			metadata.Properties = new Dictionary<uint, Range> (length);
+
+			for (uint i = 1; i <= length; i++) {
+				var type_rid = ReadTableIndex (Table.TypeDef);
+				var properties_range = ReadPropertiesRange (i);
+				metadata.AddPropertiesRange (type_rid, properties_range);
+			}
+		}
+
+		Range ReadPropertiesRange (uint rid)
+		{
+			return ReadListRange (rid, Table.PropertyMap, Table.Property);
+		}
+
+		MethodSemanticsAttributes ReadMethodSemantics (MethodDefinition method)
+		{
+			InitializeMethodSemantics ();
+			Row<MethodSemanticsAttributes, MetadataToken> row;
+			if (!metadata.Semantics.TryGetValue (method.token.RID, out row))
+				return MethodSemanticsAttributes.None;
+
+			var type = method.DeclaringType;
+
+			switch (row.Col1) {
+			case MethodSemanticsAttributes.AddOn:
+				GetEvent (type, row.Col2).add_method = method;
+				break;
+			case MethodSemanticsAttributes.Fire:
+				GetEvent (type, row.Col2).invoke_method = method;
+				break;
+			case MethodSemanticsAttributes.RemoveOn:
+				GetEvent (type, row.Col2).remove_method = method;
+				break;
+			case MethodSemanticsAttributes.Getter:
+				GetProperty (type, row.Col2).get_method = method;
+				break;
+			case MethodSemanticsAttributes.Setter:
+				GetProperty (type, row.Col2).set_method = method;
+				break;
+			case MethodSemanticsAttributes.Other:
+				switch (row.Col2.TokenType) {
+				case TokenType.Event: {
+					var @event = GetEvent (type, row.Col2);
+					if (@event.other_methods == null)
+						@event.other_methods = new Collection<MethodDefinition> ();
+
+					@event.other_methods.Add (method);
+					break;
+				}
+				case TokenType.Property: {
+					var property = GetProperty (type, row.Col2);
+					if (property.other_methods == null)
+						property.other_methods = new Collection<MethodDefinition> ();
+
+					property.other_methods.Add (method);
+
+					break;
+				}
+				default:
+					throw new NotSupportedException ();
+				}
+				break;
+			default:
+				throw new NotSupportedException ();
+			}
+
+			metadata.Semantics.Remove (method.token.RID);
+
+			return row.Col1;
+		}
+
+		static EventDefinition GetEvent (TypeDefinition type, MetadataToken token)
+		{
+			if (token.TokenType != TokenType.Event)
+				throw new ArgumentException ();
+
+			return GetMember (type.Events, token);
+		}
+
+		static PropertyDefinition GetProperty (TypeDefinition type, MetadataToken token)
+		{
+			if (token.TokenType != TokenType.Property)
+				throw new ArgumentException ();
+
+			return GetMember (type.Properties, token);
+		}
+
+		static TMember GetMember<TMember> (Collection<TMember> members, MetadataToken token) where TMember : IMemberDefinition
+		{
+			for (int i = 0; i < members.Count; i++) {
+				var member = members [i];
+				if (member.MetadataToken == token)
+					return member;
+			}
+
+			throw new ArgumentException ();
+		}
+
+		void InitializeMethodSemantics ()
+		{
+			if (metadata.Semantics != null)
+				return;
+
+			int length = MoveTo (Table.MethodSemantics);
+
+			var semantics = metadata.Semantics = new Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> (0);
+
+			for (uint i = 0; i < length; i++) {
+				var attributes = (MethodSemanticsAttributes) ReadUInt16 ();
+				var method_rid = ReadTableIndex (Table.Method);
+				var association = ReadMetadataToken (CodedIndex.HasSemantics);
+
+				semantics [method_rid] = new Row<MethodSemanticsAttributes, MetadataToken> (attributes, association);
+			}
+		}
+
+		public PropertyDefinition ReadMethods (PropertyDefinition property)
+		{
+			ReadAllSemantics (property.DeclaringType);
+			return property;
+		}
+
+		public EventDefinition ReadMethods (EventDefinition @event)
+		{
+			ReadAllSemantics (@event.DeclaringType);
+			return @event;
+		}
+
+		public MethodSemanticsAttributes ReadAllSemantics (MethodDefinition method)
+		{
+			ReadAllSemantics (method.DeclaringType);
+
+			return method.SemanticsAttributes;
+		}
+
+		void ReadAllSemantics (TypeDefinition type)
+		{
+			var methods = type.Methods;
+			for (int i = 0; i < methods.Count; i++) {
+				var method = methods [i];
+				if (method.sem_attrs.HasValue)
+					continue;
+
+				method.sem_attrs = ReadMethodSemantics (method);
+			}
+		}
+
+		Range ReadParametersRange (uint method_rid)
+		{
+			return ReadListRange (method_rid, Table.Method, Table.Param);
+		}
+
+		public Collection<MethodDefinition> ReadMethods (TypeDefinition type)
+		{
+			var methods_range = type.methods_range;
+			if (methods_range.Length == 0)
+				return new MemberDefinitionCollection<MethodDefinition> (type);
+
+			var methods = new MemberDefinitionCollection<MethodDefinition> (type, (int) methods_range.Length);
+			if (!MoveTo (Table.MethodPtr, methods_range.Start)) {
+				if (!MoveTo (Table.Method, methods_range.Start))
+					return methods;
+
+				for (uint i = 0; i < methods_range.Length; i++)
+					ReadMethod (methods_range.Start + i, methods);
+			} else
+				ReadPointers (Table.MethodPtr, Table.Method, methods_range, methods, ReadMethod);
+
+			return methods;
+		}
+
+		void ReadPointers<TMember> (Table ptr, Table table, Range range, Collection<TMember> members, Action<uint, Collection<TMember>> reader)
+			where TMember : IMemberDefinition
+		{
+			for (uint i = 0; i < range.Length; i++) {
+				MoveTo (ptr, range.Start + i);
+
+				var rid = ReadTableIndex (table);
+				MoveTo (table, rid);
+
+				reader (rid, members);
+			}
+		}
+
+		static bool IsDeleted (IMemberDefinition member)
+		{
+			return member.IsSpecialName && member.Name == "_Deleted";
+		}
+
+		void InitializeMethods ()
+		{
+			if (metadata.Methods != null)
+				return;
+
+			metadata.Methods = new MethodDefinition [image.GetTableLength (Table.Method)];
+		}
+
+		void ReadMethod (uint method_rid, Collection<MethodDefinition> methods)
+		{
+			var method = new MethodDefinition ();
+			method.rva = ReadUInt32 ();
+			method.ImplAttributes = (MethodImplAttributes) ReadUInt16 ();
+			method.Attributes = (MethodAttributes) ReadUInt16 ();
+			method.Name = ReadString ();
+			method.token = new MetadataToken (TokenType.Method, method_rid);
+
+			if (IsDeleted (method))
+				return;
+
+			methods.Add (method); // attach method
+
+			var signature = ReadBlobIndex ();
+			var param_range = ReadParametersRange (method_rid);
+
+			this.context = method;
+
+			ReadMethodSignature (signature, method);
+			metadata.AddMethodDefinition (method);
+
+			if (param_range.Length == 0)
+				return;
+
+			var position = base.position;
+			ReadParameters (method, param_range);
+			base.position = position;
+		}
+
+		void ReadParameters (MethodDefinition method, Range param_range)
+		{
+			if (!MoveTo (Table.ParamPtr, param_range.Start)) {
+				if (!MoveTo (Table.Param, param_range.Start))
+					return;
+
+				for (uint i = 0; i < param_range.Length; i++)
+					ReadParameter (param_range.Start + i, method);
+			} else
+				ReadParameterPointers (method, param_range);
+		}
+
+		void ReadParameterPointers (MethodDefinition method, Range range)
+		{
+			for (uint i = 0; i < range.Length; i++) {
+				MoveTo (Table.ParamPtr, range.Start + i);
+
+				var rid = ReadTableIndex (Table.Param);
+
+				MoveTo (Table.Param, rid);
+
+				ReadParameter (rid, method);
+			}
+		}
+
+		void ReadParameter (uint param_rid, MethodDefinition method)
+		{
+			var attributes = (ParameterAttributes) ReadUInt16 ();
+			var sequence = ReadUInt16 ();
+			var name = ReadString ();
+
+			var parameter = sequence == 0
+				? method.MethodReturnType.Parameter
+				: method.Parameters [sequence - 1];
+
+			parameter.token = new MetadataToken (TokenType.Param, param_rid);
+			parameter.Name = name;
+			parameter.Attributes = attributes;
+		}
+
+		void ReadMethodSignature (uint signature, IMethodSignature method)
+		{
+			var reader = ReadSignature (signature);
+			reader.ReadMethodSignature (method);
+		}
+
+		public PInvokeInfo ReadPInvokeInfo (MethodDefinition method)
+		{
+			InitializePInvokes ();
+			Row<PInvokeAttributes, uint, uint> row;
+
+			var rid = method.token.RID;
+
+			if (!metadata.PInvokes.TryGetValue (rid, out row))
+				return null;
+
+			metadata.PInvokes.Remove (rid);
+
+			return new PInvokeInfo (
+				row.Col1,
+				image.StringHeap.Read (row.Col2),
+				module.ModuleReferences [(int) row.Col3 - 1]);
+		}
+
+		void InitializePInvokes ()
+		{
+			if (metadata.PInvokes != null)
+				return;
+
+			int length = MoveTo (Table.ImplMap);
+
+			var pinvokes = metadata.PInvokes = new Dictionary<uint, Row<PInvokeAttributes, uint, uint>> (length);
+
+			for (int i = 1; i <= length; i++) {
+				var attributes = (PInvokeAttributes) ReadUInt16 ();
+				var method = ReadMetadataToken (CodedIndex.MemberForwarded);
+				var name = ReadStringIndex ();
+				var scope = ReadTableIndex (Table.File);
+
+				if (method.TokenType != TokenType.Method)
+					continue;
+
+				pinvokes.Add (method.RID, new Row<PInvokeAttributes, uint, uint> (attributes, name, scope));
+			}
+		}
+
+		public bool HasGenericParameters (IGenericParameterProvider provider)
+		{
+			InitializeGenericParameters ();
+
+			Range range;
+			if (!metadata.TryGetGenericParameterRange (provider, out range))
+				return false;
+
+			return range.Length > 0;
+		}
+
+		public Collection<GenericParameter> ReadGenericParameters (IGenericParameterProvider provider)
+		{
+			InitializeGenericParameters ();
+
+			Range range;
+			if (!metadata.TryGetGenericParameterRange (provider, out range)
+				|| !MoveTo (Table.GenericParam, range.Start))
+				return new Collection<GenericParameter> ();
+
+			metadata.RemoveGenericParameterRange (provider);
+
+			var generic_parameters = new Collection<GenericParameter> ((int) range.Length);
+
+			for (uint i = 0; i < range.Length; i++) {
+				ReadUInt16 (); // index
+				var flags = (GenericParameterAttributes) ReadUInt16 ();
+				ReadMetadataToken (CodedIndex.TypeOrMethodDef);
+				var name = ReadString ();
+
+				var parameter = new GenericParameter (name, provider);
+				parameter.token = new MetadataToken (TokenType.GenericParam, range.Start + i);
+				parameter.Attributes = flags;
+
+				generic_parameters.Add (parameter);
+			}
+
+			return generic_parameters;
+		}
+
+		void InitializeGenericParameters ()
+		{
+			if (metadata.GenericParameters != null)
+				return;
+
+			metadata.GenericParameters = InitializeRanges (
+				Table.GenericParam, () => {
+					Advance (4);
+					var next = ReadMetadataToken (CodedIndex.TypeOrMethodDef);
+					ReadStringIndex ();
+					return next;
+			});
+		}
+
+		Dictionary<MetadataToken, Range> InitializeRanges (Table table, Func<MetadataToken> get_next)
+		{
+			int length = MoveTo (table);
+			var ranges = new Dictionary<MetadataToken, Range> (length);
+
+			if (length == 0)
+				return ranges;
+
+			MetadataToken owner = MetadataToken.Zero;
+			Range range = new Range (1, 0);
+
+			for (uint i = 1; i <= length; i++) {
+				var next = get_next ();
+
+				if (i == 1) {
+					owner = next;
+					range.Length++;
+				} else if (next != owner) {
+					if (owner.RID != 0)
+						ranges.Add (owner, range);
+					range = new Range (i, 1);
+					owner = next;
+				} else
+					range.Length++;
+			}
+
+			if (owner != MetadataToken.Zero && !ranges.ContainsKey (owner))
+				ranges.Add (owner, range);
+
+			return ranges;
+		}
+
+		public bool HasGenericConstraints (GenericParameter generic_parameter)
+		{
+			InitializeGenericConstraints ();
+
+			MetadataToken [] mapping;
+			if (!metadata.TryGetGenericConstraintMapping (generic_parameter, out mapping))
+				return false;
+
+			return mapping.Length > 0;
+		}
+
+		public Collection<TypeReference> ReadGenericConstraints (GenericParameter generic_parameter)
+		{
+			InitializeGenericConstraints ();
+
+			MetadataToken [] mapping;
+			if (!metadata.TryGetGenericConstraintMapping (generic_parameter, out mapping))
+				return new Collection<TypeReference> ();
+
+			var constraints = new Collection<TypeReference> (mapping.Length);
+
+			this.context = (IGenericContext) generic_parameter.Owner;
+
+			for (int i = 0; i < mapping.Length; i++)
+				constraints.Add (GetTypeDefOrRef (mapping [i]));
+
+			metadata.RemoveGenericConstraintMapping (generic_parameter);
+
+			return constraints;
+		}
+
+		void InitializeGenericConstraints ()
+		{
+			if (metadata.GenericConstraints != null)
+				return;
+
+			var length = MoveTo (Table.GenericParamConstraint);
+
+			metadata.GenericConstraints = new Dictionary<uint, MetadataToken []> (length);
+
+			for (int i = 1; i <= length; i++)
+				AddGenericConstraintMapping (
+					ReadTableIndex (Table.GenericParam),
+					ReadMetadataToken (CodedIndex.TypeDefOrRef));
+		}
+
+		void AddGenericConstraintMapping (uint generic_parameter, MetadataToken constraint)
+		{
+			metadata.SetGenericConstraintMapping (
+				generic_parameter,
+				AddMapping (metadata.GenericConstraints, generic_parameter, constraint));
+		}
+
+		public bool HasOverrides (MethodDefinition method)
+		{
+			InitializeOverrides ();
+			MetadataToken [] mapping;
+
+			if (!metadata.TryGetOverrideMapping (method, out mapping))
+				return false;
+
+			return mapping.Length > 0;
+		}
+
+		public Collection<MethodReference> ReadOverrides (MethodDefinition method)
+		{
+			InitializeOverrides ();
+
+			MetadataToken [] mapping;
+			if (!metadata.TryGetOverrideMapping (method, out mapping))
+				return new Collection<MethodReference> ();
+
+			var overrides = new Collection<MethodReference> (mapping.Length);
+
+			this.context = method;
+
+			for (int i = 0; i < mapping.Length; i++)
+				overrides.Add ((MethodReference) LookupToken (mapping [i]));
+
+			metadata.RemoveOverrideMapping (method);
+
+			return overrides;
+		}
+
+		void InitializeOverrides ()
+		{
+			if (metadata.Overrides != null)
+				return;
+
+			var length = MoveTo (Table.MethodImpl);
+
+			metadata.Overrides = new Dictionary<uint, MetadataToken []> (length);
+
+			for (int i = 1; i <= length; i++) {
+				ReadTableIndex (Table.TypeDef);
+
+				var method = ReadMetadataToken (CodedIndex.MethodDefOrRef);
+				if (method.TokenType != TokenType.Method)
+					throw new NotSupportedException ();
+
+				var @override = ReadMetadataToken (CodedIndex.MethodDefOrRef);
+
+				AddOverrideMapping (method.RID, @override);
+			}
+		}
+
+		void AddOverrideMapping (uint method_rid, MetadataToken @override)
+		{
+			metadata.SetOverrideMapping (
+				method_rid,
+				AddMapping (metadata.Overrides, method_rid, @override));
+		}
+
+		public MethodBody ReadMethodBody (MethodDefinition method)
+		{
+			return code.ReadMethodBody (method);
+		}
+
+		public CallSite ReadCallSite (MetadataToken token)
+		{
+			if (!MoveTo (Table.StandAloneSig, token.RID))
+				return null;
+
+			var signature = ReadBlobIndex ();
+
+			var call_site = new CallSite ();
+
+			ReadMethodSignature (signature, call_site);
+
+			call_site.MetadataToken = token;
+
+			return call_site;
+		}
+
+		public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token)
+		{
+			if (!MoveTo (Table.StandAloneSig, local_var_token.RID))
+				return null;
+
+			var reader = ReadSignature (ReadBlobIndex ());
+			const byte local_sig = 0x7;
+
+			if (reader.ReadByte () != local_sig)
+				throw new NotSupportedException ();
+
+			var count = reader.ReadCompressedUInt32 ();
+			if (count == 0)
+				return null;
+
+			var variables = new VariableDefinitionCollection ((int) count);
+
+			for (int i = 0; i < count; i++)
+				variables.Add (new VariableDefinition (reader.ReadTypeSignature ()));
+
+			return variables;
+		}
+
+		public IMetadataTokenProvider LookupToken (MetadataToken token)
+		{
+			var rid = token.RID;
+
+			if (rid == 0)
+				return null;
+
+			IMetadataTokenProvider element;
+			var position = this.position;
+			var context = this.context;
+
+			switch (token.TokenType) {
+			case TokenType.TypeDef:
+				element = GetTypeDefinition (rid);
+				break;
+			case TokenType.TypeRef:
+				element = GetTypeReference (rid);
+				break;
+			case TokenType.TypeSpec:
+				element = GetTypeSpecification (rid);
+				break;
+			case TokenType.Field:
+				element = GetFieldDefinition (rid);
+				break;
+			case TokenType.Method:
+				element = GetMethodDefinition (rid);
+				break;
+			case TokenType.MemberRef:
+				element = GetMemberReference (rid);
+				break;
+			case TokenType.MethodSpec:
+				element = GetMethodSpecification (rid);
+				break;
+			default:
+				return null;
+			}
+
+			this.position = position;
+			this.context = context;
+
+			return element;
+		}
+
+		public FieldDefinition GetFieldDefinition (uint rid)
+		{
+			InitializeTypeDefinitions ();
+
+			var field = metadata.GetFieldDefinition (rid);
+			if (field != null)
+				return field;
+
+			return LookupField (rid);
+		}
+
+		FieldDefinition LookupField (uint rid)
+		{
+			var type = metadata.GetFieldDeclaringType (rid);
+			if (type == null)
+				return null;
+
+			InitializeCollection (type.Fields);
+
+			return metadata.GetFieldDefinition (rid);
+		}
+
+		public MethodDefinition GetMethodDefinition (uint rid)
+		{
+			InitializeTypeDefinitions ();
+
+			var method = metadata.GetMethodDefinition (rid);
+			if (method != null)
+				return method;
+
+			return LookupMethod (rid);
+		}
+
+		MethodDefinition LookupMethod (uint rid)
+		{
+			var type = metadata.GetMethodDeclaringType (rid);
+			if (type == null)
+				return null;
+
+			InitializeCollection (type.Methods);
+
+			return metadata.GetMethodDefinition (rid);
+		}
+
+		MethodSpecification GetMethodSpecification (uint rid)
+		{
+			if (!MoveTo (Table.MethodSpec, rid))
+				return null;
+
+			var element_method = (MethodReference) LookupToken (
+				ReadMetadataToken (CodedIndex.MethodDefOrRef));
+			var signature = ReadBlobIndex ();
+
+			var method_spec = ReadMethodSpecSignature (signature, element_method);
+			method_spec.token = new MetadataToken (TokenType.MethodSpec, rid);
+			return method_spec;
+		}
+
+		MethodSpecification ReadMethodSpecSignature (uint signature, MethodReference method)
+		{
+			var reader = ReadSignature (signature);
+			const byte methodspec_sig = 0x0a;
+
+			var call_conv = reader.ReadByte ();
+
+			if (call_conv != methodspec_sig)
+				throw new NotSupportedException ();
+
+			var instance = new GenericInstanceMethod (method);
+
+			reader.ReadGenericInstanceSignature (method, instance);
+
+			return instance;
+		}
+
+		MemberReference GetMemberReference (uint rid)
+		{
+			InitializeMemberReferences ();
+
+			var member = metadata.GetMemberReference (rid);
+			if (member != null)
+				return member;
+
+			member = ReadMemberReference (rid);
+			if (member != null && !member.ContainsGenericParameter)
+				metadata.AddMemberReference (member);
+			return member;
+		}
+
+		MemberReference ReadMemberReference (uint rid)
+		{
+			if (!MoveTo (Table.MemberRef, rid))
+				return null;
+
+			var token = ReadMetadataToken (CodedIndex.MemberRefParent);
+			var name = ReadString ();
+			var signature = ReadBlobIndex ();
+
+			MemberReference member;
+
+			switch (token.TokenType) {
+			case TokenType.TypeDef:
+			case TokenType.TypeRef:
+			case TokenType.TypeSpec:
+				member = ReadTypeMemberReference (token, name, signature);
+				break;
+			case TokenType.Method:
+				member = ReadMethodMemberReference (token, name, signature);
+				break;
+			default:
+				throw new NotSupportedException ();
+			}
+
+			member.token = new MetadataToken (TokenType.MemberRef, rid);
+
+			return member;
+		}
+
+		MemberReference ReadTypeMemberReference (MetadataToken type, string name, uint signature)
+		{
+			var declaring_type = GetTypeDefOrRef (type);
+
+			this.context = declaring_type;
+
+			var member = ReadMemberReferenceSignature (signature, declaring_type);
+			member.Name = name;
+
+			return member;
+		}
+
+		MemberReference ReadMemberReferenceSignature (uint signature, TypeReference declaring_type)
+		{
+			var reader = ReadSignature (signature);
+			const byte field_sig = 0x6;
+
+			if (reader.buffer [reader.position] == field_sig) {
+				reader.position++;
+				var field = new FieldReference ();
+				field.DeclaringType = declaring_type;
+				field.FieldType = reader.ReadTypeSignature ();
+				return field;
+			} else {
+				var method = new MethodReference ();
+				method.DeclaringType = declaring_type;
+				reader.ReadMethodSignature (method);
+				return method;
+			}
+		}
+
+		MemberReference ReadMethodMemberReference (MetadataToken token, string name, uint signature)
+		{
+			var method = GetMethodDefinition (token.RID);
+
+			this.context = method;
+
+			var member = ReadMemberReferenceSignature (signature, method.DeclaringType);
+			member.Name = name;
+
+			return member;
+		}
+
+		void InitializeMemberReferences ()
+		{
+			if (metadata.MemberReferences != null)
+				return;
+
+			metadata.MemberReferences = new MemberReference [image.GetTableLength (Table.MemberRef)];
+		}
+
+		public IEnumerable<MemberReference> GetMemberReferences ()
+		{
+			InitializeMemberReferences ();
+
+			var length = image.GetTableLength (Table.MemberRef);
+
+			var type_system = module.TypeSystem;
+
+			var context = new MethodReference (string.Empty, type_system.Void);
+			context.DeclaringType = new TypeReference (string.Empty, string.Empty, module, type_system.Corlib);
+
+			var member_references = new MemberReference [length];
+
+			for (uint i = 1; i <= length; i++) {
+				this.context = context;
+				member_references [i - 1] = GetMemberReference (i);
+			}
+
+			return member_references;
+		}
+
+		void InitializeConstants ()
+		{
+			if (metadata.Constants != null)
+				return;
+
+			var length = MoveTo (Table.Constant);
+
+			var constants = metadata.Constants = new Dictionary<MetadataToken, Row<ElementType, uint>> (length);
+
+			for (uint i = 1; i <= length; i++) {
+				var type = (ElementType) ReadUInt16 ();
+				var owner = ReadMetadataToken (CodedIndex.HasConstant);
+				var signature = ReadBlobIndex ();
+
+				constants.Add (owner, new Row<ElementType, uint> (type, signature));
+			}
+		}
+
+		public object ReadConstant (IConstantProvider owner)
+		{
+			InitializeConstants ();
+
+			Row<ElementType, uint> row;
+			if (!metadata.Constants.TryGetValue (owner.MetadataToken, out row))
+				return Mixin.NoValue;
+
+			metadata.Constants.Remove (owner.MetadataToken);
+
+			switch (row.Col1) {
+			case ElementType.Class:
+			case ElementType.Object:
+				return null;
+			case ElementType.String:
+				return ReadConstantString (ReadBlob (row.Col2));
+			default:
+				return ReadConstantPrimitive (row.Col1, row.Col2);
+			}
+		}
+
+		static string ReadConstantString (byte [] blob)
+		{
+			var length = blob.Length;
+			if ((length & 1) == 1)
+				length--;
+
+			return Encoding.Unicode.GetString (blob, 0, length);
+		}
+
+		object ReadConstantPrimitive (ElementType type, uint signature)
+		{
+			var reader = ReadSignature (signature);
+			return reader.ReadConstantSignature (type);
+		}
+
+		void InitializeCustomAttributes ()
+		{
+			if (metadata.CustomAttributes != null)
+				return;
+
+			metadata.CustomAttributes = InitializeRanges (
+				Table.CustomAttribute, () => {
+					var next = ReadMetadataToken (CodedIndex.HasCustomAttribute);
+					ReadMetadataToken (CodedIndex.CustomAttributeType);
+					ReadBlobIndex ();
+					return next;
+			});
+		}
+
+		public bool HasCustomAttributes (ICustomAttributeProvider owner)
+		{
+			InitializeCustomAttributes ();
+
+			Range range;
+			if (!metadata.TryGetCustomAttributeRange (owner, out range))
+				return false;
+
+			return range.Length > 0;
+		}
+
+		public Collection<CustomAttribute> ReadCustomAttributes (ICustomAttributeProvider owner)
+		{
+			InitializeCustomAttributes ();
+
+			Range range;
+			if (!metadata.TryGetCustomAttributeRange (owner, out range)
+				|| !MoveTo (Table.CustomAttribute, range.Start))
+				return new Collection<CustomAttribute> ();
+
+			var custom_attributes = new Collection<CustomAttribute> ((int) range.Length);
+
+			for (int i = 0; i < range.Length; i++) {
+				ReadMetadataToken (CodedIndex.HasCustomAttribute);
+
+				var constructor = (MethodReference) LookupToken (
+					ReadMetadataToken (CodedIndex.CustomAttributeType));
+
+				var signature = ReadBlobIndex ();
+
+				custom_attributes.Add (new CustomAttribute (signature, constructor));
+			}
+
+			metadata.RemoveCustomAttributeRange (owner);
+
+			return custom_attributes;
+		}
+
+		public byte [] ReadCustomAttributeBlob (uint signature)
+		{
+			return ReadBlob (signature);
+		}
+
+		public void ReadCustomAttributeSignature (CustomAttribute attribute)
+		{
+			var reader = ReadSignature (attribute.signature);
+			if (reader.ReadUInt16 () != 0x0001)
+			    throw new InvalidOperationException ();
+
+			var constructor = attribute.Constructor;
+			if (constructor.HasParameters)
+				reader.ReadCustomAttributeConstructorArguments (attribute, constructor.Parameters);
+
+			if (!reader.CanReadMore ())
+				return;
+
+			var named = reader.ReadUInt16 ();
+
+			if (named == 0)
+				return;
+
+			reader.ReadCustomAttributeNamedArguments (named, ref attribute.fields, ref attribute.properties);
+		}
+
+		void InitializeMarshalInfos ()
+		{
+			if (metadata.FieldMarshals != null)
+				return;
+
+			var length = MoveTo (Table.FieldMarshal);
+
+			var marshals = metadata.FieldMarshals = new Dictionary<MetadataToken, uint> (length);
+
+			for (int i = 0; i < length; i++) {
+				var token = ReadMetadataToken (CodedIndex.HasFieldMarshal);
+				var signature = ReadBlobIndex ();
+				if (token.RID == 0)
+					continue;
+
+				marshals.Add (token, signature);
+			}
+		}
+
+		public bool HasMarshalInfo (IMarshalInfoProvider owner)
+		{
+			InitializeMarshalInfos ();
+
+			return metadata.FieldMarshals.ContainsKey (owner.MetadataToken);
+		}
+
+		public MarshalInfo ReadMarshalInfo (IMarshalInfoProvider owner)
+		{
+			InitializeMarshalInfos ();
+
+			uint signature;
+			if (!metadata.FieldMarshals.TryGetValue (owner.MetadataToken, out signature))
+				return null;
+
+			var reader = ReadSignature (signature);
+
+			metadata.FieldMarshals.Remove (owner.MetadataToken);
+
+			return reader.ReadMarshalInfo ();
+		}
+
+		void InitializeSecurityDeclarations ()
+		{
+			if (metadata.SecurityDeclarations != null)
+				return;
+
+			metadata.SecurityDeclarations = InitializeRanges (
+				Table.DeclSecurity, () => {
+					ReadUInt16 ();
+					var next = ReadMetadataToken (CodedIndex.HasDeclSecurity);
+					ReadBlobIndex ();
+					return next;
+			});
+		}
+
+		public bool HasSecurityDeclarations (ISecurityDeclarationProvider owner)
+		{
+			InitializeSecurityDeclarations ();
+
+			Range range;
+			if (!metadata.TryGetSecurityDeclarationRange (owner, out range))
+				return false;
+
+			return range.Length > 0;
+		}
+
+		public Collection<SecurityDeclaration> ReadSecurityDeclarations (ISecurityDeclarationProvider owner)
+		{
+			InitializeSecurityDeclarations ();
+
+			Range range;
+			if (!metadata.TryGetSecurityDeclarationRange (owner, out range)
+				|| !MoveTo (Table.DeclSecurity, range.Start))
+				return new Collection<SecurityDeclaration> ();
+
+			var security_declarations = new Collection<SecurityDeclaration> ((int) range.Length);
+
+			for (int i = 0; i < range.Length; i++) {
+				var action = (SecurityAction) ReadUInt16 ();
+				ReadMetadataToken (CodedIndex.HasDeclSecurity);
+				var signature = ReadBlobIndex ();
+
+				security_declarations.Add (new SecurityDeclaration (action, signature, module));
+			}
+
+			metadata.RemoveSecurityDeclarationRange (owner);
+
+			return security_declarations;
+		}
+
+		public byte [] ReadSecurityDeclarationBlob (uint signature)
+		{
+			return ReadBlob (signature);
+		}
+
+		public void ReadSecurityDeclarationSignature (SecurityDeclaration declaration)
+		{
+			var signature = declaration.signature;
+			var reader = ReadSignature (signature);
+
+			if (reader.buffer [reader.position] != '.') {
+				ReadXmlSecurityDeclaration (signature, declaration);
+				return;
+			}
+
+			reader.position++;
+			var count = reader.ReadCompressedUInt32 ();
+			var attributes = new Collection<SecurityAttribute> ((int) count);
+
+			for (int i = 0; i < count; i++)
+				attributes.Add (reader.ReadSecurityAttribute ());
+
+			declaration.security_attributes = attributes;
+		}
+
+		void ReadXmlSecurityDeclaration (uint signature, SecurityDeclaration declaration)
+		{
+			var blob = ReadBlob (signature);
+			var attributes = new Collection<SecurityAttribute> (1);
+
+			var attribute = new SecurityAttribute (
+				module.TypeSystem.LookupType ("System.Security.Permissions", "PermissionSetAttribute"));
+
+			attribute.properties = new Collection<CustomAttributeNamedArgument> (1);
+			attribute.properties.Add (
+				new CustomAttributeNamedArgument (
+					"XML",
+					new CustomAttributeArgument (
+						module.TypeSystem.String,
+						Encoding.Unicode.GetString (blob, 0, blob.Length))));
+
+			attributes.Add (attribute);
+
+			declaration.security_attributes = attributes;
+		}
+
+		public Collection<ExportedType> ReadExportedTypes ()
+		{
+			var length = MoveTo (Table.ExportedType);
+			if (length == 0)
+				return new Collection<ExportedType> ();
+
+			var exported_types = new Collection<ExportedType> (length);
+
+			for (int i = 1; i <= length; i++) {
+				var attributes = (TypeAttributes) ReadUInt32 ();
+				var identifier = ReadUInt32 ();
+				var name = ReadString ();
+				var @namespace = ReadString ();
+				var implementation = ReadMetadataToken (CodedIndex.Implementation);
+
+				ExportedType declaring_type = null;
+				IMetadataScope scope = null;
+
+				switch (implementation.TokenType) {
+				case TokenType.AssemblyRef:
+				case TokenType.File:
+					scope = GetExportedTypeScope (implementation);
+					break;
+				case TokenType.ExportedType:
+					// FIXME: if the table is not properly sorted
+					declaring_type = exported_types [(int) implementation.RID - 1];
+					break;
+				}
+
+				var exported_type = new ExportedType (@namespace, name, module, scope) {
+					Attributes = attributes,
+					Identifier = (int) identifier,
+					DeclaringType = declaring_type,
+				};
+				exported_type.token = new MetadataToken (TokenType.ExportedType, i);
+
+				exported_types.Add (exported_type);
+			}
+
+			return exported_types;
+		}
+
+		IMetadataScope GetExportedTypeScope (MetadataToken token)
+		{
+			var position = this.position;
+			IMetadataScope scope;
+
+			switch (token.TokenType) {
+			case TokenType.AssemblyRef:
+				InitializeAssemblyReferences ();
+				scope = metadata.AssemblyReferences [(int) token.RID - 1];
+				break;
+			case TokenType.File:
+				InitializeModuleReferences ();
+				scope = GetModuleReferenceFromFile (token);
+				break;
+			default:
+				throw new NotSupportedException ();
+			}
+
+			this.position = position;
+			return scope;
+		}
+
+		ModuleReference GetModuleReferenceFromFile (MetadataToken token)
+		{
+			if (!MoveTo (Table.File, token.RID))
+				return null;
+
+			ReadUInt32 ();
+			var file_name = ReadString ();
+			var modules = module.ModuleReferences;
+
+			ModuleReference reference;
+			for (int i = 0; i < modules.Count; i++) {
+				reference = modules [i];
+				if (reference.Name == file_name)
+					return reference;
+			}
+
+			reference = new ModuleReference (file_name);
+			modules.Add (reference);
+			return reference;
+		}
+
+		static void InitializeCollection (object o)
+		{
+		}
+	}
+
+	sealed class SignatureReader : ByteBuffer {
+
+		readonly MetadataReader reader;
+		readonly uint start, sig_length;
+
+		TypeSystem TypeSystem {
+			get { return reader.module.TypeSystem; }
+		}
+
+		public SignatureReader (uint blob, MetadataReader reader)
+			: base (reader.buffer)
+		{
+			this.reader = reader;
+
+			MoveToBlob (blob);
+
+			this.sig_length = ReadCompressedUInt32 ();
+			this.start = (uint) position;
+		}
+
+		void MoveToBlob (uint blob)
+		{
+			position = (int) (reader.image.BlobHeap.Offset + blob);
+		}
+
+		MetadataToken ReadTypeTokenSignature ()
+		{
+			return CodedIndex.TypeDefOrRef.GetMetadataToken (ReadCompressedUInt32 ());
+		}
+
+		GenericParameter GetGenericParameter (GenericParameterType type, uint var)
+		{
+			var context = reader.context;
+
+			if (context == null)
+				throw new NotSupportedException ();
+
+			IGenericParameterProvider provider;
+
+			switch (type) {
+			case GenericParameterType.Type:
+				provider = context.Type;
+				break;
+			case GenericParameterType.Method:
+				provider = context.Method;
+				break;
+			default:
+				throw new NotSupportedException ();
+			}
+
+			int index = (int) var;
+
+			if (!context.IsDefinition)
+				CheckGenericContext (provider, index);
+
+			return provider.GenericParameters [index];
+		}
+
+		static void CheckGenericContext (IGenericParameterProvider owner, int index)
+		{
+			var owner_parameters = owner.GenericParameters;
+
+			for (int i = owner_parameters.Count; i <= index; i++)
+				owner_parameters.Add (new GenericParameter (owner));
+		}
+
+		public void ReadGenericInstanceSignature (IGenericParameterProvider provider, IGenericInstance instance)
+		{
+			var arity = ReadCompressedUInt32 ();
+
+			if (!provider.IsDefinition)
+				CheckGenericContext (provider, (int) arity - 1);
+
+			var instance_arguments = instance.GenericArguments;
+
+			for (int i = 0; i < arity; i++)
+				instance_arguments.Add (ReadTypeSignature ());
+		}
+
+		ArrayType ReadArrayTypeSignature ()
+		{
+			var array = new ArrayType (ReadTypeSignature ());
+
+			var rank = ReadCompressedUInt32 ();
+
+			var sizes = new uint [ReadCompressedUInt32 ()];
+			for (int i = 0; i < sizes.Length; i++)
+				sizes [i] = ReadCompressedUInt32 ();
+
+			var low_bounds = new int [ReadCompressedUInt32 ()];
+			for (int i = 0; i < low_bounds.Length; i++)
+				low_bounds [i] = ReadCompressedInt32 ();
+
+			array.Dimensions.Clear ();
+
+			for (int i = 0; i < rank; i++) {
+				int? lower = null, upper = null;
+
+				if (i < low_bounds.Length)
+					lower = low_bounds [i];
+
+				if (i < sizes.Length)
+					upper = lower + (int) sizes [i] - 1;
+
+				array.Dimensions.Add (new ArrayDimension (lower, upper));
+			}
+
+			return array;
+		}
+
+		TypeReference GetTypeDefOrRef (MetadataToken token)
+		{
+			return reader.GetTypeDefOrRef (token);
+		}
+
+		public TypeReference ReadTypeSignature ()
+		{
+			return ReadTypeSignature ((ElementType) ReadByte ());
+		}
+
+		TypeReference ReadTypeSignature (ElementType etype)
+		{
+			switch (etype) {
+			case ElementType.ValueType: {
+				var value_type = GetTypeDefOrRef (ReadTypeTokenSignature ());
+				value_type.IsValueType = true;
+				return value_type;
+			}
+			case ElementType.Class:
+				return GetTypeDefOrRef (ReadTypeTokenSignature ());
+			case ElementType.Ptr:
+				return new PointerType (ReadTypeSignature ());
+			case ElementType.FnPtr: {
+				var fptr = new FunctionPointerType ();
+				ReadMethodSignature (fptr);
+				return fptr;
+			}
+			case ElementType.ByRef:
+				return new ByReferenceType (ReadTypeSignature ());
+			case ElementType.Pinned:
+				return new PinnedType (ReadTypeSignature ());
+			case ElementType.SzArray:
+				return new ArrayType (ReadTypeSignature ());
+			case ElementType.Array:
+				return ReadArrayTypeSignature ();
+			case ElementType.CModOpt:
+				return new OptionalModifierType (
+					GetTypeDefOrRef (ReadTypeTokenSignature ()), ReadTypeSignature ());
+			case ElementType.CModReqD:
+				return new RequiredModifierType (
+					GetTypeDefOrRef (ReadTypeTokenSignature ()), ReadTypeSignature ());
+			case ElementType.Sentinel:
+				return new SentinelType (ReadTypeSignature ());
+			case ElementType.Var:
+				return GetGenericParameter (GenericParameterType.Type, ReadCompressedUInt32 ());
+			case ElementType.MVar:
+				return GetGenericParameter (GenericParameterType.Method, ReadCompressedUInt32 ());
+			case ElementType.GenericInst: {
+				var is_value_type = ReadByte () == (byte) ElementType.ValueType;
+				var element_type = GetTypeDefOrRef (ReadTypeTokenSignature ());
+				var generic_instance = new GenericInstanceType (element_type);
+
+				ReadGenericInstanceSignature (element_type, generic_instance);
+
+				if (is_value_type) {
+					generic_instance.IsValueType = true;
+					element_type.GetElementType ().IsValueType = true;
+				}
+
+				return generic_instance;
+			}
+			case ElementType.Object: return TypeSystem.Object;
+			case ElementType.Void: return TypeSystem.Void;
+			case ElementType.TypedByRef: return TypeSystem.TypedReference;
+			case ElementType.I: return TypeSystem.IntPtr;
+			case ElementType.U: return TypeSystem.UIntPtr;
+			default: return GetPrimitiveType (etype);
+			}
+		}
+
+		public void ReadMethodSignature (IMethodSignature method)
+		{
+			var calling_convention = ReadByte ();
+
+			const byte has_this = 0x20;
+			const byte explicit_this = 0x40;
+
+			if ((calling_convention & has_this) != 0) {
+				method.HasThis = true;
+				calling_convention = (byte) (calling_convention & ~has_this);
+			}
+
+			if ((calling_convention & explicit_this) != 0) {
+				method.ExplicitThis = true;
+				calling_convention = (byte) (calling_convention & ~explicit_this);
+			}
+
+			method.CallingConvention = (MethodCallingConvention) calling_convention;
+
+			var generic_context = method as MethodReference;
+			if (generic_context != null)
+				reader.context = generic_context;
+
+			if ((calling_convention & 0x10) != 0) {
+				var arity = ReadCompressedUInt32 ();
+
+				if (generic_context != null && !generic_context.IsDefinition)
+					CheckGenericContext (generic_context, (int) arity -1 );
+			}
+
+			var param_count = ReadCompressedUInt32 ();
+
+			method.MethodReturnType.ReturnType = ReadTypeSignature ();
+
+			if (param_count == 0)
+				return;
+
+			Collection<ParameterDefinition> parameters;
+
+			var method_ref = method as MethodReference;
+			if (method_ref != null)
+				parameters = method_ref.parameters = new ParameterDefinitionCollection (method, (int) param_count);
+			else
+				parameters = method.Parameters;
+
+			for (int i = 0; i < param_count; i++)
+				parameters.Add (new ParameterDefinition (ReadTypeSignature ()));
+		}
+
+		public object ReadConstantSignature (ElementType type)
+		{
+			return ReadPrimitiveValue (type);
+		}
+
+		public void ReadCustomAttributeConstructorArguments (CustomAttribute attribute, Collection<ParameterDefinition> parameters)
+		{
+			var count = parameters.Count;
+			if (count == 0)
+				return;
+
+			attribute.arguments = new Collection<CustomAttributeArgument> (count);
+
+			for (int i = 0; i < count; i++)
+				attribute.arguments.Add (
+					ReadCustomAttributeFixedArgument (parameters [i].ParameterType));
+		}
+
+		CustomAttributeArgument ReadCustomAttributeFixedArgument (TypeReference type)
+		{
+			if (type.IsArray)
+				return ReadCustomAttributeFixedArrayArgument ((ArrayType) type);
+
+			return ReadCustomAttributeElement (type);
+		}
+
+		public void ReadCustomAttributeNamedArguments (ushort count, ref Collection<CustomAttributeNamedArgument> fields, ref Collection<CustomAttributeNamedArgument> properties)
+		{
+			for (int i = 0; i < count; i++)
+				ReadCustomAttributeNamedArgument (ref fields, ref properties);
+		}
+
+		void ReadCustomAttributeNamedArgument (ref Collection<CustomAttributeNamedArgument> fields, ref Collection<CustomAttributeNamedArgument> properties)
+		{
+			var kind = ReadByte ();
+			var type = ReadCustomAttributeFieldOrPropType ();
+			var name = ReadUTF8String ();
+
+			Collection<CustomAttributeNamedArgument> container;
+			switch (kind) {
+			case 0x53:
+				container = GetCustomAttributeNamedArgumentCollection (ref fields);
+				break;
+			case 0x54:
+				container = GetCustomAttributeNamedArgumentCollection (ref properties);
+				break;
+			default:
+				throw new NotSupportedException ();
+			}
+
+			container.Add (new CustomAttributeNamedArgument (name, ReadCustomAttributeFixedArgument (type)));
+		}
+
+		static Collection<CustomAttributeNamedArgument> GetCustomAttributeNamedArgumentCollection (ref Collection<CustomAttributeNamedArgument> collection)
+		{
+			if (collection != null)
+				return collection;
+
+			return collection = new Collection<CustomAttributeNamedArgument> ();
+		}
+
+		CustomAttributeArgument ReadCustomAttributeFixedArrayArgument (ArrayType type)
+		{
+			var length = ReadUInt32 ();
+
+			if (length == 0xffffffff)
+				return new CustomAttributeArgument (type, null);
+
+			if (length == 0)
+				return new CustomAttributeArgument (type, Empty<CustomAttributeArgument>.Array);
+
+			var arguments = new CustomAttributeArgument [length];
+			var element_type = type.ElementType;
+
+			for (int i = 0; i < length; i++)
+				arguments [i] = ReadCustomAttributeElement (element_type);
+
+			return new CustomAttributeArgument (type, arguments);
+		}
+
+		CustomAttributeArgument ReadCustomAttributeElement (TypeReference type)
+		{
+			if (type.IsArray)
+				return ReadCustomAttributeFixedArrayArgument ((ArrayType) type);
+
+			return new CustomAttributeArgument (
+				type,
+				type.etype == ElementType.Object
+					? ReadCustomAttributeElement (ReadCustomAttributeFieldOrPropType ())
+					: ReadCustomAttributeElementValue (type));
+		}
+
+		object ReadCustomAttributeElementValue (TypeReference type)
+		{
+			var etype = type.etype;
+
+			switch (etype) {
+			case ElementType.String:
+				return ReadUTF8String ();
+			case ElementType.None:
+				if (type.IsTypeOf ("System", "Type"))
+					return ReadTypeReference ();
+
+				return ReadCustomAttributeEnum (type);
+			default:
+				return ReadPrimitiveValue (etype);
+			}
+		}
+
+		object ReadPrimitiveValue (ElementType type)
+		{
+			switch (type) {
+			case ElementType.Boolean:
+				return ReadByte () == 1;
+			case ElementType.I1:
+				return (sbyte) ReadByte ();
+			case ElementType.U1:
+				return ReadByte ();
+			case ElementType.Char:
+				return (char) ReadUInt16 ();
+			case ElementType.I2:
+				return ReadInt16 ();
+			case ElementType.U2:
+				return ReadUInt16 ();
+			case ElementType.I4:
+				return ReadInt32 ();
+			case ElementType.U4:
+				return ReadUInt32 ();
+			case ElementType.I8:
+				return ReadInt64 ();
+			case ElementType.U8:
+				return ReadUInt64 ();
+			case ElementType.R4:
+				return ReadSingle ();
+			case ElementType.R8:
+				return ReadDouble ();
+			default:
+				throw new NotImplementedException (type.ToString ());
+			}
+		}
+
+		TypeReference GetPrimitiveType (ElementType etype)
+		{
+			switch (etype) {
+			case ElementType.Boolean:
+				return TypeSystem.Boolean;
+			case ElementType.Char:
+				return TypeSystem.Char;
+			case ElementType.I1:
+				return TypeSystem.SByte;
+			case ElementType.U1:
+				return TypeSystem.Byte;
+			case ElementType.I2:
+				return TypeSystem.Int16;
+			case ElementType.U2:
+				return TypeSystem.UInt16;
+			case ElementType.I4:
+				return TypeSystem.Int32;
+			case ElementType.U4:
+				return TypeSystem.UInt32;
+			case ElementType.I8:
+				return TypeSystem.Int64;
+			case ElementType.U8:
+				return TypeSystem.UInt64;
+			case ElementType.R4:
+				return TypeSystem.Single;
+			case ElementType.R8:
+				return TypeSystem.Double;
+			case ElementType.String:
+				return TypeSystem.String;
+			default:
+				throw new NotImplementedException (etype.ToString ());
+			}
+		}
+
+		TypeReference ReadCustomAttributeFieldOrPropType ()
+		{
+			var etype = (ElementType) ReadByte ();
+
+			switch (etype) {
+			case ElementType.Boxed:
+				return TypeSystem.Object;
+			case ElementType.SzArray:
+				return new ArrayType (ReadCustomAttributeFieldOrPropType ());
+			case ElementType.Enum:
+				return ReadTypeReference ();
+			case ElementType.Type:
+				return TypeSystem.LookupType ("System", "Type");
+			default:
+				return GetPrimitiveType (etype);
+			}
+		}
+
+		public TypeReference ReadTypeReference ()
+		{
+			return TypeParser.ParseType (reader.module, ReadUTF8String ());
+		}
+
+		object ReadCustomAttributeEnum (TypeReference enum_type)
+		{
+			var type = enum_type.CheckedResolve ();
+			if (!type.IsEnum)
+				throw new ArgumentException ();
+
+			return ReadCustomAttributeElementValue (type.GetEnumUnderlyingType ());
+		}
+
+		public SecurityAttribute ReadSecurityAttribute ()
+		{
+			var attribute = new SecurityAttribute (ReadTypeReference ());
+
+			ReadCompressedUInt32 ();
+
+			ReadCustomAttributeNamedArguments (
+				(ushort) ReadCompressedUInt32 (),
+				ref attribute.fields,
+				ref attribute.properties);
+
+			return attribute;
+		}
+
+		public MarshalInfo ReadMarshalInfo ()
+		{
+			var native = ReadNativeType ();
+			switch (native) {
+			case NativeType.Array: {
+				var array = new ArrayMarshalInfo ();
+				if (CanReadMore ())
+					array.element_type = ReadNativeType ();
+				if (CanReadMore ())
+					array.size_parameter_index = (int) ReadCompressedUInt32 ();
+				if (CanReadMore ())
+					array.size = (int) ReadCompressedUInt32 ();
+				if (CanReadMore ())
+					array.size_parameter_multiplier = (int) ReadCompressedUInt32 ();
+				return array;
+			}
+			case NativeType.SafeArray: {
+				var array = new SafeArrayMarshalInfo ();
+				if (CanReadMore ())
+					array.element_type = ReadVariantType ();
+				return array;
+			}
+			case NativeType.FixedArray: {
+				var array = new FixedArrayMarshalInfo ();
+				if (CanReadMore ())
+					array.size = (int) ReadCompressedUInt32 ();
+				if (CanReadMore ())
+					array.element_type = ReadNativeType ();
+				return array;
+			}
+			case NativeType.FixedSysString: {
+				var sys_string = new FixedSysStringMarshalInfo ();
+				if (CanReadMore ())
+					sys_string.size = (int) ReadCompressedUInt32 ();
+				return sys_string;
+			}
+			case NativeType.CustomMarshaler: {
+				var marshaler = new CustomMarshalInfo ();
+				var guid_value = ReadUTF8String ();
+				marshaler.guid = !string.IsNullOrEmpty (guid_value) ? new Guid (guid_value) : Guid.Empty;
+				marshaler.unmanaged_type = ReadUTF8String ();
+				marshaler.managed_type = ReadTypeReference ();
+				marshaler.cookie = ReadUTF8String ();
+				return marshaler;
+			}
+			default:
+				return new MarshalInfo (native);
+			}
+		}
+
+		NativeType ReadNativeType ()
+		{
+			return (NativeType) ReadByte ();
+		}
+
+		VariantType ReadVariantType ()
+		{
+			return (VariantType) ReadByte ();
+		}
+
+		string ReadUTF8String ()
+		{
+			if (buffer [position] == 0xff) {
+				position++;
+				return null;
+			}
+
+			var length = (int) ReadCompressedUInt32 ();
+			if (length == 0)
+				return string.Empty;
+
+			var @string = Encoding.UTF8.GetString (buffer, position,
+				buffer [position + length - 1] == 0 ? length - 1 : length);
+
+			position += length;
+			return @string;
+		}
+
+		public bool CanReadMore ()
+		{
+			return position - start < sig_length;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/AssemblyWriter.cs	(revision 11807)
@@ -0,0 +1,2573 @@
+//
+// AssemblyWriter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+using Mono.Collections.Generic;
+using Mono.Cecil.Cil;
+using Mono.Cecil.Metadata;
+using Mono.Cecil.PE;
+
+using RVA = System.UInt32;
+using RID = System.UInt32;
+using CodedRID = System.UInt32;
+using StringIndex = System.UInt32;
+using BlobIndex = System.UInt32;
+
+namespace Mono.Cecil {
+
+#if !READ_ONLY
+
+	using TypeRefRow     = Row<CodedRID, StringIndex, StringIndex>;
+	using TypeDefRow     = Row<TypeAttributes, StringIndex, StringIndex, CodedRID, RID, RID>;
+	using FieldRow       = Row<FieldAttributes, StringIndex, BlobIndex>;
+	using MethodRow      = Row<RVA, MethodImplAttributes, MethodAttributes, StringIndex, BlobIndex, RID>;
+	using ParamRow       = Row<ParameterAttributes, ushort, StringIndex>;
+	using InterfaceImplRow = Row<uint, CodedRID>;
+	using MemberRefRow   = Row<CodedRID, StringIndex, BlobIndex>;
+	using ConstantRow    = Row<ElementType, CodedRID, BlobIndex>;
+	using CustomAttributeRow = Row<CodedRID, CodedRID, BlobIndex>;
+	using FieldMarshalRow = Row<CodedRID, BlobIndex>;
+	using DeclSecurityRow = Row<SecurityAction, CodedRID, BlobIndex>;
+	using ClassLayoutRow = Row<ushort, uint, RID>;
+	using FieldLayoutRow = Row<uint, RID>;
+	using EventMapRow    = Row<RID, RID>;
+	using EventRow       = Row<EventAttributes, StringIndex, CodedRID>;
+	using PropertyMapRow = Row<RID, RID>;
+	using PropertyRow    = Row<PropertyAttributes, StringIndex, BlobIndex>;
+	using MethodSemanticsRow = Row<MethodSemanticsAttributes, RID, CodedRID>;
+	using MethodImplRow  = Row<RID, CodedRID, CodedRID>;
+	using ImplMapRow     = Row<PInvokeAttributes, CodedRID, StringIndex, RID>;
+	using FieldRVARow    = Row<RVA, RID>;
+	using AssemblyRow    = Row<AssemblyHashAlgorithm, ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint>;
+	using AssemblyRefRow = Row<ushort, ushort, ushort, ushort, AssemblyAttributes, uint, uint, uint, uint>;
+	using FileRow        = Row<FileAttributes, StringIndex, BlobIndex>;
+	using ExportedTypeRow = Row<TypeAttributes, uint, StringIndex, StringIndex, CodedRID>;
+	using ManifestResourceRow = Row<uint, ManifestResourceAttributes, StringIndex, CodedRID>;
+	using NestedClassRow = Row<RID, RID>;
+	using GenericParamRow = Row<ushort, GenericParameterAttributes, CodedRID, StringIndex>;
+	using MethodSpecRow = Row<CodedRID, BlobIndex>;
+	using GenericParamConstraintRow = Row<RID, CodedRID>;
+
+	static class ModuleWriter {
+
+		public static void WriteModuleTo (ModuleDefinition module, Stream stream, WriterParameters parameters)
+		{
+			if ((module.Attributes & ModuleAttributes.ILOnly) == 0)
+				throw new ArgumentException ();
+
+			if (module.HasImage && module.ReadingMode == ReadingMode.Deferred)
+				ImmediateModuleReader.ReadModule (module);
+
+			module.MetadataSystem.Clear ();
+
+			var name = module.assembly != null ? module.assembly.Name : null;
+			var fq_name = stream.GetFullyQualifiedName ();
+			var symbol_writer_provider = parameters.SymbolWriterProvider;
+			if (symbol_writer_provider == null && parameters.WriteSymbols)
+				symbol_writer_provider = SymbolProvider.GetPlatformWriterProvider ();
+			var symbol_writer = GetSymbolWriter (module, fq_name, symbol_writer_provider);
+
+#if !SILVERLIGHT && !CF
+			if (parameters.StrongNameKeyPair != null && name != null)
+				name.PublicKey = parameters.StrongNameKeyPair.PublicKey;
+#endif
+
+			if (name != null && name.HasPublicKey)
+				module.Attributes |= ModuleAttributes.StrongNameSigned;
+
+			var metadata = new MetadataBuilder (module, fq_name,
+				symbol_writer_provider, symbol_writer);
+
+			BuildMetadata (module, metadata);
+
+			if (module.SymbolReader != null)
+				module.SymbolReader.Dispose ();
+
+			var writer = ImageWriter.CreateWriter (module, metadata, stream);
+
+			writer.WriteImage ();
+
+#if !SILVERLIGHT && !CF
+			if (parameters.StrongNameKeyPair != null)
+				CryptoService.StrongName (stream, writer, parameters.StrongNameKeyPair);
+#endif
+			if (symbol_writer != null)
+				symbol_writer.Dispose ();
+		}
+
+		static void BuildMetadata (ModuleDefinition module, MetadataBuilder metadata)
+		{
+			if (!module.HasImage) {
+				metadata.BuildMetadata ();
+				return;
+			}
+
+			module.Read (metadata, (builder, _) => {
+				builder.BuildMetadata ();
+				return builder;
+			});
+		}
+
+		static ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fq_name, ISymbolWriterProvider symbol_writer_provider)
+		{
+			if (symbol_writer_provider == null)
+				return null;
+
+			return symbol_writer_provider.GetSymbolWriter (module, fq_name);
+		}
+	}
+
+	abstract class MetadataTable {
+
+		public abstract int Length { get; }
+
+		public bool IsLarge {
+			get { return Length > 65535; }
+		}
+
+		public abstract void Write (TableHeapBuffer buffer);
+		public abstract void Sort ();
+	}
+
+	abstract class OneRowTable<TRow> : MetadataTable where TRow : struct {
+
+		internal TRow row;
+
+		public sealed override int Length {
+			get { return 1; }
+		}
+
+		public sealed override void Sort ()
+		{
+		}
+	}
+
+	abstract class MetadataTable<TRow> : MetadataTable where TRow : struct {
+
+		internal TRow [] rows = new TRow [2];
+		internal int length;
+
+		public sealed override int Length {
+			get { return length; }
+		}
+
+		public int AddRow (TRow row)
+		{
+			if (rows.Length == length)
+				Grow ();
+
+			rows [length++] = row;
+			return length;
+		}
+
+		void Grow ()
+		{
+			var rows = new TRow [this.rows.Length * 2];
+			Array.Copy (this.rows, rows, this.rows.Length);
+			this.rows = rows;
+		}
+
+		public override void Sort ()
+		{
+		}
+	}
+
+	abstract class SortedTable<TRow> : MetadataTable<TRow>, IComparer<TRow> where TRow : struct {
+
+		public sealed override void Sort ()
+		{
+			Array.Sort (rows, 0, length, this);
+		}
+
+		protected int Compare (uint x, uint y)
+		{
+			return x == y ? 0 : x > y ? 1 : -1;
+		}
+
+		public abstract int Compare (TRow x, TRow y);
+	}
+
+	sealed class ModuleTable : OneRowTable<uint> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			buffer.WriteUInt16 (0);		// Generation
+			buffer.WriteString (row);	// Name
+			buffer.WriteUInt16 (1);		// Mvid
+			buffer.WriteUInt16 (0);		// EncId
+			buffer.WriteUInt16 (0);		// EncBaseId
+		}
+	}
+
+	sealed class TypeRefTable : MetadataTable<TypeRefRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteCodedRID (
+					rows [i].Col1, CodedIndex.ResolutionScope);	// Scope
+				buffer.WriteString (rows [i].Col2);			// Name
+				buffer.WriteString (rows [i].Col3);			// Namespace
+			}
+		}
+	}
+
+	sealed class TypeDefTable : MetadataTable<TypeDefRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 ((uint) rows [i].Col1);	// Attributes
+				buffer.WriteString (rows [i].Col2);			// Name
+				buffer.WriteString (rows [i].Col3);			// Namespace
+				buffer.WriteCodedRID (
+					rows [i].Col4, CodedIndex.TypeDefOrRef);	// Extends
+				buffer.WriteRID (rows [i].Col5, Table.Field);	// FieldList
+				buffer.WriteRID (rows [i].Col6, Table.Method);	// MethodList
+			}
+		}
+	}
+
+	sealed class FieldTable : MetadataTable<FieldRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);	// Attributes
+				buffer.WriteString (rows [i].Col2);			// Name
+				buffer.WriteBlob (rows [i].Col3);			// Signature
+			}
+		}
+	}
+
+	sealed class MethodTable : MetadataTable<MethodRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 (rows [i].Col1);		// RVA
+				buffer.WriteUInt16 ((ushort) rows [i].Col2);	// ImplFlags
+				buffer.WriteUInt16 ((ushort) rows [i].Col3);	// Flags
+				buffer.WriteString (rows [i].Col4);		// Name
+				buffer.WriteBlob (rows [i].Col5);		// Signature
+				buffer.WriteRID (rows [i].Col6, Table.Param);	// ParamList
+			}
+		}
+	}
+
+	sealed class ParamTable : MetadataTable<ParamRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);	// Attributes
+				buffer.WriteUInt16 (rows [i].Col2);		// Sequence
+				buffer.WriteString (rows [i].Col3);		// Name
+			}
+		}
+	}
+
+	sealed class InterfaceImplTable : MetadataTable<InterfaceImplRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteRID (rows [i].Col1, Table.TypeDef);		// Class
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.TypeDefOrRef);	// Interface
+			}
+		}
+
+		/*public override int Compare (InterfaceImplRow x, InterfaceImplRow y)
+		{
+			return (int) (x.Col1 == y.Col1 ? y.Col2 - x.Col2 : x.Col1 - y.Col1);
+		}*/
+	}
+
+	sealed class MemberRefTable : MetadataTable<MemberRefRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteCodedRID (rows [i].Col1, CodedIndex.MemberRefParent);
+				buffer.WriteString (rows [i].Col2);
+				buffer.WriteBlob (rows [i].Col3);
+			}
+		}
+	}
+
+	sealed class ConstantTable : SortedTable<ConstantRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.HasConstant);
+				buffer.WriteBlob (rows [i].Col3);
+			}
+		}
+
+		public override int Compare (ConstantRow x, ConstantRow y)
+		{
+			return Compare (x.Col2, y.Col2);
+		}
+	}
+
+	sealed class CustomAttributeTable : SortedTable<CustomAttributeRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteCodedRID (rows [i].Col1, CodedIndex.HasCustomAttribute);	// Parent
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.CustomAttributeType);	// Type
+				buffer.WriteBlob (rows [i].Col3);
+			}
+		}
+
+		public override int Compare (CustomAttributeRow x, CustomAttributeRow y)
+		{
+			return Compare (x.Col1, y.Col1);
+		}
+	}
+
+	sealed class FieldMarshalTable : SortedTable<FieldMarshalRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteCodedRID (rows [i].Col1, CodedIndex.HasFieldMarshal);
+				buffer.WriteBlob (rows [i].Col2);
+			}
+		}
+
+		public override int Compare (FieldMarshalRow x, FieldMarshalRow y)
+		{
+			return Compare (x.Col1, y.Col1);
+		}
+	}
+
+	sealed class DeclSecurityTable : SortedTable<DeclSecurityRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.HasDeclSecurity);
+				buffer.WriteBlob (rows [i].Col3);
+			}
+		}
+
+		public override int Compare (DeclSecurityRow x, DeclSecurityRow y)
+		{
+			return Compare (x.Col2, y.Col2);
+		}
+	}
+
+	sealed class ClassLayoutTable : SortedTable<ClassLayoutRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 (rows [i].Col1);		// PackingSize
+				buffer.WriteUInt32 (rows [i].Col2);		// ClassSize
+				buffer.WriteRID (rows [i].Col3, Table.TypeDef);	// Parent
+			}
+		}
+
+		public override int Compare (ClassLayoutRow x, ClassLayoutRow y)
+		{
+			return Compare (x.Col3, y.Col3);
+		}
+	}
+
+	sealed class FieldLayoutTable : SortedTable<FieldLayoutRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 (rows [i].Col1);		// Offset
+				buffer.WriteRID (rows [i].Col2, Table.Field);	// Parent
+			}
+		}
+
+		public override int Compare (FieldLayoutRow x, FieldLayoutRow y)
+		{
+			return Compare (x.Col2, y.Col2);
+		}
+	}
+
+	sealed class StandAloneSigTable : MetadataTable<uint> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++)
+				buffer.WriteBlob (rows [i]);
+		}
+	}
+
+	sealed class EventMapTable : MetadataTable<EventMapRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteRID (rows [i].Col1, Table.TypeDef);		// Parent
+				buffer.WriteRID (rows [i].Col2, Table.Event);		// EventList
+			}
+		}
+	}
+
+	sealed class EventTable : MetadataTable<EventRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);	// Flags
+				buffer.WriteString (rows [i].Col2);		// Name
+				buffer.WriteCodedRID (rows [i].Col3, CodedIndex.TypeDefOrRef);	// EventType
+			}
+		}
+	}
+
+	sealed class PropertyMapTable : MetadataTable<PropertyMapRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteRID (rows [i].Col1, Table.TypeDef);		// Parent
+				buffer.WriteRID (rows [i].Col2, Table.Property);	// PropertyList
+			}
+		}
+	}
+
+	sealed class PropertyTable : MetadataTable<PropertyRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);	// Flags
+				buffer.WriteString (rows [i].Col2);		// Name
+				buffer.WriteBlob (rows [i].Col3);		// Type
+			}
+		}
+	}
+
+	sealed class MethodSemanticsTable : SortedTable<MethodSemanticsRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);	// Flags
+				buffer.WriteRID (rows [i].Col2, Table.Method);	// Method
+				buffer.WriteCodedRID (rows [i].Col3, CodedIndex.HasSemantics);	// Association
+			}
+		}
+
+		public override int Compare (MethodSemanticsRow x, MethodSemanticsRow y)
+		{
+			return Compare (x.Col3, y.Col3);
+		}
+	}
+
+	sealed class MethodImplTable : MetadataTable<MethodImplRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteRID (rows [i].Col1, Table.TypeDef);	// Class
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.MethodDefOrRef);	// MethodBody
+				buffer.WriteCodedRID (rows [i].Col3, CodedIndex.MethodDefOrRef);	// MethodDeclaration
+			}
+		}
+	}
+
+	sealed class ModuleRefTable : MetadataTable<uint> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++)
+				buffer.WriteString (rows [i]);	// Name
+		}
+	}
+
+	sealed class TypeSpecTable : MetadataTable<uint> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++)
+				buffer.WriteBlob (rows [i]);	// Signature
+		}
+	}
+
+	sealed class ImplMapTable : SortedTable<ImplMapRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 ((ushort) rows [i].Col1);	// Flags
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.MemberForwarded);	// MemberForwarded
+				buffer.WriteString (rows [i].Col3);		// ImportName
+				buffer.WriteRID (rows [i].Col4, Table.ModuleRef);	// ImportScope
+			}
+		}
+
+		public override int Compare (ImplMapRow x, ImplMapRow y)
+		{
+			return Compare (x.Col2, y.Col2);
+		}
+	}
+
+	sealed class FieldRVATable : SortedTable<FieldRVARow> {
+
+		internal int position;
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			position = buffer.position;
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 (rows [i].Col1);		// RVA
+				buffer.WriteRID (rows [i].Col2, Table.Field);	// Field
+			}
+		}
+
+		public override int Compare (FieldRVARow x, FieldRVARow y)
+		{
+			return Compare (x.Col2, y.Col2);
+		}
+	}
+
+	sealed class AssemblyTable : OneRowTable<AssemblyRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			buffer.WriteUInt32 ((uint) row.Col1);	// AssemblyHashAlgorithm
+			buffer.WriteUInt16 (row.Col2);			// MajorVersion
+			buffer.WriteUInt16 (row.Col3);			// MinorVersion
+			buffer.WriteUInt16 (row.Col4);			// Build
+			buffer.WriteUInt16 (row.Col5);			// Revision
+			buffer.WriteUInt32 ((uint) row.Col6);	// Flags
+			buffer.WriteBlob (row.Col7);			// PublicKey
+			buffer.WriteString (row.Col8);			// Name
+			buffer.WriteString (row.Col9);			// Culture
+		}
+	}
+
+	sealed class AssemblyRefTable : MetadataTable<AssemblyRefRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 (rows [i].Col1);		// MajorVersion
+				buffer.WriteUInt16 (rows [i].Col2);		// MinorVersion
+				buffer.WriteUInt16 (rows [i].Col3);		// Build
+				buffer.WriteUInt16 (rows [i].Col4);		// Revision
+				buffer.WriteUInt32 ((uint) rows [i].Col5);	// Flags
+				buffer.WriteBlob (rows [i].Col6);		// PublicKeyOrToken
+				buffer.WriteString (rows [i].Col7);		// Name
+				buffer.WriteString (rows [i].Col8);		// Culture
+				buffer.WriteBlob (rows [i].Col9);		// Hash
+			}
+		}
+	}
+
+	sealed class FileTable : MetadataTable<FileRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 ((uint) rows [i].Col1);
+				buffer.WriteString (rows [i].Col2);
+				buffer.WriteBlob (rows [i].Col3);
+			}
+		}
+	}
+
+	sealed class ExportedTypeTable : MetadataTable<ExportedTypeRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 ((uint) rows [i].Col1);
+				buffer.WriteUInt32 (rows [i].Col2);
+				buffer.WriteString (rows [i].Col3);
+				buffer.WriteString (rows [i].Col4);
+				buffer.WriteCodedRID (rows [i].Col5, CodedIndex.Implementation);
+			}
+		}
+	}
+
+	sealed class ManifestResourceTable : MetadataTable<ManifestResourceRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt32 (rows [i].Col1);
+				buffer.WriteUInt32 ((uint) rows [i].Col2);
+				buffer.WriteString (rows [i].Col3);
+				buffer.WriteCodedRID (rows [i].Col4, CodedIndex.Implementation);
+			}
+		}
+	}
+
+	sealed class NestedClassTable : SortedTable<NestedClassRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteRID (rows [i].Col1, Table.TypeDef);		// NestedClass
+				buffer.WriteRID (rows [i].Col2, Table.TypeDef);		// EnclosingClass
+			}
+		}
+
+		public override int Compare (NestedClassRow x, NestedClassRow y)
+		{
+			return Compare (x.Col1, y.Col1);
+		}
+	}
+
+	sealed class GenericParamTable : MetadataTable<GenericParamRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteUInt16 (rows [i].Col1);		// Number
+				buffer.WriteUInt16 ((ushort) rows [i].Col2);	// Flags
+				buffer.WriteCodedRID (rows [i].Col3, CodedIndex.TypeOrMethodDef);	// Owner
+				buffer.WriteString (rows [i].Col4);		// Name
+			}
+		}
+	}
+
+	sealed class MethodSpecTable : MetadataTable<MethodSpecRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteCodedRID (rows [i].Col1, CodedIndex.MethodDefOrRef);	// Method
+				buffer.WriteBlob (rows [i].Col2);	// Instantiation
+			}
+		}
+	}
+
+	sealed class GenericParamConstraintTable : MetadataTable<GenericParamConstraintRow> {
+
+		public override void Write (TableHeapBuffer buffer)
+		{
+			for (int i = 0; i < length; i++) {
+				buffer.WriteRID (rows [i].Col1, Table.GenericParam);	// Owner
+				buffer.WriteCodedRID (rows [i].Col2, CodedIndex.TypeDefOrRef);	// Constraint
+			}
+		}
+	}
+
+	sealed class MetadataBuilder {
+
+		readonly internal ModuleDefinition module;
+		readonly internal ISymbolWriterProvider symbol_writer_provider;
+		readonly internal ISymbolWriter symbol_writer;
+		readonly internal TextMap text_map;
+		readonly internal string fq_name;
+
+		readonly Dictionary<TypeRefRow, MetadataToken> type_ref_map;
+		readonly Dictionary<uint, MetadataToken> type_spec_map;
+		readonly Dictionary<MemberRefRow, MetadataToken> member_ref_map;
+		readonly Dictionary<MethodSpecRow, MetadataToken> method_spec_map;
+		readonly Collection<GenericParameter> generic_parameters;
+		readonly Dictionary<MetadataToken, MetadataToken> method_def_map;
+
+		readonly internal CodeWriter code;
+		readonly internal DataBuffer data;
+		readonly internal ResourceBuffer resources;
+		readonly internal StringHeapBuffer string_heap;
+		readonly internal UserStringHeapBuffer user_string_heap;
+		readonly internal BlobHeapBuffer blob_heap;
+		readonly internal TableHeapBuffer table_heap;
+
+		internal MetadataToken entry_point;
+
+		RID type_rid = 1;
+		RID field_rid = 1;
+		RID method_rid = 1;
+		RID param_rid = 1;
+		RID property_rid = 1;
+		RID event_rid = 1;
+
+		readonly TypeRefTable type_ref_table;
+		readonly TypeDefTable type_def_table;
+		readonly FieldTable field_table;
+		readonly MethodTable method_table;
+		readonly ParamTable param_table;
+		readonly InterfaceImplTable iface_impl_table;
+		readonly MemberRefTable member_ref_table;
+		readonly ConstantTable constant_table;
+		readonly CustomAttributeTable custom_attribute_table;
+		readonly DeclSecurityTable declsec_table;
+		readonly StandAloneSigTable standalone_sig_table;
+		readonly EventMapTable event_map_table;
+		readonly EventTable event_table;
+		readonly PropertyMapTable property_map_table;
+		readonly PropertyTable property_table;
+		readonly TypeSpecTable typespec_table;
+		readonly MethodSpecTable method_spec_table;
+
+		readonly internal bool write_symbols;
+
+		public MetadataBuilder (ModuleDefinition module, string fq_name, ISymbolWriterProvider symbol_writer_provider, ISymbolWriter symbol_writer)
+		{
+			this.module = module;
+			this.text_map = CreateTextMap ();
+			this.fq_name = fq_name;
+			this.symbol_writer_provider = symbol_writer_provider;
+			this.symbol_writer = symbol_writer;
+			this.write_symbols = symbol_writer != null;
+			this.code = new CodeWriter (this);
+			this.data = new DataBuffer ();
+			this.resources = new ResourceBuffer ();
+			this.string_heap = new StringHeapBuffer ();
+			this.user_string_heap = new UserStringHeapBuffer ();
+			this.blob_heap = new BlobHeapBuffer ();
+			this.table_heap = new TableHeapBuffer (module, this);
+
+			this.type_ref_table = GetTable<TypeRefTable> (Table.TypeRef);
+			this.type_def_table = GetTable<TypeDefTable> (Table.TypeDef);
+			this.field_table = GetTable<FieldTable> (Table.Field);
+			this.method_table = GetTable<MethodTable> (Table.Method);
+			this.param_table = GetTable<ParamTable> (Table.Param);
+			this.iface_impl_table = GetTable<InterfaceImplTable> (Table.InterfaceImpl);
+			this.member_ref_table = GetTable<MemberRefTable> (Table.MemberRef);
+			this.constant_table = GetTable<ConstantTable> (Table.Constant);
+			this.custom_attribute_table = GetTable<CustomAttributeTable> (Table.CustomAttribute);
+			this.declsec_table = GetTable<DeclSecurityTable> (Table.DeclSecurity);
+			this.standalone_sig_table = GetTable<StandAloneSigTable> (Table.StandAloneSig);
+			this.event_map_table = GetTable<EventMapTable> (Table.EventMap);
+			this.event_table = GetTable<EventTable> (Table.Event);
+			this.property_map_table = GetTable<PropertyMapTable> (Table.PropertyMap);
+			this.property_table = GetTable<PropertyTable> (Table.Property);
+			this.typespec_table = GetTable<TypeSpecTable> (Table.TypeSpec);
+			this.method_spec_table = GetTable<MethodSpecTable> (Table.MethodSpec);
+
+			var row_equality_comparer = new RowEqualityComparer ();
+			type_ref_map = new Dictionary<TypeRefRow, MetadataToken> (row_equality_comparer);
+			type_spec_map = new Dictionary<uint, MetadataToken> ();
+			member_ref_map = new Dictionary<MemberRefRow, MetadataToken> (row_equality_comparer);
+			method_spec_map = new Dictionary<MethodSpecRow, MetadataToken> (row_equality_comparer);
+			generic_parameters = new Collection<GenericParameter> ();
+			if (write_symbols)
+				method_def_map = new Dictionary<MetadataToken, MetadataToken> ();
+		}
+
+		TextMap CreateTextMap ()
+		{
+			var map = new TextMap ();
+			map.AddMap (TextSegment.ImportAddressTable, module.Architecture == TargetArchitecture.I386 ? 8 : 16);
+			map.AddMap (TextSegment.CLIHeader, 0x48, 8);
+			return map;
+		}
+
+		TTable GetTable<TTable> (Table table) where TTable : MetadataTable, new ()
+		{
+			return table_heap.GetTable<TTable> (table);
+		}
+
+		uint GetStringIndex (string @string)
+		{
+			if (string.IsNullOrEmpty (@string))
+				return 0;
+
+			return string_heap.GetStringIndex (@string);
+		}
+
+		uint GetBlobIndex (ByteBuffer blob)
+		{
+			if (blob.length == 0)
+				return 0;
+
+			return blob_heap.GetBlobIndex (blob);
+		}
+
+		uint GetBlobIndex (byte [] blob)
+		{
+			if (blob.IsNullOrEmpty ())
+				return 0;
+
+			return GetBlobIndex (new ByteBuffer (blob));
+		}
+
+		public void BuildMetadata ()
+		{
+			BuildModule ();
+
+			table_heap.WriteTableHeap ();
+		}
+
+		void BuildModule ()
+		{
+			var table = GetTable<ModuleTable> (Table.Module);
+			table.row = GetStringIndex (module.Name);
+
+			var assembly = module.Assembly;
+
+			if (assembly != null)
+				BuildAssembly ();
+
+			if (module.HasAssemblyReferences)
+				AddAssemblyReferences ();
+
+			if (module.HasModuleReferences)
+				AddModuleReferences ();
+
+			if (module.HasResources)
+				AddResources ();
+
+			if (module.HasExportedTypes)
+				AddExportedTypes ();
+
+			BuildTypes ();
+
+			if (assembly != null) {
+				if (assembly.HasCustomAttributes)
+					AddCustomAttributes (assembly);
+
+				if (assembly.HasSecurityDeclarations)
+					AddSecurityDeclarations (assembly);
+			}
+
+			if (module.HasCustomAttributes)
+				AddCustomAttributes (module);
+
+			if (module.EntryPoint != null)
+				entry_point = LookupToken (module.EntryPoint);
+		}
+
+		void BuildAssembly ()
+		{
+			var assembly = module.Assembly;
+			var name = assembly.Name;
+
+			var table = GetTable<AssemblyTable> (Table.Assembly);
+
+			table.row = new AssemblyRow (
+				name.HashAlgorithm,
+				(ushort) name.Version.Major,
+				(ushort) name.Version.Minor,
+				(ushort) name.Version.Build,
+				(ushort) name.Version.Revision,
+				name.Attributes,
+				GetBlobIndex (name.PublicKey),
+				GetStringIndex (name.Name),
+				GetStringIndex (name.Culture));
+
+			if (assembly.Modules.Count > 1)
+				BuildModules ();
+		}
+
+		void BuildModules ()
+		{
+			var modules = this.module.Assembly.Modules;
+			var table = GetTable<FileTable> (Table.File);
+
+			for (int i = 0; i < modules.Count; i++) {
+				var module = modules [i];
+				if (module.IsMain)
+					continue;
+
+				var parameters = new WriterParameters {
+					SymbolWriterProvider = symbol_writer_provider,
+				};
+
+				var file_name = GetModuleFileName (module.Name);
+				module.Write (file_name, parameters);
+
+				var hash = CryptoService.ComputeHash (file_name);
+
+				table.AddRow (new FileRow (
+					FileAttributes.ContainsMetaData,
+					GetStringIndex (module.Name),
+					GetBlobIndex (hash)));
+			}
+		}
+
+		string GetModuleFileName (string name)
+		{
+			if (string.IsNullOrEmpty (name))
+				throw new NotSupportedException ();
+
+			var path = Path.GetDirectoryName (fq_name);
+			return Path.Combine (path, name);
+		}
+
+		void AddAssemblyReferences ()
+		{
+			var references = module.AssemblyReferences;
+			var table = GetTable<AssemblyRefTable> (Table.AssemblyRef);
+
+			for (int i = 0; i < references.Count; i++) {
+				var reference = references [i];
+
+				var key_or_token = reference.PublicKey.IsNullOrEmpty ()
+					? reference.PublicKeyToken
+					: reference.PublicKey;
+
+				var version = reference.Version;
+
+				var rid = table.AddRow (new AssemblyRefRow (
+					(ushort) version.Major,
+					(ushort) version.Minor,
+					(ushort) version.Build,
+					(ushort) version.Revision,
+					reference.Attributes,
+					GetBlobIndex (key_or_token),
+					GetStringIndex (reference.Name),
+					GetStringIndex (reference.Culture),
+					GetBlobIndex (reference.Hash)));
+
+				reference.token = new MetadataToken (TokenType.AssemblyRef, rid);
+			}
+		}
+
+		void AddModuleReferences ()
+		{
+			var references = module.ModuleReferences;
+			var table = GetTable<ModuleRefTable> (Table.ModuleRef);
+
+			for (int i = 0; i < references.Count; i++) {
+				var reference = references [i];
+
+				reference.token = new MetadataToken (
+					TokenType.ModuleRef,
+					table.AddRow (GetStringIndex (reference.Name)));
+			}
+		}
+
+		void AddResources ()
+		{
+			var resources = module.Resources;
+			var table = GetTable<ManifestResourceTable> (Table.ManifestResource);
+
+			for (int i = 0; i < resources.Count; i++) {
+				var resource = resources [i];
+
+				var row = new ManifestResourceRow (
+					0,
+					resource.Attributes,
+					GetStringIndex (resource.Name),
+					0);
+
+				switch (resource.ResourceType) {
+				case ResourceType.Embedded:
+					row.Col1 = AddEmbeddedResource ((EmbeddedResource) resource);
+					break;
+				case ResourceType.Linked:
+					row.Col4 = CodedIndex.Implementation.CompressMetadataToken (
+						new MetadataToken (
+							TokenType.File,
+							AddLinkedResource ((LinkedResource) resource)));
+					break;
+				case ResourceType.AssemblyLinked:
+					row.Col4 = CodedIndex.Implementation.CompressMetadataToken (
+						((AssemblyLinkedResource) resource).Assembly.MetadataToken);
+					break;
+				default:
+					throw new NotSupportedException ();
+				}
+
+				table.AddRow (row);
+			}
+		}
+
+		uint AddLinkedResource (LinkedResource resource)
+		{
+			var table = GetTable<FileTable> (Table.File);
+
+			var hash = resource.Hash.IsNullOrEmpty ()
+				? CryptoService.ComputeHash (resource.File)
+				: resource.Hash;
+
+			return (uint) table.AddRow (new FileRow (
+				FileAttributes.ContainsNoMetaData,
+				GetStringIndex (resource.File),
+				GetBlobIndex (hash)));
+		}
+
+		uint AddEmbeddedResource (EmbeddedResource resource)
+		{
+			return resources.AddResource (resource.GetResourceData ());
+		}
+
+		void AddExportedTypes ()
+		{
+			var exported_types = module.ExportedTypes;
+			var table = GetTable<ExportedTypeTable> (Table.ExportedType);
+
+			for (int i = 0; i < exported_types.Count; i++) {
+				var exported_type = exported_types [i];
+
+				var rid = table.AddRow (new ExportedTypeRow (
+					exported_type.Attributes,
+					(uint) exported_type.Identifier,
+					GetStringIndex (exported_type.Name),
+					GetStringIndex (exported_type.Namespace),
+					MakeCodedRID (GetExportedTypeScope (exported_type), CodedIndex.Implementation)));
+
+				exported_type.token = new MetadataToken (TokenType.ExportedType, rid);
+			}
+		}
+
+		MetadataToken GetExportedTypeScope (ExportedType exported_type)
+		{
+			if (exported_type.DeclaringType != null)
+				return exported_type.DeclaringType.MetadataToken;
+
+			var scope = exported_type.Scope;
+			switch (scope.MetadataToken.TokenType) {
+			case TokenType.AssemblyRef:
+				return scope.MetadataToken;
+			case TokenType.ModuleRef:
+				var file_table = GetTable<FileTable> (Table.File);
+				for (int i = 0; i < file_table.length; i++)
+					if (file_table.rows [i].Col2 == GetStringIndex (scope.Name))
+						return new MetadataToken (TokenType.File, i + 1);
+
+				break;
+			}
+
+			throw new NotSupportedException ();
+		}
+
+		void BuildTypes ()
+		{
+			if (!module.HasTypes)
+				return;
+
+			AttachTokens ();
+			AddTypeDefs ();
+			AddGenericParameters ();
+		}
+
+		void AttachTokens ()
+		{
+			var types = module.Types;
+
+			for (int i = 0; i < types.Count; i++)
+				AttachTypeDefToken (types [i]);
+		}
+
+		void AttachTypeDefToken (TypeDefinition type)
+		{
+			type.token = new MetadataToken (TokenType.TypeDef, type_rid++);
+			type.fields_range.Start = field_rid;
+			type.methods_range.Start = method_rid;
+
+			if (type.HasFields)
+				AttachFieldsDefToken (type);
+
+			if (type.HasMethods)
+				AttachMethodsDefToken (type);
+
+			if (type.HasNestedTypes)
+				AttachNestedTypesDefToken (type);
+		}
+
+		void AttachNestedTypesDefToken (TypeDefinition type)
+		{
+			var nested_types = type.NestedTypes;
+			for (int i = 0; i < nested_types.Count; i++)
+				AttachTypeDefToken (nested_types [i]);
+		}
+
+		void AttachFieldsDefToken (TypeDefinition type)
+		{
+			var fields = type.Fields;
+			type.fields_range.Length = (uint) fields.Count;
+			for (int i = 0; i < fields.Count; i++)
+				fields [i].token = new MetadataToken (TokenType.Field, field_rid++);
+		}
+
+		void AttachMethodsDefToken (TypeDefinition type)
+		{
+			var methods = type.Methods;
+			type.methods_range.Length = (uint) methods.Count;
+			for (int i = 0; i < methods.Count; i++) {
+				var method = methods [i];
+				var new_token = new MetadataToken (TokenType.Method, method_rid++);
+
+				if (write_symbols && method.token != MetadataToken.Zero)
+					method_def_map.Add (new_token, method.token);
+
+				method.token = new_token;
+			}
+		}
+
+		public bool TryGetOriginalMethodToken (MetadataToken new_token, out MetadataToken original)
+		{
+			return method_def_map.TryGetValue (new_token, out original);
+		}
+
+		MetadataToken GetTypeToken (TypeReference type)
+		{
+			if (type == null)
+				return MetadataToken.Zero;
+
+			if (type.IsDefinition)
+				return type.token;
+
+			if (type.IsTypeSpecification ())
+				return GetTypeSpecToken (type);
+
+			return GetTypeRefToken (type);
+		}
+
+		MetadataToken GetTypeSpecToken (TypeReference type)
+		{
+			var row = GetBlobIndex (GetTypeSpecSignature (type));
+
+			MetadataToken token;
+			if (type_spec_map.TryGetValue (row, out token))
+				return token;
+
+			return AddTypeSpecification (type, row);
+		}
+
+		MetadataToken AddTypeSpecification (TypeReference type, uint row)
+		{
+			type.token = new MetadataToken (TokenType.TypeSpec, typespec_table.AddRow (row));
+
+			var token = type.token;
+			type_spec_map.Add (row, token);
+			return token;
+		}
+
+		MetadataToken GetTypeRefToken (TypeReference type)
+		{
+			var row = CreateTypeRefRow (type);
+
+			MetadataToken token;
+			if (type_ref_map.TryGetValue (row, out token))
+				return token;
+
+			return AddTypeReference (type, row);
+		}
+
+		TypeRefRow CreateTypeRefRow (TypeReference type)
+		{
+			var scope_token = type.IsNested
+				? GetTypeRefToken (type.DeclaringType)
+				: type.Scope.MetadataToken;
+
+			return new TypeRefRow (
+				MakeCodedRID (scope_token, CodedIndex.ResolutionScope),
+				GetStringIndex (type.Name),
+				GetStringIndex (type.Namespace));
+		}
+
+		static CodedRID MakeCodedRID (IMetadataTokenProvider provider, CodedIndex index)
+		{
+			return MakeCodedRID (provider.MetadataToken, index);
+		}
+
+		static CodedRID MakeCodedRID (MetadataToken token, CodedIndex index)
+		{
+			return index.CompressMetadataToken (token);
+		}
+
+		MetadataToken AddTypeReference (TypeReference type, TypeRefRow row)
+		{
+			type.token = new MetadataToken (TokenType.TypeRef, type_ref_table.AddRow (row));
+
+			var token = type.token;
+			type_ref_map.Add (row, token);
+			return token;
+		}
+
+		void AddTypeDefs ()
+		{
+			var types = module.Types;
+
+			for (int i = 0; i < types.Count; i++)
+				AddType (types [i]);
+		}
+
+		void AddType (TypeDefinition type)
+		{
+			type_def_table.AddRow (new TypeDefRow (
+				type.Attributes,
+				GetStringIndex (type.Name),
+				GetStringIndex (type.Namespace),
+				MakeCodedRID (GetTypeToken (type.BaseType), CodedIndex.TypeDefOrRef),
+				type.fields_range.Start,
+				type.methods_range.Start));
+
+			if (type.HasGenericParameters)
+				AddGenericParameters (type);
+
+			if (type.HasInterfaces)
+				AddInterfaces (type);
+
+			if (type.HasLayoutInfo)
+				AddLayoutInfo (type);
+
+			if (type.HasFields)
+				AddFields (type);
+
+			if (type.HasMethods)
+				AddMethods (type);
+
+			if (type.HasProperties)
+				AddProperties (type);
+
+			if (type.HasEvents)
+				AddEvents (type);
+
+			if (type.HasCustomAttributes)
+				AddCustomAttributes (type);
+
+			if (type.HasSecurityDeclarations)
+				AddSecurityDeclarations (type);
+
+			if (type.HasNestedTypes)
+				AddNestedTypes (type);
+		}
+
+		void AddGenericParameters (IGenericParameterProvider owner)
+		{
+			var parameters = owner.GenericParameters;
+
+			for (int i = 0; i < parameters.Count; i++)
+				generic_parameters.Add (parameters [i]);
+		}
+
+		sealed class GenericParameterComparer : IComparer<GenericParameter> {
+
+			public int Compare (GenericParameter a, GenericParameter b)
+			{
+				var a_owner = MakeCodedRID (a.Owner, CodedIndex.TypeOrMethodDef);
+				var b_owner = MakeCodedRID (b.Owner, CodedIndex.TypeOrMethodDef);
+				if (a_owner == b_owner) {
+					var a_pos = a.Position;
+					var b_pos = b.Position;
+					return a_pos == b_pos ? 0 : a_pos > b_pos ? 1 : -1;
+				}
+
+				return a_owner > b_owner ? 1 : -1;
+			}
+		}
+
+		void AddGenericParameters ()
+		{
+			var items = this.generic_parameters.items;
+			var size = this.generic_parameters.size;
+			Array.Sort (items, 0, size, new GenericParameterComparer ());
+
+			var generic_param_table = GetTable<GenericParamTable> (Table.GenericParam);
+			var generic_param_constraint_table = GetTable<GenericParamConstraintTable> (Table.GenericParamConstraint);
+
+			for (int i = 0; i < size; i++) {
+				var generic_parameter = items [i];
+
+				var rid = generic_param_table.AddRow (new GenericParamRow (
+					(ushort) generic_parameter.Position,
+					generic_parameter.Attributes,
+					MakeCodedRID (generic_parameter.Owner, CodedIndex.TypeOrMethodDef),
+					GetStringIndex (generic_parameter.Name)));
+
+				generic_parameter.token = new MetadataToken (TokenType.GenericParam, rid);
+
+				if (generic_parameter.HasConstraints)
+					AddConstraints (generic_parameter, generic_param_constraint_table);
+
+				if (generic_parameter.HasCustomAttributes)
+					AddCustomAttributes (generic_parameter);
+			}
+		}
+
+		void AddConstraints (GenericParameter generic_parameter, GenericParamConstraintTable table)
+		{
+			var constraints = generic_parameter.Constraints;
+
+			var rid = generic_parameter.token.RID;
+
+			for (int i = 0; i < constraints.Count; i++)
+				table.AddRow (new GenericParamConstraintRow (
+					rid,
+					MakeCodedRID (GetTypeToken (constraints [i]), CodedIndex.TypeDefOrRef)));
+		}
+
+		void AddInterfaces (TypeDefinition type)
+		{
+			var interfaces = type.Interfaces;
+			var type_rid = type.token.RID;
+
+			for (int i = 0; i < interfaces.Count; i++)
+				iface_impl_table.AddRow (new InterfaceImplRow (
+					type_rid,
+					MakeCodedRID (GetTypeToken (interfaces [i]), CodedIndex.TypeDefOrRef)));
+		}
+
+		void AddLayoutInfo (TypeDefinition type)
+		{
+			var table = GetTable<ClassLayoutTable> (Table.ClassLayout);
+
+			table.AddRow (new ClassLayoutRow (
+				(ushort) type.PackingSize,
+				(uint) type.ClassSize,
+				type.token.RID));
+		}
+
+		void AddNestedTypes (TypeDefinition type)
+		{
+			var nested_types = type.NestedTypes;
+			var nested_table = GetTable<NestedClassTable> (Table.NestedClass);
+
+			for (int i = 0; i < nested_types.Count; i++) {
+				var nested = nested_types [i];
+				AddType (nested);
+				nested_table.AddRow (new NestedClassRow (nested.token.RID, type.token.RID));
+			}
+		}
+
+		void AddFields (TypeDefinition type)
+		{
+			var fields = type.Fields;
+
+			for (int i = 0; i < fields.Count; i++)
+				AddField (fields [i]);
+		}
+
+		void AddField (FieldDefinition field)
+		{
+			field_table.AddRow (new FieldRow (
+				field.Attributes,
+				GetStringIndex (field.Name),
+				GetBlobIndex (GetFieldSignature (field))));
+
+			if (!field.InitialValue.IsNullOrEmpty ())
+				AddFieldRVA (field);
+
+			if (field.HasLayoutInfo)
+				AddFieldLayout (field);
+
+			if (field.HasCustomAttributes)
+				AddCustomAttributes (field);
+
+			if (field.HasConstant)
+				AddConstant (field, field.FieldType);
+
+			if (field.HasMarshalInfo)
+				AddMarshalInfo (field);
+		}
+
+		void AddFieldRVA (FieldDefinition field)
+		{
+			var table = GetTable<FieldRVATable> (Table.FieldRVA);
+			table.AddRow (new FieldRVARow (
+				data.AddData (field.InitialValue),
+				field.token.RID));
+		}
+
+		void AddFieldLayout (FieldDefinition field)
+		{
+			var table = GetTable<FieldLayoutTable> (Table.FieldLayout);
+			table.AddRow (new FieldLayoutRow ((uint) field.Offset, field.token.RID));
+		}
+
+		void AddMethods (TypeDefinition type)
+		{
+			var methods = type.Methods;
+
+			for (int i = 0; i < methods.Count; i++)
+				AddMethod (methods [i]);
+		}
+
+		void AddMethod (MethodDefinition method)
+		{
+			method_table.AddRow (new MethodRow (
+				method.HasBody ? code.WriteMethodBody (method) : 0,
+				method.ImplAttributes,
+				method.Attributes,
+				GetStringIndex (method.Name),
+				GetBlobIndex (GetMethodSignature (method)),
+				param_rid));
+
+			AddParameters (method);
+
+			if (method.HasGenericParameters)
+				AddGenericParameters (method);
+
+			if (method.IsPInvokeImpl)
+				AddPInvokeInfo (method);
+
+			if (method.HasCustomAttributes)
+				AddCustomAttributes (method);
+
+			if (method.HasSecurityDeclarations)
+				AddSecurityDeclarations (method);
+
+			if (method.HasOverrides)
+				AddOverrides (method);
+		}
+
+		void AddParameters (MethodDefinition method)
+		{
+			var return_parameter = method.MethodReturnType.parameter;
+
+			if (return_parameter != null && RequiresParameterRow (return_parameter))
+				AddParameter (0, return_parameter, param_table);
+
+			if (!method.HasParameters)
+				return;
+
+			var parameters = method.Parameters;
+
+			for (int i = 0; i < parameters.Count; i++) {
+				var parameter = parameters [i];
+				if (!RequiresParameterRow (parameter))
+					continue;
+
+				AddParameter ((ushort) (i + 1), parameter, param_table);
+			}
+		}
+
+		void AddPInvokeInfo (MethodDefinition method)
+		{
+			var pinvoke = method.PInvokeInfo;
+			if (pinvoke == null)
+				throw new ArgumentException ();
+
+			var table = GetTable<ImplMapTable> (Table.ImplMap);
+			table.AddRow (new ImplMapRow (
+				pinvoke.Attributes,
+				MakeCodedRID (method, CodedIndex.MemberForwarded),
+				GetStringIndex (pinvoke.EntryPoint),
+				pinvoke.Module.MetadataToken.RID));
+		}
+
+		void AddOverrides (MethodDefinition method)
+		{
+			var overrides = method.Overrides;
+			var table = GetTable<MethodImplTable> (Table.MethodImpl);
+
+			for (int i = 0; i < overrides.Count; i++) {
+				table.AddRow (new MethodImplRow (
+					method.DeclaringType.token.RID,
+					MakeCodedRID (method, CodedIndex.MethodDefOrRef),
+					MakeCodedRID (LookupToken (overrides [i]), CodedIndex.MethodDefOrRef)));
+			}
+		}
+
+		static bool RequiresParameterRow (ParameterDefinition parameter)
+		{
+			return !string.IsNullOrEmpty (parameter.Name)
+				|| parameter.Attributes != ParameterAttributes.None
+				|| parameter.HasMarshalInfo
+				|| parameter.HasConstant
+				|| parameter.HasCustomAttributes;
+		}
+
+		void AddParameter (ushort sequence, ParameterDefinition parameter, ParamTable table)
+		{
+			table.AddRow (new ParamRow (
+				parameter.Attributes,
+				sequence,
+				GetStringIndex (parameter.Name)));
+
+			parameter.token = new MetadataToken (TokenType.Param, param_rid++);
+
+			if (parameter.HasCustomAttributes)
+				AddCustomAttributes (parameter);
+
+			if (parameter.HasConstant)
+				AddConstant (parameter, parameter.ParameterType);
+
+			if (parameter.HasMarshalInfo)
+				AddMarshalInfo (parameter);
+		}
+
+		void AddMarshalInfo (IMarshalInfoProvider owner)
+		{
+			var table = GetTable<FieldMarshalTable> (Table.FieldMarshal);
+
+			table.AddRow (new FieldMarshalRow (
+				MakeCodedRID (owner, CodedIndex.HasFieldMarshal),
+				GetBlobIndex (GetMarshalInfoSignature (owner))));
+		}
+
+		void AddProperties (TypeDefinition type)
+		{
+			var properties = type.Properties;
+
+			property_map_table.AddRow (new PropertyMapRow (type.token.RID, property_rid));
+
+			for (int i = 0; i < properties.Count; i++)
+				AddProperty (properties [i]);
+		}
+
+		void AddProperty (PropertyDefinition property)
+		{
+			property_table.AddRow (new PropertyRow (
+				property.Attributes,
+				GetStringIndex (property.Name),
+				GetBlobIndex (GetPropertySignature (property))));
+			property.token = new MetadataToken (TokenType.Property, property_rid++);
+
+			var method = property.GetMethod;
+			if (method != null)
+				AddSemantic (MethodSemanticsAttributes.Getter, property, method);
+
+			method = property.SetMethod;
+			if (method != null)
+				AddSemantic (MethodSemanticsAttributes.Setter, property, method);
+
+			if (property.HasOtherMethods)
+				AddOtherSemantic (property, property.OtherMethods);
+
+			if (property.HasCustomAttributes)
+				AddCustomAttributes (property);
+
+			if (property.HasConstant)
+				AddConstant (property, property.PropertyType);
+		}
+
+		void AddOtherSemantic (IMetadataTokenProvider owner, Collection<MethodDefinition> others)
+		{
+			for (int i = 0; i < others.Count; i++)
+				AddSemantic (MethodSemanticsAttributes.Other, owner, others [i]);
+		}
+
+		void AddEvents (TypeDefinition type)
+		{
+			var events = type.Events;
+
+			event_map_table.AddRow (new EventMapRow (type.token.RID, event_rid));
+
+			for (int i = 0; i < events.Count; i++)
+				AddEvent (events [i]);
+		}
+
+		void AddEvent (EventDefinition @event)
+		{
+			event_table.AddRow (new EventRow (
+				@event.Attributes,
+				GetStringIndex (@event.Name),
+				MakeCodedRID (GetTypeToken (@event.EventType), CodedIndex.TypeDefOrRef)));
+			@event.token = new MetadataToken (TokenType.Event, event_rid++);
+
+			var method = @event.AddMethod;
+			if (method != null)
+				AddSemantic (MethodSemanticsAttributes.AddOn, @event, method);
+
+			method = @event.InvokeMethod;
+			if (method != null)
+				AddSemantic (MethodSemanticsAttributes.Fire, @event, method);
+
+			method = @event.RemoveMethod;
+			if (method != null)
+				AddSemantic (MethodSemanticsAttributes.RemoveOn, @event, method);
+
+			if (@event.HasOtherMethods)
+				AddOtherSemantic (@event, @event.OtherMethods);
+
+			if (@event.HasCustomAttributes)
+				AddCustomAttributes (@event);
+		}
+
+		void AddSemantic (MethodSemanticsAttributes semantics, IMetadataTokenProvider provider, MethodDefinition method)
+		{
+			method.SemanticsAttributes = semantics;
+			var table = GetTable<MethodSemanticsTable> (Table.MethodSemantics);
+
+			table.AddRow (new MethodSemanticsRow (
+				semantics,
+				method.token.RID,
+				MakeCodedRID (provider, CodedIndex.HasSemantics)));
+		}
+
+		void AddConstant (IConstantProvider owner, TypeReference type)
+		{
+			var constant = owner.Constant;
+			var etype = GetConstantType (type, constant);
+
+			constant_table.AddRow (new ConstantRow (
+				etype,
+				MakeCodedRID (owner.MetadataToken, CodedIndex.HasConstant),
+				GetBlobIndex (GetConstantSignature (etype, constant))));
+		}
+
+		static ElementType GetConstantType (TypeReference constant_type, object constant)
+		{
+			if (constant == null)
+				return ElementType.Class;
+
+			var etype = constant_type.etype;
+			switch (etype) {
+			case ElementType.None:
+				var type = constant_type.CheckedResolve ();
+				if (type.IsEnum)
+					return GetConstantType (type.GetEnumUnderlyingType (), constant);
+
+				return ElementType.Class;
+			case ElementType.String:
+				return ElementType.String;
+			case ElementType.Object:
+				return GetConstantType (constant.GetType ());
+			case ElementType.Array:
+			case ElementType.SzArray:
+			case ElementType.MVar:
+			case ElementType.Var:
+				return ElementType.Class;
+			case ElementType.GenericInst:
+			case ElementType.CModOpt:
+			case ElementType.CModReqD:
+			case ElementType.ByRef:
+			case ElementType.Sentinel:
+				return GetConstantType (((TypeSpecification) constant_type).ElementType, constant);
+			case ElementType.Boolean:
+			case ElementType.Char:
+			case ElementType.I:
+			case ElementType.I1:
+			case ElementType.I2:
+			case ElementType.I4:
+			case ElementType.I8:
+			case ElementType.U:
+			case ElementType.U1:
+			case ElementType.U2:
+			case ElementType.U4:
+			case ElementType.U8:
+			case ElementType.R4:
+			case ElementType.R8:
+				return GetConstantType (constant.GetType ());
+			default:
+				return etype;
+			}
+		}
+
+		static ElementType GetConstantType (Type type)
+		{
+			switch (Type.GetTypeCode (type)) {
+			case TypeCode.Boolean:
+				return ElementType.Boolean;
+			case TypeCode.Byte:
+				return ElementType.U1;
+			case TypeCode.SByte:
+				return ElementType.I1;
+			case TypeCode.Char:
+				return ElementType.Char;
+			case TypeCode.Int16:
+				return ElementType.I2;
+			case TypeCode.UInt16:
+				return ElementType.U2;
+			case TypeCode.Int32:
+				return ElementType.I4;
+			case TypeCode.UInt32:
+				return ElementType.U4;
+			case TypeCode.Int64:
+				return ElementType.I8;
+			case TypeCode.UInt64:
+				return ElementType.U8;
+			case TypeCode.Single:
+				return ElementType.R4;
+			case TypeCode.Double:
+				return ElementType.R8;
+			case TypeCode.String:
+				return ElementType.String;
+			default:
+				throw new NotSupportedException (type.FullName);
+			}
+		}
+
+		void AddCustomAttributes (ICustomAttributeProvider owner)
+		{
+			var custom_attributes = owner.CustomAttributes;
+
+			for (int i = 0; i < custom_attributes.Count; i++) {
+				var attribute = custom_attributes [i];
+
+				custom_attribute_table.AddRow (new CustomAttributeRow (
+					MakeCodedRID (owner, CodedIndex.HasCustomAttribute),
+					MakeCodedRID (LookupToken (attribute.Constructor), CodedIndex.CustomAttributeType),
+					GetBlobIndex (GetCustomAttributeSignature (attribute))));
+			}
+		}
+
+		void AddSecurityDeclarations (ISecurityDeclarationProvider owner)
+		{
+			var declarations = owner.SecurityDeclarations;
+
+			for (int i = 0; i < declarations.Count; i++) {
+				var declaration = declarations [i];
+
+				declsec_table.AddRow (new DeclSecurityRow (
+					declaration.Action,
+					MakeCodedRID (owner, CodedIndex.HasDeclSecurity),
+					GetBlobIndex (GetSecurityDeclarationSignature (declaration))));
+			}
+		}
+
+		MetadataToken GetMemberRefToken (MemberReference member)
+		{
+			var row = CreateMemberRefRow (member);
+
+			MetadataToken token;
+			if (member_ref_map.TryGetValue (row, out token))
+				return token;
+
+			AddMemberReference (member, row);
+
+			return member.token;
+		}
+
+		MemberRefRow CreateMemberRefRow (MemberReference member)
+		{
+			return new MemberRefRow (
+				MakeCodedRID (GetTypeToken (member.DeclaringType), CodedIndex.MemberRefParent),
+				GetStringIndex (member.Name),
+				GetBlobIndex (GetMemberRefSignature (member)));
+		}
+
+		void AddMemberReference (MemberReference member, MemberRefRow row)
+		{
+			member.token = new MetadataToken (TokenType.MemberRef, member_ref_table.AddRow (row));
+			member_ref_map.Add (row, member.token);
+		}
+
+		MetadataToken GetMethodSpecToken (MethodSpecification method_spec)
+		{
+			var row = CreateMethodSpecRow (method_spec);
+
+			MetadataToken token;
+			if (method_spec_map.TryGetValue (row, out token))
+				return token;
+
+			AddMethodSpecification (method_spec, row);
+
+			return method_spec.token;
+		}
+
+		void AddMethodSpecification (MethodSpecification method_spec, MethodSpecRow row)
+		{
+			method_spec.token = new MetadataToken (TokenType.MethodSpec, method_spec_table.AddRow (row));
+			method_spec_map.Add (row, method_spec.token);
+		}
+
+		MethodSpecRow CreateMethodSpecRow (MethodSpecification method_spec)
+		{
+			return new MethodSpecRow (
+				MakeCodedRID (LookupToken (method_spec.ElementMethod), CodedIndex.MethodDefOrRef),
+				GetBlobIndex (GetMethodSpecSignature (method_spec)));
+		}
+
+		SignatureWriter CreateSignatureWriter ()
+		{
+			return new SignatureWriter (this);
+		}
+
+		SignatureWriter GetMethodSpecSignature (MethodSpecification method_spec)
+		{
+			if (!method_spec.IsGenericInstance)
+				throw new NotSupportedException ();
+
+			var generic_instance = (GenericInstanceMethod) method_spec;
+
+			var signature = CreateSignatureWriter ();
+			signature.WriteByte (0x0a);
+
+			signature.WriteGenericInstanceSignature (generic_instance);
+
+			return signature;
+		}
+
+		public uint AddStandAloneSignature (uint signature)
+		{
+			return (uint) standalone_sig_table.AddRow (signature);
+		}
+
+		public uint GetLocalVariableBlobIndex (Collection<VariableDefinition> variables)
+		{
+			return GetBlobIndex (GetVariablesSignature (variables));
+		}
+
+		public uint GetCallSiteBlobIndex (CallSite call_site)
+		{
+			return GetBlobIndex (GetMethodSignature (call_site));
+		}
+
+		SignatureWriter GetVariablesSignature (Collection<VariableDefinition> variables)
+		{
+			var signature = CreateSignatureWriter ();
+			signature.WriteByte (0x7);
+			signature.WriteCompressedUInt32 ((uint) variables.Count);
+			for (int i = 0; i < variables.Count; i++)
+				signature.WriteTypeSignature (variables [i].VariableType);
+			return signature;
+		}
+
+		SignatureWriter GetFieldSignature (FieldReference field)
+		{
+			var signature = CreateSignatureWriter ();
+			signature.WriteByte (0x6);
+			signature.WriteTypeSignature (field.FieldType);
+			return signature;
+		}
+
+		SignatureWriter GetMethodSignature (IMethodSignature method)
+		{
+			var signature = CreateSignatureWriter ();
+			signature.WriteMethodSignature (method);
+			return signature;
+		}
+
+		SignatureWriter GetMemberRefSignature (MemberReference member)
+		{
+			var field = member as FieldReference;
+			if (field != null)
+				return GetFieldSignature (field);
+
+			var method = member as MethodReference;
+			if (method != null)
+				return GetMethodSignature (method);
+
+			throw new NotSupportedException ();
+		}
+
+		SignatureWriter GetPropertySignature (PropertyDefinition property)
+		{
+			var signature = CreateSignatureWriter ();
+			byte calling_convention = 0x8;
+			if (property.HasThis)
+				calling_convention |= 0x20;
+
+			uint param_count = 0;
+			Collection<ParameterDefinition> parameters = null;
+
+			if (property.HasParameters) {
+				parameters = property.Parameters;
+				param_count = (uint) parameters.Count;
+			}
+
+			signature.WriteByte (calling_convention);
+			signature.WriteCompressedUInt32 (param_count);
+			signature.WriteTypeSignature (property.PropertyType);
+
+			if (param_count == 0)
+				return signature;
+
+			for (int i = 0; i < param_count; i++)
+				signature.WriteTypeSignature (parameters [i].ParameterType);
+
+			return signature;
+		}
+
+		SignatureWriter GetTypeSpecSignature (TypeReference type)
+		{
+			var signature = CreateSignatureWriter ();
+			signature.WriteTypeSignature (type);
+			return signature;
+		}
+
+		SignatureWriter GetConstantSignature (ElementType type, object value)
+		{
+			var signature = CreateSignatureWriter ();
+
+			switch (type) {
+			case ElementType.Array:
+			case ElementType.SzArray:
+			case ElementType.Class:
+			case ElementType.Object:
+			case ElementType.Var:
+			case ElementType.MVar:
+				signature.WriteInt32 (0);
+				break;
+			case ElementType.String:
+				signature.WriteConstantString ((string) value);
+				break;
+			default:
+				signature.WriteConstantPrimitive (value);
+				break;
+			}
+
+			return signature;
+		}
+
+		SignatureWriter GetCustomAttributeSignature (CustomAttribute attribute)
+		{
+			var signature = CreateSignatureWriter ();
+			if (!attribute.resolved) {
+				signature.WriteBytes (attribute.GetBlob ());
+				return signature;
+			}
+
+			signature.WriteUInt16 (0x0001);
+
+			signature.WriteCustomAttributeConstructorArguments (attribute);
+
+			signature.WriteCustomAttributeNamedArguments (attribute);
+
+			return signature;
+		}
+
+		SignatureWriter GetSecurityDeclarationSignature (SecurityDeclaration declaration)
+		{
+			var signature = CreateSignatureWriter ();
+
+			if (!declaration.resolved)
+				signature.WriteBytes (declaration.GetBlob ());
+			else if (module.Runtime < TargetRuntime.Net_2_0)
+				signature.WriteXmlSecurityDeclaration (declaration);
+			else
+				signature.WriteSecurityDeclaration (declaration);
+
+			return signature;
+		}
+
+		SignatureWriter GetMarshalInfoSignature (IMarshalInfoProvider owner)
+		{
+			var signature = CreateSignatureWriter ();
+
+			signature.WriteMarshalInfo (owner.MarshalInfo);
+
+			return signature;
+		}
+
+		static Exception CreateForeignMemberException (MemberReference member)
+		{
+			return new ArgumentException (string.Format ("Member '{0}' is declared in another module and needs to be imported", member));
+		}
+
+		public MetadataToken LookupToken (IMetadataTokenProvider provider)
+		{
+			if (provider == null)
+				throw new ArgumentNullException ();
+
+			var member = provider as MemberReference;
+			if (member == null || member.Module != module)
+				throw CreateForeignMemberException (member);
+
+			var token = provider.MetadataToken;
+
+			switch (token.TokenType) {
+			case TokenType.TypeDef:
+			case TokenType.Method:
+			case TokenType.Field:
+			case TokenType.Event:
+			case TokenType.Property:
+				return token;
+			case TokenType.TypeRef:
+			case TokenType.TypeSpec:
+			case TokenType.GenericParam:
+				return GetTypeToken ((TypeReference) provider);
+			case TokenType.MethodSpec:
+				return GetMethodSpecToken ((MethodSpecification) provider);
+			case TokenType.MemberRef:
+				return GetMemberRefToken (member);
+			default:
+				throw new NotSupportedException ();
+			}
+		}
+	}
+
+	sealed class SignatureWriter : ByteBuffer {
+
+		readonly MetadataBuilder metadata;
+
+		public SignatureWriter (MetadataBuilder metadata)
+			: base (6)
+		{
+			this.metadata = metadata;
+		}
+
+		public void WriteElementType (ElementType element_type)
+		{
+			WriteByte ((byte) element_type);
+		}
+
+		public void WriteUTF8String (string @string)
+		{
+			if (@string == null) {
+				WriteByte (0xff);
+				return;
+			}
+
+			var bytes = Encoding.UTF8.GetBytes (@string);
+			WriteCompressedUInt32 ((uint) bytes.Length);
+			WriteBytes (bytes);
+		}
+
+		public void WriteMethodSignature (IMethodSignature method)
+		{
+			byte calling_convention = (byte) method.CallingConvention;
+			if (method.HasThis)
+				calling_convention |= 0x20;
+			if (method.ExplicitThis)
+				calling_convention |= 0x40;
+
+			var generic_provider = method as IGenericParameterProvider;
+			var generic_arity = generic_provider != null && generic_provider.HasGenericParameters
+				? generic_provider.GenericParameters.Count
+				: 0;
+
+			if (generic_arity > 0)
+				calling_convention |= 0x10;
+
+			var param_count = method.HasParameters ? method.Parameters.Count : 0;
+
+			WriteByte (calling_convention);
+
+			if (generic_arity > 0)
+				WriteCompressedUInt32 ((uint) generic_arity);
+
+			WriteCompressedUInt32 ((uint) param_count);
+			WriteTypeSignature (method.ReturnType);
+
+			if (param_count == 0)
+				return;
+
+			var parameters = method.Parameters;
+
+			for (int i = 0; i < param_count; i++)
+				WriteTypeSignature (parameters [i].ParameterType);
+		}
+
+		uint MakeTypeDefOrRefCodedRID (TypeReference type)
+		{
+			return CodedIndex.TypeDefOrRef.CompressMetadataToken (metadata.LookupToken (type));
+		}
+
+		public void WriteTypeSignature (TypeReference type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ();
+
+			var etype = type.etype;
+
+			switch (etype) {
+			case ElementType.MVar:
+			case ElementType.Var: {
+				var generic_parameter = (GenericParameter) type;
+
+				WriteElementType (etype);
+				var position = generic_parameter.Position;
+				if (position == -1)
+					throw new NotSupportedException ();
+
+				WriteCompressedUInt32 ((uint) position);
+				break;
+			}
+
+			case ElementType.GenericInst: {
+				var generic_instance = (GenericInstanceType) type;
+				WriteElementType (ElementType.GenericInst);
+				WriteElementType (generic_instance.IsValueType ? ElementType.ValueType : ElementType.Class);
+				WriteCompressedUInt32 (MakeTypeDefOrRefCodedRID (generic_instance.ElementType));
+
+				WriteGenericInstanceSignature (generic_instance);
+				break;
+			}
+
+			case ElementType.Ptr:
+			case ElementType.ByRef:
+			case ElementType.Pinned:
+			case ElementType.Sentinel: {
+				var type_spec = (TypeSpecification) type;
+				WriteElementType (etype);
+				WriteTypeSignature (type_spec.ElementType);
+				break;
+			}
+
+			case ElementType.FnPtr: {
+				var fptr = (FunctionPointerType) type;
+				WriteElementType (ElementType.FnPtr);
+				WriteMethodSignature (fptr);
+				break;
+			}
+
+			case ElementType.CModOpt:
+			case ElementType.CModReqD: {
+				var modifier = (IModifierType) type;
+				WriteModifierSignature (etype, modifier);
+				break;
+			}
+
+			case ElementType.Array: {
+				var array = (ArrayType) type;
+				if (!array.IsVector) {
+					WriteArrayTypeSignature (array);
+					break;
+				}
+
+				WriteElementType (ElementType.SzArray);
+				WriteTypeSignature (array.ElementType);
+				break;
+			}
+
+			case ElementType.None: {
+				WriteElementType (type.IsValueType ? ElementType.ValueType : ElementType.Class);
+				WriteCompressedUInt32 (MakeTypeDefOrRefCodedRID (type));
+				break;
+			}
+
+			default:
+				if (!TryWriteElementType (type))
+					throw new NotSupportedException ();
+
+				break;
+
+			}
+		}
+
+		void WriteArrayTypeSignature (ArrayType array)
+		{
+			WriteElementType (ElementType.Array);
+			WriteTypeSignature (array.ElementType);
+
+			var dimensions = array.Dimensions;
+			var rank = dimensions.Count;
+
+			WriteCompressedUInt32 ((uint) rank);
+
+			var sized = 0;
+			var lbounds = 0;
+
+			for (int i = 0; i < rank; i++) {
+				var dimension = dimensions [i];
+
+				if (dimension.UpperBound.HasValue) {
+					sized++;
+					lbounds++;
+				} else if (dimension.LowerBound.HasValue)
+					lbounds++;
+			}
+
+			var sizes = new int [sized];
+			var low_bounds = new int [lbounds];
+
+			for (int i = 0; i < lbounds; i++) {
+				var dimension = dimensions [i];
+				low_bounds [i] = dimension.LowerBound.GetValueOrDefault ();
+				if (dimension.UpperBound.HasValue)
+					sizes [i] = dimension.UpperBound.Value - low_bounds [i] + 1;
+			}
+
+			WriteCompressedUInt32 ((uint) sized);
+			for (int i = 0; i < sized; i++)
+				WriteCompressedUInt32 ((uint) sizes [i]);
+
+			WriteCompressedUInt32 ((uint) lbounds);
+			for (int i = 0; i < lbounds; i++)
+				WriteCompressedInt32 (low_bounds [i]);
+		}
+
+		public void WriteGenericInstanceSignature (IGenericInstance instance)
+		{
+			var generic_arguments = instance.GenericArguments;
+			var arity = generic_arguments.Count;
+
+			WriteCompressedUInt32 ((uint) arity);
+			for (int i = 0; i < arity; i++)
+				WriteTypeSignature (generic_arguments [i]);
+		}
+
+		void WriteModifierSignature (ElementType element_type, IModifierType type)
+		{
+			WriteElementType (element_type);
+			WriteCompressedUInt32 (MakeTypeDefOrRefCodedRID (type.ModifierType));
+			WriteTypeSignature (type.ElementType);
+		}
+
+		bool TryWriteElementType (TypeReference type)
+		{
+			var element = type.etype;
+
+			if (element == ElementType.None)
+				return false;
+
+			WriteElementType (element);
+			return true;
+		}
+
+		public void WriteConstantString (string value)
+		{
+			WriteBytes (Encoding.Unicode.GetBytes (value));
+		}
+
+		public void WriteConstantPrimitive (object value)
+		{
+			WritePrimitiveValue (value);
+		}
+
+		public void WriteCustomAttributeConstructorArguments (CustomAttribute attribute)
+		{
+			if (!attribute.HasConstructorArguments)
+				return;
+
+			var arguments = attribute.ConstructorArguments;
+			var parameters = attribute.Constructor.Parameters;
+
+			if (parameters.Count != arguments.Count)
+				throw new InvalidOperationException ();
+
+			for (int i = 0; i < arguments.Count; i++)
+				WriteCustomAttributeFixedArgument (parameters [i].ParameterType, arguments [i]);
+		}
+
+		void WriteCustomAttributeFixedArgument (TypeReference type, CustomAttributeArgument argument)
+		{
+			if (type.IsArray) {
+				WriteCustomAttributeFixedArrayArgument ((ArrayType) type, argument);
+				return;
+			}
+
+			WriteCustomAttributeElement (type, argument);
+		}
+
+		void WriteCustomAttributeFixedArrayArgument (ArrayType type, CustomAttributeArgument argument)
+		{
+			var values = argument.Value as CustomAttributeArgument [];
+
+			if (values == null) {
+				WriteUInt32 (0xffffffff);
+				return;
+			}
+
+			WriteInt32 (values.Length);
+
+			if (values.Length == 0)
+				return;
+
+			var element_type = type.ElementType;
+
+			for (int i = 0; i < values.Length; i++)
+				WriteCustomAttributeElement (element_type, values [i]);
+		}
+
+		void WriteCustomAttributeElement (TypeReference type, CustomAttributeArgument argument)
+		{
+			if (type.IsArray) {
+				WriteCustomAttributeFixedArrayArgument ((ArrayType) type, argument);
+				return;
+			}
+
+			if (type.etype == ElementType.Object) {
+				argument = (CustomAttributeArgument) argument.Value;
+				type = argument.Type;
+
+				WriteCustomAttributeFieldOrPropType (type);
+				WriteCustomAttributeElement (type, argument);
+				return;
+			}
+
+			WriteCustomAttributeValue (type, argument.Value);
+		}
+
+		void WriteCustomAttributeValue (TypeReference type, object value)
+		{
+			var etype = type.etype;
+
+			switch (etype) {
+			case ElementType.String:
+				var @string = (string) value;
+				if (@string == null)
+					WriteByte (0xff);
+				else
+					WriteUTF8String (@string);
+				break;
+			case ElementType.None:
+				if (type.IsTypeOf ("System", "Type"))
+					WriteTypeReference ((TypeReference) value);
+				else
+					WriteCustomAttributeEnumValue (type, value);
+				break;
+			default:
+				WritePrimitiveValue (value);
+				break;
+			}
+		}
+
+		void WritePrimitiveValue (object value)
+		{
+			if (value == null)
+				throw new ArgumentNullException ();
+
+			switch (Type.GetTypeCode (value.GetType ())) {
+			case TypeCode.Boolean:
+				WriteByte ((byte) (((bool) value) ? 1 : 0));
+				break;
+			case TypeCode.Byte:
+				WriteByte ((byte) value);
+				break;
+			case TypeCode.SByte:
+				WriteSByte ((sbyte) value);
+				break;
+			case TypeCode.Int16:
+				WriteInt16 ((short) value);
+				break;
+			case TypeCode.UInt16:
+				WriteUInt16 ((ushort) value);
+				break;
+			case TypeCode.Char:
+				WriteInt16 ((short) (char) value);
+				break;
+			case TypeCode.Int32:
+				WriteInt32 ((int) value);
+				break;
+			case TypeCode.UInt32:
+				WriteUInt32 ((uint) value);
+				break;
+			case TypeCode.Single:
+				WriteSingle ((float) value);
+				break;
+			case TypeCode.Int64:
+				WriteInt64 ((long) value);
+				break;
+			case TypeCode.UInt64:
+				WriteUInt64 ((ulong) value);
+				break;
+			case TypeCode.Double:
+				WriteDouble ((double) value);
+				break;
+			default:
+				throw new NotSupportedException (value.GetType ().FullName);
+			}
+		}
+
+		void WriteCustomAttributeEnumValue (TypeReference enum_type, object value)
+		{
+			var type = enum_type.CheckedResolve ();
+			if (!type.IsEnum)
+				throw new ArgumentException ();
+
+			WriteCustomAttributeValue (type.GetEnumUnderlyingType (), value);
+		}
+
+		void WriteCustomAttributeFieldOrPropType (TypeReference type)
+		{
+			if (type.IsArray) {
+				var array = (ArrayType) type;
+				WriteElementType (ElementType.SzArray);
+				WriteCustomAttributeFieldOrPropType (array.ElementType);
+				return;
+			}
+
+			var etype = type.etype;
+
+			switch (etype) {
+			case ElementType.Object:
+				WriteElementType (ElementType.Boxed);
+				return;
+			case ElementType.None:
+				if (type.IsTypeOf ("System", "Type"))
+					WriteElementType (ElementType.Type);
+				else {
+					WriteElementType (ElementType.Enum);
+					WriteTypeReference (type);
+				}
+				return;
+			default:
+				WriteElementType (etype);
+				return;
+			}
+		}
+
+		public void WriteCustomAttributeNamedArguments (CustomAttribute attribute)
+		{
+			var count = GetNamedArgumentCount (attribute);
+
+			WriteUInt16 ((ushort) count);
+
+			if (count == 0)
+				return;
+
+			WriteICustomAttributeNamedArguments (attribute);
+		}
+
+		static int GetNamedArgumentCount (ICustomAttribute attribute)
+		{
+			int count = 0;
+
+			if (attribute.HasFields)
+				count += attribute.Fields.Count;
+
+			if (attribute.HasProperties)
+				count += attribute.Properties.Count;
+
+			return count;
+		}
+
+		void WriteICustomAttributeNamedArguments (ICustomAttribute attribute)
+		{
+			if (attribute.HasFields)
+				WriteCustomAttributeNamedArguments (0x53, attribute.Fields);
+
+			if (attribute.HasProperties)
+				WriteCustomAttributeNamedArguments (0x54, attribute.Properties);
+		}
+
+		void WriteCustomAttributeNamedArguments (byte kind, Collection<CustomAttributeNamedArgument> named_arguments)
+		{
+			for (int i = 0; i < named_arguments.Count; i++)
+				WriteCustomAttributeNamedArgument (kind, named_arguments [i]);
+		}
+
+		void WriteCustomAttributeNamedArgument (byte kind, CustomAttributeNamedArgument named_argument)
+		{
+			var argument = named_argument.Argument;
+
+			WriteByte (kind);
+			WriteCustomAttributeFieldOrPropType (argument.Type);
+			WriteUTF8String (named_argument.Name);
+			WriteCustomAttributeFixedArgument (argument.Type, argument);
+		}
+
+		void WriteSecurityAttribute (SecurityAttribute attribute)
+		{
+			WriteTypeReference (attribute.AttributeType);
+
+			var count = GetNamedArgumentCount (attribute);
+
+			if (count == 0) {
+				WriteCompressedUInt32 (0); // length
+				WriteCompressedUInt32 (0); // count
+				return;
+			}
+
+            var buffer = new SignatureWriter (metadata);
+			buffer.WriteCompressedUInt32 ((uint) count);
+			buffer.WriteICustomAttributeNamedArguments (attribute);
+
+			WriteCompressedUInt32 ((uint) buffer.length);
+			WriteBytes (buffer);
+		}
+
+		public void WriteSecurityDeclaration (SecurityDeclaration declaration)
+		{
+			WriteByte ((byte) '.');
+
+			var attributes = declaration.security_attributes;
+			if (attributes == null)
+				throw new NotSupportedException ();
+
+			WriteCompressedUInt32 ((uint) attributes.Count);
+
+			for (int i = 0; i < attributes.Count; i++)
+				WriteSecurityAttribute (attributes [i]);
+		}
+
+		public void WriteXmlSecurityDeclaration (SecurityDeclaration declaration)
+		{
+			var xml = GetXmlSecurityDeclaration (declaration);
+			if (xml == null)
+				throw new NotSupportedException ();
+
+			WriteBytes (Encoding.Unicode.GetBytes (xml));
+		}
+
+		static string GetXmlSecurityDeclaration (SecurityDeclaration declaration)
+		{
+			if (declaration.security_attributes == null || declaration.security_attributes.Count != 1)
+				return null;
+
+			var attribute = declaration.security_attributes [0];
+
+			if (!attribute.AttributeType.IsTypeOf ("System.Security.Permissions", "PermissionSetAttribute"))
+				return null;
+
+			if (attribute.properties == null || attribute.properties.Count != 1)
+				return null;
+
+			var property = attribute.properties [0];
+			if (property.Name != "XML")
+				return null;
+
+			return (string) property.Argument.Value;
+		}
+
+		void WriteTypeReference (TypeReference type)
+		{
+			WriteUTF8String (TypeParser.ToParseable (type));
+		}
+
+		public void WriteMarshalInfo (MarshalInfo marshal_info)
+		{
+			WriteNativeType (marshal_info.native);
+
+			switch (marshal_info.native) {
+			case NativeType.Array: {
+				var array = (ArrayMarshalInfo) marshal_info;
+				if (array.element_type != NativeType.None)
+					WriteNativeType (array.element_type);
+				if (array.size_parameter_index > -1)
+					WriteCompressedUInt32 ((uint) array.size_parameter_index);
+				if (array.size > -1)
+					WriteCompressedUInt32 ((uint) array.size);
+				if (array.size_parameter_multiplier > -1)
+					WriteCompressedUInt32 ((uint) array.size_parameter_multiplier);
+				return;
+			}
+			case NativeType.SafeArray: {
+				var array = (SafeArrayMarshalInfo) marshal_info;
+				if (array.element_type != VariantType.None)
+					WriteVariantType (array.element_type);
+				return;
+			}
+			case NativeType.FixedArray: {
+				var array = (FixedArrayMarshalInfo) marshal_info;
+				if (array.size > -1)
+					WriteCompressedUInt32 ((uint) array.size);
+				if (array.element_type != NativeType.None)
+					WriteNativeType (array.element_type);
+				return;
+			}
+			case NativeType.FixedSysString:
+				var sys_string = (FixedSysStringMarshalInfo) marshal_info;
+				if (sys_string.size > -1)
+					WriteCompressedUInt32 ((uint) sys_string.size);
+				return;
+			case NativeType.CustomMarshaler:
+				var marshaler = (CustomMarshalInfo) marshal_info;
+				WriteUTF8String (marshaler.guid != Guid.Empty ? marshaler.guid.ToString () : string.Empty);
+				WriteUTF8String (marshaler.unmanaged_type);
+				WriteTypeReference (marshaler.managed_type);
+				WriteUTF8String (marshaler.cookie);
+				return;
+			}
+		}
+
+		void WriteNativeType (NativeType native)
+		{
+			WriteByte ((byte) native);
+		}
+
+		void WriteVariantType (VariantType variant)
+		{
+			WriteByte ((byte) variant);
+		}
+	}
+
+#endif
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs	(revision 11807)
@@ -0,0 +1,351 @@
+//
+// BaseAssemblyResolver.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public delegate AssemblyDefinition AssemblyResolveEventHandler (object sender, AssemblyNameReference reference);
+
+	public sealed class AssemblyResolveEventArgs : EventArgs {
+
+		readonly AssemblyNameReference reference;
+
+		public AssemblyNameReference AssemblyReference {
+			get { return reference; }
+		}
+
+		public AssemblyResolveEventArgs (AssemblyNameReference reference)
+		{
+			this.reference = reference;
+		}
+	}
+
+	public class AssemblyResolutionException : FileNotFoundException {
+
+		readonly AssemblyNameReference reference;
+
+		public AssemblyNameReference AssemblyReference {
+			get { return reference; }
+		}
+
+		public AssemblyResolutionException (AssemblyNameReference reference)
+			: base (string.Format ("Failed to resolve assembly: '{0}'", reference))
+		{
+			this.reference = reference;
+		}
+	}
+
+	public abstract class BaseAssemblyResolver : IAssemblyResolver {
+
+		static readonly bool on_mono = Type.GetType ("Mono.Runtime") != null;
+
+		readonly Collection<string> directories;
+
+#if !SILVERLIGHT && !CF
+		Collection<string> gac_paths;
+#endif
+
+		public void AddSearchDirectory (string directory)
+		{
+			directories.Add (directory);
+		}
+
+		public void RemoveSearchDirectory (string directory)
+		{
+			directories.Remove (directory);
+		}
+
+		public string [] GetSearchDirectories ()
+		{
+			var directories = new string [this.directories.size];
+			Array.Copy (this.directories.items, directories, directories.Length);
+			return directories;
+		}
+
+		public virtual AssemblyDefinition Resolve (string fullName)
+		{
+			return Resolve (fullName, new ReaderParameters ());
+		}
+
+		public virtual AssemblyDefinition Resolve (string fullName, ReaderParameters parameters)
+		{
+			if (fullName == null)
+				throw new ArgumentNullException ("fullName");
+
+			return Resolve (AssemblyNameReference.Parse (fullName), parameters);
+		}
+
+		public event AssemblyResolveEventHandler ResolveFailure;
+
+		protected BaseAssemblyResolver ()
+		{
+			directories = new Collection<string> (2) { ".", "bin" };
+		}
+
+		AssemblyDefinition GetAssembly (string file, ReaderParameters parameters)
+		{
+			if (parameters.AssemblyResolver == null)
+				parameters.AssemblyResolver = this;
+
+			return ModuleDefinition.ReadModule (file, parameters).Assembly;
+		}
+
+		public virtual AssemblyDefinition Resolve (AssemblyNameReference name)
+		{
+			return Resolve (name, new ReaderParameters ());
+		}
+
+		public virtual AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters)
+		{
+			if (name == null)
+				throw new ArgumentNullException ("name");
+			if (parameters == null)
+				parameters = new ReaderParameters ();
+
+			var assembly = SearchDirectory (name, directories, parameters);
+			if (assembly != null)
+				return assembly;
+
+#if !SILVERLIGHT && !CF
+			var framework_dir = Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName);
+
+			if (IsZero (name.Version)) {
+				assembly = SearchDirectory (name, new [] { framework_dir }, parameters);
+				if (assembly != null)
+					return assembly;
+			}
+
+			if (name.Name == "mscorlib") {
+				assembly = GetCorlib (name, parameters);
+				if (assembly != null)
+					return assembly;
+			}
+
+			assembly = GetAssemblyInGac (name, parameters);
+			if (assembly != null)
+				return assembly;
+
+			assembly = SearchDirectory (name, new [] { framework_dir }, parameters);
+			if (assembly != null)
+				return assembly;
+#endif
+
+			if (ResolveFailure != null) {
+				assembly = ResolveFailure (this, name);
+				if (assembly != null)
+					return assembly;
+			}
+
+			throw new AssemblyResolutionException (name);
+		}
+
+		AssemblyDefinition SearchDirectory (AssemblyNameReference name, IEnumerable<string> directories, ReaderParameters parameters)
+		{
+			var extensions = new [] { ".exe", ".dll" };
+			foreach (var directory in directories) {
+				foreach (var extension in extensions) {
+					string file = Path.Combine (directory, name.Name + extension);
+					if (File.Exists (file))
+						return GetAssembly (file, parameters);
+				}
+			}
+
+			return null;
+		}
+
+		static bool IsZero (Version version)
+		{
+			return version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0 && version.Revision == 0);
+		}
+
+#if !SILVERLIGHT && !CF
+		AssemblyDefinition GetCorlib (AssemblyNameReference reference, ReaderParameters parameters)
+		{
+			var version = reference.Version;
+			var corlib = typeof (object).Assembly.GetName ();
+
+			if (corlib.Version == version || IsZero (version))
+				return GetAssembly (typeof (object).Module.FullyQualifiedName, parameters);
+
+			var path = Directory.GetParent (
+				Directory.GetParent (
+					typeof (object).Module.FullyQualifiedName).FullName
+				).FullName;
+
+			if (on_mono) {
+				if (version.Major == 1)
+					path = Path.Combine (path, "1.0");
+				else if (version.Major == 2) {
+					if (version.MajorRevision == 5)
+						path = Path.Combine (path, "2.1");
+					else
+						path = Path.Combine (path, "2.0");
+				} else if (version.Major == 4)
+					path = Path.Combine (path, "4.0");
+				else
+					throw new NotSupportedException ("Version not supported: " + version);
+			} else {
+				switch (version.Major) {
+				case 1:
+					if (version.MajorRevision == 3300)
+						path = Path.Combine (path, "v1.0.3705");
+					else
+						path = Path.Combine (path, "v1.0.5000.0");
+					break;
+				case 2:
+					path = Path.Combine (path, "v2.0.50727");
+					break;
+				case 4:
+					path = Path.Combine (path, "v4.0.30319");
+					break;
+				default:
+					throw new NotSupportedException ("Version not supported: " + version);
+				}
+			}
+
+			var file = Path.Combine (path, "mscorlib.dll");
+			if (File.Exists (file))
+				return GetAssembly (file, parameters);
+
+			return null;
+		}
+
+		static Collection<string> GetGacPaths ()
+		{
+			if (on_mono)
+				return GetDefaultMonoGacPaths ();
+
+			var paths = new Collection<string> (2);
+			var windir = Environment.GetEnvironmentVariable ("WINDIR");
+			if (windir == null)
+				return paths;
+
+			paths.Add (Path.Combine (windir, "assembly"));
+			paths.Add (Path.Combine (windir, Path.Combine ("Microsoft.NET", "assembly")));
+			return paths;
+		}
+
+		static Collection<string> GetDefaultMonoGacPaths ()
+		{
+			var paths = new Collection<string> (1);
+			var gac = GetCurrentMonoGac ();
+			if (gac != null)
+				paths.Add (gac);
+
+			var gac_paths_env = Environment.GetEnvironmentVariable ("MONO_GAC_PREFIX");
+			if (string.IsNullOrEmpty (gac_paths_env))
+				return paths;
+
+			var prefixes = gac_paths_env.Split (Path.PathSeparator);
+			foreach (var prefix in prefixes) {
+				if (string.IsNullOrEmpty (prefix))
+					continue;
+
+				var gac_path = Path.Combine (Path.Combine (Path.Combine (prefix, "lib"), "mono"), "gac");
+				if (Directory.Exists (gac_path) && !paths.Contains (gac))
+					paths.Add (gac_path);
+			}
+
+			return paths;
+		}
+
+		static string GetCurrentMonoGac ()
+		{
+			return Path.Combine (
+				Directory.GetParent (
+					Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName)).FullName,
+				"gac");
+		}
+
+		AssemblyDefinition GetAssemblyInGac (AssemblyNameReference reference, ReaderParameters parameters)
+		{
+			if (reference.PublicKeyToken == null || reference.PublicKeyToken.Length == 0)
+				return null;
+
+			if (gac_paths == null)
+				gac_paths = GetGacPaths ();
+
+			if (on_mono)
+				return GetAssemblyInMonoGac (reference, parameters);
+
+			return GetAssemblyInNetGac (reference, parameters);
+		}
+
+		AssemblyDefinition GetAssemblyInMonoGac (AssemblyNameReference reference, ReaderParameters parameters)
+		{
+			for (int i = 0; i < gac_paths.Count; i++) {
+				var gac_path = gac_paths [i];
+				var file = GetAssemblyFile (reference, string.Empty, gac_path);
+				if (File.Exists (file))
+					return GetAssembly (file, parameters);
+			}
+
+			return null;
+		}
+
+		AssemblyDefinition GetAssemblyInNetGac (AssemblyNameReference reference, ReaderParameters parameters)
+		{
+			var gacs = new [] { "GAC_MSIL", "GAC_32", "GAC" };
+			var prefixes = new [] { string.Empty, "v4.0_" };
+
+			for (int i = 0; i < 2; i++) {
+				for (int j = 0; j < gacs.Length; j++) {
+					var gac = Path.Combine (gac_paths [i], gacs [j]);
+					var file = GetAssemblyFile (reference, prefixes [i], gac);
+					if (Directory.Exists (gac) && File.Exists (file))
+						return GetAssembly (file, parameters);
+				}
+			}
+
+			return null;
+		}
+
+		static string GetAssemblyFile (AssemblyNameReference reference, string prefix, string gac)
+		{
+			var gac_folder = new StringBuilder ()
+				.Append (prefix)
+				.Append (reference.Version)
+				.Append ("__");
+
+			for (int i = 0; i < reference.PublicKeyToken.Length; i++)
+				gac_folder.Append (reference.PublicKeyToken [i].ToString ("x2"));
+
+			return Path.Combine (
+				Path.Combine (
+					Path.Combine (gac, reference.Name), gac_folder.ToString ()),
+				reference.Name + ".dll");
+		}
+#endif
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/CallSite.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/CallSite.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/CallSite.cs	(revision 11807)
@@ -0,0 +1,124 @@
+//
+// CallSite.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class CallSite : IMethodSignature {
+
+		readonly MethodReference signature;
+
+		public bool HasThis {
+			get { return signature.HasThis; }
+			set { signature.HasThis = value; }
+		}
+
+		public bool ExplicitThis {
+			get { return signature.ExplicitThis; }
+			set { signature.ExplicitThis = value; }
+		}
+
+		public MethodCallingConvention CallingConvention {
+			get { return signature.CallingConvention; }
+			set { signature.CallingConvention = value; }
+		}
+
+		public bool HasParameters {
+			get { return signature.HasParameters; }
+		}
+
+		public Collection<ParameterDefinition> Parameters {
+			get { return signature.Parameters; }
+		}
+
+		public TypeReference ReturnType {
+			get { return signature.MethodReturnType.ReturnType; }
+			set { signature.MethodReturnType.ReturnType = value; }
+		}
+
+		public MethodReturnType MethodReturnType {
+			get { return signature.MethodReturnType; }
+		}
+
+		public string Name {
+			get { return string.Empty; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public string Namespace {
+			get { return string.Empty; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public ModuleDefinition Module {
+			get { return ReturnType.Module; }
+		}
+
+		public IMetadataScope Scope {
+			get { return signature.ReturnType.Scope; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return signature.token; }
+			set { signature.token = value; }
+		}
+
+		public string FullName {
+			get {
+				var signature = new StringBuilder ();
+				signature.Append (ReturnType.FullName);
+				this.MethodSignatureFullName (signature);
+				return signature.ToString ();
+			}
+		}
+
+		internal CallSite ()
+		{
+			this.signature = new MethodReference ();
+			this.signature.token = new MetadataToken (TokenType.Signature, 0);
+		}
+
+		public CallSite (TypeReference returnType)
+			: this ()
+		{
+			if (returnType == null)
+				throw new ArgumentNullException ("returnType");
+
+			this.signature.ReturnType = returnType;
+		}
+
+		public override string ToString ()
+		{
+			return FullName;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/CustomAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/CustomAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/CustomAttribute.cs	(revision 11807)
@@ -0,0 +1,232 @@
+//
+// CustomAttribute.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public struct CustomAttributeArgument {
+
+		readonly TypeReference type;
+		readonly object value;
+
+		public TypeReference Type {
+			get { return type; }
+		}
+
+		public object Value {
+			get { return value; }
+		}
+
+		public CustomAttributeArgument (TypeReference type, object value)
+		{
+			Mixin.CheckType (type);
+			this.type = type;
+			this.value = value;
+		}
+	}
+
+	public struct CustomAttributeNamedArgument {
+
+		readonly string name;
+		readonly CustomAttributeArgument argument;
+
+		public string Name {
+			get { return name; }
+		}
+
+		public CustomAttributeArgument Argument {
+			get { return argument; }
+		}
+
+		public CustomAttributeNamedArgument (string name, CustomAttributeArgument argument)
+		{
+			Mixin.CheckName (name);
+			this.name = name;
+			this.argument = argument;
+		}
+	}
+
+	public interface ICustomAttribute {
+
+		TypeReference AttributeType { get; }
+
+		bool HasFields { get; }
+		bool HasProperties { get; }
+		Collection<CustomAttributeNamedArgument> Fields { get; }
+		Collection<CustomAttributeNamedArgument> Properties { get; }
+	}
+
+	public sealed class CustomAttribute : ICustomAttribute {
+
+		readonly internal uint signature;
+		internal bool resolved;
+		MethodReference constructor;
+		byte [] blob;
+		internal Collection<CustomAttributeArgument> arguments;
+		internal Collection<CustomAttributeNamedArgument> fields;
+		internal Collection<CustomAttributeNamedArgument> properties;
+
+		public MethodReference Constructor {
+			get { return constructor; }
+			set { constructor = value; }
+		}
+
+		public TypeReference AttributeType {
+			get { return constructor.DeclaringType; }
+		}
+
+		public bool IsResolved {
+			get { return resolved; }
+		}
+
+		public bool HasConstructorArguments {
+			get {
+				Resolve ();
+
+				return !arguments.IsNullOrEmpty ();
+			}
+		}
+
+		public Collection<CustomAttributeArgument> ConstructorArguments {
+			get {
+				Resolve ();
+
+				return arguments ?? (arguments = new Collection<CustomAttributeArgument> ());
+			}
+		}
+
+		public bool HasFields {
+			get {
+				Resolve ();
+
+				return !fields.IsNullOrEmpty ();
+			}
+		}
+
+		public Collection<CustomAttributeNamedArgument> Fields {
+			get {
+				Resolve ();
+
+				return fields ?? (fields = new Collection<CustomAttributeNamedArgument> ());
+			}
+		}
+
+		public bool HasProperties {
+			get {
+				Resolve ();
+
+				return !properties.IsNullOrEmpty ();
+			}
+		}
+
+		public Collection<CustomAttributeNamedArgument> Properties {
+			get {
+				Resolve ();
+
+				return properties ?? (properties = new Collection<CustomAttributeNamedArgument> ());
+			}
+		}
+
+		internal bool HasImage {
+			get { return constructor != null && constructor.HasImage; }
+		}
+
+		internal ModuleDefinition Module {
+			get { return constructor.Module; }
+		}
+
+		internal CustomAttribute (uint signature, MethodReference constructor)
+		{
+			this.signature = signature;
+			this.constructor = constructor;
+			this.resolved = false;
+		}
+
+		public CustomAttribute (MethodReference constructor)
+		{
+			this.constructor = constructor;
+			this.resolved = true;
+		}
+
+		public CustomAttribute (MethodReference constructor, byte [] blob)
+		{
+			this.constructor = constructor;
+			this.resolved = false;
+			this.blob = blob;
+		}
+
+		public byte [] GetBlob ()
+		{
+			if (blob != null)
+				return blob;
+
+			if (!HasImage || signature == 0)
+				throw new NotSupportedException ();
+
+			return blob = Module.Read (this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature));
+		}
+
+		void Resolve ()
+		{
+			if (resolved || !HasImage)
+				return;
+
+			try {
+				Module.Read (this, (attribute, reader) => {
+					reader.ReadCustomAttributeSignature (attribute);
+					return this;
+				});
+
+				resolved = true;
+			} catch (ResolutionException) {
+				if (arguments != null)
+					arguments.Clear ();
+				if (fields != null)
+					fields.Clear ();
+				if (properties != null)
+					properties.Clear ();
+
+				resolved = false;
+			}
+		}
+	}
+
+	static partial class Mixin {
+
+		public static void CheckName (string name)
+		{
+			if (name == null)
+				throw new ArgumentNullException ("name");
+			if (name.Length == 0)
+				throw new ArgumentException ("Empty name");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/DefaultAssemblyResolver.cs	(revision 11807)
@@ -0,0 +1,75 @@
+//
+// DefaultAssemblyResolver.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public static class GlobalAssemblyResolver {
+
+		public static readonly IAssemblyResolver Instance = new DefaultAssemblyResolver ();
+	}
+
+	public class DefaultAssemblyResolver : BaseAssemblyResolver {
+
+		readonly IDictionary<string, AssemblyDefinition> cache;
+
+		public DefaultAssemblyResolver ()
+		{
+			cache = new Dictionary<string, AssemblyDefinition> ();
+		}
+
+		public override AssemblyDefinition Resolve (AssemblyNameReference name)
+		{
+			if (name == null)
+				throw new ArgumentNullException ("name");
+
+			AssemblyDefinition assembly;
+			if (cache.TryGetValue (name.FullName, out assembly))
+				return assembly;
+
+			assembly = base.Resolve (name);
+			cache [name.FullName] = assembly;
+
+			return assembly;
+		}
+
+		protected void RegisterAssembly (AssemblyDefinition assembly)
+		{
+			if (assembly == null)
+				throw new ArgumentNullException ("assembly");
+
+			var name = assembly.Name.FullName;
+			if (cache.ContainsKey (name))
+				return;
+
+			cache [name] = assembly;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EmbeddedResource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EmbeddedResource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EmbeddedResource.cs	(revision 11807)
@@ -0,0 +1,105 @@
+//
+// EmbeddedResource.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+
+namespace Mono.Cecil {
+
+	public sealed class EmbeddedResource : Resource {
+
+		readonly MetadataReader reader;
+
+		uint? offset;
+		byte [] data;
+		Stream stream;
+
+		public override ResourceType ResourceType {
+			get { return ResourceType.Embedded; }
+		}
+
+		public EmbeddedResource (string name, ManifestResourceAttributes attributes, byte [] data) :
+			base (name, attributes)
+		{
+			this.data = data;
+		}
+
+		public EmbeddedResource (string name, ManifestResourceAttributes attributes, Stream stream) :
+			base (name, attributes)
+		{
+			this.stream = stream;
+		}
+
+		internal EmbeddedResource (string name, ManifestResourceAttributes attributes, uint offset, MetadataReader reader)
+			: base (name, attributes)
+		{
+			this.offset = offset;
+			this.reader = reader;
+		}
+
+		public Stream GetResourceStream ()
+		{
+			if (stream != null)
+				return stream;
+
+			if (data != null)
+				return new MemoryStream (data);
+
+			if (offset.HasValue)
+				return reader.GetManagedResourceStream (offset.Value);
+
+			throw new InvalidOperationException ();
+		}
+
+		public byte [] GetResourceData ()
+		{
+			if (stream != null)
+				return ReadStream (stream);
+
+			if (data != null)
+				return data;
+
+			if (offset.HasValue)
+				return reader.GetManagedResourceStream (offset.Value).ToArray ();
+
+			throw new InvalidOperationException ();
+		}
+
+		static byte [] ReadStream (Stream stream)
+		{
+			var length = (int) stream.Length;
+			var data = new byte [length];
+			int offset = 0, read;
+
+			while ((read = stream.Read (data, offset, length - offset)) > 0)
+				offset += read;
+
+			return data;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventAttributes.cs	(revision 11807)
@@ -0,0 +1,39 @@
+//
+// EventAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum EventAttributes : ushort {
+		None			= 0x0000,
+		SpecialName		= 0x0200,	// Event is special
+		RTSpecialName	= 0x0400	 // CLI provides 'special' behavior, depending upon the name of the event
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventDefinition.cs	(revision 11807)
@@ -0,0 +1,168 @@
+//
+// EventDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class EventDefinition : EventReference, IMemberDefinition {
+
+		ushort attributes;
+
+		Collection<CustomAttribute> custom_attributes;
+
+		internal MethodDefinition add_method;
+		internal MethodDefinition invoke_method;
+		internal MethodDefinition remove_method;
+		internal Collection<MethodDefinition> other_methods;
+
+		public EventAttributes Attributes {
+			get { return (EventAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public MethodDefinition AddMethod {
+			get {
+				if (add_method != null)
+					return add_method;
+
+				InitializeMethods ();
+				return add_method;
+			}
+			set { add_method = value; }
+		}
+
+		public MethodDefinition InvokeMethod {
+			get {
+				if (invoke_method != null)
+					return invoke_method;
+
+				InitializeMethods ();
+				return invoke_method;
+			}
+			set { invoke_method = value; }
+		}
+
+		public MethodDefinition RemoveMethod {
+			get {
+				if (remove_method != null)
+					return remove_method;
+
+				InitializeMethods ();
+				return remove_method;
+			}
+			set { remove_method = value; }
+		}
+
+		public bool HasOtherMethods {
+			get {
+				if (other_methods != null)
+					return other_methods.Count > 0;
+
+				InitializeMethods ();
+				return !other_methods.IsNullOrEmpty ();
+			}
+		}
+
+		public Collection<MethodDefinition> OtherMethods {
+			get {
+				if (other_methods != null)
+					return other_methods;
+
+				InitializeMethods ();
+
+				if (other_methods != null)
+					return other_methods;
+
+				return other_methods = new Collection<MethodDefinition> ();
+			}
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
+		}
+
+		#region EventAttributes
+
+		public bool IsSpecialName {
+			get { return attributes.GetAttributes ((ushort) EventAttributes.SpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) EventAttributes.SpecialName, value); }
+		}
+
+		public bool IsRuntimeSpecialName {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.RTSpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.RTSpecialName, value); }
+		}
+
+		#endregion
+
+		public new TypeDefinition DeclaringType {
+			get { return (TypeDefinition) base.DeclaringType; }
+			set { base.DeclaringType = value; }
+		}
+
+		public override bool IsDefinition {
+			get { return true; }
+		}
+
+		public EventDefinition (string name, EventAttributes attributes, TypeReference eventType)
+			: base (name, eventType)
+		{
+			this.attributes = (ushort) attributes;
+			this.token = new MetadataToken (TokenType.Event);
+		}
+
+		void InitializeMethods ()
+		{
+			if (add_method != null
+				|| invoke_method != null
+				|| remove_method != null)
+				return;
+
+			var module = this.Module;
+			if (!module.HasImage ())
+				return;
+
+			module.Read (this, (@event, reader) => reader.ReadMethods (@event));
+		}
+
+		public override EventDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/EventReference.cs	(revision 11807)
@@ -0,0 +1,57 @@
+//
+// EventReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public abstract class EventReference : MemberReference {
+
+		TypeReference event_type;
+
+		public TypeReference EventType {
+			get { return event_type; }
+			set { event_type = value; }
+		}
+
+		public override string FullName {
+			get { return event_type.FullName + " " + MemberFullName (); }
+		}
+
+		protected EventReference (string name, TypeReference eventType)
+			: base (name)
+		{
+			if (eventType == null)
+				throw new ArgumentNullException ("eventType");
+
+			event_type = eventType;
+		}
+
+		public abstract EventDefinition Resolve ();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ExportedType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ExportedType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ExportedType.cs	(revision 11807)
@@ -0,0 +1,249 @@
+//
+// ExportedType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public class ExportedType : IMetadataTokenProvider {
+
+		string @namespace;
+		string name;
+		uint attributes;
+		IMetadataScope scope;
+		ModuleDefinition module;
+		int identifier;
+		ExportedType declaring_type;
+		internal MetadataToken token;
+
+		public string Namespace {
+			get { return @namespace; }
+			set { @namespace = value; }
+		}
+
+		public string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public TypeAttributes Attributes {
+			get { return (TypeAttributes) attributes; }
+			set { attributes = (uint) value; }
+		}
+
+		public IMetadataScope Scope {
+			get {
+				if (declaring_type != null)
+					return declaring_type.Scope;
+
+				return scope;
+			}
+		}
+
+		public ExportedType DeclaringType {
+			get { return declaring_type; }
+			set { declaring_type = value; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return token; }
+			set { token = value; }
+		}
+
+		public int Identifier {
+			get { return identifier; }
+			set { identifier = value; }
+		}
+
+		#region TypeAttributes
+
+		public bool IsNotPublic {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
+		}
+
+		public bool IsPublic {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
+		}
+
+		public bool IsNestedPublic {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
+		}
+
+		public bool IsNestedPrivate {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
+		}
+
+		public bool IsNestedFamily {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
+		}
+
+		public bool IsNestedAssembly {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
+		}
+
+		public bool IsNestedFamilyAndAssembly {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
+		}
+
+		public bool IsNestedFamilyOrAssembly {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
+		}
+
+		public bool IsAutoLayout {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
+		}
+
+		public bool IsSequentialLayout {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
+		}
+
+		public bool IsExplicitLayout {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
+		}
+
+		public bool IsClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
+		}
+
+		public bool IsInterface {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
+		}
+
+		public bool IsAbstract {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
+		}
+
+		public bool IsSealed {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
+		}
+
+		public bool IsSpecialName {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
+		}
+
+		public bool IsImport {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
+		}
+
+		public bool IsSerializable {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
+		}
+
+		public bool IsAnsiClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
+		}
+
+		public bool IsUnicodeClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
+		}
+
+		public bool IsAutoClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
+		}
+
+		public bool IsBeforeFieldInit {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
+		}
+
+		public bool IsRuntimeSpecialName {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
+		}
+
+		public bool HasSecurity {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
+		}
+
+		#endregion
+
+		public bool IsForwarder {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Forwarder); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Forwarder, value); }
+		}
+
+		public string FullName {
+			get {
+				if (declaring_type != null)
+					return declaring_type.FullName + "/" + name;
+
+				if (string.IsNullOrEmpty (@namespace))
+					return name;
+
+				return @namespace + "." + name;
+			}
+		}
+
+		public ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
+		{
+			this.@namespace = @namespace;
+			this.name = name;
+			this.scope = scope;
+			this.module = module;
+		}
+
+		public override string ToString ()
+		{
+			return FullName;
+		}
+
+		public TypeDefinition Resolve ()
+		{
+			return module.Resolve (CreateReference ());
+		}
+
+		internal TypeReference CreateReference ()
+		{
+			return new TypeReference (@namespace, name, module, scope) {
+				DeclaringType = declaring_type != null ? declaring_type.CreateReference () : null,
+			};
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldAttributes.cs	(revision 11807)
@@ -0,0 +1,59 @@
+//
+// FieldAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum FieldAttributes : ushort {
+		FieldAccessMask		= 0x0007,
+		CompilerControlled	= 0x0000,	// Member not referenceable
+		Private				= 0x0001,	// Accessible only by the parent type
+		FamANDAssem			= 0x0002,	// Accessible by sub-types only in this assembly
+		Assembly			= 0x0003,	// Accessible by anyone in the Assembly
+		Family				= 0x0004,	// Accessible only by type and sub-types
+		FamORAssem			= 0x0005,	// Accessible by sub-types anywhere, plus anyone in the assembly
+		Public				= 0x0006,	// Accessible by anyone who has visibility to this scope field contract attributes
+
+		Static				= 0x0010,	// Defined on type, else per instance
+		InitOnly			= 0x0020,	// Field may only be initialized, not written after init
+		Literal				= 0x0040,	// Value is compile time constant
+		NotSerialized		= 0x0080,	// Field does not have to be serialized when type is remoted
+		SpecialName			= 0x0200,	// Field is special
+
+		// Interop Attributes
+		PInvokeImpl			= 0x2000,	// Implementation is forwarded through PInvoke
+
+		// Additional flags
+		RTSpecialName		= 0x0400,	// CLI provides 'special' behavior, depending upon the name of the field
+		HasFieldMarshal		= 0x1000,	// Field has marshalling information
+		HasDefault			= 0x8000,	// Field has default
+		HasFieldRVA			= 0x0100	 // Field has RVA
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldDefinition.cs	(revision 11807)
@@ -0,0 +1,279 @@
+//
+// FieldDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class FieldDefinition : FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider {
+
+		ushort attributes;
+		Collection<CustomAttribute> custom_attributes;
+
+		int offset = Mixin.NotResolvedMarker;
+
+		internal int rva = Mixin.NotResolvedMarker;
+		byte [] initial_value;
+
+		object constant = Mixin.NotResolved;
+
+		MarshalInfo marshal_info;
+
+		void ResolveLayout ()
+		{
+			if (offset != Mixin.NotResolvedMarker)
+				return;
+
+			if (!HasImage) {
+				offset = Mixin.NoDataMarker;
+				return;
+			}
+
+			offset = Module.Read (this, (field, reader) => reader.ReadFieldLayout (field));
+		}
+
+		public bool HasLayoutInfo {
+			get {
+				if (offset >= 0)
+					return true;
+
+				ResolveLayout ();
+
+				return offset >= 0;
+			}
+		}
+
+		public int Offset {
+			get {
+				if (offset >= 0)
+					return offset;
+
+				ResolveLayout ();
+
+				return offset >= 0 ? offset : -1;
+			}
+			set { offset = value; }
+		}
+
+		void ResolveRVA ()
+		{
+			if (rva != Mixin.NotResolvedMarker)
+				return;
+
+			if (!HasImage)
+				return;
+
+			rva = Module.Read (this, (field, reader) => reader.ReadFieldRVA (field));
+		}
+
+		public int RVA {
+			get {
+				if (rva > 0)
+					return rva;
+
+				ResolveRVA ();
+
+				return rva > 0 ? rva : 0;
+			}
+		}
+
+		public byte [] InitialValue {
+			get {
+				if (initial_value != null)
+					return initial_value;
+
+				ResolveRVA ();
+
+				if (initial_value == null)
+					initial_value = Empty<byte>.Array;
+
+				return initial_value;
+			}
+			set { initial_value = value; }
+		}
+
+		public FieldAttributes Attributes {
+			get { return (FieldAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public bool HasConstant {
+			get {
+				ResolveConstant ();
+
+				return constant != Mixin.NoValue;
+			}
+			set { if (!value) constant = Mixin.NoValue; }
+		}
+
+		public object Constant {
+			get { return HasConstant ? constant : null;	}
+			set { constant = value; }
+		}
+
+		void ResolveConstant ()
+		{
+			if (constant != Mixin.NotResolved)
+				return;
+
+			this.ResolveConstant (ref constant, Module);
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
+		}
+
+		public bool HasMarshalInfo {
+			get {
+				if (marshal_info != null)
+					return true;
+
+				return this.GetHasMarshalInfo (Module);
+			}
+		}
+
+		public MarshalInfo MarshalInfo {
+			get { return marshal_info ?? (marshal_info = this.GetMarshalInfo (Module)); }
+			set { marshal_info = value; }
+		}
+
+		#region FieldAttributes
+
+		public bool IsCompilerControlled {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled, value); }
+		}
+
+		public bool IsPrivate {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private, value); }
+		}
+
+		public bool IsFamilyAndAssembly {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem, value); }
+		}
+
+		public bool IsAssembly {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly, value); }
+		}
+
+		public bool IsFamily {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family, value); }
+		}
+
+		public bool IsFamilyOrAssembly {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem, value); }
+		}
+
+		public bool IsPublic {
+			get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public, value); }
+		}
+
+		public bool IsStatic {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.Static); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Static, value); }
+		}
+
+		public bool IsInitOnly {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.InitOnly); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.InitOnly, value); }
+		}
+
+		public bool IsLiteral {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.Literal); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Literal, value); }
+		}
+
+		public bool IsNotSerialized {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.NotSerialized); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.NotSerialized, value); }
+		}
+
+		public bool IsSpecialName {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.SpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.SpecialName, value); }
+		}
+
+		public bool IsPInvokeImpl {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.PInvokeImpl); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.PInvokeImpl, value); }
+		}
+
+		public bool IsRuntimeSpecialName {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.RTSpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.RTSpecialName, value); }
+		}
+
+		public bool HasDefault {
+			get { return attributes.GetAttributes ((ushort) FieldAttributes.HasDefault); }
+			set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.HasDefault, value); }
+		}
+
+		#endregion
+
+		public override bool IsDefinition {
+			get { return true; }
+		}
+
+		public new TypeDefinition DeclaringType {
+			get { return (TypeDefinition) base.DeclaringType; }
+			set { base.DeclaringType = value; }
+		}
+
+		public FieldDefinition (string name, FieldAttributes attributes, TypeReference fieldType)
+			: base (name, fieldType)
+		{
+			this.attributes = (ushort) attributes;
+		}
+
+		public override FieldDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+
+	static partial class Mixin {
+
+		public const int NotResolvedMarker = -2;
+		public const int NoDataMarker = -1;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FieldReference.cs	(revision 11807)
@@ -0,0 +1,83 @@
+//
+// FieldReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public class FieldReference : MemberReference {
+
+		TypeReference field_type;
+
+		public TypeReference FieldType {
+			get { return field_type; }
+			set { field_type = value; }
+		}
+
+		public override string FullName {
+			get { return field_type.FullName + " " + MemberFullName (); }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return field_type.ContainsGenericParameter || base.ContainsGenericParameter; }
+		}
+
+		internal FieldReference ()
+		{
+			this.token = new MetadataToken (TokenType.MemberRef);
+		}
+
+		public FieldReference (string name, TypeReference fieldType)
+			: base (name)
+		{
+			if (fieldType == null)
+				throw new ArgumentNullException ("fieldType");
+
+			this.field_type = fieldType;
+			this.token = new MetadataToken (TokenType.MemberRef);
+		}
+
+		public FieldReference (string name, TypeReference fieldType, TypeReference declaringType)
+			: this (name, fieldType)
+		{
+			if (declaringType == null)
+				throw new ArgumentNullException("declaringType");
+
+			this.DeclaringType = declaringType;
+		}
+
+		public virtual FieldDefinition Resolve ()
+		{
+			var module = this.Module;
+			if (module == null)
+				throw new NotSupportedException ();
+
+			return module.Resolve (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FileAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FileAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FileAttributes.cs	(revision 11807)
@@ -0,0 +1,35 @@
+//
+// FileAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	enum FileAttributes : uint {
+		ContainsMetaData	= 0x0000,	// This is not a resource file
+		ContainsNoMetaData  = 0x0001,	// This is a resource file or other non-metadata-containing file
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FunctionPointerType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FunctionPointerType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/FunctionPointerType.cs	(revision 11807)
@@ -0,0 +1,128 @@
+//
+// FunctionPointerType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+using Mono.Collections.Generic;
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class FunctionPointerType : TypeSpecification, IMethodSignature {
+
+		readonly MethodReference function;
+
+		public bool HasThis {
+			get { return function.HasThis; }
+			set { function.HasThis = value; }
+		}
+
+		public bool ExplicitThis {
+			get { return function.ExplicitThis; }
+			set { function.ExplicitThis = value; }
+		}
+
+		public MethodCallingConvention CallingConvention {
+			get { return function.CallingConvention; }
+			set { function.CallingConvention = value; }
+		}
+
+		public bool HasParameters {
+			get { return function.HasParameters; }
+		}
+
+		public Collection<ParameterDefinition> Parameters {
+			get { return function.Parameters; }
+		}
+
+		public TypeReference ReturnType {
+			get { return function.MethodReturnType.ReturnType; }
+			set { function.MethodReturnType.ReturnType = value; }
+		}
+
+		public MethodReturnType MethodReturnType {
+			get { return function.MethodReturnType; }
+		}
+
+		public override string Name {
+			get { return function.Name; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override string Namespace {
+			get { return string.Empty; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override ModuleDefinition Module {
+			get { return ReturnType.Module; }
+		}
+
+		public override IMetadataScope Scope {
+			get { return function.ReturnType.Scope; }
+		}
+
+		public override bool IsFunctionPointer {
+			get { return true; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return function.ContainsGenericParameter; }
+		}
+
+		public override string FullName {
+			get {
+				var signature = new StringBuilder ();
+				signature.Append (function.Name);
+				signature.Append (" ");
+				signature.Append (function.ReturnType.FullName);
+				signature.Append (" *");
+				this.MethodSignatureFullName (signature);
+				return signature.ToString ();
+			}
+		}
+
+		public FunctionPointerType ()
+			: base (null)
+		{
+			this.function = new MethodReference ();
+			this.function.Name = "method";
+			this.etype = MD.ElementType.FnPtr;
+		}
+
+		public override TypeDefinition Resolve ()
+		{
+			return null;
+		}
+
+		public override TypeReference GetElementType ()
+		{
+			return this;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericInstanceMethod.cs	(revision 11807)
@@ -0,0 +1,85 @@
+//
+// GenericInstanceMethod.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class GenericInstanceMethod : MethodSpecification, IGenericInstance, IGenericContext {
+
+		Collection<TypeReference> arguments;
+
+		public bool HasGenericArguments {
+			get { return !arguments.IsNullOrEmpty (); }
+		}
+
+		public Collection<TypeReference> GenericArguments {
+			get { return arguments ?? (arguments = new Collection<TypeReference> ()); }
+		}
+
+		public override bool IsGenericInstance {
+			get { return true; }
+		}
+
+		IGenericParameterProvider IGenericContext.Method {
+			get { return ElementMethod; }
+		}
+
+		IGenericParameterProvider IGenericContext.Type {
+			get { return ElementMethod.DeclaringType; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return this.ContainsGenericParameter () || base.ContainsGenericParameter; }
+		}
+
+		public override string FullName {
+			get {
+				var signature = new StringBuilder ();
+				var method = this.ElementMethod;
+				signature.Append (method.ReturnType.FullName)
+					.Append (" ")
+					.Append (method.DeclaringType.FullName)
+					.Append ("::")
+					.Append (method.Name);
+				this.GenericInstanceFullName (signature);
+				this.MethodSignatureFullName (signature);
+				return signature.ToString ();
+
+			}
+		}
+
+		public GenericInstanceMethod (MethodReference method)
+			: base (method)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericInstanceType.cs	(revision 11807)
@@ -0,0 +1,83 @@
+//
+// GenericInstanceType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+
+using Mono.Collections.Generic;
+
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class GenericInstanceType : TypeSpecification, IGenericInstance, IGenericContext {
+
+		Collection<TypeReference> arguments;
+
+		public bool HasGenericArguments {
+			get { return !arguments.IsNullOrEmpty (); }
+		}
+
+		public Collection<TypeReference> GenericArguments {
+			get { return arguments ?? (arguments = new Collection<TypeReference> ()); }
+		}
+
+		public override TypeReference DeclaringType {
+			get { return ElementType.DeclaringType; }
+			set { throw new NotSupportedException (); }
+		}
+
+		public override string FullName {
+			get {
+				var name = new StringBuilder ();
+				name.Append (base.FullName);
+				this.GenericInstanceFullName (name);
+				return name.ToString ();
+			}
+		}
+
+		public override bool IsGenericInstance {
+			get { return true; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return this.ContainsGenericParameter () || base.ContainsGenericParameter; }
+		}
+
+		IGenericParameterProvider IGenericContext.Type {
+			get { return ElementType; }
+		}
+
+		public GenericInstanceType (TypeReference type)
+			: base (type)
+		{
+			base.IsValueType = type.IsValueType;
+			this.etype = MD.ElementType.GenericInst;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericParameter.cs	(revision 11807)
@@ -0,0 +1,197 @@
+//
+// GenericParameter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class GenericParameter : TypeReference, ICustomAttributeProvider {
+
+		readonly IGenericParameterProvider owner;
+
+		ushort attributes;
+		Collection<TypeReference> constraints;
+		Collection<CustomAttribute> custom_attributes;
+
+		public GenericParameterAttributes Attributes {
+			get { return (GenericParameterAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public int Position {
+			get {
+				if (owner == null)
+					return -1;
+
+				return owner.GenericParameters.IndexOf (this);
+			}
+		}
+
+		public IGenericParameterProvider Owner {
+			get { return owner; }
+		}
+
+		public bool HasConstraints {
+			get {
+				if (constraints != null)
+					return constraints.Count > 0;
+
+				if (HasImage)
+					return Module.Read (this, (generic_parameter, reader) => reader.HasGenericConstraints (generic_parameter));
+
+				return false;
+			}
+		}
+
+		public Collection<TypeReference> Constraints {
+			get {
+				if (constraints != null)
+					return constraints;
+
+				if (HasImage)
+					return constraints = Module.Read (this, (generic_parameter, reader) => reader.ReadGenericConstraints (generic_parameter));
+
+				return constraints = new Collection<TypeReference> ();
+			}
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
+		}
+
+		public override IMetadataScope Scope {
+			get {
+				if (owner.GenericParameterType == GenericParameterType.Method)
+					return ((MethodReference) owner).DeclaringType.Scope;
+
+				return ((TypeReference) owner).Scope;
+			}
+		}
+
+		public override ModuleDefinition Module {
+			get { return ((MemberReference) owner).Module; }
+		}
+
+		public override string Name {
+			get {
+				if (!string.IsNullOrEmpty (base.Name))
+					return base.Name;
+
+				return base.Name = (owner.GenericParameterType == GenericParameterType.Type ? "!" : "!!") + Position;
+			}
+		}
+
+		public override string Namespace {
+			get { return string.Empty; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override string FullName {
+			get { return Name; }
+		}
+
+		public override bool IsGenericParameter {
+			get { return true; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return true; }
+		}
+
+		public override MetadataType MetadataType {
+			get { return (MetadataType) etype; }
+		}
+
+		#region GenericParameterAttributes
+
+		public bool IsNonVariant {
+			get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant, value); }
+		}
+
+		public bool IsCovariant {
+			get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant, value); }
+		}
+
+		public bool IsContravariant {
+			get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant, value); }
+		}
+
+		public bool HasReferenceTypeConstraint {
+			get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.ReferenceTypeConstraint); }
+			set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.ReferenceTypeConstraint, value); }
+		}
+
+		public bool HasNotNullableValueTypeConstraint {
+			get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.NotNullableValueTypeConstraint); }
+			set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.NotNullableValueTypeConstraint, value); }
+		}
+
+		public bool HasDefaultConstructorConstraint {
+			get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.DefaultConstructorConstraint); }
+			set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.DefaultConstructorConstraint, value); }
+		}
+
+		#endregion
+
+		public GenericParameter (IGenericParameterProvider owner)
+			: this (string.Empty, owner)
+		{
+		}
+
+		public GenericParameter (string name, IGenericParameterProvider owner)
+			: base (string.Empty, name)
+		{
+			if (owner == null)
+				throw new ArgumentNullException ();
+
+			this.owner = owner;
+			this.etype = owner.GenericParameterType == GenericParameterType.Type ? ElementType.Var : ElementType.MVar;
+		}
+
+		public override TypeDefinition Resolve ()
+		{
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/GenericParameterAttributes.cs	(revision 11807)
@@ -0,0 +1,45 @@
+//
+// GenericParameterAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum GenericParameterAttributes : ushort {
+		VarianceMask	= 0x0003,
+		NonVariant		= 0x0000,
+		Covariant		= 0x0001,
+		Contravariant	= 0x0002,
+
+		SpecialConstraintMask			= 0x001c,
+		ReferenceTypeConstraint			= 0x0004,
+		NotNullableValueTypeConstraint	= 0x0008,
+		DefaultConstructorConstraint	= 0x0010
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IConstantProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IConstantProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IConstantProvider.cs	(revision 11807)
@@ -0,0 +1,52 @@
+//
+// IConstantProvider.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public interface IConstantProvider : IMetadataTokenProvider {
+
+		bool HasConstant { get; set; }
+		object Constant { get; set; }
+	}
+
+	static partial class Mixin {
+
+		internal static object NoValue = new object ();
+		internal static object NotResolved = new object ();
+
+		public static void ResolveConstant (
+			this IConstantProvider self,
+			ref object constant,
+			ModuleDefinition module)
+		{
+			constant = module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.ReadConstant (provider))
+				: Mixin.NoValue;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ICustomAttributeProvider.cs	(revision 11807)
@@ -0,0 +1,62 @@
+//
+// ICustomAttributeProvider.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public interface ICustomAttributeProvider : IMetadataTokenProvider {
+
+		Collection<CustomAttribute> CustomAttributes { get; }
+
+		bool HasCustomAttributes { get; }
+	}
+
+	static partial class Mixin {
+
+		public static bool GetHasCustomAttributes (
+			this ICustomAttributeProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.HasCustomAttributes (provider))
+				: false;
+		}
+
+		public static Collection<CustomAttribute> GetCustomAttributes (
+			this ICustomAttributeProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.ReadCustomAttributes (provider))
+				: new Collection<CustomAttribute> ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IGenericInstance.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IGenericInstance.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IGenericInstance.cs	(revision 11807)
@@ -0,0 +1,66 @@
+//
+// IGenericInstance.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public interface IGenericInstance : IMetadataTokenProvider {
+
+		bool HasGenericArguments { get; }
+		Collection<TypeReference> GenericArguments { get; }
+	}
+
+	static partial class Mixin {
+
+		public static bool ContainsGenericParameter (this IGenericInstance self)
+		{
+			var arguments = self.GenericArguments;
+
+			for (int i = 0; i < arguments.Count; i++)
+				if (arguments [i].ContainsGenericParameter)
+					return true;
+
+			return false;
+		}
+
+		public static void GenericInstanceFullName (this IGenericInstance self, StringBuilder builder)
+		{
+			builder.Append ("<");
+			var arguments = self.GenericArguments;
+			for (int i = 0; i < arguments.Count; i++) {
+				if (i > 0)
+					builder.Append (",");
+				builder.Append (arguments [i].FullName);
+			}
+			builder.Append (">");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IGenericParameterProvider.cs	(revision 11807)
@@ -0,0 +1,75 @@
+//
+// IGenericParameterProvider.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public interface IGenericParameterProvider : IMetadataTokenProvider {
+
+		bool HasGenericParameters { get; }
+		bool IsDefinition { get; }
+		ModuleDefinition Module { get; }
+		Collection<GenericParameter> GenericParameters { get; }
+		GenericParameterType GenericParameterType { get; }
+	}
+
+	public enum GenericParameterType {
+		Type,
+		Method
+	}
+
+	interface IGenericContext {
+
+		bool IsDefinition { get; }
+		IGenericParameterProvider Type { get; }
+		IGenericParameterProvider Method { get; }
+	}
+
+	static partial class Mixin {
+
+		public static bool GetHasGenericParameters (
+			this IGenericParameterProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.HasGenericParameters (provider))
+				: false;
+		}
+
+		public static Collection<GenericParameter> GetGenericParameters (
+			this IGenericParameterProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.ReadGenericParameters (provider))
+				: new Collection<GenericParameter> ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMarshalInfoProvider.cs	(revision 11807)
@@ -0,0 +1,57 @@
+//
+// IMarshalInfoProvider.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public interface IMarshalInfoProvider : IMetadataTokenProvider {
+
+		bool HasMarshalInfo { get; }
+		MarshalInfo MarshalInfo { get; set; }
+	}
+
+	static partial class Mixin {
+
+		public static bool GetHasMarshalInfo (
+			this IMarshalInfoProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.HasMarshalInfo (provider))
+				: false;
+		}
+
+		public static MarshalInfo GetMarshalInfo (
+			this IMarshalInfoProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.ReadMarshalInfo (provider))
+				: null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMemberDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMemberDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMemberDefinition.cs	(revision 11807)
@@ -0,0 +1,100 @@
+//
+// IMemberDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public interface IMemberDefinition : ICustomAttributeProvider {
+
+		string Name { get; set; }
+		string FullName { get; }
+
+		bool IsSpecialName { get; set; }
+		bool IsRuntimeSpecialName { get; set; }
+
+		TypeDefinition DeclaringType { get; set; }
+	}
+
+	static partial class Mixin {
+
+		public static bool GetAttributes (this uint self, uint attributes)
+		{
+			return (self & attributes) != 0;
+		}
+
+		public static uint SetAttributes (this uint self, uint attributes, bool value)
+		{
+			if (value)
+				return self | attributes;
+
+			return self & ~attributes;
+		}
+
+		public static bool GetMaskedAttributes (this uint self, uint mask, uint attributes)
+		{
+			return (self & mask) == attributes;
+		}
+
+		public static uint SetMaskedAttributes (this uint self, uint mask, uint attributes, bool value)
+		{
+			if (value) {
+				self &= ~mask;
+				return self | attributes;
+			}
+
+			return self & ~(mask & attributes);
+		}
+
+		public static bool GetAttributes (this ushort self, ushort attributes)
+		{
+			return (self & attributes) != 0;
+		}
+
+		public static ushort SetAttributes (this ushort self, ushort attributes, bool value)
+		{
+			if (value)
+				return (ushort) (self | attributes);
+
+			return (ushort) (self & ~attributes);
+		}
+
+		public static bool GetMaskedAttributes (this ushort self, ushort mask, uint attributes)
+		{
+			return (self & mask) == attributes;
+		}
+
+		public static ushort SetMaskedAttributes (this ushort self, ushort mask, uint attributes, bool value)
+		{
+			if (value) {
+				self = (ushort) (self & ~mask);
+				return (ushort) (self | attributes);
+			}
+
+			return (ushort) (self & ~(mask & attributes));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMetadataScope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMetadataScope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMetadataScope.cs	(revision 11807)
@@ -0,0 +1,41 @@
+//
+// IMetadataScope.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum MetadataScopeType {
+		AssemblyNameReference,
+		ModuleReference,
+		ModuleDefinition,
+	}
+
+	public interface IMetadataScope : IMetadataTokenProvider {
+		MetadataScopeType MetadataScopeType { get; }
+		string Name { get; set; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMetadataTokenProvider.cs	(revision 11807)
@@ -0,0 +1,35 @@
+//
+// IMetadataTokenProvider.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public interface IMetadataTokenProvider {
+
+		MetadataToken MetadataToken { get; set; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMethodSignature.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMethodSignature.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/IMethodSignature.cs	(revision 11807)
@@ -0,0 +1,70 @@
+//
+// IMethodSignature.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public interface IMethodSignature : IMetadataTokenProvider {
+
+		bool HasThis { get; set; }
+		bool ExplicitThis { get; set; }
+		MethodCallingConvention CallingConvention { get; set; }
+
+		bool HasParameters { get; }
+		Collection<ParameterDefinition> Parameters { get; }
+		TypeReference ReturnType { get; set; }
+		MethodReturnType MethodReturnType { get; }
+	}
+
+	static partial class Mixin {
+
+		public static void MethodSignatureFullName (this IMethodSignature self, StringBuilder builder)
+		{
+			builder.Append ("(");
+
+			if (self.HasParameters) {
+				var parameters = self.Parameters;
+				for (int i = 0; i < parameters.Count; i++) {
+					var parameter = parameters [i];
+					if (i > 0)
+						builder.Append (",");
+
+					if (parameter.ParameterType.IsSentinel)
+						builder.Append ("...,");
+
+					builder.Append (parameter.ParameterType.FullName);
+				}
+			}
+
+			builder.Append (")");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Import.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Import.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Import.cs	(revision 11807)
@@ -0,0 +1,566 @@
+//
+// Import.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using SR = System.Reflection;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	enum ImportGenericKind {
+		Definition,
+		Open,
+	}
+
+	class MetadataImporter {
+
+		readonly ModuleDefinition module;
+
+		public MetadataImporter (ModuleDefinition module)
+		{
+			this.module = module;
+		}
+
+#if !CF
+		static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
+			{ typeof (void), ElementType.Void },
+			{ typeof (bool), ElementType.Boolean },
+			{ typeof (char), ElementType.Char },
+			{ typeof (sbyte), ElementType.I1 },
+			{ typeof (byte), ElementType.U1 },
+			{ typeof (short), ElementType.I2 },
+			{ typeof (ushort), ElementType.U2 },
+			{ typeof (int), ElementType.I4 },
+			{ typeof (uint), ElementType.U4 },
+			{ typeof (long), ElementType.I8 },
+			{ typeof (ulong), ElementType.U8 },
+			{ typeof (float), ElementType.R4 },
+			{ typeof (double), ElementType.R8 },
+			{ typeof (string), ElementType.String },
+			{ typeof (TypedReference), ElementType.TypedByRef },
+			{ typeof (IntPtr), ElementType.I },
+			{ typeof (UIntPtr), ElementType.U },
+			{ typeof (object), ElementType.Object },
+		};
+
+		public TypeReference ImportType (Type type, IGenericContext context)
+		{
+			return ImportType (type, context, ImportGenericKind.Open);
+		}
+
+		public TypeReference ImportType (Type type, IGenericContext context, ImportGenericKind import_kind)
+		{
+			if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
+				return ImportTypeSpecification (type, context);
+
+			var reference = new TypeReference (
+				string.Empty,
+				type.Name,
+				module,
+				ImportScope (type.Assembly),
+				type.IsValueType);
+
+			reference.etype = ImportElementType (type);
+
+			if (IsNestedType (type))
+				reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
+			else
+				reference.Namespace = type.Namespace;
+
+			if (type.IsGenericType)
+				ImportGenericParameters (reference, type.GetGenericArguments ());
+
+			return reference;
+		}
+
+		static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
+		{
+			return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open;
+		}
+
+		static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
+		{
+			return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
+		}
+
+		static bool IsNestedType (Type type)
+		{
+#if !SILVERLIGHT
+			return type.IsNested;
+#else
+			return type.DeclaringType != null;
+#endif
+		}
+
+		TypeReference ImportTypeSpecification (Type type, IGenericContext context)
+		{
+			if (type.IsByRef)
+				return new ByReferenceType (ImportType (type.GetElementType (), context));
+
+			if (type.IsPointer)
+				return new PointerType (ImportType (type.GetElementType (), context));
+
+			if (type.IsArray)
+				return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
+
+			if (type.IsGenericType)
+				return ImportGenericInstance (type, context);
+
+			if (type.IsGenericParameter)
+				return ImportGenericParameter (type, context);
+
+			throw new NotSupportedException (type.FullName);
+		}
+
+		static TypeReference ImportGenericParameter (Type type, IGenericContext context)
+		{
+			if (context == null)
+				throw new InvalidOperationException ();
+
+			var owner = type.DeclaringMethod != null
+				? context.Method
+				: context.Type;
+
+			if (owner == null)
+				throw new InvalidOperationException ();
+
+			return owner.GenericParameters [type.GenericParameterPosition];
+		}
+
+		TypeReference ImportGenericInstance (Type type, IGenericContext context)
+		{
+			var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
+			var instance = new GenericInstanceType (element_type);
+			var arguments = type.GetGenericArguments ();
+			var instance_arguments = instance.GenericArguments;
+
+			for (int i = 0; i < arguments.Length; i++)
+				instance_arguments.Add (ImportType (arguments [i], context ?? element_type));
+
+			return instance;
+		}
+
+		static bool IsTypeSpecification (Type type)
+		{
+			return type.HasElementType
+				|| IsGenericInstance (type)
+				|| type.IsGenericParameter;
+		}
+
+		static bool IsGenericInstance (Type type)
+		{
+			return type.IsGenericType && !type.IsGenericTypeDefinition;
+		}
+
+		static ElementType ImportElementType (Type type)
+		{
+			ElementType etype;
+			if (!type_etype_mapping.TryGetValue (type, out etype))
+				return ElementType.None;
+
+			return etype;
+		}
+
+		AssemblyNameReference ImportScope (SR.Assembly assembly)
+		{
+			AssemblyNameReference scope;
+#if !SILVERLIGHT
+			var name = assembly.GetName ();
+
+			if (TryGetAssemblyNameReference (name, out scope))
+				return scope;
+
+			scope = new AssemblyNameReference (name.Name, name.Version) {
+				Culture = name.CultureInfo.Name,
+				PublicKeyToken = name.GetPublicKeyToken (),
+				HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
+			};
+
+			module.AssemblyReferences.Add (scope);
+
+			return scope;
+#else
+			var name = AssemblyNameReference.Parse (assembly.FullName);
+
+			if (TryGetAssemblyNameReference (name, out scope))
+				return scope;
+
+			module.AssemblyReferences.Add (name);
+
+			return name;
+#endif
+		}
+
+#if !SILVERLIGHT
+		bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
+		{
+			var references = module.AssemblyReferences;
+
+			for (int i = 0; i < references.Count; i++) {
+				var reference = references [i];
+				if (name.FullName != reference.FullName) // TODO compare field by field
+					continue;
+
+				assembly_reference = reference;
+				return true;
+			}
+
+			assembly_reference = null;
+			return false;
+		}
+#endif
+
+		public FieldReference ImportField (SR.FieldInfo field, IGenericContext context)
+		{
+			var declaring_type = ImportType (field.DeclaringType, context);
+
+			if (IsGenericInstance (field.DeclaringType))
+				field = ResolveFieldDefinition (field);
+
+			return new FieldReference {
+				Name = field.Name,
+				DeclaringType = declaring_type,
+				FieldType = ImportType (field.FieldType, context ?? declaring_type),
+			};
+		}
+
+		static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
+		{
+#if !SILVERLIGHT
+			return field.Module.ResolveField (field.MetadataToken);
+#else
+			return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name,
+				SR.BindingFlags.Public
+				| SR.BindingFlags.NonPublic
+				| (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance));
+#endif
+		}
+
+		public MethodReference ImportMethod (SR.MethodBase method, IGenericContext context, ImportGenericKind import_kind)
+		{
+			if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
+				return ImportMethodSpecification (method, context);
+
+			var declaring_type = ImportType (method.DeclaringType, context);
+
+			if (IsGenericInstance (method.DeclaringType))
+				method = method.Module.ResolveMethod (method.MetadataToken);
+
+			var reference = new MethodReference {
+				Name = method.Name,
+				HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
+				ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
+				DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
+			};
+
+			if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
+				reference.CallingConvention &= MethodCallingConvention.VarArg;
+
+			if (method.IsGenericMethod)
+				ImportGenericParameters (reference, method.GetGenericArguments ());
+
+			var method_info = method as SR.MethodInfo;
+			reference.ReturnType = method_info != null
+				? ImportType (method_info.ReturnType, context ?? reference)
+				: ImportType (typeof (void), null);
+
+			var parameters = method.GetParameters ();
+			var reference_parameters = reference.Parameters;
+
+			for (int i = 0; i < parameters.Length; i++)
+				reference_parameters.Add (
+					new ParameterDefinition (ImportType (parameters [i].ParameterType, context ?? reference)));
+
+			reference.DeclaringType = declaring_type;
+
+			return reference;
+		}
+
+		static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
+		{
+			var provider_parameters = provider.GenericParameters;
+
+			for (int i = 0; i < arguments.Length; i++)
+				provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
+		}
+
+		static bool IsMethodSpecification (SR.MethodBase method)
+		{
+			return method.IsGenericMethod && !method.IsGenericMethodDefinition;
+		}
+
+		MethodReference ImportMethodSpecification (SR.MethodBase method, IGenericContext context)
+		{
+			var method_info = method as SR.MethodInfo;
+			if (method_info == null)
+				throw new InvalidOperationException ();
+
+			var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
+			var instance = new GenericInstanceMethod (element_method);
+			var arguments = method.GetGenericArguments ();
+			var instance_arguments = instance.GenericArguments;
+
+			for (int i = 0; i < arguments.Length; i++)
+				instance_arguments.Add (ImportType (arguments [i], context ?? element_method));
+
+			return instance;
+		}
+
+		static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
+		{
+			return (method.CallingConvention & conventions) != 0;
+		}
+#endif
+
+		public TypeReference ImportType (TypeReference type, IGenericContext context)
+		{
+			if (type.IsTypeSpecification ())
+				return ImportTypeSpecification (type, context);
+
+			var reference = new TypeReference (
+				type.Namespace,
+				type.Name,
+				module,
+				ImportScope (type.Scope),
+				type.IsValueType);
+
+			MetadataSystem.TryProcessPrimitiveType (reference);
+
+			if (type.IsNested)
+				reference.DeclaringType = ImportType (type.DeclaringType, context);
+
+			if (type.HasGenericParameters)
+				ImportGenericParameters (reference, type);
+
+			return reference;
+		}
+
+		IMetadataScope ImportScope (IMetadataScope scope)
+		{
+			switch (scope.MetadataScopeType) {
+			case MetadataScopeType.AssemblyNameReference:
+				return ImportAssemblyName ((AssemblyNameReference) scope);
+			case MetadataScopeType.ModuleDefinition:
+				return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name);
+			case MetadataScopeType.ModuleReference:
+				throw new NotImplementedException ();
+			}
+
+			throw new NotSupportedException ();
+		}
+
+		AssemblyNameReference ImportAssemblyName (AssemblyNameReference name)
+		{
+			AssemblyNameReference reference;
+			if (TryGetAssemblyNameReference (name, out reference))
+				return reference;
+
+			reference = new AssemblyNameReference (name.Name, name.Version) {
+				Culture = name.Culture,
+				HashAlgorithm = name.HashAlgorithm,
+			};
+
+			var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
+				? new byte [name.PublicKeyToken.Length]
+				: Empty<byte>.Array;
+
+			if (pk_token.Length > 0)
+				Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
+
+			reference.PublicKeyToken = pk_token;
+
+			module.AssemblyReferences.Add (reference);
+
+			return reference;
+		}
+
+		bool TryGetAssemblyNameReference (AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
+		{
+			var references = module.AssemblyReferences;
+
+			for (int i = 0; i < references.Count; i++) {
+				var reference = references [i];
+				if (name_reference.FullName != reference.FullName) // TODO compare field by field
+					continue;
+
+				assembly_reference = reference;
+				return true;
+			}
+
+			assembly_reference = null;
+			return false;
+		}
+
+		static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
+		{
+			var parameters = original.GenericParameters;
+			var imported_parameters = imported.GenericParameters;
+
+			for (int i = 0; i < parameters.Count; i++)
+				imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
+		}
+
+		TypeReference ImportTypeSpecification (TypeReference type, IGenericContext context)
+		{
+			switch (type.etype) {
+			case ElementType.SzArray:
+				var vector = (ArrayType) type;
+				return new ArrayType (ImportType (vector.ElementType, context));
+			case ElementType.Ptr:
+				var pointer = (PointerType) type;
+				return new PointerType (ImportType (pointer.ElementType, context));
+			case ElementType.ByRef:
+				var byref = (ByReferenceType) type;
+				return new ByReferenceType (ImportType (byref.ElementType, context));
+			case ElementType.Pinned:
+				var pinned = (PinnedType) type;
+				return new PinnedType (ImportType (pinned.ElementType, context));
+			case ElementType.Sentinel:
+				var sentinel = (SentinelType) type;
+				return new SentinelType (ImportType (sentinel.ElementType, context));
+			case ElementType.CModOpt:
+				var modopt = (OptionalModifierType) type;
+				return new OptionalModifierType (
+					ImportType (modopt.ModifierType, context),
+					ImportType (modopt.ElementType, context));
+			case ElementType.CModReqD:
+				var modreq = (RequiredModifierType) type;
+				return new RequiredModifierType (
+					ImportType (modreq.ModifierType, context),
+					ImportType (modreq.ElementType, context));
+			case ElementType.Array:
+				var array = (ArrayType) type;
+				var imported_array = new ArrayType (ImportType (array.ElementType, context));
+				if (array.IsVector)
+					return imported_array;
+
+				var dimensions = array.Dimensions;
+				var imported_dimensions = imported_array.Dimensions;
+
+				imported_dimensions.Clear ();
+
+				for (int i = 0; i < dimensions.Count; i++) {
+					var dimension = dimensions [i];
+
+					imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
+				}
+
+				return imported_array;
+			case ElementType.GenericInst:
+				var instance = (GenericInstanceType) type;
+				var element_type = ImportType (instance.ElementType, context);
+				var imported_instance = new GenericInstanceType (element_type);
+
+				var arguments = instance.GenericArguments;
+				var imported_arguments = imported_instance.GenericArguments;
+
+				for (int i = 0; i < arguments.Count; i++)
+					imported_arguments.Add (ImportType (arguments [i], context));
+
+				return imported_instance;
+			case ElementType.Var:
+				if (context == null || context.Type == null)
+					throw new InvalidOperationException ();
+
+				return ((TypeReference) context.Type).GetElementType ().GenericParameters [((GenericParameter) type).Position];
+			case ElementType.MVar:
+				if (context == null || context.Method == null)
+					throw new InvalidOperationException ();
+
+				return context.Method.GenericParameters [((GenericParameter) type).Position];
+			}
+
+			throw new NotSupportedException (type.etype.ToString ());
+		}
+
+		public FieldReference ImportField (FieldReference field, IGenericContext context)
+		{
+			var declaring_type = ImportType (field.DeclaringType, context);
+
+			return new FieldReference {
+				Name = field.Name,
+				DeclaringType = declaring_type,
+				FieldType = ImportType (field.FieldType, context ?? declaring_type),
+			};
+		}
+
+		public MethodReference ImportMethod (MethodReference method, IGenericContext context)
+		{
+			if (method.IsGenericInstance)
+				return ImportMethodSpecification (method, context);
+
+			var declaring_type = ImportType (method.DeclaringType, context);
+
+			var reference = new MethodReference {
+				Name = method.Name,
+				HasThis = method.HasThis,
+				ExplicitThis = method.ExplicitThis,
+				DeclaringType = declaring_type,
+			};
+
+			reference.CallingConvention = method.CallingConvention;
+
+			if (method.HasGenericParameters)
+				ImportGenericParameters (reference, method);
+
+			reference.ReturnType = ImportType (method.ReturnType, context ?? reference);
+
+			if (!method.HasParameters)
+				return reference;
+
+			var reference_parameters = reference.Parameters;
+
+			var parameters = method.Parameters;
+			for (int i = 0; i < parameters.Count; i++)
+				reference_parameters.Add (
+					new ParameterDefinition (ImportType (parameters [i].ParameterType, context ?? reference)));
+
+			return reference;
+		}
+
+		MethodSpecification ImportMethodSpecification (MethodReference method, IGenericContext context)
+		{
+			if (!method.IsGenericInstance)
+				throw new NotSupportedException ();
+
+			var instance = (GenericInstanceMethod) method;
+			var element_method = ImportMethod (instance.ElementMethod, context);
+			var imported_instance = new GenericInstanceMethod (element_method);
+
+			var arguments = instance.GenericArguments;
+			var imported_arguments = imported_instance.GenericArguments;
+
+			for (int i = 0; i < arguments.Count; i++)
+				imported_arguments.Add (ImportType (arguments [i], context));
+
+			return imported_instance;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/LinkedResource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/LinkedResource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/LinkedResource.cs	(revision 11807)
@@ -0,0 +1,60 @@
+//
+// LinkedResource.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public sealed class LinkedResource : Resource {
+
+		internal byte [] hash;
+		string file;
+
+		public byte [] Hash {
+			get { return hash; }
+		}
+
+		public string File {
+			get { return file; }
+			set { file = value; }
+		}
+
+		public override ResourceType ResourceType {
+			get { return ResourceType.Linked; }
+		}
+
+		public LinkedResource (string name, ManifestResourceAttributes flags)
+			: base (name, flags)
+		{
+		}
+
+		public LinkedResource (string name, ManifestResourceAttributes flags, string file)
+			: base (name, flags)
+		{
+			this.file = file;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ManifestResourceAttributes.cs	(revision 11807)
@@ -0,0 +1,39 @@
+//
+// ManifestResourceAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum ManifestResourceAttributes : uint {
+		VisibilityMask	= 0x0007,
+		Public			= 0x0001,	// The resource is exported from the Assembly
+		Private			= 0x0002	 // The resource is private to the Assembly
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MarshalInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MarshalInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MarshalInfo.cs	(revision 11807)
@@ -0,0 +1,171 @@
+//
+// MarshalInfo.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public class MarshalInfo {
+
+		internal NativeType native;
+
+		public NativeType NativeType {
+			get { return native; }
+			set { native = value; }
+		}
+
+		public MarshalInfo (NativeType native)
+		{
+			this.native = native;
+		}
+	}
+
+	public sealed class ArrayMarshalInfo : MarshalInfo {
+
+		internal NativeType element_type;
+		internal int size_parameter_index;
+		internal int size;
+		internal int size_parameter_multiplier;
+
+		public NativeType ElementType {
+			get { return element_type; }
+			set { element_type = value; }
+		}
+
+		public int SizeParameterIndex {
+			get { return size_parameter_index; }
+			set { size_parameter_index = value; }
+		}
+
+		public int Size {
+			get { return size; }
+			set { size = value; }
+		}
+
+		public int SizeParameterMultiplier {
+			get { return size_parameter_multiplier; }
+			set { size_parameter_multiplier = value; }
+		}
+
+		public ArrayMarshalInfo ()
+			: base (NativeType.Array)
+		{
+			element_type = NativeType.None;
+			size_parameter_index = -1;
+			size = -1;
+			size_parameter_multiplier = -1;
+		}
+	}
+
+	public sealed class CustomMarshalInfo : MarshalInfo {
+
+		internal Guid guid;
+		internal string unmanaged_type;
+		internal TypeReference managed_type;
+		internal string cookie;
+
+		public Guid Guid {
+			get { return guid; }
+			set { guid = value; }
+		}
+
+		public string UnmanagedType {
+			get { return unmanaged_type; }
+			set { unmanaged_type = value; }
+		}
+
+		public TypeReference ManagedType {
+			get { return managed_type; }
+			set { managed_type = value; }
+		}
+
+		public string Cookie {
+			get { return cookie; }
+			set { cookie = value; }
+		}
+
+		public CustomMarshalInfo ()
+			: base (NativeType.CustomMarshaler)
+		{
+		}
+	}
+
+	public sealed class SafeArrayMarshalInfo : MarshalInfo {
+
+		internal VariantType element_type;
+
+		public VariantType ElementType {
+			get { return element_type; }
+			set { element_type = value; }
+		}
+
+		public SafeArrayMarshalInfo ()
+			: base (NativeType.SafeArray)
+		{
+			element_type = VariantType.None;
+		}
+	}
+
+	public sealed class FixedArrayMarshalInfo : MarshalInfo {
+
+		internal NativeType element_type;
+		internal int size;
+
+		public NativeType ElementType {
+			get { return element_type; }
+			set { element_type = value; }
+		}
+
+		public int Size {
+			get { return size; }
+			set { size = value; }
+		}
+
+		public FixedArrayMarshalInfo ()
+			: base (NativeType.FixedArray)
+		{
+			element_type = NativeType.None;
+		}
+	}
+
+	public sealed class FixedSysStringMarshalInfo : MarshalInfo {
+
+		internal int size;
+
+		public int Size {
+			get { return size; }
+			set { size = value; }
+		}
+
+		public FixedSysStringMarshalInfo ()
+			: base (NativeType.FixedSysString)
+		{
+			size = -1;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MemberDefinitionCollection.cs	(revision 11807)
@@ -0,0 +1,92 @@
+//
+// MemberDefinitionCollection.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	class MemberDefinitionCollection<T> : Collection<T> where T : IMemberDefinition {
+
+		TypeDefinition container;
+
+		internal MemberDefinitionCollection (TypeDefinition container)
+		{
+			this.container = container;
+		}
+
+		internal MemberDefinitionCollection (TypeDefinition container, int capacity)
+			: base (capacity)
+		{
+			this.container = container;
+		}
+
+		protected override void OnAdd (T item, int index)
+		{
+			Attach (item);
+		}
+
+		protected sealed override void OnSet (T item, int index)
+		{
+			Attach (item);
+		}
+
+		protected sealed override void OnInsert (T item, int index)
+		{
+			Attach (item);
+		}
+
+		protected sealed override void OnRemove (T item, int index)
+		{
+			Detach (item);
+		}
+
+		protected sealed override void OnClear ()
+		{
+			foreach (var definition in this)
+				Detach (definition);
+		}
+
+		void Attach (T element)
+		{
+			if (element.DeclaringType == container)
+				return;
+
+			if (element.DeclaringType != null)
+				throw new ArgumentException ("Member already attached");
+
+			element.DeclaringType = this.container;
+		}
+
+		static void Detach (T element)
+		{
+			element.DeclaringType = null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MemberReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MemberReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MemberReference.cs	(revision 11807)
@@ -0,0 +1,101 @@
+//
+// MemberReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public abstract class MemberReference : IMetadataTokenProvider {
+
+		string name;
+		TypeReference declaring_type;
+
+		internal MetadataToken token;
+
+		public virtual string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public abstract string FullName {
+			get;
+		}
+
+		public virtual TypeReference DeclaringType {
+			get { return declaring_type; }
+			set { declaring_type = value; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return token; }
+			set { token = value; }
+		}
+
+		internal bool HasImage {
+			get {
+				var module = Module;
+				if (module == null)
+					return false;
+
+				return module.HasImage;
+			}
+		}
+
+		public virtual ModuleDefinition Module {
+			get { return declaring_type != null ? declaring_type.Module : null; }
+		}
+
+		public virtual bool IsDefinition {
+			get { return false; }
+		}
+
+		internal virtual bool ContainsGenericParameter {
+			get { return declaring_type != null && declaring_type.ContainsGenericParameter; }
+		}
+
+		internal MemberReference ()
+		{
+		}
+
+		internal MemberReference (string name)
+		{
+			this.name = name ?? string.Empty;
+		}
+
+		internal string MemberFullName ()
+		{
+			if (declaring_type == null)
+				return name;
+
+			return declaring_type.FullName + "::" + name;
+		}
+
+		public override string ToString ()
+		{
+			return FullName;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MetadataResolver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MetadataResolver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MetadataResolver.cs	(revision 11807)
@@ -0,0 +1,324 @@
+//
+// MetadataResolver.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public interface IAssemblyResolver {
+		AssemblyDefinition Resolve (AssemblyNameReference name);
+		AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters);
+
+		AssemblyDefinition Resolve (string fullName);
+		AssemblyDefinition Resolve (string fullName, ReaderParameters parameters);
+	}
+
+	public class ResolutionException : Exception {
+
+		readonly MemberReference member;
+
+		public MemberReference Member {
+			get { return member; }
+		}
+
+		public ResolutionException (MemberReference member)
+			: base ("Failed to resolve " + member.FullName)
+		{
+			this.member = member;
+		}
+	}
+
+	static class MetadataResolver {
+
+		public static TypeDefinition Resolve (IAssemblyResolver resolver, TypeReference type)
+		{
+			type = type.GetElementType ();
+
+			var scope = type.Scope;
+			switch (scope.MetadataScopeType) {
+			case MetadataScopeType.AssemblyNameReference:
+				var assembly = resolver.Resolve ((AssemblyNameReference) scope);
+				if (assembly == null)
+					return null;
+
+				return GetType (resolver, assembly.MainModule, type);
+			case MetadataScopeType.ModuleDefinition:
+				return GetType (resolver, (ModuleDefinition) scope, type);
+			case MetadataScopeType.ModuleReference:
+				var modules = type.Module.Assembly.Modules;
+				var module_ref = (ModuleReference) scope;
+				for (int i = 0; i < modules.Count; i++) {
+					var netmodule = modules [i];
+					if (netmodule.Name == module_ref.Name)
+						return GetType (resolver, netmodule, type);
+				}
+				break;
+			}
+
+			throw new NotSupportedException ();
+		}
+
+		static TypeDefinition GetType (IAssemblyResolver resolver, ModuleDefinition module, TypeReference reference)
+		{
+			var type = GetType (module, reference);
+			if (type != null)
+				return type;
+
+			if (!module.HasExportedTypes)
+				return null;
+
+			var exported_types = module.ExportedTypes;
+
+			for (int i = 0; i < exported_types.Count; i++) {
+				var exported_type = exported_types [i];
+				if (exported_type.Name != reference.Name)
+					continue;
+
+				if (exported_type.Namespace != reference.Namespace)
+					continue;
+
+				return exported_type.Resolve ();
+			}
+
+			return null;
+		}
+
+		static TypeDefinition GetType (ModuleDefinition module, TypeReference type)
+		{
+			if (!type.IsNested)
+				return module.GetType (type.Namespace, type.Name);
+
+			var declaring_type = type.DeclaringType.Resolve ();
+			if (declaring_type == null)
+				return null;
+
+			return declaring_type.GetNestedType (type.Name);
+		}
+
+		public static FieldDefinition Resolve (IAssemblyResolver resolver, FieldReference field)
+		{
+			var type = Resolve (resolver, field.DeclaringType);
+			if (type == null)
+				return null;
+
+			if (!type.HasFields)
+				return null;
+
+			return GetField (resolver, type, field);
+		}
+
+		static FieldDefinition GetField (IAssemblyResolver resolver, TypeDefinition type, FieldReference reference)
+		{
+			while (type != null) {
+				var field = GetField (type.Fields, reference);
+				if (field != null)
+					return field;
+
+				if (type.BaseType == null)
+					return null;
+
+				type = Resolve (resolver, type.BaseType);
+			}
+
+			return null;
+		}
+
+		static FieldDefinition GetField (IList<FieldDefinition> fields, FieldReference reference)
+		{
+			for (int i = 0; i < fields.Count; i++) {
+				var field = fields [i];
+
+				if (field.Name != reference.Name)
+					continue;
+
+				if (!AreSame (field.FieldType, reference.FieldType))
+					continue;
+
+				return field;
+			}
+
+			return null;
+		}
+
+		public static MethodDefinition Resolve (IAssemblyResolver resolver, MethodReference method)
+		{
+			var type = Resolve (resolver, method.DeclaringType);
+			if (type == null)
+				return null;
+
+			method = method.GetElementMethod ();
+
+			if (!type.HasMethods)
+				return null;
+
+			return GetMethod (resolver, type, method);
+		}
+
+		static MethodDefinition GetMethod (IAssemblyResolver resolver, TypeDefinition type, MethodReference reference)
+		{
+			while (type != null) {
+				var method = GetMethod (type.Methods, reference);
+				if (method != null)
+					return method;
+
+				if (type.BaseType == null)
+					return null;
+
+				type = Resolve (resolver, type.BaseType);
+			}
+
+			return null;
+		}
+
+		public static MethodDefinition GetMethod (IList<MethodDefinition> methods, MethodReference reference)
+		{
+			for (int i = 0; i < methods.Count; i++) {
+				var method = methods [i];
+
+				if (method.Name != reference.Name)
+					continue;
+
+				if (method.HasGenericParameters != reference.HasGenericParameters)
+					continue;
+
+				if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count)
+					continue;
+
+				if (!AreSame (method.ReturnType, reference.ReturnType))
+					continue;
+
+				if (method.HasParameters != reference.HasParameters)
+					continue;
+
+				if (!method.HasParameters && !reference.HasParameters)
+					return method;
+
+				if (!AreSame (method.Parameters, reference.Parameters))
+					continue;
+
+				return method;
+			}
+
+			return null;
+		}
+
+		static bool AreSame (Collection<ParameterDefinition> a, Collection<ParameterDefinition> b)
+		{
+			var count = a.Count;
+
+			if (count != b.Count)
+				return false;
+
+			if (count == 0)
+				return true;
+
+			for (int i = 0; i < count; i++)
+				if (!AreSame (a [i].ParameterType, b [i].ParameterType))
+					return false;
+
+			return true;
+		}
+
+		static bool AreSame (TypeSpecification a, TypeSpecification b)
+		{
+			if (!AreSame (a.ElementType, b.ElementType))
+				return false;
+
+			if (a.IsGenericInstance)
+				return AreSame ((GenericInstanceType) a, (GenericInstanceType) b);
+
+			if (a.IsRequiredModifier || a.IsOptionalModifier)
+				return AreSame ((IModifierType) a, (IModifierType) b);
+
+			if (a.IsArray)
+				return AreSame ((ArrayType) a, (ArrayType) b);
+
+			return true;
+		}
+
+		static bool AreSame (ArrayType a, ArrayType b)
+		{
+			if (a.Rank != b.Rank)
+				return false;
+
+			// TODO: dimensions
+
+			return true;
+		}
+
+		static bool AreSame (IModifierType a, IModifierType b)
+		{
+			return AreSame (a.ModifierType, b.ModifierType);
+		}
+
+		static bool AreSame (GenericInstanceType a, GenericInstanceType b)
+		{
+			if (a.GenericArguments.Count != b.GenericArguments.Count)
+				return false;
+
+			for (int i = 0; i < a.GenericArguments.Count; i++)
+				if (!AreSame (a.GenericArguments [i], b.GenericArguments [i]))
+					return false;
+
+			return true;
+		}
+
+		static bool AreSame (GenericParameter a, GenericParameter b)
+		{
+			return a.Position == b.Position;
+		}
+
+		static bool AreSame (TypeReference a, TypeReference b)
+		{
+			if (ReferenceEquals (a, b))
+				return true;
+
+			if (a == null || b == null)
+				return false;
+
+			if (a.etype != b.etype)
+				return false;
+
+			if (a.IsGenericParameter)
+				return AreSame ((GenericParameter) a, (GenericParameter) b);
+
+			if (a.IsTypeSpecification ())
+				return AreSame ((TypeSpecification) a, (TypeSpecification) b);
+
+			if (a.Name != b.Name || a.Namespace != b.Namespace)
+				return false;
+
+			//TODO: check scope
+
+			return AreSame (a.DeclaringType, b.DeclaringType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MetadataSystem.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MetadataSystem.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MetadataSystem.cs	(revision 11807)
@@ -0,0 +1,380 @@
+//
+// MetadataSystem.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	struct Range {
+		public uint Start;
+		public uint Length;
+
+		public Range (uint index, uint length)
+		{
+			this.Start = index;
+			this.Length = length;
+		}
+	}
+
+	sealed class MetadataSystem {
+
+		internal AssemblyNameReference [] AssemblyReferences;
+		internal ModuleReference [] ModuleReferences;
+
+		internal TypeDefinition [] Types;
+		internal TypeReference [] TypeReferences;
+
+		internal FieldDefinition [] Fields;
+		internal MethodDefinition [] Methods;
+		internal MemberReference [] MemberReferences;
+
+		internal Dictionary<uint, uint []> NestedTypes;
+		internal Dictionary<uint, uint> ReverseNestedTypes;
+		internal Dictionary<uint, MetadataToken []> Interfaces;
+		internal Dictionary<uint, Row<ushort, uint>> ClassLayouts;
+		internal Dictionary<uint, uint> FieldLayouts;
+		internal Dictionary<uint, uint> FieldRVAs;
+		internal Dictionary<MetadataToken, uint> FieldMarshals;
+		internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants;
+		internal Dictionary<uint, MetadataToken []> Overrides;
+		internal Dictionary<MetadataToken, Range> CustomAttributes;
+		internal Dictionary<MetadataToken, Range> SecurityDeclarations;
+		internal Dictionary<uint, Range> Events;
+		internal Dictionary<uint, Range> Properties;
+		internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics;
+		internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes;
+		internal Dictionary<MetadataToken, Range> GenericParameters;
+		internal Dictionary<uint, MetadataToken []> GenericConstraints;
+
+		static Dictionary<string, Row<ElementType, bool>> primitive_value_types;
+
+		static void InitializePrimitives ()
+		{
+			primitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18) {
+				{ "Void", new Row<ElementType, bool> (ElementType.Void, false) },
+				{ "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) },
+				{ "Char", new Row<ElementType, bool> (ElementType.Char, true) },
+				{ "SByte", new Row<ElementType, bool> (ElementType.I1, true) },
+				{ "Byte", new Row<ElementType, bool> (ElementType.U1, true) },
+				{ "Int16", new Row<ElementType, bool> (ElementType.I2, true) },
+				{ "UInt16", new Row<ElementType, bool> (ElementType.U2, true) },
+				{ "Int32", new Row<ElementType, bool> (ElementType.I4, true) },
+				{ "UInt32", new Row<ElementType, bool> (ElementType.U4, true) },
+				{ "Int64", new Row<ElementType, bool> (ElementType.I8, true) },
+				{ "UInt64", new Row<ElementType, bool> (ElementType.U8, true) },
+				{ "Single", new Row<ElementType, bool> (ElementType.R4, true) },
+				{ "Double", new Row<ElementType, bool> (ElementType.R8, true) },
+				{ "String", new Row<ElementType, bool> (ElementType.String, false) },
+				{ "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) },
+				{ "IntPtr", new Row<ElementType, bool> (ElementType.I, true) },
+				{ "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) },
+				{ "Object", new Row<ElementType, bool> (ElementType.Object, false) },
+			};
+		}
+
+		public static void TryProcessPrimitiveType (TypeReference type)
+		{
+			var scope = type.scope;
+			if (scope == null)
+				return;
+
+			if (scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)
+				return;
+
+			if (scope.Name != "mscorlib")
+				return;
+
+			if (type.Namespace != "System")
+				return;
+
+			if (primitive_value_types == null)
+				InitializePrimitives ();
+
+			Row<ElementType, bool> primitive_data;
+			if (!primitive_value_types.TryGetValue (type.Name, out primitive_data))
+				return;
+
+			type.etype = primitive_data.Col1;
+			type.IsValueType = primitive_data.Col2;
+		}
+
+		public void Clear ()
+		{
+			if (NestedTypes != null) NestedTypes.Clear ();
+			if (ReverseNestedTypes != null) ReverseNestedTypes.Clear ();
+			if (Interfaces != null) Interfaces.Clear ();
+			if (ClassLayouts != null) ClassLayouts.Clear ();
+			if (FieldLayouts != null) FieldLayouts.Clear ();
+			if (FieldRVAs != null) FieldRVAs.Clear ();
+			if (FieldMarshals != null) FieldMarshals.Clear ();
+			if (Constants != null) Constants.Clear ();
+			if (Overrides != null) Overrides.Clear ();
+			if (CustomAttributes != null) CustomAttributes.Clear ();
+			if (SecurityDeclarations != null) SecurityDeclarations.Clear ();
+			if (Events != null) Events.Clear ();
+			if (Properties != null) Properties.Clear ();
+			if (Semantics != null) Semantics.Clear ();
+			if (PInvokes != null) PInvokes.Clear ();
+			if (GenericParameters != null) GenericParameters.Clear ();
+			if (GenericConstraints != null) GenericConstraints.Clear ();
+		}
+
+		public TypeDefinition GetTypeDefinition (uint rid)
+		{
+			if (rid < 1 || rid > Types.Length)
+				return null;
+
+			return Types [rid - 1];
+		}
+
+		public void AddTypeDefinition (TypeDefinition type)
+		{
+			Types [type.token.RID - 1] = type;
+		}
+
+		public TypeReference GetTypeReference (uint rid)
+		{
+			if (rid < 1 || rid > TypeReferences.Length)
+				return null;
+
+			return TypeReferences [rid - 1];
+		}
+
+		public void AddTypeReference (TypeReference type)
+		{
+			TypeReferences [type.token.RID - 1] = type;
+		}
+
+		public FieldDefinition GetFieldDefinition (uint rid)
+		{
+			if (rid < 1 || rid > Fields.Length)
+				return null;
+
+			return Fields [rid - 1];
+		}
+
+		public void AddFieldDefinition (FieldDefinition field)
+		{
+			Fields [field.token.RID - 1] = field;
+		}
+
+		public MethodDefinition GetMethodDefinition (uint rid)
+		{
+			if (rid < 1 || rid > Methods.Length)
+				return null;
+
+			return Methods [rid - 1];
+		}
+
+		public void AddMethodDefinition (MethodDefinition method)
+		{
+			Methods [method.token.RID - 1] = method;
+		}
+
+		public MemberReference GetMemberReference (uint rid)
+		{
+			if (rid < 1 || rid > MemberReferences.Length)
+				return null;
+
+			return MemberReferences [rid - 1];
+		}
+
+		public void AddMemberReference (MemberReference member)
+		{
+			MemberReferences [member.token.RID - 1] = member;
+		}
+
+		public bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping)
+		{
+			return NestedTypes.TryGetValue (type.token.RID, out mapping);
+		}
+
+		public void SetNestedTypeMapping (uint type_rid, uint [] mapping)
+		{
+			NestedTypes [type_rid] = mapping;
+		}
+
+		public void RemoveNestedTypeMapping (TypeDefinition type)
+		{
+			NestedTypes.Remove (type.token.RID);
+		}
+
+		public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring)
+		{
+			return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring);
+		}
+
+		public void SetReverseNestedTypeMapping (uint nested, uint declaring)
+		{
+			ReverseNestedTypes.Add (nested, declaring);
+		}
+
+		public void RemoveReverseNestedTypeMapping (TypeDefinition type)
+		{
+			ReverseNestedTypes.Remove (type.token.RID);
+		}
+
+		public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)
+		{
+			return Interfaces.TryGetValue (type.token.RID, out mapping);
+		}
+
+		public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)
+		{
+			Interfaces [type_rid] = mapping;
+		}
+
+		public void RemoveInterfaceMapping (TypeDefinition type)
+		{
+			Interfaces.Remove (type.token.RID);
+		}
+
+		public void AddPropertiesRange (uint type_rid, Range range)
+		{
+			Properties.Add (type_rid, range);
+		}
+
+		public bool TryGetPropertiesRange (TypeDefinition type, out Range range)
+		{
+			return Properties.TryGetValue (type.token.RID, out range);
+		}
+
+		public void RemovePropertiesRange (TypeDefinition type)
+		{
+			Properties.Remove (type.token.RID);
+		}
+
+		public void AddEventsRange (uint type_rid, Range range)
+		{
+			Events.Add (type_rid, range);
+		}
+
+		public bool TryGetEventsRange (TypeDefinition type, out Range range)
+		{
+			return Events.TryGetValue (type.token.RID, out range);
+		}
+
+		public void RemoveEventsRange (TypeDefinition type)
+		{
+			Events.Remove (type.token.RID);
+		}
+
+		public bool TryGetGenericParameterRange (IGenericParameterProvider owner, out Range range)
+		{
+			return GenericParameters.TryGetValue (owner.MetadataToken, out range);
+		}
+
+		public void RemoveGenericParameterRange (IGenericParameterProvider owner)
+		{
+			GenericParameters.Remove (owner.MetadataToken);
+		}
+
+		public bool TryGetCustomAttributeRange (ICustomAttributeProvider owner, out Range range)
+		{
+			return CustomAttributes.TryGetValue (owner.MetadataToken, out range);
+		}
+
+		public void RemoveCustomAttributeRange (ICustomAttributeProvider owner)
+		{
+			CustomAttributes.Remove (owner.MetadataToken);
+		}
+
+		public bool TryGetSecurityDeclarationRange (ISecurityDeclarationProvider owner, out Range range)
+		{
+			return SecurityDeclarations.TryGetValue (owner.MetadataToken, out range);
+		}
+
+		public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner)
+		{
+			SecurityDeclarations.Remove (owner.MetadataToken);
+		}
+
+		public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)
+		{
+			return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);
+		}
+
+		public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)
+		{
+			GenericConstraints [gp_rid] = mapping;
+		}
+
+		public void RemoveGenericConstraintMapping (GenericParameter generic_parameter)
+		{
+			GenericConstraints.Remove (generic_parameter.token.RID);
+		}
+
+		public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)
+		{
+			return Overrides.TryGetValue (method.token.RID, out mapping);
+		}
+
+		public void SetOverrideMapping (uint rid, MetadataToken [] mapping)
+		{
+			Overrides [rid] = mapping;
+		}
+
+		public void RemoveOverrideMapping (MethodDefinition method)
+		{
+			Overrides.Remove (method.token.RID);
+		}
+
+		public TypeDefinition GetFieldDeclaringType (uint field_rid)
+		{
+			return BinaryRangeSearch (Types, field_rid, true);
+		}
+
+		public TypeDefinition GetMethodDeclaringType (uint method_rid)
+		{
+			return BinaryRangeSearch (Types, method_rid, false);
+		}
+
+		static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field)
+		{
+			int min = 0;
+			int max = types.Length - 1;
+			while (min <= max) {
+				int mid = min + ((max - min) / 2);
+				var type = types [mid];
+				var range = field ? type.fields_range : type.methods_range;
+
+				if (rid < range.Start)
+					max = mid - 1;
+				else if (rid >= range.Start + range.Length)
+					min = mid + 1;
+				else
+					return type;
+			}
+
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodAttributes.cs	(revision 11807)
@@ -0,0 +1,66 @@
+//
+// MethodAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum MethodAttributes : ushort {
+		MemberAccessMask	= 0x0007,
+		CompilerControlled	= 0x0000,	// Member not referenceable
+		Private				= 0x0001,	// Accessible only by the parent type
+		FamANDAssem			= 0x0002,	// Accessible by sub-types only in this Assembly
+		Assembly				= 0x0003,	// Accessibly by anyone in the Assembly
+		Family				= 0x0004,	// Accessible only by type and sub-types
+		FamORAssem			= 0x0005,	// Accessibly by sub-types anywhere, plus anyone in assembly
+		Public				= 0x0006,	// Accessibly by anyone who has visibility to this scope
+
+		Static				= 0x0010,	// Defined on type, else per instance
+		Final				= 0x0020,	// Method may not be overridden
+		Virtual				= 0x0040,	// Method is virtual
+		HideBySig			= 0x0080,	// Method hides by name+sig, else just by name
+
+		VtableLayoutMask	= 0x0100,	// Use this mask to retrieve vtable attributes
+		ReuseSlot			= 0x0000,	// Method reuses existing slot in vtable
+		NewSlot				= 0x0100,	// Method always gets a new slot in the vtable
+
+		CheckAccessOnOverride = 0x0200,   // Method can only be overriden if also accessible
+		Abstract			= 0x0400,	// Method does not provide an implementation
+		SpecialName			= 0x0800,	// Method is special
+
+		// Interop Attributes
+		PInvokeImpl			= 0x2000,	// Implementation is forwarded through PInvoke
+		UnmanagedExport		= 0x0008,	// Reserved: shall be zero for conforming implementations
+
+		// Additional flags
+		RTSpecialName		= 0x1000,	// CLI provides 'special' behavior, depending upon the name of the method
+		HasSecurity			= 0x4000,	// Method has security associate with it
+		RequireSecObject	= 0x8000	 // Method calls another method containing security code
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodCallingConvention.cs	(revision 11807)
@@ -0,0 +1,40 @@
+//
+// MethodCallingConvention.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum MethodCallingConvention : byte {
+		Default		= 0x0,
+		C			= 0x1,
+		StdCall		= 0x2,
+		ThisCall	= 0x3,
+		FastCall	= 0x4,
+		VarArg		= 0x5,
+		Generic		= 0x10,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodDefinition.cs	(revision 11807)
@@ -0,0 +1,487 @@
+//
+// MethodDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Cecil.Cil;
+using Mono.Collections.Generic;
+
+using RVA = System.UInt32;
+
+namespace Mono.Cecil {
+
+	public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider {
+
+		ushort attributes;
+		ushort impl_attributes;
+		internal MethodSemanticsAttributes? sem_attrs;
+		Collection<CustomAttribute> custom_attributes;
+		Collection<SecurityDeclaration> security_declarations;
+
+		internal RVA rva;
+		internal PInvokeInfo pinvoke;
+		Collection<MethodReference> overrides;
+
+		internal MethodBody body;
+
+		public MethodAttributes Attributes {
+			get { return (MethodAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public MethodImplAttributes ImplAttributes {
+			get { return (MethodImplAttributes) impl_attributes; }
+			set { impl_attributes = (ushort) value; }
+		}
+
+		public MethodSemanticsAttributes SemanticsAttributes {
+			get {
+				if (sem_attrs.HasValue)
+					return sem_attrs.Value;
+
+				if (HasImage) {
+					ReadSemantics ();
+					return sem_attrs.Value;
+				}
+
+				sem_attrs = MethodSemanticsAttributes.None;
+				return sem_attrs.Value;
+			}
+			set { sem_attrs = value; }
+		}
+
+		internal void ReadSemantics ()
+		{
+			if (sem_attrs.HasValue)
+				return;
+
+			var module = this.Module;
+			if (module == null)
+				return;
+
+			if (!module.HasImage)
+				return;
+
+			module.Read (this, (method, reader) => reader.ReadAllSemantics (method));
+		}
+
+		public bool HasSecurityDeclarations {
+			get {
+				if (security_declarations != null)
+					return security_declarations.Count > 0;
+
+				return this.GetHasSecurityDeclarations (Module);
+			}
+		}
+
+		public Collection<SecurityDeclaration> SecurityDeclarations {
+			get { return security_declarations ?? (security_declarations = this.GetSecurityDeclarations (Module)); }
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
+		}
+
+		public int RVA {
+			get { return (int) rva; }
+		}
+
+		public bool HasBody {
+			get {
+				return (attributes & (ushort) MethodAttributes.Abstract) == 0 &&
+					(attributes & (ushort) MethodAttributes.PInvokeImpl) == 0 &&
+					(impl_attributes & (ushort) MethodImplAttributes.InternalCall) == 0 &&
+					(impl_attributes & (ushort) MethodImplAttributes.Native) == 0 &&
+					(impl_attributes & (ushort) MethodImplAttributes.Unmanaged) == 0 &&
+					(impl_attributes & (ushort) MethodImplAttributes.Runtime) == 0;
+			}
+		}
+
+		public MethodBody Body {
+			get {
+				if (body != null)
+					return body;
+
+				if (!HasBody)
+					return null;
+
+				if (HasImage && rva != 0)
+					return body = Module.Read (this, (method, reader) => reader.ReadMethodBody (method));
+
+				return body = new MethodBody (this);
+			}
+			set { body = value; }
+		}
+
+		public bool HasPInvokeInfo {
+			get {
+				if (pinvoke != null)
+					return true;
+
+				return IsPInvokeImpl;
+			}
+		}
+
+		public PInvokeInfo PInvokeInfo {
+			get {
+				if (pinvoke != null)
+					return pinvoke;
+
+				if (HasImage && IsPInvokeImpl)
+					return pinvoke = Module.Read (this, (method, reader) => reader.ReadPInvokeInfo (method));
+
+				return null;
+			}
+			set {
+				IsPInvokeImpl = true;
+				pinvoke = value;
+			}
+		}
+
+		public bool HasOverrides {
+			get {
+				if (overrides != null)
+					return overrides.Count > 0;
+
+				if (HasImage)
+					return Module.Read (this, (method, reader) => reader.HasOverrides (method));
+
+				return false;
+			}
+		}
+
+		public Collection<MethodReference> Overrides {
+			get {
+				if (overrides != null)
+					return overrides;
+
+				if (HasImage)
+					return overrides = Module.Read (this, (method, reader) => reader.ReadOverrides (method));
+
+				return overrides = new Collection<MethodReference> ();
+			}
+		}
+
+		public override bool HasGenericParameters {
+			get {
+				if (generic_parameters != null)
+					return generic_parameters.Count > 0;
+
+				return this.GetHasGenericParameters (Module);
+			}
+		}
+
+		public override Collection<GenericParameter> GenericParameters {
+			get { return generic_parameters ?? (generic_parameters = this.GetGenericParameters (Module)); }
+		}
+
+		#region MethodAttributes
+
+		public bool IsCompilerControlled {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled, value); }
+		}
+
+		public bool IsPrivate {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private, value); }
+		}
+
+		public bool IsFamilyAndAssembly {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem, value); }
+		}
+
+		public bool IsAssembly {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly, value); }
+		}
+
+		public bool IsFamily {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family, value); }
+		}
+
+		public bool IsFamilyOrAssembly {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem, value); }
+		}
+
+		public bool IsPublic {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public, value); }
+		}
+
+		public bool IsStatic {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.Static); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Static, value); }
+		}
+
+		public bool IsFinal {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.Final); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Final, value); }
+		}
+
+		public bool IsVirtual {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.Virtual); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Virtual, value); }
+		}
+
+		public bool IsHideBySig {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.HideBySig); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HideBySig, value); }
+		}
+
+		public bool IsReuseSlot {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot, value); }
+		}
+
+		public bool IsNewSlot {
+			get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot, value); }
+		}
+
+		public bool IsCheckAccessOnOverride {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride, value); }
+		}
+
+		public bool IsAbstract {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.Abstract); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Abstract, value); }
+		}
+
+		public bool IsSpecialName {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.SpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.SpecialName, value); }
+		}
+
+		public bool IsPInvokeImpl {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.PInvokeImpl); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.PInvokeImpl, value); }
+		}
+
+		public bool IsUnmanagedExport {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.UnmanagedExport); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.UnmanagedExport, value); }
+		}
+
+		public bool IsRuntimeSpecialName {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.RTSpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.RTSpecialName, value); }
+		}
+
+		public bool HasSecurity {
+			get { return attributes.GetAttributes ((ushort) MethodAttributes.HasSecurity); }
+			set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HasSecurity, value); }
+		}
+
+		#endregion
+
+		#region MethodImplAttributes
+
+		public bool IsIL {
+			get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL); }
+			set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL, value); }
+		}
+
+		public bool IsNative {
+			get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native); }
+			set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native, value); }
+		}
+
+		public bool IsRuntime {
+			get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime); }
+			set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime, value); }
+		}
+
+		public bool IsUnmanaged {
+			get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged); }
+			set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged, value); }
+		}
+
+		public bool IsManaged {
+			get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed); }
+			set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed, value); }
+		}
+
+		public bool IsForwardRef {
+			get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.ForwardRef); }
+			set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.ForwardRef, value); }
+		}
+
+		public bool IsPreserveSig {
+			get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.PreserveSig); }
+			set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.PreserveSig, value); }
+		}
+
+		public bool IsInternalCall {
+			get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.InternalCall); }
+			set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.InternalCall, value); }
+		}
+
+		public bool IsSynchronized {
+			get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.Synchronized); }
+			set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.Synchronized, value); }
+		}
+
+		public bool NoInlining {
+			get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoInlining); }
+			set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoInlining, value); }
+		}
+
+		public bool NoOptimization {
+			get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoOptimization); }
+			set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoOptimization, value); }
+		}
+
+		#endregion
+
+		#region MethodSemanticsAttributes
+
+		public bool IsSetter {
+			get { return this.GetSemantics (MethodSemanticsAttributes.Setter); }
+			set { this.SetSemantics (MethodSemanticsAttributes.Setter, value); }
+		}
+
+		public bool IsGetter {
+			get { return this.GetSemantics (MethodSemanticsAttributes.Getter); }
+			set { this.SetSemantics (MethodSemanticsAttributes.Getter, value); }
+		}
+
+		public bool IsOther {
+			get { return this.GetSemantics (MethodSemanticsAttributes.Other); }
+			set { this.SetSemantics (MethodSemanticsAttributes.Other, value); }
+		}
+
+		public bool IsAddOn {
+			get { return this.GetSemantics (MethodSemanticsAttributes.AddOn); }
+			set { this.SetSemantics (MethodSemanticsAttributes.AddOn, value); }
+		}
+
+		public bool IsRemoveOn {
+			get { return this.GetSemantics (MethodSemanticsAttributes.RemoveOn); }
+			set { this.SetSemantics (MethodSemanticsAttributes.RemoveOn, value); }
+		}
+
+		public bool IsFire {
+			get { return this.GetSemantics (MethodSemanticsAttributes.Fire); }
+			set { this.SetSemantics (MethodSemanticsAttributes.Fire, value); }
+		}
+
+		#endregion
+
+		public new TypeDefinition DeclaringType {
+			get { return (TypeDefinition) base.DeclaringType; }
+			set { base.DeclaringType = value; }
+		}
+
+		public bool IsConstructor {
+			get {
+				return this.IsRuntimeSpecialName
+					&& this.IsSpecialName
+					&& (this.Name == ".cctor" || this.Name == ".ctor");
+			}
+		}
+
+		public override bool IsDefinition {
+			get { return true; }
+		}
+
+		internal MethodDefinition ()
+		{
+			this.token = new MetadataToken (TokenType.Method);
+		}
+
+		public MethodDefinition (string name, MethodAttributes attributes, TypeReference returnType)
+			: base (name, returnType)
+		{
+			this.attributes = (ushort) attributes;
+			this.HasThis = !this.IsStatic;
+			this.token = new MetadataToken (TokenType.Method);
+		}
+
+		public override MethodDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+
+	static partial class Mixin {
+
+		public static ParameterDefinition GetParameter (this MethodBody self, int index)
+		{
+			var method = self.method;
+
+			if (method.HasThis) {
+				if (index == 0)
+					return self.ThisParameter;
+
+				index--;
+			}
+
+			var parameters = method.Parameters;
+
+			if (index < 0 || index >= parameters.size)
+				return null;
+
+			return parameters [index];
+		}
+
+		public static VariableDefinition GetVariable (this MethodBody self, int index)
+		{
+			var variables = self.Variables;
+
+			if (index < 0 || index >= variables.size)
+				return null;
+
+			return variables [index];
+		}
+
+		public static bool GetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics)
+		{
+			return (self.SemanticsAttributes & semantics) != 0;
+		}
+
+		public static void SetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
+		{
+			if (value)
+				self.SemanticsAttributes |= semantics;
+			else
+				self.SemanticsAttributes &= ~semantics;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodImplAttributes.cs	(revision 11807)
@@ -0,0 +1,54 @@
+//
+// MethodImplAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum MethodImplAttributes : ushort {
+		CodeTypeMask		= 0x0003,
+		IL					= 0x0000,	// Method impl is CIL
+		Native				= 0x0001,	// Method impl is native
+		OPTIL				= 0x0002,	// Reserved: shall be zero in conforming implementations
+		Runtime				= 0x0003,	// Method impl is provided by the runtime
+
+		ManagedMask			= 0x0004,	// Flags specifying whether the code is managed or unmanaged
+		Unmanaged			= 0x0004,	// Method impl is unmanaged, otherwise managed
+		Managed				= 0x0000,	// Method impl is managed
+
+		// Implementation info and interop
+		ForwardRef			= 0x0010,	// Indicates method is defined; used primarily in merge scenarios
+		PreserveSig			= 0x0080,	// Reserved: conforming implementations may ignore
+		InternalCall		= 0x1000,	// Reserved: shall be zero in conforming implementations
+		Synchronized		= 0x0020,	// Method is single threaded through the body
+		NoOptimization		= 0x0040,	// Method is not optimized by the JIT.
+		NoInlining			= 0x0008,	// Method may not be inlined
+		MaxMethodImplVal	= 0xffff	 // Range check value
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodReference.cs	(revision 11807)
@@ -0,0 +1,214 @@
+//
+// MethodReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext {
+
+		internal ParameterDefinitionCollection parameters;
+		MethodReturnType return_type;
+
+		bool has_this;
+		bool explicit_this;
+		MethodCallingConvention calling_convention;
+		internal Collection<GenericParameter> generic_parameters;
+
+		public virtual bool HasThis {
+			get { return has_this; }
+			set { has_this = value; }
+		}
+
+		public virtual bool ExplicitThis {
+			get { return explicit_this; }
+			set { explicit_this = value; }
+		}
+
+		public virtual MethodCallingConvention CallingConvention {
+			get { return calling_convention; }
+			set { calling_convention = value; }
+		}
+
+		public virtual bool HasParameters {
+			get { return !parameters.IsNullOrEmpty (); }
+		}
+
+		public virtual Collection<ParameterDefinition> Parameters {
+			get {
+				if (parameters == null)
+					parameters = new ParameterDefinitionCollection (this);
+
+				return parameters;
+			}
+		}
+
+		IGenericParameterProvider IGenericContext.Type {
+			get {
+				var declaring_type = this.DeclaringType;
+				var instance = declaring_type as GenericInstanceType;
+				if (instance != null)
+					return instance.ElementType;
+
+				return declaring_type;
+			}
+		}
+
+		IGenericParameterProvider IGenericContext.Method {
+			get { return this; }
+		}
+
+		GenericParameterType IGenericParameterProvider.GenericParameterType {
+			get { return GenericParameterType.Method; }
+		}
+
+		public virtual bool HasGenericParameters {
+			get { return !generic_parameters.IsNullOrEmpty (); }
+		}
+
+		public virtual Collection<GenericParameter> GenericParameters {
+			get {
+				if (generic_parameters != null)
+					return generic_parameters;
+
+				return generic_parameters = new Collection<GenericParameter> ();
+			}
+		}
+
+		public TypeReference ReturnType {
+			get {
+				var return_type = MethodReturnType;
+				return return_type != null ? return_type.ReturnType : null;
+			}
+			set {
+				var return_type = MethodReturnType;
+				if (return_type != null)
+					return_type.ReturnType = value;
+			}
+		}
+
+		public virtual MethodReturnType MethodReturnType {
+			get { return return_type; }
+			set { return_type = value; }
+		}
+
+		public override string FullName {
+			get {
+				var builder = new StringBuilder ();
+				builder.Append (ReturnType.FullName)
+					.Append (" ")
+					.Append (MemberFullName ());
+				this.MethodSignatureFullName (builder);
+				return builder.ToString ();
+			}
+		}
+
+		public virtual bool IsGenericInstance {
+			get { return false; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get {
+				if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter)
+					return true;
+
+				var parameters = this.Parameters;
+
+				for (int i = 0; i < parameters.Count; i++)
+					if (parameters [i].ParameterType.ContainsGenericParameter)
+						return true;
+
+				return false;
+			}
+		}
+
+		internal MethodReference ()
+		{
+			this.return_type = new MethodReturnType (this);
+			this.token = new MetadataToken (TokenType.MemberRef);
+		}
+
+		public MethodReference (string name, TypeReference returnType)
+			: base (name)
+		{
+			if (returnType == null)
+				throw new ArgumentNullException ("returnType");
+
+			this.return_type = new MethodReturnType (this);
+			this.return_type.ReturnType = returnType;
+			this.token = new MetadataToken (TokenType.MemberRef);
+		}
+
+		public MethodReference (string name, TypeReference returnType, TypeReference declaringType)
+			: this (name, returnType)
+		{
+			if (declaringType == null)
+				throw new ArgumentNullException ("declaringType");
+
+			this.DeclaringType = declaringType;
+		}
+
+		public virtual MethodReference GetElementMethod ()
+		{
+			return this;
+		}
+
+		public virtual MethodDefinition Resolve ()
+		{
+			var module = this.Module;
+			if (module == null)
+				throw new NotSupportedException ();
+
+			return module.Resolve (this);
+		}
+	}
+
+	static partial class Mixin {
+
+		public static bool IsVarArg (this IMethodSignature self)
+		{
+			return (self.CallingConvention & MethodCallingConvention.VarArg) != 0;
+		}
+
+		public static int GetSentinelPosition (this IMethodSignature self)
+		{
+			if (!self.HasParameters)
+				return -1;
+
+			var parameters = self.Parameters;
+			for (int i = 0; i < parameters.Count; i++)
+				if (parameters [i].ParameterType.IsSentinel)
+					return i;
+
+			return -1;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodReturnType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodReturnType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodReturnType.cs	(revision 11807)
@@ -0,0 +1,100 @@
+//
+// MethodReturnType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class MethodReturnType : IConstantProvider, ICustomAttributeProvider, IMarshalInfoProvider {
+
+		internal IMethodSignature method;
+		internal ParameterDefinition parameter;
+		TypeReference return_type;
+
+		public IMethodSignature Method {
+			get { return method; }
+		}
+
+		public TypeReference ReturnType {
+			get { return return_type; }
+			set { return_type = value; }
+		}
+
+		internal ParameterDefinition Parameter {
+			get { return parameter ?? (parameter = new ParameterDefinition (return_type)); }
+			set { parameter = value; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return Parameter.MetadataToken; }
+			set { Parameter.MetadataToken = value; }
+		}
+
+		public bool HasCustomAttributes {
+			get { return parameter != null && parameter.HasCustomAttributes; }
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return Parameter.CustomAttributes; }
+		}
+
+		public bool HasDefault {
+			get { return parameter != null && parameter.HasDefault; }
+			set { Parameter.HasDefault = value; }
+		}
+
+		public bool HasConstant {
+			get { return parameter != null && parameter.HasConstant; }
+			set { Parameter.HasConstant = value; }
+		}
+
+		public object Constant {
+			get { return Parameter.Constant; }
+			set { Parameter.Constant = value; }
+		}
+
+		public bool HasFieldMarshal {
+			get { return parameter != null && parameter.HasFieldMarshal; }
+			set { Parameter.HasFieldMarshal = value; }
+		}
+
+		public bool HasMarshalInfo {
+			get { return parameter != null && parameter.HasMarshalInfo; }
+		}
+
+		public MarshalInfo MarshalInfo {
+			get { return Parameter.MarshalInfo; }
+			set { Parameter.MarshalInfo = value; }
+		}
+
+		public MethodReturnType (IMethodSignature method)
+		{
+			this.method = method;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodSemanticsAttributes.cs	(revision 11807)
@@ -0,0 +1,43 @@
+//
+// MethodSemanticsattributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum MethodSemanticsAttributes : ushort {
+		None		= 0x0000,
+		Setter		= 0x0001,	// Setter for property
+		Getter		= 0x0002,	// Getter for property
+		Other		= 0x0004,	// Other method for property or event
+		AddOn		= 0x0008,	// AddOn method for event
+		RemoveOn	= 0x0010,	// RemoveOn method for event
+		Fire		= 0x0020	 // Fire method for event
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodSpecification.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodSpecification.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/MethodSpecification.cs	(revision 11807)
@@ -0,0 +1,103 @@
+//
+// MethodSpecification.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public abstract class MethodSpecification : MethodReference {
+
+		readonly MethodReference method;
+
+		public MethodReference ElementMethod {
+			get { return method; }
+		}
+
+		public override string Name {
+			get { return method.Name; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override MethodCallingConvention CallingConvention {
+			get { return method.CallingConvention; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool HasThis {
+			get { return method.HasThis; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool ExplicitThis {
+			get { return method.ExplicitThis; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override MethodReturnType MethodReturnType {
+			get { return method.MethodReturnType; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override TypeReference DeclaringType {
+			get { return method.DeclaringType; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override ModuleDefinition Module {
+			get { return method.Module; }
+		}
+
+		public override bool HasParameters {
+			get { return method.HasParameters; }
+		}
+
+		public override Collection<ParameterDefinition> Parameters {
+			get { return method.Parameters; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return method.ContainsGenericParameter; }
+		}
+
+		internal MethodSpecification (MethodReference method)
+		{
+			if (method == null)
+				throw new ArgumentNullException ("method");
+
+			this.method = method;
+			this.token = new MetadataToken (TokenType.MethodSpec);
+		}
+
+		public sealed override MethodReference GetElementMethod ()
+		{
+			return method.GetElementMethod ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Modifiers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Modifiers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Modifiers.cs	(revision 11807)
@@ -0,0 +1,137 @@
+//
+// Modifiers.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public interface IModifierType {
+		TypeReference ModifierType { get; }
+		TypeReference ElementType { get; }
+	}
+
+	public sealed class OptionalModifierType : TypeSpecification, IModifierType {
+
+		TypeReference modifier_type;
+
+		public TypeReference ModifierType {
+			get { return modifier_type; }
+			set { modifier_type = value; }
+		}
+
+		public override string Name {
+			get { return base.Name + Suffix; }
+		}
+
+		public override string FullName {
+			get { return base.FullName + Suffix; }
+		}
+
+		string Suffix {
+			get { return " modopt(" + modifier_type + ")"; }
+		}
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool IsOptionalModifier {
+			get { return true; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return modifier_type.ContainsGenericParameter || base.ContainsGenericParameter; }
+		}
+
+		public OptionalModifierType (TypeReference modifierType, TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckModifier (modifierType, type);
+			this.modifier_type = modifierType;
+			this.etype = MD.ElementType.CModOpt;
+		}
+	}
+
+	public sealed class RequiredModifierType : TypeSpecification, IModifierType {
+
+		TypeReference modifier_type;
+
+		public TypeReference ModifierType {
+			get { return modifier_type; }
+			set { modifier_type = value; }
+		}
+
+		public override string Name {
+			get { return base.Name + Suffix; }
+		}
+
+		public override string FullName {
+			get { return base.FullName + Suffix; }
+		}
+
+		string Suffix {
+			get { return " modreq(" + modifier_type + ")"; }
+		}
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool IsRequiredModifier {
+			get { return true; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return modifier_type.ContainsGenericParameter || base.ContainsGenericParameter; }
+		}
+
+		public RequiredModifierType (TypeReference modifierType, TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckModifier (modifierType, type);
+			this.modifier_type = modifierType;
+			this.etype = MD.ElementType.CModReqD;
+		}
+
+	}
+
+	static partial class Mixin {
+
+		public static void CheckModifier (TypeReference modifierType, TypeReference type)
+		{
+			if (modifierType == null)
+				throw new ArgumentNullException ("modifierType");
+			if (type == null)
+				throw new ArgumentNullException ("type");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleDefinition.cs	(revision 11807)
@@ -0,0 +1,990 @@
+//
+// ModuleDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using SR = System.Reflection;
+
+using Mono.Cecil.Cil;
+using Mono.Cecil.Metadata;
+using Mono.Cecil.PE;
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public enum ReadingMode {
+		Immediate = 1,
+		Deferred = 2,
+	}
+
+	public sealed class ReaderParameters {
+
+		ReadingMode reading_mode;
+		IAssemblyResolver assembly_resolver;
+		Stream symbol_stream;
+		ISymbolReaderProvider symbol_reader_provider;
+		bool read_symbols;
+
+		public ReadingMode ReadingMode {
+			get { return reading_mode; }
+			set { reading_mode = value; }
+		}
+
+		public IAssemblyResolver AssemblyResolver {
+			get { return assembly_resolver; }
+			set { assembly_resolver = value; }
+		}
+
+		public Stream SymbolStream {
+			get { return symbol_stream; }
+			set { symbol_stream = value; }
+		}
+
+		public ISymbolReaderProvider SymbolReaderProvider {
+			get { return symbol_reader_provider; }
+			set { symbol_reader_provider = value; }
+		}
+
+		public bool ReadSymbols {
+			get { return read_symbols; }
+			set { read_symbols = value; }
+		}
+
+		public ReaderParameters ()
+			: this (ReadingMode.Deferred)
+		{
+		}
+
+		public ReaderParameters (ReadingMode readingMode)
+		{
+			this.reading_mode = readingMode;
+		}
+	}
+
+#if !READ_ONLY
+
+	public sealed class ModuleParameters {
+
+		ModuleKind kind;
+		TargetRuntime runtime;
+		TargetArchitecture architecture;
+		IAssemblyResolver assembly_resolver;
+
+		public ModuleKind Kind {
+			get { return kind; }
+			set { kind = value; }
+		}
+
+		public TargetRuntime Runtime {
+			get { return runtime; }
+			set { runtime = value; }
+		}
+
+		public TargetArchitecture Architecture {
+			get { return architecture; }
+			set { architecture = value; }
+		}
+
+		public IAssemblyResolver AssemblyResolver {
+			get { return assembly_resolver; }
+			set { assembly_resolver = value; }
+		}
+
+		public ModuleParameters ()
+		{
+			this.kind = ModuleKind.Dll;
+			this.runtime = GetCurrentRuntime ();
+			this.architecture = TargetArchitecture.I386;
+		}
+
+		static TargetRuntime GetCurrentRuntime ()
+		{
+#if !CF
+			return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime ();
+#else
+			var corlib_version = typeof (object).Assembly.GetName ().Version;
+			switch (corlib_version.Major) {
+			case 1:
+				return corlib_version.Minor == 0
+					? TargetRuntime.Net_1_0
+					: TargetRuntime.Net_1_1;
+			case 2:
+				return TargetRuntime.Net_2_0;
+			case 4:
+				return TargetRuntime.Net_4_0;
+			default:
+				throw new NotSupportedException ();
+			}
+#endif
+		}
+	}
+
+	public sealed class WriterParameters {
+
+		Stream symbol_stream;
+		ISymbolWriterProvider symbol_writer_provider;
+		bool write_symbols;
+#if !SILVERLIGHT && !CF
+		SR.StrongNameKeyPair key_pair;
+#endif
+		public Stream SymbolStream {
+			get { return symbol_stream; }
+			set { symbol_stream = value; }
+		}
+
+		public ISymbolWriterProvider SymbolWriterProvider {
+			get { return symbol_writer_provider; }
+			set { symbol_writer_provider = value; }
+		}
+
+		public bool WriteSymbols {
+			get { return write_symbols; }
+			set { write_symbols = value; }
+		}
+#if !SILVERLIGHT && !CF
+		public SR.StrongNameKeyPair StrongNameKeyPair {
+			get { return key_pair; }
+			set { key_pair = value; }
+		}
+#endif
+	}
+
+#endif
+
+	public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider {
+
+		internal Image Image;
+		internal MetadataSystem MetadataSystem;
+		internal ReadingMode ReadingMode;
+		internal ISymbolReaderProvider SymbolReaderProvider;
+		internal ISymbolReader SymbolReader;
+
+		internal IAssemblyResolver assembly_resolver;
+		internal TypeSystem type_system;
+
+		readonly MetadataReader reader;
+		readonly string fq_name;
+
+		internal ModuleKind kind;
+		TargetRuntime runtime;
+		TargetArchitecture architecture;
+		ModuleAttributes attributes;
+		Guid mvid;
+
+		internal AssemblyDefinition assembly;
+		MethodDefinition entry_point;
+
+#if !READ_ONLY
+		MetadataImporter importer;
+#endif
+		Collection<CustomAttribute> custom_attributes;
+		Collection<AssemblyNameReference> references;
+		Collection<ModuleReference> modules;
+		Collection<Resource> resources;
+		Collection<ExportedType> exported_types;
+		TypeDefinitionCollection types;
+
+		public bool IsMain {
+			get { return kind != ModuleKind.NetModule; }
+		}
+
+		public ModuleKind Kind {
+			get { return kind; }
+			set { kind = value; }
+		}
+
+		public TargetRuntime Runtime {
+			get { return runtime; }
+			set { runtime = value; }
+		}
+
+		public TargetArchitecture Architecture {
+			get { return architecture; }
+			set { architecture = value; }
+		}
+
+		public ModuleAttributes Attributes {
+			get { return attributes; }
+			set { attributes = value; }
+		}
+
+		public string FullyQualifiedName {
+			get { return fq_name; }
+		}
+
+		public Guid Mvid {
+			get { return mvid; }
+			set { mvid = value; }
+		}
+
+		internal bool HasImage {
+			get { return Image != null; }
+		}
+
+		public bool HasSymbols {
+			get { return SymbolReader != null; }
+		}
+
+		public override MetadataScopeType MetadataScopeType {
+			get { return MetadataScopeType.ModuleDefinition; }
+		}
+
+		public AssemblyDefinition Assembly {
+			get { return assembly; }
+		}
+
+#if !READ_ONLY
+		internal MetadataImporter MetadataImporter {
+			get { return importer ?? (importer = new MetadataImporter (this)); }
+		}
+#endif
+
+		public IAssemblyResolver AssemblyResolver {
+			get { return assembly_resolver; }
+		}
+
+		public TypeSystem TypeSystem {
+			get { return type_system ?? (type_system = TypeSystem.CreateTypeSystem (this)); }
+		}
+
+		public bool HasAssemblyReferences {
+			get {
+				if (references != null)
+					return references.Count > 0;
+
+				return HasImage && Image.HasTable (Table.AssemblyRef);
+			}
+		}
+
+		public Collection<AssemblyNameReference> AssemblyReferences {
+			get {
+				if (references != null)
+					return references;
+
+				if (HasImage)
+					return references = Read (this, (_, reader) => reader.ReadAssemblyReferences ());
+
+				return references = new Collection<AssemblyNameReference> ();
+			}
+		}
+
+		public bool HasModuleReferences {
+			get {
+				if (modules != null)
+					return modules.Count > 0;
+
+				return HasImage && Image.HasTable (Table.ModuleRef);
+			}
+		}
+
+		public Collection<ModuleReference> ModuleReferences {
+			get {
+				if (modules != null)
+					return modules;
+
+				if (HasImage)
+					return modules = Read (this, (_, reader) => reader.ReadModuleReferences ());
+
+				return modules = new Collection<ModuleReference> ();
+			}
+		}
+
+		public bool HasResources {
+			get {
+				if (resources != null)
+					return resources.Count > 0;
+
+				if (HasImage)
+					return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ());
+
+				return false;
+			}
+		}
+
+		public Collection<Resource> Resources {
+			get {
+				if (resources != null)
+					return resources;
+
+				if (HasImage)
+					return resources = Read (this, (_, reader) => reader.ReadResources ());
+
+				return resources = new Collection<Resource> ();
+			}
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (this);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (this)); }
+		}
+
+		public bool HasTypes {
+			get {
+				if (types != null)
+					return types.Count > 0;
+
+				return HasImage && Image.HasTable (Table.TypeDef);
+			}
+		}
+
+		public Collection<TypeDefinition> Types {
+			get {
+				if (types != null)
+					return types;
+
+				if (HasImage)
+					return types = Read (this, (_, reader) => reader.ReadTypes ());
+
+				return types = new TypeDefinitionCollection (this);
+			}
+		}
+
+		public bool HasExportedTypes {
+			get {
+				if (exported_types != null)
+					return exported_types.Count > 0;
+
+				return HasImage && Image.HasTable (Table.ExportedType);
+			}
+		}
+
+		public Collection<ExportedType> ExportedTypes {
+			get {
+				if (exported_types != null)
+					return exported_types;
+
+				if (HasImage)
+					return exported_types = Read (this, (_, reader) => reader.ReadExportedTypes ());
+
+				return exported_types = new Collection<ExportedType> ();
+			}
+		}
+
+		public MethodDefinition EntryPoint {
+			get {
+				if (entry_point != null)
+					return entry_point;
+
+				if (HasImage)
+					return entry_point = Read (this, (_, reader) => reader.ReadEntryPoint ());
+
+				return entry_point = null;
+			}
+			set { entry_point = value; }
+		}
+
+		internal ModuleDefinition ()
+		{
+			this.MetadataSystem = new MetadataSystem ();
+			this.token = new MetadataToken (TokenType.Module, 1);
+			this.assembly_resolver = GlobalAssemblyResolver.Instance;
+		}
+
+		internal ModuleDefinition (Image image)
+			: this ()
+		{
+			this.Image = image;
+			this.kind = image.Kind;
+			this.runtime = image.Runtime;
+			this.architecture = image.Architecture;
+			this.attributes = image.Attributes;
+			this.fq_name = image.FileName;
+
+			this.reader = new MetadataReader (this);
+		}
+
+		public bool HasTypeReference (string fullName)
+		{
+			return HasTypeReference (string.Empty, fullName);
+		}
+
+		public bool HasTypeReference (string scope, string fullName)
+		{
+			CheckFullName (fullName);
+
+			if (!HasImage)
+				return false;
+
+			return GetTypeReference (scope, fullName) != null;
+		}
+
+		public bool TryGetTypeReference (string fullName, out TypeReference type)
+		{
+			return TryGetTypeReference (string.Empty, fullName, out type);
+		}
+
+		public bool TryGetTypeReference (string scope, string fullName, out TypeReference type)
+		{
+			CheckFullName (fullName);
+
+			if (!HasImage) {
+				type = null;
+				return false;
+			}
+
+			return (type = GetTypeReference (scope, fullName)) != null;
+		}
+
+		TypeReference GetTypeReference (string scope, string fullname)
+		{
+			return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2));
+		}
+
+		public IEnumerable<TypeReference> GetTypeReferences ()
+		{
+			if (!HasImage)
+				return Empty<TypeReference>.Array;
+
+			return Read (this, (_, reader) => reader.GetTypeReferences ());
+		}
+
+		public IEnumerable<MemberReference> GetMemberReferences ()
+		{
+			if (!HasImage)
+				return Empty<MemberReference>.Array;
+
+			return Read (this, (_, reader) => reader.GetMemberReferences ());
+		}
+
+		public TypeDefinition GetType (string fullName)
+		{
+			CheckFullName (fullName);
+
+			var position = fullName.IndexOf ('/');
+			if (position > 0)
+				return GetNestedType (fullName);
+
+			return ((TypeDefinitionCollection) this.Types).GetType (fullName);
+		}
+
+		public TypeDefinition GetType (string @namespace, string name)
+		{
+			Mixin.CheckName (name);
+
+			return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name);
+		}
+
+		public IEnumerable<TypeDefinition> GetTypes ()
+		{
+			return GetTypes (Types);
+		}
+
+		static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types)
+		{
+			for (int i = 0; i < types.Count; i++) {
+				var type = types [i];
+
+				yield return type;
+
+				if (!type.HasNestedTypes)
+					continue;
+
+				foreach (var nested in GetTypes (type.NestedTypes))
+					yield return nested;
+			}
+		}
+
+		static void CheckFullName (string fullName)
+		{
+			if (fullName == null)
+				throw new ArgumentNullException ("fullName");
+			if (fullName.Length == 0)
+				throw new ArgumentException ();
+		}
+
+		TypeDefinition GetNestedType (string fullname)
+		{
+			var names = fullname.Split ('/');
+			var type = GetType (names [0]);
+
+			if (type == null)
+				return null;
+
+			for (int i = 1; i < names.Length; i++) {
+				var nested_type = type.GetNestedType (names [i]);
+				if (nested_type == null)
+					return null;
+
+				type = nested_type;
+			}
+
+			return type;
+		}
+
+		internal FieldDefinition Resolve (FieldReference field)
+		{
+			return MetadataResolver.Resolve (AssemblyResolver, field);
+		}
+
+		internal MethodDefinition Resolve (MethodReference method)
+		{
+			return MetadataResolver.Resolve (AssemblyResolver, method);
+		}
+
+		internal TypeDefinition Resolve (TypeReference type)
+		{
+			return MetadataResolver.Resolve (AssemblyResolver, type);
+		}
+
+#if !READ_ONLY
+
+		static void CheckType (object type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ("type");
+		}
+
+		static void CheckField (object field)
+		{
+			if (field == null)
+				throw new ArgumentNullException ("field");
+		}
+
+		static void CheckMethod (object method)
+		{
+			if (method == null)
+				throw new ArgumentNullException ("method");
+		}
+
+		static void CheckContext (IGenericParameterProvider context, ModuleDefinition module)
+		{
+			if (context == null)
+				return;
+
+			if (context.Module != module)
+				throw new ArgumentException ();
+		}
+
+#if !CF
+		public TypeReference Import (Type type)
+		{
+			CheckType (type);
+
+			return MetadataImporter.ImportType (type, null, ImportGenericKind.Definition);
+		}
+
+		public TypeReference Import (Type type, TypeReference context)
+		{
+			return Import (type, (IGenericParameterProvider) context);
+		}
+
+		public TypeReference Import (Type type, MethodReference context)
+		{
+			return Import (type, (IGenericParameterProvider) context);
+		}
+
+		TypeReference Import (Type type, IGenericParameterProvider context)
+		{
+			CheckType (type);
+			CheckContext (context, this);
+
+			return MetadataImporter.ImportType (
+				type,
+				(IGenericContext) context,
+				context != null
+					? ImportGenericKind.Open
+					: ImportGenericKind.Definition);
+		}
+
+		public FieldReference Import (SR.FieldInfo field)
+		{
+			CheckField (field);
+
+			return MetadataImporter.ImportField (field, null);
+		}
+
+		public FieldReference Import (SR.FieldInfo field, TypeReference context)
+		{
+			return Import (field, (IGenericParameterProvider) context);
+		}
+
+		public FieldReference Import (SR.FieldInfo field, MethodReference context)
+		{
+			return Import (field, (IGenericParameterProvider) context);
+		}
+
+		FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context)
+		{
+			CheckField (field);
+			CheckContext (context, this);
+
+			return MetadataImporter.ImportField (field, (IGenericContext) context);
+		}
+
+		public MethodReference Import (SR.MethodBase method)
+		{
+			CheckMethod (method);
+
+			return MetadataImporter.ImportMethod (method, null, ImportGenericKind.Definition);
+		}
+
+		public MethodReference Import (SR.MethodBase method, TypeReference context)
+		{
+			return Import (method, (IGenericParameterProvider) context);
+		}
+
+		public MethodReference Import (SR.MethodBase method, MethodReference context)
+		{
+			return Import (method, (IGenericParameterProvider) context);
+		}
+
+		MethodReference Import (SR.MethodBase method, IGenericParameterProvider context)
+		{
+			CheckMethod (method);
+			CheckContext (context, this);
+
+			return MetadataImporter.ImportMethod (method,
+				(IGenericContext) context,
+				context != null
+					? ImportGenericKind.Open
+					: ImportGenericKind.Definition);
+		}
+#endif
+
+		public TypeReference Import (TypeReference type)
+		{
+			CheckType (type);
+
+			if (type.Module == this)
+				return type;
+
+			return MetadataImporter.ImportType (type, null);
+		}
+
+		public TypeReference Import (TypeReference type, TypeReference context)
+		{
+			return Import (type, (IGenericParameterProvider) context);
+		}
+
+		public TypeReference Import (TypeReference type, MethodReference context)
+		{
+			return Import (type, (IGenericParameterProvider) context);
+		}
+
+		TypeReference Import (TypeReference type, IGenericParameterProvider context)
+		{
+			CheckType (type);
+
+			if (type.Module == this)
+				return type;
+
+			CheckContext (context, this);
+
+			return MetadataImporter.ImportType (type, (IGenericContext) context);
+		}
+
+		public FieldReference Import (FieldReference field)
+		{
+			CheckField (field);
+
+			if (field.Module == this)
+				return field;
+
+			return MetadataImporter.ImportField (field, null);
+		}
+
+		public FieldReference Import (FieldReference field, TypeReference context)
+		{
+			return Import (field, (IGenericParameterProvider) context);
+		}
+
+		public FieldReference Import (FieldReference field, MethodReference context)
+		{
+			return Import (field, (IGenericParameterProvider) context);
+		}
+
+		FieldReference Import (FieldReference field, IGenericParameterProvider context)
+		{
+			CheckField (field);
+
+			if (field.Module == this)
+				return field;
+
+			CheckContext (context, this);
+
+			return MetadataImporter.ImportField (field, (IGenericContext) context);
+		}
+
+		public MethodReference Import (MethodReference method)
+		{
+			CheckMethod (method);
+
+			if (method.Module == this)
+				return method;
+
+			return MetadataImporter.ImportMethod (method, null);
+		}
+
+		public MethodReference Import (MethodReference method, TypeReference context)
+		{
+			return Import (method, (IGenericParameterProvider) context);
+		}
+
+		public MethodReference Import (MethodReference method, MethodReference context)
+		{
+			return Import (method, (IGenericParameterProvider) context);
+		}
+
+		MethodReference Import (MethodReference method, IGenericParameterProvider context)
+		{
+			CheckMethod (method);
+
+			if (method.Module == this)
+				return method;
+
+			CheckContext (context, this);
+
+			return MetadataImporter.ImportMethod (method, (IGenericContext) context);
+		}
+
+#endif
+
+		public IMetadataTokenProvider LookupToken (int token)
+		{
+			return LookupToken (new MetadataToken ((uint) token));
+		}
+
+		public IMetadataTokenProvider LookupToken (MetadataToken token)
+		{
+			return Read (token, (t, reader) => reader.LookupToken (t));
+		}
+
+		internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read)
+		{
+			var position = reader.position;
+			var context = reader.context;
+
+			var ret = read (item, reader);
+
+			reader.position = position;
+			reader.context = context;
+
+			return ret;
+		}
+
+		void ProcessDebugHeader ()
+		{
+			if (Image == null || Image.Debug.IsZero)
+				return;
+
+			byte [] header;
+			var directory = Image.GetDebugHeader (out header);
+
+			if (!SymbolReader.ProcessDebugHeader (directory, header))
+				throw new InvalidOperationException ();
+		}
+
+#if !READ_ONLY
+
+		public static ModuleDefinition CreateModule (string name, ModuleKind kind)
+		{
+			return CreateModule (name, new ModuleParameters { Kind = kind });
+		}
+
+		public static ModuleDefinition CreateModule (string name, ModuleParameters parameters)
+		{
+			Mixin.CheckName (name);
+			Mixin.CheckParameters (parameters);
+
+			var module = new ModuleDefinition {
+				Name = name,
+				kind = parameters.Kind,
+				runtime = parameters.Runtime,
+				architecture = parameters.Architecture,
+				mvid = Guid.NewGuid (),
+				Attributes = ModuleAttributes.ILOnly,
+			};
+
+			if (parameters.AssemblyResolver != null)
+				module.assembly_resolver = parameters.AssemblyResolver;
+
+			if (parameters.Kind != ModuleKind.NetModule) {
+				var assembly = new AssemblyDefinition ();
+				module.assembly = assembly;
+				module.assembly.Name = new AssemblyNameDefinition (name, new Version (0, 0));
+				assembly.main_module = module;
+			}
+
+			module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic));
+
+			return module;
+		}
+
+#endif
+
+		public void ReadSymbols ()
+		{
+			if (string.IsNullOrEmpty (fq_name))
+				throw new InvalidOperationException ();
+
+			var provider = SymbolProvider.GetPlatformReaderProvider ();
+
+			SymbolReader = provider.GetSymbolReader (this, fq_name);
+
+			ProcessDebugHeader ();
+		}
+
+		public void ReadSymbols (ISymbolReader reader)
+		{
+			if (reader == null)
+				throw new ArgumentNullException ("reader");
+
+			SymbolReader = reader;
+
+			ProcessDebugHeader ();
+		}
+
+		public static ModuleDefinition ReadModule (string fileName)
+		{
+			return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred));
+		}
+
+		public static ModuleDefinition ReadModule (Stream stream)
+		{
+			return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred));
+		}
+
+		public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters)
+		{
+			using (var stream = GetFileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
+				return ReadModule (stream, parameters);
+			}
+		}
+
+		static void CheckStream (object stream)
+		{
+			if (stream == null)
+				throw new ArgumentNullException ("stream");
+		}
+
+		public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters)
+		{
+			CheckStream (stream);
+			if (!stream.CanRead || !stream.CanSeek)
+				throw new ArgumentException ();
+			Mixin.CheckParameters (parameters);
+
+			return ModuleReader.CreateModuleFrom (
+				ImageReader.ReadImageFrom (stream),
+				parameters);
+		}
+
+		static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException ("fileName");
+			if (fileName.Length == 0)
+				throw new ArgumentException ();
+
+			return new FileStream (fileName, mode, access, share);
+		}
+
+#if !READ_ONLY
+
+		public void Write (string fileName)
+		{
+			Write (fileName, new WriterParameters ());
+		}
+
+		public void Write (Stream stream)
+		{
+			Write (stream, new WriterParameters ());
+		}
+
+		public void Write (string fileName, WriterParameters parameters)
+		{
+			using (var stream = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) {
+				Write (stream, parameters);
+			}
+		}
+
+		public void Write (Stream stream, WriterParameters parameters)
+		{
+			CheckStream (stream);
+			if (!stream.CanWrite || !stream.CanSeek)
+				throw new ArgumentException ();
+			Mixin.CheckParameters (parameters);
+
+			ModuleWriter.WriteModuleTo (this, stream, parameters);
+		}
+
+#endif
+
+	}
+
+	static partial class Mixin {
+
+		public static void CheckParameters (object parameters)
+		{
+			if (parameters == null)
+				throw new ArgumentNullException ("parameters");
+		}
+
+		public static bool HasImage (this ModuleDefinition self)
+		{
+			return self != null && self.HasImage;
+		}
+
+		public static string GetFullyQualifiedName (this Stream self)
+		{
+#if !SILVERLIGHT
+			var file_stream = self as FileStream;
+			if (file_stream == null)
+				return string.Empty;
+
+			return Path.GetFullPath (file_stream.Name);
+#else
+			return string.Empty;
+#endif
+		}
+
+		public static TargetRuntime ParseRuntime (this string self)
+		{
+			switch (self [1]) {
+			case '1':
+				return self [3] == '0'
+					? TargetRuntime.Net_1_0
+					: TargetRuntime.Net_1_1;
+			case '2':
+				return TargetRuntime.Net_2_0;
+			case '4':
+			default:
+				return TargetRuntime.Net_4_0;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleKind.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleKind.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleKind.cs	(revision 11807)
@@ -0,0 +1,52 @@
+//
+// ModuleKind.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public enum ModuleKind {
+		Dll,
+		Console,
+		Windows,
+		NetModule,
+	}
+
+	public enum TargetArchitecture {
+		I386,
+		AMD64,
+		IA64,
+	}
+
+	[Flags]
+	public enum ModuleAttributes {
+		ILOnly = 1,
+		Required32Bit = 2,
+		StrongNameSigned = 8,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ModuleReference.cs	(revision 11807)
@@ -0,0 +1,67 @@
+//
+// ModuleReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public class ModuleReference : IMetadataScope {
+
+		string name;
+
+		internal MetadataToken token;
+
+		public string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public virtual MetadataScopeType MetadataScopeType {
+			get { return MetadataScopeType.ModuleReference; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return token; }
+			set { token = value; }
+		}
+
+		internal ModuleReference ()
+		{
+			this.token = new MetadataToken (TokenType.ModuleRef);
+		}
+
+		public ModuleReference (string name)
+			: this ()
+		{
+			this.name = name;
+		}
+
+		public override string ToString ()
+		{
+			return name;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/NativeType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/NativeType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/NativeType.cs	(revision 11807)
@@ -0,0 +1,73 @@
+//
+// NativeType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum NativeType {
+		None = 0x66,
+
+		Boolean = 0x02,
+		I1 = 0x03,
+		U1 = 0x04,
+		I2 = 0x05,
+		U2 = 0x06,
+		I4 = 0x07,
+		U4 = 0x08,
+		I8 = 0x09,
+		U8 = 0x0a,
+		R4 = 0x0b,
+		R8 = 0x0c,
+		LPStr = 0x14,
+		Int = 0x1f,
+		UInt = 0x20,
+		Func = 0x26,
+		Array = 0x2a,
+
+		// Msft specific
+		Currency = 0x0f,
+		BStr = 0x13,
+		LPWStr = 0x15,
+		LPTStr = 0x16,
+		FixedSysString = 0x17,
+		IUnknown = 0x19,
+		IDispatch = 0x1a,
+		Struct = 0x1b,
+		IntF = 0x1c,
+		SafeArray = 0x1d,
+		FixedArray = 0x1e,
+		ByValStr = 0x22,
+		ANSIBStr = 0x23,
+		TBStr = 0x24,
+		VariantBool = 0x25,
+		ASAny = 0x28,
+		LPStruct = 0x2b,
+		CustomMarshaler = 0x2c,
+		Error = 0x2d,
+		Max = 0x50
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PInvokeAttributes.cs	(revision 11807)
@@ -0,0 +1,62 @@
+//
+// PInvokeAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum PInvokeAttributes : ushort {
+		NoMangle			= 0x0001,	// PInvoke is to use the member name as specified
+
+		// Character set
+		CharSetMask			= 0x0006,
+		CharSetNotSpec		= 0x0000,
+		CharSetAnsi			= 0x0002,
+		CharSetUnicode		= 0x0004,
+		CharSetAuto			= 0x0006,
+
+		SupportsLastError	= 0x0040,	// Information about target function. Not relevant for fields
+
+		// Calling convetion
+		CallConvMask		= 0x0700,
+		CallConvWinapi		= 0x0100,
+		CallConvCdecl		= 0x0200,
+		CallConvStdCall		= 0x0300,
+		CallConvThiscall	= 0x0400,
+		CallConvFastcall	= 0x0500,
+
+		BestFitMask			= 0x0030,
+		BestFitEnabled		= 0x0010,
+		BestFitDisabled		= 0x0020,
+
+		ThrowOnUnmappableCharMask = 0x3000,
+		ThrowOnUnmappableCharEnabled = 0x1000,
+		ThrowOnUnmappableCharDisabled = 0x2000,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PInvokeInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PInvokeInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PInvokeInfo.cs	(revision 11807)
@@ -0,0 +1,138 @@
+//
+// PInvokeInfo.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public sealed class PInvokeInfo {
+
+		ushort attributes;
+		string entry_point;
+		ModuleReference module;
+
+		public PInvokeAttributes Attributes {
+			get { return (PInvokeAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public string EntryPoint {
+			get { return entry_point; }
+			set { entry_point = value; }
+		}
+
+		public ModuleReference Module {
+			get { return module; }
+			set { module = value; }
+		}
+
+		#region PInvokeAttributes
+
+		public bool IsNoMangle {
+			get { return attributes.GetAttributes ((ushort) PInvokeAttributes.NoMangle); }
+			set { attributes = attributes.SetAttributes ((ushort) PInvokeAttributes.NoMangle, value); }
+		}
+
+		public bool IsCharSetNotSpec {
+			get { return attributes.GetMaskedAttributes((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetNotSpec); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetNotSpec, value); }
+		}
+
+		public bool IsCharSetAnsi {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAnsi); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAnsi, value); }
+		}
+
+		public bool IsCharSetUnicode {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetUnicode); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetUnicode, value); }
+		}
+
+		public bool IsCharSetAuto {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAuto); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CharSetMask, (ushort) PInvokeAttributes.CharSetAuto, value); }
+		}
+
+		public bool SupportsLastError {
+			get { return attributes.GetAttributes ((ushort) PInvokeAttributes.SupportsLastError); }
+			set { attributes = attributes.SetAttributes ((ushort) PInvokeAttributes.SupportsLastError, value); }
+		}
+
+		public bool IsCallConvWinapi {
+			get { return attributes.GetMaskedAttributes((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvWinapi); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvWinapi, value); }
+		}
+
+		public bool IsCallConvCdecl {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvCdecl); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvCdecl, value); }
+		}
+
+		public bool IsCallConvStdCall {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvStdCall); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvStdCall, value); }
+		}
+
+		public bool IsCallConvThiscall {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvThiscall); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvThiscall, value); }
+		}
+
+		public bool IsCallConvFastcall {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvFastcall); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.CallConvMask, (ushort) PInvokeAttributes.CallConvFastcall, value); }
+		}
+
+		public bool IsBestFitEnabled {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitEnabled); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitEnabled, value); }
+		}
+
+		public bool IsBestFitDisabled {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitDisabled); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.BestFitMask, (ushort) PInvokeAttributes.BestFitDisabled, value); }
+		}
+
+		public bool IsThrowOnUnmappableCharEnabled {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharEnabled); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharEnabled, value); }
+		}
+
+		public bool IsThrowOnUnmappableCharDisabled {
+			get { return attributes.GetMaskedAttributes ((ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharDisabled); }
+			set { attributes = attributes.SetMaskedAttributes ((ushort) PInvokeAttributes.ThrowOnUnmappableCharMask, (ushort) PInvokeAttributes.ThrowOnUnmappableCharDisabled, value); }
+		}
+
+		#endregion
+
+		public PInvokeInfo (PInvokeAttributes attributes, string entryPoint, ModuleReference module)
+		{
+			this.attributes = (ushort) attributes;
+			this.entry_point = entryPoint;
+			this.module = module;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterAttributes.cs	(revision 11807)
@@ -0,0 +1,45 @@
+//
+// ParameterAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum ParameterAttributes : ushort {
+		None				= 0x0000,
+		In					= 0x0001,	// Param is [In]
+		Out					= 0x0002,	// Param is [Out]
+		Lcid				= 0x0004,
+		Retval				= 0x0008,
+		Optional			= 0x0010,	// Param is optional
+		HasDefault			= 0x1000,	// Param has default value
+		HasFieldMarshal		= 0x2000,	// Param has field marshal
+		Unused				= 0xcfe0	 // Reserved: shall be zero in a conforming implementation
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterDefinition.cs	(revision 11807)
@@ -0,0 +1,166 @@
+//
+// ParameterDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class ParameterDefinition : ParameterReference, ICustomAttributeProvider, IConstantProvider, IMarshalInfoProvider {
+
+		ushort attributes;
+
+		internal IMethodSignature method;
+
+		object constant = Mixin.NotResolved;
+		Collection<CustomAttribute> custom_attributes;
+		MarshalInfo marshal_info;
+
+		public ParameterAttributes Attributes {
+			get { return (ParameterAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public IMethodSignature Method {
+			get { return method; }
+		}
+
+		public int Sequence {
+			get {
+				if (method == null)
+					return -1;
+
+				return method.HasThis ? index + 1 : index;
+			}
+		}
+
+		public bool HasConstant {
+			get {
+				ResolveConstant ();
+
+				return constant != Mixin.NoValue;
+			}
+			set { if (!value) constant = Mixin.NoValue; }
+		}
+
+		public object Constant {
+			get { return HasConstant ? constant : null;	}
+			set { constant = value; }
+		}
+
+		void ResolveConstant ()
+		{
+			if (constant != Mixin.NotResolved)
+				return;
+
+			this.ResolveConstant (ref constant, parameter_type.Module);
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (parameter_type.Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (parameter_type.Module)); }
+		}
+
+		public bool HasMarshalInfo {
+			get {
+				if (marshal_info != null)
+					return true;
+
+				return this.GetHasMarshalInfo (parameter_type.Module);
+			}
+		}
+
+		public MarshalInfo MarshalInfo {
+			get { return marshal_info ?? (marshal_info = this.GetMarshalInfo (parameter_type.Module)); }
+			set { marshal_info = value; }
+		}
+
+		#region ParameterAttributes
+
+		public bool IsIn {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.In); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.In, value); }
+		}
+
+		public bool IsOut {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.Out); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.Out, value); }
+		}
+
+		public bool IsLcid {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.Lcid); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.Lcid, value); }
+		}
+
+		public bool IsReturnValue {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.Retval); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.Retval, value); }
+		}
+
+		public bool IsOptional {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.Optional); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.Optional, value); }
+		}
+
+		public bool HasDefault {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.HasDefault); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.HasDefault, value); }
+		}
+
+		public bool HasFieldMarshal {
+			get { return attributes.GetAttributes ((ushort) ParameterAttributes.HasFieldMarshal); }
+			set { attributes = attributes.SetAttributes ((ushort) ParameterAttributes.HasFieldMarshal, value); }
+		}
+
+		#endregion
+
+		public ParameterDefinition (TypeReference parameterType)
+			: this (string.Empty, ParameterAttributes.None, parameterType)
+		{
+		}
+
+		public ParameterDefinition (string name, ParameterAttributes attributes, TypeReference parameterType)
+			: base (name, parameterType)
+		{
+			this.attributes = (ushort) attributes;
+			this.token = new MetadataToken (TokenType.Param);
+		}
+
+		public override ParameterDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterDefinitionCollection.cs	(revision 11807)
@@ -0,0 +1,80 @@
+//
+// ParameterDefinitionCollection.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	sealed class ParameterDefinitionCollection : Collection<ParameterDefinition> {
+
+		readonly IMethodSignature method;
+
+		internal ParameterDefinitionCollection (IMethodSignature method)
+		{
+			this.method = method;
+		}
+
+		internal ParameterDefinitionCollection (IMethodSignature method, int capacity)
+			: base (capacity)
+		{
+			this.method = method;
+		}
+
+		protected override void OnAdd (ParameterDefinition item, int index)
+		{
+			item.method = method;
+			item.index = index;
+		}
+
+		protected override void OnInsert (ParameterDefinition item, int index)
+		{
+			item.method = method;
+			item.index = index;
+
+			for (int i = index; i < size; i++)
+				items [i].index = i + 1;
+		}
+
+		protected override void OnSet (ParameterDefinition item, int index)
+		{
+			item.method = method;
+			item.index = index;
+		}
+
+		protected override void OnRemove (ParameterDefinition item, int index)
+		{
+			item.method = null;
+			item.index = -1;
+
+			for (int i = index + 1; i < size; i++)
+				items [i].index = i - 1;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ParameterReference.cs	(revision 11807)
@@ -0,0 +1,75 @@
+//
+// ParameterReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	public abstract class ParameterReference : IMetadataTokenProvider {
+
+		string name;
+		internal int index = -1;
+		protected TypeReference parameter_type;
+		internal MetadataToken token;
+
+		public string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public int Index {
+			get { return index; }
+		}
+
+		public TypeReference ParameterType {
+			get { return parameter_type; }
+			set { parameter_type = value; }
+		}
+
+		public MetadataToken MetadataToken {
+			get { return token; }
+			set { token = value; }
+		}
+
+		internal ParameterReference (string name, TypeReference parameterType)
+		{
+			if (parameterType == null)
+				throw new ArgumentNullException ("parameterType");
+
+			this.name = name ?? string.Empty;
+			this.parameter_type = parameterType;
+		}
+
+		public override string ToString ()
+		{
+			return name;
+		}
+
+		public abstract ParameterDefinition Resolve ();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PinnedType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PinnedType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PinnedType.cs	(revision 11807)
@@ -0,0 +1,53 @@
+//
+// PinnedType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class PinnedType : TypeSpecification {
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool IsPinned {
+			get { return true; }
+		}
+
+		public PinnedType (TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckType (type);
+			this.etype = MD.ElementType.Pinned;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PointerType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PointerType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PointerType.cs	(revision 11807)
@@ -0,0 +1,61 @@
+//
+// PointerType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class PointerType : TypeSpecification {
+
+		public override string Name {
+			get { return base.Name + "*"; }
+		}
+
+		public override string FullName {
+			get { return base.FullName + "*"; }
+		}
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool IsPointer {
+			get { return true; }
+		}
+
+		public PointerType (TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckType (type);
+			this.etype = MD.ElementType.Ptr;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyAttributes.cs	(revision 11807)
@@ -0,0 +1,41 @@
+//
+// PropertyAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum PropertyAttributes : ushort {
+		None			= 0x0000,
+		SpecialName		= 0x0200,	// Property is special
+		RTSpecialName	= 0x0400,	// Runtime(metadata internal APIs) should check name encoding
+		HasDefault		= 0x1000,	// Property has default
+		Unused			= 0xe9ff	 // Reserved: shall be zero in a conforming implementation
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyDefinition.cs	(revision 11807)
@@ -0,0 +1,265 @@
+//
+// PropertyDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Text;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider {
+
+		bool? has_this;
+		ushort attributes;
+
+		Collection<CustomAttribute> custom_attributes;
+
+		internal MethodDefinition get_method;
+		internal MethodDefinition set_method;
+		internal Collection<MethodDefinition> other_methods;
+
+		object constant = Mixin.NotResolved;
+
+		public PropertyAttributes Attributes {
+			get { return (PropertyAttributes) attributes; }
+			set { attributes = (ushort) value; }
+		}
+
+		public bool HasThis {
+			get {
+				if (has_this.HasValue)
+					return has_this.Value;
+
+				if (GetMethod != null)
+					return get_method.HasThis;
+
+				if (SetMethod != null)
+					return set_method.HasThis;
+
+				return false;
+			}
+			set { has_this = value; }
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
+		}
+
+		public MethodDefinition GetMethod {
+			get {
+				if (get_method != null)
+					return get_method;
+
+				InitializeMethods ();
+				return get_method;
+			}
+			set { get_method = value; }
+		}
+
+		public MethodDefinition SetMethod {
+			get {
+				if (set_method != null)
+					return set_method;
+
+				InitializeMethods ();
+				return set_method;
+			}
+			set { set_method = value; }
+		}
+
+		public bool HasOtherMethods {
+			get {
+				if (other_methods != null)
+					return other_methods.Count > 0;
+
+				InitializeMethods ();
+				return !other_methods.IsNullOrEmpty ();
+			}
+		}
+
+		public Collection<MethodDefinition> OtherMethods {
+			get {
+				if (other_methods != null)
+					return other_methods;
+
+				InitializeMethods ();
+
+				if (other_methods != null)
+					return other_methods;
+
+				return other_methods = new Collection<MethodDefinition> ();
+			}
+		}
+
+		public bool HasParameters {
+			get {
+				InitializeMethods ();
+
+				if (get_method != null)
+					return get_method.HasParameters;
+
+				if (set_method != null)
+					return set_method.HasParameters && set_method.Parameters.Count > 1;
+
+				return false;
+			}
+		}
+
+		public override Collection<ParameterDefinition> Parameters {
+			get {
+				InitializeMethods ();
+
+				if (get_method != null)
+					return MirrorParameters (get_method, 0);
+
+				if (set_method != null)
+					return MirrorParameters (set_method, 1);
+
+				return new Collection<ParameterDefinition> ();
+			}
+		}
+
+		static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound)
+		{
+			var parameters = new Collection<ParameterDefinition> ();
+			if (!method.HasParameters)
+				return parameters;
+
+			var original_parameters = method.Parameters;
+			var end = original_parameters.Count - bound;
+
+			for (int i = 0; i < end; i++)
+				parameters.Add (original_parameters [i]);
+
+			return parameters;
+		}
+
+		public bool HasConstant {
+			get {
+				ResolveConstant ();
+
+				return constant != Mixin.NoValue;
+			}
+			set { if (!value) constant = Mixin.NoValue; }
+		}
+
+		public object Constant {
+			get { return HasConstant ? constant : null;	}
+			set { constant = value; }
+		}
+
+		void ResolveConstant ()
+		{
+			if (constant != Mixin.NotResolved)
+				return;
+
+			this.ResolveConstant (ref constant, Module);
+		}
+
+		#region PropertyAttributes
+
+		public bool IsSpecialName {
+			get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); }
+		}
+
+		public bool IsRuntimeSpecialName {
+			get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); }
+			set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); }
+		}
+
+		public bool HasDefault {
+			get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); }
+			set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); }
+		}
+
+		#endregion
+
+		public new TypeDefinition DeclaringType {
+			get { return (TypeDefinition) base.DeclaringType; }
+			set { base.DeclaringType = value; }
+		}
+
+		public override bool IsDefinition {
+			get { return true; }
+		}
+
+		public override string FullName {
+			get {
+				var builder = new StringBuilder ();
+				builder.Append (PropertyType.ToString ());
+				builder.Append (' ');
+				builder.Append (MemberFullName ());
+				builder.Append ('(');
+				if (HasParameters) {
+					var parameters = Parameters;
+					for (int i = 0; i < parameters.Count; i++) {
+						if (i > 0)
+							builder.Append (',');
+						builder.Append (parameters [i].ParameterType.FullName);
+					}
+				}
+				builder.Append (')');
+				return builder.ToString ();
+			}
+		}
+
+		public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType)
+			: base (name, propertyType)
+		{
+			this.attributes = (ushort) attributes;
+			this.token = new MetadataToken (TokenType.Property);
+		}
+
+		void InitializeMethods ()
+		{
+			if (get_method != null || set_method != null)
+				return;
+
+			var module = this.Module;
+			if (!module.HasImage ())
+				return;
+
+			module.Read (this, (property, reader) => reader.ReadMethods (property));
+		}
+
+		public override PropertyDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/PropertyReference.cs	(revision 11807)
@@ -0,0 +1,59 @@
+//
+// PropertyReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public abstract class PropertyReference : MemberReference {
+
+		TypeReference property_type;
+
+		public TypeReference PropertyType {
+			get { return property_type; }
+			set { property_type = value; }
+		}
+
+		public abstract Collection<ParameterDefinition> Parameters {
+			get;
+		}
+
+		internal PropertyReference (string name, TypeReference propertyType)
+			: base (name)
+		{
+			if (propertyType == null)
+				throw new ArgumentNullException ("propertyType");
+
+			property_type = propertyType;
+		}
+
+		public abstract PropertyDefinition Resolve ();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ReferenceType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ReferenceType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/ReferenceType.cs	(revision 11807)
@@ -0,0 +1,61 @@
+//
+// ByReferenceType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class ByReferenceType : TypeSpecification {
+
+		public override string Name {
+			get { return base.Name + "&"; }
+		}
+
+		public override string FullName {
+			get { return base.FullName + "&"; }
+		}
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool IsByReference {
+			get { return true; }
+		}
+
+		public ByReferenceType (TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckType (type);
+			this.etype = MD.ElementType.ByRef;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Resource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Resource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/Resource.cs	(revision 11807)
@@ -0,0 +1,76 @@
+//
+// ResourceType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum ResourceType {
+		Linked,
+		Embedded,
+		AssemblyLinked,
+	}
+
+	public abstract class Resource {
+
+		string name;
+		uint attributes;
+
+		public string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public ManifestResourceAttributes Attributes {
+			get { return (ManifestResourceAttributes) attributes; }
+			set { attributes = (uint) value; }
+		}
+
+		public abstract ResourceType ResourceType {
+			get;
+		}
+
+		#region ManifestResourceAttributes
+
+		public bool IsPublic {
+			get { return attributes.GetMaskedAttributes ((uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Public); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Public, value); }
+		}
+
+		public bool IsPrivate {
+			get { return attributes.GetMaskedAttributes ((uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Private); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) ManifestResourceAttributes.VisibilityMask, (uint) ManifestResourceAttributes.Private, value); }
+		}
+
+		#endregion
+
+		internal Resource (string name, ManifestResourceAttributes attributes)
+		{
+			this.name = name;
+			this.attributes = (uint) attributes;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/SecurityDeclaration.cs	(revision 11807)
@@ -0,0 +1,182 @@
+//
+// SecurityDeclaration.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public enum SecurityAction : ushort {
+		Request = 1,
+		Demand = 2,
+		Assert = 3,
+		Deny = 4,
+		PermitOnly = 5,
+		LinkDemand = 6,
+		InheritDemand = 7,
+		RequestMinimum = 8,
+		RequestOptional = 9,
+		RequestRefuse = 10,
+		PreJitGrant = 11,
+		PreJitDeny = 12,
+		NonCasDemand = 13,
+		NonCasLinkDemand = 14,
+		NonCasInheritance = 15
+	}
+
+	public interface ISecurityDeclarationProvider : IMetadataTokenProvider {
+
+		bool HasSecurityDeclarations { get; }
+		Collection<SecurityDeclaration> SecurityDeclarations { get; }
+	}
+
+	public sealed class SecurityAttribute : ICustomAttribute {
+
+		TypeReference attribute_type;
+
+		internal Collection<CustomAttributeNamedArgument> fields;
+		internal Collection<CustomAttributeNamedArgument> properties;
+
+		public TypeReference AttributeType {
+			get { return attribute_type; }
+			set { attribute_type = value; }
+		}
+
+		public bool HasFields {
+			get { return !fields.IsNullOrEmpty (); }
+		}
+
+		public Collection<CustomAttributeNamedArgument> Fields {
+			get { return fields ?? (fields = new Collection<CustomAttributeNamedArgument> ()); }
+		}
+
+		public bool HasProperties {
+			get { return !properties.IsNullOrEmpty (); }
+		}
+
+		public Collection<CustomAttributeNamedArgument> Properties {
+			get { return properties ?? (properties = new Collection<CustomAttributeNamedArgument> ()); }
+		}
+
+		public SecurityAttribute (TypeReference attributeType)
+		{
+			this.attribute_type = attributeType;
+		}
+	}
+
+	public sealed class SecurityDeclaration {
+
+		readonly internal uint signature;
+		readonly ModuleDefinition module;
+
+		internal bool resolved;
+		SecurityAction action;
+		internal Collection<SecurityAttribute> security_attributes;
+
+		public SecurityAction Action {
+			get { return action; }
+			set { action = value; }
+		}
+
+		public bool HasSecurityAttributes {
+			get {
+				Resolve ();
+
+				return !security_attributes.IsNullOrEmpty ();
+			}
+		}
+
+		public Collection<SecurityAttribute> SecurityAttributes {
+			get {
+				Resolve ();
+
+				return security_attributes ?? (security_attributes = new Collection<SecurityAttribute> ());
+			}
+		}
+
+		internal bool HasImage {
+			get { return module != null && module.HasImage; }
+		}
+
+		internal SecurityDeclaration (SecurityAction action, uint signature, ModuleDefinition module)
+		{
+			this.action = action;
+			this.signature = signature;
+			this.module = module;
+		}
+
+		public SecurityDeclaration (SecurityAction action)
+		{
+			this.action = action;
+			this.resolved = true;
+		}
+
+		public byte [] GetBlob ()
+		{
+			if (!HasImage || signature == 0)
+				throw new NotSupportedException ();
+
+			return module.Read (this, (declaration, reader) => reader.ReadSecurityDeclarationBlob (declaration.signature));
+		}
+
+		void Resolve ()
+		{
+			if (resolved || !HasImage)
+				return;
+
+			module.Read (this, (declaration, reader) => {
+				reader.ReadSecurityDeclarationSignature (declaration);
+				return this;
+			});
+
+			resolved = true;
+		}
+	}
+
+	static partial class Mixin {
+
+		public static bool GetHasSecurityDeclarations (
+			this ISecurityDeclarationProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.HasSecurityDeclarations (provider))
+				: false;
+		}
+
+		public static Collection<SecurityDeclaration> GetSecurityDeclarations (
+			this ISecurityDeclarationProvider self,
+			ModuleDefinition module)
+		{
+			return module.HasImage ()
+				? module.Read (self, (provider, reader) => reader.ReadSecurityDeclarations (provider))
+				: new Collection<SecurityDeclaration> ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/SentinelType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/SentinelType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/SentinelType.cs	(revision 11807)
@@ -0,0 +1,53 @@
+//
+// SentinelType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using MD = Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public sealed class SentinelType : TypeSpecification {
+
+		public override bool IsValueType {
+			get { return false; }
+			set { throw new InvalidOperationException (); }
+		}
+
+		public override bool IsSentinel {
+			get { return true; }
+		}
+
+		public SentinelType (TypeReference type)
+			: base (type)
+		{
+			Mixin.CheckType (type);
+			this.etype = MD.ElementType.Sentinel;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TargetRuntime.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TargetRuntime.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TargetRuntime.cs	(revision 11807)
@@ -0,0 +1,37 @@
+//
+// TargetRuntime.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum TargetRuntime {
+		Net_1_0,
+		Net_1_1,
+		Net_2_0,
+		Net_4_0,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeAttributes.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeAttributes.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeAttributes.cs	(revision 11807)
@@ -0,0 +1,80 @@
+//
+// TypeAttributes.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace Mono.Cecil {
+
+	[Flags]
+	public enum TypeAttributes : uint {
+		// Visibility attributes
+		VisibilityMask		= 0x00000007,	// Use this mask to retrieve visibility information
+		NotPublic			= 0x00000000,	// Class has no public scope
+		Public				= 0x00000001,	// Class has public scope
+		NestedPublic		= 0x00000002,	// Class is nested with public visibility
+		NestedPrivate		= 0x00000003,	// Class is nested with private visibility
+		NestedFamily		= 0x00000004,	// Class is nested with family visibility
+		NestedAssembly		= 0x00000005,	// Class is nested with assembly visibility
+		NestedFamANDAssem	= 0x00000006,	// Class is nested with family and assembly visibility
+		NestedFamORAssem	= 0x00000007,	// Class is nested with family or assembly visibility
+
+		// Class layout attributes
+		LayoutMask			= 0x00000018,	// Use this mask to retrieve class layout information
+		AutoLayout			= 0x00000000,	// Class fields are auto-laid out
+		SequentialLayout	= 0x00000008,	// Class fields are laid out sequentially
+		ExplicitLayout		= 0x00000010,	// Layout is supplied explicitly
+
+		// Class semantics attributes
+		ClassSemanticMask	= 0x00000020,	// Use this mask to retrieve class semantics information
+		Class				= 0x00000000,	// Type is a class
+		Interface			= 0x00000020,	// Type is an interface
+
+		// Special semantics in addition to class semantics
+		Abstract			= 0x00000080,	// Class is abstract
+		Sealed				= 0x00000100,	// Class cannot be extended
+		SpecialName			= 0x00000400,	// Class name is special
+
+		// Implementation attributes
+		Import				= 0x00001000,	// Class/Interface is imported
+		Serializable		= 0x00002000,	// Class is serializable
+
+		// String formatting attributes
+		StringFormatMask	= 0x00030000,	// Use this mask to retrieve string information for native interop
+		AnsiClass			= 0x00000000,	// LPSTR is interpreted as ANSI
+		UnicodeClass		= 0x00010000,	// LPSTR is interpreted as Unicode
+		AutoClass			= 0x00020000,	// LPSTR is interpreted automatically
+
+		// Class initialization attributes
+		BeforeFieldInit		= 0x00100000,	// Initialize the class before first static field access
+
+		// Additional flags
+		RTSpecialName		= 0x00000800,	// CLI provides 'special' behavior, depending upon the name of the Type
+		HasSecurity			= 0x00040000,	// Type has security associate with it
+		Forwarder			= 0x00200000,   // Exported type is a type forwarder
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeDefinition.cs	(revision 11807)
@@ -0,0 +1,495 @@
+//
+// TypeDefinition.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider {
+
+		uint attributes;
+		TypeReference base_type;
+		internal Range fields_range;
+		internal Range methods_range;
+
+		short packing_size = Mixin.NotResolvedMarker;
+		int class_size = Mixin.NotResolvedMarker;
+
+		Collection<TypeReference> interfaces;
+		Collection<TypeDefinition> nested_types;
+		Collection<MethodDefinition> methods;
+		Collection<FieldDefinition> fields;
+		Collection<EventDefinition> events;
+		Collection<PropertyDefinition> properties;
+		Collection<CustomAttribute> custom_attributes;
+		Collection<SecurityDeclaration> security_declarations;
+
+		public TypeAttributes Attributes {
+			get { return (TypeAttributes) attributes; }
+			set { attributes = (uint) value; }
+		}
+
+		public TypeReference BaseType {
+			get { return base_type; }
+			set { base_type = value; }
+		}
+
+		void ResolveLayout ()
+		{
+			if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker)
+				return;
+
+			if (!HasImage) {
+				packing_size = Mixin.NoDataMarker;
+				class_size = Mixin.NoDataMarker;
+				return;
+			}
+
+			var row = Module.Read (this, (type, reader) => reader.ReadTypeLayout (type));
+
+			packing_size = row.Col1;
+			class_size = row.Col2;
+		}
+
+		public bool HasLayoutInfo {
+			get {
+				if (packing_size >= 0 || class_size >= 0)
+					return true;
+
+				ResolveLayout ();
+
+				return packing_size >= 0 || class_size >= 0;
+			}
+		}
+
+		public short PackingSize {
+			get {
+				if (packing_size >= 0)
+					return packing_size;
+
+				ResolveLayout ();
+
+				return packing_size >= 0 ? packing_size : (short) -1;
+			}
+			set { packing_size = value; }
+		}
+
+		public int ClassSize {
+			get {
+				if (class_size >= 0)
+					return class_size;
+
+				ResolveLayout ();
+
+				return class_size >= 0 ? class_size : -1;
+			}
+			set { class_size = value; }
+		}
+
+		public bool HasInterfaces {
+			get {
+				if (interfaces != null)
+					return interfaces.Count > 0;
+
+				if (HasImage)
+					return Module.Read (this, (type, reader) => reader.HasInterfaces (type));
+
+				return false;
+			}
+		}
+
+		public Collection<TypeReference> Interfaces {
+			get {
+				if (interfaces != null)
+					return interfaces;
+
+				if (HasImage)
+					return interfaces = Module.Read (this, (type, reader) => reader.ReadInterfaces (type));
+
+				return interfaces = new Collection<TypeReference> ();
+			}
+		}
+
+		public bool HasNestedTypes {
+			get {
+				if (nested_types != null)
+					return nested_types.Count > 0;
+
+				if (HasImage)
+					return Module.Read (this, (type, reader) => reader.HasNestedTypes (type));
+
+				return false;
+			}
+		}
+
+		public Collection<TypeDefinition> NestedTypes {
+			get {
+				if (nested_types != null)
+					return nested_types;
+
+				if (HasImage)
+					return nested_types = Module.Read (this, (type, reader) => reader.ReadNestedTypes (type));
+
+				return nested_types = new MemberDefinitionCollection<TypeDefinition> (this);
+			}
+		}
+
+		public bool HasMethods {
+			get {
+				if (methods != null)
+					return methods.Count > 0;
+
+				if (HasImage)
+					return methods_range.Length > 0;
+
+				return false;
+			}
+		}
+
+		public Collection<MethodDefinition> Methods {
+			get {
+				if (methods != null)
+					return methods;
+
+				if (HasImage)
+					return methods = Module.Read (this, (type, reader) => reader.ReadMethods (type));
+
+				return methods = new MemberDefinitionCollection<MethodDefinition> (this);
+			}
+		}
+
+		public bool HasFields {
+			get {
+				if (fields != null)
+					return fields.Count > 0;
+
+				if (HasImage)
+					return fields_range.Length > 0;
+
+				return false;
+			}
+		}
+
+		public Collection<FieldDefinition> Fields {
+			get {
+				if (fields != null)
+					return fields;
+
+				if (HasImage)
+					return fields = Module.Read (this, (type, reader) => reader.ReadFields (type));
+
+				return fields = new MemberDefinitionCollection<FieldDefinition> (this);
+			}
+		}
+
+		public bool HasEvents {
+			get {
+				if (events != null)
+					return events.Count > 0;
+
+				if (HasImage)
+					return Module.Read (this, (type, reader) => reader.HasEvents (type));
+
+				return false;
+			}
+		}
+
+		public Collection<EventDefinition> Events {
+			get {
+				if (events != null)
+					return events;
+
+				if (HasImage)
+					return events = Module.Read (this, (type, reader) => reader.ReadEvents (type));
+
+				return events = new MemberDefinitionCollection<EventDefinition> (this);
+			}
+		}
+
+		public bool HasProperties {
+			get {
+				if (properties != null)
+					return properties.Count > 0;
+
+				if (HasImage)
+					return Module.Read (this, (type, reader) => reader.HasProperties (type));
+
+				return false;
+			}
+		}
+
+		public Collection<PropertyDefinition> Properties {
+			get {
+				if (properties != null)
+					return properties;
+
+				if (HasImage)
+					return properties = Module.Read (this, (type, reader) => reader.ReadProperties (type));
+
+				return properties = new MemberDefinitionCollection<PropertyDefinition> (this);
+			}
+		}
+
+		public bool HasSecurityDeclarations {
+			get {
+				if (security_declarations != null)
+					return security_declarations.Count > 0;
+
+				return this.GetHasSecurityDeclarations (Module);
+			}
+		}
+
+		public Collection<SecurityDeclaration> SecurityDeclarations {
+			get { return security_declarations ?? (security_declarations = this.GetSecurityDeclarations (Module)); }
+		}
+
+		public bool HasCustomAttributes {
+			get {
+				if (custom_attributes != null)
+					return custom_attributes.Count > 0;
+
+				return this.GetHasCustomAttributes (Module);
+			}
+		}
+
+		public Collection<CustomAttribute> CustomAttributes {
+			get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
+		}
+
+		public override bool HasGenericParameters {
+			get {
+				if (generic_parameters != null)
+					return generic_parameters.Count > 0;
+
+				return this.GetHasGenericParameters (Module);
+			}
+		}
+
+		public override Collection<GenericParameter> GenericParameters {
+			get { return generic_parameters ?? (generic_parameters = this.GetGenericParameters (Module)); }
+		}
+
+		#region TypeAttributes
+
+		public bool IsNotPublic {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
+		}
+
+		public bool IsPublic {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
+		}
+
+		public bool IsNestedPublic {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
+		}
+
+		public bool IsNestedPrivate {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
+		}
+
+		public bool IsNestedFamily {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
+		}
+
+		public bool IsNestedAssembly {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
+		}
+
+		public bool IsNestedFamilyAndAssembly {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
+		}
+
+		public bool IsNestedFamilyOrAssembly {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
+		}
+
+		public bool IsAutoLayout {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
+		}
+
+		public bool IsSequentialLayout {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
+		}
+
+		public bool IsExplicitLayout {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
+		}
+
+		public bool IsClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
+		}
+
+		public bool IsInterface {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
+		}
+
+		public bool IsAbstract {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
+		}
+
+		public bool IsSealed {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
+		}
+
+		public bool IsSpecialName {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
+		}
+
+		public bool IsImport {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
+		}
+
+		public bool IsSerializable {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
+		}
+
+		public bool IsAnsiClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
+		}
+
+		public bool IsUnicodeClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
+		}
+
+		public bool IsAutoClass {
+			get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
+			set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
+		}
+
+		public bool IsBeforeFieldInit {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
+		}
+
+		public bool IsRuntimeSpecialName {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
+		}
+
+		public bool HasSecurity {
+			get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
+			set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
+		}
+
+		#endregion
+
+		public bool IsEnum {
+			get { return base_type != null && base_type.IsTypeOf ("System", "Enum"); }
+		}
+
+		public override bool IsValueType {
+			get {
+				if (base_type == null)
+					return false;
+
+				return base_type.IsTypeOf ("System", "Enum") || (base_type.IsTypeOf ("System", "ValueType") && !this.IsTypeOf ("System", "Enum"));
+			}
+		}
+
+		public override bool IsDefinition {
+			get { return true; }
+		}
+
+		public new TypeDefinition DeclaringType {
+			get { return (TypeDefinition) base.DeclaringType; }
+			set { base.DeclaringType = value; }
+		}
+
+		public TypeDefinition (string @namespace, string name, TypeAttributes attributes)
+			: base (@namespace, name)
+		{
+			this.attributes = (uint) attributes;
+			this.token = new MetadataToken (TokenType.TypeDef);
+		}
+
+		public TypeDefinition (string @namespace, string name, TypeAttributes attributes, TypeReference baseType) :
+			this (@namespace, name, attributes)
+		{
+			this.BaseType = baseType;
+		}
+
+		public override TypeDefinition Resolve ()
+		{
+			return this;
+		}
+	}
+
+	static partial class Mixin {
+
+		public static TypeReference GetEnumUnderlyingType (this TypeDefinition self)
+		{
+			var fields = self.Fields;
+
+			for (int i = 0; i < fields.Count; i++) {
+				var field = fields [i];
+				if (!field.IsStatic)
+					return field.FieldType;
+			}
+
+			throw new ArgumentException ();
+		}
+
+		public static TypeDefinition GetNestedType (this TypeDefinition self, string name)
+		{
+			if (!self.HasNestedTypes)
+				return null;
+
+			var nested_types = self.NestedTypes;
+
+			for (int i = 0; i < nested_types.Count; i++) {
+				var nested_type = nested_types [i];
+				if (nested_type.Name == name)
+					return nested_type;
+			}
+
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeDefinitionCollection.cs	(revision 11807)
@@ -0,0 +1,118 @@
+//
+// TypeDefinitionCollection.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+
+using Mono.Cecil.Metadata;
+
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	using Slot = Row<string, string>;
+
+	sealed class TypeDefinitionCollection : Collection<TypeDefinition> {
+
+		readonly ModuleDefinition container;
+		readonly Dictionary<Slot, TypeDefinition> name_cache;
+
+		internal TypeDefinitionCollection (ModuleDefinition container)
+		{
+			this.container = container;
+			this.name_cache = new Dictionary<Slot, TypeDefinition> (new RowEqualityComparer ());
+		}
+
+		internal TypeDefinitionCollection (ModuleDefinition container, int capacity)
+			: base (capacity)
+		{
+			this.container = container;
+			this.name_cache = new Dictionary<Slot, TypeDefinition> (capacity, new RowEqualityComparer ());
+		}
+
+		protected override void OnAdd (TypeDefinition item, int index)
+		{
+			Attach (item);
+		}
+
+		protected override void OnSet (TypeDefinition item, int index)
+		{
+			Attach (item);
+		}
+
+		protected override void OnInsert (TypeDefinition item, int index)
+		{
+			Attach (item);
+		}
+
+		protected override void OnRemove (TypeDefinition item, int index)
+		{
+			Detach (item);
+		}
+
+		protected override void OnClear ()
+		{
+			foreach (var type in this)
+				Detach (type);
+		}
+
+		void Attach (TypeDefinition type)
+		{
+			if (type.Module != null && type.Module != container)
+				throw new ArgumentException ("Type already attached");
+
+			type.module = container;
+			type.scope = container;
+			name_cache [new Slot (type.Namespace, type.Name)] = type;
+		}
+
+		void Detach (TypeDefinition type)
+		{
+			type.module = null;
+			type.scope = null;
+			name_cache.Remove (new Slot (type.Namespace, type.Name));
+		}
+
+		public TypeDefinition GetType (string fullname)
+		{
+			string @namespace, name;
+			TypeParser.SplitFullName (fullname, out @namespace, out name);
+
+			return GetType (@namespace, name);
+		}
+
+		public TypeDefinition GetType (string @namespace, string name)
+		{
+			TypeDefinition type;
+			if (name_cache.TryGetValue (new Slot (@namespace, name), out type))
+				return type;
+
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeParser.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeParser.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeParser.cs	(revision 11807)
@@ -0,0 +1,555 @@
+//
+// TypeParser.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Text;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	class TypeParser {
+
+		class Type {
+			public const int Ptr = -1;
+			public const int ByRef = -2;
+			public const int SzArray = -3;
+
+			public string type_fullname;
+			public string [] nested_names;
+			public int arity;
+			public int [] specs;
+			public Type [] generic_arguments;
+			public string assembly;
+		}
+
+		readonly string fullname;
+		readonly int length;
+
+		int position;
+
+		TypeParser (string fullname)
+		{
+			this.fullname = fullname;
+			this.length = fullname.Length;
+		}
+
+		Type ParseType (bool fq_name)
+		{
+			var type = new Type ();
+			type.type_fullname = ParsePart ();
+
+			type.nested_names = ParseNestedNames ();
+
+			if (TryGetArity (type))
+				type.generic_arguments = ParseGenericArguments (type.arity);
+
+			type.specs = ParseSpecs ();
+
+			if (fq_name)
+				type.assembly = ParseAssemblyName ();
+
+			return type;
+		}
+
+		static bool TryGetArity (Type type)
+		{
+			int arity = 0;
+
+			TryAddArity (type.type_fullname, ref arity);
+
+			var nested_names = type.nested_names;
+			if (!nested_names.IsNullOrEmpty ()) {
+				for (int i = 0; i < nested_names.Length; i++)
+					TryAddArity (nested_names [i], ref arity);
+			}
+
+			type.arity = arity;
+			return arity > 0;
+		}
+
+		static bool TryGetArity (string name, out int arity)
+		{
+			arity = 0;
+			var index = name.LastIndexOf ('`');
+			if (index == -1)
+				return false;
+
+			return ParseInt32 (name.Substring (index + 1), out arity);
+		}
+
+		static bool ParseInt32 (string value, out int result)
+		{
+#if CF
+			try {
+				result = int.Parse (value);
+				return true;
+			} catch {
+				result = 0;
+				return false;
+			}
+#else
+			return int.TryParse (value, out result);
+#endif
+		}
+
+		static void TryAddArity (string name, ref int arity)
+		{
+			int type_arity;
+			if (!TryGetArity (name, out type_arity))
+				return;
+
+			arity += type_arity;
+		}
+
+		string ParsePart ()
+		{
+			int start = position;
+			while (position < length && !IsDelimiter (fullname [position]))
+				position++;
+
+			return fullname.Substring (start, position - start);
+		}
+
+		static bool IsDelimiter (char chr)
+		{
+			return "+,[]*&".IndexOf (chr) != -1;
+		}
+
+		void TryParseWhiteSpace ()
+		{
+			while (position < length && Char.IsWhiteSpace (fullname [position]))
+				position++;
+		}
+
+		string [] ParseNestedNames ()
+		{
+			string [] nested_names = null;
+			while (TryParse ('+'))
+				Add (ref nested_names, ParsePart ());
+
+			return nested_names;
+		}
+
+		bool TryParse (char chr)
+		{
+			if (position < length && fullname [position] == chr) {
+				position++;
+				return true;
+			}
+
+			return false;
+		}
+
+		static void Add<T> (ref T [] array, T item)
+		{
+			if (array == null) {
+				array = new [] { item };
+				return;
+			}
+
+#if !CF
+			Array.Resize (ref array, array.Length + 1);
+#else
+			var copy = new T [array.Length + 1];
+			Array.Copy (array, copy, array.Length);
+			array = copy;
+#endif
+			array [array.Length - 1] = item;
+		}
+
+		int [] ParseSpecs ()
+		{
+			int [] specs = null;
+
+			while (position < length) {
+				switch (fullname [position]) {
+				case '*':
+					position++;
+					Add (ref specs, Type.Ptr);
+					break;
+				case '&':
+					position++;
+					Add (ref specs, Type.ByRef);
+					break;
+				case '[':
+					position++;
+					switch (fullname [position]) {
+					case ']':
+						position++;
+						Add (ref specs, Type.SzArray);
+						break;
+					case '*':
+						position++;
+						Add (ref specs, 1);
+						break;
+					default:
+						var rank = 1;
+						while (TryParse (','))
+							rank++;
+
+						Add (ref specs, rank);
+
+						TryParse (']');
+						break;
+					}
+					break;
+				default:
+					return specs;
+				}
+			}
+
+			return specs;
+		}
+
+		Type [] ParseGenericArguments (int arity)
+		{
+			Type [] generic_arguments = null;
+
+			if (position == length || fullname [position] != '[')
+				return generic_arguments;
+
+			TryParse ('[');
+
+			for (int i = 0; i < arity; i++) {
+				var fq_argument = TryParse ('[');
+				Add (ref generic_arguments, ParseType (fq_argument));
+				if (fq_argument)
+					TryParse (']');
+
+				TryParse (',');
+				TryParseWhiteSpace ();
+			}
+
+			TryParse (']');
+
+			return generic_arguments;
+		}
+
+		string ParseAssemblyName ()
+		{
+			if (!TryParse (','))
+				return string.Empty;
+
+			TryParseWhiteSpace ();
+
+			var start = position;
+			while (position < length) {
+				var chr = fullname [position];
+				if (chr == '[' || chr == ']')
+					break;
+
+				position++;
+			}
+
+			return fullname.Substring (start, position - start);
+		}
+
+		public static TypeReference ParseType (ModuleDefinition module, string fullname)
+		{
+			if (fullname == null)
+				return null;
+
+			var parser = new TypeParser (fullname);
+			return GetTypeReference (module, parser.ParseType (true));
+		}
+
+		static TypeReference GetTypeReference (ModuleDefinition module, Type type_info)
+		{
+			TypeReference type;
+			if (!TryGetDefinition (module, type_info, out type))
+				type = CreateReference (type_info, module, GetMetadataScope (module, type_info));
+
+			return CreateSpecs (type, type_info);
+		}
+
+		static TypeReference CreateSpecs (TypeReference type, Type type_info)
+		{
+			type = TryCreateGenericInstanceType (type, type_info);
+
+			var specs = type_info.specs;
+			if (specs.IsNullOrEmpty ())
+				return type;
+
+			for (int i = 0; i < specs.Length; i++) {
+				switch (specs [i]) {
+				case Type.Ptr:
+					type = new PointerType (type);
+					break;
+				case Type.ByRef:
+					type = new ByReferenceType (type);
+					break;
+				case Type.SzArray:
+					type = new ArrayType (type);
+					break;
+				default:
+					var array = new ArrayType (type);
+					array.Dimensions.Clear ();
+
+					for (int j = 0; j < specs [i]; j++)
+						array.Dimensions.Add (new ArrayDimension ());
+
+					type = array;
+					break;
+				}
+			}
+
+			return type;
+		}
+
+		static TypeReference TryCreateGenericInstanceType (TypeReference type, Type type_info)
+		{
+			var generic_arguments = type_info.generic_arguments;
+			if (generic_arguments.IsNullOrEmpty ())
+				return type;
+
+			var instance = new GenericInstanceType (type);
+			var instance_arguments = instance.GenericArguments;
+
+			for (int i = 0; i < generic_arguments.Length; i++)
+				instance_arguments.Add (GetTypeReference (type.Module, generic_arguments [i]));
+
+			return instance;
+		}
+
+		public static void SplitFullName (string fullname, out string @namespace, out string name)
+		{
+			var last_dot = fullname.LastIndexOf ('.');
+
+			if (last_dot == -1) {
+				@namespace = string.Empty;
+				name = fullname;
+			} else {
+				@namespace = fullname.Substring (0, last_dot);
+				name = fullname.Substring (last_dot + 1);
+			}
+		}
+
+		static TypeReference CreateReference (Type type_info, ModuleDefinition module, IMetadataScope scope)
+		{
+			string @namespace, name;
+			SplitFullName (type_info.type_fullname, out @namespace, out name);
+
+			var type = new TypeReference (@namespace, name, module, scope);
+			MetadataSystem.TryProcessPrimitiveType (type);
+
+			AdjustGenericParameters (type);
+
+			var nested_names = type_info.nested_names;
+			if (nested_names.IsNullOrEmpty ())
+				return type;
+
+			for (int i = 0; i < nested_names.Length; i++) {
+				type = new TypeReference (string.Empty, nested_names [i], module, null) {
+					DeclaringType = type,
+				};
+
+				AdjustGenericParameters (type);
+			}
+
+			return type;
+		}
+
+		static void AdjustGenericParameters (TypeReference type)
+		{
+			int arity;
+			if (!TryGetArity (type.Name, out arity))
+				return;
+
+			for (int i = 0; i < arity; i++)
+				type.GenericParameters.Add (new GenericParameter (type));
+		}
+
+		static IMetadataScope GetMetadataScope (ModuleDefinition module, Type type_info)
+		{
+			if (string.IsNullOrEmpty (type_info.assembly))
+				return module.TypeSystem.Corlib;
+
+			return MatchReference (module, AssemblyNameReference.Parse (type_info.assembly));
+		}
+
+		static AssemblyNameReference MatchReference (ModuleDefinition module, AssemblyNameReference pattern)
+		{
+			var references = module.AssemblyReferences;
+
+			for (int i = 0; i < references.Count; i++) {
+				var reference = references [i];
+				if (reference.FullName == pattern.FullName)
+					return reference;
+			}
+
+			return pattern;
+		}
+
+		static bool TryGetDefinition (ModuleDefinition module, Type type_info, out TypeReference type)
+		{
+			type = null;
+			if (!TryCurrentModule (module, type_info))
+				return false;
+
+			var typedef = module.GetType (type_info.type_fullname);
+			if (typedef == null)
+				return false;
+
+			var nested_names = type_info.nested_names;
+			if (!nested_names.IsNullOrEmpty ()) {
+				for (int i = 0; i < nested_names.Length; i++)
+					typedef = typedef.GetNestedType (nested_names [i]);
+			}
+
+			type = typedef;
+			return true;
+		}
+
+		static bool TryCurrentModule (ModuleDefinition module, Type type_info)
+		{
+			if (string.IsNullOrEmpty (type_info.assembly))
+				return true;
+
+			if (module.assembly != null && module.assembly.Name.FullName == type_info.assembly)
+				return true;
+
+			return false;
+		}
+
+		public static string ToParseable (TypeReference type)
+		{
+			if (type == null)
+				return null;
+
+			var name = new StringBuilder ();
+			AppendType (type, name, true, true);
+			return name.ToString ();
+		}
+
+		static void AppendType (TypeReference type, StringBuilder name, bool fq_name, bool top_level)
+		{
+			var declaring_type = type.DeclaringType;
+			if (declaring_type != null) {
+				AppendType (declaring_type, name, false, top_level);
+				name.Append ('+');
+			}
+
+			var @namespace = type.Namespace;
+			if (!string.IsNullOrEmpty (@namespace)) {
+				name.Append (@namespace);
+				name.Append ('.');
+			}
+
+			name.Append (type.GetElementType ().Name);
+
+			if (!fq_name)
+				return;
+
+			if (type.IsTypeSpecification ())
+				AppendTypeSpecification ((TypeSpecification) type, name);
+
+			if (RequiresFullyQualifiedName (type, top_level)) {
+				name.Append (", ");
+				name.Append (GetScopeFullName (type));
+			}
+		}
+
+		static string GetScopeFullName (TypeReference type)
+		{
+			var scope = type.Scope;
+			switch (scope.MetadataScopeType) {
+			case MetadataScopeType.AssemblyNameReference:
+				return ((AssemblyNameReference) scope).FullName;
+			case MetadataScopeType.ModuleDefinition:
+				return ((ModuleDefinition) scope).Assembly.Name.FullName;
+			}
+
+			throw new ArgumentException ();
+		}
+
+		static void AppendTypeSpecification (TypeSpecification type, StringBuilder name)
+		{
+			if (type.ElementType.IsTypeSpecification ())
+				AppendTypeSpecification ((TypeSpecification) type.ElementType, name);
+
+			switch (type.etype) {
+			case ElementType.Ptr:
+				name.Append ('*');
+				break;
+			case ElementType.ByRef:
+				name.Append ('&');
+				break;
+			case ElementType.SzArray:
+			case ElementType.Array:
+				var array = (ArrayType) type;
+				if (array.IsVector) {
+					name.Append ("[]");
+				} else {
+					name.Append ('[');
+					for (int i = 1; i < array.Rank; i++)
+						name.Append (',');
+					name.Append (']');
+				}
+				break;
+			case ElementType.GenericInst:
+				var instance = (GenericInstanceType) type;
+				var arguments = instance.GenericArguments;
+
+				name.Append ('[');
+
+				for (int i = 0; i < arguments.Count; i++) {
+					if (i > 0)
+						name.Append (',');
+
+					var argument = arguments [i];
+					var requires_fqname = argument.Scope != argument.Module;
+
+					if (requires_fqname)
+						name.Append ('[');
+
+					AppendType (argument, name, true, false);
+
+					if (requires_fqname)
+						name.Append (']');
+				}
+
+				name.Append (']');
+				break;
+			default:
+				return;
+			}
+		}
+
+		static bool RequiresFullyQualifiedName (TypeReference type, bool top_level)
+		{
+			if (type.Scope == type.Module)
+				return false;
+
+			if (type.Scope.Name == "mscorlib" && top_level)
+				return false;
+
+			return true;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeReference.cs	(revision 11807)
@@ -0,0 +1,327 @@
+//
+// TypeReference.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.Metadata;
+using Mono.Collections.Generic;
+
+namespace Mono.Cecil {
+
+	public enum MetadataType : byte {
+		Void = ElementType.Void,
+		Boolean = ElementType.Boolean,
+		Char = ElementType.Char,
+		SByte = ElementType.I1,
+		Byte = ElementType.U1,
+		Int16 = ElementType.I2,
+		UInt16 = ElementType.U2,
+		Int32 = ElementType.I4,
+		UInt32 = ElementType.U4,
+		Int64 = ElementType.I8,
+		UInt64 = ElementType.U8,
+		Single = ElementType.R4,
+		Double = ElementType.R8,
+		String = ElementType.String,
+		Pointer = ElementType.Ptr,
+		ByReference = ElementType.ByRef,
+		ValueType = ElementType.ValueType,
+		Class = ElementType.Class,
+		Var = ElementType.Var,
+		Array = ElementType.Array,
+		GenericInstance = ElementType.GenericInst,
+		TypedByReference = ElementType.TypedByRef,
+		IntPtr = ElementType.I,
+		UIntPtr = ElementType.U,
+		FunctionPointer = ElementType.FnPtr,
+		Object = ElementType.Object,
+		MVar = ElementType.MVar,
+		RequiredModifier = ElementType.CModReqD,
+		OptionalModifier = ElementType.CModOpt,
+		Sentinel = ElementType.Sentinel,
+		Pinned = ElementType.Pinned,
+	}
+
+	public class TypeReference : MemberReference, IGenericParameterProvider, IGenericContext {
+
+		string @namespace;
+		bool value_type;
+		internal IMetadataScope scope;
+		internal ModuleDefinition module;
+
+		internal ElementType etype = ElementType.None;
+
+		string fullname;
+
+		protected Collection<GenericParameter> generic_parameters;
+
+		public override string Name {
+			get { return base.Name; }
+			set {
+				base.Name = value;
+				fullname = null;
+			}
+		}
+
+		public virtual string Namespace {
+			get { return @namespace; }
+			set {
+				@namespace = value;
+				fullname = null;
+			}
+		}
+
+		public virtual bool IsValueType {
+			get { return value_type; }
+			set { value_type = value; }
+		}
+
+		public override ModuleDefinition Module {
+			get {
+				if (module != null)
+					return module;
+
+				var declaring_type = this.DeclaringType;
+				if (declaring_type != null)
+					return declaring_type.Module;
+
+				return null;
+			}
+		}
+
+		IGenericParameterProvider IGenericContext.Type {
+			get { return this; }
+		}
+
+		IGenericParameterProvider IGenericContext.Method {
+			get { return null; }
+		}
+
+		GenericParameterType IGenericParameterProvider.GenericParameterType {
+			get { return GenericParameterType.Type; }
+		}
+
+		public virtual bool HasGenericParameters {
+			get { return !generic_parameters.IsNullOrEmpty (); }
+		}
+
+		public virtual Collection<GenericParameter> GenericParameters {
+			get {
+				if (generic_parameters != null)
+					return generic_parameters;
+
+				return generic_parameters = new Collection<GenericParameter> ();
+			}
+		}
+
+		public virtual IMetadataScope Scope {
+			get {
+				var declaring_type = this.DeclaringType;
+				if (declaring_type != null)
+					return declaring_type.Scope;
+
+				return scope;
+			}
+		}
+
+		public bool IsNested {
+			get { return this.DeclaringType != null; }
+		}
+
+		public override TypeReference DeclaringType {
+			get { return base.DeclaringType; }
+			set {
+				base.DeclaringType = value;
+				fullname = null;
+			}
+		}
+
+		public override string FullName {
+			get {
+				if (fullname != null)
+					return fullname;
+
+				if (IsNested)
+					return fullname = DeclaringType.FullName + "/" + Name;
+
+				if (string.IsNullOrEmpty (@namespace))
+					return fullname = Name;
+
+				return fullname = @namespace + "." + Name;
+			}
+		}
+
+		public virtual bool IsByReference {
+			get { return false; }
+		}
+
+		public virtual bool IsPointer {
+			get { return false; }
+		}
+
+		public virtual bool IsSentinel {
+			get { return false; }
+		}
+
+		public virtual bool IsArray {
+			get { return false; }
+		}
+
+		public virtual bool IsGenericParameter {
+			get { return false; }
+		}
+
+		public virtual bool IsGenericInstance {
+			get { return false; }
+		}
+
+		public virtual bool IsRequiredModifier {
+			get { return false; }
+		}
+
+		public virtual bool IsOptionalModifier {
+			get { return false; }
+		}
+
+		public virtual bool IsPinned {
+			get { return false; }
+		}
+
+		public virtual bool IsFunctionPointer {
+			get { return false; }
+		}
+
+		public bool IsPrimitive {
+			get {
+				switch (etype) {
+				case ElementType.Boolean:
+				case ElementType.Char:
+				case ElementType.I:
+				case ElementType.U:
+				case ElementType.I1:
+				case ElementType.U1:
+				case ElementType.I2:
+				case ElementType.U2:
+				case ElementType.I4:
+				case ElementType.U4:
+				case ElementType.I8:
+				case ElementType.U8:
+				case ElementType.R4:
+				case ElementType.R8:
+					return true;
+				default:
+					return false;
+				}
+			}
+		}
+
+		public virtual MetadataType MetadataType {
+			get {
+				switch (etype) {
+				case ElementType.None:
+					return IsValueType ? MetadataType.ValueType : MetadataType.Class;
+				default:
+					return (MetadataType) etype;
+				}
+			}
+		}
+
+		protected TypeReference (string @namespace, string name)
+			: base (name)
+		{
+			this.@namespace = @namespace ?? string.Empty;
+			this.token = new MetadataToken (TokenType.TypeRef, 0);
+		}
+
+		public TypeReference (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
+			: this (@namespace, name)
+		{
+			this.module = module;
+			this.scope = scope;
+		}
+
+		public TypeReference (string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) :
+			this (@namespace, name, module, scope)
+		{
+			value_type = valueType;
+		}
+
+		public virtual TypeReference GetElementType ()
+		{
+			return this;
+		}
+
+		public virtual TypeDefinition Resolve ()
+		{
+			var module = this.Module;
+			if (module == null)
+				throw new NotSupportedException ();
+
+			return module.Resolve (this);
+		}
+	}
+
+	static partial class Mixin {
+
+		public static bool IsTypeOf (this TypeReference self, string @namespace, string name)
+		{
+			return self.Name == name
+				&& self.Namespace == @namespace;
+		}
+
+		public static bool IsTypeSpecification (this TypeReference type)
+		{
+			switch (type.etype) {
+			case ElementType.Array:
+			case ElementType.ByRef:
+			case ElementType.CModOpt:
+			case ElementType.CModReqD:
+			case ElementType.FnPtr:
+			case ElementType.GenericInst:
+			case ElementType.MVar:
+			case ElementType.Pinned:
+			case ElementType.Ptr:
+			case ElementType.SzArray:
+			case ElementType.Sentinel:
+			case ElementType.Var:
+				return true;
+			}
+
+			return false;
+		}
+
+		public static TypeDefinition CheckedResolve (this TypeReference self)
+		{
+			var type = self.Resolve ();
+			if (type == null)
+				throw new ResolutionException (self);
+
+			return type;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeSpecification.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeSpecification.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeSpecification.cs	(revision 11807)
@@ -0,0 +1,94 @@
+//
+// TypeSpecification.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public abstract class TypeSpecification : TypeReference {
+
+		readonly TypeReference element_type;
+
+		public TypeReference ElementType {
+			get { return element_type; }
+		}
+
+		public override string Name {
+			get { return element_type.Name; }
+			set { throw new NotSupportedException (); }
+		}
+
+		public override string Namespace {
+			get { return element_type.Namespace; }
+			set { throw new NotSupportedException (); }
+		}
+
+		public override IMetadataScope Scope {
+			get { return element_type.Scope; }
+		}
+
+		public override ModuleDefinition Module {
+			get { return element_type.Module; }
+		}
+
+		public override string FullName {
+			get { return element_type.FullName; }
+		}
+
+		internal override bool ContainsGenericParameter {
+			get { return element_type.ContainsGenericParameter; }
+		}
+
+		public override MetadataType MetadataType {
+			get { return (MetadataType) etype; }
+		}
+
+		internal TypeSpecification (TypeReference type)
+			: base (null, null)
+		{
+			this.element_type = type;
+			this.token = new MetadataToken (TokenType.TypeSpec);
+		}
+
+		public override TypeReference GetElementType ()
+		{
+			return element_type.GetElementType ();
+		}
+	}
+
+	static partial class Mixin {
+
+		public static void CheckType (TypeReference type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ("type");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeSystem.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeSystem.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/TypeSystem.cs	(revision 11807)
@@ -0,0 +1,273 @@
+//
+// TypeSystem.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+using Mono.Cecil.Metadata;
+
+namespace Mono.Cecil {
+
+	public abstract class TypeSystem {
+
+		sealed class CorlibTypeSystem : TypeSystem {
+
+			public CorlibTypeSystem (ModuleDefinition module)
+				: base (module)
+			{
+			}
+
+			internal override TypeReference LookupType (string @namespace, string name)
+			{
+				var metadata = module.MetadataSystem;
+				if (metadata.Types == null)
+					Initialize (module.Types);
+
+				return module.Read (new Row<string, string> (@namespace, name), (row, reader) => {
+					var types = reader.metadata.Types;
+
+					for (int i = 0; i < types.Length; i++) {
+						if (types [i] == null)
+							types [i] = reader.GetTypeDefinition ((uint) i + 1);
+
+						var type = types [i];
+
+						if (type.Name == row.Col2 && type.Namespace == row.Col1)
+							return type;
+					}
+
+					return null;
+				});
+			}
+
+			static void Initialize (object obj)
+			{
+			}
+		}
+
+		sealed class CommonTypeSystem : TypeSystem {
+
+			AssemblyNameReference corlib;
+
+			public CommonTypeSystem (ModuleDefinition module)
+				: base (module)
+			{
+			}
+
+			internal override TypeReference LookupType (string @namespace, string name)
+			{
+				return CreateTypeReference (@namespace, name);
+			}
+
+			public AssemblyNameReference GetCorlibReference ()
+			{
+				if (corlib != null)
+					return corlib;
+
+				const string mscorlib = "mscorlib";
+
+				var references = module.AssemblyReferences;
+
+				for (int i = 0; i < references.Count; i++) {
+					var reference = references [i];
+					if (reference.Name == mscorlib)
+						return corlib = reference;
+				}
+
+				corlib = new AssemblyNameReference {
+					Name = mscorlib,
+					Version = GetCorlibVersion (),
+					PublicKeyToken = new byte [] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
+				};
+
+				references.Add (corlib);
+
+				return corlib;
+			}
+
+			Version GetCorlibVersion ()
+			{
+				switch (module.Runtime) {
+				case TargetRuntime.Net_1_0:
+				case TargetRuntime.Net_1_1:
+					return new Version (1, 0, 0, 0);
+				case TargetRuntime.Net_2_0:
+					return new Version (2, 0, 0, 0);
+				case TargetRuntime.Net_4_0:
+					return new Version (4, 0, 0, 0);
+				default:
+					throw new NotSupportedException ();
+				}
+			}
+
+			TypeReference CreateTypeReference (string @namespace, string name)
+			{
+				return new TypeReference (@namespace, name, module, GetCorlibReference ());
+			}
+		}
+
+		readonly ModuleDefinition module;
+
+		TypeReference type_object;
+		TypeReference type_void;
+		TypeReference type_bool;
+		TypeReference type_char;
+		TypeReference type_sbyte;
+		TypeReference type_byte;
+		TypeReference type_int16;
+		TypeReference type_uint16;
+		TypeReference type_int32;
+		TypeReference type_uint32;
+		TypeReference type_int64;
+		TypeReference type_uint64;
+		TypeReference type_single;
+		TypeReference type_double;
+		TypeReference type_intptr;
+		TypeReference type_uintptr;
+		TypeReference type_string;
+		TypeReference type_typedref;
+
+		TypeSystem (ModuleDefinition module)
+		{
+			this.module = module;
+		}
+
+		internal static TypeSystem CreateTypeSystem (ModuleDefinition module)
+		{
+			if (IsCorlib (module))
+				return new CorlibTypeSystem (module);
+
+			return new CommonTypeSystem (module);
+		}
+
+		static bool IsCorlib (ModuleDefinition module)
+		{
+			if (module.Assembly == null)
+				return false;
+
+			return module.Assembly.Name.Name == "mscorlib";
+		}
+
+		internal abstract TypeReference LookupType (string @namespace, string name);
+
+		TypeReference LookupSystemType (string name, ElementType element_type)
+		{
+			var type = LookupType ("System", name);
+			type.etype = element_type;
+			return type;
+		}
+
+		TypeReference LookupSystemValueType (string name, ElementType element_type)
+		{
+			var type = LookupSystemType (name, element_type);
+			type.IsValueType = true;
+			return type;
+		}
+
+		public IMetadataScope Corlib {
+			get {
+				var common = this as CommonTypeSystem;
+				if (common == null)
+					return module;
+
+				return common.GetCorlibReference ();
+			}
+		}
+
+		public TypeReference Object {
+			get { return type_object ?? (type_object = LookupSystemType ("Object", ElementType.Object)); }
+		}
+
+		public TypeReference Void {
+			get { return type_void ?? (type_void = LookupSystemType ("Void", ElementType.Void)); }
+		}
+
+		public TypeReference Boolean {
+			get { return type_bool ?? (type_bool = LookupSystemValueType ("Boolean", ElementType.Boolean)); }
+		}
+
+		public TypeReference Char {
+			get { return type_char ?? (type_char = LookupSystemValueType ("Char", ElementType.Char)); }
+		}
+
+		public TypeReference SByte {
+			get { return type_sbyte ?? (type_sbyte = LookupSystemValueType ("SByte", ElementType.I1)); }
+		}
+
+		public TypeReference Byte {
+			get { return type_byte ?? (type_byte = LookupSystemValueType ("Byte", ElementType.U1)); }
+		}
+
+		public TypeReference Int16 {
+			get { return type_int16 ?? (type_int16 = LookupSystemValueType ("Int16", ElementType.I2)); }
+		}
+
+		public TypeReference UInt16 {
+			get { return type_uint16 ?? (type_uint16 = LookupSystemValueType ("UInt16", ElementType.U2)); }
+		}
+
+		public TypeReference Int32 {
+			get { return type_int32 ?? (type_int32 = LookupSystemValueType ("Int32", ElementType.I4)); }
+		}
+
+		public TypeReference UInt32 {
+			get { return type_uint32 ?? (type_uint32 = LookupSystemValueType ("UInt32", ElementType.U4)); }
+		}
+
+		public TypeReference Int64 {
+			get { return type_int64 ?? (type_int64 = LookupSystemValueType ("Int64", ElementType.I8)); }
+		}
+
+		public TypeReference UInt64 {
+			get { return type_uint64 ?? (type_uint64 = LookupSystemValueType ("UInt64", ElementType.U8)); }
+		}
+
+		public TypeReference Single {
+			get { return type_single ?? (type_single = LookupSystemValueType ("Single", ElementType.R4)); }
+		}
+
+		public TypeReference Double {
+			get { return type_double ?? (type_double = LookupSystemValueType ("Double", ElementType.R8)); }
+		}
+
+		public TypeReference IntPtr {
+			get { return type_intptr ?? (type_intptr = LookupSystemValueType ("IntPtr", ElementType.I)); }
+		}
+
+		public TypeReference UIntPtr {
+			get { return type_uintptr ?? (type_uintptr = LookupSystemValueType ("UIntPtr", ElementType.U)); }
+		}
+
+		public TypeReference String {
+			get { return type_string ?? (type_string = LookupSystemType ("String", ElementType.String)); }
+		}
+
+		public TypeReference TypedReference {
+			get { return type_typedref ?? (type_typedref = LookupSystemValueType ("TypedReference", ElementType.TypedByRef)); }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/VariantType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/VariantType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Cecil/VariantType.cs	(revision 11807)
@@ -0,0 +1,53 @@
+//
+// VariantType.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace Mono.Cecil {
+
+	public enum VariantType {
+		None = 0,
+		I2 = 2,
+		I4 = 3,
+		R4 = 4,
+		R8 = 5,
+		CY = 6,
+		Date = 7,
+		BStr = 8,
+		Dispatch = 9,
+		Error = 10,
+		Bool = 11,
+		Variant = 12,
+		Unknown = 13,
+		Decimal = 14,
+		I1 = 16,
+		UI1 = 17,
+		UI2 = 18,
+		UI4 = 19,
+		Int = 22,
+		UInt = 23
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Collections.Generic/Collection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Collections.Generic/Collection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Collections.Generic/Collection.cs	(revision 11807)
@@ -0,0 +1,420 @@
+//
+// Collection.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace Mono.Collections.Generic {
+
+	public class Collection<T> : IList<T>, IList {
+
+		internal T [] items;
+		internal int size;
+		int version;
+
+		public int Count {
+			get { return size; }
+		}
+
+		public T this [int index] {
+			get {
+				if (index >= size)
+					throw new ArgumentOutOfRangeException ();
+
+				return items [index];
+			}
+			set {
+				CheckIndex (index);
+				if (index == size)
+					throw new ArgumentOutOfRangeException ();
+
+				OnSet (value, index);
+
+				items [index] = value;
+			}
+		}
+
+		bool ICollection<T>.IsReadOnly {
+			get { return false; }
+		}
+
+		bool IList.IsFixedSize {
+			get { return false; }
+		}
+
+		bool IList.IsReadOnly {
+			get { return false; }
+		}
+
+		object IList.this [int index] {
+			get { return this [index]; }
+			set {
+				CheckIndex (index);
+
+				try {
+					this [index] = (T) value;
+					return;
+				} catch (InvalidCastException) {
+				} catch (NullReferenceException) {
+				}
+
+				throw new ArgumentException ();
+			}
+		}
+
+		int ICollection.Count {
+			get { return Count; }
+		}
+
+		bool ICollection.IsSynchronized {
+			get { return false; }
+		}
+
+		object ICollection.SyncRoot {
+			get { return this; }
+		}
+
+		public Collection ()
+		{
+			items = Empty<T>.Array;
+		}
+
+		public Collection (int capacity)
+		{
+			if (capacity < 0)
+				throw new ArgumentOutOfRangeException ();
+
+			items = new T [capacity];
+		}
+
+		public Collection (ICollection<T> items)
+		{
+			if (items == null)
+				throw new ArgumentNullException ("items");
+
+			this.items = new T [items.Count];
+			items.CopyTo (this.items, 0);
+			this.size = this.items.Length;
+		}
+
+		public void Add (T item)
+		{
+			if (size == items.Length)
+				Grow (1);
+
+			OnAdd (item, size);
+
+			items [size++] = item;
+			version++;
+		}
+
+		public bool Contains (T item)
+		{
+			return IndexOf (item) != -1;
+		}
+
+		public int IndexOf (T item)
+		{
+			return Array.IndexOf (items, item, 0, size);
+		}
+
+		public void Insert (int index, T item)
+		{
+			CheckIndex (index);
+			if (size == items.Length)
+				Grow (1);
+
+			OnInsert (item, index);
+
+			Shift (index, 1);
+			items [index] = item;
+			version++;
+		}
+
+		public void RemoveAt (int index)
+		{
+			if (index < 0 || index >= size)
+				throw new ArgumentOutOfRangeException ();
+
+			var item = items [index];
+
+			OnRemove (item, index);
+
+			Shift (index, -1);
+			Array.Clear (items, size, 1);
+			version++;
+		}
+
+		public bool Remove (T item)
+		{
+			var index = IndexOf (item);
+			if (index == -1)
+				return false;
+
+			OnRemove (item, index);
+
+			Shift (index, -1);
+			Array.Clear (items, size, 1);
+			version++;
+
+			return true;
+		}
+
+		public void Clear ()
+		{
+			OnClear ();
+
+			Array.Clear (items, 0, size);
+			size = 0;
+			version++;
+		}
+
+		public void CopyTo (T [] array, int arrayIndex)
+		{
+			Array.Copy (items, 0, array, arrayIndex, size);
+		}
+
+		public T [] ToArray ()
+		{
+			var array = new T [size];
+			Array.Copy (items, 0, array, 0, size);
+			return array;
+		}
+
+		void CheckIndex (int index)
+		{
+			if (index < 0 || index > size)
+				throw new ArgumentOutOfRangeException ();
+		}
+
+		void Shift (int start, int delta)
+		{
+			if (delta < 0)
+				start -= delta;
+
+			if (start < size)
+				Array.Copy (items, start, items, start + delta, size - start);
+
+			size += delta;
+
+			if (delta < 0)
+				Array.Clear (items, size, -delta);
+		}
+
+		protected virtual void OnAdd (T item, int index)
+		{
+		}
+
+		protected virtual void OnInsert (T item, int index)
+		{
+		}
+
+		protected virtual void OnSet (T item, int index)
+		{
+		}
+
+		protected virtual void OnRemove (T item, int index)
+		{
+		}
+
+		protected virtual void OnClear ()
+		{
+		}
+
+		internal virtual void Grow (int desired)
+		{
+			int new_size = size + desired;
+			if (new_size <= items.Length)
+				return;
+
+			const int default_capacity = 4;
+
+			new_size = System.Math.Max (
+				System.Math.Max (items.Length * 2, default_capacity),
+				new_size);
+
+#if !CF
+			Array.Resize (ref items, new_size);
+#else
+			var array = new T [new_size];
+			Array.Copy (items, array, size);
+			items = array;
+#endif
+		}
+
+		int IList.Add (object value)
+		{
+			try {
+				Add ((T) value);
+				return size - 1;
+			} catch (InvalidCastException) {
+			} catch (NullReferenceException) {
+			}
+
+			throw new ArgumentException ();
+		}
+
+		void IList.Clear ()
+		{
+			Clear ();
+		}
+
+		bool IList.Contains (object value)
+		{
+			return ((IList) this).IndexOf (value) > -1;
+		}
+
+		int IList.IndexOf (object value)
+		{
+			try {
+				return IndexOf ((T) value);
+			} catch (InvalidCastException) {
+			} catch (NullReferenceException) {
+			}
+
+			return -1;
+		}
+
+		void IList.Insert (int index, object value)
+		{
+			CheckIndex (index);
+
+			try {
+				Insert (index, (T) value);
+				return;
+			} catch (InvalidCastException) {
+			} catch (NullReferenceException) {
+			}
+
+			throw new ArgumentException ();
+		}
+
+		void IList.Remove (object value)
+		{
+			try {
+				Remove ((T) value);
+			} catch (InvalidCastException) {
+			} catch (NullReferenceException) {
+			}
+		}
+
+		void IList.RemoveAt (int index)
+		{
+			RemoveAt (index);
+		}
+
+		void ICollection.CopyTo (Array array, int index)
+		{
+			Array.Copy (items, 0, array, index, size);
+		}
+
+		public Enumerator GetEnumerator ()
+		{
+			return new Enumerator (this);
+		}
+
+		IEnumerator IEnumerable.GetEnumerator ()
+		{
+			return new Enumerator (this);
+		}
+
+		IEnumerator<T> IEnumerable<T>.GetEnumerator ()
+		{
+			return new Enumerator (this);
+		}
+
+		public struct Enumerator : IEnumerator<T>, IDisposable {
+
+			Collection<T> collection;
+			T current;
+
+			int next;
+			readonly int version;
+
+			public T Current {
+				get { return current; }
+			}
+
+			object IEnumerator.Current {
+				get {
+					CheckState ();
+
+					if (next <= 0)
+						throw new InvalidOperationException ();
+
+					return current;
+				}
+			}
+
+			internal Enumerator (Collection<T> collection)
+				: this ()
+			{
+				this.collection = collection;
+				this.version = collection.version;
+			}
+
+			public bool MoveNext ()
+			{
+				CheckState ();
+
+				if (next < 0)
+					return false;
+
+				if (next < collection.size) {
+					current = collection.items [next++];
+					return true;
+				}
+
+				next = -1;
+				return false;
+			}
+
+			public void Reset ()
+			{
+				CheckState ();
+
+				next = 0;
+			}
+
+			void CheckState ()
+			{
+				if (collection == null)
+					throw new ObjectDisposedException (GetType ().FullName);
+
+				if (version != collection.version)
+					throw new InvalidOperationException ();
+			}
+
+			public void Dispose ()
+			{
+				collection = null;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Collections.Generic/ReadOnlyCollection.cs	(revision 11807)
@@ -0,0 +1,112 @@
+//
+// ReadOnlyCollection.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System .Collections.Generic;
+
+namespace Mono.Collections.Generic {
+
+	public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IList {
+
+		static ReadOnlyCollection<T> empty;
+
+		public static ReadOnlyCollection<T> Empty {
+			get { return empty ?? (empty = new ReadOnlyCollection<T> ()); }
+		}
+
+		bool ICollection<T>.IsReadOnly {
+			get { return true; }
+		}
+
+		bool IList.IsFixedSize {
+			get { return true; }
+		}
+
+		bool IList.IsReadOnly {
+			get { return true; }
+		}
+
+		private ReadOnlyCollection ()
+		{
+		}
+
+		public ReadOnlyCollection (T [] array)
+		{
+			if (array == null)
+				throw new ArgumentNullException ();
+
+			Initialize (array, array.Length);
+		}
+
+		public ReadOnlyCollection (Collection<T> collection)
+		{
+			if (collection == null)
+				throw new ArgumentNullException ();
+
+			Initialize (collection.items, collection.size);
+		}
+
+		void Initialize (T [] items, int size)
+		{
+			this.items = new T [size];
+			Array.Copy (items, 0, this.items, 0, size);
+			this.size = size;
+		}
+
+		internal override void Grow (int desired)
+		{
+			throw new InvalidOperationException ();
+		}
+
+		protected override void OnAdd (T item, int index)
+		{
+			throw new InvalidOperationException ();
+		}
+
+		protected override void OnClear ()
+		{
+			throw new InvalidOperationException ();
+		}
+
+		protected override void OnInsert (T item, int index)
+		{
+			throw new InvalidOperationException ();
+		}
+
+		protected override void OnRemove (T item, int index)
+		{
+			throw new InvalidOperationException ();
+		}
+
+		protected override void OnSet (T item, int index)
+		{
+			throw new InvalidOperationException ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoConvert.cs	(revision 11807)
@@ -0,0 +1,243 @@
+//
+// CryptoConvert.cs - Crypto Convertion Routines
+//
+// Author:
+//	Sebastien Pouliot  <sebastien@ximian.com>
+//
+// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
+// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Security.Cryptography;
+
+#if !(SILVERLIGHT || READ_ONLY)
+
+namespace Mono.Security.Cryptography {
+
+	static class CryptoConvert {
+
+		static private int ToInt32LE (byte [] bytes, int offset)
+		{
+			return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
+		}
+
+		static private uint ToUInt32LE (byte [] bytes, int offset)
+		{
+			return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
+		}
+
+		static private byte[] Trim (byte[] array)
+		{
+			for (int i=0; i < array.Length; i++) {
+				if (array [i] != 0x00) {
+					byte[] result = new byte [array.Length - i];
+					Buffer.BlockCopy (array, i, result, 0, result.Length);
+					return result;
+				}
+			}
+			return null;
+		}
+
+		static RSA FromCapiPrivateKeyBlob (byte[] blob, int offset)
+		{
+			RSAParameters rsap = new RSAParameters ();
+			try {
+				if ((blob [offset]   != 0x07) ||				// PRIVATEKEYBLOB (0x07)
+				    (blob [offset+1] != 0x02) ||				// Version (0x02)
+				    (blob [offset+2] != 0x00) ||				// Reserved (word)
+				    (blob [offset+3] != 0x00) ||
+				    (ToUInt32LE (blob, offset+8) != 0x32415352))	// DWORD magic = RSA2
+					throw new CryptographicException ("Invalid blob header");
+
+				// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
+				// int algId = ToInt32LE (blob, offset+4);
+
+				// DWORD bitlen
+				int bitLen = ToInt32LE (blob, offset+12);
+
+				// DWORD public exponent
+				byte[] exp = new byte [4];
+				Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
+				Array.Reverse (exp);
+				rsap.Exponent = Trim (exp);
+
+				int pos = offset+20;
+				// BYTE modulus[rsapubkey.bitlen/8];
+				int byteLen = (bitLen >> 3);
+				rsap.Modulus = new byte [byteLen];
+				Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
+				Array.Reverse (rsap.Modulus);
+				pos += byteLen;
+
+				// BYTE prime1[rsapubkey.bitlen/16];
+				int byteHalfLen = (byteLen >> 1);
+				rsap.P = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen);
+				Array.Reverse (rsap.P);
+				pos += byteHalfLen;
+
+				// BYTE prime2[rsapubkey.bitlen/16];
+				rsap.Q = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen);
+				Array.Reverse (rsap.Q);
+				pos += byteHalfLen;
+
+				// BYTE exponent1[rsapubkey.bitlen/16];
+				rsap.DP = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen);
+				Array.Reverse (rsap.DP);
+				pos += byteHalfLen;
+
+				// BYTE exponent2[rsapubkey.bitlen/16];
+				rsap.DQ = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen);
+				Array.Reverse (rsap.DQ);
+				pos += byteHalfLen;
+
+				// BYTE coefficient[rsapubkey.bitlen/16];
+				rsap.InverseQ = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen);
+				Array.Reverse (rsap.InverseQ);
+				pos += byteHalfLen;
+
+				// ok, this is hackish but CryptoAPI support it so...
+				// note: only works because CRT is used by default
+				// http://bugzilla.ximian.com/show_bug.cgi?id=57941
+				rsap.D = new byte [byteLen]; // must be allocated
+				if (pos + byteLen + offset <= blob.Length) {
+					// BYTE privateExponent[rsapubkey.bitlen/8];
+					Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen);
+					Array.Reverse (rsap.D);
+				}
+			}
+			catch (Exception e) {
+				throw new CryptographicException ("Invalid blob.", e);
+			}
+
+			RSA rsa = null;
+			try {
+				rsa = RSA.Create ();
+				rsa.ImportParameters (rsap);
+			}
+			catch (CryptographicException ce) {
+				// this may cause problem when this code is run under
+				// the SYSTEM identity on Windows (e.g. ASP.NET). See
+				// http://bugzilla.ximian.com/show_bug.cgi?id=77559
+				try {
+					CspParameters csp = new CspParameters ();
+					csp.Flags = CspProviderFlags.UseMachineKeyStore;
+					rsa = new RSACryptoServiceProvider (csp);
+					rsa.ImportParameters (rsap);
+				}
+				catch {
+					// rethrow original, not the later, exception if this fails
+					throw ce;
+				}
+			}
+			return rsa;
+		}
+
+		static RSA FromCapiPublicKeyBlob (byte[] blob, int offset)
+		{
+			try {
+				if ((blob [offset]   != 0x06) ||				// PUBLICKEYBLOB (0x06)
+				    (blob [offset+1] != 0x02) ||				// Version (0x02)
+				    (blob [offset+2] != 0x00) ||				// Reserved (word)
+				    (blob [offset+3] != 0x00) ||
+				    (ToUInt32LE (blob, offset+8) != 0x31415352))	// DWORD magic = RSA1
+					throw new CryptographicException ("Invalid blob header");
+
+				// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
+				// int algId = ToInt32LE (blob, offset+4);
+
+				// DWORD bitlen
+				int bitLen = ToInt32LE (blob, offset+12);
+
+				// DWORD public exponent
+				RSAParameters rsap = new RSAParameters ();
+				rsap.Exponent = new byte [3];
+				rsap.Exponent [0] = blob [offset+18];
+				rsap.Exponent [1] = blob [offset+17];
+				rsap.Exponent [2] = blob [offset+16];
+
+				int pos = offset+20;
+				// BYTE modulus[rsapubkey.bitlen/8];
+				int byteLen = (bitLen >> 3);
+				rsap.Modulus = new byte [byteLen];
+				Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
+				Array.Reverse (rsap.Modulus);
+
+				RSA rsa = null;
+				try {
+					rsa = RSA.Create ();
+					rsa.ImportParameters (rsap);
+				}
+				catch (CryptographicException) {
+					// this may cause problem when this code is run under
+					// the SYSTEM identity on Windows (e.g. ASP.NET). See
+					// http://bugzilla.ximian.com/show_bug.cgi?id=77559
+					CspParameters csp = new CspParameters ();
+					csp.Flags = CspProviderFlags.UseMachineKeyStore;
+					rsa = new RSACryptoServiceProvider (csp);
+					rsa.ImportParameters (rsap);
+				}
+				return rsa;
+			}
+			catch (Exception e) {
+				throw new CryptographicException ("Invalid blob.", e);
+			}
+		}
+
+		// PRIVATEKEYBLOB
+		// PUBLICKEYBLOB
+		static public RSA FromCapiKeyBlob (byte[] blob)
+		{
+			return FromCapiKeyBlob (blob, 0);
+		}
+
+		static public RSA FromCapiKeyBlob (byte[] blob, int offset)
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			switch (blob [offset]) {
+				case 0x00:
+					// this could be a public key inside an header
+					// like "sn -e" would produce
+					if (blob [offset + 12] == 0x06) {
+						return FromCapiPublicKeyBlob (blob, offset + 12);
+					}
+					break;
+				case 0x06:
+					return FromCapiPublicKeyBlob (blob, offset);
+				case 0x07:
+					return FromCapiPrivateKeyBlob (blob, offset);
+			}
+			throw new CryptographicException ("Unknown blob format.");
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono.Security.Cryptography/CryptoService.cs	(revision 11807)
@@ -0,0 +1,177 @@
+//
+// CryptoService.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Reflection;
+using System.Security.Cryptography;
+
+#if !READ_ONLY
+
+#if !SILVERLIGHT && !CF
+using System.Runtime.Serialization;
+using Mono.Security.Cryptography;
+#endif
+
+using Mono.Cecil.PE;
+
+namespace Mono.Cecil {
+
+	// Most of this code has been adapted
+	// from Jeroen Frijters' fantastic work
+	// in IKVM.Reflection.Emit. Thanks!
+
+	static class CryptoService {
+
+#if !SILVERLIGHT && !CF
+		public static void StrongName (Stream stream, ImageWriter writer, StrongNameKeyPair key_pair)
+		{
+			int strong_name_pointer;
+
+			var strong_name = CreateStrongName (key_pair, HashStream (stream, writer, out strong_name_pointer));
+			PatchStrongName (stream, strong_name_pointer, strong_name);
+		}
+
+		static void PatchStrongName (Stream stream, int strong_name_pointer, byte [] strong_name)
+		{
+			stream.Seek (strong_name_pointer, SeekOrigin.Begin);
+			stream.Write (strong_name, 0, strong_name.Length);
+		}
+
+		static byte [] CreateStrongName (StrongNameKeyPair key_pair, byte [] hash)
+		{
+			const string hash_algo = "SHA1";
+
+			using (var rsa = key_pair.CreateRSA ()) {
+				var formatter = new RSAPKCS1SignatureFormatter (rsa);
+				formatter.SetHashAlgorithm (hash_algo);
+
+				byte [] signature = formatter.CreateSignature (hash);
+				Array.Reverse (signature);
+
+				return signature;
+			}
+		}
+
+		static byte [] HashStream (Stream stream, ImageWriter writer, out int strong_name_pointer)
+		{
+			const int buffer_size = 8192;
+
+			var text = writer.text;
+			var header_size = (int) writer.GetHeaderSize ();
+			var text_section_pointer = (int) text.PointerToRawData;
+			var strong_name_directory = writer.GetStrongNameSignatureDirectory ();
+
+			if (strong_name_directory.Size == 0)
+				throw new InvalidOperationException ();
+
+			strong_name_pointer = (int) (text_section_pointer
+				+ (strong_name_directory.VirtualAddress - text.VirtualAddress));
+			var strong_name_length = (int) strong_name_directory.Size;
+
+			var sha1 = new SHA1Managed ();
+			var buffer = new byte [buffer_size];
+			using (var crypto_stream = new CryptoStream (Stream.Null, sha1, CryptoStreamMode.Write)) {
+
+				stream.Seek (0, SeekOrigin.Begin);
+				CopyStreamChunk (stream, crypto_stream, buffer, header_size);
+
+				stream.Seek (text_section_pointer, SeekOrigin.Begin);
+				CopyStreamChunk (stream, crypto_stream, buffer, (int) strong_name_pointer - text_section_pointer);
+
+				stream.Seek (strong_name_length, SeekOrigin.Current);
+				CopyStreamChunk (stream, crypto_stream, buffer, (int) (stream.Length - (strong_name_pointer + strong_name_length)));
+			}
+
+			return sha1.Hash;
+		}
+#endif
+		static void CopyStreamChunk (Stream stream, Stream dest_stream, byte [] buffer, int length)
+		{
+			while (length > 0) {
+				int read = stream.Read (buffer, 0, System.Math.Min (buffer.Length, length));
+				dest_stream.Write (buffer, 0, read);
+				length -= read;
+			}
+		}
+
+		public static byte [] ComputeHash (string file)
+		{
+			if (!File.Exists (file))
+				return Empty<byte>.Array;
+
+			const int buffer_size = 8192;
+
+			var sha1 = new SHA1Managed ();
+
+			using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
+
+				var buffer = new byte [buffer_size];
+
+				using (var crypto_stream = new CryptoStream (Stream.Null, sha1, CryptoStreamMode.Write))
+					CopyStreamChunk (stream, crypto_stream, buffer, (int) stream.Length);
+			}
+
+			return sha1.Hash;
+		}
+	}
+
+#if !SILVERLIGHT && !CF
+	static partial class Mixin {
+
+		public static RSA CreateRSA (this StrongNameKeyPair key_pair)
+		{
+			byte [] key;
+			string key_container;
+
+			if (!TryGetKeyContainer (key_pair, out key, out key_container))
+				return CryptoConvert.FromCapiKeyBlob (key);
+
+			var parameters = new CspParameters {
+				Flags = CspProviderFlags.UseMachineKeyStore,
+				KeyContainerName = key_container,
+				KeyNumber = 2,
+			};
+
+			return new RSACryptoServiceProvider (parameters);
+		}
+
+		static bool TryGetKeyContainer (ISerializable key_pair, out byte [] key, out string key_container)
+		{
+			var info = new SerializationInfo (typeof (StrongNameKeyPair), new FormatterConverter ());
+			key_pair.GetObjectData (info, new StreamingContext ());
+
+			key = (byte []) info.GetValue ("_keyPairArray", typeof (byte []));
+			key_container = info.GetString ("_keyPairContainer");
+			return key_container != null;
+		}
+	}
+#endif
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Actions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Actions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Actions.cs	(revision 11807)
@@ -0,0 +1,38 @@
+//
+// Actions.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+#if !NET_3_5 && !NET_4_0
+
+namespace Mono {
+	//delegate void Action ();
+	delegate void Action<T1, T2> (T1 arg1, T2 arg2);
+	//delegate void Action<T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3);
+	//delegate void Action<T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Empty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Empty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Empty.cs	(revision 11807)
@@ -0,0 +1,53 @@
+//
+// Empty.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using Mono.Collections.Generic;
+
+namespace Mono {
+
+	static class Empty<T> {
+
+		public static readonly T [] Array = new T [0];
+	}
+}
+
+namespace Mono.Cecil {
+
+	static partial class Mixin {
+
+		public static bool IsNullOrEmpty<T> (this T [] self)
+		{
+			return self == null || self.Length == 0;
+		}
+
+		public static bool IsNullOrEmpty<T> (this Collection<T> self)
+		{
+			return self == null || self.size == 0;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Funcs.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Funcs.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/Mono/Funcs.cs	(revision 11807)
@@ -0,0 +1,39 @@
+//
+// Funcs.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+#if !NET_3_5 && !NET_4_0
+
+namespace Mono {
+	delegate TResult Func<TResult> ();
+	delegate TResult Func<T, TResult> (T arg1);
+	delegate TResult Func<T1, T2, TResult> (T1 arg1, T2 arg2);
+	//delegate TResult Func<T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3);
+	//delegate TResult Func<T1, T2, T3, T4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Mono.Cecil/System.Runtime.CompilerServices/ExtensionAttribute.cs	(revision 11807)
@@ -0,0 +1,40 @@
+//
+// ExtensionAttribute.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+#if !NET_3_5 && !NET_4_0
+
+namespace System.Runtime.CompilerServices {
+
+	[AttributeUsage (AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
+	sealed class ExtensionAttribute : Attribute {
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿//
+// AssemblyInfo.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Mono.Cecil-0.9.5")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Mono.Cecil")]
+[assembly: AssemblyCopyright("Copyright © 2008 - 2010 Jb Evain")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("5b696a2b-cdeb-43ca-a5f3-155baa532183")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("0.9.5.0")]
+[assembly: AssemblyFileVersion("0.9.5.0")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.Cecil.Mdb/MdbReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.Cecil.Mdb/MdbReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.Cecil.Mdb/MdbReader.cs	(revision 11807)
@@ -0,0 +1,213 @@
+//
+// MdbReader.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+using Mono.Cecil.Cil;
+using Mono.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
+
+namespace Mono.Cecil.Mdb {
+
+	public class MdbReaderProvider : ISymbolReaderProvider {
+
+		public ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName)
+		{
+			return new MdbReader (MonoSymbolFile.ReadSymbolFile (module, fileName));
+		}
+
+		public ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+	public class MdbReader : ISymbolReader {
+
+		readonly MonoSymbolFile symbol_file;
+		readonly Dictionary<string, Document> documents;
+
+		public MdbReader (MonoSymbolFile symFile)
+		{
+			symbol_file = symFile;
+			documents = new Dictionary<string, Document> ();
+		}
+
+		public bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header)
+		{
+			return true;
+		}
+
+		public void Read (MethodBody body, InstructionMapper mapper)
+		{
+			var method_token = body.Method.MetadataToken;
+			var entry = symbol_file.GetMethodByToken (method_token.ToInt32	());
+			if (entry == null)
+				return;
+
+			var scopes = ReadScopes (entry, body, mapper);
+			ReadLineNumbers (entry, mapper);
+			ReadLocalVariables (entry, body, scopes);
+		}
+
+		static void ReadLocalVariables (MethodEntry entry, MethodBody body, Scope [] scopes)
+		{
+			var locals = entry.GetLocals ();
+			foreach (var local in locals) {
+				var variable = body.Variables [local.Index];
+				variable.Name = local.Name;
+
+				var index = local.BlockIndex;
+				if (index < 0 || index >= scopes.Length)
+					continue;
+
+				var scope = scopes [index];
+				if (scope == null)
+					continue;
+
+				scope.Variables.Add (variable);
+			}
+		}
+
+		void ReadLineNumbers (MethodEntry entry, InstructionMapper mapper)
+		{
+			Document document = null;
+			var table = entry.GetLineNumberTable ();
+
+			foreach (var line in table.LineNumbers) {
+				var instruction = mapper (line.Offset);
+				if (instruction == null)
+					continue;
+
+				if (document == null)
+					document = GetDocument (entry.CompileUnit.SourceFile);
+
+				instruction.SequencePoint = new SequencePoint (document) {
+					StartLine = line.Row,
+					EndLine = line.Row,
+				};
+			}
+		}
+
+		Document GetDocument (SourceFileEntry file)
+		{
+			var file_name = file.FileName;
+
+			Document document;
+			if (documents.TryGetValue (file_name, out document))
+				return document;
+
+			document = new Document (file_name);
+			documents.Add (file_name, document);
+
+			return document;
+		}
+
+		static Scope [] ReadScopes (MethodEntry entry, MethodBody body, InstructionMapper mapper)
+		{
+			var blocks = entry.GetCodeBlocks ();
+			var scopes = new Scope [blocks.Length];
+
+			foreach (var block in blocks) {
+				if (block.BlockType != CodeBlockEntry.Type.Lexical)
+					continue;
+
+				var scope = new Scope ();
+				scope.Start = mapper (block.StartOffset);
+				scope.End = mapper (block.EndOffset);
+
+				scopes [block.Index] = scope;
+
+				if (body.Scope == null)
+					body.Scope = scope;
+
+				if (!AddScope (body.Scope, scope))
+					body.Scope = scope;
+			}
+
+			return scopes;
+		}
+
+		static bool AddScope (Scope provider, Scope scope)
+		{
+			foreach (var sub_scope in provider.Scopes) {
+				if (AddScope (sub_scope, scope))
+					return true;
+
+				if (scope.Start.Offset >= sub_scope.Start.Offset && scope.End.Offset <= sub_scope.End.Offset) {
+					sub_scope.Scopes.Add (scope);
+					return true;
+				}
+			}
+
+			return false;
+		}
+
+		public void Read (MethodSymbols symbols)
+		{
+			var entry = symbol_file.GetMethodByToken (symbols.MethodToken.ToInt32 ());
+			if (entry == null)
+				return;
+
+			ReadLineNumbers (entry, symbols);
+			ReadLocalVariables (entry, symbols);
+		}
+
+		void ReadLineNumbers (MethodEntry entry, MethodSymbols symbols)
+		{
+			var table = entry.GetLineNumberTable ();
+			var lines = table.LineNumbers;
+
+			var instructions = symbols.instructions = new Collection<InstructionSymbol> (lines.Length);
+
+			for (int i = 0; i < lines.Length; i++) {
+				var line = lines [i];
+
+				instructions.Add (new InstructionSymbol (line.Offset, new SequencePoint (GetDocument (entry.CompileUnit.SourceFile)) {
+					StartLine = line.Row,
+					EndLine = line.Row,
+				}));
+			}
+		}
+
+		static void ReadLocalVariables (MethodEntry entry, MethodSymbols symbols)
+		{
+			foreach (var local in entry.GetLocals ()) {
+				var variable = symbols.Variables [local.Index];
+				variable.Name = local.Name;
+			}
+		}
+
+		public void Dispose ()
+		{
+			symbol_file.Dispose ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.Cecil.Mdb/MdbWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.Cecil.Mdb/MdbWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.Cecil.Mdb/MdbWriter.cs	(revision 11807)
@@ -0,0 +1,251 @@
+//
+// MdbWriter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+using Mono.Cecil.Cil;
+using Mono.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
+
+namespace Mono.Cecil.Mdb {
+
+#if !READ_ONLY
+	public class MdbWriterProvider : ISymbolWriterProvider {
+
+		public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
+		{
+			return new MdbWriter (module.Mvid, fileName);
+		}
+
+		public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+	public class MdbWriter : ISymbolWriter {
+
+		readonly Guid mvid;
+		readonly MonoSymbolWriter writer;
+		readonly Dictionary<string, SourceFile> source_files;
+
+		public MdbWriter (Guid mvid, string assembly)
+		{
+			this.mvid = mvid;
+			this.writer = new MonoSymbolWriter (assembly);
+			this.source_files = new Dictionary<string, SourceFile> ();
+		}
+
+		static Collection<Instruction> GetInstructions (MethodBody body)
+		{
+			var instructions = new Collection<Instruction> ();
+			foreach (var instruction in body.Instructions)
+				if (instruction.SequencePoint != null)
+					instructions.Add (instruction);
+
+			return instructions;
+		}
+
+		SourceFile GetSourceFile (Document document)
+		{
+			var url = document.Url;
+
+			SourceFile source_file;
+			if (source_files.TryGetValue (url, out source_file))
+				return source_file;
+
+			var entry = writer.DefineDocument (url);
+			var compile_unit = writer.DefineCompilationUnit (entry);
+
+			source_file = new SourceFile (compile_unit, entry);
+			source_files.Add (url, source_file);
+			return source_file;
+		}
+
+		void Populate (Collection<Instruction> instructions, int [] offsets,
+			int [] startRows, int [] startCols, out SourceFile file)
+		{
+			SourceFile source_file = null;
+
+			for (int i = 0; i < instructions.Count; i++) {
+				var instruction = instructions [i];
+				offsets [i] = instruction.Offset;
+
+				var sequence_point = instruction.SequencePoint;
+				if (source_file == null)
+					source_file = GetSourceFile (sequence_point.Document);
+
+				startRows [i] = sequence_point.StartLine;
+				startCols [i] = sequence_point.StartColumn;
+			}
+
+			file = source_file;
+		}
+
+		public void Write (MethodBody body)
+		{
+			var method = new SourceMethod (body.Method);
+
+			var instructions = GetInstructions (body);
+			int count = instructions.Count;
+			if (count == 0)
+				return;
+
+			var offsets = new int [count];
+			var start_rows = new int [count];
+			var start_cols = new int [count];
+
+			SourceFile file;
+			Populate (instructions, offsets, start_rows, start_cols, out file);
+
+			var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
+
+			for (int i = 0; i < count; i++)
+				builder.MarkSequencePoint (
+					offsets [i],
+					file.CompilationUnit.SourceFile,
+					start_rows [i],
+					start_cols [i],
+					false);
+
+			if (body.HasVariables)
+				AddVariables (body.Variables);
+
+			writer.CloseMethod ();
+		}
+
+		readonly static byte [] empty_header = new byte [0];
+
+		public bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header)
+		{
+			directory = new ImageDebugDirectory ();
+			header = empty_header;
+			return false;
+		}
+
+		void AddVariables (IList<VariableDefinition> variables)
+		{
+			for (int i = 0; i < variables.Count; i++) {
+				var variable = variables [i];
+				writer.DefineLocalVariable (i, variable.Name);
+			}
+		}
+
+		public void Write (MethodSymbols symbols)
+		{
+			var method = new SourceMethodSymbol (symbols);
+
+			var file = GetSourceFile (symbols.Instructions [0].SequencePoint.Document);
+			var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
+			var count = symbols.Instructions.Count;
+
+			for (int i = 0; i < count; i++) {
+				var instruction = symbols.Instructions [i];
+				var sequence_point = instruction.SequencePoint;
+
+				builder.MarkSequencePoint (
+					instruction.Offset,
+					GetSourceFile (sequence_point.Document).CompilationUnit.SourceFile,
+					sequence_point.StartLine,
+					sequence_point.EndLine,
+					false);
+			}
+
+			if (symbols.HasVariables)
+				AddVariables (symbols.Variables);
+
+			writer.CloseMethod ();
+		}
+
+		public void Dispose ()
+		{
+			writer.WriteSymbolFile (mvid);
+		}
+
+		class SourceFile : ISourceFile {
+
+			readonly CompileUnitEntry compilation_unit;
+			readonly SourceFileEntry entry;
+
+			public SourceFileEntry Entry {
+				get { return entry; }
+			}
+
+			public CompileUnitEntry CompilationUnit {
+				get { return compilation_unit; }
+			}
+
+			public SourceFile (CompileUnitEntry comp_unit, SourceFileEntry entry)
+			{
+				this.compilation_unit = comp_unit;
+				this.entry = entry;
+			}
+		}
+
+		class SourceMethodSymbol : IMethodDef {
+
+			readonly string name;
+			readonly int token;
+
+			public string Name {
+				get { return name;}
+			}
+
+			public int Token {
+				get { return token; }
+			}
+
+			public SourceMethodSymbol (MethodSymbols symbols)
+			{
+				name = symbols.MethodName;
+				token = symbols.MethodToken.ToInt32 ();
+			}
+		}
+
+		class SourceMethod : IMethodDef {
+
+			readonly MethodDefinition method;
+
+			public string Name {
+				get { return method.Name; }
+			}
+
+			public int Token {
+				get { return method.MetadataToken.ToInt32 (); }
+			}
+
+			public SourceMethod (MethodDefinition method)
+			{
+				this.method = method;
+			}
+		}
+	}
+#endif
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs	(revision 11807)
@@ -0,0 +1,733 @@
+//
+// Mono.CSharp.Debugger/MonoSymbolFile.cs
+//
+// Author:
+//   Martin Baulig (martin@ximian.com)
+//
+// (C) 2003 Ximian, Inc.  http://www.ximian.com
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using SRE = System.Reflection.Emit;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading;
+using System.IO;
+
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class MonoSymbolFileException : Exception
+	{
+		public MonoSymbolFileException ()
+			: base ()
+		{ }
+
+		public MonoSymbolFileException (string message, params object[] args)
+			: base (String.Format (message, args))
+		{ }
+	}
+
+	internal class MyBinaryWriter : BinaryWriter
+	{
+		public MyBinaryWriter (Stream stream)
+			: base (stream)
+		{ }
+
+		public void WriteLeb128 (int value)
+		{
+			base.Write7BitEncodedInt (value);
+		}
+	}
+
+	internal class MyBinaryReader : BinaryReader
+	{
+		public MyBinaryReader (Stream stream)
+			: base (stream)
+		{ }
+
+		public int ReadLeb128 ()
+		{
+			return base.Read7BitEncodedInt ();
+		}
+
+		public string ReadString (int offset)
+		{
+			long old_pos = BaseStream.Position;
+			BaseStream.Position = offset;
+
+			string text = ReadString ();
+
+			BaseStream.Position = old_pos;
+			return text;
+		}
+	}
+
+	public interface ISourceFile
+	{
+		SourceFileEntry Entry {
+			get;
+		}
+	}
+
+	public interface ICompileUnit
+	{
+		CompileUnitEntry Entry {
+			get;
+		}
+	}
+
+	public interface IMethodDef
+	{
+		string Name {
+			get;
+		}
+
+		int Token {
+			get;
+		}
+	}
+
+#if !CECIL
+	internal class MonoDebuggerSupport
+	{
+		static GetMethodTokenFunc get_method_token;
+		static GetGuidFunc get_guid;
+		static GetLocalIndexFunc get_local_index;
+
+		delegate int GetMethodTokenFunc (MethodBase method);
+		delegate Guid GetGuidFunc (Module module);
+		delegate int GetLocalIndexFunc (SRE.LocalBuilder local);
+
+		static Delegate create_delegate (Type type, Type delegate_type, string name)
+		{
+			MethodInfo mi = type.GetMethod (name, BindingFlags.Static |
+							BindingFlags.NonPublic);
+			if (mi == null)
+				throw new Exception ("Can't find " + name);
+
+			return Delegate.CreateDelegate (delegate_type, mi);
+		}
+
+		static MonoDebuggerSupport ()
+		{
+			get_method_token = (GetMethodTokenFunc) create_delegate (
+				typeof (Assembly), typeof (GetMethodTokenFunc),
+				"MonoDebugger_GetMethodToken");
+
+			get_guid = (GetGuidFunc) create_delegate (
+				typeof (Module), typeof (GetGuidFunc), "Mono_GetGuid");
+
+			get_local_index = (GetLocalIndexFunc) create_delegate (
+				typeof (SRE.LocalBuilder), typeof (GetLocalIndexFunc),
+				"Mono_GetLocalIndex");
+		}
+
+		public static int GetMethodToken (MethodBase method)
+		{
+			return get_method_token (method);
+		}
+
+		public static Guid GetGuid (Module module)
+		{
+			return get_guid (module);
+		}
+
+		public static int GetLocalIndex (SRE.LocalBuilder local)
+		{
+			return get_local_index (local);
+		}
+	}
+#endif
+
+	public class MonoSymbolFile : IDisposable
+	{
+		List<MethodEntry> methods = new List<MethodEntry> ();
+		List<SourceFileEntry> sources = new List<SourceFileEntry> ();
+		List<CompileUnitEntry> comp_units = new List<CompileUnitEntry> ();
+		Dictionary<Type, int> type_hash = new Dictionary<Type, int> ();
+		Dictionary<int, AnonymousScopeEntry> anonymous_scopes;
+
+		OffsetTable ot;
+		int last_type_index;
+		int last_method_index;
+		int last_namespace_index;
+
+		public readonly string FileName = "<dynamic>";
+		public readonly int MajorVersion = OffsetTable.MajorVersion;
+		public readonly int MinorVersion = OffsetTable.MinorVersion;
+
+		public int NumLineNumbers;
+
+		internal MonoSymbolFile ()
+		{
+			ot = new OffsetTable ();
+		}
+
+		internal int AddSource (SourceFileEntry source)
+		{
+			sources.Add (source);
+			return sources.Count;
+		}
+
+		internal int AddCompileUnit (CompileUnitEntry entry)
+		{
+			comp_units.Add (entry);
+			return comp_units.Count;
+		}
+
+		internal int DefineType (Type type)
+		{
+			int index;
+			if (type_hash.TryGetValue (type, out index))
+				return index;
+
+			index = ++last_type_index;
+			type_hash.Add (type, index);
+			return index;
+		}
+
+		internal void AddMethod (MethodEntry entry)
+		{
+			methods.Add (entry);
+		}
+
+		public MethodEntry DefineMethod (CompileUnitEntry comp_unit, int token,
+						 ScopeVariable[] scope_vars, LocalVariableEntry[] locals,
+						 LineNumberEntry[] lines, CodeBlockEntry[] code_blocks,
+						 string real_name, MethodEntry.Flags flags,
+						 int namespace_id)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			MethodEntry method = new MethodEntry (
+				this, comp_unit, token, scope_vars, locals, lines, code_blocks,
+				real_name, flags, namespace_id);
+			AddMethod (method);
+			return method;
+		}
+
+		internal void DefineAnonymousScope (int id)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			if (anonymous_scopes == null)
+				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>  ();
+
+			anonymous_scopes.Add (id, new AnonymousScopeEntry (id));
+		}
+
+		internal void DefineCapturedVariable (int scope_id, string name, string captured_name,
+						      CapturedVariable.CapturedKind kind)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			AnonymousScopeEntry scope = anonymous_scopes [scope_id];
+			scope.AddCapturedVariable (name, captured_name, kind);
+		}
+
+		internal void DefineCapturedScope (int scope_id, int id, string captured_name)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			AnonymousScopeEntry scope = anonymous_scopes [scope_id];
+			scope.AddCapturedScope (id, captured_name);
+		}
+
+		internal int GetNextTypeIndex ()
+		{
+			return ++last_type_index;
+		}
+
+		internal int GetNextMethodIndex ()
+		{
+			return ++last_method_index;
+		}
+
+		internal int GetNextNamespaceIndex ()
+		{
+			return ++last_namespace_index;
+		}
+
+		void Write (MyBinaryWriter bw, Guid guid)
+		{
+			// Magic number and file version.
+			bw.Write (OffsetTable.Magic);
+			bw.Write (MajorVersion);
+			bw.Write (MinorVersion);
+
+			bw.Write (guid.ToByteArray ());
+
+			//
+			// Offsets of file sections; we must write this after we're done
+			// writing the whole file, so we just reserve the space for it here.
+			//
+			long offset_table_offset = bw.BaseStream.Position;
+			ot.Write (bw, MajorVersion, MinorVersion);
+
+			//
+			// Sort the methods according to their tokens and update their index.
+			//
+			methods.Sort ();
+			for (int i = 0; i < methods.Count; i++)
+				((MethodEntry) methods [i]).Index = i + 1;
+
+			//
+			// Write data sections.
+			//
+			ot.DataSectionOffset = (int) bw.BaseStream.Position;
+			foreach (SourceFileEntry source in sources)
+				source.WriteData (bw);
+			foreach (CompileUnitEntry comp_unit in comp_units)
+				comp_unit.WriteData (bw);
+			foreach (MethodEntry method in methods)
+				method.WriteData (this, bw);
+			ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset;
+
+			//
+			// Write the method index table.
+			//
+			ot.MethodTableOffset = (int) bw.BaseStream.Position;
+			for (int i = 0; i < methods.Count; i++) {
+				MethodEntry entry = (MethodEntry) methods [i];
+				entry.Write (bw);
+			}
+			ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset;
+
+			//
+			// Write source table.
+			//
+			ot.SourceTableOffset = (int) bw.BaseStream.Position;
+			for (int i = 0; i < sources.Count; i++) {
+				SourceFileEntry source = (SourceFileEntry) sources [i];
+				source.Write (bw);
+			}
+			ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset;
+
+			//
+			// Write compilation unit table.
+			//
+			ot.CompileUnitTableOffset = (int) bw.BaseStream.Position;
+			for (int i = 0; i < comp_units.Count; i++) {
+				CompileUnitEntry unit = (CompileUnitEntry) comp_units [i];
+				unit.Write (bw);
+			}
+			ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset;
+
+			//
+			// Write anonymous scope table.
+			//
+			ot.AnonymousScopeCount = anonymous_scopes != null ? anonymous_scopes.Count : 0;
+			ot.AnonymousScopeTableOffset = (int) bw.BaseStream.Position;
+			if (anonymous_scopes != null) {
+				foreach (AnonymousScopeEntry scope in anonymous_scopes.Values)
+					scope.Write (bw);
+			}
+			ot.AnonymousScopeTableSize = (int) bw.BaseStream.Position - ot.AnonymousScopeTableOffset;
+
+			//
+			// Fixup offset table.
+			//
+			ot.TypeCount = last_type_index;
+			ot.MethodCount = methods.Count;
+			ot.SourceCount = sources.Count;
+			ot.CompileUnitCount = comp_units.Count;
+
+			//
+			// Write offset table.
+			//
+			ot.TotalFileSize = (int) bw.BaseStream.Position;
+			bw.Seek ((int) offset_table_offset, SeekOrigin.Begin);
+			ot.Write (bw, MajorVersion, MinorVersion);
+			bw.Seek (0, SeekOrigin.End);
+
+#if false
+			Console.WriteLine ("TOTAL: {0} line numbes, {1} bytes, extended {2} bytes, " +
+					   "{3} methods.", NumLineNumbers, LineNumberSize,
+					   ExtendedLineNumberSize, methods.Count);
+#endif
+		}
+
+		public void CreateSymbolFile (Guid guid, FileStream fs)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			Write (new MyBinaryWriter (fs), guid);
+		}
+
+		MyBinaryReader reader;
+		Dictionary<int, SourceFileEntry> source_file_hash;
+		Dictionary<int, CompileUnitEntry> compile_unit_hash;
+
+		List<MethodEntry> method_list;
+		Dictionary<int, MethodEntry> method_token_hash;
+		Dictionary<string, int> source_name_hash;
+
+		Guid guid;
+
+		MonoSymbolFile (string filename)
+		{
+			this.FileName = filename;
+			FileStream stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
+			reader = new MyBinaryReader (stream);
+
+			try {
+				long magic = reader.ReadInt64 ();
+				int major_version = reader.ReadInt32 ();
+				int minor_version = reader.ReadInt32 ();
+
+				if (magic != OffsetTable.Magic)
+					throw new MonoSymbolFileException (
+						"Symbol file `{0}' is not a valid " +
+						"Mono symbol file", filename);
+				if (major_version != OffsetTable.MajorVersion)
+					throw new MonoSymbolFileException (
+						"Symbol file `{0}' has version {1}, " +
+						"but expected {2}", filename, major_version,
+						OffsetTable.MajorVersion);
+				if (minor_version != OffsetTable.MinorVersion)
+					throw new MonoSymbolFileException (
+						"Symbol file `{0}' has version {1}.{2}, " +
+						"but expected {3}.{4}", filename, major_version,
+						minor_version, OffsetTable.MajorVersion,
+						OffsetTable.MinorVersion);
+
+				MajorVersion = major_version;
+				MinorVersion = minor_version;
+				guid = new Guid (reader.ReadBytes (16));
+
+				ot = new OffsetTable (reader, major_version, minor_version);
+			} catch {
+				throw new MonoSymbolFileException (
+					"Cannot read symbol file `{0}'", filename);
+			}
+
+			source_file_hash = new Dictionary<int, SourceFileEntry> ();
+			compile_unit_hash = new Dictionary<int, CompileUnitEntry> ();
+		}
+
+		void CheckGuidMatch (Guid other, string filename, string assembly)
+		{
+			if (other == guid)
+				return;
+
+			throw new MonoSymbolFileException (
+				"Symbol file `{0}' does not match assembly `{1}'",
+				filename, assembly);
+		}
+
+#if CECIL
+		protected MonoSymbolFile (string filename, Mono.Cecil.ModuleDefinition module)
+			: this (filename)
+		{
+			CheckGuidMatch (module.Mvid, filename, module.FullyQualifiedName);
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (Mono.Cecil.ModuleDefinition module)
+		{
+			return ReadSymbolFile (module, module.FullyQualifiedName);
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (Mono.Cecil.ModuleDefinition module, string filename)
+		{
+			string name = filename + ".mdb";
+
+			return new MonoSymbolFile (name, module);
+		}
+#else
+		protected MonoSymbolFile (string filename, Assembly assembly) : this (filename)
+		{
+			// Check that the MDB file matches the assembly, if we have been
+			// passed an assembly.
+			if (assembly == null)
+				return;
+
+			Module[] modules = assembly.GetModules ();
+			Guid assembly_guid = MonoDebuggerSupport.GetGuid (modules [0]);
+
+			CheckGuidMatch (assembly_guid, filename, assembly.Location);
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (Assembly assembly)
+		{
+			string filename = assembly.Location;
+			string name = filename + ".mdb";
+
+			return new MonoSymbolFile (name, assembly);
+		}
+#endif
+
+		public static MonoSymbolFile ReadSymbolFile (string mdbFilename)
+		{
+			return new MonoSymbolFile (mdbFilename, null);
+		}
+
+		public int CompileUnitCount {
+			get { return ot.CompileUnitCount; }
+		}
+
+		public int SourceCount {
+			get { return ot.SourceCount; }
+		}
+
+		public int MethodCount {
+			get { return ot.MethodCount; }
+		}
+
+		public int TypeCount {
+			get { return ot.TypeCount; }
+		}
+
+		public int AnonymousScopeCount {
+			get { return ot.AnonymousScopeCount; }
+		}
+
+		public int NamespaceCount {
+			get { return last_namespace_index; }
+		}
+
+		public Guid Guid {
+			get { return guid; }
+		}
+
+		public OffsetTable OffsetTable {
+			get { return ot; }
+		}
+
+		internal int LineNumberCount = 0;
+		internal int LocalCount = 0;
+		internal int StringSize = 0;
+
+		internal int LineNumberSize = 0;
+		internal int ExtendedLineNumberSize = 0;
+
+		public SourceFileEntry GetSourceFile (int index)
+		{
+			if ((index < 1) || (index > ot.SourceCount))
+				throw new ArgumentException ();
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				SourceFileEntry source;
+				if (source_file_hash.TryGetValue (index, out source))
+					return source;
+
+				long old_pos = reader.BaseStream.Position;
+
+				reader.BaseStream.Position = ot.SourceTableOffset +
+					SourceFileEntry.Size * (index - 1);
+				source = new SourceFileEntry (this, reader);
+				source_file_hash.Add (index, source);
+
+				reader.BaseStream.Position = old_pos;
+				return source;
+			}
+		}
+
+		public SourceFileEntry[] Sources {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				SourceFileEntry[] retval = new SourceFileEntry [SourceCount];
+				for (int i = 0; i < SourceCount; i++)
+					retval [i] = GetSourceFile (i + 1);
+				return retval;
+			}
+		}
+
+		public CompileUnitEntry GetCompileUnit (int index)
+		{
+			if ((index < 1) || (index > ot.CompileUnitCount))
+				throw new ArgumentException ();
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				CompileUnitEntry unit;
+				if (compile_unit_hash.TryGetValue (index, out unit))
+					return unit;
+
+				long old_pos = reader.BaseStream.Position;
+
+				reader.BaseStream.Position = ot.CompileUnitTableOffset +
+					CompileUnitEntry.Size * (index - 1);
+				unit = new CompileUnitEntry (this, reader);
+				compile_unit_hash.Add (index, unit);
+
+				reader.BaseStream.Position = old_pos;
+				return unit;
+			}
+		}
+
+		public CompileUnitEntry[] CompileUnits {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				CompileUnitEntry[] retval = new CompileUnitEntry [CompileUnitCount];
+				for (int i = 0; i < CompileUnitCount; i++)
+					retval [i] = GetCompileUnit (i + 1);
+				return retval;
+			}
+		}
+
+		void read_methods ()
+		{
+			lock (this) {
+				if (method_token_hash != null)
+					return;
+
+				method_token_hash = new Dictionary<int, MethodEntry> ();
+				method_list = new List<MethodEntry> ();
+
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = ot.MethodTableOffset;
+
+				for (int i = 0; i < MethodCount; i++) {
+					MethodEntry entry = new MethodEntry (this, reader, i + 1);
+					method_token_hash.Add (entry.Token, entry);
+					method_list.Add (entry);
+				}
+
+				reader.BaseStream.Position = old_pos;
+			}
+		}
+
+		public MethodEntry GetMethodByToken (int token)
+		{
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				read_methods ();
+				MethodEntry me;
+				method_token_hash.TryGetValue (token, out me);
+				return me;
+			}
+		}
+
+		public MethodEntry GetMethod (int index)
+		{
+			if ((index < 1) || (index > ot.MethodCount))
+				throw new ArgumentException ();
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				read_methods ();
+				return (MethodEntry) method_list [index - 1];
+			}
+		}
+
+		public MethodEntry[] Methods {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				lock (this) {
+					read_methods ();
+					MethodEntry[] retval = new MethodEntry [MethodCount];
+					method_list.CopyTo (retval, 0);
+					return retval;
+				}
+			}
+		}
+
+		public int FindSource (string file_name)
+		{
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				if (source_name_hash == null) {
+					source_name_hash = new Dictionary<string, int> ();
+
+					for (int i = 0; i < ot.SourceCount; i++) {
+						SourceFileEntry source = GetSourceFile (i + 1);
+						source_name_hash.Add (source.FileName, i);
+					}
+				}
+
+				int value;
+				if (!source_name_hash.TryGetValue (file_name, out value))
+					return -1;
+				return value;
+			}
+		}
+
+		public AnonymousScopeEntry GetAnonymousScope (int id)
+		{
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			AnonymousScopeEntry scope;
+			lock (this) {
+				if (anonymous_scopes != null) {
+					anonymous_scopes.TryGetValue (id, out scope);
+					return scope;
+				}
+
+				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> ();
+				reader.BaseStream.Position = ot.AnonymousScopeTableOffset;
+				for (int i = 0; i < ot.AnonymousScopeCount; i++) {
+					scope = new AnonymousScopeEntry (reader);
+					anonymous_scopes.Add (scope.ID, scope);
+				}
+
+				return anonymous_scopes [id];
+			}
+		}
+
+		internal MyBinaryReader BinaryReader {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				return reader;
+			}
+		}
+
+		public void Dispose ()
+		{
+			Dispose (true);
+		}
+
+		protected virtual void Dispose (bool disposing)
+		{
+			if (disposing) {
+				if (reader != null) {
+					reader.Close ();
+					reader = null;
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs	(revision 11807)
@@ -0,0 +1,1376 @@
+//
+// Mono.CSharp.Debugger/MonoSymbolTable.cs
+//
+// Author:
+//   Martin Baulig (martin@ximian.com)
+//
+// (C) 2002 Ximian, Inc.  http://www.ximian.com
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Security.Cryptography;
+using System.Collections.Generic;
+using System.Text;
+using System.IO;
+
+//
+// Parts which are actually written into the symbol file are marked with
+//
+//         #region This is actually written to the symbol file
+//         #endregion
+//
+// Please do not modify these regions without previously talking to me.
+//
+// All changes to the file format must be synchronized in several places:
+//
+// a) The fields in these regions (and their order) must match the actual
+//    contents of the symbol file.
+//
+//    This helps people to understand the symbol file format without reading
+//    too much source code, ie. you look at the appropriate region and then
+//    you know what's actually in the file.
+//
+//    It is also required to help me enforce b).
+//
+// b) The regions must be kept in sync with the unmanaged code in
+//    mono/metadata/debug-mono-symfile.h
+//
+// When making changes to the file format, you must also increase two version
+// numbers:
+//
+// i)  OffsetTable.Version in this file.
+// ii) MONO_SYMBOL_FILE_VERSION in mono/metadata/debug-mono-symfile.h
+//
+// After doing so, recompile everything, including the debugger.  Symbol files
+// with different versions are incompatible to each other and the debugger and
+// the runtime enfore this, so you need to recompile all your assemblies after
+// changing the file format.
+//
+
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class OffsetTable
+	{
+		public const int  MajorVersion = 50;
+		public const int  MinorVersion = 0;
+		public const long Magic        = 0x45e82623fd7fa614;
+
+		#region This is actually written to the symbol file
+		public int TotalFileSize;
+		public int DataSectionOffset;
+		public int DataSectionSize;
+		public int CompileUnitCount;
+		public int CompileUnitTableOffset;
+		public int CompileUnitTableSize;
+		public int SourceCount;
+		public int SourceTableOffset;
+		public int SourceTableSize;
+		public int MethodCount;
+		public int MethodTableOffset;
+		public int MethodTableSize;
+		public int TypeCount;
+		public int AnonymousScopeCount;
+		public int AnonymousScopeTableOffset;
+		public int AnonymousScopeTableSize;
+
+		[Flags]
+		public enum Flags
+		{
+			IsAspxSource		= 1,
+			WindowsFileNames	= 2
+		}
+
+		public Flags FileFlags;
+
+		public int LineNumberTable_LineBase = LineNumberTable.Default_LineBase;
+		public int LineNumberTable_LineRange = LineNumberTable.Default_LineRange;
+		public int LineNumberTable_OpcodeBase = LineNumberTable.Default_OpcodeBase;
+		#endregion
+
+		internal OffsetTable ()
+		{
+			int platform = (int) Environment.OSVersion.Platform;
+			if ((platform != 4) && (platform != 128))
+				FileFlags |= Flags.WindowsFileNames;
+		}
+
+		internal OffsetTable (BinaryReader reader, int major_version, int minor_version)
+		{
+			TotalFileSize = reader.ReadInt32 ();
+			DataSectionOffset = reader.ReadInt32 ();
+			DataSectionSize = reader.ReadInt32 ();
+			CompileUnitCount = reader.ReadInt32 ();
+			CompileUnitTableOffset = reader.ReadInt32 ();
+			CompileUnitTableSize = reader.ReadInt32 ();
+			SourceCount = reader.ReadInt32 ();
+			SourceTableOffset = reader.ReadInt32 ();
+			SourceTableSize = reader.ReadInt32 ();
+			MethodCount = reader.ReadInt32 ();
+			MethodTableOffset = reader.ReadInt32 ();
+			MethodTableSize = reader.ReadInt32 ();
+			TypeCount = reader.ReadInt32 ();
+
+			AnonymousScopeCount = reader.ReadInt32 ();
+			AnonymousScopeTableOffset = reader.ReadInt32 ();
+			AnonymousScopeTableSize = reader.ReadInt32 ();
+
+			LineNumberTable_LineBase = reader.ReadInt32 ();
+			LineNumberTable_LineRange = reader.ReadInt32 ();
+			LineNumberTable_OpcodeBase = reader.ReadInt32 ();
+
+			FileFlags = (Flags) reader.ReadInt32 ();
+		}
+
+		internal void Write (BinaryWriter bw, int major_version, int minor_version)
+		{
+			bw.Write (TotalFileSize);
+			bw.Write (DataSectionOffset);
+			bw.Write (DataSectionSize);
+			bw.Write (CompileUnitCount);
+			bw.Write (CompileUnitTableOffset);
+			bw.Write (CompileUnitTableSize);
+			bw.Write (SourceCount);
+			bw.Write (SourceTableOffset);
+			bw.Write (SourceTableSize);
+			bw.Write (MethodCount);
+			bw.Write (MethodTableOffset);
+			bw.Write (MethodTableSize);
+			bw.Write (TypeCount);
+
+			bw.Write (AnonymousScopeCount);
+			bw.Write (AnonymousScopeTableOffset);
+			bw.Write (AnonymousScopeTableSize);
+
+			bw.Write (LineNumberTable_LineBase);
+			bw.Write (LineNumberTable_LineRange);
+			bw.Write (LineNumberTable_OpcodeBase);
+
+			bw.Write ((int) FileFlags);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format (
+				"OffsetTable [{0} - {1}:{2} - {3}:{4}:{5} - {6}:{7}:{8} - {9}]",
+				TotalFileSize, DataSectionOffset, DataSectionSize, SourceCount,
+				SourceTableOffset, SourceTableSize, MethodCount, MethodTableOffset,
+				MethodTableSize, TypeCount);
+		}
+	}
+
+	public class LineNumberEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int Row;
+		public readonly int File;
+		public readonly int Offset;
+		public readonly bool IsHidden;
+		#endregion
+
+		public LineNumberEntry (int file, int row, int offset)
+			: this (file, row, offset, false)
+		{ }
+
+		public LineNumberEntry (int file, int row, int offset, bool is_hidden)
+		{
+			this.File = file;
+			this.Row = row;
+			this.Offset = offset;
+			this.IsHidden = is_hidden;
+		}
+
+		public static LineNumberEntry Null = new LineNumberEntry (0, 0, 0);
+
+		private class OffsetComparerClass : IComparer<LineNumberEntry>
+		{
+			public int Compare (LineNumberEntry l1, LineNumberEntry l2)
+			{
+				if (l1.Offset < l2.Offset)
+					return -1;
+				else if (l1.Offset > l2.Offset)
+					return 1;
+				else
+					return 0;
+			}
+		}
+
+		private class RowComparerClass : IComparer<LineNumberEntry>
+		{
+			public int Compare (LineNumberEntry l1, LineNumberEntry l2)
+			{
+				if (l1.Row < l2.Row)
+					return -1;
+				else if (l1.Row > l2.Row)
+					return 1;
+				else
+					return 0;
+			}
+		}
+
+		public static readonly IComparer<LineNumberEntry> OffsetComparer = new OffsetComparerClass ();
+		public static readonly IComparer<LineNumberEntry> RowComparer = new RowComparerClass ();
+
+		public override string ToString ()
+		{
+			return String.Format ("[Line {0}:{1}:{2}]", File, Row, Offset);
+		}
+	}
+
+	public class CodeBlockEntry
+	{
+		public int Index;
+		#region This is actually written to the symbol file
+		public int Parent;
+		public Type BlockType;
+		public int StartOffset;
+		public int EndOffset;
+		#endregion
+
+		public enum Type {
+			Lexical			= 1,
+			CompilerGenerated	= 2,
+			IteratorBody		= 3,
+			IteratorDispatcher	= 4
+		}
+
+		public CodeBlockEntry (int index, int parent, Type type, int start_offset)
+		{
+			this.Index = index;
+			this.Parent = parent;
+			this.BlockType = type;
+			this.StartOffset = start_offset;
+		}
+
+		internal CodeBlockEntry (int index, MyBinaryReader reader)
+		{
+			this.Index = index;
+			int type_flag = reader.ReadLeb128 ();
+			BlockType = (Type) (type_flag & 0x3f);
+			this.Parent = reader.ReadLeb128 ();
+			this.StartOffset = reader.ReadLeb128 ();
+			this.EndOffset = reader.ReadLeb128 ();
+
+			/* Reserved for future extensions. */
+			if ((type_flag & 0x40) != 0) {
+				int data_size = reader.ReadInt16 ();
+				reader.BaseStream.Position += data_size;
+			}
+		}
+
+		public void Close (int end_offset)
+		{
+			this.EndOffset = end_offset;
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 ((int) BlockType);
+			bw.WriteLeb128 (Parent);
+			bw.WriteLeb128 (StartOffset);
+			bw.WriteLeb128 (EndOffset);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[CodeBlock {0}:{1}:{2}:{3}:{4}]",
+					      Index, Parent, BlockType, StartOffset, EndOffset);
+		}
+	}
+
+	public struct LocalVariableEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int Index;
+		public readonly string Name;
+		public readonly int BlockIndex;
+		#endregion
+
+		public LocalVariableEntry (int index, string name, int block)
+		{
+			this.Index = index;
+			this.Name = name;
+			this.BlockIndex = block;
+		}
+
+		internal LocalVariableEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			Index = reader.ReadLeb128 ();
+			Name = reader.ReadString ();
+			BlockIndex = reader.ReadLeb128 ();
+		}
+
+		internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (Index);
+			bw.Write (Name);
+			bw.WriteLeb128 (BlockIndex);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[LocalVariable {0}:{1}:{2}]",
+					      Name, Index, BlockIndex - 1);
+		}
+	}
+
+	public struct CapturedVariable
+	{
+		#region This is actually written to the symbol file
+		public readonly string Name;
+		public readonly string CapturedName;
+		public readonly CapturedKind Kind;
+		#endregion
+
+		public enum CapturedKind : byte
+		{
+			Local,
+			Parameter,
+			This
+		}
+
+		public CapturedVariable (string name, string captured_name,
+					 CapturedKind kind)
+		{
+			this.Name = name;
+			this.CapturedName = captured_name;
+			this.Kind = kind;
+		}
+
+		internal CapturedVariable (MyBinaryReader reader)
+		{
+			Name = reader.ReadString ();
+			CapturedName = reader.ReadString ();
+			Kind = (CapturedKind) reader.ReadByte ();
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.Write (Name);
+			bw.Write (CapturedName);
+			bw.Write ((byte) Kind);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[CapturedVariable {0}:{1}:{2}]",
+					      Name, CapturedName, Kind);
+		}
+	}
+
+	public struct CapturedScope
+	{
+		#region This is actually written to the symbol file
+		public readonly int Scope;
+		public readonly string CapturedName;
+		#endregion
+
+		public CapturedScope (int scope, string captured_name)
+		{
+			this.Scope = scope;
+			this.CapturedName = captured_name;
+		}
+
+		internal CapturedScope (MyBinaryReader reader)
+		{
+			Scope = reader.ReadLeb128 ();
+			CapturedName = reader.ReadString ();
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (Scope);
+			bw.Write (CapturedName);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[CapturedScope {0}:{1}]",
+					      Scope, CapturedName);
+		}
+	}
+
+	public struct ScopeVariable
+	{
+		#region This is actually written to the symbol file
+		public readonly int Scope;
+		public readonly int Index;
+		#endregion
+
+		public ScopeVariable (int scope, int index)
+		{
+			this.Scope = scope;
+			this.Index = index;
+		}
+
+		internal ScopeVariable (MyBinaryReader reader)
+		{
+			Scope = reader.ReadLeb128 ();
+			Index = reader.ReadLeb128 ();
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (Scope);
+			bw.WriteLeb128 (Index);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[ScopeVariable {0}:{1}]", Scope, Index);
+		}
+	}
+
+	public class AnonymousScopeEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int ID;
+		#endregion
+
+		List<CapturedVariable> captured_vars = new List<CapturedVariable> ();
+		List<CapturedScope> captured_scopes = new List<CapturedScope> ();
+
+		public AnonymousScopeEntry (int id)
+		{
+			this.ID = id;
+		}
+
+		internal AnonymousScopeEntry (MyBinaryReader reader)
+		{
+			ID = reader.ReadLeb128 ();
+
+			int num_captured_vars = reader.ReadLeb128 ();
+			for (int i = 0; i < num_captured_vars; i++)
+				captured_vars.Add (new CapturedVariable (reader));
+
+			int num_captured_scopes = reader.ReadLeb128 ();
+			for (int i = 0; i < num_captured_scopes; i++)
+				captured_scopes.Add (new CapturedScope (reader));
+		}
+
+		internal void AddCapturedVariable (string name, string captured_name,
+						   CapturedVariable.CapturedKind kind)
+		{
+			captured_vars.Add (new CapturedVariable (name, captured_name, kind));
+		}
+
+		public CapturedVariable[] CapturedVariables {
+			get {
+				CapturedVariable[] retval = new CapturedVariable [captured_vars.Count];
+				captured_vars.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		internal void AddCapturedScope (int scope, string captured_name)
+		{
+			captured_scopes.Add (new CapturedScope (scope, captured_name));
+		}
+
+		public CapturedScope[] CapturedScopes {
+			get {
+				CapturedScope[] retval = new CapturedScope [captured_scopes.Count];
+				captured_scopes.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (ID);
+
+			bw.WriteLeb128 (captured_vars.Count);
+			foreach (CapturedVariable cv in captured_vars)
+				cv.Write (bw);
+
+			bw.WriteLeb128 (captured_scopes.Count);
+			foreach (CapturedScope cs in captured_scopes)
+				cs.Write (bw);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[AnonymousScope {0}]", ID);
+		}
+	}
+
+	public class CompileUnitEntry : ICompileUnit
+	{
+		#region This is actually written to the symbol file
+		public readonly int Index;
+		int DataOffset;
+		#endregion
+
+		MonoSymbolFile file;
+		SourceFileEntry source;
+		List<SourceFileEntry> include_files;
+		List<NamespaceEntry> namespaces;
+
+		bool creating;
+
+		public static int Size {
+			get { return 8; }
+		}
+
+		CompileUnitEntry ICompileUnit.Entry {
+			get { return this; }
+		}
+
+		public CompileUnitEntry (MonoSymbolFile file, SourceFileEntry source)
+		{
+			this.file = file;
+			this.source = source;
+
+			this.Index = file.AddCompileUnit (this);
+
+			creating = true;
+			namespaces = new List<NamespaceEntry> ();
+		}
+
+		public void AddFile (SourceFileEntry file)
+		{
+			if (!creating)
+				throw new InvalidOperationException ();
+
+			if (include_files == null)
+				include_files = new List<SourceFileEntry> ();
+
+			include_files.Add (file);
+		}
+
+		public SourceFileEntry SourceFile {
+			get {
+				if (creating)
+					return source;
+
+				ReadData ();
+				return source;
+			}
+		}
+
+		public int DefineNamespace (string name, string[] using_clauses, int parent)
+		{
+			if (!creating)
+				throw new InvalidOperationException ();
+
+			int index = file.GetNextNamespaceIndex ();
+			NamespaceEntry ns = new NamespaceEntry (name, index, using_clauses, parent);
+			namespaces.Add (ns);
+			return index;
+		}
+
+		internal void WriteData (MyBinaryWriter bw)
+		{
+			DataOffset = (int) bw.BaseStream.Position;
+			bw.WriteLeb128 (source.Index);
+
+			int count_includes = include_files != null ? include_files.Count : 0;
+			bw.WriteLeb128 (count_includes);
+			if (include_files != null) {
+				foreach (SourceFileEntry entry in include_files)
+					bw.WriteLeb128 (entry.Index);
+			}
+
+			bw.WriteLeb128 (namespaces.Count);
+			foreach (NamespaceEntry ns in namespaces)
+				ns.Write (file, bw);
+		}
+
+		internal void Write (BinaryWriter bw)
+		{
+			bw.Write (Index);
+			bw.Write (DataOffset);
+		}
+
+		internal CompileUnitEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			this.file = file;
+
+			Index = reader.ReadInt32 ();
+			DataOffset = reader.ReadInt32 ();
+		}
+
+		void ReadData ()
+		{
+			if (creating)
+				throw new InvalidOperationException ();
+
+			lock (file) {
+				if (namespaces != null)
+					return;
+
+				MyBinaryReader reader = file.BinaryReader;
+				int old_pos = (int) reader.BaseStream.Position;
+
+				reader.BaseStream.Position = DataOffset;
+
+				int source_idx = reader.ReadLeb128 ();
+				source = file.GetSourceFile (source_idx);
+
+				int count_includes = reader.ReadLeb128 ();
+				if (count_includes > 0) {
+					include_files = new List<SourceFileEntry> ();
+					for (int i = 0; i < count_includes; i++)
+						include_files.Add (file.GetSourceFile (reader.ReadLeb128 ()));
+				}
+
+				int count_ns = reader.ReadLeb128 ();
+				namespaces = new List<NamespaceEntry> ();
+				for (int i = 0; i < count_ns; i ++)
+					namespaces.Add (new NamespaceEntry (file, reader));
+
+				reader.BaseStream.Position = old_pos;
+			}
+		}
+
+		public NamespaceEntry[] Namespaces {
+			get {
+				ReadData ();
+				NamespaceEntry[] retval = new NamespaceEntry [namespaces.Count];
+				namespaces.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		public SourceFileEntry[] IncludeFiles {
+			get {
+				ReadData ();
+				if (include_files == null)
+					return new SourceFileEntry [0];
+
+				SourceFileEntry[] retval = new SourceFileEntry [include_files.Count];
+				include_files.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+	}
+
+	public class SourceFileEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int Index;
+		int DataOffset;
+		#endregion
+
+		MonoSymbolFile file;
+		string file_name;
+		byte[] guid;
+		byte[] hash;
+		bool creating;
+		bool auto_generated;
+
+		public static int Size {
+			get { return 8; }
+		}
+
+		public SourceFileEntry (MonoSymbolFile file, string file_name)
+		{
+			this.file = file;
+			this.file_name = file_name;
+			this.Index = file.AddSource (this);
+
+			creating = true;
+		}
+
+		public SourceFileEntry (MonoSymbolFile file, string file_name,
+					byte[] guid, byte[] checksum)
+			: this (file, file_name)
+		{
+			this.guid = guid;
+			this.hash = checksum;
+		}
+
+		internal void WriteData (MyBinaryWriter bw)
+		{
+			DataOffset = (int) bw.BaseStream.Position;
+			bw.Write (file_name);
+
+			if (guid == null) {
+				guid = Guid.NewGuid ().ToByteArray ();
+				try {
+					using (FileStream fs = new FileStream (file_name, FileMode.Open, FileAccess.Read)) {
+						MD5 md5 = MD5.Create ();
+						hash = md5.ComputeHash (fs);
+					}
+				} catch {
+					hash = new byte [16];
+				}
+			}
+
+			bw.Write (guid);
+			bw.Write (hash);
+			bw.Write ((byte) (auto_generated ? 1 : 0));
+		}
+
+		internal void Write (BinaryWriter bw)
+		{
+			bw.Write (Index);
+			bw.Write (DataOffset);
+		}
+
+		internal SourceFileEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			this.file = file;
+
+			Index = reader.ReadInt32 ();
+			DataOffset = reader.ReadInt32 ();
+
+			int old_pos = (int) reader.BaseStream.Position;
+			reader.BaseStream.Position = DataOffset;
+
+			file_name = reader.ReadString ();
+			guid = reader.ReadBytes (16);
+			hash = reader.ReadBytes (16);
+			auto_generated = reader.ReadByte () == 1;
+
+			reader.BaseStream.Position = old_pos;
+		}
+
+		public string FileName {
+			get { return file_name; }
+		}
+
+		public bool AutoGenerated {
+			get { return auto_generated; }
+		}
+
+		public void SetAutoGenerated ()
+		{
+			if (!creating)
+				throw new InvalidOperationException ();
+
+			auto_generated = true;
+			file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource;
+		}
+
+		public bool CheckChecksum ()
+		{
+			try {
+				using (FileStream fs = new FileStream (file_name, FileMode.Open)) {
+					MD5 md5 = MD5.Create ();
+					byte[] data = md5.ComputeHash (fs);
+					for (int i = 0; i < 16; i++)
+						if (data [i] != hash [i])
+							return false;
+					return true;
+				}
+			} catch {
+				return false;
+			}
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("SourceFileEntry ({0}:{1})", Index, DataOffset);
+		}
+	}
+
+	public class LineNumberTable
+	{
+		protected LineNumberEntry[] _line_numbers;
+		public LineNumberEntry[] LineNumbers {
+			get { return _line_numbers; }
+		}
+
+		public readonly int LineBase;
+		public readonly int LineRange;
+		public readonly byte OpcodeBase;
+		public readonly int MaxAddressIncrement;
+
+#region Configurable constants
+		public const int Default_LineBase = -1;
+		public const int Default_LineRange = 8;
+		public const byte Default_OpcodeBase = 9;
+
+		public const bool SuppressDuplicates = true;
+#endregion
+
+		public const byte DW_LNS_copy = 1;
+		public const byte DW_LNS_advance_pc = 2;
+		public const byte DW_LNS_advance_line = 3;
+		public const byte DW_LNS_set_file = 4;
+		public const byte DW_LNS_const_add_pc = 8;
+
+		public const byte DW_LNE_end_sequence = 1;
+
+		// MONO extensions.
+		public const byte DW_LNE_MONO_negate_is_hidden = 0x40;
+
+		internal const byte DW_LNE_MONO__extensions_start = 0x40;
+		internal const byte DW_LNE_MONO__extensions_end   = 0x7f;
+
+		protected LineNumberTable (MonoSymbolFile file)
+		{
+			this.LineBase = file.OffsetTable.LineNumberTable_LineBase;
+			this.LineRange = file.OffsetTable.LineNumberTable_LineRange;
+			this.OpcodeBase = (byte) file.OffsetTable.LineNumberTable_OpcodeBase;
+			this.MaxAddressIncrement = (255 - OpcodeBase) / LineRange;
+		}
+
+		internal LineNumberTable (MonoSymbolFile file, LineNumberEntry[] lines)
+			: this (file)
+		{
+			this._line_numbers = lines;
+		}
+
+		internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			int start = (int) bw.BaseStream.Position;
+
+			bool last_is_hidden = false;
+			int last_line = 1, last_offset = 0, last_file = 1;
+			for (int i = 0; i < LineNumbers.Length; i++) {
+				int line_inc = LineNumbers [i].Row - last_line;
+				int offset_inc = LineNumbers [i].Offset - last_offset;
+
+				if (SuppressDuplicates && (i+1 < LineNumbers.Length)) {
+					if (LineNumbers [i+1].Equals (LineNumbers [i]))
+						continue;
+				}
+
+				if (LineNumbers [i].File != last_file) {
+					bw.Write (DW_LNS_set_file);
+					bw.WriteLeb128 (LineNumbers [i].File);
+					last_file = LineNumbers [i].File;
+				}
+
+				if (LineNumbers [i].IsHidden != last_is_hidden) {
+					bw.Write ((byte) 0);
+					bw.Write ((byte) 1);
+					bw.Write (DW_LNE_MONO_negate_is_hidden);
+					last_is_hidden = LineNumbers [i].IsHidden;
+				}
+
+				if (offset_inc >= MaxAddressIncrement) {
+					if (offset_inc < 2 * MaxAddressIncrement) {
+						bw.Write (DW_LNS_const_add_pc);
+						offset_inc -= MaxAddressIncrement;
+					} else {
+						bw.Write (DW_LNS_advance_pc);
+						bw.WriteLeb128 (offset_inc);
+						offset_inc = 0;
+					}
+				}
+
+				if ((line_inc < LineBase) || (line_inc >= LineBase + LineRange)) {
+					bw.Write (DW_LNS_advance_line);
+					bw.WriteLeb128 (line_inc);
+					if (offset_inc != 0) {
+						bw.Write (DW_LNS_advance_pc);
+						bw.WriteLeb128 (offset_inc);
+					}
+					bw.Write (DW_LNS_copy);
+				} else {
+					byte opcode;
+					opcode = (byte) (line_inc - LineBase + (LineRange * offset_inc) +
+							 OpcodeBase);
+					bw.Write (opcode);
+				}
+
+				last_line = LineNumbers [i].Row;
+				last_offset = LineNumbers [i].Offset;
+			}
+
+			bw.Write ((byte) 0);
+			bw.Write ((byte) 1);
+			bw.Write (DW_LNE_end_sequence);
+
+			file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start;
+		}
+
+		internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br)
+		{
+			LineNumberTable lnt = new LineNumberTable (file);
+			lnt.DoRead (file, br);
+			return lnt;
+		}
+
+		void DoRead (MonoSymbolFile file, MyBinaryReader br)
+		{
+			var lines = new List<LineNumberEntry> ();
+
+			bool is_hidden = false, modified = false;
+			int stm_line = 1, stm_offset = 0, stm_file = 1;
+			while (true) {
+				byte opcode = br.ReadByte ();
+
+				if (opcode == 0) {
+					byte size = br.ReadByte ();
+					long end_pos = br.BaseStream.Position + size;
+					opcode = br.ReadByte ();
+
+					if (opcode == DW_LNE_end_sequence) {
+						if (modified)
+							lines.Add (new LineNumberEntry (
+								stm_file, stm_line, stm_offset, is_hidden));
+						break;
+					} else if (opcode == DW_LNE_MONO_negate_is_hidden) {
+						is_hidden = !is_hidden;
+						modified = true;
+					} else if ((opcode >= DW_LNE_MONO__extensions_start) &&
+						   (opcode <= DW_LNE_MONO__extensions_end)) {
+						; // reserved for future extensions
+					} else {
+						throw new MonoSymbolFileException (
+							"Unknown extended opcode {0:x} in LNT ({1})",
+							opcode, file.FileName);
+					}
+
+					br.BaseStream.Position = end_pos;
+					continue;
+				} else if (opcode < OpcodeBase) {
+					switch (opcode) {
+					case DW_LNS_copy:
+						lines.Add (new LineNumberEntry (
+							stm_file, stm_line, stm_offset, is_hidden));
+						modified = false;
+						break;
+					case DW_LNS_advance_pc:
+						stm_offset += br.ReadLeb128 ();
+						modified = true;
+						break;
+					case DW_LNS_advance_line:
+						stm_line += br.ReadLeb128 ();
+						modified = true;
+						break;
+					case DW_LNS_set_file:
+						stm_file = br.ReadLeb128 ();
+						modified = true;
+						break;
+					case DW_LNS_const_add_pc:
+						stm_offset += MaxAddressIncrement;
+						modified = true;
+						break;
+					default:
+						throw new MonoSymbolFileException (
+							"Unknown standard opcode {0:x} in LNT",
+							opcode);
+					}
+				} else {
+					opcode -= OpcodeBase;
+
+					stm_offset += opcode / LineRange;
+					stm_line += LineBase + (opcode % LineRange);
+					lines.Add (new LineNumberEntry (
+						stm_file, stm_line, stm_offset, is_hidden));
+					modified = false;
+				}
+			}
+
+			_line_numbers = new LineNumberEntry [lines.Count];
+			lines.CopyTo (_line_numbers, 0);
+		}
+
+		public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end)
+		{
+			if (_line_numbers.Length > 1) {
+				start = _line_numbers [0];
+				end = _line_numbers [_line_numbers.Length - 1];
+				return true;
+			}
+
+			start = LineNumberEntry.Null;
+			end = LineNumberEntry.Null;
+			return false;
+		}
+	}
+
+	public class MethodEntry : IComparable
+	{
+		#region This is actually written to the symbol file
+		public readonly int CompileUnitIndex;
+		public readonly int Token;
+		public readonly int NamespaceID;
+
+		int DataOffset;
+		int LocalVariableTableOffset;
+		int LineNumberTableOffset;
+		int CodeBlockTableOffset;
+		int ScopeVariableTableOffset;
+		int RealNameOffset;
+		Flags flags;
+		#endregion
+
+		int index;
+
+		public Flags MethodFlags {
+			get { return flags; }
+		}
+
+		public readonly CompileUnitEntry CompileUnit;
+
+		LocalVariableEntry[] locals;
+		CodeBlockEntry[] code_blocks;
+		ScopeVariable[] scope_vars;
+		LineNumberTable lnt;
+		string real_name;
+
+		public readonly MonoSymbolFile SymbolFile;
+
+		public int Index {
+			get { return index; }
+			set { index = value; }
+		}
+
+		[Flags]
+		public enum Flags
+		{
+			LocalNamesAmbiguous	= 1
+		}
+
+		public const int Size = 12;
+
+		internal MethodEntry (MonoSymbolFile file, MyBinaryReader reader, int index)
+		{
+			this.SymbolFile = file;
+			this.index = index;
+
+			Token = reader.ReadInt32 ();
+			DataOffset = reader.ReadInt32 ();
+			LineNumberTableOffset = reader.ReadInt32 ();
+
+			long old_pos = reader.BaseStream.Position;
+			reader.BaseStream.Position = DataOffset;
+
+			CompileUnitIndex = reader.ReadLeb128 ();
+			LocalVariableTableOffset = reader.ReadLeb128 ();
+			NamespaceID = reader.ReadLeb128 ();
+
+			CodeBlockTableOffset = reader.ReadLeb128 ();
+			ScopeVariableTableOffset = reader.ReadLeb128 ();
+
+			RealNameOffset = reader.ReadLeb128 ();
+
+			flags = (Flags) reader.ReadLeb128 ();
+
+			reader.BaseStream.Position = old_pos;
+
+			CompileUnit = file.GetCompileUnit (CompileUnitIndex);
+		}
+
+		internal MethodEntry (MonoSymbolFile file, CompileUnitEntry comp_unit,
+				      int token, ScopeVariable[] scope_vars,
+				      LocalVariableEntry[] locals, LineNumberEntry[] lines,
+				      CodeBlockEntry[] code_blocks, string real_name,
+				      Flags flags, int namespace_id)
+		{
+			this.SymbolFile = file;
+			this.real_name = real_name;
+			this.locals = locals;
+			this.code_blocks = code_blocks;
+			this.scope_vars = scope_vars;
+			this.flags = flags;
+
+			index = -1;
+
+			Token = token;
+			CompileUnitIndex = comp_unit.Index;
+			CompileUnit = comp_unit;
+			NamespaceID = namespace_id;
+
+			CheckLineNumberTable (lines);
+			lnt = new LineNumberTable (file, lines);
+			file.NumLineNumbers += lines.Length;
+
+			int num_locals = locals != null ? locals.Length : 0;
+
+			if (num_locals <= 32) {
+				// Most of the time, the O(n^2) factor is actually
+				// less than the cost of allocating the hash table,
+				// 32 is a rough number obtained through some testing.
+
+				for (int i = 0; i < num_locals; i ++) {
+					string nm = locals [i].Name;
+
+					for (int j = i + 1; j < num_locals; j ++) {
+						if (locals [j].Name == nm) {
+							flags |= Flags.LocalNamesAmbiguous;
+							goto locals_check_done;
+						}
+					}
+				}
+			locals_check_done :
+				;
+			} else {
+				var local_names = new Dictionary<string, LocalVariableEntry> ();
+				foreach (LocalVariableEntry local in locals) {
+					if (local_names.ContainsKey (local.Name)) {
+						flags |= Flags.LocalNamesAmbiguous;
+						break;
+					}
+					local_names.Add (local.Name, local);
+				}
+			}
+		}
+
+		void CheckLineNumberTable (LineNumberEntry[] line_numbers)
+		{
+			int last_offset = -1;
+			int last_row = -1;
+
+			if (line_numbers == null)
+				return;
+
+			for (int i = 0; i < line_numbers.Length; i++) {
+				LineNumberEntry line = line_numbers [i];
+
+				if (line.Equals (LineNumberEntry.Null))
+					throw new MonoSymbolFileException ();
+
+				if (line.Offset < last_offset)
+					throw new MonoSymbolFileException ();
+
+				if (line.Offset > last_offset) {
+					last_row = line.Row;
+					last_offset = line.Offset;
+				} else if (line.Row > last_row) {
+					last_row = line.Row;
+				}
+			}
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			if ((index <= 0) || (DataOffset == 0))
+				throw new InvalidOperationException ();
+
+			bw.Write (Token);
+			bw.Write (DataOffset);
+			bw.Write (LineNumberTableOffset);
+		}
+
+		internal void WriteData (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			if (index <= 0)
+				throw new InvalidOperationException ();
+
+			LocalVariableTableOffset = (int) bw.BaseStream.Position;
+			int num_locals = locals != null ? locals.Length : 0;
+			bw.WriteLeb128 (num_locals);
+			for (int i = 0; i < num_locals; i++)
+				locals [i].Write (file, bw);
+			file.LocalCount += num_locals;
+
+			CodeBlockTableOffset = (int) bw.BaseStream.Position;
+			int num_code_blocks = code_blocks != null ? code_blocks.Length : 0;
+			bw.WriteLeb128 (num_code_blocks);
+			for (int i = 0; i < num_code_blocks; i++)
+				code_blocks [i].Write (bw);
+
+			ScopeVariableTableOffset = (int) bw.BaseStream.Position;
+			int num_scope_vars = scope_vars != null ? scope_vars.Length : 0;
+			bw.WriteLeb128 (num_scope_vars);
+			for (int i = 0; i < num_scope_vars; i++)
+				scope_vars [i].Write (bw);
+
+			if (real_name != null) {
+				RealNameOffset = (int) bw.BaseStream.Position;
+				bw.Write (real_name);
+			}
+
+			LineNumberTableOffset = (int) bw.BaseStream.Position;
+			lnt.Write (file, bw);
+
+			DataOffset = (int) bw.BaseStream.Position;
+
+			bw.WriteLeb128 (CompileUnitIndex);
+			bw.WriteLeb128 (LocalVariableTableOffset);
+			bw.WriteLeb128 (NamespaceID);
+
+			bw.WriteLeb128 (CodeBlockTableOffset);
+			bw.WriteLeb128 (ScopeVariableTableOffset);
+
+			bw.WriteLeb128 (RealNameOffset);
+			bw.WriteLeb128 ((int) flags);
+		}
+
+		public LineNumberTable GetLineNumberTable ()
+		{
+			lock (SymbolFile) {
+				if (lnt != null)
+					return lnt;
+
+				if (LineNumberTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = LineNumberTableOffset;
+
+				lnt = LineNumberTable.Read (SymbolFile, reader);
+
+				reader.BaseStream.Position = old_pos;
+				return lnt;
+			}
+		}
+
+		public LocalVariableEntry[] GetLocals ()
+		{
+			lock (SymbolFile) {
+				if (locals != null)
+					return locals;
+
+				if (LocalVariableTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = LocalVariableTableOffset;
+
+				int num_locals = reader.ReadLeb128 ();
+				locals = new LocalVariableEntry [num_locals];
+
+				for (int i = 0; i < num_locals; i++)
+					locals [i] = new LocalVariableEntry (SymbolFile, reader);
+
+				reader.BaseStream.Position = old_pos;
+				return locals;
+			}
+		}
+
+		public CodeBlockEntry[] GetCodeBlocks ()
+		{
+			lock (SymbolFile) {
+				if (code_blocks != null)
+					return code_blocks;
+
+				if (CodeBlockTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = CodeBlockTableOffset;
+
+				int num_code_blocks = reader.ReadLeb128 ();
+				code_blocks = new CodeBlockEntry [num_code_blocks];
+
+				for (int i = 0; i < num_code_blocks; i++)
+					code_blocks [i] = new CodeBlockEntry (i, reader);
+
+				reader.BaseStream.Position = old_pos;
+				return code_blocks;
+			}
+		}
+
+		public ScopeVariable[] GetScopeVariables ()
+		{
+			lock (SymbolFile) {
+				if (scope_vars != null)
+					return scope_vars;
+
+				if (ScopeVariableTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = ScopeVariableTableOffset;
+
+				int num_scope_vars = reader.ReadLeb128 ();
+				scope_vars = new ScopeVariable [num_scope_vars];
+
+				for (int i = 0; i < num_scope_vars; i++)
+					scope_vars [i] = new ScopeVariable (reader);
+
+				reader.BaseStream.Position = old_pos;
+				return scope_vars;
+			}
+		}
+
+		public string GetRealName ()
+		{
+			lock (SymbolFile) {
+				if (real_name != null)
+					return real_name;
+
+				if (RealNameOffset == 0)
+					return null;
+
+				real_name = SymbolFile.BinaryReader.ReadString (RealNameOffset);
+				return real_name;
+			}
+		}
+
+		public int CompareTo (object obj)
+		{
+			MethodEntry method = (MethodEntry) obj;
+
+			if (method.Token < Token)
+				return 1;
+			else if (method.Token > Token)
+				return -1;
+			else
+				return 0;
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[Method {0}:{1:x}:{2}:{3}]",
+					      index, Token, CompileUnitIndex, CompileUnit);
+		}
+	}
+
+	public struct NamespaceEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly string Name;
+		public readonly int Index;
+		public readonly int Parent;
+		public readonly string[] UsingClauses;
+		#endregion
+
+		public NamespaceEntry (string name, int index, string[] using_clauses, int parent)
+		{
+			this.Name = name;
+			this.Index = index;
+			this.Parent = parent;
+			this.UsingClauses = using_clauses != null ? using_clauses : new string [0];
+		}
+
+		internal NamespaceEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			Name = reader.ReadString ();
+			Index = reader.ReadLeb128 ();
+			Parent = reader.ReadLeb128 ();
+
+			int count = reader.ReadLeb128 ();
+			UsingClauses = new string [count];
+			for (int i = 0; i < count; i++)
+				UsingClauses [i] = reader.ReadString ();
+		}
+
+		internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			bw.Write (Name);
+			bw.WriteLeb128 (Index);
+			bw.WriteLeb128 (Parent);
+			bw.WriteLeb128 (UsingClauses.Length);
+			foreach (string uc in UsingClauses)
+				bw.Write (uc);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[Namespace {0}:{1}:{2}]", Name, Index, Parent);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs	(revision 11807)
@@ -0,0 +1,403 @@
+//
+// Mono.CSharp.Debugger/MonoSymbolWriter.cs
+//
+// Author:
+//   Martin Baulig (martin@ximian.com)
+//
+// This is the default implementation of the System.Diagnostics.SymbolStore.ISymbolWriter
+// interface.
+//
+// (C) 2002 Ximian, Inc.  http://www.ximian.com
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Collections.Generic;
+using System.IO;
+
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class MonoSymbolWriter
+	{
+		List<SourceMethodBuilder> methods;
+		List<SourceFileEntry> sources;
+		List<CompileUnitEntry> comp_units;
+		protected readonly MonoSymbolFile file;
+		string filename;
+
+		private SourceMethodBuilder current_method;
+#if NET_2_1
+		System.Collections.Stack current_method_stack = new System.Collections.Stack ();
+#else
+		Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder> ();
+#endif
+
+		public MonoSymbolWriter (string filename)
+		{
+			this.methods = new List<SourceMethodBuilder> ();
+			this.sources = new List<SourceFileEntry> ();
+			this.comp_units = new List<CompileUnitEntry> ();
+			this.file = new MonoSymbolFile ();
+
+			this.filename = filename + ".mdb";
+		}
+
+		public MonoSymbolFile SymbolFile {
+			get { return file; }
+		}
+
+		public void CloseNamespace ()
+		{ }
+
+		public void DefineLocalVariable (int index, string name)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.AddLocal (index, name);
+		}
+
+		public void DefineCapturedLocal (int scope_id, string name, string captured_name)
+		{
+			file.DefineCapturedVariable (scope_id, name, captured_name,
+						     CapturedVariable.CapturedKind.Local);
+		}
+
+		public void DefineCapturedParameter (int scope_id, string name, string captured_name)
+		{
+			file.DefineCapturedVariable (scope_id, name, captured_name,
+						     CapturedVariable.CapturedKind.Parameter);
+		}
+
+		public void DefineCapturedThis (int scope_id, string captured_name)
+		{
+			file.DefineCapturedVariable (scope_id, "this", captured_name,
+						     CapturedVariable.CapturedKind.This);
+		}
+
+		public void DefineCapturedScope (int scope_id, int id, string captured_name)
+		{
+			file.DefineCapturedScope (scope_id, id, captured_name);
+		}
+
+		public void DefineScopeVariable (int scope, int index)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.AddScopeVariable (scope, index);
+		}
+
+		public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column,
+					       bool is_hidden)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.MarkSequencePoint (offset, file, line, column, is_hidden);
+		}
+
+		public SourceMethodBuilder OpenMethod (ICompileUnit file, int ns_id, IMethodDef method)
+		{
+			SourceMethodBuilder builder = new SourceMethodBuilder (file, ns_id, method);
+			current_method_stack.Push (current_method);
+			current_method = builder;
+			methods.Add (current_method);
+			return builder;
+		}
+
+		public void CloseMethod ()
+		{
+			current_method = (SourceMethodBuilder) current_method_stack.Pop ();
+		}
+
+		public SourceFileEntry DefineDocument (string url)
+		{
+			SourceFileEntry entry = new SourceFileEntry (file, url);
+			sources.Add (entry);
+			return entry;
+		}
+
+		public SourceFileEntry DefineDocument (string url, byte[] guid, byte[] checksum)
+		{
+			SourceFileEntry entry = new SourceFileEntry (file, url, guid, checksum);
+			sources.Add (entry);
+			return entry;
+		}
+
+		public CompileUnitEntry DefineCompilationUnit (SourceFileEntry source)
+		{
+			CompileUnitEntry entry = new CompileUnitEntry (file, source);
+			comp_units.Add (entry);
+			return entry;
+		}
+
+		public int DefineNamespace (string name, CompileUnitEntry unit,
+					    string[] using_clauses, int parent)
+		{
+			if ((unit == null) || (using_clauses == null))
+				throw new NullReferenceException ();
+
+			return unit.DefineNamespace (name, using_clauses, parent);
+		}
+
+		public int OpenScope (int start_offset)
+		{
+			if (current_method == null)
+				return 0;
+
+			current_method.StartBlock (CodeBlockEntry.Type.Lexical, start_offset);
+			return 0;
+		}
+
+		public void CloseScope (int end_offset)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.EndBlock (end_offset);
+		}
+
+		public void OpenCompilerGeneratedBlock (int start_offset)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.StartBlock (CodeBlockEntry.Type.CompilerGenerated,
+						   start_offset);
+		}
+
+		public void CloseCompilerGeneratedBlock (int end_offset)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.EndBlock (end_offset);
+		}
+
+		public void StartIteratorBody (int start_offset)
+		{
+			current_method.StartBlock (CodeBlockEntry.Type.IteratorBody,
+						   start_offset);
+		}
+
+		public void EndIteratorBody (int end_offset)
+		{
+			current_method.EndBlock (end_offset);
+		}
+
+		public void StartIteratorDispatcher (int start_offset)
+		{
+			current_method.StartBlock (CodeBlockEntry.Type.IteratorDispatcher,
+						   start_offset);
+		}
+
+		public void EndIteratorDispatcher (int end_offset)
+		{
+			current_method.EndBlock (end_offset);
+		}
+
+		public void DefineAnonymousScope (int id)
+		{
+			file.DefineAnonymousScope (id);
+		}
+
+		public void WriteSymbolFile (Guid guid)
+		{
+			foreach (SourceMethodBuilder method in methods)
+				method.DefineMethod (file);
+
+			try {
+				// We mmap the file, so unlink the previous version since it may be in use
+				File.Delete (filename);
+			} catch {
+				// We can safely ignore
+			}
+			using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
+				file.CreateSymbolFile (guid, fs);
+			}
+		}
+	}
+
+	public class SourceMethodBuilder
+	{
+		List<LocalVariableEntry> _locals;
+		List<CodeBlockEntry> _blocks;
+		List<ScopeVariable> _scope_vars;
+#if NET_2_1
+		System.Collections.Stack _block_stack;
+#else
+		Stack<CodeBlockEntry> _block_stack;
+#endif
+		string _real_name;
+		IMethodDef _method;
+		ICompileUnit _comp_unit;
+//		MethodEntry.Flags _method_flags;
+		int _ns_id;
+
+		public SourceMethodBuilder (ICompileUnit comp_unit, int ns_id, IMethodDef method)
+		{
+			this._comp_unit = comp_unit;
+			this._method = method;
+			this._ns_id = ns_id;
+
+			method_lines = new LineNumberEntry [32];
+		}
+
+		private LineNumberEntry [] method_lines;
+		private int method_lines_pos = 0;
+
+		public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column,
+					       bool is_hidden)
+		{
+			if (method_lines_pos == method_lines.Length) {
+				LineNumberEntry [] tmp = method_lines;
+				method_lines = new LineNumberEntry [method_lines.Length * 2];
+				Array.Copy (tmp, method_lines, method_lines_pos);
+			}
+
+			int file_idx = file != null ? file.Index : 0;
+			method_lines [method_lines_pos++] = new LineNumberEntry (
+				file_idx, line, offset, is_hidden);
+		}
+
+		public void StartBlock (CodeBlockEntry.Type type, int start_offset)
+		{
+			if (_block_stack == null) {
+#if NET_2_1
+				_block_stack = new System.Collections.Stack ();
+#else
+				_block_stack = new Stack<CodeBlockEntry> ();
+#endif
+			}
+
+			if (_blocks == null)
+				_blocks = new List<CodeBlockEntry> ();
+
+			int parent = CurrentBlock != null ? CurrentBlock.Index : -1;
+
+			CodeBlockEntry block = new CodeBlockEntry (
+				_blocks.Count + 1, parent, type, start_offset);
+
+			_block_stack.Push (block);
+			_blocks.Add (block);
+		}
+
+		public void EndBlock (int end_offset)
+		{
+			CodeBlockEntry block = (CodeBlockEntry) _block_stack.Pop ();
+			block.Close (end_offset);
+		}
+
+		public CodeBlockEntry[] Blocks {
+			get {
+				if (_blocks == null)
+					return new CodeBlockEntry [0];
+
+				CodeBlockEntry[] retval = new CodeBlockEntry [_blocks.Count];
+				_blocks.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		public CodeBlockEntry CurrentBlock {
+			get {
+				if ((_block_stack != null) && (_block_stack.Count > 0))
+					return (CodeBlockEntry) _block_stack.Peek ();
+				else
+					return null;
+			}
+		}
+
+		public LocalVariableEntry[] Locals {
+			get {
+				if (_locals == null)
+					return new LocalVariableEntry [0];
+				else {
+					LocalVariableEntry[] retval =
+						new LocalVariableEntry [_locals.Count];
+					_locals.CopyTo (retval, 0);
+					return retval;
+				}
+			}
+		}
+
+		public void AddLocal (int index, string name)
+		{
+			if (_locals == null)
+				_locals = new List<LocalVariableEntry> ();
+			int block_idx = CurrentBlock != null ? CurrentBlock.Index : 0;
+			_locals.Add (new LocalVariableEntry (index, name, block_idx));
+		}
+
+		public ScopeVariable[] ScopeVariables {
+			get {
+				if (_scope_vars == null)
+					return new ScopeVariable [0];
+
+				ScopeVariable[] retval = new ScopeVariable [_scope_vars.Count];
+				_scope_vars.CopyTo (retval);
+				return retval;
+			}
+		}
+
+		public void AddScopeVariable (int scope, int index)
+		{
+			if (_scope_vars == null)
+				_scope_vars = new List<ScopeVariable> ();
+			_scope_vars.Add (
+				new ScopeVariable (scope, index));
+		}
+
+		public string RealMethodName {
+			get { return _real_name; }
+		}
+
+		public void SetRealMethodName (string name)
+		{
+			_real_name = name;
+		}
+
+		public ICompileUnit SourceFile {
+			get { return _comp_unit; }
+		}
+
+		public IMethodDef Method {
+			get { return _method; }
+		}
+
+		public void DefineMethod (MonoSymbolFile file)
+		{
+			LineNumberEntry[] lines = new LineNumberEntry [method_lines_pos];
+			Array.Copy (method_lines, lines, method_lines_pos);
+
+			MethodEntry entry = new MethodEntry (
+				file, _comp_unit.Entry, _method.Token, ScopeVariables,
+				Locals, lines, Blocks, RealMethodName, 0, //_method_flags,
+				_ns_id);
+
+			file.AddMethod (entry);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Mdb/Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs	(revision 11807)
@@ -0,0 +1,349 @@
+//
+// SymbolWriterImpl.cs
+//
+// Author:
+//   Lluis Sanchez Gual (lluis@novell.com)
+//
+// (C) 2005 Novell, Inc.  http://www.novell.com
+//
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+
+using System;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
+using System.Collections;
+using System.IO;
+using System.Diagnostics.SymbolStore;
+
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class SymbolWriterImpl: ISymbolWriter
+	{
+		MonoSymbolWriter msw;
+
+		int nextLocalIndex;
+		int currentToken;
+		string methodName;
+		Stack namespaceStack = new Stack ();
+		bool methodOpened;
+
+		Hashtable documents = new Hashtable ();
+
+#if !CECIL
+		ModuleBuilder mb;
+		delegate Guid GetGuidFunc (ModuleBuilder mb);
+		GetGuidFunc get_guid_func;
+
+		public SymbolWriterImpl (ModuleBuilder mb)
+		{
+			this.mb = mb;
+		}
+
+		public void Close ()
+		{
+			MethodInfo mi = typeof (ModuleBuilder).GetMethod (
+				"Mono_GetGuid",
+				BindingFlags.Static | BindingFlags.NonPublic);
+			if (mi == null)
+				return;
+
+			get_guid_func = (GetGuidFunc) System.Delegate.CreateDelegate (
+				typeof (GetGuidFunc), mi);
+
+			msw.WriteSymbolFile (get_guid_func (mb));
+		}
+#else
+		Guid guid;
+
+		public SymbolWriterImpl (Guid guid)
+		{
+			this.guid = guid;
+		}
+
+		public void Close ()
+		{
+			msw.WriteSymbolFile (guid);
+		}
+#endif
+
+		public void CloseMethod ()
+		{
+			if (methodOpened) {
+				methodOpened = false;
+				nextLocalIndex = 0;
+				msw.CloseMethod ();
+			}
+		}
+
+		public void CloseNamespace ()
+		{
+			namespaceStack.Pop ();
+			msw.CloseNamespace ();
+		}
+
+		public void CloseScope (int endOffset)
+		{
+			msw.CloseScope (endOffset);
+		}
+
+		public ISymbolDocumentWriter DefineDocument (
+			string url,
+			Guid language,
+			Guid languageVendor,
+			Guid documentType)
+		{
+			SymbolDocumentWriterImpl doc = (SymbolDocumentWriterImpl) documents [url];
+			if (doc == null) {
+				SourceFileEntry entry = msw.DefineDocument (url);
+				CompileUnitEntry comp_unit = msw.DefineCompilationUnit (entry);
+				doc = new SymbolDocumentWriterImpl (comp_unit);
+				documents [url] = doc;
+			}
+			return doc;
+		}
+
+		public void DefineField (
+			SymbolToken parent,
+			string name,
+			FieldAttributes attributes,
+			byte[] signature,
+			SymAddressKind addrKind,
+			int addr1,
+			int addr2,
+			int addr3)
+		{
+		}
+
+		public void DefineGlobalVariable (
+			string name,
+			FieldAttributes attributes,
+			byte[] signature,
+			SymAddressKind addrKind,
+			int addr1,
+			int addr2,
+			int addr3)
+		{
+		}
+
+		public void DefineLocalVariable (
+			string name,
+			FieldAttributes attributes,
+			byte[] signature,
+			SymAddressKind addrKind,
+			int addr1,
+			int addr2,
+			int addr3,
+			int startOffset,
+			int endOffset)
+		{
+			msw.DefineLocalVariable (nextLocalIndex++, name);
+		}
+
+		public void DefineParameter (
+			string name,
+			ParameterAttributes attributes,
+			int sequence,
+			SymAddressKind addrKind,
+			int addr1,
+			int addr2,
+			int addr3)
+		{
+		}
+
+		public void DefineSequencePoints (
+			ISymbolDocumentWriter document,
+			int[] offsets,
+			int[] lines,
+			int[] columns,
+			int[] endLines,
+			int[] endColumns)
+		{
+			SymbolDocumentWriterImpl doc = (SymbolDocumentWriterImpl) document;
+			SourceFileEntry file = doc != null ? doc.Entry.SourceFile : null;
+
+			for (int n=0; n<offsets.Length; n++) {
+				if (n > 0 && offsets[n] == offsets[n-1] && lines[n] == lines[n-1] && columns[n] == columns[n-1])
+					continue;
+				msw.MarkSequencePoint (offsets[n], file, lines[n], columns[n], false);
+			}
+		}
+
+		public void Initialize (IntPtr emitter, string filename, bool fFullBuild)
+		{
+			msw = new MonoSymbolWriter (filename);
+		}
+
+		public void OpenMethod (SymbolToken method)
+		{
+			currentToken = method.GetToken ();
+		}
+
+		public void OpenNamespace (string name)
+		{
+			NamespaceInfo n = new NamespaceInfo ();
+			n.NamespaceID = -1;
+			n.Name = name;
+			namespaceStack.Push (n);
+		}
+
+		public int OpenScope (int startOffset)
+		{
+			return msw.OpenScope (startOffset);
+		}
+
+		public void SetMethodSourceRange (
+			ISymbolDocumentWriter startDoc,
+			int startLine,
+			int startColumn,
+			ISymbolDocumentWriter endDoc,
+			int endLine,
+			int endColumn)
+		{
+			int nsId = GetCurrentNamespace (startDoc);
+			SourceMethodImpl sm = new SourceMethodImpl (methodName, currentToken, nsId);
+			msw.OpenMethod (((ICompileUnit)startDoc).Entry, nsId, sm);
+			methodOpened = true;
+		}
+
+		public void SetScopeRange (int scopeID, int startOffset, int endOffset)
+		{
+		}
+
+		public void SetSymAttribute (SymbolToken parent, string name, byte[] data)
+		{
+			// This is a hack! but MonoSymbolWriter needs the method name
+			// and ISymbolWriter does not have any method for providing it
+			if (name == "__name")
+				methodName = System.Text.Encoding.UTF8.GetString (data);
+		}
+
+		public void SetUnderlyingWriter (IntPtr underlyingWriter)
+		{
+		}
+
+		public void SetUserEntryPoint (SymbolToken entryMethod)
+		{
+		}
+
+		public void UsingNamespace (string fullName)
+		{
+			if (namespaceStack.Count == 0) {
+				OpenNamespace ("");
+			}
+
+			NamespaceInfo ni = (NamespaceInfo) namespaceStack.Peek ();
+			if (ni.NamespaceID != -1) {
+				NamespaceInfo old = ni;
+				CloseNamespace ();
+				OpenNamespace (old.Name);
+				ni = (NamespaceInfo) namespaceStack.Peek ();
+				ni.UsingClauses = old.UsingClauses;
+			}
+			ni.UsingClauses.Add (fullName);
+		}
+
+		int GetCurrentNamespace (ISymbolDocumentWriter doc)
+		{
+			if (namespaceStack.Count == 0) {
+				OpenNamespace ("");
+			}
+
+			NamespaceInfo ni = (NamespaceInfo) namespaceStack.Peek ();
+			if (ni.NamespaceID == -1)
+			{
+				string[] usings = (string[]) ni.UsingClauses.ToArray (typeof(string));
+
+				int parentId = 0;
+				if (namespaceStack.Count > 1) {
+					namespaceStack.Pop ();
+					parentId = ((NamespaceInfo) namespaceStack.Peek ()).NamespaceID;
+					namespaceStack.Push (ni);
+				}
+
+				ni.NamespaceID = msw.DefineNamespace (ni.Name, ((ICompileUnit)doc).Entry, usings, parentId);
+			}
+			return ni.NamespaceID;
+		}
+
+	}
+
+	class SymbolDocumentWriterImpl: ISymbolDocumentWriter, ISourceFile, ICompileUnit
+	{
+		CompileUnitEntry comp_unit;
+
+		public SymbolDocumentWriterImpl (CompileUnitEntry comp_unit)
+		{
+			this.comp_unit = comp_unit;
+		}
+
+		public void SetCheckSum (Guid algorithmId, byte[] checkSum)
+		{
+		}
+
+		public void SetSource (byte[] source)
+		{
+		}
+
+		SourceFileEntry ISourceFile.Entry {
+			get { return comp_unit.SourceFile; }
+		}
+
+		public CompileUnitEntry Entry {
+			get { return comp_unit; }
+		}
+	}
+
+	class SourceMethodImpl: IMethodDef
+	{
+		string name;
+		int token;
+		int namespaceID;
+
+		public SourceMethodImpl (string name, int token, int namespaceID)
+		{
+			this.name = name;
+			this.token = token;
+			this.namespaceID = namespaceID;
+		}
+
+		public string Name {
+			get { return name; }
+		}
+
+		public int NamespaceID {
+			get { return namespaceID; }
+		}
+
+		public int Token {
+			get { return token; }
+		}
+	}
+
+	class NamespaceInfo
+	{
+		public string Name;
+		public int NamespaceID;
+		public ArrayList UsingClauses = new ArrayList ();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/BitAccess.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/BitAccess.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/BitAccess.cs	(revision 11807)
@@ -0,0 +1,229 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+using System.Text;
+
+namespace Microsoft.Cci.Pdb {
+  internal class BitAccess {
+
+    internal BitAccess(int capacity) {
+      this.buffer = new byte[capacity];
+      this.offset = 0;
+    }
+
+    internal byte[] Buffer {
+      get { return buffer; }
+    }
+    private byte[] buffer;
+
+    internal void FillBuffer(Stream stream, int capacity) {
+      MinCapacity(capacity);
+      stream.Read(buffer, 0, capacity);
+      offset = 0;
+    }
+
+    internal int Position {
+      get { return offset; }
+      set { offset = value; }
+    }
+    private int offset;
+
+    internal void WriteBuffer(Stream stream, int count) {
+      stream.Write(buffer, 0, count);
+    }
+
+    internal void MinCapacity(int capacity) {
+      if (buffer.Length < capacity) {
+        buffer = new byte[capacity];
+      }
+      offset = 0;
+    }
+
+    internal void Align(int alignment) {
+      while ((offset % alignment) != 0) {
+        offset++;
+      }
+    }
+
+    internal void WriteInt32(int value) {
+      buffer[offset + 0] = (byte)value;
+      buffer[offset + 1] = (byte)(value >> 8);
+      buffer[offset + 2] = (byte)(value >> 16);
+      buffer[offset + 3] = (byte)(value >> 24);
+      offset += 4;
+    }
+
+    internal void WriteInt32(int[] values) {
+      for (int i = 0; i < values.Length; i++) {
+        WriteInt32(values[i]);
+      }
+    }
+
+    internal void WriteBytes(byte[] bytes) {
+      for (int i = 0; i < bytes.Length; i++) {
+        buffer[offset++] = bytes[i];
+      }
+    }
+
+    internal void ReadInt16(out short value) {
+      value = (short)((buffer[offset + 0] & 0xFF) |
+                            (buffer[offset + 1] << 8));
+      offset += 2;
+    }
+
+    internal void ReadInt32(out int value) {
+      value = (int)((buffer[offset + 0] & 0xFF) |
+                          (buffer[offset + 1] << 8) |
+                          (buffer[offset + 2] << 16) |
+                          (buffer[offset + 3] << 24));
+      offset += 4;
+    }
+
+    internal void ReadInt64(out long value) {
+      value = (long)((buffer[offset + 0] & 0xFF) |
+                           (buffer[offset + 1] << 8) |
+                           (buffer[offset + 2] << 16) |
+                           (buffer[offset + 3] << 24) |
+                           (buffer[offset + 4] << 32) |
+                           (buffer[offset + 5] << 40) |
+                           (buffer[offset + 6] << 48) |
+                           (buffer[offset + 7] << 56));
+      offset += 8;
+    }
+
+    internal void ReadUInt16(out ushort value) {
+      value = (ushort)((buffer[offset + 0] & 0xFF) |
+                             (buffer[offset + 1] << 8));
+      offset += 2;
+    }
+
+    internal void ReadUInt8(out byte value) {
+      value = (byte)((buffer[offset + 0] & 0xFF));
+      offset += 1;
+    }
+
+    internal void ReadUInt32(out uint value) {
+      value = (uint)((buffer[offset + 0] & 0xFF) |
+                           (buffer[offset + 1] << 8) |
+                           (buffer[offset + 2] << 16) |
+                           (buffer[offset + 3] << 24));
+      offset += 4;
+    }
+
+    internal void ReadUInt64(out ulong value) {
+      value = (ulong)((buffer[offset + 0] & 0xFF) |
+                           (buffer[offset + 1] << 8) |
+                           (buffer[offset + 2] << 16) |
+                           (buffer[offset + 3] << 24) |
+                           (buffer[offset + 4] << 32) |
+                           (buffer[offset + 5] << 40) |
+                           (buffer[offset + 6] << 48) |
+                           (buffer[offset + 7] << 56));
+      offset += 8;
+    }
+
+    internal void ReadInt32(int[] values) {
+      for (int i = 0; i < values.Length; i++) {
+        ReadInt32(out values[i]);
+      }
+    }
+
+    internal void ReadUInt32(uint[] values) {
+      for (int i = 0; i < values.Length; i++) {
+        ReadUInt32(out values[i]);
+      }
+    }
+
+    internal void ReadBytes(byte[] bytes) {
+      for (int i = 0; i < bytes.Length; i++) {
+        bytes[i] = buffer[offset++];
+      }
+    }
+
+    internal float ReadFloat() {
+      float result = BitConverter.ToSingle(buffer, offset);
+      offset += 4;
+      return result;
+    }
+
+    internal double ReadDouble() {
+      double result = BitConverter.ToDouble(buffer, offset);
+      offset += 8;
+      return result;
+    }
+
+    internal decimal ReadDecimal() {
+      int[] bits = new int[4];
+      this.ReadInt32(bits);
+      return new decimal(bits);
+    }
+
+    internal void ReadBString(out string value) {
+      ushort len;
+      this.ReadUInt16(out len);
+      value = Encoding.UTF8.GetString(buffer, offset, len);
+      offset += len;
+    }
+
+    internal void ReadCString(out string value) {
+      int len = 0;
+      while (offset + len < buffer.Length && buffer[offset + len] != 0) {
+        len++;
+      }
+      value = Encoding.UTF8.GetString(buffer, offset, len);
+      offset += len + 1;
+    }
+
+    internal void SkipCString(out string value) {
+      int len = 0;
+      while (offset + len < buffer.Length && buffer[offset + len] != 0) {
+        len++;
+      }
+      offset += len + 1;
+      value= null;
+    }
+
+    internal void ReadGuid(out Guid guid) {
+      uint a;
+      ushort b;
+      ushort c;
+      byte d;
+      byte e;
+      byte f;
+      byte g;
+      byte h;
+      byte i;
+      byte j;
+      byte k;
+
+      ReadUInt32(out a);
+      ReadUInt16(out b);
+      ReadUInt16(out c);
+      ReadUInt8(out d);
+      ReadUInt8(out e);
+      ReadUInt8(out f);
+      ReadUInt8(out g);
+      ReadUInt8(out h);
+      ReadUInt8(out i);
+      ReadUInt8(out j);
+      ReadUInt8(out k);
+
+      guid = new Guid(a, b, c, d, e, f, g, h, i, j, k);
+    }
+
+    internal string ReadString() {
+      int len = 0;
+      while (offset + len < buffer.Length && buffer[offset + len] != 0) {
+        len+=2;
+      }
+      string result = Encoding.Unicode.GetString(buffer, offset, len);
+      offset += len + 2;
+      return result;
+    }
+
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/BitSet.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/BitSet.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/BitSet.cs	(revision 11807)
@@ -0,0 +1,69 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal struct BitSet {
+    internal BitSet(BitAccess bits) {
+      bits.ReadInt32(out size);    // 0..3 : Number of words
+      words = new uint[size];
+      bits.ReadUInt32(words);
+    }
+
+    internal BitSet(int size) {
+      this.size = size;
+      words = new uint[size];
+    }
+
+    internal bool IsSet(int index) {
+      int word = index / 32;
+      if (word >= this.size) return false;
+      return ((words[word] & GetBit(index)) != 0);
+    }
+
+    internal void Set(int index) {
+      int word = index / 32;
+      if (word >= this.size) return;
+      words[word] |= GetBit(index);
+    }
+
+    internal void Clear(int index) {
+      int word = index / 32;
+      if (word >= this.size) return;
+      words[word] &= ~GetBit(index);
+    }
+
+    private uint GetBit(int index) {
+      return ((uint)1 << (index % 32));
+    }
+
+    private uint ReverseBits(uint value) {
+      uint o = 0;
+      for (int i = 0; i < 32; i++) {
+        o = (o << 1) | (value & 1);
+        value >>= 1;
+      }
+      return o;
+    }
+
+    internal bool IsEmpty {
+      get { return size == 0; }
+    }
+
+    internal bool GetWord(int index, out uint word) {
+      if (index < size) {
+        word = ReverseBits(words[index]);
+        return true;
+      }
+      word = 0;
+      return false;
+    }
+
+    private int size;
+    private uint[] words;
+  }
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/CvInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/CvInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/CvInfo.cs	(revision 11807)
@@ -0,0 +1,2430 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+//
+//  File:   CvInfo.cs
+//
+//  Generic CodeView information definitions
+//
+//  Structures, constants, etc. for accessing and interpreting
+//  CodeView information.
+//
+//  The master copy of this file resides in the langapi project (in C++).
+//  All Microsoft projects are required to use the master copy without
+//  modification.  Modification of the master version or a copy
+//  without consultation with all parties concerned is extremely
+//  risky.
+//
+//  When this file is modified, the corresponding documentation file
+//  omfdeb.doc in the langapi project must be updated.
+//
+//  This is a read-only copy of the C++ file converted to C#.
+//
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal struct FLOAT10 {
+    internal byte Data_0;
+    internal byte Data_1;
+    internal byte Data_2;
+    internal byte Data_3;
+    internal byte Data_4;
+    internal byte Data_5;
+    internal byte Data_6;
+    internal byte Data_7;
+    internal byte Data_8;
+    internal byte Data_9;
+  };
+
+  internal enum CV_SIGNATURE {
+    C6=0,    // Actual signature is >64K
+    C7=1,    // First explicit signature
+    C11=2,    // C11 (vc5.x) 32-bit types
+    C13=4,    // C13 (vc7.x) zero terminated names
+    RESERVERD=5,    // All signatures from 5 to 64K are reserved
+  };
+
+  //  CodeView Symbol and Type OMF type information is broken up into two
+  //  ranges.  Type indices less than 0x1000 describe type information
+  //  that is frequently used.  Type indices above 0x1000 are used to
+  //  describe more complex features such as functions, arrays and
+  //  structures.
+  //
+
+  //  Primitive types have predefined meaning that is encoded in the
+  //  values of the various bit fields in the value.
+  //
+  //  A CodeView primitive type is defined as:
+  //
+  //  1 1
+  //  1 089  7654  3  210
+  //  r mode type  r  sub
+  //
+  //  Where
+  //      mode is the pointer mode
+  //      type is a type indicator
+  //      sub  is a subtype enumeration
+  //      r    is a reserved field
+  //
+  //  See Microsoft Symbol and Type OMF (Version 4.0) for more
+  //  information.
+  //
+
+  //  pointer mode enumeration values
+
+  internal enum CV_prmode {
+    CV_TM_DIRECT=0,        // mode is not a pointer
+    CV_TM_NPTR32=4,        // mode is a 32 bit near pointer
+    CV_TM_NPTR64=6,        // mode is a 64 bit near pointer
+    CV_TM_NPTR128=7,        // mode is a 128 bit near pointer
+  };
+
+  //  type enumeration values
+
+  internal enum CV_type {
+    CV_SPECIAL=0x00,     // special type size values
+    CV_SIGNED=0x01,     // signed integral size values
+    CV_UNSIGNED=0x02,     // unsigned integral size values
+    CV_BOOLEAN=0x03,     // Boolean size values
+    CV_REAL=0x04,     // real number size values
+    CV_COMPLEX=0x05,     // complex number size values
+    CV_SPECIAL2=0x06,     // second set of special types
+    CV_INT=0x07,     // integral (int) values
+    CV_CVRESERVED=0x0f,
+  };
+
+  //  subtype enumeration values for CV_SPECIAL
+
+  internal enum CV_special {
+    CV_SP_NOTYPE=0x00,
+    CV_SP_ABS=0x01,
+    CV_SP_SEGMENT=0x02,
+    CV_SP_VOID=0x03,
+    CV_SP_CURRENCY=0x04,
+    CV_SP_NBASICSTR=0x05,
+    CV_SP_FBASICSTR=0x06,
+    CV_SP_NOTTRANS=0x07,
+    CV_SP_HRESULT=0x08,
+  };
+
+  //  subtype enumeration values for CV_SPECIAL2
+
+  internal enum CV_special2 {
+    CV_S2_BIT=0x00,
+    CV_S2_PASCHAR=0x01,     // Pascal CHAR
+  };
+
+  //  subtype enumeration values for CV_SIGNED, CV_UNSIGNED and CV_BOOLEAN
+
+  internal enum CV_integral {
+    CV_IN_1BYTE=0x00,
+    CV_IN_2BYTE=0x01,
+    CV_IN_4BYTE=0x02,
+    CV_IN_8BYTE=0x03,
+    CV_IN_16BYTE=0x04,
+  };
+
+  //  subtype enumeration values for CV_REAL and CV_COMPLEX
+
+  internal enum CV_real {
+    CV_RC_REAL32=0x00,
+    CV_RC_REAL64=0x01,
+    CV_RC_REAL80=0x02,
+    CV_RC_REAL128=0x03,
+  };
+
+  //  subtype enumeration values for CV_INT (really int)
+
+  internal enum CV_int {
+    CV_RI_CHAR=0x00,
+    CV_RI_INT1=0x00,
+    CV_RI_WCHAR=0x01,
+    CV_RI_UINT1=0x01,
+    CV_RI_INT2=0x02,
+    CV_RI_UINT2=0x03,
+    CV_RI_INT4=0x04,
+    CV_RI_UINT4=0x05,
+    CV_RI_INT8=0x06,
+    CV_RI_UINT8=0x07,
+    CV_RI_INT16=0x08,
+    CV_RI_UINT16=0x09,
+  };
+
+  internal struct CV_PRIMITIVE_TYPE {
+    const uint CV_MMASK     = 0x700;       // mode mask
+    const uint CV_TMASK     = 0x0f0;       // type mask
+    const uint CV_SMASK     = 0x00f;       // subtype mask
+
+    const int CV_MSHIFT     = 8;           // primitive mode right shift count
+    const int CV_TSHIFT     = 4;           // primitive type right shift count
+    const int CV_SSHIFT     = 0;           // primitive subtype right shift count
+
+    // function to extract primitive mode, type and size
+
+    internal static CV_prmode CV_MODE(TYPE_ENUM typ) {
+      return (CV_prmode)((((uint)typ) & CV_MMASK) >> CV_MSHIFT);
+    }
+
+    internal static CV_type CV_TYPE(TYPE_ENUM typ) {
+      return (CV_type)((((uint)typ) & CV_TMASK) >> CV_TSHIFT);
+    }
+
+    internal static uint CV_SUBT(TYPE_ENUM typ) {
+      return ((((uint)typ) & CV_SMASK) >> CV_SSHIFT);
+    }
+
+    // functions to check the type of a primitive
+
+    internal static bool CV_TYP_IS_DIRECT(TYPE_ENUM typ) {
+      return (CV_MODE(typ) == CV_prmode.CV_TM_DIRECT);
+    }
+
+    internal static bool CV_TYP_IS_PTR(TYPE_ENUM typ) {
+      return (CV_MODE(typ) != CV_prmode.CV_TM_DIRECT);
+    }
+
+    internal static bool CV_TYP_IS_SIGNED(TYPE_ENUM typ) {
+      return
+          (((CV_TYPE(typ) == CV_type.CV_SIGNED) && CV_TYP_IS_DIRECT(typ)) ||
+                 (typ == TYPE_ENUM.T_INT1)  ||
+                 (typ == TYPE_ENUM.T_INT2)  ||
+                 (typ == TYPE_ENUM.T_INT4)  ||
+                 (typ == TYPE_ENUM.T_INT8)  ||
+                 (typ == TYPE_ENUM.T_INT16) ||
+                 (typ == TYPE_ENUM.T_RCHAR));
+    }
+
+    internal static bool CV_TYP_IS_UNSIGNED(TYPE_ENUM typ) {
+      return (((CV_TYPE(typ) == CV_type.CV_UNSIGNED) && CV_TYP_IS_DIRECT(typ)) ||
+                    (typ == TYPE_ENUM.T_UINT1) ||
+                    (typ == TYPE_ENUM.T_UINT2) ||
+                    (typ == TYPE_ENUM.T_UINT4) ||
+                    (typ == TYPE_ENUM.T_UINT8) ||
+                    (typ == TYPE_ENUM.T_UINT16));
+    }
+
+    internal static bool CV_TYP_IS_REAL(TYPE_ENUM typ) {
+      return ((CV_TYPE(typ) == CV_type.CV_REAL)  && CV_TYP_IS_DIRECT(typ));
+    }
+
+    const uint CV_FIRST_NONPRIM = 0x1000;
+
+    internal static bool CV_IS_PRIMITIVE(TYPE_ENUM typ) {
+      return ((uint)(typ) < CV_FIRST_NONPRIM);
+    }
+
+    internal static bool CV_TYP_IS_COMPLEX(TYPE_ENUM typ) {
+      return ((CV_TYPE(typ) == CV_type.CV_COMPLEX) && CV_TYP_IS_DIRECT(typ));
+    }
+
+    internal static bool CV_IS_INTERNAL_PTR(TYPE_ENUM typ) {
+      return (CV_IS_PRIMITIVE(typ) &&
+                    CV_TYPE(typ) == CV_type.CV_CVRESERVED &&
+                    CV_TYP_IS_PTR(typ));
+    }
+  }
+
+  // selected values for type_index - for a more complete definition, see
+  // Microsoft Symbol and Type OMF document
+
+  //  Special Types
+
+  internal enum TYPE_ENUM {
+    //  Special Types
+
+    T_NOTYPE=0x0000,   // uncharacterized type (no type)
+    T_ABS=0x0001,   // absolute symbol
+    T_SEGMENT=0x0002,   // segment type
+    T_VOID=0x0003,   // void
+    T_HRESULT=0x0008,   // OLE/COM HRESULT
+    T_32PHRESULT=0x0408,   // OLE/COM HRESULT __ptr32//
+    T_64PHRESULT=0x0608,   // OLE/COM HRESULT __ptr64//
+    T_PVOID=0x0103,   // near pointer to void
+    T_PFVOID=0x0203,   // far pointer to void
+    T_PHVOID=0x0303,   // huge pointer to void
+    T_32PVOID=0x0403,   // 32 bit pointer to void
+    T_64PVOID=0x0603,   // 64 bit pointer to void
+    T_CURRENCY=0x0004,   // BASIC 8 byte currency value
+    T_NOTTRANS=0x0007,   // type not translated by cvpack
+    T_BIT=0x0060,   // bit
+    T_PASCHAR=0x0061,   // Pascal CHAR
+
+    //  Character types
+
+    T_CHAR=0x0010,   // 8 bit signed
+    T_32PCHAR=0x0410,   // 32 bit pointer to 8 bit signed
+    T_64PCHAR=0x0610,   // 64 bit pointer to 8 bit signed
+
+    T_UCHAR=0x0020,   // 8 bit unsigned
+    T_32PUCHAR=0x0420,   // 32 bit pointer to 8 bit unsigned
+    T_64PUCHAR=0x0620,   // 64 bit pointer to 8 bit unsigned
+
+    //  really a character types
+
+    T_RCHAR=0x0070,   // really a char
+    T_32PRCHAR=0x0470,   // 32 bit pointer to a real char
+    T_64PRCHAR=0x0670,   // 64 bit pointer to a real char
+
+    //  really a wide character types
+
+    T_WCHAR=0x0071,   // wide char
+    T_32PWCHAR=0x0471,   // 32 bit pointer to a wide char
+    T_64PWCHAR=0x0671,   // 64 bit pointer to a wide char
+
+    //  8 bit int types
+
+    T_INT1=0x0068,   // 8 bit signed int
+    T_32PINT1=0x0468,   // 32 bit pointer to 8 bit signed int
+    T_64PINT1=0x0668,   // 64 bit pointer to 8 bit signed int
+
+    T_UINT1=0x0069,   // 8 bit unsigned int
+    T_32PUINT1=0x0469,   // 32 bit pointer to 8 bit unsigned int
+    T_64PUINT1=0x0669,   // 64 bit pointer to 8 bit unsigned int
+
+    //  16 bit short types
+
+    T_SHORT=0x0011,   // 16 bit signed
+    T_32PSHORT=0x0411,   // 32 bit pointer to 16 bit signed
+    T_64PSHORT=0x0611,   // 64 bit pointer to 16 bit signed
+
+    T_USHORT=0x0021,   // 16 bit unsigned
+    T_32PUSHORT=0x0421,   // 32 bit pointer to 16 bit unsigned
+    T_64PUSHORT=0x0621,   // 64 bit pointer to 16 bit unsigned
+
+    //  16 bit int types
+
+    T_INT2=0x0072,   // 16 bit signed int
+    T_32PINT2=0x0472,   // 32 bit pointer to 16 bit signed int
+    T_64PINT2=0x0672,   // 64 bit pointer to 16 bit signed int
+
+    T_UINT2=0x0073,   // 16 bit unsigned int
+    T_32PUINT2=0x0473,   // 32 bit pointer to 16 bit unsigned int
+    T_64PUINT2=0x0673,   // 64 bit pointer to 16 bit unsigned int
+
+    //  32 bit long types
+
+    T_LONG=0x0012,   // 32 bit signed
+    T_ULONG=0x0022,   // 32 bit unsigned
+    T_32PLONG=0x0412,   // 32 bit pointer to 32 bit signed
+    T_32PULONG=0x0422,   // 32 bit pointer to 32 bit unsigned
+    T_64PLONG=0x0612,   // 64 bit pointer to 32 bit signed
+    T_64PULONG=0x0622,   // 64 bit pointer to 32 bit unsigned
+
+    //  32 bit int types
+
+    T_INT4=0x0074,   // 32 bit signed int
+    T_32PINT4=0x0474,   // 32 bit pointer to 32 bit signed int
+    T_64PINT4=0x0674,   // 64 bit pointer to 32 bit signed int
+
+    T_UINT4=0x0075,   // 32 bit unsigned int
+    T_32PUINT4=0x0475,   // 32 bit pointer to 32 bit unsigned int
+    T_64PUINT4=0x0675,   // 64 bit pointer to 32 bit unsigned int
+
+    //  64 bit quad types
+
+    T_QUAD=0x0013,   // 64 bit signed
+    T_32PQUAD=0x0413,   // 32 bit pointer to 64 bit signed
+    T_64PQUAD=0x0613,   // 64 bit pointer to 64 bit signed
+
+    T_UQUAD=0x0023,   // 64 bit unsigned
+    T_32PUQUAD=0x0423,   // 32 bit pointer to 64 bit unsigned
+    T_64PUQUAD=0x0623,   // 64 bit pointer to 64 bit unsigned
+
+    //  64 bit int types
+
+    T_INT8=0x0076,   // 64 bit signed int
+    T_32PINT8=0x0476,   // 32 bit pointer to 64 bit signed int
+    T_64PINT8=0x0676,   // 64 bit pointer to 64 bit signed int
+
+    T_UINT8=0x0077,   // 64 bit unsigned int
+    T_32PUINT8=0x0477,   // 32 bit pointer to 64 bit unsigned int
+    T_64PUINT8=0x0677,   // 64 bit pointer to 64 bit unsigned int
+
+    //  128 bit octet types
+
+    T_OCT=0x0014,   // 128 bit signed
+    T_32POCT=0x0414,   // 32 bit pointer to 128 bit signed
+    T_64POCT=0x0614,   // 64 bit pointer to 128 bit signed
+
+    T_UOCT=0x0024,   // 128 bit unsigned
+    T_32PUOCT=0x0424,   // 32 bit pointer to 128 bit unsigned
+    T_64PUOCT=0x0624,   // 64 bit pointer to 128 bit unsigned
+
+    //  128 bit int types
+
+    T_INT16=0x0078,   // 128 bit signed int
+    T_32PINT16=0x0478,   // 32 bit pointer to 128 bit signed int
+    T_64PINT16=0x0678,   // 64 bit pointer to 128 bit signed int
+
+    T_UINT16=0x0079,   // 128 bit unsigned int
+    T_32PUINT16=0x0479,   // 32 bit pointer to 128 bit unsigned int
+    T_64PUINT16=0x0679,   // 64 bit pointer to 128 bit unsigned int
+
+    //  32 bit real types
+
+    T_REAL32=0x0040,   // 32 bit real
+    T_32PREAL32=0x0440,   // 32 bit pointer to 32 bit real
+    T_64PREAL32=0x0640,   // 64 bit pointer to 32 bit real
+
+    //  64 bit real types
+
+    T_REAL64=0x0041,   // 64 bit real
+    T_32PREAL64=0x0441,   // 32 bit pointer to 64 bit real
+    T_64PREAL64=0x0641,   // 64 bit pointer to 64 bit real
+
+    //  80 bit real types
+
+    T_REAL80=0x0042,   // 80 bit real
+    T_32PREAL80=0x0442,   // 32 bit pointer to 80 bit real
+    T_64PREAL80=0x0642,   // 64 bit pointer to 80 bit real
+
+    //  128 bit real types
+
+    T_REAL128=0x0043,   // 128 bit real
+    T_32PREAL128=0x0443,   // 32 bit pointer to 128 bit real
+    T_64PREAL128=0x0643,   // 64 bit pointer to 128 bit real
+
+    //  32 bit complex types
+
+    T_CPLX32=0x0050,   // 32 bit complex
+    T_32PCPLX32=0x0450,   // 32 bit pointer to 32 bit complex
+    T_64PCPLX32=0x0650,   // 64 bit pointer to 32 bit complex
+
+    //  64 bit complex types
+
+    T_CPLX64=0x0051,   // 64 bit complex
+    T_32PCPLX64=0x0451,   // 32 bit pointer to 64 bit complex
+    T_64PCPLX64=0x0651,   // 64 bit pointer to 64 bit complex
+
+    //  80 bit complex types
+
+    T_CPLX80=0x0052,   // 80 bit complex
+    T_32PCPLX80=0x0452,   // 32 bit pointer to 80 bit complex
+    T_64PCPLX80=0x0652,   // 64 bit pointer to 80 bit complex
+
+    //  128 bit complex types
+
+    T_CPLX128=0x0053,   // 128 bit complex
+    T_32PCPLX128=0x0453,   // 32 bit pointer to 128 bit complex
+    T_64PCPLX128=0x0653,   // 64 bit pointer to 128 bit complex
+
+    //  boolean types
+
+    T_BOOL08=0x0030,   // 8 bit boolean
+    T_32PBOOL08=0x0430,   // 32 bit pointer to 8 bit boolean
+    T_64PBOOL08=0x0630,   // 64 bit pointer to 8 bit boolean
+
+    T_BOOL16=0x0031,   // 16 bit boolean
+    T_32PBOOL16=0x0431,   // 32 bit pointer to 18 bit boolean
+    T_64PBOOL16=0x0631,   // 64 bit pointer to 18 bit boolean
+
+    T_BOOL32=0x0032,   // 32 bit boolean
+    T_32PBOOL32=0x0432,   // 32 bit pointer to 32 bit boolean
+    T_64PBOOL32=0x0632,   // 64 bit pointer to 32 bit boolean
+
+    T_BOOL64=0x0033,   // 64 bit boolean
+    T_32PBOOL64=0x0433,   // 32 bit pointer to 64 bit boolean
+    T_64PBOOL64=0x0633,   // 64 bit pointer to 64 bit boolean
+  };
+
+  //  No leaf index can have a value of 0x0000.  The leaf indices are
+  //  separated into ranges depending upon the use of the type record.
+  //  The second range is for the type records that are directly referenced
+  //  in symbols. The first range is for type records that are not
+  //  referenced by symbols but instead are referenced by other type
+  //  records.  All type records must have a starting leaf index in these
+  //  first two ranges.  The third range of leaf indices are used to build
+  //  up complex lists such as the field list of a class type record.  No
+  //  type record can begin with one of the leaf indices. The fourth ranges
+  //  of type indices are used to represent numeric data in a symbol or
+  //  type record. These leaf indices are greater than 0x8000.  At the
+  //  point that type or symbol processor is expecting a numeric field, the
+  //  next two bytes in the type record are examined.  If the value is less
+  //  than 0x8000, then the two bytes contain the numeric value.  If the
+  //  value is greater than 0x8000, then the data follows the leaf index in
+  //  a format specified by the leaf index. The final range of leaf indices
+  //  are used to force alignment of subfields within a complex type record..
+  //
+
+  internal enum LEAF {
+    // leaf indices starting records but referenced from symbol records
+
+    LF_VTSHAPE=0x000a,
+    LF_COBOL1=0x000c,
+    LF_LABEL=0x000e,
+    LF_NULL=0x000f,
+    LF_NOTTRAN=0x0010,
+    LF_ENDPRECOMP=0x0014,       // not referenced from symbol
+    LF_TYPESERVER_ST=0x0016,       // not referenced from symbol
+
+    // leaf indices starting records but referenced only from type records
+
+    LF_LIST=0x0203,
+    LF_REFSYM=0x020c,
+
+    LF_ENUMERATE_ST=0x0403,
+
+    // 32-bit type index versions of leaves, all have the 0x1000 bit set
+    //
+    LF_TI16_MAX=0x1000,
+
+    LF_MODIFIER=0x1001,
+    LF_POINTER=0x1002,
+    LF_ARRAY_ST=0x1003,
+    LF_CLASS_ST=0x1004,
+    LF_STRUCTURE_ST=0x1005,
+    LF_UNION_ST=0x1006,
+    LF_ENUM_ST=0x1007,
+    LF_PROCEDURE=0x1008,
+    LF_MFUNCTION=0x1009,
+    LF_COBOL0=0x100a,
+    LF_BARRAY=0x100b,
+    LF_DIMARRAY_ST=0x100c,
+    LF_VFTPATH=0x100d,
+    LF_PRECOMP_ST=0x100e,       // not referenced from symbol
+    LF_OEM=0x100f,       // oem definable type string
+    LF_ALIAS_ST=0x1010,       // alias (typedef) type
+    LF_OEM2=0x1011,       // oem definable type string
+
+    // leaf indices starting records but referenced only from type records
+
+    LF_SKIP=0x1200,
+    LF_ARGLIST=0x1201,
+    LF_DEFARG_ST=0x1202,
+    LF_FIELDLIST=0x1203,
+    LF_DERIVED=0x1204,
+    LF_BITFIELD=0x1205,
+    LF_METHODLIST=0x1206,
+    LF_DIMCONU=0x1207,
+    LF_DIMCONLU=0x1208,
+    LF_DIMVARU=0x1209,
+    LF_DIMVARLU=0x120a,
+
+    LF_BCLASS=0x1400,
+    LF_VBCLASS=0x1401,
+    LF_IVBCLASS=0x1402,
+    LF_FRIENDFCN_ST=0x1403,
+    LF_INDEX=0x1404,
+    LF_MEMBER_ST=0x1405,
+    LF_STMEMBER_ST=0x1406,
+    LF_METHOD_ST=0x1407,
+    LF_NESTTYPE_ST=0x1408,
+    LF_VFUNCTAB=0x1409,
+    LF_FRIENDCLS=0x140a,
+    LF_ONEMETHOD_ST=0x140b,
+    LF_VFUNCOFF=0x140c,
+    LF_NESTTYPEEX_ST=0x140d,
+    LF_MEMBERMODIFY_ST=0x140e,
+    LF_MANAGED_ST=0x140f,
+
+    // Types w/ SZ names
+
+    LF_ST_MAX=0x1500,
+
+    LF_TYPESERVER=0x1501,       // not referenced from symbol
+    LF_ENUMERATE=0x1502,
+    LF_ARRAY=0x1503,
+    LF_CLASS=0x1504,
+    LF_STRUCTURE=0x1505,
+    LF_UNION=0x1506,
+    LF_ENUM=0x1507,
+    LF_DIMARRAY=0x1508,
+    LF_PRECOMP=0x1509,       // not referenced from symbol
+    LF_ALIAS=0x150a,       // alias (typedef) type
+    LF_DEFARG=0x150b,
+    LF_FRIENDFCN=0x150c,
+    LF_MEMBER=0x150d,
+    LF_STMEMBER=0x150e,
+    LF_METHOD=0x150f,
+    LF_NESTTYPE=0x1510,
+    LF_ONEMETHOD=0x1511,
+    LF_NESTTYPEEX=0x1512,
+    LF_MEMBERMODIFY=0x1513,
+    LF_MANAGED=0x1514,
+    LF_TYPESERVER2=0x1515,
+
+    LF_NUMERIC=0x8000,
+    LF_CHAR=0x8000,
+    LF_SHORT=0x8001,
+    LF_USHORT=0x8002,
+    LF_LONG=0x8003,
+    LF_ULONG=0x8004,
+    LF_REAL32=0x8005,
+    LF_REAL64=0x8006,
+    LF_REAL80=0x8007,
+    LF_REAL128=0x8008,
+    LF_QUADWORD=0x8009,
+    LF_UQUADWORD=0x800a,
+    LF_COMPLEX32=0x800c,
+    LF_COMPLEX64=0x800d,
+    LF_COMPLEX80=0x800e,
+    LF_COMPLEX128=0x800f,
+    LF_VARSTRING=0x8010,
+
+    LF_OCTWORD=0x8017,
+    LF_UOCTWORD=0x8018,
+
+    LF_DECIMAL=0x8019,
+    LF_DATE=0x801a,
+    LF_UTF8STRING=0x801b,
+
+    LF_PAD0=0xf0,
+    LF_PAD1=0xf1,
+    LF_PAD2=0xf2,
+    LF_PAD3=0xf3,
+    LF_PAD4=0xf4,
+    LF_PAD5=0xf5,
+    LF_PAD6=0xf6,
+    LF_PAD7=0xf7,
+    LF_PAD8=0xf8,
+    LF_PAD9=0xf9,
+    LF_PAD10=0xfa,
+    LF_PAD11=0xfb,
+    LF_PAD12=0xfc,
+    LF_PAD13=0xfd,
+    LF_PAD14=0xfe,
+    LF_PAD15=0xff,
+
+  };
+
+  // end of leaf indices
+
+  //  Type enum for pointer records
+  //  Pointers can be one of the following types
+
+  internal enum CV_ptrtype {
+    CV_PTR_BASE_SEG=0x03, // based on segment
+    CV_PTR_BASE_VAL=0x04, // based on value of base
+    CV_PTR_BASE_SEGVAL=0x05, // based on segment value of base
+    CV_PTR_BASE_ADDR=0x06, // based on address of base
+    CV_PTR_BASE_SEGADDR=0x07, // based on segment address of base
+    CV_PTR_BASE_TYPE=0x08, // based on type
+    CV_PTR_BASE_SELF=0x09, // based on self
+    CV_PTR_NEAR32=0x0a, // 32 bit pointer
+    CV_PTR_64=0x0c, // 64 bit pointer
+    CV_PTR_UNUSEDPTR=0x0d  // first unused pointer type
+  };
+
+  //  Mode enum for pointers
+  //  Pointers can have one of the following modes
+
+  internal enum CV_ptrmode {
+    CV_PTR_MODE_PTR=0x00, // "normal" pointer
+    CV_PTR_MODE_REF=0x01, // reference
+    CV_PTR_MODE_PMEM=0x02, // pointer to data member
+    CV_PTR_MODE_PMFUNC=0x03, // pointer to member function
+    CV_PTR_MODE_RESERVED=0x04  // first unused pointer mode
+  };
+
+  //  enumeration for pointer-to-member types
+
+  internal enum CV_pmtype {
+    CV_PMTYPE_Undef=0x00, // not specified (pre VC8)
+    CV_PMTYPE_D_Single=0x01, // member data, single inheritance
+    CV_PMTYPE_D_Multiple=0x02, // member data, multiple inheritance
+    CV_PMTYPE_D_Virtual=0x03, // member data, virtual inheritance
+    CV_PMTYPE_D_General=0x04, // member data, most general
+    CV_PMTYPE_F_Single=0x05, // member function, single inheritance
+    CV_PMTYPE_F_Multiple=0x06, // member function, multiple inheritance
+    CV_PMTYPE_F_Virtual=0x07, // member function, virtual inheritance
+    CV_PMTYPE_F_General=0x08, // member function, most general
+  };
+
+  //  enumeration for method properties
+
+  internal enum CV_methodprop {
+    CV_MTvanilla=0x00,
+    CV_MTvirtual=0x01,
+    CV_MTstatic=0x02,
+    CV_MTfriend=0x03,
+    CV_MTintro=0x04,
+    CV_MTpurevirt=0x05,
+    CV_MTpureintro=0x06
+  };
+
+  //  enumeration for virtual shape table entries
+
+  internal enum CV_VTS_desc {
+    CV_VTS_near=0x00,
+    CV_VTS_far=0x01,
+    CV_VTS_thin=0x02,
+    CV_VTS_outer=0x03,
+    CV_VTS_meta=0x04,
+    CV_VTS_near32=0x05,
+    CV_VTS_far32=0x06,
+    CV_VTS_unused=0x07
+  };
+
+  //  enumeration for LF_LABEL address modes
+
+  internal enum CV_LABEL_TYPE {
+    CV_LABEL_NEAR=0,       // near return
+    CV_LABEL_FAR=4        // far return
+  };
+
+  //  enumeration for LF_MODIFIER values
+
+  [Flags]
+  internal enum CV_modifier : ushort {
+    MOD_const=0x0001,
+    MOD_volatile=0x0002,
+    MOD_unaligned=0x0004,
+  };
+
+  //  bit field structure describing class/struct/union/enum properties
+
+  [Flags]
+  internal enum CV_prop : ushort {
+    packed=0x0001,   // true if structure is packed
+    ctor=0x0002,   // true if constructors or destructors present
+    ovlops=0x0004,   // true if overloaded operators present
+    isnested=0x0008,   // true if this is a nested class
+    cnested=0x0010,   // true if this class contains nested types
+    opassign=0x0020,   // true if overloaded assignment (=)
+    opcast=0x0040,   // true if casting methods
+    fwdref=0x0080,   // true if forward reference (incomplete defn)
+    scoped=0x0100,   // scoped definition
+  }
+
+  //  class field attribute
+
+  [Flags]
+  internal enum CV_fldattr {
+    access=0x0003,   // access protection CV_access_t
+    mprop=0x001c,   // method properties CV_methodprop_t
+    pseudo=0x0020,   // compiler generated fcn and does not exist
+    noinherit=0x0040,   // true if class cannot be inherited
+    noconstruct=0x0080,   // true if class cannot be constructed
+    compgenx=0x0100,   // compiler generated fcn and does exist
+  }
+
+  //  Structures to access to the type records
+
+  internal struct TYPTYPE {
+    internal ushort len;
+    internal ushort leaf;
+    // byte data[];
+
+    //  char *NextType (char * pType) {
+    //  return (pType + ((TYPTYPE *)pType)->len + sizeof(ushort));
+    //  }
+  };          // general types record
+
+  //  memory representation of pointer to member.  These representations are
+  //  indexed by the enumeration above in the LF_POINTER record
+
+  //  representation of a 32 bit pointer to data for a class with
+  //  or without virtual functions and no virtual bases
+
+  internal struct CV_PDMR32_NVVFCN {
+    internal int mdisp;      // displacement to data (NULL = 0x80000000)
+  };
+
+  //  representation of a 32 bit pointer to data for a class
+  //  with virtual bases
+
+  internal struct CV_PDMR32_VBASE {
+    internal int mdisp;      // displacement to data
+    internal int pdisp;      // this pointer displacement
+    internal int vdisp;      // vbase table displacement
+    // NULL = (,,0xffffffff)
+  };
+
+  //  representation of a 32 bit pointer to member function for a
+  //  class with no virtual bases and a single address point
+
+  internal struct CV_PMFR32_NVSA {
+    internal uint off;        // near address of function (NULL = 0L)
+  };
+
+  //  representation of a 32 bit pointer to member function for a
+  //  class with no virtual bases and multiple address points
+
+  internal struct CV_PMFR32_NVMA {
+    internal uint off;        // near address of function (NULL = 0L,x)
+    internal int disp;
+  };
+
+  //  representation of a 32 bit pointer to member function for a
+  //  class with virtual bases
+
+  internal struct CV_PMFR32_VBASE {
+    internal uint off;        // near address of function (NULL = 0L,x,x,x)
+    internal int mdisp;      // displacement to data
+    internal int pdisp;      // this pointer displacement
+    internal int vdisp;      // vbase table displacement
+  };
+
+  //////////////////////////////////////////////////////////////////////////////
+  //
+  //  The following type records are basically variant records of the
+  //  above structure.  The "ushort leaf" of the above structure and
+  //  the "ushort leaf" of the following type definitions are the same
+  //  symbol.
+  //
+
+  //  Notes on alignment
+  //  Alignment of the fields in most of the type records is done on the
+  //  basis of the TYPTYPE record base.  That is why in most of the lf*
+  //  records that the type is located on what appears to
+  //  be a offset mod 4 == 2 boundary.  The exception to this rule are those
+  //  records that are in a list (lfFieldList, lfMethodList), which are
+  //  aligned to their own bases since they don't have the length field
+  //
+
+  //  Type record for LF_MODIFIER
+
+  internal struct LeafModifier {
+    // internal ushort leaf;      // LF_MODIFIER [TYPTYPE]
+    internal uint type;       // (type index) modified type
+    internal CV_modifier attr;    // modifier attribute modifier_t
+  };
+
+  //  type record for LF_POINTER
+
+  [Flags]
+  internal enum LeafPointerAttr : uint {
+    ptrtype=0x0000001f,   // ordinal specifying pointer type (CV_ptrtype)
+    ptrmode=0x000000e0,   // ordinal specifying pointer mode (CV_ptrmode)
+    isflat32=0x00000100,   // true if 0:32 pointer
+    isvolatile=0x00000200,   // TRUE if volatile pointer
+    isconst=0x00000400,   // TRUE if const pointer
+    isunaligned=0x00000800,   // TRUE if unaligned pointer
+    isrestrict=0x00001000,   // TRUE if restricted pointer (allow agressive opts)
+  };
+
+  internal struct LeafPointer {
+    internal struct LeafPointerBody {
+      // internal ushort leaf;  // LF_POINTER [TYPTYPE]
+      internal uint utype;  // (type index) type index of the underlying type
+      internal LeafPointerAttr attr;
+    };
+#if false
+        union {
+            internal struct {
+                uint    pmclass;    // (type index) index of containing class for pointer to member
+                ushort  pmenum;     // enumeration specifying pm format (CV_pmtype)
+            };
+            ushort  bseg;           // base segment if PTR_BASE_SEG
+            byte[]  Sym;            // copy of base symbol record (including length)
+            internal struct  {
+                uint    index;      // (type index) type index if CV_PTR_BASE_TYPE
+                string  name;       // name of base type
+            } btype;
+        } pbase;
+#endif
+  }
+
+  //  type record for LF_ARRAY
+
+  internal struct LeafArray {
+    // internal ushort leaf;      // LF_ARRAY [TYPTYPE]
+    internal uint elemtype;   // (type index) type index of element type
+    internal uint idxtype;    // (type index) type index of indexing type
+    internal byte[] data;       // variable length data specifying size in bytes
+    internal string name;
+  };
+
+  //  type record for LF_CLASS, LF_STRUCTURE
+
+  internal struct LeafClass {
+    // internal ushort leaf;      // LF_CLASS, LF_STRUCT [TYPTYPE]
+    internal ushort count;      // count of number of elements in class
+    internal ushort property;   // (CV_prop_t) property attribute field (prop_t)
+    internal uint field;      // (type index) type index of LF_FIELD descriptor list
+    internal uint derived;    // (type index) type index of derived from list if not zero
+    internal uint vshape;     // (type index) type index of vshape table for this class
+    internal byte[] data;       // data describing length of structure in bytes
+    internal string name;
+  };
+
+  //  type record for LF_UNION
+
+  internal struct LeafUnion {
+    // internal ushort leaf;      // LF_UNION [TYPTYPE]
+    internal ushort count;      // count of number of elements in class
+    internal ushort property;   // (CV_prop_t) property attribute field
+    internal uint field;      // (type index) type index of LF_FIELD descriptor list
+    internal byte[] data;       // variable length data describing length of
+    internal string name;
+  };
+
+  //  type record for LF_ALIAS
+
+  internal struct LeafAlias {
+    // internal ushort leaf;      // LF_ALIAS [TYPTYPE]
+    internal uint utype;      // (type index) underlying type
+    internal string name;       // alias name
+  };
+
+  //  type record for LF_MANAGED
+
+  internal struct LeafManaged {
+    // internal ushort leaf;      // LF_MANAGED [TYPTYPE]
+    internal string name;       // utf8, zero terminated managed type name
+  };
+
+  //  type record for LF_ENUM
+
+  internal struct LeafEnum {
+    // internal ushort leaf;      // LF_ENUM [TYPTYPE]
+    internal ushort count;      // count of number of elements in class
+    internal ushort property;   // (CV_propt_t) property attribute field
+    internal uint utype;      // (type index) underlying type of the enum
+    internal uint field;      // (type index) type index of LF_FIELD descriptor list
+    internal string name;       // length prefixed name of enum
+  };
+
+  //  Type record for LF_PROCEDURE
+
+  internal struct LeafProc {
+    // internal ushort leaf;      // LF_PROCEDURE [TYPTYPE]
+    internal uint rvtype;     // (type index) type index of return value
+    internal byte calltype;   // calling convention (CV_call_t)
+    internal byte reserved;   // reserved for future use
+    internal ushort parmcount;  // number of parameters
+    internal uint arglist;    // (type index) type index of argument list
+  };
+
+  //  Type record for member function
+
+  internal struct LeafMFunc {
+    // internal ushort leaf;      // LF_MFUNCTION [TYPTYPE]
+    internal uint rvtype;     // (type index) type index of return value
+    internal uint classtype;  // (type index) type index of containing class
+    internal uint thistype;   // (type index) type index of this pointer (model specific)
+    internal byte calltype;   // calling convention (call_t)
+    internal byte reserved;   // reserved for future use
+    internal ushort parmcount;  // number of parameters
+    internal uint arglist;    // (type index) type index of argument list
+    internal int thisadjust; // this adjuster (long because pad required anyway)
+  };
+
+  //  type record for virtual function table shape
+
+  internal struct LeafVTShape {
+    // internal ushort leaf;      // LF_VTSHAPE [TYPTYPE]
+    internal ushort count;      // number of entries in vfunctable
+    internal byte[] desc;       // 4 bit (CV_VTS_desc) descriptors
+  };
+
+  //  type record for cobol0
+
+  internal struct LeafCobol0 {
+    // internal ushort leaf;      // LF_COBOL0 [TYPTYPE]
+    internal uint type;       // (type index) parent type record index
+    internal byte[] data;
+  };
+
+  //  type record for cobol1
+
+  internal struct LeafCobol1 {
+    // internal ushort leaf;      // LF_COBOL1 [TYPTYPE]
+    internal byte[] data;
+  };
+
+  //  type record for basic array
+
+  internal struct LeafBArray {
+    // internal ushort leaf;      // LF_BARRAY [TYPTYPE]
+    internal uint utype;      // (type index) type index of underlying type
+  };
+
+  //  type record for assembler labels
+
+  internal struct LeafLabel {
+    // internal ushort leaf;      // LF_LABEL [TYPTYPE]
+    internal ushort mode;       // addressing mode of label
+  };
+
+  //  type record for dimensioned arrays
+
+  internal struct LeafDimArray {
+    // internal ushort leaf;      // LF_DIMARRAY [TYPTYPE]
+    internal uint utype;      // (type index) underlying type of the array
+    internal uint diminfo;    // (type index) dimension information
+    internal string name;       // length prefixed name
+  };
+
+  //  type record describing path to virtual function table
+
+  internal struct LeafVFTPath {
+    // internal ushort leaf;      // LF_VFTPATH [TYPTYPE]
+    internal uint count;      // count of number of bases in path
+    internal uint[] bases;      // (type index) bases from root to leaf
+  };
+
+  //  type record describing inclusion of precompiled types
+
+  internal struct LeafPreComp {
+    // internal ushort leaf;      // LF_PRECOMP [TYPTYPE]
+    internal uint start;      // starting type index included
+    internal uint count;      // number of types in inclusion
+    internal uint signature;  // signature
+    internal string name;       // length prefixed name of included type file
+  };
+
+  //  type record describing end of precompiled types that can be
+  //  included by another file
+
+  internal struct LeafEndPreComp {
+    // internal ushort leaf;      // LF_ENDPRECOMP [TYPTYPE]
+    internal uint signature;  // signature
+  };
+
+  //  type record for OEM definable type strings
+
+  internal struct LeafOEM {
+    // internal ushort leaf;      // LF_OEM [TYPTYPE]
+    internal ushort cvOEM;      // MS assigned OEM identified
+    internal ushort recOEM;     // OEM assigned type identifier
+    internal uint count;      // count of type indices to follow
+    internal uint[] index;      // (type index) array of type indices followed
+    // by OEM defined data
+  };
+
+  internal enum OEM_ID {
+    OEM_MS_FORTRAN90=0xF090,
+    OEM_ODI=0x0010,
+    OEM_THOMSON_SOFTWARE=0x5453,
+    OEM_ODI_REC_BASELIST=0x0000,
+  };
+
+  internal struct LeafOEM2 {
+    // internal ushort leaf;      // LF_OEM2 [TYPTYPE]
+    internal Guid idOem;      // an oem ID (Guid)
+    internal uint count;      // count of type indices to follow
+    internal uint[] index;      // (type index) array of type indices followed
+    // by OEM defined data
+  };
+
+  //  type record describing using of a type server
+
+  internal struct LeafTypeServer {
+    // internal ushort leaf;      // LF_TYPESERVER [TYPTYPE]
+    internal uint signature;  // signature
+    internal uint age;        // age of database used by this module
+    internal string name;       // length prefixed name of PDB
+  };
+
+  //  type record describing using of a type server with v7 (GUID) signatures
+
+  internal struct LeafTypeServer2 {
+    // internal ushort leaf;      // LF_TYPESERVER2 [TYPTYPE]
+    internal Guid sig70;      // guid signature
+    internal uint age;        // age of database used by this module
+    internal string name;       // length prefixed name of PDB
+  };
+
+  //  description of type records that can be referenced from
+  //  type records referenced by symbols
+
+  //  type record for skip record
+
+  internal struct LeafSkip {
+    // internal ushort leaf;      // LF_SKIP [TYPTYPE]
+    internal uint type;       // (type index) next valid index
+    internal byte[] data;       // pad data
+  };
+
+  //  argument list leaf
+
+  internal struct LeafArgList {
+    // internal ushort leaf;      // LF_ARGLIST [TYPTYPE]
+    internal uint count;      // number of arguments
+    internal uint[] arg;        // (type index) number of arguments
+  };
+
+  //  derived class list leaf
+
+  internal struct LeafDerived {
+    // internal ushort leaf;      // LF_DERIVED [TYPTYPE]
+    internal uint count;      // number of arguments
+    internal uint[] drvdcls;    // (type index) type indices of derived classes
+  };
+
+  //  leaf for default arguments
+
+  internal struct LeafDefArg {
+    // internal ushort leaf;      // LF_DEFARG [TYPTYPE]
+    internal uint type;       // (type index) type of resulting expression
+    internal byte[] expr;       // length prefixed expression string
+  };
+
+  //  list leaf
+  //      This list should no longer be used because the utilities cannot
+  //      verify the contents of the list without knowing what type of list
+  //      it is.  New specific leaf indices should be used instead.
+
+  internal struct LeafList {
+    // internal ushort leaf;      // LF_LIST [TYPTYPE]
+    internal byte[] data;       // data format specified by indexing type
+  };
+
+  //  field list leaf
+  //  This is the header leaf for a complex list of class and structure
+  //  subfields.
+
+  internal struct LeafFieldList {
+    // internal ushort leaf;      // LF_FIELDLIST [TYPTYPE]
+    internal char[] data;       // field list sub lists
+  };
+
+  //  type record for non-static methods and friends in overloaded method list
+
+  internal struct mlMethod {
+    internal ushort attr;       // (CV_fldattr_t) method attribute
+    internal ushort pad0;       // internal padding, must be 0
+    internal uint index;      // (type index) index to type record for procedure
+    internal uint[] vbaseoff;   // offset in vfunctable if intro virtual
+  };
+
+  internal struct LeafMethodList {
+    // internal ushort leaf;      // LF_METHODLIST [TYPTYPE]
+    internal byte[] mList;      // really a mlMethod type
+  };
+
+  //  type record for LF_BITFIELD
+
+  internal struct LeafBitfield {
+    // internal ushort leaf;      // LF_BITFIELD [TYPTYPE]
+    internal uint type;       // (type index) type of bitfield
+    internal byte length;
+    internal byte position;
+  };
+
+  //  type record for dimensioned array with constant bounds
+
+  internal struct LeafDimCon {
+    // internal ushort leaf;      // LF_DIMCONU or LF_DIMCONLU [TYPTYPE]
+    internal uint typ;        // (type index) type of index
+    internal ushort rank;       // number of dimensions
+    internal byte[] dim;        // array of dimension information with
+    // either upper bounds or lower/upper bound
+  };
+
+  //  type record for dimensioned array with variable bounds
+
+  internal struct LeafDimVar {
+    // internal ushort leaf;      // LF_DIMVARU or LF_DIMVARLU [TYPTYPE]
+    internal uint rank;       // number of dimensions
+    internal uint typ;        // (type index) type of index
+    internal uint[] dim;        // (type index) array of type indices for either
+    // variable upper bound or variable
+    // lower/upper bound.  The count of type
+    // indices is rank or rank*2 depending on
+    // whether it is LFDIMVARU or LF_DIMVARLU.
+    // The referenced types must be
+    // LF_REFSYM or T_VOID
+  };
+
+  //  type record for referenced symbol
+
+  internal struct LeafRefSym {
+    // internal ushort leaf;      // LF_REFSYM [TYPTYPE]
+    internal byte[] Sym;        // copy of referenced symbol record
+    // (including length)
+  };
+
+  //  the following are numeric leaves.  They are used to indicate the
+  //  size of the following variable length data.  When the numeric
+  //  data is a single byte less than 0x8000, then the data is output
+  //  directly.  If the data is more the 0x8000 or is a negative value,
+  //  then the data is preceeded by the proper index.
+  //
+
+  //  signed character leaf
+
+  internal struct LeafChar {
+    // internal ushort leaf;      // LF_CHAR [TYPTYPE]
+    internal sbyte val;        // signed 8-bit value
+  };
+
+  //  signed short leaf
+
+  internal struct LeafShort {
+    // internal ushort leaf;      // LF_SHORT [TYPTYPE]
+    internal short val;        // signed 16-bit value
+  };
+
+  //  ushort leaf
+
+  internal struct LeafUShort {
+    // internal ushort leaf;      // LF_ushort [TYPTYPE]
+    internal ushort val;        // unsigned 16-bit value
+  };
+
+  //  signed (32-bit) long leaf
+
+  internal struct LeafLong {
+    // internal ushort leaf;      // LF_LONG [TYPTYPE]
+    internal int val;        // signed 32-bit value
+  };
+
+  //  uint    leaf
+
+  internal struct LeafULong {
+    // internal ushort leaf;      // LF_ULONG [TYPTYPE]
+    internal uint val;        // unsigned 32-bit value
+  };
+
+  //  signed quad leaf
+
+  internal struct LeafQuad {
+    // internal ushort leaf;      // LF_QUAD [TYPTYPE]
+    internal long val;        // signed 64-bit value
+  };
+
+  //  unsigned quad leaf
+
+  internal struct LeafUQuad {
+    // internal ushort leaf;      // LF_UQUAD [TYPTYPE]
+    internal ulong val;        // unsigned 64-bit value
+  };
+
+  //  signed int128 leaf
+
+  internal struct LeafOct {
+    // internal ushort leaf;      // LF_OCT [TYPTYPE]
+    internal ulong val0;
+    internal ulong val1;       // signed 128-bit value
+  };
+
+  //  unsigned int128 leaf
+
+  internal struct LeafUOct {
+    // internal ushort leaf;      // LF_UOCT [TYPTYPE]
+    internal ulong val0;
+    internal ulong val1;       // unsigned 128-bit value
+  };
+
+  //  real 32-bit leaf
+
+  internal struct LeafReal32 {
+    // internal ushort leaf;      // LF_REAL32 [TYPTYPE]
+    internal float val;        // 32-bit real value
+  };
+
+  //  real 64-bit leaf
+
+  internal struct LeafReal64 {
+    // internal ushort leaf;      // LF_REAL64 [TYPTYPE]
+    internal double val;        // 64-bit real value
+  };
+
+  //  real 80-bit leaf
+
+  internal struct LeafReal80 {
+    // internal ushort leaf;      // LF_REAL80 [TYPTYPE]
+    internal FLOAT10 val;        // real 80-bit value
+  };
+
+  //  real 128-bit leaf
+
+  internal struct LeafReal128 {
+    // internal ushort leaf;      // LF_REAL128 [TYPTYPE]
+    internal ulong val0;
+    internal ulong val1;       // real 128-bit value
+  };
+
+  //  complex 32-bit leaf
+
+  internal struct LeafCmplx32 {
+    // internal ushort leaf;      // LF_COMPLEX32 [TYPTYPE]
+    internal float val_real;   // real component
+    internal float val_imag;   // imaginary component
+  };
+
+  //  complex 64-bit leaf
+
+  internal struct LeafCmplx64 {
+    // internal ushort leaf;      // LF_COMPLEX64 [TYPTYPE]
+    internal double val_real;   // real component
+    internal double val_imag;   // imaginary component
+  };
+
+  //  complex 80-bit leaf
+
+  internal struct LeafCmplx80 {
+    // internal ushort leaf;      // LF_COMPLEX80 [TYPTYPE]
+    internal FLOAT10 val_real;   // real component
+    internal FLOAT10 val_imag;   // imaginary component
+  };
+
+  //  complex 128-bit leaf
+
+  internal struct LeafCmplx128 {
+    // internal ushort leaf;      // LF_COMPLEX128 [TYPTYPE]
+    internal ulong val0_real;
+    internal ulong val1_real;  // real component
+    internal ulong val0_imag;
+    internal ulong val1_imag;  // imaginary component
+  };
+
+  //  variable length numeric field
+
+  internal struct LeafVarString {
+    // internal ushort leaf;      // LF_VARSTRING [TYPTYPE]
+    internal ushort len;        // length of value in bytes
+    internal byte[] value;      // value
+  };
+
+  //  index leaf - contains type index of another leaf
+  //  a major use of this leaf is to allow the compilers to emit a
+  //  long complex list (LF_FIELD) in smaller pieces.
+
+  internal struct LeafIndex {
+    // internal ushort leaf;      // LF_INDEX [TYPTYPE]
+    internal ushort pad0;       // internal padding, must be 0
+    internal uint index;      // (type index) type index of referenced leaf
+  };
+
+  //  subfield record for base class field
+
+  internal struct LeafBClass {
+    // internal ushort leaf;      // LF_BCLASS [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) attribute
+    internal uint index;      // (type index) type index of base class
+    internal byte[] offset;     // variable length offset of base within class
+  };
+
+  //  subfield record for direct and indirect virtual base class field
+
+  internal struct LeafVBClass {
+    // internal ushort leaf;      // LF_VBCLASS | LV_IVBCLASS [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) attribute
+    internal uint index;      // (type index) type index of direct virtual base class
+    internal uint vbptr;      // (type index) type index of virtual base pointer
+    internal byte[] vbpoff;     // virtual base pointer offset from address point
+    // followed by virtual base offset from vbtable
+  };
+
+  //  subfield record for friend class
+
+  internal struct LeafFriendCls {
+    // internal ushort leaf;      // LF_FRIENDCLS [TYPTYPE]
+    internal ushort pad0;       // internal padding, must be 0
+    internal uint index;      // (type index) index to type record of friend class
+  };
+
+  //  subfield record for friend function
+
+  internal struct LeafFriendFcn {
+    // internal ushort leaf;      // LF_FRIENDFCN [TYPTYPE]
+    internal ushort pad0;       // internal padding, must be 0
+    internal uint index;      // (type index) index to type record of friend function
+    internal string name;       // name of friend function
+  };
+
+  //  subfield record for non-static data members
+
+  internal struct LeafMember {
+    // internal ushort leaf;      // LF_MEMBER [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t)attribute mask
+    internal uint index;      // (type index) index of type record for field
+    internal byte[] offset;     // variable length offset of field
+    internal string name;       // length prefixed name of field
+  };
+
+  //  type record for static data members
+
+  internal struct LeafSTMember {
+    // internal ushort leaf;      // LF_STMEMBER [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) attribute mask
+    internal uint index;      // (type index) index of type record for field
+    internal string name;       // length prefixed name of field
+  };
+
+  //  subfield record for virtual function table pointer
+
+  internal struct LeafVFuncTab {
+    // internal ushort leaf;      // LF_VFUNCTAB [TYPTYPE]
+    internal ushort pad0;       // internal padding, must be 0
+    internal uint type;       // (type index) type index of pointer
+  };
+
+  //  subfield record for virtual function table pointer with offset
+
+  internal struct LeafVFuncOff {
+    // internal ushort leaf;      // LF_VFUNCOFF [TYPTYPE]
+    internal ushort pad0;       // internal padding, must be 0.
+    internal uint type;       // (type index) type index of pointer
+    internal int offset;     // offset of virtual function table pointer
+  };
+
+  //  subfield record for overloaded method list
+
+  internal struct LeafMethod {
+    // internal ushort leaf;      // LF_METHOD [TYPTYPE]
+    internal ushort count;      // number of occurrences of function
+    internal uint mList;      // (type index) index to LF_METHODLIST record
+    internal string name;       // length prefixed name of method
+  };
+
+  //  subfield record for nonoverloaded method
+
+  internal struct LeafOneMethod {
+    // internal ushort leaf;      // LF_ONEMETHOD [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) method attribute
+    internal uint index;      // (type index) index to type record for procedure
+    internal uint[] vbaseoff;   // offset in vfunctable if intro virtual
+    internal string name;
+  };
+
+  //  subfield record for enumerate
+
+  internal struct LeafEnumerate {
+    // internal ushort leaf;      // LF_ENUMERATE [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) access
+    internal byte[] value;      // variable length value field
+    internal string name;
+  };
+
+  //  type record for nested (scoped) type definition
+
+  internal struct LeafNestType {
+    // internal ushort leaf;      // LF_NESTTYPE [TYPTYPE]
+    internal ushort pad0;       // internal padding, must be 0
+    internal uint index;      // (type index) index of nested type definition
+    internal string name;       // length prefixed type name
+  };
+
+  //  type record for nested (scoped) type definition, with attributes
+  //  new records for vC v5.0, no need to have 16-bit ti versions.
+
+  internal struct LeafNestTypeEx {
+    // internal ushort leaf;      // LF_NESTTYPEEX [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) member access
+    internal uint index;      // (type index) index of nested type definition
+    internal string name;       // length prefixed type name
+  };
+
+  //  type record for modifications to members
+
+  internal struct LeafMemberModify {
+    // internal ushort leaf;      // LF_MEMBERMODIFY [TYPTYPE]
+    internal ushort attr;       // (CV_fldattr_t) the new attributes
+    internal uint index;      // (type index) index of base class type definition
+    internal string name;       // length prefixed member name
+  };
+
+  //  type record for pad leaf
+
+  internal struct LeafPad {
+    internal byte leaf;
+  };
+
+  //  Symbol definitions
+
+  internal enum SYM {
+    S_END=0x0006,  // Block, procedure, "with" or thunk end
+    S_OEM=0x0404,  // OEM defined symbol
+
+    S_REGISTER_ST=0x1001,  // Register variable
+    S_CONSTANT_ST=0x1002,  // constant symbol
+    S_UDT_ST=0x1003,  // User defined type
+    S_COBOLUDT_ST=0x1004,  // special UDT for cobol that does not symbol pack
+    S_MANYREG_ST=0x1005,  // multiple register variable
+    S_BPREL32_ST=0x1006,  // BP-relative
+    S_LDATA32_ST=0x1007,  // Module-local symbol
+    S_GDATA32_ST=0x1008,  // Global data symbol
+    S_PUB32_ST=0x1009,  // a internal symbol (CV internal reserved)
+    S_LPROC32_ST=0x100a,  // Local procedure start
+    S_GPROC32_ST=0x100b,  // Global procedure start
+    S_VFTABLE32=0x100c,  // address of virtual function table
+    S_REGREL32_ST=0x100d,  // register relative address
+    S_LTHREAD32_ST=0x100e,  // local thread storage
+    S_GTHREAD32_ST=0x100f,  // global thread storage
+
+    S_LPROCMIPS_ST=0x1010,  // Local procedure start
+    S_GPROCMIPS_ST=0x1011,  // Global procedure start
+
+    // new symbol records for edit and continue information
+
+    S_FRAMEPROC=0x1012,  // extra frame and proc information
+    S_COMPILE2_ST=0x1013,  // extended compile flags and info
+
+    // new symbols necessary for 16-bit enumerates of IA64 registers
+    // and IA64 specific symbols
+
+    S_MANYREG2_ST=0x1014,  // multiple register variable
+    S_LPROCIA64_ST=0x1015,  // Local procedure start (IA64)
+    S_GPROCIA64_ST=0x1016,  // Global procedure start (IA64)
+
+    // Local symbols for IL
+    S_LOCALSLOT_ST=0x1017,  // local IL sym with field for local slot index
+    S_PARAMSLOT_ST=0x1018,  // local IL sym with field for parameter slot index
+
+    S_ANNOTATION=0x1019,  // Annotation string literals
+
+    // symbols to support managed code debugging
+    S_GMANPROC_ST=0x101a,  // Global proc
+    S_LMANPROC_ST=0x101b,  // Local proc
+    S_RESERVED1=0x101c,  // reserved
+    S_RESERVED2=0x101d,  // reserved
+    S_RESERVED3=0x101e,  // reserved
+    S_RESERVED4=0x101f,  // reserved
+    S_LMANDATA_ST=0x1020,
+    S_GMANDATA_ST=0x1021,
+    S_MANFRAMEREL_ST=0x1022,
+    S_MANREGISTER_ST=0x1023,
+    S_MANSLOT_ST=0x1024,
+    S_MANMANYREG_ST=0x1025,
+    S_MANREGREL_ST=0x1026,
+    S_MANMANYREG2_ST=0x1027,
+    S_MANTYPREF=0x1028,  // Index for type referenced by name from metadata
+    S_UNAMESPACE_ST=0x1029,  // Using namespace
+
+    // Symbols w/ SZ name fields. All name fields contain utf8 encoded strings.
+    S_ST_MAX=0x1100,  // starting point for SZ name symbols
+
+    S_OBJNAME=0x1101,  // path to object file name
+    S_THUNK32=0x1102,  // Thunk Start
+    S_BLOCK32=0x1103,  // block start
+    S_WITH32=0x1104,  // with start
+    S_LABEL32=0x1105,  // code label
+    S_REGISTER=0x1106,  // Register variable
+    S_CONSTANT=0x1107,  // constant symbol
+    S_UDT=0x1108,  // User defined type
+    S_COBOLUDT=0x1109,  // special UDT for cobol that does not symbol pack
+    S_MANYREG=0x110a,  // multiple register variable
+    S_BPREL32=0x110b,  // BP-relative
+    S_LDATA32=0x110c,  // Module-local symbol
+    S_GDATA32=0x110d,  // Global data symbol
+    S_PUB32=0x110e,  // a internal symbol (CV internal reserved)
+    S_LPROC32=0x110f,  // Local procedure start
+    S_GPROC32=0x1110,  // Global procedure start
+    S_REGREL32=0x1111,  // register relative address
+    S_LTHREAD32=0x1112,  // local thread storage
+    S_GTHREAD32=0x1113,  // global thread storage
+
+    S_LPROCMIPS=0x1114,  // Local procedure start
+    S_GPROCMIPS=0x1115,  // Global procedure start
+    S_COMPILE2=0x1116,  // extended compile flags and info
+    S_MANYREG2=0x1117,  // multiple register variable
+    S_LPROCIA64=0x1118,  // Local procedure start (IA64)
+    S_GPROCIA64=0x1119,  // Global procedure start (IA64)
+    S_LOCALSLOT=0x111a,  // local IL sym with field for local slot index
+    S_SLOT=S_LOCALSLOT,  // alias for LOCALSLOT
+    S_PARAMSLOT=0x111b,  // local IL sym with field for parameter slot index
+
+    // symbols to support managed code debugging
+    S_LMANDATA=0x111c,
+    S_GMANDATA=0x111d,
+    S_MANFRAMEREL=0x111e,
+    S_MANREGISTER=0x111f,
+    S_MANSLOT=0x1120,
+    S_MANMANYREG=0x1121,
+    S_MANREGREL=0x1122,
+    S_MANMANYREG2=0x1123,
+    S_UNAMESPACE=0x1124,  // Using namespace
+
+    // ref symbols with name fields
+    S_PROCREF=0x1125,  // Reference to a procedure
+    S_DATAREF=0x1126,  // Reference to data
+    S_LPROCREF=0x1127,  // Local Reference to a procedure
+    S_ANNOTATIONREF=0x1128,  // Reference to an S_ANNOTATION symbol
+    S_TOKENREF=0x1129,  // Reference to one of the many MANPROCSYM's
+
+    // continuation of managed symbols
+    S_GMANPROC=0x112a,  // Global proc
+    S_LMANPROC=0x112b,  // Local proc
+
+    // short, light-weight thunks
+    S_TRAMPOLINE=0x112c,  // trampoline thunks
+    S_MANCONSTANT=0x112d,  // constants with metadata type info
+
+    // native attributed local/parms
+    S_ATTR_FRAMEREL=0x112e,  // relative to virtual frame ptr
+    S_ATTR_REGISTER=0x112f,  // stored in a register
+    S_ATTR_REGREL=0x1130,  // relative to register (alternate frame ptr)
+    S_ATTR_MANYREG=0x1131,  // stored in >1 register
+
+    // Separated code (from the compiler) support
+    S_SEPCODE=0x1132,
+
+    S_LOCAL=0x1133,  // defines a local symbol in optimized code
+    S_DEFRANGE=0x1134,  // defines a single range of addresses in which symbol can be evaluated
+    S_DEFRANGE2=0x1135,  // defines ranges of addresses in which symbol can be evaluated
+
+    S_SECTION=0x1136,  // A COFF section in a PE executable
+    S_COFFGROUP=0x1137,  // A COFF group
+    S_EXPORT=0x1138,  // A export
+
+    S_CALLSITEINFO=0x1139,  // Indirect call site information
+    S_FRAMECOOKIE=0x113a,  // Security cookie information
+
+    S_DISCARDED=0x113b,  // Discarded by LINK /OPT:REF (experimental, see richards)
+
+    S_RECTYPE_MAX,              // one greater than last
+    S_RECTYPE_LAST=S_RECTYPE_MAX - 1,
+
+  };
+
+  //  enum describing compile flag ambient data model
+
+  internal enum CV_CFL_DATA {
+    CV_CFL_DNEAR=0x00,
+    CV_CFL_DFAR=0x01,
+    CV_CFL_DHUGE=0x02
+  };
+
+  //  enum describing compile flag ambiant code model
+
+  internal enum CV_CFL_CODE {
+    CV_CFL_CNEAR=0x00,
+    CV_CFL_CFAR=0x01,
+    CV_CFL_CHUGE=0x02
+  };
+
+  //  enum describing compile flag target floating point package
+
+  internal enum CV_CFL_FPKG {
+    CV_CFL_NDP=0x00,
+    CV_CFL_EMU=0x01,
+    CV_CFL_ALT=0x02
+  };
+
+  // enum describing function return method
+
+  [Flags]
+  internal enum CV_PROCFLAGS : byte {
+    CV_PFLAG_NOFPO=0x01, // frame pointer present
+    CV_PFLAG_INT=0x02, // interrupt return
+    CV_PFLAG_FAR=0x04, // far return
+    CV_PFLAG_NEVER=0x08, // function does not return
+    CV_PFLAG_NOTREACHED=0x10, // label isn't fallen into
+    CV_PFLAG_CUST_CALL=0x20, // custom calling convention
+    CV_PFLAG_NOINLINE=0x40, // function marked as noinline
+    CV_PFLAG_OPTDBGINFO=0x80, // function has debug information for optimized code
+  };
+
+  // Extended proc flags
+  //
+  internal struct CV_EXPROCFLAGS {
+    internal byte flags;      // (CV_PROCFLAGS)
+    internal byte reserved;   // must be zero
+  };
+
+  // local variable flags
+  [Flags]
+  internal enum CV_LVARFLAGS : ushort {
+    fIsParam=0x0001,   // variable is a parameter
+    fAddrTaken=0x0002,   // address is taken
+    fCompGenx=0x0004,   // variable is compiler generated
+    fIsAggregate=0x0008,   // the symbol is splitted in temporaries,
+    // which are treated by compiler as
+    // independent entities
+    fIsAggregated=0x0010,   // Counterpart of fIsAggregate - tells
+    // that it is a part of a fIsAggregate symbol
+    fIsAliased=0x0020,   // variable has multiple simultaneous lifetimes
+    fIsAlias=0x0040,   // represents one of the multiple simultaneous lifetimes
+  };
+
+  // represents an address range, used for optimized code debug info
+  internal struct CV_lvar_addr_range {       // defines a range of addresses
+    internal uint offStart;
+    internal ushort isectStart;
+    internal uint cbRange;
+  };
+
+  // enum describing function data return method
+
+  internal enum CV_GENERIC_STYLE {
+    CV_GENERIC_VOID=0x00,   // void return type
+    CV_GENERIC_REG=0x01,   // return data is in registers
+    CV_GENERIC_ICAN=0x02,   // indirect caller allocated near
+    CV_GENERIC_ICAF=0x03,   // indirect caller allocated far
+    CV_GENERIC_IRAN=0x04,   // indirect returnee allocated near
+    CV_GENERIC_IRAF=0x05,   // indirect returnee allocated far
+    CV_GENERIC_UNUSED=0x06    // first unused
+  };
+
+  [Flags]
+  internal enum CV_GENERIC_FLAG : ushort {
+    cstyle=0x0001,       // true push varargs right to left
+    rsclean=0x0002,       // true if returnee stack cleanup
+  };
+
+  // flag bitfields for separated code attributes
+
+  [Flags]
+  internal enum CV_SEPCODEFLAGS : uint {
+    fIsLexicalScope=0x00000001,   // S_SEPCODE doubles as lexical scope
+    fReturnsToParent=0x00000002,   // code frag returns to parent
+  };
+
+  // Generic layout for symbol records
+
+  internal struct SYMTYPE {
+    internal ushort reclen;     // Record length
+    internal ushort rectyp;     // Record type
+    // byte        data[CV_ZEROLEN];
+    //  SYMTYPE *NextSym (SYMTYPE * pSym) {
+    //  return (SYMTYPE *) ((char *)pSym + pSym->reclen + sizeof(ushort));
+    //  }
+  };
+
+  //  non-model specific symbol types
+
+  internal struct RegSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_REGISTER
+    internal uint typind;     // (type index) Type index or Metadata token
+    internal ushort reg;        // register enumerate
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct AttrRegSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANREGISTER | S_ATTR_REGISTER
+    internal uint typind;     // (type index) Type index or Metadata token
+    internal uint offCod;     // first code address where var is live
+    internal ushort segCod;
+    internal ushort flags;      // (CV_LVARFLAGS)local var flags
+    internal ushort reg;        // register enumerate
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct ManyRegSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANYREG
+    internal uint typind;     // (type index) Type index or metadata token
+    internal byte count;      // count of number of registers
+    internal byte[] reg;        // count register enumerates, most-sig first
+    internal string name;       // length-prefixed name.
+  };
+
+  internal struct ManyRegSym2 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANYREG2
+    internal uint typind;     // (type index) Type index or metadata token
+    internal ushort count;      // count of number of registers,
+    internal ushort[] reg;        // count register enumerates, most-sig first
+    internal string name;       // length-prefixed name.
+  };
+
+  internal struct AttrManyRegSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANMANYREG
+    internal uint typind;     // (type index) Type index or metadata token
+    internal uint offCod;     // first code address where var is live
+    internal ushort segCod;
+    internal ushort flags;      // (CV_LVARFLAGS)local var flags
+    internal byte count;      // count of number of registers
+    internal byte[] reg;        // count register enumerates, most-sig first
+    internal string name;       // utf-8 encoded zero terminate name
+  };
+
+  internal struct AttrManyRegSym2 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANMANYREG2 | S_ATTR_MANYREG
+    internal uint typind;     // (type index) Type index or metadata token
+    internal uint offCod;     // first code address where var is live
+    internal ushort segCod;
+    internal ushort flags;      // (CV_LVARFLAGS)local var flags
+    internal ushort count;      // count of number of registers
+    internal ushort[] reg;        // count register enumerates, most-sig first
+    internal string name;       // utf-8 encoded zero terminate name
+  };
+
+  internal struct ConstSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_CONSTANT or S_MANCONSTANT
+    internal uint typind;     // (type index) Type index (containing enum if enumerate) or metadata token
+    internal ushort value;      // numeric leaf containing value
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct UdtSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_UDT | S_COBOLUDT
+    internal uint typind;     // (type index) Type index
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct ManyTypRef {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANTYPREF
+    internal uint typind;     // (type index) Type index
+  };
+
+  internal struct SearchSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_SSEARCH
+    internal uint startsym;   // offset of the procedure
+    internal ushort seg;        // segment of symbol
+  };
+
+  [Flags]
+  internal enum CFLAGSYM_FLAGS : ushort {
+    pcode=0x0001,   // true if pcode present
+    floatprec=0x0006,   // floating precision
+    floatpkg=0x0018,   // float package
+    ambdata=0x00e0,   // ambient data model
+    ambcode=0x0700,   // ambient code model
+    mode32=0x0800,   // true if compiled 32 bit mode
+  };
+
+  internal struct CFlagSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_COMPILE
+    internal byte machine;    // target processor
+    internal byte language;   // language index
+    internal ushort flags;      // (CFLAGSYM_FLAGS)
+    internal string ver;        // Length-prefixed compiler version string
+  };
+
+  [Flags]
+  internal enum COMPILESYM_FLAGS : uint {
+    iLanguage=0x000000ff,   // language index
+    fEC=0x00000100,   // compiled for E/C
+    fNoDbgInfo=0x00000200,   // not compiled with debug info
+    fLTCG=0x00000400,   // compiled with LTCG
+    fNoDataAlign=0x00000800,   // compiled with -Bzalign
+    fManagedPresent=0x00001000,   // managed code/data present
+    fSecurityChecks=0x00002000,   // compiled with /GS
+    fHotPatch=0x00004000,   // compiled with /hotpatch
+    fCVTCIL=0x00008000,   // converted with CVTCIL
+    fMSILModule=0x00010000,   // MSIL netmodule
+  };
+
+  internal struct CompileSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_COMPILE2
+    internal uint flags;      // (COMPILESYM_FLAGS)
+    internal ushort machine;    // target processor
+    internal ushort verFEMajor; // front end major version #
+    internal ushort verFEMinor; // front end minor version #
+    internal ushort verFEBuild; // front end build version #
+    internal ushort verMajor;   // back end major version #
+    internal ushort verMinor;   // back end minor version #
+    internal ushort verBuild;   // back end build version #
+    internal string verSt;      // Length-prefixed compiler version string, followed
+    internal string[] verArgs;    // block of zero terminated strings, ended by double-zero.
+  };
+
+  internal struct ObjNameSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_OBJNAME
+    internal uint signature;  // signature
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct EndArgSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_ENDARG
+  };
+
+  internal struct ReturnSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_RETURN
+    internal CV_GENERIC_FLAG flags; // flags
+    internal byte style;      // CV_GENERIC_STYLE return style
+    // followed by return method data
+  };
+
+  internal struct EntryThisSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_ENTRYTHIS
+    internal byte thissym;    // symbol describing this pointer on entry
+  };
+
+  internal struct BpRelSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_BPREL32
+    internal int off;        // BP-relative offset
+    internal uint typind;     // (type index) Type index or Metadata token
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct FrameRelSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANFRAMEREL | S_ATTR_FRAMEREL
+    internal int off;        // Frame relative offset
+    internal uint typind;     // (type index) Type index or Metadata token
+    internal uint offCod;     // first code address where var is live
+    internal ushort segCod;
+    internal ushort flags;      // (CV_LVARFLAGS)local var flags
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct SlotSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_LOCALSLOT or S_PARAMSLOT
+    internal uint index;      // slot index
+    internal uint typind;     // (type index) Type index or Metadata token
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct AttrSlotSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANSLOT
+    internal uint index;      // slot index
+    internal uint typind;     // (type index) Type index or Metadata token
+    internal uint offCod;     // first code address where var is live
+    internal ushort segCod;
+    internal ushort flags;      // (CV_LVARFLAGS)local var flags
+    internal string name;       // Length-prefixed name
+
+  };
+
+  internal struct AnnotationSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_ANNOTATION
+    internal uint off;
+    internal ushort seg;
+    internal ushort csz;        // Count of zero terminated annotation strings
+    internal string[] rgsz;       // Sequence of zero terminated annotation strings
+  };
+
+  internal struct DatasSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_LDATA32, S_GDATA32 or S_PUB32, S_LMANDATA, S_GMANDATA
+    internal uint typind;     // (type index) Type index, or Metadata token if a managed symbol
+    internal uint off;
+    internal ushort seg;
+    internal string name;       // Length-prefixed name
+  };
+
+  [Flags]
+  internal enum CV_PUBSYMFLAGS : uint {
+    fNone=0,
+    fCode=0x00000001,     // set if internal symbol refers to a code address
+    fFunction=0x00000002,     // set if internal symbol is a function
+    fManaged=0x00000004,     // set if managed code (native or IL)
+    fMSIL=0x00000008,     // set if managed IL code
+  };
+
+  internal struct PubSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_PUB32
+    internal uint flags;      // (CV_PUBSYMFLAGS)
+    internal uint off;
+    internal ushort seg;
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct ProcSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_GPROC32 or S_LPROC32
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint next;       // pointer to next symbol
+    internal uint len;        // Proc length
+    internal uint dbgStart;   // Debug start offset
+    internal uint dbgEnd;     // Debug end offset
+    internal uint typind;     // (type index) Type index
+    internal uint off;
+    internal ushort seg;
+    internal byte flags;      // (CV_PROCFLAGS) Proc flags
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct ManProcSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_GMANPROC, S_LMANPROC, S_GMANPROCIA64 or S_LMANPROCIA64
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint next;       // pointer to next symbol
+    internal uint len;        // Proc length
+    internal uint dbgStart;   // Debug start offset
+    internal uint dbgEnd;     // Debug end offset
+    internal uint token;      // COM+ metadata token for method
+    internal uint off;
+    internal ushort seg;
+    internal byte flags;      // (CV_PROCFLAGS) Proc flags
+    internal ushort retReg;     // Register return value is in (may not be used for all archs)
+    internal string name;       // optional name field
+  };
+
+  internal struct ManProcSymMips {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_GMANPROCMIPS or S_LMANPROCMIPS
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint next;       // pointer to next symbol
+    internal uint len;        // Proc length
+    internal uint dbgStart;   // Debug start offset
+    internal uint dbgEnd;     // Debug end offset
+    internal uint regSave;    // int register save mask
+    internal uint fpSave;     // fp register save mask
+    internal uint intOff;     // int register save offset
+    internal uint fpOff;      // fp register save offset
+    internal uint token;      // COM+ token type
+    internal uint off;
+    internal ushort seg;
+    internal byte retReg;     // Register return value is in
+    internal byte frameReg;   // Frame pointer register
+    internal string name;       // optional name field
+  };
+
+  internal struct ThunkSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_THUNK32
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint next;       // pointer to next symbol
+    internal uint off;
+    internal ushort seg;
+    internal ushort len;        // length of thunk
+    internal byte ord;        // THUNK_ORDINAL specifying type of thunk
+    internal string name;       // Length-prefixed name
+    internal byte[] variant;    // variant portion of thunk
+  };
+
+  internal enum TRAMP {             // Trampoline subtype
+    trampIncremental,           // incremental thunks
+    trampBranchIsland,          // Branch island thunks
+  };
+
+  internal struct TrampolineSym {   // Trampoline thunk symbol
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_TRAMPOLINE
+    internal ushort trampType;  // trampoline sym subtype
+    internal ushort cbThunk;    // size of the thunk
+    internal uint offThunk;   // offset of the thunk
+    internal uint offTarget;  // offset of the target of the thunk
+    internal ushort sectThunk;  // section index of the thunk
+    internal ushort sectTarget; // section index of the target of the thunk
+  };
+
+  internal struct LabelSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_LABEL32
+    internal uint off;
+    internal ushort seg;
+    internal byte flags;      // (CV_PROCFLAGS) flags
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct BlockSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_BLOCK32
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint len;        // Block length
+    internal uint off;        // Offset in code segment
+    internal ushort seg;        // segment of label
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct WithSym32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_WITH32
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint len;        // Block length
+    internal uint off;        // Offset in code segment
+    internal ushort seg;        // segment of label
+    internal string expr;       // Length-prefixed expression string
+  };
+
+  internal struct VpathSym32 {
+    // internal ushort reclen;    // record length
+    // internal ushort rectyp;    // S_VFTABLE32
+    internal uint root;       // (type index) type index of the root of path
+    internal uint path;       // (type index) type index of the path record
+    internal uint off;        // offset of virtual function table
+    internal ushort seg;        // segment of virtual function table
+  };
+
+  internal struct RegRel32 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_REGREL32
+    internal uint off;        // offset of symbol
+    internal uint typind;     // (type index) Type index or metadata token
+    internal ushort reg;        // register index for symbol
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct AttrRegRel {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_MANREGREL | S_ATTR_REGREL
+    internal uint off;        // offset of symbol
+    internal uint typind;     // (type index) Type index or metadata token
+    internal ushort reg;        // register index for symbol
+    internal uint offCod;     // first code address where var is live
+    internal ushort segCod;
+    internal ushort flags;      // (CV_LVARFLAGS)local var flags
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct ThreadSym32 {
+    // internal ushort reclen;    // record length
+    // internal ushort rectyp;    // S_LTHREAD32 | S_GTHREAD32
+    internal uint typind;     // (type index) type index
+    internal uint off;        // offset into thread storage
+    internal ushort seg;        // segment of thread storage
+    internal string name;       // length prefixed name
+  };
+
+  internal struct Slink32 {
+    // internal ushort reclen;    // record length
+    // internal ushort rectyp;    // S_SLINK32
+    internal uint framesize;  // frame size of parent procedure
+    internal int off;        // signed offset where the static link was saved relative to the value of reg
+    internal ushort reg;
+  };
+
+  internal struct ProcSymMips {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_GPROCMIPS or S_LPROCMIPS
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint next;       // pointer to next symbol
+    internal uint len;        // Proc length
+    internal uint dbgStart;   // Debug start offset
+    internal uint dbgEnd;     // Debug end offset
+    internal uint regSave;    // int register save mask
+    internal uint fpSave;     // fp register save mask
+    internal uint intOff;     // int register save offset
+    internal uint fpOff;      // fp register save offset
+    internal uint typind;     // (type index) Type index
+    internal uint off;        // Symbol offset
+    internal ushort seg;        // Symbol segment
+    internal byte retReg;     // Register return value is in
+    internal byte frameReg;   // Frame pointer register
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct ProcSymIa64 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_GPROCIA64 or S_LPROCIA64
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this blocks end
+    internal uint next;       // pointer to next symbol
+    internal uint len;        // Proc length
+    internal uint dbgStart;   // Debug start offset
+    internal uint dbgEnd;     // Debug end offset
+    internal uint typind;     // (type index) Type index
+    internal uint off;        // Symbol offset
+    internal ushort seg;        // Symbol segment
+    internal ushort retReg;     // Register return value is in
+    internal byte flags;      // (CV_PROCFLAGS) Proc flags
+    internal string name;       // Length-prefixed name
+  };
+
+  internal struct RefSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_PROCREF_ST, S_DATAREF_ST, or S_LPROCREF_ST
+    internal uint sumName;    // SUC of the name
+    internal uint ibSym;      // Offset of actual symbol in $$Symbols
+    internal ushort imod;       // Module containing the actual symbol
+    internal ushort usFill;     // align this record
+  };
+
+  internal struct RefSym2 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_PROCREF, S_DATAREF, or S_LPROCREF
+    internal uint sumName;    // SUC of the name
+    internal uint ibSym;      // Offset of actual symbol in $$Symbols
+    internal ushort imod;       // Module containing the actual symbol
+    internal string name;       // hidden name made a first class member
+  };
+
+  internal struct AlignSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_ALIGN
+  };
+
+  internal struct OemSymbol {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_OEM
+    internal Guid idOem;      // an oem ID (GUID)
+    internal uint typind;     // (type index) Type index
+    internal byte[] rgl;        // user data, force 4-byte alignment
+  };
+
+  [Flags]
+  internal enum FRAMEPROCSYM_FLAGS : uint {
+    fHasAlloca=0x00000001,   // function uses _alloca()
+    fHasSetJmp=0x00000002,   // function uses setjmp()
+    fHasLongJmp=0x00000004,   // function uses longjmp()
+    fHasInlAsm=0x00000008,   // function uses inline asm
+    fHasEH=0x00000010,   // function has EH states
+    fInlSpec=0x00000020,   // function was speced as inline
+    fHasSEH=0x00000040,   // function has SEH
+    fNaked=0x00000080,   // function is __declspec(naked)
+    fSecurityChecks=0x00000100,   // function has buffer security check introduced by /GS.
+    fAsyncEH=0x00000200,   // function compiled with /EHa
+    fGSNoStackOrdering=0x00000400,   // function has /GS buffer checks, but stack ordering couldn't be done
+    fWasInlined=0x00000800,   // function was inlined within another function
+  };
+
+  internal struct FrameProcSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_FRAMEPROC
+    internal uint cbFrame;    // count of bytes of total frame of procedure
+    internal uint cbPad;      // count of bytes of padding in the frame
+    internal uint offPad;     // offset (rel to frame) to where padding starts
+    internal uint cbSaveRegs; // count of bytes of callee save registers
+    internal uint offExHdlr;  // offset of exception handler
+    internal ushort secExHdlr;  // section id of exception handler
+    internal uint flags;      // (FRAMEPROCSYM_FLAGS)
+  }
+
+  internal struct UnamespaceSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_UNAMESPACE
+    internal string name;       // name
+  };
+
+  internal struct SepCodSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_SEPCODE
+    internal uint parent;     // pointer to the parent
+    internal uint end;        // pointer to this block's end
+    internal uint length;     // count of bytes of this block
+    internal uint scf;        // (CV_SEPCODEFLAGS) flags
+    internal uint off;        // sec:off of the separated code
+    internal uint offParent;  // secParent:offParent of the enclosing scope
+    internal ushort sec;        //  (proc, block, or sepcode)
+    internal ushort secParent;
+  };
+
+  internal struct LocalSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_LOCAL
+    internal uint id;         // id of the local
+    internal uint typind;     // (type index) type index
+    internal ushort flags;      // (CV_LVARFLAGS) local var flags
+    internal uint idParent;   // This is is parent variable - fIsAggregated or fIsAlias
+    internal uint offParent;  // Offset in parent variable - fIsAggregated
+
+    internal uint expr;       // NI of expression that this temp holds
+    internal uint pad0;       // pad, must be zero
+    internal uint pad1;       // pad, must be zero
+
+    internal string name;       // Name of this symbol.
+  }
+
+  internal struct DefRangeSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_DEFRANGE
+
+    internal uint id;         // ID of the local symbol for which this formula holds
+    internal uint program;    // program to evaluate the value of the symbol
+
+    internal CV_lvar_addr_range range;   // Range of addresses where this program is valid
+  };
+
+  internal struct DefRangeSym2 {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_DEFRANGE2
+
+    internal uint id;         // ID of the local symbol for which this formula holds
+    internal uint program;    // program to evaluate the value of the symbol
+
+    internal ushort count;      // count of CV_lvar_addr_range records following
+    internal CV_lvar_addr_range[] range;// Range of addresses where this program is valid
+  };
+
+  internal struct SectionSym {
+    // internal ushort reclen     // Record length
+    // internal ushort rectyp;    // S_SECTION
+
+    internal ushort isec;       // Section number
+    internal byte align;      // Alignment of this section (power of 2)
+    internal byte bReserved;  // Reserved.  Must be zero.
+    internal uint rva;
+    internal uint cb;
+    internal uint characteristics;
+    internal string name;       // name
+  };
+
+  internal struct CoffGroupSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_COFFGROUP
+
+    internal uint cb;
+    internal uint characteristics;
+    internal uint off;        // Symbol offset
+    internal ushort seg;        // Symbol segment
+    internal string name;       // name
+  };
+
+  [Flags]
+  internal enum EXPORTSYM_FLAGS : ushort {
+    fConstant=0x0001,   // CONSTANT
+    fData=0x0002,   // DATA
+    fPrivate=0x0004,   // PRIVATE
+    fNoName=0x0008,   // NONAME
+    fOrdinal=0x0010,   // Ordinal was explicitly assigned
+    fForwarder=0x0020,   // This is a forwarder
+  }
+
+  internal struct ExportSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_EXPORT
+
+    internal ushort ordinal;
+    internal ushort flags;      // (EXPORTSYM_FLAGS)
+    internal string name;       // name of
+  };
+
+  //
+  // Symbol for describing indirect calls when they are using
+  // a function pointer cast on some other type or temporary.
+  // Typical content will be an LF_POINTER to an LF_PROCEDURE
+  // type record that should mimic an actual variable with the
+  // function pointer type in question.
+  //
+  // Since the compiler can sometimes tail-merge a function call
+  // through a function pointer, there may be more than one
+  // S_CALLSITEINFO record at an address.  This is similar to what
+  // you could do in your own code by:
+  //
+  //  if (expr)
+  //  pfn = &function1;
+  //  else
+  //  pfn = &function2;
+  //
+  //  (*pfn)(arg list);
+  //
+
+  internal struct CallsiteInfo {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_CALLSITEINFO
+    internal int off;        // offset of call site
+    internal ushort ect;        // section index of call site
+    internal ushort pad0;       // alignment padding field, must be zero
+    internal uint typind;     // (type index) type index describing function signature
+  };
+
+  // Frame cookie information
+
+  internal enum CV_cookietype {
+    CV_COOKIETYPE_COPY=0,
+    CV_COOKIETYPE_XOR_SP,
+    CV_COOKIETYPE_XOR_BP,
+    CV_COOKIETYPE_XOR_R13,
+  };
+
+  // Symbol for describing security cookie's position and type
+  // (raw, xor'd with esp, xor'd with ebp).
+
+  internal struct FrameCookie {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_FRAMECOOKIE
+    internal int off;        // Frame relative offset
+    internal ushort reg;        // Register index
+    internal int cookietype; // (CV_cookietype) Type of the cookie
+    internal byte flags;      // Flags describing this cookie
+  };
+
+  internal enum CV_DISCARDED : uint {
+    CV_DISCARDED_UNKNOWN=0,
+    CV_DISCARDED_NOT_SELECTED=1,
+    CV_DISCARDED_NOT_REFERENCED=2,
+  };
+
+  internal struct DiscardedSym {
+    // internal ushort reclen;    // Record length [SYMTYPE]
+    // internal ushort rectyp;    // S_DISCARDED
+    internal CV_DISCARDED iscarded;
+    internal uint fileid;     // First FILEID if line number info present
+    internal uint linenum;    // First line number
+    internal byte[] data;       // Original record(s) with invalid indices
+  };
+
+  //
+  // V7 line number data types
+  //
+
+  internal enum DEBUG_S_SUBSECTION_TYPE : uint {
+    DEBUG_S_IGNORE=0x80000000,   // if this bit is set in a subsection type then ignore the subsection contents
+
+    DEBUG_S_SYMBOLS=0xf1,
+    DEBUG_S_LINES=0xf2,
+    DEBUG_S_STRINGTABLE=0xf3,
+    DEBUG_S_FILECHKSMS=0xf4,
+    DEBUG_S_FRAMEDATA=0xf5,
+  };
+
+  //
+  // Line flags (data present)
+  //
+  internal enum CV_LINE_SUBSECTION_FLAGS : ushort {
+    CV_LINES_HAVE_COLUMNS=0x0001,
+  }
+
+  internal struct CV_LineSection {
+    internal uint off;
+    internal ushort sec;
+    internal ushort flags;
+    internal uint cod;
+  }
+
+  internal struct CV_SourceFile {
+    internal uint index;          // Index to file in checksum section.
+    internal uint count;          // Number of CV_Line records.
+    internal uint linsiz;         // Size of CV_Line recods.
+  }
+
+  [Flags]
+  internal enum CV_Line_Flags : uint {
+    linenumStart=0x00ffffff,   // line where statement/expression starts
+    deltaLineEnd=0x7f000000,   // delta to line where statement ends (optional)
+    fStatement=0x80000000,   // true if a statement linenumber, else an expression line num
+  };
+
+  internal struct CV_Line {
+    internal uint offset;         // Offset to start of code bytes for line number
+    internal uint flags;          // (CV_Line_Flags)
+  };
+
+  internal struct CV_Column {
+    internal ushort offColumnStart;
+    internal ushort offColumnEnd;
+  };
+
+  //  File information
+
+  internal enum CV_FILE_CHECKSUM_TYPE : byte {
+    None=0,
+    MD5=1,
+  };
+
+  internal struct CV_FileCheckSum {
+    internal uint name;           // Index of name in name table.
+    internal byte len;            // Hash length
+    internal byte type;           // Hash type
+  }
+
+  [Flags]
+  internal enum FRAMEDATA_FLAGS : uint {
+    fHasSEH=0x00000001,
+    fHasEH=0x00000002,
+    fIsFunctionStart=0x00000004,
+  };
+
+  internal struct FrameData {
+    internal uint ulRvaStart;
+    internal uint cbBlock;
+    internal uint cbLocals;
+    internal uint cbParams;
+    internal uint cbStkMax;
+    internal uint frameFunc;
+    internal ushort cbProlog;
+    internal ushort cbSavedRegs;
+    internal uint flags;          // (FRAMEDATA_FLAGS)
+  };
+
+  internal struct XFixupData {
+    internal ushort wType;
+    internal ushort wExtra;
+    internal uint rva;
+    internal uint rvaTarget;
+  };
+
+  internal enum DEBUG_S_SUBSECTION {
+    SYMBOLS=0xF1,
+    LINES=0xF2,
+    STRINGTABLE=0xF3,
+    FILECHKSMS=0xF4,
+    FRAMEDATA=0xF5,
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DataStream.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DataStream.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DataStream.cs	(revision 11807)
@@ -0,0 +1,146 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+
+namespace Microsoft.Cci.Pdb {
+  internal class DataStream {
+    internal DataStream() {
+      this.contentSize = 0;
+      this.pages = null;
+    }
+
+    internal DataStream(int contentSize, BitAccess bits, int count) {
+      this.contentSize = contentSize;
+      if (count > 0) {
+        this.pages = new int[count];
+        bits.ReadInt32(this.pages);
+      }
+    }
+
+    internal void Read(PdbReader reader, BitAccess bits) {
+      bits.MinCapacity(contentSize);
+      Read(reader, 0, bits.Buffer, 0, contentSize);
+    }
+
+    internal void Read(PdbReader reader, int position,
+                     byte[] bytes, int offset, int data) {
+      if (position + data > contentSize) {
+        throw new PdbException("DataStream can't read off end of stream. " +
+                                       "(pos={0},siz={1})",
+                               position, data);
+      }
+      if (position == contentSize) {
+        return;
+      }
+
+      int left = data;
+      int page = position / reader.pageSize;
+      int rema = position % reader.pageSize;
+
+      // First get remained of first page.
+      if (rema != 0) {
+        int todo = reader.pageSize - rema;
+        if (todo > left) {
+          todo = left;
+        }
+
+        reader.Seek(pages[page], rema);
+        reader.Read(bytes, offset, todo);
+
+        offset += todo;
+        left -= todo;
+        page++;
+      }
+
+      // Now get the remaining pages.
+      while (left > 0) {
+        int todo = reader.pageSize;
+        if (todo > left) {
+          todo = left;
+        }
+
+        reader.Seek(pages[page], 0);
+        reader.Read(bytes, offset, todo);
+
+        offset += todo;
+        left -= todo;
+        page++;
+      }
+    }
+
+    internal void Write(PdbWriter writer, byte[] bytes) {
+      Write(writer, bytes, bytes.Length);
+    }
+
+    internal void Write(PdbWriter writer, byte[] bytes, int data) {
+      if (bytes == null || data == 0) {
+        return;
+      }
+
+      int left = data;
+      int used = 0;
+      int rema = contentSize % writer.pageSize;
+      if (rema != 0) {
+        int todo = writer.pageSize - rema;
+        if (todo > left) {
+          todo = left;
+        }
+
+        int lastPage = pages[pages.Length - 1];
+        writer.Seek(lastPage, rema);
+        writer.Write(bytes, used, todo);
+        used += todo;
+        left -= todo;
+      }
+
+      if (left > 0) {
+        int count = (left + writer.pageSize - 1) / writer.pageSize;
+        int page0 = writer.AllocatePages(count);
+
+        writer.Seek(page0, 0);
+        writer.Write(bytes, used, left);
+
+        AddPages(page0, count);
+      }
+
+      contentSize += data;
+    }
+
+    private void AddPages(int page0, int count) {
+      if (pages == null) {
+        pages = new int[count];
+        for (int i = 0; i < count; i++) {
+          pages[i] = page0 + i;
+        }
+      } else {
+        int[] old = pages;
+        int used = old.Length;
+
+        pages = new int[used + count];
+        Array.Copy(old, pages, used);
+        for (int i = 0; i < count; i++) {
+          pages[used + i] = page0 + i;
+        }
+      }
+    }
+
+    internal int Pages {
+      get { return pages == null ? 0 : pages.Length; }
+    }
+
+    internal int Length {
+      get { return contentSize; }
+    }
+
+    internal int GetPage(int index) {
+      return pages[index];
+    }
+
+    internal int contentSize;
+    internal int[] pages;
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiDbgHdr.cs	(revision 11807)
@@ -0,0 +1,36 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal struct DbiDbgHdr {
+    internal DbiDbgHdr(BitAccess bits) {
+      bits.ReadUInt16(out snFPO);
+      bits.ReadUInt16(out snException);
+      bits.ReadUInt16(out snFixup);
+      bits.ReadUInt16(out snOmapToSrc);
+      bits.ReadUInt16(out snOmapFromSrc);
+      bits.ReadUInt16(out snSectionHdr);
+      bits.ReadUInt16(out snTokenRidMap);
+      bits.ReadUInt16(out snXdata);
+      bits.ReadUInt16(out snPdata);
+      bits.ReadUInt16(out snNewFPO);
+      bits.ReadUInt16(out snSectionHdrOrig);
+    }
+
+    internal ushort snFPO;                 // 0..1
+    internal ushort snException;           // 2..3 (deprecated)
+    internal ushort snFixup;               // 4..5
+    internal ushort snOmapToSrc;           // 6..7
+    internal ushort snOmapFromSrc;         // 8..9
+    internal ushort snSectionHdr;          // 10..11
+    internal ushort snTokenRidMap;         // 12..13
+    internal ushort snXdata;               // 14..15
+    internal ushort snPdata;               // 16..17
+    internal ushort snNewFPO;              // 18..19
+    internal ushort snSectionHdrOrig;      // 20..21
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiHeader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiHeader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiHeader.cs	(revision 11807)
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal struct DbiHeader {
+    internal DbiHeader(BitAccess bits) {
+      bits.ReadInt32(out sig);
+      bits.ReadInt32(out ver);
+      bits.ReadInt32(out age);
+      bits.ReadInt16(out gssymStream);
+      bits.ReadUInt16(out vers);
+      bits.ReadInt16(out pssymStream);
+      bits.ReadUInt16(out pdbver);
+      bits.ReadInt16(out symrecStream);
+      bits.ReadUInt16(out pdbver2);
+      bits.ReadInt32(out gpmodiSize);
+      bits.ReadInt32(out secconSize);
+      bits.ReadInt32(out secmapSize);
+      bits.ReadInt32(out filinfSize);
+      bits.ReadInt32(out tsmapSize);
+      bits.ReadInt32(out mfcIndex);
+      bits.ReadInt32(out dbghdrSize);
+      bits.ReadInt32(out ecinfoSize);
+      bits.ReadUInt16(out flags);
+      bits.ReadUInt16(out machine);
+      bits.ReadInt32(out reserved);
+    }
+
+    internal int sig;                        // 0..3
+    internal int ver;                        // 4..7
+    internal int age;                        // 8..11
+    internal short gssymStream;                // 12..13
+    internal ushort vers;                       // 14..15
+    internal short pssymStream;                // 16..17
+    internal ushort pdbver;                     // 18..19
+    internal short symrecStream;               // 20..21
+    internal ushort pdbver2;                    // 22..23
+    internal int gpmodiSize;                 // 24..27
+    internal int secconSize;                 // 28..31
+    internal int secmapSize;                 // 32..35
+    internal int filinfSize;                 // 36..39
+    internal int tsmapSize;                  // 40..43
+    internal int mfcIndex;                   // 44..47
+    internal int dbghdrSize;                 // 48..51
+    internal int ecinfoSize;                 // 52..55
+    internal ushort flags;                      // 56..57
+    internal ushort machine;                    // 58..59
+    internal int reserved;                   // 60..63
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiModuleInfo.cs	(revision 11807)
@@ -0,0 +1,52 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal class DbiModuleInfo {
+    internal DbiModuleInfo(BitAccess bits, bool readStrings) {
+      bits.ReadInt32(out opened);
+      section = new DbiSecCon(bits);
+      bits.ReadUInt16(out flags);
+      bits.ReadInt16(out stream);
+      bits.ReadInt32(out cbSyms);
+      bits.ReadInt32(out cbOldLines);
+      bits.ReadInt32(out cbLines);
+      bits.ReadInt16(out files);
+      bits.ReadInt16(out pad1);
+      bits.ReadUInt32(out offsets);
+      bits.ReadInt32(out niSource);
+      bits.ReadInt32(out niCompiler);
+      if (readStrings) {
+        bits.ReadCString(out moduleName);
+        bits.ReadCString(out objectName);
+      } else {
+        bits.SkipCString(out moduleName);
+        bits.SkipCString(out objectName);
+      }
+      bits.Align(4);
+      //if (opened != 0 || pad1 != 0) {
+      //  throw new PdbException("Invalid DBI module. "+
+      //                                 "(opened={0}, pad={1})", opened, pad1);
+      //}
+    }
+
+    internal int opened;                 //  0..3
+    internal DbiSecCon section;                //  4..31
+    internal ushort flags;                  // 32..33
+    internal short stream;                 // 34..35
+    internal int cbSyms;                 // 36..39
+    internal int cbOldLines;             // 40..43
+    internal int cbLines;                // 44..57
+    internal short files;                  // 48..49
+    internal short pad1;                   // 50..51
+    internal uint offsets;
+    internal int niSource;
+    internal int niCompiler;
+    internal string moduleName;
+    internal string objectName;
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiSecCon.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiSecCon.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/DbiSecCon.cs	(revision 11807)
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal struct DbiSecCon {
+    internal DbiSecCon(BitAccess bits) {
+      bits.ReadInt16(out section);
+      bits.ReadInt16(out pad1);
+      bits.ReadInt32(out offset);
+      bits.ReadInt32(out size);
+      bits.ReadUInt32(out flags);
+      bits.ReadInt16(out module);
+      bits.ReadInt16(out pad2);
+      bits.ReadUInt32(out dataCrc);
+      bits.ReadUInt32(out relocCrc);
+      //if (pad1 != 0 || pad2 != 0) {
+      //  throw new PdbException("Invalid DBI section. "+
+      //                                 "(pad1={0}, pad2={1})",
+      //                         pad1, pad2);
+      //}
+    }
+
+    internal short section;                    // 0..1
+    internal short pad1;                       // 2..3
+    internal int offset;                     // 4..7
+    internal int size;                       // 8..11
+    internal uint flags;                      // 12..15
+    internal short module;                     // 16..17
+    internal short pad2;                       // 18..19
+    internal uint dataCrc;                    // 20..23
+    internal uint relocCrc;                   // 24..27
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/IntHashTable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/IntHashTable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/IntHashTable.cs	(revision 11807)
@@ -0,0 +1,581 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.Collections;
+
+namespace Microsoft.Cci.Pdb {
+  // The IntHashTable class represents a dictionary of associated keys and
+  // values with constant lookup time.
+  //
+  // Objects used as keys in a hashtable must implement the GetHashCode
+  // and Equals methods (or they can rely on the default implementations
+  // inherited from Object if key equality is simply reference
+  // equality). Furthermore, the GetHashCode and Equals methods of
+  // a key object must produce the same results given the same parameters
+  // for the entire time the key is present in the hashtable. In practical
+  // terms, this means that key objects should be immutable, at least for
+  // the time they are used as keys in a hashtable.
+  //
+  // When entries are added to a hashtable, they are placed into
+  // buckets based on the hashcode of their keys. Subsequent lookups of
+  // keys will use the hashcode of the keys to only search a particular
+  // bucket, thus substantially reducing the number of key comparisons
+  // required to find an entry. A hashtable's maximum load factor, which
+  // can be specified when the hashtable is instantiated, determines the
+  // maximum ratio of hashtable entries to hashtable buckets. Smaller load
+  // factors cause faster average lookup times at the cost of increased
+  // memory consumption. The default maximum load factor of 1.0 generally
+  // provides the best balance between speed and size. As entries are added
+  // to a hashtable, the hashtable's actual load factor increases, and when
+  // the actual load factor reaches the maximum load factor value, the
+  // number of buckets in the hashtable is automatically increased by
+  // approximately a factor of two (to be precise, the number of hashtable
+  // buckets is increased to the smallest prime number that is larger than
+  // twice the current number of hashtable buckets).
+  //
+  // Each object provides their own hash function, accessed by calling
+  // GetHashCode().  However, one can write their own object
+  // implementing IHashCodeProvider and pass it to a constructor on
+  // the IntHashTable.  That hash function would be used for all objects in
+  // the table.
+  //
+  // This IntHashTable is implemented to support multiple concurrent readers
+  // and one concurrent writer without using any synchronization primitives.
+  // All read methods essentially must protect themselves from a resize
+  // occuring while they are running.  This was done by enforcing an
+  // ordering on inserts & removes, as well as removing some member variables
+  // and special casing the expand code to work in a temporary array instead
+  // of the live bucket array.  All inserts must set a bucket's value and
+  // key before setting the hash code & collision field.
+  //
+  // By Brian Grunkemeyer, algorithm by Patrick Dussud.
+  // Version 1.30 2/20/2000
+  //| <include path='docs/doc[@for="IntHashTable"]/*' />
+  internal class IntHashTable : IEnumerable {
+    /*
+      Implementation Notes:
+
+      This IntHashTable uses double hashing.  There are hashsize buckets in
+      the table, and each bucket can contain 0 or 1 element.  We a bit to
+      mark whether there's been a collision when we inserted multiple
+      elements (ie, an inserted item was hashed at least a second time and
+      we probed this bucket, but it was already in use).  Using the
+      collision bit, we can terminate lookups & removes for elements that
+      aren't in the hash table more quickly.  We steal the most
+      significant bit from the hash code to store the collision bit.
+
+      Our hash function is of the following form:
+
+      h(key, n) = h1(key) + n*h2(key)
+
+      where n is the number of times we've hit a collided bucket and
+      rehashed (on this particular lookup).  Here are our hash functions:
+
+      h1(key) = GetHash(key);  // default implementation calls key.GetHashCode();
+      h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1));
+
+      The h1 can return any number.  h2 must return a number between 1 and
+      hashsize - 1 that is relatively prime to hashsize (not a problem if
+      hashsize is prime).  (Knuth's Art of Computer Programming, Vol. 3,
+      p. 528-9)
+
+      If this is true, then we are guaranteed to visit every bucket in
+      exactly hashsize probes, since the least common multiple of hashsize
+      and h2(key) will be hashsize * h2(key).  (This is the first number
+      where adding h2 to h1 mod hashsize will be 0 and we will search the
+      same bucket twice).
+
+      We previously used a different h2(key, n) that was not constant.
+      That is a horrifically bad idea, unless you can prove that series
+      will never produce any identical numbers that overlap when you mod
+      them by hashsize, for all subranges from i to i+hashsize, for all i.
+      It's not worth investigating, since there was no clear benefit from
+      using that hash function, and it was broken.
+
+      For efficiency reasons, we've implemented this by storing h1 and h2
+      in a temporary, and setting a variable called seed equal to h1.  We
+      do a probe, and if we collided, we simply add h2 to seed each time
+      through the loop.
+
+      A good test for h2() is to subclass IntHashTable, provide your own
+      implementation of GetHash() that returns a constant, then add many
+      items to the hash table.  Make sure Count equals the number of items
+      you inserted.
+
+      -- Brian Grunkemeyer, 10/28/1999
+    */
+
+    // A typical resize algorithm would pick the smallest prime number in this array
+    // that is larger than twice the previous capacity.
+    // Suppose our Hashtable currently has capacity x and enough elements are added
+    // such that a resize needs to occur. Resizing first computes 2x then finds the
+    // first prime in the table greater than 2x, i.e. if primes are ordered
+    // p_1, p_2, 
+, p_i,
+, it finds p_n such that p_n-1 < 2x < p_n.
+    // Doubling is important for preserving the asymptotic complexity of the
+    // hashtable operations such as add.  Having a prime guarantees that double
+    // hashing does not lead to infinite loops.  IE, your hash function will be
+    // h1(key) + i*h2(key), 0 <= i < size.  h2 and the size must be relatively prime.
+    private static readonly int[] primes = {
+            3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,
+            1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
+            17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
+            187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,
+            1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369};
+
+    private int GetPrime(int minSize) {
+      if (minSize < 0) {
+        throw new ArgumentException("Arg_HTCapacityOverflow");
+      }
+      for (int i = 0; i < primes.Length; i++) {
+        int size = primes[i];
+        if (size >= minSize) {
+          return size;
+        }
+      }
+      throw new ArgumentException("Arg_HTCapacityOverflow");
+    }
+
+    // Deleted entries have their key set to buckets
+
+    // The hash table data.
+    // This cannot be serialised
+    private struct bucket {
+      internal int key;
+      internal int hash_coll;   // Store hash code; sign bit means there was a collision.
+      internal Object val;
+    }
+
+    private bucket[] buckets;
+
+    // The total number of entries in the hash table.
+    private int count;
+
+    // The total number of collision bits set in the hashtable
+    private int occupancy;
+
+    private int loadsize;
+    private int loadFactorPerc;    // 100 = 1.0
+
+    private int version;
+
+    // Constructs a new hashtable. The hashtable is created with an initial
+    // capacity of zero and a load factor of 1.0.
+    //| <include path='docs/doc[@for="IntHashTable.IntHashTable"]/*' />
+    internal IntHashTable()
+      : this(0, 100) {
+    }
+
+    // Constructs a new hashtable with the given initial capacity and a load
+    // factor of 1.0. The capacity argument serves as an indication of
+    // the number of entries the hashtable will contain. When this number (or
+    // an approximation) is known, specifying it in the constructor can
+    // eliminate a number of resizing operations that would otherwise be
+    // performed when elements are added to the hashtable.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.IntHashTable1"]/*' />
+    internal IntHashTable(int capacity)
+      : this(capacity, 100) {
+    }
+
+    // Constructs a new hashtable with the given initial capacity and load
+    // factor. The capacity argument serves as an indication of the
+    // number of entries the hashtable will contain. When this number (or an
+    // approximation) is known, specifying it in the constructor can eliminate
+    // a number of resizing operations that would otherwise be performed when
+    // elements are added to the hashtable. The loadFactorPerc argument
+    // indicates the maximum ratio of hashtable entries to hashtable buckets.
+    // Smaller load factors cause faster average lookup times at the cost of
+    // increased memory consumption. A load factor of 1.0 generally provides
+    // the best balance between speed and size.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.IntHashTable3"]/*' />
+    internal IntHashTable(int capacity, int loadFactorPerc) {
+      if (capacity < 0)
+        throw new ArgumentOutOfRangeException("capacity", "ArgumentOutOfRange_NeedNonNegNum");
+      if (!(loadFactorPerc >= 10 && loadFactorPerc <= 100))
+        throw new ArgumentOutOfRangeException("loadFactorPerc", String.Format("ArgumentOutOfRange_IntHashTableLoadFactor", 10, 100));
+
+      // Based on perf work, .72 is the optimal load factor for this table.
+      this.loadFactorPerc = (loadFactorPerc * 72) / 100;
+
+      int hashsize = GetPrime((int)(capacity / this.loadFactorPerc));
+      buckets = new bucket[hashsize];
+
+      loadsize = (int)(this.loadFactorPerc * hashsize) / 100;
+      if (loadsize >= hashsize)
+        loadsize = hashsize-1;
+    }
+
+    // Computes the hash function:  H(key, i) = h1(key) + i*h2(key, hashSize).
+    // The out parameter seed is h1(key), while the out parameter
+    // incr is h2(key, hashSize).  Callers of this function should
+    // add incr each time through a loop.
+    private uint InitHash(int key, int hashsize, out uint seed, out uint incr) {
+      // Hashcode must be positive.  Also, we must not use the sign bit, since
+      // that is used for the collision bit.
+      uint hashcode = (uint)key & 0x7FFFFFFF;
+      seed = (uint)hashcode;
+      // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for
+      // the modular arithmetic to work correctly.  This guarantees you'll
+      // visit every bucket in the table exactly once within hashsize
+      // iterations.  Violate this and it'll cause obscure bugs forever.
+      // If you change this calculation for h2(key), update putEntry too!
+      incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)hashsize - 1)));
+      return hashcode;
+    }
+
+    // Adds an entry with the given key and value to this hashtable. An
+    // ArgumentException is thrown if the key is null or if the key is already
+    // present in the hashtable.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.Add"]/*' />
+    internal void Add(int key, Object value) {
+      Insert(key, value, true);
+    }
+
+    // Removes all entries from this hashtable.
+    //| <include path='docs/doc[@for="IntHashTable.Clear"]/*' />
+    internal void Clear() {
+      if (count == 0)
+        return;
+
+      for (int i = 0; i < buckets.Length; i++) {
+        buckets[i].hash_coll = 0;
+        buckets[i].key = -1;
+        buckets[i].val = null;
+      }
+
+      count = 0;
+      occupancy = 0;
+    }
+
+    // Checks if this hashtable contains an entry with the given key.  This is
+    // an O(1) operation.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.Contains"]/*' />
+    internal bool Contains(int key) {
+      if (key < 0) {
+        throw new ArgumentException("Argument_KeyLessThanZero");
+      }
+
+      uint seed;
+      uint incr;
+      // Take a snapshot of buckets, in case another thread resizes table
+      bucket[] lbuckets = buckets;
+      uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
+      int ntry = 0;
+
+      bucket b;
+      do {
+        int bucketNumber = (int)(seed % (uint)lbuckets.Length);
+        b = lbuckets[bucketNumber];
+        if (b.val == null) {
+          return false;
+        }
+        if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && b.key == key) {
+          return true;
+        }
+        seed += incr;
+      } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
+      return false;
+    }
+
+    // Returns the value associated with the given key. If an entry with the
+    // given key is not found, the returned value is null.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.this"]/*' />
+    internal Object this[int key] {
+      get {
+        if (key < 0) {
+          throw new ArgumentException("Argument_KeyLessThanZero");
+        }
+        uint seed;
+        uint incr;
+        // Take a snapshot of buckets, in case another thread does a resize
+        bucket[] lbuckets = buckets;
+        uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
+        int ntry = 0;
+
+        bucket b;
+        do {
+          int bucketNumber = (int)(seed % (uint)lbuckets.Length);
+          b = lbuckets[bucketNumber];
+          if (b.val == null) {
+            return null;
+          }
+          if (((b.hash_coll & 0x7FFFFFFF) == hashcode) && key == b.key) {
+            return b.val;
+          }
+          seed += incr;
+        } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
+        return null;
+      }
+      set {
+        Insert(key, value, false);
+      }
+    }
+
+    // Increases the bucket count of this hashtable. This method is called from
+    // the Insert method when the actual load factor of the hashtable reaches
+    // the upper limit specified when the hashtable was constructed. The number
+    // of buckets in the hashtable is increased to the smallest prime number
+    // that is larger than twice the current number of buckets, and the entries
+    // in the hashtable are redistributed into the new buckets using the cached
+    // hashcodes.
+    private void expand() {
+      rehash(GetPrime(1+buckets.Length*2));
+    }
+
+    // We occationally need to rehash the table to clean up the collision bits.
+    private void rehash() {
+      rehash(buckets.Length);
+    }
+
+    private void rehash(int newsize) {
+
+      // reset occupancy
+      occupancy=0;
+
+      // Don't replace any internal state until we've finished adding to the
+      // new bucket[].  This serves two purposes:
+      //   1) Allow concurrent readers to see valid hashtable contents
+      //      at all times
+      //   2) Protect against an OutOfMemoryException while allocating this
+      //      new bucket[].
+      bucket[] newBuckets = new bucket[newsize];
+
+      // rehash table into new buckets
+      int nb;
+      for (nb = 0; nb < buckets.Length; nb++) {
+        bucket oldb = buckets[nb];
+        if (oldb.val != null) {
+          putEntry(newBuckets, oldb.key, oldb.val, oldb.hash_coll & 0x7FFFFFFF);
+        }
+      }
+
+      // New bucket[] is good to go - replace buckets and other internal state.
+      version++;
+      buckets = newBuckets;
+      loadsize = (int)(loadFactorPerc * newsize) / 100;
+
+      if (loadsize >= newsize) {
+        loadsize = newsize-1;
+      }
+
+      return;
+    }
+
+    // Returns an enumerator for this hashtable.
+    // If modifications made to the hashtable while an enumeration is
+    // in progress, the MoveNext and Current methods of the
+    // enumerator will throw an exception.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.IEnumerable.GetEnumerator"]/*' />
+    IEnumerator IEnumerable.GetEnumerator() {
+      return new IntHashTableEnumerator(this);
+    }
+
+    // Internal method to compare two keys.
+    //
+    // Inserts an entry into this hashtable. This method is called from the Set
+    // and Add methods. If the add parameter is true and the given key already
+    // exists in the hashtable, an exception is thrown.
+    private void Insert(int key, Object nvalue, bool add) {
+      if (key < 0) {
+        throw new ArgumentException("Argument_KeyLessThanZero");
+      }
+      if (nvalue == null) {
+        throw new ArgumentNullException("nvalue", "ArgumentNull_Value");
+      }
+      if (count >= loadsize) {
+        expand();
+      } else if (occupancy > loadsize && count > 100) {
+        rehash();
+      }
+
+      uint seed;
+      uint incr;
+      // Assume we only have one thread writing concurrently.  Modify
+      // buckets to contain new data, as long as we insert in the right order.
+      uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
+      int ntry = 0;
+      int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots
+      // create by remove that have the collision bit set over using up new slots.
+
+      do {
+        int bucketNumber = (int)(seed % (uint)buckets.Length);
+
+        // Set emptySlot number to current bucket if it is the first available bucket that we have seen
+        // that once contained an entry and also has had a collision.
+        // We need to search this entire collision chain because we have to ensure that there are no
+        // duplicate entries in the table.
+
+        // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry
+        // OR
+        // This bucket once contained an entry but there has never been a collision
+        if (buckets[bucketNumber].val == null) {
+          // If we have found an available bucket that has never had a collision, but we've seen an available
+          // bucket in the past that has the collision bit set, use the previous bucket instead
+          if (emptySlotNumber != -1) { // Reuse slot
+            bucketNumber = emptySlotNumber;
+          }
+
+          // We pretty much have to insert in this order.  Don't set hash
+          // code until the value & key are set appropriately.
+          buckets[bucketNumber].val = nvalue;
+          buckets[bucketNumber].key = key;
+          buckets[bucketNumber].hash_coll |= (int)hashcode;
+          count++;
+          version++;
+          return;
+        }
+
+        // The current bucket is in use
+        // OR
+        // it is available, but has had the collision bit set and we have already found an available bucket
+        if (((buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) &&
+                    key == buckets[bucketNumber].key) {
+          if (add) {
+            throw new ArgumentException("Argument_AddingDuplicate__" + buckets[bucketNumber].key);
+          }
+          buckets[bucketNumber].val = nvalue;
+          version++;
+          return;
+        }
+
+        // The current bucket is full, and we have therefore collided.  We need to set the collision bit
+        // UNLESS
+        // we have remembered an available slot previously.
+        if (emptySlotNumber == -1) {// We don't need to set the collision bit here since we already have an empty slot
+          if (buckets[bucketNumber].hash_coll >= 0) {
+            buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
+            occupancy++;
+          }
+        }
+        seed += incr;
+      } while (++ntry < buckets.Length);
+
+      // This code is here if and only if there were no buckets without a collision bit set in the entire table
+      if (emptySlotNumber != -1) {
+        // We pretty much have to insert in this order.  Don't set hash
+        // code until the value & key are set appropriately.
+        buckets[emptySlotNumber].val = nvalue;
+        buckets[emptySlotNumber].key  = key;
+        buckets[emptySlotNumber].hash_coll |= (int)hashcode;
+        count++;
+        version++;
+        return;
+
+      }
+
+      // If you see this assert, make sure load factor & count are reasonable.
+      // Then verify that our double hash function (h2, described at top of file)
+      // meets the requirements described above. You should never see this assert.
+      throw new InvalidOperationException("InvalidOperation_HashInsertFailed");
+    }
+
+    private void putEntry(bucket[] newBuckets, int key, Object nvalue, int hashcode) {
+      uint seed = (uint)hashcode;
+      uint incr = (uint)(1 + (((seed >> 5) + 1) % ((uint)newBuckets.Length - 1)));
+
+      do {
+        int bucketNumber = (int)(seed % (uint)newBuckets.Length);
+
+        if ((newBuckets[bucketNumber].val == null)) {
+          newBuckets[bucketNumber].val = nvalue;
+          newBuckets[bucketNumber].key = key;
+          newBuckets[bucketNumber].hash_coll |= hashcode;
+          return;
+        }
+
+        if (newBuckets[bucketNumber].hash_coll >= 0) {
+          newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
+          occupancy++;
+        }
+        seed += incr;
+      } while (true);
+    }
+
+    // Returns the number of associations in this hashtable.
+    //
+    //| <include path='docs/doc[@for="IntHashTable.Count"]/*' />
+    internal int Count {
+      get { return count; }
+    }
+
+    // Implements an enumerator for a hashtable. The enumerator uses the
+    // internal version number of the hashtabke to ensure that no modifications
+    // are made to the hashtable while an enumeration is in progress.
+    private class IntHashTableEnumerator : IEnumerator {
+      private IntHashTable hashtable;
+      private int bucket;
+      private int version;
+      private bool current;
+      private int currentKey;
+      private Object currentValue;
+
+      internal IntHashTableEnumerator(IntHashTable hashtable) {
+        this.hashtable = hashtable;
+        bucket = hashtable.buckets.Length;
+        version = hashtable.version;
+        current = false;
+      }
+
+      public bool MoveNext() {
+        if (version != hashtable.version)
+          throw new InvalidOperationException("InvalidOperation_EnumFailedVersion");
+        while (bucket > 0) {
+          bucket--;
+          Object val = hashtable.buckets[bucket].val;
+          if (val != null) {
+            currentKey = hashtable.buckets[bucket].key;
+            currentValue = val;
+            current = true;
+            return true;
+          }
+        }
+        current = false;
+        return false;
+      }
+
+      internal int Key {
+        get {
+          if (current == false)
+            throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen");
+          return currentKey;
+        }
+      }
+
+      public Object Current {
+        get {
+          if (current == false)
+            throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen");
+          return currentValue;
+        }
+      }
+
+      public Object Value {
+        get {
+          if (version != hashtable.version)
+            throw new InvalidOperationException("InvalidOperation_EnumFailedVersion");
+          if (current == false)
+            throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen");
+          return currentValue;
+        }
+      }
+
+      public void Reset() {
+        if (version != hashtable.version) throw new InvalidOperationException("InvalidOperation_EnumFailedVersion");
+        current = false;
+        bucket = hashtable.buckets.Length;
+        currentKey = -1;
+        currentValue = null;
+      }
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/Interfaces.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/Interfaces.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/Interfaces.cs	(revision 11807)
@@ -0,0 +1,77 @@
+using System;
+using System.Collections.Generic;
+
+namespace Microsoft.Cci {
+
+  /// <summary>
+  /// A range of CLR IL operations that comprise a lexical scope, specified as an IL offset and a length.
+  /// </summary>
+  public interface ILocalScope {
+    /// <summary>
+    /// The offset of the first operation in the scope.
+    /// </summary>
+    uint Offset { get; }
+
+    /// <summary>
+    /// The length of the scope. Offset+Length equals the offset of the first operation outside the scope, or equals the method body length.
+    /// </summary>
+    uint Length { get; }
+  }
+
+  /// <summary>
+  /// A description of the lexical scope in which a namespace type has been nested. This scope is tied to a particular
+  /// method body, so that partial types can be accommodated.
+  /// </summary>
+  public interface INamespaceScope {
+
+    /// <summary>
+    /// Zero or more used namespaces. These correspond to using clauses in C#.
+    /// </summary>
+    IEnumerable<IUsedNamespace> UsedNamespaces { get; }
+
+  }
+
+
+  /// <summary>
+  /// A namespace that is used (imported) inside a namespace scope.
+  /// </summary>
+  public interface IUsedNamespace {
+    /// <summary>
+    /// An alias for a namespace. For example the "x" of "using x = y.z;" in C#. Empty if no alias is present.
+    /// </summary>
+    IName Alias { get; }
+
+    /// <summary>
+    /// The name of a namepace that has been aliased.  For example the "y.z" of "using x = y.z;" or "using y.z" in C#.
+    /// </summary>
+    IName NamespaceName { get; }
+  }
+
+  /// <summary>
+  /// The name of an entity. Typically name instances come from a common pool. Within the pool no two distinct instances will have the same Value or UniqueKey.
+  /// </summary>
+  public interface IName {
+    /// <summary>
+    /// An integer that is unique within the pool from which the name instance has been allocated. Useful as a hashtable key.
+    /// </summary>
+    int UniqueKey {
+      get;
+        //^ ensures result > 0;
+    }
+
+    /// <summary>
+    /// An integer that is unique within the pool from which the name instance has been allocated. Useful as a hashtable key.
+    /// All name instances in the pool that have the same string value when ignoring the case of the characters in the string
+    /// will have the same key value.
+    /// </summary>
+    int UniqueKeyIgnoringCase {
+      get;
+      //^ ensures result > 0;
+    }
+
+    /// <summary>
+    /// The string value corresponding to this name.
+    /// </summary>
+    string Value { get; }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/LICENSE
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/LICENSE	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/LICENSE	(revision 11807)
@@ -0,0 +1,22 @@
+Microsoft Public License (Ms-PL)
+
+This license governs use of the accompanying software. If you use the software, you
+accept this license. If you do not accept the license, do not use the software.
+
+1. Definitions
+The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
+same meaning here as under U.S. copyright law.
+A "contribution" is the original software, or any additions or changes to the software.
+A "contributor" is any person that distributes its contribution under this license.
+"Licensed patents" are a contributor's patent claims that read directly on its contribution.
+
+2. Grant of Rights
+(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
+(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
+
+3. Conditions and Limitations
+(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
+(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
+(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
+(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
+(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/MsfDirectory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/MsfDirectory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/MsfDirectory.cs	(revision 11807)
@@ -0,0 +1,45 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal class MsfDirectory {
+    internal MsfDirectory(PdbReader reader, PdbFileHeader head, BitAccess bits) {
+      bits.MinCapacity(head.directorySize);
+      int pages = reader.PagesFromSize(head.directorySize);
+
+      // 0..n in page of directory pages.
+      reader.Seek(head.directoryRoot, 0);
+      bits.FillBuffer(reader.reader, pages * 4);
+
+      DataStream stream = new DataStream(head.directorySize, bits, pages);
+      bits.MinCapacity(head.directorySize);
+      stream.Read(reader, bits);
+
+      // 0..3 in directory pages
+      int count;
+      bits.ReadInt32(out count);
+
+      // 4..n
+      int[] sizes = new int[count];
+      bits.ReadInt32(sizes);
+
+      // n..m
+      streams = new DataStream[count];
+      for (int i = 0; i < count; i++) {
+        if (sizes[i] <= 0) {
+          streams[i] = new DataStream();
+        } else {
+          streams[i] = new DataStream(sizes[i], bits,
+                                      reader.PagesFromSize(sizes[i]));
+        }
+      }
+    }
+
+    internal DataStream[] streams;
+  }
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbConstant.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbConstant.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbConstant.cs	(revision 11807)
@@ -0,0 +1,79 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.Runtime.InteropServices;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbConstant {
+    internal string name;
+    internal uint token;
+    internal object value;
+
+    internal PdbConstant(BitAccess bits) {
+      bits.ReadUInt32(out this.token);
+      byte tag1;
+      bits.ReadUInt8(out tag1);
+      byte tag2;
+      bits.ReadUInt8(out tag2);
+      if (tag2 == 0) {
+        this.value = tag1;
+      } else if (tag2 == 0x80) {
+        switch (tag1) {
+          case 0x01: //short
+            short s;
+            bits.ReadInt16(out s);
+            this.value = s;
+            break;
+          case 0x02: //ushort
+            ushort us;
+            bits.ReadUInt16(out us);
+            this.value = us;
+            break;
+          case 0x03: //int
+            int i;
+            bits.ReadInt32(out i);
+            this.value = i;
+            break;
+          case 0x04: //uint
+            uint ui;
+            bits.ReadUInt32(out ui);
+            this.value = ui;
+            break;
+          case 0x05: //float
+            this.value = bits.ReadFloat();
+            break;
+          case 0x06: //double
+            this.value = bits.ReadDouble();
+            break;
+          case 0x09: //long
+            long sl;
+            bits.ReadInt64(out sl);
+            this.value = sl;
+            break;
+          case 0x0a: //ulong
+            ulong ul;
+            bits.ReadUInt64(out ul);
+            this.value = ul;
+            break;
+          case 0x10: //string
+            string str;
+            bits.ReadBString(out str);
+            this.value = str;
+            break;
+          case 0x19: //decimal
+            this.value = bits.ReadDecimal();
+            break;
+          default:
+            //TODO: error
+            break;
+        }
+      } else {
+        //TODO: error
+      }
+      bits.ReadCString(out name);
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbDebugException.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbDebugException.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbDebugException.cs	(revision 11807)
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbDebugException : IOException {
+    internal PdbDebugException(String format, params object[] args)
+      : base(String.Format(format, args)) {
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbException.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbException.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbException.cs	(revision 11807)
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbException : IOException {
+    internal PdbException(String format, params object[] args)
+      : base(String.Format(format, args)) {
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFile.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFile.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFile.cs	(revision 11807)
@@ -0,0 +1,421 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Diagnostics.SymbolStore;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbFile {
+    private PdbFile()   // This class can't be instantiated.
+    {
+    }
+
+    static void LoadGuidStream(BitAccess bits, out Guid doctype, out Guid language, out Guid vendor) {
+      bits.ReadGuid(out language);
+      bits.ReadGuid(out vendor);
+      bits.ReadGuid(out doctype);
+    }
+
+    static Dictionary<string,int> LoadNameIndex(BitAccess bits, out int age, out Guid guid) {
+      Dictionary<string, int> result = new Dictionary<string, int>();
+      int ver;
+      int sig;
+      bits.ReadInt32(out ver);    //  0..3  Version
+      bits.ReadInt32(out sig);    //  4..7  Signature
+      bits.ReadInt32(out age);    //  8..11 Age
+      bits.ReadGuid(out guid);       // 12..27 GUID
+
+      if (ver != 20000404) {
+        throw new PdbDebugException("Unsupported PDB Stream version {0}", ver);
+      }
+
+      // Read string buffer.
+      int buf;
+      bits.ReadInt32(out buf);    // 28..31 Bytes of Strings
+
+      int beg = bits.Position;
+      int nxt = bits.Position + buf;
+
+      bits.Position = nxt;
+
+      // Read map index.
+      int cnt;        // n+0..3 hash size.
+      int max;        // n+4..7 maximum ni.
+
+      bits.ReadInt32(out cnt);
+      bits.ReadInt32(out max);
+
+      BitSet present = new BitSet(bits);
+      BitSet deleted = new BitSet(bits);
+      if (!deleted.IsEmpty) {
+        throw new PdbDebugException("Unsupported PDB deleted bitset is not empty.");
+      }
+
+      int j = 0;
+      for (int i = 0; i < max; i++) {
+        if (present.IsSet(i)) {
+          int ns;
+          int ni;
+          bits.ReadInt32(out ns);
+          bits.ReadInt32(out ni);
+
+          string name;
+          int saved = bits.Position;
+          bits.Position = beg + ns;
+          bits.ReadCString(out name);
+          bits.Position = saved;
+
+          result.Add(name, ni);
+          j++;
+        }
+      }
+      if (j != cnt) {
+        throw new PdbDebugException("Count mismatch. ({0} != {1})", j, cnt);
+      }
+      return result;
+    }
+
+    static IntHashTable LoadNameStream(BitAccess bits) {
+      IntHashTable ht = new IntHashTable();
+
+      uint sig;
+      int ver;
+      bits.ReadUInt32(out sig);   //  0..3  Signature
+      bits.ReadInt32(out ver);    //  4..7  Version
+
+      // Read (or skip) string buffer.
+      int buf;
+      bits.ReadInt32(out buf);    //  8..11 Bytes of Strings
+
+      if (sig != 0xeffeeffe || ver != 1) {
+        throw new PdbDebugException("Unsupported Name Stream version. "+
+                                            "(sig={0:x8}, ver={1})",
+                                    sig, ver);
+      }
+      int beg = bits.Position;
+      int nxt = bits.Position + buf;
+      bits.Position = nxt;
+
+      // Read hash table.
+      int siz;
+      bits.ReadInt32(out siz);    // n+0..3 Number of hash buckets.
+      nxt = bits.Position;
+
+      for (int i = 0; i < siz; i++) {
+        int ni;
+        string name;
+
+        bits.ReadInt32(out ni);
+
+        if (ni != 0) {
+          int saved = bits.Position;
+          bits.Position = beg + ni;
+          bits.ReadCString(out name);
+          bits.Position = saved;
+
+          ht.Add(ni, name);
+        }
+      }
+      bits.Position = nxt;
+
+      return ht;
+    }
+
+    private static PdbFunction match = new PdbFunction();
+
+    private static PdbFunction FindFunction(PdbFunction[] funcs, ushort sec, uint off) {
+      match.segment = sec;
+      match.address = off;
+
+      int item = Array.BinarySearch(funcs, match, PdbFunction.byAddress);
+      if (item >= 0) {
+        return funcs[item];
+      }
+      return null;
+    }
+
+    static void LoadManagedLines(PdbFunction[] funcs,
+                                 IntHashTable names,
+                                 BitAccess bits,
+                                 MsfDirectory dir,
+                                 Dictionary<string, int> nameIndex,
+                                 PdbReader reader,
+                                 uint limit) {
+      Array.Sort(funcs, PdbFunction.byAddress);
+      IntHashTable checks = new IntHashTable();
+
+      // Read the files first
+      int begin = bits.Position;
+      while (bits.Position < limit) {
+        int sig;
+        int siz;
+        bits.ReadInt32(out sig);
+        bits.ReadInt32(out siz);
+        int place = bits.Position;
+        int endSym = bits.Position + siz;
+
+        switch ((DEBUG_S_SUBSECTION)sig) {
+          case DEBUG_S_SUBSECTION.FILECHKSMS:
+            while (bits.Position < endSym) {
+              CV_FileCheckSum chk;
+
+              int ni = bits.Position - place;
+              bits.ReadUInt32(out chk.name);
+              bits.ReadUInt8(out chk.len);
+              bits.ReadUInt8(out chk.type);
+
+              string name = (string)names[(int)chk.name];
+              int guidStream;
+              Guid doctypeGuid = SymDocumentType.Text;
+              Guid languageGuid = SymLanguageType.CSharp;
+              Guid vendorGuid = SymLanguageVendor.Microsoft;
+              if (nameIndex.TryGetValue("/src/files/"+name, out guidStream)) {
+                var guidBits = new BitAccess(0x100);
+                dir.streams[guidStream].Read(reader, guidBits);
+                LoadGuidStream(guidBits, out doctypeGuid, out languageGuid, out vendorGuid);
+              }
+
+              PdbSource src = new PdbSource((uint)ni, name, doctypeGuid, languageGuid, vendorGuid);
+              checks.Add(ni, src);
+              bits.Position += chk.len;
+              bits.Align(4);
+            }
+            bits.Position = endSym;
+            break;
+
+          default:
+            bits.Position = endSym;
+            break;
+        }
+      }
+
+      // Read the lines next.
+      bits.Position = begin;
+      while (bits.Position < limit) {
+        int sig;
+        int siz;
+        bits.ReadInt32(out sig);
+        bits.ReadInt32(out siz);
+        int endSym = bits.Position + siz;
+
+        switch ((DEBUG_S_SUBSECTION)sig) {
+          case DEBUG_S_SUBSECTION.LINES: {
+              CV_LineSection sec;
+
+              bits.ReadUInt32(out sec.off);
+              bits.ReadUInt16(out sec.sec);
+              bits.ReadUInt16(out sec.flags);
+              bits.ReadUInt32(out sec.cod);
+              PdbFunction func = FindFunction(funcs, sec.sec, sec.off);
+              if (func == null) break;
+
+              // Count the line blocks.
+              int begSym = bits.Position;
+              int blocks = 0;
+              while (bits.Position < endSym) {
+                CV_SourceFile file;
+                bits.ReadUInt32(out file.index);
+                bits.ReadUInt32(out file.count);
+                bits.ReadUInt32(out file.linsiz);   // Size of payload.
+                int linsiz = (int)file.count * (8 + ((sec.flags & 1) != 0 ? 4 : 0));
+                bits.Position += linsiz;
+                blocks++;
+              }
+
+              func.lines = new PdbLines[blocks];
+              int block = 0;
+
+              bits.Position = begSym;
+              while (bits.Position < endSym) {
+                CV_SourceFile file;
+                bits.ReadUInt32(out file.index);
+                bits.ReadUInt32(out file.count);
+                bits.ReadUInt32(out file.linsiz);   // Size of payload.
+
+                PdbSource src = (PdbSource)checks[(int)file.index];
+                PdbLines tmp = new PdbLines(src, file.count);
+                func.lines[block++] = tmp;
+                PdbLine[] lines = tmp.lines;
+
+                int plin = bits.Position;
+                int pcol = bits.Position + 8 * (int)file.count;
+
+                for (int i = 0; i < file.count; i++) {
+                  CV_Line line;
+                  CV_Column column = new CV_Column();
+
+                  bits.Position = plin + 8 * i;
+                  bits.ReadUInt32(out line.offset);
+                  bits.ReadUInt32(out line.flags);
+
+                  uint lineBegin = line.flags & (uint)CV_Line_Flags.linenumStart;
+                  uint delta = (line.flags & (uint)CV_Line_Flags.deltaLineEnd) >> 24;
+                  bool statement = ((line.flags & (uint)CV_Line_Flags.fStatement) == 0);
+                  if ((sec.flags & 1) != 0) {
+                    bits.Position = pcol + 4 * i;
+                    bits.ReadUInt16(out column.offColumnStart);
+                    bits.ReadUInt16(out column.offColumnEnd);
+                  }
+
+                  lines[i] = new PdbLine(line.offset,
+                                         lineBegin,
+                                         column.offColumnStart,
+                                         lineBegin+delta,
+                                         column.offColumnEnd);
+                }
+              }
+              break;
+            }
+        }
+        bits.Position = endSym;
+      }
+    }
+
+    static void LoadFuncsFromDbiModule(BitAccess bits,
+                                       DbiModuleInfo info,
+                                       IntHashTable names,
+                                       ArrayList funcList,
+                                       bool readStrings,
+                                       MsfDirectory dir,
+                                       Dictionary<string, int> nameIndex,
+                                       PdbReader reader) {
+      PdbFunction[] funcs = null;
+
+      bits.Position = 0;
+      int sig;
+      bits.ReadInt32(out sig);
+      if (sig != 4) {
+        throw new PdbDebugException("Invalid signature. (sig={0})", sig);
+      }
+
+      bits.Position = 4;
+      // Console.WriteLine("{0}:", info.moduleName);
+      funcs = PdbFunction.LoadManagedFunctions(info.moduleName,
+                                               bits, (uint)info.cbSyms,
+                                               readStrings);
+      if (funcs != null) {
+        bits.Position = info.cbSyms + info.cbOldLines;
+        LoadManagedLines(funcs, names, bits, dir, nameIndex, reader,
+                         (uint)(info.cbSyms + info.cbOldLines + info.cbLines));
+
+        for (int i = 0; i < funcs.Length; i++) {
+          funcList.Add(funcs[i]);
+        }
+      }
+    }
+
+    static void LoadDbiStream(BitAccess bits,
+                              out DbiModuleInfo[] modules,
+                              out DbiDbgHdr header,
+                              bool readStrings) {
+      DbiHeader dh = new DbiHeader(bits);
+      header = new DbiDbgHdr();
+
+      if (dh.sig != -1 || dh.ver != 19990903) {
+        throw new PdbException("Unsupported DBI Stream version, sig={0}, ver={1}",
+                               dh.sig, dh.ver);
+      }
+
+      // Read gpmod section.
+      ArrayList modList = new ArrayList();
+      int end = bits.Position + dh.gpmodiSize;
+      while (bits.Position < end) {
+        DbiModuleInfo mod = new DbiModuleInfo(bits, readStrings);
+        modList.Add(mod);
+      }
+      if (bits.Position != end) {
+        throw new PdbDebugException("Error reading DBI stream, pos={0} != {1}",
+                                    bits.Position, end);
+      }
+
+      if (modList.Count > 0) {
+        modules = (DbiModuleInfo[])modList.ToArray(typeof(DbiModuleInfo));
+      } else {
+        modules = null;
+      }
+
+      // Skip the Section Contribution substream.
+      bits.Position += dh.secconSize;
+
+      // Skip the Section Map substream.
+      bits.Position += dh.secmapSize;
+
+      // Skip the File Info substream.
+      bits.Position += dh.filinfSize;
+
+      // Skip the TSM substream.
+      bits.Position += dh.tsmapSize;
+
+      // Skip the EC substream.
+      bits.Position += dh.ecinfoSize;
+
+      // Read the optional header.
+      end = bits.Position + dh.dbghdrSize;
+      if (dh.dbghdrSize > 0) {
+        header = new DbiDbgHdr(bits);
+      }
+      bits.Position = end;
+    }
+
+    internal static PdbFunction[] LoadFunctions(Stream read, bool readAllStrings, out int age, out Guid guid) {
+      BitAccess bits = new BitAccess(512 * 1024);
+      return LoadFunctions(read, bits, readAllStrings, out age, out guid);
+    }
+
+    internal static PdbFunction[] LoadFunctions(Stream read, BitAccess bits, bool readAllStrings, out int age, out Guid guid) {
+      PdbFileHeader head = new PdbFileHeader(read, bits);
+      PdbReader reader = new PdbReader(read, head.pageSize);
+      MsfDirectory dir = new MsfDirectory(reader, head, bits);
+      DbiModuleInfo[] modules = null;
+      DbiDbgHdr header;
+
+      dir.streams[1].Read(reader, bits);
+      Dictionary<string, int> nameIndex = LoadNameIndex(bits, out age, out guid);
+      int nameStream;
+      if (!nameIndex.TryGetValue("/names", out nameStream)) {
+        throw new PdbException("No `name' stream");
+      }
+
+      dir.streams[nameStream].Read(reader, bits);
+      IntHashTable names = LoadNameStream(bits);
+
+      dir.streams[3].Read(reader, bits);
+      LoadDbiStream(bits, out modules, out header, readAllStrings);
+
+      ArrayList funcList = new ArrayList();
+
+      if (modules != null) {
+        for (int m = 0; m < modules.Length; m++) {
+          if (modules[m].stream > 0) {
+            dir.streams[modules[m].stream].Read(reader, bits);
+            LoadFuncsFromDbiModule(bits, modules[m], names, funcList,
+                                   readAllStrings, dir, nameIndex, reader);
+          }
+        }
+      }
+
+      PdbFunction[] funcs = (PdbFunction[])funcList.ToArray(typeof(PdbFunction));
+
+      // After reading the functions, apply the token remapping table if it exists.
+      if (header.snTokenRidMap != 0 && header.snTokenRidMap != 0xffff) {
+        dir.streams[header.snTokenRidMap].Read(reader, bits);
+        uint[] ridMap = new uint[dir.streams[header.snTokenRidMap].Length / 4];
+        bits.ReadUInt32(ridMap);
+
+        foreach (PdbFunction func in funcs) {
+          func.token = 0x06000000 | ridMap[func.token & 0xffffff];
+        }
+      }
+
+      //
+      Array.Sort(funcs, PdbFunction.byAddress);
+      //Array.Sort(funcs, PdbFunction.byToken);
+      return funcs;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFileHeader.cs	(revision 11807)
@@ -0,0 +1,82 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+using System.Text;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbFileHeader {
+    internal PdbFileHeader(int pageSize) {
+      this.magic = new byte[32] {
+                0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, // "Microsof"
+                0x74, 0x20, 0x43, 0x2F, 0x43, 0x2B, 0x2B, 0x20, // "t C/C++ "
+                0x4D, 0x53, 0x46, 0x20, 0x37, 0x2E, 0x30, 0x30, // "MSF 7.00"
+                0x0D, 0x0A, 0x1A, 0x44, 0x53, 0x00, 0x00, 0x00  // "^^^DS^^^"
+            };
+      this.pageSize = pageSize;
+      this.zero = 0;
+    }
+
+    internal PdbFileHeader(Stream reader, BitAccess bits) {
+      bits.MinCapacity(56);
+      reader.Seek(0, SeekOrigin.Begin);
+      bits.FillBuffer(reader, 56);
+
+      this.magic = new byte[32];
+      bits.ReadBytes(this.magic);                 //   0..31
+      bits.ReadInt32(out this.pageSize);          //  32..35
+      bits.ReadInt32(out this.freePageMap);       //  36..39
+      bits.ReadInt32(out this.pagesUsed);         //  40..43
+      bits.ReadInt32(out this.directorySize);     //  44..47
+      bits.ReadInt32(out this.zero);              //  48..51
+      bits.ReadInt32(out this.directoryRoot);     //  52..55
+    }
+
+    internal string Magic {
+      get { return StringFromBytesUTF8(magic); }
+    }
+
+    internal void Write(Stream writer, BitAccess bits) {
+      bits.MinCapacity(56);
+      bits.WriteBytes(magic);                     //   0..31
+      bits.WriteInt32(pageSize);                  //  32..35
+      bits.WriteInt32(freePageMap);               //  36..39
+      bits.WriteInt32(pagesUsed);                 //  40..43
+      bits.WriteInt32(directorySize);             //  44..47
+      bits.WriteInt32(zero);                      //  48..51
+      bits.WriteInt32(directoryRoot);             //  52..55
+
+      writer.Seek(0, SeekOrigin.Begin);
+      bits.WriteBuffer(writer, 56);
+    }
+
+    //////////////////////////////////////////////////// Helper Functions.
+    //
+    internal string StringFromBytesUTF8(byte[] bytes) {
+      return StringFromBytesUTF8(bytes, 0, bytes.Length);
+    }
+
+    internal string StringFromBytesUTF8(byte[] bytes, int offset, int length) {
+      for (int i = 0; i < length; i++) {
+        if (bytes[offset + i] < ' ') {
+          length = i;
+        }
+      }
+      return Encoding.UTF8.GetString(bytes, offset, length);
+    }
+
+    ////////////////////////////////////////////////////////////// Fields.
+    //
+    internal readonly byte[] magic;
+    internal readonly int pageSize;
+    internal int freePageMap;
+    internal int pagesUsed;
+    internal int directorySize;
+    internal readonly int zero;
+    internal int directoryRoot;
+  }
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFunction.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFunction.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbFunction.cs	(revision 11807)
@@ -0,0 +1,399 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbFunction {
+    static internal readonly Guid msilMetaData = new Guid(0xc6ea3fc9, 0x59b3, 0x49d6, 0xbc, 0x25,
+                                                        0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60);
+    static internal readonly IComparer byAddress = new PdbFunctionsByAddress();
+    static internal readonly IComparer byToken = new PdbFunctionsByToken();
+
+    internal uint token;
+    internal uint slotToken;
+    internal string name;
+    internal string module;
+    internal ushort flags;
+
+    internal uint segment;
+    internal uint address;
+    internal uint length;
+
+    //internal byte[] metadata;
+    internal PdbScope[] scopes;
+    internal PdbLines[] lines;
+    internal ushort[]/*?*/ usingCounts;
+    internal IEnumerable<INamespaceScope>/*?*/ namespaceScopes;
+    internal string/*?*/ iteratorClass;
+    internal List<ILocalScope>/*?*/ iteratorScopes;
+
+    private static string StripNamespace(string module) {
+      int li = module.LastIndexOf('.');
+      if (li > 0) {
+        return module.Substring(li + 1);
+      }
+      return module;
+    }
+
+
+    internal static PdbFunction[] LoadManagedFunctions(string module,
+                                                       BitAccess bits, uint limit,
+                                                       bool readStrings) {
+      string mod = StripNamespace(module);
+      int begin = bits.Position;
+      int count = 0;
+
+      while (bits.Position < limit) {
+        ushort siz;
+        ushort rec;
+
+        bits.ReadUInt16(out siz);
+        int star = bits.Position;
+        int stop = bits.Position + siz;
+        bits.Position = star;
+        bits.ReadUInt16(out rec);
+
+        switch ((SYM)rec) {
+          case SYM.S_GMANPROC:
+          case SYM.S_LMANPROC:
+            ManProcSym proc;
+            bits.ReadUInt32(out proc.parent);
+            bits.ReadUInt32(out proc.end);
+            bits.Position = (int)proc.end;
+            count++;
+            break;
+
+          case SYM.S_END:
+            bits.Position = stop;
+            break;
+
+          default:
+            //Console.WriteLine("{0,6}: {1:x2} {2}",
+            //                  bits.Position, rec, (SYM)rec);
+            bits.Position = stop;
+            break;
+        }
+      }
+      if (count == 0) {
+        return null;
+      }
+
+      bits.Position = begin;
+      PdbFunction[] funcs = new PdbFunction[count];
+      int func = 0;
+
+      while (bits.Position < limit) {
+        ushort siz;
+        ushort rec;
+
+        bits.ReadUInt16(out siz);
+        int star = bits.Position;
+        int stop = bits.Position + siz;
+        bits.ReadUInt16(out rec);
+
+        switch ((SYM)rec) {
+
+          case SYM.S_GMANPROC:
+          case SYM.S_LMANPROC:
+            ManProcSym proc;
+            int offset = bits.Position;
+
+            bits.ReadUInt32(out proc.parent);
+            bits.ReadUInt32(out proc.end);
+            bits.ReadUInt32(out proc.next);
+            bits.ReadUInt32(out proc.len);
+            bits.ReadUInt32(out proc.dbgStart);
+            bits.ReadUInt32(out proc.dbgEnd);
+            bits.ReadUInt32(out proc.token);
+            bits.ReadUInt32(out proc.off);
+            bits.ReadUInt16(out proc.seg);
+            bits.ReadUInt8(out proc.flags);
+            bits.ReadUInt16(out proc.retReg);
+            if (readStrings) {
+              bits.ReadCString(out proc.name);
+            } else {
+              bits.SkipCString(out proc.name);
+            }
+            //Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name);
+
+            bits.Position = stop;
+            funcs[func++] = new PdbFunction(module, proc, bits);
+            break;
+
+          default: {
+              //throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec);
+              bits.Position = stop;
+              break;
+            }
+        }
+      }
+      return funcs;
+    }
+
+    internal static void CountScopesAndSlots(BitAccess bits, uint limit,
+                                             out int constants, out int scopes, out int slots, out int usedNamespaces) {
+      int pos = bits.Position;
+      BlockSym32 block;
+      constants = 0;
+      slots = 0;
+      scopes = 0;
+      usedNamespaces = 0;
+
+      while (bits.Position < limit) {
+        ushort siz;
+        ushort rec;
+
+        bits.ReadUInt16(out siz);
+        int star = bits.Position;
+        int stop = bits.Position + siz;
+        bits.Position = star;
+        bits.ReadUInt16(out rec);
+
+        switch ((SYM)rec) {
+          case SYM.S_BLOCK32: {
+              bits.ReadUInt32(out block.parent);
+              bits.ReadUInt32(out block.end);
+
+              scopes++;
+              bits.Position = (int)block.end;
+              break;
+            }
+
+          case SYM.S_MANSLOT:
+            slots++;
+            bits.Position = stop;
+            break;
+
+          case SYM.S_UNAMESPACE:
+            usedNamespaces++;
+            bits.Position = stop;
+            break;
+
+          case SYM.S_MANCONSTANT:
+            constants++;
+            bits.Position = stop;
+            break;
+
+          default:
+            bits.Position = stop;
+            break;
+        }
+      }
+      bits.Position = pos;
+    }
+
+    internal PdbFunction() {
+    }
+
+    internal PdbFunction(string module, ManProcSym proc, BitAccess bits) {
+      this.token = proc.token;
+      this.module = module;
+      this.name = proc.name;
+      this.flags = proc.flags;
+      this.segment = proc.seg;
+      this.address = proc.off;
+      this.length = proc.len;
+      this.slotToken = 0;
+
+      if (proc.seg != 1) {
+        throw new PdbDebugException("Segment is {0}, not 1.", proc.seg);
+      }
+      if (proc.parent != 0 || proc.next != 0) {
+        throw new PdbDebugException("Warning parent={0}, next={1}",
+                                    proc.parent, proc.next);
+      }
+      if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
+        throw new PdbDebugException("Warning DBG start={0}, end={1}",
+                                    proc.dbgStart, proc.dbgEnd);
+      }
+
+      int constantCount;
+      int scopeCount;
+      int slotCount;
+      int usedNamespacesCount;
+      CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount);
+      scopes = new PdbScope[scopeCount];
+      int scope = 0;
+
+      while (bits.Position < proc.end) {
+        ushort siz;
+        ushort rec;
+
+        bits.ReadUInt16(out siz);
+        int star = bits.Position;
+        int stop = bits.Position + siz;
+        bits.Position = star;
+        bits.ReadUInt16(out rec);
+
+        switch ((SYM)rec) {
+          case SYM.S_OEM: {          // 0x0404
+              OemSymbol oem;
+
+              bits.ReadGuid(out oem.idOem);
+              bits.ReadUInt32(out oem.typind);
+              // internal byte[]   rgl;        // user data, force 4-byte alignment
+
+              if (oem.idOem == msilMetaData) {
+                string name = bits.ReadString();
+                if (name == "MD2") {
+                  byte version;
+                  bits.ReadUInt8(out version);
+                  if (version == 4) {
+                    byte count;
+                    bits.ReadUInt8(out count);
+                    bits.Align(4);
+                    while (count-- > 0)
+                      this.ReadCustomMetadata(bits);
+                  }
+                }
+                bits.Position = stop;
+                break;
+              } else {
+                throw new PdbDebugException("OEM section: guid={0} ti={1}",
+                                            oem.idOem, oem.typind);
+                // bits.Position = stop;
+              }
+            }
+
+          case SYM.S_BLOCK32: {
+              BlockSym32 block = new BlockSym32();
+
+              bits.ReadUInt32(out block.parent);
+              bits.ReadUInt32(out block.end);
+              bits.ReadUInt32(out block.len);
+              bits.ReadUInt32(out this.address);
+              bits.ReadUInt16(out block.seg);
+              bits.SkipCString(out block.name);
+              bits.Position = stop;
+
+              scopes[scope] = new PdbScope(block, bits, out slotToken);
+              bits.Position = (int)block.end;
+              break;
+            }
+
+          case SYM.S_UNAMESPACE:
+            bits.Position = stop;
+            break;
+
+          case SYM.S_END:
+            bits.Position = stop;
+            break;
+
+          default: {
+              //throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec);
+              bits.Position = stop;
+              break;
+            }
+        }
+      }
+
+      if (bits.Position != proc.end) {
+        throw new PdbDebugException("Not at S_END");
+      }
+
+      ushort esiz;
+      ushort erec;
+      bits.ReadUInt16(out esiz);
+      bits.ReadUInt16(out erec);
+
+      if (erec != (ushort)SYM.S_END) {
+        throw new PdbDebugException("Missing S_END");
+      }
+    }
+
+    private void ReadCustomMetadata(BitAccess bits) {
+      int savedPosition = bits.Position;
+      byte version;
+      bits.ReadUInt8(out version);
+      if (version != 4) {
+        throw new PdbDebugException("Unknown custom metadata item version: {0}", version);
+      }
+      byte kind;
+      bits.ReadUInt8(out kind);
+      bits.Align(4);
+      uint numberOfBytesInItem;
+      bits.ReadUInt32(out numberOfBytesInItem);
+      switch (kind) {
+        case 0: this.ReadUsingInfo(bits); break;
+        case 1: this.ReadForwardInfo(bits); break;
+        case 2: this.ReadForwardedToModuleInfo(bits); break;
+        case 3: this.ReadIteratorLocals(bits); break;
+        case 4: this.ReadForwardIterator(bits); break;
+        default: throw new PdbDebugException("Unknown custom metadata item kind: {0}", kind);
+      }
+      bits.Position = savedPosition+(int)numberOfBytesInItem;
+    }
+
+    private void ReadForwardIterator(BitAccess bits) {
+      this.iteratorClass = bits.ReadString();
+    }
+
+    private void ReadIteratorLocals(BitAccess bits) {
+      uint numberOfLocals;
+      bits.ReadUInt32(out numberOfLocals);
+      this.iteratorScopes = new List<ILocalScope>((int)numberOfLocals);
+      while (numberOfLocals-- > 0) {
+        uint ilStartOffset;
+        uint ilEndOffset;
+        bits.ReadUInt32(out ilStartOffset);
+        bits.ReadUInt32(out ilEndOffset);
+        this.iteratorScopes.Add(new PdbIteratorScope(ilStartOffset, ilEndOffset-ilStartOffset));
+      }
+    }
+
+    private void ReadForwardedToModuleInfo(BitAccess bits) {
+    }
+
+    private void ReadForwardInfo(BitAccess bits) {
+    }
+
+    private void ReadUsingInfo(BitAccess bits) {
+      ushort numberOfNamespaces;
+      bits.ReadUInt16(out numberOfNamespaces);
+      this.usingCounts = new ushort[numberOfNamespaces];
+      for (ushort i = 0; i < numberOfNamespaces; i++) {
+        bits.ReadUInt16(out this.usingCounts[i]);
+      }
+    }
+
+    internal class PdbFunctionsByAddress : IComparer {
+      public int Compare(Object x, Object y) {
+        PdbFunction fx = (PdbFunction)x;
+        PdbFunction fy = (PdbFunction)y;
+
+        if (fx.segment < fy.segment) {
+          return -1;
+        } else if (fx.segment > fy.segment) {
+          return 1;
+        } else if (fx.address < fy.address) {
+          return -1;
+        } else if (fx.address > fy.address) {
+          return 1;
+        } else {
+          return 0;
+        }
+      }
+    }
+
+    internal class PdbFunctionsByToken : IComparer {
+      public int Compare(Object x, Object y) {
+        PdbFunction fx = (PdbFunction)x;
+        PdbFunction fy = (PdbFunction)y;
+
+        if (fx.token < fy.token) {
+          return -1;
+        } else if (fx.token > fy.token) {
+          return 1;
+        } else {
+          return 0;
+        }
+      }
+
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbLine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbLine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbLine.cs	(revision 11807)
@@ -0,0 +1,24 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal struct PdbLine {
+    internal uint offset;
+    internal uint lineBegin;
+    internal uint lineEnd;
+    internal ushort colBegin;
+    internal ushort colEnd;
+
+    internal PdbLine(uint offset, uint lineBegin, ushort colBegin, uint lineEnd, ushort colEnd) {
+      this.offset = offset;
+      this.lineBegin = lineBegin;
+      this.colBegin = colBegin;
+      this.lineEnd = lineEnd;
+      this.colEnd = colEnd;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbLines.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbLines.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbLines.cs	(revision 11807)
@@ -0,0 +1,18 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbLines {
+    internal PdbSource file;
+    internal PdbLine[] lines;
+
+    internal PdbLines(PdbSource file, uint count) {
+      this.file = file;
+      this.lines = new PdbLine[count];
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbReader.cs	(revision 11807)
@@ -0,0 +1,35 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbReader {
+    internal PdbReader(Stream reader, int pageSize) {
+      this.pageSize = pageSize;
+      this.reader = reader;
+    }
+
+    internal void Seek(int page, int offset) {
+      reader.Seek(page * pageSize + offset, SeekOrigin.Begin);
+    }
+
+    internal void Read(byte[] bytes, int offset, int count) {
+      reader.Read(bytes, offset, count);
+    }
+
+    internal int PagesFromSize(int size) {
+      return (size + pageSize - 1) / (pageSize);
+    }
+
+    internal int PageSize {
+      get { return pageSize; }
+    }
+
+    internal readonly int pageSize;
+    internal readonly Stream reader;
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbScope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbScope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbScope.cs	(revision 11807)
@@ -0,0 +1,104 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbScope {
+    internal PdbConstant[] constants;
+    internal PdbSlot[] slots;
+    internal PdbScope[] scopes;
+    internal string[] usedNamespaces;
+
+    internal uint segment;
+    internal uint address;
+    internal uint length;
+
+    internal PdbScope(BlockSym32 block, BitAccess bits, out uint typind) {
+      this.segment = block.seg;
+      this.address = block.off;
+      this.length = block.len;
+      typind = 0;
+
+      int constantCount;
+      int scopeCount;
+      int slotCount;
+      int namespaceCount;
+      PdbFunction.CountScopesAndSlots(bits, block.end, out constantCount, out scopeCount, out slotCount, out namespaceCount);
+      constants = new PdbConstant[constantCount];
+      scopes = new PdbScope[scopeCount];
+      slots = new PdbSlot[slotCount];
+      usedNamespaces = new string[namespaceCount];
+      int constant = 0;
+      int scope = 0;
+      int slot = 0;
+      int usedNs = 0;
+
+      while (bits.Position < block.end) {
+        ushort siz;
+        ushort rec;
+
+        bits.ReadUInt16(out siz);
+        int star = bits.Position;
+        int stop = bits.Position + siz;
+        bits.Position = star;
+        bits.ReadUInt16(out rec);
+
+        switch ((SYM)rec) {
+          case SYM.S_BLOCK32: {
+              BlockSym32 sub = new BlockSym32();
+
+              bits.ReadUInt32(out sub.parent);
+              bits.ReadUInt32(out sub.end);
+              bits.ReadUInt32(out sub.len);
+              bits.ReadUInt32(out sub.off);
+              bits.ReadUInt16(out sub.seg);
+              bits.SkipCString(out sub.name);
+
+              bits.Position = stop;
+              scopes[scope++] = new PdbScope(sub, bits, out typind);
+              break;
+            }
+
+          case SYM.S_MANSLOT:
+            slots[slot++] = new PdbSlot(bits, out typind);
+            bits.Position = stop;
+            break;
+
+          case SYM.S_UNAMESPACE:
+            bits.ReadCString(out usedNamespaces[usedNs++]);
+            bits.Position = stop;
+            break;
+
+          case SYM.S_END:
+            bits.Position = stop;
+            break;
+
+          case SYM.S_MANCONSTANT:
+            constants[constant++] = new PdbConstant(bits);
+            bits.Position = stop;
+            break;
+
+          default:
+            throw new PdbException("Unknown SYM in scope {0}", (SYM)rec);
+          // bits.Position = stop;
+        }
+      }
+
+      if (bits.Position != block.end) {
+        throw new Exception("Not at S_END");
+      }
+
+      ushort esiz;
+      ushort erec;
+      bits.ReadUInt16(out esiz);
+      bits.ReadUInt16(out erec);
+
+      if (erec != (ushort)SYM.S_END) {
+        throw new Exception("Missing S_END");
+      }
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbSlot.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbSlot.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbSlot.cs	(revision 11807)
@@ -0,0 +1,35 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbSlot {
+    internal uint slot;
+    internal string name;
+    internal ushort flags;
+    internal uint segment;
+    internal uint address;
+
+    internal PdbSlot(BitAccess bits, out uint typind) {
+      AttrSlotSym slot;
+
+      bits.ReadUInt32(out slot.index);
+      bits.ReadUInt32(out slot.typind);
+      bits.ReadUInt32(out slot.offCod);
+      bits.ReadUInt16(out slot.segCod);
+      bits.ReadUInt16(out slot.flags);
+      bits.ReadCString(out slot.name);
+
+      this.slot = slot.index;
+      this.name = slot.name;
+      this.flags = slot.flags;
+      this.segment = slot.segCod;
+      this.address = slot.offCod;
+
+      typind = slot.typind;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbSource.cs	(revision 11807)
@@ -0,0 +1,24 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbSource {
+    internal uint index;
+    internal string name;
+    internal Guid doctype;
+    internal Guid language;
+    internal Guid vendor;
+
+    internal PdbSource(uint index, string name, Guid doctype, Guid language, Guid vendor) {
+      this.index = index;
+      this.name = name;
+      this.doctype = doctype;
+      this.language = language;
+      this.vendor = vendor;
+    }
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/PdbWriter.cs	(revision 11807)
@@ -0,0 +1,129 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.IO;
+
+namespace Microsoft.Cci.Pdb {
+  internal class PdbWriter {
+    internal PdbWriter(Stream writer, int pageSize) {
+      this.pageSize = pageSize;
+      this.usedBytes = pageSize * 3;
+      this.writer = writer;
+
+      writer.SetLength(usedBytes);
+    }
+
+    internal void WriteMeta(DataStream[] streams, BitAccess bits) {
+      PdbFileHeader head = new PdbFileHeader(pageSize);
+
+      WriteDirectory(streams,
+                     out head.directoryRoot,
+                     out head.directorySize,
+                     bits);
+      WriteFreeMap();
+
+      head.freePageMap = 2;
+      head.pagesUsed = usedBytes / pageSize;
+
+      writer.Seek(0, SeekOrigin.Begin);
+      head.Write(writer, bits);
+    }
+
+    private void WriteDirectory(DataStream[] streams,
+                                out int directoryRoot,
+                                out int directorySize,
+                                BitAccess bits) {
+      DataStream directory = new DataStream();
+
+      int pages = 0;
+      for (int s = 0; s < streams.Length; s++) {
+        if (streams[s].Length > 0) {
+          pages += streams[s].Pages;
+        }
+      }
+
+      int use = 4 * (1 + streams.Length + pages);
+      bits.MinCapacity(use);
+      bits.WriteInt32(streams.Length);
+      for (int s = 0; s < streams.Length; s++) {
+        bits.WriteInt32(streams[s].Length);
+      }
+      for (int s = 0; s < streams.Length; s++) {
+        if (streams[s].Length > 0) {
+          bits.WriteInt32(streams[s].pages);
+        }
+      }
+      directory.Write(this, bits.Buffer, use);
+      directorySize = directory.Length;
+
+      use = 4 * directory.Pages;
+      bits.MinCapacity(use);
+      bits.WriteInt32(directory.pages);
+
+      DataStream ddir = new DataStream();
+      ddir.Write(this, bits.Buffer, use);
+
+      directoryRoot = ddir.pages[0];
+    }
+
+    private void WriteFreeMap() {
+      byte[] buffer = new byte[pageSize];
+
+      // We configure the old free map with only the first 3 pages allocated.
+      buffer[0] = 0xf8;
+      for (int i = 1; i < pageSize; i++) {
+        buffer[i] = 0xff;
+      }
+      Seek(1, 0);
+      Write(buffer, 0, pageSize);
+
+      // We configure the new free map with all of the used pages gone.
+      int count = usedBytes / pageSize;
+      int full = count / 8;
+      for (int i = 0; i < full; i++) {
+        buffer[i] = 0;
+      }
+      int rema = count % 8;
+      buffer[full] = (byte)(0xff << rema);
+
+      Seek(2, 0);
+      Write(buffer, 0, pageSize);
+    }
+
+    internal int AllocatePages(int count) {
+      int begin = usedBytes;
+
+      usedBytes += count * pageSize;
+      writer.SetLength(usedBytes);
+
+      if (usedBytes > pageSize * pageSize * 8) {
+        throw new Exception("PdbWriter does not support multiple free maps.");
+      }
+      return begin / pageSize;
+    }
+
+    internal void Seek(int page, int offset) {
+      writer.Seek(page * pageSize + offset, SeekOrigin.Begin);
+    }
+
+    internal void Write(byte[] bytes, int offset, int count) {
+      writer.Write(bytes, offset, count);
+    }
+
+    //////////////////////////////////////////////////////////////////////
+    //
+    internal int PageSize {
+      get { return pageSize; }
+    }
+
+    //////////////////////////////////////////////////////////////////////
+    //
+    internal readonly int pageSize;
+    private Stream writer;
+    private int usedBytes;
+  }
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Microsoft.Cci.Pdb/SourceLocationProvider.cs	(revision 11807)
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------------
+//
+// Copyright (C) Microsoft Corporation.  All Rights Reserved.
+//
+//-----------------------------------------------------------------------------
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Microsoft.Cci;
+using Microsoft.Cci.Pdb;
+using System.Text;
+using System.Diagnostics.SymbolStore;
+
+namespace Microsoft.Cci {
+
+  internal sealed class UsedNamespace : IUsedNamespace {
+
+    internal UsedNamespace(IName alias, IName namespaceName) {
+      this.alias = alias;
+      this.namespaceName = namespaceName;
+    }
+
+    public IName Alias {
+      get { return this.alias; }
+    }
+    readonly IName alias;
+
+    public IName NamespaceName {
+      get { return this.namespaceName; }
+    }
+    readonly IName namespaceName;
+
+  }
+
+  internal class NamespaceScope : INamespaceScope {
+
+    internal NamespaceScope(IEnumerable<IUsedNamespace> usedNamespaces) {
+      this.usedNamespaces = usedNamespaces;
+    }
+
+    public IEnumerable<IUsedNamespace> UsedNamespaces {
+      get { return this.usedNamespaces; }
+    }
+    readonly IEnumerable<IUsedNamespace> usedNamespaces;
+
+  }
+
+  internal sealed class PdbIteratorScope : ILocalScope {
+
+    internal PdbIteratorScope(uint offset, uint length) {
+      this.offset = offset;
+      this.length = length;
+    }
+
+    public uint Offset {
+      get { return this.offset; }
+    }
+    uint offset;
+
+    public uint Length {
+      get { return this.length; }
+    }
+    uint length;
+
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ISymUnmanagedDocumentWriter.cs	(revision 11807)
@@ -0,0 +1,41 @@
+// ISymUnmanagedDocumentWriter.cs
+//
+// Author:
+//   Juerg Billeter (j@bitron.ch)
+//
+// (C) 2008 Juerg Billeter
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Runtime.InteropServices;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Pdb {
+
+	[Guid ("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")]
+	[InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]
+	[ComImport]
+	interface ISymUnmanagedDocumentWriter {
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ISymUnmanagedWriter2.cs	(revision 11807)
@@ -0,0 +1,103 @@
+//
+// ISymUnmanagedWriter2.cs
+//
+// Author:
+//   Juerg Billeter (j@bitron.ch)
+//
+// (C) 2008 Juerg Billeter
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Diagnostics.SymbolStore;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.ComTypes;
+
+using Mono.Cecil.Cil;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Pdb {
+
+	[Guid ("0B97726E-9E6D-4f05-9A26-424022093CAA")]
+	[InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]
+	[ComImport]
+	interface ISymUnmanagedWriter2 {
+
+		void DefineDocument (
+			[In, MarshalAs (UnmanagedType.LPWStr)] string url,
+			[In] ref Guid langauge,
+			[In] ref Guid languageVendor,
+			[In] ref Guid documentType,
+			[Out, MarshalAs (UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal);
+		void SetUserEntryPoint ([In] SymbolToken method);
+		void OpenMethod ([In] SymbolToken method);
+		void CloseMethod ();
+		void OpenScope ([In] int startOffset, [Out] out int pRetVal);
+		void CloseScope ([In] int endOffset);
+		void SetScopeRange_Placeholder ();
+		void DefineLocalVariable_Placeholder ();
+		void DefineParameter_Placeholder ();
+		void DefineField_Placeholder ();
+		void DefineGlobalVariable_Placeholder ();
+		void Close ();
+		void SetSymAttribute_Placeholder ();
+		void OpenNamespace ([In, MarshalAs (UnmanagedType.LPWStr)] string name);
+		void CloseNamespace ();
+		void UsingNamespace ([In, MarshalAs (UnmanagedType.LPWStr)] string fullName);
+		void SetMethodSourceRange_Placeholder ();
+		void Initialize (
+			[In, MarshalAs (UnmanagedType.IUnknown)] object emitter,
+			[In, MarshalAs (UnmanagedType.LPWStr)] string filename,
+			[In] IStream pIStream,
+			[In] bool fFullBuild);
+		void GetDebugInfo (
+			[Out] out ImageDebugDirectory pIDD,
+			[In] int cData,
+			[Out] out int pcData,
+			[In, Out, MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 1)] byte [] data);
+		void DefineSequencePoints (
+			[In, MarshalAs (UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document,
+			[In] int spCount,
+			[In, MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 1)] int [] offsets,
+			[In, MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 1)] int [] lines,
+			[In, MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 1)] int [] columns,
+			[In, MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 1)] int [] endLines,
+			[In, MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 1)] int [] endColumns);
+		void RemapToken_Placeholder ();
+		void Initialize2_Placeholder ();
+		void DefineConstant_Placeholder ();
+		void Abort_Placeholder ();
+
+		void DefineLocalVariable2 (
+			[In, MarshalAs (UnmanagedType.LPWStr)] string name,
+			[In] int attributes,
+			[In] SymbolToken sigToken,
+			[In] int addrKind,
+			[In] int addr1,
+			[In] int addr2,
+			[In] int addr3,
+			[In] int startOffset,
+			[In] int endOffset);
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ModuleMetadata.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ModuleMetadata.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/ModuleMetadata.cs	(revision 11807)
@@ -0,0 +1,715 @@
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Pdb {
+
+	[ComImport, InterfaceType (ComInterfaceType.InterfaceIsIUnknown), Guid ("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")]
+	interface IMetaDataEmit {
+		void SetModuleProps (string szName);
+		void Save (string szFile, uint dwSaveFlags);
+		void SaveToStream (IntPtr pIStream, uint dwSaveFlags);
+		uint GetSaveSize (uint fSave);
+		uint DefineTypeDef (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);
+		uint DefineNestedType (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser);
+		void SetHandler ([MarshalAs (UnmanagedType.IUnknown), In]object pUnk);
+		uint DefineMethod (uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags);
+		void DefineMethodImpl (uint td, uint tkBody, uint tkDecl);
+		uint DefineTypeRefByName (uint tkResolutionScope, IntPtr szName);
+		uint DefineImportType (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport,
+		  uint tdImport, IntPtr pAssemEmit);
+		uint DefineMemberRef (uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob);
+		uint DefineImportMember (IntPtr pAssemImport, IntPtr /* void* */ pbHashValue, uint cbHashValue,
+		  IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent);
+		uint DefineEvent (uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr /* uint* */ rmdOtherMethods);
+		void SetClassLayout (uint td, uint dwPackSize, IntPtr /*COR_FIELD_OFFSET**/ rFieldOffsets, uint ulClassSize);
+		void DeleteClassLayout (uint td);
+		void SetFieldMarshal (uint tk, IntPtr /* byte* */ pvNativeType, uint cbNativeType);
+		void DeleteFieldMarshal (uint tk);
+		uint DefinePermissionSet (uint tk, uint dwAction, IntPtr /* void* */ pvPermission, uint cbPermission);
+		void SetRVA (uint md, uint ulRVA);
+		uint GetTokenFromSig (IntPtr /* byte* */ pvSig, uint cbSig);
+		uint DefineModuleRef (string szName);
+		void SetParent (uint mr, uint tk);
+		uint GetTokenFromTypeSpec (IntPtr /* byte* */ pvSig, uint cbSig);
+		void SaveToMemory (IntPtr /* void* */ pbData, uint cbData);
+		uint DefineUserString (string szString, uint cchString);
+		void DeleteToken (uint tkObj);
+		void SetMethodProps (uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags);
+		void SetTypeDefProps (uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr /* uint* */ rtkImplements);
+		void SetEventProps (uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr /* uint* */ rmdOtherMethods);
+		uint SetPermissionSetProps (uint tk, uint dwAction, IntPtr /* void* */ pvPermission, uint cbPermission);
+		void DefinePinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);
+		void SetPinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);
+		void DeletePinvokeMap (uint tk);
+		uint DefineCustomAttribute (uint tkObj, uint tkType, IntPtr /* void* */ pCustomAttribute, uint cbCustomAttribute);
+		void SetCustomAttributeValue (uint pcv, IntPtr /* void* */ pCustomAttribute, uint cbCustomAttribute);
+		uint DefineField (uint td, string szName, uint dwFieldFlags, IntPtr /* byte* */ pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
+		uint DefineProperty (uint td, string szProperty, uint dwPropFlags, IntPtr /* byte* */ pvSig, uint cbSig, uint dwCPlusTypeFlag,
+		  IntPtr /* void* */ pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr /* uint*  */ rmdOtherMethods);
+		uint DefineParam (uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
+		void SetFieldProps (uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
+		void SetPropertyProps (uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr /* uint* */ rmdOtherMethods);
+		void SetParamProps (uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
+		uint DefineSecurityAttributeSet (uint tkObj, IntPtr rSecAttrs, uint cSecAttrs);
+		void ApplyEditAndContinue ([MarshalAs (UnmanagedType.IUnknown)]object pImport);
+		uint TranslateSigWithScope (IntPtr pAssemImport, IntPtr /* void* */ pbHashValue, uint cbHashValue,
+		  IMetaDataImport import, IntPtr /* byte* */ pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr /* byte* */ pvTranslatedSig, uint cbTranslatedSigMax);
+		void SetMethodImplFlags (uint md, uint dwImplFlags);
+		void SetFieldRVA (uint fd, uint ulRVA);
+		void Merge (IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs (UnmanagedType.IUnknown)]object pHandler);
+		void MergeEnd ();
+	}
+
+	[ComImport, InterfaceType (ComInterfaceType.InterfaceIsIUnknown), Guid ("7DAC8207-D3AE-4c75-9B67-92801A497D44")]
+	interface IMetaDataImport {
+		[PreserveSig]
+		void CloseEnum (uint hEnum);
+		uint CountEnum (uint hEnum);
+		void ResetEnum (uint hEnum, uint ulPos);
+		uint EnumTypeDefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeDefs, uint cMax);
+		uint EnumInterfaceImpls (ref uint phEnum, uint td, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rImpls, uint cMax);
+		uint EnumTypeRefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeRefs, uint cMax);
+		uint FindTypeDefByName (string szTypeDef, uint tkEnclosingClass);
+		Guid GetScopeProps (StringBuilder szName, uint cchName, out uint pchName);
+		uint GetModuleFromScope ();
+		uint GetTypeDefProps (uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, ref uint pdwTypeDefFlags);
+		uint GetInterfaceImplProps (uint iiImpl, out uint pClass);
+		uint GetTypeRefProps (uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName);
+		uint ResolveTypeRef (uint tr, [In] ref Guid riid, [MarshalAs (UnmanagedType.Interface)] out object ppIScope);
+		uint EnumMembers (ref uint phEnum, uint cl, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rMembers, uint cMax);
+		uint EnumMembersWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMembers, uint cMax);
+		uint EnumMethods (ref uint phEnum, uint cl, IntPtr /* uint* */ rMethods, uint cMax);
+		uint EnumMethodsWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethods, uint cMax);
+		uint EnumFields (ref uint phEnum, uint cl, IntPtr /* uint* */ rFields, uint cMax);
+		uint EnumFieldsWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rFields, uint cMax);
+		uint EnumParams (ref uint phEnum, uint mb, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rParams, uint cMax);
+		uint EnumMemberRefs (ref uint phEnum, uint tkParent, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rMemberRefs, uint cMax);
+		uint EnumMethodImpls (ref uint phEnum, uint td, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethodBody,
+		   [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethodDecl, uint cMax);
+		uint EnumPermissionSets (ref uint phEnum, uint tk, uint dwActions, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rPermission,
+		   uint cMax);
+		uint FindMember (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
+		uint FindMethod (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
+		uint FindField (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
+		uint FindMemberRef (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
+		uint GetMethodProps (uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr,
+		  IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA);
+		uint GetMemberRefProps (uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr /* byte* */ ppvSigBlob);
+		uint EnumProperties (ref uint phEnum, uint td, IntPtr /* uint* */ rProperties, uint cMax);
+		uint EnumEvents (ref uint phEnum, uint td, IntPtr /* uint* */ rEvents, uint cMax);
+		uint GetEventProps (uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags,
+		  out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire,
+		  [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 11)] uint [] rmdOtherMethod, uint cMax);
+		uint EnumMethodSemantics (ref uint phEnum, uint mb, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rEventProp, uint cMax);
+		uint GetMethodSemantics (uint mb, uint tkEventProp);
+		uint GetClassLayout (uint td, out uint pdwPackSize, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr /*COR_FIELD_OFFSET **/ rFieldOffset, uint cMax, out uint pcFieldOffset);
+		uint GetFieldMarshal (uint tk, out IntPtr /* byte* */ ppvNativeType);
+		uint GetRVA (uint tk, out uint pulCodeRVA);
+		uint GetPermissionSetProps (uint pm, out uint pdwAction, out IntPtr /* void* */ ppvPermission);
+		uint GetSigFromToken (uint mdSig, out IntPtr /* byte* */ ppvSig);
+		uint GetModuleRefProps (uint mur, StringBuilder szName, uint cchName);
+		uint EnumModuleRefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rModuleRefs, uint cmax);
+		uint GetTypeSpecFromToken (uint typespec, out IntPtr /* byte* */ ppvSig);
+		uint GetNameFromToken (uint tk);
+		uint EnumUnresolvedMethods (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rMethods, uint cMax);
+		uint GetUserString (uint stk, StringBuilder szString, uint cchString);
+		uint GetPinvokeMap (uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName);
+		uint EnumSignatures (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rSignatures, uint cmax);
+		uint EnumTypeSpecs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeSpecs, uint cmax);
+		uint EnumUserStrings (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rStrings, uint cmax);
+		[PreserveSig]
+		int GetParamForMethodIndex (uint md, uint ulParamSeq, out uint pParam);
+		uint EnumCustomAttributes (ref uint phEnum, uint tk, uint tkType, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rCustomAttributes, uint cMax);
+		uint GetCustomAttributeProps (uint cv, out uint ptkObj, out uint ptkType, out IntPtr /* void* */ ppBlob);
+		uint FindTypeRef (uint tkResolutionScope, string szName);
+		uint GetMemberProps (uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr,
+		  out IntPtr /* byte* */ ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue);
+		uint GetFieldProps (uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr,
+		  out IntPtr /* byte* */ ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue);
+		uint GetPropertyProps (uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags,
+		  out IntPtr /* byte* */ ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter,
+		  out uint pmdGetter, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 14)] uint [] rmdOtherMethod, uint cMax);
+		uint GetParamProps (uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName,
+		  out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue);
+		uint GetCustomAttributeByName (uint tkObj, string szName, out IntPtr /* void* */ ppData);
+		[PreserveSig]
+		[return: MarshalAs (UnmanagedType.Bool)]
+		bool IsValidToken (uint tk);
+		uint GetNestedClassProps (uint tdNestedClass);
+		uint GetNativeCallConvFromSig (IntPtr /* void* */ pvSig, uint cbSig);
+		int IsGlobal (uint pd);
+	}
+
+	class ModuleMetadata : IMetaDataEmit, IMetaDataImport {
+
+		readonly ModuleDefinition module;
+
+		public ModuleMetadata (ModuleDefinition module)
+		{
+			this.module = module;
+		}
+
+		public void SetModuleProps (string szName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void Save (string szFile, uint dwSaveFlags)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SaveToStream (IntPtr pIStream, uint dwSaveFlags)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetSaveSize (uint fSave)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineTypeDef (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineNestedType (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetHandler (object pUnk)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineMethod (uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void DefineMethodImpl (uint td, uint tkBody, uint tkDecl)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineTypeRefByName (uint tkResolutionScope, IntPtr szName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineImportType (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineMemberRef (uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineImportMember (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineEvent (uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetClassLayout (uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void DeleteClassLayout (uint td)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetFieldMarshal (uint tk, IntPtr pvNativeType, uint cbNativeType)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void DeleteFieldMarshal (uint tk)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefinePermissionSet (uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetRVA (uint md, uint ulRVA)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetTokenFromSig (IntPtr pvSig, uint cbSig)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineModuleRef (string szName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetParent (uint mr, uint tk)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetTokenFromTypeSpec (IntPtr pvSig, uint cbSig)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SaveToMemory (IntPtr pbData, uint cbData)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineUserString (string szString, uint cchString)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void DeleteToken (uint tkObj)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetMethodProps (uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetTypeDefProps (uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetEventProps (uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint SetPermissionSetProps (uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void DefinePinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetPinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void DeletePinvokeMap (uint tk)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineCustomAttribute (uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetCustomAttributeValue (uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineField (uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineProperty (uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineParam (uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetFieldProps (uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetPropertyProps (uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetParamProps (uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint DefineSecurityAttributeSet (uint tkObj, IntPtr rSecAttrs, uint cSecAttrs)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void ApplyEditAndContinue (object pImport)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint TranslateSigWithScope (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetMethodImplFlags (uint md, uint dwImplFlags)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void SetFieldRVA (uint fd, uint ulRVA)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void Merge (IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void MergeEnd ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void CloseEnum (uint hEnum)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint CountEnum (uint hEnum)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void ResetEnum (uint hEnum, uint ulPos)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumTypeDefs (ref uint phEnum, uint[] rTypeDefs, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumInterfaceImpls (ref uint phEnum, uint td, uint[] rImpls, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumTypeRefs (ref uint phEnum, uint[] rTypeRefs, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint FindTypeDefByName (string szTypeDef, uint tkEnclosingClass)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public Guid GetScopeProps (StringBuilder szName, uint cchName, out uint pchName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetModuleFromScope ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetTypeDefProps (uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, ref uint pdwTypeDefFlags)
+		{
+			pchTypeDef = 0;
+			return td;
+		}
+
+		public uint GetInterfaceImplProps (uint iiImpl, out uint pClass)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetTypeRefProps (uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint ResolveTypeRef (uint tr, ref Guid riid, out object ppIScope)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMembers (ref uint phEnum, uint cl, uint[] rMembers, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMembersWithName (ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMethods (ref uint phEnum, uint cl, IntPtr rMethods, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMethodsWithName (ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumFields (ref uint phEnum, uint cl, IntPtr rFields, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumFieldsWithName (ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumParams (ref uint phEnum, uint mb, uint[] rParams, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMemberRefs (ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMethodImpls (ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumPermissionSets (ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint FindMember (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint FindMethod (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint FindField (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint FindMemberRef (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetMethodProps (uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA)
+		{
+			pClass = 0;
+			pchMethod = 0;
+			return mb;
+		}
+
+		public uint GetMemberRefProps (uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumProperties (ref uint phEnum, uint td, IntPtr rProperties, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumEvents (ref uint phEnum, uint td, IntPtr rEvents, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetEventProps (uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumMethodSemantics (ref uint phEnum, uint mb, uint[] rEventProp, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetMethodSemantics (uint mb, uint tkEventProp)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetClassLayout (uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetFieldMarshal (uint tk, out IntPtr ppvNativeType)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetRVA (uint tk, out uint pulCodeRVA)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetPermissionSetProps (uint pm, out uint pdwAction, out IntPtr ppvPermission)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetSigFromToken (uint mdSig, out IntPtr ppvSig)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetModuleRefProps (uint mur, StringBuilder szName, uint cchName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumModuleRefs (ref uint phEnum, uint[] rModuleRefs, uint cmax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetTypeSpecFromToken (uint typespec, out IntPtr ppvSig)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetNameFromToken (uint tk)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumUnresolvedMethods (ref uint phEnum, uint[] rMethods, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetUserString (uint stk, StringBuilder szString, uint cchString)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetPinvokeMap (uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumSignatures (ref uint phEnum, uint[] rSignatures, uint cmax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumTypeSpecs (ref uint phEnum, uint[] rTypeSpecs, uint cmax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumUserStrings (ref uint phEnum, uint[] rStrings, uint cmax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public int GetParamForMethodIndex (uint md, uint ulParamSeq, out uint pParam)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint EnumCustomAttributes (ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetCustomAttributeProps (uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint FindTypeRef (uint tkResolutionScope, string szName)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetMemberProps (uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetFieldProps (uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetPropertyProps (uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetParamProps (uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetCustomAttributeByName (uint tkObj, string szName, out IntPtr ppData)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public bool IsValidToken (uint tk)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetNestedClassProps (uint tdNestedClass)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public uint GetNativeCallConvFromSig (IntPtr pvSig, uint cbSig)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public int IsGlobal (uint pd)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbHelper.cs	(revision 11807)
@@ -0,0 +1,205 @@
+//
+// PdbHelper.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+using Mono.Cecil.Cil;
+
+namespace Mono.Cecil.Pdb {
+
+	class PdbHelper {
+
+#if !READ_ONLY
+		public static SymWriter CreateWriter (ModuleDefinition module, string pdb)
+		{
+			var writer = new SymWriter ();
+
+			if (File.Exists (pdb))
+				File.Delete (pdb);
+
+			writer.Initialize (new ModuleMetadata (module), pdb, true);
+
+			return writer;
+		}
+#endif
+
+		public static string GetPdbFileName (string assemblyFileName)
+		{
+			return Path.ChangeExtension (assemblyFileName, ".pdb");
+		}
+	}
+
+	public class PdbReaderProvider : ISymbolReaderProvider {
+
+		public ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName)
+		{
+			return new PdbReader (File.OpenRead (PdbHelper.GetPdbFileName (fileName)));
+		}
+
+		public ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream)
+		{
+			return new PdbReader (symbolStream);
+		}
+	}
+
+#if !READ_ONLY
+
+	public class PdbWriterProvider : ISymbolWriterProvider {
+
+		public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
+		{
+			return new PdbWriter (module, PdbHelper.CreateWriter (module, PdbHelper.GetPdbFileName (fileName)));
+		}
+
+		public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+#endif
+
+	static class GuidMapping {
+
+		static readonly Dictionary<Guid, DocumentLanguage> guid_language = new Dictionary<Guid, DocumentLanguage> ();
+		static readonly Dictionary<DocumentLanguage, Guid> language_guid = new Dictionary<DocumentLanguage, Guid> ();
+
+		static GuidMapping ()
+		{
+			AddMapping (DocumentLanguage.C, new Guid (0x63a08714, 0xfc37, 0x11d2, 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1));
+			AddMapping (DocumentLanguage.Cpp, new Guid (0x3a12d0b7, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
+			AddMapping (DocumentLanguage.CSharp, new Guid (0x3f5162f8, 0x07c6, 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1));
+			AddMapping (DocumentLanguage.Basic, new Guid (0x3a12d0b8, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
+			AddMapping (DocumentLanguage.Java, new Guid (0x3a12d0b4, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
+			AddMapping (DocumentLanguage.Cobol, new Guid (0xaf046cd1, 0xd0e1, 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc));
+			AddMapping (DocumentLanguage.Pascal, new Guid (0xaf046cd2, 0xd0e1, 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc));
+			AddMapping (DocumentLanguage.Cil, new Guid (0xaf046cd3, 0xd0e1, 0x11d2, 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc));
+			AddMapping (DocumentLanguage.JScript, new Guid (0x3a12d0b6, 0xc26c, 0x11d0, 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2));
+			AddMapping (DocumentLanguage.Smc, new Guid (0xd9b9f7b, 0x6611, 0x11d3, 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd));
+			AddMapping (DocumentLanguage.MCpp, new Guid (0x4b35fde8, 0x07c6, 0x11d3, 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1));
+		}
+
+		static void AddMapping (DocumentLanguage language, Guid guid)
+		{
+			guid_language.Add (guid, language);
+			language_guid.Add (language, guid);
+		}
+
+		static readonly Guid type_text = new Guid (0x5a869d0b, 0x6611, 0x11d3, 0xbd, 0x2a, 0x00, 0x00, 0xf8, 0x08, 0x49, 0xbd);
+
+		public static DocumentType ToType (this Guid guid)
+		{
+			if (guid == type_text)
+				return DocumentType.Text;
+
+			return DocumentType.Other;
+		}
+
+		public static Guid ToGuid (this DocumentType type)
+		{
+			if (type == DocumentType.Text)
+				return type_text;
+
+			return new Guid ();
+		}
+
+		static readonly Guid hash_md5 = new Guid (0x406ea660, 0x64cf, 0x4c82, 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99);
+		static readonly Guid hash_sha1 = new Guid (0xff1816ec, 0xaa5e, 0x4d10, 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60);
+
+		public static DocumentHashAlgorithm ToHashAlgorithm (this Guid guid)
+		{
+			if (guid == hash_md5)
+				return DocumentHashAlgorithm.MD5;
+
+			if (guid == hash_sha1)
+				return DocumentHashAlgorithm.SHA1;
+
+			return DocumentHashAlgorithm.None;
+		}
+
+		public static Guid ToGuid (this DocumentHashAlgorithm hash_algo)
+		{
+			if (hash_algo == DocumentHashAlgorithm.MD5)
+				return hash_md5;
+
+			if (hash_algo == DocumentHashAlgorithm.SHA1)
+				return hash_sha1;
+
+			return new Guid ();
+		}
+
+		public static DocumentLanguage ToLanguage (this Guid guid)
+		{
+			DocumentLanguage language;
+			if (!guid_language.TryGetValue (guid, out language))
+				return DocumentLanguage.Other;
+
+			return language;
+		}
+
+		public static Guid ToGuid (this DocumentLanguage language)
+		{
+			Guid guid;
+			if (!language_guid.TryGetValue (language, out guid))
+				return new Guid ();
+
+			return guid;
+		}
+
+		static readonly Guid vendor_ms = new Guid (0x994b45c4, 0xe6e9, 0x11d2, 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1);
+
+		public static DocumentLanguageVendor ToVendor (this Guid guid)
+		{
+			if (guid == vendor_ms)
+				return DocumentLanguageVendor.Microsoft;
+
+			return DocumentLanguageVendor.Other;
+		}
+
+		public static Guid ToGuid (this DocumentLanguageVendor vendor)
+		{
+			if (vendor == DocumentLanguageVendor.Microsoft)
+				return vendor_ms;
+
+			return new Guid ();
+		}
+	}
+}
+
+#if !NET_3_5 && !NET_4_0
+
+namespace System.Runtime.CompilerServices {
+
+	[AttributeUsage (AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
+	sealed class ExtensionAttribute : Attribute {
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbReader.cs	(revision 11807)
@@ -0,0 +1,282 @@
+//
+// PdbReader.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+using Microsoft.Cci.Pdb;
+
+using Mono.Cecil.Cil;
+
+namespace Mono.Cecil.Pdb {
+
+	public class PdbReader : ISymbolReader {
+
+		int age;
+		Guid guid;
+
+		readonly Stream pdb_file;
+		readonly Dictionary<string, Document> documents = new Dictionary<string, Document> ();
+		readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction> ();
+
+		internal PdbReader (Stream file)
+		{
+			this.pdb_file = file;
+		}
+
+		/*
+		uint Magic = 0x53445352;
+		Guid Signature;
+		uint Age;
+		string FileName;
+		 */
+
+		public bool ProcessDebugHeader (ImageDebugDirectory directory, byte [] header)
+		{
+			if (header.Length < 24)
+				return false;
+
+			var magic = ReadInt32 (header, 0);
+			if (magic != 0x53445352)
+				return false;
+
+			var guid_bytes = new byte [16];
+			Buffer.BlockCopy (header, 4, guid_bytes, 0, 16);
+
+			this.guid = new Guid (guid_bytes);
+			this.age = ReadInt32 (header, 20);
+
+			return PopulateFunctions ();
+		}
+
+		static int ReadInt32 (byte [] bytes, int start)
+		{
+			return (bytes [start]
+				| (bytes [start + 1] << 8)
+				| (bytes [start + 2] << 16)
+				| (bytes [start + 3] << 24));
+		}
+
+		bool PopulateFunctions ()
+		{
+			using (pdb_file) {
+				int age;
+				Guid guid;
+				var funcs = PdbFile.LoadFunctions (pdb_file, true, out age, out guid);
+
+				if (this.age != 0) {
+					if (this.age != age)
+						return false;
+					if (this.guid != guid)
+						return false;
+				}
+
+				foreach (PdbFunction function in funcs)
+					functions.Add (function.token, function);
+			}
+
+			return true;
+		}
+
+		public void Read (MethodBody body, InstructionMapper mapper)
+		{
+			var method_token = body.Method.MetadataToken;
+
+			PdbFunction function;
+			if (!functions.TryGetValue (method_token.ToUInt32 (), out function))
+				return;
+
+			ReadSequencePoints (function, mapper);
+			ReadScopeAndLocals (function.scopes, null, body, mapper);
+		}
+
+		static void ReadScopeAndLocals (PdbScope [] scopes, Scope parent, MethodBody body, InstructionMapper mapper)
+		{
+			foreach (PdbScope scope in scopes)
+				ReadScopeAndLocals (scope, parent, body, mapper);
+
+			CreateRootScope (body);
+		}
+
+		static void CreateRootScope (MethodBody body)
+		{
+			if (!body.HasVariables)
+				return;
+
+			var instructions = body.Instructions;
+
+			var root = new Scope ();
+			root.Start = instructions [0];
+			root.End = instructions [instructions.Count - 1];
+
+			var variables = body.Variables;
+			for (int i = 0; i < variables.Count; i++)
+				root.Variables.Add (variables [i]);
+
+			body.Scope = root;
+		}
+
+		static void ReadScopeAndLocals (PdbScope scope, Scope parent, MethodBody body, InstructionMapper mapper)
+		{
+			//Scope s = new Scope ();
+			//s.Start = GetInstruction (body, instructions, (int) scope.address);
+			//s.End = GetInstruction (body, instructions, (int) scope.length - 1);
+
+			//if (parent != null)
+			//	parent.Scopes.Add (s);
+			//else
+			//	body.Scopes.Add (s);
+
+			if (scope == null)
+				return;
+
+			foreach (PdbSlot slot in scope.slots) {
+				int index = (int) slot.slot;
+				if (index < 0 || index >= body.Variables.Count)
+					continue;
+
+				VariableDefinition variable = body.Variables [index];
+				variable.Name = slot.name;
+
+				//s.Variables.Add (variable);
+			}
+
+			ReadScopeAndLocals (scope.scopes, null /* s */, body, mapper);
+		}
+
+		void ReadSequencePoints (PdbFunction function, InstructionMapper mapper)
+		{
+			if (function.lines == null)
+				return;
+
+			foreach (PdbLines lines in function.lines)
+				ReadLines (lines, mapper);
+		}
+
+		void ReadLines (PdbLines lines, InstructionMapper mapper)
+		{
+			var document = GetDocument (lines.file);
+
+			foreach (var line in lines.lines)
+				ReadLine (line, document, mapper);
+		}
+
+		static void ReadLine (PdbLine line, Document document, InstructionMapper mapper)
+		{
+			var instruction = mapper ((int) line.offset);
+			if (instruction == null)
+				return;
+
+			var sequence_point = new SequencePoint (document);
+			sequence_point.StartLine = (int) line.lineBegin;
+			sequence_point.StartColumn = (int) line.colBegin;
+			sequence_point.EndLine = (int) line.lineEnd;
+			sequence_point.EndColumn = (int) line.colEnd;
+
+			instruction.SequencePoint = sequence_point;
+		}
+
+		Document GetDocument (PdbSource source)
+		{
+			string name = source.name;
+			Document document;
+			if (documents.TryGetValue (name, out document))
+				return document;
+
+			document = new Document (name) {
+				Language = source.language.ToLanguage (),
+				LanguageVendor = source.vendor.ToVendor (),
+				Type = source.doctype.ToType (),
+			};
+			documents.Add (name, document);
+			return document;
+		}
+
+		public void Read (MethodSymbols symbols)
+		{
+			PdbFunction function;
+			if (!functions.TryGetValue (symbols.MethodToken.ToUInt32 (), out function))
+				return;
+
+			ReadSequencePoints (function, symbols);
+			ReadLocals (function.scopes, symbols);
+		}
+
+		void ReadLocals (PdbScope [] scopes, MethodSymbols symbols)
+		{
+			foreach (var scope in scopes)
+				ReadLocals (scope, symbols);
+		}
+
+		void ReadLocals (PdbScope scope, MethodSymbols symbols)
+		{
+			if (scope == null)
+				return;
+
+			foreach (var slot in scope.slots) {
+				int index = (int) slot.slot;
+				if (index < 0 || index >= symbols.Variables.Count)
+					continue;
+
+				var variable = symbols.Variables [index];
+				variable.Name = slot.name;
+			}
+
+			ReadLocals (scope.scopes, symbols);
+		}
+
+		void ReadSequencePoints (PdbFunction function, MethodSymbols symbols)
+		{
+			if (function.lines == null)
+				return;
+
+			foreach (PdbLines lines in function.lines)
+				ReadLines (lines, symbols);
+		}
+
+		void ReadLines (PdbLines lines, MethodSymbols symbols)
+		{
+			for (int i = 0; i < lines.lines.Length; i++) {
+				var line = lines.lines [i];
+
+				symbols.Instructions.Add (new InstructionSymbol ((int) line.offset, new SequencePoint (GetDocument (lines.file)) {
+					StartLine = (int) line.lineBegin,
+					StartColumn = (int) line.colBegin,
+					EndLine = (int) line.lineEnd,
+					EndColumn = (int) line.colEnd,
+				}));
+			}
+		}
+
+		public void Dispose ()
+		{
+			pdb_file.Close ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/PdbWriter.cs	(revision 11807)
@@ -0,0 +1,222 @@
+//
+// PdbWriter.cs
+//
+// Author:
+//   Jb Evain (jbevain@gmail.com)
+//
+// Copyright (c) 2008 - 2011 Jb Evain
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.SymbolStore;
+
+using Mono.Cecil.Cil;
+using Mono.Collections.Generic;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Pdb {
+
+	public class PdbWriter : Cil.ISymbolWriter {
+
+		readonly ModuleDefinition module;
+		readonly SymWriter writer;
+		readonly Dictionary<string, SymDocumentWriter> documents;
+
+		internal PdbWriter (ModuleDefinition module, SymWriter writer)
+		{
+			this.module = module;
+			this.writer = writer;
+			this.documents = new Dictionary<string, SymDocumentWriter> ();
+		}
+
+		public bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header)
+		{
+			header = writer.GetDebugInfo (out directory);
+			return true;
+		}
+
+		public void Write (MethodBody body)
+		{
+			var method_token = body.Method.MetadataToken;
+			var sym_token = new SymbolToken (method_token.ToInt32 ());
+
+			var instructions = CollectInstructions (body);
+			if (instructions.Count == 0)
+				return;
+
+			var start_offset = 0;
+			var end_offset = body.CodeSize;
+
+			writer.OpenMethod (sym_token);
+			writer.OpenScope (start_offset);
+
+			DefineSequencePoints (instructions);
+			DefineVariables (body, start_offset, end_offset);
+
+			writer.CloseScope (end_offset);
+			writer.CloseMethod ();
+		}
+
+		Collection<Instruction> CollectInstructions (MethodBody body)
+		{
+			var collection = new Collection<Instruction> ();
+			var instructions = body.Instructions;
+
+			for (int i = 0; i < instructions.Count; i++) {
+				var instruction = instructions [i];
+				var sequence_point = instruction.SequencePoint;
+				if (sequence_point == null)
+					continue;
+
+				GetDocument (sequence_point.Document);
+				collection.Add (instruction);
+			}
+
+			return collection;
+		}
+
+		void DefineVariables (MethodBody body, int start_offset, int end_offset)
+		{
+			if (!body.HasVariables)
+				return;
+
+			var sym_token = new SymbolToken (body.LocalVarToken.ToInt32 ());
+
+			var variables = body.Variables;
+			for (int i = 0; i < variables.Count; i++) {
+				var variable = variables [i];
+				CreateLocalVariable (variable, sym_token, start_offset, end_offset);
+			}
+		}
+
+		void DefineSequencePoints (Collection<Instruction> instructions)
+		{
+			for (int i = 0; i < instructions.Count; i++) {
+				var instruction = instructions [i];
+				var sequence_point = instruction.SequencePoint;
+
+				writer.DefineSequencePoints (
+					GetDocument (sequence_point.Document),
+					new [] { instruction.Offset },
+					new [] { sequence_point.StartLine },
+					new [] { sequence_point.StartColumn },
+					new [] { sequence_point.EndLine },
+					new [] { sequence_point.EndColumn });
+			}
+		}
+
+		void CreateLocalVariable (VariableDefinition variable, SymbolToken local_var_token, int start_offset, int end_offset)
+		{
+			writer.DefineLocalVariable2 (
+				variable.Name,
+				0,
+				local_var_token,
+				SymAddressKind.ILOffset,
+				variable.Index,
+				0,
+				0,
+				start_offset,
+				end_offset);
+		}
+
+		SymDocumentWriter GetDocument (Document document)
+		{
+			if (document == null)
+				return null;
+
+			SymDocumentWriter doc_writer;
+			if (documents.TryGetValue (document.Url, out doc_writer))
+				return doc_writer;
+
+			doc_writer = writer.DefineDocument (
+				document.Url,
+				document.Language.ToGuid (),
+				document.LanguageVendor.ToGuid (),
+				document.Type.ToGuid ());
+
+			documents [document.Url] = doc_writer;
+			return doc_writer;
+		}
+
+		public void Write (MethodSymbols symbols)
+		{
+			var sym_token = new SymbolToken (symbols.MethodToken.ToInt32 ());
+
+			var start_offset = 0;
+			var end_offset = symbols.CodeSize;
+
+			writer.OpenMethod (sym_token);
+			writer.OpenScope (start_offset);
+
+			DefineSequencePoints (symbols);
+			DefineVariables (symbols, start_offset, end_offset);
+
+			writer.CloseScope (end_offset);
+			writer.CloseMethod ();
+		}
+
+		void DefineSequencePoints (MethodSymbols symbols)
+		{
+			var instructions = symbols.instructions;
+
+			for (int i = 0; i < instructions.Count; i++) {
+				var instruction = instructions [i];
+				var sequence_point = instruction.SequencePoint;
+
+				writer.DefineSequencePoints (
+					GetDocument (sequence_point.Document),
+					new [] { instruction.Offset },
+					new [] { sequence_point.StartLine },
+					new [] { sequence_point.StartColumn },
+					new [] { sequence_point.EndLine },
+					new [] { sequence_point.EndColumn });
+			}
+		}
+
+		void DefineVariables (MethodSymbols symbols, int start_offset, int end_offset)
+		{
+			if (!symbols.HasVariables)
+				return;
+
+			var sym_token = new SymbolToken (symbols.LocalVarToken.ToInt32 ());
+
+			var variables = symbols.Variables;
+			for (int i = 0; i < variables.Count; i++) {
+				var variable = variables [i];
+				CreateLocalVariable (variable, sym_token, start_offset, end_offset);
+			}
+		}
+
+		public void Dispose ()
+		{
+			var entry_point = module.EntryPoint;
+			if (entry_point != null)
+				writer.SetUserEntryPoint (new SymbolToken (entry_point.MetadataToken.ToInt32 ()));
+
+			writer.Close ();
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/SymDocumentWriter.cs	(revision 11807)
@@ -0,0 +1,51 @@
+//
+// SymDocumentWriter.cs
+//
+// Author:
+//   Juerg Billeter (j@bitron.ch)
+//
+// (C) 2008 Juerg Billeter
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Pdb
+{
+	internal class SymDocumentWriter
+	{
+		readonly ISymUnmanagedDocumentWriter m_unmanagedDocumentWriter;
+
+		public SymDocumentWriter (ISymUnmanagedDocumentWriter unmanagedDocumentWriter)
+		{
+			m_unmanagedDocumentWriter = unmanagedDocumentWriter;
+		}
+
+		public ISymUnmanagedDocumentWriter GetUnmanaged ()
+		{
+			return m_unmanagedDocumentWriter;
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/SymWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/SymWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Cecil/0.9.5/Mono.Cecil-0.9.5/Symbols/Mono.Cecil.Pdb/Mono.Cecil.Pdb/SymWriter.cs	(revision 11807)
@@ -0,0 +1,170 @@
+//
+// SymWriter.cs
+//
+// Author:
+//   Juerg Billeter (j@bitron.ch)
+//
+// (C) 2008 Juerg Billeter
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.SymbolStore;
+using System.Runtime.InteropServices;
+
+using Mono.Cecil.Cil;
+using Mono.Collections.Generic;
+
+#if !READ_ONLY
+
+namespace Mono.Cecil.Pdb
+{
+	internal class SymWriter
+	{
+		[DllImport("ole32.dll")]
+		static extern int CoCreateInstance (
+			[In] ref Guid rclsid,
+			[In, MarshalAs (UnmanagedType.IUnknown)] object pUnkOuter,
+			[In] uint dwClsContext,
+			[In] ref Guid riid,
+			[Out, MarshalAs (UnmanagedType.Interface)] out object ppv);
+
+		static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa");
+		static Guid s_CorSymWriter_SxS_ClassID = new Guid ("108296c1-281e-11d3-bd22-0000f80849bd");
+
+		readonly ISymUnmanagedWriter2 m_writer;
+		readonly Collection<ISymUnmanagedDocumentWriter> documents;
+
+		public SymWriter ()
+		{
+			object objWriter;
+			CoCreateInstance (ref s_CorSymWriter_SxS_ClassID, null, 1, ref s_symUnmangedWriterIID, out objWriter);
+
+			m_writer = (ISymUnmanagedWriter2) objWriter;
+			documents = new Collection<ISymUnmanagedDocumentWriter> ();
+		}
+
+		public byte[] GetDebugInfo (out ImageDebugDirectory idd)
+		{
+			int size;
+
+			// get size of debug info
+			m_writer.GetDebugInfo (out idd, 0, out size, null);
+
+			byte[] debug_info = new byte[size];
+			m_writer.GetDebugInfo (out idd, size, out size, debug_info);
+
+			return debug_info;
+		}
+
+		public void DefineLocalVariable2 (
+			string name,
+			FieldAttributes attributes,
+			SymbolToken sigToken,
+			SymAddressKind addrKind,
+			int addr1,
+			int addr2,
+			int addr3,
+			int startOffset,
+			int endOffset)
+		{
+			m_writer.DefineLocalVariable2 (name, (int)attributes, sigToken, (int)addrKind, addr1, addr2, addr3, startOffset, endOffset);
+		}
+
+		public void Close ()
+		{
+			m_writer.Close ();
+			Marshal.ReleaseComObject (m_writer);
+
+			foreach (var document in documents)
+				Marshal.ReleaseComObject (document);
+		}
+
+		public void CloseMethod ()
+		{
+			m_writer.CloseMethod ();
+		}
+
+		public void CloseNamespace ()
+		{
+			m_writer.CloseNamespace ();
+		}
+
+		public void CloseScope (int endOffset)
+		{
+			m_writer.CloseScope (endOffset);
+		}
+
+		public SymDocumentWriter DefineDocument (string url, Guid language, Guid languageVendor, Guid documentType)
+		{
+			ISymUnmanagedDocumentWriter unmanagedDocumentWriter;
+			m_writer.DefineDocument (url, ref language, ref languageVendor, ref documentType, out unmanagedDocumentWriter);
+
+			documents.Add (unmanagedDocumentWriter);
+			return new SymDocumentWriter (unmanagedDocumentWriter);
+		}
+
+		public void DefineParameter (string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3)
+		{
+			throw new Exception ("The method or operation is not implemented.");
+		}
+
+		public void DefineSequencePoints (SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
+		{
+			m_writer.DefineSequencePoints (document.GetUnmanaged(), offsets.Length, offsets, lines, columns, endLines, endColumns);
+		}
+
+		public void Initialize (object emitter, string filename, bool fFullBuild)
+		{
+			m_writer.Initialize (emitter, filename, null, fFullBuild);
+		}
+
+		public void SetUserEntryPoint (SymbolToken method)
+		{
+			m_writer.SetUserEntryPoint (method);
+		}
+
+		public void OpenMethod (SymbolToken method)
+		{
+			m_writer.OpenMethod (method);
+		}
+
+		public void OpenNamespace (string name)
+		{
+			m_writer.OpenNamespace (name);
+		}
+
+		public int OpenScope (int startOffset)
+		{
+			int result;
+			m_writer.OpenScope (startOffset, out result);
+			return result;
+		}
+
+		public void UsingNamespace (string fullName)
+		{
+			m_writer.UsingNamespace (fullName);
+		}
+	}
+}
+
+#endif
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/HeuristicLab.NRefactory-5.5.0.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/HeuristicLab.NRefactory-5.5.0.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/HeuristicLab.NRefactory-5.5.0.csproj	(revision 11807)
@@ -0,0 +1,136 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{168B628A-3815-4567-8ACF-2878AE92891A}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>HeuristicLab.NRefactory</RootNamespace>
+    <AssemblyName>HeuristicLab.NRefactory-5.5.0</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="Plugin.cs.frame" />
+    <Compile Include="Plugin.cs" />
+    <None Include="Properties\AssemblyInfo.cs.frame" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="ICSharpCode.NRefactory License-5.5.0.txt">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </Content>
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\..\..\HeuristicLab.PluginInfrastructure\3.3\HeuristicLab.PluginInfrastructure-3.3.csproj">
+      <Project>{94186a6a-5176-4402-ae83-886557b53cca}</Project>
+      <Name>HeuristicLab.PluginInfrastructure-3.3</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\NRefactory-5.5.0\ICSharpCode.NRefactory-5.5.0.csproj">
+      <Project>{1022483b-7cf4-4162-827f-984b64eaf8b3}</Project>
+      <Name>ICSharpCode.NRefactory-5.5.0</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\NRefactory.Cecil-5.5.0\ICSharpCode.NRefactory.Cecil-5.5.0.csproj">
+      <Project>{6661ee06-91d3-489b-ae80-bc951ea65e9a}</Project>
+      <Name>ICSharpCode.NRefactory.Cecil-5.5.0</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\NRefactory.CSharp-5.5.0\ICSharpCode.NRefactory.CSharp-5.5.0.csproj">
+      <Project>{c06a9187-4e8e-4129-bda3-91d2297682d2}</Project>
+      <Name>ICSharpCode.NRefactory.CSharp-5.5.0</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <PropertyGroup>
+    <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd
+</PreBuildEvent>
+  </PropertyGroup>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
@@ -0,0 +1,17 @@
+Copyright (c) 2010-2014 AlphaSierraPapa, Xamarin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this
+software and associated documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/Plugin.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/Plugin.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/Plugin.cs.frame	(revision 11807)
@@ -0,0 +1,33 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.NRefactory {
+  [Plugin("HeuristicLab.NRefactory", "HeuristicLab wrapper for NRefactory", "5.5.0.$WCREV$")]
+  [PluginFile("HeuristicLab.NRefactory-5.5.0.dll", PluginFileType.Assembly)]
+  [PluginFile("ICSharpCode.NRefactory.dll", PluginFileType.Assembly)]
+  [PluginFile("ICSharpCode.NRefactory.Cecil.dll", PluginFileType.Assembly)]
+  [PluginFile("ICSharpCode.NRefactory.CSharp.dll", PluginFileType.Assembly)]
+  [PluginFile("ICSharpCode.NRefactory License-5.5.0.txt", PluginFileType.License)]
+  public class HeuristicLabNRefactoryPlugin : PluginBase {
+  }
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/Properties/AssemblyInfo.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/Properties/AssemblyInfo.cs.frame	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/HeuristicLab.NRefactory-5.5.0/Properties/AssemblyInfo.cs.frame	(revision 11807)
@@ -0,0 +1,56 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.NRefactory")]
+[assembly: AssemblyDescription("HeuristicLab transport plugin for NRefactory")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2014 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("3a13309e-98b5-4b12-b439-d0b781df0f02")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.5.0.0")]
+[assembly: AssemblyFileVersion("5.5.0.$WCREV$")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/AbiComparer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/AbiComparer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/AbiComparer.cs	(revision 11807)
@@ -0,0 +1,248 @@
+//
+// ABIComparer.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Analysis
+{
+	/// <summary>
+	/// Used to check the compatibility state of two compilations.
+	/// </summary>
+	public enum AbiCompatibility
+	{
+		/// <summary>
+		/// The ABI is equal
+		/// </summary>
+		Equal,
+
+		/// <summary>
+		/// Some items got added, but the ABI remains to be compatible
+		/// </summary>
+		Bigger,
+
+		/// <summary>
+		/// The ABI has changed
+		/// </summary>
+		Incompatible
+	}
+
+	[Serializable]
+	public sealed class AbiEventArgs : EventArgs
+	{
+		public string Message { get; set; }
+
+		public AbiEventArgs(string message)
+		{
+			this.Message = message;
+		}
+	}
+
+	/// <summary>
+	/// The Abi comparer checks the public API of two compilation and determines the compatibility state.
+	/// </summary>
+	public class AbiComparer
+	{
+		public bool StopOnIncompatibility {
+			get; 
+			set;
+		}
+		void CheckContstraints(IType otype, ITypeParameter p1, ITypeParameter p2, ref AbiCompatibility compatibility)
+		{
+			if (p1.DirectBaseTypes.Count () != p2.DirectBaseTypes.Count () ||
+			    p1.HasReferenceTypeConstraint != p2.HasReferenceTypeConstraint ||
+			    p1.HasValueTypeConstraint != p2.HasValueTypeConstraint ||
+			    p1.HasDefaultConstructorConstraint != p2.HasDefaultConstructorConstraint) {
+				OnIncompatibilityFound (new AbiEventArgs (string.Format (TranslateString ("Type parameter constraints of type {0} have changed."), otype.FullName)));
+				compatibility = AbiCompatibility.Incompatible;
+			}
+		}
+
+		void CheckContstraints(IMethod omethod, ITypeParameter p1, ITypeParameter p2, ref AbiCompatibility compatibility)
+		{
+			if (p1.DirectBaseTypes.Count () != p2.DirectBaseTypes.Count () ||
+			    p1.HasReferenceTypeConstraint != p2.HasReferenceTypeConstraint ||
+			    p1.HasValueTypeConstraint != p2.HasValueTypeConstraint ||
+			    p1.HasDefaultConstructorConstraint != p2.HasDefaultConstructorConstraint) {
+				OnIncompatibilityFound (new AbiEventArgs (string.Format (TranslateString ("Type parameter constraints of method {0} have changed."), omethod.FullName)));
+				compatibility = AbiCompatibility.Incompatible;
+			}
+		}
+
+		void CheckTypes (ITypeDefinition oType, ITypeDefinition nType, ref AbiCompatibility compatibility)
+		{
+			int oldMemberCount = 0;
+			Predicate<IUnresolvedMember> pred = null;
+			if (oType.Kind == TypeKind.Class || oType.Kind == TypeKind.Struct)
+				pred = m => (m.IsPublic || m.IsProtected) && !m.IsOverride && !m.IsSynthetic;
+
+			for (int i = 0; i < oType.TypeParameterCount; i++) {
+				CheckContstraints (oType, oType.TypeParameters[i], nType.TypeParameters[i], ref compatibility);
+				if (compatibility == AbiCompatibility.Incompatible && StopOnIncompatibility)
+					return;
+			}
+
+			foreach (var member in oType.GetMembers (pred, GetMemberOptions.IgnoreInheritedMembers)) {
+				var newMember = nType.GetMembers (m => member.UnresolvedMember.Name == m.Name && m.IsPublic == member.IsPublic && m.IsProtected == member.IsProtected);
+				var equalMember = newMember.FirstOrDefault (m => SignatureComparer.Ordinal.Equals (member, m));
+				if (equalMember == null) {
+					compatibility = AbiCompatibility.Incompatible;
+					if (StopOnIncompatibility)
+						return;
+					continue;
+				}
+				var om = member as IMethod;
+				if (om != null) {
+					for (int i = 0; i < om.TypeParameters.Count; i++) {
+						CheckContstraints (om, om.TypeParameters[i], ((IMethod)equalMember).TypeParameters[i], ref compatibility);
+						if (compatibility == AbiCompatibility.Incompatible && StopOnIncompatibility)
+							return;
+					}
+				}
+
+				oldMemberCount++;
+			}
+			if (compatibility == AbiCompatibility.Bigger && oType.Kind != TypeKind.Interface)
+				return;
+			if (oldMemberCount != nType.GetMembers (pred, GetMemberOptions.IgnoreInheritedMembers).Count ()) {
+				if (oType.Kind == TypeKind.Interface) {
+					OnIncompatibilityFound (new AbiEventArgs (string.Format (TranslateString ("Interafce {0} has changed."), oType.FullName)));
+					compatibility = AbiCompatibility.Incompatible;
+				} else {
+					if (compatibility == AbiCompatibility.Equal)
+						compatibility = AbiCompatibility.Bigger;
+				}
+			}
+		}
+
+		void CheckNamespace(INamespace oNs, INamespace nNs, ref AbiCompatibility compatibility)
+		{
+			foreach (var type in oNs.Types) {
+				if (!type.IsPublic && !type.IsProtected)
+					continue;
+				var newType = nNs.GetTypeDefinition (type.Name, type.TypeParameterCount);
+				if (newType == null) {
+					OnIncompatibilityFound (new AbiEventArgs (string.Format (TranslateString ("Type definition {0} is missing."), type.FullName)));
+					compatibility = AbiCompatibility.Incompatible;
+					if (StopOnIncompatibility) 
+						return;
+					continue;
+				}
+				CheckTypes (type, newType, ref compatibility);
+				if (compatibility == AbiCompatibility.Incompatible && StopOnIncompatibility)
+					return;
+			}
+
+			if (compatibility == AbiCompatibility.Bigger)
+				return;
+			foreach (var type in nNs.Types) {
+				if (!type.IsPublic && !type.IsProtected)
+					continue;
+				if (oNs.GetTypeDefinition (type.Name, type.TypeParameterCount) == null) {
+					if (compatibility == AbiCompatibility.Equal)
+						compatibility = AbiCompatibility.Bigger;
+					return;
+				}
+			}
+		}
+
+		static bool ContainsPublicTypes(INamespace testNs)
+		{
+			var stack = new Stack<INamespace> ();
+			stack.Push (testNs);
+			while (stack.Count > 0) {
+				var ns = stack.Pop ();
+				if (ns.Types.Any (t => t.IsPublic))
+					return true;
+				foreach (var child in ns.ChildNamespaces)
+					stack.Push (child);
+			}
+			return false;
+		}
+
+		/// <summary>
+		/// Check the specified oldProject and newProject if they're compatible.
+		/// </summary>
+		/// <param name="oldProject">Old project.</param>
+		/// <param name="newProject">New project.</param>
+		public AbiCompatibility Check (ICompilation oldProject, ICompilation newProject)
+		{
+			var oldStack = new Stack<INamespace> ();
+			var newStack = new Stack<INamespace> ();
+			oldStack.Push (oldProject.MainAssembly.RootNamespace);
+			newStack.Push (newProject.MainAssembly.RootNamespace);
+
+			AbiCompatibility compatibility = AbiCompatibility.Equal;
+			while (oldStack.Count > 0) {
+				var oNs = oldStack.Pop ();
+				var nNs = newStack.Pop ();
+
+				CheckNamespace (oNs, nNs, ref compatibility);
+				if (compatibility == AbiCompatibility.Incompatible && StopOnIncompatibility)
+					return AbiCompatibility.Incompatible;
+				foreach (var child in oNs.ChildNamespaces) {
+					var newChild = nNs.GetChildNamespace (child.Name);
+					if (newChild == null) {
+						OnIncompatibilityFound (new AbiEventArgs (string.Format (TranslateString ("Namespace {0} is missing."), child.FullName)));
+						if (StopOnIncompatibility)
+							return AbiCompatibility.Incompatible;
+						continue;
+					}
+					oldStack.Push (child);
+					newStack.Push (newChild);
+				}
+
+				// check if namespaces are added
+				if (compatibility != AbiCompatibility.Bigger) {
+					foreach (var child in nNs.ChildNamespaces) {
+						if (oNs.GetChildNamespace (child.Name) == null) {
+							if (compatibility == AbiCompatibility.Equal && ContainsPublicTypes (child))
+								compatibility = AbiCompatibility.Bigger;
+							break;
+						}
+					}
+				}
+			}
+			return compatibility;
+		}
+
+		public virtual string TranslateString(string str)
+		{
+			return str;
+		}
+
+		public event EventHandler<AbiEventArgs> IncompatibilityFound;
+
+		protected virtual void OnIncompatibilityFound(AbiEventArgs e)
+		{
+			var handler = IncompatibilityFound;
+			if (handler != null)
+				handler(this, e);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/SymbolCollector.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/SymbolCollector.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/SymbolCollector.cs	(revision 11807)
@@ -0,0 +1,165 @@
+// Copyright (c) 2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Analysis
+{
+	/// <summary>
+	/// The symbol collector collects related symbols that form a group of symbols that should be renamed
+	/// when a name of one symbol changes. For example if a type definition name should be changed
+	/// the constructors and destructor names should change as well.
+	/// </summary>
+	public class SymbolCollector
+	{
+		/// <summary>
+		/// Gets or sets a value indicating whether this <see cref="ICSharpCode.NRefactory.Analysis.SymbolCollector"/> should include overloads.
+		/// </summary>
+		/// <value><c>true</c> if overloads should be included; otherwise, <c>false</c>.</value>
+		public bool IncludeOverloads { 
+			get;
+			set;
+		}
+
+		public bool GroupForRenaming {
+			get;
+			set;
+		}
+
+		static IEnumerable<ISymbol> CollectTypeRelatedMembers (ITypeDefinition type)
+		{
+			yield return type;
+			foreach (var c in type.GetDefinition ().GetMembers (m => !m.IsSynthetic && (m.SymbolKind == SymbolKind.Constructor || m.SymbolKind == SymbolKind.Destructor), GetMemberOptions.IgnoreInheritedMembers)) {
+				yield return c;
+			}
+		}
+
+		static IEnumerable<ISymbol> CollectOverloads (IMethod method)
+		{
+			return method.DeclaringType
+				.GetMethods (m => m.Name == method.Name)
+				.Where (m => m != method);
+		}
+
+		static IMember SearchMember (ITypeDefinition derivedType, IMember method)
+		{
+			foreach (var m in derivedType.Members) {
+				if (m.ImplementedInterfaceMembers.Contains (method))
+					return m;
+			}
+			return null;
+		}
+
+		static IEnumerable<ISymbol> MakeUnique (List<ISymbol> symbols)
+		{
+			HashSet<ISymbol> taken = new HashSet<ISymbol> ();
+			foreach (var sym in symbols) {
+				if (taken.Contains (sym))
+					continue;
+				taken.Add (sym);
+				yield return sym;
+			}
+		}
+
+		/// <summary>
+		/// Gets the related symbols.
+		/// </summary>
+		/// <returns>The related symbols.</returns>
+		/// <param name="g">The type graph.</param>
+		/// <param name="m">The symbol to search</param>
+		public IEnumerable<ISymbol> GetRelatedSymbols(Lazy<TypeGraph> g, ISymbol m)
+		{
+			switch (m.SymbolKind) {
+			case SymbolKind.TypeDefinition:
+				return CollectTypeRelatedMembers ((ITypeDefinition)m);
+	
+			case SymbolKind.Field:
+			case SymbolKind.Operator:
+			case SymbolKind.Variable:
+			case SymbolKind.Parameter:
+			case SymbolKind.TypeParameter:
+				return new ISymbol[] { m };
+	
+			case SymbolKind.Constructor:
+				if (GroupForRenaming)
+					return GetRelatedSymbols (g, ((IMethod)m).DeclaringTypeDefinition);
+				List<ISymbol> constructorSymbols = new List<ISymbol> ();
+				if (IncludeOverloads) {
+					foreach (var m3 in CollectOverloads ((IMethod)m)) {
+						constructorSymbols.Add (m3);
+					}
+				}
+				return constructorSymbols;
+
+			case SymbolKind.Destructor:
+				if (GroupForRenaming)
+					return GetRelatedSymbols (g, ((IMethod)m).DeclaringTypeDefinition);
+				return new ISymbol[] { m };
+
+			case SymbolKind.Indexer:
+			case SymbolKind.Event:
+			case SymbolKind.Property:
+			case SymbolKind.Method: {
+				var member = (IMember)m;
+				List<ISymbol> symbols = new List<ISymbol> ();
+				if (!member.IsExplicitInterfaceImplementation)
+					symbols.Add (member);
+				if (GroupForRenaming) {
+					foreach (var m2 in member.ImplementedInterfaceMembers) {
+						symbols.AddRange (GetRelatedSymbols (g, m2));
+					}
+				} else {
+					symbols.AddRange(member.ImplementedInterfaceMembers);
+				}
+
+				if (member.DeclaringType.Kind == TypeKind.Interface) {
+					var declaringTypeNode = g.Value.GetNode(member.DeclaringTypeDefinition);
+					if (declaringTypeNode != null) {
+						foreach (var derivedType in declaringTypeNode.DerivedTypes) {
+							var mem = SearchMember (derivedType.TypeDefinition, member);
+							if (mem != null)
+								symbols.Add (mem);
+						}
+					}
+				}
+
+
+				if (IncludeOverloads) {
+					IncludeOverloads = false;
+					if (member is IMethod) {
+						foreach (var m3 in CollectOverloads ((IMethod)member)) {
+							symbols.AddRange (GetRelatedSymbols (g, m3));
+						}
+					} else if (member.SymbolKind == SymbolKind.Indexer) {
+						symbols.AddRange (member.DeclaringTypeDefinition.GetProperties (p => p.IsIndexer));
+					}
+				}
+				return MakeUnique (symbols);
+			}
+			case SymbolKind.Namespace:
+				// TODO?
+				return new ISymbol[] { m };
+			default:
+				throw new ArgumentOutOfRangeException ("symbol:"+m.SymbolKind);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/TypeGraph.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/TypeGraph.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/TypeGraph.cs	(revision 11807)
@@ -0,0 +1,82 @@
+﻿// Copyright (c) 2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Analysis
+{
+	/// <summary>
+	/// A graph where type definitions are nodes; and edges are given by inheritance.
+	/// </summary>
+	public class TypeGraph
+	{
+		Dictionary<AssemblyQualifiedTypeName, TypeGraphNode> dict;
+		
+		/// <summary>
+		/// Builds a graph of all type definitions in the specified set of assemblies.
+		/// </summary>
+		/// <param name="assemblies">The input assemblies. The assemblies may belong to multiple compilations.</param>
+		/// <remarks>The resulting graph may be cyclic if there are cyclic type definitions.</remarks>
+		public TypeGraph(IEnumerable<IAssembly> assemblies)
+		{
+			if (assemblies == null)
+				throw new ArgumentNullException("assemblies");
+			dict = new Dictionary<AssemblyQualifiedTypeName, TypeGraphNode>();
+			foreach (IAssembly assembly in assemblies) {
+				foreach (ITypeDefinition typeDef in assembly.GetAllTypeDefinitions()) {
+					// Overwrite previous entry - duplicates can occur if there are multiple versions of the
+					// same project loaded in the solution (e.g. separate .csprojs for separate target frameworks)
+					dict[new AssemblyQualifiedTypeName(typeDef)] = new TypeGraphNode(typeDef);
+				}
+			}
+			foreach (IAssembly assembly in assemblies) {
+				foreach (ITypeDefinition typeDef in assembly.GetAllTypeDefinitions()) {
+					TypeGraphNode typeNode = dict[new AssemblyQualifiedTypeName(typeDef)];
+					foreach (IType baseType in typeDef.DirectBaseTypes) {
+						ITypeDefinition baseTypeDef = baseType.GetDefinition();
+						if (baseTypeDef != null) {
+							TypeGraphNode baseTypeNode;
+							if (dict.TryGetValue(new AssemblyQualifiedTypeName(baseTypeDef), out baseTypeNode)) {
+								typeNode.BaseTypes.Add(baseTypeNode);
+								baseTypeNode.DerivedTypes.Add(typeNode);
+							}
+						}
+					}
+				}
+			}
+		}
+		
+		public TypeGraphNode GetNode(ITypeDefinition typeDefinition)
+		{
+			if (typeDefinition == null)
+				return null;
+			return GetNode(new AssemblyQualifiedTypeName(typeDefinition));
+		}
+		
+		public TypeGraphNode GetNode(AssemblyQualifiedTypeName typeName)
+		{
+			TypeGraphNode node;
+			if (dict.TryGetValue(typeName, out node))
+				return node;
+			else
+				return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/TypeGraphNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/TypeGraphNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Analysis/TypeGraphNode.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// Copyright (c) 2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Analysis
+{
+	public sealed class TypeGraphNode
+	{
+		readonly ITypeDefinition typeDef;
+		readonly List<TypeGraphNode> baseTypes = new List<TypeGraphNode>();
+		readonly List<TypeGraphNode> derivedTypes = new List<TypeGraphNode>();
+		
+		/// <summary>
+		/// Creates a new unconnected type graph node.
+		/// </summary>
+		public TypeGraphNode(ITypeDefinition typeDef)
+		{
+			this.typeDef = typeDef;
+		}
+		
+		public ITypeDefinition TypeDefinition {
+			get { return typeDef; }
+		}
+		
+		public IList<TypeGraphNode> DerivedTypes {
+			get { return derivedTypes; }
+		}
+		
+		public IList<TypeGraphNode> BaseTypes {
+			get { return baseTypes; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/CompletionCategory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/CompletionCategory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/CompletionCategory.cs	(revision 11807)
@@ -0,0 +1,49 @@
+﻿// 
+// CompletionCategory.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	public abstract class CompletionCategory : IComparable<CompletionCategory>
+	{
+		public string DisplayText { get; set; }
+		
+		public string Icon { get; set; }
+		
+		protected CompletionCategory ()
+		{
+		}
+		
+		protected CompletionCategory (string displayText, string icon)
+		{
+			this.DisplayText = displayText;
+			this.Icon = icon;
+		}
+		
+		public abstract int CompareTo (CompletionCategory other);
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/CompletionExtensionMethods.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/CompletionExtensionMethods.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/CompletionExtensionMethods.cs	(revision 11807)
@@ -0,0 +1,72 @@
+//
+// CompletionExtensionMethods.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	public static class CompletionExtensionMethods
+	{
+		/// <summary>
+		/// Gets the EditorBrowsableState of an entity.
+		/// </summary>
+		/// <returns>
+		/// The editor browsable state.
+		/// </returns>
+		/// <param name='entity'>
+		/// Entity.
+		/// </param>
+		public static System.ComponentModel.EditorBrowsableState GetEditorBrowsableState(this IEntity entity)
+		{
+			if (entity == null)
+				throw new ArgumentNullException ("entity");
+
+			var browsableState = entity.Attributes.FirstOrDefault(attr => attr.AttributeType.Name == "EditorBrowsableAttribute" && attr.AttributeType.Namespace == "System.ComponentModel");
+			if (browsableState != null && browsableState.PositionalArguments.Count == 1) {
+				if (browsableState.PositionalArguments [0].ConstantValue is int)
+					return (System.ComponentModel.EditorBrowsableState)(int)browsableState.PositionalArguments [0].ConstantValue;
+			}
+			return System.ComponentModel.EditorBrowsableState.Always;
+		}
+		
+		/// <summary>
+		/// Determines if an entity should be shown in the code completion window. This is the same as:
+		/// <c>GetEditorBrowsableState (entity) != System.ComponentModel.EditorBrowsableState.Never</c>
+		/// </summary>
+		/// <returns>
+		/// <c>true</c> if the entity should be shown; otherwise, <c>false</c>.
+		/// </returns>
+		/// <param name='entity'>
+		/// The entity.
+		/// </param>
+		public static bool IsBrowsable(this IEntity entity)
+		{
+			return GetEditorBrowsableState (entity) != System.ComponentModel.EditorBrowsableState.Never;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/DisplayFlags.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/DisplayFlags.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/DisplayFlags.cs	(revision 11807)
@@ -0,0 +1,42 @@
+// 
+// DisplayFlags.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	[Flags]
+	public enum DisplayFlags
+	{
+		None = 0,
+		Hidden = 1,
+		Obsolete = 2,
+		DescriptionHasMarkup = 4,
+		NamedArgument = 8,
+		IsImportCompletion = 16,
+		MarkedBold = 32
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/FrameworkLookup.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/FrameworkLookup.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/FrameworkLookup.cs	(revision 11807)
@@ -0,0 +1,490 @@
+//
+// FrameworkLookup.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	/// <summary>
+	/// The framework lookup provides a fast lookup where an unknow type or extension method may be defined in.
+	/// </summary>
+	public sealed class FrameworkLookup 
+	{
+		/*		 Binary format:
+		 * [Header]
+		 *    [Version] : [Major (byte)] [Minor (byte)] [Build  (byte)]
+		 * 	  [#Types (int)]
+		 *    [#Methods (int)]
+		 *    [#Assemblies (int)]
+		 * [AssemblyListTable] : #Assemblies x [OffsetToAssemblyLists (int)]
+		 * [TypeLookupTable] : #Types x ( [NameHash (int)] [AssemblyPtrToAssemblyListTable (ushort)]
+		 * [ExtMethodLookupTable] : #Methods x ( [NameHash (int)] [AssemblyPtrToAssemblyListTable (ushort)]
+		 * [AssemblyLists] 
+		 *    [#Count (byte)]
+		 *    #Count x [AssemblyLookup] : [Package (string)] [FullName (string)] [Namespace (string)] 
+		*/
+		const int headerSize = 
+			3 + // Version
+			4 + // #Types
+			4 + // #Methods
+			4   // #Assembly
+			/*			+ 4*/;
+
+		public static readonly Version CurrentVersion = new Version (2, 0, 1);
+		public static readonly FrameworkLookup Empty = new FrameworkLookup ();
+
+		string fileName;
+		int[] assemblyListTable;
+		int[] typeLookupTable;
+		int[] extLookupTable;
+
+		/// <summary>
+		/// This method tries to get a matching extension method.
+		/// </summary>
+		/// <returns>The extension method lookups.</returns>
+		/// <param name="resolveResult">The resolve result.</param>
+		public IEnumerable<AssemblyLookup> GetExtensionMethodLookups (UnknownMemberResolveResult resolveResult)
+		{
+			return GetLookup (resolveResult.MemberName, extLookupTable, headerSize + assemblyListTable.Length * 4 + typeLookupTable.Length * 8);
+		}
+
+		/// <summary>
+		/// Tries to get a type out of an unknow identifier result.
+		/// </summary>
+		/// <returns>The assemblies the type may be defined (if any).</returns>
+		/// <param name="resolveResult">The resolve result.</param>
+		/// <param name="typeParameterCount">Type parameter count.</param>
+		/// <param name="isInsideAttributeType">If set to <c>true</c> this resolve result may be inside an attribute.</param>
+		public IEnumerable<AssemblyLookup> GetLookups (UnknownIdentifierResolveResult resolveResult, int typeParameterCount, bool isInsideAttributeType)
+		{
+			string name = isInsideAttributeType ? resolveResult.Identifier + "Attribute" : resolveResult.Identifier;
+
+			var identifier = GetIdentifier (name, typeParameterCount);
+			return GetLookup (identifier, typeLookupTable, headerSize + assemblyListTable.Length * 4);
+		}
+
+		/// <summary>
+		/// Tries to get a type out of an unknow member resolve result. (In case of fully qualified names)
+		/// </summary>
+		/// <returns>The assemblies the type may be defined (if any).</returns>
+		/// <param name="resolveResult">The resolve result.</param>
+		/// <param name="fullMemberName"></param>
+		/// <param name="typeParameterCount">Type parameter count.</param>
+		/// <param name="isInsideAttributeType">If set to <c>true</c> this resolve result may be inside an attribute.</param>
+		public IEnumerable<AssemblyLookup> GetLookups (UnknownMemberResolveResult resolveResult, string fullMemberName, int typeParameterCount, bool isInsideAttributeType)
+		{
+			string name = isInsideAttributeType ? resolveResult.MemberName + "Attribute" : resolveResult.MemberName;
+
+			var identifier = GetIdentifier (name, typeParameterCount);
+			foreach (var lookup in GetLookup (identifier, typeLookupTable, headerSize + assemblyListTable.Length * 4)) {
+				if (fullMemberName.StartsWith (lookup.Namespace, StringComparison.Ordinal))
+					yield return lookup;
+			}
+		}
+
+		/// <summary>
+		/// The assembly lookup determines where a type might be defined.
+		/// It contains the assembly &amp; the namespace.
+		/// </summary>
+		public struct AssemblyLookup
+		{
+			readonly string nspace;
+
+			/// <summary>
+			/// The namespace the requested type is in.
+			/// </summary>
+			public string Namespace {
+				get {
+					return nspace;
+				}
+			}
+
+			readonly string fullName;
+			/// <summary>
+			/// Gets the full name af the assembly.
+			/// </summary>
+			public string FullName {
+				get {
+					return fullName;
+				}
+			}
+
+			readonly string package;
+			/// <summary>
+			/// Gets the package the assembly is in.
+			/// </summary>
+			public string Package {
+				get {
+					return package;
+				}
+			}
+
+			/// <summary>
+			/// Initializes a new instance of the <see cref="AssemblyLookup"/> struct.
+			/// </summary>
+			/// <param name="package">The package name.</param>
+			/// <param name="fullName">The full name of the assembly.</param>
+			/// <param name="nspace">The namespace the type is in.</param>
+			internal AssemblyLookup (string package, string fullName, string nspace)
+			{
+				if (nspace == null)
+					throw new ArgumentNullException ("nspace");
+				if (fullName == null)
+					throw new ArgumentNullException ("fullName");
+				this.package = package;
+				this.fullName = fullName;
+				this.nspace = nspace;
+			}
+
+			public override string ToString ()
+			{
+				return string.Format ("[AssemblyLookup: Namespace={0}, FullName={1}, Package={2}]", Namespace, FullName, Package);
+			}
+
+			public override bool Equals (object obj)
+			{
+				if (obj == null)
+					return false;
+				//					if (ReferenceEquals (this, obj))
+				//						return true;
+				if (obj.GetType () != typeof(AssemblyLookup))
+					return false;
+				var other = (AssemblyLookup)obj;
+				return Namespace == other.Namespace && FullName == other.FullName && Package == other.Package;
+			}
+
+			public override int GetHashCode ()
+			{
+				unchecked {
+					return (Namespace != null ? Namespace.GetHashCode () : 0) ^
+						(FullName != null ? FullName.GetHashCode () : 0) ^ 
+						(Package != null ? Package.GetHashCode () : 0);
+				}
+			}
+		}
+
+		/// <summary>
+		/// This method returns a new framework builder to build a new framework lookup data file.
+		/// </summary>
+		/// <param name="fileName">The file name of the data file.</param>
+		public static FrameworkBuilder Create (string fileName)
+		{
+			return new FrameworkBuilder (fileName);
+		}
+
+		/// <summary>
+		/// Loads a framework lookup object from a file. May return null, if the file wasn't found or has a version mismatch.
+		/// </summary>
+		/// <param name="fileName">File name.</param>
+		public static FrameworkLookup Load (string fileName)
+		{
+			try {
+				if (!File.Exists (fileName))
+					return null;
+			} catch (Exception) {
+				return null;
+			}
+			var result = new FrameworkLookup ();
+			result.fileName = fileName;
+			var fs = File.OpenRead (fileName);
+			using (var reader = new BinaryReader (fs, Encoding.UTF8)) {
+				var major = reader.ReadByte ();
+				var minor = reader.ReadByte ();
+				var build = reader.ReadByte ();
+				var version = new Version (major, minor, build);
+				if (version != CurrentVersion)
+					return null;
+				int typeLookupListCount = reader.ReadInt32 ();
+				int extLookupListCount = reader.ReadInt32 ();
+				int assemblyLookupCount = reader.ReadInt32 ();
+
+				result.assemblyListTable = new int[assemblyLookupCount];
+				for (int i = 0; i < assemblyLookupCount; i++) {
+					result.assemblyListTable[i] = reader.ReadInt32 ();
+				}
+
+				result.typeLookupTable = new int[typeLookupListCount];
+				for (int i = 0; i < typeLookupListCount; i++) {
+					result.typeLookupTable [i] = reader.ReadInt32 ();
+					// skip list offset
+					reader.ReadInt32 ();
+				}
+
+				result.extLookupTable = new int[extLookupListCount];
+				for (int i = 0; i < extLookupListCount; i++) {
+					result.extLookupTable [i] = reader.ReadInt32 ();
+					// skip list offset
+					reader.ReadInt32 ();
+				}
+			}
+			return result;
+		}
+
+		FrameworkLookup ()
+		{
+		}
+
+		IEnumerable<AssemblyLookup> GetLookup (string identifier, int[] lookupTable, int tableOffset)
+		{
+			if (lookupTable == null)
+				yield break;
+
+			int index = Array.BinarySearch (lookupTable, GetStableHashCode (identifier));
+			if (index < 0)
+				yield break;
+
+			using (var reader = new BinaryReader (File.Open (fileName, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8)) {
+				reader.BaseStream.Seek (tableOffset + index * 8 + 4, SeekOrigin.Begin);
+				int listPtr = reader.ReadInt32 ();
+
+				reader.BaseStream.Seek (listPtr, SeekOrigin.Begin);
+				var b = reader.ReadInt32 ();
+				var assemblies = new List<ushort> ();
+				while (b-- > 0) {
+					var assembly = reader.ReadUInt16 ();
+					if (assembly < 0 || assembly >= assemblyListTable.Length)
+						throw new InvalidDataException ("Assembly lookup was " + assembly + " but only " + assemblyListTable.Length + " are known.");
+					assemblies.Add (assembly);
+				}
+				foreach (var assembly in assemblies) {
+					reader.BaseStream.Seek (assemblyListTable [assembly], SeekOrigin.Begin);
+
+					var package = reader.ReadString ();
+					var fullName = reader.ReadString ();
+					var ns = reader.ReadString ();
+					yield return new AssemblyLookup (package, fullName, ns);
+				}
+			}
+		}
+
+		/// <summary>
+		/// Retrieves a hash code for the specified string that is stable across
+		/// .NET upgrades.
+		/// 
+		/// Use this method instead of the normal <c>string.GetHashCode</c> if the hash code
+		/// is persisted to disk.
+		/// </summary>
+		static int GetStableHashCode(string text)
+		{
+			unchecked {
+				int h = 0;
+				foreach (char c in text) {
+					h = (h << 5) - h + c;
+				}
+				return h;
+			}
+		}
+
+		static string GetIdentifier (string identifier, int tc)
+		{
+			if (tc == 0)
+				return identifier;
+			return identifier + "`" + tc;
+		}
+
+		public class FrameworkBuilder : IDisposable
+		{
+			readonly string fileName;
+
+			Dictionary<int, List<ushort>> typeLookup = new Dictionary<int, List<ushort>>  ();
+			Dictionary<int, List<ushort>> extensionMethodLookup = new Dictionary<int, List<ushort>>  ();
+			List<AssemblyLookup> assemblyLookups = new List<AssemblyLookup> ();
+			Dictionary<int, string> methodCheck = new Dictionary<int, string> ();
+			Dictionary<int, string> typeCheck = new Dictionary<int, string> ();
+
+			internal FrameworkBuilder (string fileName)
+			{
+				this.fileName = fileName;
+			}
+
+			static int[] WriteTable (MemoryStream stream, Dictionary<int, List<ushort>> table, out List<KeyValuePair<int, List<ushort>>> list)
+			{
+				list = new List<KeyValuePair<int, List<ushort>>> (table);
+				list.Sort ((x, y) => x.Key.CompareTo (y.Key));
+
+				var result = new int[list.Count];
+				using (var bw = new BinaryWriter (stream)) {
+					for (int i = 0; i < result.Length; i++) {
+						result [i] = (int)stream.Length;
+						bw.Write (list [i].Value.Count);
+						foreach (var ii in list [i].Value)
+							bw.Write (ii);
+					}
+				}
+
+				return result;
+			}
+
+			#region IDisposable implementation
+
+			void IDisposable.Dispose ()
+			{
+				var typeLookupMemory = new MemoryStream ();
+				List<KeyValuePair<int, List<ushort>>> typeLookupList;
+				var typeTable = WriteTable (typeLookupMemory, typeLookup, out typeLookupList);
+
+				var extMethodLookupMemory = new MemoryStream ();
+				List<KeyValuePair<int, List<ushort>>> extMethodLookuplist;
+				var extMethodTable = WriteTable (extMethodLookupMemory, extensionMethodLookup, out extMethodLookuplist);
+
+				var assemblyLookupMemory = new MemoryStream ();
+				var assemblyPositionTable = new int[assemblyLookups.Count];
+				using (var writer = new BinaryWriter (assemblyLookupMemory, Encoding.UTF8)) {
+					for (int i = 0; i < assemblyLookups.Count; i++) {
+						var lookup = assemblyLookups[i];
+						assemblyPositionTable[i] = (int)assemblyLookupMemory.Length;
+						writer.Write (lookup.Package);
+						writer.Write (lookup.FullName);
+						writer.Write (lookup.Namespace);
+					}
+				}
+
+				using (var stream = new BinaryWriter (File.OpenWrite (fileName), Encoding.UTF8)) {
+					stream.Write ((byte)CurrentVersion.Major);
+					stream.Write ((byte)CurrentVersion.Minor);
+					stream.Write ((byte)CurrentVersion.Build);
+
+					stream.Write (typeLookupList.Count);
+					stream.Write (extMethodLookuplist.Count);
+					stream.Write (assemblyLookups.Count);
+
+					var typeBuffer = typeLookupMemory.ToArray ();
+					var extMethodBuffer = extMethodLookupMemory.ToArray ();
+
+					int dataOffset = 
+						headerSize + 
+						assemblyLookups.Count * 4 + 
+						typeLookupList.Count * (4 + 4) + 
+						extMethodLookuplist.Count * (4 + 4);
+
+					for (int i = 0; i < assemblyLookups.Count; i++) {
+						stream.Write ((int)(dataOffset + typeBuffer.Length + extMethodBuffer.Length + assemblyPositionTable[i]));
+					}
+
+					for (int i = 0; i < typeLookupList.Count; i++) {
+						stream.Write (typeLookupList [i].Key);
+						stream.Write (dataOffset + typeTable[i]);
+					}
+
+					for (int i = 0; i < extMethodLookuplist.Count; i++) {
+						stream.Write (extMethodLookuplist [i].Key);
+						stream.Write (dataOffset + typeBuffer.Length + extMethodTable[i]);
+					}
+
+					stream.Write (typeBuffer);
+					stream.Write (extMethodBuffer);
+					stream.Write (assemblyLookupMemory.ToArray ());
+					stream.Flush ();
+				}
+			}
+			#endregion
+
+			struct FrameworkLookupId 
+			{
+				public string PackageName;
+				public string AssemblyName;
+				public string NameSpace;
+			}
+
+			Dictionary<FrameworkLookupId, ushort> frameworkLookupTable = new Dictionary<FrameworkLookupId, ushort> ();
+			ushort GetLookup (string packageName, string assemblyName, string ns)
+			{
+				var id = new FrameworkLookupId {
+					PackageName = packageName,
+					AssemblyName = assemblyName,
+					NameSpace = ns
+				};
+				ushort value;
+				if (frameworkLookupTable.TryGetValue (id, out value))
+					return value;
+
+				var result = new AssemblyLookup (packageName, assemblyName, ns);
+				assemblyLookups.Add (result);
+				var index = assemblyLookups.Count - 1;
+				if (index > ushort.MaxValue)
+					throw new InvalidOperationException ("Assembly lookup list overflow > " + ushort.MaxValue + " assemblies.");
+				frameworkLookupTable.Add (id, (ushort)index);
+				return (ushort)index;
+			}
+
+			bool AddToTable (string packageName, string assemblyName, Dictionary<int, List<ushort>> table, Dictionary<int, string> checkTable, string id, string ns)
+			{
+				List<ushort> list;
+				var hash = GetStableHashCode (id);
+
+				if (!table.TryGetValue (hash, out list)) {
+					list = new List<ushort> ();
+					table [hash] = list;
+				} else {
+					string existingString;
+					if (checkTable.TryGetValue (hash, out existingString)) {
+						if (existingString != id)
+							throw new InvalidOperationException ("Duplicate hash for " + existingString + " and "+ id); 
+					} else {
+						checkTable.Add (hash, id);
+					}
+				}
+				var assemblyLookup = GetLookup (packageName, assemblyName, ns);
+				if (!list.Any (a => a.Equals (assemblyLookup))) {
+					list.Add (assemblyLookup);
+					return true;
+				}
+				return false;
+			}
+
+			/// <summary>
+			/// Add a type to the framework lookup.
+			/// </summary>
+			/// <param name="packageName">The package the assembly of the type is defined (can be null).</param>
+			/// <param name="fullAssemblyName">The full assembly name the type is defined (needs to be != null).</param>
+			/// <param name="type">The type definition  (needs to be != null).</param>
+			public void AddLookup (string packageName, string fullAssemblyName, IUnresolvedTypeDefinition type)
+			{
+				if (fullAssemblyName == null)
+					throw new ArgumentNullException ("fullAssemblyName");
+				if (type == null)
+					throw new ArgumentNullException ("type");
+				var id = GetIdentifier (type.Name, type.TypeParameters.Count);
+				if (AddToTable (packageName, fullAssemblyName, typeLookup, typeCheck, id, type.Namespace)) {
+					if (type.IsSealed || type.IsStatic) {
+						foreach (var method in type.Methods) {
+							var m = method as DefaultUnresolvedMethod;
+							if (m == null || !m.IsExtensionMethod)
+								continue;
+							AddToTable (packageName, fullAssemblyName, extensionMethodLookup, methodCheck, method.Name, method.DeclaringTypeDefinition.Namespace);
+						}
+					}
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/ICompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/ICompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/ICompletionData.cs	(revision 11807)
@@ -0,0 +1,53 @@
+// 
+// ICompletionData.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	public interface ICompletionData
+	{
+		CompletionCategory CompletionCategory { get; set; }
+		
+		string DisplayText { get; set; }
+
+		string Description { get; set; }
+		
+		string CompletionText { get; set; }
+		
+		DisplayFlags DisplayFlags { get; set; }
+		
+		bool HasOverloads { 
+			get;
+		}
+		
+		IEnumerable<ICompletionData> OverloadedData {
+			get;
+		}
+		
+		void AddOverload (ICompletionData data);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IEntityCompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IEntityCompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IEntityCompletionData.cs	(revision 11807)
@@ -0,0 +1,37 @@
+// 
+// IEntityCompletionData.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	public interface IEntityCompletionData : ICompletionData
+	{
+		IEntity Entity {
+			get;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IParameterDataProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IParameterDataProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IParameterDataProvider.cs	(revision 11807)
@@ -0,0 +1,84 @@
+// 
+// IParameterDataProvider.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	/// <summary>
+	/// Provides intellisense information for a collection of parametrized members.
+	/// </summary>
+	public interface IParameterDataProvider
+	{
+		/// <summary>
+		/// Gets the overload count.
+		/// </summary>
+		int Count { 
+			get; 
+		}
+		
+		/// <summary>
+		/// Gets the start offset of the parameter expression node.
+		/// </summary>
+		int StartOffset { 
+			get; 
+		}
+		
+		/// <summary>
+		/// Returns the markup to use to represent the specified method overload
+		/// in the parameter information window.
+		/// </summary>
+		string GetHeading (int overload, string[] parameterDescription, int currentParameter);
+		
+		/// <summary>
+		/// Returns the markup for the description to use to represent the specified method overload
+		/// in the parameter information window.
+		/// </summary>
+		string GetDescription (int overload, int currentParameter);
+		
+		/// <summary>
+		/// Returns the text to use to represent the specified parameter
+		/// </summary>
+		string GetParameterDescription (int overload, int paramIndex);
+		
+		/// <summary>
+		/// Gets the name of the parameter.
+		/// </summary>
+		string GetParameterName (int overload, int currentParameter);
+
+		/// <summary>
+		/// Returns the number of parameters of the specified method
+		/// </summary>
+		int GetParameterCount (int overload);
+		
+		/// <summary>
+		/// Used for the params lists. (for example "params" in c#).
+		/// </summary>
+		bool AllowParameterList (int overload);
+	}
+}
+
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IVariableCompletionData.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IVariableCompletionData.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Completion/IVariableCompletionData.cs	(revision 11807)
@@ -0,0 +1,38 @@
+// 
+// IVariableCompletionData.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Completion
+{
+	public interface IVariableCompletionData : ICompletionData
+	{
+		IVariable Variable {
+			get;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/DocumentationComment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/DocumentationComment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/DocumentationComment.cs	(revision 11807)
@@ -0,0 +1,95 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Documentation
+{
+	/// <summary>
+	/// Represents a documentation comment.
+	/// </summary>
+	public class DocumentationComment
+	{
+		ITextSource xml;
+		protected readonly ITypeResolveContext context;
+		
+		/// <summary>
+		/// Gets the XML code for this documentation comment.
+		/// </summary>
+		public ITextSource Xml {
+			get { return xml; }
+		}
+		
+		/// <summary>
+		/// Creates a new DocumentationComment.
+		/// </summary>
+		/// <param name="xml">The XML text.</param>
+		/// <param name="context">Context for resolving cref attributes.</param>
+		public DocumentationComment(ITextSource xml, ITypeResolveContext context)
+		{
+			if (xml == null)
+				throw new ArgumentNullException("xml");
+			if (context == null)
+				throw new ArgumentNullException("context");
+			this.xml = xml;
+			this.context = context;
+		}
+		
+		/// <summary>
+		/// Creates a new DocumentationComment.
+		/// </summary>
+		/// <param name="xml">The XML text.</param>
+		/// <param name="context">Context for resolving cref attributes.</param>
+		public DocumentationComment(string xml, ITypeResolveContext context)
+		{
+			if (xml == null)
+				throw new ArgumentNullException("xml");
+			if (context == null)
+				throw new ArgumentNullException("context");
+			this.xml = new StringTextSource(xml);
+			this.context = context;
+		}
+		
+		/// <summary>
+		/// Resolves the given cref value to an entity.
+		/// Returns null if the entity is not found, or if the cref attribute is syntactically invalid.
+		/// </summary>
+		public virtual IEntity ResolveCref(string cref)
+		{
+			try {
+				return IdStringProvider.FindEntity(cref, context);
+			} catch (ReflectionNameParseException) {
+				return null;
+			}
+		}
+		
+		public override string ToString ()
+		{
+			return Xml.Text;
+		}
+		
+		public static implicit operator string (DocumentationComment documentationComment)
+		{
+			if (documentationComment != null)
+				return documentationComment.ToString ();
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/GetPotentiallyNestedClassTypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/GetPotentiallyNestedClassTypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/GetPotentiallyNestedClassTypeReference.cs	(revision 11807)
@@ -0,0 +1,71 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.Documentation
+{
+	/// <summary>
+	/// A type reference of the form 'Some.Namespace.TopLevelType.NestedType`n'.
+	/// We do not know the boundary between namespace name and top level type, so we have to try
+	/// all possibilities.
+	/// The type parameter count only applies to the innermost type, all outer types must be non-generic.
+	/// </summary>
+	[Serializable]
+	class GetPotentiallyNestedClassTypeReference : ITypeReference
+	{
+		readonly string typeName;
+		readonly int typeParameterCount;
+		
+		public GetPotentiallyNestedClassTypeReference(string typeName, int typeParameterCount)
+		{
+			this.typeName = typeName;
+			this.typeParameterCount = typeParameterCount;
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			string[] parts = typeName.Split('.');
+			var assemblies = new [] { context.CurrentAssembly }.Concat(context.Compilation.Assemblies);
+			for (int i = parts.Length - 1; i >= 0; i--) {
+				string ns = string.Join(".", parts, 0, i);
+				string name = parts[i];
+				int topLevelTPC = (i == parts.Length - 1 ? typeParameterCount : 0);
+				foreach (var asm in assemblies) {
+					if (asm == null)
+						continue;
+					ITypeDefinition typeDef = asm.GetTypeDefinition(new TopLevelTypeName(ns, name, topLevelTPC));
+					for (int j = i + 1; j < parts.Length && typeDef != null; j++) {
+						int tpc = (j == parts.Length - 1 ? typeParameterCount : 0);
+						typeDef = typeDef.NestedTypes.FirstOrDefault(n => n.Name == parts[j] && n.TypeParameterCount == tpc);
+					}
+					if (typeDef != null)
+						return typeDef;
+				}
+			}
+			int idx = typeName.LastIndexOf('.');
+			if (idx < 0)
+				return new UnknownType("", typeName, typeParameterCount);
+			// give back a guessed namespace/type name
+			return  new UnknownType(typeName.Substring(0, idx), typeName.Substring(idx + 1), typeParameterCount);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IDocumentationProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IDocumentationProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IDocumentationProvider.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Documentation
+{
+	/// <summary>
+	/// Provides XML documentation for entities.
+	/// </summary>
+	public interface IDocumentationProvider
+	{
+		/// <summary>
+		/// Gets the XML documentation for the specified entity.
+		/// </summary>
+		DocumentationComment GetDocumentation(IEntity entity);
+	}
+	
+	/// <summary>
+	/// Provides XML documentation for entities.
+	/// </summary>
+	public interface IUnresolvedDocumentationProvider
+	{
+		/// <summary>
+		/// Gets the XML documentation for the specified entity.
+		/// </summary>
+		string GetDocumentation(IUnresolvedEntity entity);
+		
+		/// <summary>
+		/// Gets the XML documentation for the specified entity.
+		/// </summary>
+		DocumentationComment GetDocumentation(IUnresolvedEntity entity, IEntity resolvedEntity);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IdStringMemberReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IdStringMemberReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IdStringMemberReference.cs	(revision 11807)
@@ -0,0 +1,77 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Documentation
+{
+	[Serializable]
+	class IdStringMemberReference : IMemberReference
+	{
+		readonly ITypeReference declaringTypeReference;
+		readonly char memberType;
+		readonly string memberIdString;
+		
+		public IdStringMemberReference(ITypeReference declaringTypeReference, char memberType, string memberIdString)
+		{
+			this.declaringTypeReference = declaringTypeReference;
+			this.memberType = memberType;
+			this.memberIdString = memberIdString;
+		}
+		
+		bool CanMatch(IUnresolvedMember member)
+		{
+			switch (member.SymbolKind) {
+				case SymbolKind.Field:
+					return memberType == 'F';
+				case SymbolKind.Property:
+				case SymbolKind.Indexer:
+					return memberType == 'P';
+				case SymbolKind.Event:
+					return memberType == 'E';
+				case SymbolKind.Method:
+				case SymbolKind.Operator:
+				case SymbolKind.Constructor:
+				case SymbolKind.Destructor:
+					return memberType == 'M';
+				default:
+					throw new NotSupportedException(member.SymbolKind.ToString());
+			}
+		}
+		
+		public ITypeReference DeclaringTypeReference {
+			get { return declaringTypeReference; }
+		}
+		
+		public IMember Resolve(ITypeResolveContext context)
+		{
+			IType declaringType = declaringTypeReference.Resolve(context);
+			foreach (var member in declaringType.GetMembers(CanMatch, GetMemberOptions.IgnoreInheritedMembers)) {
+				if (IdStringProvider.GetIdString(member) == memberIdString)
+					return member;
+			}
+			return null;
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return Resolve(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IdStringProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IdStringProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/IdStringProvider.cs	(revision 11807)
@@ -0,0 +1,391 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Text;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.Documentation
+{
+	/// <summary>
+	/// Provides ID strings for entities. (C# 4.0 spec, §A.3.1)
+	/// ID strings are used to identify members in XML documentation files.
+	/// </summary>
+	public static class IdStringProvider
+	{
+		#region GetIdString
+		/// <summary>
+		/// Gets the ID string (C# 4.0 spec, §A.3.1) for the specified entity.
+		/// </summary>
+		public static string GetIdString(this IEntity entity)
+		{
+			StringBuilder b = new StringBuilder();
+			switch (entity.SymbolKind) {
+				case SymbolKind.TypeDefinition:
+					b.Append("T:");
+					AppendTypeName(b, (ITypeDefinition)entity, false);
+					return b.ToString();
+				case SymbolKind.Field:
+					b.Append("F:");
+					break;
+				case SymbolKind.Property:
+				case SymbolKind.Indexer:
+					b.Append("P:");
+					break;
+				case SymbolKind.Event:
+					b.Append("E:");
+					break;
+				default:
+					b.Append("M:");
+					break;
+			}
+			IMember member = (IMember)entity;
+			AppendTypeName(b, member.DeclaringType, false);
+			b.Append('.');
+			if (member.IsExplicitInterfaceImplementation && member.Name.IndexOf('.') < 0 && member.ImplementedInterfaceMembers.Count == 1) {
+				AppendTypeName(b, member.ImplementedInterfaceMembers[0].DeclaringType, true);
+				b.Append('#');
+			}
+			b.Append(member.Name.Replace('.', '#'));
+			IMethod method = member as IMethod;
+			if (method != null && method.TypeParameters.Count > 0) {
+				b.Append("``");
+				b.Append(method.TypeParameters.Count);
+			}
+			IParameterizedMember parameterizedMember = member as IParameterizedMember;
+			if (parameterizedMember != null && parameterizedMember.Parameters.Count > 0) {
+				b.Append('(');
+				var parameters = parameterizedMember.Parameters;
+				for (int i = 0; i < parameters.Count; i++) {
+					if (i > 0) b.Append(',');
+					AppendTypeName(b, parameters[i].Type, false);
+				}
+				b.Append(')');
+			}
+			if (member.SymbolKind == SymbolKind.Operator && (member.Name == "op_Implicit" || member.Name == "op_Explicit")) {
+				b.Append('~');
+				AppendTypeName(b, member.ReturnType, false);
+			}
+			return b.ToString();
+		}
+		#endregion
+		
+		#region GetTypeName
+		public static string GetTypeName(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			StringBuilder b = new StringBuilder();
+			AppendTypeName(b, type, false);
+			return b.ToString();
+		}
+		
+		static void AppendTypeName(StringBuilder b, IType type, bool explicitInterfaceImpl)
+		{
+			switch (type.Kind) {
+				case TypeKind.Dynamic:
+					b.Append(explicitInterfaceImpl ? "System#Object" : "System.Object");
+					break;
+				case TypeKind.TypeParameter:
+					ITypeParameter tp = (ITypeParameter)type;
+					if (explicitInterfaceImpl) {
+						b.Append(tp.Name);
+					} else {
+						b.Append('`');
+						if (tp.OwnerType == SymbolKind.Method)
+							b.Append('`');
+						b.Append(tp.Index);
+					}
+					break;
+				case TypeKind.Array:
+					ArrayType array = (ArrayType)type;
+					AppendTypeName(b, array.ElementType, explicitInterfaceImpl);
+					b.Append('[');
+					if (array.Dimensions > 1) {
+						for (int i = 0; i < array.Dimensions; i++) {
+							if (i > 0)
+								b.Append(explicitInterfaceImpl ? '@' : ',');
+							if (!explicitInterfaceImpl)
+								b.Append("0:");
+						}
+					}
+					b.Append(']');
+					break;
+				case TypeKind.Pointer:
+					AppendTypeName(b, ((PointerType)type).ElementType, explicitInterfaceImpl);
+					b.Append('*');
+					break;
+				case TypeKind.ByReference:
+					AppendTypeName(b, ((ByReferenceType)type).ElementType, explicitInterfaceImpl);
+					b.Append('@');
+					break;
+				default:
+					IType declType = type.DeclaringType;
+					if (declType != null) {
+						AppendTypeName(b, declType, explicitInterfaceImpl);
+						b.Append(explicitInterfaceImpl ? '#' : '.');
+						b.Append(type.Name);
+						AppendTypeParameters(b, type, declType.TypeParameterCount, explicitInterfaceImpl);
+					} else {
+						if (explicitInterfaceImpl)
+							b.Append(type.FullName.Replace('.', '#'));
+						else
+							b.Append(type.FullName);
+						AppendTypeParameters(b, type, 0, explicitInterfaceImpl);
+					}
+					break;
+			}
+		}
+		
+		static void AppendTypeParameters(StringBuilder b, IType type, int outerTypeParameterCount, bool explicitInterfaceImpl)
+		{
+			int tpc = type.TypeParameterCount - outerTypeParameterCount;
+			if (tpc > 0) {
+				ParameterizedType pt = type as ParameterizedType;
+				if (pt != null) {
+					b.Append('{');
+					var ta = pt.TypeArguments;
+					for (int i = outerTypeParameterCount; i < ta.Count; i++) {
+						if (i > outerTypeParameterCount)
+							b.Append(explicitInterfaceImpl ? '@' : ',');
+						AppendTypeName(b, ta[i], explicitInterfaceImpl);
+					}
+					b.Append('}');
+				} else {
+					b.Append('`');
+					b.Append(tpc);
+				}
+			}
+		}
+		#endregion
+		
+		#region ParseMemberName
+		/// <summary>
+		/// Parse the ID string into a member reference.
+		/// </summary>
+		/// <param name="memberIdString">The ID string representing the member (with "M:", "F:", "P:" or "E:" prefix).</param>
+		/// <returns>A member reference that represents the ID string.</returns>
+		/// <exception cref="ReflectionNameParseException">The syntax of the ID string is invalid</exception>
+		/// <remarks>
+		/// The member reference will look in <see cref="ITypeResolveContext.CurrentAssembly"/> first,
+		/// and if the member is not found there,
+		/// it will look in all other assemblies of the compilation.
+		/// </remarks>
+		public static IMemberReference ParseMemberIdString(string memberIdString)
+		{
+			if (memberIdString == null)
+				throw new ArgumentNullException("memberIdString");
+			if (memberIdString.Length < 2 || memberIdString[1] != ':')
+				throw new ReflectionNameParseException(0, "Missing type tag");
+			char typeChar = memberIdString[0];
+			int parenPos = memberIdString.IndexOf('(');
+			if (parenPos < 0)
+				parenPos = memberIdString.LastIndexOf('~');
+			if (parenPos < 0)
+				parenPos = memberIdString.Length;
+			int dotPos = memberIdString.LastIndexOf('.', parenPos - 1);
+			if (dotPos < 0)
+				throw new ReflectionNameParseException(0, "Could not find '.' separating type name from member name");
+			string typeName = memberIdString.Substring(0, dotPos);
+			int pos = 2;
+			ITypeReference typeReference = ParseTypeName(typeName, ref pos);
+			if (pos != typeName.Length)
+				throw new ReflectionNameParseException(pos, "Expected end of type name");
+//			string memberName = memberIDString.Substring(dotPos + 1, parenPos - (dotPos + 1));
+//			pos = memberName.LastIndexOf("``");
+//			if (pos > 0)
+//				memberName = memberName.Substring(0, pos);
+//			memberName = memberName.Replace('#', '.');
+			return new IdStringMemberReference(typeReference, typeChar, memberIdString);
+		}
+		#endregion
+		
+		#region ParseTypeName
+		/// <summary>
+		/// Parse the ID string type name into a type reference.
+		/// </summary>
+		/// <param name="typeName">The ID string representing the type (the "T:" prefix is optional).</param>
+		/// <returns>A type reference that represents the ID string.</returns>
+		/// <exception cref="ReflectionNameParseException">The syntax of the ID string is invalid</exception>
+		/// <remarks>
+		/// <para>
+		/// The type reference will look in <see cref="ITypeResolveContext.CurrentAssembly"/> first,
+		/// and if the type is not found there,
+		/// it will look in all other assemblies of the compilation.
+		/// </para>
+		/// <para>
+		/// If the type is open (contains type parameters '`0' or '``0'),
+		/// an <see cref="ITypeResolveContext"/> with the appropriate CurrentTypeDefinition/CurrentMember is required
+		/// to resolve the reference to the ITypeParameter.
+		/// </para>
+		/// </remarks>
+		public static ITypeReference ParseTypeName(string typeName)
+		{
+			if (typeName == null)
+				throw new ArgumentNullException("typeName");
+			int pos = 0;
+			if (typeName.StartsWith("T:", StringComparison.Ordinal))
+				pos = 2;
+			ITypeReference r = ParseTypeName(typeName, ref pos);
+			if (pos < typeName.Length)
+				throw new ReflectionNameParseException(pos, "Expected end of type name");
+			return r;
+		}
+		
+		static bool IsIDStringSpecialCharacter(char c)
+		{
+			switch (c) {
+				case ':':
+				case '{':
+				case '}':
+				case '[':
+				case ']':
+				case '(':
+				case ')':
+				case '`':
+				case '*':
+				case '@':
+				case ',':
+					return true;
+				default:
+					return false;
+			}
+		}
+		
+		static ITypeReference ParseTypeName(string typeName, ref int pos)
+		{
+			string reflectionTypeName = typeName;
+			if (pos == typeName.Length)
+				throw new ReflectionNameParseException(pos, "Unexpected end");
+			ITypeReference result;
+			if (reflectionTypeName[pos] == '`') {
+				// type parameter reference
+				pos++;
+				if (pos == reflectionTypeName.Length)
+					throw new ReflectionNameParseException(pos, "Unexpected end");
+				if (reflectionTypeName[pos] == '`') {
+					// method type parameter reference
+					pos++;
+					int index = ReflectionHelper.ReadTypeParameterCount(reflectionTypeName, ref pos);
+					result = TypeParameterReference.Create(SymbolKind.Method, index);
+				} else {
+					// class type parameter reference
+					int index = ReflectionHelper.ReadTypeParameterCount(reflectionTypeName, ref pos);
+					result = TypeParameterReference.Create(SymbolKind.TypeDefinition, index);
+				}
+			} else {
+				// not a type parameter reference: read the actual type name
+				List<ITypeReference> typeArguments = new List<ITypeReference>();
+				int typeParameterCount;
+				string typeNameWithoutSuffix = ReadTypeName(typeName, ref pos, true, out typeParameterCount, typeArguments);
+				result = new GetPotentiallyNestedClassTypeReference(typeNameWithoutSuffix, typeParameterCount);
+				while (pos < typeName.Length && typeName[pos] == '.') {
+					pos++;
+					string nestedTypeName = ReadTypeName(typeName, ref pos, false, out typeParameterCount, typeArguments);
+					result = new NestedTypeReference(result, nestedTypeName, typeParameterCount);
+				}
+				if (typeArguments.Count > 0) {
+					result = new ParameterizedTypeReference(result, typeArguments);
+				}
+			}
+			while (pos < typeName.Length) {
+				switch (typeName[pos]) {
+					case '[':
+						int dimensions = 1;
+						do {
+							pos++;
+							if (pos == typeName.Length)
+								throw new ReflectionNameParseException(pos, "Unexpected end");
+							if (typeName[pos] == ',')
+								dimensions++;
+						} while (typeName[pos] != ']');
+						result = new ArrayTypeReference(result, dimensions);
+						break;
+					case '*':
+						result = new PointerTypeReference(result);
+						break;
+					case '@':
+						result = new ByReferenceTypeReference(result);
+						break;
+					default:
+						return result;
+				}
+				pos++;
+			}
+			return result;
+		}
+		
+		static string ReadTypeName(string typeName, ref int pos, bool allowDottedName, out int typeParameterCount, List<ITypeReference> typeArguments)
+		{
+			int startPos = pos;
+			// skip the simple name portion:
+			while (pos < typeName.Length && !IsIDStringSpecialCharacter(typeName[pos]) && (allowDottedName || typeName[pos] != '.'))
+				pos++;
+			if (pos == startPos)
+				throw new ReflectionNameParseException(pos, "Expected type name");
+			string shortTypeName = typeName.Substring(startPos, pos - startPos);
+			// read type arguments:
+			typeParameterCount = 0;
+			if (pos < typeName.Length && typeName[pos] == '`') {
+				// unbound generic type
+				pos++;
+				typeParameterCount = ReflectionHelper.ReadTypeParameterCount(typeName, ref pos);
+			} else if (pos < typeName.Length && typeName[pos] == '{') {
+				// bound generic type
+				typeArguments = new List<ITypeReference>();
+				do {
+					pos++;
+					typeArguments.Add(ParseTypeName(typeName, ref pos));
+					typeParameterCount++;
+					if (pos == typeName.Length)
+						throw new ReflectionNameParseException(pos, "Unexpected end");
+				} while (typeName[pos] == ',');
+				if (typeName[pos] != '}')
+					throw new ReflectionNameParseException(pos, "Expected '}'");
+				pos++;
+			}
+			return shortTypeName;
+		}
+		#endregion
+		
+		#region FindEntity
+		/// <summary>
+		/// Finds the entity in the given type resolve context.
+		/// </summary>
+		/// <param name="idString">ID string of the entity.</param>
+		/// <param name="context">Type resolve context</param>
+		/// <returns>Returns the entity, or null if it is not found.</returns>
+		/// <exception cref="ReflectionNameParseException">The syntax of the ID string is invalid</exception>
+		public static IEntity FindEntity(string idString, ITypeResolveContext context)
+		{
+			if (idString == null)
+				throw new ArgumentNullException("idString");
+			if (context == null)
+				throw new ArgumentNullException("context");
+			if (idString.StartsWith("T:", StringComparison.Ordinal)) {
+				return ParseTypeName(idString.Substring(2)).Resolve(context).GetDefinition();
+			} else {
+				return ParseMemberIdString(idString).Resolve(context);
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/XmlDocumentationProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/XmlDocumentationProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Documentation/XmlDocumentationProvider.cs	(revision 11807)
@@ -0,0 +1,405 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Runtime.Serialization;
+using System.Xml;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Documentation
+{
+	/// <summary>
+	/// Provides documentation from an .xml file (as generated by the Microsoft C# compiler).
+	/// </summary>
+	/// <remarks>
+	/// This class first creates an in-memory index of the .xml file, and then uses that to read only the requested members.
+	/// This way, we avoid keeping all the documentation in memory.
+	/// The .xml file is only opened when necessary, the file handle is not kept open all the time.
+	/// If the .xml file is changed, the index will automatically be recreated.
+	/// </remarks>
+	[Serializable]
+	public class XmlDocumentationProvider : IDocumentationProvider, IDeserializationCallback
+	{
+		#region Cache
+		sealed class XmlDocumentationCache
+		{
+			readonly KeyValuePair<string, string>[] entries;
+			int pos;
+			
+			public XmlDocumentationCache(int size = 50)
+			{
+				if (size <= 0)
+					throw new ArgumentOutOfRangeException("size", size, "Value must be positive");
+				this.entries = new KeyValuePair<string, string>[size];
+			}
+			
+			internal bool TryGet(string key, out string value)
+			{
+				foreach (var pair in entries) {
+					if (pair.Key == key) {
+						value = pair.Value;
+						return true;
+					}
+				}
+				value = null;
+				return false;
+			}
+			
+			internal void Add(string key, string value)
+			{
+				entries[pos++] = new KeyValuePair<string, string>(key, value);
+				if (pos == entries.Length)
+					pos = 0;
+			}
+		}
+		#endregion
+		
+		[Serializable]
+		struct IndexEntry : IComparable<IndexEntry>
+		{
+			/// <summary>
+			/// Hash code of the documentation tag
+			/// </summary>
+			internal readonly int HashCode;
+			
+			/// <summary>
+			/// Position in the .xml file where the documentation starts
+			/// </summary>
+			internal readonly int PositionInFile;
+			
+			internal IndexEntry(int hashCode, int positionInFile)
+			{
+				this.HashCode = hashCode;
+				this.PositionInFile = positionInFile;
+			}
+			
+			public int CompareTo(IndexEntry other)
+			{
+				return this.HashCode.CompareTo(other.HashCode);
+			}
+		}
+		
+		[NonSerialized]
+		XmlDocumentationCache cache = new XmlDocumentationCache();
+		
+		readonly string fileName;
+		volatile IndexEntry[] index; // SORTED array of index entries
+		
+		#region Constructor / Redirection support
+		/// <summary>
+		/// Creates a new XmlDocumentationProvider.
+		/// </summary>
+		/// <param name="fileName">Name of the .xml file.</param>
+		/// <exception cref="IOException">Error reading from XML file (or from redirected file)</exception>
+		/// <exception cref="XmlException">Invalid XML file</exception>
+		public XmlDocumentationProvider(string fileName)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException("fileName");
+			
+			using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
+				using (XmlTextReader xmlReader = new XmlTextReader(fs)) {
+					xmlReader.XmlResolver = null; // no DTD resolving
+					xmlReader.MoveToContent();
+					if (string.IsNullOrEmpty(xmlReader.GetAttribute("redirect"))) {
+						this.fileName = fileName;
+						ReadXmlDoc(xmlReader);
+					} else {
+						string redirectionTarget = GetRedirectionTarget(fileName, xmlReader.GetAttribute("redirect"));
+						if (redirectionTarget != null) {
+							Debug.WriteLine("XmlDoc " + fileName + " is redirecting to " + redirectionTarget);
+							using (FileStream redirectedFs = new FileStream(redirectionTarget, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
+								using (XmlTextReader redirectedXmlReader = new XmlTextReader(redirectedFs)) {
+									redirectedXmlReader.XmlResolver = null; // no DTD resolving
+									this.fileName = redirectionTarget;
+									ReadXmlDoc(redirectedXmlReader);
+								}
+							}
+						} else {
+							throw new XmlException("XmlDoc " + fileName + " is redirecting to " + xmlReader.GetAttribute("redirect") + ", but that file was not found.");
+						}
+					}
+				}
+			}
+		}
+		
+		static string GetRedirectionTarget(string xmlFileName, string target)
+		{
+			string programFilesDir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
+			programFilesDir = AppendDirectorySeparator(programFilesDir);
+			
+			string corSysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
+			corSysDir = AppendDirectorySeparator(corSysDir);
+			
+			var fileName = target.Replace ("%PROGRAMFILESDIR%", programFilesDir)
+				.Replace ("%CORSYSDIR%", corSysDir);
+			if (!Path.IsPathRooted (fileName))
+				fileName = Path.Combine (Path.GetDirectoryName (xmlFileName), fileName);
+			return LookupLocalizedXmlDoc(fileName);
+		}
+		
+		static string AppendDirectorySeparator(string dir)
+		{
+			if (dir.EndsWith("\\", StringComparison.Ordinal) || dir.EndsWith("/", StringComparison.Ordinal))
+				return dir;
+			else
+				return dir + Path.DirectorySeparatorChar;
+		}
+		
+		/// <summary>
+		/// Given the assembly file name, looks up the XML documentation file name.
+		/// Returns null if no XML documentation file is found.
+		/// </summary>
+		public static string LookupLocalizedXmlDoc(string fileName)
+		{
+			string xmlFileName = Path.ChangeExtension(fileName, ".xml");
+			string currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
+			string localizedXmlDocFile = GetLocalizedName(xmlFileName, currentCulture);
+			
+			Debug.WriteLine("Try find XMLDoc @" + localizedXmlDocFile);
+			if (File.Exists(localizedXmlDocFile)) {
+				return localizedXmlDocFile;
+			}
+			Debug.WriteLine("Try find XMLDoc @" + xmlFileName);
+			if (File.Exists(xmlFileName)) {
+				return xmlFileName;
+			}
+			if (currentCulture != "en") {
+				string englishXmlDocFile = GetLocalizedName(xmlFileName, "en");
+				Debug.WriteLine("Try find XMLDoc @" + englishXmlDocFile);
+				if (File.Exists(englishXmlDocFile)) {
+					return englishXmlDocFile;
+				}
+			}
+			return null;
+		}
+		
+		static string GetLocalizedName(string fileName, string language)
+		{
+			string localizedXmlDocFile = Path.GetDirectoryName(fileName);
+			localizedXmlDocFile = Path.Combine(localizedXmlDocFile, language);
+			localizedXmlDocFile = Path.Combine(localizedXmlDocFile, Path.GetFileName(fileName));
+			return localizedXmlDocFile;
+		}
+		#endregion
+		
+		#region Load / Create Index
+		void ReadXmlDoc(XmlTextReader reader)
+		{
+			//lastWriteDate = File.GetLastWriteTimeUtc(fileName);
+			// Open up a second file stream for the line<->position mapping
+			using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
+				LinePositionMapper linePosMapper = new LinePositionMapper(fs);
+				List<IndexEntry> indexList = new List<IndexEntry>();
+				while (reader.Read()) {
+					if (reader.IsStartElement()) {
+						switch (reader.LocalName) {
+							case "members":
+								ReadMembersSection(reader, linePosMapper, indexList);
+								break;
+						}
+					}
+				}
+				indexList.Sort();
+				this.index = indexList.ToArray(); // volatile write
+			}
+		}
+		
+		sealed class LinePositionMapper
+		{
+			readonly FileStream fs;
+			int currentLine = 1;
+			
+			public LinePositionMapper(FileStream fs)
+			{
+				this.fs = fs;
+			}
+			
+			public int GetPositionForLine(int line)
+			{
+				Debug.Assert(line >= currentLine);
+				while (line > currentLine) {
+					int b = fs.ReadByte();
+					if (b < 0)
+						throw new EndOfStreamException();
+					if (b == '\n') {
+						currentLine++;
+					}
+				}
+				return checked((int)fs.Position);
+			}
+		}
+		
+		static void ReadMembersSection(XmlTextReader reader, LinePositionMapper linePosMapper, List<IndexEntry> indexList)
+		{
+			while (reader.Read()) {
+				switch (reader.NodeType) {
+					case XmlNodeType.EndElement:
+						if (reader.LocalName == "members") {
+							return;
+						}
+						break;
+					case XmlNodeType.Element:
+						if (reader.LocalName == "member") {
+							int pos = linePosMapper.GetPositionForLine(reader.LineNumber) + Math.Max(reader.LinePosition - 2, 0);
+							string memberAttr = reader.GetAttribute("name");
+							if (memberAttr != null)
+								indexList.Add(new IndexEntry(GetHashCode(memberAttr), pos));
+							reader.Skip();
+						}
+						break;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Hash algorithm used for the index.
+		/// This is a custom implementation so that old index files work correctly
+		/// even when the .NET string.GetHashCode implementation changes
+		/// (e.g. due to .NET 4.5 hash randomization)
+		/// </summary>
+		static int GetHashCode(string key)
+		{
+			unchecked {
+				int h = 0;
+				foreach (char c in key) {
+					h = (h << 5) - h + c;
+				}
+				return h;
+			}
+		}
+		#endregion
+		
+		#region GetDocumentation
+		/// <summary>
+		/// Get the documentation for the member with the specified documentation key.
+		/// </summary>
+		public string GetDocumentation(string key)
+		{
+			if (key == null)
+				throw new ArgumentNullException("key");
+			return GetDocumentation(key, true);
+		}
+		
+		string GetDocumentation(string key, bool allowReload)
+		{
+			int hashcode = GetHashCode(key);
+			var index = this.index; // read volatile field
+			// index is sorted, so we can use binary search
+			int m = Array.BinarySearch(index, new IndexEntry(hashcode, 0));
+			if (m < 0)
+				return null;
+			// correct hash code found.
+			// possibly there are multiple items with the same hash, so go to the first.
+			while (--m >= 0 && index[m].HashCode == hashcode);
+			// m is now 1 before the first item with the correct hash
+			
+			XmlDocumentationCache cache = this.cache;
+			lock (cache) {
+				string val;
+				if (!cache.TryGet(key, out val)) {
+					try {
+						// go through all items that have the correct hash
+						while (++m < index.Length && index[m].HashCode == hashcode) {
+							val = LoadDocumentation(key, index[m].PositionInFile);
+							if (val != null)
+								break;
+						}
+						// cache the result (even if it is null)
+						cache.Add(key, val);
+					} catch (IOException) {
+						// may happen if the documentation file was deleted/is inaccessible/changed (EndOfStreamException)
+						return allowReload ? ReloadAndGetDocumentation(key) : null;
+					} catch (XmlException) {
+						// may happen if the documentation file was changed so that the file position no longer starts on a valid XML element
+						return allowReload ? ReloadAndGetDocumentation(key) : null;
+					}
+				}
+				return val;
+			}
+		}
+		
+		string ReloadAndGetDocumentation(string key)
+		{
+			try {
+				// Reload the index
+				using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
+					using (XmlTextReader xmlReader = new XmlTextReader(fs)) {
+						xmlReader.XmlResolver = null; // no DTD resolving
+						xmlReader.MoveToContent();
+						ReadXmlDoc(xmlReader);
+					}
+				}
+			} catch (IOException) {
+				// Ignore errors on reload; IEntity.Documentation callers aren't prepared to handle exceptions
+				this.index = new IndexEntry[0]; // clear index to avoid future load attempts
+				return null;
+			} catch (XmlException) {
+				this.index = new IndexEntry[0]; // clear index to avoid future load attempts
+				return null;				
+			}
+			return GetDocumentation(key, allowReload: false); // prevent infinite reload loops
+		}
+		#endregion
+		
+		#region GetDocumentation for entity
+		/// <inheritdoc/>
+		public DocumentationComment GetDocumentation(IEntity entity)
+		{
+			string xmlDoc = GetDocumentation(IdStringProvider.GetIdString(entity));
+			if (xmlDoc != null) {
+				return new DocumentationComment(new StringTextSource(xmlDoc), new SimpleTypeResolveContext(entity));
+			} else {
+				return null;
+			}
+		}
+		#endregion
+		
+		#region Load / Read XML
+		string LoadDocumentation(string key, int positionInFile)
+		{
+			using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
+				fs.Position = positionInFile;
+				using (XmlTextReader r = new XmlTextReader(fs, XmlNodeType.Element, null)) {
+					r.XmlResolver = null; // no DTD resolving
+					while (r.Read()) {
+						if (r.NodeType == XmlNodeType.Element) {
+							string memberAttr = r.GetAttribute("name");
+							if (memberAttr == key) {
+								return r.ReadInnerXml();
+							} else {
+								return null;
+							}
+						}
+					}
+					return null;
+				}
+			}
+		}
+		#endregion
+		
+		public virtual void OnDeserialization(object sender)
+		{
+			cache = new XmlDocumentationCache();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/IDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/IDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/IDocument.cs	(revision 11807)
@@ -0,0 +1,205 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// A document representing a source code file for refactoring.
+	/// Line and column counting starts at 1.
+	/// Offset counting starts at 0.
+	/// </summary>
+	public interface IDocument : ITextSource, IServiceProvider
+	{
+		/// <summary>
+		/// Creates an immutable snapshot of this document.
+		/// </summary>
+		IDocument CreateDocumentSnapshot();
+		
+		/// <summary>
+		/// Gets/Sets the text of the whole document..
+		/// </summary>
+		new string Text { get; set; } // hides ITextSource.Text to add the setter
+		
+		/// <summary>
+		/// This event is called directly before a change is applied to the document.
+		/// </summary>
+		/// <remarks>
+		/// It is invalid to modify the document within this event handler.
+		/// Aborting the change (by throwing an exception) is likely to cause corruption of data structures
+		/// that listen to the Changing and Changed events.
+		/// </remarks>
+		event EventHandler<TextChangeEventArgs> TextChanging;
+		
+		/// <summary>
+		/// This event is called directly after a change is applied to the document.
+		/// </summary>
+		/// <remarks>
+		/// It is invalid to modify the document within this event handler.
+		/// Aborting the event handler (by throwing an exception) is likely to cause corruption of data structures
+		/// that listen to the Changing and Changed events.
+		/// </remarks>
+		event EventHandler<TextChangeEventArgs> TextChanged;
+		
+		/// <summary>
+		/// This event is called after a group of changes is completed.
+		/// </summary>
+		/// <seealso cref="EndUndoableAction"/>
+		event EventHandler ChangeCompleted;
+		
+		/// <summary>
+		/// Gets the number of lines in the document.
+		/// </summary>
+		int LineCount { get; }
+		
+		/// <summary>
+		/// Gets the document line with the specified number.
+		/// </summary>
+		/// <param name="lineNumber">The number of the line to retrieve. The first line has number 1.</param>
+		IDocumentLine GetLineByNumber(int lineNumber);
+		
+		/// <summary>
+		/// Gets the document line that contains the specified offset.
+		/// </summary>
+		IDocumentLine GetLineByOffset(int offset);
+		
+		/// <summary>
+		/// Gets the offset from a text location.
+		/// </summary>
+		/// <seealso cref="GetLocation"/>
+		int GetOffset(int line, int column);
+		
+		/// <summary>
+		/// Gets the offset from a text location.
+		/// </summary>
+		/// <seealso cref="GetLocation"/>
+		int GetOffset(TextLocation location);
+		
+		/// <summary>
+		/// Gets the location from an offset.
+		/// </summary>
+		/// <seealso cref="GetOffset(TextLocation)"/>
+		TextLocation GetLocation(int offset);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <remarks>
+		/// Anchors positioned exactly at the insertion offset will move according to their movement type.
+		/// For AnchorMovementType.Default, they will move behind the inserted text.
+		/// The caret will also move behind the inserted text.
+		/// </remarks>
+		void Insert(int offset, string text);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <remarks>
+		/// Anchors positioned exactly at the insertion offset will move according to their movement type.
+		/// For AnchorMovementType.Default, they will move behind the inserted text.
+		/// The caret will also move behind the inserted text.
+		/// </remarks>
+		void Insert(int offset, ITextSource text);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="defaultAnchorMovementType">
+		/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
+		/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
+		/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
+		/// </param>
+		void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType);
+		
+		/// <summary>
+		/// Inserts text.
+		/// </summary>
+		/// <param name="offset">The offset at which the text is inserted.</param>
+		/// <param name="text">The new text.</param>
+		/// <param name="defaultAnchorMovementType">
+		/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
+		/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
+		/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
+		/// </param>
+		void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType);
+		
+		/// <summary>
+		/// Removes text.
+		/// </summary>
+		/// <param name="offset">Starting offset of the text to be removed.</param>
+		/// <param name="length">Length of the text to be removed.</param>
+		void Remove(int offset, int length);
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="newText">The new text.</param>
+		void Replace(int offset, int length, string newText);
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="newText">The new text.</param>
+		void Replace(int offset, int length, ITextSource newText);
+		
+		/// <summary>
+		/// Make the document combine the following actions into a single
+		/// action for undo purposes.
+		/// </summary>
+		void StartUndoableAction();
+		
+		/// <summary>
+		/// Ends the undoable action started with <see cref="StartUndoableAction"/>.
+		/// </summary>
+		void EndUndoableAction();
+		
+		/// <summary>
+		/// Creates an undo group. Dispose the returned value to close the undo group.
+		/// </summary>
+		/// <returns>An object that closes the undo group when Dispose() is called.</returns>
+		IDisposable OpenUndoGroup();
+		
+		/// <summary>
+		/// Creates a new <see cref="ITextAnchor"/> at the specified offset.
+		/// </summary>
+		/// <inheritdoc cref="ITextAnchor" select="remarks|example"/>
+		ITextAnchor CreateAnchor(int offset);
+		
+		/// <summary>
+		/// Gets the name of the file the document is stored in.
+		/// Could also be a non-existent dummy file name or null if no name has been set.
+		/// </summary>
+		string FileName { get; }
+		
+		/// <summary>
+		/// Fired when the file name of the document changes.
+		/// </summary>
+		event EventHandler FileNameChanged;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/IDocumentLine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/IDocumentLine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/IDocumentLine.cs	(revision 11807)
@@ -0,0 +1,60 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// A line inside a <see cref="IDocument"/>.
+	/// </summary>
+	public interface IDocumentLine : ISegment
+	{
+		/// <summary>
+		/// Gets the length of this line, including the line delimiter.
+		/// </summary>
+		int TotalLength { get; }
+		
+		/// <summary>
+		/// Gets the length of the line terminator.
+		/// Returns 1 or 2; or 0 at the end of the document.
+		/// </summary>
+		int DelimiterLength { get; }
+		
+		/// <summary>
+		/// Gets the number of this line.
+		/// The first line has the number 1.
+		/// </summary>
+		int LineNumber { get; }
+		
+		/// <summary>
+		/// Gets the previous line. Returns null if this is the first line in the document.
+		/// </summary>
+		IDocumentLine PreviousLine { get; }
+		
+		/// <summary>
+		/// Gets the next line. Returns null if this is the last line in the document.
+		/// </summary>
+		IDocumentLine NextLine { get; }
+		
+		/// <summary>
+		/// Gets whether the line was deleted.
+		/// </summary>
+		bool IsDeleted { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ISegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ISegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ISegment.cs	(revision 11807)
@@ -0,0 +1,71 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// An (Offset,Length)-pair.
+	/// </summary>
+	public interface ISegment
+	{
+		/// <summary>
+		/// Gets the start offset of the segment.
+		/// </summary>
+		int Offset { get; }
+		
+		/// <summary>
+		/// Gets the length of the segment.
+		/// </summary>
+		/// <remarks>For line segments (IDocumentLine), the length does not include the line delimeter.</remarks>
+		int Length { get; }
+		
+		/// <summary>
+		/// Gets the end offset of the segment.
+		/// </summary>
+		/// <remarks>EndOffset = Offset + Length;</remarks>
+		int EndOffset { get; }
+	}
+	
+	/// <summary>
+	/// Extension methods for <see cref="ISegment"/>.
+	/// </summary>
+	public static class ISegmentExtensions
+	{
+		/// <summary>
+		/// Gets whether <paramref name="segment"/> fully contains the specified segment.
+		/// </summary>
+		/// <remarks>
+		/// Use <c>segment.Contains(offset, 0)</c> to detect whether a segment (end inclusive) contains offset;
+		/// use <c>segment.Contains(offset, 1)</c> to detect whether a segment (end exclusive) contains offset.
+		/// </remarks>
+		public static bool Contains (this ISegment segment, int offset, int length)
+		{
+			return segment.Offset <= offset && offset + length <= segment.EndOffset;
+		}
+		
+		/// <summary>
+		/// Gets whether <paramref name="thisSegment"/> fully contains the specified segment.
+		/// </summary>
+		public static bool Contains (this ISegment thisSegment, ISegment segment)
+		{
+			return segment != null && thisSegment.Offset <= segment.Offset && segment.EndOffset <= thisSegment.EndOffset;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextAnchor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextAnchor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextAnchor.cs	(revision 11807)
@@ -0,0 +1,139 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// The TextAnchor class references an offset (a position between two characters).
+	/// It automatically updates the offset when text is inserted/removed in front of the anchor.
+	/// </summary>
+	/// <remarks>
+	/// <para>Use the <see cref="ITextAnchor.Offset"/> property to get the offset from a text anchor.
+	/// Use the <see cref="IDocument.CreateAnchor"/> method to create an anchor from an offset.
+	/// </para>
+	/// <para>
+	/// The document will automatically update all text anchors; and because it uses weak references to do so,
+	/// the garbage collector can simply collect the anchor object when you don't need it anymore.
+	/// </para>
+	/// <para>Moreover, the document is able to efficiently update a large number of anchors without having to look
+	/// at each anchor object individually. Updating the offsets of all anchors usually only takes time logarithmic
+	/// to the number of anchors. Retrieving the <see cref="ITextAnchor.Offset"/> property also runs in O(lg N).</para>
+	/// </remarks>
+	/// <example>
+	/// Usage:
+	/// <code>TextAnchor anchor = document.CreateAnchor(offset);
+	/// ChangeMyDocument();
+	/// int newOffset = anchor.Offset;
+	/// </code>
+	/// </example>
+	public interface ITextAnchor
+	{
+		/// <summary>
+		/// Gets the text location of this anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		TextLocation Location { get; }
+		
+		/// <summary>
+		/// Gets the offset of the text anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		int Offset { get; }
+		
+		/// <summary>
+		/// Controls how the anchor moves.
+		/// </summary>
+		/// <remarks>Anchor movement is ambiguous if text is inserted exactly at the anchor's location.
+		/// Does the anchor stay before the inserted text, or does it move after it?
+		/// The property <see cref="MovementType"/> will be used to determine which of these two options the anchor will choose.
+		/// The default value is <see cref="AnchorMovementType.Default"/>.</remarks>
+		AnchorMovementType MovementType { get; set; }
+		
+		/// <summary>
+		/// <para>
+		/// Specifies whether the anchor survives deletion of the text containing it.
+		/// </para><para>
+		/// <c>false</c>: The anchor is deleted when the a selection that includes the anchor is deleted.
+		/// <c>true</c>: The anchor is not deleted.
+		/// </para>
+		/// </summary>
+		/// <remarks><inheritdoc cref="IsDeleted" /></remarks>
+		bool SurviveDeletion { get; set; }
+		
+		/// <summary>
+		/// Gets whether the anchor was deleted.
+		/// </summary>
+		/// <remarks>
+		/// <para>When a piece of text containing an anchor is removed, then that anchor will be deleted.
+		/// First, the <see cref="IsDeleted"/> property is set to true on all deleted anchors,
+		/// then the <see cref="Deleted"/> events are raised.
+		/// You cannot retrieve the offset from an anchor that has been deleted.</para>
+		/// <para>This deletion behavior might be useful when using anchors for building a bookmark feature,
+		/// but in other cases you want to still be able to use the anchor. For those cases, set <c><see cref="SurviveDeletion"/> = true</c>.</para>
+		/// </remarks>
+		bool IsDeleted { get; }
+		
+		/// <summary>
+		/// Occurs after the anchor was deleted.
+		/// </summary>
+		/// <remarks>
+		/// <inheritdoc cref="IsDeleted" />
+		/// <para>Due to the 'weak reference' nature of text anchors, you will receive
+		/// the Deleted event only while your code holds a reference to the TextAnchor object.
+		/// </para>
+		/// </remarks>
+		event EventHandler Deleted;
+		
+		/// <summary>
+		/// Gets the line number of the anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		int Line { get; }
+		
+		/// <summary>
+		/// Gets the column number of this anchor.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">Thrown when trying to get the Offset from a deleted anchor.</exception>
+		int Column { get; }
+	}
+	
+	/// <summary>
+	/// Defines how a text anchor moves.
+	/// </summary>
+	public enum AnchorMovementType
+	{
+		/// <summary>
+		/// When text is inserted at the anchor position, the type of the insertion
+		/// determines where the caret moves to. For normal insertions, the anchor will move
+		/// after the inserted text.
+		/// </summary>
+		Default,
+		/// <summary>
+		/// Behaves like a start marker - when text is inserted at the anchor position, the anchor will stay
+		/// before the inserted text.
+		/// </summary>
+		BeforeInsertion,
+		/// <summary>
+		/// Behave like an end marker - when text is insered at the anchor position, the anchor will move
+		/// after the inserted text.
+		/// </summary>
+		AfterInsertion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextPasteHandler.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextPasteHandler.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextPasteHandler.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// ITextPasteHandler.cs
+//
+// Author:
+//   Mike Krüger <mkrueger@novell.com>
+//
+// Copyright (c) 2008 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// The text paste handler can do formattings to a text that is about to be pasted
+	/// into the text document.
+	/// </summary>
+	public interface ITextPasteHandler
+	{
+		/// <summary>
+		/// Formats plain text that is inserted at a specified offset.
+		/// </summary>
+		/// <returns>
+		/// The text that will get inserted at that position.
+		/// </returns>
+		/// <param name="offset">The offset where the text will be inserted.</param>
+		/// <param name="text">The text to be inserted.</param>
+		/// <param name="copyData">Additional data in case the text was copied from a Mono.TextEditor.</param>
+		string FormatPlainText(int offset, string text, byte[] copyData);
+
+		/// <summary>
+		/// Gets the copy data for a specific segment inside the document. This can contain additional information.
+		/// </summary>
+		/// <param name="segment">The text segment that is about to be copied.</param>
+		byte[] GetCopyData(ISegment segment);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ITextSource.cs	(revision 11807)
@@ -0,0 +1,218 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// A read-only view on a (potentially mutable) text source.
+	/// The IDocument interface derives from this interface.
+	/// </summary>
+	public interface ITextSource
+	{
+		/// <summary>
+		/// Gets a version identifier for this text source.
+		/// Returns null for unversioned text sources.
+		/// </summary>
+		ITextSourceVersion Version { get; }
+		
+		/// <summary>
+		/// Creates an immutable snapshot of this text source.
+		/// Unlike all other methods in this interface, this method is thread-safe.
+		/// </summary>
+		ITextSource CreateSnapshot();
+		
+		/// <summary>
+		/// Creates an immutable snapshot of a part of this text source.
+		/// Unlike all other methods in this interface, this method is thread-safe.
+		/// </summary>
+		ITextSource CreateSnapshot(int offset, int length);
+		
+		/// <summary>
+		/// Creates a new TextReader to read from this text source.
+		/// </summary>
+		TextReader CreateReader();
+		
+		/// <summary>
+		/// Creates a new TextReader to read from this text source.
+		/// </summary>
+		TextReader CreateReader(int offset, int length);
+		
+		/// <summary>
+		/// Gets the total text length.
+		/// </summary>
+		/// <returns>The length of the text, in characters.</returns>
+		/// <remarks>This is the same as Text.Length, but is more efficient because
+		///  it doesn't require creating a String object.</remarks>
+		int TextLength { get; }
+		
+		/// <summary>
+		/// Gets the whole text as string.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
+		string Text { get; }
+		
+		/// <summary>
+		/// Gets a character at the specified position in the document.
+		/// </summary>
+		/// <paramref name="offset">The index of the character to get.</paramref>
+		/// <exception cref="ArgumentOutOfRangeException">Offset is outside the valid range (0 to TextLength-1).</exception>
+		/// <returns>The character at the specified position.</returns>
+		/// <remarks>This is the same as Text[offset], but is more efficient because
+		///  it doesn't require creating a String object.</remarks>
+		char GetCharAt(int offset);
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the document.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		/// <remarks>This is the same as Text.Substring, but is more efficient because
+		///  it doesn't require creating a String object for the whole document.</remarks>
+		string GetText(int offset, int length);
+		
+		/// <summary>
+		/// Retrieves the text for a portion of the document.
+		/// </summary>
+		/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
+		string GetText(ISegment segment);
+		
+		/// <summary>
+		/// Writes the text from this document into the TextWriter.
+		/// </summary>
+		void WriteTextTo(TextWriter writer);
+		
+		/// <summary>
+		/// Writes the text from this document into the TextWriter.
+		/// </summary>
+		void WriteTextTo(TextWriter writer, int offset, int length);
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of the character in the specified array.
+		/// </summary>
+		/// <param name="c">Character to search for</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The first index where the character was found; or -1 if no occurrence was found.</returns>
+		int IndexOf(char c, int startIndex, int count);
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of any character in the specified array.
+		/// </summary>
+		/// <param name="anyOf">Characters to search for</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The first index where any character was found; or -1 if no occurrence was found.</returns>
+		int IndexOfAny(char[] anyOf, int startIndex, int count);
+		
+		/// <summary>
+		/// Gets the index of the first occurrence of the specified search text in this text source.
+		/// </summary>
+		/// <param name="searchText">The search text</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <param name="comparisonType">String comparison to use.</param>
+		/// <returns>The first index where the search term was found; or -1 if no occurrence was found.</returns>
+		int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType);
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the specified character in this text source.
+		/// </summary>
+		/// <param name="c">The search character</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <returns>The last index where the search term was found; or -1 if no occurrence was found.</returns>
+		/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
+		/// This is different than the meaning of the parameters on string.LastIndexOf!</remarks>
+		int LastIndexOf(char c, int startIndex, int count);
+		
+		/// <summary>
+		/// Gets the index of the last occurrence of the specified search text in this text source.
+		/// </summary>
+		/// <param name="searchText">The search text</param>
+		/// <param name="startIndex">Start index of the area to search.</param>
+		/// <param name="count">Length of the area to search.</param>
+		/// <param name="comparisonType">String comparison to use.</param>
+		/// <returns>The last index where the search term was found; or -1 if no occurrence was found.</returns>
+		/// <remarks>The search proceeds backwards from (startIndex+count) to startIndex.
+		/// This is different than the meaning of the parameters on string.LastIndexOf!</remarks>
+		int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType);
+		
+		/* What about:
+		void Insert (int offset, string value);
+		void Remove (int offset, int count);
+		void Remove (ISegment segment);
+		
+		void Replace (int offset, int count, string value);
+		
+		Or more search operations:
+		
+		IEnumerable<int> SearchForward (string pattern, int startIndex);
+		IEnumerable<int> SearchForwardIgnoreCase (string pattern, int startIndex);
+		
+		IEnumerable<int> SearchBackward (string pattern, int startIndex);
+		IEnumerable<int> SearchBackwardIgnoreCase (string pattern, int startIndex);
+		 */
+	}
+	
+	/// <summary>
+	/// Represents a version identifier for a text source.
+	/// </summary>
+	/// <remarks>
+	/// Verions can be used to efficiently detect whether a document has changed and needs reparsing;
+	/// or even to implement incremental parsers.
+	/// It is a separate class from ITextSource to allow the GC to collect the text source while
+	/// the version checkpoint is still in use.
+	/// </remarks>
+	public interface ITextSourceVersion
+	{
+		/// <summary>
+		/// Gets whether this checkpoint belongs to the same document as the other checkpoint.
+		/// </summary>
+		/// <remarks>
+		/// Returns false when given <c>null</c>.
+		/// </remarks>
+		bool BelongsToSameDocumentAs(ITextSourceVersion other);
+		
+		/// <summary>
+		/// Compares the age of this checkpoint to the other checkpoint.
+		/// </summary>
+		/// <remarks>This method is thread-safe.</remarks>
+		/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this version.</exception>
+		/// <returns>-1 if this version is older than <paramref name="other"/>.
+		/// 0 if <c>this</c> version instance represents the same version as <paramref name="other"/>.
+		/// 1 if this version is newer than <paramref name="other"/>.</returns>
+		int CompareAge(ITextSourceVersion other);
+		
+		/// <summary>
+		/// Gets the changes from this checkpoint to the other checkpoint.
+		/// If 'other' is older than this checkpoint, reverse changes are calculated.
+		/// </summary>
+		/// <remarks>This method is thread-safe.</remarks>
+		/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this checkpoint.</exception>
+		IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other);
+		
+		/// <summary>
+		/// Calculates where the offset has moved in the other buffer version.
+		/// </summary>
+		/// <exception cref="ArgumentException">Raised if 'other' belongs to a different document than this checkpoint.</exception>
+		int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement = AnchorMovementType.Default);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ReadOnlyDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ReadOnlyDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/ReadOnlyDocument.cs	(revision 11807)
@@ -0,0 +1,447 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// Read-only implementation of <see cref="IDocument"/>.
+	/// </summary>
+	[Serializable]
+	public sealed class ReadOnlyDocument : IDocument
+	{
+		readonly ITextSource textSource;
+		readonly string fileName;
+		int[] lines;
+		
+		static readonly char[] newline = { '\r', '\n' };
+		
+		/// <summary>
+		/// Creates a new ReadOnlyDocument from the given text source.
+		/// </summary>
+		public ReadOnlyDocument(ITextSource textSource)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			// ensure that underlying buffer is immutable
+			this.textSource = textSource.CreateSnapshot();
+			List<int> lines = new List<int>();
+			lines.Add(0);
+			int offset = 0;
+			int textLength = textSource.TextLength;
+			while ((offset = textSource.IndexOfAny(newline, offset, textLength - offset)) >= 0) {
+				offset++;
+				if (textSource.GetCharAt(offset - 1) == '\r' && offset < textLength && textSource.GetCharAt(offset) == '\n') {
+					offset++;
+				}
+				lines.Add(offset);
+			}
+			this.lines = lines.ToArray();
+		}
+		
+		/// <summary>
+		/// Creates a new ReadOnlyDocument from the given string.
+		/// </summary>
+		public ReadOnlyDocument(string text)
+			: this(new StringTextSource(text))
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new ReadOnlyDocument from the given text source;
+		/// and sets IDocument.FileName to the specified file name.
+		/// </summary>
+		public ReadOnlyDocument(ITextSource textSource, string fileName)
+			: this(textSource)
+		{
+			this.fileName = fileName;
+		}
+		
+		/// <inheritdoc/>
+		public IDocumentLine GetLineByNumber(int lineNumber)
+		{
+			if (lineNumber < 1 || lineNumber > lines.Length)
+				throw new ArgumentOutOfRangeException("lineNumber", lineNumber, "Value must be between 1 and " + lines.Length);
+			return new ReadOnlyDocumentLine(this, lineNumber);
+		}
+		
+		sealed class ReadOnlyDocumentLine : IDocumentLine
+		{
+			readonly ReadOnlyDocument doc;
+			readonly int lineNumber;
+			readonly int offset, endOffset;
+			
+			public ReadOnlyDocumentLine(ReadOnlyDocument doc, int lineNumber)
+			{
+				this.doc = doc;
+				this.lineNumber = lineNumber;
+				this.offset = doc.GetStartOffset(lineNumber);
+				this.endOffset = doc.GetEndOffset(lineNumber);
+			}
+			
+			public override int GetHashCode()
+			{
+				return doc.GetHashCode() ^ lineNumber;
+			}
+			
+			public override bool Equals(object obj)
+			{
+				ReadOnlyDocumentLine other = obj as ReadOnlyDocumentLine;
+				return other != null && doc == other.doc && lineNumber == other.lineNumber;
+			}
+			
+			public int Offset {
+				get { return offset; }
+			}
+			
+			public int Length {
+				get { return endOffset - offset; }
+			}
+			
+			public int EndOffset {
+				get { return endOffset; }
+			}
+			
+			public int TotalLength {
+				get {
+					return doc.GetTotalEndOffset(lineNumber) - offset;
+				}
+			}
+			
+			public int DelimiterLength {
+				get {
+					return doc.GetTotalEndOffset(lineNumber) - endOffset;
+				}
+			}
+			
+			public int LineNumber {
+				get { return lineNumber; }
+			}
+			
+			public IDocumentLine PreviousLine {
+				get {
+					if (lineNumber == 1)
+						return null;
+					else
+						return new ReadOnlyDocumentLine(doc, lineNumber - 1);
+				}
+			}
+			
+			public IDocumentLine NextLine {
+				get {
+					if (lineNumber == doc.LineCount)
+						return null;
+					else
+						return new ReadOnlyDocumentLine(doc, lineNumber + 1);
+				}
+			}
+			
+			public bool IsDeleted {
+				get { return false; }
+			}
+		}
+		
+		int GetStartOffset(int lineNumber)
+		{
+			return lines[lineNumber-1];
+		}
+		
+		int GetTotalEndOffset(int lineNumber)
+		{
+			return lineNumber < lines.Length ? lines[lineNumber] : textSource.TextLength;
+		}
+		
+		int GetEndOffset(int lineNumber)
+		{
+			if (lineNumber == lines.Length)
+				return textSource.TextLength;
+			int off = lines[lineNumber] - 1;
+			if (off > 0 && textSource.GetCharAt(off - 1) == '\r' && textSource.GetCharAt(off) == '\n')
+				off--;
+			return off;
+		}
+		
+		/// <inheritdoc/>
+		public IDocumentLine GetLineByOffset(int offset)
+		{
+			return GetLineByNumber(GetLineNumberForOffset(offset));
+		}
+		
+		int GetLineNumberForOffset(int offset)
+		{
+			int r = Array.BinarySearch(lines, offset);
+			return r < 0 ? ~r : r + 1;
+		}
+		
+		/// <inheritdoc/>
+		public int GetOffset(int line, int column)
+		{
+			if (line < 1 || line > lines.Length)
+				throw new ArgumentOutOfRangeException("line", line, "Value must be between 1 and " + lines.Length);
+			int lineStart = GetStartOffset(line);
+			if (column <= 1)
+				return lineStart;
+			int lineEnd = GetEndOffset(line);
+			if (column - 1 >= lineEnd - lineStart)
+				return lineEnd;
+			return lineStart + column - 1;
+		}
+		
+		/// <inheritdoc/>
+		public int GetOffset(TextLocation location)
+		{
+			return GetOffset(location.Line, location.Column);
+		}
+		
+		/// <inheritdoc/>
+		public TextLocation GetLocation(int offset)
+		{
+			if (offset < 0 || offset > textSource.TextLength)
+				throw new ArgumentOutOfRangeException("offset", offset, "Value must be between 0 and " + textSource.TextLength);
+			int line = GetLineNumberForOffset(offset);
+			return new TextLocation(line, offset-GetStartOffset(line)+1);
+		}
+		
+		/// <inheritdoc/>
+		public string Text {
+			get { return textSource.Text; }
+			set {
+				throw new NotSupportedException();
+			}
+		}
+		
+		/// <inheritdoc/>
+		public int LineCount {
+			get { return lines.Length; }
+		}
+		
+		/// <inheritdoc/>
+		public ITextSourceVersion Version {
+			get { return textSource.Version; }
+		}
+		
+		/// <inheritdoc/>
+		public int TextLength {
+			get { return textSource.TextLength; }
+		}
+		
+		event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add {} remove {} }
+		
+		event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add {} remove {} }
+		
+		event EventHandler IDocument.ChangeCompleted { add {} remove {} }
+		
+		void IDocument.Insert(int offset, string text)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.Remove(int offset, int length)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.Replace(int offset, int length, string newText)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.Insert(int offset, ITextSource text)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.Replace(int offset, int length, ITextSource newText)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IDocument.StartUndoableAction()
+		{
+		}
+		
+		void IDocument.EndUndoableAction()
+		{
+		}
+		
+		IDisposable IDocument.OpenUndoGroup()
+		{
+			return null;
+		}
+		
+		/// <inheritdoc/>
+		public ITextAnchor CreateAnchor(int offset)
+		{
+			return new ReadOnlyDocumentTextAnchor(GetLocation(offset), offset);
+		}
+		
+		sealed class ReadOnlyDocumentTextAnchor : ITextAnchor
+		{
+			readonly TextLocation location;
+			readonly int offset;
+			
+			public ReadOnlyDocumentTextAnchor(TextLocation location, int offset)
+			{
+				this.location = location;
+				this.offset = offset;
+			}
+			
+			public event EventHandler Deleted { add {} remove {} }
+			
+			public TextLocation Location {
+				get { return location; }
+			}
+			
+			public int Offset {
+				get { return offset; }
+			}
+			
+			public AnchorMovementType MovementType { get; set; }
+			
+			public bool SurviveDeletion { get; set; }
+			
+			public bool IsDeleted {
+				get { return false; }
+			}
+			
+			public int Line {
+				get { return location.Line; }
+			}
+			
+			public int Column {
+				get { return location.Column; }
+			}
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot()
+		{
+			return textSource; // textBuffer is immutable
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot(int offset, int length)
+		{
+			return textSource.CreateSnapshot(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public IDocument CreateDocumentSnapshot()
+		{
+			return this; // ReadOnlyDocument is immutable
+		}
+		
+		/// <inheritdoc/>
+		public System.IO.TextReader CreateReader()
+		{
+			return textSource.CreateReader();
+		}
+		
+		/// <inheritdoc/>
+		public System.IO.TextReader CreateReader(int offset, int length)
+		{
+			return textSource.CreateReader(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(System.IO.TextWriter writer)
+		{
+			textSource.WriteTextTo(writer);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(System.IO.TextWriter writer, int offset, int length)
+		{
+			textSource.WriteTextTo(writer, offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public char GetCharAt(int offset)
+		{
+			return textSource.GetCharAt(offset);
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(int offset, int length)
+		{
+			return textSource.GetText(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(ISegment segment)
+		{
+			return textSource.GetText(segment);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(char c, int startIndex, int count)
+		{
+			return textSource.IndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOfAny(char[] anyOf, int startIndex, int count)
+		{
+			return textSource.IndexOfAny(anyOf, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return textSource.IndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(char c, int startIndex, int count)
+		{
+			return textSource.LastIndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return textSource.LastIndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		object IServiceProvider.GetService(Type serviceType)
+		{
+			return null;
+		}
+		
+		/// <inheritdoc/>
+		/// <remarks>Will never be raised on <see cref="ReadOnlyDocument" />.</remarks>
+		public event EventHandler FileNameChanged { add {} remove {} }
+		
+		/// <inheritdoc/>
+		public string FileName {
+			get { return fileName; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/StringBuilderDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/StringBuilderDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/StringBuilderDocument.cs	(revision 11807)
@@ -0,0 +1,493 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// Document based on a string builder.
+	/// This class serves as a reference implementation for the IDocument interface.
+	/// </summary>
+	public class StringBuilderDocument : IDocument
+	{
+		readonly StringBuilder b;
+		readonly TextSourceVersionProvider versionProvider = new TextSourceVersionProvider();
+		
+		/// <summary>
+		/// Creates a new StringBuilderDocument.
+		/// </summary>
+		public StringBuilderDocument()
+		{
+			b = new StringBuilder();
+		}
+		
+		/// <summary>
+		/// Creates a new StringBuilderDocument with the specified initial text.
+		/// </summary>
+		public StringBuilderDocument(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			b = new StringBuilder(text);
+		}
+		
+		/// <summary>
+		/// Creates a new StringBuilderDocument with the initial text copied from the specified text source.
+		/// </summary>
+		public StringBuilderDocument(ITextSource textSource)
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			b = new StringBuilder(textSource.TextLength);
+			textSource.WriteTextTo(new StringWriter(b));
+		}
+		
+		/// <inheritdoc/>
+		public event EventHandler<TextChangeEventArgs> TextChanging;
+		
+		/// <inheritdoc/>
+		public event EventHandler<TextChangeEventArgs> TextChanged;
+		
+		/// <inheritdoc/>
+		public event EventHandler ChangeCompleted;
+		
+		/// <inheritdoc/>
+		public ITextSourceVersion Version {
+			get { return versionProvider.CurrentVersion; }
+		}
+		
+		#region Line<->Offset
+		/// <inheritdoc/>
+		public int LineCount {
+			get { return CreateDocumentSnapshot().LineCount; }
+		}
+		
+		/// <inheritdoc/>
+		public IDocumentLine GetLineByNumber(int lineNumber)
+		{
+			return CreateDocumentSnapshot().GetLineByNumber(lineNumber);
+		}
+		
+		/// <inheritdoc/>
+		public IDocumentLine GetLineByOffset(int offset)
+		{
+			return CreateDocumentSnapshot().GetLineByOffset(offset);
+		}
+		
+		/// <inheritdoc/>
+		public int GetOffset(int line, int column)
+		{
+			return CreateDocumentSnapshot().GetOffset(line, column);
+		}
+		
+		/// <inheritdoc/>
+		public int GetOffset(TextLocation location)
+		{
+			return CreateDocumentSnapshot().GetOffset(location);
+		}
+		
+		/// <inheritdoc/>
+		public TextLocation GetLocation(int offset)
+		{
+			return CreateDocumentSnapshot().GetLocation(offset);
+		}
+		#endregion
+		
+		#region Insert/Remove/Replace
+		/// <inheritdoc/>
+		public void Insert(int offset, string text)
+		{
+			Replace(offset, 0, text);
+		}
+		
+		/// <inheritdoc/>
+		public void Insert(int offset, ITextSource text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			Replace(offset, 0, text.Text);
+		}
+		
+		/// <inheritdoc/>
+		public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
+		{
+			if (offset < 0 || offset > this.TextLength)
+				throw new ArgumentOutOfRangeException("offset");
+			if (text == null)
+				throw new ArgumentNullException("text");
+			if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
+				PerformChange(new InsertionWithMovementBefore(offset, text));
+			else
+				Replace(offset, 0, text);
+		}
+		
+		/// <inheritdoc/>
+		public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			Insert(offset, text.Text, defaultAnchorMovementType);
+		}
+		
+		[Serializable]
+		sealed class InsertionWithMovementBefore : TextChangeEventArgs
+		{
+			public InsertionWithMovementBefore(int offset, string newText) : base(offset, string.Empty, newText)
+			{
+			}
+			
+			public override int GetNewOffset(int offset, AnchorMovementType movementType)
+			{
+				if (offset == this.Offset && movementType == AnchorMovementType.Default)
+					return offset;
+				else
+					return base.GetNewOffset(offset, movementType);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public void Remove(int offset, int length)
+		{
+			Replace(offset, length, string.Empty);
+		}
+		
+		/// <inheritdoc/>
+		public void Replace(int offset, int length, string newText)
+		{
+			if (offset < 0 || offset > this.TextLength)
+				throw new ArgumentOutOfRangeException("offset");
+			if (length < 0 || length > this.TextLength - offset)
+				throw new ArgumentOutOfRangeException("length");
+			if (newText == null)
+				throw new ArgumentNullException("newText");
+			PerformChange(new TextChangeEventArgs(offset, b.ToString(offset, length), newText));
+		}
+		
+		/// <inheritdoc/>
+		public void Replace(int offset, int length, ITextSource newText)
+		{
+			if (newText == null)
+				throw new ArgumentNullException("newText");
+			Replace(offset, length, newText.Text);
+		}
+		
+		bool isInChange;
+		
+		void PerformChange(TextChangeEventArgs change)
+		{
+			// Ensure that all changes take place inside an update group.
+			// Will also take care of throwing an exception if isInChange is set.
+			StartUndoableAction();
+			try {
+				isInChange = true;
+				try {
+					if (TextChanging != null)
+						TextChanging(this, change);
+					
+					// Perform changes to document and Version property
+					documentSnapshot = null;
+					cachedText = null;
+					b.Remove(change.Offset, change.RemovalLength);
+					b.Insert(change.Offset, change.InsertedText.Text);
+					versionProvider.AppendChange(change);
+					
+					// Update anchors and fire Deleted events
+					UpdateAnchors(change);
+					
+					if (TextChanged != null)
+						TextChanged(this, change);
+				} finally {
+					isInChange = false;
+				}
+			} finally {
+				EndUndoableAction();
+			}
+		}
+		#endregion
+		
+		#region Undo
+		int undoGroupNesting = 0;
+		
+		/// <inheritdoc/>
+		public void StartUndoableAction()
+		{
+			// prevent changes from within the TextChanging/TextChanged event handlers
+			if (isInChange)
+				throw new InvalidOperationException();
+			undoGroupNesting++;
+		}
+		
+		/// <inheritdoc/>
+		public void EndUndoableAction()
+		{
+			undoGroupNesting--;
+			if (undoGroupNesting == 0) {
+				if (ChangeCompleted != null)
+					ChangeCompleted(this, EventArgs.Empty);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public IDisposable OpenUndoGroup()
+		{
+			StartUndoableAction();
+			return new CallbackOnDispose(EndUndoableAction);
+		}
+		#endregion
+		
+		#region CreateSnapshot/CreateReader
+		ReadOnlyDocument documentSnapshot;
+		
+		/// <inheritdoc/>
+		public IDocument CreateDocumentSnapshot()
+		{
+			if (documentSnapshot == null)
+				documentSnapshot = new ReadOnlyDocument(this, this.FileName);
+			return documentSnapshot;
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot()
+		{
+			return new StringTextSource(this.Text, versionProvider.CurrentVersion);
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot(int offset, int length)
+		{
+			return new StringTextSource(GetText(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader()
+		{
+			return new StringReader(this.Text);
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader(int offset, int length)
+		{
+			return new StringReader(GetText(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer)
+		{
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			writer.Write(this.Text);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer, int offset, int length)
+		{
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			writer.Write(GetText(offset, length));
+		}
+		#endregion
+		
+		#region GetText / IndexOf
+		string cachedText;
+		
+		/// <inheritdoc/>
+		public string Text {
+			get {
+				if (cachedText == null)
+					cachedText = b.ToString();
+				return cachedText;
+			}
+			set {
+				Replace(0, b.Length, value);
+			}
+		}
+		
+		/// <inheritdoc/>
+		public int TextLength {
+			get { return b.Length; }
+		}
+		
+		/// <inheritdoc/>
+		public char GetCharAt(int offset)
+		{
+			return b[offset];
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(int offset, int length)
+		{
+			return b.ToString(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return b.ToString(segment.Offset, segment.Length);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(char c, int startIndex, int count)
+		{
+			return this.Text.IndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOfAny(char[] anyOf, int startIndex, int count)
+		{
+			return this.Text.IndexOfAny(anyOf, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return this.Text.IndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(char c, int startIndex, int count)
+		{
+			return this.Text.LastIndexOf(c, startIndex + count - 1, count);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return this.Text.LastIndexOf(searchText, startIndex + count - 1, count, comparisonType);
+		}
+		#endregion
+		
+		#region CreateAnchor
+		readonly List<WeakReference> anchors = new List<WeakReference>();
+		
+		/// <inheritdoc/>
+		public ITextAnchor CreateAnchor(int offset)
+		{
+			var newAnchor = new SimpleAnchor(this, offset);
+			for (int i = 0; i < anchors.Count; i++) {
+				if (!anchors[i].IsAlive)
+					anchors[i] = new WeakReference(newAnchor);
+			}
+			anchors.Add(new WeakReference(newAnchor));
+			return newAnchor;
+		}
+		
+		void UpdateAnchors(TextChangeEventArgs change)
+		{
+			// First update all anchors, then fire the deleted events.
+			List<int> deletedAnchors = new List<int>();
+			for (int i = 0; i < anchors.Count; i++) {
+				var anchor = anchors[i].Target as SimpleAnchor;
+				if (anchor != null) {
+					anchor.Update(change);
+					if (anchor.IsDeleted)
+						deletedAnchors.Add(i);
+				}
+			}
+			deletedAnchors.Reverse();
+			foreach (var index in deletedAnchors) {
+				var anchor = anchors[index].Target as SimpleAnchor;
+				if (anchor != null)
+					anchor.RaiseDeletedEvent();
+				anchors.RemoveAt(index);
+			}
+		}
+		
+		sealed class SimpleAnchor : ITextAnchor
+		{
+			readonly StringBuilderDocument document;
+			int offset;
+			
+			public SimpleAnchor(StringBuilderDocument document, int offset)
+			{
+				this.document = document;
+				this.offset = offset;
+			}
+			
+			public event EventHandler Deleted;
+			
+			public TextLocation Location {
+				get {
+					if (IsDeleted)
+						throw new InvalidOperationException();
+					return document.GetLocation(offset);
+				}
+			}
+			
+			public int Offset {
+				get {
+					if (IsDeleted)
+						throw new InvalidOperationException();
+					return offset;
+				}
+			}
+			
+			public AnchorMovementType MovementType { get; set; }
+			
+			public bool SurviveDeletion { get; set; }
+			
+			public bool IsDeleted {
+				get { return offset < 0; }
+			}
+			
+			public void Update(TextChangeEventArgs change)
+			{
+				if (SurviveDeletion || offset <= change.Offset || offset >= change.Offset + change.RemovalLength) {
+					offset = change.GetNewOffset(offset, MovementType);
+				} else {
+					offset = -1;
+				}
+			}
+			
+			public void RaiseDeletedEvent()
+			{
+				if (Deleted != null)
+					Deleted(this, EventArgs.Empty);
+			}
+			
+			public int Line {
+				get { return this.Location.Line; }
+			}
+			
+			public int Column {
+				get { return this.Location.Column; }
+			}
+		}
+		#endregion
+		
+		/// <inheritdoc/>
+		public virtual object GetService(Type serviceType)
+		{
+			return null;
+		}
+		
+		/// <inheritdoc/>
+		public virtual event EventHandler FileNameChanged { add {} remove {} }
+		
+		/// <inheritdoc/>
+		public virtual string FileName {
+			get { return string.Empty; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/StringTextSource.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/StringTextSource.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/StringTextSource.cs	(revision 11807)
@@ -0,0 +1,160 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// Implements the ITextSource interface using a string.
+	/// </summary>
+	[Serializable]
+	public class StringTextSource : ITextSource
+	{
+		/// <summary>
+		/// Gets a text source containing the empty string.
+		/// </summary>
+		public static readonly StringTextSource Empty = new StringTextSource(string.Empty);
+		
+		readonly string text;
+		readonly ITextSourceVersion version;
+		
+		/// <summary>
+		/// Creates a new StringTextSource with the given text.
+		/// </summary>
+		public StringTextSource(string text)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+		}
+		
+		/// <summary>
+		/// Creates a new StringTextSource with the given text.
+		/// </summary>
+		public StringTextSource(string text, ITextSourceVersion version)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.text = text;
+			this.version = version;
+		}
+		
+		/// <inheritdoc/>
+		public ITextSourceVersion Version {
+			get { return version; }
+		}
+		
+		/// <inheritdoc/>
+		public int TextLength {
+			get { return text.Length; }
+		}
+		
+		/// <inheritdoc/>
+		public string Text {
+			get { return text; }
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot()
+		{
+			return this; // StringTextSource is immutable
+		}
+		
+		/// <inheritdoc/>
+		public ITextSource CreateSnapshot(int offset, int length)
+		{
+			return new StringTextSource(text.Substring(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader()
+		{
+			return new StringReader(text);
+		}
+		
+		/// <inheritdoc/>
+		public TextReader CreateReader(int offset, int length)
+		{
+			return new StringReader(text.Substring(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer)
+		{
+			writer.Write(text);
+		}
+		
+		/// <inheritdoc/>
+		public void WriteTextTo(TextWriter writer, int offset, int length)
+		{
+			writer.Write(text.Substring(offset, length));
+		}
+		
+		/// <inheritdoc/>
+		public char GetCharAt(int offset)
+		{
+			return text[offset];
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(int offset, int length)
+		{
+			return text.Substring(offset, length);
+		}
+		
+		/// <inheritdoc/>
+		public string GetText(ISegment segment)
+		{
+			if (segment == null)
+				throw new ArgumentNullException("segment");
+			return text.Substring(segment.Offset, segment.Length);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(char c, int startIndex, int count)
+		{
+			return text.IndexOf(c, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOfAny(char[] anyOf, int startIndex, int count)
+		{
+			return text.IndexOfAny(anyOf, startIndex, count);
+		}
+		
+		/// <inheritdoc/>
+		public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return text.IndexOf(searchText, startIndex, count, comparisonType);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(char c, int startIndex, int count)
+		{
+			return text.LastIndexOf(c, startIndex + count - 1, count);
+		}
+		
+		/// <inheritdoc/>
+		public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
+		{
+			return text.LastIndexOf(searchText, startIndex + count - 1, count, comparisonType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/TextChangeEventArgs.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/TextChangeEventArgs.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/TextChangeEventArgs.cs	(revision 11807)
@@ -0,0 +1,118 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// Describes a change of the document text.
+	/// This class is thread-safe.
+	/// </summary>
+	[Serializable]
+	public class TextChangeEventArgs : EventArgs
+	{
+		readonly int offset;
+		readonly ITextSource removedText;
+		readonly ITextSource insertedText;
+		
+		/// <summary>
+		/// The offset at which the change occurs.
+		/// </summary>
+		public int Offset {
+			get { return offset; }
+		}
+		
+		/// <summary>
+		/// The text that was removed.
+		/// </summary>
+		public ITextSource RemovedText {
+			get { return removedText; }
+		}
+		
+		/// <summary>
+		/// The number of characters removed.
+		/// </summary>
+		public int RemovalLength {
+			get { return removedText.TextLength; }
+		}
+		
+		/// <summary>
+		/// The text that was inserted.
+		/// </summary>
+		public ITextSource InsertedText {
+			get { return insertedText; }
+		}
+		
+		/// <summary>
+		/// The number of characters inserted.
+		/// </summary>
+		public int InsertionLength {
+			get { return insertedText.TextLength; }
+		}
+		
+		/// <summary>
+		/// Creates a new TextChangeEventArgs object.
+		/// </summary>
+		public TextChangeEventArgs(int offset, string removedText, string insertedText)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset", offset, "offset must not be negative");
+			this.offset = offset;
+			this.removedText = removedText != null ? new StringTextSource(removedText) : StringTextSource.Empty;
+			this.insertedText = insertedText != null ? new StringTextSource(insertedText) : StringTextSource.Empty;
+		}
+		
+		/// <summary>
+		/// Creates a new TextChangeEventArgs object.
+		/// </summary>
+		public TextChangeEventArgs(int offset, ITextSource removedText, ITextSource insertedText)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset", offset, "offset must not be negative");
+			this.offset = offset;
+			this.removedText = removedText ?? StringTextSource.Empty;
+			this.insertedText = insertedText ?? StringTextSource.Empty;
+		}
+		
+		/// <summary>
+		/// Gets the new offset where the specified offset moves after this document change.
+		/// </summary>
+		public virtual int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
+		{
+			if (offset >= this.Offset && offset <= this.Offset + this.RemovalLength) {
+				if (movementType == AnchorMovementType.BeforeInsertion)
+					return this.Offset;
+				else
+					return this.Offset + this.InsertionLength;
+			} else if (offset > this.Offset) {
+				return offset + this.InsertionLength - this.RemovalLength;
+			} else {
+				return offset;
+			}
+		}
+		
+		/// <summary>
+		/// Creates TextChangeEventArgs for the reverse change.
+		/// </summary>
+		public virtual TextChangeEventArgs Invert()
+		{
+			return new TextChangeEventArgs(offset, insertedText, removedText);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/TextSourceVersionProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/TextSourceVersionProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/TextSourceVersionProvider.cs	(revision 11807)
@@ -0,0 +1,130 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Editor
+{
+	/// <summary>
+	/// Provides ITextSourceVersion instances.
+	/// </summary>
+	public class TextSourceVersionProvider
+	{
+		Version currentVersion;
+		
+		public TextSourceVersionProvider()
+		{
+			this.currentVersion = new Version(this);
+		}
+		
+		/// <summary>
+		/// Gets the current version.
+		/// </summary>
+		public ITextSourceVersion CurrentVersion {
+			get { return currentVersion; }
+		}
+		
+		/// <summary>
+		/// Replaces the current version with a new version.
+		/// </summary>
+		/// <param name="change">Change from current version to new version</param>
+		public void AppendChange(TextChangeEventArgs change)
+		{
+			if (change == null)
+				throw new ArgumentNullException("change");
+			currentVersion.change = change;
+			currentVersion.next = new Version(currentVersion);
+			currentVersion = currentVersion.next;
+		}
+		
+		[DebuggerDisplay("Version #{id}")]
+		sealed class Version : ITextSourceVersion
+		{
+			// Reference back to the provider.
+			// Used to determine if two checkpoints belong to the same document.
+			readonly TextSourceVersionProvider provider;
+			// ID used for CompareAge()
+			readonly int id;
+			
+			// the change from this version to the next version
+			internal TextChangeEventArgs change;
+			internal Version next;
+			
+			internal Version(TextSourceVersionProvider provider)
+			{
+				this.provider = provider;
+			}
+			
+			internal Version(Version prev)
+			{
+				this.provider = prev.provider;
+				this.id = unchecked( prev.id + 1 );
+			}
+			
+			public bool BelongsToSameDocumentAs(ITextSourceVersion other)
+			{
+				Version o = other as Version;
+				return o != null && provider == o.provider;
+			}
+			
+			public int CompareAge(ITextSourceVersion other)
+			{
+				if (other == null)
+					throw new ArgumentNullException("other");
+				Version o = other as Version;
+				if (o == null || provider != o.provider)
+					throw new ArgumentException("Versions do not belong to the same document.");
+				// We will allow overflows, but assume that the maximum distance between checkpoints is 2^31-1.
+				// This is guaranteed on x86 because so many checkpoints don't fit into memory.
+				return Math.Sign(unchecked( this.id - o.id ));
+			}
+			
+			public IEnumerable<TextChangeEventArgs> GetChangesTo(ITextSourceVersion other)
+			{
+				int result = CompareAge(other);
+				Version o = (Version)other;
+				if (result < 0)
+					return GetForwardChanges(o);
+				else if (result > 0)
+					return o.GetForwardChanges(this).Reverse().Select(change => change.Invert());
+				else
+					return EmptyList<TextChangeEventArgs>.Instance;
+			}
+			
+			IEnumerable<TextChangeEventArgs> GetForwardChanges(Version other)
+			{
+				// Return changes from this(inclusive) to other(exclusive).
+				for (Version node = this; node != other; node = node.next) {
+					yield return node.change;
+				}
+			}
+			
+			public int MoveOffsetTo(ITextSourceVersion other, int oldOffset, AnchorMovementType movement)
+			{
+				int offset = oldOffset;
+				foreach (var e in GetChangesTo(other)) {
+					offset = e.GetNewOffset(offset, movement);
+				}
+				return offset;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/UnicodeNewline.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/UnicodeNewline.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Editor/UnicodeNewline.cs	(revision 11807)
@@ -0,0 +1,365 @@
+//
+// UnicodeNewline.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory
+{
+	public enum UnicodeNewline {
+		Unknown,
+
+		/// <summary>
+		/// Line Feed, U+000A
+		/// </summary>
+		LF = 0x0A,
+
+
+		CRLF = 0x0D0A,
+
+		/// <summary>
+		/// Carriage Return, U+000D
+		/// </summary>
+		CR = 0x0D,
+
+		/// <summary>
+		/// Next Line, U+0085
+		/// </summary>
+		NEL = 0x85,
+
+		/// <summary>
+		/// Vertical Tab, U+000B
+		/// </summary>
+		VT = 0x0B,
+
+		/// <summary>
+		/// Form Feed, U+000C
+		/// </summary>
+		FF = 0x0C,
+
+		/// <summary>
+		/// Line Separator, U+2028
+		/// </summary>
+		LS = 0x2028,
+
+		/// <summary>
+		/// Paragraph Separator, U+2029
+		/// </summary>
+		PS = 0x2029
+	}
+
+
+	/// <summary>
+	/// Defines unicode new lines according to  Unicode Technical Report #13
+	/// http://www.unicode.org/standard/reports/tr13/tr13-5.html
+	/// </summary>
+	public static class NewLine
+	{
+		/// <summary>
+		/// Carriage Return, U+000D
+		/// </summary>
+		public const char CR = (char)0x0D;
+
+		/// <summary>
+		/// Line Feed, U+000A
+		/// </summary>
+		public const char LF = (char)0x0A;
+
+		/// <summary>
+		/// Next Line, U+0085
+		/// </summary>
+		public const char NEL = (char)0x85;
+
+		/// <summary>
+		/// Vertical Tab, U+000B
+		/// </summary>
+		public const char VT  = (char)0x0B;
+
+		/// <summary>
+		/// Form Feed, U+000C
+		/// </summary>
+		public const char FF  = (char)0x0C;
+
+		/// <summary>
+		/// Line Separator, U+2028
+		/// </summary>
+		public const char LS  = (char)0x2028;
+
+		/// <summary>
+		/// Paragraph Separator, U+2029
+		/// </summary>
+		public const char PS  = (char)0x2029;
+
+		/// <summary>
+		/// Determines if a char is a new line delimiter.
+		/// </summary>
+		/// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns>
+		/// <param name="curChar">The current character.</param>
+		/// <param name="nextChar">A callback getting the next character (may be null).</param>
+		public static int GetDelimiterLength (char curChar, Func<char> nextChar = null)
+		{
+			if (curChar == CR) {
+				if (nextChar != null && nextChar () == LF)
+					return 2;
+				return 1;
+			}
+
+			if (curChar == LF || curChar == NEL || curChar == VT || curChar == FF || curChar == LS || curChar == PS)
+				return 1;
+			return 0;
+		}
+
+		/// <summary>
+		/// Determines if a char is a new line delimiter.
+		/// </summary>
+		/// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns>
+		/// <param name="curChar">The current character.</param>
+		/// <param name="nextChar">The next character (if != LF then length will always be 0 or 1).</param>
+		public static int GetDelimiterLength (char curChar, char nextChar)
+		{
+			if (curChar == CR) {
+				if (nextChar == LF)
+					return 2;
+				return 1;
+			}
+
+			if (curChar == LF || curChar == NEL || curChar == VT || curChar == FF || curChar == LS || curChar == PS)
+				return 1;
+			return 0;
+		}
+
+
+		/// <summary>
+		/// Determines if a char is a new line delimiter.
+		/// </summary>
+		/// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns>
+		/// <param name="curChar">The current character.</param>
+		/// <param name = "length">The length of the delimiter</param>
+		/// <param name = "type">The type of the delimiter</param>
+		/// <param name="nextChar">A callback getting the next character (may be null).</param>
+		public static bool TryGetDelimiterLengthAndType (char curChar, out int length, out UnicodeNewline type, Func<char> nextChar = null)
+		{
+			if (curChar == CR) {
+				if (nextChar != null && nextChar () == LF) {
+					length = 2;
+					type = UnicodeNewline.CRLF;
+				} else {
+					length = 1;
+					type = UnicodeNewline.CR;
+
+				}
+				return true;
+			}
+
+			switch (curChar) {
+			case LF:
+				type = UnicodeNewline.LF;
+				length = 1;
+				return true;
+			case NEL:
+				type = UnicodeNewline.NEL;
+				length = 1;
+				return true;
+			case VT:
+				type = UnicodeNewline.VT;
+				length = 1;
+				return true;
+			case FF:
+				type = UnicodeNewline.FF;
+				length = 1;
+				return true;
+			case LS:
+				type = UnicodeNewline.LS;
+				length = 1;
+				return true;
+			case PS:
+				type = UnicodeNewline.PS;
+				length = 1;
+				return true;
+			}
+			length = -1;
+			type = UnicodeNewline.Unknown;
+			return false;
+		}
+
+		/// <summary>
+		/// Determines if a char is a new line delimiter.
+		/// </summary>
+		/// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns>
+		/// <param name="curChar">The current character.</param>
+		/// <param name = "length">The length of the delimiter</param>
+		/// <param name = "type">The type of the delimiter</param>
+		/// <param name="nextChar">The next character (if != LF then length will always be 0 or 1).</param>
+		public static bool TryGetDelimiterLengthAndType (char curChar, out int length, out UnicodeNewline type, char nextChar)
+		{
+			if (curChar == CR) {
+				if (nextChar == LF) {
+					length = 2;
+					type = UnicodeNewline.CRLF;
+				} else {
+					length = 1;
+					type = UnicodeNewline.CR;
+
+				}
+				return true;
+			}
+
+			switch (curChar) {
+			case LF:
+				type = UnicodeNewline.LF;
+				length = 1;
+				return true;
+			case NEL:
+				type = UnicodeNewline.NEL;
+				length = 1;
+				return true;
+			case VT:
+				type = UnicodeNewline.VT;
+				length = 1;
+				return true;
+			case FF:
+				type = UnicodeNewline.FF;
+				length = 1;
+				return true;
+			case LS:
+				type = UnicodeNewline.LS;
+				length = 1;
+				return true;
+			case PS:
+				type = UnicodeNewline.PS;
+				length = 1;
+				return true;
+			}
+			length = -1;
+			type = UnicodeNewline.Unknown;
+			return false;
+		}
+
+		/// <summary>
+		/// Gets the new line type of a given char/next char.
+		/// </summary>
+		/// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns>
+		/// <param name="curChar">The current character.</param>
+		/// <param name="nextChar">A callback getting the next character (may be null).</param>
+		public static UnicodeNewline GetDelimiterType (char curChar, Func<char> nextChar = null)
+		{
+			switch (curChar) {
+				case CR:
+				if (nextChar != null && nextChar () == LF)
+					return UnicodeNewline.CRLF;
+				return UnicodeNewline.CR;
+				case LF:
+				return UnicodeNewline.LF;
+				case NEL:
+				return UnicodeNewline.NEL;
+				case VT:
+				return UnicodeNewline.VT;
+				case FF:
+				return UnicodeNewline.FF;
+				case LS:
+				return UnicodeNewline.LS;
+				case PS:
+				return UnicodeNewline.PS;
+			}
+			return UnicodeNewline.Unknown;
+		}
+
+		/// <summary>
+		/// Gets the new line type of a given char/next char.
+		/// </summary>
+		/// <returns>0 == no new line, otherwise it returns either 1 or 2 depending of the length of the delimiter.</returns>
+		/// <param name="curChar">The current character.</param>
+		/// <param name="nextChar">The next character (if != LF then length will always be 0 or 1).</param>
+		public static UnicodeNewline GetDelimiterType (char curChar, char nextChar)
+		{
+			switch (curChar) {
+			case CR:
+				if (nextChar == LF)
+					return UnicodeNewline.CRLF;
+				return UnicodeNewline.CR;
+			case LF:
+				return UnicodeNewline.LF;
+			case NEL:
+				return UnicodeNewline.NEL;
+			case VT:
+				return UnicodeNewline.VT;
+			case FF:
+				return UnicodeNewline.FF;
+			case LS:
+				return UnicodeNewline.LS;
+			case PS:
+				return UnicodeNewline.PS;
+			}
+			return UnicodeNewline.Unknown;
+		}
+
+		/// <summary>
+		/// Determines if a char is a new line delimiter. 
+		/// 
+		/// Note that the only 2 char wide new line is CR LF and both chars are new line
+		/// chars on their own. For most cases GetDelimiterLength is the better choice.
+		/// </summary>
+		public static bool IsNewLine(char ch)
+		{
+			return
+				ch == NewLine.CR ||
+				ch == NewLine.LF ||
+				ch == NewLine.NEL ||
+				ch == NewLine.VT ||
+				ch == NewLine.FF ||
+				ch == NewLine.LS ||
+				ch == NewLine.PS;
+		}
+
+		/// <summary>
+		/// Gets the new line as a string.
+		/// </summary>
+		public static string GetString (UnicodeNewline newLine)
+		{
+			switch (newLine) {
+			case UnicodeNewline.Unknown:
+				return "";
+			case UnicodeNewline.LF:
+				return "\n";
+			case UnicodeNewline.CRLF:
+				return "\r\n";
+			case UnicodeNewline.CR:
+				return "\r";
+			case UnicodeNewline.NEL:
+				return "\u0085";
+			case UnicodeNewline.VT:
+				return "\u000B";
+			case UnicodeNewline.FF:
+				return "\u000C";
+			case UnicodeNewline.LS:
+				return "\u2028";
+			case UnicodeNewline.PS:
+				return "\u2029";
+			default:
+				throw new ArgumentOutOfRangeException ();
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/IAnnotatable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/IAnnotatable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/IAnnotatable.cs	(revision 11807)
@@ -0,0 +1,252 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory
+{
+	/// <summary>
+	/// Provides an interface to handle annotations in an object.
+	/// </summary>
+	public interface IAnnotatable
+	{
+		/// <summary>
+		/// Gets all annotations stored on this IAnnotatable.
+		/// </summary>
+		IEnumerable<object> Annotations {
+			get;
+		}
+		
+		/// <summary>
+		/// Gets the first annotation of the specified type.
+		/// Returns null if no matching annotation exists.
+		/// </summary>
+		/// <typeparam name='T'>
+		/// The type of the annotation.
+		/// </typeparam>
+		T Annotation<T> () where T: class;
+		
+		/// <summary>
+		/// Gets the first annotation of the specified type.
+		/// Returns null if no matching annotation exists.
+		/// </summary>
+		/// <param name='type'>
+		/// The type of the annotation.
+		/// </param>
+		object Annotation (Type type);
+		
+		/// <summary>
+		/// Adds an annotation to this instance.
+		/// </summary>
+		/// <param name='annotation'>
+		/// The annotation to add.
+		/// </param>
+		void AddAnnotation (object annotation);
+		
+		/// <summary>
+		/// Removes all annotations of the specified type.
+		/// </summary>
+		/// <typeparam name='T'>
+		/// The type of the annotations to remove.
+		/// </typeparam>
+		void RemoveAnnotations<T> () where T : class;
+		
+		/// <summary>
+		/// Removes all annotations of the specified type.
+		/// </summary>
+		/// <param name='type'>
+		/// The type of the annotations to remove.
+		/// </param>
+		void RemoveAnnotations(Type type);
+	}
+	
+	/// <summary>
+	/// Base class used to implement the IAnnotatable interface.
+	/// This implementation is thread-safe.
+	/// </summary>
+	[Serializable]
+	public abstract class AbstractAnnotatable : IAnnotatable
+	{
+		// Annotations: points either null (no annotations), to the single annotation,
+		// or to an AnnotationList.
+		// Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list)
+		
+		object annotations;
+		
+		/// <summary>
+		/// Clones all annotations.
+		/// This method is intended to be called by Clone() implementations in derived classes.
+		/// <code>
+		/// AstNode copy = (AstNode)MemberwiseClone();
+		/// copy.CloneAnnotations();
+		/// </code>
+		/// </summary>
+		protected void CloneAnnotations()
+		{
+			ICloneable cloneable = annotations as ICloneable;
+			if (cloneable != null)
+				annotations = cloneable.Clone();
+		}
+
+		sealed class AnnotationList : List<object>, ICloneable
+		{
+			// There are two uses for this custom list type:
+			// 1) it's private, and thus (unlike List<object>) cannot be confused with real annotations
+			// 2) It allows us to simplify the cloning logic by making the list behave the same as a clonable annotation.
+			public AnnotationList (int initialCapacity) : base(initialCapacity)
+			{
+			}
+			
+			public object Clone ()
+			{
+				lock (this) {
+					AnnotationList copy = new AnnotationList (this.Count);
+					for (int i = 0; i < this.Count; i++) {
+						object obj = this [i];
+						ICloneable c = obj as ICloneable;
+						copy.Add (c != null ? c.Clone () : obj);
+					}
+					return copy;
+				}
+			}
+		}
+		
+		public virtual void AddAnnotation (object annotation)
+		{
+			if (annotation == null)
+				throw new ArgumentNullException ("annotation");
+		retry: // Retry until successful
+			object oldAnnotation = Interlocked.CompareExchange (ref this.annotations, annotation, null);
+			if (oldAnnotation == null) {
+				return; // we successfully added a single annotation
+			}
+			AnnotationList list = oldAnnotation as AnnotationList;
+			if (list == null) {
+				// we need to transform the old annotation into a list
+				list = new AnnotationList (4);
+				list.Add (oldAnnotation);
+				list.Add (annotation);
+				if (Interlocked.CompareExchange (ref this.annotations, list, oldAnnotation) != oldAnnotation) {
+					// the transformation failed (some other thread wrote to this.annotations first)
+					goto retry;
+				}
+			} else {
+				// once there's a list, use simple locking
+				lock (list) {
+					list.Add (annotation);
+				}
+			}
+		}
+		
+		public virtual void RemoveAnnotations<T> () where T : class
+		{
+		retry: // Retry until successful
+			object oldAnnotations = this.annotations;
+			AnnotationList list = oldAnnotations as AnnotationList;
+			if (list != null) {
+				lock (list)
+					list.RemoveAll (obj => obj is T);
+			} else if (oldAnnotations is T) {
+				if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) {
+					// Operation failed (some other thread wrote to this.annotations first)
+					goto retry;
+				}
+			}
+		}
+		
+		public virtual void RemoveAnnotations (Type type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ("type");
+		retry: // Retry until successful
+			object oldAnnotations = this.annotations;
+			AnnotationList list = oldAnnotations as AnnotationList;
+			if (list != null) {
+				lock (list)
+					list.RemoveAll(type.IsInstanceOfType);
+			} else if (type.IsInstanceOfType (oldAnnotations)) {
+				if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) {
+					// Operation failed (some other thread wrote to this.annotations first)
+					goto retry;
+				}
+			}
+		}
+		
+		public T Annotation<T> () where T: class
+		{
+			object annotations = this.annotations;
+			AnnotationList list = annotations as AnnotationList;
+			if (list != null) {
+				lock (list) {
+					foreach (object obj in list) {
+						T t = obj as T;
+						if (t != null)
+							return t;
+					}
+					return null;
+				}
+			} else {
+				return annotations as T;
+			}
+		}
+		
+		public object Annotation (Type type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ("type");
+			object annotations = this.annotations;
+			AnnotationList list = annotations as AnnotationList;
+			if (list != null) {
+				lock (list) {
+					foreach (object obj in list) {
+						if (type.IsInstanceOfType (obj))
+							return obj;
+					}
+				}
+			} else {
+				if (type.IsInstanceOfType (annotations))
+					return annotations;
+			}
+			return null;
+		}
+		
+		/// <summary>
+		/// Gets all annotations stored on this AstNode.
+		/// </summary>
+		public IEnumerable<object> Annotations {
+			get {
+				object annotations = this.annotations;
+				AnnotationList list = annotations as AnnotationList;
+				if (list != null) {
+					lock (list) {
+						return list.ToArray ();
+					}
+				} else {
+					if (annotations != null)
+						return new object[] { annotations };
+					else
+						return Enumerable.Empty<object> ();
+				}
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
@@ -0,0 +1,17 @@
+Copyright (c) 2010-2014 AlphaSierraPapa, Xamarin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this
+software and associated documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/ICSharpCode.NRefactory-5.5.0.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/ICSharpCode.NRefactory-5.5.0.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/ICSharpCode.NRefactory-5.5.0.csproj	(revision 11807)
@@ -0,0 +1,315 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <TargetFrameworkProfile />
+    <ProjectGuid>{1022483B-7CF4-4162-827F-984B64EAF8B3}</ProjectGuid>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <PropertyGroup>
+    <OutputType>Library</OutputType>
+  </PropertyGroup>
+  <PropertyGroup>
+    <StartupObject />
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyName>ICSharpCode.NRefactory</AssemblyName>
+  </PropertyGroup>
+  <PropertyGroup>
+    <RootNamespace>ICSharpCode.NRefactory</RootNamespace>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Analysis\AbiComparer.cs" />
+    <Compile Include="Analysis\SymbolCollector.cs" />
+    <Compile Include="Analysis\TypeGraph.cs" />
+    <Compile Include="Analysis\TypeGraphNode.cs" />
+    <Compile Include="Completion\CompletionCategory.cs" />
+    <Compile Include="Completion\CompletionExtensionMethods.cs" />
+    <Compile Include="Completion\DisplayFlags.cs" />
+    <Compile Include="Completion\FrameworkLookup.cs" />
+    <Compile Include="Completion\ICompletionData.cs" />
+    <Compile Include="Completion\IEntityCompletionData.cs" />
+    <Compile Include="Completion\IParameterDataProvider.cs" />
+    <Compile Include="Completion\IVariableCompletionData.cs" />
+    <Compile Include="Documentation\DocumentationComment.cs" />
+    <Compile Include="Documentation\GetPotentiallyNestedClassTypeReference.cs" />
+    <Compile Include="Documentation\IDocumentationProvider.cs" />
+    <Compile Include="Documentation\IdStringMemberReference.cs" />
+    <Compile Include="Documentation\IdStringProvider.cs" />
+    <Compile Include="Documentation\XmlDocumentationProvider.cs" />
+    <Compile Include="Editor\IDocument.cs" />
+    <Compile Include="Editor\IDocumentLine.cs" />
+    <Compile Include="Editor\ISegment.cs" />
+    <Compile Include="Editor\ITextAnchor.cs" />
+    <Compile Include="Editor\ITextPasteHandler.cs" />
+    <Compile Include="Editor\ITextSource.cs" />
+    <Compile Include="Editor\ReadOnlyDocument.cs" />
+    <Compile Include="Editor\StringBuilderDocument.cs" />
+    <Compile Include="Editor\StringTextSource.cs" />
+    <Compile Include="Editor\TextChangeEventArgs.cs" />
+    <Compile Include="Editor\TextSourceVersionProvider.cs" />
+    <Compile Include="Editor\UnicodeNewline.cs" />
+    <Compile Include="IAnnotatable.cs" />
+    <Compile Include="PatternMatching\AnyNode.cs" />
+    <Compile Include="PatternMatching\AnyNodeOrNull.cs" />
+    <Compile Include="PatternMatching\Backreference.cs" />
+    <Compile Include="PatternMatching\BacktrackingInfo.cs" />
+    <Compile Include="PatternMatching\Choice.cs" />
+    <Compile Include="PatternMatching\INode.cs" />
+    <Compile Include="PatternMatching\Match.cs" />
+    <Compile Include="PatternMatching\NamedNode.cs" />
+    <Compile Include="PatternMatching\OptionalNode.cs" />
+    <Compile Include="PatternMatching\Pattern.cs" />
+    <Compile Include="PatternMatching\Repeat.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Refactoring\IssueMarker.cs" />
+    <Compile Include="Refactoring\Severity.cs" />
+    <Compile Include="Role.cs" />
+    <Compile Include="Semantics\AmbiguousResolveResult.cs" />
+    <Compile Include="Semantics\ArrayAccessResolveResult.cs" />
+    <Compile Include="Semantics\ArrayCreateResolveResult.cs" />
+    <Compile Include="Semantics\ByReferenceResolveResult.cs" />
+    <Compile Include="Semantics\ConstantResolveResult.cs" />
+    <Compile Include="Semantics\Conversion.cs" />
+    <Compile Include="Semantics\ConversionResolveResult.cs" />
+    <Compile Include="Semantics\ErrorResolveResult.cs" />
+    <Compile Include="Semantics\ForEachResolveResult.cs" />
+    <Compile Include="Semantics\InitializedObjectResolveResult.cs" />
+    <Compile Include="Semantics\InvocationResolveResult.cs" />
+    <Compile Include="Semantics\LocalResolveResult.cs" />
+    <Compile Include="Semantics\MemberResolveResult.cs" />
+    <Compile Include="Semantics\NamedArgumentResolveResult.cs" />
+    <Compile Include="Semantics\NamespaceResolveResult.cs" />
+    <Compile Include="Semantics\OperatorResolveResult.cs" />
+    <Compile Include="Semantics\ResolveResult.cs" />
+    <Compile Include="Semantics\SizeOfResolveResult.cs" />
+    <Compile Include="Semantics\ThisResolveResult.cs" />
+    <Compile Include="Semantics\TypeIsResolveResult.cs" />
+    <Compile Include="Semantics\TypeOfResolveResult.cs" />
+    <Compile Include="Semantics\TypeResolveResult.cs" />
+    <Compile Include="Semantics\UnknownMemberResolveResult.cs" />
+    <Compile Include="TextLocation.cs" />
+    <Compile Include="TypeSystem\Accessibility.cs" />
+    <Compile Include="TypeSystem\AnonymousType.cs" />
+    <Compile Include="TypeSystem\ArrayType.cs" />
+    <Compile Include="TypeSystem\AssemblyLoader.cs" />
+    <Compile Include="TypeSystem\AssemblyQualifiedTypeName.cs" />
+    <Compile Include="TypeSystem\ByReferenceType.cs" />
+    <Compile Include="TypeSystem\ComHelper.cs" />
+    <Compile Include="TypeSystem\DefaultSolutionSnapshot.cs" />
+    <Compile Include="TypeSystem\DomRegion.cs" />
+    <Compile Include="TypeSystem\EntityType.cs" />
+    <Compile Include="TypeSystem\Error.cs" />
+    <Compile Include="TypeSystem\FullTypeName.cs" />
+    <Compile Include="TypeSystem\IAmbience.cs" />
+    <Compile Include="TypeSystem\IAssembly.cs" />
+    <Compile Include="TypeSystem\IAttribute.cs" />
+    <Compile Include="TypeSystem\ICodeContext.cs" />
+    <Compile Include="TypeSystem\ICompilation.cs" />
+    <Compile Include="TypeSystem\IConstantValue.cs" />
+    <Compile Include="TypeSystem\IEntity.cs" />
+    <Compile Include="TypeSystem\IEvent.cs" />
+    <Compile Include="TypeSystem\IField.cs" />
+    <Compile Include="TypeSystem\IFreezable.cs" />
+    <Compile Include="TypeSystem\IInterningProvider.cs" />
+    <Compile Include="TypeSystem\IMember.cs" />
+    <Compile Include="TypeSystem\IMethod.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractFreezable.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractResolvedEntity.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractResolvedMember.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractResolvedTypeParameter.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractType.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractUnresolvedEntity.cs" />
+    <Compile Include="TypeSystem\Implementation\AbstractUnresolvedMember.cs" />
+    <Compile Include="TypeSystem\Implementation\AccessorOwnerMemberReference.cs" />
+    <Compile Include="TypeSystem\Implementation\BaseTypeCollector.cs" />
+    <Compile Include="TypeSystem\Implementation\BlobReader.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultAssemblyReference.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultAttribute.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultMemberReference.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultParameter.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultResolvedEvent.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultResolvedField.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultResolvedMethod.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultResolvedProperty.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultResolvedTypeDefinition.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultResolvedTypeParameter.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedAssembly.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedAttribute.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedEvent.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedField.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedMethod.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedParameter.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedProperty.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedTypeDefinition.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultUnresolvedTypeParameter.cs" />
+    <Compile Include="TypeSystem\Implementation\DefaultVariable.cs" />
+    <Compile Include="TypeSystem\Implementation\DummyTypeParameter.cs" />
+    <Compile Include="TypeSystem\Implementation\ExplicitInterfaceImplementationMemberReference.cs" />
+    <Compile Include="TypeSystem\Implementation\FullNameAndTypeParameterCount.cs" />
+    <Compile Include="TypeSystem\Implementation\GetClassTypeReference.cs" />
+    <Compile Include="TypeSystem\Implementation\GetMembersHelper.cs" />
+    <Compile Include="TypeSystem\Implementation\KnownTypeCache.cs" />
+    <Compile Include="TypeSystem\Implementation\MergedNamespace.cs" />
+    <Compile Include="TypeSystem\Implementation\MinimalCorlib.cs" />
+    <Compile Include="TypeSystem\Implementation\NestedTypeReference.cs" />
+    <Compile Include="TypeSystem\Implementation\ResolvedAttributeBlob.cs" />
+    <Compile Include="TypeSystem\Implementation\SimpleCompilation.cs" />
+    <Compile Include="TypeSystem\Implementation\SimpleConstantValue.cs" />
+    <Compile Include="TypeSystem\Implementation\SimpleInterningProvider.cs" />
+    <Compile Include="TypeSystem\Implementation\SpecializedEvent.cs" />
+    <Compile Include="TypeSystem\Implementation\SpecializedField.cs" />
+    <Compile Include="TypeSystem\Implementation\SpecializedMember.cs" />
+    <Compile Include="TypeSystem\Implementation\SpecializedMethod.cs" />
+    <Compile Include="TypeSystem\Implementation\SpecializedProperty.cs" />
+    <Compile Include="TypeSystem\Implementation\SpecializingMemberReference.cs" />
+    <Compile Include="TypeSystem\Implementation\TypeParameterReference.cs" />
+    <Compile Include="TypeSystem\Implementation\TypeWithElementType.cs" />
+    <Compile Include="TypeSystem\Implementation\UnknownType.cs" />
+    <Compile Include="TypeSystem\Implementation\UnresolvedAttributeBlob.cs" />
+    <Compile Include="TypeSystem\Implementation\UnresolvedSecurityDeclarationBlob.cs" />
+    <Compile Include="TypeSystem\Implementation\VoidTypeDefinition.cs" />
+    <Compile Include="TypeSystem\INamedElement.cs" />
+    <Compile Include="TypeSystem\INamespace.cs" />
+    <Compile Include="TypeSystem\InheritanceHelper.cs" />
+    <Compile Include="TypeSystem\IntersectionType.cs" />
+    <Compile Include="TypeSystem\IParameter.cs" />
+    <Compile Include="TypeSystem\IParameterizedMember.cs" />
+    <Compile Include="TypeSystem\IProjectContent.cs" />
+    <Compile Include="TypeSystem\IProperty.cs" />
+    <Compile Include="TypeSystem\ISolutionSnapshot.cs" />
+    <Compile Include="TypeSystem\ISupportsInterning.cs" />
+    <Compile Include="TypeSystem\ISymbol.cs" />
+    <Compile Include="TypeSystem\IType.cs" />
+    <Compile Include="TypeSystem\ITypeDefinition.cs" />
+    <Compile Include="TypeSystem\ITypeParameter.cs" />
+    <Compile Include="TypeSystem\ITypeReference.cs" />
+    <Compile Include="TypeSystem\IUnresolvedFile.cs" />
+    <Compile Include="TypeSystem\IVariable.cs" />
+    <Compile Include="TypeSystem\KnownTypeReference.cs" />
+    <Compile Include="TypeSystem\NullableType.cs" />
+    <Compile Include="TypeSystem\ParameterizedType.cs" />
+    <Compile Include="TypeSystem\ParameterListComparer.cs" />
+    <Compile Include="TypeSystem\PointerType.cs" />
+    <Compile Include="TypeSystem\ProjectReference.cs" />
+    <Compile Include="TypeSystem\ReflectionHelper.cs" />
+    <Compile Include="TypeSystem\ReflectionNameParseException.cs" />
+    <Compile Include="TypeSystem\SimpleTypeResolveContext.cs" />
+    <Compile Include="TypeSystem\SpecialType.cs" />
+    <Compile Include="TypeSystem\TaskType.cs" />
+    <Compile Include="TypeSystem\TopLevelTypeName.cs" />
+    <Compile Include="TypeSystem\TypeKind.cs" />
+    <Compile Include="TypeSystem\TypeParameterSubstitution.cs" />
+    <Compile Include="TypeSystem\TypeSystemExtensions.cs" />
+    <Compile Include="TypeSystem\TypeVisitor.cs" />
+    <Compile Include="Utils\7BitEncodedInts.cs" />
+    <Compile Include="Utils\BitVector16.cs" />
+    <Compile Include="Utils\BusyManager.cs" />
+    <Compile Include="Utils\CacheManager.cs" />
+    <Compile Include="Utils\CallbackOnDispose.cs" />
+    <Compile Include="Utils\ComparableList.cs" />
+    <Compile Include="Utils\CompositeFormatStringParser\CompositeFormatStringParser.cs" />
+    <Compile Include="Utils\CompositeFormatStringParser\FormatItem.cs" />
+    <Compile Include="Utils\CompositeFormatStringParser\FormatStringSegmentBase.cs" />
+    <Compile Include="Utils\CompositeFormatStringParser\IFormatStringError.cs" />
+    <Compile Include="Utils\CompositeFormatStringParser\IFormatStringSegment.cs" />
+    <Compile Include="Utils\CompositeFormatStringParser\TextSegment.cs" />
+    <Compile Include="Utils\CSharpPrimitiveCast.cs" />
+    <Compile Include="Utils\EmptyList.cs" />
+    <Compile Include="Utils\ExtensionMethods.cs" />
+    <Compile Include="Utils\FastSerializer.cs" />
+    <Compile Include="Utils\GraphVizGraph.cs" />
+    <Compile Include="Utils\ImmutableStack.cs" />
+    <Compile Include="Utils\KeyComparer.cs" />
+    <Compile Include="Utils\LazyInit.cs" />
+    <Compile Include="Utils\MultiDictionary.cs" />
+    <Compile Include="Utils\Platform.cs" />
+    <Compile Include="Utils\ProjectedList.cs" />
+    <Compile Include="Utils\ReferenceComparer.cs" />
+    <Compile Include="Utils\TreeTraversal.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="ICSharpCode.NRefactory License-5.5.0.txt" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/AnyNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/AnyNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/AnyNode.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Matches any node.
+	/// </summary>
+	/// <remarks>Does not match null nodes.</remarks>
+	public class AnyNode : Pattern
+	{
+		readonly string groupName;
+		
+		public string GroupName {
+			get { return groupName; }
+		}
+		
+		public AnyNode(string groupName = null)
+		{
+			this.groupName = groupName;
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			match.Add(this.groupName, other);
+			return other != null && !other.IsNull;
+		}
+	}
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/AnyNodeOrNull.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/AnyNodeOrNull.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/AnyNodeOrNull.cs	(revision 11807)
@@ -0,0 +1,58 @@
+//
+// AnyNodeOrNull.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Matches any node.
+	/// </summary>
+	/// <remarks>Does not match null nodes.</remarks>
+	public class AnyNodeOrNull : Pattern
+	{
+		readonly string groupName;
+
+		public string GroupName {
+			get { return groupName; }
+		}
+
+		public AnyNodeOrNull(string groupName = null)
+		{
+			this.groupName = groupName;
+		}
+
+		public override bool DoMatch(INode other, Match match)
+		{
+			if (other == null) {
+				match.AddNull(this.groupName);
+			} else {
+				match.Add(this.groupName, other);
+			}
+			return true;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Backreference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Backreference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Backreference.cs	(revision 11807)
@@ -0,0 +1,50 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Matches the last entry in the specified named group.
+	/// </summary>
+	public class Backreference : Pattern
+	{
+		readonly string referencedGroupName;
+		
+		public string ReferencedGroupName {
+			get { return referencedGroupName; }
+		}
+		
+		public Backreference(string referencedGroupName)
+		{
+			if (referencedGroupName == null)
+				throw new ArgumentNullException("referencedGroupName");
+			this.referencedGroupName = referencedGroupName;
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			var last = match.Get (referencedGroupName).Last ();
+			if (last == null && other == null)
+				return true;
+			return last.IsMatch(other);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/BacktrackingInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/BacktrackingInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/BacktrackingInfo.cs	(revision 11807)
@@ -0,0 +1,32 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Container for the backtracking info.
+	/// </summary>
+	public class BacktrackingInfo
+	{
+		internal Stack<Pattern.PossibleMatch> backtrackingStack = new Stack<Pattern.PossibleMatch>();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Choice.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Choice.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Choice.cs	(revision 11807)
@@ -0,0 +1,68 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Matches one of several alternatives.
+	/// </summary>
+	public class Choice : Pattern, IEnumerable<INode>
+	{
+		readonly List<INode> alternatives = new List<INode>();
+		
+		public void Add(string name, INode alternative)
+		{
+			if (alternative == null)
+				throw new ArgumentNullException("alternative");
+			alternatives.Add(new NamedNode(name, alternative));
+		}
+		
+		public void Add(INode alternative)
+		{
+			if (alternative == null)
+				throw new ArgumentNullException("alternative");
+			alternatives.Add(alternative);
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			var checkPoint = match.CheckPoint();
+			foreach (INode alt in alternatives) {
+				if (alt.DoMatch(other, match))
+					return true;
+				else
+					match.RestoreCheckPoint(checkPoint);
+			}
+			return false;
+		}
+		
+		IEnumerator<INode> IEnumerable<INode>.GetEnumerator()
+		{
+			return alternatives.GetEnumerator();
+		}
+		
+		IEnumerator IEnumerable.GetEnumerator()
+		{
+			return alternatives.GetEnumerator();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/INode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/INode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/INode.cs	(revision 11807)
@@ -0,0 +1,69 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// AST node that supports pattern matching.
+	/// </summary>
+	public interface INode
+	{
+		Role Role { get; }
+		INode FirstChild { get; }
+		INode NextSibling { get; }
+		bool IsNull { get; }
+		
+		bool DoMatch(INode other, Match match);
+		bool DoMatchCollection(Role role, INode pos, Match match, BacktrackingInfo backtrackingInfo);
+	}
+	
+	public static class PatternExtensions
+	{
+		/// <summary>
+		/// Performs a pattern matching operation.
+		/// <c>this</c> is the pattern, <paramref name="other"/> is the AST that is being matched.
+		/// </summary>
+		/// <returns>
+		/// A match object. Check <see cref="PatternMatching.Match.Success"/> to see whether the match was successful.
+		/// </returns>
+		/// <remarks>
+		/// Patterns are ASTs that contain special pattern nodes (from the PatternMatching namespace).
+		/// However, it is also possible to match two ASTs without any pattern nodes -
+		/// doing so will produce a successful match if the two ASTs are structurally identical.
+		/// </remarks>
+		public static Match Match(this INode pattern, INode other)
+		{
+			if (pattern == null)
+				throw new ArgumentNullException("pattern");
+			Match match = PatternMatching.Match.CreateNew();
+			if (pattern.DoMatch(other, match))
+				return match;
+			else
+				return default(PatternMatching.Match);
+		}
+		
+		public static bool IsMatch(this INode pattern, INode other)
+		{
+			if (pattern == null)
+				throw new ArgumentNullException("pattern");
+			return pattern.DoMatch(other, PatternMatching.Match.CreateNew());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Match.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Match.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Match.cs	(revision 11807)
@@ -0,0 +1,100 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Represents the result of a pattern matching operation.
+	/// </summary>
+	public struct Match
+	{
+		// TODO: maybe we should add an implicit Match->bool conversion? (implicit operator bool(Match m) { return m != null; })
+		
+		List<KeyValuePair<string, INode>> results;
+		
+		public bool Success {
+			get { return results != null; }
+		}
+		
+		internal static Match CreateNew()
+		{
+			Match m;
+			m.results = new List<KeyValuePair<string, INode>>();
+			return m;
+		}
+		
+		internal int CheckPoint()
+		{
+			return results.Count;
+		}
+		
+		internal void RestoreCheckPoint(int checkPoint)
+		{
+			results.RemoveRange(checkPoint, results.Count - checkPoint);
+		}
+		
+		public IEnumerable<INode> Get(string groupName)
+		{
+			if (results == null)
+				yield break;
+			foreach (var pair in results) {
+				if (pair.Key == groupName)
+					yield return pair.Value;
+			}
+		}
+		
+		public IEnumerable<T> Get<T>(string groupName) where T : INode
+		{
+			if (results == null)
+				yield break;
+			foreach (var pair in results) {
+				if (pair.Key == groupName)
+					yield return (T)pair.Value;
+			}
+		}
+		
+		public bool Has(string groupName)
+		{
+			if (results == null)
+				return false;
+			foreach (var pair in results) {
+				if (pair.Key == groupName)
+					return true;
+			}
+			return false;
+		}
+		
+		public void Add(string groupName, INode node)
+		{
+			if (groupName != null && node != null) {
+				results.Add(new KeyValuePair<string, INode>(groupName, node));
+			}
+		}
+
+		internal void AddNull (string groupName)
+		{
+			if (groupName != null) {
+				results.Add(new KeyValuePair<string, INode>(groupName, null));
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/NamedNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/NamedNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/NamedNode.cs	(revision 11807)
@@ -0,0 +1,53 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Represents a named node within a pattern.
+	/// </summary>
+	public class NamedNode : Pattern
+	{
+		readonly string groupName;
+		readonly INode childNode;
+		
+		public string GroupName {
+			get { return groupName; }
+		}
+		
+		public INode ChildNode {
+			get { return childNode; }
+		}
+		
+		public NamedNode(string groupName, INode childNode)
+		{
+			if (childNode == null)
+				throw new ArgumentNullException("childNode");
+			this.groupName = groupName;
+			this.childNode = childNode;
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			match.Add(this.groupName, other);
+			return childNode.DoMatch(other, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/OptionalNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/OptionalNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/OptionalNode.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	public class OptionalNode : Pattern
+	{
+		readonly INode childNode;
+		
+		public INode ChildNode {
+			get { return childNode; }
+		}
+		
+		public OptionalNode(INode childNode)
+		{
+			if (childNode == null)
+				throw new ArgumentNullException("childNode");
+			this.childNode = childNode;
+		}
+		
+		public OptionalNode(string groupName, INode childNode) : this(new NamedNode(groupName, childNode))
+		{
+		}
+		
+		public override bool DoMatchCollection(Role role, INode pos, Match match, BacktrackingInfo backtrackingInfo)
+		{
+			backtrackingInfo.backtrackingStack.Push(new PossibleMatch(pos, match.CheckPoint()));
+			return childNode.DoMatch(pos, match);
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			if (other == null || other.IsNull)
+				return true;
+			else
+				return childNode.DoMatch(other, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Pattern.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Pattern.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Pattern.cs	(revision 11807)
@@ -0,0 +1,114 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Base class for all patterns.
+	/// </summary>
+	public abstract class Pattern : INode
+	{
+		/// <summary>
+		/// Gets the string that matches any string.
+		/// </summary>
+		public static readonly string AnyString = "$any$";
+		
+		public static bool MatchString(string pattern, string text)
+		{
+			return pattern == AnyString || pattern == text;
+		}
+		
+		internal struct PossibleMatch
+		{
+			public readonly INode NextOther; // next node after the last matched node
+			public readonly int Checkpoint; // checkpoint
+			
+			public PossibleMatch(INode nextOther, int checkpoint)
+			{
+				this.NextOther = nextOther;
+				this.Checkpoint = checkpoint;
+			}
+		}
+		
+		bool INode.IsNull {
+			get { return false; }
+		}
+		
+		Role INode.Role {
+			get { return null; }
+		}
+		
+		INode INode.NextSibling {
+			get { return null; }
+		}
+		
+		INode INode.FirstChild {
+			get { return null; }
+		}
+		
+		public abstract bool DoMatch(INode other, Match match);
+		
+		public virtual bool DoMatchCollection(Role role, INode pos, Match match, BacktrackingInfo backtrackingInfo)
+		{
+			return DoMatch (pos, match);
+		}
+		
+		public static bool DoMatchCollection(Role role, INode firstPatternChild, INode firstOtherChild, Match match)
+		{
+			BacktrackingInfo backtrackingInfo = new BacktrackingInfo();
+			Stack<INode> patternStack = new Stack<INode>();
+			Stack<PossibleMatch> stack = backtrackingInfo.backtrackingStack;
+			patternStack.Push(firstPatternChild);
+			stack.Push(new PossibleMatch(firstOtherChild, match.CheckPoint()));
+			while (stack.Count > 0) {
+				INode cur1 = patternStack.Pop();
+				INode cur2 = stack.Peek().NextOther;
+				match.RestoreCheckPoint(stack.Pop().Checkpoint);
+				bool success = true;
+				while (cur1 != null && success) {
+					while (cur1 != null && cur1.Role != role)
+						cur1 = cur1.NextSibling;
+					while (cur2 != null && cur2.Role != role)
+						cur2 = cur2.NextSibling;
+					if (cur1 == null)
+						break;
+					
+					Debug.Assert(stack.Count == patternStack.Count);
+					success = cur1.DoMatchCollection(role, cur2, match, backtrackingInfo);
+					Debug.Assert(stack.Count >= patternStack.Count);
+					while (stack.Count > patternStack.Count)
+						patternStack.Push(cur1.NextSibling);
+					
+					cur1 = cur1.NextSibling;
+					if (cur2 != null)
+						cur2 = cur2.NextSibling;
+				}
+				while (cur2 != null && cur2.Role != role)
+					cur2 = cur2.NextSibling;
+				if (success && cur2 == null)
+					return true;
+			}
+			return false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Repeat.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Repeat.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/PatternMatching/Repeat.cs	(revision 11807)
@@ -0,0 +1,74 @@
+﻿// Copyright (c) 2011-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+	/// <summary>
+	/// Represents an optional node.
+	/// </summary>
+	public class Repeat : Pattern
+	{
+		readonly INode childNode;
+		
+		public int MinCount { get; set; }
+		public int MaxCount { get; set; }
+		
+		public INode ChildNode {
+			get { return childNode; }
+		}
+		
+		public Repeat(INode childNode)
+		{
+			if (childNode == null)
+				throw new ArgumentNullException("childNode");
+			this.childNode = childNode;
+			this.MinCount = 0;
+			this.MaxCount = int.MaxValue;
+		}
+		
+		public override bool DoMatchCollection(Role role, INode pos, Match match, BacktrackingInfo backtrackingInfo)
+		{
+			var backtrackingStack = backtrackingInfo.backtrackingStack;
+			Debug.Assert(pos == null || pos.Role == role);
+			int matchCount = 0;
+			if (this.MinCount <= 0)
+				backtrackingStack.Push(new PossibleMatch(pos, match.CheckPoint()));
+			while (matchCount < this.MaxCount && pos != null && childNode.DoMatch(pos, match)) {
+				matchCount++;
+				do {
+					pos = pos.NextSibling;
+				} while (pos != null && pos.Role != role);
+				if (matchCount >= this.MinCount)
+					backtrackingStack.Push(new PossibleMatch(pos, match.CheckPoint()));
+			}
+			return false; // never do a normal (single-element) match; always make the caller look at the results on the back-tracking stack.
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			if (other == null || other.IsNull)
+				return this.MinCount <= 0;
+			else
+				return this.MaxCount >= 1 && childNode.DoMatch(other, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,41 @@
+﻿using System;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ICSharpCode.NRefactory")]
+[assembly: AssemblyDescription("Type system and other language-independent parts of NRefactory")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("ICSharpCode")]
+[assembly: AssemblyProduct("SharpDevelop/MonoDevelop")]
+[assembly: AssemblyCopyright("Copyright 2010-2014 AlphaSierraPapa and Xamarin Inc.")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+[assembly: CLSCompliant(true)]
+
+[assembly: InternalsVisibleTo("ICSharpCode.NRefactory.Cecil, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3d38bc66a0dd8dd36f57285e34632ec04b3049866ab1e64cf230e95ffcbfbb90c437b4d11dfe74ba981f746274290bb03f3e636e139e685b501031dc6e0bc8409153f0c842721eb9e8e2a703c9e4d102283f3ddbdfab4078c08de51869715992a694d2f608d0fa865c9d17c06b8d6a9135004e982fd862cdb2277e4ad15a4a6")]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("db38a872-9621-4899-bf2f-5d88b6ba6a54")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.0.0.0")]
+[assembly: AssemblyFileVersion("5.5.0")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Refactoring/IssueMarker.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Refactoring/IssueMarker.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Refactoring/IssueMarker.cs	(revision 11807)
@@ -0,0 +1,57 @@
+// 
+// IssueMarker.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.Refactoring
+{
+	/// <summary>
+	/// The issue marker is used to set how an issue should be marked inside the text editor.
+	/// </summary>
+	public enum IssueMarker
+	{
+		/// <summary>
+		/// The issue is not shown inside the text editor. (But in the task bar)
+		/// </summary>
+		None,
+
+		/// <summary>
+		/// The region is marked as underline in the severity color.
+		/// </summary>
+		WavedLine,
+
+		/// <summary>
+		/// The region is marked as dotted line in the severity color.
+		/// </summary>
+		DottedLine,
+
+		/// <summary>
+		/// The text is grayed out.
+		/// </summary>
+		GrayOut
+	}
+
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Refactoring/Severity.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Refactoring/Severity.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Refactoring/Severity.cs	(revision 11807)
@@ -0,0 +1,61 @@
+// 
+// Severity.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.Refactoring
+{
+	/// <summary>
+	/// The severity influences how the task bar reacts on found issues.
+	/// </summary>
+	public enum Severity
+	{
+		/// <summary>
+		/// None means that the task bar doesn't show the issue.
+		/// </summary>
+		None,
+
+		/// <summary>
+		/// Errors are shown in red and that the task bar is in error state if 1 error is found.
+		/// </summary>
+		Error,
+
+		/// <summary>
+		/// Warnings are shown in yellow and set the task bar to warning state (if no error is found).
+		/// </summary>
+		Warning,
+
+		/// <summary>
+		/// Suggestions are shown in green and doesn't influence the task bar state
+		/// </summary>
+		Suggestion,
+
+		/// <summary>
+		/// Hints are shown in blue and doesn't influence the task bar state
+		/// </summary>
+		Hint
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Role.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Role.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Role.cs	(revision 11807)
@@ -0,0 +1,113 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory
+{
+	/// <summary>
+	/// Represents the role a node plays within its parent.
+	/// </summary>
+	public abstract class Role
+	{
+		public const int RoleIndexBits = 9;
+		
+		static readonly Role[] roles = new Role[1 << RoleIndexBits];
+		static int nextRoleIndex = 0;
+		
+		readonly uint index;
+		
+		[CLSCompliant(false)]
+		public uint Index {
+			get { return index; }
+		}
+		
+		// don't allow NRefactory consumers to derive from Role
+		internal Role()
+		{
+			this.index = (uint)Interlocked.Increment(ref nextRoleIndex);
+			if (this.index >= roles.Length)
+				throw new InvalidOperationException("Too many roles");
+			roles[this.index] = this;
+		}
+		
+		/// <summary>
+		/// Gets whether the specified node is valid in this role.
+		/// </summary>
+		public abstract bool IsValid(object node);
+		
+		/// <summary>
+		/// Gets the role with the specified index.
+		/// </summary>
+		[CLSCompliant(false)]
+		public static Role GetByIndex(uint index)
+		{
+			return roles[index];
+		}
+	}
+	
+	/// <summary>
+	/// Represents the role a node plays within its parent.
+	/// All nodes with this role have type T.
+	/// </summary>
+	public class Role<T> : Role where T : class
+	{
+		readonly string name; // helps with debugging the AST
+		readonly T nullObject;
+		
+		/// <summary>
+		/// Gets the null object used when there's no node with this role.
+		/// Not every role has a null object; this property returns null for roles without a null object.
+		/// </summary>
+		/// <remarks>
+		/// Roles used for non-collections should always have a null object, so that no AST property returns null.
+		/// However, if a role used for collections only, it may leave out the null object.
+		/// </remarks>
+		public T NullObject {
+			get { return nullObject; }
+		}
+		
+		public override bool IsValid(object node)
+		{
+			return node is T;
+		}
+		
+		public Role(string name)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.name = name;
+		}
+		
+		public Role(string name, T nullObject)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+			if (nullObject == null)
+				throw new ArgumentNullException ("nullObject");
+			this.nullObject = nullObject;
+			this.name = name;
+		}
+		
+		public override string ToString()
+		{
+			return name;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/AmbiguousResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/AmbiguousResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/AmbiguousResolveResult.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents an ambiguous type resolve result.
+	/// </summary>
+	public class AmbiguousTypeResolveResult : TypeResolveResult
+	{
+		public AmbiguousTypeResolveResult(IType type) : base(type)
+		{
+		}
+		
+		public override bool IsError {
+			get { return true; }
+		}
+	}
+	
+	/// <summary>
+	/// Represents an ambiguous field/property/event access.
+	/// </summary>
+	public class AmbiguousMemberResolveResult : MemberResolveResult
+	{
+		public AmbiguousMemberResolveResult(ResolveResult targetResult, IMember member) : base(targetResult, member)
+		{
+		}
+		
+		public override bool IsError {
+			get { return true; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ArrayAccessResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ArrayAccessResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ArrayAccessResolveResult.cs	(revision 11807)
@@ -0,0 +1,50 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Resolve result representing an array access.
+	/// </summary>
+	public class ArrayAccessResolveResult : ResolveResult
+	{
+		public readonly ResolveResult Array;
+		public readonly IList<ResolveResult> Indexes;
+		
+		public ArrayAccessResolveResult(IType elementType, ResolveResult array, IList<ResolveResult> indexes) : base(elementType)
+		{
+			if (array == null)
+				throw new ArgumentNullException("array");
+			if (indexes == null)
+				throw new ArgumentNullException("indexes");
+			this.Array = array;
+			this.Indexes = indexes;
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			return new [] { Array }.Concat(Indexes);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ArrayCreateResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ArrayCreateResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ArrayCreateResolveResult.cs	(revision 11807)
@@ -0,0 +1,60 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Resolve result representing an array creation.
+	/// </summary>
+	public class ArrayCreateResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// Gets the size arguments.
+		/// </summary>
+		public readonly IList<ResolveResult> SizeArguments;
+		
+		/// <summary>
+		/// Gets the initializer elements.
+		/// This field may be null if no initializer was specified.
+		/// </summary>
+		public readonly IList<ResolveResult> InitializerElements;
+		
+		public ArrayCreateResolveResult(IType arrayType, IList<ResolveResult> sizeArguments, IList<ResolveResult> initializerElements)
+			: base(arrayType)
+		{
+			if (sizeArguments == null)
+				throw new ArgumentNullException("sizeArguments");
+			this.SizeArguments = sizeArguments;
+			this.InitializerElements = initializerElements;
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			if (InitializerElements != null)
+				return SizeArguments.Concat(InitializerElements);
+			else
+				return SizeArguments;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ByReferenceResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ByReferenceResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ByReferenceResolveResult.cs	(revision 11807)
@@ -0,0 +1,66 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the resolve result of an 'ref x' or 'out x' expression.
+	/// </summary>
+	public class ByReferenceResolveResult : ResolveResult
+	{
+		public bool IsOut { get; private set; }
+		public bool IsRef { get { return !IsOut;} }
+		
+		public readonly ResolveResult ElementResult;
+		
+		public ByReferenceResolveResult(ResolveResult elementResult, bool isOut)
+			: this(elementResult.Type, isOut)
+		{
+			this.ElementResult = elementResult;
+		}
+		
+		public ByReferenceResolveResult(IType elementType, bool isOut)
+			: base(new ByReferenceType(elementType))
+		{
+			this.IsOut = isOut;
+		}
+		
+		public IType ElementType {
+			get { return ((ByReferenceType)this.Type).ElementType; }
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			if (ElementResult != null)
+				return new[] { ElementResult };
+			else
+				return Enumerable.Empty<ResolveResult>();
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} {1} {2}]", GetType().Name, IsOut ? "out" : "ref", ElementType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ConstantResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ConstantResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ConstantResolveResult.cs	(revision 11807)
@@ -0,0 +1,55 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// ResolveResult representing a compile-time constant.
+	/// Note: this class is mainly used for literals; there may be other ResolveResult classes
+	/// which are compile-time constants as well.
+	/// For example, a reference to a <c>const</c> field results in a <see cref="MemberResolveResult"/>.
+	/// 
+	/// Check <see cref="ResolveResult.IsCompileTimeConstant"/> to determine is a resolve result is a constant.
+	/// </summary>
+	public class ConstantResolveResult : ResolveResult
+	{
+		object constantValue;
+		
+		public ConstantResolveResult(IType type, object constantValue) : base(type)
+		{
+			this.constantValue = constantValue;
+		}
+		
+		public override bool IsCompileTimeConstant {
+			get { return true; }
+		}
+		
+		public override object ConstantValue {
+			get { return constantValue; }
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} {1} = {2}]", GetType().Name, this.Type, constantValue);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/Conversion.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/Conversion.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/Conversion.cs	(revision 11807)
@@ -0,0 +1,568 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Holds information about a conversion between two types.
+	/// </summary>
+	public abstract class Conversion : IEquatable<Conversion>
+	{
+		#region Conversion factory methods
+		/// <summary>
+		/// Not a valid conversion.
+		/// </summary>
+		public static readonly Conversion None = new InvalidConversion();
+		
+		/// <summary>
+		/// Identity conversion.
+		/// </summary>
+		public static readonly Conversion IdentityConversion = new BuiltinConversion(true, 0);
+		
+		public static readonly Conversion ImplicitNumericConversion = new NumericOrEnumerationConversion(true, false);
+		public static readonly Conversion ExplicitNumericConversion = new NumericOrEnumerationConversion(false, false);
+		public static readonly Conversion ImplicitLiftedNumericConversion = new NumericOrEnumerationConversion(true, true);
+		public static readonly Conversion ExplicitLiftedNumericConversion = new NumericOrEnumerationConversion(false, true);
+		
+		public static Conversion EnumerationConversion(bool isImplicit, bool isLifted)
+		{
+			return new NumericOrEnumerationConversion(isImplicit, isLifted, true);
+		}
+		
+		public static readonly Conversion NullLiteralConversion = new BuiltinConversion(true, 1);
+		
+		/// <summary>
+		/// The numeric conversion of a constant expression.
+		/// </summary>
+		public static readonly Conversion ImplicitConstantExpressionConversion = new BuiltinConversion(true, 2);
+		
+		public static readonly Conversion ImplicitReferenceConversion = new BuiltinConversion(true, 3);
+		public static readonly Conversion ExplicitReferenceConversion = new BuiltinConversion(false, 3);
+		
+		public static readonly Conversion ImplicitDynamicConversion = new BuiltinConversion(true, 4);
+		public static readonly Conversion ExplicitDynamicConversion = new BuiltinConversion(false, 4);
+		
+		public static readonly Conversion ImplicitNullableConversion = new BuiltinConversion(true, 5);
+		public static readonly Conversion ExplicitNullableConversion = new BuiltinConversion(false, 5);
+		
+		public static readonly Conversion ImplicitPointerConversion = new BuiltinConversion(true, 6);
+		public static readonly Conversion ExplicitPointerConversion = new BuiltinConversion(false, 6);
+		
+		public static readonly Conversion BoxingConversion = new BuiltinConversion(true, 7);
+		public static readonly Conversion UnboxingConversion = new BuiltinConversion(false, 8);
+		
+		/// <summary>
+		/// C# 'as' cast.
+		/// </summary>
+		public static readonly Conversion TryCast = new BuiltinConversion(false, 9);
+		
+		[Obsolete("Use UserDefinedConversion() instead")]
+		public static Conversion UserDefinedImplicitConversion(IMethod operatorMethod, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted)
+		{
+			if (operatorMethod == null)
+				throw new ArgumentNullException("operatorMethod");
+			return new UserDefinedConv(true, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, false);
+		}
+		
+		[Obsolete("Use UserDefinedConversion() instead")]
+		public static Conversion UserDefinedExplicitConversion(IMethod operatorMethod, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted)
+		{
+			if (operatorMethod == null)
+				throw new ArgumentNullException("operatorMethod");
+			return new UserDefinedConv(false, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, false);
+		}
+		
+		public static Conversion UserDefinedConversion(IMethod operatorMethod, bool isImplicit, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted = false, bool isAmbiguous = false)
+		{
+			if (operatorMethod == null)
+				throw new ArgumentNullException("operatorMethod");
+			return new UserDefinedConv(isImplicit, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, isAmbiguous);
+		}
+		
+		public static Conversion MethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument)
+		{
+			if (chosenMethod == null)
+				throw new ArgumentNullException("chosenMethod");
+			return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: true);
+		}
+		
+		public static Conversion InvalidMethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument)
+		{
+			if (chosenMethod == null)
+				throw new ArgumentNullException("chosenMethod");
+			return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: false);
+		}
+		#endregion
+		
+		#region Inner classes
+		sealed class InvalidConversion : Conversion
+		{
+			public override bool IsValid {
+				get { return false; }
+			}
+			
+			public override string ToString()
+			{
+				return "None";
+			}
+		}
+		
+		sealed class NumericOrEnumerationConversion : Conversion
+		{
+			readonly bool isImplicit;
+			readonly bool isLifted;
+			readonly bool isEnumeration;
+			
+			public NumericOrEnumerationConversion(bool isImplicit, bool isLifted, bool isEnumeration = false)
+			{
+				this.isImplicit = isImplicit;
+				this.isLifted = isLifted;
+				this.isEnumeration = isEnumeration;
+			}
+			
+			public override bool IsImplicit {
+				get { return isImplicit; }
+			}
+			
+			public override bool IsExplicit {
+				get { return !isImplicit; }
+			}
+			
+			public override bool IsNumericConversion {
+				get { return !isEnumeration; }
+			}
+			
+			public override bool IsEnumerationConversion {
+				get { return isEnumeration; }
+			}
+			
+			public override bool IsLifted {
+				get { return isLifted; }
+			}
+			
+			public override string ToString()
+			{
+				return (isImplicit ? "implicit" : "explicit")
+					+ (isLifted ? " lifted" : "")
+					+ (isEnumeration ? " enumeration" : " numeric")
+					+ " conversion";
+			}
+			
+			public override bool Equals(Conversion other)
+			{
+				NumericOrEnumerationConversion o = other as NumericOrEnumerationConversion;
+				return o != null && isImplicit == o.isImplicit && isLifted == o.isLifted && isEnumeration == o.isEnumeration;
+			}
+			
+			public override int GetHashCode()
+			{
+				return (isImplicit ? 1 : 0) + (isLifted ? 2 : 0) + (isEnumeration ? 4 : 0);
+			}
+		}
+		
+		sealed class BuiltinConversion : Conversion
+		{
+			readonly bool isImplicit;
+			readonly byte type;
+			
+			public BuiltinConversion(bool isImplicit, byte type)
+			{
+				this.isImplicit = isImplicit;
+				this.type = type;
+			}
+			
+			public override bool IsImplicit {
+				get { return isImplicit; }
+			}
+			
+			public override bool IsExplicit {
+				get { return !isImplicit; }
+			}
+			
+			public override bool IsIdentityConversion {
+				get { return type == 0; }
+			}
+			
+			public override bool IsNullLiteralConversion {
+				get { return type == 1; }
+			}
+			
+			public override bool IsConstantExpressionConversion {
+				get { return type == 2; }
+			}
+
+			public override bool IsReferenceConversion {
+				get { return type == 3; }
+			}
+			
+			public override bool IsDynamicConversion {
+				get { return type == 4; }
+			}
+			
+			public override bool IsNullableConversion {
+				get { return type == 5; }
+			}
+			
+			public override bool IsPointerConversion {
+				get { return type == 6; }
+			}
+			
+			public override bool IsBoxingConversion {
+				get { return type == 7; }
+			}
+			
+			public override bool IsUnboxingConversion {
+				get { return type == 8; }
+			}
+			
+			public override bool IsTryCast {
+				get { return type == 9; }
+			}
+			
+			public override string ToString()
+			{
+				string name = null;
+				switch (type) {
+					case 0:
+						return "identity conversion";
+					case 1:
+						return "null-literal conversion";
+					case 2:
+						name = "constant-expression";
+						break;
+					case 3:
+						name = "reference";
+						break;
+					case 4:
+						name = "dynamic";
+						break;
+					case 5:
+						name = "nullable";
+						break;
+					case 6:
+						name = "pointer";
+						break;
+					case 7:
+						return "boxing conversion";
+					case 8:
+						return "unboxing conversion";
+					case 9:
+						return "try cast";
+				}
+				return (isImplicit ? "implicit " : "explicit ") + name + " conversion";
+			}
+		}
+		
+		sealed class UserDefinedConv : Conversion
+		{
+			readonly IMethod method;
+			readonly bool isLifted;
+			readonly Conversion conversionBeforeUserDefinedOperator;
+			readonly Conversion conversionAfterUserDefinedOperator;
+			readonly bool isImplicit;
+			readonly bool isValid;
+			
+			public UserDefinedConv(bool isImplicit, IMethod method, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted, bool isAmbiguous)
+			{
+				this.method = method;
+				this.isLifted = isLifted;
+				this.conversionBeforeUserDefinedOperator = conversionBeforeUserDefinedOperator;
+				this.conversionAfterUserDefinedOperator = conversionAfterUserDefinedOperator;
+				this.isImplicit = isImplicit;
+				this.isValid = !isAmbiguous;
+			}
+			
+			public override bool IsValid {
+				get { return isValid; }
+			}
+			
+			public override bool IsImplicit {
+				get { return isImplicit; }
+			}
+			
+			public override bool IsExplicit {
+				get { return !isImplicit; }
+			}
+			
+			public override bool IsLifted {
+				get { return isLifted; }
+			}
+			
+			public override bool IsUserDefined {
+				get { return true; }
+			}
+			
+			public override Conversion ConversionBeforeUserDefinedOperator {
+				get { return conversionBeforeUserDefinedOperator; }
+			}
+		
+			public override Conversion ConversionAfterUserDefinedOperator {
+				get { return conversionAfterUserDefinedOperator; }
+			}
+
+			public override IMethod Method {
+				get { return method; }
+			}
+			
+			public override bool Equals(Conversion other)
+			{
+				UserDefinedConv o = other as UserDefinedConv;
+				return o != null && isLifted == o.isLifted && isImplicit == o.isImplicit && isValid == o.isValid && method.Equals(o.method);
+			}
+			
+			public override int GetHashCode()
+			{
+				return unchecked(method.GetHashCode() + (isLifted ? 31 : 27) + (isImplicit ? 71 : 61) + (isValid ? 107 : 109));
+			}
+			
+			public override string ToString()
+			{
+				return (isImplicit ? "implicit" : "explicit")
+					+ (isLifted ? " lifted" : "")
+					+ (isValid ? "" : " ambiguous")
+					+ "user-defined conversion (" + method + ")";
+			}
+		}
+		
+		sealed class MethodGroupConv : Conversion
+		{
+			readonly IMethod method;
+			readonly bool isVirtualMethodLookup;
+			readonly bool delegateCapturesFirstArgument;
+			readonly bool isValid;
+			
+			public MethodGroupConv(IMethod method, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument, bool isValid)
+			{
+				this.method = method;
+				this.isVirtualMethodLookup = isVirtualMethodLookup;
+				this.delegateCapturesFirstArgument = delegateCapturesFirstArgument;
+				this.isValid = isValid;
+			}
+			
+			public override bool IsValid {
+				get { return isValid; }
+			}
+			
+			public override bool IsImplicit {
+				get { return true; }
+			}
+			
+			public override bool IsMethodGroupConversion {
+				get { return true; }
+			}
+			
+			public override bool IsVirtualMethodLookup {
+				get { return isVirtualMethodLookup; }
+			}
+			
+			public override bool DelegateCapturesFirstArgument {
+				get { return delegateCapturesFirstArgument; }
+			}
+
+			public override IMethod Method {
+				get { return method; }
+			}
+			
+			public override bool Equals(Conversion other)
+			{
+				MethodGroupConv o = other as MethodGroupConv;
+				return o != null && method.Equals(o.method);
+			}
+			
+			public override int GetHashCode()
+			{
+				return method.GetHashCode();
+			}
+		}
+		#endregion
+		
+		/// <summary>
+		/// Gets whether the conversion is valid.
+		/// </summary>
+		public virtual bool IsValid {
+			get { return true; }
+		}
+		
+		public virtual bool IsImplicit {
+			get { return false; }
+		}
+		
+		public virtual bool IsExplicit {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether the conversion is an '<c>as</c>' cast.
+		/// </summary>
+		public virtual bool IsTryCast {
+			get { return false; }
+		}
+		
+		public virtual bool IsIdentityConversion {
+			get { return false; }
+		}
+		
+		public virtual bool IsNullLiteralConversion {
+			get { return false; }
+		}
+		
+		public virtual bool IsConstantExpressionConversion {
+			get { return false; }
+		}
+
+		public virtual bool IsNumericConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether this conversion is a lifted version of another conversion.
+		/// </summary>
+		public virtual bool IsLifted {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether the conversion is dynamic.
+		/// </summary>
+		public virtual bool IsDynamicConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether the conversion is a reference conversion.
+		/// </summary>
+		public virtual bool IsReferenceConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether the conversion is an enumeration conversion.
+		/// </summary>
+		public virtual bool IsEnumerationConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether the conversion is a nullable conversion
+		/// (conversion between a nullable type and the regular type).
+		/// </summary>
+		public virtual bool IsNullableConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether this conversion is user-defined (op_Implicit or op_Explicit).
+		/// </summary>
+		public virtual bool IsUserDefined {
+			get { return false; }
+		}
+
+		/// <summary>
+		/// The conversion that is applied to the input before the user-defined conversion operator is invoked.
+		/// </summary>
+		public virtual Conversion ConversionBeforeUserDefinedOperator {
+			get { return null; }
+		}
+		
+		/// <summary>
+		/// The conversion that is applied to the result of the user-defined conversion operator.
+		/// </summary>
+		public virtual Conversion ConversionAfterUserDefinedOperator {
+			get { return null; }
+		}
+
+		/// <summary>
+		/// Gets whether this conversion is a boxing conversion.
+		/// </summary>
+		public virtual bool IsBoxingConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether this conversion is an unboxing conversion.
+		/// </summary>
+		public virtual bool IsUnboxingConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether this conversion is a pointer conversion.
+		/// </summary>
+		public virtual bool IsPointerConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets whether this conversion is a method group conversion.
+		/// </summary>
+		public virtual bool IsMethodGroupConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// For method-group conversions, gets whether to perform a virtual method lookup at runtime.
+		/// </summary>
+		public virtual bool IsVirtualMethodLookup {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// For method-group conversions, gets whether the conversion captures the first argument.
+		/// 
+		/// For instance methods, this property always returns true for C# method-group conversions.
+		/// For static methods, this property returns true for method-group conversions of an extension method performed on an instance (eg. <c>Func&lt;int&gt; f = myEnumerable.Single</c>).
+		/// </summary>
+		public virtual bool DelegateCapturesFirstArgument {
+			get { return false; }
+		}
+
+		/// <summary>
+		/// Gets whether this conversion is an anonymous function conversion.
+		/// </summary>
+		public virtual bool IsAnonymousFunctionConversion {
+			get { return false; }
+		}
+		
+		/// <summary>
+		/// Gets the method associated with this conversion.
+		/// For user-defined conversions, this is the method being called.
+		/// For method-group conversions, this is the method that was chosen from the group.
+		/// </summary>
+		public virtual IMethod Method {
+			get { return null; }
+		}
+		
+		public override sealed bool Equals(object obj)
+		{
+			return Equals(obj as Conversion);
+		}
+		
+		public override int GetHashCode()
+		{
+			return base.GetHashCode();
+		}
+		
+		public virtual bool Equals(Conversion other)
+		{
+			return this == other;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ConversionResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ConversionResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ConversionResolveResult.cs	(revision 11807)
@@ -0,0 +1,68 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents an implicit or explicit type conversion.
+	/// <c>conversionResolveResult.Input.Type</c> is the source type;
+	/// <c>conversionResolveResult.Type</c> is the target type.
+	/// The <see cref="Conversion"/> property provides details about the kind of conversion.
+	/// </summary>
+	public class ConversionResolveResult : ResolveResult
+	{
+		public readonly ResolveResult Input;
+		public readonly Conversion Conversion;
+		
+		/// <summary>
+		/// For numeric conversions, specifies whether overflow checking is enabled.
+		/// </summary>
+		public readonly bool CheckForOverflow;
+		
+		public ConversionResolveResult(IType targetType, ResolveResult input, Conversion conversion)
+			: base(targetType)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			if (conversion == null)
+				throw new ArgumentNullException("conversion");
+			this.Input = input;
+			this.Conversion = conversion;
+		}
+		
+		public ConversionResolveResult(IType targetType, ResolveResult input, Conversion conversion, bool checkForOverflow)
+			: this(targetType, input, conversion)
+		{
+			this.CheckForOverflow = checkForOverflow;
+		}
+		
+		public override bool IsError {
+			get { return !Conversion.IsValid; }
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			return new [] { Input };
+		}
+
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ErrorResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ErrorResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ErrorResolveResult.cs	(revision 11807)
@@ -0,0 +1,56 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents a resolve error.
+	/// 
+	/// Note: some errors are represented by other classes; for example a <see cref="ConversionResolveResult"/> may
+	/// be erroneous if the conversion is invalid.
+	/// </summary>
+	/// <seealso cref="ResolveResult.IsError"/>.
+	public class ErrorResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// Gets an ErrorResolveResult instance with <c>Type</c> = <c>SpecialType.UnknownType</c>.
+		/// </summary>
+		public static readonly ErrorResolveResult UnknownError = new ErrorResolveResult(SpecialType.UnknownType);
+		
+		public ErrorResolveResult(IType type) : base(type)
+		{
+		}
+		
+		public ErrorResolveResult(IType type, string message, TextLocation location) : base(type)
+		{
+			this.Message = message;
+			this.Location = location;
+		}
+		
+		public override bool IsError {
+			get { return true; }
+		}
+		
+		public string Message { get; private set; }
+		
+		public TextLocation Location { get; private set; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ForEachResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ForEachResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ForEachResolveResult.cs	(revision 11807)
@@ -0,0 +1,90 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Resolve result representing a 'foreach' loop.
+	/// </summary>
+	public class ForEachResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// Gets the semantic tree for the call to GetEnumerator.
+		/// </summary>
+		public readonly ResolveResult GetEnumeratorCall;
+		
+		/// <summary>
+		/// Gets the collection type.
+		/// </summary>
+		public readonly IType CollectionType;
+		
+		/// <summary>
+		/// Gets the enumerator type.
+		/// </summary>
+		public readonly IType EnumeratorType;
+		
+		/// <summary>
+		/// Gets the element type.
+		/// This is the type that would be inferred for an implicitly-typed element variable.
+		/// For explicitly-typed element variables, this type may differ from <c>ElementVariable.Type</c>.
+		/// </summary>
+		public readonly IType ElementType;
+		
+		/// <summary>
+		/// Gets the element variable.
+		/// </summary>
+		public readonly IVariable ElementVariable;
+		
+		/// <summary>
+		/// Gets the Current property on the IEnumerator.
+		/// Returns null if the property is not found.
+		/// </summary>
+		public readonly IProperty CurrentProperty;
+		
+		/// <summary>
+		/// Gets the MoveNext() method on the IEnumerator.
+		/// Returns null if the method is not found.
+		/// </summary>
+		public readonly IMethod MoveNextMethod;
+		
+		public ForEachResolveResult(ResolveResult getEnumeratorCall, IType collectionType, IType enumeratorType, IType elementType, IVariable elementVariable, IProperty currentProperty, IMethod moveNextMethod, IType voidType)
+			: base(voidType)
+		{
+			if (getEnumeratorCall == null)
+				throw new ArgumentNullException("getEnumeratorCall");
+			if (collectionType == null)
+				throw new ArgumentNullException("collectionType");
+			if (enumeratorType == null)
+				throw new ArgumentNullException("enumeratorType");
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			if (elementVariable == null)
+				throw new ArgumentNullException("elementVariable");
+			this.GetEnumeratorCall = getEnumeratorCall;
+			this.CollectionType = collectionType;
+			this.EnumeratorType = enumeratorType;
+			this.ElementType = elementType;
+			this.ElementVariable = elementVariable;
+			this.CurrentProperty = currentProperty;
+			this.MoveNextMethod = moveNextMethod;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/InitializedObjectResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/InitializedObjectResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/InitializedObjectResolveResult.cs	(revision 11807)
@@ -0,0 +1,34 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Refers to the object that is currently being initialized.
+	/// Used within <see cref="InvocationResolveResult.InitializerStatements"/>.
+	/// </summary>
+	public class InitializedObjectResolveResult : ResolveResult
+	{
+		public InitializedObjectResolveResult(IType type) : base(type)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/InvocationResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/InvocationResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/InvocationResolveResult.cs	(revision 11807)
@@ -0,0 +1,75 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the result of a method, constructor or indexer invocation.
+	/// </summary>
+	public class InvocationResolveResult : MemberResolveResult
+	{
+		/// <summary>
+		/// Gets the arguments that are being passed to the method, in the order the arguments are being evaluated.
+		/// </summary>
+		public readonly IList<ResolveResult> Arguments;
+		
+		/// <summary>
+		/// Gets the list of initializer statements that are appplied to the result of this invocation.
+		/// This is used to represent object and collection initializers.
+		/// With the initializer statements, the <see cref="InitializedObjectResolveResult"/> is used
+		/// to refer to the result of this invocation.
+		/// </summary>
+		public readonly IList<ResolveResult> InitializerStatements;
+		
+		public InvocationResolveResult(ResolveResult targetResult, IParameterizedMember member,
+		                               IList<ResolveResult> arguments = null,
+		                               IList<ResolveResult> initializerStatements = null,
+		                               IType returnTypeOverride = null)
+			: base(targetResult, member, returnTypeOverride)
+		{
+			this.Arguments = arguments ?? EmptyList<ResolveResult>.Instance;
+			this.InitializerStatements = initializerStatements ?? EmptyList<ResolveResult>.Instance;
+		}
+		
+		public new IParameterizedMember Member {
+			get { return (IParameterizedMember)base.Member; }
+		}
+		
+		/// <summary>
+		/// Gets the arguments in the order they are being passed to the method.
+		/// For parameter arrays (params), this will return an ArrayCreateResolveResult.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
+		                                                 Justification = "Derived methods may be expensive and create new lists")]
+		public virtual IList<ResolveResult> GetArgumentsForCall()
+		{
+			return Arguments;
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			return base.GetChildResults().Concat(this.Arguments).Concat(this.InitializerStatements);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/LocalResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/LocalResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/LocalResolveResult.cs	(revision 11807)
@@ -0,0 +1,77 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents a local variable or parameter.
+	/// </summary>
+	public class LocalResolveResult : ResolveResult
+	{
+		readonly IVariable variable;
+		
+		public LocalResolveResult(IVariable variable)
+			: base(UnpackTypeIfByRefParameter(variable))
+		{
+			this.variable = variable;
+		}
+		
+		static IType UnpackTypeIfByRefParameter(IVariable variable)
+		{
+			if (variable == null)
+				throw new ArgumentNullException("variable");
+			IType type = variable.Type;
+			if (type.Kind == TypeKind.ByReference) {
+				IParameter p = variable as IParameter;
+				if (p != null && (p.IsRef || p.IsOut))
+					return ((ByReferenceType)type).ElementType;
+			}
+			return type;
+		}
+		
+		public IVariable Variable {
+			get { return variable; }
+		}
+		
+		public bool IsParameter {
+			get { return variable is IParameter; }
+		}
+		
+		public override bool IsCompileTimeConstant {
+			get { return variable.IsConst; }
+		}
+		
+		public override object ConstantValue {
+			get { return IsParameter ? null : variable.ConstantValue; }
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[LocalResolveResult {0}]", variable);
+		}
+		
+		public override DomRegion GetDefinitionRegion()
+		{
+			return variable.Region;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/MemberResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/MemberResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/MemberResolveResult.cs	(revision 11807)
@@ -0,0 +1,148 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the result of a member invocation.
+	/// Used for field/property/event access.
+	/// Also, <see cref="InvocationResolveResult"/> derives from MemberResolveResult.
+	/// </summary>
+	public class MemberResolveResult : ResolveResult
+	{
+		readonly IMember member;
+		readonly bool isConstant;
+		readonly object constantValue;
+		readonly ResolveResult targetResult;
+		readonly bool isVirtualCall;
+		
+		public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnTypeOverride = null)
+			: base(returnTypeOverride ?? ComputeType(member))
+		{
+			this.targetResult = targetResult;
+			this.member = member;
+			var thisRR = targetResult as ThisResolveResult;
+			this.isVirtualCall = member.IsOverridable && !(thisRR != null && thisRR.CausesNonVirtualInvocation);
+			
+			IField field = member as IField;
+			if (field != null) {
+				isConstant = field.IsConst;
+				if (isConstant)
+					constantValue = field.ConstantValue;
+			}
+		}
+		
+		public MemberResolveResult(ResolveResult targetResult, IMember member, bool isVirtualCall, IType returnTypeOverride = null)
+			: base(returnTypeOverride ?? ComputeType(member))
+		{
+			this.targetResult = targetResult;
+			this.member = member;
+			this.isVirtualCall = isVirtualCall;
+			IField field = member as IField;
+			if (field != null) {
+				isConstant = field.IsConst;
+				if (isConstant)
+					constantValue = field.ConstantValue;
+			}
+		}
+		
+		static IType ComputeType(IMember member)
+		{
+			switch (member.SymbolKind) {
+				case SymbolKind.Constructor:
+					return member.DeclaringType;
+				case SymbolKind.Field:
+					if (((IField)member).IsFixed)
+						return new PointerType(member.ReturnType);
+					break;
+			}
+			return member.ReturnType;
+		}
+		
+		public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnType, bool isConstant, object constantValue)
+			: base(returnType)
+		{
+			this.targetResult = targetResult;
+			this.member = member;
+			this.isConstant = isConstant;
+			this.constantValue = constantValue;
+		}
+		
+		public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnType, bool isConstant, object constantValue, bool isVirtualCall)
+			: base(returnType)
+		{
+			this.targetResult = targetResult;
+			this.member = member;
+			this.isConstant = isConstant;
+			this.constantValue = constantValue;
+			this.isVirtualCall = isVirtualCall;
+		}
+		
+		public ResolveResult TargetResult {
+			get { return targetResult; }
+		}
+		
+		/// <summary>
+		/// Gets the member.
+		/// This property never returns null.
+		/// </summary>
+		public IMember Member {
+			get { return member; }
+		}
+		
+		/// <summary>
+		/// Gets whether this MemberResolveResult is a virtual call.
+		/// </summary>
+		public bool IsVirtualCall {
+			get { return isVirtualCall; }
+		}
+		
+		public override bool IsCompileTimeConstant {
+			get { return isConstant; }
+		}
+		
+		public override object ConstantValue {
+			get { return constantValue; }
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			if (targetResult != null)
+				return new[] { targetResult };
+			else
+				return Enumerable.Empty<ResolveResult>();
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} {1}]", GetType().Name, member);
+		}
+		
+		public override DomRegion GetDefinitionRegion()
+		{
+			return member.Region;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/NamedArgumentResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/NamedArgumentResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/NamedArgumentResolveResult.cs	(revision 11807)
@@ -0,0 +1,81 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents a named argument.
+	/// </summary>
+	public class NamedArgumentResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// Gets the member to which the parameter belongs.
+		/// This field can be null.
+		/// </summary>
+		public readonly IParameterizedMember Member;
+		
+		/// <summary>
+		/// Gets the parameter.
+		/// This field can be null.
+		/// </summary>
+		public readonly IParameter Parameter;
+		
+		/// <summary>
+		/// Gets the parameter name.
+		/// </summary>
+		public readonly string ParameterName;
+		
+		/// <summary>
+		/// Gets the argument passed to the parameter.
+		/// </summary>
+		public readonly ResolveResult Argument;
+		
+		public NamedArgumentResolveResult(IParameter parameter, ResolveResult argument, IParameterizedMember member = null)
+			: base(argument.Type)
+		{
+			if (parameter == null)
+				throw new ArgumentNullException("parameter");
+			if (argument == null)
+				throw new ArgumentNullException("argument");
+			this.Member = member;
+			this.Parameter = parameter;
+			this.ParameterName = parameter.Name;
+			this.Argument = argument;
+		}
+		
+		public NamedArgumentResolveResult(string parameterName, ResolveResult argument)
+			: base(argument.Type)
+		{
+			if (parameterName == null)
+				throw new ArgumentNullException("parameterName");
+			if (argument == null)
+				throw new ArgumentNullException("argument");
+			this.ParameterName = parameterName;
+			this.Argument = argument;
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			return new [] { Argument };
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/NamespaceResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/NamespaceResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/NamespaceResolveResult.cs	(revision 11807)
@@ -0,0 +1,50 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents that an expression resolved to a namespace.
+	/// </summary>
+	public class NamespaceResolveResult : ResolveResult
+	{
+		readonly INamespace ns;
+		
+		public NamespaceResolveResult(INamespace ns) : base(SpecialType.UnknownType)
+		{
+			this.ns = ns;
+		}
+		
+		public INamespace Namespace {
+			get { return ns; }
+		}
+		
+		public string NamespaceName {
+			get { return ns.FullName; }
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} {1}]", GetType().Name, ns);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/OperatorResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/OperatorResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/OperatorResolveResult.cs	(revision 11807)
@@ -0,0 +1,90 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq.Expressions;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents a unary/binary/ternary operator invocation.
+	/// </summary>
+	public class OperatorResolveResult : ResolveResult
+	{
+		readonly ExpressionType operatorType;
+		readonly IMethod userDefinedOperatorMethod;
+		readonly IList<ResolveResult> operands;
+		readonly bool isLiftedOperator;
+		
+		public OperatorResolveResult(IType resultType, ExpressionType operatorType, params ResolveResult[] operands)
+			: base(resultType)
+		{
+			if (operands == null)
+				throw new ArgumentNullException("operands");
+			this.operatorType = operatorType;
+			this.operands = operands;
+		}
+		
+		public OperatorResolveResult(IType resultType, ExpressionType operatorType, IMethod userDefinedOperatorMethod, bool isLiftedOperator, IList<ResolveResult> operands)
+			: base(resultType)
+		{
+			if (operands == null)
+				throw new ArgumentNullException("operands");
+			this.operatorType = operatorType;
+			this.userDefinedOperatorMethod = userDefinedOperatorMethod;
+			this.isLiftedOperator = isLiftedOperator;
+			this.operands = operands;
+		}
+		
+		/// <summary>
+		/// Gets the operator type.
+		/// </summary>
+		public ExpressionType OperatorType {
+			get { return operatorType; }
+		}
+		
+		/// <summary>
+		/// Gets the operands.
+		/// </summary>
+		public IList<ResolveResult> Operands {
+			get { return operands; }
+		}
+		
+		/// <summary>
+		/// Gets the user defined operator method.
+		/// Returns null if this is a predefined operator.
+		/// </summary>
+		public IMethod UserDefinedOperatorMethod {
+			get { return userDefinedOperatorMethod; }
+		}
+		
+		/// <summary>
+		/// Gets whether this is a lifted operator.
+		/// </summary>
+		public bool IsLiftedOperator {
+			get { return isLiftedOperator; }
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			return operands;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ResolveResult.cs	(revision 11807)
@@ -0,0 +1,78 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the result of resolving an expression.
+	/// </summary>
+	public class ResolveResult
+	{
+		readonly IType type;
+		
+		public ResolveResult(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			this.type = type;
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods",
+		                                                 Justification = "Unrelated to object.GetType()")]
+		public IType Type {
+			get { return type; }
+		}
+		
+		public virtual bool IsCompileTimeConstant {
+			get { return false; }
+		}
+		
+		public virtual object ConstantValue {
+			get { return null; }
+		}
+		
+		public virtual bool IsError {
+			get { return false; }
+		}
+		
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " " + type + "]";
+		}
+		
+		public virtual IEnumerable<ResolveResult> GetChildResults()
+		{
+			return Enumerable.Empty<ResolveResult>();
+		}
+		
+		public virtual DomRegion GetDefinitionRegion()
+		{
+			return DomRegion.Empty;
+		}
+		
+		public virtual ResolveResult ShallowClone()
+		{
+			return (ResolveResult)MemberwiseClone();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/SizeOfResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/SizeOfResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/SizeOfResolveResult.cs	(revision 11807)
@@ -0,0 +1,66 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the 'sizeof'.
+	/// </summary>
+	public class SizeOfResolveResult : ResolveResult
+	{
+		readonly IType referencedType;
+		readonly int? constantValue;
+		
+		public SizeOfResolveResult(IType int32, IType referencedType, int? constantValue)
+			: base(int32)
+		{
+			if (referencedType == null)
+				throw new ArgumentNullException("referencedType");
+			this.referencedType = referencedType;
+			this.constantValue = constantValue;
+		}
+		
+		/// <summary>
+		/// The type referenced by the 'sizeof'.
+		/// </summary>
+		public IType ReferencedType {
+			get { return referencedType; }
+		}
+
+		public override bool IsCompileTimeConstant {
+			get {
+				return constantValue != null;
+			}
+		}
+
+		public override object ConstantValue {
+			get {
+				return constantValue;
+			}
+		}
+
+		public override bool IsError {
+			get {
+				return referencedType.IsReferenceType != false;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ThisResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ThisResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/ThisResolveResult.cs	(revision 11807)
@@ -0,0 +1,44 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the 'this' reference.
+	/// Also used for the 'base' reference.
+	/// </summary>
+	public class ThisResolveResult : ResolveResult
+	{
+		bool causesNonVirtualInvocation;
+		
+		public ThisResolveResult(IType type, bool causesNonVirtualInvocation = false) : base(type)
+		{
+			this.causesNonVirtualInvocation = causesNonVirtualInvocation;
+		}
+		
+		/// <summary>
+		/// Gets whether this resolve result causes member invocations to be non-virtual.
+		/// </summary>
+		public bool CausesNonVirtualInvocation {
+			get { return causesNonVirtualInvocation; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeIsResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeIsResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeIsResolveResult.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Resolve result for a C# 'is' expression.
+	/// "Input is TargetType".
+	/// </summary>
+	public class TypeIsResolveResult : ResolveResult
+	{
+		public readonly ResolveResult Input;
+		/// <summary>
+		/// Type that is being compared with.
+		/// </summary>
+		public readonly IType TargetType;
+		
+		public TypeIsResolveResult(ResolveResult input, IType targetType, IType booleanType)
+			: base(booleanType)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			if (targetType == null)
+				throw new ArgumentNullException("targetType");
+			this.Input = input;
+			this.TargetType = targetType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeOfResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeOfResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeOfResolveResult.cs	(revision 11807)
@@ -0,0 +1,46 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents the 'typeof'.
+	/// </summary>
+	public class TypeOfResolveResult : ResolveResult
+	{
+		readonly IType referencedType;
+		
+		public TypeOfResolveResult(IType systemType, IType referencedType)
+			: base(systemType)
+		{
+			if (referencedType == null)
+				throw new ArgumentNullException("referencedType");
+			this.referencedType = referencedType;
+		}
+		
+		/// <summary>
+		/// The type referenced by the 'typeof'.
+		/// </summary>
+		public IType ReferencedType {
+			get { return referencedType; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/TypeResolveResult.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// The resolved expression refers to a type name.
+	/// </summary>
+	public class TypeResolveResult : ResolveResult
+	{
+		public TypeResolveResult(IType type)
+			: base(type)
+		{
+		}
+		
+		public override bool IsError {
+			get { return this.Type.Kind == TypeKind.Unknown; }
+		}
+		
+		public override DomRegion GetDefinitionRegion()
+		{
+			ITypeDefinition def = this.Type.GetDefinition();
+			if (def != null)
+				return def.Region;
+			else
+				return DomRegion.Empty;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/UnknownMemberResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/UnknownMemberResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Semantics/UnknownMemberResolveResult.cs	(revision 11807)
@@ -0,0 +1,122 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.Semantics
+{
+	/// <summary>
+	/// Represents an unknown member.
+	/// </summary>
+	public class UnknownMemberResolveResult : ResolveResult
+	{
+		readonly IType targetType;
+		readonly string memberName;
+		readonly ReadOnlyCollection<IType> typeArguments;
+		
+		public UnknownMemberResolveResult(IType targetType, string memberName, IEnumerable<IType> typeArguments)
+			: base(SpecialType.UnknownType)
+		{
+			if (targetType == null)
+				throw new ArgumentNullException("targetType");
+			this.targetType = targetType;
+			this.memberName = memberName;
+			this.typeArguments = new ReadOnlyCollection<IType>(typeArguments.ToArray());
+		}
+		
+		/// <summary>
+		/// The type on which the method is being called.
+		/// </summary>
+		public IType TargetType {
+			get { return targetType; }
+		}
+		
+		public string MemberName {
+			get { return memberName; }
+		}
+		
+		public ReadOnlyCollection<IType> TypeArguments {
+			get { return typeArguments; }
+		}
+		
+		public override bool IsError {
+			get { return true; }
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} {1}.{2}]", GetType().Name, targetType, memberName);
+		}
+	}
+	
+	/// <summary>
+	/// Represents an unknown method.
+	/// </summary>
+	public class UnknownMethodResolveResult : UnknownMemberResolveResult
+	{
+		readonly ReadOnlyCollection<IParameter> parameters;
+		
+		public UnknownMethodResolveResult(IType targetType, string methodName, IEnumerable<IType> typeArguments, IEnumerable<IParameter> parameters)
+			: base(targetType, methodName, typeArguments)
+		{
+			this.parameters = new ReadOnlyCollection<IParameter>(parameters.ToArray());
+		}
+		
+		public ReadOnlyCollection<IParameter> Parameters {
+			get { return parameters; }
+		}
+	}
+	
+	/// <summary>
+	/// Represents an unknown identifier.
+	/// </summary>
+	public class UnknownIdentifierResolveResult : ResolveResult
+	{
+		readonly string identifier;
+		readonly int typeArgumentCount;
+		
+		public UnknownIdentifierResolveResult(string identifier, int typeArgumentCount = 0)
+			: base(SpecialType.UnknownType)
+		{
+			this.identifier = identifier;
+			this.typeArgumentCount = typeArgumentCount;
+		}
+		
+		public string Identifier {
+			get { return identifier; }
+		}
+		
+		public int TypeArgumentCount {
+			get { return typeArgumentCount; }
+		}
+		
+		public override bool IsError {
+			get { return true; }
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} {1}]", GetType().Name, identifier);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TextLocation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TextLocation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TextLocation.cs	(revision 11807)
@@ -0,0 +1,223 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using System.Globalization;
+
+namespace ICSharpCode.NRefactory
+{
+	/// <summary>
+	/// A line/column position.
+	/// Text editor lines/columns are counted started from one.
+	/// </summary>
+	/// <remarks>
+	/// The document provides the methods <see cref="Editor.IDocument.GetLocation"/> and
+	/// <see cref="Editor.IDocument.GetOffset(TextLocation)"/> to convert between offsets and TextLocations.
+	/// </remarks>
+	[Serializable]
+	[TypeConverter(typeof(TextLocationConverter))]
+	public struct TextLocation : IComparable<TextLocation>, IEquatable<TextLocation>
+	{
+		/// <summary>
+		/// Represents no text location (0, 0).
+		/// </summary>
+		public static readonly TextLocation Empty = new TextLocation(0, 0);
+		
+		/// <summary>
+		/// Constant of the minimum line.
+		/// </summary>
+		public const int MinLine   = 1;
+		
+		/// <summary>
+		/// Constant of the minimum column.
+		/// </summary>
+		public const int MinColumn = 1;
+		
+		/// <summary>
+		/// Creates a TextLocation instance.
+		/// </summary>
+		public TextLocation(int line, int column)
+		{
+			this.line = line;
+			this.column = column;
+		}
+		
+		int column, line;
+		
+		/// <summary>
+		/// Gets the line number.
+		/// </summary>
+		public int Line {
+			get { return line; }
+		}
+		
+		/// <summary>
+		/// Gets the column number.
+		/// </summary>
+		public int Column {
+			get { return column; }
+		}
+		
+		/// <summary>
+		/// Gets whether the TextLocation instance is empty.
+		/// </summary>
+		public bool IsEmpty {
+			get {
+				return column < MinLine && line < MinColumn;
+			}
+		}
+		
+		/// <summary>
+		/// Gets a string representation for debugging purposes.
+		/// </summary>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "(Line {1}, Col {0})", this.column, this.line);
+		}
+		
+		/// <summary>
+		/// Gets a hash code.
+		/// </summary>
+		public override int GetHashCode()
+		{
+			return unchecked (191 * column.GetHashCode() ^ line.GetHashCode());
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public override bool Equals(object obj)
+		{
+			if (!(obj is TextLocation)) return false;
+			return (TextLocation)obj == this;
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public bool Equals(TextLocation other)
+		{
+			return this == other;
+		}
+		
+		/// <summary>
+		/// Equality test.
+		/// </summary>
+		public static bool operator ==(TextLocation left, TextLocation right)
+		{
+			return left.column == right.column && left.line == right.line;
+		}
+		
+		/// <summary>
+		/// Inequality test.
+		/// </summary>
+		public static bool operator !=(TextLocation left, TextLocation right)
+		{
+			return left.column != right.column || left.line != right.line;
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator <(TextLocation left, TextLocation right)
+		{
+			if (left.line < right.line)
+				return true;
+			else if (left.line == right.line)
+				return left.column < right.column;
+			else
+				return false;
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator >(TextLocation left, TextLocation right)
+		{
+			if (left.line > right.line)
+				return true;
+			else if (left.line == right.line)
+				return left.column > right.column;
+			else
+				return false;
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator <=(TextLocation left, TextLocation right)
+		{
+			return !(left > right);
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public static bool operator >=(TextLocation left, TextLocation right)
+		{
+			return !(left < right);
+		}
+		
+		/// <summary>
+		/// Compares two text locations.
+		/// </summary>
+		public int CompareTo(TextLocation other)
+		{
+			if (this == other)
+				return 0;
+			if (this < other)
+				return -1;
+			else
+				return 1;
+		}
+	}
+	
+	public class TextLocationConverter : TypeConverter
+	{
+		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
+		{
+			return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
+		}
+		
+		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
+		{
+			return destinationType == typeof(TextLocation) || base.CanConvertTo(context, destinationType);
+		}
+		
+		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
+		{
+			if (value is string) {
+				string[] parts = ((string)value).Split(';', ',');
+				if (parts.Length == 2) {
+					return new TextLocation(int.Parse(parts[0]), int.Parse(parts[1]));
+				}
+			}
+			return base.ConvertFrom(context, culture, value);
+		}
+		
+		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
+		{
+			if (value is TextLocation) {
+				var loc = (TextLocation)value;
+				return loc.Line + ";" + loc.Column;
+			}
+			return base.ConvertTo(context, culture, value, destinationType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Accessibility.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Accessibility.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Accessibility.cs	(revision 11807)
@@ -0,0 +1,117 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Enum that describes the accessibility of an entity.
+	/// </summary>
+	public enum Accessibility : byte
+	{
+		// note: some code depends on the fact that these values are within the range 0-7
+		
+		/// <summary>
+		/// The entity is completely inaccessible. This is used for C# explicit interface implementations.
+		/// </summary>
+		None,
+		/// <summary>
+		/// The entity is only accessible within the same class.
+		/// </summary>
+		Private,
+		/// <summary>
+		/// The entity is accessible everywhere.
+		/// </summary>
+		Public,
+		/// <summary>
+		/// The entity is only accessible within the same class and in derived classes.
+		/// </summary>
+		Protected,
+		/// <summary>
+		/// The entity is accessible within the same project content.
+		/// </summary>
+		Internal,
+		/// <summary>
+		/// The entity is accessible both everywhere in the project content, and in all derived classes.
+		/// </summary>
+		/// <remarks>This corresponds to C# 'protected internal'.</remarks>
+		ProtectedOrInternal,
+		/// <summary>
+		/// The entity is accessible in derived classes within the same project content.
+		/// </summary>
+		/// <remarks>C# does not support this accessibility.</remarks>
+		ProtectedAndInternal,
+	}
+	
+	public interface IHasAccessibility
+	{
+		/// <summary>
+		/// Gets the accessibility of this entity.
+		/// </summary>
+		Accessibility Accessibility { get; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance is private.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance is private; otherwise, <c>false</c>.
+		/// </value>
+		bool IsPrivate { get; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance is public.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance is public; otherwise, <c>false</c>.
+		/// </value>
+		bool IsPublic { get; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance is protected.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance is protected; otherwise, <c>false</c>.
+		/// </value>
+		bool IsProtected { get; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance is internal.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance is internal; otherwise, <c>false</c>.
+		/// </value>
+		bool IsInternal { get; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance is protected or internal.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance is protected or internal; otherwise, <c>false</c>.
+		/// </value>
+		bool IsProtectedOrInternal { get; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance is protected and internal.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance is protected and internal; otherwise, <c>false</c>.
+		/// </value>
+		bool IsProtectedAndInternal { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AnonymousType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AnonymousType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AnonymousType.cs	(revision 11807)
@@ -0,0 +1,221 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Anonymous type.
+	/// </summary>
+	public class AnonymousType : AbstractType
+	{
+		ICompilation compilation;
+		IUnresolvedProperty[] unresolvedProperties;
+		IList<IProperty> resolvedProperties;
+		
+		public AnonymousType(ICompilation compilation, IList<IUnresolvedProperty> properties)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (properties == null)
+				throw new ArgumentNullException("properties");
+			this.compilation = compilation;
+			this.unresolvedProperties = properties.ToArray();
+			var context = new SimpleTypeResolveContext(compilation.MainAssembly);
+			this.resolvedProperties = new ProjectedList<ITypeResolveContext, IUnresolvedProperty, IProperty>(context, unresolvedProperties, (c, p) => new AnonymousTypeProperty(p, c, this));
+		}
+		
+		sealed class AnonymousTypeProperty : DefaultResolvedProperty
+		{
+			readonly AnonymousType declaringType;
+			
+			public AnonymousTypeProperty(IUnresolvedProperty unresolved, ITypeResolveContext parentContext, AnonymousType declaringType)
+				: base(unresolved, parentContext)
+			{
+				this.declaringType = declaringType;
+			}
+			
+			public override IType DeclaringType {
+				get { return declaringType; }
+			}
+			
+			public override bool Equals(object obj)
+			{
+				AnonymousTypeProperty p = obj as AnonymousTypeProperty;
+				return p != null && this.Name == p.Name && declaringType.Equals(p.declaringType);
+			}
+			
+			public override int GetHashCode()
+			{
+				return declaringType.GetHashCode() ^ unchecked(27 * this.Name.GetHashCode());
+			}
+			
+			protected override IMethod CreateResolvedAccessor(IUnresolvedMethod unresolvedAccessor)
+			{
+				return new AnonymousTypeAccessor(unresolvedAccessor, context, this);
+			}
+		}
+		
+		sealed class AnonymousTypeAccessor : DefaultResolvedMethod
+		{
+			readonly AnonymousTypeProperty owner;
+			
+			public AnonymousTypeAccessor(IUnresolvedMethod unresolved, ITypeResolveContext parentContext, AnonymousTypeProperty owner)
+				: base(unresolved, parentContext, isExtensionMethod: false)
+			{
+				this.owner = owner;
+			}
+			
+			public override IMember AccessorOwner {
+				get { return owner; }
+			}
+			
+			public override IType DeclaringType {
+				get { return owner.DeclaringType; }
+			}
+			
+			public override bool Equals(object obj)
+			{
+				AnonymousTypeAccessor p = obj as AnonymousTypeAccessor;
+				return p != null && this.Name == p.Name && owner.DeclaringType.Equals(p.owner.DeclaringType);
+			}
+			
+			public override int GetHashCode()
+			{
+				return owner.DeclaringType.GetHashCode() ^ unchecked(27 * this.Name.GetHashCode());
+			}
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return new AnonymousTypeReference(unresolvedProperties);
+		}
+		
+		public override string Name {
+			get { return "Anonymous Type"; }
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.Anonymous; }
+		}
+
+		public override IEnumerable<IType> DirectBaseTypes {
+			get {
+				yield return compilation.FindType(KnownTypeCode.Object);
+			}
+		}
+		
+		public override bool? IsReferenceType {
+			get { return true; }
+		}
+		
+		public IList<IProperty> Properties {
+			get { return resolvedProperties; }
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return compilation.FindType(KnownTypeCode.Object).GetMethods(filter, options);
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return compilation.FindType(KnownTypeCode.Object).GetMethods(typeArguments, filter, options);
+		}
+		
+		public override IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			for (int i = 0; i < unresolvedProperties.Length; i++) {
+				if (filter == null || filter(unresolvedProperties[i]))
+					yield return resolvedProperties[i];
+			}
+		}
+		
+		public override IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			for (int i = 0; i < unresolvedProperties.Length; i++) {
+				if (unresolvedProperties[i].CanGet) {
+					if (filter == null || filter(unresolvedProperties[i].Getter))
+						yield return resolvedProperties[i].Getter;
+				}
+				if (unresolvedProperties[i].CanSet) {
+					if (filter == null || filter(unresolvedProperties[i].Setter))
+						yield return resolvedProperties[i].Setter;
+				}
+			}
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				int hashCode = resolvedProperties.Count;
+				foreach (var p in resolvedProperties) {
+					hashCode *= 31;
+					hashCode += p.Name.GetHashCode() ^ p.ReturnType.GetHashCode();
+				}
+				return hashCode;
+			}
+		}
+		
+		public override bool Equals(IType other)
+		{
+			AnonymousType o = other as AnonymousType;
+			if (o == null || resolvedProperties.Count != o.resolvedProperties.Count)
+				return false;
+			for (int i = 0; i < resolvedProperties.Count; i++) {
+				IProperty p1 = resolvedProperties[i];
+				IProperty p2 = o.resolvedProperties[i];
+				if (p1.Name != p2.Name || !p1.ReturnType.Equals(p2.ReturnType))
+					return false;
+			}
+			return true;
+		}
+	}
+	
+	/// <summary>
+	/// Anonymous type reference.
+	/// </summary>
+	[Serializable]
+	public class AnonymousTypeReference : ITypeReference
+	{
+		readonly IUnresolvedProperty[] unresolvedProperties;
+		
+		public AnonymousTypeReference(IUnresolvedProperty[] properties)
+		{
+			if (properties == null)
+				throw new ArgumentNullException("properties");
+			this.unresolvedProperties = properties;
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			return new AnonymousType(context.Compilation, unresolvedProperties);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ArrayType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ArrayType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ArrayType.cs	(revision 11807)
@@ -0,0 +1,200 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an array type.
+	/// </summary>
+	public sealed class ArrayType : TypeWithElementType, ICompilationProvider
+	{
+		readonly int dimensions;
+		readonly ICompilation compilation;
+		
+		public ArrayType(ICompilation compilation, IType elementType, int dimensions = 1) : base(elementType)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (dimensions <= 0)
+				throw new ArgumentOutOfRangeException("dimensions", dimensions, "dimensions must be positive");
+			this.compilation = compilation;
+			this.dimensions = dimensions;
+			
+			ICompilationProvider p = elementType as ICompilationProvider;
+			if (p != null && p.Compilation != compilation)
+				throw new InvalidOperationException("Cannot create an array type using a different compilation from the element type.");
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.Array; }
+		}
+		
+		public ICompilation Compilation {
+			get { return compilation; }
+		}
+		
+		public int Dimensions {
+			get { return dimensions; }
+		}
+		
+		public override string NameSuffix {
+			get {
+				return "[" + new string(',', dimensions-1) + "]";
+			}
+		}
+		
+		public override bool? IsReferenceType {
+			get { return true; }
+		}
+		
+		public override int GetHashCode()
+		{
+			return unchecked(elementType.GetHashCode() * 71681 + dimensions);
+		}
+		
+		public override bool Equals(IType other)
+		{
+			ArrayType a = other as ArrayType;
+			return a != null && elementType.Equals(a.elementType) && a.dimensions == dimensions;
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return new ArrayTypeReference(elementType.ToTypeReference(), dimensions);
+		}
+		
+		public override IEnumerable<IType> DirectBaseTypes {
+			get {
+				List<IType> baseTypes = new List<IType>();
+				IType t = compilation.FindType(KnownTypeCode.Array);
+				if (t.Kind != TypeKind.Unknown)
+					baseTypes.Add(t);
+				if (dimensions == 1 && elementType.Kind != TypeKind.Pointer) {
+					// single-dimensional arrays implement IList<T>
+					ITypeDefinition def = compilation.FindType(KnownTypeCode.IListOfT) as ITypeDefinition;
+					if (def != null)
+						baseTypes.Add(new ParameterizedType(def, new[] { elementType }));
+					// And in .NET 4.5 they also implement IReadOnlyList<T>
+					def = compilation.FindType(KnownTypeCode.IReadOnlyListOfT) as ITypeDefinition;
+					if (def != null)
+						baseTypes.Add(new ParameterizedType(def, new[] { elementType }));
+				}
+				return baseTypes;
+			}
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return compilation.FindType(KnownTypeCode.Array).GetMethods(filter, options);
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return compilation.FindType(KnownTypeCode.Array).GetMethods(typeArguments, filter, options);
+		}
+		
+		public override IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return compilation.FindType(KnownTypeCode.Array).GetAccessors(filter, options);
+		}
+		
+		public override IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IProperty>.Instance;
+			else
+				return compilation.FindType(KnownTypeCode.Array).GetProperties(filter, options);
+		}
+		
+		// NestedTypes, Events, Fields: System.Array doesn't have any; so we can use the AbstractType default implementation
+		// that simply returns an empty list
+		
+		public override IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitArrayType(this);
+		}
+		
+		public override IType VisitChildren(TypeVisitor visitor)
+		{
+			IType e = elementType.AcceptVisitor(visitor);
+			if (e == elementType)
+				return this;
+			else
+				return new ArrayType(compilation, e, dimensions);
+		}
+	}
+	
+	[Serializable]
+	public sealed class ArrayTypeReference : ITypeReference, ISupportsInterning
+	{
+		readonly ITypeReference elementType;
+		readonly int dimensions;
+		
+		public ArrayTypeReference(ITypeReference elementType, int dimensions = 1)
+		{
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			if (dimensions <= 0)
+				throw new ArgumentOutOfRangeException("dimensions", dimensions, "dimensions must be positive");
+			this.elementType = elementType;
+			this.dimensions = dimensions;
+		}
+		
+		public ITypeReference ElementType {
+			get { return elementType; }
+		}
+		
+		public int Dimensions {
+			get { return dimensions; }
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			return new ArrayType(context.Compilation, elementType.Resolve(context), dimensions);
+		}
+		
+		public override string ToString()
+		{
+			return elementType.ToString() + "[" + new string(',', dimensions - 1) + "]";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return elementType.GetHashCode() ^ dimensions;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			ArrayTypeReference o = other as ArrayTypeReference;
+			return o != null && elementType == o.elementType && dimensions == o.dimensions;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AssemblyLoader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AssemblyLoader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AssemblyLoader.cs	(revision 11807)
@@ -0,0 +1,94 @@
+//
+// AssemblyLoader.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Reflection;
+using System.Threading;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public enum AssemblyLoaderBackend {
+		Auto,
+		Cecil,
+		IKVM
+	}
+
+	public abstract class AssemblyLoader
+	{
+		public static AssemblyLoader Create ()
+		{
+			return Create (AssemblyLoaderBackend.Auto);
+		}
+		
+		public static AssemblyLoader Create (AssemblyLoaderBackend backend)
+		{
+			switch (backend) {
+				case AssemblyLoaderBackend.Auto:
+				case AssemblyLoaderBackend.Cecil:
+					return (AssemblyLoader)Assembly.Load ("ICSharpCode.NRefactory.Cecil").CreateInstance ("ICSharpCode.NRefactory.TypeSystem.CecilLoader");
+				case AssemblyLoaderBackend.IKVM:
+					return (AssemblyLoader)Assembly.Load ("ICSharpCode.NRefactory.IKVM").CreateInstance ("ICSharpCode.NRefactory.TypeSystem.IkvmLoader");
+				default:
+					throw new ArgumentOutOfRangeException ();
+			}
+		}
+
+		/// <summary>
+		/// Specifies whether to include internal members. The default is false.
+		/// </summary>
+		public bool IncludeInternalMembers { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the cancellation token used by the assembly loader.
+		/// </summary>
+		public CancellationToken CancellationToken { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets the documentation provider that is used to retrieve the XML documentation for all members.
+		/// </summary>
+		public IDocumentationProvider DocumentationProvider { get; set; }
+
+		[CLSCompliant(false)]
+		protected InterningProvider interningProvider = new SimpleInterningProvider();
+
+		/// <summary>
+		/// Gets/Sets the interning provider.
+		/// </summary>
+		public InterningProvider InterningProvider {
+			get { return interningProvider; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				interningProvider = value;
+			}
+		}
+		
+		public abstract IUnresolvedAssembly LoadAssemblyFile(string fileName);
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AssemblyQualifiedTypeName.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AssemblyQualifiedTypeName.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/AssemblyQualifiedTypeName.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// Copyright (c) 2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public struct AssemblyQualifiedTypeName : IEquatable<AssemblyQualifiedTypeName>
+	{
+		public readonly string AssemblyName;
+		public readonly FullTypeName TypeName;
+		
+		public AssemblyQualifiedTypeName(FullTypeName typeName, string assemblyName)
+		{
+			this.AssemblyName = assemblyName;
+			this.TypeName = typeName;
+		}
+		
+		public AssemblyQualifiedTypeName(ITypeDefinition typeDefinition)
+		{
+			this.AssemblyName = typeDefinition.ParentAssembly.AssemblyName;
+			this.TypeName = typeDefinition.FullTypeName;
+		}
+		
+		public override string ToString()
+		{
+			if (string.IsNullOrEmpty(AssemblyName))
+				return TypeName.ToString();
+			else
+				return TypeName.ToString() + ", " + AssemblyName;
+		}
+		
+		public override bool Equals(object obj)
+		{
+			return (obj is AssemblyQualifiedTypeName) && Equals((AssemblyQualifiedTypeName)obj);
+		}
+		
+		public bool Equals(AssemblyQualifiedTypeName other)
+		{
+			return this.AssemblyName == other.AssemblyName && this.TypeName == other.TypeName;
+		}
+		
+		public override int GetHashCode()
+		{
+			int hashCode = 0;
+			unchecked {
+				if (AssemblyName != null)
+					hashCode += 1000000007 * AssemblyName.GetHashCode();
+				hashCode += TypeName.GetHashCode();
+			}
+			return hashCode;
+		}
+		
+		public static bool operator ==(AssemblyQualifiedTypeName lhs, AssemblyQualifiedTypeName rhs)
+		{
+			return lhs.Equals(rhs);
+		}
+		
+		public static bool operator !=(AssemblyQualifiedTypeName lhs, AssemblyQualifiedTypeName rhs)
+		{
+			return !lhs.Equals(rhs);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ByReferenceType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ByReferenceType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ByReferenceType.cs	(revision 11807)
@@ -0,0 +1,112 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public sealed class ByReferenceType : TypeWithElementType
+	{
+		public ByReferenceType(IType elementType) : base(elementType)
+		{
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.ByReference; }
+		}
+		
+		public override string NameSuffix {
+			get {
+				return "&";
+			}
+		}
+		
+		public override bool? IsReferenceType {
+			get { return null; }
+		}
+		
+		public override int GetHashCode()
+		{
+			return elementType.GetHashCode() ^ 91725813;
+		}
+		
+		public override bool Equals(IType other)
+		{
+			ByReferenceType a = other as ByReferenceType;
+			return a != null && elementType.Equals(a.elementType);
+		}
+		
+		public override IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitByReferenceType(this);
+		}
+		
+		public override IType VisitChildren(TypeVisitor visitor)
+		{
+			IType e = elementType.AcceptVisitor(visitor);
+			if (e == elementType)
+				return this;
+			else
+				return new ByReferenceType(e);
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return new ByReferenceTypeReference(elementType.ToTypeReference());
+		}
+	}
+	
+	[Serializable]
+	public sealed class ByReferenceTypeReference : ITypeReference, ISupportsInterning
+	{
+		readonly ITypeReference elementType;
+		
+		public ByReferenceTypeReference(ITypeReference elementType)
+		{
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			this.elementType = elementType;
+		}
+		
+		public ITypeReference ElementType {
+			get { return elementType; }
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			return new ByReferenceType(elementType.Resolve(context));
+		}
+		
+		public override string ToString()
+		{
+			return elementType.ToString() + "&";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return elementType.GetHashCode() ^ 91725814;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			ByReferenceTypeReference brt = other as ByReferenceTypeReference;
+			return brt != null && this.elementType == brt.elementType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ComHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ComHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ComHelper.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Helper methods for COM.
+	/// </summary>
+	public static class ComHelper
+	{
+		static bool IsComAttribute(IAttribute attribute, string name)
+		{
+			return attribute.AttributeType.Name == name && attribute.AttributeType.Namespace == "System.Runtime.InteropServices";
+		}
+		
+		/// <summary>
+		/// Gets whether the specified type is imported from COM.
+		/// </summary>
+		public static bool IsComImport(ITypeDefinition typeDefinition)
+		{
+			return typeDefinition != null
+				&& typeDefinition.Kind == TypeKind.Interface
+				&& typeDefinition.Attributes.Any(a => IsComAttribute(a, "ComImportAttribute"));
+		}
+		
+		/// <summary>
+		/// Gets the CoClass of the specified COM interface.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Co",
+		                                                 Justification = "Consistent with CoClassAttribute")]
+		public static IType GetCoClass(ITypeDefinition typeDefinition)
+		{
+			if (typeDefinition == null)
+				return SpecialType.UnknownType;
+			var coClassAttribute = typeDefinition.Attributes.FirstOrDefault(a => IsComAttribute(a, "CoClassAttribute"));
+			if (coClassAttribute != null && coClassAttribute.PositionalArguments.Count == 1) {
+				var rr = coClassAttribute.PositionalArguments[0] as TypeOfResolveResult;
+				if (rr != null)
+					return rr.ReferencedType;
+			}
+			return SpecialType.UnknownType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/DefaultSolutionSnapshot.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/DefaultSolutionSnapshot.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/DefaultSolutionSnapshot.cs	(revision 11807)
@@ -0,0 +1,86 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Default implementation of ISolutionSnapshot.
+	/// </summary>
+	public class DefaultSolutionSnapshot : ISolutionSnapshot
+	{
+		readonly Dictionary<string, IProjectContent> projectDictionary = new Dictionary<string, IProjectContent>(Platform.FileNameComparer);
+		ConcurrentDictionary<IProjectContent, ICompilation> dictionary = new ConcurrentDictionary<IProjectContent, ICompilation>();
+		
+		/// <summary>
+		/// Creates a new DefaultSolutionSnapshot with the specified projects.
+		/// </summary>
+		public DefaultSolutionSnapshot(IEnumerable<IProjectContent> projects)
+		{
+			foreach (var project in projects) {
+				if (project.ProjectFileName != null)
+					projectDictionary.Add(project.ProjectFileName, project);
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new DefaultSolutionSnapshot that does not support <see cref="ProjectReference"/>s.
+		/// </summary>
+		public DefaultSolutionSnapshot()
+		{
+		}
+		
+		public IProjectContent GetProjectContent(string projectFileName)
+		{
+			IProjectContent pc;
+			lock (projectDictionary) {
+				if (projectDictionary.TryGetValue(projectFileName, out pc))
+					return pc;
+				else
+					return null;
+			}
+		}
+		
+		public ICompilation GetCompilation(IProjectContent project)
+		{
+			if (project == null)
+				throw new ArgumentNullException("project");
+			return dictionary.GetOrAdd(project, p => p.CreateCompilation(this));
+		}
+		
+		public void AddCompilation(IProjectContent project, ICompilation compilation)
+		{
+			if (project == null)
+				throw new ArgumentNullException("project");
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (!dictionary.TryAdd(project, compilation))
+				throw new InvalidOperationException();
+			if (project.ProjectFileName != null) {
+				lock (projectDictionary) {
+					projectDictionary.Add(project.ProjectFileName, project);
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/DomRegion.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/DomRegion.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/DomRegion.cs	(revision 11807)
@@ -0,0 +1,230 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	[Serializable]
+	public struct DomRegion : IEquatable<DomRegion>
+	{
+		readonly string fileName;
+		readonly int beginLine;
+		readonly int endLine;
+		readonly int beginColumn;
+		readonly int endColumn;
+		
+		public readonly static DomRegion Empty = new DomRegion();
+		
+		public bool IsEmpty {
+			get {
+				return BeginLine <= 0;
+			}
+		}
+		
+		public string FileName {
+			get { return fileName; }
+		}
+		
+		public int BeginLine {
+			get {
+				return beginLine;
+			}
+		}
+		
+		/// <value>
+		/// if the end line is == -1 the end column is -1 too
+		/// this stands for an unknwon end
+		/// </value>
+		public int EndLine {
+			get {
+				return endLine;
+			}
+		}
+		
+		public int BeginColumn {
+			get {
+				return beginColumn;
+			}
+		}
+		
+		/// <value>
+		/// if the end column is == -1 the end line is -1 too
+		/// this stands for an unknown end
+		/// </value>
+		public int EndColumn {
+			get {
+				return endColumn;
+			}
+		}
+		
+		public TextLocation Begin {
+			get {
+				return new TextLocation (beginLine, beginColumn);
+			}
+		}
+		
+		public TextLocation End {
+			get {
+				return new TextLocation (endLine, endColumn);
+			}
+		}
+		
+		public DomRegion (int beginLine, int beginColumn, int endLine, int endColumn) : this (null, beginLine, beginColumn, endLine, endColumn)
+		{
+		}
+
+		public DomRegion(string fileName, int beginLine, int beginColumn, int endLine, int endColumn)
+		{
+			this.fileName = fileName;
+			this.beginLine   = beginLine;
+			this.beginColumn = beginColumn;
+			this.endLine     = endLine;
+			this.endColumn   = endColumn;
+		}
+		
+		public DomRegion (int beginLine, int beginColumn) : this (null, beginLine, beginColumn)
+		{
+		}
+		
+		public DomRegion (string fileName, int beginLine, int beginColumn)
+		{
+			this.fileName = fileName;
+			this.beginLine = beginLine;
+			this.beginColumn = beginColumn;
+			this.endLine = -1;
+			this.endColumn = -1;
+		}
+		
+		public DomRegion (TextLocation begin, TextLocation end) : this (null, begin, end)
+		{
+		}
+		
+		public DomRegion (string fileName, TextLocation begin, TextLocation end)
+		{
+			this.fileName = fileName;
+			this.beginLine = begin.Line;
+			this.beginColumn = begin.Column;
+			this.endLine = end.Line;
+			this.endColumn = end.Column;
+		}
+		
+		public DomRegion (TextLocation begin) : this (null, begin)
+		{
+		}
+		
+		public DomRegion (string fileName, TextLocation begin)
+		{
+			this.fileName = fileName;
+			this.beginLine = begin.Line;
+			this.beginColumn = begin.Column;
+			this.endLine = -1;
+			this.endColumn = -1;
+		}
+		
+		/// <remarks>
+		/// Returns true, if the given coordinates (line, column) are in the region.
+		/// This method assumes that for an unknown end the end line is == -1
+		/// </remarks>
+		public bool IsInside(int line, int column)
+		{
+			if (IsEmpty)
+				return false;
+			return line >= BeginLine &&
+				(line <= EndLine   || EndLine == -1) &&
+				(line != BeginLine || column >= BeginColumn) &&
+				(line != EndLine   || column <= EndColumn);
+		}
+
+		public bool IsInside(TextLocation location)
+		{
+			return IsInside(location.Line, location.Column);
+		}
+
+		/// <remarks>
+		/// Returns true, if the given coordinates (line, column) are in the region.
+		/// This method assumes that for an unknown end the end line is == -1
+		/// </remarks>
+		public bool Contains(int line, int column)
+		{
+			if (IsEmpty)
+				return false;
+			return line >= BeginLine &&
+				(line <= EndLine   || EndLine == -1) &&
+				(line != BeginLine || column >= BeginColumn) &&
+				(line != EndLine   || column < EndColumn);
+		}
+
+		public bool Contains(TextLocation location)
+		{
+			return Contains(location.Line, location.Column);
+		}
+
+		public bool IntersectsWith (DomRegion region)
+		{
+			return region.Begin <= End && region.End >= Begin;
+		}
+
+		public bool OverlapsWith (DomRegion region)
+		{
+			var maxBegin = Begin > region.Begin ? Begin : region.Begin;
+			var minEnd = End < region.End ? End : region.End;
+			return maxBegin < minEnd;
+		}
+
+		public override string ToString()
+		{
+			return string.Format(
+				CultureInfo.InvariantCulture,
+				"[DomRegion FileName={0}, Begin=({1}, {2}), End=({3}, {4})]",
+				fileName, beginLine, beginColumn, endLine, endColumn);
+		}
+		
+		public override bool Equals(object obj)
+		{
+			return obj is DomRegion && Equals((DomRegion)obj);
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				int hashCode = fileName != null ? fileName.GetHashCode() : 0;
+				hashCode ^= beginColumn + 1100009 * beginLine + 1200007 * endLine + 1300021 * endColumn;
+				return hashCode;
+			}
+		}
+		
+		public bool Equals(DomRegion other)
+		{
+			return beginLine == other.beginLine && beginColumn == other.beginColumn
+				&& endLine == other.endLine && endColumn == other.endColumn
+				&& fileName == other.fileName;
+		}
+		
+		public static bool operator ==(DomRegion left, DomRegion right)
+		{
+			return left.Equals(right);
+		}
+		
+		public static bool operator !=(DomRegion left, DomRegion right)
+		{
+			return !left.Equals(right);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/EntityType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/EntityType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/EntityType.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	[Obsolete("Use SymbolKind instead")]
+	public enum EntityType : byte
+	{
+		None = SymbolKind.None,
+		/// <seealso cref="ITypeDefinition"/>
+		TypeDefinition = SymbolKind.TypeDefinition,
+		/// <seealso cref="IField"/>
+		Field = SymbolKind.Field,
+		/// <summary>
+		/// The symbol is a property, but not an indexer.
+		/// </summary>
+		/// <seealso cref="IProperty"/>
+		Property = SymbolKind.Property,
+		/// <summary>
+		/// The symbol is an indexer, not a regular property.
+		/// </summary>
+		/// <seealso cref="IProperty"/>
+		Indexer = SymbolKind.Indexer,
+		/// <seealso cref="IEvent"/>
+		Event = SymbolKind.Event,
+		/// <summary>
+		/// The symbol is a method which is not an operator/constructor/destructor or accessor.
+		/// </summary>
+		/// <seealso cref="IMethod"/>
+		Method = SymbolKind.Method,
+		/// <summary>
+		/// The symbol is a user-defined operator.
+		/// </summary>
+		/// <seealso cref="IMethod"/>
+		Operator = SymbolKind.Operator,
+		/// <seealso cref="IMethod"/>
+		Constructor = SymbolKind.Constructor,
+		/// <seealso cref="IMethod"/>
+		Destructor = SymbolKind.Destructor,
+		/// <summary>
+		/// The accessor method for a property getter/setter or event add/remove.
+		/// </summary>
+		/// <seealso cref="IMethod"/>
+		Accessor = SymbolKind.Accessor,
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Error.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Error.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Error.cs	(revision 11807)
@@ -0,0 +1,139 @@
+﻿// 
+// Error.cs
+//  
+// Author:
+//       Mike Krüger <mike@icsharpcode.net>
+// 
+// Copyright (c) 2011 Mike Krüger <mike@icsharpcode.net>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Enum that describes the type of an error.
+	/// </summary>
+	public enum ErrorType
+	{
+		Unknown,
+		Error,
+		Warning
+	}
+	
+	/// <summary>
+	/// Descibes an error during parsing.
+	/// </summary>
+	[Serializable]
+	public class Error
+	{
+		readonly ErrorType errorType;
+		readonly string message;
+		readonly DomRegion region;
+		
+		/// <summary>
+		/// The type of the error.
+		/// </summary>
+		public ErrorType ErrorType { get { return errorType; } }
+		
+		/// <summary>
+		/// The error description.
+		/// </summary>
+		public string Message { get { return message; } }
+		
+		/// <summary>
+		/// The region of the error.
+		/// </summary>
+		public DomRegion Region { get { return region; } }
+		
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.Error"/> class.
+		/// </summary>
+		/// <param name='errorType'>
+		/// The error type.
+		/// </param>
+		/// <param name='message'>
+		/// The description of the error.
+		/// </param>
+		/// <param name='region'>
+		/// The region of the error.
+		/// </param>
+		public Error (ErrorType errorType, string message, DomRegion region)
+		{
+			this.errorType = errorType;
+			this.message = message;
+			this.region = region;
+		}
+		
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.Error"/> class.
+		/// </summary>
+		/// <param name='errorType'>
+		/// The error type.
+		/// </param>
+		/// <param name='message'>
+		/// The description of the error.
+		/// </param>
+		/// <param name='location'>
+		/// The location of the error.
+		/// </param>
+		public Error (ErrorType errorType, string message, TextLocation location)
+		{
+			this.errorType = errorType;
+			this.message = message;
+			this.region = new DomRegion (location, location);
+		}
+		
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.Error"/> class.
+		/// </summary>
+		/// <param name='errorType'>
+		/// The error type.
+		/// </param>
+		/// <param name='message'>
+		/// The description of the error.
+		/// </param>
+		/// <param name='line'>
+		/// The line of the error.
+		/// </param>
+		/// <param name='col'>
+		/// The column of the error.
+		/// </param>
+		public Error (ErrorType errorType, string message, int line, int col) : this (errorType, message, new TextLocation (line, col))
+		{
+		}
+		
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.Error"/> class.
+		/// </summary>
+		/// <param name='errorType'>
+		/// The error type.
+		/// </param>
+		/// <param name='message'>
+		/// The description of the error.
+		/// </param>
+		public Error (ErrorType errorType, string message)
+		{
+			this.errorType = errorType;
+			this.message = message;
+			this.region = DomRegion.Empty;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/FullTypeName.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/FullTypeName.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/FullTypeName.cs	(revision 11807)
@@ -0,0 +1,315 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Holds the full name of a type definition.
+	/// A full type name uniquely identifies a type definition within a single assembly.
+	/// </summary>
+	/// <remarks>
+	/// A full type name can only represent type definitions, not arbitrary types.
+	/// It does not include any type arguments, and can not refer to array or pointer types.
+	/// 
+	/// A full type name represented as reflection name has the syntax:
+	/// <c>NamespaceName '.' TopLevelTypeName ['`'#] { '+' NestedTypeName ['`'#] }</c>
+	/// </remarks>
+	[Serializable]
+	public struct FullTypeName : IEquatable<FullTypeName>
+	{
+		[Serializable]
+		struct NestedTypeName
+		{
+			public readonly string Name;
+			public readonly int AdditionalTypeParameterCount;
+			
+			public NestedTypeName(string name, int additionalTypeParameterCount)
+			{
+				if (name == null)
+					throw new ArgumentNullException("name");
+				this.Name = name;
+				this.AdditionalTypeParameterCount = additionalTypeParameterCount;
+			}
+		}
+		
+		readonly TopLevelTypeName topLevelType;
+		readonly NestedTypeName[] nestedTypes;
+		
+		FullTypeName(TopLevelTypeName topLevelTypeName, NestedTypeName[] nestedTypes)
+		{
+			this.topLevelType = topLevelTypeName;
+			this.nestedTypes = nestedTypes;
+		}
+		
+		/// <summary>
+		/// Constructs a FullTypeName representing the given top-level type.
+		/// </summary>
+		/// <remarks>
+		/// FullTypeName has an implicit conversion operator from TopLevelTypeName,
+		/// so you can simply write:
+		/// <c>FullTypeName f = new TopLevelTypeName(...);</c>
+		/// </remarks>
+		public FullTypeName(TopLevelTypeName topLevelTypeName)
+		{
+			this.topLevelType = topLevelTypeName;
+			this.nestedTypes = null;
+		}
+		
+		/// <summary>
+		/// Constructs a FullTypeName by parsing the given reflection name.
+		/// Note that FullTypeName can only represent type definition names. If the reflection name
+		/// might refer to a parameterized type or array etc., use
+		/// <see cref="ReflectionHelper.ParseReflectionName(string)"/> instead.
+		/// </summary>
+		/// <remarks>
+		/// Expected syntax: <c>NamespaceName '.' TopLevelTypeName ['`'#] { '+' NestedTypeName ['`'#] }</c>
+		/// where # are type parameter counts
+		/// </remarks>
+		public FullTypeName(string reflectionName)
+		{
+			int pos = reflectionName.IndexOf('+');
+			if (pos < 0) {
+				// top-level type
+				this.topLevelType = new TopLevelTypeName(reflectionName);
+				this.nestedTypes = null;
+			} else {
+				// nested type
+				string[] parts = reflectionName.Split('+');
+				this.topLevelType = new TopLevelTypeName(parts[0]);
+				this.nestedTypes = new NestedTypeName[parts.Length - 1];
+				for (int i = 0; i < nestedTypes.Length; i++) {
+					int tpc;
+					string name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(parts[i + 1], out tpc);
+					nestedTypes[i] = new NestedTypeName(name, tpc);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the top-level type name.
+		/// </summary>
+		public TopLevelTypeName TopLevelTypeName {
+			get { return topLevelType; }
+		}
+		
+		/// <summary>
+		/// Gets whether this is a nested type.
+		/// </summary>
+		public bool IsNested {
+			get {
+				return nestedTypes != null;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the nesting level.
+		/// </summary>
+		public int NestingLevel {
+			get {
+				return nestedTypes != null ? nestedTypes.Length : 0;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the name of the type.
+		/// For nested types, this is the name of the innermost type.
+		/// </summary>
+		public string Name {
+			get {
+				if (nestedTypes != null)
+					return nestedTypes[nestedTypes.Length - 1].Name;
+				else
+					return topLevelType.Name;
+			}
+		}
+		
+		public string ReflectionName {
+			get {
+				if (nestedTypes == null)
+					return topLevelType.ReflectionName;
+				StringBuilder b = new StringBuilder(topLevelType.ReflectionName);
+				foreach (NestedTypeName nt in nestedTypes) {
+					b.Append('+');
+					b.Append(nt.Name);
+					if (nt.AdditionalTypeParameterCount > 0) {
+						b.Append('`');
+						b.Append(nt.AdditionalTypeParameterCount);
+					}
+				}
+				return b.ToString();
+			}
+		}
+		
+		/// <summary>
+		/// Gets the total type parameter count.
+		/// </summary>
+		public int TypeParameterCount {
+			get {
+				int tpc = topLevelType.TypeParameterCount;
+				if (nestedTypes != null) {
+					foreach (var nt in nestedTypes) {
+						tpc += nt.AdditionalTypeParameterCount;
+					}
+				}
+				return tpc;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the name of the nested type at the given level.
+		/// </summary>
+		public string GetNestedTypeName(int nestingLevel)
+		{
+			if (nestedTypes == null)
+				throw new InvalidOperationException();
+			return nestedTypes[nestingLevel].Name;
+		}
+		
+		/// <summary>
+		/// Gets the number of additional type parameters of the nested type at the given level.
+		/// </summary>
+		public int GetNestedTypeAdditionalTypeParameterCount(int nestingLevel)
+		{
+			if (nestedTypes == null)
+				throw new InvalidOperationException();
+			return nestedTypes[nestingLevel].AdditionalTypeParameterCount;
+		}
+		
+		/// <summary>
+		/// Gets the declaring type name.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">This is a top-level type name.</exception>
+		/// <example><c>new FullTypeName("NS.A+B+C").GetDeclaringType()</c> will return <c>new FullTypeName("NS.A+B")</c></example>
+		public FullTypeName GetDeclaringType()
+		{
+			if (nestedTypes == null)
+				throw new InvalidOperationException();
+			if (nestedTypes.Length == 1)
+				return topLevelType;
+			NestedTypeName[] outerNestedTypeNames = new NestedTypeName[nestedTypes.Length - 1];
+			Array.Copy(nestedTypes, 0, outerNestedTypeNames, 0, outerNestedTypeNames.Length);
+			return new FullTypeName(topLevelType, nestedTypes);
+		}
+		
+		/// <summary>
+		/// Creates a nested type name.
+		/// </summary>
+		/// <example><c>new FullTypeName("NS.A+B").NestedType("C", 1)</c> will return <c>new FullTypeName("NS.A+B+C`1")</c></example>
+		public FullTypeName NestedType(string name, int additionalTypeParameterCount)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+			var newNestedType = new NestedTypeName(name, additionalTypeParameterCount);
+			if (nestedTypes == null)
+				return new FullTypeName(topLevelType, new[] { newNestedType });
+			NestedTypeName[] newNestedTypeNames = new NestedTypeName[nestedTypes.Length + 1];
+			nestedTypes.CopyTo(newNestedTypeNames, 0);
+			newNestedTypeNames[newNestedTypeNames.Length - 1] = newNestedType;
+			return new FullTypeName(topLevelType, newNestedTypeNames);
+		}
+		
+		public static implicit operator FullTypeName(TopLevelTypeName topLevelTypeName)
+		{
+			return new FullTypeName(topLevelTypeName);
+		}
+		
+		public override string ToString()
+		{
+			return this.ReflectionName;
+		}
+		
+		#region Equals and GetHashCode implementation
+		public override bool Equals(object obj)
+		{
+			return obj is FullTypeName && Equals((FullTypeName)obj);
+		}
+		
+		public bool Equals(FullTypeName other)
+		{
+			return FullTypeNameComparer.Ordinal.Equals(this, other);
+		}
+		
+		public override int GetHashCode()
+		{
+			return FullTypeNameComparer.Ordinal.GetHashCode(this);
+		}
+		
+		public static bool operator ==(FullTypeName left, FullTypeName right)
+		{
+			return left.Equals(right);
+		}
+		
+		public static bool operator !=(FullTypeName left, FullTypeName right)
+		{
+			return !left.Equals(right);
+		}
+		#endregion
+	}
+	
+	[Serializable]
+	public sealed class FullTypeNameComparer : IEqualityComparer<FullTypeName>
+	{
+		public static readonly FullTypeNameComparer Ordinal = new FullTypeNameComparer(StringComparer.Ordinal);
+		public static readonly FullTypeNameComparer OrdinalIgnoreCase = new FullTypeNameComparer(StringComparer.OrdinalIgnoreCase);
+		
+		public readonly StringComparer NameComparer;
+		
+		public FullTypeNameComparer(StringComparer nameComparer)
+		{
+			this.NameComparer = nameComparer;
+		}
+		
+		public bool Equals(FullTypeName x, FullTypeName y)
+		{
+			if (x.NestingLevel != y.NestingLevel)
+				return false;
+			TopLevelTypeName topX = x.TopLevelTypeName;
+			TopLevelTypeName topY = y.TopLevelTypeName;
+			if (topX.TypeParameterCount == topY.TypeParameterCount
+			    && NameComparer.Equals(topX.Name, topY.Name)
+			    && NameComparer.Equals(topX.Namespace, topY.Namespace))
+			{
+				for (int i = 0; i < x.NestingLevel; i++) {
+					if (x.GetNestedTypeAdditionalTypeParameterCount(i) != y.GetNestedTypeAdditionalTypeParameterCount(i))
+						return false;
+					if (!NameComparer.Equals(x.GetNestedTypeName(i), y.GetNestedTypeName(i)))
+						return false;
+				}
+				return true;
+			}
+			return false;
+		}
+		
+		public int GetHashCode(FullTypeName obj)
+		{
+			TopLevelTypeName top = obj.TopLevelTypeName;
+			int hash = NameComparer.GetHashCode(top.Name) ^ NameComparer.GetHashCode(top.Namespace) ^ top.TypeParameterCount;
+			unchecked {
+				for (int i = 0; i < obj.NestingLevel; i++) {
+					hash *= 31;
+					hash += NameComparer.GetHashCode(obj.Name) ^ obj.TypeParameterCount;
+				}
+			}
+			return hash;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAmbience.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAmbience.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAmbience.cs	(revision 11807)
@@ -0,0 +1,107 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	[Flags]
+	public enum ConversionFlags
+	{
+		/// <summary>
+		/// Convert only the name.
+		/// </summary>
+		None = 0,
+		/// <summary>
+		/// Show the parameter list
+		/// </summary>
+		ShowParameterList      = 1,
+		/// <summary>
+		/// Show names for parameters
+		/// </summary>
+		ShowParameterNames     = 2,
+		/// <summary>
+		/// Show the accessibility (private, public, etc.)
+		/// </summary>
+		ShowAccessibility      = 4,
+		/// <summary>
+		/// Show the definition key word (class, struct, Sub, Function, etc.)
+		/// </summary>
+		ShowDefinitionKeyword  = 8,
+		/// <summary>
+		/// Show the declaring type for the member
+		/// </summary>
+		ShowDeclaringType = 0x10,
+		/// <summary>
+		/// Show modifiers (virtual, override, etc.)
+		/// </summary>
+		ShowModifiers          = 0x20,
+		/// <summary>
+		/// Show the return type
+		/// </summary>
+		ShowReturnType = 0x40,
+		/// <summary>
+		/// Use fully qualified names for types.
+		/// </summary>
+		UseFullyQualifiedTypeNames = 0x80,
+		/// <summary>
+		/// Show the list of type parameters on method and class declarations.
+		/// Type arguments for parameter/return types are always shown.
+		/// </summary>
+		ShowTypeParameterList = 0x100,
+		/// <summary>
+		/// For fields, events and methods: adds a semicolon at the end.
+		/// For properties: shows "{ get; }" or similar.
+		/// </summary>
+		ShowBody = 0x200,
+		
+		/// <summary>
+		/// Use fully qualified names for members.
+		/// </summary>
+		UseFullyQualifiedEntityNames = 0x400,
+		
+		StandardConversionFlags = ShowParameterNames |
+			ShowAccessibility |
+			ShowParameterList |
+			ShowReturnType |
+			ShowModifiers |
+			ShowTypeParameterList |
+			ShowDefinitionKeyword |
+			ShowBody,
+		
+		All = 0x7ff,
+	}
+	
+	/// <summary>
+	/// Ambiences are used to convert type system symbols to text (usually for displaying the symbol to the user; e.g. in editor tooltips).
+	/// </summary>
+	public interface IAmbience
+	{
+		ConversionFlags ConversionFlags { get; set; }
+		
+		[Obsolete("Use ConvertSymbol() instead")]
+		string ConvertEntity(IEntity entity);
+		string ConvertSymbol(ISymbol symbol);
+		string ConvertType(IType type);
+		[Obsolete("Use ConvertSymbol() instead")]
+		string ConvertVariable(IVariable variable);
+		string ConvertConstantValue(object constantValue);
+		
+		string WrapComment(string comment);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAssembly.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAssembly.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAssembly.cs	(revision 11807)
@@ -0,0 +1,128 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an unresolved assembly.
+	/// </summary>
+	public interface IUnresolvedAssembly : IAssemblyReference
+	{
+		/// <summary>
+		/// Gets the assembly name (short name).
+		/// </summary>
+		string AssemblyName { get; }
+		
+		/// <summary>
+		/// Gets the full assembly name (including public key token etc.)
+		/// </summary>
+		string FullAssemblyName { get; }
+		
+		/// <summary>
+		/// Gets the path to the assembly location. 
+		/// For projects it is the same as the output path.
+		/// </summary>
+		string Location { get; }
+
+		/// <summary>
+		/// Gets the list of all assembly attributes in the project.
+		/// </summary>
+		IEnumerable<IUnresolvedAttribute> AssemblyAttributes { get; }
+		
+		/// <summary>
+		/// Gets the list of all module attributes in the project.
+		/// </summary>
+		IEnumerable<IUnresolvedAttribute> ModuleAttributes { get; }
+		
+		/// <summary>
+		/// Gets all non-nested types in the assembly.
+		/// </summary>
+		IEnumerable<IUnresolvedTypeDefinition> TopLevelTypeDefinitions { get; }
+	}
+	
+	public interface IAssemblyReference
+	{
+		/// <summary>
+		/// Resolves this assembly.
+		/// </summary>
+		IAssembly Resolve(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Represents an assembly.
+	/// </summary>
+	public interface IAssembly : ICompilationProvider
+	{
+		/// <summary>
+		/// Gets the original unresolved assembly.
+		/// </summary>
+		IUnresolvedAssembly UnresolvedAssembly { get; }
+		
+		/// <summary>
+		/// Gets whether this assembly is the main assembly of the compilation.
+		/// </summary>
+		bool IsMainAssembly { get; }
+		
+		/// <summary>
+		/// Gets the assembly name (short name).
+		/// </summary>
+		string AssemblyName { get; }
+		
+		/// <summary>
+		/// Gets the full assembly name (including public key token etc.)
+		/// </summary>
+		string FullAssemblyName { get; }
+		
+		/// <summary>
+		/// Gets the list of all assembly attributes in the project.
+		/// </summary>
+		IList<IAttribute> AssemblyAttributes { get; }
+		
+		/// <summary>
+		/// Gets the list of all module attributes in the project.
+		/// </summary>
+		IList<IAttribute> ModuleAttributes { get; }
+		
+		/// <summary>
+		/// Gets whether the internals of this assembly are visible in the specified assembly.
+		/// </summary>
+		bool InternalsVisibleTo(IAssembly assembly);
+		
+		/// <summary>
+		/// Gets the root namespace for this assembly.
+		/// </summary>
+		/// <remarks>
+		/// This always is the namespace without a name - it's unrelated to the 'root namespace' project setting.
+		/// </remarks>
+		INamespace RootNamespace { get; }
+		
+		/// <summary>
+		/// Gets the type definition for a top-level type.
+		/// </summary>
+		/// <remarks>This method uses ordinal name comparison, not the compilation's name comparer.</remarks>
+		ITypeDefinition GetTypeDefinition(TopLevelTypeName topLevelTypeName);
+		
+		/// <summary>
+		/// Gets all non-nested types in the assembly.
+		/// </summary>
+		IEnumerable<ITypeDefinition> TopLevelTypeDefinitions { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IAttribute.cs	(revision 11807)
@@ -0,0 +1,75 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an unresolved attribute.
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
+	public interface IUnresolvedAttribute
+	{
+		/// <summary>
+		/// Gets the code region of this attribute.
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Resolves the attribute.
+		/// </summary>
+		IAttribute CreateResolvedAttribute(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Represents an attribute.
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
+	public interface IAttribute
+	{
+		/// <summary>
+		/// Gets the code region of this attribute.
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Gets the type of the attribute.
+		/// </summary>
+		IType AttributeType { get; }
+		
+		/// <summary>
+		/// Gets the constructor being used.
+		/// This property may return null if no matching constructor was found.
+		/// </summary>
+		IMethod Constructor { get; }
+		
+		/// <summary>
+		/// Gets the positional arguments.
+		/// </summary>
+		IList<ResolveResult> PositionalArguments { get; }
+		
+		/// <summary>
+		/// Gets the named arguments passed to the attribute.
+		/// </summary>
+		IList<KeyValuePair<IMember, ResolveResult>> NamedArguments { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ICodeContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ICodeContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ICodeContext.cs	(revision 11807)
@@ -0,0 +1,38 @@
+﻿// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface ICodeContext : ITypeResolveContext
+	{
+		/// <summary>
+		/// Gets all currently visible local variables and lambda parameters.
+		/// Does not include method parameters.
+		/// </summary>
+		IEnumerable<IVariable> LocalVariables { get; }
+		
+		/// <summary>
+		/// Gets whether the context is within a lambda expression or anonymous method.
+		/// </summary>
+		bool IsWithinLambdaExpression { get; }
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ICompilation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ICompilation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ICompilation.cs	(revision 11807)
@@ -0,0 +1,91 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface ICompilation
+	{
+		/// <summary>
+		/// Gets the current assembly.
+		/// </summary>
+		IAssembly MainAssembly { get; }
+		
+		/// <summary>
+		/// Gets the type resolve context that specifies this compilation and no current assembly or entity.
+		/// </summary>
+		ITypeResolveContext TypeResolveContext { get; }
+		
+		/// <summary>
+		/// Gets the list of all assemblies in the compilation.
+		/// </summary>
+		/// <remarks>
+		/// This main assembly is the first entry in the list.
+		/// </remarks>
+		IList<IAssembly> Assemblies { get; }
+		
+		/// <summary>
+		/// Gets the referenced assemblies.
+		/// This list does not include the main assembly.
+		/// </summary>
+		IList<IAssembly> ReferencedAssemblies { get; }
+		
+		/// <summary>
+		/// Gets the root namespace of this compilation.
+		/// This is a merged version of the root namespaces of all assemblies.
+		/// </summary>
+		/// <remarks>
+		/// This always is the namespace without a name - it's unrelated to the 'root namespace' project setting.
+		/// </remarks>
+		INamespace RootNamespace { get; }
+		
+		/// <summary>
+		/// Gets the root namespace for a given extern alias.
+		/// </summary>
+		/// <remarks>
+		/// If <paramref name="alias"/> is <c>null</c> or an empty string, this method
+		/// returns the global root namespace.
+		/// If no alias with the specified name exists, this method returns null.
+		/// </remarks>
+		INamespace GetNamespaceForExternAlias(string alias);
+		
+		IType FindType(KnownTypeCode typeCode);
+		
+		/// <summary>
+		/// Gets the name comparer for the language being compiled.
+		/// This is the string comparer used for the INamespace.GetTypeDefinition method.
+		/// </summary>
+		StringComparer NameComparer { get; }
+		
+		ISolutionSnapshot SolutionSnapshot { get; }
+		
+		CacheManager CacheManager { get; }
+	}
+	
+	public interface ICompilationProvider
+	{
+		/// <summary>
+		/// Gets the parent compilation.
+		/// This property never returns null.
+		/// </summary>
+		ICompilation Compilation { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IConstantValue.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IConstantValue.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IConstantValue.cs	(revision 11807)
@@ -0,0 +1,38 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics.Contracts;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an unresolved constant value.
+	/// </summary>
+	public interface IConstantValue
+	{
+		/// <summary>
+		/// Resolves the value of this constant.
+		/// </summary>
+		/// <param name="context">Context where the constant value will be used.</param>
+		/// <returns>Resolve result representing the constant value.
+		/// This method never returns null; in case of errors, an ErrorResolveResult will be returned.</returns>
+		ResolveResult Resolve(ITypeResolveContext context);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IEntity.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IEntity.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IEntity.cs	(revision 11807)
@@ -0,0 +1,178 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using ICSharpCode.NRefactory.Documentation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an unresolved entity.
+	/// </summary>
+	public interface IUnresolvedEntity : INamedElement, IHasAccessibility
+	{
+		/// <summary>
+		/// Gets the entity type.
+		/// </summary>
+		SymbolKind SymbolKind { get; }
+		
+		/// <summary>
+		/// Gets the complete entity region (including header+body)
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Gets the entity body region.
+		/// </summary>
+		DomRegion BodyRegion { get; }
+		
+		/// <summary>
+		/// Gets the declaring class.
+		/// For members, this is the class that contains the member.
+		/// For nested classes, this is the outer class. For top-level entities, this property returns null.
+		/// </summary>
+		IUnresolvedTypeDefinition DeclaringTypeDefinition { get; }
+		
+		/// <summary>
+		/// Gets the parsed file in which this entity is defined.
+		/// Returns null if this entity wasn't parsed from source code (e.g. loaded from a .dll with CecilLoader).
+		/// </summary>
+		IUnresolvedFile UnresolvedFile { get; }
+		
+		/// <summary>
+		/// Gets the attributes on this entity.
+		/// </summary>
+		IList<IUnresolvedAttribute> Attributes { get; }
+		
+		/// <summary>
+		/// Gets whether this entity is static.
+		/// Returns true if either the 'static' or the 'const' modifier is set.
+		/// </summary>
+		bool IsStatic { get; }
+		
+		/// <summary>
+		/// Returns whether this entity is abstract.
+		/// </summary>
+		/// <remarks>Static classes also count as abstract classes.</remarks>
+		bool IsAbstract { get; }
+		
+		/// <summary>
+		/// Returns whether this entity is sealed.
+		/// </summary>
+		/// <remarks>Static classes also count as sealed classes.</remarks>
+		bool IsSealed { get; }
+		
+		/// <summary>
+		/// Gets whether this member is declared to be shadowing another member with the same name.
+		/// </summary>
+		bool IsShadowing { get; }
+		
+		/// <summary>
+		/// Gets whether this member is generated by a macro/compiler feature.
+		/// </summary>
+		bool IsSynthetic { get; }
+	}
+	
+	/// <summary>
+	/// Represents a resolved entity.
+	/// </summary>
+	public interface IEntity : ISymbol, ICompilationProvider, INamedElement, IHasAccessibility
+	{
+		/// <summary>
+		/// Gets the entity type.
+		/// </summary>
+		[Obsolete("Use the SymbolKind property instead.")]
+		EntityType EntityType { get; }
+		
+		/// <summary>
+		/// Gets the short name of the entity.
+		/// </summary>
+		new string Name { get; }
+		
+		/// <summary>
+		/// Gets the complete entity region (including header+body)
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Gets the entity body region.
+		/// </summary>
+		DomRegion BodyRegion { get; }
+		
+		/// <summary>
+		/// Gets the declaring class.
+		/// For members, this is the class that contains the member.
+		/// For nested classes, this is the outer class. For top-level entities, this property returns null.
+		/// </summary>
+		ITypeDefinition DeclaringTypeDefinition { get; }
+		
+		/// <summary>
+		/// Gets/Sets the declaring type (incl. type arguments, if any).
+		/// This property never returns null -- for top-level entities, it returns SharedTypes.UnknownType.
+		/// If this is not a specialized member, the value returned is equal to <see cref="DeclaringTypeDefinition"/>.
+		/// </summary>
+		IType DeclaringType { get; }
+		
+		/// <summary>
+		/// The assembly in which this entity is defined.
+		/// This property never returns null.
+		/// </summary>
+		IAssembly ParentAssembly { get; }
+		
+		/// <summary>
+		/// Gets the attributes on this entity.
+		/// </summary>
+		IList<IAttribute> Attributes { get; }
+		
+		/// <summary>
+		/// Gets the documentation for this entity.
+		/// </summary>
+		DocumentationComment Documentation { get; }
+		
+		/// <summary>
+		/// Gets whether this entity is static.
+		/// Returns true if either the 'static' or the 'const' modifier is set.
+		/// </summary>
+		bool IsStatic { get; }
+		
+		/// <summary>
+		/// Returns whether this entity is abstract.
+		/// </summary>
+		/// <remarks>Static classes also count as abstract classes.</remarks>
+		bool IsAbstract { get; }
+		
+		/// <summary>
+		/// Returns whether this entity is sealed.
+		/// </summary>
+		/// <remarks>Static classes also count as sealed classes.</remarks>
+		bool IsSealed { get; }
+		
+		/// <summary>
+		/// Gets whether this member is declared to be shadowing another member with the same name.
+		/// (C# 'new' keyword)
+		/// </summary>
+		bool IsShadowing { get; }
+		
+		/// <summary>
+		/// Gets whether this member is generated by a macro/compiler feature.
+		/// </summary>
+		bool IsSynthetic { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IEvent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IEvent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IEvent.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics.Contracts;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface IUnresolvedEvent : IUnresolvedMember
+	{
+		bool CanAdd { get; }
+		bool CanRemove { get; }
+		bool CanInvoke { get; }
+		
+		IUnresolvedMethod AddAccessor { get; }
+		IUnresolvedMethod RemoveAccessor { get; }
+		IUnresolvedMethod InvokeAccessor { get; }
+		
+		/// <summary>
+		/// Resolves the member.
+		/// </summary>
+		/// <param name="context">
+		/// Context for looking up the member. The context must specify the current assembly.
+		/// A <see cref="SimpleTypeResolveContext"/> that specifies the current assembly is sufficient.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved member, or <c>null</c> if the member could not be found.
+		/// </returns>
+		new IEvent Resolve(ITypeResolveContext context);
+	}
+	
+	public interface IEvent : IMember
+	{
+		bool CanAdd { get; }
+		bool CanRemove { get; }
+		bool CanInvoke { get; }
+		
+		IMethod AddAccessor { get; }
+		IMethod RemoveAccessor { get; }
+		IMethod InvokeAccessor { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IField.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IField.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IField.cs	(revision 11807)
@@ -0,0 +1,99 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a field or constant.
+	/// </summary>
+	public interface IUnresolvedField : IUnresolvedMember
+	{
+		/// <summary>
+		/// Gets whether this field is readonly.
+		/// </summary>
+		bool IsReadOnly { get; }
+		
+		/// <summary>
+		/// Gets whether this field is volatile.
+		/// </summary>
+		bool IsVolatile { get; }
+		
+		/// <summary>
+		/// Gets whether this field is a constant (C#-like const).
+		/// </summary>
+		bool IsConst { get; }
+
+		/// <summary>
+		/// Gets whether this field is a fixed size buffer (C#-like fixed).
+		/// If this is true, then ConstantValue contains the size of the buffer.
+		/// </summary>
+		bool IsFixed { get; }
+
+
+		IConstantValue ConstantValue { get; }
+		
+		/// <summary>
+		/// Resolves the member.
+		/// </summary>
+		/// <param name="context">
+		/// Context for looking up the member. The context must specify the current assembly.
+		/// A <see cref="SimpleTypeResolveContext"/> that specifies the current assembly is sufficient.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved member, or <c>null</c> if the member could not be found.
+		/// </returns>
+		new IField Resolve(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Represents a field or constant.
+	/// </summary>
+	public interface IField : IMember, IVariable
+	{
+		/// <summary>
+		/// Gets the name of the field.
+		/// </summary>
+		new string Name { get; } // solve ambiguity between IMember.Name and IVariable.Name
+		
+		/// <summary>
+		/// Gets the region where the field is declared.
+		/// </summary>
+		new DomRegion Region { get; } // solve ambiguity between IEntity.Region and IVariable.Region
+		
+		/// <summary>
+		/// Gets whether this field is readonly.
+		/// </summary>
+		bool IsReadOnly { get; }
+		
+		/// <summary>
+		/// Gets whether this field is volatile.
+		/// </summary>
+		bool IsVolatile { get; }
+
+		/// <summary>
+		/// Gets whether this field is a fixed size buffer (C#-like fixed).
+		/// If this is true, then ConstantValue contains the size of the buffer.
+		/// </summary>
+		bool IsFixed { get; }
+		
+		new IMemberReference ToReference(); // solve ambiguity between IMember.ToReference() and IVariable.ToReference()
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IFreezable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IFreezable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IFreezable.cs	(revision 11807)
@@ -0,0 +1,35 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface IFreezable
+	{
+		/// <summary>
+		/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
+		/// </summary>
+		bool IsFrozen { get; }
+		
+		/// <summary>
+		/// Freezes this instance.
+		/// </summary>
+		void Freeze();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IInterningProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IInterningProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IInterningProvider.cs	(revision 11807)
@@ -0,0 +1,102 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Provider used for interning.
+	/// </summary>
+	/// <remarks>
+	/// A simple IInterningProvider implementation could use 3 dictionaries:
+	///  1. using value equality comparer (for certain types known to implement value equality, e.g. string and IType)
+	///  2. using comparer that calls into ISupportsInterning (for types implementing ISupportsInterning)
+	///  3. list comparer (for InternList method)
+	/// 
+	/// On the first Intern()-call, the provider tells the object to prepare for interning (ISupportsInterning.PrepareForInterning)
+	/// and stores it into a dictionary. On further Intern() calls, the original object is returned for all equal objects.
+	/// This allows reducing the memory usage by using a single object instance where possible.
+	/// 
+	/// Interning provider implementations could also use the interning logic for different purposes:
+	/// for example, it could be used to determine which objects are used jointly between multiple type definitions
+	/// and which are used only within a single type definition. Then a persistent file format could be organized so
+	/// that shared objects are loaded only once, yet non-shared objects get loaded lazily together with the class.
+	/// </remarks>
+	public abstract class InterningProvider
+	{
+		public static readonly InterningProvider Dummy = new DummyInterningProvider();
+		
+		/// <summary>
+		/// Interns the specified object.
+		/// 
+		/// If the object is freezable, it will be frozen.
+		/// </summary>
+		public abstract ISupportsInterning Intern(ISupportsInterning obj);
+		
+		/// <summary>
+		/// Interns the specified object.
+		/// 
+		/// If the object is freezable, it will be frozen.
+		/// </summary>
+		public T Intern<T>(T obj) where T : class, ISupportsInterning
+		{
+			ISupportsInterning input = obj;
+			return (T)Intern(input);
+		}
+		
+		/// <summary>
+		/// Interns the specified string.
+		/// </summary>
+		public abstract string Intern(string text);
+		
+		/// <summary>
+		/// Inters a boxed value type.
+		/// </summary>
+		public abstract object InternValue(object obj);
+		
+		/// <summary>
+		/// Interns the given list. Uses reference equality to compare the list elements.
+		/// </summary>
+		public abstract IList<T> InternList<T>(IList<T> list) where T : class;
+		
+		sealed class DummyInterningProvider : InterningProvider
+		{
+			public override ISupportsInterning Intern(ISupportsInterning obj)
+			{
+				return obj;
+			}
+			
+			public override string Intern(string text)
+			{
+				return text;
+			}
+			
+			public override object InternValue(object obj)
+			{
+				return obj;
+			}
+			
+			public override IList<T> InternList<T>(IList<T> list)
+			{
+				return list;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IMember.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IMember.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IMember.cs	(revision 11807)
@@ -0,0 +1,196 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Method/field/property/event.
+	/// </summary>
+	public interface IUnresolvedMember : IUnresolvedEntity, IMemberReference
+	{
+		/// <summary>
+		/// Gets the return type of this member.
+		/// This property never returns null.
+		/// </summary>
+		ITypeReference ReturnType { get; }
+		
+		/// <summary>
+		/// Gets whether this member is explicitly implementing an interface.
+		/// If this property is true, the member can only be called through the interfaces it implements.
+		/// </summary>
+		bool IsExplicitInterfaceImplementation { get; }
+		
+		/// <summary>
+		/// Gets the interfaces that are explicitly implemented by this member.
+		/// </summary>
+		IList<IMemberReference> ExplicitInterfaceImplementations { get; }
+		
+		/// <summary>
+		/// Gets if the member is virtual. Is true only if the "virtual" modifier was used, but non-virtual
+		/// members can be overridden, too; if they are abstract or overriding a method.
+		/// </summary>
+		bool IsVirtual { get; }
+		
+		/// <summary>
+		/// Gets whether this member is overriding another member.
+		/// </summary>
+		bool IsOverride { get; }
+		
+		/// <summary>
+		/// Gets if the member can be overridden. Returns true when the member is "abstract", "virtual" or "override" but not "sealed".
+		/// </summary>
+		bool IsOverridable { get; }
+		
+		/// <summary>
+		/// Resolves the member.
+		/// </summary>
+		/// <param name="context">
+		/// Context for looking up the member. The context must specify the current assembly.
+		/// A <see cref="SimpleTypeResolveContext"/> that specifies the current assembly is sufficient.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved member, or <c>null</c> if the member could not be found.
+		/// </returns>
+		new IMember Resolve(ITypeResolveContext context);
+		
+		/// <summary>
+		/// Creates the resolved member.
+		/// </summary>
+		/// <param name="context">
+		/// The language-specific context that includes the parent type definition.
+		/// <see cref="IUnresolvedTypeDefinition.CreateResolveContext"/>
+		/// </param>
+		IMember CreateResolved(ITypeResolveContext context);
+	}
+	
+	public interface IMemberReference : ISymbolReference
+	{
+		/// <summary>
+		/// Gets the declaring type reference for the member.
+		/// </summary>
+		ITypeReference DeclaringTypeReference { get; }
+		
+		/// <summary>
+		/// Resolves the member.
+		/// </summary>
+		/// <param name="context">
+		/// Context to use for resolving this member reference.
+		/// Which kind of context is required depends on the which kind of member reference this is;
+		/// please consult the documentation of the method that was used to create this member reference,
+		/// or that of the class implementing this method.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved member, or <c>null</c> if the member could not be found.
+		/// </returns>
+		new IMember Resolve(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Method/field/property/event.
+	/// </summary>
+	public interface IMember : IEntity
+	{
+		/// <summary>
+		/// Gets the original member definition for this member.
+		/// Returns <c>this</c> if this is not a specialized member.
+		/// Specialized members are the result of overload resolution with type substitution.
+		/// </summary>
+		IMember MemberDefinition { get; }
+		
+		/// <summary>
+		/// Gets the unresolved member instance from which this member was created.
+		/// This property may return <c>null</c> for special members that do not have a corresponding unresolved member instance.
+		/// </summary>
+		/// <remarks>
+		/// For specialized members, this property returns the unresolved member for the original member definition.
+		/// For partial methods, this property returns the implementing partial method declaration, if one exists, and the
+		/// defining partial method declaration otherwise.
+		/// For the members used to represent the built-in C# operators like "operator +(int, int);", this property returns <c>null</c>.
+		/// </remarks>
+		IUnresolvedMember UnresolvedMember { get; }
+		
+		/// <summary>
+		/// Gets the return type of this member.
+		/// This property never returns <c>null</c>.
+		/// </summary>
+		IType ReturnType { get; }
+		
+		/// <summary>
+		/// Gets the interface members implemented by this member (both implicitly and explicitly).
+		/// </summary>
+		IList<IMember> ImplementedInterfaceMembers { get; }
+		
+		/// <summary>
+		/// Gets whether this member is explicitly implementing an interface.
+		/// </summary>
+		bool IsExplicitInterfaceImplementation { get; }
+		
+		/// <summary>
+		/// Gets if the member is virtual. Is true only if the "virtual" modifier was used, but non-virtual
+		/// members can be overridden, too; if they are abstract or overriding a method.
+		/// </summary>
+		bool IsVirtual { get; }
+		
+		/// <summary>
+		/// Gets whether this member is overriding another member.
+		/// </summary>
+		bool IsOverride { get; }
+		
+		/// <summary>
+		/// Gets if the member can be overridden. Returns true when the member is "abstract", "virtual" or "override" but not "sealed".
+		/// </summary>
+		bool IsOverridable { get; }
+		
+		/// <summary>
+		/// Creates a member reference that can be used to rediscover this member in another compilation.
+		/// </summary>
+		/// <remarks>
+		/// If this member is specialized using open generic types, the resulting member reference will need to be looked up in an appropriate generic context.
+		/// Otherwise, the main resolve context of a compilation is sufficient.
+		/// </remarks>
+		[Obsolete("Use the ToReference method instead.")]
+		IMemberReference ToMemberReference();
+		
+				/// <summary>
+		/// Creates a member reference that can be used to rediscover this member in another compilation.
+		/// </summary>
+		/// <remarks>
+		/// If this member is specialized using open generic types, the resulting member reference will need to be looked up in an appropriate generic context.
+		/// Otherwise, the main resolve context of a compilation is sufficient.
+		/// </remarks>
+		new IMemberReference ToReference();
+
+		/// <summary>
+		/// Gets the substitution belonging to this specialized member.
+		/// Returns TypeParameterSubstitution.Identity for not specialized members.
+		/// </summary>
+		TypeParameterSubstitution Substitution {
+			get;
+		}
+
+		/// <summary>
+		/// Specializes this member with the given substitution.
+		/// If this member is already specialized, the new substitution is composed with the existing substition.
+		/// </summary>
+		IMember Specialize(TypeParameterSubstitution substitution);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IMethod.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IMethod.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IMethod.cs	(revision 11807)
@@ -0,0 +1,168 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface IUnresolvedMethod : IUnresolvedParameterizedMember
+	{
+		/// <summary>
+		/// Gets the attributes associated with the return type. (e.g. [return: MarshalAs(...)])
+		/// </summary>
+		IList<IUnresolvedAttribute> ReturnTypeAttributes { get; }
+		
+		IList<IUnresolvedTypeParameter> TypeParameters { get; }
+		
+		bool IsConstructor { get; }
+		bool IsDestructor { get; }
+		bool IsOperator { get; }
+		
+		/// <summary>
+		/// Gets whether the method is a C#-style partial method.
+		/// Check <see cref="HasBody"/> to test if it is a partial method declaration or implementation.
+		/// </summary>
+		bool IsPartial { get; }
+
+		/// <summary>
+		/// Gets whether the method is a C#-style async method.
+		/// </summary>
+		bool IsAsync { get; }
+
+		[Obsolete("Use IsPartial && !HasBody instead")]
+		bool IsPartialMethodDeclaration { get; }
+		
+		[Obsolete("Use IsPartial && HasBody instead")]
+		bool IsPartialMethodImplementation { get; }
+		
+		/// <summary>
+		/// Gets whether the method has a body.
+		/// This property returns <c>false</c> for <c>abstract</c> or <c>extern</c> methods,
+		/// or for <c>partial</c> methods without implementation.
+		/// </summary>
+		bool HasBody { get; }
+		
+		/// <summary>
+		/// If this method is an accessor, returns a reference to the corresponding property/event.
+		/// Otherwise, returns null.
+		/// </summary>
+		IUnresolvedMember AccessorOwner { get; }
+		
+		/// <summary>
+		/// Resolves the member.
+		/// </summary>
+		/// <param name="context">
+		/// Context for looking up the member. The context must specify the current assembly.
+		/// A <see cref="SimpleTypeResolveContext"/> that specifies the current assembly is sufficient.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved member, or <c>null</c> if the member could not be found.
+		/// </returns>
+		new IMethod Resolve(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Represents a method, constructor, destructor or operator.
+	/// </summary>
+	public interface IMethod : IParameterizedMember
+	{
+		/// <summary>
+		/// Gets the unresolved method parts.
+		/// For partial methods, this returns all parts.
+		/// Otherwise, this returns an array with a single element (new[] { UnresolvedMember }).
+		/// NOTE: The type will change to IReadOnlyList&lt;IUnresolvedMethod&gt; in future versions.
+		/// </summary>
+		IList<IUnresolvedMethod> Parts { get; }
+		
+		/// <summary>
+		/// Gets the attributes associated with the return type. (e.g. [return: MarshalAs(...)])
+		/// NOTE: The type will change to IReadOnlyList&lt;IAttribute&gt; in future versions.
+		/// </summary>
+		IList<IAttribute> ReturnTypeAttributes { get; }
+
+		/// <summary>
+		/// Gets the type parameters of this method; or an empty list if the method is not generic.
+		/// NOTE: The type will change to IReadOnlyList&lt;ITypeParameter&gt; in future versions.
+		/// </summary>
+		IList<ITypeParameter> TypeParameters { get; }
+
+		/// <summary>
+		/// Gets whether this is a generic method that has been parameterized.
+		/// </summary>
+		bool IsParameterized { get; }
+		
+		/// <summary>
+		/// Gets the type arguments passed to this method.
+		/// If the method is generic but not parameterized yet, this property returns the type parameters,
+		/// as if the method was parameterized with its own type arguments (<c>void M&lt;T&gt;() { M&lt;T&gt;(); }</c>).
+		/// 
+		/// NOTE: The type will change to IReadOnlyList&lt;IType&gt; in future versions.
+		/// </summary>
+		IList<IType> TypeArguments { get; }
+
+		bool IsExtensionMethod { get; }
+		bool IsConstructor { get; }
+		bool IsDestructor { get; }
+		bool IsOperator { get; }
+		
+		/// <summary>
+		/// Gets whether the method is a C#-style partial method.
+		/// A call to such a method is ignored by the compiler if the partial method has no body.
+		/// </summary>
+		/// <seealso cref="HasBody"/>
+		bool IsPartial { get; }
+
+		/// <summary>
+		/// Gets whether the method is a C#-style async method.
+		/// </summary>
+		bool IsAsync { get; }
+
+		/// <summary>
+		/// Gets whether the method has a body.
+		/// This property returns <c>false</c> for <c>abstract</c> or <c>extern</c> methods,
+		/// or for <c>partial</c> methods without implementation.
+		/// </summary>
+		bool HasBody { get; }
+		
+		/// <summary>
+		/// Gets whether the method is a property/event accessor.
+		/// </summary>
+		bool IsAccessor { get; }
+		
+		/// <summary>
+		/// If this method is an accessor, returns the corresponding property/event.
+		/// Otherwise, returns null.
+		/// </summary>
+		IMember AccessorOwner { get; }
+
+		/// <summary>
+		/// If this method is reduced from an extension method return the original method, <c>null</c> otherwise.
+		/// A reduced method doesn't contain the extension method parameter. That means that has one parameter less than it's definition.
+		/// </summary>
+		IMethod ReducedFrom { get; }
+		
+		/// <summary>
+		/// Specializes this method with the given substitution.
+		/// If this method is already specialized, the new substitution is composed with the existing substition.
+		/// </summary>
+		new IMethod Specialize(TypeParameterSubstitution substitution);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/INamedElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/INamedElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/INamedElement.cs	(revision 11807)
@@ -0,0 +1,66 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface INamedElement
+	{
+		/// <summary>
+		/// Gets the fully qualified name of the class the return type is pointing to.
+		/// </summary>
+		/// <returns>
+		/// "System.Int32[]" for int[]<br/>
+		/// "System.Collections.Generic.List" for List&lt;string&gt;
+		/// "System.Environment.SpecialFolder" for Environment.SpecialFolder
+		/// </returns>
+		string FullName { get; }
+		
+		/// <summary>
+		/// Gets the short name of the class the return type is pointing to.
+		/// </summary>
+		/// <returns>
+		/// "Int32[]" for int[]<br/>
+		/// "List" for List&lt;string&gt;
+		/// "SpecialFolder" for Environment.SpecialFolder
+		/// </returns>
+		string Name { get; }
+		
+		/// <summary>
+		/// Gets the full reflection name of the element.
+		/// </summary>
+		/// <remarks>
+		/// For types, the reflection name can be parsed back into a ITypeReference by using
+		/// <see cref="ReflectionHelper.ParseReflectionName(string)"/>.
+		/// </remarks>
+		/// <returns>
+		/// "System.Int32[]" for int[]<br/>
+		/// "System.Int32[][,]" for C# int[,][]<br/>
+		/// "System.Collections.Generic.List`1[[System.String]]" for List&lt;string&gt;
+		/// "System.Environment+SpecialFolder" for Environment.SpecialFolder
+		/// </returns>
+		string ReflectionName { get; }
+		
+		/// <summary>
+		/// Gets the full name of the namespace containing this entity.
+		/// </summary>
+		string Namespace { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/INamespace.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/INamespace.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/INamespace.cs	(revision 11807)
@@ -0,0 +1,88 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a resolved namespace.
+	/// </summary>
+	public interface INamespace : ISymbol, ICompilationProvider
+	{
+		// No pointer back to unresolved namespace:
+		// multiple unresolved namespaces (from different assemblies) get
+		// merged into one INamespace.
+		
+		/// <summary>
+		/// Gets the extern alias for this namespace.
+		/// Returns an empty string for normal namespaces.
+		/// </summary>
+		string ExternAlias { get; }
+		
+		/// <summary>
+		/// Gets the full name of this namespace. (e.g. "System.Collections")
+		/// </summary>
+		string FullName { get; }
+		
+		/// <summary>
+		/// Gets the short name of this namespace (e.g. "Collections").
+		/// </summary>
+		new string Name { get; }
+		
+		/// <summary>
+		/// Gets the parent namespace.
+		/// Returns null if this is the root namespace.
+		/// </summary>
+		INamespace ParentNamespace { get; }
+		
+		/// <summary>
+		/// Gets the child namespaces in this namespace.
+		/// </summary>
+		IEnumerable<INamespace> ChildNamespaces { get; }
+		
+		/// <summary>
+		/// Gets the types in this namespace.
+		/// </summary>
+		IEnumerable<ITypeDefinition> Types { get; }
+		
+		/// <summary>
+		/// Gets the assemblies that contribute types to this namespace (or to child namespaces).
+		/// </summary>
+		IEnumerable<IAssembly> ContributingAssemblies { get; }
+		
+		/// <summary>
+		/// Gets a direct child namespace by its short name.
+		/// Returns null when the namespace cannot be found.
+		/// </summary>
+		/// <remarks>
+		/// This method uses the compilation's current string comparer.
+		/// </remarks>
+		INamespace GetChildNamespace(string name);
+		
+		/// <summary>
+		/// Gets the type with the specified short name and type parameter count.
+		/// Returns null if the type cannot be found.
+		/// </summary>
+		/// <remarks>
+		/// This method uses the compilation's current string comparer.
+		/// </remarks>
+		ITypeDefinition GetTypeDefinition(string name, int typeParameterCount);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IParameter.cs	(revision 11807)
@@ -0,0 +1,104 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public interface IUnresolvedParameter
+	{
+		/// <summary>
+		/// Gets the name of the variable.
+		/// </summary>
+		string Name { get; }
+		
+		/// <summary>
+		/// Gets the declaration region of the variable.
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Gets the type of the variable.
+		/// </summary>
+		ITypeReference Type { get; }
+		
+		/// <summary>
+		/// Gets the list of attributes.
+		/// </summary>
+		IList<IUnresolvedAttribute> Attributes { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is a C# 'ref' parameter.
+		/// </summary>
+		bool IsRef { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is a C# 'out' parameter.
+		/// </summary>
+		bool IsOut { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is a C# 'params' parameter.
+		/// </summary>
+		bool IsParams { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is optional.
+		/// </summary>
+		bool IsOptional { get; }
+		
+		IParameter CreateResolvedParameter(ITypeResolveContext context);
+	}
+	
+	public interface IParameter : IVariable
+	{
+		/// <summary>
+		/// Gets the list of attributes.
+		/// </summary>
+		IList<IAttribute> Attributes { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is a C# 'ref' parameter.
+		/// </summary>
+		bool IsRef { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is a C# 'out' parameter.
+		/// </summary>
+		bool IsOut { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is a C# 'params' parameter.
+		/// </summary>
+		bool IsParams { get; }
+		
+		/// <summary>
+		/// Gets whether this parameter is optional.
+		/// The default value is given by the <see cref="IVariable.ConstantValue"/> property.
+		/// </summary>
+		bool IsOptional { get; }
+		
+		/// <summary>
+		/// Gets the owner of this parameter.
+		/// May return null; for example when parameters belong to lambdas or anonymous methods.
+		/// </summary>
+		IParameterizedMember Owner { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IParameterizedMember.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IParameterizedMember.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IParameterizedMember.cs	(revision 11807)
@@ -0,0 +1,40 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a method or property.
+	/// </summary>
+	public interface IUnresolvedParameterizedMember : IUnresolvedMember
+	{
+		IList<IUnresolvedParameter> Parameters { get; }
+	}
+	
+	/// <summary>
+	/// Represents a method or property.
+	/// </summary>
+	public interface IParameterizedMember : IMember
+	{
+		IList<IParameter> Parameters { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IProjectContent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IProjectContent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IProjectContent.cs	(revision 11807)
@@ -0,0 +1,159 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an assembly consisting of source code (parsed files).
+	/// </summary>
+	public interface IProjectContent : IUnresolvedAssembly
+	{
+		/// <summary>
+		/// Gets the path to the project file (e.g. .csproj).
+		/// </summary>
+		string ProjectFileName { get; }
+		
+		/// <summary>
+		/// Gets a parsed file by its file name.
+		/// </summary>
+		IUnresolvedFile GetFile(string fileName);
+		
+		/// <summary>
+		/// Gets the list of all files in the project content.
+		/// </summary>
+		IEnumerable<IUnresolvedFile> Files { get; }
+		
+		/// <summary>
+		/// Gets the referenced assemblies.
+		/// </summary>
+		IEnumerable<IAssemblyReference> AssemblyReferences { get; }
+		
+		/// <summary>
+		/// Gets the compiler settings object.
+		/// The concrete type of the settings object depends on the programming language used to implement this project.
+		/// </summary>
+		object CompilerSettings { get; }
+		
+		/// <summary>
+		/// Creates a new <see cref="ICompilation"/> that allows resolving within this project.
+		/// </summary>
+		/// <remarks>
+		/// This method does not support <see cref="ProjectReference"/>s. When dealing with a solution
+		/// containing multiple projects, consider using <see cref="ISolutionSnapshot.GetCompilation"/> instead.
+		/// </remarks>
+		ICompilation CreateCompilation();
+		
+		/// <summary>
+		/// Creates a new <see cref="ICompilation"/> that allows resolving within this project.
+		/// </summary>
+		/// <param name="solutionSnapshot">The parent solution snapshot to use for the compilation.</param>
+		/// <remarks>
+		/// This method is intended to be called by ISolutionSnapshot implementations. Other code should
+		/// call <see cref="ISolutionSnapshot.GetCompilation"/> instead.
+		/// This method always creates a new compilation, even if the solution snapshot already contains
+		/// one for this project.
+		/// </remarks>
+		ICompilation CreateCompilation(ISolutionSnapshot solutionSnapshot);
+		
+		/// <summary>
+		/// Changes the assembly name of this project content.
+		/// </summary>
+		IProjectContent SetAssemblyName(string newAssemblyName);
+
+		/// <summary>
+		/// Changes the project file name of this project content.
+		/// </summary>
+		IProjectContent SetProjectFileName(string newProjectFileName);
+		
+		/// <summary>
+		/// Changes the path to the assembly location (the output path where the project compiles to).
+		/// </summary>
+		IProjectContent SetLocation(string newLocation);
+
+		/// <summary>
+		/// Add assembly references to this project content.
+		/// </summary>
+		IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references);
+		
+		/// <summary>
+		/// Add assembly references to this project content.
+		/// </summary>
+		IProjectContent AddAssemblyReferences(params IAssemblyReference[] references);
+		
+		/// <summary>
+		/// Removes assembly references from this project content.
+		/// </summary>
+		IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references);
+		
+		/// <summary>
+		/// Removes assembly references from this project content.
+		/// </summary>
+		IProjectContent RemoveAssemblyReferences(params IAssemblyReference[] references);
+		
+		/// <summary>
+		/// Adds the specified files to the project content.
+		/// If a file with the same name already exists, updated the existing file.
+		/// </summary>
+		/// <remarks>
+		/// You can create an unresolved file by calling <c>ToTypeSystem()</c> on a syntax tree.
+		/// </remarks>
+		IProjectContent AddOrUpdateFiles(IEnumerable<IUnresolvedFile> newFiles);
+		
+		/// <summary>
+		/// Adds the specified files to the project content.
+		/// If a file with the same name already exists, this method updates the existing file.
+		/// </summary>
+		/// <remarks>
+		/// You can create an unresolved file by calling <c>ToTypeSystem()</c> on a syntax tree.
+		/// </remarks>
+		IProjectContent AddOrUpdateFiles(params IUnresolvedFile[] newFiles);
+		
+		/// <summary>
+		/// Removes the files with the specified names.
+		/// </summary>
+		IProjectContent RemoveFiles(IEnumerable<string> fileNames);
+		
+		/// <summary>
+		/// Removes the files with the specified names.
+		/// </summary>
+		IProjectContent RemoveFiles(params string[] fileNames);
+		
+		/// <summary>
+		/// Removes types and attributes from oldFile from the project, and adds those from newFile.
+		/// </summary>
+		[Obsolete("Use RemoveFiles()/AddOrUpdateFiles() instead")]
+		IProjectContent UpdateProjectContent(IUnresolvedFile oldFile, IUnresolvedFile newFile);
+		
+		/// <summary>
+		/// Removes types and attributes from oldFiles from the project, and adds those from newFiles.
+		/// </summary>
+		[Obsolete("Use RemoveFiles()/AddOrUpdateFiles() instead")]
+		IProjectContent UpdateProjectContent(IEnumerable<IUnresolvedFile> oldFiles, IEnumerable<IUnresolvedFile> newFiles);
+		
+		/// <summary>
+		/// Sets the compiler settings object.
+		/// The concrete type of the settings object depends on the programming language used to implement this project.
+		/// Using the incorrect type of settings object results in an <see cref="ArgumentException"/>.
+		/// </summary>
+		IProjectContent SetCompilerSettings(object compilerSettings);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IProperty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IProperty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IProperty.cs	(revision 11807)
@@ -0,0 +1,62 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a property or indexer.
+	/// </summary>
+	public interface IUnresolvedProperty : IUnresolvedParameterizedMember
+	{
+		bool CanGet { get; }
+		bool CanSet { get; }
+		
+		IUnresolvedMethod Getter { get; }
+		IUnresolvedMethod Setter { get; }
+		
+		bool IsIndexer { get; }
+		
+		/// <summary>
+		/// Resolves the member.
+		/// </summary>
+		/// <param name="context">
+		/// Context for looking up the member. The context must specify the current assembly.
+		/// A <see cref="SimpleTypeResolveContext"/> that specifies the current assembly is sufficient.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved member, or <c>null</c> if the member could not be found.
+		/// </returns>
+		new IProperty Resolve(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Represents a property or indexer.
+	/// </summary>
+	public interface IProperty : IParameterizedMember
+	{
+		bool CanGet { get; }
+		bool CanSet { get; }
+		
+		IMethod Getter { get; }
+		IMethod Setter { get; }
+		
+		bool IsIndexer { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISolutionSnapshot.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISolutionSnapshot.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISolutionSnapshot.cs	(revision 11807)
@@ -0,0 +1,43 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a snapshot of the whole solution (multiple compilations).
+	/// </summary>
+	public interface ISolutionSnapshot
+	{
+		/// <summary>
+		/// Gets the project content with the specified file name.
+		/// Returns null if no such project exists in the solution.
+		/// </summary>
+		/// <remarks>
+		/// This method is used by the <see cref="ProjectReference"/> class.
+		/// </remarks>
+		IProjectContent GetProjectContent(string projectFileName);
+		
+		/// <summary>
+		/// Gets the compilation for the specified project.
+		/// The project must be a part of the solution (passed to the solution snapshot's constructor).
+		/// </summary>
+		ICompilation GetCompilation(IProjectContent project);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISupportsInterning.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISupportsInterning.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISupportsInterning.cs	(revision 11807)
@@ -0,0 +1,39 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Interface for TypeSystem objects that support interning.
+	/// See <see cref="InterningProvider"/> for more information.
+	/// </summary>
+	public interface ISupportsInterning
+	{
+		/// <summary>
+		/// Gets a hash code for interning.
+		/// </summary>
+		int GetHashCodeForInterning();
+		
+		/// <summary>
+		/// Equality test for interning.
+		/// </summary>
+		bool EqualsForInterning(ISupportsInterning other);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISymbol.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISymbol.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ISymbol.cs	(revision 11807)
@@ -0,0 +1,100 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public enum SymbolKind : byte
+	{
+		None,
+		/// <seealso cref="ITypeDefinition"/>
+		TypeDefinition,
+		/// <seealso cref="IField"/>
+		Field,
+		/// <summary>
+		/// The symbol is a property, but not an indexer.
+		/// </summary>
+		/// <seealso cref="IProperty"/>
+		Property,
+		/// <summary>
+		/// The symbol is an indexer, not a regular property.
+		/// </summary>
+		/// <seealso cref="IProperty"/>
+		Indexer,
+		/// <seealso cref="IEvent"/>
+		Event,
+		/// <summary>
+		/// The symbol is a method which is not an operator/constructor/destructor or accessor.
+		/// </summary>
+		/// <seealso cref="IMethod"/>
+		Method,
+		/// <summary>
+		/// The symbol is a user-defined operator.
+		/// </summary>
+		/// <seealso cref="IMethod"/>
+		Operator,
+		/// <seealso cref="IMethod"/>
+		Constructor,
+		/// <seealso cref="IMethod"/>
+		Destructor,
+		/// <summary>
+		/// The accessor method for a property getter/setter or event add/remove.
+		/// </summary>
+		/// <seealso cref="IMethod"/>
+		Accessor,
+		/// <seealso cref="INamespace"/>
+		Namespace,
+		/// <summary>
+		/// The symbol is a variable, but not a parameter.
+		/// </summary>
+		/// <seealso cref="IVariable"/>
+		Variable,
+		/// <seealso cref="IParameter"/>
+		Parameter,
+		/// <seealso cref="ITypeParameter"/>
+		TypeParameter,
+	}
+	
+	/// <summary>
+	/// Interface for type system symbols.
+	/// </summary>
+	public interface ISymbol
+	{
+		/// <summary>
+		/// This property returns an enum specifying which kind of symbol this is
+		/// (which derived interfaces of ISymbol are implemented)
+		/// </summary>
+		SymbolKind SymbolKind { get; }
+		
+		/// <summary>
+		/// Gets the short name of the symbol.
+		/// </summary>
+		string Name { get; }
+		
+		/// <summary>
+		/// Creates a symbol reference that can be used to rediscover this symbol in another compilation.
+		/// </summary>
+		ISymbolReference ToReference();
+	}
+	
+	public interface ISymbolReference
+	{
+		ISymbol Resolve(ITypeResolveContext context);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IType.cs	(revision 11807)
@@ -0,0 +1,350 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// This interface represents a resolved type in the type system.
+	/// </summary>
+	/// <remarks>
+	/// <para>
+	/// A type is potentially
+	/// - a type definition (<see cref="ITypeDefinition"/>, i.e. a class, struct, interface, delegate, or built-in primitive type)
+	/// - a parameterized type (<see cref="ParameterizedType"/>, e.g. List&lt;int>)
+	/// - a type parameter (<see cref="ITypeParameter"/>, e.g. T)
+	/// - an array (<see cref="ArrayType"/>)
+	/// - a pointer (<see cref="PointerType"/>)
+	/// - a managed reference (<see cref="ByReferenceType"/>)
+	/// - one of the special types (<see cref="SpecialType.UnknownType"/>, <see cref="SpecialType.NullType"/>,
+	///      <see cref="SpecialType.Dynamic"/>, <see cref="SpecialType.UnboundTypeArgument"/>)
+	/// 
+	/// The <see cref="IType.Kind"/> property can be used to switch on the kind of a type.
+	/// </para>
+	/// <para>
+	/// IType uses the null object pattern: <see cref="SpecialType.UnknownType"/> serves as the null object.
+	/// Methods or properties returning IType never return null unless documented otherwise.
+	/// </para>
+	/// <para>
+	/// Types should be compared for equality using the <see cref="IEquatable{IType}.Equals(IType)"/> method.
+	/// Identical types do not necessarily use the same object reference.
+	/// </para>
+	/// </remarks>
+	public interface IType : INamedElement, IEquatable<IType>
+	{
+		/// <summary>
+		/// Gets the type kind.
+		/// </summary>
+		TypeKind Kind { get; }
+		
+		/// <summary>
+		/// Gets whether the type is a reference type or value type.
+		/// </summary>
+		/// <returns>
+		/// true, if the type is a reference type.
+		/// false, if the type is a value type.
+		/// null, if the type is not known (e.g. unconstrained generic type parameter or type not found)
+		/// </returns>
+		bool? IsReferenceType { get; }
+		
+		/// <summary>
+		/// Gets the underlying type definition.
+		/// Can return null for types which do not have a type definition (for example arrays, pointers, type parameters).
+		/// </summary>
+		ITypeDefinition GetDefinition();
+		
+		/// <summary>
+		/// Gets the parent type, if this is a nested type.
+		/// Returns null for top-level types.
+		/// </summary>
+		IType DeclaringType { get; }
+		
+		/// <summary>
+		/// Gets the number of type parameters.
+		/// </summary>
+		int TypeParameterCount { get; }
+
+		/// <summary>
+		/// Gets the type arguments passed to this type.
+		/// If this type is a generic type definition that is not parameterized, this property returns the type parameters,
+		/// as if the type was parameterized with its own type arguments (<c>class C&lt;T&gt; { C&lt;T&gt; field; }</c>).
+		/// 
+		/// NOTE: The type will change to IReadOnlyList&lt;IType&gt; in future versions.
+		/// </summary>
+		IList<IType> TypeArguments { get; }
+
+		/// <summary>
+		/// If true the type represents an instance of a generic type.
+		/// </summary>
+		bool IsParameterized { get; }
+
+		/// <summary>
+		/// Calls ITypeVisitor.Visit for this type.
+		/// </summary>
+		/// <returns>The return value of the ITypeVisitor.Visit call</returns>
+		IType AcceptVisitor(TypeVisitor visitor);
+		
+		/// <summary>
+		/// Calls ITypeVisitor.Visit for all children of this type, and reconstructs this type with the children based
+		/// on the return values of the visit calls.
+		/// </summary>
+		/// <returns>A copy of this type, with all children replaced by the return value of the corresponding visitor call.
+		/// If the visitor returned the original types for all children (or if there are no children), returns <c>this</c>.
+		/// </returns>
+		IType VisitChildren(TypeVisitor visitor);
+		
+		/// <summary>
+		/// Gets the direct base types.
+		/// </summary>
+		/// <returns>Returns the direct base types including interfaces</returns>
+		IEnumerable<IType> DirectBaseTypes { get; }
+		
+		/// <summary>
+		/// Creates a type reference that can be used to look up a type equivalent to this type in another compilation.
+		/// </summary>
+		/// <remarks>
+		/// If this type contains open generics, the resulting type reference will need to be looked up in an appropriate generic context.
+		/// Otherwise, the main resolve context of a compilation is sufficient.
+		/// </remarks>
+		ITypeReference ToTypeReference();
+
+		/// <summary>
+		/// Gets a type visitor that performs the substitution of class type parameters with the type arguments
+		/// of this parameterized type.
+		/// Returns TypeParameterSubstitution.Identity if the type is not parametrized.
+		/// </summary>
+		TypeParameterSubstitution GetSubstitution();
+		
+		/// <summary>
+		/// Gets a type visitor that performs the substitution of class type parameters with the type arguments
+		/// of this parameterized type,
+		/// and also substitutes method type parameters with the specified method type arguments.
+		/// Returns TypeParameterSubstitution.Identity if the type is not parametrized.
+		/// </summary>
+		TypeParameterSubstitution GetSubstitution(IList<IType> methodTypeArguments);
+
+		
+		/// <summary>
+		/// Gets inner classes (including inherited inner classes).
+		/// </summary>
+		/// <param name="filter">The filter used to select which types to return.
+		/// The filter is tested on the original type definitions (before parameterization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// <para>
+		/// If the nested type is generic, this method will return a parameterized type,
+		/// where the additional type parameters are set to <see cref="SpecialType.UnboundTypeArgument"/>.
+		/// </para>
+		/// <para>
+		/// Type parameters belonging to the outer class will have the value copied from the outer type
+		/// if it is a parameterized type. Otherwise, those existing type parameters will be self-parameterized,
+		/// and thus 'leaked' to the caller in the same way the GetMembers() method does not specialize members
+		/// from an <see cref="ITypeDefinition"/> and 'leaks' type parameters in member signatures.
+		/// </para>
+		/// </remarks>
+		/// <example>
+		/// <code>
+		/// class Base&lt;T> {
+		/// 	class Nested&lt;X> {}
+		/// }
+		/// class Derived&lt;A, B> : Base&lt;B> {}
+		/// 
+		/// Derived[string,int].GetNestedTypes() = { Base`1+Nested`1[int, unbound] }
+		/// Derived.GetNestedTypes() = { Base`1+Nested`1[`1, unbound] }
+		/// Base[`1].GetNestedTypes() = { Base`1+Nested`1[`1, unbound] }
+		/// Base.GetNestedTypes() = { Base`1+Nested`1[`0, unbound] }
+		/// </code>
+		/// </example>
+		IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		// Note that we cannot 'leak' the additional type parameter as we leak the normal type parameters, because
+		// the index might collide. For example,
+		//   class Base<T> { class Nested<X> {} }
+		//   class Derived<A, B> : Base<B> { }
+		// 
+		// Derived<string, int>.GetNestedTypes() = Base+Nested<int, UnboundTypeArgument>
+		// Derived.GetNestedTypes() = Base+Nested<`1, >
+		//  Here `1 refers to B, and there's no way to return X as it would collide with B.
+		
+		/// <summary>
+		/// Gets inner classes (including inherited inner classes)
+		/// that have <c>typeArguments.Count</c> additional type parameters.
+		/// </summary>
+		/// <param name="typeArguments">The type arguments passed to the inner class</param>
+		/// <param name="filter">The filter used to select which types to return.
+		/// The filter is tested on the original type definitions (before parameterization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// Type parameters belonging to the outer class will have the value copied from the outer type
+		/// if it is a parameterized type. Otherwise, those existing type parameters will be self-parameterized,
+		/// and thus 'leaked' to the caller in the same way the GetMembers() method does not specialize members
+		/// from an <see cref="ITypeDefinition"/> and 'leaks' type parameters in member signatures.
+		/// </remarks>
+		IEnumerable<IType> GetNestedTypes(IList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all instance constructors for this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which constructors to return.
+		/// The filter is tested on the original method definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// <para>The result does not include static constructors.
+		/// Constructors in base classes are not returned by default, as GetMemberOptions.IgnoreInheritedMembers is the default value.</para>
+		/// <para>
+		/// For methods on parameterized types, type substitution will be performed on the method signature,
+		/// and the appropriate <see cref="Implementation.SpecializedMethod"/> will be returned.
+		/// </para>
+		/// </remarks>
+		IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers);
+		
+		/// <summary>
+		/// Gets all methods that can be called on this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which methods to return.
+		/// The filter is tested on the original method definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// <para>
+		/// The result does not include constructors or accessors.
+		/// </para>
+		/// <para>
+		/// For methods on parameterized types, type substitution will be performed on the method signature,
+		/// and the appropriate <see cref="Implementation.SpecializedMethod"/> will be returned.
+		/// </para>
+		/// <para>
+		/// If the method being returned is generic, and this type is a parameterized type where the type
+		/// arguments involve another method's type parameters, the resulting specialized signature
+		/// will be ambiguous as to which method a type parameter belongs to.
+		/// For example, "List[[``0]].GetMethods()" will return "ConvertAll(Converter`2[[``0, ``0]])".
+		/// 
+		/// If possible, use the other GetMethods() overload to supply type arguments to the method,
+		/// so that both class and method type parameter can be substituted at the same time, so that
+		/// the ambiguity can be avoided.
+		/// </para>
+		/// </remarks>
+		IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all generic methods that can be called on this type with the specified type arguments.
+		/// </summary>
+		/// <param name="typeArguments">The type arguments used for the method call.</param>
+		/// <param name="filter">The filter used to select which methods to return.
+		/// The filter is tested on the original method definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// <para>The result does not include constructors or accessors.</para>
+		/// <para>
+		/// Type substitution will be performed on the method signature, creating a <see cref="Implementation.SpecializedMethod"/>
+		/// with the specified type arguments.
+		/// </para>
+		/// <para>
+		/// When the list of type arguments is empty, this method acts like the GetMethods() overload without
+		/// the type arguments parameter - that is, it also returns generic methods,
+		/// and the other overload's remarks about ambiguous signatures apply here as well.
+		/// </para>
+		/// </remarks>
+		IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all properties that can be called on this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which properties to return.
+		/// The filter is tested on the original property definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// For properties on parameterized types, type substitution will be performed on the property signature,
+		/// and the appropriate <see cref="Implementation.SpecializedProperty"/> will be returned.
+		/// </remarks>
+		IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all fields that can be accessed on this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which constructors to return.
+		/// The filter is tested on the original field definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// For fields on parameterized types, type substitution will be performed on the field's return type,
+		/// and the appropriate <see cref="Implementation.SpecializedField"/> will be returned.
+		/// </remarks>
+		IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all events that can be accessed on this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which events to return.
+		/// The filter is tested on the original event definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// For fields on parameterized types, type substitution will be performed on the event's return type,
+		/// and the appropriate <see cref="Implementation.SpecializedEvent"/> will be returned.
+		/// </remarks>
+		IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all members that can be called on this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which members to return.
+		/// The filter is tested on the original member definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// <para>
+		/// The resulting list is the union of GetFields(), GetProperties(), GetMethods() and GetEvents().
+		/// It does not include constructors.
+		/// For parameterized types, type substitution will be performed.
+		/// </para>
+		/// <para>
+		/// For generic methods, the remarks about ambiguous signatures from the
+		/// <see cref="GetMethods(Predicate{IUnresolvedMethod}, GetMemberOptions)"/> method apply here as well.
+		/// </para>
+		/// </remarks>
+		IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter = null, GetMemberOptions options = GetMemberOptions.None);
+		
+		/// <summary>
+		/// Gets all accessors belonging to properties or events on this type.
+		/// </summary>
+		/// <param name="filter">The filter used to select which members to return.
+		/// The filter is tested on the original member definitions (before specialization).</param>
+		/// <param name="options">Specified additional options for the GetMembers() operation.</param>
+		/// <remarks>
+		/// Accessors are not returned by GetMembers() or GetMethods().
+		/// </remarks>
+		IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None);
+	}
+	
+	[Flags]
+	public enum GetMemberOptions
+	{
+		/// <summary>
+		/// No options specified - this is the default.
+		/// Members will be specialized, and inherited members will be included.
+		/// </summary>
+		None = 0x00,
+		/// <summary>
+		/// Do not specialize the returned members - directly return the definitions.
+		/// </summary>
+		ReturnMemberDefinitions = 0x01,
+		/// <summary>
+		/// Do not list inherited members - only list members defined directly on this type.
+		/// </summary>
+		IgnoreInheritedMembers = 0x02
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeDefinition.cs	(revision 11807)
@@ -0,0 +1,170 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an unresolved class, enum, interface, struct, delegate or VB module.
+	/// For partial classes, an unresolved type definition represents only a single part.
+	/// </summary>
+	public interface IUnresolvedTypeDefinition : ITypeReference, IUnresolvedEntity
+	{
+		TypeKind Kind { get; }
+		
+		FullTypeName FullTypeName { get; }
+		IList<ITypeReference> BaseTypes { get; }
+		IList<IUnresolvedTypeParameter> TypeParameters { get; }
+		
+		IList<IUnresolvedTypeDefinition> NestedTypes { get; }
+		IList<IUnresolvedMember> Members { get; }
+		
+		IEnumerable<IUnresolvedMethod> Methods { get; }
+		IEnumerable<IUnresolvedProperty> Properties { get; }
+		IEnumerable<IUnresolvedField> Fields { get; }
+		IEnumerable<IUnresolvedEvent> Events { get; }
+		
+		/// <summary>
+		/// Gets whether the type definition contains extension methods.
+		/// Returns null when the type definition needs to be resolved in order to determine whether
+		/// methods are extension methods.
+		/// </summary>
+		bool? HasExtensionMethods { get; }
+		
+		/// <summary>
+		/// Gets whether the partial modifier is set on this part of the type definition.
+		/// </summary>
+		bool IsPartial { get; }
+		
+		/// <summary>
+		/// Gets whether this unresolved type definition causes the addition of a default constructor
+		/// if no other constructor is present.
+		/// </summary>
+		bool AddDefaultConstructorIfRequired { get; }
+		
+		/// <summary>
+		/// Looks up the resolved type definition from the <paramref name="context"/> corresponding to this unresolved
+		/// type definition.
+		/// </summary>
+		/// <param name="context">
+		/// Context for looking up the type. The context must specify the current assembly.
+		/// A <see cref="SimpleTypeResolveContext"/> that specifies the current assembly is sufficient.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved type definition.
+		/// In case of an error, returns an <see cref="Implementation.UnknownType"/> instance.
+		/// Never returns null.
+		/// </returns>
+		new IType Resolve(ITypeResolveContext context);
+		
+		/// <summary>
+		/// This method is used to add language-specific elements like the C# UsingScope
+		/// to the type resolve context.
+		/// </summary>
+		/// <param name="parentContext">The parent context (e.g. the parent assembly),
+		/// including the parent type definition for inner classes.</param>
+		/// <returns>
+		/// The parent context, modified to include language-specific elements (e.g. using scope)
+		/// associated with this type definition.
+		/// </returns>
+		/// <remarks>
+		/// Use <c>unresolvedTypeDef.CreateResolveContext(parentContext).WithTypeDefinition(typeDef)</c> to
+		/// create the context for use within the type definition.
+		/// </remarks>
+		ITypeResolveContext CreateResolveContext(ITypeResolveContext parentContext);
+	}
+	
+	/// <summary>
+	/// Represents a class, enum, interface, struct, delegate or VB module.
+	/// For partial classes, this represents the whole class.
+	/// </summary>
+	public interface ITypeDefinition : IType, IEntity
+	{
+		/// <summary>
+		/// Returns all parts that contribute to this type definition.
+		/// Non-partial classes have a single part that represents the whole class.
+		/// </summary>
+		IList<IUnresolvedTypeDefinition> Parts { get; }
+		
+		IList<ITypeParameter> TypeParameters { get; }
+		
+		IList<ITypeDefinition> NestedTypes { get; }
+		IList<IMember> Members { get; }
+		
+		IEnumerable<IField> Fields { get; }
+		IEnumerable<IMethod> Methods { get; }
+		IEnumerable<IProperty> Properties { get; }
+		IEnumerable<IEvent> Events { get; }
+		
+		/// <summary>
+		/// Gets the known type code for this type definition.
+		/// </summary>
+		KnownTypeCode KnownTypeCode { get; }
+		
+		/// <summary>
+		/// For enums: returns the underlying primitive type.
+		/// For all other types: returns <see cref="SpecialType.UnknownType"/>.
+		/// </summary>
+		IType EnumUnderlyingType { get; }
+		
+		/// <summary>
+		/// Gets the full name of this type.
+		/// </summary>
+		FullTypeName FullTypeName { get; }
+		
+		/// <summary>
+		/// Gets/Sets the declaring type (incl. type arguments, if any).
+		/// This property never returns null -- for top-level entities, it returns SharedTypes.UnknownType.
+		/// </summary>
+		new IType DeclaringType { get; } // solves ambiguity between IType.DeclaringType and IEntity.DeclaringType
+		
+		/// <summary>
+		/// Gets whether this type contains extension methods.
+		/// </summary>
+		/// <remarks>This property is used to speed up the search for extension methods.</remarks>
+		bool HasExtensionMethods { get; }
+		
+		/// <summary>
+		/// Gets whether this type definition is made up of one or more partial classes.
+		/// </summary>
+		bool IsPartial { get; }
+		
+		/// <summary>
+		/// Determines how this type is implementing the specified interface member.
+		/// </summary>
+		/// <returns>
+		/// The method on this type that implements the interface member;
+		/// or null if the type does not implement the interface.
+		/// </returns>
+		IMember GetInterfaceImplementation(IMember interfaceMember);
+		
+		/// <summary>
+		/// Determines how this type is implementing the specified interface members.
+		/// </summary>
+		/// <returns>
+		/// For each interface member, this method returns the class member 
+		/// that implements the interface member.
+		/// For interface members that are missing an implementation, the
+		/// result collection will contain a null element.
+		/// </returns>
+		IList<IMember> GetInterfaceImplementation(IList<IMember> interfaceMembers);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeParameter.cs	(revision 11807)
@@ -0,0 +1,151 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Type parameter of a generic class/method.
+	/// </summary>
+	public interface IUnresolvedTypeParameter : INamedElement
+	{
+		/// <summary>
+		/// Get the type of this type parameter's owner.
+		/// </summary>
+		/// <returns>SymbolKind.TypeDefinition or SymbolKind.Method</returns>
+		SymbolKind OwnerType { get; }
+		
+		/// <summary>
+		/// Gets the index of the type parameter in the type parameter list of the owning method/class.
+		/// </summary>
+		int Index { get; }
+		
+		/// <summary>
+		/// Gets the list of attributes declared on this type parameter.
+		/// </summary>
+		IList<IUnresolvedAttribute> Attributes { get; }
+		
+		/// <summary>
+		/// Gets the variance of this type parameter.
+		/// </summary>
+		VarianceModifier Variance { get; }
+		
+		/// <summary>
+		/// Gets the region where the type parameter is defined.
+		/// </summary>
+		DomRegion Region { get; }
+		
+		ITypeParameter CreateResolvedTypeParameter(ITypeResolveContext context);
+	}
+	
+	/// <summary>
+	/// Type parameter of a generic class/method.
+	/// </summary>
+	public interface ITypeParameter : IType, ISymbol
+	{
+		/// <summary>
+		/// Get the type of this type parameter's owner.
+		/// </summary>
+		/// <returns>SymbolKind.TypeDefinition or SymbolKind.Method</returns>
+		SymbolKind OwnerType { get; }
+		
+		/// <summary>
+		/// Gets the owning method/class.
+		/// This property may return null (for example for the dummy type parameters used by <see cref="ParameterListComparer.NormalizeMethodTypeParameters"/>).
+		/// </summary>
+		/// <remarks>
+		/// For "class Outer&lt;T&gt; { class Inner {} }",
+		/// inner.TypeParameters[0].Owner will be the outer class, because the same
+		/// ITypeParameter instance is used both on Outer`1 and Outer`1+Inner.
+		/// </remarks>
+		IEntity Owner { get; }
+		
+		/// <summary>
+		/// Gets the index of the type parameter in the type parameter list of the owning method/class.
+		/// </summary>
+		int Index { get; }
+		
+		/// <summary>
+		/// Gets the name of the type parameter.
+		/// </summary>
+		new string Name { get; }
+		
+		/// <summary>
+		/// Gets the list of attributes declared on this type parameter.
+		/// </summary>
+		IList<IAttribute> Attributes { get; }
+		
+		/// <summary>
+		/// Gets the variance of this type parameter.
+		/// </summary>
+		VarianceModifier Variance { get; }
+		
+		/// <summary>
+		/// Gets the region where the type parameter is defined.
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Gets the effective base class of this type parameter.
+		/// </summary>
+		IType EffectiveBaseClass { get; }
+		
+		/// <summary>
+		/// Gets the effective interface set of this type parameter.
+		/// </summary>
+		ICollection<IType> EffectiveInterfaceSet { get; }
+		
+		/// <summary>
+		/// Gets if the type parameter has the 'new()' constraint.
+		/// </summary>
+		bool HasDefaultConstructorConstraint { get; }
+		
+		/// <summary>
+		/// Gets if the type parameter has the 'class' constraint.
+		/// </summary>
+		bool HasReferenceTypeConstraint { get; }
+		
+		/// <summary>
+		/// Gets if the type parameter has the 'struct' constraint.
+		/// </summary>
+		bool HasValueTypeConstraint { get; }
+	}
+	
+	/// <summary>
+	/// Represents the variance of a type parameter.
+	/// </summary>
+	public enum VarianceModifier : byte
+	{
+		/// <summary>
+		/// The type parameter is not variant.
+		/// </summary>
+		Invariant,
+		/// <summary>
+		/// The type parameter is covariant (used in output position).
+		/// </summary>
+		Covariant,
+		/// <summary>
+		/// The type parameter is contravariant (used in input position).
+		/// </summary>
+		Contravariant
+	};
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ITypeReference.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a reference to a type.
+	/// Must be resolved before it can be used as type.
+	/// </summary>
+	public interface ITypeReference
+	{
+		// Keep this interface simple: I decided against having GetMethods/GetEvents etc. here,
+		// so that the Resolve step is never hidden from the consumer.
+		
+		// I decided against implementing IFreezable here: IUnresolvedTypeDefinition can be used as ITypeReference,
+		// but when freezing the reference, one wouldn't expect the definition to freeze.
+		
+		/// <summary>
+		/// Resolves this type reference.
+		/// </summary>
+		/// <param name="context">
+		/// Context to use for resolving this type reference.
+		/// Which kind of context is required depends on the which kind of type reference this is;
+		/// please consult the documentation of the method that was used to create this type reference,
+		/// or that of the class implementing this method.
+		/// </param>
+		/// <returns>
+		/// Returns the resolved type.
+		/// In case of an error, returns an unknown type (<see cref="TypeKind.Unknown"/>).
+		/// Never returns null.
+		/// </returns>
+		IType Resolve(ITypeResolveContext context);
+	}
+	
+	public interface ITypeResolveContext : ICompilationProvider
+	{
+		/// <summary>
+		/// Gets the current assembly.
+		/// This property may return null if this context does not specify any assembly.
+		/// </summary>
+		IAssembly CurrentAssembly { get; }
+		
+		/// <summary>
+		/// Gets the current type definition.
+		/// </summary>
+		ITypeDefinition CurrentTypeDefinition { get ;}
+		
+		/// <summary>
+		/// Gets the current member.
+		/// </summary>
+		IMember CurrentMember { get; }
+		
+		ITypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition);
+		ITypeResolveContext WithCurrentMember(IMember member);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IUnresolvedFile.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IUnresolvedFile.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IUnresolvedFile.cs	(revision 11807)
@@ -0,0 +1,80 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	[Obsolete("IParsedFile was renamed to IUnresolvedFile", true)]
+	public interface IParsedFile {}
+	
+	/// <summary>
+	/// Represents a single file that was parsed.
+	/// </summary>
+	public interface IUnresolvedFile
+	{
+		/// <summary>
+		/// Returns the full path of the file.
+		/// </summary>
+		string FileName { get; }
+		
+		/// <summary>
+		/// Gets the time when the file was last written.
+		/// </summary>
+		DateTime? LastWriteTime { get; set; }
+		
+		/// <summary>
+		/// Gets all top-level type definitions.
+		/// </summary>
+		IList<IUnresolvedTypeDefinition> TopLevelTypeDefinitions { get; }
+		
+		/// <summary>
+		/// Gets all assembly attributes that are defined in this file.
+		/// </summary>
+		IList<IUnresolvedAttribute> AssemblyAttributes { get; }
+		
+		/// <summary>
+		/// Gets all module attributes that are defined in this file.
+		/// </summary>
+		IList<IUnresolvedAttribute> ModuleAttributes { get; }
+		
+		/// <summary>
+		/// Gets the top-level type defined at the specified location.
+		/// Returns null if no type is defined at that location.
+		/// </summary>
+		IUnresolvedTypeDefinition GetTopLevelTypeDefinition(TextLocation location);
+		
+		/// <summary>
+		/// Gets the type (potentially a nested type) defined at the specified location.
+		/// Returns null if no type is defined at that location.
+		/// </summary>
+		IUnresolvedTypeDefinition GetInnermostTypeDefinition(TextLocation location);
+		
+		/// <summary>
+		/// Gets the member defined at the specified location.
+		/// Returns null if no member is defined at that location.
+		/// </summary>
+		IUnresolvedMember GetMember(TextLocation location);
+		
+		/// <summary>
+		/// Gets the parser errors.
+		/// </summary>
+		IList<Error> Errors { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IVariable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IVariable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IVariable.cs	(revision 11807)
@@ -0,0 +1,54 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents a variable (name/type pair).
+	/// </summary>
+	public interface IVariable : ISymbol
+	{
+		/// <summary>
+		/// Gets the name of the variable.
+		/// </summary>
+		new string Name { get; }
+		
+		/// <summary>
+		/// Gets the declaration region of the variable.
+		/// </summary>
+		DomRegion Region { get; }
+		
+		/// <summary>
+		/// Gets the type of the variable.
+		/// </summary>
+		IType Type { get; }
+		
+		/// <summary>
+		/// Gets whether this variable is a constant (C#-like const).
+		/// </summary>
+		bool IsConst { get; }
+		
+		/// <summary>
+		/// If this field is a constant, retrieves the value.
+		/// For parameters, this is the default value.
+		/// </summary>
+		object ConstantValue { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractFreezable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractFreezable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractFreezable.cs	(revision 11807)
@@ -0,0 +1,110 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public static class FreezableHelper
+	{
+		public static void ThrowIfFrozen(IFreezable freezable)
+		{
+			if (freezable.IsFrozen)
+				throw new InvalidOperationException("Cannot mutate frozen " + freezable.GetType().Name);
+		}
+		
+		public static IList<T> FreezeListAndElements<T>(IList<T> list)
+		{
+			if (list != null) {
+				foreach (T item in list)
+					Freeze(item);
+			}
+			return FreezeList(list);
+		}
+		
+		public static IList<T> FreezeList<T>(IList<T> list)
+		{
+			if (list == null || list.Count == 0)
+				return EmptyList<T>.Instance;
+			if (list.IsReadOnly) {
+				// If the list is already read-only, return it directly.
+				// This is important, otherwise we might undo the effects of interning.
+				return list;
+			} else {
+				return new ReadOnlyCollection<T>(list.ToArray());
+			}
+		}
+		
+		public static void Freeze(object item)
+		{
+			IFreezable f = item as IFreezable;
+			if (f != null)
+				f.Freeze();
+		}
+		
+		public static T FreezeAndReturn<T>(T item) where T : IFreezable
+		{
+			item.Freeze();
+			return item;
+		}
+		
+		/// <summary>
+		/// If the item is not frozen, this method creates and returns a frozen clone.
+		/// If the item is already frozen, it is returned without creating a clone.
+		/// </summary>
+		public static T GetFrozenClone<T>(T item) where T : IFreezable, ICloneable
+		{
+			if (!item.IsFrozen) {
+				item = (T)item.Clone();
+				item.Freeze();
+			}
+			return item;
+		}
+	}
+
+	[Serializable]
+	public abstract class AbstractFreezable : IFreezable
+	{
+		bool isFrozen;
+		
+		/// <summary>
+		/// Gets if this instance is frozen. Frozen instances are immutable and thus thread-safe.
+		/// </summary>
+		public bool IsFrozen {
+			get { return isFrozen; }
+		}
+		
+		/// <summary>
+		/// Freezes this instance.
+		/// </summary>
+		public void Freeze()
+		{
+			if (!isFrozen) {
+				FreezeInternal();
+				isFrozen = true;
+			}
+		}
+		
+		protected virtual void FreezeInternal()
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedEntity.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedEntity.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedEntity.cs	(revision 11807)
@@ -0,0 +1,124 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Documentation;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Implementation of <see cref="IEntity"/> that resolves an unresolved entity.
+	/// </summary>
+	public abstract class AbstractResolvedEntity : IEntity
+	{
+		protected readonly IUnresolvedEntity unresolved;
+		protected readonly ITypeResolveContext parentContext;
+		
+		protected AbstractResolvedEntity(IUnresolvedEntity unresolved, ITypeResolveContext parentContext)
+		{
+			if (unresolved == null)
+				throw new ArgumentNullException("unresolved");
+			if (parentContext == null)
+				throw new ArgumentNullException("parentContext");
+			this.unresolved = unresolved;
+			this.parentContext = parentContext;
+			this.Attributes = unresolved.Attributes.CreateResolvedAttributes(parentContext);
+		}
+		
+		public SymbolKind SymbolKind {
+			get { return unresolved.SymbolKind; }
+		}
+		
+		[Obsolete("Use the SymbolKind property instead.")]
+		public EntityType EntityType {
+			get { return (EntityType)unresolved.SymbolKind; }
+		}
+		
+		public DomRegion Region {
+			get { return unresolved.Region; }
+		}
+		
+		public DomRegion BodyRegion {
+			get { return unresolved.BodyRegion; }
+		}
+		
+		public ITypeDefinition DeclaringTypeDefinition {
+			get { return parentContext.CurrentTypeDefinition; }
+		}
+		
+		public virtual IType DeclaringType {
+			get { return parentContext.CurrentTypeDefinition ?? (IType)SpecialType.UnknownType; }
+		}
+		
+		public IAssembly ParentAssembly {
+			get { return parentContext.CurrentAssembly; }
+		}
+		
+		public IList<IAttribute> Attributes { get; protected set; }
+		
+		public virtual DocumentationComment Documentation {
+			get {
+				IDocumentationProvider provider = FindDocumentation(parentContext);
+				if (provider != null)
+					return provider.GetDocumentation(this);
+				else
+					return null;
+			}
+		}
+		
+		internal static IDocumentationProvider FindDocumentation(ITypeResolveContext context)
+		{
+			IAssembly asm = context.CurrentAssembly;
+			if (asm != null)
+				return asm.UnresolvedAssembly as IDocumentationProvider;
+			else
+				return null;
+		}
+
+		public abstract ISymbolReference ToReference();
+		
+		public bool IsStatic { get { return unresolved.IsStatic; } }
+		public bool IsAbstract { get { return unresolved.IsAbstract; } }
+		public bool IsSealed { get { return unresolved.IsSealed; } }
+		public bool IsShadowing { get { return unresolved.IsShadowing; } }
+		public bool IsSynthetic { get { return unresolved.IsSynthetic; } }
+		
+		public ICompilation Compilation {
+			get { return parentContext.Compilation; }
+		}
+		
+		public string FullName { get { return unresolved.FullName; } }
+		public string Name { get { return unresolved.Name; } }
+		public string ReflectionName { get { return unresolved.ReflectionName; } }
+		public string Namespace { get { return unresolved.Namespace; } }
+		
+		public Accessibility Accessibility { get { return unresolved.Accessibility; } }
+		public bool IsPrivate { get { return unresolved.IsPrivate; } }
+		public bool IsPublic { get { return unresolved.IsPublic; } }
+		public bool IsProtected { get { return unresolved.IsProtected; } }
+		public bool IsInternal { get { return unresolved.IsInternal; } }
+		public bool IsProtectedOrInternal { get { return unresolved.IsProtectedOrInternal; } }
+		public bool IsProtectedAndInternal { get { return unresolved.IsProtectedAndInternal; } }
+		
+		public override string ToString()
+		{
+			return "[" + this.SymbolKind.ToString() + " " + this.ReflectionName + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedMember.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedMember.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedMember.cs	(revision 11807)
@@ -0,0 +1,167 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Implementation of <see cref="IMember"/> that resolves an unresolved member.
+	/// </summary>
+	public abstract class AbstractResolvedMember : AbstractResolvedEntity, IMember
+	{
+		protected new readonly IUnresolvedMember unresolved;
+		protected readonly ITypeResolveContext context;
+		volatile IType returnType;
+		IList<IMember> implementedInterfaceMembers;
+		
+		protected AbstractResolvedMember(IUnresolvedMember unresolved, ITypeResolveContext parentContext)
+			: base(unresolved, parentContext)
+		{
+			this.unresolved = unresolved;
+			this.context = parentContext.WithCurrentMember(this);
+		}
+		
+		IMember IMember.MemberDefinition {
+			get { return this; }
+		}
+		
+		public IType ReturnType {
+			get {
+				return this.returnType ?? (this.returnType = unresolved.ReturnType.Resolve(context));
+			}
+		}
+		
+		public IUnresolvedMember UnresolvedMember {
+			get { return unresolved; }
+		}
+		
+		public IList<IMember> ImplementedInterfaceMembers {
+			get {
+				IList<IMember> result = LazyInit.VolatileRead(ref this.implementedInterfaceMembers);
+				if (result != null) {
+					return result;
+				} else {
+					return LazyInit.GetOrSet(ref implementedInterfaceMembers, FindImplementedInterfaceMembers());
+				}
+			}
+		}
+		
+		IList<IMember> FindImplementedInterfaceMembers()
+		{
+			if (unresolved.IsExplicitInterfaceImplementation) {
+				List<IMember> result = new List<IMember>();
+				foreach (var memberReference in unresolved.ExplicitInterfaceImplementations) {
+					IMember member = memberReference.Resolve(context);
+					if (member != null)
+						result.Add(member);
+				}
+				return result.ToArray();
+			} else if (unresolved.IsStatic || !unresolved.IsPublic || DeclaringTypeDefinition == null || DeclaringTypeDefinition.Kind == TypeKind.Interface) {
+				return EmptyList<IMember>.Instance;
+			} else {
+				// TODO: implement interface member mappings correctly
+				var result = InheritanceHelper.GetBaseMembers(this, true)
+					.Where(m => m.DeclaringTypeDefinition != null && m.DeclaringTypeDefinition.Kind == TypeKind.Interface)
+					.ToArray();
+
+				IEnumerable<IMember> otherMembers = DeclaringTypeDefinition.Members;
+				if (SymbolKind == SymbolKind.Accessor)
+					otherMembers = DeclaringTypeDefinition.GetAccessors(options: GetMemberOptions.IgnoreInheritedMembers);
+				result = result.Where(item => !otherMembers.Any(m => m.IsExplicitInterfaceImplementation && m.ImplementedInterfaceMembers.Contains(item))).ToArray();
+
+				return result;
+			}
+		}
+		
+		public override DocumentationComment Documentation {
+			get {
+				IUnresolvedDocumentationProvider docProvider = unresolved.UnresolvedFile as IUnresolvedDocumentationProvider;
+				if (docProvider != null) {
+					var doc = docProvider.GetDocumentation(unresolved, this);
+					if (doc != null)
+						return doc;
+				}
+				return base.Documentation;
+			}
+		}
+		
+		public bool IsExplicitInterfaceImplementation {
+			get { return unresolved.IsExplicitInterfaceImplementation; }
+		}
+		
+		public bool IsVirtual {
+			get { return unresolved.IsVirtual; }
+		}
+		
+		public bool IsOverride {
+			get { return unresolved.IsOverride; }
+		}
+		
+		public bool IsOverridable {
+			get { return unresolved.IsOverridable; }
+		}
+
+		public TypeParameterSubstitution Substitution {
+			get { return TypeParameterSubstitution.Identity; }
+		}
+
+		public abstract IMember Specialize(TypeParameterSubstitution substitution);
+		
+		IMemberReference IMember.ToReference()
+		{
+			return (IMemberReference)ToReference();
+		}
+		
+		public override ISymbolReference ToReference()
+		{
+			var declTypeRef = this.DeclaringType.ToTypeReference();
+			if (IsExplicitInterfaceImplementation && ImplementedInterfaceMembers.Count == 1) {
+				return new ExplicitInterfaceImplementationMemberReference(declTypeRef, ImplementedInterfaceMembers[0].ToReference());
+			} else {
+				return new DefaultMemberReference(this.SymbolKind, declTypeRef, this.Name);
+			}
+		}
+		
+		public virtual IMemberReference ToMemberReference()
+		{
+			return (IMemberReference)ToReference();
+		}
+		
+		internal IMethod GetAccessor(ref IMethod accessorField, IUnresolvedMethod unresolvedAccessor)
+		{
+			if (unresolvedAccessor == null)
+				return null;
+			IMethod result = LazyInit.VolatileRead(ref accessorField);
+			if (result != null) {
+				return result;
+			} else {
+				return LazyInit.GetOrSet(ref accessorField, CreateResolvedAccessor(unresolvedAccessor));
+			}
+		}
+		
+		protected virtual IMethod CreateResolvedAccessor(IUnresolvedMethod unresolvedAccessor)
+		{
+			return (IMethod)unresolvedAccessor.CreateResolved(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedTypeParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedTypeParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractResolvedTypeParameter.cs	(revision 11807)
@@ -0,0 +1,412 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public abstract class AbstractTypeParameter : ITypeParameter, ICompilationProvider
+	{
+		readonly ICompilation compilation;
+		readonly SymbolKind ownerType;
+		readonly IEntity owner;
+		readonly int index;
+		readonly string name;
+		readonly IList<IAttribute> attributes;
+		readonly DomRegion region;
+		readonly VarianceModifier variance;
+		
+		protected AbstractTypeParameter(IEntity owner, int index, string name, VarianceModifier variance, IList<IAttribute> attributes, DomRegion region)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			this.owner = owner;
+			this.compilation = owner.Compilation;
+			this.ownerType = owner.SymbolKind;
+			this.index = index;
+			this.name = name ?? ((this.OwnerType == SymbolKind.Method ? "!!" : "!") + index.ToString(CultureInfo.InvariantCulture));
+			this.attributes = attributes ?? EmptyList<IAttribute>.Instance;
+			this.region = region;
+			this.variance = variance;
+		}
+		
+		protected AbstractTypeParameter(ICompilation compilation, SymbolKind ownerType, int index, string name, VarianceModifier variance, IList<IAttribute> attributes, DomRegion region)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			this.compilation = compilation;
+			this.ownerType = ownerType;
+			this.index = index;
+			this.name = name ?? ((this.OwnerType == SymbolKind.Method ? "!!" : "!") + index.ToString(CultureInfo.InvariantCulture));
+			this.attributes = attributes ?? EmptyList<IAttribute>.Instance;
+			this.region = region;
+			this.variance = variance;
+		}
+		
+		SymbolKind ISymbol.SymbolKind {
+			get { return SymbolKind.TypeParameter; }
+		}
+		
+		public SymbolKind OwnerType {
+			get { return ownerType; }
+		}
+		
+		public IEntity Owner {
+			get { return owner; }
+		}
+		
+		public int Index {
+			get { return index; }
+		}
+		
+		public IList<IAttribute> Attributes {
+			get { return attributes; }
+		}
+		
+		public VarianceModifier Variance {
+			get { return variance; }
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+		}
+		
+		public ICompilation Compilation {
+			get { return compilation; }
+		}
+		
+		volatile IType effectiveBaseClass;
+		
+		public IType EffectiveBaseClass {
+			get {
+				if (effectiveBaseClass == null) {
+					// protect against cyclic type parameters
+					using (var busyLock = BusyManager.Enter(this)) {
+						if (!busyLock.Success)
+							return SpecialType.UnknownType; // don't cache this error
+						effectiveBaseClass = CalculateEffectiveBaseClass();
+					}
+				}
+				return effectiveBaseClass;
+			}
+		}
+		
+		IType CalculateEffectiveBaseClass()
+		{
+			if (HasValueTypeConstraint)
+				return this.Compilation.FindType(KnownTypeCode.ValueType);
+			
+			List<IType> classTypeConstraints = new List<IType>();
+			foreach (IType constraint in this.DirectBaseTypes) {
+				if (constraint.Kind == TypeKind.Class) {
+					classTypeConstraints.Add(constraint);
+				} else if (constraint.Kind == TypeKind.TypeParameter) {
+					IType baseClass = ((ITypeParameter)constraint).EffectiveBaseClass;
+					if (baseClass.Kind == TypeKind.Class)
+						classTypeConstraints.Add(baseClass);
+				}
+			}
+			if (classTypeConstraints.Count == 0)
+				return this.Compilation.FindType(KnownTypeCode.Object);
+			// Find the derived-most type in the resulting set:
+			IType result = classTypeConstraints[0];
+			for (int i = 1; i < classTypeConstraints.Count; i++) {
+				if (classTypeConstraints[i].GetDefinition().IsDerivedFrom(result.GetDefinition()))
+					result = classTypeConstraints[i];
+			}
+			return result;
+		}
+		
+		ICollection<IType> effectiveInterfaceSet;
+		
+		public ICollection<IType> EffectiveInterfaceSet {
+			get {
+				var result = LazyInit.VolatileRead(ref effectiveInterfaceSet);
+				if (result != null) {
+					return result;
+				} else {
+					// protect against cyclic type parameters
+					using (var busyLock = BusyManager.Enter(this)) {
+						if (!busyLock.Success)
+							return EmptyList<IType>.Instance; // don't cache this error
+						return LazyInit.GetOrSet(ref effectiveInterfaceSet, CalculateEffectiveInterfaceSet());
+					}
+				}
+			}
+		}
+		
+		ICollection<IType> CalculateEffectiveInterfaceSet()
+		{
+			HashSet<IType> result = new HashSet<IType>();
+			foreach (IType constraint in this.DirectBaseTypes) {
+				if (constraint.Kind == TypeKind.Interface) {
+					result.Add(constraint);
+				} else if (constraint.Kind == TypeKind.TypeParameter) {
+					result.UnionWith(((ITypeParameter)constraint).EffectiveInterfaceSet);
+				}
+			}
+			return result;
+		}
+		
+		public abstract bool HasDefaultConstructorConstraint { get; }
+		public abstract bool HasReferenceTypeConstraint { get; }
+		public abstract bool HasValueTypeConstraint { get; }
+		
+		public TypeKind Kind {
+			get { return TypeKind.TypeParameter; }
+		}
+		
+		public bool? IsReferenceType {
+			get {
+				if (this.HasValueTypeConstraint)
+					return false;
+				if (this.HasReferenceTypeConstraint)
+					return true;
+				
+				// A type parameter is known to be a reference type if it has the reference type constraint
+				// or its effective base class is not object or System.ValueType.
+				IType effectiveBaseClass = this.EffectiveBaseClass;
+				if (effectiveBaseClass.Kind == TypeKind.Class || effectiveBaseClass.Kind == TypeKind.Delegate) {
+					ITypeDefinition effectiveBaseClassDef = effectiveBaseClass.GetDefinition();
+					if (effectiveBaseClassDef != null) {
+						switch (effectiveBaseClassDef.KnownTypeCode) {
+							case KnownTypeCode.Object:
+							case KnownTypeCode.ValueType:
+							case KnownTypeCode.Enum:
+								return null;
+						}
+					}
+					return true;
+				} else if (effectiveBaseClass.Kind == TypeKind.Struct || effectiveBaseClass.Kind == TypeKind.Enum) {
+					return false;
+				}
+				return null;
+			}
+		}
+		
+		IType IType.DeclaringType {
+			get { return null; }
+		}
+		
+		int IType.TypeParameterCount {
+			get { return 0; }
+		}
+
+		bool IType.IsParameterized { 
+			get { return false; }
+		}
+
+		readonly static IList<IType> emptyTypeArguments = new IType[0];
+		IList<IType> IType.TypeArguments {
+			get { return emptyTypeArguments; }
+		}
+
+		public abstract IEnumerable<IType> DirectBaseTypes { get; }
+		
+		public string Name {
+			get { return name; }
+		}
+		
+		string INamedElement.Namespace {
+			get { return string.Empty; }
+		}
+		
+		string INamedElement.FullName {
+			get { return name; }
+		}
+		
+		public string ReflectionName {
+			get {
+				return (this.OwnerType == SymbolKind.Method ? "``" : "`") + index.ToString(CultureInfo.InvariantCulture);
+			}
+		}
+		
+		ITypeDefinition IType.GetDefinition()
+		{
+			return null;
+		}
+		
+		public IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitTypeParameter(this);
+		}
+		
+		public IType VisitChildren(TypeVisitor visitor)
+		{
+			return this;
+		}
+		
+		public ITypeReference ToTypeReference()
+		{
+			return TypeParameterReference.Create(this.OwnerType, this.Index);
+		}
+		
+		IEnumerable<IType> IType.GetNestedTypes(Predicate<ITypeDefinition> filter, GetMemberOptions options)
+		{
+			return EmptyList<IType>.Instance;
+		}
+		
+		IEnumerable<IType> IType.GetNestedTypes(IList<IType> typeArguments, Predicate<ITypeDefinition> filter, GetMemberOptions options)
+		{
+			return EmptyList<IType>.Instance;
+		}
+		
+		public IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				if (this.HasDefaultConstructorConstraint || this.HasValueTypeConstraint) {
+					if (filter == null || filter(DefaultUnresolvedMethod.DummyConstructor)) {
+						return new [] { DefaultResolvedMethod.GetDummyConstructor(compilation, this) };
+					}
+				}
+				return EmptyList<IMethod>.Instance;
+			} else {
+				return GetMembersHelper.GetConstructors(this, filter, options);
+			}
+		}
+		
+		public IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return GetMembersHelper.GetMethods(this, FilterNonStatic(filter), options);
+		}
+		
+		public IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return GetMembersHelper.GetMethods(this, typeArguments, FilterNonStatic(filter), options);
+		}
+		
+		public IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IProperty>.Instance;
+			else
+				return GetMembersHelper.GetProperties(this, FilterNonStatic(filter), options);
+		}
+		
+		public IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IField>.Instance;
+			else
+				return GetMembersHelper.GetFields(this, FilterNonStatic(filter), options);
+		}
+		
+		public IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IEvent>.Instance;
+			else
+				return GetMembersHelper.GetEvents(this, FilterNonStatic(filter), options);
+		}
+		
+		public IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMember>.Instance;
+			else
+				return GetMembersHelper.GetMembers(this, FilterNonStatic(filter), options);
+		}
+		
+		public IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers)
+				return EmptyList<IMethod>.Instance;
+			else
+				return GetMembersHelper.GetAccessors(this, FilterNonStatic(filter), options);
+		}
+
+		public TypeParameterSubstitution GetSubstitution()
+		{
+			return TypeParameterSubstitution.Identity;
+		}
+		
+		public TypeParameterSubstitution GetSubstitution(IList<IType> methodTypeArguments)
+		{
+			return TypeParameterSubstitution.Identity;
+		}
+
+		static Predicate<T> FilterNonStatic<T>(Predicate<T> filter) where T : class, IUnresolvedMember
+		{
+			if (filter == null)
+				return member => !member.IsStatic;
+			else
+				return member => !member.IsStatic && filter(member);
+		}
+		
+		public sealed override bool Equals(object obj)
+		{
+			return Equals(obj as IType);
+		}
+		
+		public override int GetHashCode()
+		{
+			return base.GetHashCode();
+		}
+		
+		public virtual bool Equals(IType other)
+		{
+			return this == other; // use reference equality for type parameters
+		}
+
+		public virtual ISymbolReference ToReference()
+		{
+			if (owner == null)
+				return TypeParameterReference.Create(ownerType, index);
+			return new OwnedTypeParameterReference(owner.ToReference(), index);
+		}
+		
+		public override string ToString()
+		{
+			return this.ReflectionName + " (owner=" + owner + ")";
+		}
+	}
+	
+	public sealed class OwnedTypeParameterReference : ISymbolReference
+	{
+		ISymbolReference owner;
+		int index;
+		
+		public OwnedTypeParameterReference(ISymbolReference owner, int index)
+		{
+			if (owner == null)
+				throw new ArgumentNullException("owner");
+			this.owner = owner;
+			this.index = index;
+		}
+		
+		public ISymbol Resolve(ITypeResolveContext context)
+		{
+			var entity = owner.Resolve(context) as IEntity;
+			if (entity is ITypeDefinition)
+				return ((ITypeDefinition)entity).TypeParameters[index];
+			if (entity is IMethod)
+				return ((IMethod)entity).TypeParameters[index];
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractType.cs	(revision 11807)
@@ -0,0 +1,180 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation for IType interface.
+	/// </summary>
+	[Serializable]
+	public abstract class AbstractType : IType
+	{
+		public virtual string FullName {
+			get {
+				string ns = this.Namespace;
+				string name = this.Name;
+				if (string.IsNullOrEmpty(ns)) {
+					return name;
+				} else {
+					return ns + "." + name;
+				}
+			}
+		}
+		
+		public abstract string Name { get; }
+		
+		public virtual string Namespace {
+			get { return string.Empty; }
+		}
+		
+		public virtual string ReflectionName {
+			get { return this.FullName; }
+		}
+		
+		public abstract bool? IsReferenceType  { get; }
+		
+		public abstract TypeKind Kind { get; }
+		
+		public virtual int TypeParameterCount {
+			get { return 0; }
+		}
+
+		readonly static IList<IType> emptyTypeArguments = new IType[0];
+		public virtual IList<IType> TypeArguments {
+			get { return emptyTypeArguments; }
+		}
+
+		public virtual IType DeclaringType {
+			get { return null; }
+		}
+
+		public virtual bool IsParameterized { 
+			get { return false; }
+		}
+
+		public virtual ITypeDefinition GetDefinition()
+		{
+			return null;
+		}
+		
+		public virtual IEnumerable<IType> DirectBaseTypes {
+			get { return EmptyList<IType>.Instance; }
+		}
+		
+		public abstract ITypeReference ToTypeReference();
+		
+		public virtual IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IType>.Instance;
+		}
+		
+		public virtual IEnumerable<IType> GetNestedTypes(IList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IType>.Instance;
+		}
+		
+		public virtual IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public virtual IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public virtual IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public virtual IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IProperty>.Instance;
+		}
+		
+		public virtual IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IField>.Instance;
+		}
+		
+		public virtual IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IEvent>.Instance;
+		}
+		
+		public virtual IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			IEnumerable<IMember> members = GetMethods(filter, options);
+			return members
+				.Concat(GetProperties(filter, options))
+				.Concat(GetFields(filter, options))
+				.Concat(GetEvents(filter, options));
+		}
+		
+		public virtual IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public TypeParameterSubstitution GetSubstitution()
+		{
+			return TypeParameterSubstitution.Identity;
+		}
+		
+		public TypeParameterSubstitution GetSubstitution(IList<IType> methodTypeArguments)
+		{
+			return TypeParameterSubstitution.Identity;
+		}
+
+		public override sealed bool Equals(object obj)
+		{
+			return Equals(obj as IType);
+		}
+		
+		public override int GetHashCode()
+		{
+			return base.GetHashCode();
+		}
+		
+		public virtual bool Equals(IType other)
+		{
+			return this == other; // use reference equality by default
+		}
+		
+		public override string ToString()
+		{
+			return this.ReflectionName;
+		}
+		
+		public virtual IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitOtherType(this);
+		}
+		
+		public virtual IType VisitChildren(TypeVisitor visitor)
+		{
+			return this;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractUnresolvedEntity.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractUnresolvedEntity.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractUnresolvedEntity.cs	(revision 11807)
@@ -0,0 +1,334 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Base class for <see cref="IUnresolvedEntity"/> implementations.
+	/// </summary>
+	[Serializable]
+	public abstract class AbstractUnresolvedEntity : IUnresolvedEntity, IFreezable
+	{
+		// possible optimizations to reduce the memory usage of AbstractUnresolvedEntity:
+		// - store regions in more compact form (e.g. assume both file names are identical; use ushort for columns)
+		
+		IUnresolvedTypeDefinition declaringTypeDefinition;
+		
+		string name = string.Empty;
+		IList<IUnresolvedAttribute> attributes;
+		internal RareFields rareFields;
+		
+		// 1 byte per enum + 2 bytes for flags
+		SymbolKind symbolKind;
+		Accessibility accessibility;
+		internal BitVector16 flags;
+		
+		// flags for AbstractUnresolvedEntity:
+		internal const ushort FlagFrozen    = 0x0001;
+		internal const ushort FlagSealed    = 0x0002;
+		internal const ushort FlagAbstract  = 0x0004;
+		internal const ushort FlagShadowing = 0x0008;
+		internal const ushort FlagSynthetic = 0x0010;
+		internal const ushort FlagStatic    = 0x0020;
+		// flags for DefaultUnresolvedTypeDefinition/LazyCecilTypeDefinition
+		internal const ushort FlagAddDefaultConstructorIfRequired = 0x0040;
+		internal const ushort FlagHasExtensionMethods = 0x0080;
+		internal const ushort FlagHasNoExtensionMethods = 0x0100;
+		internal const ushort FlagPartialTypeDefinition = 0x0200;
+		// flags for AbstractUnresolvedMember:
+		internal const ushort FlagExplicitInterfaceImplementation = 0x0040;
+		internal const ushort FlagVirtual = 0x0080;
+		internal const ushort FlagOverride = 0x0100;
+		// flags for DefaultField:
+		internal const ushort FlagFieldIsReadOnly = 0x1000;
+		internal const ushort FlagFieldIsVolatile = 0x2000;
+		internal const ushort FlagFieldIsFixedSize = 0x4000;
+		// flags for DefaultMethod:
+		internal const ushort FlagExtensionMethod = 0x1000;
+		internal const ushort FlagPartialMethod = 0x2000;
+		internal const ushort FlagHasBody = 0x4000;
+		internal const ushort FlagAsyncMethod = 0x8000;
+		
+		public bool IsFrozen {
+			get { return flags[FlagFrozen]; }
+		}
+		
+		public void Freeze()
+		{
+			if (!flags[FlagFrozen]) {
+				FreezeInternal();
+				flags[FlagFrozen] = true;
+			}
+		}
+		
+		protected virtual void FreezeInternal()
+		{
+			attributes = FreezableHelper.FreezeListAndElements(attributes);
+			if (rareFields != null)
+				rareFields.FreezeInternal();
+		}
+		
+		/// <summary>
+		/// Uses the specified interning provider to intern
+		/// strings and lists in this entity.
+		/// This method does not test arbitrary objects to see if they implement ISupportsInterning;
+		/// instead we assume that those are interned immediately when they are created (before they are added to this entity).
+		/// </summary>
+		public virtual void ApplyInterningProvider(InterningProvider provider)
+		{
+			if (provider == null)
+				throw new ArgumentNullException("provider");
+			ThrowIfFrozen();
+			name = provider.Intern(name);
+			attributes = provider.InternList(attributes);
+			if (rareFields != null)
+				rareFields.ApplyInterningProvider(provider);
+		}
+		
+		/// <summary>
+		/// Creates a shallow clone of this entity.
+		/// Collections (e.g. a type's member list) will be cloned as well, but the elements
+		/// of said list will not be.
+		/// If this instance is frozen, the clone will be unfrozen.
+		/// </summary>
+		public virtual object Clone()
+		{
+			var copy = (AbstractUnresolvedEntity)MemberwiseClone();
+			copy.flags[FlagFrozen] = false;
+			if (attributes != null)
+				copy.attributes = new List<IUnresolvedAttribute>(attributes);
+			if (rareFields != null)
+				copy.rareFields = (RareFields)rareFields.Clone();
+			return copy;
+		}
+		
+		[Serializable]
+		internal class RareFields
+		{
+			internal DomRegion region;
+			internal DomRegion bodyRegion;
+			internal IUnresolvedFile unresolvedFile;
+			
+			protected internal virtual void FreezeInternal()
+			{
+			}
+			
+			public virtual void ApplyInterningProvider(InterningProvider provider)
+			{
+			}
+			
+			public virtual object Clone()
+			{
+				return MemberwiseClone();
+			}
+		}
+		
+		protected void ThrowIfFrozen()
+		{
+			FreezableHelper.ThrowIfFrozen(this);
+		}
+		
+		public SymbolKind SymbolKind {
+			get { return symbolKind; }
+			set {
+				ThrowIfFrozen();
+				symbolKind = value;
+			}
+		}
+		
+		internal virtual RareFields WriteRareFields()
+		{
+			ThrowIfFrozen();
+			if (rareFields == null) rareFields = new RareFields();
+			return rareFields;
+		}
+		
+		public DomRegion Region {
+			get { return rareFields != null ? rareFields.region : DomRegion.Empty; }
+			set {
+				if (value != DomRegion.Empty || rareFields != null)
+					WriteRareFields().region = value;
+			}
+		}
+		
+		public DomRegion BodyRegion {
+			get { return rareFields != null ? rareFields.bodyRegion : DomRegion.Empty; }
+			set {
+				if (value != DomRegion.Empty || rareFields != null)
+					WriteRareFields().bodyRegion = value;
+			}
+		}
+		
+		public IUnresolvedFile UnresolvedFile {
+			get { return rareFields != null ? rareFields.unresolvedFile : null; }
+			set {
+				if (value != null || rareFields != null)
+					WriteRareFields().unresolvedFile = value;
+			}
+		}
+		
+		public IUnresolvedTypeDefinition DeclaringTypeDefinition {
+			get { return declaringTypeDefinition; }
+			set {
+				ThrowIfFrozen();
+				declaringTypeDefinition = value;
+			}
+		}
+		
+		public IList<IUnresolvedAttribute> Attributes {
+			get {
+				if (attributes == null)
+					attributes = new List<IUnresolvedAttribute>();
+				return attributes;
+			}
+		}
+		
+		public string Name {
+			get { return name; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				ThrowIfFrozen();
+				name = value;
+			}
+		}
+		
+		public virtual string FullName {
+			get {
+				if (declaringTypeDefinition != null)
+					return declaringTypeDefinition.FullName + "." + name;
+				else if (!string.IsNullOrEmpty(this.Namespace))
+					return this.Namespace + "." + name;
+				else
+					return name;
+			}
+		}
+		
+		public virtual string Namespace {
+			get {
+				if (declaringTypeDefinition != null)
+					return declaringTypeDefinition.Namespace;
+				else
+					return string.Empty;
+			}
+			set {
+				throw new NotSupportedException();
+			}
+		}
+		
+		public virtual string ReflectionName {
+			get {
+				if (declaringTypeDefinition != null)
+					return declaringTypeDefinition.ReflectionName + "." + name;
+				else
+					return name;
+			}
+		}
+		
+		public Accessibility Accessibility {
+			get { return accessibility; }
+			set {
+				ThrowIfFrozen();
+				accessibility = value;
+			}
+		}
+		
+		public bool IsStatic {
+			get { return flags[FlagStatic]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagStatic] = value;
+			}
+		}
+		
+		public bool IsAbstract {
+			get { return flags[FlagAbstract]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagAbstract] = value;
+			}
+		}
+		
+		public bool IsSealed {
+			get { return flags[FlagSealed]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagSealed] = value;
+			}
+		}
+		
+		public bool IsShadowing {
+			get { return flags[FlagShadowing]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagShadowing] = value;
+			}
+		}
+		
+		public bool IsSynthetic {
+			get { return flags[FlagSynthetic]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagSynthetic] = value;
+			}
+		}
+		
+		bool IHasAccessibility.IsPrivate {
+			get { return accessibility == Accessibility.Private; }
+		}
+		
+		bool IHasAccessibility.IsPublic {
+			get { return accessibility == Accessibility.Public; }
+		}
+		
+		bool IHasAccessibility.IsProtected {
+			get { return accessibility == Accessibility.Protected; }
+		}
+		
+		bool IHasAccessibility.IsInternal {
+			get { return accessibility == Accessibility.Internal; }
+		}
+		
+		bool IHasAccessibility.IsProtectedOrInternal {
+			get { return accessibility == Accessibility.ProtectedOrInternal; }
+		}
+		
+		bool IHasAccessibility.IsProtectedAndInternal {
+			get { return accessibility == Accessibility.ProtectedAndInternal; }
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[");
+			b.Append(GetType().Name);
+			b.Append(' ');
+			if (this.DeclaringTypeDefinition != null) {
+				b.Append(this.DeclaringTypeDefinition.Name);
+				b.Append('.');
+			}
+			b.Append(this.Name);
+			b.Append(']');
+			return b.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractUnresolvedMember.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractUnresolvedMember.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AbstractUnresolvedMember.cs	(revision 11807)
@@ -0,0 +1,272 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Base class for <see cref="IUnresolvedMember"/> implementations.
+	/// </summary>
+	[Serializable]
+	public abstract class AbstractUnresolvedMember : AbstractUnresolvedEntity, IUnresolvedMember
+	{
+		ITypeReference returnType = SpecialType.UnknownType;
+		IList<IMemberReference> interfaceImplementations;
+		
+		public override void ApplyInterningProvider(InterningProvider provider)
+		{
+			base.ApplyInterningProvider(provider);
+			interfaceImplementations = provider.InternList(interfaceImplementations);
+		}
+		
+		protected override void FreezeInternal()
+		{
+			base.FreezeInternal();
+			interfaceImplementations = FreezableHelper.FreezeList(interfaceImplementations);
+		}
+		
+		public override object Clone()
+		{
+			var copy = (AbstractUnresolvedMember)base.Clone();
+			if (interfaceImplementations != null)
+				copy.interfaceImplementations = new List<IMemberReference>(interfaceImplementations);
+			return copy;
+		}
+		
+		/*
+		[Serializable]
+		internal new class RareFields : AbstractUnresolvedEntity.RareFields
+		{
+			internal IList<IMemberReference> interfaceImplementations;
+			
+			public override void ApplyInterningProvider(IInterningProvider provider)
+			{
+				base.ApplyInterningProvider(provider);
+				interfaceImplementations = provider.InternList(interfaceImplementations);
+			}
+			
+			protected internal override void FreezeInternal()
+			{
+				interfaceImplementations = FreezableHelper.FreezeListAndElements(interfaceImplementations);
+				base.FreezeInternal();
+			}
+			
+			override Clone(){}
+		}
+		
+		internal override AbstractUnresolvedEntity.RareFields WriteRareFields()
+		{
+			ThrowIfFrozen();
+			if (rareFields == null) rareFields = new RareFields();
+			return rareFields;
+		}*/
+		
+		public ITypeReference ReturnType {
+			get { return returnType; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				ThrowIfFrozen();
+				returnType = value;
+			}
+		}
+		
+		public bool IsExplicitInterfaceImplementation {
+			get { return flags[FlagExplicitInterfaceImplementation]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagExplicitInterfaceImplementation] = value;
+			}
+		}
+		
+		public IList<IMemberReference> ExplicitInterfaceImplementations {
+			get {
+				/*
+				RareFields rareFields = (RareFields)this.rareFields;
+				if (rareFields == null || rareFields.interfaceImplementations == null) {
+					rareFields = (RareFields)WriteRareFields();
+					return rareFields.interfaceImplementations = new List<IMemberReference>();
+				}
+				return rareFields.interfaceImplementations;
+				*/
+				if (interfaceImplementations == null)
+					interfaceImplementations = new List<IMemberReference>();
+				return interfaceImplementations;
+			}
+		}
+		
+		public bool IsVirtual {
+			get { return flags[FlagVirtual]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagVirtual] = value;
+			}
+		}
+		
+		public bool IsOverride {
+			get { return flags[FlagOverride]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagOverride] = value;
+			}
+		}
+		
+		public bool IsOverridable {
+			get {
+				// override or virtual or abstract but not sealed
+				return (flags.Data & (FlagOverride | FlagVirtual | FlagAbstract)) != 0 && !this.IsSealed;
+			}
+		}
+		
+		ITypeReference IMemberReference.DeclaringTypeReference {
+			get { return this.DeclaringTypeDefinition; }
+		}
+		
+		#region Resolve
+		public abstract IMember CreateResolved(ITypeResolveContext context);
+		
+		public virtual IMember Resolve(ITypeResolveContext context)
+		{
+			ITypeReference interfaceTypeReference = null;
+			if (this.IsExplicitInterfaceImplementation && this.ExplicitInterfaceImplementations.Count == 1)
+				interfaceTypeReference = this.ExplicitInterfaceImplementations[0].DeclaringTypeReference;
+			return Resolve(ExtendContextForType(context, this.DeclaringTypeDefinition), this.SymbolKind, this.Name, interfaceTypeReference);
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return ((IUnresolvedMember)this).Resolve(context);
+		}
+		
+		protected static ITypeResolveContext ExtendContextForType(ITypeResolveContext assemblyContext, IUnresolvedTypeDefinition typeDef)
+		{
+			if (typeDef == null)
+				return assemblyContext;
+			ITypeResolveContext parentContext;
+			if (typeDef.DeclaringTypeDefinition != null)
+				parentContext = ExtendContextForType(assemblyContext, typeDef.DeclaringTypeDefinition);
+			else
+				parentContext = assemblyContext;
+			ITypeDefinition resolvedTypeDef = typeDef.Resolve(assemblyContext).GetDefinition();
+			return typeDef.CreateResolveContext(parentContext).WithCurrentTypeDefinition(resolvedTypeDef);
+		}
+		
+		public static IMember Resolve(ITypeResolveContext context,
+		                              SymbolKind symbolKind,
+		                              string name,
+		                              ITypeReference explicitInterfaceTypeReference = null,
+		                              IList<string> typeParameterNames = null,
+		                              IList<ITypeReference> parameterTypeReferences = null)
+		{
+			if (context.CurrentTypeDefinition == null)
+				return null;
+			if (parameterTypeReferences == null)
+				parameterTypeReferences = EmptyList<ITypeReference>.Instance;
+			if (typeParameterNames == null || typeParameterNames.Count == 0) {
+				// non-generic member
+				// In this case, we can simply resolve the parameter types in the given context
+				var parameterTypes = parameterTypeReferences.Resolve(context);
+				if (explicitInterfaceTypeReference == null) {
+					foreach (IMember member in context.CurrentTypeDefinition.Members) {
+						if (member.IsExplicitInterfaceImplementation)
+							continue;
+						if (IsNonGenericMatch(member, symbolKind, name, parameterTypes))
+							return member;
+					}
+				} else {
+					IType explicitInterfaceType = explicitInterfaceTypeReference.Resolve(context);
+					foreach (IMember member in context.CurrentTypeDefinition.Members) {
+						if (!member.IsExplicitInterfaceImplementation)
+							continue;
+						if (member.ImplementedInterfaceMembers.Count != 1)
+							continue;
+						if (IsNonGenericMatch(member, symbolKind, name, parameterTypes)) {
+							if (explicitInterfaceType.Equals(member.ImplementedInterfaceMembers[0].DeclaringType))
+								return member;
+						}
+					}
+				}
+			} else {
+				// generic member
+				// In this case, we must specify the correct context for resolving the parameter types
+				foreach (IMethod method in context.CurrentTypeDefinition.Methods) {
+					if (method.SymbolKind != symbolKind)
+						continue;
+					if (method.Name != name)
+						continue;
+					if (method.Parameters.Count != parameterTypeReferences.Count)
+						continue;
+					// Compare type parameter count and names:
+					if (!typeParameterNames.SequenceEqual(method.TypeParameters.Select(tp => tp.Name)))
+						continue;
+					// Once we know the type parameter names are fitting, we can resolve the
+					// type references in the context of the method:
+					var contextForMethod = context.WithCurrentMember(method);
+					var parameterTypes = parameterTypeReferences.Resolve(contextForMethod);
+					if (!IsParameterTypeMatch(method, parameterTypes))
+						continue;
+					if (explicitInterfaceTypeReference == null) {
+						if (!method.IsExplicitInterfaceImplementation)
+							return method;
+					} else if (method.IsExplicitInterfaceImplementation && method.ImplementedInterfaceMembers.Count == 1) {
+						IType explicitInterfaceType = explicitInterfaceTypeReference.Resolve(contextForMethod);
+						if (explicitInterfaceType.Equals(method.ImplementedInterfaceMembers[0].DeclaringType))
+							return method;
+					}
+				}
+			}
+			return null;
+		}
+		
+		static bool IsNonGenericMatch(IMember member, SymbolKind symbolKind, string name, IList<IType> parameterTypes)
+		{
+			if (member.SymbolKind != symbolKind)
+				return false;
+			if (member.Name != name)
+				return false;
+			IMethod method = member as IMethod;
+			if (method != null && method.TypeParameters.Count > 0)
+				return false;
+			return IsParameterTypeMatch(member, parameterTypes);
+		}
+		
+		static bool IsParameterTypeMatch(IMember member, IList<IType> parameterTypes)
+		{
+			IParameterizedMember parameterizedMember = member as IParameterizedMember;
+			if (parameterizedMember == null) {
+				return parameterTypes.Count == 0;
+			} else if (parameterTypes.Count == parameterizedMember.Parameters.Count) {
+				for (int i = 0; i < parameterTypes.Count; i++) {
+					IType type1 = parameterTypes[i];
+					IType type2 = parameterizedMember.Parameters[i].Type;
+					if (!type1.Equals(type2)) {
+						return false;
+					}
+				}
+				return true;
+			} else {
+				return false;
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AccessorOwnerMemberReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AccessorOwnerMemberReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/AccessorOwnerMemberReference.cs	(revision 11807)
@@ -0,0 +1,56 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Given a reference to an accessor, returns the accessor's owner.
+	/// </summary>
+	[Serializable]
+	sealed class AccessorOwnerMemberReference : IMemberReference
+	{
+		readonly IMemberReference accessorReference;
+		
+		public AccessorOwnerMemberReference(IMemberReference accessorReference)
+		{
+			if (accessorReference == null)
+				throw new ArgumentNullException("accessorReference");
+			this.accessorReference = accessorReference;
+		}
+		
+		public ITypeReference DeclaringTypeReference {
+			get { return accessorReference.DeclaringTypeReference; }
+		}
+		
+		public IMember Resolve(ITypeResolveContext context)
+		{
+			IMethod method = accessorReference.Resolve(context) as IMethod;
+			if (method != null)
+				return method.AccessorOwner;
+			else
+				return null;
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return ((IMemberReference)this).Resolve(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/BaseTypeCollector.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/BaseTypeCollector.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/BaseTypeCollector.cs	(revision 11807)
@@ -0,0 +1,75 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Helper class for the GetAllBaseTypes() implementation.
+	/// </summary>
+	sealed class BaseTypeCollector : List<IType>
+	{
+		readonly Stack<IType> activeTypes = new Stack<IType>();
+		
+		/// <summary>
+		/// If this option is enabled, the list will not contain interfaces when retrieving the base types
+		/// of a class.
+		/// </summary>
+		internal bool SkipImplementedInterfaces;
+		
+		public void CollectBaseTypes(IType type)
+		{
+			IType def = type.GetDefinition() ?? type;
+			
+			// Maintain a stack of currently active type definitions, and avoid having one definition
+			// multiple times on that stack.
+			// This is necessary to ensure the output is finite in the presence of cyclic inheritance:
+			// class C<X> : C<C<X>> {} would not be caught by the 'no duplicate output' check, yet would
+			// produce infinite output.
+			if (activeTypes.Contains(def))
+				return;
+			activeTypes.Push(def);
+			// Note that we also need to push non-type definitions, e.g. for protecting against
+			// cyclic inheritance in type parameters (where T : S where S : T).
+			// The output check doesn't help there because we call Add(type) only at the end.
+			// We can't simply call this.Add(type); at the start because that would return in an incorrect order.
+			
+			// Avoid outputting a type more than once - necessary for "diamond" multiple inheritance
+			// (e.g. C implements I1 and I2, and both interfaces derive from Object)
+			if (!this.Contains(type)) {
+				foreach (IType baseType in type.DirectBaseTypes) {
+					if (SkipImplementedInterfaces && def != null && def.Kind != TypeKind.Interface && def.Kind != TypeKind.TypeParameter) {
+						if (baseType.Kind == TypeKind.Interface) {
+							// skip the interface
+							continue;
+						}
+					}
+					CollectBaseTypes(baseType);
+				}
+				// Add(type) at the end - we want a type to be output only after all its base types were added.
+				this.Add(type);
+				// Note that this is not the same as putting the this.Add() call in front and then reversing the list.
+				// For the diamond inheritance, Add() at the start produces "C, I1, Object, I2",
+				// while Add() at the end produces "Object, I1, I2, C".
+			}
+			activeTypes.Pop();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/BlobReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/BlobReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/BlobReader.cs	(revision 11807)
@@ -0,0 +1,387 @@
+﻿//
+// BlobReader.cs
+//
+// Author:
+//       Daniel Grunwald <daniel@danielgrunwald.de>
+//
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	sealed class BlobReader
+	{
+		internal static int GetBlobHashCode(byte[] blob)
+		{
+			unchecked {
+				int hash = 0;
+				foreach (byte b in blob) {
+					hash *= 257;
+					hash += b;
+				}
+				return hash;
+			}
+		}
+		
+		internal static bool BlobEquals(byte[] a, byte[] b)
+		{
+			if (a.Length != b.Length)
+				return false;
+			for (int i = 0; i < a.Length; i++) {
+				if (a[i] != b[i])
+					return false;
+			}
+			return true;
+		}
+		
+		byte[] buffer;
+		int position;
+		readonly IAssembly currentResolvedAssembly;
+
+		public BlobReader(byte[] buffer, IAssembly currentResolvedAssembly)
+		{
+			if (buffer == null)
+				throw new ArgumentNullException("buffer");
+			this.buffer = buffer;
+			this.currentResolvedAssembly = currentResolvedAssembly;
+		}
+		
+		public byte ReadByte()
+		{
+			return buffer[position++];
+		}
+
+		public sbyte ReadSByte()
+		{
+			unchecked {
+				return(sbyte) ReadByte();
+			}
+		}
+		
+		public byte[] ReadBytes(int length)
+		{
+			var bytes = new byte[length];
+			Buffer.BlockCopy(buffer, position, bytes, 0, length);
+			position += length;
+			return bytes;
+		}
+
+		public ushort ReadUInt16()
+		{
+			unchecked {
+				ushort value =(ushort)(buffer[position]
+				                       |(buffer[position + 1] << 8));
+				position += 2;
+				return value;
+			}
+		}
+
+		public short ReadInt16()
+		{
+			unchecked {
+				return(short) ReadUInt16();
+			}
+		}
+
+		public uint ReadUInt32()
+		{
+			unchecked {
+				uint value =(uint)(buffer[position]
+				                   |(buffer[position + 1] << 8)
+				                   |(buffer[position + 2] << 16)
+				                   |(buffer[position + 3] << 24));
+				position += 4;
+				return value;
+			}
+		}
+
+		public int ReadInt32()
+		{
+			unchecked {
+				return(int) ReadUInt32();
+			}
+		}
+
+		public ulong ReadUInt64()
+		{
+			unchecked {
+				uint low = ReadUInt32();
+				uint high = ReadUInt32();
+
+				return(((ulong) high) << 32) | low;
+			}
+		}
+
+		public long ReadInt64()
+		{
+			unchecked {
+				return(long) ReadUInt64();
+			}
+		}
+
+		public uint ReadCompressedUInt32()
+		{
+			unchecked {
+				byte first = ReadByte();
+				if((first & 0x80) == 0)
+					return first;
+
+				if((first & 0x40) == 0)
+					return((uint)(first & ~0x80) << 8)
+						| ReadByte();
+
+				return((uint)(first & ~0xc0) << 24)
+					|(uint) ReadByte() << 16
+					|(uint) ReadByte() << 8
+					| ReadByte();
+			}
+		}
+
+		public float ReadSingle()
+		{
+			unchecked {
+				if(!BitConverter.IsLittleEndian) {
+					var bytes = ReadBytes(4);
+					Array.Reverse(bytes);
+					return BitConverter.ToSingle(bytes, 0);
+				}
+
+				float value = BitConverter.ToSingle(buffer, position);
+				position += 4;
+				return value;
+			}
+		}
+
+		public double ReadDouble()
+		{
+			unchecked {
+				if(!BitConverter.IsLittleEndian) {
+					var bytes = ReadBytes(8);
+					Array.Reverse(bytes);
+					return BitConverter.ToDouble(bytes, 0);
+				}
+
+				double value = BitConverter.ToDouble(buffer, position);
+				position += 8;
+				return value;
+			}
+		}
+		
+		public ResolveResult ReadFixedArg(IType argType)
+		{
+			if (argType.Kind == TypeKind.Array) {
+				if (((ArrayType)argType).Dimensions != 1) {
+					// Only single-dimensional arrays are supported
+					return ErrorResolveResult.UnknownError;
+				}
+				IType elementType = ((ArrayType)argType).ElementType;
+				uint numElem = ReadUInt32();
+				if (numElem == 0xffffffff) {
+					// null reference
+					return new ConstantResolveResult(argType, null);
+				} else {
+					ResolveResult[] elements = new ResolveResult[numElem];
+					for (int i = 0; i < elements.Length; i++) {
+						elements[i] = ReadElem(elementType);
+						// Stop decoding when encountering an error:
+						if (elements[i].IsError)
+							return ErrorResolveResult.UnknownError;
+					}
+					IType int32 = currentResolvedAssembly.Compilation.FindType(KnownTypeCode.Int32);
+					ResolveResult[] sizeArgs = { new ConstantResolveResult(int32, elements.Length) };
+					return new ArrayCreateResolveResult(argType, sizeArgs, elements);
+				}
+			} else {
+				return ReadElem(argType);
+			}
+		}
+		
+		public ResolveResult ReadElem(IType elementType)
+		{
+			ITypeDefinition underlyingType;
+			if (elementType.Kind == TypeKind.Enum) {
+				underlyingType = elementType.GetDefinition().EnumUnderlyingType.GetDefinition();
+			} else {
+				underlyingType = elementType.GetDefinition();
+			}
+			if (underlyingType == null)
+				return ErrorResolveResult.UnknownError;
+			KnownTypeCode typeCode = underlyingType.KnownTypeCode;
+			if (typeCode == KnownTypeCode.Object) {
+				// boxed value type
+				IType boxedTyped = ReadCustomAttributeFieldOrPropType();
+				ResolveResult elem = ReadElem(boxedTyped);
+				if (elem.IsCompileTimeConstant && elem.ConstantValue == null)
+					return new ConstantResolveResult(elementType, null);
+				else
+					return new ConversionResolveResult(elementType, elem, Conversion.BoxingConversion);
+			} else if (typeCode == KnownTypeCode.Type) {
+				return new TypeOfResolveResult(underlyingType, ReadType());
+			} else {
+				return new ConstantResolveResult(elementType, ReadElemValue(typeCode));
+			}
+		}
+		
+		object ReadElemValue(KnownTypeCode typeCode)
+		{
+			switch (typeCode) {
+				case KnownTypeCode.Boolean:
+					return ReadByte() != 0;
+				case KnownTypeCode.Char:
+					return (char)ReadUInt16();
+				case KnownTypeCode.SByte:
+					return ReadSByte();
+				case KnownTypeCode.Byte:
+					return ReadByte();
+				case KnownTypeCode.Int16:
+					return ReadInt16();
+				case KnownTypeCode.UInt16:
+					return ReadUInt16();
+				case KnownTypeCode.Int32:
+					return ReadInt32();
+				case KnownTypeCode.UInt32:
+					return ReadUInt32();
+				case KnownTypeCode.Int64:
+					return ReadInt64();
+				case KnownTypeCode.UInt64:
+					return ReadUInt64();
+				case KnownTypeCode.Single:
+					return ReadSingle();
+				case KnownTypeCode.Double:
+					return ReadDouble();
+				case KnownTypeCode.String:
+					return ReadSerString();
+				default:
+					throw new NotSupportedException();
+			}
+		}
+		
+		public string ReadSerString ()
+		{
+			if (buffer [position] == 0xff) {
+				position++;
+				return null;
+			}
+
+			int length = (int) ReadCompressedUInt32();
+			if (length == 0)
+				return string.Empty;
+
+			string @string = System.Text.Encoding.UTF8.GetString(
+				buffer, position,
+				buffer [position + length - 1] == 0 ? length - 1 : length);
+
+			position += length;
+			return @string;
+		}
+		
+		public KeyValuePair<IMember, ResolveResult> ReadNamedArg(IType attributeType)
+		{
+			SymbolKind memberType;
+			var b = ReadByte();
+			switch (b) {
+				case 0x53:
+					memberType = SymbolKind.Field;
+					break;
+				case 0x54:
+					memberType = SymbolKind.Property;
+					break;
+				default:
+					throw new NotSupportedException(string.Format("Custom member type 0x{0:x} is not supported.", b));
+			}
+			IType type = ReadCustomAttributeFieldOrPropType();
+			string name = ReadSerString();
+			ResolveResult val = ReadFixedArg(type);
+			IMember member = null;
+			// Use last matching member, as GetMembers() returns members from base types first.
+			foreach (IMember m in attributeType.GetMembers(m => m.SymbolKind == memberType && m.Name == name)) {
+				if (m.ReturnType.Equals(type))
+					member = m;
+			}
+			return new KeyValuePair<IMember, ResolveResult>(member, val);
+		}
+
+		IType ReadCustomAttributeFieldOrPropType()
+		{
+			ICompilation compilation = currentResolvedAssembly.Compilation;
+			var b = ReadByte();
+			switch (b) {
+				case 0x02:
+					return compilation.FindType(KnownTypeCode.Boolean);
+				case 0x03:
+					return compilation.FindType(KnownTypeCode.Char);
+				case 0x04:
+					return compilation.FindType(KnownTypeCode.SByte);
+				case 0x05:
+					return compilation.FindType(KnownTypeCode.Byte);
+				case 0x06:
+					return compilation.FindType(KnownTypeCode.Int16);
+				case 0x07:
+					return compilation.FindType(KnownTypeCode.UInt16);
+				case 0x08:
+					return compilation.FindType(KnownTypeCode.Int32);
+				case 0x09:
+					return compilation.FindType(KnownTypeCode.UInt32);
+				case 0x0a:
+					return compilation.FindType(KnownTypeCode.Int64);
+				case 0x0b:
+					return compilation.FindType(KnownTypeCode.UInt64);
+				case 0x0c:
+					return compilation.FindType(KnownTypeCode.Single);
+				case 0x0d:
+					return compilation.FindType(KnownTypeCode.Double);
+				case 0x0e:
+					return compilation.FindType(KnownTypeCode.String);
+				case 0x1d:
+					return new ArrayType(compilation, ReadCustomAttributeFieldOrPropType());
+				case 0x50:
+					return compilation.FindType(KnownTypeCode.Type);
+				case 0x51: // boxed value type
+					return compilation.FindType(KnownTypeCode.Object);
+				case 0x55: // enum
+					return ReadType();
+				default:
+					throw new NotSupportedException(string.Format("Custom attribute type 0x{0:x} is not supported.", b));
+			}
+		}
+		
+		IType ReadType()
+		{
+			string typeName = ReadSerString();
+			ITypeReference typeReference = ReflectionHelper.ParseReflectionName(typeName);
+			IType typeInCurrentAssembly = typeReference.Resolve(new SimpleTypeResolveContext(currentResolvedAssembly));
+			if (typeInCurrentAssembly.Kind != TypeKind.Unknown)
+				return typeInCurrentAssembly;
+			
+			// look for the type in mscorlib
+			ITypeDefinition systemObject = currentResolvedAssembly.Compilation.FindType(KnownTypeCode.Object).GetDefinition();
+			if (systemObject != null) {
+				return typeReference.Resolve(new SimpleTypeResolveContext(systemObject.ParentAssembly));
+			} else {
+				// couldn't find corlib - return the unknown IType for the current assembly
+				return typeInCurrentAssembly;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultAssemblyReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultAssemblyReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultAssemblyReference.cs	(revision 11807)
@@ -0,0 +1,87 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// References an existing assembly by name.
+	/// </summary>
+	[Serializable]
+	public sealed class DefaultAssemblyReference : IAssemblyReference, ISupportsInterning
+	{
+		public static readonly IAssemblyReference CurrentAssembly = new CurrentAssemblyReference();
+		
+		[Obsolete("The corlib is not always called 'mscorlib' (as returned by this property), but might be 'System.Runtime'.")]
+		public static readonly IAssemblyReference Corlib = new DefaultAssemblyReference("mscorlib");
+		
+		readonly string shortName;
+		
+		public DefaultAssemblyReference(string assemblyName)
+		{
+			int pos = assemblyName != null ? assemblyName.IndexOf(',') : -1;
+			if (pos >= 0)
+				shortName = assemblyName.Substring(0, pos);
+			else
+				shortName = assemblyName;
+		}
+		
+		public IAssembly Resolve(ITypeResolveContext context)
+		{
+			IAssembly current = context.CurrentAssembly;
+			if (current != null && string.Equals(shortName, current.AssemblyName, StringComparison.OrdinalIgnoreCase))
+				return current;
+			foreach (IAssembly asm in context.Compilation.Assemblies) {
+				if (string.Equals(shortName, asm.AssemblyName, StringComparison.OrdinalIgnoreCase))
+					return asm;
+			}
+			return null;
+		}
+		
+		public override string ToString()
+		{
+			return shortName;
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				return shortName.GetHashCode();
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			DefaultAssemblyReference o = other as DefaultAssemblyReference;
+			return o != null && shortName == o.shortName;
+		}
+		
+		[Serializable]
+		sealed class CurrentAssemblyReference : IAssemblyReference
+		{
+			public IAssembly Resolve(ITypeResolveContext context)
+			{
+				IAssembly asm = context.CurrentAssembly;
+				if (asm == null)
+					throw new ArgumentException("A reference to the current assembly cannot be resolved in the compilation's global type resolve context.");
+				return asm;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultAttribute.cs	(revision 11807)
@@ -0,0 +1,97 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// IAttribute implementation for already-resolved attributes.
+	/// </summary>
+	public class DefaultAttribute : IAttribute
+	{
+		readonly IType attributeType;
+		readonly IList<ResolveResult> positionalArguments;
+		readonly IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
+		readonly DomRegion region;
+		volatile IMethod constructor;
+		
+		public DefaultAttribute(IType attributeType, IList<ResolveResult> positionalArguments = null,
+		                        IList<KeyValuePair<IMember, ResolveResult>> namedArguments = null,
+		                        DomRegion region = default(DomRegion))
+		{
+			if (attributeType == null)
+				throw new ArgumentNullException("attributeType");
+			this.attributeType = attributeType;
+			this.positionalArguments = positionalArguments ?? EmptyList<ResolveResult>.Instance;
+			this.namedArguments = namedArguments ?? EmptyList<KeyValuePair<IMember, ResolveResult>>.Instance;
+			this.region = region;
+		}
+		
+		public DefaultAttribute(IMethod constructor, IList<ResolveResult> positionalArguments = null,
+		                        IList<KeyValuePair<IMember, ResolveResult>> namedArguments = null,
+		                        DomRegion region = default(DomRegion))
+		{
+			if (constructor == null)
+				throw new ArgumentNullException("constructor");
+			this.constructor = constructor;
+			this.attributeType = constructor.DeclaringType;
+			this.positionalArguments = positionalArguments ?? EmptyList<ResolveResult>.Instance;
+			this.namedArguments = namedArguments ?? EmptyList<KeyValuePair<IMember, ResolveResult>>.Instance;
+			this.region = region;
+			if (this.positionalArguments.Count != constructor.Parameters.Count) {
+				throw new ArgumentException("Positional argument count must match the constructor's parameter count");
+			}
+		}
+		
+		public IType AttributeType {
+			get { return attributeType; }
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+		}
+		
+		public IMethod Constructor {
+			get {
+				IMethod ctor = this.constructor;
+				if (ctor == null) {
+					foreach (IMethod candidate in this.AttributeType.GetConstructors(m => m.Parameters.Count == positionalArguments.Count)) {
+						if (candidate.Parameters.Select(p => p.Type).SequenceEqual(this.PositionalArguments.Select(a => a.Type))) {
+							ctor = candidate;
+							break;
+						}
+					}
+					this.constructor = ctor;
+				}
+				return ctor;
+			}
+		}
+		
+		public IList<ResolveResult> PositionalArguments {
+			get { return positionalArguments; }
+		}
+		
+		public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments {
+			get { return namedArguments; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultMemberReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultMemberReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultMemberReference.cs	(revision 11807)
@@ -0,0 +1,118 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// References an entity by its type and name.
+	/// This class can be used to refer to all members except for constructors and explicit interface implementations.
+	/// </summary>
+	/// <remarks>
+	/// Resolving a DefaultMemberReference requires a context that provides enough information for resolving the declaring type reference
+	/// and the parameter types references.
+	/// </remarks>
+	[Serializable]
+	public sealed class DefaultMemberReference : IMemberReference, ISupportsInterning
+	{
+		readonly SymbolKind symbolKind;
+		readonly ITypeReference typeReference;
+		readonly string name;
+		readonly int typeParameterCount;
+		readonly IList<ITypeReference> parameterTypes;
+		
+		public DefaultMemberReference(SymbolKind symbolKind, ITypeReference typeReference, string name, int typeParameterCount = 0, IList<ITypeReference> parameterTypes = null)
+		{
+			if (typeReference == null)
+				throw new ArgumentNullException("typeReference");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			if (typeParameterCount != 0 && symbolKind != SymbolKind.Method)
+				throw new ArgumentException("Type parameter count > 0 is only supported for methods.");
+			this.symbolKind = symbolKind;
+			this.typeReference = typeReference;
+			this.name = name;
+			this.typeParameterCount = typeParameterCount;
+			this.parameterTypes = parameterTypes ?? EmptyList<ITypeReference>.Instance;
+		}
+		
+		public ITypeReference DeclaringTypeReference {
+			get { return typeReference; }
+		}
+		
+		public IMember Resolve(ITypeResolveContext context)
+		{
+			IType type = typeReference.Resolve(context);
+			IEnumerable<IMember> members;
+			if (symbolKind == SymbolKind.Accessor) {
+				members = type.GetAccessors(
+					m => m.Name == name && !m.IsExplicitInterfaceImplementation,
+					GetMemberOptions.IgnoreInheritedMembers);
+			} else if (symbolKind == SymbolKind.Method) {
+				members = type.GetMethods(
+					m => m.Name == name && m.SymbolKind == SymbolKind.Method
+					&& m.TypeParameters.Count == typeParameterCount && !m.IsExplicitInterfaceImplementation,
+					GetMemberOptions.IgnoreInheritedMembers);
+			} else {
+				members = type.GetMembers(
+					m => m.Name == name && m.SymbolKind == symbolKind && !m.IsExplicitInterfaceImplementation,
+					GetMemberOptions.IgnoreInheritedMembers);
+			}
+			var resolvedParameterTypes = parameterTypes.Resolve(context);
+			foreach (IMember member in members) {
+				IParameterizedMember parameterizedMember = member as IParameterizedMember;
+				if (parameterizedMember == null) {
+					if (parameterTypes.Count == 0)
+						return member;
+				} else if (parameterTypes.Count == parameterizedMember.Parameters.Count) {
+					bool signatureMatches = true;
+					for (int i = 0; i < parameterTypes.Count; i++) {
+						IType type1 = DummyTypeParameter.NormalizeAllTypeParameters(resolvedParameterTypes[i]);
+						IType type2 = DummyTypeParameter.NormalizeAllTypeParameters(parameterizedMember.Parameters[i].Type);
+						if (!type1.Equals(type2)) {
+							signatureMatches = false;
+							break;
+						}
+					}
+					if (signatureMatches)
+						return member;
+				}
+			}
+			return null;
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return ((IMemberReference)this).Resolve(context);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return (int)symbolKind ^ typeReference.GetHashCode() ^ name.GetHashCode() ^ parameterTypes.GetHashCode();
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			DefaultMemberReference o = other as DefaultMemberReference;
+			return o != null && symbolKind == o.symbolKind && typeReference == o.typeReference && name == o.name && parameterTypes == o.parameterTypes;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultParameter.cs	(revision 11807)
@@ -0,0 +1,202 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IParameter"/>.
+	/// </summary>
+	public sealed class DefaultParameter : IParameter
+	{
+		readonly IType type;
+		readonly string name;
+		readonly DomRegion region;
+		readonly IList<IAttribute> attributes;
+		readonly bool isRef, isOut, isParams, isOptional;
+		readonly object defaultValue;
+		readonly IParameterizedMember owner;
+		
+		public DefaultParameter(IType type, string name)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.type = type;
+			this.name = name;
+		}
+		
+		public DefaultParameter(IType type, string name, IParameterizedMember owner = null, DomRegion region = default(DomRegion), IList<IAttribute> attributes = null,
+		                        bool isRef = false, bool isOut = false, bool isParams = false, bool isOptional = false, object defaultValue = null)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.type = type;
+			this.name = name;
+			this.owner = owner;
+			this.region = region;
+			this.attributes = attributes;
+			this.isRef = isRef;
+			this.isOut = isOut;
+			this.isParams = isParams;
+			this.isOptional = isOptional;
+			this.defaultValue = defaultValue;
+		}
+		
+		SymbolKind ISymbol.SymbolKind {
+			get { return SymbolKind.Parameter; }
+		}
+		
+		public IParameterizedMember Owner {
+			get { return owner; }
+		}
+		
+		public IList<IAttribute> Attributes {
+			get { return attributes; }
+		}
+		
+		public bool IsRef {
+			get { return isRef; }
+		}
+		
+		public bool IsOut {
+			get { return isOut; }
+		}
+		
+		public bool IsParams {
+			get { return isParams; }
+		}
+		
+		public bool IsOptional {
+			get { return isOptional; }
+		}
+		
+		public string Name {
+			get { return name; }
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+		}
+		
+		public IType Type {
+			get { return type; }
+		}
+		
+		bool IVariable.IsConst {
+			get { return false; }
+		}
+		
+		public object ConstantValue {
+			get { return defaultValue; }
+		}
+		
+		public override string ToString()
+		{
+			return ToString(this);
+		}
+		
+		public static string ToString(IParameter parameter)
+		{
+			StringBuilder b = new StringBuilder();
+			if (parameter.IsRef)
+				b.Append("ref ");
+			if (parameter.IsOut)
+				b.Append("out ");
+			if (parameter.IsParams)
+				b.Append("params ");
+			b.Append(parameter.Name);
+			b.Append(':');
+			b.Append(parameter.Type.ReflectionName);
+			if (parameter.IsOptional) {
+				b.Append(" = ");
+				if (parameter.ConstantValue != null)
+					b.Append(parameter.ConstantValue.ToString());
+				else
+					b.Append("null");
+			}
+			return b.ToString();
+		}
+
+		public ISymbolReference ToReference()
+		{
+			if (owner == null)
+				return new ParameterReference(type.ToTypeReference(), name, region, isRef, isOut, isParams, isOptional, defaultValue);
+			return new OwnedParameterReference(owner.ToReference(), owner.Parameters.IndexOf(this));
+		}
+	}
+	
+	sealed class OwnedParameterReference : ISymbolReference
+	{
+		readonly IMemberReference memberReference;
+		readonly int index;
+		
+		public OwnedParameterReference(IMemberReference member, int index)
+		{
+			if (member == null)
+				throw new ArgumentNullException("member");
+			this.memberReference = member;
+			this.index = index;
+		}
+		
+		public ISymbol Resolve(ITypeResolveContext context)
+		{
+			IParameterizedMember member = memberReference.Resolve(context) as IParameterizedMember;
+			if (member != null && index >= 0 && index < member.Parameters.Count)
+				return member.Parameters[index];
+			else
+				return null;
+		}
+	}
+	
+	public sealed class ParameterReference : ISymbolReference
+	{
+		readonly ITypeReference type;
+		readonly string name;
+		readonly DomRegion region;
+		readonly bool isRef, isOut, isParams, isOptional;
+		readonly object defaultValue;
+		
+		public ParameterReference(ITypeReference type, string name, DomRegion region, bool isRef, bool isOut, bool isParams, bool isOptional, object defaultValue)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.type = type;
+			this.name = name;
+			this.region = region;
+			this.isRef = isRef;
+			this.isOut = isOut;
+			this.isParams = isParams;
+			this.isOptional = isOptional;
+			this.defaultValue = defaultValue;
+		}
+
+		public ISymbol Resolve(ITypeResolveContext context)
+		{
+			return new DefaultParameter(type.Resolve(context), name, region: region, isRef: isRef, isOut: isOut, isParams: isParams, isOptional: isOptional, defaultValue: defaultValue);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedEvent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedEvent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedEvent.cs	(revision 11807)
@@ -0,0 +1,69 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public class DefaultResolvedEvent : AbstractResolvedMember, IEvent
+	{
+		protected new readonly IUnresolvedEvent unresolved;
+		IMethod addAccessor;
+		IMethod removeAccessor;
+		IMethod invokeAccessor;
+		
+		public DefaultResolvedEvent(IUnresolvedEvent unresolved, ITypeResolveContext parentContext)
+			: base(unresolved, parentContext)
+		{
+			this.unresolved = unresolved;
+		}
+		
+		public bool CanAdd {
+			get { return unresolved.CanAdd; }
+		}
+		
+		public bool CanRemove {
+			get { return unresolved.CanRemove; }
+		}
+		
+		public bool CanInvoke {
+			get { return unresolved.CanInvoke; }
+		}
+		
+		public IMethod AddAccessor {
+			get { return GetAccessor(ref addAccessor, unresolved.AddAccessor); }
+		}
+		
+		public IMethod RemoveAccessor {
+			get { return GetAccessor(ref removeAccessor, unresolved.RemoveAccessor); }
+		}
+		
+		public IMethod InvokeAccessor {
+			get { return GetAccessor(ref invokeAccessor, unresolved.InvokeAccessor); }
+		}
+		
+		public override IMember Specialize(TypeParameterSubstitution substitution)
+		{
+			if (TypeParameterSubstitution.Identity.Equals(substitution))
+				return this;
+			return new SpecializedEvent(this, substitution);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedField.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedField.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedField.cs	(revision 11807)
@@ -0,0 +1,87 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public class DefaultResolvedField : AbstractResolvedMember, IField
+	{
+		volatile ResolveResult constantValue;
+		
+		public DefaultResolvedField(IUnresolvedField unresolved, ITypeResolveContext parentContext)
+			: base(unresolved, parentContext)
+		{
+		}
+		
+		public bool IsReadOnly {
+			get { return ((IUnresolvedField)unresolved).IsReadOnly; }
+		}
+		
+		public bool IsVolatile {
+			get { return ((IUnresolvedField)unresolved).IsVolatile; }
+		}
+		
+		IType IVariable.Type {
+			get { return this.ReturnType; }
+		}
+		
+		public bool IsConst {
+			get { return ((IUnresolvedField)unresolved).IsConst; }
+		}
+
+		public bool IsFixed {
+			get { return ((IUnresolvedField)unresolved).IsFixed; }
+		}
+
+		public object ConstantValue {
+			get {
+				ResolveResult rr = this.constantValue;
+				if (rr == null) {
+					using (var busyLock = BusyManager.Enter(this)) {
+						if (!busyLock.Success)
+							return null;
+
+						IConstantValue unresolvedCV = ((IUnresolvedField)unresolved).ConstantValue;
+						if (unresolvedCV != null)
+							rr = unresolvedCV.Resolve(context);
+						else
+							rr = ErrorResolveResult.UnknownError;
+						this.constantValue = rr;
+					}
+				}
+				return rr.ConstantValue;
+			}
+		}
+		
+		public override IMember Specialize(TypeParameterSubstitution substitution)
+		{
+			if (TypeParameterSubstitution.Identity.Equals(substitution))
+				return this;
+			return new SpecializedField(this, substitution);
+		}
+		
+		IMemberReference IField.ToReference()
+		{
+			return (IMemberReference)ToReference();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedMethod.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedMethod.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedMethod.cs	(revision 11807)
@@ -0,0 +1,322 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IMethod"/> that resolves an unresolved method.
+	/// </summary>
+	public class DefaultResolvedMethod : AbstractResolvedMember, IMethod
+	{
+		IUnresolvedMethod[] parts;
+		
+		public DefaultResolvedMethod(DefaultUnresolvedMethod unresolved, ITypeResolveContext parentContext)
+			: this(unresolved, parentContext, unresolved.IsExtensionMethod)
+		{
+		}
+		
+		public DefaultResolvedMethod(IUnresolvedMethod unresolved, ITypeResolveContext parentContext, bool isExtensionMethod)
+			: base(unresolved, parentContext)
+		{
+			this.Parameters = unresolved.Parameters.CreateResolvedParameters(context);
+			this.ReturnTypeAttributes = unresolved.ReturnTypeAttributes.CreateResolvedAttributes(parentContext);
+			this.TypeParameters = unresolved.TypeParameters.CreateResolvedTypeParameters(context);
+			this.IsExtensionMethod = isExtensionMethod;
+		}
+
+		class ListOfLists<T> : IList<T>
+		{
+			List<IList<T>> lists =new List<IList<T>> ();
+
+			public void AddList(IList<T> list)
+			{
+				lists.Add (list);
+			}
+
+			#region IEnumerable implementation
+			System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+			{
+				return GetEnumerator();
+			}
+			#endregion
+
+			#region IEnumerable implementation
+			public IEnumerator<T> GetEnumerator ()
+			{
+				for (int i = 0; i < this.Count; i++) {
+					yield return this[i];
+				}
+			}
+			#endregion
+
+			#region ICollection implementation
+			public void Add (T item)
+			{
+				throw new NotSupportedException();
+			}
+
+			public void Clear ()
+			{
+				throw new NotSupportedException();
+			}
+
+			public bool Contains (T item)
+			{
+				var comparer = EqualityComparer<T>.Default;
+				for (int i = 0; i < this.Count; i++) {
+					if (comparer.Equals(this[i], item))
+						return true;
+				}
+				return false;
+			}
+
+			public void CopyTo (T[] array, int arrayIndex)
+			{
+				for (int i = 0; i < Count; i++) {
+					array[arrayIndex + i] = this[i];
+				}
+			}
+
+			public bool Remove (T item)
+			{
+				throw new NotSupportedException();
+			}
+
+			public int Count {
+				get {
+					return lists.Sum (l => l.Count);
+				}
+			}
+
+			public bool IsReadOnly {
+				get {
+					return true;
+				}
+			}
+			#endregion
+
+			#region IList implementation
+			public int IndexOf (T item)
+			{
+				var comparer = EqualityComparer<T>.Default;
+				for (int i = 0; i < this.Count; i++) {
+					if (comparer.Equals(this[i], item))
+						return i;
+				}
+				return -1;
+			}
+
+			public void Insert (int index, T item)
+			{
+				throw new NotSupportedException();
+			}
+
+			public void RemoveAt (int index)
+			{
+				throw new NotSupportedException();
+			}
+
+			public T this[int index] {
+				get {
+					foreach (var list in lists){
+						if (index < list.Count)
+							return list[index];
+						index -= list.Count;
+					}
+					throw new IndexOutOfRangeException ();
+				}
+				set {
+					throw new NotSupportedException();
+				}
+			}
+			#endregion
+		}
+
+		public static DefaultResolvedMethod CreateFromMultipleParts(IUnresolvedMethod[] parts, ITypeResolveContext[] contexts, bool isExtensionMethod)
+		{
+			DefaultResolvedMethod method = new DefaultResolvedMethod(parts[0], contexts[0], isExtensionMethod);
+			method.parts = parts;
+			if (parts.Length > 1) {
+				var attrs = new ListOfLists <IAttribute>();
+				attrs.AddList (method.Attributes);
+				for (int i = 1; i < parts.Length; i++) {
+					attrs.AddList (parts[i].Attributes.CreateResolvedAttributes(contexts[i]));
+				}
+				method.Attributes = attrs;
+			}
+			return method;
+		}
+		
+		public IList<IParameter> Parameters { get; private set; }
+		public IList<IAttribute> ReturnTypeAttributes { get; private set; }
+		public IList<ITypeParameter> TypeParameters { get; private set; }
+
+		public IList<IType> TypeArguments {
+			get {
+				// ToList() call is necessary because IList<> isn't covariant
+				return TypeParameters.ToList<IType>();
+			}
+		}
+		
+		bool IMethod.IsParameterized {
+			get { return false; }
+		}
+
+		public bool IsExtensionMethod { get; private set; }
+		
+		public IList<IUnresolvedMethod> Parts {
+			get {
+				return parts ?? new IUnresolvedMethod[] { (IUnresolvedMethod)unresolved };
+			}
+		}
+		
+		public bool IsConstructor {
+			get { return ((IUnresolvedMethod)unresolved).IsConstructor; }
+		}
+		
+		public bool IsDestructor {
+			get { return ((IUnresolvedMethod)unresolved).IsDestructor; }
+		}
+		
+		public bool IsOperator {
+			get { return ((IUnresolvedMethod)unresolved).IsOperator; }
+		}
+		
+		public bool IsPartial {
+			get { return ((IUnresolvedMethod)unresolved).IsPartial; }
+		}
+
+		public bool IsAsync {
+			get { return ((IUnresolvedMethod)unresolved).IsAsync; }
+		}
+
+		public bool HasBody {
+			get { return ((IUnresolvedMethod)unresolved).HasBody; }
+		}
+		
+		public bool IsAccessor {
+			get { return ((IUnresolvedMethod)unresolved).AccessorOwner != null; }
+		}
+
+		IMethod IMethod.ReducedFrom {
+			get { return null; }
+		}
+
+		public virtual IMember AccessorOwner {
+			get {
+				var reference = ((IUnresolvedMethod)unresolved).AccessorOwner;
+				if (reference != null)
+					return reference.Resolve(context);
+				else
+					return null;
+			}
+		}
+		
+		public override ISymbolReference ToReference()
+		{
+			var declTypeRef = this.DeclaringType.ToTypeReference();
+			if (IsExplicitInterfaceImplementation && ImplementedInterfaceMembers.Count == 1) {
+				return new ExplicitInterfaceImplementationMemberReference(declTypeRef, ImplementedInterfaceMembers[0].ToReference());
+			} else {
+				return new DefaultMemberReference(
+					this.SymbolKind, declTypeRef, this.Name, this.TypeParameters.Count,
+					this.Parameters.Select(p => p.Type.ToTypeReference()).ToList());
+			}
+		}
+		
+		public override IMemberReference ToMemberReference()
+		{
+			return (IMemberReference)ToReference();
+		}
+		
+		public override IMember Specialize(TypeParameterSubstitution substitution)
+		{
+			if (TypeParameterSubstitution.Identity.Equals(substitution))
+				return this;
+			return new SpecializedMethod(this, substitution);
+		}
+		
+		IMethod IMethod.Specialize(TypeParameterSubstitution substitution)
+		{
+			if (TypeParameterSubstitution.Identity.Equals(substitution))
+				return this;
+			return new SpecializedMethod(this, substitution);
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[");
+			b.Append(this.SymbolKind);
+			b.Append(' ');
+			if (this.DeclaringType.Kind != TypeKind.Unknown) {
+				b.Append(this.DeclaringType.ReflectionName);
+				b.Append('.');
+			}
+			b.Append(this.Name);
+			if (this.TypeParameters.Count > 0) {
+				b.Append("``");
+				b.Append(this.TypeParameters.Count);
+			}
+			b.Append('(');
+			for (int i = 0; i < this.Parameters.Count; i++) {
+				if (i > 0) b.Append(", ");
+				b.Append(this.Parameters[i].ToString());
+			}
+			b.Append("):");
+			b.Append(this.ReturnType.ReflectionName);
+			b.Append(']');
+			return b.ToString();
+		}
+		
+		/// <summary>
+		/// Gets a dummy constructor for the specified compilation.
+		/// </summary>
+		/// <returns>
+		/// A public instance constructor with IsSynthetic=true and no declaring type.
+		/// </returns>
+		/// <seealso cref="DefaultUnresolvedMethod.DummyConstructor"/>
+		public static IMethod GetDummyConstructor(ICompilation compilation)
+		{
+			var dummyConstructor = DefaultUnresolvedMethod.DummyConstructor;
+			// Reuse the same IMethod instance for all dummy constructors
+			// so that two occurrences of 'new T()' refer to the same constructor.
+			return (IMethod)compilation.CacheManager.GetOrAddShared(
+				dummyConstructor, _ => dummyConstructor.CreateResolved(compilation.TypeResolveContext));
+		}
+		
+		/// <summary>
+		/// Gets a dummy constructor for the specified type.
+		/// </summary>
+		/// <returns>
+		/// A public instance constructor with IsSynthetic=true and the specified declaring type.
+		/// </returns>
+		/// <seealso cref="DefaultUnresolvedMethod.DummyConstructor"/>
+		public static IMethod GetDummyConstructor(ICompilation compilation, IType declaringType)
+		{
+			var resolvedCtor = GetDummyConstructor(compilation);
+			return new SpecializedMethod(resolvedCtor, TypeParameterSubstitution.Identity) { DeclaringType = declaringType };
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedProperty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedProperty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedProperty.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public class DefaultResolvedProperty : AbstractResolvedMember, IProperty
+	{
+		protected new readonly IUnresolvedProperty unresolved;
+		readonly IList<IParameter> parameters;
+		IMethod getter;
+		IMethod setter;
+		
+		public DefaultResolvedProperty(IUnresolvedProperty unresolved, ITypeResolveContext parentContext)
+			: base(unresolved, parentContext)
+		{
+			this.unresolved = unresolved;
+			this.parameters = unresolved.Parameters.CreateResolvedParameters(context);
+		}
+		
+		public IList<IParameter> Parameters {
+			get { return parameters; }
+		}
+		
+		public bool CanGet {
+			get { return unresolved.CanGet; }
+		}
+		
+		public bool CanSet {
+			get { return unresolved.CanSet; }
+		}
+		
+		public IMethod Getter {
+			get { return GetAccessor(ref getter, unresolved.Getter); }
+		}
+		
+		public IMethod Setter {
+			get { return GetAccessor(ref setter, unresolved.Setter); }
+		}
+		
+		public bool IsIndexer {
+			get { return unresolved.IsIndexer; }
+		}
+		
+		public override ISymbolReference ToReference()
+		{
+			var declTypeRef = this.DeclaringType.ToTypeReference();
+			if (IsExplicitInterfaceImplementation && ImplementedInterfaceMembers.Count == 1) {
+				return new ExplicitInterfaceImplementationMemberReference(declTypeRef, ImplementedInterfaceMembers[0].ToReference());
+			} else {
+				return new DefaultMemberReference(
+					this.SymbolKind, declTypeRef, this.Name, 0,
+					this.Parameters.Select(p => p.Type.ToTypeReference()).ToList());
+			}
+		}
+		
+		public override IMember Specialize(TypeParameterSubstitution substitution)
+		{
+			if (TypeParameterSubstitution.Identity.Equals(substitution))
+				return this;
+			return new SpecializedProperty(this, substitution);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs	(revision 11807)
@@ -0,0 +1,963 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="ITypeDefinition"/>.
+	/// </summary>
+	public class DefaultResolvedTypeDefinition : ITypeDefinition
+	{
+		readonly ITypeResolveContext parentContext;
+		readonly IUnresolvedTypeDefinition[] parts;
+		Accessibility accessibility = Accessibility.Internal;
+		bool isAbstract, isSealed, isShadowing;
+		bool isSynthetic = true; // true if all parts are synthetic
+		
+		public DefaultResolvedTypeDefinition(ITypeResolveContext parentContext, params IUnresolvedTypeDefinition[] parts)
+		{
+			if (parentContext == null || parentContext.CurrentAssembly == null)
+				throw new ArgumentException("Parent context does not specify any assembly", "parentContext");
+			if (parts == null || parts.Length == 0)
+				throw new ArgumentException("No parts were specified", "parts");
+			this.parentContext = parentContext;
+			this.parts = parts;
+			
+			foreach (IUnresolvedTypeDefinition part in parts) {
+				isAbstract  |= part.IsAbstract;
+				isSealed    |= part.IsSealed;
+				isShadowing |= part.IsShadowing;
+				isSynthetic &= part.IsSynthetic; // true if all parts are synthetic
+				
+				// internal is the default, so use another part's accessibility until we find a non-internal accessibility
+				if (accessibility == Accessibility.Internal)
+					accessibility = part.Accessibility;
+			}
+		}
+		
+		IList<ITypeParameter> typeParameters;
+		
+		public IList<ITypeParameter> TypeParameters {
+			get {
+				var result = LazyInit.VolatileRead(ref this.typeParameters);
+				if (result != null) {
+					return result;
+				}
+				ITypeResolveContext contextForTypeParameters = parts[0].CreateResolveContext(parentContext);
+				contextForTypeParameters = contextForTypeParameters.WithCurrentTypeDefinition(this);
+				if (parentContext.CurrentTypeDefinition == null || parentContext.CurrentTypeDefinition.TypeParameterCount == 0) {
+					result = parts[0].TypeParameters.CreateResolvedTypeParameters(contextForTypeParameters);
+				} else {
+					// This is a nested class inside a generic class; copy type parameters from outer class if we can:
+					var outerClass = parentContext.CurrentTypeDefinition;
+					ITypeParameter[] typeParameters = new ITypeParameter[parts[0].TypeParameters.Count];
+					for (int i = 0; i < typeParameters.Length; i++) {
+						var unresolvedTP = parts[0].TypeParameters[i];
+						if (i < outerClass.TypeParameterCount && outerClass.TypeParameters[i].Name == unresolvedTP.Name)
+							typeParameters[i] = outerClass.TypeParameters[i];
+						else
+							typeParameters[i] = unresolvedTP.CreateResolvedTypeParameter(contextForTypeParameters);
+					}
+					result = Array.AsReadOnly(typeParameters);
+				}
+				return LazyInit.GetOrSet(ref this.typeParameters, result);
+			}
+		}
+		
+		IList<IAttribute> attributes;
+		
+		public IList<IAttribute> Attributes {
+			get {
+				var result = LazyInit.VolatileRead(ref this.attributes);
+				if (result != null) {
+					return result;
+				}
+				result = new List<IAttribute>();
+				var context = parentContext.WithCurrentTypeDefinition(this);
+				foreach (IUnresolvedTypeDefinition part in parts) {
+					ITypeResolveContext parentContextForPart = part.CreateResolveContext(context);
+					foreach (var attr in part.Attributes) {
+						result.Add(attr.CreateResolvedAttribute(parentContextForPart));
+					}
+				}
+				if (result.Count == 0)
+					result = EmptyList<IAttribute>.Instance;
+				return LazyInit.GetOrSet(ref this.attributes, result);
+			}
+		}
+		
+		public IList<IUnresolvedTypeDefinition> Parts {
+			get { return parts; }
+		}
+		
+		public SymbolKind SymbolKind {
+			get { return parts[0].SymbolKind; }
+		}
+		
+		[Obsolete("Use the SymbolKind property instead.")]
+		public EntityType EntityType {
+			get { return (EntityType)parts[0].SymbolKind; }
+		}
+		
+		public virtual TypeKind Kind {
+			get { return parts[0].Kind; }
+		}
+		
+		#region NestedTypes
+		IList<ITypeDefinition> nestedTypes;
+		
+		public IList<ITypeDefinition> NestedTypes {
+			get {
+				IList<ITypeDefinition> result = LazyInit.VolatileRead(ref this.nestedTypes);
+				if (result != null) {
+					return result;
+				} else {
+					result = (
+						from part in parts
+						from nestedTypeRef in part.NestedTypes
+						group nestedTypeRef by new { nestedTypeRef.Name, nestedTypeRef.TypeParameters.Count } into g
+						select new DefaultResolvedTypeDefinition(new SimpleTypeResolveContext(this), g.ToArray())
+					).ToList<ITypeDefinition>().AsReadOnly();
+					return LazyInit.GetOrSet(ref this.nestedTypes, result);
+				}
+			}
+		}
+		#endregion
+		
+		#region Members
+		sealed class MemberList : IList<IMember>
+		{
+			internal readonly ITypeResolveContext[] contextPerMember;
+			internal readonly IUnresolvedMember[] unresolvedMembers;
+			internal readonly IMember[] resolvedMembers;
+			internal readonly int NonPartialMemberCount;
+			
+			public MemberList(List<ITypeResolveContext> contextPerMember, List<IUnresolvedMember> unresolvedNonPartialMembers, List<PartialMethodInfo> partialMethodInfos)
+			{
+				this.NonPartialMemberCount = unresolvedNonPartialMembers.Count;
+				this.contextPerMember = contextPerMember.ToArray();
+				this.unresolvedMembers = unresolvedNonPartialMembers.ToArray();
+				if (partialMethodInfos == null) {
+					this.resolvedMembers = new IMember[unresolvedNonPartialMembers.Count];
+				} else {
+					this.resolvedMembers = new IMember[unresolvedNonPartialMembers.Count + partialMethodInfos.Count];
+					for (int i = 0; i < partialMethodInfos.Count; i++) {
+						var info = partialMethodInfos[i];
+						int memberIndex = NonPartialMemberCount + i;
+						resolvedMembers[memberIndex] = DefaultResolvedMethod.CreateFromMultipleParts(
+							info.Parts.ToArray(), info.Contexts.ToArray (), false);
+					}
+				}
+			}
+			
+			public IMember this[int index] {
+				get {
+					IMember output = LazyInit.VolatileRead(ref resolvedMembers[index]);
+					if (output != null) {
+						return output;
+					}
+					return LazyInit.GetOrSet(ref resolvedMembers[index], unresolvedMembers[index].CreateResolved(contextPerMember[index]));
+				}
+				set { throw new NotSupportedException(); }
+			}
+			
+			public int Count {
+				get { return resolvedMembers.Length; }
+			}
+			
+			bool ICollection<IMember>.IsReadOnly {
+				get { return true; }
+			}
+			
+			public int IndexOf(IMember item)
+			{
+				for (int i = 0; i < this.Count; i++) {
+					if (this[i].Equals(item))
+						return i;
+				}
+				return -1;
+			}
+			
+			void IList<IMember>.Insert(int index, IMember item)
+			{
+				throw new NotSupportedException();
+			}
+			
+			void IList<IMember>.RemoveAt(int index)
+			{
+				throw new NotSupportedException();
+			}
+			
+			void ICollection<IMember>.Add(IMember item)
+			{
+				throw new NotSupportedException();
+			}
+			
+			void ICollection<IMember>.Clear()
+			{
+				throw new NotSupportedException();
+			}
+			
+			bool ICollection<IMember>.Contains(IMember item)
+			{
+				return IndexOf(item) >= 0;
+			}
+			
+			void ICollection<IMember>.CopyTo(IMember[] array, int arrayIndex)
+			{
+				for (int i = 0; i < this.Count; i++) {
+					array[arrayIndex + i] = this[i];
+				}
+			}
+			
+			bool ICollection<IMember>.Remove(IMember item)
+			{
+				throw new NotSupportedException();
+			}
+			
+			public IEnumerator<IMember> GetEnumerator()
+			{
+				for (int i = 0; i < this.Count; i++) {
+					yield return this[i];
+				}
+			}
+			
+			System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+			{
+				return GetEnumerator();
+			}
+		}
+		
+		sealed class PartialMethodInfo
+		{
+			public readonly string Name;
+			public readonly int TypeParameterCount;
+			public readonly IList<IParameter> Parameters;
+			public readonly List<IUnresolvedMethod> Parts = new List<IUnresolvedMethod>();
+			public readonly List<ITypeResolveContext> Contexts = new List<ITypeResolveContext>();
+
+			public PartialMethodInfo(IUnresolvedMethod method, ITypeResolveContext context)
+			{
+				this.Name = method.Name;
+				this.TypeParameterCount = method.TypeParameters.Count;
+				this.Parameters = method.Parameters.CreateResolvedParameters(context);
+				this.Parts.Add(method);
+				this.Contexts.Add (context);
+			}
+			
+			public void AddPart(IUnresolvedMethod method, ITypeResolveContext context)
+			{
+				if (method.HasBody) {
+					// make the implementation the primary part
+					this.Parts.Insert(0, method);
+					this.Contexts.Insert (0, context);
+				} else {
+					this.Parts.Add(method);
+					this.Contexts.Add (context);
+				}
+			}
+			
+			public bool IsSameSignature(PartialMethodInfo other, StringComparer nameComparer)
+			{
+				return nameComparer.Equals(this.Name, other.Name)
+					&& this.TypeParameterCount == other.TypeParameterCount
+					&& ParameterListComparer.Instance.Equals(this.Parameters, other.Parameters);
+			}
+		}
+		
+		MemberList memberList;
+		
+		MemberList GetMemberList()
+		{
+			var result = LazyInit.VolatileRead(ref this.memberList);
+			if (result != null) {
+				return result;
+			}
+			List<IUnresolvedMember> unresolvedMembers = new List<IUnresolvedMember>();
+			List<ITypeResolveContext> contextPerMember = new List<ITypeResolveContext>();
+			List<PartialMethodInfo> partialMethodInfos = null;
+			bool addDefaultConstructorIfRequired = false;
+			foreach (IUnresolvedTypeDefinition part in parts) {
+				ITypeResolveContext parentContextForPart = part.CreateResolveContext(parentContext);
+				ITypeResolveContext contextForPart = parentContextForPart.WithCurrentTypeDefinition(this);
+				foreach (var member in part.Members) {
+					IUnresolvedMethod method = member as IUnresolvedMethod;
+					if (method != null && method.IsPartial) {
+						// Merge partial method declaration and implementation
+						if (partialMethodInfos == null)
+							partialMethodInfos = new List<PartialMethodInfo>();
+						PartialMethodInfo newInfo = new PartialMethodInfo(method, contextForPart);
+						PartialMethodInfo existingInfo = null;
+						foreach (var info in partialMethodInfos) {
+							if (newInfo.IsSameSignature(info, Compilation.NameComparer)) {
+								existingInfo = info;
+								break;
+							}
+						}
+						if (existingInfo != null) {
+							// Add the unresolved method to the PartialMethodInfo:
+							existingInfo.AddPart(method, contextForPart);
+						} else {
+							partialMethodInfos.Add(newInfo);
+						}
+					} else {
+						unresolvedMembers.Add(member);
+						contextPerMember.Add(contextForPart);
+					}
+				}
+				
+				addDefaultConstructorIfRequired |= part.AddDefaultConstructorIfRequired;
+			}
+			if (addDefaultConstructorIfRequired) {
+				TypeKind kind = this.Kind;
+				if (kind == TypeKind.Class && !this.IsStatic && !unresolvedMembers.Any(m => m.SymbolKind == SymbolKind.Constructor && !m.IsStatic)
+				    || kind == TypeKind.Enum || kind == TypeKind.Struct)
+				{
+					contextPerMember.Add(parts[0].CreateResolveContext(parentContext).WithCurrentTypeDefinition(this));
+					unresolvedMembers.Add(DefaultUnresolvedMethod.CreateDefaultConstructor(parts[0]));
+				}
+			}
+			result = new MemberList(contextPerMember, unresolvedMembers, partialMethodInfos);
+			return LazyInit.GetOrSet(ref this.memberList, result);
+		}
+		
+		public IList<IMember> Members {
+			get { return GetMemberList(); }
+		}
+		
+		public IEnumerable<IField> Fields {
+			get {
+				var members = GetMemberList();
+				for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+					if (members.unresolvedMembers[i].SymbolKind == SymbolKind.Field)
+						yield return (IField)members[i];
+				}
+			}
+		}
+		
+		public IEnumerable<IMethod> Methods {
+			get {
+				var members = GetMemberList();
+				for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+					if (members.unresolvedMembers[i] is IUnresolvedMethod)
+						yield return (IMethod)members[i];
+				}
+				for (int i = members.unresolvedMembers.Length; i < members.Count; i++) {
+					yield return (IMethod)members[i];
+				}
+			}
+		}
+		
+		public IEnumerable<IProperty> Properties {
+			get {
+				var members = GetMemberList();
+				for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+					switch (members.unresolvedMembers[i].SymbolKind) {
+						case SymbolKind.Property:
+						case SymbolKind.Indexer:
+							yield return (IProperty)members[i];
+							break;
+					}
+				}
+			}
+		}
+		
+		public IEnumerable<IEvent> Events {
+			get {
+				var members = GetMemberList();
+				for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+					if (members.unresolvedMembers[i].SymbolKind == SymbolKind.Event)
+						yield return (IEvent)members[i];
+				}
+			}
+		}
+		#endregion
+		
+		volatile KnownTypeCode knownTypeCode = (KnownTypeCode)(-1);
+		
+		public KnownTypeCode KnownTypeCode {
+			get {
+				KnownTypeCode result = this.knownTypeCode;
+				if (result == (KnownTypeCode)(-1)) {
+					result = KnownTypeCode.None;
+					ICompilation compilation = this.Compilation;
+					for (int i = 0; i < KnownTypeReference.KnownTypeCodeCount; i++) {
+						if (compilation.FindType((KnownTypeCode)i) == this) {
+							result = (KnownTypeCode)i;
+							break;
+						}
+					}
+					this.knownTypeCode = result;
+				}
+				return result;
+			}
+		}
+		
+		volatile IType enumUnderlyingType;
+		
+		public IType EnumUnderlyingType {
+			get {
+				IType result = this.enumUnderlyingType;
+				if (result == null) {
+					if (this.Kind == TypeKind.Enum) {
+						result = CalculateEnumUnderlyingType();
+					} else {
+						result = SpecialType.UnknownType;
+					}
+					this.enumUnderlyingType = result;
+				}
+				return result;
+			}
+		}
+		
+		IType CalculateEnumUnderlyingType()
+		{
+			foreach (var part in parts) {
+				var context = part.CreateResolveContext(parentContext).WithCurrentTypeDefinition(this);
+				foreach (var baseTypeRef in part.BaseTypes) {
+					IType type = baseTypeRef.Resolve(context);
+					if (type.Kind != TypeKind.Unknown)
+						return type;
+				}
+			}
+			return this.Compilation.FindType(KnownTypeCode.Int32);
+		}
+		
+		volatile byte hasExtensionMethods; // 0 = unknown, 1 = true, 2 = false
+		
+		public bool HasExtensionMethods {
+			get {
+				byte val = this.hasExtensionMethods;
+				if (val == 0) {
+					if (CalculateHasExtensionMethods())
+						val = 1;
+					else
+						val = 2;
+					this.hasExtensionMethods = val;
+				}
+				return val == 1;
+			}
+		}
+		
+		bool CalculateHasExtensionMethods()
+		{
+			bool noExtensionMethods = true;
+			foreach (var part in parts) {
+				// Return true if any part has extension methods
+				if (part.HasExtensionMethods == true)
+					return true;
+				if (part.HasExtensionMethods == null)
+					noExtensionMethods = false;
+			}
+			// Return false if all parts are known to have no extension methods
+			if (noExtensionMethods)
+				return false;
+			// If unsure, look at the resolved methods.
+			return Methods.Any(m => m.IsExtensionMethod);
+		}
+		
+		public bool IsPartial {
+			get { return parts.Length > 1 || parts[0].IsPartial; }
+		}
+		
+		public bool? IsReferenceType {
+			get {
+				switch (this.Kind) {
+					case TypeKind.Class:
+					case TypeKind.Interface:
+					case TypeKind.Module:
+					case TypeKind.Delegate:
+						return true;
+					case TypeKind.Struct:
+					case TypeKind.Enum:
+					case TypeKind.Void:
+						return false;
+					default:
+						throw new InvalidOperationException("Invalid value for TypeKind");
+				}
+			}
+		}
+		
+		public int TypeParameterCount {
+			get { return parts[0].TypeParameters.Count; }
+		}
+
+		public IList<IType> TypeArguments {
+			get {
+				// ToList() call is necessary because IList<> isn't covariant
+				return TypeParameters.ToList<IType>();
+			}
+		}
+
+		public bool IsParameterized {
+			get { return false; }
+		}
+
+		#region DirectBaseTypes
+		IList<IType> directBaseTypes;
+		
+		public IEnumerable<IType> DirectBaseTypes {
+			get {
+				IList<IType> result = LazyInit.VolatileRead(ref this.directBaseTypes);
+				if (result != null) {
+					return result;
+				}
+				using (var busyLock = BusyManager.Enter(this)) {
+					if (busyLock.Success) {
+						result = CalculateDirectBaseTypes();
+						return LazyInit.GetOrSet(ref this.directBaseTypes, result);
+					} else {
+						// This can happen for "class Test : $Test.Base$ { public class Base {} }"
+						// and also for the valid code
+						// "class Test : Base<Test.Inner> { public class Inner {} }"
+						
+						// Don't cache the error!
+						return EmptyList<IType>.Instance;
+					}
+				}
+			}
+		}
+		
+		IList<IType> CalculateDirectBaseTypes()
+		{
+			List<IType> result = new List<IType>();
+			bool hasNonInterface = false;
+			if (this.Kind != TypeKind.Enum) {
+				foreach (var part in parts) {
+					var context = part.CreateResolveContext(parentContext).WithCurrentTypeDefinition(this);
+					foreach (var baseTypeRef in part.BaseTypes) {
+						IType baseType = baseTypeRef.Resolve(context);
+						if (!(baseType.Kind == TypeKind.Unknown || result.Contains(baseType))) {
+							result.Add(baseType);
+							if (baseType.Kind != TypeKind.Interface)
+								hasNonInterface = true;
+						}
+					}
+				}
+			}
+			if (!hasNonInterface && !(this.Name == "Object" && this.Namespace == "System" && this.TypeParameterCount == 0)) {
+				KnownTypeCode primitiveBaseType;
+				switch (this.Kind) {
+					case TypeKind.Enum:
+						primitiveBaseType = KnownTypeCode.Enum;
+						break;
+					case TypeKind.Struct:
+					case TypeKind.Void:
+						primitiveBaseType = KnownTypeCode.ValueType;
+						break;
+					case TypeKind.Delegate:
+						primitiveBaseType = KnownTypeCode.Delegate;
+						break;
+					default:
+						primitiveBaseType = KnownTypeCode.Object;
+						break;
+				}
+				IType t = parentContext.Compilation.FindType(primitiveBaseType);
+				if (t.Kind != TypeKind.Unknown)
+					result.Add(t);
+			}
+			return result;
+		}
+		#endregion
+		
+		public string FullName {
+			get { return parts[0].FullName; }
+		}
+		
+		public string Name {
+			get { return parts[0].Name; }
+		}
+		
+		public string ReflectionName {
+			get { return parts[0].ReflectionName; }
+		}
+		
+		public string Namespace {
+			get { return parts[0].Namespace; }
+		}
+		
+		public FullTypeName FullTypeName {
+			get { return parts[0].FullTypeName; }
+		}
+		
+		public DomRegion Region {
+			get { return parts[0].Region; }
+		}
+		
+		public DomRegion BodyRegion {
+			get { return parts[0].BodyRegion; }
+		}
+		
+		public ITypeDefinition DeclaringTypeDefinition {
+			get { return parentContext.CurrentTypeDefinition; }
+		}
+		
+		public IType DeclaringType {
+			get { return parentContext.CurrentTypeDefinition; }
+		}
+		
+		public IAssembly ParentAssembly {
+			get { return parentContext.CurrentAssembly; }
+		}
+		
+		public virtual DocumentationComment Documentation {
+			get {
+				foreach (var part in parts) {
+					var unresolvedProvider = part.UnresolvedFile as IUnresolvedDocumentationProvider;
+					if (unresolvedProvider != null) {
+						var doc = unresolvedProvider.GetDocumentation(part, this);
+						if (doc != null)
+							return doc;
+					}
+				}
+				IDocumentationProvider provider = AbstractResolvedEntity.FindDocumentation(parentContext);
+				if (provider != null)
+					return provider.GetDocumentation(this);
+				else
+					return null;
+			}
+		}
+		
+		public ICompilation Compilation {
+			get { return parentContext.Compilation; }
+		}
+		
+		#region Modifiers
+		public bool IsStatic    { get { return isAbstract && isSealed; } }
+		public bool IsAbstract  { get { return isAbstract; } }
+		public bool IsSealed    { get { return isSealed; } }
+		public bool IsShadowing { get { return isShadowing; } }
+		public bool IsSynthetic { get { return isSynthetic; } }
+		
+		public Accessibility Accessibility {
+			get { return accessibility; }
+		}
+		
+		bool IHasAccessibility.IsPrivate {
+			get { return accessibility == Accessibility.Private; }
+		}
+		
+		bool IHasAccessibility.IsPublic {
+			get { return accessibility == Accessibility.Public; }
+		}
+		
+		bool IHasAccessibility.IsProtected {
+			get { return accessibility == Accessibility.Protected; }
+		}
+		
+		bool IHasAccessibility.IsInternal {
+			get { return accessibility == Accessibility.Internal; }
+		}
+		
+		bool IHasAccessibility.IsProtectedOrInternal {
+			get { return accessibility == Accessibility.ProtectedOrInternal; }
+		}
+		
+		bool IHasAccessibility.IsProtectedAndInternal {
+			get { return accessibility == Accessibility.ProtectedAndInternal; }
+		}
+		#endregion
+		
+		ITypeDefinition IType.GetDefinition()
+		{
+			return this;
+		}
+		
+		IType IType.AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitTypeDefinition(this);
+		}
+		
+		IType IType.VisitChildren(TypeVisitor visitor)
+		{
+			return this;
+		}
+		
+		public ITypeReference ToTypeReference()
+		{
+			ITypeDefinition declTypeDef = this.DeclaringTypeDefinition;
+			if (declTypeDef != null) {
+				return new NestedTypeReference(declTypeDef.ToTypeReference(), this.Name, this.TypeParameterCount - declTypeDef.TypeParameterCount);
+			} else {
+				IAssembly asm = this.ParentAssembly;
+				IAssemblyReference asmRef;
+				if (asm != null)
+					asmRef = new DefaultAssemblyReference(asm.AssemblyName);
+				else
+					asmRef = null;
+				return new GetClassTypeReference(asmRef, this.Namespace, this.Name, this.TypeParameterCount);
+			}
+		}
+		
+		ISymbolReference ISymbol.ToReference()
+		{
+			return (ISymbolReference)ToTypeReference();
+		}
+		
+		public IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			const GetMemberOptions opt = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions;
+			if ((options & opt) == opt) {
+				if (filter == null)
+					return this.NestedTypes;
+				else
+					return GetNestedTypesImpl(filter);
+			} else {
+				return GetMembersHelper.GetNestedTypes(this, filter, options);
+			}
+		}
+		
+		IEnumerable<IType> GetNestedTypesImpl(Predicate<ITypeDefinition> filter)
+		{
+			foreach (var nestedType in this.NestedTypes) {
+				if (filter(nestedType))
+					yield return nestedType;
+			}
+		}
+		
+		public IEnumerable<IType> GetNestedTypes(IList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return GetMembersHelper.GetNestedTypes(this, typeArguments, filter, options);
+		}
+		
+		#region GetMembers()
+		IEnumerable<IMember> GetFilteredMembers(Predicate<IUnresolvedMember> filter)
+		{
+			var members = GetMemberList();
+			for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+				if (filter == null || filter(members.unresolvedMembers[i])) {
+					yield return members[i];
+				}
+			}
+			for (int i = members.unresolvedMembers.Length; i < members.Count; i++) {
+				var method = (IMethod)members[i];
+				bool ok = false;
+				foreach (var part in method.Parts) {
+					if (filter == null || filter(part)) {
+						ok = true;
+						break;
+					}
+				}
+				if (ok)
+					yield return method;
+			}
+		}
+		
+		IEnumerable<IMethod> GetFilteredMethods(Predicate<IUnresolvedMethod> filter)
+		{
+			var members = GetMemberList();
+			for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+				IUnresolvedMethod unresolved = members.unresolvedMembers[i] as IUnresolvedMethod;
+				if (unresolved != null && (filter == null || filter(unresolved))) {
+					yield return (IMethod)members[i];
+				}
+			}
+			for (int i = members.unresolvedMembers.Length; i < members.Count; i++) {
+				var method = (IMethod)members[i];
+				bool ok = false;
+				foreach (var part in method.Parts) {
+					if (filter == null || filter(part)) {
+						ok = true;
+						break;
+					}
+				}
+				if (ok)
+					yield return method;
+			}
+		}
+		
+		IEnumerable<TResolved> GetFilteredNonMethods<TUnresolved, TResolved>(Predicate<TUnresolved> filter) where TUnresolved : class, IUnresolvedMember where TResolved : class, IMember
+		{
+			var members = GetMemberList();
+			for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+				TUnresolved unresolved = members.unresolvedMembers[i] as TUnresolved;
+				if (unresolved != null && (filter == null || filter(unresolved))) {
+					yield return (TResolved)members[i];
+				}
+			}
+		}
+		
+		public virtual IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredMethods(Utils.ExtensionMethods.And(m => !m.IsConstructor, filter));
+			} else {
+				return GetMembersHelper.GetMethods(this, filter, options);
+			}
+		}
+		
+		public virtual IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			return GetMembersHelper.GetMethods(this, typeArguments, filter, options);
+		}
+		
+		public virtual IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
+		{
+			if (ComHelper.IsComImport(this)) {
+				IType coClass = ComHelper.GetCoClass(this);
+				using (var busyLock = BusyManager.Enter(this)) {
+					if (busyLock.Success) {
+						return coClass.GetConstructors(filter, options)
+							.Select(m => new SpecializedMethod(m, m.Substitution) { DeclaringType = this });
+					}
+				}
+				return EmptyList<IMethod>.Instance;
+			}
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredMethods(Utils.ExtensionMethods.And(m => m.IsConstructor && !m.IsStatic, filter));
+			} else {
+				return GetMembersHelper.GetConstructors(this, filter, options);
+			}
+		}
+		
+		public virtual IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredNonMethods<IUnresolvedProperty, IProperty>(filter);
+			} else {
+				return GetMembersHelper.GetProperties(this, filter, options);
+			}
+		}
+		
+		public virtual IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredNonMethods<IUnresolvedField, IField>(filter);
+			} else {
+				return GetMembersHelper.GetFields(this, filter, options);
+			}
+		}
+		
+		public virtual IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredNonMethods<IUnresolvedEvent, IEvent>(filter);
+			} else {
+				return GetMembersHelper.GetEvents(this, filter, options);
+			}
+		}
+		
+		public virtual IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredMembers(filter);
+			} else {
+				return GetMembersHelper.GetMembers(this, filter, options);
+			}
+		}
+		
+		public virtual IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFilteredAccessors(filter);
+			} else {
+				return GetMembersHelper.GetAccessors(this, filter, options);
+			}
+		}
+		
+		IEnumerable<IMethod> GetFilteredAccessors(Predicate<IUnresolvedMethod> filter)
+		{
+			var members = GetMemberList();
+			for (int i = 0; i < members.unresolvedMembers.Length; i++) {
+				IUnresolvedMember unresolved = members.unresolvedMembers[i];
+				var unresolvedProperty = unresolved as IUnresolvedProperty;
+				var unresolvedEvent = unresolved as IUnresolvedEvent;
+				if (unresolvedProperty != null) {
+					if (unresolvedProperty.CanGet && (filter == null || filter(unresolvedProperty.Getter)))
+						yield return ((IProperty)members[i]).Getter;
+					if (unresolvedProperty.CanSet && (filter == null || filter(unresolvedProperty.Setter)))
+						yield return ((IProperty)members[i]).Setter;
+				} else if (unresolvedEvent != null) {
+					if (unresolvedEvent.CanAdd && (filter == null || filter(unresolvedEvent.AddAccessor)))
+						yield return ((IEvent)members[i]).AddAccessor;
+					if (unresolvedEvent.CanRemove && (filter == null || filter(unresolvedEvent.RemoveAccessor)))
+						yield return ((IEvent)members[i]).RemoveAccessor;
+					if (unresolvedEvent.CanInvoke && (filter == null || filter(unresolvedEvent.InvokeAccessor)))
+						yield return ((IEvent)members[i]).InvokeAccessor;
+				}
+			}
+		}
+		#endregion
+		
+		#region GetInterfaceImplementation
+		public IMember GetInterfaceImplementation(IMember interfaceMember)
+		{
+			return GetInterfaceImplementation(new[] { interfaceMember })[0];
+		}
+		
+		public IList<IMember> GetInterfaceImplementation(IList<IMember> interfaceMembers)
+		{
+			// TODO: review the subtle rules for interface reimplementation,
+			// write tests and fix this method.
+			// Also virtual/override is going to be tricky -
+			// I think we'll need to consider the 'virtual' method first for
+			// reimplemenatation purposes, but then actually return the 'override'
+			// (as that's the method that ends up getting called)
+			
+			interfaceMembers = interfaceMembers.ToList(); // avoid evaluating more than once
+			
+			var result = new IMember[interfaceMembers.Count];
+			var signatureToIndexDict = new MultiDictionary<IMember, int>(SignatureComparer.Ordinal);
+			for (int i = 0; i < interfaceMembers.Count; i++) {
+				signatureToIndexDict.Add(interfaceMembers[i], i);
+			}
+			foreach (var member in GetMembers(m => !m.IsExplicitInterfaceImplementation)) {
+				foreach (int interfaceMemberIndex in signatureToIndexDict[member]) {
+					result[interfaceMemberIndex] = member;
+				}
+			}
+			foreach (var explicitImpl in GetMembers(m => m.IsExplicitInterfaceImplementation)) {
+				foreach (var interfaceMember in explicitImpl.ImplementedInterfaceMembers) {
+					foreach (int potentialMatchingIndex in signatureToIndexDict[interfaceMember]) {
+						if (interfaceMember.Equals(interfaceMembers[potentialMatchingIndex])) {
+							result[potentialMatchingIndex] = explicitImpl;
+						}
+					}
+				}
+			}
+			return result;
+		}
+		#endregion
+		
+		public TypeParameterSubstitution GetSubstitution()
+		{
+			return TypeParameterSubstitution.Identity;
+		}
+		
+		public TypeParameterSubstitution GetSubstitution(IList<IType> methodTypeArguments)
+		{
+			return TypeParameterSubstitution.Identity;
+		}
+
+		public bool Equals(IType other)
+		{
+			return this == other;
+		}
+		
+		public override string ToString()
+		{
+			return this.ReflectionName;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedTypeParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedTypeParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultResolvedTypeParameter.cs	(revision 11807)
@@ -0,0 +1,257 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public class DefaultTypeParameter : AbstractTypeParameter
+	{
+		readonly bool hasValueTypeConstraint;
+		readonly bool hasReferenceTypeConstraint;
+		readonly bool hasDefaultConstructorConstraint;
+		readonly IList<IType> constraints;
+		
+		public DefaultTypeParameter(
+			IEntity owner,
+			int index, string name = null,
+			VarianceModifier variance = VarianceModifier.Invariant,
+			IList<IAttribute> attributes = null,
+			DomRegion region = default(DomRegion),
+			bool hasValueTypeConstraint = false, bool hasReferenceTypeConstraint = false, bool hasDefaultConstructorConstraint = false,
+			IList<IType> constraints = null)
+			: base(owner, index, name, variance, attributes, region)
+		{
+			this.hasValueTypeConstraint = hasValueTypeConstraint;
+			this.hasReferenceTypeConstraint = hasReferenceTypeConstraint;
+			this.hasDefaultConstructorConstraint = hasDefaultConstructorConstraint;
+			this.constraints = constraints ?? EmptyList<IType>.Instance;
+		}
+		
+		public DefaultTypeParameter(
+			ICompilation compilation, SymbolKind ownerType,
+			int index, string name = null,
+			VarianceModifier variance = VarianceModifier.Invariant,
+			IList<IAttribute> attributes = null,
+			DomRegion region = default(DomRegion),
+			bool hasValueTypeConstraint = false, bool hasReferenceTypeConstraint = false, bool hasDefaultConstructorConstraint = false,
+			IList<IType> constraints = null)
+			: base(compilation, ownerType, index, name, variance, attributes, region)
+		{
+			this.hasValueTypeConstraint = hasValueTypeConstraint;
+			this.hasReferenceTypeConstraint = hasReferenceTypeConstraint;
+			this.hasDefaultConstructorConstraint = hasDefaultConstructorConstraint;
+			this.constraints = constraints ?? EmptyList<IType>.Instance;
+		}
+		
+		public override bool HasValueTypeConstraint {
+			get { return hasValueTypeConstraint; }
+		}
+		
+		public override bool HasReferenceTypeConstraint {
+			get { return hasReferenceTypeConstraint; }
+		}
+		
+		public override bool HasDefaultConstructorConstraint {
+			get { return hasDefaultConstructorConstraint; }
+		}
+		
+		public override IEnumerable<IType> DirectBaseTypes {
+			get {
+				bool hasNonInterfaceConstraint = false;
+				foreach (IType c in constraints) {
+					yield return c;
+					if (c.Kind != TypeKind.Interface)
+						hasNonInterfaceConstraint = true;
+				}
+				// Do not add the 'System.Object' constraint if there is another constraint with a base class.
+				if (this.HasValueTypeConstraint || !hasNonInterfaceConstraint) {
+					yield return this.Compilation.FindType(this.HasValueTypeConstraint ? KnownTypeCode.ValueType : KnownTypeCode.Object);
+				}
+			}
+		}
+	}
+	
+	/*
+	/// <summary>
+	/// Default implementation of <see cref="ITypeParameter"/>.
+	/// </summary>
+	[Serializable]
+	public sealed class DefaultTypeParameter : AbstractTypeParameter
+	{
+		IList<ITypeReference> constraints;
+		
+		BitVector16 flags;
+		
+		const ushort FlagReferenceTypeConstraint      = 0x0001;
+		const ushort FlagValueTypeConstraint          = 0x0002;
+		const ushort FlagDefaultConstructorConstraint = 0x0004;
+		
+		protected override void FreezeInternal()
+		{
+			constraints = FreezeList(constraints);
+			base.FreezeInternal();
+		}
+		
+		public DefaultTypeParameter(SymbolKind ownerType, int index, string name)
+			: base(ownerType, index, name)
+		{
+		}
+		
+		public IList<ITypeReference> Constraints {
+			get {
+				if (constraints == null)
+					constraints = new List<ITypeReference>();
+				return constraints;
+			}
+		}
+		
+		public bool HasDefaultConstructorConstraint {
+			get { return flags[FlagDefaultConstructorConstraint]; }
+			set {
+				CheckBeforeMutation();
+				flags[FlagDefaultConstructorConstraint] = value;
+			}
+		}
+		
+		public bool HasReferenceTypeConstraint {
+			get { return flags[FlagReferenceTypeConstraint]; }
+			set {
+				CheckBeforeMutation();
+				flags[FlagReferenceTypeConstraint] = value;
+			}
+		}
+		
+		public bool HasValueTypeConstraint {
+			get { return flags[FlagValueTypeConstraint]; }
+			set {
+				CheckBeforeMutation();
+				flags[FlagValueTypeConstraint] = value;
+			}
+		}
+		
+		public override bool? IsReferenceType(ITypeResolveContext context)
+		{
+			switch (flags.Data & (FlagReferenceTypeConstraint | FlagValueTypeConstraint)) {
+				case FlagReferenceTypeConstraint:
+					return true;
+				case FlagValueTypeConstraint:
+					return false;
+			}
+			
+			return base.IsReferenceTypeHelper(GetEffectiveBaseClass(context));
+		}
+		
+		public override IType GetEffectiveBaseClass(ITypeResolveContext context)
+		{
+			// protect against cyclic type parameters
+			using (var busyLock = BusyManager.Enter(this)) {
+				if (!busyLock.Success)
+					return SpecialTypes.UnknownType;
+				
+				if (HasValueTypeConstraint)
+					return context.GetTypeDefinition("System", "ValueType", 0, StringComparer.Ordinal) ?? SpecialTypes.UnknownType;
+				
+				List<IType> classTypeConstraints = new List<IType>();
+				foreach (ITypeReference constraintRef in this.Constraints) {
+					IType constraint = constraintRef.Resolve(context);
+					if (constraint.Kind == TypeKind.Class) {
+						classTypeConstraints.Add(constraint);
+					} else if (constraint.Kind == TypeKind.TypeParameter) {
+						IType baseClass = ((ITypeParameter)constraint).GetEffectiveBaseClass(context);
+						if (baseClass.Kind == TypeKind.Class)
+							classTypeConstraints.Add(baseClass);
+					}
+				}
+				if (classTypeConstraints.Count == 0)
+					return KnownTypeReference.Object.Resolve(context);
+				// Find the derived-most type in the resulting set:
+				IType result = classTypeConstraints[0];
+				for (int i = 1; i < classTypeConstraints.Count; i++) {
+					if (classTypeConstraints[i].GetDefinition().IsDerivedFrom(result.GetDefinition(), context))
+						result = classTypeConstraints[i];
+				}
+				return result;
+			}
+		}
+		
+		public override IEnumerable<IType> GetEffectiveInterfaceSet(ITypeResolveContext context)
+		{
+			List<IType> result = new List<IType>();
+			// protect against cyclic type parameters
+			using (var busyLock = BusyManager.Enter(this)) {
+				if (busyLock.Success) {
+					foreach (ITypeReference constraintRef in this.Constraints) {
+						IType constraint = constraintRef.Resolve(context);
+						if (constraint.Kind == TypeKind.Interface) {
+							result.Add(constraint);
+						} else if (constraint.Kind == TypeKind.TypeParameter) {
+							result.AddRange(((ITypeParameter)constraint).GetEffectiveInterfaceSet(context));
+						}
+					}
+				}
+			}
+			return result.Distinct();
+		}
+		
+		public override ITypeParameterConstraints GetConstraints(ITypeResolveContext context)
+		{
+			return new DefaultTypeParameterConstraints(
+				this.Constraints.Select(c => c.Resolve(context)),
+				this.HasDefaultConstructorConstraint, this.HasReferenceTypeConstraint, this.HasValueTypeConstraint);
+		}
+		
+		/*
+	 * Interning for type parameters is disabled; we can't intern cyclic structures as might
+	 * occur in the constraints, and incomplete interning is dangerous for type parameters
+	 * as we use reference equality.
+		void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
+		{
+			// protect against cyclic constraints
+			using (var busyLock = BusyManager.Enter(this)) {
+				if (busyLock.Success) {
+					constraints = provider.InternList(constraints);
+					base.PrepareForInterning(provider);
+				}
+			}
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				int hashCode = base.GetHashCodeForInterning();
+				if (constraints != null)
+					hashCode += constraints.GetHashCode();
+				hashCode += 771 * flags.Data;
+				return hashCode;
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			DefaultTypeParameter o = other as DefaultTypeParameter;
+			return base.EqualsForInterning(o)
+				&& this.constraints == o.constraints
+				&& this.flags == o.flags;
+		}
+	}*/
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedAssembly.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedAssembly.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedAssembly.cs	(revision 11807)
@@ -0,0 +1,575 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Threading;
+
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation for <see cref="IUnresolvedAssembly"/>.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedAssembly : AbstractFreezable, IUnresolvedAssembly
+	{
+		string assemblyName;
+		string fullAssemblyName;
+		IList<IUnresolvedAttribute> assemblyAttributes;
+		IList<IUnresolvedAttribute> moduleAttributes;
+		Dictionary<TopLevelTypeName, IUnresolvedTypeDefinition> typeDefinitions = new Dictionary<TopLevelTypeName, IUnresolvedTypeDefinition>(TopLevelTypeNameComparer.Ordinal);
+		Dictionary<TopLevelTypeName, ITypeReference> typeForwarders = new Dictionary<TopLevelTypeName, ITypeReference>(TopLevelTypeNameComparer.Ordinal);
+		
+		protected override void FreezeInternal()
+		{
+			base.FreezeInternal();
+			assemblyAttributes = FreezableHelper.FreezeListAndElements(assemblyAttributes);
+			moduleAttributes = FreezableHelper.FreezeListAndElements(moduleAttributes);
+			foreach (var type in typeDefinitions.Values) {
+				FreezableHelper.Freeze(type);
+			}
+		}
+		
+		/// <summary>
+		/// Creates a new unresolved assembly.
+		/// </summary>
+		/// <param name="assemblyName">Full assembly name</param>
+		public DefaultUnresolvedAssembly(string assemblyName)
+		{
+			if (assemblyName == null)
+				throw new ArgumentNullException("assemblyName");
+			this.fullAssemblyName = assemblyName;
+			int pos = assemblyName != null ? assemblyName.IndexOf(',') : -1;
+			this.assemblyName = pos < 0 ? assemblyName : assemblyName.Substring(0, pos);
+			this.assemblyAttributes = new List<IUnresolvedAttribute>();
+			this.moduleAttributes = new List<IUnresolvedAttribute>();
+		}
+		
+		/// <summary>
+		/// Gets/Sets the short assembly name.
+		/// </summary>
+		/// <remarks>
+		/// This class handles the short and the full name independently;
+		/// if you change the short name, you should also change the full name.
+		/// </remarks>
+		public string AssemblyName {
+			get { return assemblyName; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				FreezableHelper.ThrowIfFrozen(this);
+				assemblyName = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the full assembly name.
+		/// </summary>
+		/// <remarks>
+		/// This class handles the short and the full name independently;
+		/// if you change the full name, you should also change the short name.
+		/// </remarks>
+		public string FullAssemblyName {
+			get { return fullAssemblyName; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				FreezableHelper.ThrowIfFrozen(this);
+				fullAssemblyName = value;
+			}
+		}
+		
+		string location;
+		public string Location {
+			get {
+				return location;
+			}
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				location = value;
+			}
+		}
+
+		public IList<IUnresolvedAttribute> AssemblyAttributes {
+			get { return assemblyAttributes; }
+		}
+		
+		IEnumerable<IUnresolvedAttribute> IUnresolvedAssembly.AssemblyAttributes {
+			get { return assemblyAttributes; }
+		}
+		
+		public IList<IUnresolvedAttribute> ModuleAttributes {
+			get { return moduleAttributes; }
+		}
+		
+		IEnumerable<IUnresolvedAttribute> IUnresolvedAssembly.ModuleAttributes {
+			get { return moduleAttributes; }
+		}
+		
+		public IEnumerable<IUnresolvedTypeDefinition> TopLevelTypeDefinitions {
+			get { return typeDefinitions.Values; }
+		}
+		
+		/// <summary>
+		/// Adds a new top-level type definition to this assembly.
+		/// </summary>
+		/// <remarks>DefaultUnresolvedAssembly does not support partial classes.
+		/// Adding more than one part of a type will cause an ArgumentException.</remarks>
+		public void AddTypeDefinition(IUnresolvedTypeDefinition typeDefinition)
+		{
+			if (typeDefinition == null)
+				throw new ArgumentNullException("typeDefinition");
+			if (typeDefinition.DeclaringTypeDefinition != null)
+				throw new ArgumentException("Cannot add nested types.");
+			FreezableHelper.ThrowIfFrozen(this);
+			var key = new TopLevelTypeName(typeDefinition.Namespace, typeDefinition.Name, typeDefinition.TypeParameters.Count);
+			typeDefinitions.Add(key, typeDefinition);
+		}
+		
+		static readonly ITypeReference typeForwardedToAttributeTypeRef = typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute).ToTypeReference();
+		
+		/// <summary>
+		/// Adds a type forwarder.
+		/// This adds both an assembly attribute and an internal forwarder entry, which will be used
+		/// by the resolved assembly to provide the forwarded types.
+		/// </summary>
+		/// <param name="typeName">The name of the type.</param>
+		/// <param name="referencedType">The reference used to look up the type in the target assembly.</param>
+		public void AddTypeForwarder(TopLevelTypeName typeName, ITypeReference referencedType)
+		{
+			if (referencedType == null)
+				throw new ArgumentNullException("referencedType");
+			FreezableHelper.ThrowIfFrozen(this);
+			var attribute = new DefaultUnresolvedAttribute(typeForwardedToAttributeTypeRef, new[] { KnownTypeReference.Type });
+			attribute.PositionalArguments.Add(new TypeOfConstantValue(referencedType));
+			assemblyAttributes.Add(attribute);
+			
+			typeForwarders[typeName] = referencedType;
+		}
+		
+		[Serializable]
+		sealed class TypeOfConstantValue : IConstantValue
+		{
+			readonly ITypeReference typeRef;
+			
+			public TypeOfConstantValue(ITypeReference typeRef)
+			{
+				this.typeRef = typeRef;
+			}
+			
+			public ResolveResult Resolve(ITypeResolveContext context)
+			{
+				return new TypeOfResolveResult(context.Compilation.FindType(KnownTypeCode.Type), typeRef.Resolve(context));
+			}
+		}
+		
+		public IUnresolvedTypeDefinition GetTypeDefinition(string ns, string name, int typeParameterCount)
+		{
+			var key = new TopLevelTypeName(ns ?? string.Empty, name, typeParameterCount);
+			IUnresolvedTypeDefinition td;
+			if (typeDefinitions.TryGetValue(key, out td))
+				return td;
+			else
+				return null;
+		}
+		
+		public IAssembly Resolve(ITypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			Freeze();
+			var cache = context.Compilation.CacheManager;
+			IAssembly asm = (IAssembly)cache.GetShared(this);
+			if (asm != null) {
+				return asm;
+			} else {
+				asm = new DefaultResolvedAssembly(context.Compilation, this);
+				return (IAssembly)cache.GetOrAddShared(this, asm);
+			}
+		}
+		
+		public override string ToString()
+		{
+			return "[" + GetType().Name + " " + assemblyName + "]";
+		}
+		
+		//[NonSerialized]
+		//List<Dictionary<TopLevelTypeName, IUnresolvedTypeDefinition>> cachedTypeDictionariesPerNameComparer;
+		
+		Dictionary<TopLevelTypeName, IUnresolvedTypeDefinition> GetTypeDictionary(StringComparer nameComparer)
+		{
+			Debug.Assert(IsFrozen);
+			if (nameComparer == StringComparer.Ordinal)
+				return typeDefinitions;
+			else
+				throw new NotImplementedException();
+		}
+		
+		#region UnresolvedNamespace
+		sealed class UnresolvedNamespace
+		{
+			internal readonly string FullName;
+			internal readonly string Name;
+			internal readonly List<UnresolvedNamespace> Children = new List<UnresolvedNamespace>();
+			
+			public UnresolvedNamespace(string fullName, string name)
+			{
+				this.FullName = fullName;
+				this.Name = name;
+			}
+		}
+		
+		[NonSerialized]
+		List<KeyValuePair<StringComparer, UnresolvedNamespace>> unresolvedNamespacesPerNameComparer;
+		
+		UnresolvedNamespace GetUnresolvedRootNamespace(StringComparer nameComparer)
+		{
+			Debug.Assert(IsFrozen);
+			LazyInitializer.EnsureInitialized(ref unresolvedNamespacesPerNameComparer);
+			lock (unresolvedNamespacesPerNameComparer) {
+				foreach (var pair in unresolvedNamespacesPerNameComparer) {
+					if (pair.Key == nameComparer)
+						return pair.Value;
+				}
+				var root = new UnresolvedNamespace(string.Empty, string.Empty);
+				var dict = new Dictionary<string, UnresolvedNamespace>(nameComparer);
+				dict.Add(root.FullName, root);
+				foreach (var typeName in typeDefinitions.Keys) {
+					GetOrAddNamespace(dict, typeName.Namespace);
+				}
+				unresolvedNamespacesPerNameComparer.Add(new KeyValuePair<StringComparer, UnresolvedNamespace>(nameComparer, root));
+				return root;
+			}
+		}
+		
+		static UnresolvedNamespace GetOrAddNamespace(Dictionary<string, UnresolvedNamespace> dict, string fullName)
+		{
+			UnresolvedNamespace ns;
+			if (dict.TryGetValue(fullName, out ns))
+				return ns;
+			int pos = fullName.LastIndexOf('.');
+			UnresolvedNamespace parent;
+			string name;
+			if (pos < 0) {
+				parent = dict[string.Empty]; // root
+				name = fullName;
+			} else {
+				parent = GetOrAddNamespace(dict, fullName.Substring(0, pos));
+				name = fullName.Substring(pos + 1);
+			}
+			ns = new UnresolvedNamespace(fullName, name);
+			parent.Children.Add(ns);
+			dict.Add(fullName, ns);
+			return ns;
+		}
+		#endregion
+		
+		sealed class DefaultResolvedAssembly : IAssembly
+		{
+			readonly DefaultUnresolvedAssembly unresolvedAssembly;
+			readonly ICompilation compilation;
+			readonly ITypeResolveContext context;
+			readonly Dictionary<TopLevelTypeName, IUnresolvedTypeDefinition> unresolvedTypeDict;
+			readonly ConcurrentDictionary<IUnresolvedTypeDefinition, ITypeDefinition> typeDict = new ConcurrentDictionary<IUnresolvedTypeDefinition, ITypeDefinition>();
+			readonly INamespace rootNamespace;
+			
+			public DefaultResolvedAssembly(ICompilation compilation, DefaultUnresolvedAssembly unresolved)
+			{
+				this.compilation = compilation;
+				this.unresolvedAssembly = unresolved;
+				this.unresolvedTypeDict = unresolved.GetTypeDictionary(compilation.NameComparer);
+				this.rootNamespace = new NS(this, unresolved.GetUnresolvedRootNamespace(compilation.NameComparer), null);
+				this.context = new SimpleTypeResolveContext(this);
+				this.AssemblyAttributes = unresolved.AssemblyAttributes.CreateResolvedAttributes(context);
+				this.ModuleAttributes = unresolved.ModuleAttributes.CreateResolvedAttributes(context);
+			}
+			
+			public IUnresolvedAssembly UnresolvedAssembly {
+				get { return unresolvedAssembly; }
+			}
+			
+			public bool IsMainAssembly {
+				get { return this.Compilation.MainAssembly == this; }
+			}
+			
+			public string AssemblyName {
+				get { return unresolvedAssembly.AssemblyName; }
+			}
+			
+			public string FullAssemblyName {
+				get { return unresolvedAssembly.FullAssemblyName; }
+			}
+			
+			public IList<IAttribute> AssemblyAttributes { get; private set; }
+			public IList<IAttribute> ModuleAttributes { get; private set; }
+			
+			public INamespace RootNamespace {
+				get { return rootNamespace; }
+			}
+			
+			public ICompilation Compilation {
+				get { return compilation; }
+			}
+	
+			public bool InternalsVisibleTo(IAssembly assembly)
+			{
+				if (this == assembly)
+					return true;
+				foreach (string shortName in GetInternalsVisibleTo()) {
+					if (assembly.AssemblyName == shortName)
+						return true;
+				}
+				return false;
+			}
+
+			volatile string[] internalsVisibleTo;
+
+			string[] GetInternalsVisibleTo()
+			{
+				var result = this.internalsVisibleTo;
+				if (result != null) {
+					return result;
+				} else {
+					using (var busyLock = BusyManager.Enter(this)) {
+						Debug.Assert(busyLock.Success);
+						if (!busyLock.Success) {
+							return new string[0];
+						}
+						internalsVisibleTo = (
+							from attr in this.AssemblyAttributes
+							where attr.AttributeType.Name == "InternalsVisibleToAttribute"
+							&& attr.AttributeType.Namespace == "System.Runtime.CompilerServices"
+							&& attr.PositionalArguments.Count == 1
+							select GetShortName(attr.PositionalArguments.Single().ConstantValue as string)
+						).ToArray();
+					}
+					return internalsVisibleTo;
+				}
+			}
+
+			static string GetShortName(string fullAssemblyName)
+			{
+				if (fullAssemblyName == null)
+					return null;
+				int pos = fullAssemblyName.IndexOf(',');
+				if (pos < 0)
+					return fullAssemblyName;
+				else
+					return fullAssemblyName.Substring(0, pos);
+			}
+
+			public ITypeDefinition GetTypeDefinition(TopLevelTypeName topLevelTypeName)
+			{
+				IUnresolvedTypeDefinition td;
+				ITypeReference typeRef;
+				if (unresolvedAssembly.typeDefinitions.TryGetValue(topLevelTypeName, out td))
+					return GetTypeDefinition(td);
+				if (unresolvedAssembly.typeForwarders.TryGetValue(topLevelTypeName, out typeRef)) {
+					// Protect against cyclic type forwarders:
+					using (var busyLock = BusyManager.Enter(typeRef)) {
+						if (busyLock.Success)
+							return typeRef.Resolve(compilation.TypeResolveContext).GetDefinition();
+					}
+				}
+				return null;
+			}
+			
+			ITypeDefinition GetTypeDefinition(IUnresolvedTypeDefinition unresolved)
+			{
+				return typeDict.GetOrAdd(unresolved, t => CreateTypeDefinition(t));
+			}
+			
+			ITypeDefinition CreateTypeDefinition(IUnresolvedTypeDefinition unresolved)
+			{
+				if (unresolved.DeclaringTypeDefinition != null) {
+					ITypeDefinition declaringType = GetTypeDefinition(unresolved.DeclaringTypeDefinition);
+					return new DefaultResolvedTypeDefinition(context.WithCurrentTypeDefinition(declaringType), unresolved);
+				} else if (unresolved.Name == "Void" && unresolved.Namespace == "System" && unresolved.TypeParameters.Count == 0) {
+					return new VoidTypeDefinition(context, unresolved);
+				} else {
+					return new DefaultResolvedTypeDefinition(context, unresolved);
+				}
+			}
+			
+			public IEnumerable<ITypeDefinition> TopLevelTypeDefinitions {
+				get {
+					return unresolvedAssembly.TopLevelTypeDefinitions.Select(t => GetTypeDefinition(t));
+				}
+			}
+			
+			public override string ToString()
+			{
+				return "[DefaultResolvedAssembly " + AssemblyName + "]";
+			}
+			
+			sealed class NS : INamespace
+			{
+				readonly DefaultResolvedAssembly assembly;
+				readonly UnresolvedNamespace ns;
+				readonly INamespace parentNamespace;
+				readonly IList<NS> childNamespaces;
+				IEnumerable<ITypeDefinition> types;
+				
+				public NS(DefaultResolvedAssembly assembly, UnresolvedNamespace ns, INamespace parentNamespace)
+				{
+					this.assembly = assembly;
+					this.ns = ns;
+					this.parentNamespace = parentNamespace;
+					this.childNamespaces = new ProjectedList<NS, UnresolvedNamespace, NS>(
+						this, ns.Children, (self, c) => new NS(self.assembly, c, self));
+				}
+				
+				string INamespace.ExternAlias {
+					get { return null; }
+				}
+				
+				string INamespace.FullName {
+					get { return ns.FullName; }
+				}
+				
+				SymbolKind ISymbol.SymbolKind {
+					get { return SymbolKind.Namespace; }
+				}
+				
+				public string Name {
+					get { return ns.Name; }
+				}
+				
+				INamespace INamespace.ParentNamespace {
+					get { return parentNamespace; }
+				}
+				
+				IEnumerable<IAssembly> INamespace.ContributingAssemblies {
+					get { return new [] { assembly }; }
+				}
+				
+				IEnumerable<INamespace> INamespace.ChildNamespaces {
+					get { return childNamespaces; }
+				}
+				
+				INamespace INamespace.GetChildNamespace(string name)
+				{
+					var nameComparer = assembly.compilation.NameComparer;
+					for (int i = 0; i < childNamespaces.Count; i++) {
+						if (nameComparer.Equals(name, ns.Children[i].Name))
+							return childNamespaces[i];
+					}
+					return null;
+				}
+				
+				ICompilation ICompilationProvider.Compilation {
+					get { return assembly.compilation; }
+				}
+				
+				IEnumerable<ITypeDefinition> INamespace.Types {
+					get {
+						var result = LazyInit.VolatileRead(ref this.types);
+						if (result != null) {
+							return result;
+						} else {
+							var hashSet = new HashSet<ITypeDefinition>();
+							foreach (IUnresolvedTypeDefinition typeDef in assembly.UnresolvedAssembly.TopLevelTypeDefinitions) {
+								if (typeDef.Namespace == ns.FullName)
+									hashSet.Add(assembly.GetTypeDefinition(typeDef));
+							}
+							return LazyInit.GetOrSet(ref this.types, hashSet.ToArray());
+						}
+					}
+				}
+				
+				ITypeDefinition INamespace.GetTypeDefinition(string name, int typeParameterCount)
+				{
+					var key = new TopLevelTypeName(ns.FullName, name, typeParameterCount);
+					IUnresolvedTypeDefinition unresolvedTypeDef;
+					if (assembly.unresolvedTypeDict.TryGetValue(key, out unresolvedTypeDef))
+						return assembly.GetTypeDefinition(unresolvedTypeDef);
+					else
+						return null;
+				}
+				
+				public ISymbolReference ToReference()
+				{
+					return new NamespaceReference(new DefaultAssemblyReference(assembly.AssemblyName), ns.FullName);
+				}
+			}
+		}
+	}
+	
+	public sealed class NamespaceReference : ISymbolReference
+	{
+		IAssemblyReference assemblyReference;
+		string fullName;
+		
+		public NamespaceReference(IAssemblyReference assemblyReference, string fullName)
+		{
+			if (assemblyReference == null)
+				throw new ArgumentNullException("assemblyReference");
+			this.assemblyReference = assemblyReference;
+			this.fullName = fullName;
+		}
+		
+		public ISymbol Resolve(ITypeResolveContext context)
+		{
+			IAssembly assembly = assemblyReference.Resolve(context);
+			INamespace parent = assembly.RootNamespace;
+			
+			string[] parts = fullName.Split('.');
+			
+			int i = 0;
+			while (i < parts.Length && parent != null) {
+				parent = parent.GetChildNamespace(parts[i]);
+				i++;
+			}
+			
+			return parent;
+		}
+	}
+	
+	public sealed class MergedNamespaceReference : ISymbolReference
+	{
+		string externAlias;
+		string fullName;
+		
+		public MergedNamespaceReference(string externAlias, string fullName)
+		{
+			this.externAlias = externAlias;
+			this.fullName = fullName;
+		}
+		
+		public ISymbol Resolve(ITypeResolveContext context)
+		{
+			string[] parts = fullName.Split('.');
+			INamespace parent = context.Compilation.GetNamespaceForExternAlias(externAlias);
+			
+			int i = 0;
+			while (i < parts.Length && parent != null) {
+				parent = parent.GetChildNamespace(parts[i]);
+				i++;
+			}
+			
+			return parent;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedAttribute.cs	(revision 11807)
@@ -0,0 +1,283 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IUnresolvedAttribute"/>.
+	/// </summary>
+	[Serializable]
+	public sealed class DefaultUnresolvedAttribute : AbstractFreezable, IUnresolvedAttribute, IFreezable, ISupportsInterning
+	{
+		ITypeReference attributeType;
+		DomRegion region;
+		IList<ITypeReference> constructorParameterTypes;
+		IList<IConstantValue> positionalArguments;
+		IList<KeyValuePair<IMemberReference, IConstantValue>> namedArguments;
+		
+		public DefaultUnresolvedAttribute(ITypeReference attributeType)
+		{
+			if (attributeType == null)
+				throw new ArgumentNullException("attributeType");
+			this.attributeType = attributeType;
+		}
+		
+		public DefaultUnresolvedAttribute(ITypeReference attributeType, IEnumerable<ITypeReference> constructorParameterTypes)
+		{
+			if (attributeType == null)
+				throw new ArgumentNullException("attributeType");
+			this.attributeType = attributeType;
+			this.ConstructorParameterTypes.AddRange(constructorParameterTypes);
+		}
+		
+		protected override void FreezeInternal()
+		{
+			base.FreezeInternal();
+			constructorParameterTypes = FreezableHelper.FreezeList(constructorParameterTypes);
+			positionalArguments = FreezableHelper.FreezeListAndElements(positionalArguments);
+			namedArguments = FreezableHelper.FreezeList(namedArguments);
+			foreach (var pair in namedArguments) {
+				FreezableHelper.Freeze(pair.Key);
+				FreezableHelper.Freeze(pair.Value);
+			}
+		}
+		
+		public ITypeReference AttributeType {
+			get { return attributeType; }
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				region = value;
+			}
+		}
+		
+		public IList<ITypeReference> ConstructorParameterTypes {
+			get {
+				if (constructorParameterTypes == null)
+					constructorParameterTypes = new List<ITypeReference>();
+				return constructorParameterTypes;
+			}
+		}
+		
+		public IList<IConstantValue> PositionalArguments {
+			get {
+				if (positionalArguments == null)
+					positionalArguments = new List<IConstantValue>();
+				return positionalArguments;
+			}
+		}
+		
+		public IList<KeyValuePair<IMemberReference, IConstantValue>> NamedArguments {
+			get {
+				if (namedArguments == null)
+					namedArguments = new List<KeyValuePair<IMemberReference, IConstantValue>>();
+				return namedArguments;
+			}
+		}
+		
+		public void AddNamedFieldArgument(string fieldName, IConstantValue value)
+		{
+			this.NamedArguments.Add(new KeyValuePair<IMemberReference, IConstantValue>(
+				new DefaultMemberReference(SymbolKind.Field, attributeType, fieldName),
+				value
+			));
+		}
+		
+		public void AddNamedPropertyArgument(string propertyName, IConstantValue value)
+		{
+			this.NamedArguments.Add(new KeyValuePair<IMemberReference, IConstantValue>(
+				new DefaultMemberReference(SymbolKind.Property, attributeType, propertyName),
+				value
+			));
+		}
+		
+		public IAttribute CreateResolvedAttribute(ITypeResolveContext context)
+		{
+			return new DefaultResolvedAttribute(this, context);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			int hash = attributeType.GetHashCode() ^ constructorParameterTypes.GetHashCode();
+			unchecked {
+				if (constructorParameterTypes != null) {
+					foreach (var type in constructorParameterTypes) {
+						hash *= 27;
+						hash += type.GetHashCode();
+					}
+				}
+				if (positionalArguments != null) {
+					foreach (var arg in positionalArguments) {
+						hash *= 31;
+						hash += arg.GetHashCode();
+					}
+				}
+				if (namedArguments != null) {
+					foreach (var pair in namedArguments) {
+						hash *= 71;
+						hash += pair.Key.GetHashCode() + pair.Value.GetHashCode() * 73;
+					}
+				}
+			}
+			return hash;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			DefaultUnresolvedAttribute o = other as DefaultUnresolvedAttribute;
+			return o != null && attributeType == o.attributeType
+				&& ListEquals(constructorParameterTypes, o.constructorParameterTypes)
+				&& ListEquals(positionalArguments, o.positionalArguments)
+				&& ListEquals(namedArguments ?? EmptyList<KeyValuePair<IMemberReference, IConstantValue>>.Instance,
+				              o.namedArguments ?? EmptyList<KeyValuePair<IMemberReference, IConstantValue>>.Instance);
+		}
+		
+		static bool ListEquals<T>(IList<T> list1, IList<T> list2) where T : class
+		{
+			if (list1 == null)
+				list1 = EmptyList<T>.Instance;
+			if (list2 == null)
+				list2 = EmptyList<T>.Instance;
+			if (list1 == list2)
+				return true;
+			if (list1.Count != list2.Count)
+				return false;
+			for (int i = 0; i < list1.Count; i++) {
+				if (list1[i] != list2[i])
+					return false;
+			}
+			return true;
+		}
+		
+		static bool ListEquals(IList<KeyValuePair<IMemberReference, IConstantValue>> list1, IList<KeyValuePair<IMemberReference, IConstantValue>> list2)
+		{
+			if (list1 == list2)
+				return true;
+			if (list1.Count != list2.Count)
+				return false;
+			for (int i = 0; i < list1.Count; i++) {
+				var a = list1[i];
+				var b = list2[i];
+				if (!(a.Key == b.Key && a.Value == b.Value))
+					return false;
+			}
+			return true;
+		}
+		
+		sealed class DefaultResolvedAttribute : IAttribute, ICompilationProvider
+		{
+			readonly DefaultUnresolvedAttribute unresolved;
+			readonly ITypeResolveContext context;
+			readonly IType attributeType;
+			readonly IList<ResolveResult> positionalArguments;
+			
+			// cannot use ProjectedList because KeyValuePair is value type
+			IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
+			
+			IMethod constructor;
+			volatile bool constructorResolved;
+			
+			public DefaultResolvedAttribute(DefaultUnresolvedAttribute unresolved, ITypeResolveContext context)
+			{
+				this.unresolved = unresolved;
+				this.context = context;
+				
+				this.attributeType = unresolved.AttributeType.Resolve(context);
+				this.positionalArguments = unresolved.PositionalArguments.Resolve(context);
+			}
+			
+			public IType AttributeType {
+				get { return attributeType; }
+			}
+			
+			public DomRegion Region {
+				get { return unresolved.Region; }
+			}
+			
+			public IMethod Constructor {
+				get {
+					if (!constructorResolved) {
+						constructor = ResolveConstructor();
+						constructorResolved = true;
+					}
+					return constructor;
+				}
+			}
+			
+			IMethod ResolveConstructor()
+			{
+				var parameterTypes = unresolved.ConstructorParameterTypes.Resolve(context);
+				foreach (var ctor in attributeType.GetConstructors(m => m.Parameters.Count == parameterTypes.Count)) {
+					bool ok = true;
+					for (int i = 0; i < parameterTypes.Count; i++) {
+						if (!ctor.Parameters[i].Type.Equals(parameterTypes[i])) {
+							ok = false;
+							break;
+						}
+					}
+					if (ok)
+						return ctor;
+				}
+				return null;
+			}
+			
+			public IList<ResolveResult> PositionalArguments {
+				get { return positionalArguments; }
+			}
+			
+			public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments {
+				get {
+					var namedArgs = LazyInit.VolatileRead(ref this.namedArguments);
+					if (namedArgs != null) {
+						return namedArgs;
+					} else {
+						namedArgs = new List<KeyValuePair<IMember, ResolveResult>>();
+						foreach (var pair in unresolved.NamedArguments) {
+							IMember member = pair.Key.Resolve(context);
+							if (member != null) {
+								ResolveResult val = pair.Value.Resolve(context);
+								namedArgs.Add(new KeyValuePair<IMember, ResolveResult>(member, val));
+							}
+						}
+						return LazyInit.GetOrSet(ref this.namedArguments, namedArgs);
+					}
+				}
+			}
+			
+			public ICompilation Compilation {
+				get { return context.Compilation; }
+			}
+			
+			public override string ToString()
+			{
+				if (positionalArguments.Count == 0)
+					return "[" + attributeType.ToString() + "]";
+				else
+					return "[" + attributeType.ToString() + "(...)]";
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedEvent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedEvent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedEvent.cs	(revision 11807)
@@ -0,0 +1,99 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IUnresolvedEvent"/>.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedEvent : AbstractUnresolvedMember, IUnresolvedEvent
+	{
+		IUnresolvedMethod addAccessor, removeAccessor, invokeAccessor;
+		
+		protected override void FreezeInternal()
+		{
+			base.FreezeInternal();
+			FreezableHelper.Freeze(addAccessor);
+			FreezableHelper.Freeze(removeAccessor);
+			FreezableHelper.Freeze(invokeAccessor);
+		}
+		
+		public DefaultUnresolvedEvent()
+		{
+			this.SymbolKind = SymbolKind.Event;
+		}
+		
+		public DefaultUnresolvedEvent(IUnresolvedTypeDefinition declaringType, string name)
+		{
+			this.SymbolKind = SymbolKind.Event;
+			this.DeclaringTypeDefinition = declaringType;
+			this.Name = name;
+			if (declaringType != null)
+				this.UnresolvedFile = declaringType.UnresolvedFile;
+		}
+		
+		public bool CanAdd {
+			get { return addAccessor != null; }
+		}
+		
+		public bool CanRemove {
+			get { return removeAccessor != null; }
+		}
+		
+		public bool CanInvoke {
+			get { return invokeAccessor != null; }
+		}
+		
+		public IUnresolvedMethod AddAccessor {
+			get { return addAccessor; }
+			set {
+				ThrowIfFrozen();
+				addAccessor = value;
+			}
+		}
+		
+		public IUnresolvedMethod RemoveAccessor {
+			get { return removeAccessor; }
+			set {
+				ThrowIfFrozen();
+				removeAccessor = value;
+			}
+		}
+		
+		public IUnresolvedMethod InvokeAccessor {
+			get { return invokeAccessor; }
+			set {
+				ThrowIfFrozen();
+				invokeAccessor = value;
+			}
+		}
+		
+		public override IMember CreateResolved(ITypeResolveContext context)
+		{
+			return new DefaultResolvedEvent(this, context);
+		}
+		
+		IEvent IUnresolvedEvent.Resolve(ITypeResolveContext context)
+		{
+			return (IEvent)Resolve(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedField.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedField.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedField.cs	(revision 11807)
@@ -0,0 +1,97 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IUnresolvedField"/>.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedField : AbstractUnresolvedMember, IUnresolvedField
+	{
+		IConstantValue constantValue;
+		
+		protected override void FreezeInternal()
+		{
+			FreezableHelper.Freeze(constantValue);
+			base.FreezeInternal();
+		}
+		
+		public DefaultUnresolvedField()
+		{
+			this.SymbolKind = SymbolKind.Field;
+		}
+		
+		public DefaultUnresolvedField(IUnresolvedTypeDefinition declaringType, string name)
+		{
+			this.SymbolKind = SymbolKind.Field;
+			this.DeclaringTypeDefinition = declaringType;
+			this.Name = name;
+			if (declaringType != null)
+				this.UnresolvedFile = declaringType.UnresolvedFile;
+		}
+		
+		public bool IsConst {
+			get { return constantValue != null && !IsFixed; }
+		}
+		
+		public bool IsReadOnly {
+			get { return flags[FlagFieldIsReadOnly]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagFieldIsReadOnly] = value;
+			}
+		}
+		
+		public bool IsVolatile {
+			get { return flags[FlagFieldIsVolatile]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagFieldIsVolatile] = value;
+			}
+		}
+
+		public bool IsFixed {
+			get { return flags[FlagFieldIsFixedSize]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagFieldIsFixedSize] = value;
+			}
+		}
+		
+		public IConstantValue ConstantValue {
+			get { return constantValue; }
+			set {
+				ThrowIfFrozen();
+				constantValue = value;
+			}
+		}
+		
+		public override IMember CreateResolved(ITypeResolveContext context)
+		{
+			return new DefaultResolvedField(this, context);
+		}
+		
+		IField IUnresolvedField.Resolve(ITypeResolveContext context)
+		{
+			return (IField)Resolve(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedMethod.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedMethod.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedMethod.cs	(revision 11807)
@@ -0,0 +1,287 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IUnresolvedMethod" /> interface.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedMethod : AbstractUnresolvedMember, IUnresolvedMethod
+	{
+		IList<IUnresolvedAttribute> returnTypeAttributes;
+		IList<IUnresolvedTypeParameter> typeParameters;
+		IList<IUnresolvedParameter> parameters;
+		IUnresolvedMember accessorOwner;
+		
+		protected override void FreezeInternal()
+		{
+			returnTypeAttributes = FreezableHelper.FreezeListAndElements(returnTypeAttributes);
+			typeParameters = FreezableHelper.FreezeListAndElements(typeParameters);
+			parameters = FreezableHelper.FreezeListAndElements(parameters);
+			base.FreezeInternal();
+		}
+		
+		public override object Clone()
+		{
+			var copy = (DefaultUnresolvedMethod)base.Clone();
+			if (returnTypeAttributes != null)
+				copy.returnTypeAttributes = new List<IUnresolvedAttribute>(returnTypeAttributes);
+			if (typeParameters != null)
+				copy.typeParameters = new List<IUnresolvedTypeParameter>(typeParameters);
+			if (parameters != null)
+				copy.parameters = new List<IUnresolvedParameter>(parameters);
+			return copy;
+		}
+		
+		public override void ApplyInterningProvider(InterningProvider provider)
+		{
+			base.ApplyInterningProvider(provider);
+			if (provider != null) {
+				returnTypeAttributes = provider.InternList(returnTypeAttributes);
+				typeParameters = provider.InternList(typeParameters);
+				parameters = provider.InternList(parameters);
+			}
+		}
+		
+		public DefaultUnresolvedMethod()
+		{
+			this.SymbolKind = SymbolKind.Method;
+		}
+		
+		public DefaultUnresolvedMethod(IUnresolvedTypeDefinition declaringType, string name)
+		{
+			this.SymbolKind = SymbolKind.Method;
+			this.DeclaringTypeDefinition = declaringType;
+			this.Name = name;
+			if (declaringType != null)
+				this.UnresolvedFile = declaringType.UnresolvedFile;
+		}
+		
+		public IList<IUnresolvedAttribute> ReturnTypeAttributes {
+			get {
+				if (returnTypeAttributes == null)
+					returnTypeAttributes = new List<IUnresolvedAttribute>();
+				return returnTypeAttributes;
+			}
+		}
+		
+		public IList<IUnresolvedTypeParameter> TypeParameters {
+			get {
+				if (typeParameters == null)
+					typeParameters = new List<IUnresolvedTypeParameter>();
+				return typeParameters;
+			}
+		}
+		
+		public bool IsExtensionMethod {
+			get { return flags[FlagExtensionMethod]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagExtensionMethod] = value;
+			}
+		}
+		
+		public bool IsConstructor {
+			get { return this.SymbolKind == SymbolKind.Constructor; }
+		}
+		
+		public bool IsDestructor {
+			get { return this.SymbolKind == SymbolKind.Destructor; }
+		}
+		
+		public bool IsOperator {
+			get { return this.SymbolKind == SymbolKind.Operator; }
+		}
+		
+		public bool IsPartial {
+			get { return flags[FlagPartialMethod]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagPartialMethod] = value;
+			}
+		}
+
+		public bool IsAsync {
+			get { return flags[FlagAsyncMethod]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagAsyncMethod] = value;
+			}
+		}
+
+		public bool HasBody {
+			get { return flags[FlagHasBody]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagHasBody] = value;
+			}
+		}
+		
+		[Obsolete]
+		public bool IsPartialMethodDeclaration {
+			get { return IsPartial && !HasBody; }
+			set {
+				if (value) {
+					IsPartial = true;
+					HasBody = false;
+				} else if (!value && IsPartial && !HasBody) {
+					IsPartial = false;
+				}
+			}
+		}
+		
+		[Obsolete]
+		public bool IsPartialMethodImplementation {
+			get { return IsPartial && HasBody; }
+			set {
+				if (value) {
+					IsPartial = true;
+					HasBody = true;
+				} else if (!value && IsPartial && HasBody) {
+					IsPartial = false;
+				}
+			}
+		}
+		
+		public IList<IUnresolvedParameter> Parameters {
+			get {
+				if (parameters == null)
+					parameters = new List<IUnresolvedParameter>();
+				return parameters;
+			}
+		}
+		
+		public IUnresolvedMember AccessorOwner {
+			get { return accessorOwner; }
+			set {
+				ThrowIfFrozen();
+				accessorOwner = value;
+			}
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[");
+			b.Append(SymbolKind.ToString());
+			b.Append(' ');
+			if (DeclaringTypeDefinition != null) {
+				b.Append(DeclaringTypeDefinition.Name);
+				b.Append('.');
+			}
+			b.Append(Name);
+			b.Append('(');
+			b.Append(string.Join(", ", this.Parameters));
+			b.Append("):");
+			b.Append(ReturnType.ToString());
+			b.Append(']');
+			return b.ToString();
+		}
+		
+		public override IMember CreateResolved(ITypeResolveContext context)
+		{
+			return new DefaultResolvedMethod(this, context);
+		}
+		
+		public override IMember Resolve(ITypeResolveContext context)
+		{
+			if (accessorOwner != null) {
+				var owner = accessorOwner.Resolve(context);
+				if (owner != null) {
+					IProperty p = owner as IProperty;
+					if (p != null) {
+						if (p.CanGet && p.Getter.Name == this.Name)
+							return p.Getter;
+						if (p.CanSet && p.Setter.Name == this.Name)
+							return p.Setter;
+					}
+					IEvent e = owner as IEvent;
+					if (e != null) {
+						if (e.CanAdd && e.AddAccessor.Name == this.Name)
+							return e.AddAccessor;
+						if (e.CanRemove && e.RemoveAccessor.Name == this.Name)
+							return e.RemoveAccessor;
+						if (e.CanInvoke && e.InvokeAccessor.Name == this.Name)
+							return e.InvokeAccessor;
+					}
+				}
+				return null;
+			}
+			
+			ITypeReference interfaceTypeReference = null;
+			if (this.IsExplicitInterfaceImplementation && this.ExplicitInterfaceImplementations.Count == 1)
+				interfaceTypeReference = this.ExplicitInterfaceImplementations[0].DeclaringTypeReference;
+			return Resolve(ExtendContextForType(context, this.DeclaringTypeDefinition),
+			               this.SymbolKind, this.Name, interfaceTypeReference,
+			               this.TypeParameters.Select(tp => tp.Name).ToList(),
+			               this.Parameters.Select(p => p.Type).ToList());
+		}
+		
+		IMethod IUnresolvedMethod.Resolve(ITypeResolveContext context)
+		{
+			return (IMethod)Resolve(context);
+		}
+		
+		public static DefaultUnresolvedMethod CreateDefaultConstructor(IUnresolvedTypeDefinition typeDefinition)
+		{
+			if (typeDefinition == null)
+				throw new ArgumentNullException("typeDefinition");
+			DomRegion region = typeDefinition.Region;
+			region = new DomRegion(region.FileName, region.BeginLine, region.BeginColumn); // remove endline/endcolumn
+			return new DefaultUnresolvedMethod(typeDefinition, ".ctor") {
+				SymbolKind = SymbolKind.Constructor,
+				Accessibility = typeDefinition.IsAbstract ? Accessibility.Protected : Accessibility.Public,
+				IsSynthetic = true,
+				HasBody = true,
+				Region = region,
+				BodyRegion = region,
+				ReturnType = KnownTypeReference.Void
+			};
+		}
+		
+		static readonly IUnresolvedMethod dummyConstructor = CreateDummyConstructor();
+		
+		/// <summary>
+		/// Returns a dummy constructor instance:
+		/// </summary>
+		/// <returns>
+		/// A public instance constructor with IsSynthetic=true and no declaring type.
+		/// </returns>
+		public static IUnresolvedMethod DummyConstructor {
+			get { return dummyConstructor; }
+		}
+		
+		static IUnresolvedMethod CreateDummyConstructor()
+		{
+			var m = new DefaultUnresolvedMethod {
+				SymbolKind = SymbolKind.Constructor,
+				Name = ".ctor",
+				Accessibility = Accessibility.Public,
+				IsSynthetic = true,
+				ReturnType = KnownTypeReference.Void
+			};
+			m.Freeze();
+			return m;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedParameter.cs	(revision 11807)
@@ -0,0 +1,275 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation for IUnresolvedParameter.
+	/// </summary>
+	[Serializable]
+	public sealed class DefaultUnresolvedParameter : IUnresolvedParameter, IFreezable, ISupportsInterning
+	{
+		string name = string.Empty;
+		ITypeReference type = SpecialType.UnknownType;
+		IList<IUnresolvedAttribute> attributes;
+		IConstantValue defaultValue;
+		DomRegion region;
+		byte flags;
+		
+		public DefaultUnresolvedParameter()
+		{
+		}
+		
+		public DefaultUnresolvedParameter(ITypeReference type, string name)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.type = type;
+			this.name = name;
+		}
+		
+		void FreezeInternal()
+		{
+			attributes = FreezableHelper.FreezeListAndElements(attributes);
+			FreezableHelper.Freeze(defaultValue);
+		}
+		
+		public string Name {
+			get { return name; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				FreezableHelper.ThrowIfFrozen(this);
+				name = value;
+			}
+		}
+		
+		public ITypeReference Type {
+			get { return type; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				FreezableHelper.ThrowIfFrozen(this);
+				type = value;
+			}
+		}
+		
+		public IList<IUnresolvedAttribute> Attributes {
+			get {
+				if (attributes == null)
+					attributes = new List<IUnresolvedAttribute>();
+				return attributes;
+			}
+		}
+		
+		public IConstantValue DefaultValue {
+			get { return defaultValue; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				defaultValue = value;
+			}
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				region = value;
+			}
+		}
+		
+		bool HasFlag(byte flag)
+		{
+			return (this.flags & flag) != 0;
+		}
+		void SetFlag(byte flag, bool value)
+		{
+			FreezableHelper.ThrowIfFrozen(this);
+			if (value)
+				this.flags |= flag;
+			else
+				this.flags &= unchecked((byte)~flag);
+		}
+		
+		public bool IsFrozen {
+			get { return HasFlag(1); }
+		}
+		
+		public void Freeze()
+		{
+			if (!this.IsFrozen) {
+				FreezeInternal();
+				this.flags |= 1;
+			}
+		}
+		
+		public bool IsRef {
+			get { return HasFlag(2); }
+			set { SetFlag(2, value); }
+		}
+		
+		public bool IsOut {
+			get { return HasFlag(4); }
+			set { SetFlag(4, value); }
+		}
+		
+		public bool IsParams {
+			get { return HasFlag(8); }
+			set { SetFlag(8, value); }
+		}
+		
+		public bool IsOptional {
+			get { return this.DefaultValue != null; }
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				int hashCode = 1919191 ^ (flags & ~1);
+				hashCode *= 31;
+				hashCode += type.GetHashCode();
+				hashCode *= 31;
+				hashCode += name.GetHashCode();
+				if (attributes != null) {
+					foreach (var attr in attributes)
+						hashCode ^= attr.GetHashCode ();
+				}
+				if (defaultValue != null)
+					hashCode ^= defaultValue.GetHashCode ();
+				return hashCode;
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			// compare everything except for the IsFrozen flag
+			DefaultUnresolvedParameter p = other as DefaultUnresolvedParameter;
+			return p != null && type == p.type && name == p.name &&
+				defaultValue == p.defaultValue && region == p.region && (flags & ~1) == (p.flags & ~1) && ListEquals(attributes, p.attributes);
+		}
+		
+		static bool ListEquals(IList<IUnresolvedAttribute> list1, IList<IUnresolvedAttribute> list2)
+		{
+			return (list1 ?? EmptyList<IUnresolvedAttribute>.Instance).SequenceEqual(list2 ?? EmptyList<IUnresolvedAttribute>.Instance);
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder();
+			if (IsRef)
+				b.Append("ref ");
+			if (IsOut)
+				b.Append("out ");
+			if (IsParams)
+				b.Append("params ");
+			b.Append(name);
+			b.Append(':');
+			b.Append(type.ToString());
+			if (defaultValue != null) {
+				b.Append(" = ");
+				b.Append(defaultValue.ToString());
+			}
+			return b.ToString();
+		}
+
+		static bool IsOptionalAttribute (IType attributeType)
+		{
+			return attributeType.Name == "OptionalAttribute" && attributeType.Namespace == "System.Runtime.InteropServices";
+		}
+		
+		public IParameter CreateResolvedParameter(ITypeResolveContext context)
+		{
+			Freeze();
+			if (defaultValue != null) {
+				return new ResolvedParameterWithDefaultValue(defaultValue, context) {
+					Type = type.Resolve(context),
+					Name = name,
+					Region = region,
+					Attributes = attributes.CreateResolvedAttributes(context),
+					IsRef = this.IsRef,
+					IsOut = this.IsOut,
+					IsParams = this.IsParams
+				};
+			} else {
+				var owner = context.CurrentMember as IParameterizedMember;
+				var resolvedAttributes = attributes.CreateResolvedAttributes (context);
+				bool isOptional = resolvedAttributes != null && resolvedAttributes.Any (a => IsOptionalAttribute (a.AttributeType));
+				return new DefaultParameter (type.Resolve (context), name, owner, region,
+				                             resolvedAttributes, IsRef, IsOut, IsParams, isOptional);
+			}
+		}
+		
+		sealed class ResolvedParameterWithDefaultValue : IParameter
+		{
+			readonly IConstantValue defaultValue;
+			readonly ITypeResolveContext context;
+			
+			public ResolvedParameterWithDefaultValue(IConstantValue defaultValue, ITypeResolveContext context)
+			{
+				this.defaultValue = defaultValue;
+				this.context = context;
+			}
+			
+			SymbolKind ISymbol.SymbolKind { get { return SymbolKind.Parameter; } }
+			public IParameterizedMember Owner { get { return context.CurrentMember as IParameterizedMember; } }
+			public IType Type { get; internal set; }
+			public string Name { get; internal set; }
+			public DomRegion Region { get; internal set; }
+			public IList<IAttribute> Attributes { get; internal set; }
+			public bool IsRef { get; internal set; }
+			public bool IsOut { get; internal set; }
+			public bool IsParams { get; internal set; }
+			public bool IsOptional { get { return true; } }
+			bool IVariable.IsConst { get { return false; } }
+			
+			ResolveResult resolvedDefaultValue;
+			
+			public object ConstantValue {
+				get {
+					ResolveResult rr = LazyInit.VolatileRead(ref this.resolvedDefaultValue);
+					if (rr == null) {
+						rr = defaultValue.Resolve(context);
+						LazyInit.GetOrSet(ref this.resolvedDefaultValue, rr);
+					}
+					return rr.ConstantValue;
+				}
+			}
+			
+			public override string ToString()
+			{
+				return DefaultParameter.ToString(this);
+			}
+
+			public ISymbolReference ToReference()
+			{
+				if (Owner == null)
+					return new ParameterReference(Type.ToTypeReference(), Name, Region, IsRef, IsOut, IsParams, true, ConstantValue);
+				return new OwnedParameterReference(Owner.ToReference(), Owner.Parameters.IndexOf(this));
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedProperty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedProperty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedProperty.cs	(revision 11807)
@@ -0,0 +1,126 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IUnresolvedProperty"/>.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedProperty : AbstractUnresolvedMember, IUnresolvedProperty
+	{
+		IUnresolvedMethod getter, setter;
+		IList<IUnresolvedParameter> parameters;
+		
+		protected override void FreezeInternal()
+		{
+			parameters = FreezableHelper.FreezeListAndElements(parameters);
+			FreezableHelper.Freeze(getter);
+			FreezableHelper.Freeze(setter);
+			base.FreezeInternal();
+		}
+		
+		public override object Clone()
+		{
+			var copy = (DefaultUnresolvedProperty)base.Clone();
+			if (parameters != null)
+				copy.parameters = new List<IUnresolvedParameter>(parameters);
+			return copy;
+		}
+		
+		public override void ApplyInterningProvider(InterningProvider provider)
+		{
+			base.ApplyInterningProvider(provider);
+			parameters = provider.InternList(parameters);
+		}
+		
+		public DefaultUnresolvedProperty()
+		{
+			this.SymbolKind = SymbolKind.Property;
+		}
+		
+		public DefaultUnresolvedProperty(IUnresolvedTypeDefinition declaringType, string name)
+		{
+			this.SymbolKind = SymbolKind.Property;
+			this.DeclaringTypeDefinition = declaringType;
+			this.Name = name;
+			if (declaringType != null)
+				this.UnresolvedFile = declaringType.UnresolvedFile;
+		}
+		
+		public bool IsIndexer {
+			get { return this.SymbolKind == SymbolKind.Indexer; }
+		}
+		
+		public IList<IUnresolvedParameter> Parameters {
+			get {
+				if (parameters == null)
+					parameters = new List<IUnresolvedParameter>();
+				return parameters;
+			}
+		}
+		
+		public bool CanGet {
+			get { return getter != null; }
+		}
+		
+		public bool CanSet {
+			get { return setter != null; }
+		}
+		
+		public IUnresolvedMethod Getter {
+			get { return getter; }
+			set {
+				ThrowIfFrozen();
+				getter = value;
+			}
+		}
+		
+		public IUnresolvedMethod Setter {
+			get { return setter; }
+			set {
+				ThrowIfFrozen();
+				setter = value;
+			}
+		}
+		
+		public override IMember CreateResolved(ITypeResolveContext context)
+		{
+			return new DefaultResolvedProperty(this, context);
+		}
+		
+		public override IMember Resolve(ITypeResolveContext context)
+		{
+			ITypeReference interfaceTypeReference = null;
+			if (this.IsExplicitInterfaceImplementation && this.ExplicitInterfaceImplementations.Count == 1)
+				interfaceTypeReference = this.ExplicitInterfaceImplementations[0].DeclaringTypeReference;
+			return Resolve(ExtendContextForType(context, this.DeclaringTypeDefinition), 
+			               this.SymbolKind, this.Name, interfaceTypeReference,
+			               parameterTypeReferences: this.Parameters.Select(p => p.Type).ToList());
+		}
+		
+		IProperty IUnresolvedProperty.Resolve(ITypeResolveContext context)
+		{
+			return (IProperty)Resolve(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedTypeDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedTypeDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedTypeDefinition.cs	(revision 11807)
@@ -0,0 +1,240 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Represents an unresolved type definition.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedTypeDefinition : AbstractUnresolvedEntity, IUnresolvedTypeDefinition
+	{
+		TypeKind kind = TypeKind.Class;
+		string namespaceName;
+		IList<ITypeReference> baseTypes;
+		IList<IUnresolvedTypeParameter> typeParameters;
+		IList<IUnresolvedTypeDefinition> nestedTypes;
+		IList<IUnresolvedMember> members;
+		
+		public DefaultUnresolvedTypeDefinition()
+		{
+			this.SymbolKind = SymbolKind.TypeDefinition;
+		}
+		
+		public DefaultUnresolvedTypeDefinition(string fullName)
+		{
+			string namespaceName;
+			string name;
+			int idx = fullName.LastIndexOf ('.');
+			if (idx > 0) {
+				namespaceName = fullName.Substring (0, idx);
+				name = fullName.Substring (idx + 1);
+			} else {
+				namespaceName = "";
+				name = fullName;
+			}
+
+			this.SymbolKind = SymbolKind.TypeDefinition;
+			this.namespaceName = namespaceName;
+			this.Name = name;
+		}
+		
+		public DefaultUnresolvedTypeDefinition(string namespaceName, string name)
+		{
+			this.SymbolKind = SymbolKind.TypeDefinition;
+			this.namespaceName = namespaceName;
+			this.Name = name;
+		}
+		
+		public DefaultUnresolvedTypeDefinition(IUnresolvedTypeDefinition declaringTypeDefinition, string name)
+		{
+			this.SymbolKind = SymbolKind.TypeDefinition;
+			this.DeclaringTypeDefinition = declaringTypeDefinition;
+			this.namespaceName = declaringTypeDefinition.Namespace;
+			this.Name = name;
+			this.UnresolvedFile = declaringTypeDefinition.UnresolvedFile;
+		}
+		
+		protected override void FreezeInternal()
+		{
+			base.FreezeInternal();
+			baseTypes = FreezableHelper.FreezeList(baseTypes);
+			typeParameters = FreezableHelper.FreezeListAndElements(typeParameters);
+			nestedTypes = FreezableHelper.FreezeListAndElements(nestedTypes);
+			members = FreezableHelper.FreezeListAndElements(members);
+		}
+		
+		public override object Clone()
+		{
+			var copy = (DefaultUnresolvedTypeDefinition)base.Clone();
+			if (baseTypes != null)
+				copy.baseTypes = new List<ITypeReference>(baseTypes);
+			if (typeParameters != null)
+				copy.typeParameters = new List<IUnresolvedTypeParameter>(typeParameters);
+			if (nestedTypes != null)
+				copy.nestedTypes = new List<IUnresolvedTypeDefinition>(nestedTypes);
+			if (members != null)
+				copy.members = new List<IUnresolvedMember>(members);
+			return copy;
+		}
+		
+		public TypeKind Kind {
+			get { return kind; }
+			set {
+				ThrowIfFrozen();
+				kind = value;
+			}
+		}
+		
+		public bool AddDefaultConstructorIfRequired {
+			get { return flags[FlagAddDefaultConstructorIfRequired]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagAddDefaultConstructorIfRequired] = value;
+			}
+		}
+		
+		public bool? HasExtensionMethods {
+			get {
+				if (flags[FlagHasExtensionMethods])
+					return true;
+				else if (flags[FlagHasNoExtensionMethods])
+					return false;
+				else
+					return null;
+			}
+			set {
+				ThrowIfFrozen();
+				flags[FlagHasExtensionMethods] = (value == true);
+				flags[FlagHasNoExtensionMethods] = (value == false);
+			}
+		}
+		
+		public bool IsPartial {
+			get { return flags[FlagPartialTypeDefinition]; }
+			set {
+				ThrowIfFrozen();
+				flags[FlagPartialTypeDefinition] = value;
+			}
+		}
+		
+		public override string Namespace {
+			get { return namespaceName; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				ThrowIfFrozen();
+				namespaceName = value;
+			}
+		}
+		
+		public override string ReflectionName {
+			get {
+				return this.FullTypeName.ReflectionName;
+			}
+		}
+		
+		public FullTypeName FullTypeName {
+			get {
+				IUnresolvedTypeDefinition declaringTypeDef = this.DeclaringTypeDefinition;
+				if (declaringTypeDef != null) {
+					return declaringTypeDef.FullTypeName.NestedType(this.Name, this.TypeParameters.Count - declaringTypeDef.TypeParameters.Count);
+				} else {
+					return new TopLevelTypeName(namespaceName, this.Name, this.TypeParameters.Count);
+				}
+			}
+		}
+		
+		public IList<ITypeReference> BaseTypes {
+			get {
+				if (baseTypes == null)
+					baseTypes = new List<ITypeReference>();
+				return baseTypes;
+			}
+		}
+		
+		public IList<IUnresolvedTypeParameter> TypeParameters {
+			get {
+				if (typeParameters == null)
+					typeParameters = new List<IUnresolvedTypeParameter>();
+				return typeParameters;
+			}
+		}
+		
+		public IList<IUnresolvedTypeDefinition> NestedTypes {
+			get {
+				if (nestedTypes == null)
+					nestedTypes = new List<IUnresolvedTypeDefinition>();
+				return nestedTypes;
+			}
+		}
+		
+		public IList<IUnresolvedMember> Members {
+			get {
+				if (members == null)
+					members = new List<IUnresolvedMember>();
+				return members;
+			}
+		}
+		
+		public IEnumerable<IUnresolvedMethod> Methods {
+			get {
+				return Members.OfType<IUnresolvedMethod> ();
+			}
+		}
+		
+		public IEnumerable<IUnresolvedProperty> Properties {
+			get {
+				return Members.OfType<IUnresolvedProperty> ();
+			}
+		}
+		
+		public IEnumerable<IUnresolvedField> Fields {
+			get {
+				return Members.OfType<IUnresolvedField> ();
+			}
+		}
+		
+		public IEnumerable<IUnresolvedEvent> Events {
+			get {
+				return Members.OfType<IUnresolvedEvent> ();
+			}
+		}
+		
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			if (context.CurrentAssembly == null)
+				throw new ArgumentException("An ITypeDefinition cannot be resolved in a context without a current assembly.");
+			return context.CurrentAssembly.GetTypeDefinition(this.FullTypeName)
+				?? (IType)new UnknownType(this.Namespace, this.Name, this.TypeParameters.Count);
+		}
+		
+		public virtual ITypeResolveContext CreateResolveContext(ITypeResolveContext parentContext)
+		{
+			return parentContext;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultUnresolvedTypeParameter.cs	(revision 11807)
@@ -0,0 +1,194 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IUnresolvedTypeParameter"/>.
+	/// </summary>
+	[Serializable]
+	public class DefaultUnresolvedTypeParameter : IUnresolvedTypeParameter, IFreezable
+	{
+		readonly int index;
+		IList<IUnresolvedAttribute> attributes;
+		IList<ITypeReference> constraints;
+		string name;
+		DomRegion region;
+		
+		SymbolKind ownerType;
+		VarianceModifier variance;
+		BitVector16 flags;
+		const ushort FlagFrozen                       = 0x0001;
+		const ushort FlagReferenceTypeConstraint      = 0x0002;
+		const ushort FlagValueTypeConstraint          = 0x0004;
+		const ushort FlagDefaultConstructorConstraint = 0x0008;
+		
+		public void Freeze()
+		{
+			if (!flags[FlagFrozen]) {
+				FreezeInternal();
+				flags[FlagFrozen] = true;
+			}
+		}
+		
+		protected virtual void FreezeInternal()
+		{
+			attributes = FreezableHelper.FreezeListAndElements(attributes);
+			constraints = FreezableHelper.FreezeList(constraints);
+		}
+		
+		public DefaultUnresolvedTypeParameter(SymbolKind ownerType, int index, string name = null)
+		{
+			this.ownerType = ownerType;
+			this.index = index;
+			this.name = name ?? ((ownerType == SymbolKind.Method ? "!!" : "!") + index.ToString(CultureInfo.InvariantCulture));
+		}
+		
+		public SymbolKind OwnerType {
+			get { return ownerType; }
+		}
+		
+		public int Index {
+			get { return index; }
+		}
+		
+		public bool IsFrozen {
+			get { return flags[FlagFrozen]; }
+		}
+		
+		public string Name {
+			get { return name; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				name = value;
+			}
+		}
+		
+		string INamedElement.FullName {
+			get { return name; }
+		}
+		
+		string INamedElement.Namespace {
+			get { return string.Empty; }
+		}
+		
+		string INamedElement.ReflectionName {
+			get {
+				if (ownerType == SymbolKind.Method)
+					return "``" + index.ToString(CultureInfo.InvariantCulture);
+				else
+					return "`" + index.ToString(CultureInfo.InvariantCulture);
+			}
+		}
+		
+		public IList<IUnresolvedAttribute> Attributes {
+			get {
+				if (attributes == null)
+					attributes = new List<IUnresolvedAttribute>();
+				return attributes;
+			}
+		}
+		
+		public IList<ITypeReference> Constraints {
+			get {
+				if (constraints == null)
+					constraints = new List<ITypeReference>();
+				return constraints;
+			}
+		}
+		
+		public VarianceModifier Variance {
+			get { return variance; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				variance = value;
+			}
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				region = value;
+			}
+		}
+		
+		public bool HasDefaultConstructorConstraint {
+			get { return flags[FlagDefaultConstructorConstraint]; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				flags[FlagDefaultConstructorConstraint] = value;
+			}
+		}
+		
+		public bool HasReferenceTypeConstraint {
+			get { return flags[FlagReferenceTypeConstraint]; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				flags[FlagReferenceTypeConstraint] = value;
+			}
+		}
+		
+		public bool HasValueTypeConstraint {
+			get { return flags[FlagValueTypeConstraint]; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				flags[FlagValueTypeConstraint] = value;
+			}
+		}
+		
+		/// <summary>
+		/// Uses the specified interning provider to intern
+		/// strings and lists in this entity.
+		/// This method does not test arbitrary objects to see if they implement ISupportsInterning;
+		/// instead we assume that those are interned immediately when they are created (before they are added to this entity).
+		/// </summary>
+		public virtual void ApplyInterningProvider(InterningProvider provider)
+		{
+			if (provider == null)
+				throw new ArgumentNullException("provider");
+			FreezableHelper.ThrowIfFrozen(this);
+			name = provider.Intern(name);
+			attributes = provider.InternList(attributes);
+			constraints = provider.InternList(constraints);
+		}
+		
+		public virtual ITypeParameter CreateResolvedTypeParameter(ITypeResolveContext context)
+		{
+			IEntity owner = null;
+			if (this.OwnerType == SymbolKind.Method) {
+				owner = context.CurrentMember as IMethod;
+			} else if (this.OwnerType == SymbolKind.TypeDefinition) {
+				owner = context.CurrentTypeDefinition;
+			}
+			if (owner == null)
+				throw new InvalidOperationException("Could not determine the type parameter's owner.");
+			return new DefaultTypeParameter(
+				owner, index, name, variance,
+				this.Attributes.CreateResolvedAttributes(context), this.Region,
+				this.HasValueTypeConstraint, this.HasReferenceTypeConstraint, this.HasDefaultConstructorConstraint, this.Constraints.Resolve(context)
+			);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultVariable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultVariable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DefaultVariable.cs	(revision 11807)
@@ -0,0 +1,109 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Default implementation of <see cref="IVariable"/>.
+	/// </summary>
+	public sealed class DefaultVariable : IVariable
+	{
+		readonly string name;
+		readonly DomRegion region;
+		readonly IType type;
+		readonly object constantValue;
+		readonly bool isConst;
+		
+		public DefaultVariable(IType type, string name)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.type = type;
+			this.name = name;
+		}
+		
+		public DefaultVariable(IType type, string name, DomRegion region = default(DomRegion),
+		                       bool isConst = false, object constantValue = null)
+			: this(type, name)
+		{
+			this.region = region;
+			this.isConst = isConst;
+			this.constantValue = constantValue;
+		}
+		
+		public string Name {
+			get { return name; }
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+		}
+		
+		public IType Type {
+			get { return type; }
+		}
+		
+		public bool IsConst {
+			get { return isConst; }
+		}
+		
+		public object ConstantValue {
+			get { return constantValue; }
+		}
+		
+		public SymbolKind SymbolKind {
+			get { return SymbolKind.Variable; }
+		}
+
+		public ISymbolReference ToReference()
+		{
+			return new VariableReference(type.ToTypeReference(), name, region, isConst, constantValue);
+		}
+	}
+	
+	public sealed class VariableReference : ISymbolReference
+	{
+		ITypeReference variableTypeReference;
+		string name;
+		DomRegion region;
+		bool isConst;
+		object constantValue;
+		
+		public VariableReference(ITypeReference variableTypeReference, string name, DomRegion region, bool isConst, object constantValue)
+		{
+			if (variableTypeReference == null)
+				throw new ArgumentNullException("variableTypeReference");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.variableTypeReference = variableTypeReference;
+			this.name = name;
+			this.region = region;
+			this.isConst = isConst;
+			this.constantValue = constantValue;
+		}
+		
+		public ISymbol Resolve(ITypeResolveContext context)
+		{
+			return new DefaultVariable(variableTypeReference.Resolve(context), name, region, isConst, constantValue);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DummyTypeParameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DummyTypeParameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/DummyTypeParameter.cs	(revision 11807)
@@ -0,0 +1,217 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public sealed class DummyTypeParameter : AbstractType, ITypeParameter
+	{
+		static ITypeParameter[] methodTypeParameters = { new DummyTypeParameter(SymbolKind.Method, 0) };
+		static ITypeParameter[] classTypeParameters = { new DummyTypeParameter(SymbolKind.TypeDefinition, 0) };
+		
+		public static ITypeParameter GetMethodTypeParameter(int index)
+		{
+			return GetTypeParameter(ref methodTypeParameters, SymbolKind.Method, index);
+		}
+		
+		public static ITypeParameter GetClassTypeParameter(int index)
+		{
+			return GetTypeParameter(ref classTypeParameters, SymbolKind.TypeDefinition, index);
+		}
+		
+		static ITypeParameter GetTypeParameter(ref ITypeParameter[] typeParameters, SymbolKind symbolKind, int index)
+		{
+			ITypeParameter[] tps = typeParameters;
+			while (index >= tps.Length) {
+				// We don't have a normal type parameter for this index, so we need to extend our array.
+				// Because the array can be used concurrently from multiple threads, we have to use
+				// Interlocked.CompareExchange.
+				ITypeParameter[] newTps = new ITypeParameter[index + 1];
+				tps.CopyTo(newTps, 0);
+				for (int i = tps.Length; i < newTps.Length; i++) {
+					newTps[i] = new DummyTypeParameter(symbolKind, i);
+				}
+				ITypeParameter[] oldTps = Interlocked.CompareExchange(ref typeParameters, newTps, tps);
+				if (oldTps == tps) {
+					// exchange successful
+					tps = newTps;
+				} else {
+					// exchange not successful
+					tps = oldTps;
+				}
+			}
+			return tps[index];
+		}
+		
+		sealed class NormalizeMethodTypeParametersVisitor : TypeVisitor
+		{
+			public override IType VisitTypeParameter(ITypeParameter type)
+			{
+				if (type.OwnerType == SymbolKind.Method) {
+					return DummyTypeParameter.GetMethodTypeParameter(type.Index);
+				} else {
+					return base.VisitTypeParameter(type);
+				}
+			}
+		}
+		sealed class NormalizeClassTypeParametersVisitor : TypeVisitor
+		{
+			public override IType VisitTypeParameter(ITypeParameter type)
+			{
+				if (type.OwnerType == SymbolKind.TypeDefinition) {
+					return DummyTypeParameter.GetClassTypeParameter(type.Index);
+				} else {
+					return base.VisitTypeParameter(type);
+				}
+			}
+		}
+		
+		static readonly NormalizeMethodTypeParametersVisitor normalizeMethodTypeParameters = new NormalizeMethodTypeParametersVisitor();
+		static readonly NormalizeClassTypeParametersVisitor normalizeClassTypeParameters = new NormalizeClassTypeParametersVisitor();
+		
+		/// <summary>
+		/// Replaces all occurrences of method type parameters in the given type
+		/// by normalized type parameters. This allows comparing parameter types from different
+		/// generic methods.
+		/// </summary>
+		public static IType NormalizeMethodTypeParameters(IType type)
+		{
+			return type.AcceptVisitor(normalizeMethodTypeParameters);
+		}
+		
+		/// <summary>
+		/// Replaces all occurrences of class type parameters in the given type
+		/// by normalized type parameters. This allows comparing parameter types from different
+		/// generic methods.
+		/// </summary>
+		public static IType NormalizeClassTypeParameters(IType type)
+		{
+			return type.AcceptVisitor(normalizeClassTypeParameters);
+		}
+		
+		/// <summary>
+		/// Replaces all occurrences of class and method type parameters in the given type
+		/// by normalized type parameters. This allows comparing parameter types from different
+		/// generic methods.
+		/// </summary>
+		public static IType NormalizeAllTypeParameters(IType type)
+		{
+			return type.AcceptVisitor(normalizeClassTypeParameters).AcceptVisitor(normalizeMethodTypeParameters);
+		}
+		
+		readonly SymbolKind ownerType;
+		readonly int index;
+		
+		private DummyTypeParameter(SymbolKind ownerType, int index)
+		{
+			this.ownerType = ownerType;
+			this.index = index;
+		}
+		
+		SymbolKind ISymbol.SymbolKind {
+			get { return SymbolKind.TypeParameter; }
+		}
+		
+		public override string Name {
+			get {
+				return (ownerType == SymbolKind.Method ? "!!" : "!") + index;
+			}
+		}
+		
+		public override string ReflectionName {
+			get {
+				return (ownerType == SymbolKind.Method ? "``" : "`") + index;
+			}
+		}
+		
+		public override string ToString()
+		{
+			return ReflectionName + " (dummy)";
+		}
+		
+		public override bool? IsReferenceType {
+			get { return null; }
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.TypeParameter; }
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return TypeParameterReference.Create(ownerType, index);
+		}
+		
+		public override IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitTypeParameter(this);
+		}
+		
+		public int Index {
+			get { return index; }
+		}
+		
+		IList<IAttribute> ITypeParameter.Attributes {
+			get { return EmptyList<IAttribute>.Instance; }
+		}
+		
+		SymbolKind ITypeParameter.OwnerType {
+			get { return ownerType; }
+		}
+		
+		VarianceModifier ITypeParameter.Variance {
+			get { return VarianceModifier.Invariant; }
+		}
+		
+		DomRegion ITypeParameter.Region {
+			get { return DomRegion.Empty; }
+		}
+		
+		IEntity ITypeParameter.Owner {
+			get { return null; }
+		}
+		
+		IType ITypeParameter.EffectiveBaseClass {
+			get { return SpecialType.UnknownType; }
+		}
+		
+		ICollection<IType> ITypeParameter.EffectiveInterfaceSet {
+			get { return EmptyList<IType>.Instance; }
+		}
+		
+		bool ITypeParameter.HasDefaultConstructorConstraint {
+			get { return false; }
+		}
+		
+		bool ITypeParameter.HasReferenceTypeConstraint {
+			get { return false; }
+		}
+		
+		bool ITypeParameter.HasValueTypeConstraint {
+			get { return false; }
+		}
+
+		public ISymbolReference ToReference()
+		{
+			return new TypeParameterReference(ownerType, index);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/ExplicitInterfaceImplementationMemberReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/ExplicitInterfaceImplementationMemberReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/ExplicitInterfaceImplementationMemberReference.cs	(revision 11807)
@@ -0,0 +1,80 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// References a member that is an explicit interface implementation.
+	/// </summary>
+	/// <remarks>
+	/// Resolving an ExplicitInterfaceImplementationMemberReference requires a context
+	/// that provides enough information for resolving the declaring type reference
+	/// and the interface member reference.
+	/// Note that the interface member reference is resolved in '<c>context.WithCurrentTypeDefinition(declaringType.GetDefinition())</c>'
+	/// - this is done to ensure that open generics in the interface member reference resolve to the type parameters of the
+	/// declaring type.
+	/// </remarks>
+	[Serializable]
+	public sealed class ExplicitInterfaceImplementationMemberReference : IMemberReference
+	{
+		ITypeReference typeReference;
+		IMemberReference interfaceMemberReference;
+		
+		public ExplicitInterfaceImplementationMemberReference(ITypeReference typeReference, IMemberReference interfaceMemberReference)
+		{
+			if (typeReference == null)
+				throw new ArgumentNullException("typeReference");
+			if (interfaceMemberReference == null)
+				throw new ArgumentNullException("interfaceMemberReference");
+			this.typeReference = typeReference;
+			this.interfaceMemberReference = interfaceMemberReference;
+		}
+		
+		public ITypeReference DeclaringTypeReference {
+			get { return typeReference; }
+		}
+		
+		public IMember Resolve(ITypeResolveContext context)
+		{
+			IType declaringType = typeReference.Resolve(context);
+			IMember interfaceMember = interfaceMemberReference.Resolve(context.WithCurrentTypeDefinition(declaringType.GetDefinition()));
+			if (interfaceMember == null)
+				return null;
+			IEnumerable<IMember> members;
+			if (interfaceMember.SymbolKind == SymbolKind.Accessor) {
+				members = declaringType.GetAccessors(
+					m => m.IsExplicitInterfaceImplementation,
+					GetMemberOptions.IgnoreInheritedMembers);
+			} else {
+				members = declaringType.GetMembers(
+					m => m.SymbolKind == interfaceMember.SymbolKind && m.IsExplicitInterfaceImplementation,
+					GetMemberOptions.IgnoreInheritedMembers);
+			}
+			return members.FirstOrDefault(m => m.ImplementedInterfaceMembers.Count == 1 && interfaceMember.Equals(m.ImplementedInterfaceMembers[0]));
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return Resolve(context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/FullNameAndTypeParameterCount.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/FullNameAndTypeParameterCount.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/FullNameAndTypeParameterCount.cs	(revision 11807)
@@ -0,0 +1,28 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	[Obsolete("This struct was renamed to 'TopLevelTypeName'.", true)]
+	public struct FullNameAndTypeParameterCount
+	{
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/GetClassTypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/GetClassTypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/GetClassTypeReference.cs	(revision 11807)
@@ -0,0 +1,158 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Type Reference used when the fully qualified type name is known.
+	/// </summary>
+	[Serializable]
+	public sealed class GetClassTypeReference : ITypeReference, ISymbolReference, ISupportsInterning
+	{
+		readonly IAssemblyReference assembly;
+		readonly FullTypeName fullTypeName;
+		
+		/// <summary>
+		/// Creates a new GetClassTypeReference that searches a type definition.
+		/// </summary>
+		/// <param name="fullTypeName">The full name of the type.</param>
+		/// <param name="assembly">A reference to the assembly containing this type.
+		/// If this parameter is null, the GetClassTypeReference will search in all
+		/// assemblies belonging to the compilation.
+		/// </param>
+		public GetClassTypeReference(FullTypeName fullTypeName, IAssemblyReference assembly = null)
+		{
+			this.fullTypeName = fullTypeName;
+			this.assembly = assembly;
+		}
+		
+		/// <summary>
+		/// Creates a new GetClassTypeReference that searches a top-level type in all assemblies.
+		/// </summary>
+		/// <param name="namespaceName">The namespace name containing the type, e.g. "System.Collections.Generic".</param>
+		/// <param name="name">The name of the type, e.g. "List".</param>
+		/// <param name="typeParameterCount">The number of type parameters, (e.g. 1 for List&lt;T&gt;).</param>
+		public GetClassTypeReference(string namespaceName, string name, int typeParameterCount = 0)
+		{
+			this.fullTypeName = new TopLevelTypeName(namespaceName, name, typeParameterCount);
+		}
+		
+		/// <summary>
+		/// Creates a new GetClassTypeReference that searches a top-level type in the specified assembly.
+		/// </summary>
+		/// <param name="assembly">A reference to the assembly containing this type.
+		/// If this parameter is null, the GetClassTypeReference will search in all assemblies belonging to the ICompilation.</param>
+		/// <param name="namespaceName">The namespace name containing the type, e.g. "System.Collections.Generic".</param>
+		/// <param name="name">The name of the type, e.g. "List".</param>
+		/// <param name="typeParameterCount">The number of type parameters, (e.g. 1 for List&lt;T&gt;).</param>
+		public GetClassTypeReference(IAssemblyReference assembly, string namespaceName, string name, int typeParameterCount = 0)
+		{
+			this.assembly = assembly;
+			this.fullTypeName = new TopLevelTypeName(namespaceName, name, typeParameterCount);
+		}
+		
+		/// <summary>
+		/// Gets the assembly reference.
+		/// This property returns null if the GetClassTypeReference is searching in all assemblies
+		/// of the compilation.
+		/// </summary>
+		public IAssemblyReference Assembly { get { return assembly; } }
+		
+		/// <summary>
+		/// Gets the full name of the type this reference is searching for.
+		/// </summary>
+		public FullTypeName FullTypeName { get { return fullTypeName; } }
+		
+		[Obsolete("Use the FullTypeName property instead. GetClassTypeReference now supports nested types, where the Namespace/Name/TPC tripel isn't sufficient for identifying the type.")]
+		public string Namespace { get { return fullTypeName.TopLevelTypeName.Namespace; } }
+		[Obsolete("Use the FullTypeName property instead. GetClassTypeReference now supports nested types, where the Namespace/Name/TPC tripel isn't sufficient for identifying the type.")]
+		public string Name { get { return fullTypeName.Name; } }
+		[Obsolete("Use the FullTypeName property instead. GetClassTypeReference now supports nested types, where the Namespace/Name/TPC tripel isn't sufficient for identifying the type.")]
+		public int TypeParameterCount { get { return fullTypeName.TypeParameterCount; } }
+
+		IType ResolveInAllAssemblies(ITypeResolveContext context)
+		{
+			var compilation = context.Compilation;
+			foreach (var asm in compilation.Assemblies) {
+				IType type = asm.GetTypeDefinition(fullTypeName);
+				if (type != null)
+					return type;
+			}
+			return null;
+		}
+
+		public IType Resolve(ITypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			
+			IType type = null;
+			if (assembly == null) {
+				// No assembly specified: look in all assemblies, but prefer the current assembly
+				if (context.CurrentAssembly != null) {
+					type = context.CurrentAssembly.GetTypeDefinition(fullTypeName);
+				}
+				if (type == null) {
+					type = ResolveInAllAssemblies(context);
+				}
+			} else {
+				// Assembly specified: only look in the specified assembly.
+				// But if that's not loaded in the compilation, allow fall back to other assemblies.
+				// (the non-loaded assembly might be a facade containing type forwarders -
+				//  for example, when referencing a portable library from a non-portable project)
+				IAssembly asm = assembly.Resolve(context);
+				if (asm != null) {
+					type = asm.GetTypeDefinition(fullTypeName);
+				} else {
+					type = ResolveInAllAssemblies(context);
+				}
+			}
+			return type ?? new UnknownType(fullTypeName);
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			var type = Resolve(context);
+			if (type is ITypeDefinition)
+				return (ISymbol)type;
+			return null;
+		}
+		
+		public override string ToString()
+		{
+			return fullTypeName.ToString() + (assembly != null ? ", " + assembly.ToString() : null);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				return 33 * assembly.GetHashCode() + fullTypeName.GetHashCode();
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			GetClassTypeReference o = other as GetClassTypeReference;
+			return o != null && assembly == o.assembly && fullTypeName == o.fullTypeName;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/GetMembersHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/GetMembersHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/GetMembersHelper.cs	(revision 11807)
@@ -0,0 +1,296 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Provides helper methods for implementing GetMembers() on IType-implementations.
+	/// Note: GetMembersHelper will recursively call back into IType.GetMembers(), but only with
+	/// both GetMemberOptions.IgnoreInheritedMembers and GetMemberOptions.ReturnMemberDefinitions set,
+	/// and only the 'simple' overloads (not taking type arguments).
+	/// 
+	/// Ensure that your IType implementation does not use the GetMembersHelper if both flags are set,
+	/// otherwise you'll get a StackOverflowException!
+	/// </summary>
+	static class GetMembersHelper
+	{
+		#region GetNestedTypes
+		public static IEnumerable<IType> GetNestedTypes(IType type, Predicate<ITypeDefinition> filter, GetMemberOptions options)
+		{
+			return GetNestedTypes(type, null, filter, options);
+		}
+		
+		public static IEnumerable<IType> GetNestedTypes(IType type, IList<IType> nestedTypeArguments, Predicate<ITypeDefinition> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetNestedTypesImpl(type, nestedTypeArguments, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetNestedTypesImpl(t, nestedTypeArguments, filter, options));
+			}
+		}
+		
+		static IEnumerable<IType> GetNestedTypesImpl(IType outerType, IList<IType> nestedTypeArguments, Predicate<ITypeDefinition> filter, GetMemberOptions options)
+		{
+			ITypeDefinition outerTypeDef = outerType.GetDefinition();
+			if (outerTypeDef == null)
+				yield break;
+			
+			int outerTypeParameterCount = outerTypeDef.TypeParameterCount;
+			ParameterizedType pt = outerType as ParameterizedType;
+			foreach (ITypeDefinition nestedType in outerTypeDef.NestedTypes) {
+				int totalTypeParameterCount = nestedType.TypeParameterCount;
+				if (nestedTypeArguments != null) {
+					if (totalTypeParameterCount - outerTypeParameterCount != nestedTypeArguments.Count)
+						continue;
+				}
+				if (!(filter == null || filter(nestedType)))
+					continue;
+				
+				if (totalTypeParameterCount == 0 || (options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) {
+					yield return nestedType;
+				} else {
+					// We need to parameterize the nested type
+					IType[] newTypeArguments = new IType[totalTypeParameterCount];
+					for (int i = 0; i < outerTypeParameterCount; i++) {
+						newTypeArguments[i] = pt != null ? pt.GetTypeArgument(i) : outerTypeDef.TypeParameters[i];
+					}
+					for (int i = outerTypeParameterCount; i < totalTypeParameterCount; i++) {
+						if (nestedTypeArguments != null)
+							newTypeArguments[i] = nestedTypeArguments[i - outerTypeParameterCount];
+						else
+							newTypeArguments[i] = SpecialType.UnboundTypeArgument;
+					}
+					yield return new ParameterizedType(nestedType, newTypeArguments);
+				}
+			}
+		}
+		#endregion
+		
+		#region GetMethods
+		public static IEnumerable<IMethod> GetMethods(IType type, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return GetMethods(type, null, filter, options);
+		}
+		
+		public static IEnumerable<IMethod> GetMethods(IType type, IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			if (typeArguments != null && typeArguments.Count > 0) {
+				filter = FilterTypeParameterCount(typeArguments.Count).And(filter);
+			}
+			
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetMethodsImpl(type, typeArguments, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetMethodsImpl(t, typeArguments, filter, options));
+			}
+		}
+		
+		static Predicate<IUnresolvedMethod> FilterTypeParameterCount(int expectedTypeParameterCount)
+		{
+			return m => m.TypeParameters.Count == expectedTypeParameterCount;
+		}
+		
+		const GetMemberOptions declaredMembers = GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions;
+		
+		static IEnumerable<IMethod> GetMethodsImpl(IType baseType, IList<IType> methodTypeArguments, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			IEnumerable<IMethod> declaredMethods = baseType.GetMethods(filter, options | declaredMembers);
+			
+			ParameterizedType pt = baseType as ParameterizedType;
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == 0
+			    && (pt != null || (methodTypeArguments != null && methodTypeArguments.Count > 0)))
+			{
+				TypeParameterSubstitution substitution = null;
+				foreach (IMethod m in declaredMethods) {
+					if (methodTypeArguments != null && methodTypeArguments.Count > 0) {
+						if (m.TypeParameters.Count != methodTypeArguments.Count)
+							continue;
+					}
+					if (substitution == null) {
+						if (pt != null)
+							substitution = pt.GetSubstitution(methodTypeArguments);
+						else
+							substitution = new TypeParameterSubstitution(null, methodTypeArguments);
+					}
+					yield return new SpecializedMethod(m, substitution);
+				}
+			} else {
+				foreach (IMethod m in declaredMethods) {
+					yield return m;
+				}
+			}
+		}
+		#endregion
+		
+		#region GetAccessors
+		public static IEnumerable<IMethod> GetAccessors(IType type, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetAccessorsImpl(type, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetAccessorsImpl(t, filter, options));
+			}
+		}
+		
+		static IEnumerable<IMethod> GetAccessorsImpl(IType baseType, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return GetConstructorsOrAccessorsImpl(baseType, baseType.GetAccessors(filter, options | declaredMembers), filter, options);
+		}
+		#endregion
+		
+		#region GetConstructors
+		public static IEnumerable<IMethod> GetConstructors(IType type, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetConstructorsImpl(type, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetConstructorsImpl(t, filter, options));
+			}
+		}
+		
+		static IEnumerable<IMethod> GetConstructorsImpl(IType baseType, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return GetConstructorsOrAccessorsImpl(baseType, baseType.GetConstructors(filter, options | declaredMembers), filter, options);
+		}
+		
+		static IEnumerable<IMethod> GetConstructorsOrAccessorsImpl(IType baseType, IEnumerable<IMethod> declaredMembers, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) {
+				return declaredMembers;
+			}
+			
+			ParameterizedType pt = baseType as ParameterizedType;
+			if (pt != null) {
+				var substitution = pt.GetSubstitution();
+				return declaredMembers.Select(m => new SpecializedMethod(m, substitution) { DeclaringType = pt });
+			} else {
+				return declaredMembers;
+			}
+		}
+		#endregion
+		
+		#region GetProperties
+		public static IEnumerable<IProperty> GetProperties(IType type, Predicate<IUnresolvedProperty> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetPropertiesImpl(type, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetPropertiesImpl(t, filter, options));
+			}
+		}
+		
+		static IEnumerable<IProperty> GetPropertiesImpl(IType baseType, Predicate<IUnresolvedProperty> filter, GetMemberOptions options)
+		{
+			IEnumerable<IProperty> declaredProperties = baseType.GetProperties(filter, options | declaredMembers);
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) {
+				return declaredProperties;
+			}
+			
+			ParameterizedType pt = baseType as ParameterizedType;
+			if (pt != null) {
+				var substitution = pt.GetSubstitution();
+				return declaredProperties.Select(m => new SpecializedProperty(m, substitution) { DeclaringType = pt });
+			} else {
+				return declaredProperties;
+			}
+		}
+		#endregion
+		
+		#region GetFields
+		public static IEnumerable<IField> GetFields(IType type, Predicate<IUnresolvedField> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetFieldsImpl(type, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetFieldsImpl(t, filter, options));
+			}
+		}
+		
+		static IEnumerable<IField> GetFieldsImpl(IType baseType, Predicate<IUnresolvedField> filter, GetMemberOptions options)
+		{
+			IEnumerable<IField> declaredFields = baseType.GetFields(filter, options | declaredMembers);
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) {
+				return declaredFields;
+			}
+			
+			ParameterizedType pt = baseType as ParameterizedType;
+			if (pt != null) {
+				var substitution = pt.GetSubstitution();
+				return declaredFields.Select(m => new SpecializedField(m, substitution) { DeclaringType = pt });
+			} else {
+				return declaredFields;
+			}
+		}
+		#endregion
+		
+		#region GetEvents
+		public static IEnumerable<IEvent> GetEvents(IType type, Predicate<IUnresolvedEvent> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetEventsImpl(type, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetEventsImpl(t, filter, options));
+			}
+		}
+		
+		static IEnumerable<IEvent> GetEventsImpl(IType baseType, Predicate<IUnresolvedEvent> filter, GetMemberOptions options)
+		{
+			IEnumerable<IEvent> declaredEvents = baseType.GetEvents(filter, options | declaredMembers);
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions) {
+				return declaredEvents;
+			}
+			
+			ParameterizedType pt = baseType as ParameterizedType;
+			if (pt != null) {
+				var substitution = pt.GetSubstitution();
+				return declaredEvents.Select(m => new SpecializedEvent(m, substitution) { DeclaringType = pt });
+			} else {
+				return declaredEvents;
+			}
+		}
+		#endregion
+		
+		#region GetMembers
+		public static IEnumerable<IMember> GetMembers(IType type, Predicate<IUnresolvedMember> filter, GetMemberOptions options)
+		{
+			if ((options & GetMemberOptions.IgnoreInheritedMembers) == GetMemberOptions.IgnoreInheritedMembers) {
+				return GetMembersImpl(type, filter, options);
+			} else {
+				return type.GetNonInterfaceBaseTypes().SelectMany(t => GetMembersImpl(t, filter, options));
+			}
+		}
+		
+		static IEnumerable<IMember> GetMembersImpl(IType baseType, Predicate<IUnresolvedMember> filter, GetMemberOptions options)
+		{
+			foreach (var m in GetMethodsImpl(baseType, null, filter, options))
+				yield return m;
+			foreach (var m in GetPropertiesImpl(baseType, filter, options))
+				yield return m;
+			foreach (var m in GetFieldsImpl(baseType, filter, options))
+				yield return m;
+			foreach (var m in GetEventsImpl(baseType, filter, options))
+				yield return m;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/KnownTypeCache.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/KnownTypeCache.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/KnownTypeCache.cs	(revision 11807)
@@ -0,0 +1,60 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Cache for KnownTypeReferences.
+	/// </summary>
+	sealed class KnownTypeCache
+	{
+		readonly ICompilation compilation;
+		readonly IType[] knownTypes = new IType[KnownTypeReference.KnownTypeCodeCount];
+		
+		public KnownTypeCache(ICompilation compilation)
+		{
+			this.compilation = compilation;
+		}
+		
+		public IType FindType(KnownTypeCode typeCode)
+		{
+			IType type = LazyInit.VolatileRead(ref knownTypes[(int)typeCode]);
+			if (type != null) {
+				return type;
+			}
+			return LazyInit.GetOrSet(ref knownTypes[(int)typeCode], SearchType(typeCode));
+		}
+		
+		IType SearchType(KnownTypeCode typeCode)
+		{
+			KnownTypeReference typeRef = KnownTypeReference.Get(typeCode);
+			if (typeRef == null)
+				return SpecialType.UnknownType;
+			var typeName = new TopLevelTypeName(typeRef.Namespace, typeRef.Name, typeRef.TypeParameterCount);
+			foreach (IAssembly asm in compilation.Assemblies) {
+				var typeDef = asm.GetTypeDefinition(typeName);
+				if (typeDef != null)
+					return typeDef;
+			}
+			return new UnknownType(typeName);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/MergedNamespace.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/MergedNamespace.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/MergedNamespace.cs	(revision 11807)
@@ -0,0 +1,164 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// A merged namespace.
+	/// </summary>
+	public sealed class MergedNamespace : INamespace
+	{
+		readonly string externAlias;
+		readonly ICompilation compilation;
+		readonly INamespace parentNamespace;
+		readonly INamespace[] namespaces;
+		Dictionary<string, INamespace> childNamespaces;
+		
+		/// <summary>
+		/// Creates a new merged root namespace.
+		/// </summary>
+		/// <param name="compilation">The main compilation.</param>
+		/// <param name="namespaces">The individual namespaces being merged.</param>
+		/// <param name="externAlias">The extern alias for this namespace.</param>
+		public MergedNamespace(ICompilation compilation, INamespace[] namespaces, string externAlias = null)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (namespaces == null)
+				throw new ArgumentNullException("namespaces");
+			this.compilation = compilation;
+			this.namespaces = namespaces;
+			this.externAlias = externAlias;
+		}
+		
+		/// <summary>
+		/// Creates a new merged child namespace.
+		/// </summary>
+		/// <param name="parentNamespace">The parent merged namespace.</param>
+		/// <param name="namespaces">The individual namespaces being merged.</param>
+		public MergedNamespace(INamespace parentNamespace, INamespace[] namespaces)
+		{
+			if (parentNamespace == null)
+				throw new ArgumentNullException("parentNamespace");
+			if (namespaces == null)
+				throw new ArgumentNullException("namespaces");
+			this.parentNamespace = parentNamespace;
+			this.namespaces = namespaces;
+			this.compilation = parentNamespace.Compilation;
+			this.externAlias = parentNamespace.ExternAlias;
+		}
+		
+		public string ExternAlias {
+			get { return externAlias; }
+		}
+		
+		public string FullName {
+			get { return namespaces[0].FullName; }
+		}
+		
+		public string Name {
+			get { return namespaces[0].Name; }
+		}
+		
+		public INamespace ParentNamespace {
+			get { return parentNamespace; }
+		}
+		
+		public IEnumerable<ITypeDefinition> Types {
+			get {
+				return namespaces.SelectMany(ns => ns.Types);
+			}
+		}
+		
+		public SymbolKind SymbolKind {
+			get { return SymbolKind.Namespace; }
+		}
+		
+		public ICompilation Compilation {
+			get { return compilation; }
+		}
+		
+		public IEnumerable<IAssembly> ContributingAssemblies {
+			get { return namespaces.SelectMany(ns => ns.ContributingAssemblies); }
+		}
+		
+		public IEnumerable<INamespace> ChildNamespaces {
+			get { return GetChildNamespaces().Values; }
+		}
+		
+		public INamespace GetChildNamespace(string name)
+		{
+			INamespace ns;
+			if (GetChildNamespaces().TryGetValue(name, out ns))
+				return ns;
+			else
+				return null;
+		}
+		
+		Dictionary<string, INamespace> GetChildNamespaces()
+		{
+			var result = LazyInit.VolatileRead(ref this.childNamespaces);
+			if (result != null) {
+				return result;
+			} else {
+				result = new Dictionary<string, INamespace>(compilation.NameComparer);
+				foreach (var g in namespaces.SelectMany(ns => ns.ChildNamespaces).GroupBy(ns => ns.Name, compilation.NameComparer)) {
+					result.Add(g.Key, new MergedNamespace(this, g.ToArray()));
+				}
+				return LazyInit.GetOrSet(ref this.childNamespaces, result);
+			}
+		}
+		
+		public ITypeDefinition GetTypeDefinition(string name, int typeParameterCount)
+		{
+			ITypeDefinition anyTypeDef = null;
+			foreach (var ns in namespaces) {
+				ITypeDefinition typeDef = ns.GetTypeDefinition(name, typeParameterCount);
+				if (typeDef != null) {
+					if (typeDef.IsPublic) {
+						// Prefer accessible types over non-accessible types.
+						return typeDef;
+						// || (typeDef.IsInternal && typeDef.ParentAssembly.InternalsVisibleTo(...))
+						// We can't call InternalsVisibleTo() here as we don't know the correct 'current' assembly,
+						// and using the main assembly can cause a stack overflow if there
+						// are internal assembly attributes.
+					}
+					anyTypeDef = typeDef;
+				}
+			}
+			return anyTypeDef;
+		}
+		
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[MergedNamespace {0}{1} (from {2} assemblies)]",
+			                     externAlias != null ? externAlias + "::" : null, this.FullName, this.namespaces.Length);
+		}
+
+		public ISymbolReference ToReference()
+		{
+			return new MergedNamespaceReference(externAlias, FullName);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/MinimalCorlib.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/MinimalCorlib.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/MinimalCorlib.cs	(revision 11807)
@@ -0,0 +1,65 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Resolve context represents the minimal mscorlib required for evaluating constants.
+	/// This contains all known types (<see cref="KnownTypeCode"/>) and no other types.
+	/// </summary>
+	public sealed class MinimalCorlib : DefaultUnresolvedAssembly
+	{
+		static readonly Lazy<MinimalCorlib> instance = new Lazy<MinimalCorlib>(() => new MinimalCorlib());
+		
+		public static MinimalCorlib Instance {
+			get { return instance.Value; }
+		}
+		
+		public ICompilation CreateCompilation()
+		{
+			return new SimpleCompilation(new DefaultSolutionSnapshot(), this);
+		}
+		
+		private MinimalCorlib() : base("corlib")
+		{
+			var types = new DefaultUnresolvedTypeDefinition[KnownTypeReference.KnownTypeCodeCount];
+			for (int i = 0; i < types.Length; i++) {
+				var typeRef = KnownTypeReference.Get((KnownTypeCode)i);
+				if (typeRef != null) {
+					types[i] = new DefaultUnresolvedTypeDefinition(typeRef.Namespace, typeRef.Name);
+					for (int j = 0; j < typeRef.TypeParameterCount; j++) {
+						types[i].TypeParameters.Add(new DefaultUnresolvedTypeParameter(SymbolKind.TypeDefinition, j));
+					}
+					AddTypeDefinition(types[i]);
+				}
+			}
+			for (int i = 0; i < types.Length; i++) {
+				var typeRef = KnownTypeReference.Get((KnownTypeCode)i);
+				if (typeRef != null && typeRef.baseType != KnownTypeCode.None) {
+					types[i].BaseTypes.Add(types[(int)typeRef.baseType]);
+					if (typeRef.baseType == KnownTypeCode.ValueType && i != (int)KnownTypeCode.Enum) {
+						types[i].Kind = TypeKind.Struct;
+					}
+				}
+			}
+			Freeze();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/NestedTypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/NestedTypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/NestedTypeReference.cs	(revision 11807)
@@ -0,0 +1,106 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Type reference used to reference nested types.
+	/// </summary>
+	[Serializable]
+	public sealed class NestedTypeReference : ITypeReference, ISymbolReference, ISupportsInterning
+	{
+		readonly ITypeReference declaringTypeRef;
+		readonly string name;
+		readonly int additionalTypeParameterCount;
+		
+		/// <summary>
+		/// Creates a new NestedTypeReference.
+		/// </summary>
+		/// <param name="declaringTypeRef">Reference to the declaring type.</param>
+		/// <param name="name">Name of the nested class</param>
+		/// <param name="additionalTypeParameterCount">Number of type parameters on the inner class (without type parameters on baseTypeRef)</param>
+		/// <remarks>
+		/// <paramref name="declaringTypeRef"/> must be exactly the (unbound) declaring type, not a derived type, not a parameterized type.
+		/// NestedTypeReference thus always resolves to a type definition, never to (partially) parameterized types.
+		/// </remarks>
+		public NestedTypeReference(ITypeReference declaringTypeRef, string name, int additionalTypeParameterCount)
+		{
+			if (declaringTypeRef == null)
+				throw new ArgumentNullException("declaringTypeRef");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.declaringTypeRef = declaringTypeRef;
+			this.name = name;
+			this.additionalTypeParameterCount = additionalTypeParameterCount;
+		}
+		
+		public ITypeReference DeclaringTypeReference {
+			get { return declaringTypeRef; }
+		}
+		
+		public string Name {
+			get { return name; }
+		}
+		
+		public int AdditionalTypeParameterCount {
+			get { return additionalTypeParameterCount; }
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			ITypeDefinition declaringType = declaringTypeRef.Resolve(context) as ITypeDefinition;
+			if (declaringType != null) {
+				int tpc = declaringType.TypeParameterCount;
+				foreach (IType type in declaringType.NestedTypes) {
+					if (type.Name == name && type.TypeParameterCount == tpc + additionalTypeParameterCount)
+						return type;
+				}
+			}
+			return new UnknownType(null, name, additionalTypeParameterCount);
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			var type = Resolve(context);
+			if (type is ITypeDefinition)
+				return (ISymbol)type;
+			return null;
+		}
+		
+		public override string ToString()
+		{
+			if (additionalTypeParameterCount == 0)
+				return declaringTypeRef + "+" + name;
+			else
+				return declaringTypeRef + "+" + name + "`" + additionalTypeParameterCount;
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return declaringTypeRef.GetHashCode() ^ name.GetHashCode() ^ additionalTypeParameterCount;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			NestedTypeReference o = other as NestedTypeReference;
+			return o != null && declaringTypeRef == o.declaringTypeRef && name == o.name && additionalTypeParameterCount == o.additionalTypeParameterCount;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/ResolvedAttributeBlob.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/ResolvedAttributeBlob.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/ResolvedAttributeBlob.cs	(revision 11807)
@@ -0,0 +1,176 @@
+﻿//
+// ResolvedAttributeBlob.cs
+//
+// Author:
+//       Daniel Grunwald <daniel@danielgrunwald.de>
+//
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	sealed class CecilResolvedAttribute : IAttribute
+	{
+		readonly ITypeResolveContext context;
+		readonly byte[] blob;
+		readonly IList<ITypeReference> ctorParameterTypes;
+		readonly IType attributeType;
+		
+		IMethod constructor;
+		volatile bool constructorResolved;
+		
+		IList<ResolveResult> positionalArguments;
+		IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
+		
+		public CecilResolvedAttribute(ITypeResolveContext context, UnresolvedAttributeBlob unresolved)
+		{
+			this.context = context;
+			this.blob = unresolved.blob;
+			this.ctorParameterTypes = unresolved.ctorParameterTypes;
+			this.attributeType = unresolved.attributeType.Resolve(context);
+		}
+		
+		public CecilResolvedAttribute(ITypeResolveContext context, IType attributeType)
+		{
+			this.context = context;
+			this.attributeType = attributeType;
+			this.ctorParameterTypes = EmptyList<ITypeReference>.Instance;
+		}
+		
+		DomRegion IAttribute.Region {
+			get { return DomRegion.Empty; }
+		}
+		
+		public IType AttributeType {
+			get { return attributeType; }
+		}
+		
+		public IMethod Constructor {
+			get {
+				if (!constructorResolved) {
+					constructor = ResolveConstructor();
+					constructorResolved = true;
+				}
+				return constructor;
+			}
+		}
+		
+		IMethod ResolveConstructor()
+		{
+			var parameterTypes = ctorParameterTypes.Resolve(context);
+			foreach (var ctor in attributeType.GetConstructors(m => m.Parameters.Count == parameterTypes.Count)) {
+				bool ok = true;
+				for (int i = 0; i < parameterTypes.Count; i++) {
+					if (!ctor.Parameters[i].Type.Equals(parameterTypes[i])) {
+						ok = false;
+						break;
+					}
+				}
+				if (ok)
+					return ctor;
+			}
+			return null;
+		}
+		
+		public IList<ResolveResult> PositionalArguments {
+			get {
+				var result = LazyInit.VolatileRead(ref this.positionalArguments);
+				if (result != null) {
+					return result;
+				}
+				DecodeBlob();
+				return positionalArguments;
+			}
+		}
+		
+		public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments {
+			get {
+				var result = LazyInit.VolatileRead(ref this.namedArguments);
+				if (result != null) {
+					return result;
+				}
+				DecodeBlob();
+				return namedArguments;
+			}
+		}
+		
+		public override string ToString()
+		{
+			return "[" + attributeType.ToString() + "(...)]";
+		}
+		
+		void DecodeBlob()
+		{
+			var positionalArguments = new List<ResolveResult>();
+			var namedArguments = new List<KeyValuePair<IMember, ResolveResult>>();
+			DecodeBlob(positionalArguments, namedArguments);
+			Interlocked.CompareExchange(ref this.positionalArguments, positionalArguments, null);
+			Interlocked.CompareExchange(ref this.namedArguments, namedArguments, null);
+		}
+		
+		void DecodeBlob(List<ResolveResult> positionalArguments, List<KeyValuePair<IMember, ResolveResult>> namedArguments)
+		{
+			if (blob == null)
+				return;
+			BlobReader reader = new BlobReader(blob, context.CurrentAssembly);
+			if (reader.ReadUInt16() != 0x0001) {
+				Debug.WriteLine("Unknown blob prolog");
+				return;
+			}
+			foreach (var ctorParameter in ctorParameterTypes.Resolve(context)) {
+				ResolveResult arg;
+				bool isError;
+				try {
+					arg = reader.ReadFixedArg (ctorParameter);
+					positionalArguments.Add(arg);
+					isError = arg.IsError;
+				} catch (Exception ex) {
+					Debug.WriteLine("Crash during blob decoding: " + ex);
+					isError = true;
+				}
+				if (isError) {
+					// After a decoding error, we must stop decoding the blob because
+					// we might have read too few bytes due to the error.
+					// Just fill up the remaining arguments with ErrorResolveResult:
+					while (positionalArguments.Count < ctorParameterTypes.Count)
+						positionalArguments.Add(ErrorResolveResult.UnknownError);
+					return;
+				}
+			}
+			try {
+				ushort numNamed = reader.ReadUInt16();
+				for (int i = 0; i < numNamed; i++) {
+					var namedArg = reader.ReadNamedArg(attributeType);
+					if (namedArg.Key != null)
+						namedArguments.Add(namedArg);
+				}
+			} catch (Exception ex) {
+				Debug.WriteLine("Crash during blob decoding: " + ex);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleCompilation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleCompilation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleCompilation.cs	(revision 11807)
@@ -0,0 +1,168 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Simple compilation implementation.
+	/// </summary>
+	public class SimpleCompilation : ICompilation
+	{
+		readonly ISolutionSnapshot solutionSnapshot;
+		readonly ITypeResolveContext context;
+		readonly CacheManager cacheManager = new CacheManager();
+		readonly KnownTypeCache knownTypeCache;
+		readonly IAssembly mainAssembly;
+		readonly IList<IAssembly> assemblies;
+		readonly IList<IAssembly> referencedAssemblies;
+		INamespace rootNamespace;
+		
+		public SimpleCompilation(IUnresolvedAssembly mainAssembly, params IAssemblyReference[] assemblyReferences)
+			: this(new DefaultSolutionSnapshot(), mainAssembly, (IEnumerable<IAssemblyReference>)assemblyReferences)
+		{
+		}
+		
+		public SimpleCompilation(IUnresolvedAssembly mainAssembly, IEnumerable<IAssemblyReference> assemblyReferences)
+			: this(new DefaultSolutionSnapshot(), mainAssembly, assemblyReferences)
+		{
+		}
+		
+		public SimpleCompilation(ISolutionSnapshot solutionSnapshot, IUnresolvedAssembly mainAssembly, params IAssemblyReference[] assemblyReferences)
+			: this(solutionSnapshot, mainAssembly, (IEnumerable<IAssemblyReference>)assemblyReferences)
+		{
+		}
+		
+		public SimpleCompilation(ISolutionSnapshot solutionSnapshot, IUnresolvedAssembly mainAssembly, IEnumerable<IAssemblyReference> assemblyReferences)
+		{
+			if (solutionSnapshot == null)
+				throw new ArgumentNullException("solutionSnapshot");
+			if (mainAssembly == null)
+				throw new ArgumentNullException("mainAssembly");
+			if (assemblyReferences == null)
+				throw new ArgumentNullException("assemblyReferences");
+			this.solutionSnapshot = solutionSnapshot;
+			this.context = new SimpleTypeResolveContext(this);
+			this.mainAssembly = mainAssembly.Resolve(context);
+			List<IAssembly> assemblies = new List<IAssembly>();
+			assemblies.Add(this.mainAssembly);
+			List<IAssembly> referencedAssemblies = new List<IAssembly>();
+			foreach (var asmRef in assemblyReferences) {
+				IAssembly asm;
+				try {
+					asm = asmRef.Resolve(context);
+				} catch (InvalidOperationException) {
+					throw new InvalidOperationException("Tried to initialize compilation with an invalid assembly reference. (Forgot to load the assembly reference ? - see CecilLoader)");
+				}
+				if (asm != null && !assemblies.Contains(asm))
+					assemblies.Add(asm);
+				if (asm != null && !referencedAssemblies.Contains(asm))
+					referencedAssemblies.Add(asm);
+			}
+			this.assemblies = assemblies.AsReadOnly();
+			this.referencedAssemblies = referencedAssemblies.AsReadOnly();
+			this.knownTypeCache = new KnownTypeCache(this);
+		}
+		
+		public IAssembly MainAssembly {
+			get {
+				if (mainAssembly == null)
+					throw new InvalidOperationException("Compilation isn't initialized yet");
+				return mainAssembly;
+			}
+		}
+		
+		public IList<IAssembly> Assemblies {
+			get {
+				if (assemblies == null)
+					throw new InvalidOperationException("Compilation isn't initialized yet");
+				return assemblies;
+			}
+		}
+		
+		public IList<IAssembly> ReferencedAssemblies {
+			get {
+				if (referencedAssemblies == null)
+					throw new InvalidOperationException("Compilation isn't initialized yet");
+				return referencedAssemblies;
+			}
+		}
+		
+		public ITypeResolveContext TypeResolveContext {
+			get { return context; }
+		}
+		
+		public INamespace RootNamespace {
+			get {
+				INamespace ns = LazyInit.VolatileRead(ref this.rootNamespace);
+				if (ns != null) {
+					return ns;
+				} else {
+					if (referencedAssemblies == null)
+						throw new InvalidOperationException("Compilation isn't initialized yet");
+					return LazyInit.GetOrSet(ref this.rootNamespace, CreateRootNamespace());
+				}
+			}
+		}
+		
+		protected virtual INamespace CreateRootNamespace()
+		{
+			// SimpleCompilation does not support extern aliases; but derived classes might.
+			// CreateRootNamespace() is virtual so that derived classes can change the global namespace.
+			INamespace[] namespaces = new INamespace[referencedAssemblies.Count + 1];
+			namespaces[0] = mainAssembly.RootNamespace;
+			for (int i = 0; i < referencedAssemblies.Count; i++) {
+				namespaces[i + 1] = referencedAssemblies[i].RootNamespace;
+			}
+			return new MergedNamespace(this, namespaces);
+		}
+		
+		public CacheManager CacheManager {
+			get { return cacheManager; }
+		}
+		
+		public virtual INamespace GetNamespaceForExternAlias(string alias)
+		{
+			if (string.IsNullOrEmpty(alias))
+				return this.RootNamespace;
+			// SimpleCompilation does not support extern aliases; but derived classes might.
+			return null;
+		}
+		
+		public IType FindType(KnownTypeCode typeCode)
+		{
+			return knownTypeCache.FindType(typeCode);
+		}
+		
+		public StringComparer NameComparer {
+			get { return StringComparer.Ordinal; }
+		}
+		
+		public ISolutionSnapshot SolutionSnapshot {
+			get { return solutionSnapshot; }
+		}
+		
+		public override string ToString()
+		{
+			return "[SimpleCompilation " + mainAssembly.AssemblyName + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleConstantValue.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleConstantValue.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleConstantValue.cs	(revision 11807)
@@ -0,0 +1,69 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// A simple constant value that is independent of the resolve context.
+	/// </summary>
+	[Serializable]
+	public sealed class SimpleConstantValue : IConstantValue, ISupportsInterning
+	{
+		readonly ITypeReference type;
+		readonly object value;
+		
+		public SimpleConstantValue(ITypeReference type, object value)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			this.type = type;
+			this.value = value;
+		}
+		
+		public ResolveResult Resolve(ITypeResolveContext context)
+		{
+			return new ConstantResolveResult(type.Resolve(context), value);
+		}
+		
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase",
+		                                                 Justification = "The C# keyword is lower case")]
+		public override string ToString()
+		{
+			if (value == null)
+				return "null";
+			else if (value is bool)
+				return value.ToString().ToLowerInvariant();
+			else
+				return value.ToString();
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return type.GetHashCode() ^ (value != null ? value.GetHashCode() : 0);
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			SimpleConstantValue scv = other as SimpleConstantValue;
+			return scv != null && type == scv.type && value == scv.value;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleInterningProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleInterningProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SimpleInterningProvider.cs	(revision 11807)
@@ -0,0 +1,143 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Runtime.CompilerServices;
+
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Simple interning provider.
+	/// </summary>
+	public sealed class SimpleInterningProvider : InterningProvider
+	{
+		sealed class InterningComparer : IEqualityComparer<ISupportsInterning>
+		{
+			public bool Equals(ISupportsInterning x, ISupportsInterning y)
+			{
+				return x.EqualsForInterning(y);
+			}
+			
+			public int GetHashCode(ISupportsInterning obj)
+			{
+				return obj.GetHashCodeForInterning();
+			}
+		}
+		
+		sealed class ListComparer : IEqualityComparer<IEnumerable>
+		{
+			public bool Equals(IEnumerable a, IEnumerable b)
+			{
+				if (a.GetType() != b.GetType())
+					return false;
+				IEnumerator e1 = a.GetEnumerator();
+				IEnumerator e2 = b.GetEnumerator();
+				while (e1.MoveNext()) {
+					// e1 has more elements than e2; or elements are different
+					if (!e2.MoveNext() || e1.Current != e2.Current)
+						return false;
+				}
+				if (e2.MoveNext()) // e2 has more elements than e1
+					return false;
+				// No need to dispose e1/e2: non-generic IEnumerator doesn't implement IDisposable,
+				// and the underlying enumerator will likely be a List<T>.Enumerator which has an empty Dispose() method.
+				return true;
+			}
+			
+			public int GetHashCode(IEnumerable obj)
+			{
+				int hashCode = obj.GetType().GetHashCode();
+				unchecked {
+					foreach (object o in obj) {
+						hashCode *= 27;
+						hashCode += RuntimeHelpers.GetHashCode(o);
+					}
+				}
+				return hashCode;
+			}
+		}
+		
+		Dictionary<object, object> byValueDict = new Dictionary<object, object>();
+		Dictionary<ISupportsInterning, ISupportsInterning> supportsInternDict = new Dictionary<ISupportsInterning, ISupportsInterning>(new InterningComparer());
+		Dictionary<IEnumerable, IEnumerable> listDict = new Dictionary<IEnumerable, IEnumerable>(new ListComparer());
+		
+		public override ISupportsInterning Intern(ISupportsInterning obj)
+		{
+			if (obj == null)
+				return null;
+			
+			// ensure objects are frozen when we put them into the dictionary
+			// note that Freeze may change the hash code of the object
+			FreezableHelper.Freeze(obj);
+
+			ISupportsInterning output;
+			if (supportsInternDict.TryGetValue(obj, out output)) {
+				return output;
+			} else {
+				supportsInternDict.Add(obj, obj);
+				return obj;
+			}
+		}
+		
+		public override string Intern(string text)
+		{
+			if (text == null)
+				return null;
+			
+			object output;
+			if (byValueDict.TryGetValue(text, out output))
+				return (string)output;
+			else
+				return text;
+		}
+		
+		public override object InternValue(object obj)
+		{
+			if (obj == null)
+				return null;
+			
+			object output;
+			if (byValueDict.TryGetValue(obj, out output))
+				return output;
+			else
+				return obj;
+		}
+		
+		public override IList<T> InternList<T>(IList<T> list)
+		{
+			if (list == null)
+				return null;
+			if (list.Count == 0)
+				return EmptyList<T>.Instance;
+			if (!list.IsReadOnly)
+				list = new ReadOnlyCollection<T>(list);
+			IEnumerable output;
+			if (listDict.TryGetValue(list, out output))
+				list = (IList<T>)output;
+			else
+				listDict.Add(list, list);
+			return list;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedEvent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedEvent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedEvent.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Represents a specialized IEvent (event after type substitution).
+	/// </summary>
+	public class SpecializedEvent : SpecializedMember, IEvent
+	{
+		readonly IEvent eventDefinition;
+		
+		public SpecializedEvent(IEvent eventDefinition, TypeParameterSubstitution substitution)
+			: base(eventDefinition)
+		{
+			this.eventDefinition = eventDefinition;
+			AddSubstitution(substitution);
+		}
+		
+		public bool CanAdd {
+			get { return eventDefinition.CanAdd; }
+		}
+		
+		public bool CanRemove {
+			get { return eventDefinition.CanRemove; }
+		}
+		
+		public bool CanInvoke {
+			get { return eventDefinition.CanInvoke; }
+		}
+		
+		IMethod addAccessor, removeAccessor, invokeAccessor;
+		
+		public IMethod AddAccessor {
+			get { return WrapAccessor(ref this.addAccessor, eventDefinition.AddAccessor); }
+		}
+		
+		public IMethod RemoveAccessor {
+			get { return WrapAccessor(ref this.removeAccessor, eventDefinition.RemoveAccessor); }
+		}
+		
+		public IMethod InvokeAccessor {
+			get { return WrapAccessor(ref this.invokeAccessor, eventDefinition.InvokeAccessor); }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedField.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedField.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedField.cs	(revision 11807)
@@ -0,0 +1,61 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Represents a specialized IField (field after type substitution).
+	/// </summary>
+	public class SpecializedField : SpecializedMember, IField
+	{
+		readonly IField fieldDefinition;
+		
+		public SpecializedField(IField fieldDefinition, TypeParameterSubstitution substitution)
+			: base(fieldDefinition)
+		{
+			this.fieldDefinition = fieldDefinition;
+			AddSubstitution(substitution);
+		}
+		
+		public bool IsReadOnly {
+			get { return fieldDefinition.IsReadOnly; }
+		}
+		
+		public bool IsVolatile {
+			get { return fieldDefinition.IsVolatile; }
+		}
+		
+		IType IVariable.Type {
+			get { return this.ReturnType; }
+		}
+		
+		public bool IsConst {
+			get { return fieldDefinition.IsConst; }
+		}
+
+		public bool IsFixed {
+			get { return fieldDefinition.IsFixed; }
+		}
+
+		public object ConstantValue {
+			get { return fieldDefinition.ConstantValue; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedMember.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedMember.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedMember.cs	(revision 11807)
@@ -0,0 +1,410 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Represents a SpecializedMember (a member on which type substitution has been performed).
+	/// </summary>
+	public abstract class SpecializedMember : IMember
+	{
+		protected readonly IMember baseMember;
+		TypeParameterSubstitution substitution;
+		
+		IType declaringType;
+		IType returnType;
+		
+		protected SpecializedMember(IMember memberDefinition)
+		{
+			if (memberDefinition == null)
+				throw new ArgumentNullException("memberDefinition");
+			if (memberDefinition is SpecializedMember)
+				throw new ArgumentException("Member definition cannot be specialized. Please use IMember.Specialize() instead of directly constructing SpecializedMember instances.");
+			
+			this.baseMember = memberDefinition;
+			this.substitution = TypeParameterSubstitution.Identity;
+		}
+		
+		/// <summary>
+		/// Performs a substitution. This method may only be called by constructors in derived classes.
+		/// </summary>
+		protected void AddSubstitution(TypeParameterSubstitution newSubstitution)
+		{
+			Debug.Assert(declaringType == null);
+			Debug.Assert(returnType == null);
+			this.substitution = TypeParameterSubstitution.Compose(newSubstitution, this.substitution);
+		}
+		
+		[Obsolete("Use IMember.Specialize() instead")]
+		public static IMember Create(IMember memberDefinition, TypeParameterSubstitution substitution)
+		{
+			if (memberDefinition == null) {
+				return null;
+			} else {
+				return memberDefinition.Specialize(substitution);
+			}
+		}
+		
+		public virtual IMemberReference ToMemberReference()
+		{
+			return ToReference();
+		}
+		
+		public virtual IMemberReference ToReference()
+		{
+			return new SpecializingMemberReference(
+				baseMember.ToReference(),
+				ToTypeReference(substitution.ClassTypeArguments),
+				null);
+		}
+		
+		ISymbolReference ISymbol.ToReference()
+		{
+			return ToReference();
+		}
+		
+		internal static IList<ITypeReference> ToTypeReference(IList<IType> typeArguments)
+		{
+			if (typeArguments == null)
+				return null;
+			else
+				return typeArguments.Select(t => t.ToTypeReference()).ToArray();
+		}
+		
+		internal IMethod WrapAccessor(ref IMethod cachingField, IMethod accessorDefinition)
+		{
+			if (accessorDefinition == null)
+				return null;
+			var result = LazyInit.VolatileRead(ref cachingField);
+			if (result != null) {
+				return result;
+			} else {
+				var sm = accessorDefinition.Specialize(substitution);
+				//sm.AccessorOwner = this;
+				return LazyInit.GetOrSet(ref cachingField, sm);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the substitution belonging to this specialized member.
+		/// </summary>
+		public TypeParameterSubstitution Substitution {
+			get { return substitution; }
+		}
+		
+		public IType DeclaringType {
+			get {
+				var result = LazyInit.VolatileRead(ref this.declaringType);
+				if (result != null)
+					return result;
+				IType definitionDeclaringType = baseMember.DeclaringType;
+				ITypeDefinition definitionDeclaringTypeDef = definitionDeclaringType as ITypeDefinition;
+				if (definitionDeclaringTypeDef != null && definitionDeclaringType.TypeParameterCount > 0) {
+					if (substitution.ClassTypeArguments != null && substitution.ClassTypeArguments.Count == definitionDeclaringType.TypeParameterCount) {
+						result = new ParameterizedType(definitionDeclaringTypeDef, substitution.ClassTypeArguments);
+					} else {
+						result = new ParameterizedType(definitionDeclaringTypeDef, definitionDeclaringTypeDef.TypeParameters).AcceptVisitor(substitution);
+					}
+				} else {
+					result = definitionDeclaringType.AcceptVisitor(substitution);
+				}
+				return LazyInit.GetOrSet(ref this.declaringType, result);
+			}
+			internal set {
+				// This setter is used as an optimization when the code constructing
+				// the SpecializedMember already knows the declaring type.
+				Debug.Assert(this.declaringType == null);
+				Debug.Assert(value != null);
+				// As this setter is used only during construction before the member is published
+				// to other threads, we don't need a volatile write.
+				this.declaringType = value;
+			}
+		}
+		
+		public IMember MemberDefinition {
+			get { return baseMember.MemberDefinition; }
+		}
+		
+		public IUnresolvedMember UnresolvedMember {
+			get { return baseMember.UnresolvedMember; }
+		}
+		
+		public IType ReturnType {
+			get {
+				var result = LazyInit.VolatileRead(ref this.returnType);
+				if (result != null)
+					return result;
+				else
+					return LazyInit.GetOrSet(ref this.returnType, baseMember.ReturnType.AcceptVisitor(substitution));
+			}
+			protected set {
+				// This setter is used for LiftedUserDefinedOperator, a special case of specialized member
+				// (not a normal type parameter substitution).
+				
+				// As this setter is used only during construction before the member is published
+				// to other threads, we don't need a volatile write.
+				this.returnType = value;
+			}
+		}
+		
+		public bool IsVirtual {
+			get { return baseMember.IsVirtual; }
+		}
+		
+		public bool IsOverride {
+			get { return baseMember.IsOverride; }
+		}
+		
+		public bool IsOverridable {
+			get { return baseMember.IsOverridable; }
+		}
+		
+		public SymbolKind SymbolKind {
+			get { return baseMember.SymbolKind; }
+		}
+		
+		[Obsolete("Use the SymbolKind property instead.")]
+		public EntityType EntityType {
+			get { return baseMember.EntityType; }
+		}
+		
+		public DomRegion Region {
+			get { return baseMember.Region; }
+		}
+		
+		public DomRegion BodyRegion {
+			get { return baseMember.BodyRegion; }
+		}
+		
+		public ITypeDefinition DeclaringTypeDefinition {
+			get { return baseMember.DeclaringTypeDefinition; }
+		}
+		
+		public IList<IAttribute> Attributes {
+			get { return baseMember.Attributes; }
+		}
+		
+		IList<IMember> implementedInterfaceMembers;
+		
+		public IList<IMember> ImplementedInterfaceMembers {
+			get {
+				return LazyInitializer.EnsureInitialized(ref implementedInterfaceMembers, FindImplementedInterfaceMembers);
+			}
+		}
+		
+		IList<IMember> FindImplementedInterfaceMembers()
+		{
+			var definitionImplementations = baseMember.ImplementedInterfaceMembers;
+			IMember[] result = new IMember[definitionImplementations.Count];
+			for (int i = 0; i < result.Length; i++) {
+				result[i] = definitionImplementations[i].Specialize(substitution);
+			}
+			return result;
+		}
+		
+		public bool IsExplicitInterfaceImplementation {
+			get { return baseMember.IsExplicitInterfaceImplementation; }
+		}
+		
+		public DocumentationComment Documentation {
+			get { return baseMember.Documentation; }
+		}
+		
+		public Accessibility Accessibility {
+			get { return baseMember.Accessibility; }
+		}
+		
+		public bool IsStatic {
+			get { return baseMember.IsStatic; }
+		}
+		
+		public bool IsAbstract {
+			get { return baseMember.IsAbstract; }
+		}
+		
+		public bool IsSealed {
+			get { return baseMember.IsSealed; }
+		}
+		
+		public bool IsShadowing {
+			get { return baseMember.IsShadowing; }
+		}
+		
+		public bool IsSynthetic {
+			get { return baseMember.IsSynthetic; }
+		}
+		
+		public bool IsPrivate {
+			get { return baseMember.IsPrivate; }
+		}
+		
+		public bool IsPublic {
+			get { return baseMember.IsPublic; }
+		}
+		
+		public bool IsProtected {
+			get { return baseMember.IsProtected; }
+		}
+		
+		public bool IsInternal {
+			get { return baseMember.IsInternal; }
+		}
+		
+		public bool IsProtectedOrInternal {
+			get { return baseMember.IsProtectedOrInternal; }
+		}
+		
+		public bool IsProtectedAndInternal {
+			get { return baseMember.IsProtectedAndInternal; }
+		}
+		
+		public string FullName {
+			get { return baseMember.FullName; }
+		}
+		
+		public string Name {
+			get { return baseMember.Name; }
+		}
+		
+		public string Namespace {
+			get { return baseMember.Namespace; }
+		}
+		
+		public string ReflectionName {
+			get { return baseMember.ReflectionName; }
+		}
+		
+		public ICompilation Compilation {
+			get { return baseMember.Compilation; }
+		}
+		
+		public IAssembly ParentAssembly {
+			get { return baseMember.ParentAssembly; }
+		}
+
+		public virtual IMember Specialize(TypeParameterSubstitution newSubstitution)
+		{
+			return baseMember.Specialize(TypeParameterSubstitution.Compose(newSubstitution, this.substitution));
+		}
+
+		public override bool Equals(object obj)
+		{
+			SpecializedMember other = obj as SpecializedMember;
+			if (other == null)
+				return false;
+			return this.baseMember.Equals(other.baseMember) && this.substitution.Equals(other.substitution);
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				return 1000000007 * baseMember.GetHashCode() + 1000000009 * substitution.GetHashCode();
+			}
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[");
+			b.Append(GetType().Name);
+			b.Append(' ');
+			b.Append(this.DeclaringType.ToString());
+			b.Append('.');
+			b.Append(this.Name);
+			b.Append(':');
+			b.Append(this.ReturnType.ToString());
+			b.Append(']');
+			return b.ToString();
+		}
+	}
+	
+	public abstract class SpecializedParameterizedMember : SpecializedMember, IParameterizedMember
+	{
+		IList<IParameter> parameters;
+		
+		protected SpecializedParameterizedMember(IParameterizedMember memberDefinition)
+			: base(memberDefinition)
+		{
+		}
+		
+		public IList<IParameter> Parameters {
+			get {
+				var result = LazyInit.VolatileRead(ref this.parameters);
+				if (result != null)
+					return result;
+				else
+					return LazyInit.GetOrSet(ref this.parameters, CreateParameters(this.Substitution));
+			}
+			protected set {
+				// This setter is used for LiftedUserDefinedOperator, a special case of specialized member
+				// (not a normal type parameter substitution).
+				
+				// As this setter is used only during construction before the member is published
+				// to other threads, we don't need a volatile write.
+				this.parameters = value;
+			}
+		}
+		
+		protected IList<IParameter> CreateParameters(TypeVisitor substitution)
+		{
+			var paramDefs = ((IParameterizedMember)this.baseMember).Parameters;
+			if (paramDefs.Count == 0) {
+				return EmptyList<IParameter>.Instance;
+			} else {
+				var parameters = new IParameter[paramDefs.Count];
+				for (int i = 0; i < parameters.Length; i++) {
+					var p = paramDefs[i];
+					IType newType = p.Type.AcceptVisitor(substitution);
+					parameters[i] = new DefaultParameter(
+						newType, p.Name, this,
+						p.Region, p.Attributes, p.IsRef, p.IsOut,
+						p.IsParams, p.IsOptional, p.ConstantValue
+					);
+				}
+				return Array.AsReadOnly(parameters);
+			}
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[");
+			b.Append(GetType().Name);
+			b.Append(' ');
+			b.Append(this.DeclaringType.ReflectionName);
+			b.Append('.');
+			b.Append(this.Name);
+			b.Append('(');
+			for (int i = 0; i < this.Parameters.Count; i++) {
+				if (i > 0) b.Append(", ");
+				b.Append(this.Parameters[i].ToString());
+			}
+			b.Append("):");
+			b.Append(this.ReturnType.ReflectionName);
+			b.Append(']');
+			return b.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedMethod.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedMethod.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedMethod.cs	(revision 11807)
@@ -0,0 +1,286 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Represents a specialized IMethod (e.g. after type substitution).
+	/// </summary>
+	public class SpecializedMethod : SpecializedParameterizedMember, IMethod
+	{
+		readonly IMethod methodDefinition;
+		readonly ITypeParameter[] specializedTypeParameters;
+		readonly bool isParameterized;
+		readonly TypeParameterSubstitution substitutionWithoutSpecializedTypeParameters;
+		
+		public SpecializedMethod(IMethod methodDefinition, TypeParameterSubstitution substitution)
+			: base(methodDefinition)
+		{
+			if (substitution == null)
+				throw new ArgumentNullException("substitution");
+			this.methodDefinition = methodDefinition;
+			this.isParameterized = substitution.MethodTypeArguments != null;
+			if (methodDefinition.TypeParameters.Count > 0) {
+				// The method is generic, so we need to specialize the type parameters
+				// (for specializing the constraints, and also to set the correct Owner)
+				specializedTypeParameters = new ITypeParameter[methodDefinition.TypeParameters.Count];
+				for (int i = 0; i < specializedTypeParameters.Length; i++) {
+					specializedTypeParameters[i] = new SpecializedTypeParameter(methodDefinition.TypeParameters[i], this);
+				}
+				if (!isParameterized) {
+					// Add substitution that replaces the base method's type parameters with our specialized version
+					// but do this only if the type parameters on the baseMember have not already been substituted
+					substitutionWithoutSpecializedTypeParameters = this.Substitution;
+					AddSubstitution(new TypeParameterSubstitution(null, specializedTypeParameters));
+				}
+			}
+			// Add the main substitution after the method type parameter specialization.
+			AddSubstitution(substitution);
+			if (substitutionWithoutSpecializedTypeParameters != null) {
+				// If we already have a substitution without specialized type parameters, update that:
+				substitutionWithoutSpecializedTypeParameters = TypeParameterSubstitution.Compose(substitution, substitutionWithoutSpecializedTypeParameters);
+			} else {
+				// Otherwise just use the whole substitution, as that doesn't contain specialized type parameters
+				// in this case.
+				substitutionWithoutSpecializedTypeParameters = this.Substitution;
+			}
+			if (specializedTypeParameters != null) {
+				// Set the substitution on the type parameters to the final composed substitution
+				foreach (var tp in specializedTypeParameters.OfType<SpecializedTypeParameter>()) {
+					if (tp.Owner == this)
+						tp.substitution = base.Substitution;
+				}
+			}
+		}
+		
+		public IList<IType> TypeArguments {
+			get { return this.Substitution.MethodTypeArguments ?? EmptyList<IType>.Instance; }
+		}
+		
+		public bool IsParameterized {
+			get { return isParameterized; }
+		}
+		
+		public IList<IUnresolvedMethod> Parts {
+			get { return methodDefinition.Parts; }
+		}
+		
+		public IList<IAttribute> ReturnTypeAttributes {
+			get { return methodDefinition.ReturnTypeAttributes; }
+		}
+		
+		public IList<ITypeParameter> TypeParameters {
+			get {
+				return specializedTypeParameters ?? methodDefinition.TypeParameters;
+			}
+		}
+		
+		public bool IsExtensionMethod {
+			get { return methodDefinition.IsExtensionMethod; }
+		}
+		
+		public bool IsConstructor {
+			get { return methodDefinition.IsConstructor; }
+		}
+		
+		public bool IsDestructor {
+			get { return methodDefinition.IsDestructor; }
+		}
+		
+		public bool IsOperator {
+			get { return methodDefinition.IsOperator; }
+		}
+		
+		public bool IsPartial {
+			get { return methodDefinition.IsPartial; }
+		}
+		
+		public bool IsAsync {
+			get { return methodDefinition.IsAsync; }
+		}
+		
+		public bool HasBody {
+			get { return methodDefinition.HasBody; }
+		}
+		
+		public bool IsAccessor {
+			get { return methodDefinition.IsAccessor; }
+		}
+
+		public IMethod ReducedFrom {
+			get { return null; }
+		}
+
+		IMember accessorOwner;
+		
+		public IMember AccessorOwner {
+			get {
+				var result = LazyInit.VolatileRead(ref accessorOwner);
+				if (result != null) {
+					return result;
+				} else {
+					var ownerDefinition = methodDefinition.AccessorOwner;
+					if (ownerDefinition == null)
+						return null;
+					result = ownerDefinition.Specialize(this.Substitution);
+					return LazyInit.GetOrSet(ref accessorOwner, result);
+				}
+			}
+			internal set {
+				accessorOwner = value;
+			}
+		}
+
+		public override IMemberReference ToReference()
+		{
+			// Pass the MethodTypeArguments to the SpecializingMemberReference only if
+			// the generic method itself is parameterized, not if the generic method is only
+			// specialized with class type arguments.
+			
+			// This is necessary due to this part of the ToMemberReference() contract:
+			//   If this member is specialized using open generic types, the resulting member reference will need to be looked up in an appropriate generic context.
+			//   Otherwise, the main resolve context of a compilation is sufficient.
+			// ->
+			// This means that if the method itself isn't specialized,
+			// we must not include TypeParameterReferences for the specialized type parameters
+			// in the resulting member reference.
+			if (isParameterized) {
+				return new SpecializingMemberReference(
+					baseMember.ToReference(),
+					ToTypeReference(base.Substitution.ClassTypeArguments),
+					ToTypeReference(base.Substitution.MethodTypeArguments));
+			} else {
+				return base.ToReference();
+			}
+		}
+		
+		public override IMemberReference ToMemberReference()
+		{
+			return ToReference();
+		}
+		
+		public override bool Equals(object obj)
+		{
+			SpecializedMethod other = obj as SpecializedMethod;
+			if (other == null)
+				return false;
+			return this.baseMember.Equals(other.baseMember) && this.substitutionWithoutSpecializedTypeParameters.Equals(other.substitutionWithoutSpecializedTypeParameters);
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				return 1000000013 * baseMember.GetHashCode() + 1000000009 * substitutionWithoutSpecializedTypeParameters.GetHashCode();
+			}
+		}
+
+		public override IMember Specialize(TypeParameterSubstitution newSubstitution)
+		{
+			return methodDefinition.Specialize(TypeParameterSubstitution.Compose(newSubstitution, substitutionWithoutSpecializedTypeParameters));
+		}
+		
+		IMethod IMethod.Specialize(TypeParameterSubstitution newSubstitution)
+		{
+			return methodDefinition.Specialize(TypeParameterSubstitution.Compose(newSubstitution, substitutionWithoutSpecializedTypeParameters));
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[");
+			b.Append(GetType().Name);
+			b.Append(' ');
+			b.Append(this.DeclaringType.ReflectionName);
+			b.Append('.');
+			b.Append(this.Name);
+			if (this.TypeArguments.Count > 0) {
+				b.Append('[');
+				for (int i = 0; i < this.TypeArguments.Count; i++) {
+					if (i > 0) b.Append(", ");
+					b.Append(this.TypeArguments[i].ReflectionName);
+				}
+				b.Append(']');
+			} else if (this.TypeParameters.Count > 0) {
+				b.Append("``");
+				b.Append(this.TypeParameters.Count);
+			}
+			b.Append('(');
+			for (int i = 0; i < this.Parameters.Count; i++) {
+				if (i > 0) b.Append(", ");
+				b.Append(this.Parameters[i].ToString());
+			}
+			b.Append("):");
+			b.Append(this.ReturnType.ReflectionName);
+			b.Append(']');
+			return b.ToString();
+		}
+		
+		sealed class SpecializedTypeParameter : AbstractTypeParameter
+		{
+			readonly ITypeParameter baseTp;
+			
+			// The substition is set at the end of SpecializedMethod constructor
+			internal TypeVisitor substitution;
+			
+			public SpecializedTypeParameter(ITypeParameter baseTp, IMethod specializedOwner)
+				: base(specializedOwner, baseTp.Index, baseTp.Name, baseTp.Variance, baseTp.Attributes, baseTp.Region)
+			{
+				// We don't have to consider already-specialized baseTps because
+				// we read the baseTp directly from the unpacked memberDefinition.
+				this.baseTp = baseTp;
+			}
+			
+			public override int GetHashCode()
+			{
+				return baseTp.GetHashCode() ^ this.Owner.GetHashCode();
+			}
+			
+			public override bool Equals(IType other)
+			{
+				// Compare the owner, not the substitution, because the substitution may contain this specialized type parameter recursively
+				SpecializedTypeParameter o = other as SpecializedTypeParameter;
+				return o != null && baseTp.Equals(o.baseTp) && this.Owner.Equals(o.Owner);
+			}
+			
+			public override bool HasValueTypeConstraint {
+				get { return baseTp.HasValueTypeConstraint; }
+			}
+			
+			public override bool HasReferenceTypeConstraint {
+				get { return baseTp.HasReferenceTypeConstraint; }
+			}
+			
+			public override bool HasDefaultConstructorConstraint {
+				get { return baseTp.HasDefaultConstructorConstraint; }
+			}
+			
+			public override IEnumerable<IType> DirectBaseTypes {
+				get {
+					return baseTp.DirectBaseTypes.Select(t => t.AcceptVisitor(substitution));
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedProperty.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedProperty.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializedProperty.cs	(revision 11807)
@@ -0,0 +1,59 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Represents a specialized IProperty (property after type substitution).
+	/// </summary>
+	public class SpecializedProperty : SpecializedParameterizedMember, IProperty
+	{
+		readonly IProperty propertyDefinition;
+		
+		public SpecializedProperty(IProperty propertyDefinition, TypeParameterSubstitution substitution)
+			: base(propertyDefinition)
+		{
+			this.propertyDefinition = propertyDefinition;
+			AddSubstitution(substitution);
+		}
+		
+		public bool CanGet {
+			get { return propertyDefinition.CanGet; }
+		}
+		
+		public bool CanSet {
+			get { return propertyDefinition.CanSet; }
+		}
+		
+		IMethod getter, setter;
+		
+		public IMethod Getter {
+			get { return WrapAccessor(ref this.getter, propertyDefinition.Getter); }
+		}
+		
+		public IMethod Setter {
+			get { return WrapAccessor(ref this.setter, propertyDefinition.Setter); }
+		}
+		
+		public bool IsIndexer {
+			get { return propertyDefinition.IsIndexer; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializingMemberReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializingMemberReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/SpecializingMemberReference.cs	(revision 11807)
@@ -0,0 +1,67 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	[Serializable]
+	public sealed class SpecializingMemberReference : IMemberReference
+	{
+		IMemberReference memberDefinitionReference;
+		IList<ITypeReference> classTypeArgumentReferences;
+		IList<ITypeReference> methodTypeArgumentReferences;
+		
+		public SpecializingMemberReference(IMemberReference memberDefinitionReference, IList<ITypeReference> classTypeArgumentReferences = null, IList<ITypeReference> methodTypeArgumentReferences = null)
+		{
+			if (memberDefinitionReference == null)
+				throw new ArgumentNullException("memberDefinitionReference");
+			this.memberDefinitionReference = memberDefinitionReference;
+			this.classTypeArgumentReferences = classTypeArgumentReferences;
+			this.methodTypeArgumentReferences = methodTypeArgumentReferences;
+		}
+		
+		public IMember Resolve(ITypeResolveContext context)
+		{
+			var memberDefinition = memberDefinitionReference.Resolve(context);
+			if (memberDefinition == null)
+				return null;
+			return memberDefinition.Specialize(
+				new TypeParameterSubstitution(
+					classTypeArgumentReferences != null ? classTypeArgumentReferences.Resolve(context) : null,
+					methodTypeArgumentReferences != null ? methodTypeArgumentReferences.Resolve(context) : null
+				)
+			);
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return Resolve(context);
+		}
+		
+		public ITypeReference DeclaringTypeReference {
+			get {
+				if (classTypeArgumentReferences != null)
+					return new ParameterizedTypeReference(memberDefinitionReference.DeclaringTypeReference, classTypeArgumentReferences);
+				else
+					return memberDefinitionReference.DeclaringTypeReference;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/TypeParameterReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/TypeParameterReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/TypeParameterReference.cs	(revision 11807)
@@ -0,0 +1,96 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	[Serializable]
+	public sealed class TypeParameterReference : ITypeReference, ISymbolReference
+	{
+		static readonly TypeParameterReference[] classTypeParameterReferences = new TypeParameterReference[8];
+		static readonly TypeParameterReference[] methodTypeParameterReferences = new TypeParameterReference[8];
+		
+		/// <summary>
+		/// Creates a type parameter reference.
+		/// For common type parameter references, this method may return a shared instance.
+		/// </summary>
+		public static TypeParameterReference Create(SymbolKind ownerType, int index)
+		{
+			if (index >= 0 && index < 8 && (ownerType == SymbolKind.TypeDefinition || ownerType == SymbolKind.Method)) {
+				TypeParameterReference[] arr = (ownerType == SymbolKind.TypeDefinition) ? classTypeParameterReferences : methodTypeParameterReferences;
+				TypeParameterReference result = LazyInit.VolatileRead(ref arr[index]);
+				if (result == null) {
+					result = LazyInit.GetOrSet(ref arr[index], new TypeParameterReference(ownerType, index));
+				}
+				return result;
+			} else {
+				return new TypeParameterReference(ownerType, index);
+			}
+		}
+		
+		readonly SymbolKind ownerType;
+		readonly int index;
+
+		public int Index {
+			get {
+				return index;
+			}
+		}
+
+		public TypeParameterReference(SymbolKind ownerType, int index)
+		{
+			this.ownerType = ownerType;
+			this.index = index;
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			if (ownerType == SymbolKind.Method) {
+				IMethod method = context.CurrentMember as IMethod;
+				if (method != null && index < method.TypeParameters.Count) {
+					return method.TypeParameters[index];
+				}
+				return DummyTypeParameter.GetMethodTypeParameter(index);
+			} else if (ownerType == SymbolKind.TypeDefinition) {
+				ITypeDefinition typeDef = context.CurrentTypeDefinition;
+				if (typeDef != null && index < typeDef.TypeParameters.Count) {
+					return typeDef.TypeParameters[index];
+				}
+				return DummyTypeParameter.GetClassTypeParameter(index);
+			} else {
+				return SpecialType.UnknownType;
+			}
+		}
+		
+		ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+		{
+			return Resolve(context) as ISymbol;
+		}
+		
+		public override string ToString()
+		{
+			if (ownerType == SymbolKind.Method)
+				return "!!" + index.ToString(CultureInfo.InvariantCulture);
+			else
+				return "!" + index.ToString(CultureInfo.InvariantCulture);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/TypeWithElementType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/TypeWithElementType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/TypeWithElementType.cs	(revision 11807)
@@ -0,0 +1,61 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	public abstract class TypeWithElementType : AbstractType
+	{
+		[CLSCompliant(false)]
+		protected IType elementType;
+		
+		protected TypeWithElementType(IType elementType)
+		{
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			this.elementType = elementType;
+		}
+		
+		public override string Name {
+			get { return elementType.Name + NameSuffix; }
+		}
+		
+		public override string Namespace {
+			get { return elementType.Namespace; }
+		}
+		
+		public override string FullName {
+			get { return elementType.FullName + NameSuffix; }
+		}
+		
+		public override string ReflectionName {
+			get { return elementType.ReflectionName + NameSuffix; }
+		}
+		
+		public abstract string NameSuffix { get; }
+		
+		public IType ElementType {
+			get { return elementType; }
+		}
+		
+		// Force concrete implementations to override VisitChildren - the base implementation
+		// in AbstractType assumes there are no children, but we know there is (at least) 1.
+		public abstract override IType VisitChildren(TypeVisitor visitor);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnknownType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnknownType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnknownType.cs	(revision 11807)
@@ -0,0 +1,117 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// An unknown type where (part) of the name is known.
+	/// </summary>
+	[Serializable]
+	public class UnknownType : AbstractType, ITypeReference
+	{
+		readonly bool namespaceKnown;
+		readonly FullTypeName fullTypeName;
+		
+		/// <summary>
+		/// Creates a new unknown type.
+		/// </summary>
+		/// <param name="namespaceName">Namespace name, if known. Can be null if unknown.</param>
+		/// <param name="name">Name of the type, must not be null.</param>
+		/// <param name="typeParameterCount">Type parameter count, zero if unknown.</param>
+		public UnknownType(string namespaceName, string name, int typeParameterCount = 0)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.namespaceKnown = namespaceName != null;
+			this.fullTypeName = new TopLevelTypeName(namespaceName ?? string.Empty, name, typeParameterCount);
+		}
+		
+		/// <summary>
+		/// Creates a new unknown type.
+		/// </summary>
+		/// <param name="fullTypeName">Full name of the unknown type.</param>
+		public UnknownType(FullTypeName fullTypeName)
+		{
+			if (fullTypeName.Name == null) {
+				Debug.Assert(fullTypeName == default(FullTypeName));
+				this.namespaceKnown = false;
+				this.fullTypeName = new TopLevelTypeName(string.Empty, "?", 0);
+			} else {
+				this.namespaceKnown = true;
+				this.fullTypeName = fullTypeName;
+			}
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.Unknown; }
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return this;
+		}
+		
+		IType ITypeReference.Resolve(ITypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			return this;
+		}
+		
+		public override string Name {
+			get { return fullTypeName.Name; }
+		}
+		
+		public override string Namespace {
+			get { return fullTypeName.TopLevelTypeName.Namespace; }
+		}
+		
+		public override string ReflectionName {
+			get { return namespaceKnown ? fullTypeName.ReflectionName : "?"; }
+		}
+		
+		public override int TypeParameterCount {
+			get { return fullTypeName.TypeParameterCount; }
+		}
+		
+		public override bool? IsReferenceType {
+			get { return null; }
+		}
+		
+		public override int GetHashCode()
+		{
+			return (namespaceKnown ? 812571 : 12651) ^ fullTypeName.GetHashCode();
+		}
+		
+		public override bool Equals(IType other)
+		{
+			UnknownType o = other as UnknownType;
+			if (o == null)
+				return false;
+			return this.namespaceKnown == o.namespaceKnown && this.fullTypeName == o.fullTypeName;
+		}
+		
+		public override string ToString()
+		{
+			return "[UnknownType " + fullTypeName.ReflectionName + "]";
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnresolvedAttributeBlob.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnresolvedAttributeBlob.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnresolvedAttributeBlob.cs	(revision 11807)
@@ -0,0 +1,78 @@
+﻿//
+// UnresolvedAttributeBlob.cs
+//
+// Author:
+//       Daniel Grunwald <daniel@danielgrunwald.de>
+//
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// <c>IUnresolvedAttribute</c> implementation that loads the arguments from a binary blob.
+	/// </summary>
+	[Serializable]
+	public sealed class UnresolvedAttributeBlob : IUnresolvedAttribute, ISupportsInterning
+	{
+		internal readonly ITypeReference attributeType;
+		internal readonly IList<ITypeReference> ctorParameterTypes;
+		internal readonly byte[] blob;
+		
+		public UnresolvedAttributeBlob(ITypeReference attributeType, IList<ITypeReference> ctorParameterTypes, byte[] blob)
+		{
+			if (attributeType == null)
+				throw new ArgumentNullException("attributeType");
+			if (ctorParameterTypes == null)
+				throw new ArgumentNullException("ctorParameterTypes");
+			if (blob == null)
+				throw new ArgumentNullException("blob");
+			this.attributeType = attributeType;
+			this.ctorParameterTypes = ctorParameterTypes;
+			this.blob = blob;
+		}
+		
+		DomRegion IUnresolvedAttribute.Region {
+			get { return DomRegion.Empty; }
+		}
+		
+		public IAttribute CreateResolvedAttribute(ITypeResolveContext context)
+		{
+			if (context.CurrentAssembly == null)
+				throw new InvalidOperationException("Cannot resolve CecilUnresolvedAttribute without a parent assembly");
+			return new CecilResolvedAttribute(context, this);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return attributeType.GetHashCode() ^ ctorParameterTypes.GetHashCode() ^ BlobReader.GetBlobHashCode(blob);
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			UnresolvedAttributeBlob o = other as UnresolvedAttributeBlob;
+			return o != null && attributeType == o.attributeType && ctorParameterTypes == o.ctorParameterTypes
+				&& BlobReader.BlobEquals(blob, o.blob);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnresolvedSecurityDeclarationBlob.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnresolvedSecurityDeclarationBlob.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/UnresolvedSecurityDeclarationBlob.cs	(revision 11807)
@@ -0,0 +1,152 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	[Serializable]
+	public sealed class UnresolvedSecurityDeclarationBlob
+	{
+		static readonly ITypeReference securityActionTypeReference = typeof(System.Security.Permissions.SecurityAction).ToTypeReference();
+		static readonly ITypeReference permissionSetAttributeTypeReference = typeof(System.Security.Permissions.PermissionSetAttribute).ToTypeReference();
+		
+		readonly IConstantValue securityAction;
+		readonly byte[] blob;
+		readonly IList<IUnresolvedAttribute> unresolvedAttributes = new List<IUnresolvedAttribute>();
+		
+		public UnresolvedSecurityDeclarationBlob(int securityAction, byte[] blob)
+		{
+			BlobReader reader = new BlobReader(blob, null);
+			this.securityAction = new SimpleConstantValue(securityActionTypeReference, securityAction);
+			this.blob = blob;
+			if (reader.ReadByte() == '.') {
+				// binary attribute
+				uint attributeCount = reader.ReadCompressedUInt32();
+				for (uint i = 0; i < attributeCount; i++) {
+					unresolvedAttributes.Add(new UnresolvedSecurityAttribute(this, (int)i));
+				}
+			} else {
+				// for backward compatibility with .NET 1.0: XML-encoded attribute
+				var attr = new DefaultUnresolvedAttribute(permissionSetAttributeTypeReference);
+				attr.ConstructorParameterTypes.Add(securityActionTypeReference);
+				attr.PositionalArguments.Add(this.securityAction);
+				string xml = System.Text.Encoding.Unicode.GetString(blob);
+				attr.AddNamedPropertyArgument("XML", new SimpleConstantValue(KnownTypeReference.String, xml));
+				unresolvedAttributes.Add(attr);
+			}
+		}
+		
+		public IList<IUnresolvedAttribute> UnresolvedAttributes {
+			get { return unresolvedAttributes; }
+		}
+		
+		public IList<IAttribute> Resolve(IAssembly currentAssembly)
+		{
+			// TODO: make this a per-assembly cache
+//				CacheManager cache = currentAssembly.Compilation.CacheManager;
+//				IList<IAttribute> result = (IList<IAttribute>)cache.GetShared(this);
+//				if (result != null)
+//					return result;
+			
+			ITypeResolveContext context = new SimpleTypeResolveContext(currentAssembly);
+			BlobReader reader = new BlobReader(blob, currentAssembly);
+			if (reader.ReadByte() != '.') {
+				// should not use UnresolvedSecurityDeclaration for XML secdecls
+				throw new InvalidOperationException();
+			}
+			ResolveResult securityActionRR = securityAction.Resolve(context);
+			uint attributeCount = reader.ReadCompressedUInt32();
+			IAttribute[] attributes = new IAttribute[attributeCount];
+			try {
+				ReadSecurityBlob(reader, attributes, context, securityActionRR);
+			} catch (NotSupportedException ex) {
+				// ignore invalid blobs
+				Debug.WriteLine(ex.ToString());
+			}
+			for (int i = 0; i < attributes.Length; i++) {
+				if (attributes[i] == null)
+					attributes[i] = new CecilResolvedAttribute(context, SpecialType.UnknownType);
+			}
+			return attributes;
+//				return (IList<IAttribute>)cache.GetOrAddShared(this, attributes);
+		}
+		
+		void ReadSecurityBlob(BlobReader reader, IAttribute[] attributes, ITypeResolveContext context, ResolveResult securityActionRR)
+		{
+			for (int i = 0; i < attributes.Length; i++) {
+				string attributeTypeName = reader.ReadSerString();
+				ITypeReference attributeTypeRef = ReflectionHelper.ParseReflectionName(attributeTypeName);
+				IType attributeType = attributeTypeRef.Resolve(context);
+				
+				reader.ReadCompressedUInt32(); // ??
+				// The specification seems to be incorrect here, so I'm using the logic from Cecil instead.
+				uint numNamed = reader.ReadCompressedUInt32();
+				
+				var namedArgs = new List<KeyValuePair<IMember, ResolveResult>>((int)numNamed);
+				for (uint j = 0; j < numNamed; j++) {
+					var namedArg = reader.ReadNamedArg(attributeType);
+					if (namedArg.Key != null)
+						namedArgs.Add(namedArg);
+					
+				}
+				attributes[i] = new DefaultAttribute(
+					attributeType,
+					positionalArguments: new ResolveResult[] { securityActionRR },
+					namedArguments: namedArgs);
+			}
+		}
+	}
+	
+	[Serializable]
+	sealed class UnresolvedSecurityAttribute : IUnresolvedAttribute, ISupportsInterning
+	{
+		readonly UnresolvedSecurityDeclarationBlob secDecl;
+		readonly int index;
+		
+		public UnresolvedSecurityAttribute(UnresolvedSecurityDeclarationBlob secDecl, int index)
+		{
+			Debug.Assert(secDecl != null);
+			this.secDecl = secDecl;
+			this.index = index;
+		}
+		
+		DomRegion IUnresolvedAttribute.Region {
+			get { return DomRegion.Empty; }
+		}
+		
+		IAttribute IUnresolvedAttribute.CreateResolvedAttribute(ITypeResolveContext context)
+		{
+			return secDecl.Resolve(context.CurrentAssembly)[index];
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return index ^ secDecl.GetHashCode();
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			UnresolvedSecurityAttribute attr = other as UnresolvedSecurityAttribute;
+			return attr != null && index == attr.index && secDecl == attr.secDecl;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/VoidTypeDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/VoidTypeDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/Implementation/VoidTypeDefinition.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.TypeSystem.Implementation
+{
+	/// <summary>
+	/// Special type definition for 'void'.
+	/// </summary>
+	public class VoidTypeDefinition : DefaultResolvedTypeDefinition
+	{
+		public VoidTypeDefinition(ITypeResolveContext parentContext, params IUnresolvedTypeDefinition[] parts)
+			: base(parentContext, parts)
+		{
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.Void; }
+		}
+		
+		public override IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public override IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter, GetMemberOptions options)
+		{
+			return EmptyList<IEvent>.Instance;
+		}
+		
+		public override IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter, GetMemberOptions options)
+		{
+			return EmptyList<IField>.Instance;
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return EmptyList<IMethod>.Instance;
+		}
+		
+		public override IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter, GetMemberOptions options)
+		{
+			return EmptyList<IProperty>.Instance;
+		}
+		
+		public override IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter, GetMemberOptions options)
+		{
+			return EmptyList<IMember>.Instance;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/InheritanceHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/InheritanceHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/InheritanceHelper.cs	(revision 11807)
@@ -0,0 +1,148 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Provides helper methods for inheritance.
+	/// </summary>
+	public static class InheritanceHelper
+	{
+		// TODO: maybe these should be extension methods?
+		// or even part of the interface itself? (would allow for easy caching)
+		
+		#region GetBaseMember
+		/// <summary>
+		/// Gets the base member that has the same signature.
+		/// </summary>
+		public static IMember GetBaseMember(IMember member)
+		{
+			return GetBaseMembers(member, false).FirstOrDefault();
+		}
+
+		/// <summary>
+		/// Gets all base members that have the same signature.
+		/// </summary>
+		/// <returns>
+		/// List of base members with the same signature. The member from the derived-most base class is returned first.
+		/// </returns>
+		public static IEnumerable<IMember> GetBaseMembers(IMember member, bool includeImplementedInterfaces)
+		{
+			if (member == null)
+				throw new ArgumentNullException("member");
+
+			if (member.IsExplicitInterfaceImplementation && member.ImplementedInterfaceMembers.Count == 1) {
+				// C#-style explicit interface implementation
+				member = member.ImplementedInterfaceMembers[0];
+				yield return member;
+			}
+			
+			// Remove generic specialization
+			var substitution = member.Substitution;
+			member = member.MemberDefinition;
+			
+			if (member.DeclaringTypeDefinition == null) {
+				// For global methods, return empty list. (prevent SharpDevelop UDC crash 4524)
+				yield break;
+			}
+			
+			IEnumerable<IType> allBaseTypes;
+			if (includeImplementedInterfaces) {
+				allBaseTypes = member.DeclaringTypeDefinition.GetAllBaseTypes();
+			} else {
+				allBaseTypes = member.DeclaringTypeDefinition.GetNonInterfaceBaseTypes();
+			}
+			foreach (IType baseType in allBaseTypes.Reverse()) {
+				if (baseType == member.DeclaringTypeDefinition)
+					continue;
+
+				IEnumerable<IMember> baseMembers;
+				if (member.SymbolKind == SymbolKind.Accessor) {
+					baseMembers = baseType.GetAccessors(m => m.Name == member.Name && !m.IsExplicitInterfaceImplementation, GetMemberOptions.IgnoreInheritedMembers);
+				} else {
+					baseMembers = baseType.GetMembers(m => m.Name == member.Name && !m.IsExplicitInterfaceImplementation, GetMemberOptions.IgnoreInheritedMembers);
+				}
+				foreach (IMember baseMember in baseMembers) {
+					if (SignatureComparer.Ordinal.Equals(member, baseMember)) {
+						yield return baseMember.Specialize(substitution);
+					}
+				}
+			}
+		}
+		#endregion
+		
+		#region GetDerivedMember
+		/// <summary>
+		/// Finds the member declared in 'derivedType' that has the same signature (could override) 'baseMember'.
+		/// </summary>
+		public static IMember GetDerivedMember(IMember baseMember, ITypeDefinition derivedType)
+		{
+			if (baseMember == null)
+				throw new ArgumentNullException("baseMember");
+			if (derivedType == null)
+				throw new ArgumentNullException("derivedType");
+			
+			if (baseMember.Compilation != derivedType.Compilation)
+				throw new ArgumentException("baseMember and derivedType must be from the same compilation");
+			
+			baseMember = baseMember.MemberDefinition;
+			bool includeInterfaces = baseMember.DeclaringTypeDefinition.Kind == TypeKind.Interface;
+			IMethod method = baseMember as IMethod;
+			if (method != null) {
+				foreach (IMethod derivedMethod in derivedType.Methods) {
+					if (derivedMethod.Name == method.Name && derivedMethod.Parameters.Count == method.Parameters.Count) {
+						if (derivedMethod.TypeParameters.Count == method.TypeParameters.Count) {
+							// The method could override the base method:
+							if (GetBaseMembers(derivedMethod, includeInterfaces).Any(m => m.MemberDefinition == baseMember))
+								return derivedMethod;
+						}
+					}
+				}
+			}
+			IProperty property = baseMember as IProperty;
+			if (property != null) {
+				foreach (IProperty derivedProperty in derivedType.Properties) {
+					if (derivedProperty.Name == property.Name && derivedProperty.Parameters.Count == property.Parameters.Count) {
+						// The property could override the base property:
+						if (GetBaseMembers(derivedProperty, includeInterfaces).Any(m => m.MemberDefinition == baseMember))
+							return derivedProperty;
+					}
+				}
+			}
+			if (baseMember is IEvent) {
+				foreach (IEvent derivedEvent in derivedType.Events) {
+					if (derivedEvent.Name == baseMember.Name)
+						return derivedEvent;
+				}
+			}
+			if (baseMember is IField) {
+				foreach (IField derivedField in derivedType.Fields) {
+					if (derivedField.Name == baseMember.Name)
+						return derivedField;
+				}
+			}
+			return null;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IntersectionType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IntersectionType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/IntersectionType.cs	(revision 11807)
@@ -0,0 +1,178 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents the intersection of several types.
+	/// </summary>
+	public class IntersectionType : AbstractType
+	{
+		readonly ReadOnlyCollection<IType> types;
+		
+		public ReadOnlyCollection<IType> Types {
+			get { return types; }
+		}
+		
+		private IntersectionType(IType[] types)
+		{
+			Debug.Assert(types.Length >= 2);
+			this.types = Array.AsReadOnly(types);
+		}
+		
+		public static IType Create(IEnumerable<IType> types)
+		{
+			IType[] arr = types.Distinct().ToArray();
+			foreach (IType type in arr) {
+				if (type == null)
+					throw new ArgumentNullException();
+			}
+			if (arr.Length == 0)
+				return SpecialType.UnknownType;
+			else if (arr.Length == 1)
+				return arr[0];
+			else
+				return new IntersectionType(arr);
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.Intersection; }
+		}
+		
+		public override string Name {
+			get {
+				StringBuilder b = new StringBuilder();
+				foreach (var t in types) {
+					if (b.Length > 0)
+						b.Append(" & ");
+					b.Append(t.Name);
+				}
+				return b.ToString();
+			}
+		}
+		
+		public override string ReflectionName {
+			get {
+				StringBuilder b = new StringBuilder();
+				foreach (var t in types) {
+					if (b.Length > 0)
+						b.Append(" & ");
+					b.Append(t.ReflectionName);
+				}
+				return b.ToString();
+			}
+		}
+		
+		public override bool? IsReferenceType {
+			get {
+				foreach (var t in types) {
+					bool? isReferenceType = t.IsReferenceType;
+					if (isReferenceType.HasValue)
+						return isReferenceType.Value;
+				}
+				return null;
+			}
+		}
+		
+		public override int GetHashCode()
+		{
+			int hashCode = 0;
+			unchecked {
+				foreach (var t in types) {
+					hashCode *= 7137517;
+					hashCode += t.GetHashCode();
+				}
+			}
+			return hashCode;
+		}
+		
+		public override bool Equals(IType other)
+		{
+			IntersectionType o = other as IntersectionType;
+			if (o != null && types.Count == o.types.Count) {
+				for (int i = 0; i < types.Count; i++) {
+					if (!types[i].Equals(o.types[i]))
+						return false;
+				}
+				return true;
+			}
+			return false;
+		}
+		
+		public override IEnumerable<IType> DirectBaseTypes {
+			get { return types; }
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			throw new NotSupportedException();
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetMethods(this, FilterNonStatic(filter), options);
+		}
+		
+		public override IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetMethods(this, typeArguments, filter, options);
+		}
+		
+		public override IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetProperties(this, FilterNonStatic(filter), options);
+		}
+		
+		public override IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetFields(this, FilterNonStatic(filter), options);
+		}
+		
+		public override IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetEvents(this, FilterNonStatic(filter), options);
+		}
+		
+		public override IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetMembers(this, FilterNonStatic(filter), options);
+		}
+		
+		public override IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter, GetMemberOptions options)
+		{
+			return GetMembersHelper.GetAccessors(this, FilterNonStatic(filter), options);
+		}
+		
+		static Predicate<T> FilterNonStatic<T>(Predicate<T> filter) where T : class, IUnresolvedMember
+		{
+			if (filter == null)
+				return member => !member.IsStatic;
+			else
+				return member => !member.IsStatic && filter(member);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/KnownTypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/KnownTypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/KnownTypeReference.cs	(revision 11807)
@@ -0,0 +1,500 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents some well-known types.
+	/// </summary>
+	public enum KnownTypeCode
+	{
+		// Note: DefaultResolvedTypeDefinition uses (KnownTypeCode)-1 as special value for "not yet calculated".
+		// The order of type codes at the beginning must correspond to those in System.TypeCode.
+		
+		/// <summary>
+		/// Not one of the known types.
+		/// </summary>
+		None,
+		/// <summary><c>object</c> (System.Object)</summary>
+		Object,
+		/// <summary><c>System.DBNull</c></summary>
+		DBNull,
+		/// <summary><c>bool</c> (System.Boolean)</summary>
+		Boolean,
+		/// <summary><c>char</c> (System.Char)</summary>
+		Char,
+		/// <summary><c>sbyte</c> (System.SByte)</summary>
+		SByte,
+		/// <summary><c>byte</c> (System.Byte)</summary>
+		Byte,
+		/// <summary><c>short</c> (System.Int16)</summary>
+		Int16,
+		/// <summary><c>ushort</c> (System.UInt16)</summary>
+		UInt16,
+		/// <summary><c>int</c> (System.Int32)</summary>
+		Int32,
+		/// <summary><c>uint</c> (System.UInt32)</summary>
+		UInt32,
+		/// <summary><c>long</c> (System.Int64)</summary>
+		Int64,
+		/// <summary><c>ulong</c> (System.UInt64)</summary>
+		UInt64,
+		/// <summary><c>float</c> (System.Single)</summary>
+		Single,
+		/// <summary><c>double</c> (System.Double)</summary>
+		Double,
+		/// <summary><c>decimal</c> (System.Decimal)</summary>
+		Decimal,
+		/// <summary><c>System.DateTime</c></summary>
+		DateTime,
+		/// <summary><c>string</c> (System.String)</summary>
+		String = 18,
+		
+		// String was the last element from System.TypeCode, now our additional known types start
+		
+		/// <summary><c>void</c> (System.Void)</summary>
+		Void,
+		/// <summary><c>System.Type</c></summary>
+		Type,
+		/// <summary><c>System.Array</c></summary>
+		Array,
+		/// <summary><c>System.Attribute</c></summary>
+		Attribute,
+		/// <summary><c>System.ValueType</c></summary>
+		ValueType,
+		/// <summary><c>System.Enum</c></summary>
+		Enum,
+		/// <summary><c>System.Delegate</c></summary>
+		Delegate,
+		/// <summary><c>System.MulticastDelegate</c></summary>
+		MulticastDelegate,
+		/// <summary><c>System.Exception</c></summary>
+		Exception,
+		/// <summary><c>System.IntPtr</c></summary>
+		IntPtr,
+		/// <summary><c>System.UIntPtr</c></summary>
+		UIntPtr,
+		/// <summary><c>System.Collections.IEnumerable</c></summary>
+		IEnumerable,
+		/// <summary><c>System.Collections.IEnumerator</c></summary>
+		IEnumerator,
+		/// <summary><c>System.Collections.Generic.IEnumerable{T}</c></summary>
+		IEnumerableOfT,
+		/// <summary><c>System.Collections.Generic.IEnumerator{T}</c></summary>
+		IEnumeratorOfT,
+		/// <summary><c>System.Collections.Generic.ICollection</c></summary>
+		ICollection,
+		/// <summary><c>System.Collections.Generic.ICollection{T}</c></summary>
+		ICollectionOfT,
+		/// <summary><c>System.Collections.Generic.IList</c></summary>
+		IList,
+		/// <summary><c>System.Collections.Generic.IList{T}</c></summary>
+		IListOfT,
+		/// <summary><c>System.Collections.Generic.IReadOnlyCollection{T}</c></summary>
+		IReadOnlyCollectionOfT,
+		/// <summary><c>System.Collections.Generic.IReadOnlyList{T}</c></summary>
+		IReadOnlyListOfT,
+		/// <summary><c>System.Threading.Tasks.Task</c></summary>
+		Task,
+		/// <summary><c>System.Threading.Tasks.Task{T}</c></summary>
+		TaskOfT,
+		/// <summary><c>System.Nullable{T}</c></summary>
+		NullableOfT,
+		/// <summary><c>System.IDisposable</c></summary>
+		IDisposable,
+		/// <summary><c>System.Runtime.CompilerServices.INotifyCompletion</c></summary>
+		INotifyCompletion,
+		/// <summary><c>System.Runtime.CompilerServices.ICriticalNotifyCompletion</c></summary>
+		ICriticalNotifyCompletion,
+	}
+	
+	/// <summary>
+	/// Contains well-known type references.
+	/// </summary>
+	[Serializable]
+	public sealed class KnownTypeReference : ITypeReference
+	{
+		internal const int KnownTypeCodeCount = (int)KnownTypeCode.ICriticalNotifyCompletion + 1;
+		
+		static readonly KnownTypeReference[] knownTypeReferences = new KnownTypeReference[KnownTypeCodeCount] {
+			null, // None
+			new KnownTypeReference(KnownTypeCode.Object,   "System", "Object", baseType: KnownTypeCode.None),
+			new KnownTypeReference(KnownTypeCode.DBNull,   "System", "DBNull"),
+			new KnownTypeReference(KnownTypeCode.Boolean,  "System", "Boolean",  baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Char,     "System", "Char",     baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.SByte,    "System", "SByte",    baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Byte,     "System", "Byte",     baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Int16,    "System", "Int16",    baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.UInt16,   "System", "UInt16",   baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Int32,    "System", "Int32",    baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.UInt32,   "System", "UInt32",   baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Int64,    "System", "Int64",    baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.UInt64,   "System", "UInt64",   baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Single,   "System", "Single",   baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Double,   "System", "Double",   baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Decimal,  "System", "Decimal",  baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.DateTime, "System", "DateTime", baseType: KnownTypeCode.ValueType),
+			null,
+			new KnownTypeReference(KnownTypeCode.String,    "System", "String"),
+			new KnownTypeReference(KnownTypeCode.Void,      "System", "Void"),
+			new KnownTypeReference(KnownTypeCode.Type,      "System", "Type"),
+			new KnownTypeReference(KnownTypeCode.Array,     "System", "Array"),
+			new KnownTypeReference(KnownTypeCode.Attribute, "System", "Attribute"),
+			new KnownTypeReference(KnownTypeCode.ValueType, "System", "ValueType"),
+			new KnownTypeReference(KnownTypeCode.Enum,      "System", "Enum", baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.Delegate,  "System", "Delegate"),
+			new KnownTypeReference(KnownTypeCode.MulticastDelegate, "System", "MulticastDelegate", baseType: KnownTypeCode.Delegate),
+			new KnownTypeReference(KnownTypeCode.Exception, "System", "Exception"),
+			new KnownTypeReference(KnownTypeCode.IntPtr,    "System", "IntPtr", baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.UIntPtr,   "System", "UIntPtr", baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.IEnumerable,    "System.Collections", "IEnumerable"),
+			new KnownTypeReference(KnownTypeCode.IEnumerator,    "System.Collections", "IEnumerator"),
+			new KnownTypeReference(KnownTypeCode.IEnumerableOfT, "System.Collections.Generic", "IEnumerable", 1),
+			new KnownTypeReference(KnownTypeCode.IEnumeratorOfT, "System.Collections.Generic", "IEnumerator", 1),
+			new KnownTypeReference(KnownTypeCode.ICollection,    "System.Collections", "ICollection"),
+			new KnownTypeReference(KnownTypeCode.ICollectionOfT, "System.Collections.Generic", "ICollection", 1),
+			new KnownTypeReference(KnownTypeCode.IList,          "System.Collections", "IList"),
+			new KnownTypeReference(KnownTypeCode.IListOfT,       "System.Collections.Generic", "IList", 1),
+
+			new KnownTypeReference(KnownTypeCode.IReadOnlyCollectionOfT, "System.Collections.Generic", "IReadOnlyCollection", 1),
+			new KnownTypeReference(KnownTypeCode.IReadOnlyListOfT, "System.Collections.Generic", "IReadOnlyList", 1),
+			new KnownTypeReference(KnownTypeCode.Task,        "System.Threading.Tasks", "Task"),
+			new KnownTypeReference(KnownTypeCode.TaskOfT,     "System.Threading.Tasks", "Task", 1, baseType: KnownTypeCode.Task),
+			new KnownTypeReference(KnownTypeCode.NullableOfT, "System", "Nullable", 1, baseType: KnownTypeCode.ValueType),
+			new KnownTypeReference(KnownTypeCode.IDisposable, "System", "IDisposable"),
+			new KnownTypeReference(KnownTypeCode.INotifyCompletion, "System.Runtime.CompilerServices", "INotifyCompletion"),
+			new KnownTypeReference(KnownTypeCode.ICriticalNotifyCompletion, "System.Runtime.CompilerServices", "ICriticalNotifyCompletion"),
+		};
+		
+		/// <summary>
+		/// Gets the known type reference for the specified type code.
+		/// Returns null for KnownTypeCode.None.
+		/// </summary>
+		public static KnownTypeReference Get(KnownTypeCode typeCode)
+		{
+			return knownTypeReferences[(int)typeCode];
+		}
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>object</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Object = Get(KnownTypeCode.Object);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.DBNull</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference DBNull = Get(KnownTypeCode.DBNull);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>bool</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Boolean = Get(KnownTypeCode.Boolean);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>char</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Char = Get(KnownTypeCode.Char);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>sbyte</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference SByte = Get(KnownTypeCode.SByte);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>byte</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Byte = Get(KnownTypeCode.Byte);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>short</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Int16 = Get(KnownTypeCode.Int16);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>ushort</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference UInt16 = Get(KnownTypeCode.UInt16);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>int</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Int32 = Get(KnownTypeCode.Int32);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>uint</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference UInt32 = Get(KnownTypeCode.UInt32);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>long</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Int64 = Get(KnownTypeCode.Int64);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>ulong</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference UInt64 = Get(KnownTypeCode.UInt64);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>float</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Single = Get(KnownTypeCode.Single);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>double</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Double = Get(KnownTypeCode.Double);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>decimal</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Decimal = Get(KnownTypeCode.Decimal);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.DateTime</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference DateTime = Get(KnownTypeCode.DateTime);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>string</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference String = Get(KnownTypeCode.String);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>void</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Void = Get(KnownTypeCode.Void);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Type</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Type = Get(KnownTypeCode.Type);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Array</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Array = Get(KnownTypeCode.Array);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Attribute</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Attribute = Get(KnownTypeCode.Attribute);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.ValueType</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference ValueType = Get(KnownTypeCode.ValueType);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Enum</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Enum = Get(KnownTypeCode.Enum);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Delegate</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Delegate = Get(KnownTypeCode.Delegate);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.MulticastDelegate</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference MulticastDelegate = Get(KnownTypeCode.MulticastDelegate);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Exception</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Exception = Get(KnownTypeCode.Exception);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.IntPtr</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IntPtr = Get(KnownTypeCode.IntPtr);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.UIntPtr</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference UIntPtr = Get(KnownTypeCode.UIntPtr);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.IEnumerable</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IEnumerable = Get(KnownTypeCode.IEnumerable);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.IEnumerator</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IEnumerator = Get(KnownTypeCode.IEnumerator);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.Generic.IEnumerable{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IEnumerableOfT = Get(KnownTypeCode.IEnumerableOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.Generic.IEnumerator{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IEnumeratorOfT = Get(KnownTypeCode.IEnumeratorOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.ICollection</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference ICollection = Get(KnownTypeCode.ICollection);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.Generic.ICollection{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference ICollectionOfT = Get(KnownTypeCode.ICollectionOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.IList</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IList = Get(KnownTypeCode.IList);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.Generic.IList{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IListOfT = Get(KnownTypeCode.IListOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.Generic.IReadOnlyCollection{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IReadOnlyCollectionOfT = Get(KnownTypeCode.IReadOnlyCollectionOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Collections.Generic.IReadOnlyList{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IReadOnlyListOfT = Get(KnownTypeCode.IReadOnlyListOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Threading.Tasks.Task</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference Task = Get(KnownTypeCode.Task);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Threading.Tasks.Task{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference TaskOfT = Get(KnownTypeCode.TaskOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Nullable{T}</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference NullableOfT = Get(KnownTypeCode.NullableOfT);
+		
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.IDisposable</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference IDisposable = Get(KnownTypeCode.IDisposable);
+
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Runtime.CompilerServices.INotifyCompletion</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference INotifyCompletion = Get(KnownTypeCode.INotifyCompletion);
+
+		/// <summary>
+		/// Gets a type reference pointing to the <c>System.Runtime.CompilerServices.ICriticalNotifyCompletion</c> type.
+		/// </summary>
+		public static readonly KnownTypeReference ICriticalNotifyCompletion = Get(KnownTypeCode.ICriticalNotifyCompletion);
+
+		readonly KnownTypeCode knownTypeCode;
+		readonly string namespaceName;
+		readonly string name;
+		readonly int typeParameterCount;
+		internal readonly KnownTypeCode baseType;
+		
+		private KnownTypeReference(KnownTypeCode knownTypeCode, string namespaceName, string name, int typeParameterCount = 0, KnownTypeCode baseType = KnownTypeCode.Object)
+		{
+			this.knownTypeCode = knownTypeCode;
+			this.namespaceName = namespaceName;
+			this.name = name;
+			this.typeParameterCount = typeParameterCount;
+			this.baseType = baseType;
+		}
+		
+		public KnownTypeCode KnownTypeCode {
+			get { return knownTypeCode; }
+		}
+		
+		public string Namespace {
+			get { return namespaceName; }
+		}
+		
+		public string Name {
+			get { return name; }
+		}
+		
+		public int TypeParameterCount {
+			get { return typeParameterCount; }
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			return context.Compilation.FindType(knownTypeCode);
+		}
+		
+		public override string ToString()
+		{
+			return GetCSharpNameByTypeCode(knownTypeCode) ?? (this.Namespace + "." + this.Name);
+		}
+		
+		/// <summary>
+		/// Gets the C# primitive type name from the known type code.
+		/// Returns null if there is no primitive name for the specified type.
+		/// </summary>
+		public static string GetCSharpNameByTypeCode(KnownTypeCode knownTypeCode)
+		{
+			switch (knownTypeCode) {
+				case KnownTypeCode.Object:
+					return "object";
+				case KnownTypeCode.Boolean:
+					return "bool";
+				case KnownTypeCode.Char:
+					return "char";
+				case KnownTypeCode.SByte:
+					return "sbyte";
+				case KnownTypeCode.Byte:
+					return "byte";
+				case KnownTypeCode.Int16:
+					return "short";
+				case KnownTypeCode.UInt16:
+					return "ushort";
+				case KnownTypeCode.Int32:
+					return "int";
+				case KnownTypeCode.UInt32:
+					return "uint";
+				case KnownTypeCode.Int64:
+					return "long";
+				case KnownTypeCode.UInt64:
+					return "ulong";
+				case KnownTypeCode.Single:
+					return "float";
+				case KnownTypeCode.Double:
+					return "double";
+				case KnownTypeCode.Decimal:
+					return "decimal";
+				case KnownTypeCode.String:
+					return "string";
+				case KnownTypeCode.Void:
+					return "void";
+				default:
+					return null;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/NullableType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/NullableType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/NullableType.cs	(revision 11807)
@@ -0,0 +1,87 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Static helper methods for working with nullable types.
+	/// </summary>
+	public static class NullableType
+	{
+		/// <summary>
+		/// Gets whether the specified type is a nullable type.
+		/// </summary>
+		public static bool IsNullable(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			ParameterizedType pt = type as ParameterizedType;
+			return pt != null && pt.TypeParameterCount == 1 && pt.GetDefinition().KnownTypeCode == KnownTypeCode.NullableOfT;
+		}
+		
+		public static bool IsNonNullableValueType(IType type)
+		{
+			return type.IsReferenceType == false && !IsNullable(type);
+		}
+		
+		/// <summary>
+		/// Returns the element type, if <paramref name="type"/> is a nullable type.
+		/// Otherwise, returns the type itself.
+		/// </summary>
+		public static IType GetUnderlyingType(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			ParameterizedType pt = type as ParameterizedType;
+			if (pt != null && pt.TypeParameterCount == 1 && pt.FullName == "System.Nullable")
+				return pt.GetTypeArgument(0);
+			else
+				return type;
+		}
+		
+		/// <summary>
+		/// Creates a nullable type.
+		/// </summary>
+		public static IType Create(ICompilation compilation, IType elementType)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			
+			IType nullableType = compilation.FindType(KnownTypeCode.NullableOfT);
+			ITypeDefinition nullableTypeDef = nullableType.GetDefinition();
+			if (nullableTypeDef != null)
+				return new ParameterizedType(nullableTypeDef, new [] { elementType });
+			else
+				return nullableType;
+		}
+		
+		/// <summary>
+		/// Creates a nullable type reference.
+		/// </summary>
+		public static ParameterizedTypeReference Create(ITypeReference elementType)
+		{
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			return new ParameterizedTypeReference(KnownTypeReference.NullableOfT, new [] { elementType });
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ParameterListComparer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ParameterListComparer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ParameterListComparer.cs	(revision 11807)
@@ -0,0 +1,168 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Compares parameter lists by comparing the types of all parameters.
+	/// </summary>
+	/// <remarks>
+	/// 'ref int' and 'out int' are considered to be equal.
+	/// 'object' and 'dynamic' are also equal.
+	/// For generic methods, "Method{T}(T a)" and "Method{S}(S b)" are considered equal.
+	/// However, "Method(T a)" and "Method(S b)" are not considered equal when the type parameters T and S belong to classes.
+	/// </remarks>
+	public sealed class ParameterListComparer : IEqualityComparer<IList<IParameter>>
+	{
+		public static readonly ParameterListComparer Instance = new ParameterListComparer();
+		
+		sealed class NormalizeTypeVisitor : TypeVisitor
+		{
+			public override IType VisitTypeParameter(ITypeParameter type)
+			{
+				if (type.OwnerType == SymbolKind.Method) {
+					return DummyTypeParameter.GetMethodTypeParameter(type.Index);
+				} else {
+					return base.VisitTypeParameter(type);
+				}
+			}
+			
+			public override IType VisitTypeDefinition(ITypeDefinition type)
+			{
+				if (type.KnownTypeCode == KnownTypeCode.Object)
+					return SpecialType.Dynamic;
+				return base.VisitTypeDefinition(type);
+			}
+		}
+		
+		static readonly NormalizeTypeVisitor normalizationVisitor = new NormalizeTypeVisitor();
+		
+		/// <summary>
+		/// Replaces all occurrences of method type parameters in the given type
+		/// by normalized type parameters. This allows comparing parameter types from different
+		/// generic methods.
+		/// </summary>
+		[Obsolete("Use DummyTypeParameter.NormalizeMethodTypeParameters instead if you only need to normalize type parameters. Also, consider if you need to normalize object vs. dynamic as well.")]
+		public IType NormalizeMethodTypeParameters(IType type)
+		{
+			return DummyTypeParameter.NormalizeMethodTypeParameters(type);
+		}
+		
+		public bool Equals(IList<IParameter> x, IList<IParameter> y)
+		{
+			if (x == y)
+				return true;
+			if (x == null || y == null || x.Count != y.Count)
+				return false;
+			for (int i = 0; i < x.Count; i++) {
+				var a = x[i];
+				var b = y[i];
+				if (a == null && b == null)
+					continue;
+				if (a == null || b == null)
+					return false;
+				
+				// We want to consider the parameter lists "Method<T>(T a)" and "Method<S>(S b)" as equal.
+				// However, the parameter types are not considered equal, as T is a different type parameter than S.
+				// In order to compare the method signatures, we will normalize all method type parameters.
+				IType aType = a.Type.AcceptVisitor(normalizationVisitor);
+				IType bType = b.Type.AcceptVisitor(normalizationVisitor);
+				
+				if (!aType.Equals(bType))
+					return false;
+			}
+			return true;
+		}
+		
+		public int GetHashCode(IList<IParameter> obj)
+		{
+			int hashCode = obj.Count;
+			unchecked {
+				foreach (IParameter p in obj) {
+					hashCode *= 27;
+					IType type = p.Type.AcceptVisitor(normalizationVisitor);
+					hashCode += type.GetHashCode();
+				}
+			}
+			return hashCode;
+		}
+	}
+	
+	/// <summary>
+	/// Compares member signatures.
+	/// </summary>
+	/// <remarks>
+	/// This comparer checks for equal short name, equal type parameter count, and equal parameter types (using ParameterListComparer).
+	/// </remarks>
+	public sealed class SignatureComparer : IEqualityComparer<IMember>
+	{
+		StringComparer nameComparer;
+		
+		public SignatureComparer(StringComparer nameComparer)
+		{
+			if (nameComparer == null)
+				throw new ArgumentNullException("nameComparer");
+			this.nameComparer = nameComparer;
+		}
+		
+		/// <summary>
+		/// Gets a signature comparer that uses an ordinal comparison for the member name.
+		/// </summary>
+		public static readonly SignatureComparer Ordinal = new SignatureComparer(StringComparer.Ordinal);
+		
+		public bool Equals(IMember x, IMember y)
+		{
+			if (x == y)
+				return true;
+			if (x == null || y == null || x.SymbolKind != y.SymbolKind || !nameComparer.Equals(x.Name, y.Name))
+				return false;
+			IParameterizedMember px = x as IParameterizedMember;
+			IParameterizedMember py = y as IParameterizedMember;
+			if (px != null && py != null) {
+				IMethod mx = x as IMethod;
+				IMethod my = y as IMethod;
+				if (mx != null && my != null && mx.TypeParameters.Count != my.TypeParameters.Count)
+					return false;
+				return ParameterListComparer.Instance.Equals(px.Parameters, py.Parameters);
+			} else {
+				return true;
+			}
+		}
+		
+		public int GetHashCode(IMember obj)
+		{
+			unchecked {
+				int hash = (int)obj.SymbolKind * 33 + nameComparer.GetHashCode(obj.Name);
+				IParameterizedMember pm = obj as IParameterizedMember;
+				if (pm != null) {
+					hash *= 27;
+					hash += ParameterListComparer.Instance.GetHashCode(pm.Parameters);
+					IMethod m = pm as IMethod;
+					if (m != null)
+						hash += m.TypeParameters.Count;
+				}
+				return hash;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ParameterizedType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ParameterizedType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ParameterizedType.cs	(revision 11807)
@@ -0,0 +1,436 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// ParameterizedType represents an instance of a generic type.
+	/// Example: List&lt;string&gt;
+	/// </summary>
+	/// <remarks>
+	/// When getting the members, this type modifies the lists so that
+	/// type parameters in the signatures of the members are replaced with
+	/// the type arguments.
+	/// </remarks>
+	[Serializable]
+	public sealed class ParameterizedType : IType, ICompilationProvider
+	{
+		readonly ITypeDefinition genericType;
+		readonly IType[] typeArguments;
+		
+		public ParameterizedType(ITypeDefinition genericType, IEnumerable<IType> typeArguments)
+		{
+			if (genericType == null)
+				throw new ArgumentNullException("genericType");
+			if (typeArguments == null)
+				throw new ArgumentNullException("typeArguments");
+			this.genericType = genericType;
+			this.typeArguments = typeArguments.ToArray(); // copy input array to ensure it isn't modified
+			if (this.typeArguments.Length == 0)
+				throw new ArgumentException("Cannot use ParameterizedType with 0 type arguments.");
+			if (genericType.TypeParameterCount != this.typeArguments.Length)
+				throw new ArgumentException("Number of type arguments must match the type definition's number of type parameters");
+			for (int i = 0; i < this.typeArguments.Length; i++) {
+				if (this.typeArguments[i] == null)
+					throw new ArgumentNullException("typeArguments[" + i + "]");
+				ICompilationProvider p = this.typeArguments[i] as ICompilationProvider;
+				if (p != null && p.Compilation != genericType.Compilation)
+					throw new InvalidOperationException("Cannot parameterize a type with type arguments from a different compilation.");
+			}
+		}
+		
+		/// <summary>
+		/// Fast internal version of the constructor. (no safety checks)
+		/// Keeps the array that was passed and assumes it won't be modified.
+		/// </summary>
+		internal ParameterizedType(ITypeDefinition genericType, IType[] typeArguments)
+		{
+			Debug.Assert(genericType.TypeParameterCount == typeArguments.Length);
+			this.genericType = genericType;
+			this.typeArguments = typeArguments;
+		}
+		
+		public TypeKind Kind {
+			get { return genericType.Kind; }
+		}
+		
+		public ICompilation Compilation {
+			get { return genericType.Compilation; }
+		}
+		
+		public bool? IsReferenceType {
+			get { return genericType.IsReferenceType; }
+		}
+		
+		public IType DeclaringType {
+			get {
+				ITypeDefinition declaringTypeDef = genericType.DeclaringTypeDefinition;
+				if (declaringTypeDef != null && declaringTypeDef.TypeParameterCount > 0
+				    && declaringTypeDef.TypeParameterCount <= genericType.TypeParameterCount)
+				{
+					IType[] newTypeArgs = new IType[declaringTypeDef.TypeParameterCount];
+					Array.Copy(this.typeArguments, 0, newTypeArgs, 0, newTypeArgs.Length);
+					return new ParameterizedType(declaringTypeDef, newTypeArgs);
+				}
+				return declaringTypeDef;
+			}
+		}
+		
+		public int TypeParameterCount {
+			get { return typeArguments.Length; }
+		}
+		
+		public string FullName {
+			get { return genericType.FullName; }
+		}
+		
+		public string Name {
+			get { return genericType.Name; }
+		}
+		
+		public string Namespace {
+			get { return genericType.Namespace; }
+		}
+		
+		public string ReflectionName {
+			get {
+				StringBuilder b = new StringBuilder(genericType.ReflectionName);
+				b.Append('[');
+				for (int i = 0; i < typeArguments.Length; i++) {
+					if (i > 0)
+						b.Append(',');
+					b.Append('[');
+					b.Append(typeArguments[i].ReflectionName);
+					b.Append(']');
+				}
+				b.Append(']');
+				return b.ToString();
+			}
+		}
+		
+		public override string ToString()
+		{
+			return ReflectionName;
+		}
+		
+		public IList<IType> TypeArguments {
+			get {
+				return typeArguments;
+			}
+		}
+
+		public bool IsParameterized { 
+			get {
+				return true;
+			}
+		}
+
+		/// <summary>
+		/// Same as 'parameterizedType.TypeArguments[index]', but is a bit more efficient (doesn't require the read-only wrapper).
+		/// </summary>
+		public IType GetTypeArgument(int index)
+		{
+			return typeArguments[index];
+		}
+		
+		/// <summary>
+		/// Gets the definition of the generic type.
+		/// For <c>ParameterizedType</c>, this method never returns null.
+		/// </summary>
+		public ITypeDefinition GetDefinition()
+		{
+			return genericType;
+		}
+		
+		public ITypeReference ToTypeReference()
+		{
+			return new ParameterizedTypeReference(genericType.ToTypeReference(), typeArguments.Select(t => t.ToTypeReference()));
+		}
+		
+		/// <summary>
+		/// Gets a type visitor that performs the substitution of class type parameters with the type arguments
+		/// of this parameterized type.
+		/// </summary>
+		public TypeParameterSubstitution GetSubstitution()
+		{
+			return new TypeParameterSubstitution(typeArguments, null);
+		}
+		
+		/// <summary>
+		/// Gets a type visitor that performs the substitution of class type parameters with the type arguments
+		/// of this parameterized type,
+		/// and also substitutes method type parameters with the specified method type arguments.
+		/// </summary>
+		public TypeParameterSubstitution GetSubstitution(IList<IType> methodTypeArguments)
+		{
+			return new TypeParameterSubstitution(typeArguments, methodTypeArguments);
+		}
+		
+		public IEnumerable<IType> DirectBaseTypes {
+			get {
+				var substitution = GetSubstitution();
+				return genericType.DirectBaseTypes.Select(t => t.AcceptVisitor(substitution));
+			}
+		}
+		
+		public IEnumerable<IType> GetNestedTypes(Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetNestedTypes(filter, options);
+			else
+				return GetMembersHelper.GetNestedTypes(this, filter, options);
+		}
+		
+		public IEnumerable<IType> GetNestedTypes(IList<IType> typeArguments, Predicate<ITypeDefinition> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetNestedTypes(typeArguments, filter, options);
+			else
+				return GetMembersHelper.GetNestedTypes(this, typeArguments, filter, options);
+		}
+		
+		public IEnumerable<IMethod> GetConstructors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.IgnoreInheritedMembers)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetConstructors(filter, options);
+			else
+				return GetMembersHelper.GetConstructors(this, filter, options);
+		}
+		
+		public IEnumerable<IMethod> GetMethods(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetMethods(filter, options);
+			else
+				return GetMembersHelper.GetMethods(this, filter, options);
+		}
+		
+		public IEnumerable<IMethod> GetMethods(IList<IType> typeArguments, Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetMethods(typeArguments, filter, options);
+			else
+				return GetMembersHelper.GetMethods(this, typeArguments, filter, options);
+		}
+		
+		public IEnumerable<IProperty> GetProperties(Predicate<IUnresolvedProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetProperties(filter, options);
+			else
+				return GetMembersHelper.GetProperties(this, filter, options);
+		}
+		
+		public IEnumerable<IField> GetFields(Predicate<IUnresolvedField> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetFields(filter, options);
+			else
+				return GetMembersHelper.GetFields(this, filter, options);
+		}
+		
+		public IEnumerable<IEvent> GetEvents(Predicate<IUnresolvedEvent> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetEvents(filter, options);
+			else
+				return GetMembersHelper.GetEvents(this, filter, options);
+		}
+		
+		public IEnumerable<IMember> GetMembers(Predicate<IUnresolvedMember> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetMembers(filter, options);
+			else
+				return GetMembersHelper.GetMembers(this, filter, options);
+		}
+		
+		public IEnumerable<IMethod> GetAccessors(Predicate<IUnresolvedMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
+		{
+			if ((options & GetMemberOptions.ReturnMemberDefinitions) == GetMemberOptions.ReturnMemberDefinitions)
+				return genericType.GetAccessors(filter, options);
+			else
+				return GetMembersHelper.GetAccessors(this, filter, options);
+		}
+		
+		public override bool Equals(object obj)
+		{
+			return Equals(obj as IType);
+		}
+		
+		public bool Equals(IType other)
+		{
+			ParameterizedType c = other as ParameterizedType;
+			if (c == null || !genericType.Equals(c.genericType) || typeArguments.Length != c.typeArguments.Length)
+				return false;
+			for (int i = 0; i < typeArguments.Length; i++) {
+				if (!typeArguments[i].Equals(c.typeArguments[i]))
+					return false;
+			}
+			return true;
+		}
+		
+		public override int GetHashCode()
+		{
+			int hashCode = genericType.GetHashCode();
+			unchecked {
+				foreach (var ta in typeArguments) {
+					hashCode *= 1000000007;
+					hashCode += 1000000009 * ta.GetHashCode();
+				}
+			}
+			return hashCode;
+		}
+		
+		public IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitParameterizedType(this);
+		}
+		
+		public IType VisitChildren(TypeVisitor visitor)
+		{
+			IType g = genericType.AcceptVisitor(visitor);
+			ITypeDefinition def = g as ITypeDefinition;
+			if (def == null)
+				return g;
+			// Keep ta == null as long as no elements changed, allocate the array only if necessary.
+			IType[] ta = (g != genericType) ? new IType[typeArguments.Length] : null;
+			for (int i = 0; i < typeArguments.Length; i++) {
+				IType r = typeArguments[i].AcceptVisitor(visitor);
+				if (r == null)
+					throw new NullReferenceException("TypeVisitor.Visit-method returned null");
+				if (ta == null && r != typeArguments[i]) {
+					// we found a difference, so we need to allocate the array
+					ta = new IType[typeArguments.Length];
+					for (int j = 0; j < i; j++) {
+						ta[j] = typeArguments[j];
+					}
+				}
+				if (ta != null)
+					ta[i] = r;
+			}
+			if (def == genericType && ta == null)
+				return this;
+			else
+				return new ParameterizedType(def, ta ?? typeArguments);
+		}
+	}
+	
+	/// <summary>
+	/// ParameterizedTypeReference is a reference to generic class that specifies the type parameters.
+	/// Example: List&lt;string&gt;
+	/// </summary>
+	[Serializable]
+	public sealed class ParameterizedTypeReference : ITypeReference, ISupportsInterning
+	{
+		readonly ITypeReference genericType;
+		readonly ITypeReference[] typeArguments;
+		
+		public ParameterizedTypeReference(ITypeReference genericType, IEnumerable<ITypeReference> typeArguments)
+		{
+			if (genericType == null)
+				throw new ArgumentNullException("genericType");
+			if (typeArguments == null)
+				throw new ArgumentNullException("typeArguments");
+			this.genericType = genericType;
+			this.typeArguments = typeArguments.ToArray();
+			for (int i = 0; i < this.typeArguments.Length; i++) {
+				if (this.typeArguments[i] == null)
+					throw new ArgumentNullException("typeArguments[" + i + "]");
+			}
+		}
+		
+		public ITypeReference GenericType {
+			get { return genericType; }
+		}
+		
+		public ReadOnlyCollection<ITypeReference> TypeArguments {
+			get {
+				return Array.AsReadOnly(typeArguments);
+			}
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			IType baseType = genericType.Resolve(context);
+			ITypeDefinition baseTypeDef = baseType.GetDefinition();
+			if (baseTypeDef == null)
+				return baseType;
+			int tpc = baseTypeDef.TypeParameterCount;
+			if (tpc == 0)
+				return baseTypeDef;
+			IType[] resolvedTypes = new IType[tpc];
+			for (int i = 0; i < resolvedTypes.Length; i++) {
+				if (i < typeArguments.Length)
+					resolvedTypes[i] = typeArguments[i].Resolve(context);
+				else
+					resolvedTypes[i] = SpecialType.UnknownType;
+			}
+			return new ParameterizedType(baseTypeDef, resolvedTypes);
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder(genericType.ToString());
+			b.Append('[');
+			for (int i = 0; i < typeArguments.Length; i++) {
+				if (i > 0)
+					b.Append(',');
+				b.Append('[');
+				b.Append(typeArguments[i].ToString());
+				b.Append(']');
+			}
+			b.Append(']');
+			return b.ToString();
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			int hashCode = genericType.GetHashCode();
+			unchecked {
+				foreach (ITypeReference t in typeArguments) {
+					hashCode *= 27;
+					hashCode += t.GetHashCode();
+				}
+			}
+			return hashCode;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			ParameterizedTypeReference o = other as ParameterizedTypeReference;
+			if (o != null && genericType == o.genericType && typeArguments.Length == o.typeArguments.Length) {
+				for (int i = 0; i < typeArguments.Length; i++) {
+					if (typeArguments[i] != o.typeArguments[i])
+						return false;
+				}
+				return true;
+			}
+			return false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/PointerType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/PointerType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/PointerType.cs	(revision 11807)
@@ -0,0 +1,113 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	public sealed class PointerType : TypeWithElementType
+	{
+		public PointerType(IType elementType) : base(elementType)
+		{
+		}
+		
+		public override TypeKind Kind {
+			get { return TypeKind.Pointer; }
+		}
+		
+		public override string NameSuffix {
+			get {
+				return "*";
+			}
+		}
+		
+		public override bool? IsReferenceType {
+			get { return null; }
+		}
+		
+		public override int GetHashCode()
+		{
+			return elementType.GetHashCode() ^ 91725811;
+		}
+		
+		public override bool Equals(IType other)
+		{
+			PointerType a = other as PointerType;
+			return a != null && elementType.Equals(a.elementType);
+		}
+		
+		public override IType AcceptVisitor(TypeVisitor visitor)
+		{
+			return visitor.VisitPointerType(this);
+		}
+		
+		public override IType VisitChildren(TypeVisitor visitor)
+		{
+			IType e = elementType.AcceptVisitor(visitor);
+			if (e == elementType)
+				return this;
+			else
+				return new PointerType(e);
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return new PointerTypeReference(elementType.ToTypeReference());
+		}
+	}
+	
+	[Serializable]
+	public sealed class PointerTypeReference : ITypeReference, ISupportsInterning
+	{
+		readonly ITypeReference elementType;
+		
+		public PointerTypeReference(ITypeReference elementType)
+		{
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			this.elementType = elementType;
+		}
+		
+		public ITypeReference ElementType {
+			get { return elementType; }
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			return new PointerType(elementType.Resolve(context));
+		}
+		
+		public override string ToString()
+		{
+			return elementType.ToString() + "*";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return elementType.GetHashCode() ^ 91725812;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			PointerTypeReference o = other as PointerTypeReference;
+			return o != null && this.elementType == o.elementType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ProjectReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ProjectReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ProjectReference.cs	(revision 11807)
@@ -0,0 +1,56 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// References another project content in the same solution.
+	/// Using the <see cref="ProjectReference"/> class requires that you 
+	/// </summary>
+	[Serializable]
+	public class ProjectReference : IAssemblyReference
+	{
+		readonly string projectFileName;
+		
+		/// <summary>
+		/// Creates a new reference to the specified project (must be part of the same solution).
+		/// </summary>
+		/// <param name="projectFileName">Full path to the file name. Must be identical to <see cref="IProjectContent.ProjectFileName"/> of the target project; do not use a relative path.</param>
+		public ProjectReference(string projectFileName)
+		{
+			this.projectFileName = projectFileName;
+		}
+		
+		public IAssembly Resolve(ITypeResolveContext context)
+		{
+			var solution = context.Compilation.SolutionSnapshot;
+			var pc = solution.GetProjectContent(projectFileName);
+			if (pc != null)
+				return pc.Resolve(context);
+			else
+				return null;
+		}
+		
+		public override string ToString()
+		{
+			return string.Format("[ProjectReference {0}]", projectFileName);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ReflectionHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ReflectionHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ReflectionHelper.cs	(revision 11807)
@@ -0,0 +1,424 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Static helper methods for reflection names.
+	/// </summary>
+	public static class ReflectionHelper
+	{
+		/// <summary>
+		/// A reflection class used to represent <c>null</c>.
+		/// </summary>
+		public sealed class Null {}
+		
+		/// <summary>
+		/// A reflection class used to represent <c>dynamic</c>.
+		/// </summary>
+		public sealed class Dynamic {}
+		
+		/// <summary>
+		/// A reflection class used to represent an unbound type argument.
+		/// </summary>
+		public sealed class UnboundTypeArgument {}
+		
+		#region ICompilation.FindType
+		/// <summary>
+		/// Retrieves the specified type in this compilation.
+		/// Returns <see cref="SpecialType.UnknownType"/> if the type cannot be found in this compilation.
+		/// </summary>
+		/// <remarks>
+		/// This method cannot be used with open types; all type parameters will be substituted
+		/// with <see cref="SpecialType.UnknownType"/>.
+		/// </remarks>
+		public static IType FindType(this ICompilation compilation, Type type)
+		{
+			return type.ToTypeReference().Resolve(compilation.TypeResolveContext);
+		}
+		#endregion
+		
+		#region Type.ToTypeReference()
+		/// <summary>
+		/// Creates a reference to the specified type.
+		/// </summary>
+		/// <param name="type">The type to be converted.</param>
+		/// <returns>Returns the type reference.</returns>
+		/// <remarks>
+		/// If the type is open (contains type parameters '`0' or '``0'),
+		/// an <see cref="ITypeResolveContext"/> with the appropriate CurrentTypeDefinition/CurrentMember is required
+		/// to resolve the type reference.
+		/// For closed types, the root type resolve context for the compilation is sufficient.
+		/// </remarks>
+		public static ITypeReference ToTypeReference(this Type type)
+		{
+			if (type == null)
+				return SpecialType.UnknownType;
+			if (type.IsGenericType && !type.IsGenericTypeDefinition) {
+				ITypeReference def = ToTypeReference(type.GetGenericTypeDefinition());
+				Type[] arguments = type.GetGenericArguments();
+				ITypeReference[] args = new ITypeReference[arguments.Length];
+				bool allUnbound = true;
+				for (int i = 0; i < arguments.Length; i++) {
+					args[i] = ToTypeReference(arguments[i]);
+					allUnbound &= args[i].Equals(SpecialType.UnboundTypeArgument);
+				}
+				if (allUnbound)
+					return def;
+				else
+					return new ParameterizedTypeReference(def, args);
+			} else if (type.IsArray) {
+				return new ArrayTypeReference(ToTypeReference(type.GetElementType()), type.GetArrayRank());
+			} else if (type.IsPointer) {
+				return new PointerTypeReference(ToTypeReference(type.GetElementType()));
+			} else if (type.IsByRef) {
+				return new ByReferenceTypeReference(ToTypeReference(type.GetElementType()));
+			} else if (type.IsGenericParameter) {
+				if (type.DeclaringMethod != null) {
+					return TypeParameterReference.Create(SymbolKind.Method, type.GenericParameterPosition);
+				} else {
+					return TypeParameterReference.Create(SymbolKind.TypeDefinition, type.GenericParameterPosition);
+				}
+			} else if (type.DeclaringType != null) {
+				if (type == typeof(Dynamic))
+					return SpecialType.Dynamic;
+				else if (type == typeof(Null))
+					return SpecialType.NullType;
+				else if (type == typeof(UnboundTypeArgument))
+					return SpecialType.UnboundTypeArgument;
+				ITypeReference baseTypeRef = ToTypeReference(type.DeclaringType);
+				int typeParameterCount;
+				string name = SplitTypeParameterCountFromReflectionName(type.Name, out typeParameterCount);
+				return new NestedTypeReference(baseTypeRef, name, typeParameterCount);
+			} else {
+				IAssemblyReference assemblyReference = new DefaultAssemblyReference(type.Assembly.FullName);
+				int typeParameterCount;
+				string name = SplitTypeParameterCountFromReflectionName(type.Name, out typeParameterCount);
+				return new GetClassTypeReference(assemblyReference, type.Namespace, name, typeParameterCount);
+			}
+		}
+		#endregion
+		
+		#region SplitTypeParameterCountFromReflectionName
+		/// <summary>
+		/// Removes the ` with type parameter count from the reflection name.
+		/// </summary>
+		/// <remarks>Do not use this method with the full name of inner classes.</remarks>
+		public static string SplitTypeParameterCountFromReflectionName(string reflectionName)
+		{
+			int pos = reflectionName.LastIndexOf('`');
+			if (pos < 0) {
+				return reflectionName;
+			} else {
+				return reflectionName.Substring(0, pos);
+			}
+		}
+		
+		/// <summary>
+		/// Removes the ` with type parameter count from the reflection name.
+		/// </summary>
+		/// <remarks>Do not use this method with the full name of inner classes.</remarks>
+		public static string SplitTypeParameterCountFromReflectionName(string reflectionName, out int typeParameterCount)
+		{
+			int pos = reflectionName.LastIndexOf('`');
+			if (pos < 0) {
+				typeParameterCount = 0;
+				return reflectionName;
+			} else {
+				string typeCount = reflectionName.Substring(pos + 1);
+				if (int.TryParse(typeCount, out typeParameterCount))
+					return reflectionName.Substring(0, pos);
+				else
+					return reflectionName;
+			}
+		}
+		#endregion
+		
+		#region TypeCode support
+		/// <summary>
+		/// Retrieves a built-in type using the specified type code.
+		/// </summary>
+		public static IType FindType(this ICompilation compilation, TypeCode typeCode)
+		{
+			return compilation.FindType((KnownTypeCode)typeCode);
+		}
+		
+		/// <summary>
+		/// Creates a reference to the specified type.
+		/// </summary>
+		/// <param name="typeCode">The type to be converted.</param>
+		/// <returns>Returns the type reference.</returns>
+		public static ITypeReference ToTypeReference(this TypeCode typeCode)
+		{
+			return KnownTypeReference.Get((KnownTypeCode)typeCode);
+		}
+		
+		/// <summary>
+		/// Gets the type code for the specified type, or TypeCode.Empty if none of the other type codes match.
+		/// </summary>
+		public static TypeCode GetTypeCode(IType type)
+		{
+			ITypeDefinition def = type as ITypeDefinition;
+			if (def != null) {
+				KnownTypeCode typeCode = def.KnownTypeCode;
+				if (typeCode <= KnownTypeCode.String && typeCode != KnownTypeCode.Void)
+					return (TypeCode)typeCode;
+				else
+					return TypeCode.Empty;
+			}
+			return TypeCode.Empty;
+		}
+		#endregion
+		
+		#region ParseReflectionName
+		/// <summary>
+		/// Parses a reflection name into a type reference.
+		/// </summary>
+		/// <param name="reflectionTypeName">The reflection name of the type.</param>
+		/// <returns>A type reference that represents the reflection name.</returns>
+		/// <exception cref="ReflectionNameParseException">The syntax of the reflection type name is invalid</exception>
+		/// <remarks>
+		/// If the type is open (contains type parameters '`0' or '``0'),
+		/// an <see cref="ITypeResolveContext"/> with the appropriate CurrentTypeDefinition/CurrentMember is required
+		/// to resolve the reference to the ITypeParameter.
+		/// For looking up closed, assembly qualified type names, the root type resolve context for the compilation
+		/// is sufficient.
+		/// When looking up a type name that isn't assembly qualified, the type reference will look in
+		/// <see cref="ITypeResolveContext.CurrentAssembly"/> first, and if the type is not found there,
+		/// it will look in all other assemblies of the compilation.
+		/// </remarks>
+		/// <seealso cref="FullTypeName(string)"/>
+		public static ITypeReference ParseReflectionName(string reflectionTypeName)
+		{
+			if (reflectionTypeName == null)
+				throw new ArgumentNullException("reflectionTypeName");
+			int pos = 0;
+			ITypeReference r = ParseReflectionName(reflectionTypeName, ref pos);
+			if (pos < reflectionTypeName.Length)
+				throw new ReflectionNameParseException(pos, "Expected end of type name");
+			return r;
+		}
+		
+		static bool IsReflectionNameSpecialCharacter(char c)
+		{
+			switch (c) {
+				case '+':
+				case '`':
+				case '[':
+				case ']':
+				case ',':
+				case '*':
+				case '&':
+					return true;
+				default:
+					return false;
+			}
+		}
+		
+		static ITypeReference ParseReflectionName(string reflectionTypeName, ref int pos)
+		{
+			if (pos == reflectionTypeName.Length)
+				throw new ReflectionNameParseException(pos, "Unexpected end");
+			ITypeReference reference;
+			if (reflectionTypeName[pos] == '`') {
+				// type parameter reference
+				pos++;
+				if (pos == reflectionTypeName.Length)
+					throw new ReflectionNameParseException(pos, "Unexpected end");
+				if (reflectionTypeName[pos] == '`') {
+					// method type parameter reference
+					pos++;
+					int index = ReadTypeParameterCount(reflectionTypeName, ref pos);
+					reference = TypeParameterReference.Create(SymbolKind.Method, index);
+				} else {
+					// class type parameter reference
+					int index = ReadTypeParameterCount(reflectionTypeName, ref pos);
+					reference = TypeParameterReference.Create(SymbolKind.TypeDefinition, index);
+				}
+			} else {
+				// not a type parameter reference: read the actual type name
+				int tpc;
+				string typeName = ReadTypeName(reflectionTypeName, ref pos, out tpc);
+				string assemblyName = SkipAheadAndReadAssemblyName(reflectionTypeName, pos);
+				reference = CreateGetClassTypeReference(assemblyName, typeName, tpc);
+			}
+			// read type suffixes
+			while (pos < reflectionTypeName.Length) {
+				switch (reflectionTypeName[pos++]) {
+					case '+':
+						int tpc;
+						string typeName = ReadTypeName(reflectionTypeName, ref pos, out tpc);
+						reference = new NestedTypeReference(reference, typeName, tpc);
+						break;
+					case '*':
+						reference = new PointerTypeReference(reference);
+						break;
+					case '&':
+						reference = new ByReferenceTypeReference(reference);
+						break;
+					case '[':
+						// this might be an array or a generic type
+						if (pos == reflectionTypeName.Length)
+							throw new ReflectionNameParseException(pos, "Unexpected end");
+						if (reflectionTypeName[pos] == '[') {
+							// it's a generic type
+							List<ITypeReference> typeArguments = new List<ITypeReference>();
+							pos++;
+							typeArguments.Add(ParseReflectionName(reflectionTypeName, ref pos));
+							if (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ']')
+								pos++;
+							else
+								throw new ReflectionNameParseException(pos, "Expected end of type argument");
+							
+							while (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ',') {
+								pos++;
+								if (pos < reflectionTypeName.Length && reflectionTypeName[pos] == '[')
+									pos++;
+								else
+									throw new ReflectionNameParseException(pos, "Expected another type argument");
+								
+								typeArguments.Add(ParseReflectionName(reflectionTypeName, ref pos));
+								
+								if (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ']')
+									pos++;
+								else
+									throw new ReflectionNameParseException(pos, "Expected end of type argument");
+							}
+							
+							if (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ']') {
+								pos++;
+								reference = new ParameterizedTypeReference(reference, typeArguments);
+							} else {
+								throw new ReflectionNameParseException(pos, "Expected end of generic type");
+							}
+						} else {
+							// it's an array
+							int dimensions = 1;
+							while (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ',') {
+								dimensions++;
+								pos++;
+							}
+							if (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ']') {
+								pos++; // end of array
+								reference = new ArrayTypeReference(reference, dimensions);
+							} else {
+								throw new ReflectionNameParseException(pos, "Invalid array modifier");
+							}
+						}
+						break;
+					case ',':
+						// assembly qualified name, ignore everything up to the end/next ']'
+						while (pos < reflectionTypeName.Length && reflectionTypeName[pos] != ']')
+							pos++;
+						break;
+					default:
+						pos--; // reset pos to the character we couldn't read
+						if (reflectionTypeName[pos] == ']')
+							return reference; // return from a nested generic
+						else
+							throw new ReflectionNameParseException(pos, "Unexpected character: '" + reflectionTypeName[pos] + "'");
+				}
+			}
+			return reference;
+		}
+		
+		static ITypeReference CreateGetClassTypeReference(string assemblyName, string typeName, int tpc)
+		{
+			IAssemblyReference assemblyReference;
+			if (assemblyName != null) {
+				assemblyReference = new DefaultAssemblyReference(assemblyName);
+			} else {
+				assemblyReference = null;
+			}
+			int pos = typeName.LastIndexOf('.');
+			if (pos < 0)
+				return new GetClassTypeReference(assemblyReference, string.Empty, typeName, tpc);
+			else
+				return new GetClassTypeReference(assemblyReference, typeName.Substring(0, pos), typeName.Substring(pos + 1), tpc);
+		}
+		
+		static string SkipAheadAndReadAssemblyName(string reflectionTypeName, int pos)
+		{
+			int nestingLevel = 0;
+			while (pos < reflectionTypeName.Length) {
+				switch (reflectionTypeName[pos++]) {
+					case '[':
+						nestingLevel++;
+						break;
+					case ']':
+						if (nestingLevel == 0)
+							return null;
+						nestingLevel--;
+						break;
+					case ',':
+						if (nestingLevel == 0) {
+							// first skip the whitespace
+							while (pos < reflectionTypeName.Length && reflectionTypeName[pos] == ' ')
+								pos++;
+							// everything up to the end/next ']' is the assembly name
+							int endPos = pos;
+							while (endPos < reflectionTypeName.Length && reflectionTypeName[endPos] != ']')
+								endPos++;
+							return reflectionTypeName.Substring(pos, endPos - pos);
+						}
+						break;
+				}
+			}
+			return null;
+		}
+		
+		static string ReadTypeName(string reflectionTypeName, ref int pos, out int tpc)
+		{
+			int startPos = pos;
+			// skip the simple name portion:
+			while (pos < reflectionTypeName.Length && !IsReflectionNameSpecialCharacter(reflectionTypeName[pos]))
+				pos++;
+			if (pos == startPos)
+				throw new ReflectionNameParseException(pos, "Expected type name");
+			string typeName = reflectionTypeName.Substring(startPos, pos - startPos);
+			if (pos < reflectionTypeName.Length && reflectionTypeName[pos] == '`') {
+				pos++;
+				tpc = ReadTypeParameterCount(reflectionTypeName, ref pos);
+			} else {
+				tpc = 0;
+			}
+			return typeName;
+		}
+		
+		internal static int ReadTypeParameterCount(string reflectionTypeName, ref int pos)
+		{
+			int startPos = pos;
+			while (pos < reflectionTypeName.Length) {
+				char c = reflectionTypeName[pos];
+				if (c < '0' || c > '9')
+					break;
+				pos++;
+			}
+			int tpc;
+			if (!int.TryParse(reflectionTypeName.Substring(startPos, pos - startPos), out tpc))
+				throw new ReflectionNameParseException(pos, "Expected type parameter count");
+			return tpc;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ReflectionNameParseException.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ReflectionNameParseException.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/ReflectionNameParseException.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Runtime.Serialization;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Represents an error while parsing a reflection name.
+	/// </summary>
+	[Serializable]
+	public class ReflectionNameParseException : Exception
+	{
+		int position;
+		
+		public int Position {
+			get { return position; }
+		}
+		
+		public ReflectionNameParseException(int position)
+		{
+			this.position = position;
+		}
+		
+		public ReflectionNameParseException(int position, string message) : base(message)
+		{
+			this.position = position;
+		}
+		
+		public ReflectionNameParseException(int position, string message, Exception innerException) : base(message, innerException)
+		{
+			this.position = position;
+		}
+		
+		// This constructor is needed for serialization.
+		protected ReflectionNameParseException(SerializationInfo info, StreamingContext context) : base(info, context)
+		{
+			position = info.GetInt32("position");
+		}
+		
+		public override void GetObjectData(SerializationInfo info, StreamingContext context)
+		{
+			base.GetObjectData(info, context);
+			info.AddValue("position", position);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/SimpleTypeResolveContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/SimpleTypeResolveContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/SimpleTypeResolveContext.cs	(revision 11807)
@@ -0,0 +1,92 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Default ITypeResolveContext implementation.
+	/// </summary>
+	public class SimpleTypeResolveContext : ITypeResolveContext
+	{
+		readonly ICompilation compilation;
+		readonly IAssembly currentAssembly;
+		readonly ITypeDefinition currentTypeDefinition;
+		readonly IMember currentMember;
+		
+		public SimpleTypeResolveContext(ICompilation compilation)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			this.compilation = compilation;
+		}
+		
+		public SimpleTypeResolveContext(IAssembly assembly)
+		{
+			if (assembly == null)
+				throw new ArgumentNullException("assembly");
+			this.compilation = assembly.Compilation;
+			this.currentAssembly = assembly;
+		}
+		
+		public SimpleTypeResolveContext(IEntity entity)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			this.compilation = entity.Compilation;
+			this.currentAssembly = entity.ParentAssembly;
+			this.currentTypeDefinition = (entity as ITypeDefinition) ?? entity.DeclaringTypeDefinition;
+			this.currentMember = entity as IMember;
+		}
+		
+		private SimpleTypeResolveContext(ICompilation compilation, IAssembly currentAssembly, ITypeDefinition currentTypeDefinition, IMember currentMember)
+		{
+			this.compilation = compilation;
+			this.currentAssembly = currentAssembly;
+			this.currentTypeDefinition = currentTypeDefinition;
+			this.currentMember = currentMember;
+		}
+		
+		public ICompilation Compilation {
+			get { return compilation; }
+		}
+		
+		public IAssembly CurrentAssembly {
+			get { return currentAssembly; }
+		}
+		
+		public ITypeDefinition CurrentTypeDefinition {
+			get { return currentTypeDefinition; }
+		}
+		
+		public IMember CurrentMember {
+			get { return currentMember; }
+		}
+		
+		public ITypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition)
+		{
+			return new SimpleTypeResolveContext(compilation, currentAssembly, typeDefinition, currentMember);
+		}
+		
+		public ITypeResolveContext WithCurrentMember(IMember member)
+		{
+			return new SimpleTypeResolveContext(compilation, currentAssembly, currentTypeDefinition, member);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/SpecialType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/SpecialType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/SpecialType.cs	(revision 11807)
@@ -0,0 +1,101 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Contains static implementations of special types.
+	/// </summary>
+	[Serializable]
+	public sealed class SpecialType : AbstractType, ITypeReference
+	{
+		/// <summary>
+		/// Gets the type representing resolve errors.
+		/// </summary>
+		public readonly static SpecialType UnknownType = new SpecialType(TypeKind.Unknown, "?", isReferenceType: null);
+		
+		/// <summary>
+		/// The null type is used as type of the null literal. It is a reference type without any members; and it is a subtype of all reference types.
+		/// </summary>
+		public readonly static SpecialType NullType = new SpecialType(TypeKind.Null, "null", isReferenceType: true);
+		
+		/// <summary>
+		/// Type representing the C# 'dynamic' type.
+		/// </summary>
+		public readonly static SpecialType Dynamic = new SpecialType(TypeKind.Dynamic, "dynamic", isReferenceType: true);
+		
+		/// <summary>
+		/// A type used for unbound type arguments in partially parameterized types.
+		/// </summary>
+		/// <see cref="IType.GetNestedTypes(Predicate{ITypeDefinition}, GetMemberOptions)"/>
+		public readonly static SpecialType UnboundTypeArgument = new SpecialType(TypeKind.UnboundTypeArgument, "", isReferenceType: null);
+		
+		readonly TypeKind kind;
+		readonly string name;
+		readonly bool? isReferenceType;
+		
+		private SpecialType(TypeKind kind, string name, bool? isReferenceType)
+		{
+			this.kind = kind;
+			this.name = name;
+			this.isReferenceType = isReferenceType;
+		}
+		
+		public override ITypeReference ToTypeReference()
+		{
+			return this;
+		}
+		
+		public override string Name {
+			get { return name; }
+		}
+		
+		public override TypeKind Kind {
+			get { return kind; }
+		}
+		
+		public override bool? IsReferenceType {
+			get { return isReferenceType; }
+		}
+		
+		IType ITypeReference.Resolve(ITypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			return this;
+		}
+		
+		#pragma warning disable 809
+		[Obsolete("Please compare special types using the kind property instead.")]
+		public override bool Equals(IType other)
+		{
+			// We consider a special types equal when they have equal types.
+			// However, an unknown type with additional information is not considered to be equal to the SpecialType with TypeKind.Unknown.
+			return other is SpecialType && other.Kind == kind;
+		}
+		
+		public override int GetHashCode()
+		{
+			return 81625621 ^ (int)kind;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TaskType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TaskType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TaskType.cs	(revision 11807)
@@ -0,0 +1,78 @@
+﻿// Copyright (c) 2010-2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Helper class for dealing with System.Threading.Tasks.Task.
+	/// </summary>
+	public static class TaskType
+	{
+		/// <summary>
+		/// Gets the T in Task&lt;T&gt;.
+		/// Returns void for non-generic Task.
+		/// Any other type is returned unmodified.
+		/// </summary>
+		public static IType UnpackTask(ICompilation compilation, IType type)
+		{
+			if (!IsTask(type))
+				return type;
+			if (type.TypeParameterCount == 0)
+				return compilation.FindType(KnownTypeCode.Void);
+			else
+				return type.TypeArguments[0];
+		}
+		
+		/// <summary>
+		/// Gets whether the specified type is Task or Task&lt;T&gt;.
+		/// </summary>
+		public static bool IsTask(IType type)
+		{
+			ITypeDefinition def = type.GetDefinition();
+			if (def != null) {
+				if (def.KnownTypeCode == KnownTypeCode.Task)
+					return true;
+				if (def.KnownTypeCode == KnownTypeCode.TaskOfT)
+					return type is ParameterizedType;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Creates a task type.
+		/// </summary>
+		public static IType Create(ICompilation compilation, IType elementType)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (elementType == null)
+				throw new ArgumentNullException("elementType");
+			
+			if (elementType.Kind == TypeKind.Void)
+				return compilation.FindType(KnownTypeCode.Task);
+			IType taskType = compilation.FindType(KnownTypeCode.TaskOfT);
+			ITypeDefinition taskTypeDef = taskType.GetDefinition();
+			if (taskTypeDef != null)
+				return new ParameterizedType(taskTypeDef, new [] { elementType });
+			else
+				return taskType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TopLevelTypeName.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TopLevelTypeName.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TopLevelTypeName.cs	(revision 11807)
@@ -0,0 +1,144 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Holds the name of a top-level type.
+	/// This struct cannot refer to nested classes.
+	/// </summary>
+	[Serializable]
+	public struct TopLevelTypeName : IEquatable<TopLevelTypeName>
+	{
+		readonly string namespaceName;
+		readonly string name;
+		readonly int typeParameterCount;
+		
+		public TopLevelTypeName(string namespaceName, string name, int typeParameterCount = 0)
+		{
+			if (namespaceName == null)
+				throw new ArgumentNullException("namespaceName");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.namespaceName = namespaceName;
+			this.name = name;
+			this.typeParameterCount = typeParameterCount;
+		}
+		
+		public TopLevelTypeName(string reflectionName)
+		{
+			int pos = reflectionName.LastIndexOf('.');
+			if (pos < 0) {
+				namespaceName = string.Empty;
+				name = reflectionName;
+			} else {
+				namespaceName = reflectionName.Substring(0, pos);
+				name = reflectionName.Substring(pos + 1);
+			}
+			name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(name, out typeParameterCount);
+		}
+		
+		public string Namespace {
+			get { return namespaceName; }
+		}
+		
+		public string Name {
+			get { return name; }
+		}
+		
+		public int TypeParameterCount {
+			get { return typeParameterCount; }
+		}
+		
+		public string ReflectionName {
+			get {
+				StringBuilder b = new StringBuilder();
+				if (!string.IsNullOrEmpty(namespaceName)) {
+					b.Append(namespaceName);
+					b.Append('.');
+				}
+				b.Append(name);
+				if (typeParameterCount > 0) {
+					b.Append('`');
+					b.Append(typeParameterCount);
+				}
+				return b.ToString();
+			}
+		}
+		
+		public override string ToString()
+		{
+			return this.ReflectionName;
+		}
+		
+		public override bool Equals(object obj)
+		{
+			return (obj is TopLevelTypeName) && Equals((TopLevelTypeName)obj);
+		}
+		
+		public bool Equals(TopLevelTypeName other)
+		{
+			return this.namespaceName == other.namespaceName && this.name == other.name && this.typeParameterCount == other.typeParameterCount;
+		}
+		
+		public override int GetHashCode()
+		{
+			return (name != null ? name.GetHashCode() : 0) ^ (namespaceName != null ? namespaceName.GetHashCode() : 0) ^ typeParameterCount;
+		}
+		
+		public static bool operator ==(TopLevelTypeName lhs, TopLevelTypeName rhs)
+		{
+			return lhs.Equals(rhs);
+		}
+		
+		public static bool operator !=(TopLevelTypeName lhs, TopLevelTypeName rhs)
+		{
+			return !lhs.Equals(rhs);
+		}
+	}
+	
+	[Serializable]
+	public sealed class TopLevelTypeNameComparer : IEqualityComparer<TopLevelTypeName>
+	{
+		public static readonly TopLevelTypeNameComparer Ordinal = new TopLevelTypeNameComparer(StringComparer.Ordinal);
+		public static readonly TopLevelTypeNameComparer OrdinalIgnoreCase = new TopLevelTypeNameComparer(StringComparer.OrdinalIgnoreCase);
+		
+		public readonly StringComparer NameComparer;
+		
+		public TopLevelTypeNameComparer(StringComparer nameComparer)
+		{
+			this.NameComparer = nameComparer;
+		}
+		
+		public bool Equals(TopLevelTypeName x, TopLevelTypeName y)
+		{
+			return x.TypeParameterCount == y.TypeParameterCount
+				&& NameComparer.Equals(x.Name, y.Name)
+				&& NameComparer.Equals(x.Namespace, y.Namespace);
+		}
+		
+		public int GetHashCode(TopLevelTypeName obj)
+		{
+			return NameComparer.GetHashCode(obj.Name) ^ NameComparer.GetHashCode(obj.Namespace) ^ obj.TypeParameterCount;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeKind.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeKind.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeKind.cs	(revision 11807)
@@ -0,0 +1,84 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// .
+	/// </summary>
+	public enum TypeKind : byte
+	{
+		/// <summary>Language-specific type that is not part of NRefactory.TypeSystem itself.</summary>
+		Other,
+		
+		/// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is a class.</summary>
+		Class,
+		/// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is an interface.</summary>
+		Interface,
+		/// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is a struct.</summary>
+		Struct,
+		/// <summary>A <see cref="ITypeDefinition"/> or <see cref="ParameterizedType"/> that is a delegate.</summary>
+		/// <remarks><c>System.Delegate</c> itself is TypeKind.Class</remarks>
+		Delegate,
+		/// <summary>A <see cref="ITypeDefinition"/> that is an enum.</summary>
+		/// <remarks><c>System.Enum</c> itself is TypeKind.Class</remarks>
+		Enum,
+		/// <summary>A <see cref="ITypeDefinition"/> that is a module (VB).</summary>
+		Module,
+		
+		/// <summary>The <c>System.Void</c> type.</summary>
+		/// <see cref="KnownTypeReference.Void"/>
+		Void,
+		
+		/// <see cref="SpecialType.UnknownType"/>
+		Unknown,
+		/// <summary>The type of the null literal.</summary>
+		/// <see cref="SpecialType.NullType"/>
+		Null,
+		/// <summary>Type representing the C# 'dynamic' type.</summary>
+		/// <see cref="SpecialType.Dynamic"/>
+		Dynamic,
+		/// <summary>Represents missing type arguments in partially parameterized types.</summary>
+		/// <see cref="SpecialType.UnboundTypeArgument"/>
+		/// <see cref="IType.GetNestedTypes(Predicate{ITypeDefinition}, GetMemberOptions)"/>
+		UnboundTypeArgument,
+		
+		/// <summary>The type is a type parameter.</summary>
+		/// <see cref="ITypeParameter"/>
+		TypeParameter,
+		
+		/// <summary>An array type</summary>
+		/// <see cref="ArrayType"/>
+		Array,
+		/// <summary>A pointer type</summary>
+		/// <see cref="PointerType"/>
+		Pointer,
+		/// <summary>A managed reference type</summary>
+		/// <see cref="ByReferenceType"/>
+		ByReference,
+		/// <summary>An anonymous type</summary>
+		/// <see cref="AnonymousType"/>
+		Anonymous,
+		
+		/// <summary>Intersection of several types</summary>
+		/// <see cref="IntersectionType"/>
+		Intersection
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeParameterSubstitution.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeParameterSubstitution.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeParameterSubstitution.cs	(revision 11807)
@@ -0,0 +1,193 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Substitutes class and method type parameters.
+	/// </summary>
+	public class TypeParameterSubstitution : TypeVisitor
+	{
+		/// <summary>
+		/// The identity function.
+		/// </summary>
+		public static readonly TypeParameterSubstitution Identity = new TypeParameterSubstitution(null, null);
+		
+		readonly IList<IType> classTypeArguments;
+		readonly IList<IType> methodTypeArguments;
+		
+		/// <summary>
+		/// Creates a new type parameter substitution.
+		/// </summary>
+		/// <param name="classTypeArguments">
+		/// The type arguments to substitute for class type parameters.
+		/// Pass <c>null</c> to keep class type parameters unmodified.
+		/// </param>
+		/// <param name="methodTypeArguments">
+		/// The type arguments to substitute for method type parameters.
+		/// Pass <c>null</c> to keep method type parameters unmodified.
+		/// </param>
+		public TypeParameterSubstitution(IList<IType> classTypeArguments, IList<IType> methodTypeArguments)
+		{
+			this.classTypeArguments = classTypeArguments;
+			this.methodTypeArguments = methodTypeArguments;
+		}
+		
+		/// <summary>
+		/// Gets the list of class type arguments.
+		/// Returns <c>null</c> if this substitution keeps class type parameters unmodified.
+		/// </summary>
+		public IList<IType> ClassTypeArguments {
+			get { return classTypeArguments; }
+		}
+		
+		/// <summary>
+		/// Gets the list of method type arguments.
+		/// Returns <c>null</c> if this substitution keeps method type parameters unmodified.
+		/// </summary>
+		public IList<IType> MethodTypeArguments {
+			get { return methodTypeArguments; }
+		}
+		
+		#region Compose
+		/// <summary>
+		/// Computes a single TypeParameterSubstitution so that for all types <c>t</c>:
+		/// <c>t.AcceptVisitor(Compose(g, f)) equals t.AcceptVisitor(f).AcceptVisitor(g)</c>
+		/// </summary>
+		/// <remarks>If you consider type parameter substitution to be a function, this is function composition.</remarks>
+		public static TypeParameterSubstitution Compose(TypeParameterSubstitution g, TypeParameterSubstitution f)
+		{
+			if (g == null)
+				return f;
+			if (f == null || (f.classTypeArguments == null && f.methodTypeArguments == null))
+				return g;
+			// The composition is a copy of 'f', with 'g' applied on the array elements.
+			// If 'f' has a null list (keeps type parameters unmodified), we have to treat it as
+			// the identity function, and thus use the list from 'g'.
+			var classTypeArguments = f.classTypeArguments != null ? GetComposedTypeArguments(f.classTypeArguments, g) : g.classTypeArguments;
+			var methodTypeArguments = f.methodTypeArguments != null ? GetComposedTypeArguments(f.methodTypeArguments, g) : g.methodTypeArguments;
+			return new TypeParameterSubstitution(classTypeArguments, methodTypeArguments);
+		}
+		
+		static IList<IType> GetComposedTypeArguments(IList<IType> input, TypeParameterSubstitution substitution)
+		{
+			IType[] result = new IType[input.Count];
+			for (int i = 0; i < result.Length; i++) {
+				result[i] = input[i].AcceptVisitor(substitution);
+			}
+			return result;
+		}
+		#endregion
+		
+		#region Equals and GetHashCode implementation
+		public override bool Equals(object obj)
+		{
+			TypeParameterSubstitution other = obj as TypeParameterSubstitution;
+			if (other == null)
+				return false;
+			return TypeListEquals(classTypeArguments, other.classTypeArguments)
+				&& TypeListEquals(methodTypeArguments, other.methodTypeArguments);
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				return 1124131 * TypeListHashCode(classTypeArguments) + 1821779 * TypeListHashCode(methodTypeArguments);
+			}
+		}
+		
+		static bool TypeListEquals(IList<IType> a, IList<IType> b)
+		{
+			if (a == b)
+				return true;
+			if (a == null || b == null)
+				return false;
+			if (a.Count != b.Count)
+				return false;
+			for (int i = 0; i < a.Count; i++) {
+				if (!a[i].Equals(b[i]))
+					return false;
+			}
+			return true;
+		}
+		
+		static int TypeListHashCode(IList<IType> obj)
+		{
+			if (obj == null)
+				return 0;
+			unchecked {
+				int hashCode = 1;
+				foreach (var element in obj) {
+					hashCode *= 27;
+					hashCode += element.GetHashCode();
+				}
+				return hashCode;
+			}
+		}
+		#endregion
+		
+		public override IType VisitTypeParameter(ITypeParameter type)
+		{
+			int index = type.Index;
+			if (classTypeArguments != null && type.OwnerType == SymbolKind.TypeDefinition) {
+				if (index >= 0 && index < classTypeArguments.Count)
+					return classTypeArguments[index];
+				else
+					return SpecialType.UnknownType;
+			} else if (methodTypeArguments != null && type.OwnerType == SymbolKind.Method) {
+				if (index >= 0 && index < methodTypeArguments.Count)
+					return methodTypeArguments[index];
+				else
+					return SpecialType.UnknownType;
+			} else {
+				return base.VisitTypeParameter(type);
+			}
+		}
+		
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder();
+			b.Append('[');
+			bool first = true;
+			if (classTypeArguments != null) {
+				for (int i = 0; i < classTypeArguments.Count; i++) {
+					if (first) first = false; else b.Append(", ");
+					b.Append('`');
+					b.Append(i);
+					b.Append(" -> ");
+					b.Append(classTypeArguments[i].ReflectionName);
+				}
+			}
+			if (methodTypeArguments != null) {
+				for (int i = 0; i < methodTypeArguments.Count; i++) {
+					if (first) first = false; else b.Append(", ");
+					b.Append("``");
+					b.Append(i);
+					b.Append(" -> ");
+					b.Append(methodTypeArguments[i].ReflectionName);
+				}
+			}
+			b.Append(']');
+			return b.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeSystemExtensions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeSystemExtensions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeSystemExtensions.cs	(revision 11807)
@@ -0,0 +1,788 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Contains extension methods for the type system.
+	/// </summary>
+	public static class TypeSystemExtensions
+	{
+		#region GetAllBaseTypes
+		/// <summary>
+		/// Gets all base types.
+		/// </summary>
+		/// <remarks>This is the reflexive and transitive closure of <see cref="IType.DirectBaseTypes"/>.
+		/// Note that this method does not return all supertypes - doing so is impossible due to contravariance
+		/// (and undesirable for covariance as the list could become very large).
+		/// 
+		/// The output is ordered so that base types occur before derived types.
+		/// </remarks>
+		public static IEnumerable<IType> GetAllBaseTypes(this IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			BaseTypeCollector collector = new BaseTypeCollector();
+			collector.CollectBaseTypes(type);
+			return collector;
+		}
+		
+		/// <summary>
+		/// Gets all non-interface base types.
+		/// </summary>
+		/// <remarks>
+		/// When <paramref name="type"/> is an interface, this method will also return base interfaces (return same output as GetAllBaseTypes()).
+		/// 
+		/// The output is ordered so that base types occur before derived types.
+		/// </remarks>
+		public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			BaseTypeCollector collector = new BaseTypeCollector();
+			collector.SkipImplementedInterfaces = true;
+			collector.CollectBaseTypes(type);
+			return collector;
+		}
+		#endregion
+		
+		#region GetAllBaseTypeDefinitions
+		/// <summary>
+		/// Gets all base type definitions.
+		/// The output is ordered so that base types occur before derived types.
+		/// </summary>
+		/// <remarks>
+		/// This is equivalent to type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct().
+		/// </remarks>
+		public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			
+			return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct();
+		}
+		
+		/// <summary>
+		/// Gets whether this type definition is derived from the base type definition.
+		/// </summary>
+		public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (baseType == null)
+				return false;
+			if (type.Compilation != baseType.Compilation) {
+				throw new InvalidOperationException("Both arguments to IsDerivedFrom() must be from the same compilation.");
+			}
+			return type.GetAllBaseTypeDefinitions().Contains(baseType);
+		}
+		
+		/// <summary>
+		/// Gets whether this type definition is derived from a given known type.
+		/// </summary>
+		public static bool IsDerivedFrom(this ITypeDefinition type, KnownTypeCode baseType)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (baseType == KnownTypeCode.None)
+				return false;
+			return IsDerivedFrom(type, type.Compilation.FindType(baseType).GetDefinition());
+		}
+		#endregion
+		
+		#region IsOpen / IsUnbound / IsKnownType
+		sealed class TypeClassificationVisitor : TypeVisitor
+		{
+			internal bool isOpen;
+			internal IEntity typeParameterOwner;
+			int typeParameterOwnerNestingLevel;
+			
+			public override IType VisitTypeParameter(ITypeParameter type)
+			{
+				isOpen = true;
+				// If both classes and methods, or different classes (nested types)
+				// are involved, find the most specific one
+				int newNestingLevel = GetNestingLevel(type.Owner);
+				if (newNestingLevel > typeParameterOwnerNestingLevel) {
+					typeParameterOwner = type.Owner;
+					typeParameterOwnerNestingLevel = newNestingLevel;
+				}
+				return base.VisitTypeParameter(type);
+			}
+			
+			static int GetNestingLevel(IEntity entity)
+			{
+				int level = 0;
+				while (entity != null) {
+					level++;
+					entity = entity.DeclaringTypeDefinition;
+				}
+				return level;
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether the type is an open type (contains type parameters).
+		/// </summary>
+		/// <example>
+		/// <code>
+		/// class X&lt;T&gt; {
+		///   List&lt;T&gt; open;
+		///   X&lt;X&lt;T[]&gt;&gt; open;
+		///   X&lt;string&gt; closed;
+		///   int closed;
+		/// }
+		/// </code>
+		/// </example>
+		public static bool IsOpen(this IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			TypeClassificationVisitor v = new TypeClassificationVisitor();
+			type.AcceptVisitor(v);
+			return v.isOpen;
+		}
+		
+		/// <summary>
+		/// Gets the entity that owns the type parameters occurring in the specified type.
+		/// If both class and method type parameters are present, the method is returned.
+		/// Returns null if the specified type is closed.
+		/// </summary>
+		/// <seealso cref="IsOpen"/>
+		static IEntity GetTypeParameterOwner(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			TypeClassificationVisitor v = new TypeClassificationVisitor();
+			type.AcceptVisitor(v);
+			return v.typeParameterOwner;
+		}
+		
+		/// <summary>
+		/// Gets whether the type is unbound (is a generic type, but no type arguments were provided).
+		/// </summary>
+		/// <remarks>
+		/// In "<c>typeof(List&lt;Dictionary&lt;,&gt;&gt;)</c>", only the Dictionary is unbound, the List is considered
+		/// bound despite containing an unbound type.
+		/// This method returns false for partially parameterized types (<c>Dictionary&lt;string, &gt;</c>).
+		/// </remarks>
+		public static bool IsUnbound(this IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			return type is ITypeDefinition && type.TypeParameterCount > 0;
+		}
+		
+		/// <summary>
+		/// Gets whether the type is the specified known type.
+		/// For generic known types, this returns true any parameterization of the type (and also for the definition itself).
+		/// </summary>
+		public static bool IsKnownType(this IType type, KnownTypeCode knownType)
+		{
+			var def = type.GetDefinition();
+			return def != null && def.KnownTypeCode == knownType;
+		}
+		#endregion
+		
+		#region Import
+		/// <summary>
+		/// Imports a symbol from another compilation.
+		/// </summary>
+		public static ISymbol Import(this ICompilation compilation, ISymbol symbol)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (symbol == null)
+				return null;
+			switch (symbol.SymbolKind) {
+				case SymbolKind.TypeParameter:
+					return (ITypeParameter)Import(compilation, (IType)symbol);
+				case SymbolKind.Variable:
+					IVariable v = (IVariable)symbol;
+					return new DefaultVariable(
+						Import(compilation, v.Type),
+						v.Name, v.Region, v.IsConst, v.ConstantValue
+					);
+				case SymbolKind.Parameter:
+					IParameter p = (IParameter)symbol;
+					if (p.Owner != null) {
+						int index = p.Owner.Parameters.IndexOf(p);
+						var owner = (IParameterizedMember)Import(compilation, p.Owner);
+						if (owner == null || index < 0 || index >= owner.Parameters.Count)
+							return null;
+						return owner.Parameters[index];
+					} else {
+						return new DefaultParameter(
+							Import(compilation, p.Type),
+							p.Name, null, p.Region,
+							null, p.IsRef, p.IsOut, p.IsParams
+						);
+					}
+				case SymbolKind.Namespace:
+					return Import(compilation, (INamespace)symbol);
+				default:
+					if (symbol is IEntity)
+						return Import(compilation, (IEntity)symbol);
+					throw new NotSupportedException("Unsupported symbol kind: " + symbol.SymbolKind);
+			}
+		}
+		
+		/// <summary>
+		/// Imports a type from another compilation.
+		/// </summary>
+		public static IType Import(this ICompilation compilation, IType type)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (type == null)
+				return null;
+			var compilationProvider = type as ICompilationProvider;
+			if (compilationProvider != null && compilationProvider.Compilation == compilation)
+				return type;
+			IEntity typeParameterOwner = GetTypeParameterOwner(type);
+			IEntity importedTypeParameterOwner = compilation.Import(typeParameterOwner);
+			if (importedTypeParameterOwner != null) {
+				return type.ToTypeReference().Resolve(new SimpleTypeResolveContext(importedTypeParameterOwner));
+			} else {
+				return type.ToTypeReference().Resolve(compilation.TypeResolveContext);
+			}
+		}
+		
+		/// <summary>
+		/// Imports a type from another compilation.
+		/// </summary>
+		public static ITypeDefinition Import(this ICompilation compilation, ITypeDefinition typeDefinition)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (typeDefinition == null)
+				return null;
+			if (typeDefinition.Compilation == compilation)
+				return typeDefinition;
+			return typeDefinition.ToTypeReference().Resolve(compilation.TypeResolveContext).GetDefinition();
+		}
+		
+		/// <summary>
+		/// Imports an entity from another compilation.
+		/// </summary>
+		public static IEntity Import(this ICompilation compilation, IEntity entity)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (entity == null)
+				return null;
+			if (entity.Compilation == compilation)
+				return entity;
+			if (entity is IMember)
+				return ((IMember)entity).ToReference().Resolve(compilation.TypeResolveContext);
+			else if (entity is ITypeDefinition)
+				return ((ITypeDefinition)entity).ToTypeReference().Resolve(compilation.TypeResolveContext).GetDefinition();
+			else
+				throw new NotSupportedException("Unknown entity type");
+		}
+		
+		/// <summary>
+		/// Imports a member from another compilation.
+		/// </summary>
+		public static IMember Import(this ICompilation compilation, IMember member)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (member == null)
+				return null;
+			if (member.Compilation == compilation)
+				return member;
+			return member.ToReference().Resolve(compilation.TypeResolveContext);
+		}
+		
+		/// <summary>
+		/// Imports a member from another compilation.
+		/// </summary>
+		public static IMethod Import(this ICompilation compilation, IMethod method)
+		{
+			return (IMethod)compilation.Import((IMember)method);
+		}
+		
+		/// <summary>
+		/// Imports a member from another compilation.
+		/// </summary>
+		public static IField Import(this ICompilation compilation, IField field)
+		{
+			return (IField)compilation.Import((IMember)field);
+		}
+		
+		/// <summary>
+		/// Imports a member from another compilation.
+		/// </summary>
+		public static IEvent Import(this ICompilation compilation, IEvent ev)
+		{
+			return (IEvent)compilation.Import((IMember)ev);
+		}
+		
+		/// <summary>
+		/// Imports a member from another compilation.
+		/// </summary>
+		public static IProperty Import(this ICompilation compilation, IProperty property)
+		{
+			return (IProperty)compilation.Import((IMember)property);
+		}
+		
+		/// <summary>
+		/// Imports a namespace from another compilation.
+		/// </summary>
+		/// <remarks>
+		/// This method may return null if the namespace does not exist in the target compilation.
+		/// </remarks>
+		public static INamespace Import(this ICompilation compilation, INamespace ns)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (ns == null)
+				return null;
+			if (ns.ParentNamespace == null) {
+				// root namespace
+				return compilation.GetNamespaceForExternAlias(ns.ExternAlias);
+			} else {
+				INamespace parent = Import(compilation, ns.ParentNamespace);
+				if (parent != null)
+					return parent.GetChildNamespace(ns.Name);
+				else
+					return null;
+			}
+		}
+		#endregion
+		
+		#region GetDelegateInvokeMethod
+		/// <summary>
+		/// Gets the invoke method for a delegate type.
+		/// </summary>
+		/// <remarks>
+		/// Returns null if the type is not a delegate type; or if the invoke method could not be found.
+		/// </remarks>
+		public static IMethod GetDelegateInvokeMethod(this IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (type.Kind == TypeKind.Delegate)
+				return type.GetMethods(m => m.Name == "Invoke", GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
+			else
+				return null;
+		}
+		#endregion
+		
+		#region GetType/Member
+		/// <summary>
+		/// Gets all unresolved type definitions from the file.
+		/// For partial classes, each part is returned.
+		/// </summary>
+		public static IEnumerable<IUnresolvedTypeDefinition> GetAllTypeDefinitions (this IUnresolvedFile file)
+		{
+			return TreeTraversal.PreOrder(file.TopLevelTypeDefinitions, t => t.NestedTypes);
+		}
+		
+		/// <summary>
+		/// Gets all unresolved type definitions from the assembly.
+		/// For partial classes, each part is returned.
+		/// </summary>
+		public static IEnumerable<IUnresolvedTypeDefinition> GetAllTypeDefinitions (this IUnresolvedAssembly assembly)
+		{
+			return TreeTraversal.PreOrder(assembly.TopLevelTypeDefinitions, t => t.NestedTypes);
+		}
+		
+		public static IEnumerable<ITypeDefinition> GetAllTypeDefinitions (this IAssembly assembly)
+		{
+			return TreeTraversal.PreOrder(assembly.TopLevelTypeDefinitions, t => t.NestedTypes);
+		}
+		
+		/// <summary>
+		/// Gets all type definitions in the compilation.
+		/// This may include types from referenced assemblies that are not accessible in the main assembly.
+		/// </summary>
+		public static IEnumerable<ITypeDefinition> GetAllTypeDefinitions (this ICompilation compilation)
+		{
+			return compilation.Assemblies.SelectMany(a => a.GetAllTypeDefinitions());
+		}
+
+		/// <summary>
+		/// Gets all top level type definitions in the compilation.
+		/// This may include types from referenced assemblies that are not accessible in the main assembly.
+		/// </summary>
+		public static IEnumerable<ITypeDefinition> GetTopLevelTypeDefinitons (this ICompilation compilation)
+		{
+			return compilation.Assemblies.SelectMany(a => a.TopLevelTypeDefinitions);
+		}
+		
+		/// <summary>
+		/// Gets the type (potentially a nested type) defined at the specified location.
+		/// Returns null if no type is defined at that location.
+		/// </summary>
+		public static IUnresolvedTypeDefinition GetInnermostTypeDefinition (this IUnresolvedFile file, int line, int column)
+		{
+			return file.GetInnermostTypeDefinition (new TextLocation (line, column));
+		}
+		
+		/// <summary>
+		/// Gets the member defined at the specified location.
+		/// Returns null if no member is defined at that location.
+		/// </summary>
+		public static IUnresolvedMember GetMember (this IUnresolvedFile file, int line, int column)
+		{
+			return file.GetMember (new TextLocation (line, column));
+		}
+		#endregion
+		
+		#region Resolve on collections
+		public static IList<IAttribute> CreateResolvedAttributes(this IList<IUnresolvedAttribute> attributes, ITypeResolveContext context)
+		{
+			if (attributes == null)
+				throw new ArgumentNullException("attributes");
+			if (attributes.Count == 0)
+				return EmptyList<IAttribute>.Instance;
+			else
+				return new ProjectedList<ITypeResolveContext, IUnresolvedAttribute, IAttribute>(context, attributes, (c, a) => a.CreateResolvedAttribute(c));
+		}
+		
+		public static IList<ITypeParameter> CreateResolvedTypeParameters(this IList<IUnresolvedTypeParameter> typeParameters, ITypeResolveContext context)
+		{
+			if (typeParameters == null)
+				throw new ArgumentNullException("typeParameters");
+			if (typeParameters.Count == 0)
+				return EmptyList<ITypeParameter>.Instance;
+			else
+				return new ProjectedList<ITypeResolveContext, IUnresolvedTypeParameter, ITypeParameter>(context, typeParameters, (c, a) => a.CreateResolvedTypeParameter(c));
+		}
+		
+		public static IList<IParameter> CreateResolvedParameters(this IList<IUnresolvedParameter> parameters, ITypeResolveContext context)
+		{
+			if (parameters == null)
+				throw new ArgumentNullException("parameters");
+			if (parameters.Count == 0)
+				return EmptyList<IParameter>.Instance;
+			else
+				return new ProjectedList<ITypeResolveContext, IUnresolvedParameter, IParameter>(context, parameters, (c, a) => a.CreateResolvedParameter(c));
+		}
+		
+		public static IList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context)
+		{
+			if (typeReferences == null)
+				throw new ArgumentNullException("typeReferences");
+			if (typeReferences.Count == 0)
+				return EmptyList<IType>.Instance;
+			else
+				return new ProjectedList<ITypeResolveContext, ITypeReference, IType>(context, typeReferences, (c, t) => t.Resolve(c));
+		}
+		
+		// There is intentionally no Resolve() overload for IList<IMemberReference>: the resulting IList<Member> would
+		// contains nulls when there are resolve errors.
+		
+		public static IList<ResolveResult> Resolve(this IList<IConstantValue> constantValues, ITypeResolveContext context)
+		{
+			if (constantValues == null)
+				throw new ArgumentNullException("constantValues");
+			if (constantValues.Count == 0)
+				return EmptyList<ResolveResult>.Instance;
+			else
+				return new ProjectedList<ITypeResolveContext, IConstantValue, ResolveResult>(context, constantValues, (c, t) => t.Resolve(c));
+		}
+		#endregion
+		
+		#region GetSubTypeDefinitions
+		public static IEnumerable<ITypeDefinition> GetSubTypeDefinitions (this IType baseType)
+		{
+			if (baseType == null)
+				throw new ArgumentNullException ("baseType");
+			var def = baseType.GetDefinition ();
+			if (def == null)
+				return Enumerable.Empty<ITypeDefinition> ();
+			return def.GetSubTypeDefinitions ();
+		}
+		
+		/// <summary>
+		/// Gets all sub type definitions defined in a context.
+		/// </summary>
+		public static IEnumerable<ITypeDefinition> GetSubTypeDefinitions (this ITypeDefinition baseType)
+		{
+			if (baseType == null)
+				throw new ArgumentNullException ("baseType");
+			foreach (var contextType in baseType.Compilation.GetAllTypeDefinitions ()) {
+				if (contextType.IsDerivedFrom (baseType))
+					yield return contextType;
+			}
+		}
+		#endregion
+		
+		#region IAssembly.GetTypeDefinition()
+		/// <summary>
+		/// Retrieves the specified type in this compilation.
+		/// Returns an <see cref="UnknownType"/> if the type cannot be found in this compilation.
+		/// </summary>
+		/// <remarks>
+		/// There can be multiple types with the same full name in a compilation, as a
+		/// full type name is only unique per assembly.
+		/// If there are multiple possible matches, this method will return just one of them.
+		/// When possible, use <see cref="IAssembly.GetTypeDefinition"/> instead to
+		/// retrieve a type from a specific assembly.
+		/// </remarks>
+		public static IType FindType(this ICompilation compilation, FullTypeName fullTypeName)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			foreach (IAssembly asm in compilation.Assemblies) {
+				ITypeDefinition def = asm.GetTypeDefinition(fullTypeName);
+				if (def != null)
+					return def;
+			}
+			return new UnknownType(fullTypeName);
+		}
+		
+		/// <summary>
+		/// Gets the type definition for the specified unresolved type.
+		/// Returns null if the unresolved type does not belong to this assembly.
+		/// </summary>
+		public static ITypeDefinition GetTypeDefinition(this IAssembly assembly, FullTypeName fullTypeName)
+		{
+			if (assembly == null)
+				throw new ArgumentNullException("assembly");
+			TopLevelTypeName topLevelTypeName = fullTypeName.TopLevelTypeName;
+			ITypeDefinition typeDef = assembly.GetTypeDefinition(topLevelTypeName);
+			if (typeDef == null)
+				return null;
+			int typeParameterCount = topLevelTypeName.TypeParameterCount;
+			for (int i = 0; i < fullTypeName.NestingLevel; i++) {
+				string name = fullTypeName.GetNestedTypeName(i);
+				typeParameterCount += fullTypeName.GetNestedTypeAdditionalTypeParameterCount(i);
+				typeDef = FindNestedType(typeDef, name, typeParameterCount);
+				if (typeDef == null)
+					break;
+			}
+			return typeDef;
+		}
+		
+		static ITypeDefinition FindNestedType(ITypeDefinition typeDef, string name, int typeParameterCount)
+		{
+			foreach (var nestedType in typeDef.NestedTypes) {
+				if (nestedType.Name == name && nestedType.TypeParameterCount == typeParameterCount)
+					return nestedType;
+			}
+			return null;
+		}
+		#endregion
+
+		#region ITypeReference.Resolve(ICompilation)
+
+		/// <summary>
+		/// Resolves a type reference in the compilation's main type resolve context.
+		/// Some type references require a more specific type resolve context and will not resolve using this method.
+		/// </summary>
+		/// <returns>
+		/// Returns the resolved type.
+		/// In case of an error, returns <see cref="SpecialType.UnknownType"/>.
+		/// Never returns null.
+		/// </returns>
+		public static IType Resolve (this ITypeReference reference, ICompilation compilation)
+		{
+			if (reference == null)
+				throw new ArgumentNullException ("reference");
+			if (compilation == null)
+				throw new ArgumentNullException ("compilation");
+			return reference.Resolve (compilation.TypeResolveContext);
+		}
+		#endregion
+		
+		#region ITypeDefinition.GetAttribute
+		/// <summary>
+		/// Gets the attribute of the specified attribute type (or derived attribute types).
+		/// </summary>
+		/// <param name="entity">The entity on which the attributes are declared.</param>
+		/// <param name="attributeType">The attribute type to look for.</param>
+		/// <param name="inherit">
+		/// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>)
+		/// should be returned. The default is <c>true</c>.
+		/// </param>
+		/// <returns>
+		/// Returns the attribute that was found; or <c>null</c> if none was found.
+		/// If inherit is true, an from the entity itself will be returned if possible;
+		/// and the base entity will only be searched if none exists.
+		/// </returns>
+		public static IAttribute GetAttribute(this IEntity entity, IType attributeType, bool inherit = true)
+		{
+			return GetAttributes(entity, attributeType, inherit).FirstOrDefault();
+		}
+		
+		/// <summary>
+		/// Gets the attributes of the specified attribute type (or derived attribute types).
+		/// </summary>
+		/// <param name="entity">The entity on which the attributes are declared.</param>
+		/// <param name="attributeType">The attribute type to look for.</param>
+		/// <param name="inherit">
+		/// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>)
+		/// should be returned. The default is <c>true</c>.
+		/// </param>
+		/// <returns>
+		/// Returns the list of attributes that were found.
+		/// If inherit is true, attributes from the entity itself are returned first; followed by attributes inherited from the base entity.
+		/// </returns>
+		public static IEnumerable<IAttribute> GetAttributes(this IEntity entity, IType attributeType, bool inherit = true)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			if (attributeType == null)
+				throw new ArgumentNullException("attributeType");
+			return GetAttributes(entity, attributeType.Equals, inherit);
+		}
+		
+		/// <summary>
+		/// Gets the attribute of the specified attribute type (or derived attribute types).
+		/// </summary>
+		/// <param name="entity">The entity on which the attributes are declared.</param>
+		/// <param name="attributeType">The attribute type to look for.</param>
+		/// <param name="inherit">
+		/// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>)
+		/// should be returned. The default is <c>true</c>.
+		/// </param>
+		/// <returns>
+		/// Returns the attribute that was found; or <c>null</c> if none was found.
+		/// If inherit is true, an from the entity itself will be returned if possible;
+		/// and the base entity will only be searched if none exists.
+		/// </returns>
+		public static IAttribute GetAttribute(this IEntity entity, FullTypeName attributeType, bool inherit = true)
+		{
+			return GetAttributes(entity, attributeType, inherit).FirstOrDefault();
+		}
+		
+		/// <summary>
+		/// Gets the attributes of the specified attribute type (or derived attribute types).
+		/// </summary>
+		/// <param name="entity">The entity on which the attributes are declared.</param>
+		/// <param name="attributeType">The attribute type to look for.</param>
+		/// <param name="inherit">
+		/// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>)
+		/// should be returned. The default is <c>true</c>.
+		/// </param>
+		/// <returns>
+		/// Returns the list of attributes that were found.
+		/// If inherit is true, attributes from the entity itself are returned first; followed by attributes inherited from the base entity.
+		/// </returns>
+		public static IEnumerable<IAttribute> GetAttributes(this IEntity entity, FullTypeName attributeType, bool inherit = true)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			return GetAttributes(entity, attrType => {
+			                     	ITypeDefinition typeDef = attrType.GetDefinition();
+			                     	return typeDef != null && typeDef.FullTypeName == attributeType;
+			                     }, inherit);
+		}
+
+		/// <summary>
+		/// Gets the attribute of the specified attribute type (or derived attribute types).
+		/// </summary>
+		/// <param name="entity">The entity on which the attributes are declared.</param>
+		/// <param name="inherit">
+		/// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>)
+		/// should be returned. The default is <c>true</c>.
+		/// </param>
+		/// <returns>
+		/// Returns the attribute that was found; or <c>null</c> if none was found.
+		/// If inherit is true, an from the entity itself will be returned if possible;
+		/// and the base entity will only be searched if none exists.
+		/// </returns>
+		public static IEnumerable<IAttribute> GetAttributes(this IEntity entity, bool inherit = true)
+		{
+			if (entity == null)
+				throw new ArgumentNullException ("entity");
+			return GetAttributes(entity, a => true, inherit);
+		}
+		
+		static IEnumerable<IAttribute> GetAttributes(IEntity entity, Predicate<IType> attributeTypePredicate, bool inherit)
+		{
+			if (!inherit) {
+				foreach (var attr in entity.Attributes) {
+					if (attributeTypePredicate(attr.AttributeType))
+						yield return attr;
+				}
+				yield break;
+			}
+			ITypeDefinition typeDef = entity as ITypeDefinition;
+			if (typeDef != null) {
+				foreach (var baseType in typeDef.GetNonInterfaceBaseTypes().Reverse()) {
+					ITypeDefinition baseTypeDef = baseType.GetDefinition();
+					if (baseTypeDef == null)
+						continue;
+					foreach (var attr in baseTypeDef.Attributes) {
+						if (attributeTypePredicate(attr.AttributeType))
+							yield return attr;
+					}
+				}
+				yield break;
+			}
+			IMember member = entity as IMember;
+			if (member != null) {
+				HashSet<IMember> visitedMembers = new HashSet<IMember>();
+				do {
+					member = member.MemberDefinition; // it's sufficient to look at the definitions
+					if (!visitedMembers.Add(member)) {
+						// abort if we seem to be in an infinite loop (cyclic inheritance)
+						break;
+					}
+					foreach (var attr in member.Attributes) {
+						if (attributeTypePredicate(attr.AttributeType))
+							yield return attr;
+					}
+				} while (member.IsOverride && (member = InheritanceHelper.GetBaseMember(member)) != null);
+				yield break;
+			}
+			throw new NotSupportedException("Unknown entity type");
+		}
+		#endregion
+		
+		#region IAssembly.GetTypeDefinition(string,string,int)
+		/// <summary>
+		/// Gets the type definition for a top-level type.
+		/// </summary>
+		/// <remarks>This method uses ordinal name comparison, not the compilation's name comparer.</remarks>
+		public static ITypeDefinition GetTypeDefinition(this IAssembly assembly, string namespaceName, string name, int typeParameterCount = 0)
+		{
+			if (assembly == null)
+				throw new ArgumentNullException ("assembly");
+			return assembly.GetTypeDefinition (new TopLevelTypeName (namespaceName, name, typeParameterCount));
+		}
+		#endregion
+		
+		#region ResolveResult
+		public static ISymbol GetSymbol(this ResolveResult rr)
+		{
+			if (rr is LocalResolveResult) {
+				return ((LocalResolveResult)rr).Variable;
+			} else if (rr is MemberResolveResult) {
+				return ((MemberResolveResult)rr).Member;
+			} else if (rr is TypeResolveResult) {
+				return ((TypeResolveResult)rr).Type.GetDefinition();
+			}
+			
+			return null;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/TypeSystem/TypeVisitor.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Base class for the visitor pattern on <see cref="IType"/>.
+	/// </summary>
+	public abstract class TypeVisitor
+	{
+		public virtual IType VisitTypeDefinition(ITypeDefinition type)
+		{
+			return type.VisitChildren(this);
+		}
+		
+		public virtual IType VisitTypeParameter(ITypeParameter type)
+		{
+			return type.VisitChildren(this);
+		}
+		
+		public virtual IType VisitParameterizedType(ParameterizedType type)
+		{
+			return type.VisitChildren(this);
+		}
+		
+		public virtual IType VisitArrayType(ArrayType type)
+		{
+			return type.VisitChildren(this);
+		}
+		
+		public virtual IType VisitPointerType(PointerType type)
+		{
+			return type.VisitChildren(this);
+		}
+		
+		public virtual IType VisitByReferenceType(ByReferenceType type)
+		{
+			return type.VisitChildren(this);
+		}
+		
+		public virtual IType VisitOtherType(IType type)
+		{
+			return type.VisitChildren(this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/7BitEncodedInts.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/7BitEncodedInts.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/7BitEncodedInts.cs	(revision 11807)
@@ -0,0 +1,123 @@
+﻿// Copyright (c) 2011 Daniel Grunwald
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// A binary reader that can read the output of BinaryWriterWith7BitEncodedInts.
+	/// </summary>
+	public sealed class BinaryReaderWith7BitEncodedInts : BinaryReader
+	{
+		public BinaryReaderWith7BitEncodedInts(Stream stream) : base(stream)
+		{
+		}
+		
+		public override short ReadInt16()
+		{
+			return unchecked((short)(ushort)base.Read7BitEncodedInt());
+		}
+		
+		[CLSCompliant(false)]
+		public override ushort ReadUInt16()
+		{
+			return unchecked((ushort)base.Read7BitEncodedInt());
+		}
+		
+		public override int ReadInt32()
+		{
+			return base.Read7BitEncodedInt();
+		}
+		
+		[CLSCompliant(false)]
+		public override uint ReadUInt32()
+		{
+			return unchecked((uint)base.Read7BitEncodedInt());
+		}
+		
+		public override long ReadInt64()
+		{
+			return unchecked((long)this.ReadUInt64());
+		}
+		
+		[CLSCompliant(false)]
+		public override ulong ReadUInt64()
+		{
+			ulong num = 0;
+			int shift = 0;
+			while (shift < 64) {
+				byte b = this.ReadByte();
+				num |= (ulong)(b & 127) << shift;
+				shift += 7;
+				if ((b & 128) == 0) {
+					return num;
+				}
+			}
+			throw new FormatException("Invalid 7-bit int64");
+		}
+	}
+
+	/// <summary>
+	/// A binary writer that encodes all integers as 7-bit-encoded-ints.
+	/// </summary>
+	public sealed class BinaryWriterWith7BitEncodedInts : BinaryWriter
+	{
+		public BinaryWriterWith7BitEncodedInts(Stream stream) : base(stream)
+		{
+		}
+		
+		public override void Write(short value)
+		{
+			base.Write7BitEncodedInt(unchecked((ushort)value));
+		}
+		
+		[CLSCompliant(false)]
+		public override void Write(ushort value)
+		{
+			base.Write7BitEncodedInt(value);
+		}
+		
+		public override void Write(int value)
+		{
+			base.Write7BitEncodedInt(value);
+		}
+		
+		[CLSCompliant(false)]
+		public override void Write(uint value)
+		{
+			base.Write7BitEncodedInt(unchecked((int)value));
+		}
+		
+		public override void Write(long value)
+		{
+			this.Write(unchecked((ulong)value));
+		}
+		
+		[CLSCompliant(false)]
+		public override void Write(ulong value)
+		{
+			while (value >= 128) {
+				this.Write(unchecked((byte)(value | 128u)));
+				value >>= 7;
+			}
+			this.Write(unchecked((byte)value));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/BitVector16.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/BitVector16.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/BitVector16.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Holds 16 boolean values.
+	/// </summary>
+	[Serializable]
+	[CLSCompliant(false)]
+	public struct BitVector16 : IEquatable<BitVector16>
+	{
+		ushort data;
+		
+		public bool this[ushort mask] {
+			get { return (data & mask) != 0; }
+			set {
+				if (value)
+					data |= mask;
+				else
+					data &= unchecked((ushort)~mask);
+			}
+		}
+		
+		public ushort Data {
+			get { return data; }
+			set { data = value; }
+		}
+		
+		#region Equals and GetHashCode implementation
+		public override bool Equals(object obj)
+		{
+			if (obj is BitVector16)
+				return Equals((BitVector16)obj); // use Equals method below
+			else
+				return false;
+		}
+		
+		public bool Equals(BitVector16 other)
+		{
+			return this.data == other.data;
+		}
+		
+		public override int GetHashCode()
+		{
+			return data;
+		}
+		
+		public static bool operator ==(BitVector16 left, BitVector16 right)
+		{
+			return left.data == right.data;
+		}
+		
+		public static bool operator !=(BitVector16 left, BitVector16 right)
+		{
+			return left.data != right.data;
+		}
+		#endregion
+		
+		public override string ToString()
+		{
+			return data.ToString("x4", CultureInfo.InvariantCulture);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/BusyManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/BusyManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/BusyManager.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// This class is used to prevent stack overflows by representing a 'busy' flag
+	/// that prevents reentrance when another call is running.
+	/// However, using a simple 'bool busy' is not thread-safe, so we use a
+	/// thread-static BusyManager.
+	/// </summary>
+	public static class BusyManager
+	{
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible",
+		                                                 Justification = "Should always be used with 'var'")]
+		public struct BusyLock : IDisposable
+		{
+			public static readonly BusyLock Failed = new BusyLock(null);
+			
+			readonly List<object> objectList;
+			
+			internal BusyLock(List<object> objectList)
+			{
+				this.objectList = objectList;
+			}
+			
+			public bool Success {
+				get { return objectList != null; }
+			}
+			
+			public void Dispose()
+			{
+				if (objectList != null) {
+					objectList.RemoveAt(objectList.Count - 1);
+				}
+			}
+		}
+		
+		[ThreadStatic] static List<object> _activeObjects;
+		
+		public static BusyLock Enter(object obj)
+		{
+			List<object> activeObjects = _activeObjects;
+			if (activeObjects == null)
+				activeObjects = _activeObjects = new List<object>();
+			for (int i = 0; i < activeObjects.Count; i++) {
+				if (activeObjects[i] == obj)
+					return BusyLock.Failed;
+			}
+			activeObjects.Add(obj);
+			return new BusyLock(activeObjects);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CSharpPrimitiveCast.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CSharpPrimitiveCast.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CSharpPrimitiveCast.cs	(revision 11807)
@@ -0,0 +1,431 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Static helper method for converting between primitive types.
+	/// </summary>
+	public static class CSharpPrimitiveCast
+	{
+		/// <summary>
+		/// Performs a conversion between primitive types.
+		/// Unfortunately we cannot use Convert.ChangeType because it has different semantics
+		/// (e.g. rounding behavior for floats, overflow, etc.), so we write down every possible primitive C# cast
+		/// and let the compiler figure out the exact semantics.
+		/// And we have to do everything twice, once in a checked-block, once in an unchecked-block.
+		/// </summary>
+		/// <exception cref="OverflowException">Overflow checking is enabled and an overflow occurred.</exception>
+		/// <exception cref="InvalidCastException">The cast is invalid, e.g. casting a boolean to an integer.</exception>
+		public static object Cast(TypeCode targetType, object input, bool checkForOverflow)
+		{
+			if (input == null)
+				return null;
+			if (checkForOverflow)
+				return CSharpPrimitiveCastChecked(targetType, input);
+			else
+				return CSharpPrimitiveCastUnchecked(targetType, input);
+		}
+		
+		static object CSharpPrimitiveCastChecked(TypeCode targetType, object input)
+		{
+			checked {
+				TypeCode sourceType = Type.GetTypeCode(input.GetType());
+				if (sourceType == targetType)
+					return input;
+				switch (targetType) {
+					case TypeCode.Char:
+						switch (sourceType) {
+								case TypeCode.SByte:   return (char)(sbyte)input;
+								case TypeCode.Byte:    return (char)(byte)input;
+								case TypeCode.Int16:   return (char)(short)input;
+								case TypeCode.UInt16:  return (char)(ushort)input;
+								case TypeCode.Int32:   return (char)(int)input;
+								case TypeCode.UInt32:  return (char)(uint)input;
+								case TypeCode.Int64:   return (char)(long)input;
+								case TypeCode.UInt64:  return (char)(ulong)input;
+								case TypeCode.Single:  return (char)(float)input;
+								case TypeCode.Double:  return (char)(double)input;
+								case TypeCode.Decimal: return (char)(decimal)input;
+						}
+						break;
+					case TypeCode.SByte:
+						switch (sourceType) {
+								case TypeCode.Char:    return (sbyte)(char)input;
+								case TypeCode.Byte:    return (sbyte)(byte)input;
+								case TypeCode.Int16:   return (sbyte)(short)input;
+								case TypeCode.UInt16:  return (sbyte)(ushort)input;
+								case TypeCode.Int32:   return (sbyte)(int)input;
+								case TypeCode.UInt32:  return (sbyte)(uint)input;
+								case TypeCode.Int64:   return (sbyte)(long)input;
+								case TypeCode.UInt64:  return (sbyte)(ulong)input;
+								case TypeCode.Single:  return (sbyte)(float)input;
+								case TypeCode.Double:  return (sbyte)(double)input;
+								case TypeCode.Decimal: return (sbyte)(decimal)input;
+						}
+						break;
+					case TypeCode.Byte:
+						switch (sourceType) {
+								case TypeCode.Char:    return (byte)(char)input;
+								case TypeCode.SByte:   return (byte)(sbyte)input;
+								case TypeCode.Int16:   return (byte)(short)input;
+								case TypeCode.UInt16:  return (byte)(ushort)input;
+								case TypeCode.Int32:   return (byte)(int)input;
+								case TypeCode.UInt32:  return (byte)(uint)input;
+								case TypeCode.Int64:   return (byte)(long)input;
+								case TypeCode.UInt64:  return (byte)(ulong)input;
+								case TypeCode.Single:  return (byte)(float)input;
+								case TypeCode.Double:  return (byte)(double)input;
+								case TypeCode.Decimal: return (byte)(decimal)input;
+						}
+						break;
+					case TypeCode.Int16:
+						switch (sourceType) {
+								case TypeCode.Char:    return (short)(char)input;
+								case TypeCode.SByte:   return (short)(sbyte)input;
+								case TypeCode.Byte:    return (short)(byte)input;
+								case TypeCode.UInt16:  return (short)(ushort)input;
+								case TypeCode.Int32:   return (short)(int)input;
+								case TypeCode.UInt32:  return (short)(uint)input;
+								case TypeCode.Int64:   return (short)(long)input;
+								case TypeCode.UInt64:  return (short)(ulong)input;
+								case TypeCode.Single:  return (short)(float)input;
+								case TypeCode.Double:  return (short)(double)input;
+								case TypeCode.Decimal: return (short)(decimal)input;
+						}
+						break;
+					case TypeCode.UInt16:
+						switch (sourceType) {
+								case TypeCode.Char:    return (ushort)(char)input;
+								case TypeCode.SByte:   return (ushort)(sbyte)input;
+								case TypeCode.Byte:    return (ushort)(byte)input;
+								case TypeCode.Int16:   return (ushort)(short)input;
+								case TypeCode.Int32:   return (ushort)(int)input;
+								case TypeCode.UInt32:  return (ushort)(uint)input;
+								case TypeCode.Int64:   return (ushort)(long)input;
+								case TypeCode.UInt64:  return (ushort)(ulong)input;
+								case TypeCode.Single:  return (ushort)(float)input;
+								case TypeCode.Double:  return (ushort)(double)input;
+								case TypeCode.Decimal: return (ushort)(decimal)input;
+						}
+						break;
+					case TypeCode.Int32:
+						switch (sourceType) {
+								case TypeCode.Char:    return (int)(char)input;
+								case TypeCode.SByte:   return (int)(sbyte)input;
+								case TypeCode.Byte:    return (int)(byte)input;
+								case TypeCode.Int16:   return (int)(short)input;
+								case TypeCode.UInt16:  return (int)(ushort)input;
+								case TypeCode.UInt32:  return (int)(uint)input;
+								case TypeCode.Int64:   return (int)(long)input;
+								case TypeCode.UInt64:  return (int)(ulong)input;
+								case TypeCode.Single:  return (int)(float)input;
+								case TypeCode.Double:  return (int)(double)input;
+								case TypeCode.Decimal: return (int)(decimal)input;
+						}
+						break;
+					case TypeCode.UInt32:
+						switch (sourceType) {
+								case TypeCode.Char:    return (uint)(char)input;
+								case TypeCode.SByte:   return (uint)(sbyte)input;
+								case TypeCode.Byte:    return (uint)(byte)input;
+								case TypeCode.Int16:   return (uint)(short)input;
+								case TypeCode.UInt16:  return (uint)(ushort)input;
+								case TypeCode.Int32:   return (uint)(int)input;
+								case TypeCode.Int64:   return (uint)(long)input;
+								case TypeCode.UInt64:  return (uint)(ulong)input;
+								case TypeCode.Single:  return (uint)(float)input;
+								case TypeCode.Double:  return (uint)(double)input;
+								case TypeCode.Decimal: return (uint)(decimal)input;
+						}
+						break;
+					case TypeCode.Int64:
+						switch (sourceType) {
+								case TypeCode.Char:    return (long)(char)input;
+								case TypeCode.SByte:   return (long)(sbyte)input;
+								case TypeCode.Byte:    return (long)(byte)input;
+								case TypeCode.Int16:   return (long)(short)input;
+								case TypeCode.UInt16:  return (long)(ushort)input;
+								case TypeCode.Int32:   return (long)(int)input;
+								case TypeCode.UInt32:  return (long)(uint)input;
+								case TypeCode.UInt64:  return (long)(ulong)input;
+								case TypeCode.Single:  return (long)(float)input;
+								case TypeCode.Double:  return (long)(double)input;
+								case TypeCode.Decimal: return (long)(decimal)input;
+						}
+						break;
+					case TypeCode.UInt64:
+						switch (sourceType) {
+								case TypeCode.Char:    return (ulong)(char)input;
+								case TypeCode.SByte:   return (ulong)(sbyte)input;
+								case TypeCode.Byte:    return (ulong)(byte)input;
+								case TypeCode.Int16:   return (ulong)(short)input;
+								case TypeCode.UInt16:  return (ulong)(ushort)input;
+								case TypeCode.Int32:   return (ulong)(int)input;
+								case TypeCode.UInt32:  return (ulong)(uint)input;
+								case TypeCode.Int64:   return (ulong)(long)input;
+								case TypeCode.Single:  return (ulong)(float)input;
+								case TypeCode.Double:  return (ulong)(double)input;
+								case TypeCode.Decimal: return (ulong)(decimal)input;
+						}
+						break;
+					case TypeCode.Single:
+						switch (sourceType) {
+								case TypeCode.Char:    return (float)(char)input;
+								case TypeCode.SByte:   return (float)(sbyte)input;
+								case TypeCode.Byte:    return (float)(byte)input;
+								case TypeCode.Int16:   return (float)(short)input;
+								case TypeCode.UInt16:  return (float)(ushort)input;
+								case TypeCode.Int32:   return (float)(int)input;
+								case TypeCode.UInt32:  return (float)(uint)input;
+								case TypeCode.Int64:   return (float)(long)input;
+								case TypeCode.UInt64:  return (float)(ulong)input;
+								case TypeCode.Double:  return (float)(double)input;
+								case TypeCode.Decimal: return (float)(decimal)input;
+						}
+						break;
+					case TypeCode.Double:
+						switch (sourceType) {
+								case TypeCode.Char:    return (double)(char)input;
+								case TypeCode.SByte:   return (double)(sbyte)input;
+								case TypeCode.Byte:    return (double)(byte)input;
+								case TypeCode.Int16:   return (double)(short)input;
+								case TypeCode.UInt16:  return (double)(ushort)input;
+								case TypeCode.Int32:   return (double)(int)input;
+								case TypeCode.UInt32:  return (double)(uint)input;
+								case TypeCode.Int64:   return (double)(long)input;
+								case TypeCode.UInt64:  return (double)(ulong)input;
+								case TypeCode.Single:  return (double)(float)input;
+								case TypeCode.Decimal: return (double)(decimal)input;
+						}
+						break;
+					case TypeCode.Decimal:
+						switch (sourceType) {
+								case TypeCode.Char:    return (decimal)(char)input;
+								case TypeCode.SByte:   return (decimal)(sbyte)input;
+								case TypeCode.Byte:    return (decimal)(byte)input;
+								case TypeCode.Int16:   return (decimal)(short)input;
+								case TypeCode.UInt16:  return (decimal)(ushort)input;
+								case TypeCode.Int32:   return (decimal)(int)input;
+								case TypeCode.UInt32:  return (decimal)(uint)input;
+								case TypeCode.Int64:   return (decimal)(long)input;
+								case TypeCode.UInt64:  return (decimal)(ulong)input;
+								case TypeCode.Single:  return (decimal)(float)input;
+								case TypeCode.Double:  return (decimal)(double)input;
+						}
+						break;
+				}
+				throw new InvalidCastException("Cast from " + sourceType + " to " + targetType + "not supported.");
+			}
+		}
+		
+		static object CSharpPrimitiveCastUnchecked(TypeCode targetType, object input)
+		{
+			unchecked {
+				TypeCode sourceType = Type.GetTypeCode(input.GetType());
+				if (sourceType == targetType)
+					return input;
+				switch (targetType) {
+					case TypeCode.Char:
+						switch (sourceType) {
+								case TypeCode.SByte:   return (char)(sbyte)input;
+								case TypeCode.Byte:    return (char)(byte)input;
+								case TypeCode.Int16:   return (char)(short)input;
+								case TypeCode.UInt16:  return (char)(ushort)input;
+								case TypeCode.Int32:   return (char)(int)input;
+								case TypeCode.UInt32:  return (char)(uint)input;
+								case TypeCode.Int64:   return (char)(long)input;
+								case TypeCode.UInt64:  return (char)(ulong)input;
+								case TypeCode.Single:  return (char)(float)input;
+								case TypeCode.Double:  return (char)(double)input;
+								case TypeCode.Decimal: return (char)(decimal)input;
+						}
+						break;
+					case TypeCode.SByte:
+						switch (sourceType) {
+								case TypeCode.Char:    return (sbyte)(char)input;
+								case TypeCode.Byte:    return (sbyte)(byte)input;
+								case TypeCode.Int16:   return (sbyte)(short)input;
+								case TypeCode.UInt16:  return (sbyte)(ushort)input;
+								case TypeCode.Int32:   return (sbyte)(int)input;
+								case TypeCode.UInt32:  return (sbyte)(uint)input;
+								case TypeCode.Int64:   return (sbyte)(long)input;
+								case TypeCode.UInt64:  return (sbyte)(ulong)input;
+								case TypeCode.Single:  return (sbyte)(float)input;
+								case TypeCode.Double:  return (sbyte)(double)input;
+								case TypeCode.Decimal: return (sbyte)(decimal)input;
+						}
+						break;
+					case TypeCode.Byte:
+						switch (sourceType) {
+								case TypeCode.Char:    return (byte)(char)input;
+								case TypeCode.SByte:   return (byte)(sbyte)input;
+								case TypeCode.Int16:   return (byte)(short)input;
+								case TypeCode.UInt16:  return (byte)(ushort)input;
+								case TypeCode.Int32:   return (byte)(int)input;
+								case TypeCode.UInt32:  return (byte)(uint)input;
+								case TypeCode.Int64:   return (byte)(long)input;
+								case TypeCode.UInt64:  return (byte)(ulong)input;
+								case TypeCode.Single:  return (byte)(float)input;
+								case TypeCode.Double:  return (byte)(double)input;
+								case TypeCode.Decimal: return (byte)(decimal)input;
+						}
+						break;
+					case TypeCode.Int16:
+						switch (sourceType) {
+								case TypeCode.Char:    return (short)(char)input;
+								case TypeCode.SByte:   return (short)(sbyte)input;
+								case TypeCode.Byte:    return (short)(byte)input;
+								case TypeCode.UInt16:  return (short)(ushort)input;
+								case TypeCode.Int32:   return (short)(int)input;
+								case TypeCode.UInt32:  return (short)(uint)input;
+								case TypeCode.Int64:   return (short)(long)input;
+								case TypeCode.UInt64:  return (short)(ulong)input;
+								case TypeCode.Single:  return (short)(float)input;
+								case TypeCode.Double:  return (short)(double)input;
+								case TypeCode.Decimal: return (short)(decimal)input;
+						}
+						break;
+					case TypeCode.UInt16:
+						switch (sourceType) {
+								case TypeCode.Char:    return (ushort)(char)input;
+								case TypeCode.SByte:   return (ushort)(sbyte)input;
+								case TypeCode.Byte:    return (ushort)(byte)input;
+								case TypeCode.Int16:   return (ushort)(short)input;
+								case TypeCode.Int32:   return (ushort)(int)input;
+								case TypeCode.UInt32:  return (ushort)(uint)input;
+								case TypeCode.Int64:   return (ushort)(long)input;
+								case TypeCode.UInt64:  return (ushort)(ulong)input;
+								case TypeCode.Single:  return (ushort)(float)input;
+								case TypeCode.Double:  return (ushort)(double)input;
+								case TypeCode.Decimal: return (ushort)(decimal)input;
+						}
+						break;
+					case TypeCode.Int32:
+						switch (sourceType) {
+								case TypeCode.Char:    return (int)(char)input;
+								case TypeCode.SByte:   return (int)(sbyte)input;
+								case TypeCode.Byte:    return (int)(byte)input;
+								case TypeCode.Int16:   return (int)(short)input;
+								case TypeCode.UInt16:  return (int)(ushort)input;
+								case TypeCode.UInt32:  return (int)(uint)input;
+								case TypeCode.Int64:   return (int)(long)input;
+								case TypeCode.UInt64:  return (int)(ulong)input;
+								case TypeCode.Single:  return (int)(float)input;
+								case TypeCode.Double:  return (int)(double)input;
+								case TypeCode.Decimal: return (int)(decimal)input;
+						}
+						break;
+					case TypeCode.UInt32:
+						switch (sourceType) {
+								case TypeCode.Char:    return (uint)(char)input;
+								case TypeCode.SByte:   return (uint)(sbyte)input;
+								case TypeCode.Byte:    return (uint)(byte)input;
+								case TypeCode.Int16:   return (uint)(short)input;
+								case TypeCode.UInt16:  return (uint)(ushort)input;
+								case TypeCode.Int32:   return (uint)(int)input;
+								case TypeCode.Int64:   return (uint)(long)input;
+								case TypeCode.UInt64:  return (uint)(ulong)input;
+								case TypeCode.Single:  return (uint)(float)input;
+								case TypeCode.Double:  return (uint)(double)input;
+								case TypeCode.Decimal: return (uint)(decimal)input;
+						}
+						break;
+					case TypeCode.Int64:
+						switch (sourceType) {
+								case TypeCode.Char:    return (long)(char)input;
+								case TypeCode.SByte:   return (long)(sbyte)input;
+								case TypeCode.Byte:    return (long)(byte)input;
+								case TypeCode.Int16:   return (long)(short)input;
+								case TypeCode.UInt16:  return (long)(ushort)input;
+								case TypeCode.Int32:   return (long)(int)input;
+								case TypeCode.UInt32:  return (long)(uint)input;
+								case TypeCode.UInt64:  return (long)(ulong)input;
+								case TypeCode.Single:  return (long)(float)input;
+								case TypeCode.Double:  return (long)(double)input;
+								case TypeCode.Decimal: return (long)(decimal)input;
+						}
+						break;
+					case TypeCode.UInt64:
+						switch (sourceType) {
+								case TypeCode.Char:    return (ulong)(char)input;
+								case TypeCode.SByte:   return (ulong)(sbyte)input;
+								case TypeCode.Byte:    return (ulong)(byte)input;
+								case TypeCode.Int16:   return (ulong)(short)input;
+								case TypeCode.UInt16:  return (ulong)(ushort)input;
+								case TypeCode.Int32:   return (ulong)(int)input;
+								case TypeCode.UInt32:  return (ulong)(uint)input;
+								case TypeCode.Int64:   return (ulong)(long)input;
+								case TypeCode.Single:  return (ulong)(float)input;
+								case TypeCode.Double:  return (ulong)(double)input;
+								case TypeCode.Decimal: return (ulong)(decimal)input;
+						}
+						break;
+					case TypeCode.Single:
+						switch (sourceType) {
+								case TypeCode.Char:    return (float)(char)input;
+								case TypeCode.SByte:   return (float)(sbyte)input;
+								case TypeCode.Byte:    return (float)(byte)input;
+								case TypeCode.Int16:   return (float)(short)input;
+								case TypeCode.UInt16:  return (float)(ushort)input;
+								case TypeCode.Int32:   return (float)(int)input;
+								case TypeCode.UInt32:  return (float)(uint)input;
+								case TypeCode.Int64:   return (float)(long)input;
+								case TypeCode.UInt64:  return (float)(ulong)input;
+								case TypeCode.Double:  return (float)(double)input;
+								case TypeCode.Decimal: return (float)(decimal)input;
+						}
+						break;
+					case TypeCode.Double:
+						switch (sourceType) {
+								case TypeCode.Char:    return (double)(char)input;
+								case TypeCode.SByte:   return (double)(sbyte)input;
+								case TypeCode.Byte:    return (double)(byte)input;
+								case TypeCode.Int16:   return (double)(short)input;
+								case TypeCode.UInt16:  return (double)(ushort)input;
+								case TypeCode.Int32:   return (double)(int)input;
+								case TypeCode.UInt32:  return (double)(uint)input;
+								case TypeCode.Int64:   return (double)(long)input;
+								case TypeCode.UInt64:  return (double)(ulong)input;
+								case TypeCode.Single:  return (double)(float)input;
+								case TypeCode.Decimal: return (double)(decimal)input;
+						}
+						break;
+					case TypeCode.Decimal:
+						switch (sourceType) {
+								case TypeCode.Char:    return (decimal)(char)input;
+								case TypeCode.SByte:   return (decimal)(sbyte)input;
+								case TypeCode.Byte:    return (decimal)(byte)input;
+								case TypeCode.Int16:   return (decimal)(short)input;
+								case TypeCode.UInt16:  return (decimal)(ushort)input;
+								case TypeCode.Int32:   return (decimal)(int)input;
+								case TypeCode.UInt32:  return (decimal)(uint)input;
+								case TypeCode.Int64:   return (decimal)(long)input;
+								case TypeCode.UInt64:  return (decimal)(ulong)input;
+								case TypeCode.Single:  return (decimal)(float)input;
+								case TypeCode.Double:  return (decimal)(double)input;
+						}
+						break;
+				}
+				throw new InvalidCastException("Cast from " + sourceType + " to " + targetType + " not supported.");
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CacheManager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CacheManager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CacheManager.cs	(revision 11807)
@@ -0,0 +1,59 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Allows caching values for a specific compilation.
+	/// A CacheManager consists of a for shared instances (shared among all threads working with that resolve context).
+	/// </summary>
+	/// <remarks>This class is thread-safe</remarks>
+	public sealed class CacheManager
+	{
+		readonly ConcurrentDictionary<object, object> sharedDict = new ConcurrentDictionary<object, object>(ReferenceComparer.Instance);
+		// There used to be a thread-local dictionary here, but I removed it as it was causing memory
+		// leaks in some use cases.
+		
+		public object GetShared(object key)
+		{
+			object value;
+			sharedDict.TryGetValue(key, out value);
+			return value;
+		}
+		
+		public object GetOrAddShared(object key, Func<object, object> valueFactory)
+		{
+			return sharedDict.GetOrAdd(key, valueFactory);
+		}
+		
+		public object GetOrAddShared(object key, object value)
+		{
+			return sharedDict.GetOrAdd(key, value);
+		}
+		
+		public void SetShared(object key, object value)
+		{
+			sharedDict[key] = value;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CallbackOnDispose.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CallbackOnDispose.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CallbackOnDispose.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Invokes an action when it is disposed.
+	/// </summary>
+	/// <remarks>
+	/// This class ensures the callback is invoked at most once,
+	/// even when Dispose is called on multiple threads.
+	/// </remarks>
+	public sealed class CallbackOnDispose : IDisposable
+	{
+		Action action;
+		
+		public CallbackOnDispose(Action action)
+		{
+			if (action == null)
+				throw new ArgumentNullException("action");
+			this.action = action;
+		}
+		
+		public void Dispose()
+		{
+			Action a = Interlocked.Exchange(ref action, null);
+			if (a != null) {
+				a();
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ComparableList.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ComparableList.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ComparableList.cs	(revision 11807)
@@ -0,0 +1,166 @@
+//
+// NullValueAnalysisTests.cs
+//
+// Author:
+//       LuÃ­s Reis <luiscubal@gmail.com
+//
+// Copyright (c) 2013 LuÃ­s Reis
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// A list that can be compared to other ComparableLists for equality.
+	/// Can not be used to store null values.
+	/// </summary>
+	public sealed class ComparableList<T> : IList<T>, IEquatable<ComparableList<T>>
+	{
+		List<T> elements;
+
+		public ComparableList()
+		{
+			elements = new List<T> ();
+		}
+
+		public ComparableList(IEnumerable<T> values)
+		{
+			elements = new List<T> (values);
+		}
+
+		public int IndexOf (T item)
+		{
+			if (item == null)
+				throw new ArgumentNullException ("item");
+			return elements.IndexOf (item);
+		}
+
+		public void Insert (int index, T item)
+		{
+			elements.Insert (index, item);
+		}
+
+		public void RemoveAt (int index)
+		{
+			elements.RemoveAt (index);
+		}
+
+		public T this [int index] {
+			get {
+				return elements [index];
+			}
+			set {
+				elements [index] = value;
+			}
+		}
+
+		public void Add (T item)
+		{
+			elements.Add (item);
+		}
+
+		public void Clear ()
+		{
+			elements.Clear ();
+		}
+
+		public bool Contains (T item)
+		{
+			return elements.Contains (item);
+		}
+
+		public void CopyTo (T[] array, int arrayIndex)
+		{
+			elements.CopyTo (array, arrayIndex);
+		}
+
+		public bool Remove (T item)
+		{
+			return elements.Remove (item);
+		}
+
+		public int Count {
+			get {
+				return elements.Count;
+			}
+		}
+
+		public bool IsReadOnly {
+			get {
+				return false;
+			}
+		}
+
+		public IEnumerator<T> GetEnumerator()
+		{
+			return elements.GetEnumerator();
+		}
+
+		IEnumerator IEnumerable.GetEnumerator()
+		{
+			return GetEnumerator ();
+		}
+
+		public override bool Equals (object obj)
+		{
+			return Equals (obj as ComparableList<T>);
+		}
+
+		public bool Equals (ComparableList<T> obj)
+		{
+			if (obj == null || Count != obj.Count) {
+				return false;
+			}
+
+			for (int index = 0; index < Count; ++index) {
+				if (!this [index].Equals(obj [index])) {
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		public override int GetHashCode ()
+		{
+			int hash = 19;
+			foreach (var item in this) {
+				unchecked {
+					hash *= 31;
+					hash += item.GetHashCode();
+				}
+			}
+			return hash;
+		}
+
+		public static bool operator==(ComparableList<T> item1, ComparableList<T> item2) {
+			if (object.ReferenceEquals (item1, null))
+				return object.ReferenceEquals (item2, null);
+			return item1.Equals (item2);
+		}
+
+		public static bool operator!=(ComparableList<T> item1, ComparableList<T> item2) {
+			return !(item1 == item2);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/CompositeFormatStringParser.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/CompositeFormatStringParser.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/CompositeFormatStringParser.cs	(revision 11807)
@@ -0,0 +1,343 @@
+//
+// CompositeFormatStringParser.cs
+//
+// Authors:
+//   Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Composite format string parser.
+	/// </summary>
+	/// <remarks>
+	/// Implements a complete parser for valid strings as well as
+	/// error reporting and best-effort parsing for invalid strings.
+	/// </remarks>		
+	public class CompositeFormatStringParser
+	{
+
+		public CompositeFormatStringParser ()
+		{
+			errors = new List<IFormatStringError> ();
+		}
+
+		/// <summary>
+		/// Parse the specified format string.
+		/// </summary>
+		/// <param name='format'>
+		/// The format string.
+		/// </param>
+		public FormatStringParseResult Parse (string format)
+		{
+			if (format == null)
+				throw new ArgumentNullException ("format");
+
+			var result = new FormatStringParseResult();
+
+			// Format string syntax: http://msdn.microsoft.com/en-us/library/txafckwd.aspx
+			int textStart = 0;
+			var length = format.Length;
+			for (int i = 0; i < length; i++) {
+				// Get fixed text
+				GetText (format, ref i);
+
+				if (i < format.Length && format [i] == '{') {
+					int formatItemStart = i;
+					int index;
+					int? alignment;
+					string argumentFormat;
+					var textSegmentErrors = new List<IFormatStringError>(GetErrors());
+
+					// Try to parse the parts of the format item
+					++i;
+					index = ParseIndex (format, ref i);
+					CheckForMissingEndBrace (format, i, length);
+
+					alignment = ParseAlignment (format, ref i, length);
+					CheckForMissingEndBrace (format, i, length);
+
+					argumentFormat = ParseSubFormatString (format, ref i, length);
+					CheckForMissingEndBrace (format, i, length);
+
+					// Check what we parsed
+					if (i == formatItemStart + 1 && (i == length || (i < length && format[i] != '}'))) {
+						// There were no format item after all, this was just an
+						// unescaped left brace, or the initial brace of an escape sequence
+						SetErrors(textSegmentErrors);
+						if (i >= length || format[i] != '{') {
+							AddError (new DefaultFormatStringError {
+								Message = "Unescaped '{'",
+								StartLocation = formatItemStart,
+								EndLocation = formatItemStart + 1,
+								OriginalText = "{",
+								SuggestedReplacementText = "{{"
+							});
+						}
+						continue;
+					}
+
+					if (formatItemStart - textStart > 0) {
+						// We have parsed a format item, end the text segment
+						var textSegment = new TextSegment (UnEscape (format.Substring (textStart, formatItemStart - textStart)));
+						textSegment.Errors = textSegmentErrors;
+						result.Segments.Add (textSegment);
+					}
+					
+					// Unclosed format items in fixed text advances i one step too far
+					if (i < length && format [i] != '}')
+						--i;
+
+					// i may actually point outside of format if there is a syntactical error
+					// if that happens, we want the last position
+					var endLocation = Math.Min (length, i + 1);
+					result.Segments.Add (new FormatItem (index, alignment, argumentFormat) {
+						StartLocation = formatItemStart,
+						EndLocation = endLocation,
+						Errors = GetErrors ()
+					});
+					ClearErrors ();
+
+					// The next potential text segment starts after this format item
+					textStart = i + 1;
+				}
+			}
+			// Handle remaining text
+			if (textStart < length) {
+				var textSegment = new TextSegment (UnEscape (format.Substring (textStart)), textStart);
+				textSegment.Errors = GetErrors();
+				result.Segments.Add (textSegment);
+
+			}
+			return result;
+		}
+
+		int ParseIndex (string format, ref int i)
+		{
+			int parsedCharacters;
+			int? maybeIndex = GetAndCheckNumber (format, ",:}", ref i, i, out parsedCharacters);
+			if (parsedCharacters == 0) {
+				AddError (new DefaultFormatStringError {
+					StartLocation = i,
+					EndLocation = i,
+					Message = "Missing index",
+					OriginalText = "",
+					SuggestedReplacementText = "0"
+				});
+			}
+			return maybeIndex ?? 0;
+		}
+
+		int? ParseAlignment(string format, ref int i, int length)
+		{
+			if (i < length && format [i] == ',') {
+				int alignmentBegin = i;
+				++i;
+				while (i < length && char.IsWhiteSpace(format [i]))
+					++i;
+
+				int parsedCharacters;
+				var number = GetAndCheckNumber (format, ",:}", ref i, alignmentBegin + 1, out parsedCharacters);
+				if (parsedCharacters == 0) {
+					AddError (new DefaultFormatStringError {
+						StartLocation = i,
+						EndLocation = i,
+						Message = "Missing alignment",
+						OriginalText = "",
+						SuggestedReplacementText = "0"
+					});
+				}
+				return number ?? 0;
+			}
+			return null;
+		}
+
+		string ParseSubFormatString(string format, ref int i, int length)
+		{
+			if (i < length && format [i] == ':') {
+				++i;
+				int begin = i;
+				GetText(format, ref i, "", true);
+				var escaped = format.Substring (begin, i - begin);
+				return UnEscape (escaped);
+			}
+			return null;
+		}
+
+		void CheckForMissingEndBrace (string format, int i, int length)
+		{
+			if (i == length) {
+				int j;
+				for (j = i - 1; format[j] == '}'; j--);
+				var oddEndBraceCount = (i - j) % 2 == 1;
+				if (oddEndBraceCount) {
+					AddMissingEndBraceError(i, i, "Missing '}'", "");
+				}
+				return;
+			}
+			return;
+		}
+		
+		void GetText (string format, ref int index, string delimiters = "", bool allowEscape = false)
+		{
+			while (index < format.Length) {
+				if (format [index] == '{' || format[index] == '}') {
+					if (index + 1 < format.Length && format [index + 1] == format[index] && allowEscape)
+						++index;
+					else
+						break;
+				} else if (delimiters.Contains(format[index].ToString())) {
+					break;
+				}
+				++index;
+			};
+		}
+		
+		int? GetNumber (string format, ref int index)
+		{
+			if (format.Length == 0) {
+				return null;
+			}
+			int sum = 0;
+			int i = index;
+			bool positive = format [i] != '-';
+			if (!positive)
+				++i;
+			int numberStartIndex = i;
+			while (i < format.Length && format[i] >= '0' && format[i] <= '9') {
+				sum = 10 * sum + format [i] - '0';
+				++i;
+			}
+			if (i == numberStartIndex)
+				return null;
+
+			index = i;
+			return positive ? sum : -sum;
+		}
+
+		int? GetAndCheckNumber (string format, string delimiters, ref int index, int numberFieldStart, out int parsedCharacters)
+		{
+			int fieldIndex = index;
+			GetText (format, ref fieldIndex, delimiters);
+			int fieldEnd = fieldIndex;
+			var numberText = format.Substring(index, fieldEnd - index);
+			parsedCharacters = numberText.Length;
+			int numberLength = 0;
+			int? number = GetNumber (numberText, ref numberLength);
+			if (numberLength != parsedCharacters && fieldEnd < format.Length && delimiters.Contains (format [fieldEnd])) {
+				// Not the entire number field could be parsed
+				// The field actually ended as intended, so set the index to the end of the field
+				index = fieldEnd;
+				var suggestedNumber = (number ?? 0).ToString ();
+				AddInvalidNumberFormatError (numberFieldStart, format.Substring (numberFieldStart, index - numberFieldStart), suggestedNumber);
+			} else {
+				var endingChar = index + numberLength;
+				if (numberLength != parsedCharacters) {
+					// Not the entire number field could be parsed
+					// The field didn't end, it was cut off so we are missing an ending brace
+					index = endingChar;
+					AddMissingEndBraceError (index, index, "Missing ending '}'", "");
+				} else {
+					index = endingChar;
+				}
+			}
+			return number;
+		}
+
+		public static string UnEscape (string unEscaped)
+		{
+			return unEscaped.Replace ("{{", "{").Replace ("}}", "}");
+		}
+
+		IList<IFormatStringError> errors;
+		
+		bool hasMissingEndBrace = false;
+
+		void AddError (IFormatStringError error)
+		{
+			errors.Add (error);
+		}
+
+		void AddMissingEndBraceError(int start, int end, string message, string originalText)
+		{
+			// Only add a single missing end brace per format item
+			if (hasMissingEndBrace)
+				return;
+			AddError (new DefaultFormatStringError {
+				StartLocation = start,
+				EndLocation = end,
+				Message = message,
+				OriginalText = originalText,
+				SuggestedReplacementText = "}"
+			});
+			hasMissingEndBrace = true;
+		}
+
+		void AddInvalidNumberFormatError (int i, string number, string replacementText)
+		{
+			AddError (new DefaultFormatStringError {
+				StartLocation = i,
+				EndLocation = i + number.Length,
+				Message = string.Format ("Invalid number '{0}'", number),
+				OriginalText = number,
+				SuggestedReplacementText = replacementText
+			});
+		}
+
+		IList<IFormatStringError> GetErrors ()
+		{
+			return errors;
+		}
+		
+		void SetErrors (IList<IFormatStringError> errors)
+		{
+			this.errors = errors;
+		}
+
+		void ClearErrors ()
+		{
+			hasMissingEndBrace = false;
+			errors = new List<IFormatStringError> ();
+		}
+	}
+
+	public class FormatStringParseResult
+	{
+		public FormatStringParseResult()
+		{
+			Segments = new List<IFormatStringSegment>();
+		}
+
+		public IList<IFormatStringSegment> Segments { get; private set; }
+
+		public bool HasErrors
+		{
+			get {
+				return Segments.SelectMany(segment => segment.Errors).Any();
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/FormatItem.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/FormatItem.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/FormatItem.cs	(revision 11807)
@@ -0,0 +1,93 @@
+//
+// FormatItem.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public class FormatItem : FormatStringSegmentBase
+	{
+		public FormatItem (int index, int? alignment = null, string formatString = null)
+		{
+			Index = index;
+			Alignment = alignment;
+			FormatString = formatString;
+		}
+
+		public int Index { get; private set; }
+
+		public int? Alignment { get; private set; }
+
+		public string FormatString { get; private set; }
+
+		#region Equality
+		public override bool Equals (object obj)
+		{
+			if (obj == null)
+				return false;
+			if (obj.GetType () != typeof(FormatItem))
+				return false;
+			var other = (FormatItem)obj;
+				
+			return FieldsEquals (other);
+		}
+			
+		public bool Equals (FormatItem other)
+		{
+			if (other == null)
+				return false;
+				
+			return FieldsEquals (other);
+		}
+
+		bool FieldsEquals (FormatItem other)
+		{
+			return Index == other.Index &&
+				Alignment == other.Alignment &&
+				FormatString == other.FormatString &&
+				StartLocation == other.StartLocation &&
+				EndLocation == other.EndLocation;
+		}
+			
+		public override int GetHashCode ()
+		{
+			unchecked {
+				int hash = 23;
+				hash = hash * 37 + Index.GetHashCode ();
+				hash = hash * 37 + Alignment.GetHashCode ();
+				hash = hash * 37 + FormatString.GetHashCode ();
+				hash = hash * 37 + StartLocation.GetHashCode ();
+				hash = hash * 37 + EndLocation.GetHashCode ();
+				return hash;
+			}
+		}
+		#endregion
+
+		public override string ToString ()
+		{
+			return string.Format ("[FormatItem: Index={0}, Alignment={1}, FormatString={2}, StartLocation={3}, EndLocation={4}]", Index, Alignment, FormatString, StartLocation, EndLocation);
+		}
+	}
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/FormatStringSegmentBase.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/FormatStringSegmentBase.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/FormatStringSegmentBase.cs	(revision 11807)
@@ -0,0 +1,66 @@
+//
+// FormatStringSegmentBase.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Composite format string parser.
+	/// </summary>
+	/// <remarks>
+	/// Implements a complete parser for valid strings as well as
+	/// error reporting and best-effort parsing for invalid strings.
+	/// </remarks>		
+	public abstract class FormatStringSegmentBase : IFormatStringSegment
+	{
+		public FormatStringSegmentBase ()
+		{
+			Errors = new List<IFormatStringError> ();
+		}
+
+		#region IFormatStringSegment implementation
+		public int StartLocation { get; set; }
+
+		public int EndLocation { get; set; }
+
+		public bool HasErrors {
+			get {
+				return Errors.Any ();
+			}
+		}
+
+		public IList<IFormatStringError> Errors { get; set; }
+
+		IEnumerable<IFormatStringError> IFormatStringSegment.Errors {
+			get {
+				return Errors;
+			}
+		}
+		#endregion
+	}
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/IFormatStringError.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/IFormatStringError.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/IFormatStringError.cs	(revision 11807)
@@ -0,0 +1,68 @@
+//
+// IFormatStringError.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public interface IFormatStringError
+	{
+		int StartLocation { get; }
+
+		int EndLocation { get; }
+
+		string Message { get; }
+
+		string OriginalText { get; }
+
+		string SuggestedReplacementText { get; }
+	}
+
+	public class DefaultFormatStringError : IFormatStringError
+	{
+		public DefaultFormatStringError()
+		{
+			Message = "";
+			OriginalText = "";
+			SuggestedReplacementText = "";
+		}
+
+		#region IFormatStringError implementation
+		public int StartLocation { get; set; }
+		
+		public int EndLocation { get; set; }
+		
+		public string Message { get; set; }
+		
+		public string OriginalText { get; set; }
+		
+		public string SuggestedReplacementText { get; set; }
+		#endregion
+
+		public override string ToString ()
+		{
+			return string.Format ("[DefaultFormatStringError: StartLocation={0}, EndLocation={1}, Message={2}, OriginalText={3}, SuggestedReplacementText={4}]", StartLocation, EndLocation, Message, OriginalText, SuggestedReplacementText);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/IFormatStringSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/IFormatStringSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/IFormatStringSegment.cs	(revision 11807)
@@ -0,0 +1,48 @@
+//
+// IFormatStringSegment.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Composite format string parser.
+	/// </summary>
+	/// <remarks>
+	/// Implements a complete parser for valid strings as well as
+	/// error reporting and best-effort parsing for invalid strings.
+	/// </remarks>		
+	public interface IFormatStringSegment
+	{
+		int StartLocation { get; set; }
+
+		int EndLocation { get; set; }
+
+		bool HasErrors { get; }
+
+		IEnumerable<IFormatStringError> Errors { get; }
+	}
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/TextSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/TextSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/CompositeFormatStringParser/TextSegment.cs	(revision 11807)
@@ -0,0 +1,79 @@
+//
+// TextSegment.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public class TextSegment : FormatStringSegmentBase
+	{
+		public TextSegment (string text, int startLocation = 0, int? endLocation = null)
+		{
+			Text = text;
+			StartLocation = startLocation;
+			EndLocation = endLocation ?? startLocation + text.Length;
+		}
+
+		public string Text { get; set; }
+
+		#region Equality
+		public override bool Equals (object obj)
+		{
+			if (obj == null)
+				return false;
+			if (obj.GetType () != typeof(TextSegment))
+				return false;
+			var other = (TextSegment)obj;
+			
+			return Equals (Text, other.Text);
+		}
+		
+		public bool Equals (TextSegment other)
+		{
+			if (other == null)
+				return false;
+			
+			return Equals (Text, other.Text) &&
+				StartLocation == other.StartLocation &&
+				EndLocation == other.EndLocation;
+		}
+		
+		public override int GetHashCode ()
+		{
+			unchecked {
+				int hash = 23;
+				hash = hash * 37 + Text.GetHashCode ();
+				hash = hash * 37 + StartLocation.GetHashCode ();
+				hash = hash * 37 + EndLocation.GetHashCode ();
+				return hash;
+			}
+		}
+		#endregion
+
+		public override string ToString ()
+		{
+			return string.Format ("[TextSegment: Text={0}, StartLocation={1}, EndLocation={2}]", Text, StartLocation, EndLocation);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/EmptyList.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/EmptyList.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/EmptyList.cs	(revision 11807)
@@ -0,0 +1,118 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+
+namespace ICSharpCode.NRefactory
+{
+	[Serializable]
+	public sealed class EmptyList<T> : IList<T>, IEnumerator<T>
+		#if NET_4_5
+		, IReadOnlyList<T>
+		#endif
+	{
+		public static readonly EmptyList<T> Instance = new EmptyList<T>();
+		
+		private EmptyList() {}
+		
+		public T this[int index] {
+			get { throw new ArgumentOutOfRangeException("index"); }
+			set { throw new ArgumentOutOfRangeException("index"); }
+		}
+		
+		public int Count {
+			get { return 0; }
+		}
+		
+		bool ICollection<T>.IsReadOnly {
+			get { return true; }
+		}
+		
+		int IList<T>.IndexOf(T item)
+		{
+			return -1;
+		}
+		
+		void IList<T>.Insert(int index, T item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IList<T>.RemoveAt(int index)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<T>.Add(T item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<T>.Clear()
+		{
+		}
+		
+		bool ICollection<T>.Contains(T item)
+		{
+			return false;
+		}
+		
+		void ICollection<T>.CopyTo(T[] array, int arrayIndex)
+		{
+		}
+		
+		bool ICollection<T>.Remove(T item)
+		{
+			return false;
+		}
+		
+		IEnumerator<T> IEnumerable<T>.GetEnumerator()
+		{
+			return this;
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this;
+		}
+		
+		T IEnumerator<T>.Current {
+			get { return default(T); }
+		}
+		
+		object IEnumerator.Current {
+			get { return default(T); }
+		}
+		
+		void IDisposable.Dispose()
+		{
+		}
+		
+		bool IEnumerator.MoveNext()
+		{
+			return false;
+		}
+		
+		void IEnumerator.Reset()
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ExtensionMethods.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ExtensionMethods.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ExtensionMethods.cs	(revision 11807)
@@ -0,0 +1,44 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Contains extension methods for use within NRefactory.
+	/// </summary>
+	static class ExtensionMethods
+	{
+		public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> input)
+		{
+			foreach (T item in input)
+				target.Add(item);
+		}
+		
+		public static Predicate<T> And<T>(this Predicate<T> filter1, Predicate<T> filter2)
+		{
+			if (filter1 == null)
+				return filter2;
+			if (filter2 == null)
+				return filter1;
+			return m => filter1(m) && filter2(m);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/FastSerializer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/FastSerializer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/FastSerializer.cs	(revision 11807)
@@ -0,0 +1,1371 @@
+﻿// Copyright (c) 2011 Daniel Grunwald
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.Serialization;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public class FastSerializer
+	{
+		#region Properties
+		/// <summary>
+		/// Gets/Sets the serialization binder that is being used.
+		/// The default value is null, which will cause the FastSerializer to use the
+		/// full assembly and type names.
+		/// </summary>
+		public SerializationBinder SerializationBinder { get; set; }
+		
+		/// <summary>
+		/// Can be used to set several 'fixed' instances.
+		/// When serializing, such instances will not be included; and any references to a fixed instance
+		/// will be stored as the index in this array.
+		/// When deserializing, the same (or equivalent) instances must be specified, and the deserializer
+		/// will use them in place of the fixed instances.
+		/// </summary>
+		public object[] FixedInstances { get; set; }
+		#endregion
+		
+		#region Constants
+		const int magic = 0x71D28A5E;
+		
+		const byte Type_ReferenceType = 1;
+		const byte Type_ValueType = 2;
+		const byte Type_SZArray = 3;
+		const byte Type_ParameterizedType = 4;
+		#endregion
+		
+		#region Serialization
+		sealed class SerializationType
+		{
+			public readonly int ID;
+			public readonly Type Type;
+			
+			public SerializationType(int iD, Type type)
+			{
+				this.ID = iD;
+				this.Type = type;
+			}
+			
+			public ObjectScanner Scanner;
+			public ObjectWriter Writer;
+			public string TypeName;
+			public int AssemblyNameID;
+		}
+		
+		sealed class SerializationContext
+		{
+			readonly Dictionary<object, int> objectToID = new Dictionary<object, int>(ReferenceComparer.Instance);
+			readonly List<object> instances = new List<object>(); // index: object ID
+			readonly List<SerializationType> objectTypes = new List<SerializationType>(); // index: object ID
+			SerializationType stringType;
+			
+			readonly Dictionary<Type, SerializationType> typeMap = new Dictionary<Type, SerializationType>();
+			readonly List<SerializationType> types = new List<SerializationType>();
+			
+			readonly Dictionary<string, int> assemblyNameToID = new Dictionary<string, int>();
+			readonly List<string> assemblyNames = new List<string>();
+			
+			readonly FastSerializer fastSerializer;
+			public readonly BinaryWriter writer;
+			int fixedInstanceCount;
+			
+			internal SerializationContext(FastSerializer fastSerializer, BinaryWriter writer)
+			{
+				this.fastSerializer = fastSerializer;
+				this.writer = writer;
+				instances.Add(null); // use object ID 0 for null
+				objectTypes.Add(null);
+			}
+			
+			#region Scanning
+			public void MarkFixedInstances(object[] fixedInstances)
+			{
+				if (fixedInstances == null)
+					return;
+				foreach (object obj in fixedInstances) {
+					if (!objectToID.ContainsKey(obj)) {
+						objectToID.Add(obj, instances.Count);
+						instances.Add(obj);
+						fixedInstanceCount++;
+					}
+				}
+			}
+			
+			/// <summary>
+			/// Marks an instance for future scanning.
+			/// </summary>
+			public void Mark(object instance)
+			{
+				if (instance == null || objectToID.ContainsKey(instance))
+					return;
+				Log(" Mark {0}", instance.GetType().Name);
+				
+				objectToID.Add(instance, instances.Count);
+				instances.Add(instance);
+			}
+			
+			internal void Scan()
+			{
+				Log("Scanning...");
+				// starting from 1, because index 0 is null
+				// Also, do not scan any of the 'fixed instances'.
+				for (int i = 1 + fixedInstanceCount; i < instances.Count; i++) {
+					object instance = instances[i];
+					ISerializable serializable = instance as ISerializable;
+					Type type = instance.GetType();
+					Log("Scan #{0}: {1}", i, type.Name);
+					SerializationType sType = MarkType(type);
+					objectTypes.Add(sType);
+					if (serializable != null) {
+						SerializationInfo info = new SerializationInfo(type, fastSerializer.formatterConverter);
+						serializable.GetObjectData(info, fastSerializer.streamingContext);
+						instances[i] = info;
+						foreach (SerializationEntry entry in info) {
+							Mark(entry.Value);
+						}
+						sType.Writer = serializationInfoWriter;
+					} else {
+						ObjectScanner objectScanner = sType.Scanner;
+						if (objectScanner == null) {
+							objectScanner = fastSerializer.GetScanner(type);
+							sType.Scanner = objectScanner;
+							sType.Writer = fastSerializer.GetWriter(type);
+						}
+						objectScanner(this, instance);
+					}
+				}
+			}
+			#endregion
+			
+			#region Scan Types
+			SerializationType MarkType(Type type)
+			{
+				SerializationType sType;
+				if (!typeMap.TryGetValue(type, out sType)) {
+					string assemblyName = null;
+					string typeName = null;
+					if (type.HasElementType) {
+						Debug.Assert(type.IsArray);
+						MarkType(type.GetElementType());
+					} else if (type.IsGenericType && !type.IsGenericTypeDefinition) {
+						MarkType(type.GetGenericTypeDefinition());
+						foreach (Type typeArg in type.GetGenericArguments())
+							MarkType(typeArg);
+					} else if (type.IsGenericParameter) {
+						throw new NotSupportedException();
+					} else {
+						var serializationBinder = fastSerializer.SerializationBinder;
+						if (serializationBinder != null) {
+							serializationBinder.BindToName(type, out assemblyName, out typeName);
+						} else {
+							assemblyName = type.Assembly.FullName;
+							typeName = type.FullName;
+							Debug.Assert(typeName != null);
+						}
+					}
+					
+					sType = new SerializationType(typeMap.Count, type);
+					sType.TypeName = typeName;
+					if (assemblyName != null) {
+						if (!assemblyNameToID.TryGetValue(assemblyName, out sType.AssemblyNameID)) {
+							sType.AssemblyNameID = assemblyNames.Count;
+							assemblyNameToID.Add(assemblyName, sType.AssemblyNameID);
+							assemblyNames.Add(assemblyName);
+							Log("Registered assembly #{0}: {1}", sType.AssemblyNameID, assemblyName);
+						}
+					}
+					typeMap.Add(type, sType);
+					types.Add(sType);
+					Log("Registered type %{0}: {1}", sType.ID, type);
+					if (type == typeof(string)) {
+						stringType = sType;
+					}
+				}
+				return sType;
+			}
+			
+			internal void ScanTypes()
+			{
+				for (int i = 0; i < types.Count; i++) {
+					Type type = types[i].Type;
+					if (type.IsGenericTypeDefinition || type.HasElementType)
+						continue;
+					if (typeof(ISerializable).IsAssignableFrom(type))
+						continue;
+					foreach (FieldInfo field in GetSerializableFields(type)) {
+						MarkType(field.FieldType);
+					}
+				}
+			}
+			#endregion
+			
+			#region Writing
+			public void WriteObjectID(object instance)
+			{
+				int id = (instance == null) ? 0 : objectToID[instance];
+				if (instances.Count <= ushort.MaxValue)
+					writer.Write((ushort)id);
+				else
+					writer.Write(id);
+			}
+			
+			void WriteTypeID(Type type)
+			{
+				Debug.Assert(typeMap.ContainsKey(type));
+				int typeID = typeMap[type].ID;
+				if (types.Count <= ushort.MaxValue)
+					writer.Write((ushort)typeID);
+				else
+					writer.Write(typeID);
+			}
+			
+			internal void Write()
+			{
+				Log("Writing...");
+				writer.Write(magic);
+				// Write out type information
+				writer.Write(instances.Count);
+				writer.Write(types.Count);
+				writer.Write(assemblyNames.Count);
+				writer.Write(fixedInstanceCount);
+				
+				foreach (string assemblyName in assemblyNames) {
+					writer.Write(assemblyName);
+				}
+				
+				foreach (SerializationType sType in types) {
+					Type type = sType.Type;
+					if (type.HasElementType) {
+						if (type.IsArray) {
+							if (type.GetArrayRank() == 1)
+								writer.Write(Type_SZArray);
+							else
+								throw new NotSupportedException();
+						} else {
+							throw new NotSupportedException();
+						}
+						WriteTypeID(type.GetElementType());
+					} else if (type.IsGenericType && !type.IsGenericTypeDefinition) {
+						writer.Write(Type_ParameterizedType);
+						WriteTypeID(type.GetGenericTypeDefinition());
+						foreach (Type typeArg in type.GetGenericArguments()) {
+							WriteTypeID(typeArg);
+						}
+					} else {
+						if (type.IsValueType) {
+							writer.Write(Type_ValueType);
+						} else {
+							writer.Write(Type_ReferenceType);
+						}
+						if (assemblyNames.Count <= ushort.MaxValue)
+							writer.Write((ushort)sType.AssemblyNameID);
+						else
+							writer.Write(sType.AssemblyNameID);
+						writer.Write(sType.TypeName);
+					}
+				}
+				foreach (SerializationType sType in types) {
+					Type type = sType.Type;
+					if (type.IsGenericTypeDefinition || type.HasElementType)
+						continue;
+					writer.Write(FastSerializerVersionAttribute.GetVersionNumber(type));
+					if (type.IsPrimitive || typeof(ISerializable).IsAssignableFrom(type)) {
+						writer.Write(byte.MaxValue);
+					} else {
+						var fields = GetSerializableFields(type);
+						if (fields.Count >= byte.MaxValue)
+							throw new SerializationException("Too many fields.");
+						writer.Write((byte)fields.Count);
+						foreach (var field in fields) {
+							WriteTypeID(field.FieldType);
+							writer.Write(field.Name);
+						}
+					}
+				}
+				
+				// Write out information necessary to create the instances
+				// starting from 1, because index 0 is null
+				for (int i = 1 + fixedInstanceCount; i < instances.Count; i++) {
+					SerializationType sType = objectTypes[i];
+					if (types.Count <= ushort.MaxValue)
+						writer.Write((ushort)sType.ID);
+					else
+						writer.Write(sType.ID);
+					if (sType == stringType) {
+						// Strings are written to the output immediately
+						// - we can't create an empty string and fill it later
+						writer.Write((string)instances[i]);
+					} else if (sType.Type.IsArray) {
+						// For arrays, write down the length, because we need that to create the array instance
+						writer.Write(((Array)instances[i]).Length);
+					}
+				}
+				// Write out information necessary to fill data into the instances
+				for (int i = 1 + fixedInstanceCount; i < instances.Count; i++) {
+					Log("0x{2:x6}, Write #{0}: {1}", i, objectTypes[i].Type.Name, writer.BaseStream.Position);
+					objectTypes[i].Writer(this, instances[i]);
+				}
+				Log("Serialization done.");
+			}
+			#endregion
+		}
+		
+		#region Object Scanners
+		delegate void ObjectScanner(SerializationContext context, object instance);
+		
+		static readonly MethodInfo mark = typeof(SerializationContext).GetMethod("Mark", new[] { typeof(object) });
+		static readonly FieldInfo writerField = typeof(SerializationContext).GetField("writer");
+		
+		Dictionary<Type, ObjectScanner> scanners = new Dictionary<Type, ObjectScanner>();
+		
+		ObjectScanner GetScanner(Type type)
+		{
+			ObjectScanner scanner;
+			if (!scanners.TryGetValue(type, out scanner)) {
+				scanner = CreateScanner(type);
+				scanners.Add(type, scanner);
+			}
+			return scanner;
+		}
+		
+		ObjectScanner CreateScanner(Type type)
+		{
+			bool isArray = type.IsArray;
+			if (isArray) {
+				if (type.GetArrayRank() != 1)
+					throw new NotSupportedException();
+				type = type.GetElementType();
+				if (!type.IsValueType) {
+					return delegate (SerializationContext context, object array) {
+						foreach (object val in (object[])array) {
+							context.Mark(val);
+						}
+					};
+				}
+			}
+			for (Type baseType = type; baseType != null; baseType = baseType.BaseType) {
+				if (!baseType.IsSerializable)
+					throw new SerializationException("Type " + baseType + " is not [Serializable].");
+			}
+			List<FieldInfo> fields = GetSerializableFields(type);
+			fields.RemoveAll(f => !IsReferenceOrContainsReferences(f.FieldType));
+			if (fields.Count == 0) {
+				// The scanner has nothing to do for this object.
+				return delegate { };
+			}
+			
+			DynamicMethod dynamicMethod = new DynamicMethod(
+				(isArray ? "ScanArray_" : "Scan_") + type.Name,
+				typeof(void), new [] { typeof(SerializationContext), typeof(object) },
+				true);
+			ILGenerator il = dynamicMethod.GetILGenerator();
+			
+			
+			if (isArray) {
+				var instance = il.DeclareLocal(type.MakeArrayType());
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Castclass, type.MakeArrayType());
+				il.Emit(OpCodes.Stloc, instance); // instance = (type[])arg_1;
+				
+				// for (int i = 0; i < instance.Length; i++) scan instance[i];
+				var loopStart = il.DefineLabel();
+				var loopHead = il.DefineLabel();
+				var loopVariable = il.DeclareLocal(typeof(int));
+				il.Emit(OpCodes.Ldc_I4_0);
+				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable = 0
+				il.Emit(OpCodes.Br, loopHead); // goto loopHead;
+				
+				il.MarkLabel(loopStart);
+				
+				il.Emit(OpCodes.Ldloc, instance); // instance
+				il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
+				il.Emit(OpCodes.Ldelem, type); // &instance[loopVariable]
+				EmitScanValueType(il, type);
+				
+				
+				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
+				il.Emit(OpCodes.Ldc_I4_1); // loopVariable, 1
+				il.Emit(OpCodes.Add); // loopVariable+1
+				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable++;
+				
+				il.MarkLabel(loopHead);
+				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
+				il.Emit(OpCodes.Ldloc, instance); // loopVariable, instance
+				il.Emit(OpCodes.Ldlen); // loopVariable, instance.Length
+				il.Emit(OpCodes.Conv_I4);
+				il.Emit(OpCodes.Blt, loopStart); // if (loopVariable < instance.Length) goto loopStart;
+			} else if (type.IsValueType) {
+				// boxed value type
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Unbox_Any, type);
+				EmitScanValueType(il, type);
+			} else {
+				// reference type
+				var instance = il.DeclareLocal(type);
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Castclass, type);
+				il.Emit(OpCodes.Stloc, instance); // instance = (type)arg_1;
+				
+				foreach (FieldInfo field in fields) {
+					EmitScanField(il, instance, field); // scan instance.Field
+				}
+			}
+			il.Emit(OpCodes.Ret);
+			return (ObjectScanner)dynamicMethod.CreateDelegate(typeof(ObjectScanner));
+		}
+
+		/// <summary>
+		/// Emit 'scan instance.Field'.
+		/// Stack transition: ... => ...
+		/// </summary>
+		void EmitScanField(ILGenerator il, LocalBuilder instance, FieldInfo field)
+		{
+			if (field.FieldType.IsValueType) {
+				il.Emit(OpCodes.Ldloc, instance); // instance
+				il.Emit(OpCodes.Ldfld, field); // instance.field
+				EmitScanValueType(il, field.FieldType);
+			} else {
+				il.Emit(OpCodes.Ldarg_0); // context
+				il.Emit(OpCodes.Ldloc, instance); // context, instance
+				il.Emit(OpCodes.Ldfld, field); // context, instance.field
+				il.Emit(OpCodes.Call, mark); // context.Mark(instance.field);
+			}
+		}
+
+		/// <summary>
+		/// Stack transition: ..., value => ...
+		/// </summary>
+		void EmitScanValueType(ILGenerator il, Type valType)
+		{
+			var fieldRef = il.DeclareLocal(valType);
+			il.Emit(OpCodes.Stloc, fieldRef);
+			
+			foreach (FieldInfo field in GetSerializableFields(valType)) {
+				if (IsReferenceOrContainsReferences(field.FieldType)) {
+					EmitScanField(il, fieldRef, field);
+				}
+			}
+		}
+
+		static List<FieldInfo> GetSerializableFields(Type type)
+		{
+			List<FieldInfo> fields = new List<FieldInfo>();
+			for (Type baseType = type; baseType != null; baseType = baseType.BaseType) {
+				FieldInfo[] declFields = baseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
+				Array.Sort(declFields, (a,b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
+				fields.AddRange(declFields);
+			}
+			fields.RemoveAll(f => f.IsNotSerialized);
+			return fields;
+		}
+
+		static bool IsReferenceOrContainsReferences(Type type)
+		{
+			if (!type.IsValueType)
+				return true;
+			if (type.IsPrimitive)
+				return false;
+			foreach (FieldInfo field in GetSerializableFields(type)) {
+				if (IsReferenceOrContainsReferences(field.FieldType))
+					return true;
+			}
+			return false;
+		}
+		#endregion
+
+		#region Object Writers
+		delegate void ObjectWriter(SerializationContext context, object instance);
+
+		static readonly MethodInfo writeObjectID = typeof(SerializationContext).GetMethod("WriteObjectID", new[] { typeof(object) });
+
+		static readonly MethodInfo writeByte = typeof(BinaryWriter).GetMethod("Write", new[] { typeof(byte) });
+		static readonly MethodInfo writeShort = typeof(BinaryWriter).GetMethod("Write", new[] { typeof(short) });
+		static readonly MethodInfo writeInt = typeof(BinaryWriter).GetMethod("Write", new[] { typeof(int) });
+		static readonly MethodInfo writeLong = typeof(BinaryWriter).GetMethod("Write", new[] { typeof(long) });
+		static readonly MethodInfo writeFloat = typeof(BinaryWriter).GetMethod("Write", new[] { typeof(float) });
+		static readonly MethodInfo writeDouble = typeof(BinaryWriter).GetMethod("Write", new[] { typeof(double) });
+		OpCode callVirt = OpCodes.Callvirt;
+
+		static readonly ObjectWriter serializationInfoWriter = delegate(SerializationContext context, object instance) {
+			BinaryWriter writer = context.writer;
+			SerializationInfo info = (SerializationInfo)instance;
+			writer.Write(info.MemberCount);
+			foreach (SerializationEntry entry in info) {
+				writer.Write(entry.Name);
+				context.WriteObjectID(entry.Value);
+			}
+		};
+
+		Dictionary<Type, ObjectWriter> writers = new Dictionary<Type, ObjectWriter>();
+
+		ObjectWriter GetWriter(Type type)
+		{
+			ObjectWriter writer;
+			if (!writers.TryGetValue(type, out writer)) {
+				writer = CreateWriter(type);
+				writers.Add(type, writer);
+			}
+			return writer;
+		}
+
+		ObjectWriter CreateWriter(Type type)
+		{
+			if (type == typeof(string)) {
+				// String contents are written in the object creation section,
+				// not into the field value section.
+				return delegate {};
+			}
+			bool isArray = type.IsArray;
+			if (isArray) {
+				if (type.GetArrayRank() != 1)
+					throw new NotSupportedException();
+				type = type.GetElementType();
+				if (!type.IsValueType) {
+					return delegate (SerializationContext context, object array) {
+						foreach (object val in (object[])array) {
+							context.WriteObjectID(val);
+						}
+					};
+				} else if (type == typeof(byte)) {
+					return delegate (SerializationContext context, object array) {
+						context.writer.Write((byte[])array);
+					};
+				}
+			}
+			List<FieldInfo> fields = GetSerializableFields(type);
+			if (fields.Count == 0) {
+				// The writer has nothing to do for this object.
+				return delegate { };
+			}
+			
+			
+			DynamicMethod dynamicMethod = new DynamicMethod(
+				(isArray ? "WriteArray_" : "Write_") + type.Name,
+				typeof(void), new [] { typeof(SerializationContext), typeof(object) },
+				true);
+			ILGenerator il = dynamicMethod.GetILGenerator();
+			
+			var writer = il.DeclareLocal(typeof(BinaryWriter));
+			
+			il.Emit(OpCodes.Ldarg_0);
+			il.Emit(OpCodes.Ldfld, writerField);
+			il.Emit(OpCodes.Stloc, writer); // writer = context.writer;
+			
+			if (isArray) {
+				var instance = il.DeclareLocal(type.MakeArrayType());
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Castclass, type.MakeArrayType());
+				il.Emit(OpCodes.Stloc, instance); // instance = (type[])arg_1;
+				
+				// for (int i = 0; i < instance.Length; i++) write instance[i];
+				
+				var loopStart = il.DefineLabel();
+				var loopHead = il.DefineLabel();
+				var loopVariable = il.DeclareLocal(typeof(int));
+				il.Emit(OpCodes.Ldc_I4_0);
+				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable = 0
+				il.Emit(OpCodes.Br, loopHead); // goto loopHead;
+				
+				il.MarkLabel(loopStart);
+				
+				if (type.IsEnum || type.IsPrimitive) {
+					if (type.IsEnum) {
+						type = type.GetEnumUnderlyingType();
+					}
+					Debug.Assert(type.IsPrimitive);
+					il.Emit(OpCodes.Ldloc, writer); // writer
+					il.Emit(OpCodes.Ldloc, instance); // writer, instance
+					il.Emit(OpCodes.Ldloc, loopVariable); // writer, instance, loopVariable
+					switch (Type.GetTypeCode(type)) {
+						case TypeCode.Boolean:
+						case TypeCode.SByte:
+						case TypeCode.Byte:
+							il.Emit(OpCodes.Ldelem_I1); // writer, instance[loopVariable]
+							il.Emit(callVirt, writeByte); // writer.Write(instance[loopVariable]);
+							break;
+						case TypeCode.Char:
+						case TypeCode.Int16:
+						case TypeCode.UInt16:
+							il.Emit(OpCodes.Ldelem_I2); // writer, instance[loopVariable]
+							il.Emit(callVirt, writeShort); // writer.Write(instance[loopVariable]);
+							break;
+						case TypeCode.Int32:
+						case TypeCode.UInt32:
+							il.Emit(OpCodes.Ldelem_I4);  // writer, instance[loopVariable]
+							il.Emit(callVirt, writeInt); // writer.Write(instance[loopVariable]);
+							break;
+						case TypeCode.Int64:
+						case TypeCode.UInt64:
+							il.Emit(OpCodes.Ldelem_I8);  // writer, instance[loopVariable]
+							il.Emit(callVirt, writeLong); // writer.Write(instance[loopVariable]);
+							break;
+						case TypeCode.Single:
+							il.Emit(OpCodes.Ldelem_R4);  // writer, instance[loopVariable]
+							il.Emit(callVirt, writeFloat); // writer.Write(instance[loopVariable]);
+							break;
+						case TypeCode.Double:
+							il.Emit(OpCodes.Ldelem_R8);  // writer, instance[loopVariable]
+							il.Emit(callVirt, writeDouble); // writer.Write(instance[loopVariable]);
+							break;
+						default:
+							throw new NotSupportedException("Unknown primitive type " + type);
+					}
+				} else {
+					il.Emit(OpCodes.Ldloc, instance); // instance
+					il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
+					il.Emit(OpCodes.Ldelem, type); // instance[loopVariable]
+					EmitWriteValueType(il, writer, type);
+				}
+				
+				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
+				il.Emit(OpCodes.Ldc_I4_1); // loopVariable, 1
+				il.Emit(OpCodes.Add); // loopVariable+1
+				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable++;
+				
+				il.MarkLabel(loopHead);
+				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
+				il.Emit(OpCodes.Ldloc, instance); // loopVariable, instance
+				il.Emit(OpCodes.Ldlen); // loopVariable, instance.Length
+				il.Emit(OpCodes.Conv_I4);
+				il.Emit(OpCodes.Blt, loopStart); // if (loopVariable < instance.Length) goto loopStart;
+			} else if (type.IsValueType) {
+				// boxed value type
+				if (type.IsEnum || type.IsPrimitive) {
+					il.Emit(OpCodes.Ldloc, writer);
+					il.Emit(OpCodes.Ldarg_1);
+					il.Emit(OpCodes.Unbox_Any, type);
+					WritePrimitiveValue(il, type);
+				} else {
+					il.Emit(OpCodes.Ldarg_1);
+					il.Emit(OpCodes.Unbox_Any, type);
+					EmitWriteValueType(il, writer, type);
+				}
+			} else {
+				// reference type
+				var instance = il.DeclareLocal(type);
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Castclass, type);
+				il.Emit(OpCodes.Stloc, instance); // instance = (type)arg_1;
+				
+				foreach (FieldInfo field in fields) {
+					EmitWriteField(il, writer, instance, field); // write instance.Field
+				}
+			}
+			il.Emit(OpCodes.Ret);
+			return (ObjectWriter)dynamicMethod.CreateDelegate(typeof(ObjectWriter));
+		}
+
+		/// <summary>
+		/// Emit 'write instance.Field'.
+		/// Stack transition: ... => ...
+		/// </summary>
+		void EmitWriteField(ILGenerator il, LocalBuilder writer, LocalBuilder instance, FieldInfo field)
+		{
+			Type fieldType = field.FieldType;
+			if (fieldType.IsValueType) {
+				if (fieldType.IsPrimitive || fieldType.IsEnum) {
+					il.Emit(OpCodes.Ldloc, writer); // writer
+					il.Emit(OpCodes.Ldloc, instance); // writer, instance
+					il.Emit(OpCodes.Ldfld, field); // writer, instance.field
+					WritePrimitiveValue(il, fieldType);
+				} else {
+					il.Emit(OpCodes.Ldloc, instance); // instance
+					il.Emit(OpCodes.Ldfld, field); // instance.field
+					EmitWriteValueType(il, writer, fieldType);
+				}
+			} else {
+				il.Emit(OpCodes.Ldarg_0); // context
+				il.Emit(OpCodes.Ldloc, instance); // context, instance
+				il.Emit(OpCodes.Ldfld, field); // context, instance.field
+				il.Emit(OpCodes.Call, writeObjectID); // context.WriteObjectID(instance.field);
+			}
+		}
+		
+		/// <summary>
+		/// Writes a primitive value of the specified type.
+		/// Stack transition: ..., writer, value => ...
+		/// </summary>
+		void WritePrimitiveValue(ILGenerator il, Type fieldType)
+		{
+			if (fieldType.IsEnum) {
+				fieldType = fieldType.GetEnumUnderlyingType();
+				Debug.Assert(fieldType.IsPrimitive);
+			}
+			switch (Type.GetTypeCode(fieldType)) {
+				case TypeCode.Boolean:
+				case TypeCode.SByte:
+				case TypeCode.Byte:
+					il.Emit(callVirt, writeByte); // writer.Write(value);
+					break;
+				case TypeCode.Char:
+				case TypeCode.Int16:
+				case TypeCode.UInt16:
+					il.Emit(callVirt, writeShort); // writer.Write(value);
+					break;
+				case TypeCode.Int32:
+				case TypeCode.UInt32:
+					il.Emit(callVirt, writeInt); // writer.Write(value);
+					break;
+				case TypeCode.Int64:
+				case TypeCode.UInt64:
+					il.Emit(callVirt, writeLong); // writer.Write(value);
+					break;
+				case TypeCode.Single:
+					il.Emit(callVirt, writeFloat); // writer.Write(value);
+					break;
+				case TypeCode.Double:
+					il.Emit(callVirt, writeDouble); // writer.Write(value);
+					break;
+				default:
+					throw new NotSupportedException("Unknown primitive type " + fieldType);
+			}
+		}
+
+		/// <summary>
+		/// Stack transition: ..., value => ...
+		/// </summary>
+		void EmitWriteValueType(ILGenerator il, LocalBuilder writer, Type valType)
+		{
+			Debug.Assert(valType.IsValueType);
+			Debug.Assert(!(valType.IsEnum || valType.IsPrimitive));
+			
+			var fieldVal = il.DeclareLocal(valType);
+			il.Emit(OpCodes.Stloc, fieldVal);
+			
+			foreach (FieldInfo field in GetSerializableFields(valType)) {
+				EmitWriteField(il, writer, fieldVal, field);
+			}
+		}
+		#endregion
+
+		StreamingContext streamingContext = new StreamingContext(StreamingContextStates.All);
+		FormatterConverter formatterConverter = new FormatterConverter();
+
+		public void Serialize(Stream stream, object instance)
+		{
+			Serialize(new BinaryWriterWith7BitEncodedInts(stream), instance);
+		}
+
+		public void Serialize(BinaryWriter writer, object instance)
+		{
+			SerializationContext context = new SerializationContext(this, writer);
+			context.MarkFixedInstances(this.FixedInstances);
+			context.Mark(instance);
+			context.Scan();
+			context.ScanTypes();
+			context.Write();
+			context.WriteObjectID(instance);
+		}
+
+		delegate void TypeSerializer(object instance, SerializationContext context);
+		#endregion
+
+		#region Deserialization
+		sealed class DeserializationContext
+		{
+			public Type[] Types; // index: type ID
+			
+			public object[] Objects; // index: object ID
+			
+			public BinaryReader Reader;
+			
+			public object ReadObject()
+			{
+				if (this.Objects.Length <= ushort.MaxValue)
+					return this.Objects[Reader.ReadUInt16()];
+				else
+					return this.Objects[Reader.ReadInt32()];
+			}
+			
+			#region DeserializeTypeDescriptions
+			internal int ReadTypeID()
+			{
+				if (this.Types.Length <= ushort.MaxValue)
+					return Reader.ReadUInt16();
+				else
+					return Reader.ReadInt32();
+			}
+			
+			internal void DeserializeTypeDescriptions()
+			{
+				for (int i = 0; i < this.Types.Length; i++) {
+					Type type = this.Types[i];
+					if (type.IsGenericTypeDefinition || type.HasElementType)
+						continue;
+					int versionNumber = Reader.ReadInt32();
+					if (versionNumber != FastSerializerVersionAttribute.GetVersionNumber(type))
+						throw new SerializationException("Type '" + type.FullName + "' was serialized with version " + versionNumber + ", but is version " + FastSerializerVersionAttribute.GetVersionNumber(type));
+					
+					bool isCustomSerialization = typeof(ISerializable).IsAssignableFrom(type);
+					bool typeIsSpecial = type.IsPrimitive || isCustomSerialization;
+					
+					byte serializedFieldCount = Reader.ReadByte();
+					if (serializedFieldCount == byte.MaxValue) {
+						// special type
+						if (!typeIsSpecial)
+							throw new SerializationException("Type '" + type.FullName + "' was serialized as special type, but isn't special now.");
+					} else {
+						if (typeIsSpecial)
+							throw new SerializationException("Type '" + type.FullName + "' wasn't serialized as special type, but is special now.");
+						
+						var availableFields = GetSerializableFields(this.Types[i]);
+						if (availableFields.Count != serializedFieldCount)
+							throw new SerializationException("Number of fields on " + type.FullName + " has changed.");
+						for (int j = 0; j < serializedFieldCount; j++) {
+							int fieldTypeID = ReadTypeID();
+							
+							string fieldName = Reader.ReadString();
+							FieldInfo fieldInfo = availableFields[j];
+							if (fieldInfo.Name != fieldName)
+								throw new SerializationException("Field mismatch on type " + type.FullName);
+							if (fieldInfo.FieldType != this.Types[fieldTypeID])
+								throw new SerializationException(type.FullName + "." + fieldName + " was serialized as " + this.Types[fieldTypeID] + ", but now is " + fieldInfo.FieldType);
+						}
+					}
+				}
+			}
+			#endregion
+		}
+		
+		delegate void ObjectReader(DeserializationContext context, object instance);
+		
+		public object Deserialize(Stream stream)
+		{
+			return Deserialize(new BinaryReaderWith7BitEncodedInts(stream));
+		}
+		
+		public object Deserialize(BinaryReader reader)
+		{
+			if (reader.ReadInt32() != magic)
+				throw new SerializationException("The data cannot be read by FastSerializer (unknown magic value)");
+			
+			DeserializationContext context = new DeserializationContext();
+			context.Reader = reader;
+			context.Objects = new object[reader.ReadInt32()];
+			context.Types = new Type[reader.ReadInt32()];
+			string[] assemblyNames = new string[reader.ReadInt32()];
+			int fixedInstanceCount = reader.ReadInt32();
+			
+			if (fixedInstanceCount != 0) {
+				if (this.FixedInstances == null || this.FixedInstances.Length != fixedInstanceCount)
+					throw new SerializationException("Number of fixed instances doesn't match");
+				for (int i = 0; i < fixedInstanceCount; i++) {
+					context.Objects[i + 1] = this.FixedInstances[i];
+				}
+			}
+			
+			for (int i = 0; i < assemblyNames.Length; i++) {
+				assemblyNames[i] = reader.ReadString();
+			}
+			int stringTypeID = -1;
+			for (int i = 0; i < context.Types.Length; i++) {
+				byte typeKind = reader.ReadByte();
+				switch (typeKind) {
+					case Type_ReferenceType:
+					case Type_ValueType:
+						int assemblyID;
+						if (assemblyNames.Length <= ushort.MaxValue)
+							assemblyID = reader.ReadUInt16();
+						else
+							assemblyID = reader.ReadInt32();
+						string assemblyName = assemblyNames[assemblyID];
+						string typeName = reader.ReadString();
+						Type type;
+						if (SerializationBinder != null) {
+							type = SerializationBinder.BindToType(assemblyName, typeName);
+						} else {
+							type = Assembly.Load(assemblyName).GetType(typeName);
+						}
+						if (type == null)
+							throw new SerializationException("Could not find '" + typeName + "' in '" + assemblyName + "'");
+						if (typeKind == Type_ValueType && !type.IsValueType)
+							throw new SerializationException("Expected '" + typeName + "' to be a value type, but it is reference type");
+						if (typeKind == Type_ReferenceType && type.IsValueType)
+							throw new SerializationException("Expected '" + typeName + "' to be a reference type, but it is value type");
+						context.Types[i] = type;
+						if (type == typeof(string))
+							stringTypeID = i;
+						break;
+					case Type_SZArray:
+						context.Types[i] = context.Types[context.ReadTypeID()].MakeArrayType();
+						break;
+					case Type_ParameterizedType:
+						Type genericType = context.Types[context.ReadTypeID()];
+						int typeParameterCount = genericType.GetGenericArguments().Length;
+						Type[] typeArguments = new Type[typeParameterCount];
+						for (int j = 0; j < typeArguments.Length; j++) {
+							typeArguments[j] = context.Types[context.ReadTypeID()];
+						}
+						context.Types[i] = genericType.MakeGenericType(typeArguments);
+						break;
+					default:
+						throw new SerializationException("Unknown type kind");
+				}
+			}
+			context.DeserializeTypeDescriptions();
+			int[] typeIDByObjectID = new int[context.Objects.Length];
+			for (int i = 1 + fixedInstanceCount; i < context.Objects.Length; i++) {
+				int typeID = context.ReadTypeID();
+				
+				object instance;
+				if (typeID == stringTypeID) {
+					instance = reader.ReadString();
+				} else {
+					Type type = context.Types[typeID];
+					if (type.IsArray) {
+						int length = reader.ReadInt32();
+						instance = Array.CreateInstance(type.GetElementType(), length);
+					} else {
+						instance = FormatterServices.GetUninitializedObject(type);
+					}
+				}
+				context.Objects[i] = instance;
+				typeIDByObjectID[i] = typeID;
+			}
+			List<CustomDeserialization> customDeserializatons = new List<CustomDeserialization>();
+			ObjectReader[] objectReaders = new ObjectReader[context.Types.Length]; // index: type ID
+			for (int i = 1 + fixedInstanceCount; i < context.Objects.Length; i++) {
+				object instance = context.Objects[i];
+				int typeID = typeIDByObjectID[i];
+				Log("0x{2:x6} Read #{0}: {1}", i, context.Types[typeID].Name, reader.BaseStream.Position);
+				ISerializable serializable = instance as ISerializable;
+				if (serializable != null) {
+					Type type = context.Types[typeID];
+					SerializationInfo info = new SerializationInfo(type, formatterConverter);
+					int count = reader.ReadInt32();
+					for (int j = 0; j < count; j++) {
+						string name = reader.ReadString();
+						object val = context.ReadObject();
+						info.AddValue(name, val);
+					}
+					CustomDeserializationAction action = GetCustomDeserializationAction(type);
+					customDeserializatons.Add(new CustomDeserialization(instance, info, action));
+				} else {
+					ObjectReader objectReader = objectReaders[typeID];
+					if (objectReader == null) {
+						objectReader = GetReader(context.Types[typeID]);
+						objectReaders[typeID] = objectReader;
+					}
+					objectReader(context, instance);
+				}
+			}
+			Log("File was read successfully, now running {0} custom deserializations...", customDeserializatons.Count);
+			foreach (CustomDeserialization customDeserializaton in customDeserializatons) {
+				customDeserializaton.Run(streamingContext);
+			}
+			for (int i = 1 + fixedInstanceCount; i < context.Objects.Length; i++) {
+				IDeserializationCallback dc = context.Objects[i] as IDeserializationCallback;
+				if (dc != null)
+					dc.OnDeserialization(null);
+			}
+			
+			return context.ReadObject();
+		}
+		
+		#region Object Reader
+		static readonly FieldInfo readerField = typeof(DeserializationContext).GetField("Reader");
+		static readonly MethodInfo readObject = typeof(DeserializationContext).GetMethod("ReadObject");
+		
+		static readonly MethodInfo readByte = typeof(BinaryReader).GetMethod("ReadByte");
+		static readonly MethodInfo readShort = typeof(BinaryReader).GetMethod("ReadInt16");
+		static readonly MethodInfo readInt = typeof(BinaryReader).GetMethod("ReadInt32");
+		static readonly MethodInfo readLong = typeof(BinaryReader).GetMethod("ReadInt64");
+		static readonly MethodInfo readFloat = typeof(BinaryReader).GetMethod("ReadSingle");
+		static readonly MethodInfo readDouble = typeof(BinaryReader).GetMethod("ReadDouble");
+		
+		Dictionary<Type, ObjectReader> readers = new Dictionary<Type, ObjectReader>();
+
+		ObjectReader GetReader(Type type)
+		{
+			ObjectReader reader;
+			if (!readers.TryGetValue(type, out reader)) {
+				reader = CreateReader(type);
+				readers.Add(type, reader);
+			}
+			return reader;
+		}
+		
+		ObjectReader CreateReader(Type type)
+		{
+			if (type == typeof(string)) {
+				// String contents are written in the object creation section,
+				// not into the field value section; so there's nothing to read here.
+				return delegate {};
+			}
+			bool isArray = type.IsArray;
+			if (isArray) {
+				if (type.GetArrayRank() != 1)
+					throw new NotSupportedException();
+				type = type.GetElementType();
+				if (!type.IsValueType) {
+					return delegate (DeserializationContext context, object arrayInstance) {
+						object[] array = (object[])arrayInstance;
+						for (int i = 0; i < array.Length; i++) {
+							array[i] = context.ReadObject();
+						}
+					};
+				} else if (type == typeof(byte)) {
+					return delegate (DeserializationContext context, object arrayInstance) {
+						byte[] array = (byte[])arrayInstance;
+						BinaryReader binaryReader = context.Reader;
+						int pos = 0;
+						int bytesRead;
+						do {
+							bytesRead = binaryReader.Read(array, pos, array.Length - pos);
+							pos += bytesRead;
+						} while (bytesRead > 0);
+						if (pos != array.Length)
+							throw new EndOfStreamException();
+					};
+				}
+			}
+			var fields = GetSerializableFields(type);
+			if (fields.Count == 0) {
+				// The reader has nothing to do for this object.
+				return delegate { };
+			}
+			
+			DynamicMethod dynamicMethod = new DynamicMethod(
+				(isArray ? "ReadArray_" : "Read_") + type.Name,
+				MethodAttributes.Public | MethodAttributes.Static,
+				CallingConventions.Standard,
+				typeof(void), new [] { typeof(DeserializationContext), typeof(object) },
+				type,
+				true);
+			ILGenerator il = dynamicMethod.GetILGenerator();
+			
+			var reader = il.DeclareLocal(typeof(BinaryReader));
+			
+			il.Emit(OpCodes.Ldarg_0);
+			il.Emit(OpCodes.Ldfld, readerField);
+			il.Emit(OpCodes.Stloc, reader); // reader = context.reader;
+			
+			if (isArray) {
+				var instance = il.DeclareLocal(type.MakeArrayType());
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Castclass, type.MakeArrayType());
+				il.Emit(OpCodes.Stloc, instance); // instance = (type[])arg_1;
+				
+				// for (int i = 0; i < instance.Length; i++) read &instance[i];
+				
+				var loopStart = il.DefineLabel();
+				var loopHead = il.DefineLabel();
+				var loopVariable = il.DeclareLocal(typeof(int));
+				il.Emit(OpCodes.Ldc_I4_0);
+				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable = 0
+				il.Emit(OpCodes.Br, loopHead); // goto loopHead;
+				
+				il.MarkLabel(loopStart);
+				
+				if (type.IsEnum || type.IsPrimitive) {
+					if (type.IsEnum) {
+						type = type.GetEnumUnderlyingType();
+					}
+					Debug.Assert(type.IsPrimitive);
+					il.Emit(OpCodes.Ldloc, instance); // instance
+					il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
+					ReadPrimitiveValue(il, reader, type); // instance, loopVariable, value
+					switch (Type.GetTypeCode(type)) {
+						case TypeCode.Boolean:
+						case TypeCode.SByte:
+						case TypeCode.Byte:
+							il.Emit(OpCodes.Stelem_I1); // instance[loopVariable] = value;
+							break;
+						case TypeCode.Char:
+						case TypeCode.Int16:
+						case TypeCode.UInt16:
+							il.Emit(OpCodes.Stelem_I2); // instance[loopVariable] = value;
+							break;
+						case TypeCode.Int32:
+						case TypeCode.UInt32:
+							il.Emit(OpCodes.Stelem_I4); // instance[loopVariable] = value;
+							break;
+						case TypeCode.Int64:
+						case TypeCode.UInt64:
+							il.Emit(OpCodes.Stelem_I8); // instance[loopVariable] = value;
+							break;
+						case TypeCode.Single:
+							il.Emit(OpCodes.Stelem_R4); // instance[loopVariable] = value;
+							break;
+						case TypeCode.Double:
+							il.Emit(OpCodes.Stelem_R8); // instance[loopVariable] = value;
+							break;
+						default:
+							throw new NotSupportedException("Unknown primitive type " + type);
+					}
+				} else {
+					il.Emit(OpCodes.Ldloc, instance); // instance
+					il.Emit(OpCodes.Ldloc, loopVariable); // instance, loopVariable
+					il.Emit(OpCodes.Ldelema, type); // instance[loopVariable]
+					EmitReadValueType(il, reader, type);
+				}
+				
+				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
+				il.Emit(OpCodes.Ldc_I4_1); // loopVariable, 1
+				il.Emit(OpCodes.Add); // loopVariable+1
+				il.Emit(OpCodes.Stloc, loopVariable); // loopVariable++;
+				
+				il.MarkLabel(loopHead);
+				il.Emit(OpCodes.Ldloc, loopVariable); // loopVariable
+				il.Emit(OpCodes.Ldloc, instance); // loopVariable, instance
+				il.Emit(OpCodes.Ldlen); // loopVariable, instance.Length
+				il.Emit(OpCodes.Conv_I4);
+				il.Emit(OpCodes.Blt, loopStart); // if (loopVariable < instance.Length) goto loopStart;
+			} else if (type.IsValueType) {
+				// boxed value type
+				il.Emit(OpCodes.Ldarg_1); // instance
+				il.Emit(OpCodes.Unbox, type); // &(Type)instance
+				if (type.IsEnum || type.IsPrimitive) {
+					if (type.IsEnum) {
+						type = type.GetEnumUnderlyingType();
+					}
+					Debug.Assert(type.IsPrimitive);
+					ReadPrimitiveValue(il, reader, type); // &(Type)instance, value
+					switch (Type.GetTypeCode(type)) {
+						case TypeCode.Boolean:
+						case TypeCode.SByte:
+						case TypeCode.Byte:
+							il.Emit(OpCodes.Stind_I1);
+							break;
+						case TypeCode.Char:
+						case TypeCode.Int16:
+						case TypeCode.UInt16:
+							il.Emit(OpCodes.Stind_I2);
+							break;
+						case TypeCode.Int32:
+						case TypeCode.UInt32:
+							il.Emit(OpCodes.Stind_I4);
+							break;
+						case TypeCode.Int64:
+						case TypeCode.UInt64:
+							il.Emit(OpCodes.Stind_I8);
+							break;
+						case TypeCode.Single:
+							il.Emit(OpCodes.Stind_R4);
+							break;
+						case TypeCode.Double:
+							il.Emit(OpCodes.Stind_R8);
+							break;
+						default:
+							throw new NotSupportedException("Unknown primitive type " + type);
+					}
+				} else {
+					EmitReadValueType(il, reader, type);
+				}
+			} else {
+				// reference type
+				var instance = il.DeclareLocal(type);
+				il.Emit(OpCodes.Ldarg_1);
+				il.Emit(OpCodes.Castclass, type);
+				il.Emit(OpCodes.Stloc, instance); // instance = (type)arg_1;
+				
+				foreach (FieldInfo field in fields) {
+					EmitReadField(il, reader, instance, field); // read instance.Field
+				}
+			}
+			il.Emit(OpCodes.Ret);
+			return (ObjectReader)dynamicMethod.CreateDelegate(typeof(ObjectReader));
+		}
+
+		void EmitReadField(ILGenerator il, LocalBuilder reader, LocalBuilder instance, FieldInfo field)
+		{
+			Type fieldType = field.FieldType;
+			if (fieldType.IsValueType) {
+				if (fieldType.IsPrimitive || fieldType.IsEnum) {
+					il.Emit(OpCodes.Ldloc, instance); // instance
+					ReadPrimitiveValue(il, reader, fieldType); // instance, value
+					il.Emit(OpCodes.Stfld, field); // instance.field = value;
+				} else {
+					il.Emit(OpCodes.Ldloc, instance); // instance
+					il.Emit(OpCodes.Ldflda, field); // &instance.field
+					EmitReadValueType(il, reader, fieldType);
+				}
+			} else {
+				il.Emit(OpCodes.Ldloc, instance); // instance
+				il.Emit(OpCodes.Ldarg_0); // instance, context
+				il.Emit(OpCodes.Call, readObject); // instance, context.ReadObject()
+				il.Emit(OpCodes.Castclass, fieldType);
+				il.Emit(OpCodes.Stfld, field); // instance.field = (fieldType) context.ReadObject();
+			}
+		}
+
+		/// <summary>
+		/// Reads a primitive value of the specified type.
+		/// Stack transition: ... => ..., value
+		/// </summary>
+		void ReadPrimitiveValue(ILGenerator il, LocalBuilder reader, Type fieldType)
+		{
+			if (fieldType.IsEnum) {
+				fieldType = fieldType.GetEnumUnderlyingType();
+				Debug.Assert(fieldType.IsPrimitive);
+			}
+			il.Emit(OpCodes.Ldloc, reader);
+			switch (Type.GetTypeCode(fieldType)) {
+				case TypeCode.Boolean:
+				case TypeCode.SByte:
+				case TypeCode.Byte:
+					il.Emit(callVirt, readByte);
+					break;
+				case TypeCode.Char:
+				case TypeCode.Int16:
+				case TypeCode.UInt16:
+					il.Emit(callVirt, readShort);
+					break;
+				case TypeCode.Int32:
+				case TypeCode.UInt32:
+					il.Emit(callVirt, readInt);
+					break;
+				case TypeCode.Int64:
+				case TypeCode.UInt64:
+					il.Emit(callVirt, readLong);
+					break;
+				case TypeCode.Single:
+					il.Emit(callVirt, readFloat);
+					break;
+				case TypeCode.Double:
+					il.Emit(callVirt, readDouble);
+					break;
+				default:
+					throw new NotSupportedException("Unknown primitive type " + fieldType);
+			}
+		}
+
+		/// <summary>
+		/// Stack transition: ..., field-ref => ...
+		/// </summary>
+		void EmitReadValueType(ILGenerator il, LocalBuilder reader, Type valType)
+		{
+			Debug.Assert(valType.IsValueType);
+			Debug.Assert(!(valType.IsEnum || valType.IsPrimitive));
+			
+			var fieldRef = il.DeclareLocal(valType.MakeByRefType());
+			il.Emit(OpCodes.Stloc, fieldRef);
+			
+			foreach (FieldInfo field in GetSerializableFields(valType)) {
+				EmitReadField(il, reader, fieldRef, field);
+			}
+		}
+		#endregion
+		
+		#region Custom Deserialization
+		struct CustomDeserialization
+		{
+			readonly object instance;
+			readonly SerializationInfo serializationInfo;
+			readonly CustomDeserializationAction action;
+			
+			public CustomDeserialization(object instance, SerializationInfo serializationInfo, CustomDeserializationAction action)
+			{
+				this.instance = instance;
+				this.serializationInfo = serializationInfo;
+				this.action = action;
+			}
+			
+			public void Run(StreamingContext context)
+			{
+				action(instance, serializationInfo, context);
+			}
+		}
+		
+		delegate void CustomDeserializationAction(object instance, SerializationInfo info, StreamingContext context);
+		
+		Dictionary<Type, CustomDeserializationAction> customDeserializationActions = new Dictionary<Type, CustomDeserializationAction>();
+		
+		CustomDeserializationAction GetCustomDeserializationAction(Type type)
+		{
+			CustomDeserializationAction action;
+			if (!customDeserializationActions.TryGetValue(type, out action)) {
+				action = CreateCustomDeserializationAction(type);
+				customDeserializationActions.Add(type, action);
+			}
+			return action;
+		}
+		
+		static CustomDeserializationAction CreateCustomDeserializationAction(Type type)
+		{
+			ConstructorInfo ctor = type.GetConstructor(
+				BindingFlags.DeclaredOnly | BindingFlags.ExactBinding | BindingFlags.Instance
+				| BindingFlags.NonPublic | BindingFlags.Public,
+				null,
+				new Type [] { typeof(SerializationInfo), typeof(StreamingContext) },
+				null);
+			if (ctor == null)
+				throw new SerializationException("Could not find deserialization constructor for " + type.FullName);
+			
+			DynamicMethod dynamicMethod = new DynamicMethod(
+				"CallCtor_" + type.Name,
+				MethodAttributes.Public | MethodAttributes.Static,
+				CallingConventions.Standard,
+				typeof(void), new [] { typeof(object), typeof(SerializationInfo), typeof(StreamingContext) },
+				type,
+				true);
+			ILGenerator il = dynamicMethod.GetILGenerator();
+			il.Emit(OpCodes.Ldarg_0);
+			il.Emit(OpCodes.Ldarg_1);
+			il.Emit(OpCodes.Ldarg_2);
+			il.Emit(OpCodes.Call, ctor);
+			il.Emit(OpCodes.Ret);
+			return (CustomDeserializationAction)dynamicMethod.CreateDelegate(typeof(CustomDeserializationAction));
+		}
+		#endregion
+		#endregion
+		
+		[Conditional("DEBUG_SERIALIZER")]
+		static void Log(string format, params object[] args)
+		{
+			Debug.WriteLine(format, args);
+		}
+	}
+	
+	/// <summary>
+	/// Specifies the version of the class.
+	/// The <see cref="FastSerializer"/> will refuse to deserialize an instance that was stored by
+	/// a different version of the class than the current one.
+	/// </summary>
+	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
+	public class FastSerializerVersionAttribute : Attribute
+	{
+		readonly int versionNumber;
+		
+		public FastSerializerVersionAttribute(int versionNumber)
+		{
+			this.versionNumber = versionNumber;
+		}
+		
+		public int VersionNumber {
+			get {
+				return versionNumber;
+			}
+		}
+		
+		internal static int GetVersionNumber(Type type)
+		{
+			var arr = type.GetCustomAttributes(typeof(FastSerializerVersionAttribute), false);
+			if (arr.Length == 0)
+				return 0;
+			else
+				return ((FastSerializerVersionAttribute)arr[0]).VersionNumber;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/GraphVizGraph.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/GraphVizGraph.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/GraphVizGraph.cs	(revision 11807)
@@ -0,0 +1,219 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Text.RegularExpressions;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// GraphViz graph.
+	/// </summary>
+	public sealed class GraphVizGraph
+	{
+		List<GraphVizNode> nodes = new List<GraphVizNode>();
+		List<GraphVizEdge> edges = new List<GraphVizEdge>();
+		
+		public string rankdir;
+		public string Title;
+		
+		public void AddEdge(GraphVizEdge edge)
+		{
+			edges.Add(edge);
+		}
+		
+		public void AddNode(GraphVizNode node)
+		{
+			nodes.Add(node);
+		}
+		
+		public void Save(string fileName)
+		{
+			using (StreamWriter writer = new StreamWriter(fileName))
+				Save(writer);
+		}
+		
+		public void Show()
+		{
+			Show(null);
+		}
+		
+		public void Show(string name)
+		{
+			if (name == null)
+				name = Title;
+			if (name != null)
+				foreach (char c in Path.GetInvalidFileNameChars())
+					name = name.Replace(c, '-');
+			string fileName = name != null ? Path.Combine(Path.GetTempPath(), name) : Path.GetTempFileName();
+			Save(fileName + ".gv");
+			Process.Start("dot", "\"" + fileName + ".gv\" -Tpng -o \"" + fileName + ".png\"").WaitForExit();
+			Process.Start(fileName + ".png");
+		}
+		
+		static string Escape(string text)
+		{
+			if (Regex.IsMatch(text, @"^[\w\d]+$")) {
+				return text;
+			} else {
+				return "\"" + text.Replace("\\", "\\\\").Replace("\r", "").Replace("\n", "\\n").Replace("\"", "\\\"") + "\"";
+			}
+		}
+		
+		static void WriteGraphAttribute(TextWriter writer, string name, string value)
+		{
+			if (value != null)
+				writer.WriteLine("{0}={1};", name, Escape(value));
+		}
+		
+		internal static void WriteAttribute(TextWriter writer, string name, double? value, ref bool isFirst)
+		{
+			if (value != null) {
+				WriteAttribute(writer, name, value.Value.ToString(CultureInfo.InvariantCulture), ref isFirst);
+			}
+		}
+		
+		internal static void WriteAttribute(TextWriter writer, string name, bool? value, ref bool isFirst)
+		{
+			if (value != null) {
+				WriteAttribute(writer, name, value.Value ? "true" : "false", ref isFirst);
+			}
+		}
+		
+		internal static void WriteAttribute(TextWriter writer, string name, string value, ref bool isFirst)
+		{
+			if (value != null) {
+				if (isFirst)
+					isFirst = false;
+				else
+					writer.Write(',');
+				writer.Write("{0}={1}", name, Escape(value));
+			}
+		}
+		
+		public void Save(TextWriter writer)
+		{
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			writer.WriteLine("digraph G {");
+			writer.WriteLine("node [fontsize = 16];");
+			WriteGraphAttribute(writer, "rankdir", rankdir);
+			foreach (GraphVizNode node in nodes) {
+				node.Save(writer);
+			}
+			foreach (GraphVizEdge edge in edges) {
+				edge.Save(writer);
+			}
+			writer.WriteLine("}");
+		}
+	}
+	
+	public sealed class GraphVizEdge
+	{
+		public readonly string Source, Target;
+		
+		/// <summary>edge stroke color</summary>
+		public string color;
+		/// <summary>use edge to affect node ranking</summary>
+		public bool? constraint;
+		
+		public string label;
+		
+		public string style;
+		
+		/// <summary>point size of label</summary>
+		public int? fontsize;
+		
+		public GraphVizEdge(string source, string target)
+		{
+			if (source == null)
+				throw new ArgumentNullException("source");
+			if (target == null)
+				throw new ArgumentNullException("target");
+			this.Source = source;
+			this.Target = target;
+		}
+		
+		public GraphVizEdge(int source, int target)
+		{
+			this.Source = source.ToString(CultureInfo.InvariantCulture);
+			this.Target = target.ToString(CultureInfo.InvariantCulture);
+		}
+		
+		public void Save(TextWriter writer)
+		{
+			writer.Write("{0} -> {1} [", Source, Target);
+			bool isFirst = true;
+			GraphVizGraph.WriteAttribute(writer, "label", label, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "style", style, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "fontsize", fontsize, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "color", color, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "constraint", constraint, ref isFirst);
+			writer.WriteLine("];");
+		}
+	}
+	
+	public sealed class GraphVizNode
+	{
+		public readonly string ID;
+		public string label;
+		
+		public string labelloc;
+		
+		/// <summary>point size of label</summary>
+		public int? fontsize;
+		
+		/// <summary>minimum height in inches</summary>
+		public double? height;
+		
+		/// <summary>space around label</summary>
+		public string margin;
+		
+		/// <summary>node shape</summary>
+		public string shape;
+		
+		public GraphVizNode(string id)
+		{
+			if (id == null)
+				throw new ArgumentNullException("id");
+			this.ID = id;
+		}
+		
+		public GraphVizNode(int id)
+		{
+			this.ID = id.ToString(CultureInfo.InvariantCulture);
+		}
+		
+		public void Save(TextWriter writer)
+		{
+			writer.Write(ID);
+			writer.Write(" [");
+			bool isFirst = true;
+			GraphVizGraph.WriteAttribute(writer, "label", label, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "labelloc", labelloc, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "fontsize", fontsize, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "margin", margin, ref isFirst);
+			GraphVizGraph.WriteAttribute(writer, "shape", shape, ref isFirst);
+			writer.WriteLine("];");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ImmutableStack.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ImmutableStack.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ImmutableStack.cs	(revision 11807)
@@ -0,0 +1,132 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// An immutable stack.
+	/// 
+	/// Using 'foreach' on the stack will return the items from top to bottom (in the order they would be popped).
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
+	[Serializable]
+	public sealed class ImmutableStack<T> : IEnumerable<T>
+	{
+		/// <summary>
+		/// Gets the empty stack instance.
+		/// </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "ImmutableStack is immutable")]
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
+		public static readonly ImmutableStack<T> Empty = new ImmutableStack<T>();
+		
+		readonly T value;
+		readonly ImmutableStack<T> next;
+		
+		private ImmutableStack()
+		{
+		}
+		
+		private ImmutableStack(T value, ImmutableStack<T> next)
+		{
+			this.value = value;
+			this.next = next;
+		}
+		
+		/// <summary>
+		/// Pushes an item on the stack. This does not modify the stack itself, but returns a new
+		/// one with the value pushed.
+		/// </summary>
+		public ImmutableStack<T> Push(T item)
+		{
+			return new ImmutableStack<T>(item, this);
+		}
+		
+		/// <summary>
+		/// Gets the item on the top of the stack.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The stack is empty.</exception>
+		public T Peek()
+		{
+			if (IsEmpty)
+				throw new InvalidOperationException("Operation not valid on empty stack.");
+			return value;
+		}
+		
+		/// <summary>
+		/// Gets the item on the top of the stack.
+		/// Returns <c>default(T)</c> if the stack is empty.
+		/// </summary>
+		public T PeekOrDefault()
+		{
+			return value;
+		}
+		
+		/// <summary>
+		/// Gets the stack with the top item removed.
+		/// </summary>
+		/// <exception cref="InvalidOperationException">The stack is empty.</exception>
+		public ImmutableStack<T> Pop()
+		{
+			if (IsEmpty)
+				throw new InvalidOperationException("Operation not valid on empty stack.");
+			return next;
+		}
+		
+		/// <summary>
+		/// Gets if this stack is empty.
+		/// </summary>
+		public bool IsEmpty {
+			get { return next == null; }
+		}
+		
+		/// <summary>
+		/// Gets an enumerator that iterates through the stack top-to-bottom.
+		/// </summary>
+		public IEnumerator<T> GetEnumerator()
+		{
+			ImmutableStack<T> t = this;
+			while (!t.IsEmpty) {
+				yield return t.value;
+				t = t.next;
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.GetEnumerator();
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			StringBuilder b = new StringBuilder("[Stack");
+			foreach (T val in this) {
+				b.Append(' ');
+				b.Append(val);
+			}
+			b.Append(']');
+			return b.ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/KeyComparer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/KeyComparer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/KeyComparer.cs	(revision 11807)
@@ -0,0 +1,81 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public static class KeyComparer
+	{
+		public static KeyComparer<TElement, TKey> Create<TElement, TKey>(Func<TElement, TKey> keySelector)
+		{
+			return new KeyComparer<TElement, TKey>(keySelector, Comparer<TKey>.Default, EqualityComparer<TKey>.Default);
+		}
+		
+		public static KeyComparer<TElement, TKey> Create<TElement, TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, IEqualityComparer<TKey> equalityComparer)
+		{
+			return new KeyComparer<TElement, TKey>(keySelector, comparer, equalityComparer);
+		}
+		
+		public static IComparer<TElement> Create<TElement, TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer)
+		{
+			return new KeyComparer<TElement, TKey>(keySelector, comparer, EqualityComparer<TKey>.Default);
+		}
+		
+		public static IEqualityComparer<TElement> Create<TElement, TKey>(Func<TElement, TKey> keySelector, IEqualityComparer<TKey> equalityComparer)
+		{
+			return new KeyComparer<TElement, TKey>(keySelector, Comparer<TKey>.Default, equalityComparer);
+		}
+	}
+	
+	public class KeyComparer<TElement, TKey> : IComparer<TElement>, IEqualityComparer<TElement>
+	{
+		readonly Func<TElement, TKey> keySelector;
+		readonly IComparer<TKey> keyComparer;
+		readonly IEqualityComparer<TKey> keyEqualityComparer;
+		
+		public KeyComparer(Func<TElement, TKey> keySelector, IComparer<TKey> keyComparer, IEqualityComparer<TKey> keyEqualityComparer)
+		{
+			if (keySelector == null)
+				throw new ArgumentNullException("keySelector");
+			if (keyComparer == null)
+				throw new ArgumentNullException("keyComparer");
+			if (keyEqualityComparer == null)
+				throw new ArgumentNullException("keyEqualityComparer");
+			this.keySelector = keySelector;
+			this.keyComparer = keyComparer;
+			this.keyEqualityComparer = keyEqualityComparer;
+		}
+		
+		public int Compare(TElement x, TElement y)
+		{
+			return keyComparer.Compare(keySelector(x), keySelector(y));
+		}
+		
+		public bool Equals(TElement x, TElement y)
+		{
+			return keyEqualityComparer.Equals(keySelector(x), keySelector(y));
+		}
+		
+		public int GetHashCode(TElement obj)
+		{
+			return keyEqualityComparer.GetHashCode(keySelector(obj));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/LazyInit.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/LazyInit.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/LazyInit.cs	(revision 11807)
@@ -0,0 +1,48 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public static class LazyInit
+	{
+		public static T VolatileRead<T>(ref T location) where T : class
+		{
+			#if NET_4_5
+			return Volatile.Read(ref location);
+			#else
+			T result = location;
+			Thread.MemoryBarrier();
+			return result;
+			#endif
+		}
+		
+		/// <summary>
+		/// Atomically performs the following operation:
+		/// - If target is null: stores newValue in target and returns newValue.
+		/// - If target is not null: returns target.
+		/// </summary>
+		public static T GetOrSet<T>(ref T target, T newValue) where T : class
+		{
+			T oldValue = Interlocked.CompareExchange(ref target, newValue, null);
+			return oldValue ?? newValue;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/MultiDictionary.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/MultiDictionary.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/MultiDictionary.cs	(revision 11807)
@@ -0,0 +1,154 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// A dictionary that allows multiple pairs with the same key.
+	/// </summary>
+	public class MultiDictionary<TKey, TValue> : ILookup<TKey, TValue>
+	{
+		readonly Dictionary<TKey, List<TValue>> dict;
+		
+		public MultiDictionary()
+		{
+			dict = new Dictionary<TKey, List<TValue>>();
+		}
+		
+		public MultiDictionary(IEqualityComparer<TKey> comparer)
+		{
+			dict = new Dictionary<TKey, List<TValue>>(comparer);
+		}
+		
+		public void Add(TKey key, TValue value)
+		{
+			List<TValue> valueList;
+			if (!dict.TryGetValue(key, out valueList)) {
+				valueList = new List<TValue>();
+				dict.Add(key, valueList);
+			}
+			valueList.Add(value);
+		}
+
+		public bool Remove(TKey key, TValue value)
+		{
+			List<TValue> valueList;
+			if (dict.TryGetValue(key, out valueList)) {
+				if (valueList.Remove(value)) {
+					if (valueList.Count == 0)
+						dict.Remove(key);
+					return true;
+				}
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Removes all entries with the specified key.
+		/// </summary>
+		/// <returns>Returns true if at least one entry was removed.</returns>
+		public bool RemoveAll(TKey key)
+		{
+			return dict.Remove(key);
+		}
+		
+		public void Clear()
+		{
+			dict.Clear();
+		}
+		
+		#if NET_4_5
+		public IReadOnlyList<TValue> this[TKey key] {
+		#else
+		public IList<TValue> this[TKey key] {
+		#endif
+			get {
+				List<TValue> list;
+				if (dict.TryGetValue(key, out list))
+					return list;
+				else
+					return EmptyList<TValue>.Instance;
+			}
+		}
+		
+		/// <summary>
+		/// Returns the number of different keys.
+		/// </summary>
+		public int Count {
+			get { return dict.Count; }
+		}
+		
+		public ICollection<TKey> Keys {
+			get { return dict.Keys; }
+		}
+		
+		public IEnumerable<TValue> Values {
+			get { return dict.Values.SelectMany(list => list); }
+		}
+		
+		IEnumerable<TValue> ILookup<TKey, TValue>.this[TKey key] {
+			get { return this[key]; }
+		}
+		
+		bool ILookup<TKey, TValue>.Contains(TKey key)
+		{
+			return dict.ContainsKey(key);
+		}
+		
+		public IEnumerator<IGrouping<TKey, TValue>> GetEnumerator()
+		{
+			foreach (var pair in dict)
+				yield return new Grouping(pair.Key, pair.Value);
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return GetEnumerator();
+		}
+		
+		sealed class Grouping : IGrouping<TKey, TValue>
+		{
+			readonly TKey key;
+			readonly List<TValue> values;
+			
+			public Grouping(TKey key, List<TValue> values)
+			{
+				this.key = key;
+				this.values = values;
+			}
+			
+			public TKey Key {
+				get { return key; }
+			}
+			
+			public IEnumerator<TValue> GetEnumerator()
+			{
+				return values.GetEnumerator();
+			}
+			
+			System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+			{
+				return values.GetEnumerator();
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/Platform.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/Platform.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/Platform.cs	(revision 11807)
@@ -0,0 +1,40 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Platform-specific code.
+	/// </summary>
+	public static class Platform
+	{
+		public static StringComparer FileNameComparer {
+			get {
+				switch (Environment.OSVersion.Platform) {
+					case PlatformID.Unix:
+					case PlatformID.MacOSX:
+						return StringComparer.Ordinal;
+					default:
+						return StringComparer.OrdinalIgnoreCase;
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ProjectedList.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ProjectedList.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ProjectedList.cs	(revision 11807)
@@ -0,0 +1,239 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public sealed class ProjectedList<TInput, TOutput> : IList<TOutput> where TOutput : class
+	{
+		readonly IList<TInput> input;
+		readonly Func<TInput, TOutput> projection;
+		readonly TOutput[] items;
+		
+		public ProjectedList(IList<TInput> input, Func<TInput, TOutput> projection)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			if (projection == null)
+				throw new ArgumentNullException("projection");
+			this.input = input;
+			this.projection = projection;
+			this.items = new TOutput[input.Count];
+		}
+		
+		public TOutput this[int index] {
+			get {
+				TOutput output = LazyInit.VolatileRead(ref items[index]);
+				if (output != null) {
+					return output;
+				}
+				return LazyInit.GetOrSet(ref items[index], projection(input[index]));
+			}
+		}
+		
+		TOutput IList<TOutput>.this[int index] {
+			get { return this[index]; }
+			set {
+				throw new NotSupportedException();
+			}
+		}
+		
+		public int Count {
+			get { return items.Length; }
+		}
+		
+		bool ICollection<TOutput>.IsReadOnly {
+			get { return true; }
+		}
+		
+		int IList<TOutput>.IndexOf(TOutput item)
+		{
+			var comparer = EqualityComparer<TOutput>.Default;
+			for (int i = 0; i < this.Count; i++) {
+				if (comparer.Equals(this[i], item))
+					return i;
+			}
+			return -1;
+		}
+		
+		void IList<TOutput>.Insert(int index, TOutput item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IList<TOutput>.RemoveAt(int index)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<TOutput>.Add(TOutput item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<TOutput>.Clear()
+		{
+			throw new NotSupportedException();
+		}
+		
+		bool ICollection<TOutput>.Contains(TOutput item)
+		{
+			var comparer = EqualityComparer<TOutput>.Default;
+			for (int i = 0; i < this.Count; i++) {
+				if (comparer.Equals(this[i], item))
+					return true;
+			}
+			return false;
+		}
+		
+		void ICollection<TOutput>.CopyTo(TOutput[] array, int arrayIndex)
+		{
+			for (int i = 0; i < items.Length; i++) {
+				array[arrayIndex + i] = this[i];
+			}
+		}
+		
+		bool ICollection<TOutput>.Remove(TOutput item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		public IEnumerator<TOutput> GetEnumerator()
+		{
+			for (int i = 0; i < this.Count; i++) {
+				yield return this[i];
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return GetEnumerator();
+		}
+	}
+	
+	public sealed class ProjectedList<TContext, TInput, TOutput> : IList<TOutput> where TOutput : class
+	{
+		readonly IList<TInput> input;
+		readonly TContext context;
+		readonly Func<TContext, TInput, TOutput> projection;
+		readonly TOutput[] items;
+		
+		public ProjectedList(TContext context, IList<TInput> input, Func<TContext, TInput, TOutput> projection)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			if (projection == null)
+				throw new ArgumentNullException("projection");
+			this.input = input;
+			this.context = context;
+			this.projection = projection;
+			this.items = new TOutput[input.Count];
+		}
+		
+		public TOutput this[int index] {
+			get {
+				TOutput output = LazyInit.VolatileRead(ref items[index]);
+				if (output != null) {
+					return output;
+				}
+				return LazyInit.GetOrSet(ref items[index], projection(context, input[index]));
+			}
+		}
+		
+		TOutput IList<TOutput>.this[int index] {
+			get { return this[index]; }
+			set {
+				throw new NotSupportedException();
+			}
+		}
+		
+		public int Count {
+			get { return items.Length; }
+		}
+		
+		bool ICollection<TOutput>.IsReadOnly {
+			get { return true; }
+		}
+		
+		int IList<TOutput>.IndexOf(TOutput item)
+		{
+			var comparer = EqualityComparer<TOutput>.Default;
+			for (int i = 0; i < this.Count; i++) {
+				if (comparer.Equals(this[i], item))
+					return i;
+			}
+			return -1;
+		}
+		
+		void IList<TOutput>.Insert(int index, TOutput item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void IList<TOutput>.RemoveAt(int index)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<TOutput>.Add(TOutput item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		void ICollection<TOutput>.Clear()
+		{
+			throw new NotSupportedException();
+		}
+		
+		bool ICollection<TOutput>.Contains(TOutput item)
+		{
+			var comparer = EqualityComparer<TOutput>.Default;
+			for (int i = 0; i < this.Count; i++) {
+				if (comparer.Equals(this[i], item))
+					return true;
+			}
+			return false;
+		}
+		
+		void ICollection<TOutput>.CopyTo(TOutput[] array, int arrayIndex)
+		{
+			for (int i = 0; i < items.Length; i++) {
+				array[arrayIndex + i] = this[i];
+			}
+		}
+		
+		bool ICollection<TOutput>.Remove(TOutput item)
+		{
+			throw new NotSupportedException();
+		}
+		
+		public IEnumerator<TOutput> GetEnumerator()
+		{
+			for (int i = 0; i < this.Count; i++) {
+				yield return this[i];
+			}
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return GetEnumerator();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ReferenceComparer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ReferenceComparer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/ReferenceComparer.cs	(revision 11807)
@@ -0,0 +1,39 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	public sealed class ReferenceComparer : IEqualityComparer<object>
+	{
+		public readonly static ReferenceComparer Instance = new ReferenceComparer();
+		
+		public new bool Equals(object x, object y)
+		{
+			return x == y;
+		}
+		
+		public int GetHashCode(object obj)
+		{
+			return RuntimeHelpers.GetHashCode(obj);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/TreeTraversal.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/TreeTraversal.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory-5.5.0/Utils/TreeTraversal.cs	(revision 11807)
@@ -0,0 +1,112 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Utils
+{
+	/// <summary>
+	/// Static helper methods for traversing trees.
+	/// </summary>
+	public static class TreeTraversal
+	{
+		/// <summary>
+		/// Converts a tree data structure into a flat list by traversing it in pre-order.
+		/// </summary>
+		/// <param name="root">The root element of the tree.</param>
+		/// <param name="recursion">The function that gets the children of an element.</param>
+		/// <returns>Iterator that enumerates the tree structure in pre-order.</returns>
+		public static IEnumerable<T> PreOrder<T>(T root, Func<T, IEnumerable<T>> recursion)
+		{
+			return PreOrder(new T[] { root }, recursion);
+		}
+		
+		/// <summary>
+		/// Converts a tree data structure into a flat list by traversing it in pre-order.
+		/// </summary>
+		/// <param name="input">The root elements of the forest.</param>
+		/// <param name="recursion">The function that gets the children of an element.</param>
+		/// <returns>Iterator that enumerates the tree structure in pre-order.</returns>
+		public static IEnumerable<T> PreOrder<T>(IEnumerable<T> input, Func<T, IEnumerable<T>> recursion)
+		{
+			Stack<IEnumerator<T>> stack = new Stack<IEnumerator<T>>();
+			try {
+				stack.Push(input.GetEnumerator());
+				while (stack.Count > 0) {
+					while (stack.Peek().MoveNext()) {
+						T element = stack.Peek().Current;
+						yield return element;
+						IEnumerable<T> children = recursion(element);
+						if (children != null) {
+							stack.Push(children.GetEnumerator());
+						}
+					}
+					stack.Pop().Dispose();
+				}
+			} finally {
+				while (stack.Count > 0) {
+					stack.Pop().Dispose();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Converts a tree data structure into a flat list by traversing it in post-order.
+		/// </summary>
+		/// <param name="root">The root element of the tree.</param>
+		/// <param name="recursion">The function that gets the children of an element.</param>
+		/// <returns>Iterator that enumerates the tree structure in post-order.</returns>
+		public static IEnumerable<T> PostOrder<T>(T root, Func<T, IEnumerable<T>> recursion)
+		{
+			return PostOrder(new T[] { root }, recursion);
+		}
+		
+		/// <summary>
+		/// Converts a tree data structure into a flat list by traversing it in post-order.
+		/// </summary>
+		/// <param name="input">The root elements of the forest.</param>
+		/// <param name="recursion">The function that gets the children of an element.</param>
+		/// <returns>Iterator that enumerates the tree structure in post-order.</returns>
+		public static IEnumerable<T> PostOrder<T>(IEnumerable<T> input, Func<T, IEnumerable<T>> recursion)
+		{
+			Stack<IEnumerator<T>> stack = new Stack<IEnumerator<T>>();
+			try {
+				stack.Push(input.GetEnumerator());
+				while (stack.Count > 0) {
+					while (stack.Peek().MoveNext()) {
+						T element = stack.Peek().Current;
+						IEnumerable<T> children = recursion(element);
+						if (children != null) {
+							stack.Push(children.GetEnumerator());
+						} else {
+							yield return element;
+						}
+					}
+					stack.Pop().Dispose();
+					if (stack.Count > 0)
+						yield return stack.Peek().Current;
+				}
+			} finally {
+				while (stack.Count > 0) {
+					stack.Pop().Dispose();
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/AnnotationNames.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/AnnotationNames.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/AnnotationNames.cs	(revision 11807)
@@ -0,0 +1,48 @@
+// 
+// Annotations.cs
+//  
+// Author:
+//       LuÃ­s Reis <luiscubal@gmail.com>
+// 
+// Copyright (c) 2013 LuÃ­s Reis
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public static class AnnotationNames
+	{
+		//Used const instead of readonly to allow values to be used in switch cases.
+
+		public const string AssertionMethodAttribute = "JetBrains.Annotations.AssertionMethodAttribute";
+		public const string AssertionConditionAttribute = "JetBrains.Annotations.AssertionConditionAttribute";
+		public const string AssertionConditionTypeAttribute = "JetBrains.Annotations.AssertionConditionType";
+
+		public const string AssertionConditionTypeIsTrue = "JetBrains.Annotations.AssertionConditionType.IS_TRUE";
+		public const string AssertionConditionTypeIsFalse = "JetBrains.Annotations.AssertionConditionType.IS_FALSE";
+		public const string AssertionConditionTypeIsNull = "JetBrains.Annotations.AssertionConditionType.IS_NULL";
+		public const string AssertionConditionTypeIsNotNull = "JetBrains.Annotations.AssertionConditionType.IS_NOT_NULL";
+
+		public const string NotNullAttribute = "JetBrains.Annotations.NotNullAttribute";
+		public const string CanBeNullAttribute = "JetBrains.Annotations.CanBeNullAttribute";
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/ControlFlow.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/ControlFlow.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/ControlFlow.cs	(revision 11807)
@@ -0,0 +1,803 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	/// <summary>
+	/// Represents a node in the control flow graph of a C# method.
+	/// </summary>
+	public class ControlFlowNode
+	{
+		public readonly Statement PreviousStatement;
+		public readonly Statement NextStatement;
+		
+		public readonly ControlFlowNodeType Type;
+		
+		public readonly List<ControlFlowEdge> Outgoing = new List<ControlFlowEdge>();
+		public readonly List<ControlFlowEdge> Incoming = new List<ControlFlowEdge>();
+		
+		public ControlFlowNode(Statement previousStatement, Statement nextStatement, ControlFlowNodeType type)
+		{
+			if (previousStatement == null && nextStatement == null)
+				throw new ArgumentException("previousStatement and nextStatement must not be both null");
+			this.PreviousStatement = previousStatement;
+			this.NextStatement = nextStatement;
+			this.Type = type;
+		}
+	}
+	
+	public enum ControlFlowNodeType
+	{
+		/// <summary>
+		/// Unknown node type
+		/// </summary>
+		None,
+		/// <summary>
+		/// Node in front of a statement
+		/// </summary>
+		StartNode,
+		/// <summary>
+		/// Node between two statements
+		/// </summary>
+		BetweenStatements,
+		/// <summary>
+		/// Node at the end of a statement list
+		/// </summary>
+		EndNode,
+		/// <summary>
+		/// Node representing the position before evaluating the condition of a loop.
+		/// </summary>
+		LoopCondition
+	}
+	
+	public class ControlFlowEdge
+	{
+		public readonly ControlFlowNode From;
+		public readonly ControlFlowNode To;
+		public readonly ControlFlowEdgeType Type;
+		
+		List<TryCatchStatement> jumpOutOfTryFinally;
+		
+		public ControlFlowEdge(ControlFlowNode from, ControlFlowNode to, ControlFlowEdgeType type)
+		{
+			if (from == null)
+				throw new ArgumentNullException("from");
+			if (to == null)
+				throw new ArgumentNullException("to");
+			this.From = from;
+			this.To = to;
+			this.Type = type;
+		}
+		
+		internal void AddJumpOutOfTryFinally(TryCatchStatement tryFinally)
+		{
+			if (jumpOutOfTryFinally == null)
+				jumpOutOfTryFinally = new List<TryCatchStatement>();
+			jumpOutOfTryFinally.Add(tryFinally);
+		}
+		
+		/// <summary>
+		/// Gets whether this control flow edge is leaving any try-finally statements.
+		/// </summary>
+		public bool IsLeavingTryFinally {
+			get { return jumpOutOfTryFinally != null; }
+		}
+		
+		/// <summary>
+		/// Gets the try-finally statements that this control flow edge is leaving.
+		/// </summary>
+		public IEnumerable<TryCatchStatement> TryFinallyStatements {
+			get { return jumpOutOfTryFinally ?? Enumerable.Empty<TryCatchStatement>(); }
+		}
+	}
+	
+	public enum ControlFlowEdgeType
+	{
+		/// <summary>
+		/// Regular control flow.
+		/// </summary>
+		Normal,
+		/// <summary>
+		/// Conditional control flow (edge taken if condition is true)
+		/// </summary>
+		ConditionTrue,
+		/// <summary>
+		/// Conditional control flow (edge taken if condition is false)
+		/// </summary>
+		ConditionFalse,
+		/// <summary>
+		/// A jump statement (goto, goto case, break or continue)
+		/// </summary>
+		Jump
+	}
+	
+	/// <summary>
+	/// Constructs the control flow graph for C# statements.
+	/// </summary>
+	public class ControlFlowGraphBuilder
+	{
+		// Written according to the reachability rules in the C# spec (§8.1 End points and reachability)
+		
+		protected virtual ControlFlowNode CreateNode(Statement previousStatement, Statement nextStatement, ControlFlowNodeType type)
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+			return new ControlFlowNode(previousStatement, nextStatement, type);
+		}
+		
+		protected virtual ControlFlowEdge CreateEdge(ControlFlowNode from, ControlFlowNode to, ControlFlowEdgeType type)
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+			return new ControlFlowEdge(from, to, type);
+		}
+		
+		Statement rootStatement;
+		CSharpTypeResolveContext typeResolveContext;
+		Func<AstNode, CancellationToken, ResolveResult> resolver;
+		List<ControlFlowNode> nodes;
+		Dictionary<string, ControlFlowNode> labels;
+		List<ControlFlowNode> gotoStatements;
+		CancellationToken cancellationToken;
+		
+		public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (statement == null)
+				throw new ArgumentNullException("statement");
+			CSharpResolver r = new CSharpResolver(MinimalCorlib.Instance.CreateCompilation());
+			return BuildControlFlowGraph(statement, new CSharpAstResolver(r, statement), cancellationToken);
+		}
+		
+		public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, CSharpAstResolver resolver, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (statement == null)
+				throw new ArgumentNullException("statement");
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			return BuildControlFlowGraph(statement, resolver.Resolve, resolver.TypeResolveContext, cancellationToken);
+		}
+		
+		internal IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, Func<AstNode, CancellationToken, ResolveResult> resolver, CSharpTypeResolveContext typeResolveContext, CancellationToken cancellationToken)
+		{
+			NodeCreationVisitor nodeCreationVisitor = new NodeCreationVisitor();
+			nodeCreationVisitor.builder = this;
+			try {
+				this.nodes = new List<ControlFlowNode>();
+				this.labels = new Dictionary<string, ControlFlowNode>();
+				this.gotoStatements = new List<ControlFlowNode>();
+				this.rootStatement = statement;
+				this.resolver = resolver;
+				this.typeResolveContext = typeResolveContext;
+				this.cancellationToken = cancellationToken;
+				
+				ControlFlowNode entryPoint = CreateStartNode(statement);
+				statement.AcceptVisitor(nodeCreationVisitor, entryPoint);
+				
+				// Resolve goto statements:
+				foreach (ControlFlowNode gotoStmt in gotoStatements) {
+					string label = ((GotoStatement)gotoStmt.NextStatement).Label;
+					ControlFlowNode labelNode;
+					if (labels.TryGetValue(label, out labelNode))
+						nodeCreationVisitor.Connect(gotoStmt, labelNode, ControlFlowEdgeType.Jump);
+				}
+				
+				AnnotateLeaveEdgesWithTryFinallyBlocks();
+				
+				return nodes;
+			} finally {
+				this.nodes = null;
+				this.labels = null;
+				this.gotoStatements = null;
+				this.rootStatement = null;
+				this.resolver = null;
+				this.typeResolveContext = null;
+				this.cancellationToken = CancellationToken.None;
+			}
+		}
+		
+		void AnnotateLeaveEdgesWithTryFinallyBlocks()
+		{
+			foreach (ControlFlowEdge edge in nodes.SelectMany(n => n.Outgoing)) {
+				if (edge.Type != ControlFlowEdgeType.Jump) {
+					// Only jumps are potential candidates for leaving try-finally blocks.
+					// Note that the regular edges leaving try or catch blocks are already annotated by the visitor.
+					continue;
+				}
+				Statement gotoStatement = edge.From.NextStatement;
+				Debug.Assert(gotoStatement is GotoStatement || gotoStatement is GotoDefaultStatement || gotoStatement is GotoCaseStatement || gotoStatement is BreakStatement || gotoStatement is ContinueStatement);
+				Statement targetStatement = edge.To.PreviousStatement ?? edge.To.NextStatement;
+				if (gotoStatement.Parent == targetStatement.Parent)
+					continue;
+				HashSet<TryCatchStatement> targetParentTryCatch = new HashSet<TryCatchStatement>(targetStatement.Ancestors.OfType<TryCatchStatement>());
+				for (AstNode node = gotoStatement.Parent; node != null; node = node.Parent) {
+					TryCatchStatement leftTryCatch = node as TryCatchStatement;
+					if (leftTryCatch != null) {
+						if (targetParentTryCatch.Contains(leftTryCatch))
+							break;
+						if (!leftTryCatch.FinallyBlock.IsNull)
+							edge.AddJumpOutOfTryFinally(leftTryCatch);
+					}
+				}
+			}
+		}
+		
+		#region Create*Node
+		ControlFlowNode CreateStartNode(Statement statement)
+		{
+			if (statement.IsNull)
+				return null;
+			ControlFlowNode node = CreateNode(null, statement, ControlFlowNodeType.StartNode);
+			nodes.Add(node);
+			return node;
+		}
+		
+		ControlFlowNode CreateSpecialNode(Statement statement, ControlFlowNodeType type, bool addToNodeList = true)
+		{
+			ControlFlowNode node = CreateNode(null, statement, type);
+			if (addToNodeList)
+				nodes.Add(node);
+			return node;
+		}
+		
+		ControlFlowNode CreateEndNode(Statement statement, bool addToNodeList = true)
+		{
+			Statement nextStatement;
+			if (statement == rootStatement) {
+				nextStatement = null;
+			} else {
+				// Find the next statement in the same role:
+				AstNode next = statement;
+				do {
+					next = next.NextSibling;
+				} while (next != null && next.Role != statement.Role);
+				nextStatement = next as Statement;
+			}
+			ControlFlowNodeType type = nextStatement != null ? ControlFlowNodeType.BetweenStatements : ControlFlowNodeType.EndNode;
+			ControlFlowNode node = CreateNode(statement, nextStatement, type);
+			if (addToNodeList)
+				nodes.Add(node);
+			return node;
+		}
+		#endregion
+		
+		#region Constant evaluation
+		/// <summary>
+		/// Gets/Sets whether to handle only primitive expressions as constants (no complex expressions like "a + b").
+		/// </summary>
+		public bool EvaluateOnlyPrimitiveConstants { get; set; }
+		
+		/// <summary>
+		/// Evaluates an expression.
+		/// </summary>
+		/// <returns>The constant value of the expression; or null if the expression is not a constant.</returns>
+		ResolveResult EvaluateConstant(Expression expr)
+		{
+			if (expr.IsNull)
+				return null;
+			if (EvaluateOnlyPrimitiveConstants) {
+				if (!(expr is PrimitiveExpression || expr is NullReferenceExpression))
+					return null;
+			}
+			return resolver(expr, cancellationToken);
+		}
+		
+		/// <summary>
+		/// Evaluates an expression.
+		/// </summary>
+		/// <returns>The value of the constant boolean expression; or null if the value is not a constant boolean expression.</returns>
+		bool? EvaluateCondition(Expression expr)
+		{
+			ResolveResult rr = EvaluateConstant(expr);
+			if (rr != null && rr.IsCompileTimeConstant)
+				return rr.ConstantValue as bool?;
+			else
+				return null;
+		}
+		
+		bool AreEqualConstants(ResolveResult c1, ResolveResult c2)
+		{
+			if (c1 == null || c2 == null || !c1.IsCompileTimeConstant || !c2.IsCompileTimeConstant)
+				return false;
+			CSharpResolver r = new CSharpResolver(typeResolveContext);
+			ResolveResult c = r.ResolveBinaryOperator(BinaryOperatorType.Equality, c1, c2);
+			return c.IsCompileTimeConstant && (c.ConstantValue as bool?) == true;
+		}
+		#endregion
+		
+		sealed class NodeCreationVisitor : DepthFirstAstVisitor<ControlFlowNode, ControlFlowNode>
+		{
+			// 'data' parameter: input control flow node (start of statement being visited)
+			// Return value: result control flow node (end of statement being visited)
+			
+			internal ControlFlowGraphBuilder builder;
+			Stack<ControlFlowNode> breakTargets = new Stack<ControlFlowNode>();
+			Stack<ControlFlowNode> continueTargets = new Stack<ControlFlowNode>();
+			List<ControlFlowNode> gotoCaseOrDefault = new List<ControlFlowNode>();
+			
+			internal ControlFlowEdge Connect(ControlFlowNode from, ControlFlowNode to, ControlFlowEdgeType type = ControlFlowEdgeType.Normal)
+			{
+				if (from == null || to == null)
+					return null;
+				ControlFlowEdge edge = builder.CreateEdge(from, to, type);
+				from.Outgoing.Add(edge);
+				to.Incoming.Add(edge);
+				return edge;
+			}
+			
+			/// <summary>
+			/// Creates an end node for <c>stmt</c> and connects <c>from</c> with the new node.
+			/// </summary>
+			ControlFlowNode CreateConnectedEndNode(Statement stmt, ControlFlowNode from)
+			{
+				ControlFlowNode newNode = builder.CreateEndNode(stmt);
+				Connect(from, newNode);
+				return newNode;
+			}
+			
+			protected override ControlFlowNode VisitChildren(AstNode node, ControlFlowNode data)
+			{
+				// We have overrides for all possible statements and should visit statements only.
+				throw new NotSupportedException();
+			}
+			
+			public override ControlFlowNode VisitBlockStatement(BlockStatement blockStatement, ControlFlowNode data)
+			{
+				// C# 4.0 spec: §8.2 Blocks
+				ControlFlowNode childNode = HandleStatementList(blockStatement.Statements, data);
+				return CreateConnectedEndNode(blockStatement, childNode);
+			}
+			
+			ControlFlowNode HandleStatementList(AstNodeCollection<Statement> statements, ControlFlowNode source)
+			{
+				ControlFlowNode childNode = null;
+				foreach (Statement stmt in statements) {
+					if (childNode == null) {
+						childNode = builder.CreateStartNode(stmt);
+						if (source != null)
+							Connect(source, childNode);
+					}
+					Debug.Assert(childNode.NextStatement == stmt);
+					childNode = stmt.AcceptVisitor(this, childNode);
+					Debug.Assert(childNode.PreviousStatement == stmt);
+				}
+				return childNode ?? source;
+			}
+			
+			public override ControlFlowNode VisitEmptyStatement(EmptyStatement emptyStatement, ControlFlowNode data)
+			{
+				return CreateConnectedEndNode(emptyStatement, data);
+			}
+			
+			public override ControlFlowNode VisitLabelStatement(LabelStatement labelStatement, ControlFlowNode data)
+			{
+				ControlFlowNode end = CreateConnectedEndNode(labelStatement, data);
+				builder.labels[labelStatement.Label] = end;
+				return end;
+			}
+			
+			public override ControlFlowNode VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, ControlFlowNode data)
+			{
+				return CreateConnectedEndNode(variableDeclarationStatement, data);
+			}
+			
+			public override ControlFlowNode VisitExpressionStatement(ExpressionStatement expressionStatement, ControlFlowNode data)
+			{
+				return CreateConnectedEndNode(expressionStatement, data);
+			}
+			
+			public override ControlFlowNode VisitIfElseStatement(IfElseStatement ifElseStatement, ControlFlowNode data)
+			{
+				bool? cond = builder.EvaluateCondition(ifElseStatement.Condition);
+				
+				ControlFlowNode trueBegin = builder.CreateStartNode(ifElseStatement.TrueStatement);
+				if (cond != false)
+					Connect(data, trueBegin, ControlFlowEdgeType.ConditionTrue);
+				ControlFlowNode trueEnd = ifElseStatement.TrueStatement.AcceptVisitor(this, trueBegin);
+				
+				ControlFlowNode falseBegin = builder.CreateStartNode(ifElseStatement.FalseStatement);
+				if (cond != true)
+					Connect(data, falseBegin, ControlFlowEdgeType.ConditionFalse);
+				ControlFlowNode falseEnd = ifElseStatement.FalseStatement.AcceptVisitor(this, falseBegin);
+				// (if no else statement exists, both falseBegin and falseEnd will be null)
+				
+				ControlFlowNode end = builder.CreateEndNode(ifElseStatement);
+				Connect(trueEnd, end);
+				if (falseEnd != null) {
+					Connect(falseEnd, end);
+				} else if (cond != true) {
+					Connect(data, end, ControlFlowEdgeType.ConditionFalse);
+				}
+				return end;
+			}
+			
+			public override ControlFlowNode VisitSwitchStatement(SwitchStatement switchStatement, ControlFlowNode data)
+			{
+				// First, figure out which switch section will get called (if the expression is constant):
+				ResolveResult constant = builder.EvaluateConstant(switchStatement.Expression);
+				SwitchSection defaultSection = null;
+				SwitchSection sectionMatchedByConstant = null;
+				foreach (SwitchSection section in switchStatement.SwitchSections) {
+					foreach (CaseLabel label in section.CaseLabels) {
+						if (label.Expression.IsNull) {
+							defaultSection = section;
+						} else if (constant != null && constant.IsCompileTimeConstant) {
+							ResolveResult labelConstant = builder.EvaluateConstant(label.Expression);
+							if (builder.AreEqualConstants(constant, labelConstant))
+								sectionMatchedByConstant = section;
+						}
+					}
+				}
+				if (constant != null && constant.IsCompileTimeConstant && sectionMatchedByConstant == null)
+					sectionMatchedByConstant = defaultSection;
+				
+				int gotoCaseOrDefaultInOuterScope = gotoCaseOrDefault.Count;
+				List<ControlFlowNode> sectionStartNodes = new List<ControlFlowNode>();
+				
+				ControlFlowNode end = builder.CreateEndNode(switchStatement, addToNodeList: false);
+				breakTargets.Push(end);
+				foreach (SwitchSection section in switchStatement.SwitchSections) {
+					int sectionStartNodeID = builder.nodes.Count;
+					if (constant == null || !constant.IsCompileTimeConstant || section == sectionMatchedByConstant) {
+						HandleStatementList(section.Statements, data);
+					} else {
+						// This section is unreachable: pass null to HandleStatementList.
+						HandleStatementList(section.Statements, null);
+					}
+					// Don't bother connecting the ends of the sections: the 'break' statement takes care of that.
+					
+					// Store the section start node for 'goto case' statements.
+					sectionStartNodes.Add(sectionStartNodeID < builder.nodes.Count ? builder.nodes[sectionStartNodeID] : null);
+				}
+				breakTargets.Pop();
+				if (defaultSection == null && sectionMatchedByConstant == null) {
+					Connect(data, end);
+				}
+				
+				if (gotoCaseOrDefault.Count > gotoCaseOrDefaultInOuterScope) {
+					// Resolve 'goto case' statements:
+					for (int i = gotoCaseOrDefaultInOuterScope; i < gotoCaseOrDefault.Count; i++) {
+						ControlFlowNode gotoCaseNode = gotoCaseOrDefault[i];
+						GotoCaseStatement gotoCaseStatement = gotoCaseNode.NextStatement as GotoCaseStatement;
+						ResolveResult gotoCaseConstant = null;
+						if (gotoCaseStatement != null) {
+							gotoCaseConstant = builder.EvaluateConstant(gotoCaseStatement.LabelExpression);
+						}
+						int targetSectionIndex = -1;
+						int currentSectionIndex = 0;
+						foreach (SwitchSection section in switchStatement.SwitchSections) {
+							foreach (CaseLabel label in section.CaseLabels) {
+								if (gotoCaseStatement != null) {
+									// goto case
+									if (!label.Expression.IsNull) {
+										ResolveResult labelConstant = builder.EvaluateConstant(label.Expression);
+										if (builder.AreEqualConstants(gotoCaseConstant, labelConstant))
+											targetSectionIndex = currentSectionIndex;
+									}
+								} else {
+									// goto default
+									if (label.Expression.IsNull)
+										targetSectionIndex = currentSectionIndex;
+								}
+							}
+							currentSectionIndex++;
+						}
+						if (targetSectionIndex >= 0 && sectionStartNodes[targetSectionIndex] != null)
+							Connect(gotoCaseNode, sectionStartNodes[targetSectionIndex], ControlFlowEdgeType.Jump);
+						else
+							Connect(gotoCaseNode, end, ControlFlowEdgeType.Jump);
+					}
+					gotoCaseOrDefault.RemoveRange(gotoCaseOrDefaultInOuterScope, gotoCaseOrDefault.Count - gotoCaseOrDefaultInOuterScope);
+				}
+				
+				builder.nodes.Add(end);
+				return end;
+			}
+			
+			public override ControlFlowNode VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, ControlFlowNode data)
+			{
+				gotoCaseOrDefault.Add(data);
+				return builder.CreateEndNode(gotoCaseStatement);
+			}
+			
+			public override ControlFlowNode VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, ControlFlowNode data)
+			{
+				gotoCaseOrDefault.Add(data);
+				return builder.CreateEndNode(gotoDefaultStatement);
+			}
+			
+			public override ControlFlowNode VisitWhileStatement(WhileStatement whileStatement, ControlFlowNode data)
+			{
+				// <data> <condition> while (cond) { <bodyStart> embeddedStmt; <bodyEnd> } <end>
+				ControlFlowNode end = builder.CreateEndNode(whileStatement, addToNodeList: false);
+				ControlFlowNode conditionNode = builder.CreateSpecialNode(whileStatement, ControlFlowNodeType.LoopCondition);
+				breakTargets.Push(end);
+				continueTargets.Push(conditionNode);
+				
+				Connect(data, conditionNode);
+				
+				bool? cond = builder.EvaluateCondition(whileStatement.Condition);
+				ControlFlowNode bodyStart = builder.CreateStartNode(whileStatement.EmbeddedStatement);
+				if (cond != false)
+					Connect(conditionNode, bodyStart, ControlFlowEdgeType.ConditionTrue);
+				ControlFlowNode bodyEnd = whileStatement.EmbeddedStatement.AcceptVisitor(this, bodyStart);
+				Connect(bodyEnd, conditionNode);
+				if (cond != true)
+					Connect(conditionNode, end, ControlFlowEdgeType.ConditionFalse);
+				
+				breakTargets.Pop();
+				continueTargets.Pop();
+				builder.nodes.Add(end);
+				return end;
+			}
+			
+			public override ControlFlowNode VisitDoWhileStatement(DoWhileStatement doWhileStatement, ControlFlowNode data)
+			{
+				// <data> do { <bodyStart> embeddedStmt; <bodyEnd>} <condition> while(cond); <end>
+				ControlFlowNode end = builder.CreateEndNode(doWhileStatement, addToNodeList: false);
+				ControlFlowNode conditionNode = builder.CreateSpecialNode(doWhileStatement, ControlFlowNodeType.LoopCondition, addToNodeList: false);
+				breakTargets.Push(end);
+				continueTargets.Push(conditionNode);
+				
+				ControlFlowNode bodyStart = builder.CreateStartNode(doWhileStatement.EmbeddedStatement);
+				Connect(data, bodyStart);
+				ControlFlowNode bodyEnd = doWhileStatement.EmbeddedStatement.AcceptVisitor(this, bodyStart);
+				Connect(bodyEnd, conditionNode);
+				
+				bool? cond = builder.EvaluateCondition(doWhileStatement.Condition);
+				if (cond != false)
+					Connect(conditionNode, bodyStart, ControlFlowEdgeType.ConditionTrue);
+				if (cond != true)
+					Connect(conditionNode, end, ControlFlowEdgeType.ConditionFalse);
+				
+				breakTargets.Pop();
+				continueTargets.Pop();
+				builder.nodes.Add(conditionNode);
+				builder.nodes.Add(end);
+				return end;
+			}
+			
+			public override ControlFlowNode VisitForStatement(ForStatement forStatement, ControlFlowNode data)
+			{
+				data = HandleStatementList(forStatement.Initializers, data);
+				// for (initializers <data>; <condition>cond; <iteratorStart>iterators<iteratorEnd>) { <bodyStart> embeddedStmt; <bodyEnd> } <end>
+				ControlFlowNode end = builder.CreateEndNode(forStatement, addToNodeList: false);
+				ControlFlowNode conditionNode = builder.CreateSpecialNode(forStatement, ControlFlowNodeType.LoopCondition);
+				Connect(data, conditionNode);
+				
+				int iteratorStartNodeID = builder.nodes.Count;
+				ControlFlowNode iteratorEnd = HandleStatementList(forStatement.Iterators, null);
+				ControlFlowNode iteratorStart;
+				if (iteratorEnd != null) {
+					iteratorStart = builder.nodes[iteratorStartNodeID];
+					Connect(iteratorEnd, conditionNode);
+				} else {
+					iteratorStart = conditionNode;
+				}
+				
+				breakTargets.Push(end);
+				continueTargets.Push(iteratorStart);
+				
+				ControlFlowNode bodyStart = builder.CreateStartNode(forStatement.EmbeddedStatement);
+				ControlFlowNode bodyEnd = forStatement.EmbeddedStatement.AcceptVisitor(this, bodyStart);
+				Connect(bodyEnd, iteratorStart);
+				
+				breakTargets.Pop();
+				continueTargets.Pop();
+				
+				bool? cond = forStatement.Condition.IsNull ? true : builder.EvaluateCondition(forStatement.Condition);
+				if (cond != false)
+					Connect(conditionNode, bodyStart, ControlFlowEdgeType.ConditionTrue);
+				if (cond != true)
+					Connect(conditionNode, end, ControlFlowEdgeType.ConditionFalse);
+				
+				builder.nodes.Add(end);
+				return end;
+			}
+			
+			ControlFlowNode HandleEmbeddedStatement(Statement embeddedStatement, ControlFlowNode source)
+			{
+				if (embeddedStatement == null || embeddedStatement.IsNull)
+					return source;
+				ControlFlowNode bodyStart = builder.CreateStartNode(embeddedStatement);
+				if (source != null)
+					Connect(source, bodyStart);
+				return embeddedStatement.AcceptVisitor(this, bodyStart);
+			}
+			
+			public override ControlFlowNode VisitForeachStatement(ForeachStatement foreachStatement, ControlFlowNode data)
+			{
+				// <data> foreach (<condition>...) { <bodyStart>embeddedStmt<bodyEnd> } <end>
+				ControlFlowNode end = builder.CreateEndNode(foreachStatement, addToNodeList: false);
+				ControlFlowNode conditionNode = builder.CreateSpecialNode(foreachStatement, ControlFlowNodeType.LoopCondition);
+				Connect(data, conditionNode);
+				
+				breakTargets.Push(end);
+				continueTargets.Push(conditionNode);
+				
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(foreachStatement.EmbeddedStatement, conditionNode);
+				Connect(bodyEnd, conditionNode);
+				
+				breakTargets.Pop();
+				continueTargets.Pop();
+				
+				Connect(conditionNode, end);
+				builder.nodes.Add(end);
+				return end;
+			}
+			
+			public override ControlFlowNode VisitBreakStatement(BreakStatement breakStatement, ControlFlowNode data)
+			{
+				if (breakTargets.Count > 0)
+					Connect(data, breakTargets.Peek(), ControlFlowEdgeType.Jump);
+				return builder.CreateEndNode(breakStatement);
+			}
+			
+			public override ControlFlowNode VisitContinueStatement(ContinueStatement continueStatement, ControlFlowNode data)
+			{
+				if (continueTargets.Count > 0)
+					Connect(data, continueTargets.Peek(), ControlFlowEdgeType.Jump);
+				return builder.CreateEndNode(continueStatement);
+			}
+			
+			public override ControlFlowNode VisitGotoStatement(GotoStatement gotoStatement, ControlFlowNode data)
+			{
+				builder.gotoStatements.Add(data);
+				return builder.CreateEndNode(gotoStatement);
+			}
+			
+			public override ControlFlowNode VisitReturnStatement(ReturnStatement returnStatement, ControlFlowNode data)
+			{
+				return builder.CreateEndNode(returnStatement); // end not connected with data
+			}
+			
+			public override ControlFlowNode VisitThrowStatement(ThrowStatement throwStatement, ControlFlowNode data)
+			{
+				return builder.CreateEndNode(throwStatement); // end not connected with data
+			}
+			
+			public override ControlFlowNode VisitTryCatchStatement(TryCatchStatement tryCatchStatement, ControlFlowNode data)
+			{
+				ControlFlowNode end = builder.CreateEndNode(tryCatchStatement, addToNodeList: false);
+				var edge = Connect(HandleEmbeddedStatement(tryCatchStatement.TryBlock, data), end);
+				if (!tryCatchStatement.FinallyBlock.IsNull)
+					edge.AddJumpOutOfTryFinally(tryCatchStatement);
+				foreach (CatchClause cc in tryCatchStatement.CatchClauses) {
+					edge = Connect(HandleEmbeddedStatement(cc.Body, data), end);
+					if (!tryCatchStatement.FinallyBlock.IsNull)
+						edge.AddJumpOutOfTryFinally(tryCatchStatement);
+				}
+				if (!tryCatchStatement.FinallyBlock.IsNull) {
+					// Don't connect the end of the try-finally block to anything.
+					// Consumers of the CFG will have to special-case try-finally.
+					HandleEmbeddedStatement(tryCatchStatement.FinallyBlock, data);
+				}
+				builder.nodes.Add(end);
+				return end;
+			}
+			
+			public override ControlFlowNode VisitCheckedStatement(CheckedStatement checkedStatement, ControlFlowNode data)
+			{
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(checkedStatement.Body, data);
+				return CreateConnectedEndNode(checkedStatement, bodyEnd);
+			}
+			
+			public override ControlFlowNode VisitUncheckedStatement(UncheckedStatement uncheckedStatement, ControlFlowNode data)
+			{
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(uncheckedStatement.Body, data);
+				return CreateConnectedEndNode(uncheckedStatement, bodyEnd);
+			}
+			
+			public override ControlFlowNode VisitLockStatement(LockStatement lockStatement, ControlFlowNode data)
+			{
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(lockStatement.EmbeddedStatement, data);
+				return CreateConnectedEndNode(lockStatement, bodyEnd);
+			}
+			
+			public override ControlFlowNode VisitUsingStatement(UsingStatement usingStatement, ControlFlowNode data)
+			{
+				data = HandleEmbeddedStatement(usingStatement.ResourceAcquisition as Statement, data);
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(usingStatement.EmbeddedStatement, data);
+				return CreateConnectedEndNode(usingStatement, bodyEnd);
+			}
+			
+			public override ControlFlowNode VisitYieldReturnStatement(YieldReturnStatement yieldStatement, ControlFlowNode data)
+			{
+				return CreateConnectedEndNode(yieldStatement, data);
+			}
+			
+			public override ControlFlowNode VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, ControlFlowNode data)
+			{
+				return builder.CreateEndNode(yieldBreakStatement); // end not connected with data
+			}
+			
+			public override ControlFlowNode VisitUnsafeStatement(UnsafeStatement unsafeStatement, ControlFlowNode data)
+			{
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(unsafeStatement.Body, data);
+				return CreateConnectedEndNode(unsafeStatement, bodyEnd);
+			}
+			
+			public override ControlFlowNode VisitFixedStatement(FixedStatement fixedStatement, ControlFlowNode data)
+			{
+				ControlFlowNode bodyEnd = HandleEmbeddedStatement(fixedStatement.EmbeddedStatement, data);
+				return CreateConnectedEndNode(fixedStatement, bodyEnd);
+			}
+		}
+		
+		/// <summary>
+		/// Debugging helper that exports a control flow graph.
+		/// </summary>
+		public static GraphVizGraph ExportGraph(IList<ControlFlowNode> nodes)
+		{
+			GraphVizGraph g = new GraphVizGraph();
+			GraphVizNode[] n = new GraphVizNode[nodes.Count];
+			Dictionary<ControlFlowNode, int> dict = new Dictionary<ControlFlowNode, int>();
+			for (int i = 0; i < n.Length; i++) {
+				dict.Add(nodes[i], i);
+				n[i] = new GraphVizNode(i);
+				string name = "#" + i + " = ";
+				switch (nodes[i].Type) {
+					case ControlFlowNodeType.StartNode:
+					case ControlFlowNodeType.BetweenStatements:
+						name += nodes[i].NextStatement.DebugToString();
+						break;
+					case ControlFlowNodeType.EndNode:
+						name += "End of " + nodes[i].PreviousStatement.DebugToString();
+						break;
+					case ControlFlowNodeType.LoopCondition:
+						name += "Condition in " + nodes[i].NextStatement.DebugToString();
+						break;
+					default:
+						name += "?";
+						break;
+				}
+				n[i].label = name;
+				g.AddNode(n[i]);
+			}
+			for (int i = 0; i < n.Length; i++) {
+				foreach (ControlFlowEdge edge in nodes[i].Outgoing) {
+					GraphVizEdge ge = new GraphVizEdge(i, dict[edge.To]);
+					if (edge.IsLeavingTryFinally)
+						ge.style = "dashed";
+					switch (edge.Type) {
+						case ControlFlowEdgeType.ConditionTrue:
+							ge.color = "green";
+							break;
+						case ControlFlowEdgeType.ConditionFalse:
+							ge.color = "red";
+							break;
+						case ControlFlowEdgeType.Jump:
+							ge.color = "blue";
+							break;
+					}
+					g.AddEdge(ge);
+				}
+			}
+			return g;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DeclarationSpace/LocalDeclarationSpace.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DeclarationSpace/LocalDeclarationSpace.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DeclarationSpace/LocalDeclarationSpace.cs	(revision 11807)
@@ -0,0 +1,157 @@
+// 
+// LovalVariableDeclarationSpace.cs
+//  
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+// 
+// Copyright (c) 2013 Simon Lindgren
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using ICSharpCode.NRefactory.Utils;
+using System.Collections.Generic;
+using System.Linq;
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	/// <summary>
+	/// Represents a declaration space. (Â§3.3)
+	/// </summary>
+	public class LocalDeclarationSpace
+	{
+		/// <summary>
+		/// Maps from variable name to the declarations in this declaration space.
+		/// </summary>
+		/// <remarks>
+		/// This maps from variable name
+		/// </remarks>
+		MultiDictionary<string, AstNode> declarations = new MultiDictionary<string, AstNode> ();
+
+		public LocalDeclarationSpace()
+		{
+			Children = new List<LocalDeclarationSpace> ();
+		}
+
+		/// <summary>
+		/// The child declaration spaces.
+		/// </summary>
+		public IList<LocalDeclarationSpace> Children {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// The parent declaration space.
+		/// </summary>
+		/// <value>The parent.</value>
+		public LocalDeclarationSpace Parent {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// The names declared in this declaration space, excluding child spaces.
+		/// </summary>
+		/// <value>The declared names.</value>
+		public ICollection<string> DeclaredNames {
+			get {
+				return declarations.Keys;
+			}
+		}
+
+		/// <summary>
+		/// Get all nodes declaring the name specified in <paramref name="name"/>.
+		/// </summary>
+		/// <returns>The declaring nodes.</returns>
+		/// <param name="name">The declaration name.</param>
+		public IEnumerable<AstNode> GetNameDeclarations(string name)
+		{
+			return declarations [name].Concat(Children.SelectMany(child => child.GetNameDeclarations(name)));
+		}
+
+		/// <summary>
+		/// Adds a child declaration space.
+		/// </summary>
+		/// <param name="child">The <see cref="LocalDeclarationSpace"/> to add.</param>
+		public void AddChildSpace(LocalDeclarationSpace child)
+		{
+			if (child == null)
+				throw new ArgumentNullException("child");
+			if (Children.Contains(child))
+				throw new InvalidOperationException("the child was already added");
+
+			Children.Add(child);
+			child.Parent = this;
+		}
+
+		/// <summary>
+		/// Adds a new declaration to the declaration space.
+		/// </summary>
+		/// <param name="name">The name of the declared variable.</param>
+		/// <param name="node">A node associated with the declaration.</param>
+		public void AddDeclaration(string name, AstNode node)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+			if (node == null)
+				throw new ArgumentNullException("node");
+			declarations.Add(name, node);
+		}
+
+		/// <summary>
+		/// Determines if the name exists in the this declaration space.
+		/// </summary>
+		/// <returns><c>true</c>, if the name specified in <paramref name="name"/> is used in this variable declaration space, <c>false</c> otherwise.</returns>
+		/// <param name="name">The name to look for.</param>
+		/// <param name="includeChildren">When <c>true</c>, child declaration spaces are included in the search.</param>
+		public bool ContainsName(string name, bool includeChildren)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+
+			if (declarations.Keys.Contains(name)) 
+				return true;
+			return includeChildren && Children.Any(child => child.ContainsName(name, true));
+		}
+
+		/// <summary>
+		/// Determines whether the name specified in <paramref name="name"/> is used in surrouding code.
+		/// </summary>
+		/// <returns><c>true</c> if the name is used, <c>false</c> otherwise.</returns>
+		/// <param name="name">The name to check.</param>
+		/// <remarks>
+		/// Contrary to <see cref="ContainsName"/>, this method also checks parent declaration spaces
+		/// for name conflicts. Typically, this will be the right method to use when determining if a name can be used.
+		/// </remarks>
+		public bool IsNameUsed(string name)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+
+			return IsNameUsedBySelfOrParent(name) || Children.Any(child => child.ContainsName(name, true));
+		}
+
+		bool IsNameUsedBySelfOrParent(string name)
+		{
+			if (declarations.Keys.Contains(name))
+				return true;
+			return Parent != null && Parent.IsNameUsedBySelfOrParent(name);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DeclarationSpace/LocalDeclarationSpaceVisitor.cs	(revision 11807)
@@ -0,0 +1,138 @@
+//
+// LocalDeclarationSpaceVisitor.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2013 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	public class LocalDeclarationSpaceVisitor : DepthFirstAstVisitor
+	{
+		LocalDeclarationSpace currentDeclarationSpace;
+		Dictionary<AstNode, LocalDeclarationSpace> nodeDeclarationSpaces = new Dictionary<AstNode, LocalDeclarationSpace>();
+		
+		public LocalDeclarationSpace GetDeclarationSpace(AstNode node)
+		{
+			if (node == null)
+				throw new ArgumentNullException("node");
+			while (node != null) {
+				LocalDeclarationSpace declarationSpace;
+				if (nodeDeclarationSpaces.TryGetValue(node, out declarationSpace))
+					return declarationSpace;
+				node = node.Parent;
+			}
+			return null;
+		}
+
+		#region Visitor
+
+		void AddDeclaration(string name, AstNode node)
+		{
+			if (currentDeclarationSpace != null)
+				currentDeclarationSpace.AddDeclaration(name, node);
+		}
+
+		public override void VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			AddDeclaration(variableInitializer.Name, variableInitializer);
+			base.VisitVariableInitializer(variableInitializer);
+		}
+
+		public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			AddDeclaration(parameterDeclaration.Name, parameterDeclaration);
+			base.VisitParameterDeclaration(parameterDeclaration);
+		}
+
+		void VisitNewDeclarationSpace(AstNode node)
+		{
+			var oldDeclarationSpace = currentDeclarationSpace;
+			currentDeclarationSpace = new LocalDeclarationSpace();
+			if (oldDeclarationSpace != null)
+				oldDeclarationSpace.AddChildSpace(currentDeclarationSpace);
+
+			VisitChildren(node);
+
+			nodeDeclarationSpaces.Add(node, currentDeclarationSpace);
+			currentDeclarationSpace = oldDeclarationSpace;
+		}
+
+		#region Declaration space creating nodes
+		
+		public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			VisitNewDeclarationSpace(methodDeclaration);
+		}
+
+		public override void VisitBlockStatement(BlockStatement blockStatement)
+		{
+			VisitNewDeclarationSpace(blockStatement);
+		}
+
+		public override void VisitSwitchStatement(SwitchStatement switchStatement)
+		{
+			VisitNewDeclarationSpace(switchStatement);
+		}
+
+		public override void VisitForeachStatement(ForeachStatement foreachStatement)
+		{
+			AddDeclaration(foreachStatement.VariableName, foreachStatement);
+			VisitNewDeclarationSpace(foreachStatement);
+		}
+		
+		public override void VisitForStatement(ForStatement forStatement)
+		{
+			VisitNewDeclarationSpace(forStatement);
+		}
+
+		public override void VisitUsingStatement(UsingStatement usingStatement)
+		{
+			VisitNewDeclarationSpace(usingStatement);
+		}
+
+		public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
+		{
+			VisitNewDeclarationSpace(lambdaExpression);
+		}
+
+		public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
+		{
+			VisitNewDeclarationSpace(anonymousMethodExpression);
+		}
+
+		public override void VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			AddDeclaration(eventDeclaration.Name, eventDeclaration);
+		}
+
+		public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
+		{
+			VisitNewDeclarationSpace(eventDeclaration);
+		}
+
+		#endregion
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DefiniteAssignmentAnalysis.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DefiniteAssignmentAnalysis.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/DefiniteAssignmentAnalysis.cs	(revision 11807)
@@ -0,0 +1,759 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	/// <summary>
+	/// Represents the definite assignment status of a variable at a specific location.
+	/// </summary>
+	public enum DefiniteAssignmentStatus
+	{
+		/// <summary>
+		/// The variable might be assigned or unassigned.
+		/// </summary>
+		PotentiallyAssigned,
+		/// <summary>
+		/// The variable is definitely assigned.
+		/// </summary>
+		DefinitelyAssigned,
+		/// <summary>
+		/// The variable is definitely assigned iff the expression results in the value 'true'.
+		/// </summary>
+		AssignedAfterTrueExpression,
+		/// <summary>
+		/// The variable is definitely assigned iff the expression results in the value 'false'.
+		/// </summary>
+		AssignedAfterFalseExpression,
+		/// <summary>
+		/// The code is unreachable.
+		/// </summary>
+		CodeUnreachable
+	}
+	
+	/// <summary>
+	/// Implements the C# definite assignment analysis (C# 4.0 Spec: §5.3 Definite assignment)
+	/// </summary>
+	public class DefiniteAssignmentAnalysis
+	{
+		sealed class DefiniteAssignmentNode : ControlFlowNode
+		{
+			public int Index;
+			public DefiniteAssignmentStatus NodeStatus;
+			
+			public DefiniteAssignmentNode(Statement previousStatement, Statement nextStatement, ControlFlowNodeType type)
+				: base(previousStatement, nextStatement, type)
+			{
+			}
+		}
+		
+		sealed class DerivedControlFlowGraphBuilder : ControlFlowGraphBuilder
+		{
+			protected override ControlFlowNode CreateNode(Statement previousStatement, Statement nextStatement, ControlFlowNodeType type)
+			{
+				return new DefiniteAssignmentNode(previousStatement, nextStatement, type);
+			}
+		}
+		
+		readonly DefiniteAssignmentVisitor visitor = new DefiniteAssignmentVisitor();
+		readonly List<DefiniteAssignmentNode> allNodes = new List<DefiniteAssignmentNode>();
+		readonly Dictionary<Statement, DefiniteAssignmentNode> beginNodeDict = new Dictionary<Statement, DefiniteAssignmentNode>();
+		readonly Dictionary<Statement, DefiniteAssignmentNode> endNodeDict = new Dictionary<Statement, DefiniteAssignmentNode>();
+		readonly Dictionary<Statement, DefiniteAssignmentNode> conditionNodeDict = new Dictionary<Statement, DefiniteAssignmentNode>();
+		readonly CSharpAstResolver resolver;
+		Dictionary<ControlFlowEdge, DefiniteAssignmentStatus> edgeStatus = new Dictionary<ControlFlowEdge, DefiniteAssignmentStatus>();
+		
+		string variableName;
+		List<IdentifierExpression> unassignedVariableUses = new List<IdentifierExpression>();
+		int analyzedRangeStart, analyzedRangeEnd;
+		CancellationToken analysisCancellationToken;
+		
+		Queue<DefiniteAssignmentNode> nodesWithModifiedInput = new Queue<DefiniteAssignmentNode>();
+		
+		public DefiniteAssignmentAnalysis(Statement rootStatement, CancellationToken cancellationToken)
+			: this(rootStatement,
+			       new CSharpAstResolver(new CSharpResolver(MinimalCorlib.Instance.CreateCompilation()), rootStatement),
+			       cancellationToken)
+		{
+		}
+		
+		public DefiniteAssignmentAnalysis(Statement rootStatement, CSharpAstResolver resolver, CancellationToken cancellationToken)
+		{
+			if (rootStatement == null)
+				throw new ArgumentNullException("rootStatement");
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			this.resolver = resolver;
+			
+			visitor.analysis = this;
+			DerivedControlFlowGraphBuilder cfgBuilder = new DerivedControlFlowGraphBuilder();
+			if (resolver.TypeResolveContext.Compilation.MainAssembly.UnresolvedAssembly is MinimalCorlib) {
+				cfgBuilder.EvaluateOnlyPrimitiveConstants = true;
+			}
+			allNodes.AddRange(cfgBuilder.BuildControlFlowGraph(rootStatement, resolver, cancellationToken).Cast<DefiniteAssignmentNode>());
+			for (int i = 0; i < allNodes.Count; i++) {
+				DefiniteAssignmentNode node = allNodes[i];
+				node.Index = i; // assign numbers to the nodes
+				if (node.Type == ControlFlowNodeType.StartNode || node.Type == ControlFlowNodeType.BetweenStatements) {
+					// Anonymous methods have separate control flow graphs, but we also need to analyze those.
+					// Iterate backwards so that anonymous methods are inserted in the correct order
+					for (AstNode child = node.NextStatement.LastChild; child != null; child = child.PrevSibling) {
+						InsertAnonymousMethods(i + 1, child, cfgBuilder, cancellationToken);
+					}
+				}
+				// Now register the node in the dictionaries:
+				if (node.Type == ControlFlowNodeType.StartNode || node.Type == ControlFlowNodeType.BetweenStatements)
+					beginNodeDict.Add(node.NextStatement, node);
+				if (node.Type == ControlFlowNodeType.BetweenStatements || node.Type == ControlFlowNodeType.EndNode)
+					endNodeDict.Add(node.PreviousStatement, node);
+				if (node.Type == ControlFlowNodeType.LoopCondition)
+					conditionNodeDict.Add(node.NextStatement, node);
+			}
+			// Verify that we created nodes for all statements:
+			Debug.Assert(!rootStatement.DescendantsAndSelf.OfType<Statement>().Except(allNodes.Select(n => n.NextStatement)).Any());
+			// Verify that we put all nodes into the dictionaries:
+			Debug.Assert(rootStatement.DescendantsAndSelf.OfType<Statement>().All(stmt => beginNodeDict.ContainsKey(stmt)));
+			Debug.Assert(rootStatement.DescendantsAndSelf.OfType<Statement>().All(stmt => endNodeDict.ContainsKey(stmt)));
+			
+			this.analyzedRangeStart = 0;
+			this.analyzedRangeEnd = allNodes.Count - 1;
+		}
+		
+		void InsertAnonymousMethods(int insertPos, AstNode node, ControlFlowGraphBuilder cfgBuilder, CancellationToken cancellationToken)
+		{
+			// Ignore any statements, as those have their own ControlFlowNode and get handled separately
+			if (node is Statement)
+				return;
+			AnonymousMethodExpression ame = node as AnonymousMethodExpression;
+			if (ame != null) {
+				allNodes.InsertRange(insertPos, cfgBuilder.BuildControlFlowGraph(ame.Body, resolver, cancellationToken).Cast<DefiniteAssignmentNode>());
+				return;
+			}
+			LambdaExpression lambda = node as LambdaExpression;
+			if (lambda != null && lambda.Body is Statement) {
+				allNodes.InsertRange(insertPos, cfgBuilder.BuildControlFlowGraph((Statement)lambda.Body, resolver, cancellationToken).Cast<DefiniteAssignmentNode>());
+				return;
+			}
+			// Descend into child expressions
+			// Iterate backwards so that anonymous methods are inserted in the correct order
+			for (AstNode child = node.LastChild; child != null; child = child.PrevSibling) {
+				InsertAnonymousMethods(insertPos, child, cfgBuilder, cancellationToken);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the unassigned usages of the previously analyzed variable.
+		/// </summary>
+		public IList<IdentifierExpression> UnassignedVariableUses {
+			get {
+				return unassignedVariableUses.AsReadOnly();
+			}
+		}
+		
+		/// <summary>
+		/// Sets the range of statements to be analyzed.
+		/// This method can be used to restrict the analysis to only a part of the method.
+		/// Only the control flow paths that are fully contained within the selected part will be analyzed.
+		/// </summary>
+		/// <remarks>By default, both 'start' and 'end' are inclusive.</remarks>
+		public void SetAnalyzedRange(Statement start, Statement end, bool startInclusive = true, bool endInclusive = true)
+		{
+			var dictForStart = startInclusive ? beginNodeDict : endNodeDict;
+			var dictForEnd = endInclusive ? endNodeDict : beginNodeDict;
+			Debug.Assert(dictForStart.ContainsKey(start) && dictForEnd.ContainsKey(end));
+			int startIndex = dictForStart[start].Index;
+			int endIndex = dictForEnd[end].Index;
+			if (startIndex > endIndex)
+				throw new ArgumentException("The start statement must be lexically preceding the end statement");
+			this.analyzedRangeStart = startIndex;
+			this.analyzedRangeEnd = endIndex;
+		}
+		
+		public void Analyze(string variable, DefiniteAssignmentStatus initialStatus = DefiniteAssignmentStatus.PotentiallyAssigned, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			this.analysisCancellationToken = cancellationToken;
+			this.variableName = variable;
+			try {
+				// Reset the status:
+				unassignedVariableUses.Clear();
+				foreach (DefiniteAssignmentNode node in allNodes) {
+					node.NodeStatus = DefiniteAssignmentStatus.CodeUnreachable;
+					foreach (ControlFlowEdge edge in node.Outgoing)
+						edgeStatus[edge] = DefiniteAssignmentStatus.CodeUnreachable;
+				}
+				
+				ChangeNodeStatus(allNodes[analyzedRangeStart], initialStatus);
+				// Iterate as long as the input status of some nodes is changing:
+				while (nodesWithModifiedInput.Count > 0) {
+					DefiniteAssignmentNode node = nodesWithModifiedInput.Dequeue();
+					DefiniteAssignmentStatus inputStatus = DefiniteAssignmentStatus.CodeUnreachable;
+					foreach (ControlFlowEdge edge in node.Incoming) {
+						inputStatus = MergeStatus(inputStatus, edgeStatus[edge]);
+					}
+					ChangeNodeStatus(node, inputStatus);
+				}
+			} finally {
+				this.analysisCancellationToken = CancellationToken.None;
+				this.variableName = null;
+			}
+		}
+		
+		public DefiniteAssignmentStatus GetStatusBefore(Statement statement)
+		{
+			return beginNodeDict[statement].NodeStatus;
+		}
+		
+		public DefiniteAssignmentStatus GetStatusAfter(Statement statement)
+		{
+			return endNodeDict[statement].NodeStatus;
+		}
+		
+		public DefiniteAssignmentStatus GetStatusBeforeLoopCondition(Statement statement)
+		{
+			return conditionNodeDict[statement].NodeStatus;
+		}
+		
+		/// <summary>
+		/// Exports the CFG. This method is intended to help debugging issues related to definite assignment.
+		/// </summary>
+		public GraphVizGraph ExportGraph()
+		{
+			GraphVizGraph g = new GraphVizGraph();
+			g.Title = "DefiniteAssignment - " + variableName;
+			for (int i = 0; i < allNodes.Count; i++) {
+				string name = "#" + i + " = " + allNodes[i].NodeStatus.ToString() + Environment.NewLine;
+				switch (allNodes[i].Type) {
+					case ControlFlowNodeType.StartNode:
+					case ControlFlowNodeType.BetweenStatements:
+						name += allNodes[i].NextStatement.ToString();
+						break;
+					case ControlFlowNodeType.EndNode:
+						name += "End of " + allNodes[i].PreviousStatement.ToString();
+						break;
+					case ControlFlowNodeType.LoopCondition:
+						name += "Condition in " + allNodes[i].NextStatement.ToString();
+						break;
+					default:
+						name += allNodes[i].Type.ToString();
+						break;
+				}
+				g.AddNode(new GraphVizNode(i) { label = name });
+				foreach (ControlFlowEdge edge in allNodes[i].Outgoing) {
+					GraphVizEdge ge = new GraphVizEdge(i, ((DefiniteAssignmentNode)edge.To).Index);
+					if (edgeStatus.Count > 0)
+						ge.label = edgeStatus[edge].ToString();
+					if (edge.IsLeavingTryFinally)
+						ge.style = "dashed";
+					switch (edge.Type) {
+						case ControlFlowEdgeType.ConditionTrue:
+							ge.color = "green";
+							break;
+						case ControlFlowEdgeType.ConditionFalse:
+							ge.color = "red";
+							break;
+						case ControlFlowEdgeType.Jump:
+							ge.color = "blue";
+							break;
+					}
+					g.AddEdge(ge);
+				}
+			}
+			return g;
+		}
+		
+		static DefiniteAssignmentStatus MergeStatus(DefiniteAssignmentStatus a, DefiniteAssignmentStatus b)
+		{
+			// The result will be DefinitelyAssigned if at least one incoming edge is DefinitelyAssigned and all others are unreachable.
+			// The result will be DefinitelyUnassigned if at least one incoming edge is DefinitelyUnassigned and all others are unreachable.
+			// The result will be Unreachable if all incoming edges are unreachable.
+			// Otherwise, the result will be PotentiallyAssigned.
+			
+			if (a == b)
+				return a;
+			else if (a == DefiniteAssignmentStatus.CodeUnreachable)
+				return b;
+			else if (b == DefiniteAssignmentStatus.CodeUnreachable)
+				return a;
+			else
+				return DefiniteAssignmentStatus.PotentiallyAssigned;
+		}
+		
+		void ChangeNodeStatus (DefiniteAssignmentNode node, DefiniteAssignmentStatus inputStatus)
+		{
+			if (node.NodeStatus == inputStatus)
+				return;
+			node.NodeStatus = inputStatus;
+			DefiniteAssignmentStatus outputStatus;
+			switch (node.Type) {
+			case ControlFlowNodeType.StartNode:
+			case ControlFlowNodeType.BetweenStatements:
+				if (node.NextStatement is IfElseStatement) {
+					// Handle if-else as a condition node
+						goto case ControlFlowNodeType.LoopCondition;
+				}
+				if (inputStatus == DefiniteAssignmentStatus.DefinitelyAssigned) {
+					// There isn't any way to un-assign variables, so we don't have to check the expression
+					// if the status already is definitely assigned.
+					outputStatus = DefiniteAssignmentStatus.DefinitelyAssigned;
+				} else {
+					outputStatus = CleanSpecialValues (node.NextStatement.AcceptVisitor (visitor, inputStatus));
+				}
+				break;
+			case ControlFlowNodeType.EndNode:
+				outputStatus = inputStatus;
+				if (node.PreviousStatement.Role == TryCatchStatement.FinallyBlockRole
+					&& (outputStatus == DefiniteAssignmentStatus.DefinitelyAssigned || outputStatus == DefiniteAssignmentStatus.PotentiallyAssigned)) {
+					TryCatchStatement tryFinally = (TryCatchStatement)node.PreviousStatement.Parent;
+					// Changing the status on a finally block potentially changes the status of all edges leaving that finally block:
+					foreach (ControlFlowEdge edge in allNodes.SelectMany(n => n.Outgoing)) {
+						if (edge.IsLeavingTryFinally && edge.TryFinallyStatements.Contains (tryFinally)) {
+							DefiniteAssignmentStatus s = edgeStatus [edge];
+							if (s == DefiniteAssignmentStatus.PotentiallyAssigned) {
+								ChangeEdgeStatus (edge, outputStatus);
+							}
+						}
+					}
+				}
+				break;
+			case ControlFlowNodeType.LoopCondition:
+				ForeachStatement foreachStmt = node.NextStatement as ForeachStatement;
+				if (foreachStmt != null) {
+					outputStatus = CleanSpecialValues (foreachStmt.InExpression.AcceptVisitor (visitor, inputStatus));
+					if (foreachStmt.VariableName == this.variableName)
+						outputStatus = DefiniteAssignmentStatus.DefinitelyAssigned;
+					break;
+				} else {
+					Debug.Assert (node.NextStatement is IfElseStatement || node.NextStatement is WhileStatement || node.NextStatement is ForStatement || node.NextStatement is DoWhileStatement);
+					Expression condition = node.NextStatement.GetChildByRole (Roles.Condition);
+						if (condition.IsNull)
+							outputStatus = inputStatus;
+						else
+							outputStatus = condition.AcceptVisitor(visitor, inputStatus);
+						foreach (ControlFlowEdge edge in node.Outgoing) {
+							if (edge.Type == ControlFlowEdgeType.ConditionTrue && outputStatus == DefiniteAssignmentStatus.AssignedAfterTrueExpression) {
+								ChangeEdgeStatus(edge, DefiniteAssignmentStatus.DefinitelyAssigned);
+							} else if (edge.Type == ControlFlowEdgeType.ConditionFalse && outputStatus == DefiniteAssignmentStatus.AssignedAfterFalseExpression) {
+								ChangeEdgeStatus(edge, DefiniteAssignmentStatus.DefinitelyAssigned);
+							} else {
+								ChangeEdgeStatus(edge, CleanSpecialValues(outputStatus));
+							}
+						}
+						return;
+					}
+				default:
+					throw new InvalidOperationException();
+			}
+			foreach (ControlFlowEdge edge in node.Outgoing) {
+				ChangeEdgeStatus(edge, outputStatus);
+			}
+		}
+		
+		void ChangeEdgeStatus(ControlFlowEdge edge, DefiniteAssignmentStatus newStatus)
+		{
+			DefiniteAssignmentStatus oldStatus = edgeStatus[edge];
+			if (oldStatus == newStatus)
+				return;
+			// Ensure that status can cannot change back to CodeUnreachable after it once was reachable.
+			// Also, don't ever use AssignedAfter... for statements.
+			if (newStatus == DefiniteAssignmentStatus.CodeUnreachable
+			    || newStatus == DefiniteAssignmentStatus.AssignedAfterFalseExpression
+			    || newStatus == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+			{
+				throw new InvalidOperationException();
+			}
+			// Note that the status can change from DefinitelyAssigned
+			// back to PotentiallyAssigned as unreachable input edges are
+			// discovered to be reachable.
+			
+			edgeStatus[edge] = newStatus;
+			DefiniteAssignmentNode targetNode = (DefiniteAssignmentNode)edge.To;
+			if (analyzedRangeStart <= targetNode.Index && targetNode.Index <= analyzedRangeEnd) {
+				// TODO: potential optimization: visit previously unreachable nodes with higher priority
+				// (e.g. use Deque and enqueue previously unreachable nodes at the front, but
+				// other nodes at the end)
+				nodesWithModifiedInput.Enqueue(targetNode);
+			}
+		}
+		
+		/// <summary>
+		/// Evaluates an expression.
+		/// </summary>
+		/// <returns>The constant value of the expression; or null if the expression is not a constant.</returns>
+		ResolveResult EvaluateConstant(Expression expr)
+		{
+			return resolver.Resolve(expr, analysisCancellationToken);
+		}
+		
+		/// <summary>
+		/// Evaluates an expression.
+		/// </summary>
+		/// <returns>The value of the constant boolean expression; or null if the value is not a constant boolean expression.</returns>
+		bool? EvaluateCondition(Expression expr)
+		{
+			ResolveResult rr = EvaluateConstant(expr);
+			if (rr != null && rr.IsCompileTimeConstant)
+				return rr.ConstantValue as bool?;
+			else
+				return null;
+		}
+		
+		static DefiniteAssignmentStatus CleanSpecialValues(DefiniteAssignmentStatus status)
+		{
+			if (status == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+				return DefiniteAssignmentStatus.PotentiallyAssigned;
+			else if (status == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+				return DefiniteAssignmentStatus.PotentiallyAssigned;
+			else
+				return status;
+		}
+		
+		sealed class DefiniteAssignmentVisitor : DepthFirstAstVisitor<DefiniteAssignmentStatus, DefiniteAssignmentStatus>
+		{
+			internal DefiniteAssignmentAnalysis analysis;
+			
+			// The general approach for unknown nodes is to pass the status through all child nodes in order
+			protected override DefiniteAssignmentStatus VisitChildren(AstNode node, DefiniteAssignmentStatus data)
+			{
+				// the special values are valid as output only, not as input
+				Debug.Assert(data == CleanSpecialValues(data));
+				DefiniteAssignmentStatus status = data;
+				for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
+					analysis.analysisCancellationToken.ThrowIfCancellationRequested();
+					
+					Debug.Assert(!(child is Statement)); // statements are visited with the CFG, not with the visitor pattern
+					status = child.AcceptVisitor(this, status);
+					status = CleanSpecialValues(status);
+				}
+				return status;
+			}
+			
+			#region Statements
+			// For statements, the visitor only describes the effect of the statement itself;
+			// we do not consider the effect of any nested statements.
+			// This is done because the nested statements will be reached using the control flow graph.
+			
+			// In fact, these methods are present so that the default logic in VisitChildren does not try to visit the nested statements.
+			
+			public override DefiniteAssignmentStatus VisitBlockStatement(BlockStatement blockStatement, DefiniteAssignmentStatus data)
+			{
+				return data;
+			}
+			
+			public override DefiniteAssignmentStatus VisitCheckedStatement(CheckedStatement checkedStatement, DefiniteAssignmentStatus data)
+			{
+				return data;
+			}
+			
+			public override DefiniteAssignmentStatus VisitUncheckedStatement(UncheckedStatement uncheckedStatement, DefiniteAssignmentStatus data)
+			{
+				return data;
+			}
+			
+			// ExpressionStatement handled by default logic
+			// VariableDeclarationStatement handled by default logic
+			
+			public override DefiniteAssignmentStatus VisitVariableInitializer(VariableInitializer variableInitializer, DefiniteAssignmentStatus data)
+			{
+				if (variableInitializer.Initializer.IsNull) {
+					return data;
+				} else {
+					DefiniteAssignmentStatus status = variableInitializer.Initializer.AcceptVisitor(this, data);
+					if (variableInitializer.Name == analysis.variableName)
+						return DefiniteAssignmentStatus.DefinitelyAssigned;
+					else
+						return status;
+				}
+			}
+			
+			// IfStatement not handled by visitor, but special-cased in the code consuming the control flow graph
+			
+			public override DefiniteAssignmentStatus VisitSwitchStatement(SwitchStatement switchStatement, DefiniteAssignmentStatus data)
+			{
+				return switchStatement.Expression.AcceptVisitor(this, data);
+			}
+			
+			public override DefiniteAssignmentStatus VisitWhileStatement(WhileStatement whileStatement, DefiniteAssignmentStatus data)
+			{
+				return data; // condition is handled by special condition CFG node
+			}
+			
+			public override DefiniteAssignmentStatus VisitDoWhileStatement(DoWhileStatement doWhileStatement, DefiniteAssignmentStatus data)
+			{
+				return data; // condition is handled by special condition CFG node
+			}
+			
+			public override DefiniteAssignmentStatus VisitForStatement(ForStatement forStatement, DefiniteAssignmentStatus data)
+			{
+				return data; // condition is handled by special condition CFG node; initializer and iterator statements are handled by CFG
+			}
+			
+			// Break/Continue/Goto: handled by default logic
+			
+			// ThrowStatement: handled by default logic (just visit the expression)
+			// ReturnStatement: handled by default logic (just visit the expression)
+			
+			public override DefiniteAssignmentStatus VisitTryCatchStatement(TryCatchStatement tryCatchStatement, DefiniteAssignmentStatus data)
+			{
+				return data; // no special logic when entering the try-catch-finally statement
+				// TODO: where to put the special logic when exiting the try-finally statement?
+			}
+			
+			public override DefiniteAssignmentStatus VisitForeachStatement(ForeachStatement foreachStatement, DefiniteAssignmentStatus data)
+			{
+				return data; // assignment of the foreach loop variable is done when handling the condition node
+			}
+			
+			public override DefiniteAssignmentStatus VisitUsingStatement(UsingStatement usingStatement, DefiniteAssignmentStatus data)
+			{
+				if (usingStatement.ResourceAcquisition is Expression)
+					return usingStatement.ResourceAcquisition.AcceptVisitor(this, data);
+				else
+					return data; // don't handle resource acquisition statements, as those are connected in the control flow graph
+			}
+			
+			public override DefiniteAssignmentStatus VisitLockStatement(LockStatement lockStatement, DefiniteAssignmentStatus data)
+			{
+				return lockStatement.Expression.AcceptVisitor(this, data);
+			}
+			
+			// Yield statements use the default logic
+			
+			public override DefiniteAssignmentStatus VisitUnsafeStatement(UnsafeStatement unsafeStatement, DefiniteAssignmentStatus data)
+			{
+				return data;
+			}
+			
+			public override DefiniteAssignmentStatus VisitFixedStatement(FixedStatement fixedStatement, DefiniteAssignmentStatus data)
+			{
+				DefiniteAssignmentStatus status = data;
+				foreach (var variable in fixedStatement.Variables)
+					status = variable.AcceptVisitor(this, status);
+				return status;
+			}
+			#endregion
+			
+			#region Expressions
+			public override DefiniteAssignmentStatus VisitDirectionExpression(DirectionExpression directionExpression, DefiniteAssignmentStatus data)
+			{
+				if (directionExpression.FieldDirection == FieldDirection.Out) {
+					return HandleAssignment(directionExpression.Expression, null, data);
+				} else {
+					// use default logic for 'ref'
+					return VisitChildren(directionExpression, data);
+				}
+			}
+			
+			public override DefiniteAssignmentStatus VisitAssignmentExpression(AssignmentExpression assignmentExpression, DefiniteAssignmentStatus data)
+			{
+				if (assignmentExpression.Operator == AssignmentOperatorType.Assign) {
+					return HandleAssignment(assignmentExpression.Left, assignmentExpression.Right, data);
+				} else {
+					// use default logic for compound assignment operators
+					return VisitChildren(assignmentExpression, data);
+				}
+			}
+			
+			DefiniteAssignmentStatus HandleAssignment(Expression left, Expression right, DefiniteAssignmentStatus initialStatus)
+			{
+				IdentifierExpression ident = left as IdentifierExpression;
+				if (ident != null && ident.Identifier == analysis.variableName) {
+					// right==null is special case when handling 'out' expressions
+					if (right != null)
+						right.AcceptVisitor(this, initialStatus);
+					return DefiniteAssignmentStatus.DefinitelyAssigned;
+				} else {
+					DefiniteAssignmentStatus status = left.AcceptVisitor(this, initialStatus);
+					if (right != null)
+						status = right.AcceptVisitor(this, CleanSpecialValues(status));
+					return CleanSpecialValues(status);
+				}
+			}
+			
+			public override DefiniteAssignmentStatus VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, DefiniteAssignmentStatus data)
+			{
+				// Don't use the default logic here because we don't want to clean up the special values.
+				return parenthesizedExpression.Expression.AcceptVisitor(this, data);
+			}
+			
+			public override DefiniteAssignmentStatus VisitCheckedExpression(CheckedExpression checkedExpression, DefiniteAssignmentStatus data)
+			{
+				return checkedExpression.Expression.AcceptVisitor(this, data);
+			}
+			
+			public override DefiniteAssignmentStatus VisitUncheckedExpression(UncheckedExpression uncheckedExpression, DefiniteAssignmentStatus data)
+			{
+				return uncheckedExpression.Expression.AcceptVisitor(this, data);
+			}
+			
+			public override DefiniteAssignmentStatus VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, DefiniteAssignmentStatus data)
+			{
+				if (binaryOperatorExpression.Operator == BinaryOperatorType.ConditionalAnd) {
+					// Handle constant left side of && expressions (not in the C# spec, but done by the MS compiler)
+					bool? cond = analysis.EvaluateCondition(binaryOperatorExpression.Left);
+					if (cond == true)
+						return binaryOperatorExpression.Right.AcceptVisitor(this, data); // right operand gets evaluated unconditionally
+					else if (cond == false)
+						return data; // right operand never gets evaluated
+					// C# 4.0 spec: §5.3.3.24 Definite Assignment for && expressions
+					DefiniteAssignmentStatus afterLeft = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+					DefiniteAssignmentStatus beforeRight;
+					if (afterLeft == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+						beforeRight = DefiniteAssignmentStatus.DefinitelyAssigned;
+					else if (afterLeft == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+						beforeRight = DefiniteAssignmentStatus.PotentiallyAssigned;
+					else
+						beforeRight = afterLeft;
+					DefiniteAssignmentStatus afterRight = binaryOperatorExpression.Right.AcceptVisitor(this, beforeRight);
+					if (afterLeft == DefiniteAssignmentStatus.DefinitelyAssigned)
+						return DefiniteAssignmentStatus.DefinitelyAssigned;
+					else if (afterRight == DefiniteAssignmentStatus.DefinitelyAssigned && afterLeft == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+						return DefiniteAssignmentStatus.DefinitelyAssigned;
+					else if (afterRight == DefiniteAssignmentStatus.DefinitelyAssigned || afterRight == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+						return DefiniteAssignmentStatus.AssignedAfterTrueExpression;
+					else if (afterLeft == DefiniteAssignmentStatus.AssignedAfterFalseExpression && afterRight == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+						return DefiniteAssignmentStatus.AssignedAfterFalseExpression;
+					else
+						return DefiniteAssignmentStatus.PotentiallyAssigned;
+				} else if (binaryOperatorExpression.Operator == BinaryOperatorType.ConditionalOr) {
+					// C# 4.0 spec: §5.3.3.25 Definite Assignment for || expressions
+					bool? cond = analysis.EvaluateCondition(binaryOperatorExpression.Left);
+					if (cond == false)
+						return binaryOperatorExpression.Right.AcceptVisitor(this, data); // right operand gets evaluated unconditionally
+					else if (cond == true)
+						return data; // right operand never gets evaluated
+					DefiniteAssignmentStatus afterLeft = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+					DefiniteAssignmentStatus beforeRight;
+					if (afterLeft == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+						beforeRight = DefiniteAssignmentStatus.PotentiallyAssigned;
+					else if (afterLeft == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+						beforeRight = DefiniteAssignmentStatus.DefinitelyAssigned;
+					else
+						beforeRight = afterLeft;
+					DefiniteAssignmentStatus afterRight = binaryOperatorExpression.Right.AcceptVisitor(this, beforeRight);
+					if (afterLeft == DefiniteAssignmentStatus.DefinitelyAssigned)
+						return DefiniteAssignmentStatus.DefinitelyAssigned;
+					else if (afterRight == DefiniteAssignmentStatus.DefinitelyAssigned && afterLeft == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+						return DefiniteAssignmentStatus.DefinitelyAssigned;
+					else if (afterRight == DefiniteAssignmentStatus.DefinitelyAssigned || afterRight == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+						return DefiniteAssignmentStatus.AssignedAfterFalseExpression;
+					else if (afterLeft == DefiniteAssignmentStatus.AssignedAfterTrueExpression && afterRight == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+						return DefiniteAssignmentStatus.AssignedAfterTrueExpression;
+					else
+						return DefiniteAssignmentStatus.PotentiallyAssigned;
+				} else if (binaryOperatorExpression.Operator == BinaryOperatorType.NullCoalescing) {
+					// C# 4.0 spec: §5.3.3.27 Definite assignment for ?? expressions
+					ResolveResult crr = analysis.EvaluateConstant(binaryOperatorExpression.Left);
+					if (crr != null && crr.IsCompileTimeConstant && crr.ConstantValue == null)
+						return binaryOperatorExpression.Right.AcceptVisitor(this, data);
+					DefiniteAssignmentStatus status = CleanSpecialValues(binaryOperatorExpression.Left.AcceptVisitor(this, data));
+					binaryOperatorExpression.Right.AcceptVisitor(this, status);
+					return status;
+				} else {
+					// use default logic for other operators
+					return VisitChildren(binaryOperatorExpression, data);
+				}
+			}
+			
+			public override DefiniteAssignmentStatus VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, DefiniteAssignmentStatus data)
+			{
+				if (unaryOperatorExpression.Operator == UnaryOperatorType.Not) {
+					// C# 4.0 spec: §5.3.3.26 Definite assignment for ! expressions
+					DefiniteAssignmentStatus status = unaryOperatorExpression.Expression.AcceptVisitor(this, data);
+					if (status == DefiniteAssignmentStatus.AssignedAfterFalseExpression)
+						return DefiniteAssignmentStatus.AssignedAfterTrueExpression;
+					else if (status == DefiniteAssignmentStatus.AssignedAfterTrueExpression)
+						return DefiniteAssignmentStatus.AssignedAfterFalseExpression;
+					else
+						return status;
+				} else {
+					// use default logic for other operators
+					return VisitChildren(unaryOperatorExpression, data);
+				}
+			}
+			
+			public override DefiniteAssignmentStatus VisitConditionalExpression(ConditionalExpression conditionalExpression, DefiniteAssignmentStatus data)
+			{
+				// C# 4.0 spec: §5.3.3.28 Definite assignment for ?: expressions
+				bool? cond = analysis.EvaluateCondition(conditionalExpression.Condition);
+				if (cond == true) {
+					return conditionalExpression.TrueExpression.AcceptVisitor(this, data);
+				} else if (cond == false) {
+					return conditionalExpression.FalseExpression.AcceptVisitor(this, data);
+				} else {
+					DefiniteAssignmentStatus afterCondition = conditionalExpression.Condition.AcceptVisitor(this, data);
+					
+					DefiniteAssignmentStatus beforeTrue, beforeFalse;
+					if (afterCondition == DefiniteAssignmentStatus.AssignedAfterTrueExpression) {
+						beforeTrue = DefiniteAssignmentStatus.DefinitelyAssigned;
+						beforeFalse = DefiniteAssignmentStatus.PotentiallyAssigned;
+					} else if (afterCondition == DefiniteAssignmentStatus.AssignedAfterFalseExpression) {
+						beforeTrue = DefiniteAssignmentStatus.PotentiallyAssigned;
+						beforeFalse = DefiniteAssignmentStatus.DefinitelyAssigned;
+					} else {
+						beforeTrue = afterCondition;
+						beforeFalse = afterCondition;
+					}
+					
+					DefiniteAssignmentStatus afterTrue = conditionalExpression.TrueExpression.AcceptVisitor(this, beforeTrue);
+					DefiniteAssignmentStatus afterFalse = conditionalExpression.FalseExpression.AcceptVisitor(this, beforeFalse);
+					return MergeStatus(CleanSpecialValues(afterTrue), CleanSpecialValues(afterFalse));
+				}
+			}
+			
+			public override DefiniteAssignmentStatus VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, DefiniteAssignmentStatus data)
+			{
+				BlockStatement body = anonymousMethodExpression.Body;
+				analysis.ChangeNodeStatus(analysis.beginNodeDict[body], data);
+				return data;
+			}
+			
+			public override DefiniteAssignmentStatus VisitLambdaExpression(LambdaExpression lambdaExpression, DefiniteAssignmentStatus data)
+			{
+				Statement body = lambdaExpression.Body as Statement;
+				if (body != null) {
+					analysis.ChangeNodeStatus(analysis.beginNodeDict[body], data);
+				} else {
+					lambdaExpression.Body.AcceptVisitor(this, data);
+				}
+				return data;
+			}
+			
+			public override DefiniteAssignmentStatus VisitIdentifierExpression(IdentifierExpression identifierExpression, DefiniteAssignmentStatus data)
+			{
+				if (data != DefiniteAssignmentStatus.DefinitelyAssigned
+				    && identifierExpression.Identifier == analysis.variableName && identifierExpression.TypeArguments.Count == 0)
+				{
+					analysis.unassignedVariableUses.Add(identifierExpression);
+				}
+				return data;
+			}
+			#endregion
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/NullValueAnalysis.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/NullValueAnalysis.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/NullValueAnalysis.cs	(revision 11807)
@@ -0,0 +1,2215 @@
+// 
+// NullValueAnalysis.cs
+//  
+// Author:
+//       LuÃ­s Reis <luiscubal@gmail.com>
+// 
+// Copyright (c) 2013 LuÃ­s Reis
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+using System.Text;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.PatternMatching;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	public class NullValueAnalysis
+	{
+		sealed class VariableStatusInfo : IEquatable<VariableStatusInfo>, IEnumerable<KeyValuePair<string, NullValueStatus>>
+		{
+			readonly Dictionary<string, NullValueStatus> VariableStatus = new Dictionary<string, NullValueStatus>();
+
+			public NullValueStatus this[string name]
+			{
+				get {
+					NullValueStatus status;
+					if (VariableStatus.TryGetValue(name, out status)) {
+						return status;
+					}
+					return NullValueStatus.UnreachableOrInexistent;
+				}
+				set {
+					if (value == NullValueStatus.UnreachableOrInexistent) {
+						VariableStatus.Remove(name);
+					} else {
+						VariableStatus [name] = value;
+					}
+				}
+			}
+
+			/// <summary>
+			/// Modifies the variable state to consider a new incoming path
+			/// </summary>
+			/// <returns><c>true</c>, if the state has changed, <c>false</c> otherwise.</returns>
+			/// <param name="incomingState">The variable state of the incoming path</param>
+			public bool ReceiveIncoming(VariableStatusInfo incomingState)
+			{
+				bool changed = false;
+				var listOfVariables = VariableStatus.Keys.Concat(incomingState.VariableStatus.Keys).ToList();
+				foreach (string variable in listOfVariables)
+				{
+					var newValue = CombineStatus(this [variable], incomingState [variable]);
+					if (this [variable] != newValue) {
+						this [variable] = newValue;
+						changed = true;
+					}
+				}
+
+				return changed;
+			}
+
+			public static NullValueStatus CombineStatus(NullValueStatus oldValue, NullValueStatus incomingValue)
+			{
+				if (oldValue == NullValueStatus.Error || incomingValue == NullValueStatus.Error)
+					return NullValueStatus.Error;
+
+				if (oldValue == NullValueStatus.UnreachableOrInexistent ||
+				    oldValue == NullValueStatus.Unassigned)
+					return incomingValue;
+
+				if (incomingValue == NullValueStatus.Unassigned) {
+					return NullValueStatus.Unassigned;
+				}
+
+				if (oldValue == NullValueStatus.CapturedUnknown || incomingValue == NullValueStatus.CapturedUnknown) {
+					//TODO: Check if this is right
+					return NullValueStatus.CapturedUnknown;
+				}
+
+				if (oldValue == NullValueStatus.Unknown) {
+					return NullValueStatus.Unknown;
+				}
+
+				if (oldValue == NullValueStatus.DefinitelyNull) {
+					return incomingValue == NullValueStatus.DefinitelyNull ?
+						NullValueStatus.DefinitelyNull : NullValueStatus.PotentiallyNull;
+				}
+
+				if (oldValue == NullValueStatus.DefinitelyNotNull) {
+					if (incomingValue == NullValueStatus.Unknown)
+						return NullValueStatus.Unknown;
+					if (incomingValue == NullValueStatus.DefinitelyNotNull)
+						return NullValueStatus.DefinitelyNotNull;
+					return NullValueStatus.PotentiallyNull;
+				}
+
+				Debug.Assert(oldValue == NullValueStatus.PotentiallyNull);
+				return NullValueStatus.PotentiallyNull;
+			}
+
+			public bool HasVariable(string variable) {
+				return VariableStatus.ContainsKey(variable);
+			}
+
+			public VariableStatusInfo Clone() {
+				var clone = new VariableStatusInfo();
+				foreach (var item in VariableStatus) {
+					clone.VariableStatus.Add(item.Key, item.Value);
+				}
+				return clone;
+			}
+
+			public override bool Equals(object obj)
+			{
+				return Equals(obj as VariableStatusInfo);
+			}
+
+			public bool Equals(VariableStatusInfo obj)
+			{
+				if (obj == null) {
+					return false;
+				}
+
+				if (VariableStatus.Count != obj.VariableStatus.Count)
+					return false;
+
+				return VariableStatus.All(item => item.Value == obj[item.Key]);
+			}
+
+			public override int GetHashCode()
+			{
+				//STUB
+				return VariableStatus.Count.GetHashCode();
+			}
+
+			public static bool operator ==(VariableStatusInfo obj1, VariableStatusInfo obj2) {
+				return object.ReferenceEquals(obj1, null) ?
+					object.ReferenceEquals(obj2, null) : obj1.Equals(obj2);
+			}
+
+			public static bool operator !=(VariableStatusInfo obj1, VariableStatusInfo obj2) {
+				return !(obj1 == obj2);
+			}
+
+			public IEnumerator<KeyValuePair<string, NullValueStatus>> GetEnumerator()
+			{
+				return VariableStatus.GetEnumerator();
+			}
+
+			IEnumerator IEnumerable.GetEnumerator()
+			{
+				return GetEnumerator();
+			}
+
+			public override string ToString()
+			{
+				var builder = new StringBuilder("[");
+				foreach (var item in this) {
+					builder.Append(item.Key);
+					builder.Append("=");
+					builder.Append(item.Value);
+				}
+				builder.Append("]");
+				return builder.ToString();
+			}
+		}
+
+		sealed class NullAnalysisNode : ControlFlowNode
+		{
+			public readonly VariableStatusInfo VariableState = new VariableStatusInfo();
+			public bool Visited { get; private set; }
+
+			public NullAnalysisNode(Statement previousStatement, Statement nextStatement, ControlFlowNodeType type)
+				: base(previousStatement, nextStatement, type)
+			{
+			}
+
+			public bool ReceiveIncoming(VariableStatusInfo incomingState)
+			{
+				bool changed = VariableState.ReceiveIncoming(incomingState);
+				if (!Visited) {
+					Visited = true;
+					return true;
+				}
+				return changed;
+			}
+		}
+
+		sealed class NullAnalysisGraphBuilder : ControlFlowGraphBuilder
+		{
+			protected override ControlFlowNode CreateNode(Statement previousStatement, Statement nextStatement, ControlFlowNodeType type)
+			{
+				return new NullAnalysisNode(previousStatement, nextStatement, type);
+			}
+		}
+
+		class PendingNode : IEquatable<PendingNode> {
+			internal readonly NullAnalysisNode nodeToVisit;
+			internal readonly VariableStatusInfo statusInfo;
+			internal readonly ComparableList<NullAnalysisNode> pendingTryFinallyNodes;
+			internal readonly NullAnalysisNode nodeAfterFinally;
+
+			internal PendingNode(NullAnalysisNode nodeToVisit, VariableStatusInfo statusInfo)
+				: this(nodeToVisit, statusInfo, new ComparableList<NullAnalysisNode>(), null)
+			{
+			}
+
+			public PendingNode(NullAnalysisNode nodeToVisit, VariableStatusInfo statusInfo, ComparableList<NullAnalysisNode> pendingFinallyNodes, NullAnalysisNode nodeAfterFinally)
+			{
+				this.nodeToVisit = nodeToVisit;
+				this.statusInfo = statusInfo;
+				this.pendingTryFinallyNodes = pendingFinallyNodes;
+				this.nodeAfterFinally = nodeAfterFinally;
+			}
+
+			public override bool Equals(object obj)
+			{
+				return Equals(obj as PendingNode);
+			}
+
+			public bool Equals(PendingNode obj) {
+				if (obj == null) return false;
+
+				if (nodeToVisit != obj.nodeToVisit) return false;
+				if (statusInfo != obj.statusInfo) return false;
+				if (pendingTryFinallyNodes != obj.pendingTryFinallyNodes) return false;
+				if (nodeAfterFinally != obj.nodeAfterFinally) return false;
+
+				return true;
+			}
+
+			public override int GetHashCode()
+			{
+				return nodeToVisit.GetHashCode() ^
+					statusInfo.GetHashCode() ^
+					pendingTryFinallyNodes.GetHashCode() ^
+					(nodeAfterFinally == null ? 0 : nodeAfterFinally.GetHashCode());
+			}
+		}
+
+		readonly BaseRefactoringContext context;
+		readonly NullAnalysisVisitor visitor;
+		List<NullAnalysisNode> allNodes;
+		readonly HashSet<PendingNode> nodesToVisit = new HashSet<PendingNode>();
+		Dictionary<Statement, NullAnalysisNode> nodeBeforeStatementDict;
+		Dictionary<Statement, NullAnalysisNode> nodeAfterStatementDict;
+		readonly Dictionary<Expression, NullValueStatus> expressionResult = new Dictionary<Expression, NullValueStatus>();
+
+		public NullValueAnalysis(BaseRefactoringContext context, MethodDeclaration methodDeclaration, CancellationToken cancellationToken)
+			: this(context, methodDeclaration.Body, methodDeclaration.Parameters, cancellationToken)
+		{
+		}
+
+		readonly IEnumerable<ParameterDeclaration> parameters;
+		readonly Statement rootStatement;
+
+		readonly CancellationToken cancellationToken;
+
+		public NullValueAnalysis(BaseRefactoringContext context, Statement rootStatement, IEnumerable<ParameterDeclaration> parameters, CancellationToken cancellationToken)
+		{
+			if (rootStatement == null)
+				throw new ArgumentNullException("rootStatement");
+			if (context == null)
+				throw new ArgumentNullException("context");
+
+			this.context = context;
+			this.rootStatement = rootStatement;
+			this.parameters = parameters;
+			this.visitor = new NullAnalysisVisitor(this);
+			this.cancellationToken = cancellationToken;
+		}
+
+		/// <summary>
+		/// Sets the local variable value.
+		/// This method does not change anything if identifier does not refer to a local variable.
+		/// Do not use this in variable declarations since resolving the variable won't work yet.
+		/// </summary>
+		/// <returns><c>true</c>, if local variable value was set, <c>false</c> otherwise.</returns>
+		/// <param name="data">The variable status data to change.</param>
+		/// <param name="identifierNode">The identifier to set.</param>
+		/// <param name="identifierName">The name of the identifier to set.</param>
+		/// <param name="value">The value to set the identifier.</param>
+		bool SetLocalVariableValue (VariableStatusInfo data, AstNode identifierNode, string identifierName, NullValueStatus value) {
+			var resolveResult = context.Resolve(identifierNode);
+			if (resolveResult is LocalResolveResult) {
+				if (data [identifierName] != NullValueStatus.CapturedUnknown) {
+					data [identifierName] = value;
+
+					return true;
+				}
+			}
+			return false;
+		}
+
+		bool SetLocalVariableValue (VariableStatusInfo data, IdentifierExpression identifierExpression, NullValueStatus value) {
+			return SetLocalVariableValue(data, identifierExpression, identifierExpression.Identifier, value);
+		}
+
+		bool SetLocalVariableValue (VariableStatusInfo data, Identifier identifier, NullValueStatus value) {
+			return SetLocalVariableValue(data, identifier, identifier.Name, value);
+		}
+
+		void SetupNode(NullAnalysisNode node)
+		{
+			foreach (var parameter in parameters) {
+				var resolveResult = context.Resolve(parameter.Type);
+				node.VariableState[parameter.Name] = GetInitialVariableStatus(resolveResult);
+			}
+
+			nodesToVisit.Add(new PendingNode(node, node.VariableState));
+		}
+
+		static bool IsTypeNullable(IType type)
+		{
+			return type.IsReferenceType == true || type.FullName == "System.Nullable";
+		}
+
+		public bool IsParametersAreUninitialized {
+			get;
+			set;
+		}
+
+		NullValueStatus GetInitialVariableStatus(ResolveResult resolveResult)
+		{
+			var typeResolveResult = resolveResult as TypeResolveResult;
+			if (typeResolveResult == null) {
+				return NullValueStatus.Error;
+			}
+			var type = typeResolveResult.Type;
+			if (type.IsReferenceType == null) {
+				return NullValueStatus.Error;
+			}
+			if (!IsParametersAreUninitialized)
+				return NullValueStatus.DefinitelyNotNull;
+			return IsTypeNullable(type) ? NullValueStatus.PotentiallyNull : NullValueStatus.DefinitelyNotNull;
+		}
+
+		public void Analyze()
+		{
+			var cfgBuilder = new NullAnalysisGraphBuilder();
+			allNodes = cfgBuilder.BuildControlFlowGraph(rootStatement, cancellationToken).Cast<NullAnalysisNode>().ToList();
+			nodeBeforeStatementDict = allNodes.Where(node => node.Type == ControlFlowNodeType.StartNode || node.Type == ControlFlowNodeType.BetweenStatements)
+				.ToDictionary(node => node.NextStatement);
+			nodeAfterStatementDict = allNodes.Where(node => node.Type == ControlFlowNodeType.BetweenStatements || node.Type == ControlFlowNodeType.EndNode)
+				.ToDictionary(node => node.PreviousStatement);
+
+			foreach (var node in allNodes) {
+				if (node.Type == ControlFlowNodeType.StartNode && node.NextStatement == rootStatement) {
+					Debug.Assert(!nodesToVisit.Any());
+
+					SetupNode(node);
+				}
+			}
+
+			while (nodesToVisit.Any()) {
+				var nodeToVisit = nodesToVisit.First();
+				nodesToVisit.Remove(nodeToVisit);
+
+				Visit(nodeToVisit);
+			}
+		}
+
+		int visits = 0;
+
+		public int NodeVisits
+		{
+			get {
+				return visits;
+			}
+		}
+
+		void Visit(PendingNode nodeInfo)
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+
+			var node = nodeInfo.nodeToVisit;
+			var statusInfo = nodeInfo.statusInfo;
+
+			visits++;
+			if (visits > 100) {
+				//Visiting way too often, let's enter fast mode
+				//Fast mode is slighly less accurate but visits each node less times
+				nodesToVisit.RemoveWhere(candidate => candidate.nodeToVisit == nodeInfo.nodeToVisit &&
+				                         candidate.pendingTryFinallyNodes.Equals(nodeInfo.pendingTryFinallyNodes) &&
+				                         candidate.nodeAfterFinally == nodeInfo.nodeAfterFinally);
+				statusInfo = node.VariableState;
+			}
+
+			var nextStatement = node.NextStatement;
+			VariableStatusInfo outgoingStatusInfo = statusInfo;
+			VisitorResult result = null;
+
+			if (nextStatement != null && (!(nextStatement is DoWhileStatement) || node.Type == ControlFlowNodeType.LoopCondition)) {
+				result = nextStatement.AcceptVisitor(visitor, statusInfo);
+				if (result == null) {
+					Console.WriteLine("Failure in {0}", nextStatement);
+					throw new InvalidOperationException();
+				}
+
+				outgoingStatusInfo = result.Variables;
+			}
+
+			if ((result == null || !result.ThrowsException) && node.Outgoing.Any()) {
+				var tryFinallyStatement = nextStatement as TryCatchStatement;
+
+				foreach (var outgoingEdge in node.Outgoing) {
+					VariableStatusInfo edgeInfo;
+					edgeInfo = outgoingStatusInfo.Clone();
+
+					if (node.Type == ControlFlowNodeType.EndNode) {
+						var previousBlock = node.PreviousStatement as BlockStatement;
+						if (previousBlock != null) {
+							//We're leaving a block statement.
+							//As such, we'll remove the variables that were declared *in* the loop
+							//This helps GetVariableStatusAfter/BeforeStatement be more accurate
+							//and prevents some redundant revisiting.
+
+							foreach (var variableInitializer in previousBlock.Statements
+							         .OfType<VariableDeclarationStatement>()
+							         .SelectMany(declaration => declaration.Variables)) {
+
+								edgeInfo [variableInitializer.Name] = NullValueStatus.UnreachableOrInexistent;
+							}
+						}
+					}
+
+					if (tryFinallyStatement != null) {
+						//With the exception of try statements, this needs special handling:
+						//we'll set all changed variables to Unknown or CapturedUnknown
+						if (outgoingEdge.To.NextStatement == tryFinallyStatement.FinallyBlock) {
+							foreach (var identifierExpression in tryFinallyStatement.TryBlock.Descendants.OfType<IdentifierExpression>()) {
+								//TODO: Investigate CaptureUnknown
+								SetLocalVariableValue(edgeInfo, identifierExpression, NullValueStatus.Unknown);
+							}
+						} else {
+							var clause = tryFinallyStatement.CatchClauses
+								.FirstOrDefault(candidateClause => candidateClause.Body == outgoingEdge.To.NextStatement);
+
+							if (clause != null) {
+								SetLocalVariableValue(edgeInfo, clause.VariableNameToken, NullValueStatus.DefinitelyNotNull);
+
+								foreach (var identifierExpression in tryFinallyStatement.TryBlock.Descendants.OfType<IdentifierExpression>()) {
+									//TODO: Investigate CaptureUnknown
+									SetLocalVariableValue(edgeInfo, identifierExpression, NullValueStatus.Unknown);
+								}
+							}
+						}
+					}
+
+					if (result != null) {
+						switch (outgoingEdge.Type) {
+							case ControlFlowEdgeType.ConditionTrue:
+								if (result.KnownBoolResult == false) {
+									//No need to explore this path -- expression is known to be false
+									continue;
+								}
+								edgeInfo = result.TruePathVariables;
+								break;
+							case ControlFlowEdgeType.ConditionFalse:
+								if (result.KnownBoolResult == true) {
+									//No need to explore this path -- expression is known to be true
+									continue;
+								}
+								edgeInfo = result.FalsePathVariables;
+								break;
+						}
+					}
+
+					if (outgoingEdge.IsLeavingTryFinally) {
+						var nodeAfterFinally = (NullAnalysisNode)outgoingEdge.To;
+						var finallyNodes = outgoingEdge.TryFinallyStatements.Select(tryFinally => nodeBeforeStatementDict [tryFinally.FinallyBlock]).ToList();
+						var nextNode = finallyNodes.First();
+						var remainingFinallyNodes = new ComparableList<NullAnalysisNode>(finallyNodes.Skip(1));
+						//We have to visit the node even if ReceiveIncoming returns false
+						//since the finallyNodes/nodeAfterFinally might be different even if the values of variables are the same -- and they need to be visited either way!
+						//TODO 1: Is there any point in visiting the finally statement here?
+						//TODO 2: Do we need the ReceiveIncoming at all?
+						nextNode.ReceiveIncoming(edgeInfo);
+						nodesToVisit.Add(new PendingNode(nextNode, edgeInfo, remainingFinallyNodes, nodeAfterFinally));
+					} else {
+						var outgoingNode = (NullAnalysisNode)outgoingEdge.To;
+						if (outgoingNode.ReceiveIncoming(edgeInfo)) {
+							nodesToVisit.Add(new PendingNode(outgoingNode, edgeInfo));
+						}
+					}
+				}
+			} else {
+				//We found a return/throw/yield break or some other termination node
+				var finallyBlockStarts = nodeInfo.pendingTryFinallyNodes;
+				var nodeAfterFinally = nodeInfo.nodeAfterFinally;
+
+				if (finallyBlockStarts.Any()) {
+					var nextNode = finallyBlockStarts.First();
+					if (nextNode.ReceiveIncoming(outgoingStatusInfo))
+						nodesToVisit.Add(new PendingNode(nextNode, outgoingStatusInfo, new ComparableList<NullAnalysisNode>(finallyBlockStarts.Skip(1)), nodeInfo.nodeAfterFinally));
+				} else if (nodeAfterFinally != null && nodeAfterFinally.ReceiveIncoming(outgoingStatusInfo)) {
+					nodesToVisit.Add(new PendingNode(nodeAfterFinally, outgoingStatusInfo));
+				} else {
+					//Maybe we finished a try/catch/finally statement the "normal" way (no direct jumps)
+					//so let's check that case
+					var statement = node.PreviousStatement ?? node.NextStatement;
+					Debug.Assert(statement != null);
+					var parent = statement.GetParent<Statement>();
+					var parentTryCatch = parent as TryCatchStatement;
+					if (parentTryCatch != null) {
+						var nextNode = nodeAfterStatementDict [parentTryCatch];
+						if (nextNode.ReceiveIncoming(outgoingStatusInfo)) {
+							nodesToVisit.Add(new PendingNode(nextNode, outgoingStatusInfo));
+						}
+					}
+				}
+			}
+		}
+
+		public NullValueStatus GetExpressionResult(Expression expr)
+		{
+			if (expr == null)
+				throw new ArgumentNullException("expr");
+
+			NullValueStatus info;
+			if (expressionResult.TryGetValue(expr, out info)) {
+				return info;
+			}
+
+			return NullValueStatus.UnreachableOrInexistent;
+		}
+
+		public NullValueStatus GetVariableStatusBeforeStatement(Statement stmt, string variableName)
+		{
+			if (stmt == null)
+				throw new ArgumentNullException("stmt");
+			if (variableName == null)
+				throw new ArgumentNullException("variableName");
+
+			NullAnalysisNode node;
+			if (nodeBeforeStatementDict.TryGetValue(stmt, out node)) {
+				return node.VariableState [variableName];
+			}
+
+			return NullValueStatus.UnreachableOrInexistent;
+		}
+
+		public NullValueStatus GetVariableStatusAfterStatement(Statement stmt, string variableName)
+		{
+			if (stmt == null)
+				throw new ArgumentNullException("stmt");
+			if (variableName == null)
+				throw new ArgumentNullException("variableName");
+
+			NullAnalysisNode node;
+			if (nodeAfterStatementDict.TryGetValue(stmt, out node)) {
+				return node.VariableState [variableName];
+			}
+
+			return NullValueStatus.UnreachableOrInexistent;
+		}
+
+		class ConditionalBranchInfo
+		{
+			/// <summary>
+			/// True if the variable is null for the true path, false if it is false for the true path.
+			/// </summary>
+			public Dictionary<string, bool> TrueResultVariableNullStates = new Dictionary<string, bool>();
+			/// <summary>
+			/// True if the variable is null for the false path, false if it is false for the false path.
+			/// </summary>
+			public Dictionary<string, bool> FalseResultVariableNullStates = new Dictionary<string, bool>();
+		}
+
+		class VisitorResult
+		{
+			/// <summary>
+			/// Indicates the return value of the expression.
+			/// </summary>
+			/// <remarks>
+			/// Only applicable for expressions.
+			/// </remarks>
+			public NullValueStatus NullableReturnResult;
+
+			/// <summary>
+			/// Indicates the value of each item in an array or linq query.
+			/// </summary>
+			public NullValueStatus EnumeratedValueResult;
+
+			/// <summary>
+			/// Information that indicates the restrictions to add
+			/// when branching.
+			/// </summary>
+			/// <remarks>
+			/// Used in if/else statements, conditional expressions and
+			/// while statements.
+			/// </remarks>
+			public ConditionalBranchInfo ConditionalBranchInfo;
+
+			/// <summary>
+			/// The state of the variables after the expression is executed.
+			/// </summary>
+			public VariableStatusInfo Variables;
+
+			/// <summary>
+			/// The expression is known to be invalid and trigger an error
+			/// (e.g. a NullReferenceException)
+			/// </summary>
+			public bool ThrowsException;
+
+			/// <summary>
+			/// The known bool result of an expression.
+			/// </summary>
+			public bool? KnownBoolResult;
+
+			public static VisitorResult ForEnumeratedValue(VariableStatusInfo variables, NullValueStatus itemValues)
+			{
+				var result = new VisitorResult();
+				result.NullableReturnResult = NullValueStatus.DefinitelyNotNull;
+				result.EnumeratedValueResult = itemValues;
+				result.Variables = variables.Clone();
+				return result;
+			}
+
+			public static VisitorResult ForValue(VariableStatusInfo variables, NullValueStatus returnValue)
+			{
+				var result = new VisitorResult();
+				result.NullableReturnResult = returnValue;
+				result.Variables = variables.Clone();
+				return result;
+			}
+
+			public static VisitorResult ForBoolValue(VariableStatusInfo variables, bool newValue)
+			{
+				var result = new VisitorResult();
+				result.NullableReturnResult = NullValueStatus.DefinitelyNotNull; //Bool expressions are never null
+				result.KnownBoolResult = newValue;
+				result.Variables = variables.Clone();
+				return result;
+			}
+
+			public static VisitorResult ForException(VariableStatusInfo variables) {
+				var result = new VisitorResult();
+				result.NullableReturnResult = NullValueStatus.UnreachableOrInexistent;
+				result.ThrowsException = true;
+				result.Variables = variables.Clone();
+				return result;
+			}
+
+			public VisitorResult Negated {
+				get {
+					var result = new VisitorResult();
+					if (NullableReturnResult.IsDefiniteValue()) {
+						result.NullableReturnResult = NullableReturnResult == NullValueStatus.DefinitelyNull
+							? NullValueStatus.DefinitelyNotNull : NullValueStatus.DefinitelyNull;
+					} else {
+						result.NullableReturnResult = NullableReturnResult;
+					}
+					result.Variables = Variables.Clone();
+					result.KnownBoolResult = !KnownBoolResult;
+					if (ConditionalBranchInfo != null) {
+						result.ConditionalBranchInfo = new ConditionalBranchInfo();
+						foreach (var item in ConditionalBranchInfo.TrueResultVariableNullStates) {
+							result.ConditionalBranchInfo.FalseResultVariableNullStates [item.Key] = item.Value;
+						}
+						foreach (var item in ConditionalBranchInfo.FalseResultVariableNullStates) {
+							result.ConditionalBranchInfo.TrueResultVariableNullStates [item.Key] = item.Value;
+						}
+					}
+					return result;
+				}
+			}
+
+			public VariableStatusInfo TruePathVariables {
+				get {
+					var variables = Variables.Clone();
+					if (ConditionalBranchInfo != null) {
+						foreach (var item in ConditionalBranchInfo.TrueResultVariableNullStates) {
+							variables [item.Key] = item.Value ? NullValueStatus.DefinitelyNull : NullValueStatus.DefinitelyNotNull;
+						}
+					}
+					return variables;
+				}
+			}
+
+			public VariableStatusInfo FalsePathVariables {
+				get {
+					var variables = Variables.Clone();
+					if (ConditionalBranchInfo != null) {
+						foreach (var item in ConditionalBranchInfo.FalseResultVariableNullStates) {
+							variables [item.Key] = item.Value ? NullValueStatus.DefinitelyNull : NullValueStatus.DefinitelyNotNull;
+						}
+					}
+					return variables;
+				}
+			}
+
+			public static VisitorResult AndOperation(VisitorResult tentativeLeftResult, VisitorResult tentativeRightResult)
+			{
+				var result = new VisitorResult();
+				result.KnownBoolResult = tentativeLeftResult.KnownBoolResult & tentativeRightResult.KnownBoolResult;
+
+				var trueTruePath = tentativeRightResult.TruePathVariables;
+				var trueFalsePath = tentativeRightResult.FalsePathVariables;
+				var falsePath = tentativeLeftResult.FalsePathVariables;
+
+				var trueVariables = trueTruePath;
+
+				var falseVariables = trueFalsePath.Clone();
+				falseVariables.ReceiveIncoming(falsePath);
+				result.Variables = trueVariables.Clone();
+				result.Variables.ReceiveIncoming(falseVariables);
+
+				result.ConditionalBranchInfo = new ConditionalBranchInfo();
+
+				foreach (var variable in trueVariables) {
+					if (!variable.Value.IsDefiniteValue())
+						continue;
+
+					string variableName = variable.Key;
+
+					if (variable.Value != result.Variables[variableName]) {
+						bool isNull = variable.Value == NullValueStatus.DefinitelyNull;
+						result.ConditionalBranchInfo.TrueResultVariableNullStates.Add(variableName, isNull);
+					}
+				}
+
+				foreach (var variable in falseVariables) {
+					if (!variable.Value.IsDefiniteValue())
+						continue;
+
+					string variableName = variable.Key;
+
+					if (variable.Value != result.Variables [variableName]) {
+						bool isNull = variable.Value == NullValueStatus.DefinitelyNull;
+						result.ConditionalBranchInfo.FalseResultVariableNullStates.Add(variableName, isNull);
+					}
+				}
+
+				return result;
+			}
+
+			public static VisitorResult OrOperation(VisitorResult tentativeLeftResult, VisitorResult tentativeRightResult)
+			{
+				return VisitorResult.AndOperation(tentativeLeftResult.Negated, tentativeRightResult.Negated).Negated;
+			}
+		}
+
+		class NullAnalysisVisitor : DepthFirstAstVisitor<VariableStatusInfo, VisitorResult>
+		{
+			NullValueAnalysis analysis;
+
+			public NullAnalysisVisitor(NullValueAnalysis analysis) {
+				this.analysis = analysis;
+			}
+
+			protected override VisitorResult VisitChildren(AstNode node, VariableStatusInfo data)
+			{
+				Debug.Fail("Missing override for " + node.GetType().Name);
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+			
+			public override VisitorResult VisitNullNode(AstNode nullNode, VariableStatusInfo data)
+			{
+				// can occur due to syntax errors
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+			
+			public override VisitorResult VisitEmptyStatement(EmptyStatement emptyStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitBlockStatement(BlockStatement blockStatement, VariableStatusInfo data)
+			{
+				//We'll visit the child statements later (we'll visit each one directly from the CFG)
+				//As such this is mostly a dummy node.
+				return new VisitorResult { Variables = data };
+			}
+
+			public override VisitorResult VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, VariableStatusInfo data)
+			{
+				foreach (var variable in variableDeclarationStatement.Variables) {
+					var result = variable.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables;
+				}
+
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitVariableInitializer(VariableInitializer variableInitializer, VariableStatusInfo data)
+			{
+				if (variableInitializer.Initializer.IsNull) {
+					data = data.Clone();
+					data[variableInitializer.Name] = NullValueStatus.Unassigned;
+				} else {
+					var result = variableInitializer.Initializer.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables.Clone();
+					data[variableInitializer.Name] = result.NullableReturnResult;
+				}
+
+				return VisitorResult.ForValue(data, data [variableInitializer.Name]);
+			}
+
+			public override VisitorResult VisitIfElseStatement(IfElseStatement ifElseStatement, VariableStatusInfo data)
+			{
+				//We'll visit the true/false statements later (directly from the CFG)
+				return ifElseStatement.Condition.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitWhileStatement(WhileStatement whileStatement, VariableStatusInfo data)
+			{
+				return whileStatement.Condition.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitDoWhileStatement(DoWhileStatement doWhileStatement, VariableStatusInfo data)
+			{
+				return doWhileStatement.Condition.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitForStatement(ForStatement forStatement, VariableStatusInfo data)
+			{
+				//The initializers, the embedded statement and the iterators aren't visited here
+				//because they have their own CFG nodes.
+				if (forStatement.Condition.IsNull)
+					return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+				return forStatement.Condition.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitForeachStatement(ForeachStatement foreachStatement, VariableStatusInfo data)
+			{
+				var newVariable = foreachStatement.VariableNameToken;
+				var inExpressionResult = foreachStatement.InExpression.AcceptVisitor(this, data);
+				if (inExpressionResult.ThrowsException)
+					return inExpressionResult;
+
+				var newData = inExpressionResult.Variables.Clone();
+
+				var resolveResult = analysis.context.Resolve(foreachStatement.VariableNameToken) as LocalResolveResult;
+				if (resolveResult != null) {
+					//C# 5.0 changed the meaning of foreach so that each iteration declares a new variable
+					//as such, the variable is "uncaptured" only for C# >= 5.0
+					if (analysis.context.Supports(new Version(5, 0)) || data[newVariable.Name] != NullValueStatus.CapturedUnknown) {
+						newData[newVariable.Name] = NullValueAnalysis.IsTypeNullable(resolveResult.Type) ? inExpressionResult.EnumeratedValueResult : NullValueStatus.DefinitelyNotNull;
+					}
+				}
+
+				return VisitorResult.ForValue(newData, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitUsingStatement(UsingStatement usingStatement, VariableStatusInfo data)
+			{
+				return usingStatement.ResourceAcquisition.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitFixedStatement(FixedStatement fixedStatement, VariableStatusInfo data)
+			{
+				foreach (var variable in fixedStatement.Variables) {
+					var result = variable.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables;
+				}
+
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitSwitchStatement(SwitchStatement switchStatement, VariableStatusInfo data)
+			{
+				//We could do better than this, but it would require special handling outside the visitor
+				//so for now, for simplicity, we'll just take the easy way
+
+				var tentativeResult = switchStatement.Expression.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException) {
+					return tentativeResult;
+				}
+
+				foreach (var section in switchStatement.SwitchSections) {
+					//No need to check for ThrowsException, since it will always be false (see VisitSwitchSection)
+					section.AcceptVisitor(this, tentativeResult.Variables);
+				}
+
+				return VisitorResult.ForValue(tentativeResult.Variables, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitSwitchSection(SwitchSection switchSection, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitExpressionStatement(ExpressionStatement expressionStatement, VariableStatusInfo data)
+			{
+				return expressionStatement.Expression.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitReturnStatement(ReturnStatement returnStatement, VariableStatusInfo data)
+			{
+				if (returnStatement.Expression.IsNull)
+					return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+				return returnStatement.Expression.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitTryCatchStatement(TryCatchStatement tryCatchStatement, VariableStatusInfo data)
+			{
+				//The needs special treatment in the analyser itself
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitBreakStatement(BreakStatement breakStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitContinueStatement(ContinueStatement continueStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitGotoStatement(GotoStatement gotoStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitLabelStatement(LabelStatement labelStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitUnsafeStatement(UnsafeStatement unsafeStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitLockStatement(LockStatement lockStatement, VariableStatusInfo data)
+			{
+				var expressionResult = lockStatement.Expression.AcceptVisitor(this, data);
+				if (expressionResult.ThrowsException)
+					return expressionResult;
+
+				if (expressionResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+					return VisitorResult.ForException(expressionResult.Variables);
+				}
+
+				var identifier = CSharpUtil.GetInnerMostExpression(lockStatement.Expression) as IdentifierExpression;
+				if (identifier != null) {
+					var identifierValue = expressionResult.Variables [identifier.Identifier];
+					if (identifierValue != NullValueStatus.CapturedUnknown) {
+						var newVariables = expressionResult.Variables.Clone();
+						analysis.SetLocalVariableValue(newVariables, identifier, NullValueStatus.DefinitelyNotNull);
+
+						return VisitorResult.ForValue(newVariables, NullValueStatus.Unknown);
+					}
+				}
+
+				return VisitorResult.ForValue(expressionResult.Variables, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitThrowStatement(ThrowStatement throwStatement, VariableStatusInfo data)
+			{
+				if (throwStatement.Expression.IsNull)
+					return VisitorResult.ForValue(data, NullValueStatus.DefinitelyNotNull);
+				return throwStatement.Expression.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, VariableStatusInfo data)
+			{
+				return yieldReturnStatement.Expression.AcceptVisitor(this, data);
+			}
+
+			public override VisitorResult VisitCheckedStatement(CheckedStatement checkedStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitUncheckedStatement(UncheckedStatement uncheckedStatement, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			void RegisterExpressionResult(Expression expression, NullValueStatus expressionResult)
+			{
+				NullValueStatus oldStatus;
+				if (analysis.expressionResult.TryGetValue(expression, out oldStatus)) {
+					analysis.expressionResult[expression] = VariableStatusInfo.CombineStatus(analysis.expressionResult[expression], expressionResult);
+				}
+				else {
+					analysis.expressionResult[expression] = expressionResult;
+				}
+			}
+
+			VisitorResult HandleExpressionResult(Expression expression, VariableStatusInfo dataAfterExpression, NullValueStatus expressionResult) {
+				RegisterExpressionResult(expression, expressionResult);
+
+				return VisitorResult.ForValue(dataAfterExpression, expressionResult);
+			}
+
+			VisitorResult HandleExpressionResult(Expression expression, VariableStatusInfo dataAfterExpression, bool expressionResult) {
+				RegisterExpressionResult(expression, NullValueStatus.DefinitelyNotNull);
+
+				return VisitorResult.ForBoolValue(dataAfterExpression, expressionResult);
+			}
+
+			VisitorResult HandleExpressionResult(Expression expression, VisitorResult result) {
+				RegisterExpressionResult(expression, result.NullableReturnResult);
+
+				return result;
+			}
+
+			public override VisitorResult VisitAssignmentExpression(AssignmentExpression assignmentExpression, VariableStatusInfo data)
+			{
+				var tentativeResult = assignmentExpression.Left.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException)
+					return HandleExpressionResult(assignmentExpression, tentativeResult);
+				tentativeResult = assignmentExpression.Right.AcceptVisitor(this, tentativeResult.Variables);
+				if (tentativeResult.ThrowsException)
+					return HandleExpressionResult(assignmentExpression, tentativeResult);
+
+				var leftIdentifier = assignmentExpression.Left as IdentifierExpression;
+				if (leftIdentifier != null) {
+					var resolveResult = analysis.context.Resolve(leftIdentifier);
+					if (resolveResult.IsError) {
+						return HandleExpressionResult(assignmentExpression, data, NullValueStatus.Error);
+					}
+
+					if (resolveResult is LocalResolveResult) {
+						var result = new VisitorResult();
+						result.NullableReturnResult = tentativeResult.NullableReturnResult;
+						result.Variables = tentativeResult.Variables.Clone();
+						var oldValue = result.Variables [leftIdentifier.Identifier];
+
+						if (assignmentExpression.Operator == AssignmentOperatorType.Assign ||
+						    oldValue == NullValueStatus.Unassigned ||
+						    oldValue == NullValueStatus.DefinitelyNotNull ||
+						    tentativeResult.NullableReturnResult == NullValueStatus.Error ||
+						    tentativeResult.NullableReturnResult == NullValueStatus.Unknown) {
+							analysis.SetLocalVariableValue(result.Variables, leftIdentifier, tentativeResult.NullableReturnResult);
+						} else {
+							if (oldValue == NullValueStatus.DefinitelyNull) {
+								//Do nothing --it'll remain null
+							} else {
+								analysis.SetLocalVariableValue(result.Variables, leftIdentifier, NullValueStatus.PotentiallyNull);
+							}
+						}
+
+						return HandleExpressionResult(assignmentExpression, result);
+					}
+				}
+
+				return HandleExpressionResult(assignmentExpression, tentativeResult);
+			}
+
+			public override VisitorResult VisitIdentifierExpression(IdentifierExpression identifierExpression, VariableStatusInfo data)
+			{
+				var resolveResult = analysis.context.Resolve(identifierExpression);
+				if (resolveResult.IsError) {
+					return HandleExpressionResult(identifierExpression, data, NullValueStatus.Error);
+				}
+				var local = resolveResult as LocalResolveResult;
+				if (local != null) {
+					var value = data [local.Variable.Name];
+					if (value == NullValueStatus.CapturedUnknown)
+						value = NullValueStatus.Unknown;
+					return HandleExpressionResult(identifierExpression, data, value);
+				}
+				if (resolveResult.IsCompileTimeConstant) {
+					object value = resolveResult.ConstantValue;
+					if (value == null) {
+						return HandleExpressionResult(identifierExpression, data, NullValueStatus.DefinitelyNull);
+					}
+					var boolValue = value as bool?;
+					if (boolValue != null) {
+						return VisitorResult.ForBoolValue(data, (bool)boolValue);
+					}
+					return HandleExpressionResult(identifierExpression, data, NullValueStatus.DefinitelyNotNull);
+				}
+
+				var memberResolveResult = resolveResult as MemberResolveResult;
+
+				var returnValue = GetFieldReturnValue(memberResolveResult, data);
+
+				return HandleExpressionResult(identifierExpression, data, returnValue);
+			}
+
+			public override VisitorResult VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, VariableStatusInfo data)
+			{
+				var resolveResult = analysis.context.Resolve(defaultValueExpression);
+				if (resolveResult.IsError) {
+					return HandleExpressionResult(defaultValueExpression, data, NullValueStatus.Unknown);
+				}
+
+				Debug.Assert(resolveResult.IsCompileTimeConstant);
+
+				var status = resolveResult.ConstantValue == null  && resolveResult.Type.IsReferenceType != false ? NullValueStatus.DefinitelyNull : NullValueStatus.DefinitelyNotNull;
+				return HandleExpressionResult(defaultValueExpression, data, status);
+			}
+
+			public override VisitorResult VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(nullReferenceExpression, data, NullValueStatus.DefinitelyNull);
+			}
+
+			public override VisitorResult VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(primitiveExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(parenthesizedExpression, parenthesizedExpression.Expression.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitConditionalExpression(ConditionalExpression conditionalExpression, VariableStatusInfo data)
+			{
+				var tentativeBaseResult = conditionalExpression.Condition.AcceptVisitor(this, data);
+				if (tentativeBaseResult.ThrowsException)
+					return HandleExpressionResult(conditionalExpression, tentativeBaseResult);
+
+				var conditionResolveResult = analysis.context.Resolve(conditionalExpression.Condition);
+
+				if (tentativeBaseResult.KnownBoolResult == true || true.Equals(conditionResolveResult.ConstantValue)) {
+					return HandleExpressionResult(conditionalExpression, conditionalExpression.TrueExpression.AcceptVisitor(this, tentativeBaseResult.TruePathVariables));
+				}
+				if (tentativeBaseResult.KnownBoolResult == false || false.Equals(conditionResolveResult.ConstantValue)) {
+					return HandleExpressionResult(conditionalExpression, conditionalExpression.FalseExpression.AcceptVisitor(this, tentativeBaseResult.FalsePathVariables));
+				}
+
+				//No known bool result
+				var trueCaseResult = conditionalExpression.TrueExpression.AcceptVisitor(this, tentativeBaseResult.TruePathVariables);
+				if (trueCaseResult.ThrowsException) {
+					//We know that the true case will never be completed, then the right case is the only possible route.
+					return HandleExpressionResult(conditionalExpression, conditionalExpression.FalseExpression.AcceptVisitor(this, tentativeBaseResult.FalsePathVariables));
+				}
+				var falseCaseResult = conditionalExpression.FalseExpression.AcceptVisitor(this, tentativeBaseResult.FalsePathVariables);
+				if (falseCaseResult.ThrowsException) {
+					return HandleExpressionResult(conditionalExpression, trueCaseResult.Variables, true);
+				}
+
+				return HandleExpressionResult(conditionalExpression, VisitorResult.OrOperation(trueCaseResult, falseCaseResult));
+			}
+
+			public override VisitorResult VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, VariableStatusInfo data)
+			{
+				//Let's not evaluate the sides just yet because of ??, && and ||
+
+				//We'll register the results here (with HandleExpressionResult)
+				//so each Visit*Expression won't have to do it itself
+				switch (binaryOperatorExpression.Operator) {
+					case BinaryOperatorType.ConditionalAnd:
+						return HandleExpressionResult(binaryOperatorExpression, VisitConditionalAndExpression(binaryOperatorExpression, data));
+					case BinaryOperatorType.ConditionalOr:
+						return HandleExpressionResult(binaryOperatorExpression, VisitConditionalOrExpression(binaryOperatorExpression, data));
+					case BinaryOperatorType.NullCoalescing:
+						return HandleExpressionResult(binaryOperatorExpression, VisitNullCoalescing(binaryOperatorExpression, data));
+					case BinaryOperatorType.Equality:
+						return HandleExpressionResult(binaryOperatorExpression, VisitEquality(binaryOperatorExpression, data));
+					case BinaryOperatorType.InEquality:
+						return HandleExpressionResult(binaryOperatorExpression, VisitEquality(binaryOperatorExpression, data).Negated);
+					default:
+						return HandleExpressionResult(binaryOperatorExpression, VisitOtherBinaryExpression(binaryOperatorExpression, data));
+				}
+			}
+
+			VisitorResult VisitOtherBinaryExpression(BinaryOperatorExpression binaryOperatorExpression, VariableStatusInfo data)
+			{
+				var leftTentativeResult = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+				if (leftTentativeResult.ThrowsException)
+					return leftTentativeResult;
+				var rightTentativeResult = binaryOperatorExpression.Right.AcceptVisitor(this, leftTentativeResult.Variables);
+				if (rightTentativeResult.ThrowsException)
+					return rightTentativeResult;
+
+				//TODO: Assuming operators are not overloaded by users
+				// (or, if they are, that they retain similar behavior to the default ones)
+
+				switch (binaryOperatorExpression.Operator) {
+					case BinaryOperatorType.LessThan:
+					case BinaryOperatorType.GreaterThan:
+						//Operations < and > with nulls always return false
+						//Those same operations will other values may or may not return false
+						if (leftTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull &&
+							rightTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+							return VisitorResult.ForBoolValue(rightTentativeResult.Variables, false);
+						}
+						//We don't know what the value is, but we know that both true and false are != null.
+						return VisitorResult.ForValue(rightTentativeResult.Variables, NullValueStatus.DefinitelyNotNull);
+					case BinaryOperatorType.LessThanOrEqual:
+					case BinaryOperatorType.GreaterThanOrEqual:
+						if (leftTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+							if (rightTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull)
+								return VisitorResult.ForBoolValue(rightTentativeResult.Variables, true);
+							if (rightTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNotNull)
+								return VisitorResult.ForBoolValue(rightTentativeResult.Variables, false);
+						} else if (leftTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNotNull) {
+							if (rightTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull)
+								return VisitorResult.ForBoolValue(rightTentativeResult.Variables, false);
+						}
+
+						return VisitorResult.ForValue(rightTentativeResult.Variables, NullValueStatus.Unknown);
+					default:
+						//Anything else: null + anything == anything + null == null.
+						//not null + not null = not null
+						if (leftTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+							return VisitorResult.ForValue(rightTentativeResult.Variables, NullValueStatus.DefinitelyNull);
+						}
+						if (leftTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNotNull) {
+							if (rightTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull)
+								return VisitorResult.ForValue(rightTentativeResult.Variables, NullValueStatus.DefinitelyNull);
+							if (rightTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNotNull)
+								return VisitorResult.ForValue(rightTentativeResult.Variables, NullValueStatus.DefinitelyNotNull);
+						}
+
+						return VisitorResult.ForValue(rightTentativeResult.Variables, NullValueStatus.Unknown);
+				}
+			}
+
+			VisitorResult WithVariableValue(VisitorResult result, IdentifierExpression identifier, bool isNull)
+			{
+				var localVariableResult = analysis.context.Resolve(identifier) as LocalResolveResult;
+				if (localVariableResult != null) {
+					result.ConditionalBranchInfo.TrueResultVariableNullStates[identifier.Identifier] = isNull;
+					if (isNull) {
+						result.ConditionalBranchInfo.FalseResultVariableNullStates[identifier.Identifier] = false;
+					}
+				}
+				return result;
+			}
+
+			VisitorResult VisitEquality(BinaryOperatorExpression binaryOperatorExpression, VariableStatusInfo data)
+			{
+				//TODO: Should this check for user operators?
+
+				var tentativeLeftResult = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+				if (tentativeLeftResult.ThrowsException)
+					return tentativeLeftResult;
+				var tentativeRightResult = binaryOperatorExpression.Right.AcceptVisitor(this, tentativeLeftResult.Variables);
+				if (tentativeRightResult.ThrowsException)
+					return tentativeRightResult;
+
+				if (tentativeLeftResult.KnownBoolResult != null && tentativeLeftResult.KnownBoolResult == tentativeRightResult.KnownBoolResult) {
+					return VisitorResult.ForBoolValue(tentativeRightResult.Variables, true);
+				}
+
+				if (tentativeLeftResult.KnownBoolResult != null && tentativeLeftResult.KnownBoolResult == !tentativeRightResult.KnownBoolResult) {
+					return VisitorResult.ForBoolValue(tentativeRightResult.Variables, false);
+				}
+
+				if (tentativeLeftResult.NullableReturnResult.IsDefiniteValue()) {
+					if (tentativeRightResult.NullableReturnResult.IsDefiniteValue()) {
+						if (tentativeLeftResult.NullableReturnResult == NullValueStatus.DefinitelyNull || tentativeRightResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+							return VisitorResult.ForBoolValue(tentativeRightResult.Variables, tentativeLeftResult.NullableReturnResult == tentativeRightResult.NullableReturnResult);
+						}
+					}
+				}
+
+				var result = new VisitorResult();
+				result.Variables = tentativeRightResult.Variables;
+				result.NullableReturnResult = NullValueStatus.Unknown;
+				result.ConditionalBranchInfo = new ConditionalBranchInfo();
+
+				if (tentativeRightResult.NullableReturnResult.IsDefiniteValue()) {
+					var identifier = CSharpUtil.GetInnerMostExpression(binaryOperatorExpression.Left) as IdentifierExpression;
+
+					if (identifier != null) {
+						bool isNull = (tentativeRightResult.NullableReturnResult == NullValueStatus.DefinitelyNull);
+
+						WithVariableValue(result, identifier, isNull);
+					}
+				}
+
+				if (tentativeLeftResult.NullableReturnResult.IsDefiniteValue()) {
+					var identifier = CSharpUtil.GetInnerMostExpression(binaryOperatorExpression.Right) as IdentifierExpression;
+
+					if (identifier != null) {
+						bool isNull = (tentativeLeftResult.NullableReturnResult == NullValueStatus.DefinitelyNull);
+
+						WithVariableValue(result, identifier, isNull);
+					}
+				}
+
+				return result;
+			}
+
+			VisitorResult VisitConditionalAndExpression(BinaryOperatorExpression binaryOperatorExpression, VariableStatusInfo data)
+			{
+				var tentativeLeftResult = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+				if (tentativeLeftResult.KnownBoolResult == false || tentativeLeftResult.ThrowsException) {
+					return tentativeLeftResult;
+				}
+
+				var truePath = tentativeLeftResult.TruePathVariables;
+				var tentativeRightResult = binaryOperatorExpression.Right.AcceptVisitor(this, truePath);
+				if (tentativeRightResult.ThrowsException) {
+					//If the true path throws an exception, then the only way for the expression to complete
+					//successfully is if the left expression is false
+					return VisitorResult.ForBoolValue(tentativeLeftResult.FalsePathVariables, false);
+				}
+
+				return VisitorResult.AndOperation(tentativeLeftResult, tentativeRightResult);
+			}
+
+			VisitorResult VisitConditionalOrExpression(BinaryOperatorExpression binaryOperatorExpression, VariableStatusInfo data)
+			{
+				var tentativeLeftResult = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+				if (tentativeLeftResult.KnownBoolResult == true || tentativeLeftResult.ThrowsException) {
+					return tentativeLeftResult;
+				}
+
+				var falsePath = tentativeLeftResult.FalsePathVariables;
+				var tentativeRightResult = binaryOperatorExpression.Right.AcceptVisitor(this, falsePath);
+				if (tentativeRightResult.ThrowsException) {
+					//If the false path throws an exception, then the only way for the expression to complete
+					//successfully is if the left expression is true
+					return VisitorResult.ForBoolValue(tentativeLeftResult.TruePathVariables, true);
+				}
+
+				return VisitorResult.OrOperation(tentativeLeftResult, tentativeRightResult);
+			}
+
+			VisitorResult VisitNullCoalescing(BinaryOperatorExpression binaryOperatorExpression, VariableStatusInfo data)
+			{
+				var leftTentativeResult = binaryOperatorExpression.Left.AcceptVisitor(this, data);
+				if (leftTentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNotNull || leftTentativeResult.ThrowsException) {
+					return leftTentativeResult;
+				}
+
+				//If the right side is found, then the left side is known to be null
+				var newData = leftTentativeResult.Variables;
+				var leftIdentifier = CSharpUtil.GetInnerMostExpression(binaryOperatorExpression.Left) as IdentifierExpression;
+				if (leftIdentifier != null) {
+					newData = newData.Clone();
+					analysis.SetLocalVariableValue(newData, leftIdentifier, NullValueStatus.DefinitelyNull);
+				}
+
+				var rightTentativeResult = binaryOperatorExpression.Right.AcceptVisitor(this, newData);
+				if (rightTentativeResult.ThrowsException) {
+					//This means the left expression was not null all along (or else the expression will throw an exception)
+
+					if (leftIdentifier != null) {
+						newData = newData.Clone();
+						analysis.SetLocalVariableValue(newData, leftIdentifier, NullValueStatus.DefinitelyNotNull);
+						return VisitorResult.ForValue(newData, NullValueStatus.DefinitelyNotNull);
+					}
+
+					return VisitorResult.ForValue(leftTentativeResult.Variables, NullValueStatus.DefinitelyNotNull);
+				}
+
+				var mergedVariables = rightTentativeResult.Variables;
+				var nullValue = rightTentativeResult.NullableReturnResult;
+
+				if (leftTentativeResult.NullableReturnResult != NullValueStatus.DefinitelyNull) {
+					mergedVariables = mergedVariables.Clone();
+					mergedVariables.ReceiveIncoming(leftTentativeResult.Variables);
+					if (nullValue == NullValueStatus.DefinitelyNull) {
+						nullValue = NullValueStatus.PotentiallyNull;
+					}
+				}
+
+				return VisitorResult.ForValue(mergedVariables, nullValue);
+			}
+
+			public override VisitorResult VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, VariableStatusInfo data)
+			{
+				//TODO: Again, what to do when overloaded operators are found?
+
+				var tentativeResult = unaryOperatorExpression.Expression.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException)
+					return HandleExpressionResult(unaryOperatorExpression, tentativeResult);
+
+				if (unaryOperatorExpression.Operator == UnaryOperatorType.Not) {
+					return HandleExpressionResult(unaryOperatorExpression, tentativeResult.Negated);
+				}
+				return HandleExpressionResult(unaryOperatorExpression, tentativeResult);
+			}
+
+			public override VisitorResult VisitInvocationExpression(InvocationExpression invocationExpression, VariableStatusInfo data)
+			{
+				//TODO: Handle some common methods such as string.IsNullOrEmpty
+
+				var targetResult = invocationExpression.Target.AcceptVisitor(this, data);
+				if (targetResult.ThrowsException)
+					return HandleExpressionResult(invocationExpression, targetResult);
+
+				data = targetResult.Variables;
+
+				var methodResolveResult = analysis.context.Resolve(invocationExpression) as CSharpInvocationResolveResult;
+
+				List<VisitorResult> parameterResults = new List<VisitorResult>();
+
+				foreach (var argumentToHandle in invocationExpression.Arguments.Select((argument, parameterIndex) => new { argument, parameterIndex })) {
+					var argument = argumentToHandle.argument;
+					var parameterIndex = argumentToHandle.parameterIndex;
+
+					var result = argument.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return HandleExpressionResult(invocationExpression, result);
+					parameterResults.Add(result);
+
+					var namedArgument = argument as NamedArgumentExpression;
+					
+					var directionExpression = (namedArgument == null ? argument : namedArgument.Expression) as DirectionExpression;
+					if (directionExpression != null && methodResolveResult != null) {
+						var identifier = directionExpression.Expression as IdentifierExpression;
+						if (identifier != null) {
+							//out and ref parameters do *NOT* capture the variable (since they must stop changing it by the time they return)
+							var identifierResolveResult = analysis.context.Resolve(identifier) as LocalResolveResult;
+							if (identifierResolveResult != null && IsTypeNullable(identifierResolveResult.Type)) {
+								data = data.Clone();
+
+								FixParameter(argument, methodResolveResult.Member.Parameters, parameterIndex, identifier, data);
+							}
+						}
+
+
+						continue;
+					}
+
+					data = result.Variables;
+				}
+
+				var identifierExpression = CSharpUtil.GetInnerMostExpression(invocationExpression.Target) as IdentifierExpression;
+				if (identifierExpression != null) {
+					if (targetResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+						return HandleExpressionResult(invocationExpression, VisitorResult.ForException(data));
+					}
+
+					var descendentIdentifiers = invocationExpression.Arguments.SelectMany(argument => argument.DescendantsAndSelf).OfType<IdentifierExpression>();
+					if (!descendentIdentifiers.Any(identifier => identifier.Identifier == identifierExpression.Identifier)) {
+						//TODO: We can make this check better (see VisitIndexerExpression for more details)
+						data = data.Clone();
+						analysis.SetLocalVariableValue(data, identifierExpression, NullValueStatus.DefinitelyNotNull);
+					}
+				}
+
+				return HandleExpressionResult(invocationExpression, GetMethodVisitorResult(methodResolveResult, data, parameterResults));
+			}
+
+			static VisitorResult GetMethodVisitorResult(CSharpInvocationResolveResult methodResolveResult, VariableStatusInfo data, List<VisitorResult> parameterResults)
+			{
+				if (methodResolveResult == null)
+					return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+
+				var method = methodResolveResult.Member as IMethod;
+				if (method != null) {
+					if (method.GetAttribute(new FullTypeName(AnnotationNames.AssertionMethodAttribute)) != null) {
+						var assertionParameters = method.Parameters.Select((parameter, index) => new { index, parameter })
+							.Select(parameter => new { parameter.index, parameter.parameter, attributes = parameter.parameter.Attributes.Where(attribute => attribute.AttributeType.FullName == AnnotationNames.AssertionConditionAttribute).ToList() })
+							.Where(parameter => parameter.attributes.Count() == 1)
+							.Select(parameter => new { parameter.index, parameter.parameter, attribute = parameter.attributes[0] })
+							.ToList();
+
+						//Unclear what should be done if there are multiple assertion conditions
+						if (assertionParameters.Count() == 1) {
+							Debug.Assert(methodResolveResult.Arguments.Count == parameterResults.Count);
+
+							var assertionParameter = assertionParameters [0];
+							VisitorResult assertionParameterResult = null;
+
+							object intendedResult = true;
+							var positionalArgument = assertionParameter.attribute.PositionalArguments.FirstOrDefault() as MemberResolveResult;
+							if (positionalArgument != null && positionalArgument.Type.FullName == AnnotationNames.AssertionConditionTypeAttribute) {
+								switch (positionalArgument.Member.FullName) {
+									case AnnotationNames.AssertionConditionTypeIsTrue:
+										intendedResult = true;
+										break;
+									case AnnotationNames.AssertionConditionTypeIsFalse:
+										intendedResult = false;
+										break;
+									case AnnotationNames.AssertionConditionTypeIsNull:
+										intendedResult = null;
+										break;
+									case AnnotationNames.AssertionConditionTypeIsNotNull:
+										intendedResult = "<not-null>";
+										break;
+								}
+							}
+
+							int parameterIndex = assertionParameter.index;
+							if (assertionParameter.index < methodResolveResult.Arguments.Count && !(methodResolveResult.Arguments [assertionParameter.index] is NamedArgumentResolveResult)) {
+								//Use index
+								assertionParameterResult = parameterResults [assertionParameter.index];
+							} else {
+								//Use named argument
+								int? nameIndex = methodResolveResult.Arguments.Select((argument, index) => new { argument, index})
+									.Where(argument => {
+										var namedArgument = argument.argument as NamedArgumentResolveResult;
+										return namedArgument != null && namedArgument.ParameterName == assertionParameter.parameter.Name;
+									}).Select(argument => (int?)argument.index).FirstOrDefault();
+
+								if (nameIndex != null) {
+									parameterIndex = nameIndex.Value;
+									assertionParameterResult = parameterResults [nameIndex.Value];
+								} else if (assertionParameter.parameter.IsOptional) {
+									//Try to use default value
+
+									if (intendedResult is string) {
+										if (assertionParameter.parameter.ConstantValue == null) {
+											return VisitorResult.ForException(data);
+										}
+									} else {
+										if (!object.Equals(assertionParameter.parameter.ConstantValue, intendedResult)) {
+											return VisitorResult.ForException(data);
+										}
+									}
+								} else {
+									//The parameter was not specified, yet it is not optional?
+									return VisitorResult.ForException(data);
+								}
+							}
+
+							//Now check assertion
+							if (assertionParameterResult != null) {
+								if (intendedResult is bool) {
+									if (assertionParameterResult.KnownBoolResult == !(bool)intendedResult) {
+										return VisitorResult.ForException(data);
+									}
+
+									data = (bool)intendedResult ? assertionParameterResult.TruePathVariables : assertionParameterResult.FalsePathVariables;
+								} else {
+									bool shouldBeNull = intendedResult == null;
+
+									if (assertionParameterResult.NullableReturnResult == (shouldBeNull ? NullValueStatus.DefinitelyNotNull : NullValueStatus.DefinitelyNull)) {
+										return VisitorResult.ForException(data);
+									}
+
+									var parameterResolveResult = methodResolveResult.Arguments [parameterIndex];
+
+									LocalResolveResult localVariableResult = null;
+
+									var conversionResolveResult = parameterResolveResult as ConversionResolveResult;
+									if (conversionResolveResult != null) {
+										if (!IsTypeNullable(conversionResolveResult.Type)) {
+											if (intendedResult == null) {
+												return VisitorResult.ForException(data);
+											}
+										} else {
+											localVariableResult = conversionResolveResult.Input as LocalResolveResult;
+										}
+									} else {
+										localVariableResult = parameterResolveResult as LocalResolveResult;
+									}
+
+									if (localVariableResult != null && data[localVariableResult.Variable.Name] != NullValueStatus.CapturedUnknown) {
+										data = data.Clone();
+										data [localVariableResult.Variable.Name] = shouldBeNull ? NullValueStatus.DefinitelyNull : NullValueStatus.DefinitelyNotNull;
+									}
+								}
+							}
+						}
+					}
+				}
+
+				bool isNullable = IsTypeNullable(methodResolveResult.Type);
+				if (!isNullable) {
+					return VisitorResult.ForValue(data, NullValueStatus.DefinitelyNotNull);
+				}
+
+				if (method != null)
+					return VisitorResult.ForValue(data, GetNullableStatus(method));
+
+				return VisitorResult.ForValue(data, GetNullableStatus(methodResolveResult.TargetResult.Type.GetDefinition()));
+			}
+
+			static NullValueStatus GetNullableStatus(IEntity entity)
+			{
+				if (entity.DeclaringType != null && entity.DeclaringType.Kind == TypeKind.Delegate) {
+					//Handle Delegate.Invoke method
+					return GetNullableStatus(entity.DeclaringTypeDefinition);
+				}
+				
+				return GetNullableStatus(fullTypeName => entity.GetAttribute(new FullTypeName(fullTypeName)));
+			}
+
+			static NullValueStatus GetNullableStatus(IParameter parameter)
+			{
+				return GetNullableStatus(fullTypeName => parameter.Attributes.FirstOrDefault(attribute => attribute.AttributeType.FullName == fullTypeName));
+			}
+
+			static NullValueStatus GetNullableStatus(Func<string, IAttribute> attributeGetter)
+			{
+				if (attributeGetter(AnnotationNames.NotNullAttribute) != null) {
+					return NullValueStatus.DefinitelyNotNull;
+				}
+				if (attributeGetter(AnnotationNames.CanBeNullAttribute) != null) {
+					return NullValueStatus.PotentiallyNull;
+				}
+				return NullValueStatus.Unknown;
+			}
+
+			public override VisitorResult VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, VariableStatusInfo data)
+			{
+				var targetResult = memberReferenceExpression.Target.AcceptVisitor(this, data);
+				if (targetResult.ThrowsException)
+					return HandleExpressionResult(memberReferenceExpression, targetResult);
+
+				var variables = targetResult.Variables;
+
+				var memberResolveResult = analysis.context.Resolve(memberReferenceExpression) as MemberResolveResult;
+
+				var targetIdentifier = CSharpUtil.GetInnerMostExpression(memberReferenceExpression.Target) as IdentifierExpression;
+				if (targetIdentifier != null) {
+					if (memberResolveResult == null) {
+						var invocation = memberReferenceExpression.Parent as InvocationExpression;
+						if (invocation != null) {
+							memberResolveResult = analysis.context.Resolve(invocation) as MemberResolveResult;
+						}
+					}
+
+					if (memberResolveResult != null && memberResolveResult.Member.FullName != "System.Nullable.HasValue") {
+						var method = memberResolveResult.Member as IMethod;
+						if (method == null || !method.IsExtensionMethod) {
+							if (targetResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+								return HandleExpressionResult(memberReferenceExpression, VisitorResult.ForException(variables));
+							}
+							if (variables [targetIdentifier.Identifier] != NullValueStatus.CapturedUnknown) {
+								variables = variables.Clone();
+								analysis.SetLocalVariableValue(variables, targetIdentifier, NullValueStatus.DefinitelyNotNull);
+							}
+						}
+					}
+				}
+
+				var returnValue = GetFieldReturnValue(memberResolveResult, data);
+				return HandleExpressionResult(memberReferenceExpression, variables, returnValue);
+			}
+
+			static NullValueStatus GetFieldReturnValue(MemberResolveResult memberResolveResult, VariableStatusInfo data)
+			{
+				bool isNullable = memberResolveResult == null || IsTypeNullable(memberResolveResult.Type);
+				if (!isNullable) {
+					return NullValueStatus.DefinitelyNotNull;
+				}
+
+				if (memberResolveResult != null) {
+					return GetNullableStatus(memberResolveResult.Member);
+				}
+
+				return NullValueStatus.Unknown;
+			}
+
+			public override VisitorResult VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(typeReferenceExpression, data, NullValueStatus.Unknown);
+
+			}
+
+			void FixParameter(Expression argument, IList<IParameter> parameters, int parameterIndex, IdentifierExpression identifier, VariableStatusInfo data)
+			{
+				NullValueStatus newValue = NullValueStatus.Unknown;
+				if (argument is NamedArgumentExpression) {
+					var namedResolveResult = analysis.context.Resolve(argument) as NamedArgumentResolveResult;
+					if (namedResolveResult != null) {
+						newValue = GetNullableStatus(namedResolveResult.Parameter);
+					}
+				}
+				else {
+					var parameter = parameters[parameterIndex];
+					newValue = GetNullableStatus(parameter);
+				}
+				analysis.SetLocalVariableValue(data, identifier, newValue);
+			}
+
+			public override VisitorResult VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, VariableStatusInfo data)
+			{
+				foreach (var argumentToHandle in objectCreateExpression.Arguments.Select((argument, parameterIndex) => new { argument, parameterIndex })) {
+					var argument = argumentToHandle.argument;
+					var parameterIndex = argumentToHandle.parameterIndex;
+
+					var namedArgument = argument as NamedArgumentExpression;
+
+					var directionExpression = (namedArgument == null ? argument : namedArgument.Expression) as DirectionExpression;
+					if (directionExpression != null) {
+						var identifier = directionExpression.Expression as IdentifierExpression;
+						if (identifier != null && data [identifier.Identifier] != NullValueStatus.CapturedUnknown) {
+							//out and ref parameters do *NOT* capture the variable (since they must stop changing it by the time they return)
+							data = data.Clone();
+
+							var constructorResolveResult = analysis.context.Resolve(objectCreateExpression) as CSharpInvocationResolveResult;
+							if (constructorResolveResult != null)
+								FixParameter(argument, constructorResolveResult.Member.Parameters, parameterIndex, identifier, data);
+						}
+						continue;
+					}
+
+					var argumentResult = argument.AcceptVisitor(this, data);
+					if (argumentResult.ThrowsException)
+						return argumentResult;
+
+					data = argumentResult.Variables;
+				}
+
+				//Constructors never return null
+				return HandleExpressionResult(objectCreateExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, VariableStatusInfo data)
+			{
+				foreach (var argument in arrayCreateExpression.Arguments) {
+					var result = argument.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables.Clone();
+				}
+
+				if (arrayCreateExpression.Initializer.IsNull) {
+					return HandleExpressionResult(arrayCreateExpression, data, NullValueStatus.DefinitelyNotNull);
+				}
+
+				return HandleExpressionResult(arrayCreateExpression, arrayCreateExpression.Initializer.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, VariableStatusInfo data)
+			{
+				if (arrayInitializerExpression.IsSingleElement) {
+					return HandleExpressionResult(arrayInitializerExpression, arrayInitializerExpression.Elements.Single().AcceptVisitor(this, data));
+				}
+				if (!arrayInitializerExpression.Elements.Any()) {
+					//Empty array
+					return HandleExpressionResult(arrayInitializerExpression, VisitorResult.ForValue(data, NullValueStatus.Unknown));
+				}
+
+				NullValueStatus enumeratedValue = NullValueStatus.UnreachableOrInexistent;
+				foreach (var element in arrayInitializerExpression.Elements) {
+					var result = element.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables.Clone();
+					enumeratedValue = VariableStatusInfo.CombineStatus(enumeratedValue, result.NullableReturnResult);
+
+				}
+				return HandleExpressionResult(arrayInitializerExpression, VisitorResult.ForEnumeratedValue(data, enumeratedValue));
+			}
+
+			public override VisitorResult VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, VariableStatusInfo data)
+			{
+				foreach (var initializer in anonymousTypeCreateExpression.Initializers) {
+					var result = initializer.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables;
+				}
+
+				return HandleExpressionResult(anonymousTypeCreateExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitLambdaExpression(LambdaExpression lambdaExpression, VariableStatusInfo data)
+			{
+				var newData = data.Clone();
+
+				var identifiers = lambdaExpression.Descendants.OfType<IdentifierExpression>();
+				foreach (var identifier in identifiers) {
+					//Check if it is in a "change-null-state" context
+					//For instance, x++ does not change the null state
+					//but `x = y` does.
+					if (identifier.Parent is AssignmentExpression && identifier.Role == AssignmentExpression.LeftRole) {
+						var parent = (AssignmentExpression)identifier.Parent;
+						if (parent.Operator != AssignmentOperatorType.Assign) {
+							continue;
+						}
+					} else {
+						//No other context matters
+						//Captured variables are never passed by reference (out/ref)
+						continue;
+					}
+
+					//At this point, we know there's a good chance the variable has been changed
+					var identifierResolveResult = analysis.context.Resolve(identifier) as LocalResolveResult;
+					if (identifierResolveResult != null && IsTypeNullable(identifierResolveResult.Type)) {
+						analysis.SetLocalVariableValue(newData, identifier, NullValueStatus.CapturedUnknown);
+					}
+				}
+
+				//The lambda itself is known not to be null
+				return HandleExpressionResult(lambdaExpression, newData, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, VariableStatusInfo data)
+			{
+				var newData = data.Clone();
+
+				var identifiers = anonymousMethodExpression.Descendants.OfType<IdentifierExpression>();
+				foreach (var identifier in identifiers) {
+					//Check if it is in a "change-null-state" context
+					//For instance, x++ does not change the null state
+					//but `x = y` does.
+					if (identifier.Parent is AssignmentExpression && identifier.Role == AssignmentExpression.LeftRole) {
+						var parent = (AssignmentExpression)identifier.Parent;
+						if (parent.Operator != AssignmentOperatorType.Assign) {
+							continue;
+						}
+					} else {
+						//No other context matters
+						//Captured variables are never passed by reference (out/ref)
+						continue;
+					}
+
+					//At this point, we know there's a good chance the variable has been changed
+					var identifierResolveResult = analysis.context.Resolve(identifier) as LocalResolveResult;
+					if (identifierResolveResult != null && IsTypeNullable(identifierResolveResult.Type)) {
+						analysis.SetLocalVariableValue(newData, identifier, NullValueStatus.CapturedUnknown);
+					}
+				}
+
+				//The anonymous method itself is known not to be null
+				return HandleExpressionResult(anonymousMethodExpression, newData, NullValueStatus.DefinitelyNotNull);
+			}
+
+
+			public override VisitorResult VisitNamedExpression(NamedExpression namedExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(namedExpression, namedExpression.Expression.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitAsExpression(AsExpression asExpression, VariableStatusInfo data)
+			{
+				var tentativeResult = asExpression.Expression.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException)
+					return tentativeResult;
+
+				NullValueStatus result;
+				if (tentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+					result = NullValueStatus.DefinitelyNull;
+				} else {
+					var asResolveResult = analysis.context.Resolve(asExpression) as CastResolveResult;
+					if (asResolveResult == null ||
+					    asResolveResult.IsError ||
+					    asResolveResult.Input.Type.Kind == TypeKind.Unknown ||
+					    asResolveResult.Type.Kind == TypeKind.Unknown) {
+
+						result = NullValueStatus.Unknown;
+					} else {
+						var conversion = new CSharpConversions(analysis.context.Compilation);
+						var foundConversion = conversion.ExplicitConversion(asResolveResult.Input.Type, asResolveResult.Type);
+
+						if (foundConversion == Conversion.None) {
+							result = NullValueStatus.DefinitelyNull;
+						} else if (foundConversion == Conversion.IdentityConversion) {
+							result = tentativeResult.NullableReturnResult;
+						} else {
+							result = NullValueStatus.PotentiallyNull;
+						}
+					}
+				}
+				return HandleExpressionResult(asExpression, tentativeResult.Variables, result);
+			}
+
+			public override VisitorResult VisitCastExpression(CastExpression castExpression, VariableStatusInfo data)
+			{
+				var tentativeResult = castExpression.Expression.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException)
+					return tentativeResult;
+
+				NullValueStatus result;
+				if (tentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull) {
+					result = NullValueStatus.DefinitelyNull;
+				} else {
+					result = NullValueStatus.Unknown;
+				}
+
+				VariableStatusInfo variables = tentativeResult.Variables;
+
+				var resolveResult = analysis.context.Resolve(castExpression) as CastResolveResult;
+				if (resolveResult != null && !IsTypeNullable(resolveResult.Type)) {
+					if (result == NullValueStatus.DefinitelyNull) {
+						return HandleExpressionResult(castExpression, VisitorResult.ForException(tentativeResult.Variables));
+					}
+
+					var identifierExpression = CSharpUtil.GetInnerMostExpression(castExpression.Expression) as IdentifierExpression;
+					if (identifierExpression != null) {
+						var currentValue = variables [identifierExpression.Identifier];
+						if (currentValue != NullValueStatus.CapturedUnknown &&
+						    currentValue != NullValueStatus.UnreachableOrInexistent &&
+						    currentValue != NullValueStatus.DefinitelyNotNull) {
+							//DefinitelyNotNull is included in this list because if that's the status
+							// then we don't need to change anything
+
+							variables = variables.Clone();
+							variables [identifierExpression.Identifier] = NullValueStatus.DefinitelyNotNull;
+						}
+					}
+
+					result = NullValueStatus.DefinitelyNotNull;
+				}
+
+				return HandleExpressionResult(castExpression, variables, result);
+			}
+
+			public override VisitorResult VisitIsExpression(IsExpression isExpression, VariableStatusInfo data)
+			{
+				var tentativeResult = isExpression.Expression.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException)
+					return tentativeResult;
+
+				//TODO: Consider, for instance: new X() is X. The result is known to be true, so we can use KnownBoolValue
+				return HandleExpressionResult(isExpression, tentativeResult.Variables, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitDirectionExpression(DirectionExpression directionExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(directionExpression, directionExpression.Expression.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitCheckedExpression(CheckedExpression checkedExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(checkedExpression, checkedExpression.Expression.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitUncheckedExpression(UncheckedExpression uncheckedExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(uncheckedExpression, uncheckedExpression.Expression.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(thisReferenceExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitIndexerExpression(IndexerExpression indexerExpression, VariableStatusInfo data)
+			{
+				var tentativeResult = indexerExpression.Target.AcceptVisitor(this, data);
+				if (tentativeResult.ThrowsException)
+					return tentativeResult;
+
+				data = tentativeResult.Variables;
+
+				foreach (var argument in indexerExpression.Arguments) {
+					var result = argument.AcceptVisitor(this, data);
+					if (result.ThrowsException)
+						return result;
+					data = result.Variables.Clone();
+				}
+
+				IdentifierExpression targetAsIdentifier = CSharpUtil.GetInnerMostExpression(indexerExpression.Target) as IdentifierExpression;
+				if (targetAsIdentifier != null) {
+					if (tentativeResult.NullableReturnResult == NullValueStatus.DefinitelyNull)
+						return HandleExpressionResult(indexerExpression, VisitorResult.ForException(data));
+
+					//If this doesn't cause an exception, then the target is not null
+					//But we won't set it if it has been changed
+					var descendentIdentifiers = indexerExpression.Arguments
+						.SelectMany(argument => argument.DescendantsAndSelf).OfType<IdentifierExpression>();
+					if (!descendentIdentifiers.Any(identifier => identifier.Identifier == targetAsIdentifier.Identifier)) {
+						//TODO: this check might be improved to include more legitimate cases
+						//A good check will necessarily have to consider captured variables
+						data = data.Clone();
+						analysis.SetLocalVariableValue(data, targetAsIdentifier, NullValueStatus.DefinitelyNotNull);
+					}
+				}
+
+				var indexerResolveResult = analysis.context.Resolve(indexerExpression) as CSharpInvocationResolveResult;
+				bool isNullable = indexerResolveResult == null || IsTypeNullable(indexerResolveResult.Type);
+				
+				var returnValue = isNullable ? NullValueStatus.Unknown : NullValueStatus.DefinitelyNotNull;
+				return HandleExpressionResult(indexerExpression, data, returnValue);
+			}
+
+			public override VisitorResult VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(baseReferenceExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitTypeOfExpression(TypeOfExpression typeOfExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(typeOfExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitSizeOfExpression(SizeOfExpression sizeOfExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(sizeOfExpression, data, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, VariableStatusInfo data)
+			{
+				var targetResult = pointerReferenceExpression.Target.AcceptVisitor(this, data);
+				if (targetResult.ThrowsException)
+					return targetResult;
+				return HandleExpressionResult(pointerReferenceExpression, targetResult.Variables, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitStackAllocExpression(StackAllocExpression stackAllocExpression, VariableStatusInfo data)
+			{
+				var countResult = stackAllocExpression.CountExpression.AcceptVisitor(this, data);
+				if (countResult.ThrowsException)
+					return countResult;
+				return HandleExpressionResult(stackAllocExpression, countResult.Variables, NullValueStatus.DefinitelyNotNull);
+			}
+
+			public override VisitorResult VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, VariableStatusInfo data)
+			{
+				return HandleExpressionResult(namedArgumentExpression, namedArgumentExpression.Expression.AcceptVisitor(this, data));
+			}
+
+			public override VisitorResult VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, VariableStatusInfo data)
+			{
+				throw new NotImplementedException();
+			}
+
+			public override VisitorResult VisitQueryExpression(QueryExpression queryExpression, VariableStatusInfo data)
+			{
+				VariableStatusInfo outgoingData = data.Clone();
+				NullValueStatus? outgoingEnumeratedValue = null;
+				var clauses = queryExpression.Clauses.ToList();
+
+				var backtracingClauses = (from item in clauses.Select((clause, i) => new { clause, i })
+				                                where item.clause is QueryFromClause || item.clause is QueryJoinClause || item.clause is QueryContinuationClause
+				                                select item.i).ToList();
+
+				var beforeClauseVariableStates = Enumerable.Range(0, clauses.Count).ToDictionary(clauseIndex => clauseIndex,
+				                                                                                 clauseIndex => new VariableStatusInfo());
+				var afterClauseVariableStates = Enumerable.Range(0, clauses.Count).ToDictionary(clauseIndex => clauseIndex,
+				                                                                                clauseIndex => new VariableStatusInfo());
+
+				VisitorResult lastValidResult = null;
+				int currentClauseIndex = 0;
+				for (;;) {
+					VisitorResult result = null;
+					QueryClause clause = null;
+					bool backtrack = false;
+
+					if (currentClauseIndex >= clauses.Count) {
+						backtrack = true;
+					} else {
+						clause = clauses [currentClauseIndex];
+						beforeClauseVariableStates [currentClauseIndex].ReceiveIncoming(data);
+						result = clause.AcceptVisitor(this, data);
+						data = result.Variables;
+						lastValidResult = result;
+						if (result.KnownBoolResult == false) {
+							backtrack = true;
+						}
+						if (result.ThrowsException) {
+							//Don't backtrack. Exceptions completely stop the query.
+							break;
+						}
+						else {
+							afterClauseVariableStates [currentClauseIndex].ReceiveIncoming(data);
+						}
+					}
+
+					if (backtrack) {
+						int? newIndex;
+						for (;;) {
+							newIndex = backtracingClauses.LastOrDefault(index => index < currentClauseIndex);
+							if (newIndex == null) {
+								//We've reached the end
+								break;
+							}
+
+							currentClauseIndex = (int)newIndex + 1;
+
+							if (!beforeClauseVariableStates[currentClauseIndex].ReceiveIncoming(lastValidResult.Variables)) {
+								newIndex = null;
+								break;
+							}
+						}
+
+						if (newIndex == null) {
+							break;
+						}
+
+					} else {
+						if (clause is QuerySelectClause) {
+							outgoingData.ReceiveIncoming(data);
+							if (outgoingEnumeratedValue == null)
+								outgoingEnumeratedValue = result.EnumeratedValueResult;
+							else
+								outgoingEnumeratedValue = VariableStatusInfo.CombineStatus(outgoingEnumeratedValue.Value, result.EnumeratedValueResult);
+						}
+
+						++currentClauseIndex;
+					}
+				}
+
+				var finalData = new VariableStatusInfo();
+				var endingClauseIndices = from item in clauses.Select((clause, i) => new { clause, i })
+					let clause = item.clause
+						where clause is QueryFromClause ||
+					clause is QueryContinuationClause ||
+					clause is QueryJoinClause ||
+					clause is QuerySelectClause ||
+					clause is QueryWhereClause
+						select item.i;
+				foreach (var clauseIndex in endingClauseIndices) {
+					finalData.ReceiveIncoming(afterClauseVariableStates [clauseIndex]);
+				}
+
+				return VisitorResult.ForEnumeratedValue(finalData, outgoingEnumeratedValue ?? NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, VariableStatusInfo data)
+			{
+				return IntroduceVariableFromEnumeratedValue(queryContinuationClause.Identifier, queryContinuationClause.PrecedingQuery, data);
+			}
+
+			VisitorResult IntroduceVariableFromEnumeratedValue(string newVariable, Expression expression, VariableStatusInfo data)
+			{
+				var result = expression.AcceptVisitor(this, data);
+				var newVariables = result.Variables.Clone();
+				newVariables[newVariable] = result.EnumeratedValueResult;
+				return VisitorResult.ForValue(newVariables, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitQueryFromClause(QueryFromClause queryFromClause, VariableStatusInfo data)
+			{
+				return IntroduceVariableFromEnumeratedValue(queryFromClause.Identifier, queryFromClause.Expression, data);
+			}
+
+			public override VisitorResult VisitQueryJoinClause(QueryJoinClause queryJoinClause, VariableStatusInfo data)
+			{
+				//TODO: Check if this really works in weird edge-cases.
+				var tentativeResult = IntroduceVariableFromEnumeratedValue(queryJoinClause.JoinIdentifier, queryJoinClause.InExpression, data);
+				tentativeResult = queryJoinClause.OnExpression.AcceptVisitor(this, tentativeResult.Variables);
+				tentativeResult = queryJoinClause.EqualsExpression.AcceptVisitor(this, tentativeResult.Variables);
+
+				if (queryJoinClause.IsGroupJoin) {
+					var newVariables = tentativeResult.Variables.Clone();
+					analysis.SetLocalVariableValue(newVariables, queryJoinClause.IntoIdentifierToken, NullValueStatus.DefinitelyNotNull);
+					return VisitorResult.ForValue(newVariables, NullValueStatus.Unknown);
+				}
+
+				return tentativeResult;
+			}
+
+			public override VisitorResult VisitQueryLetClause(QueryLetClause queryLetClause, VariableStatusInfo data)
+			{
+				var result = queryLetClause.Expression.AcceptVisitor(this, data);
+
+				string newVariable = queryLetClause.Identifier;
+				var newVariables = result.Variables.Clone();
+				newVariables [newVariable] = result.NullableReturnResult;
+
+				return VisitorResult.ForValue(newVariables, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitQuerySelectClause(QuerySelectClause querySelectClause, VariableStatusInfo data)
+			{
+				var result = querySelectClause.Expression.AcceptVisitor(this, data);
+
+				//The value of the expression in select becomes the "enumerated" value
+				return VisitorResult.ForEnumeratedValue(result.Variables, result.NullableReturnResult);
+			}
+
+			public override VisitorResult VisitQueryWhereClause(QueryWhereClause queryWhereClause, VariableStatusInfo data)
+			{
+				var result = queryWhereClause.Condition.AcceptVisitor(this, data);
+
+				return VisitorResult.ForEnumeratedValue(result.TruePathVariables, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitQueryOrderClause(QueryOrderClause queryOrderClause, VariableStatusInfo data)
+			{
+				foreach (var ordering in queryOrderClause.Orderings) {
+					data = ordering.AcceptVisitor(this, data).Variables;
+				}
+
+				return VisitorResult.ForValue(data, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitQueryOrdering(QueryOrdering queryOrdering, VariableStatusInfo data)
+			{
+				return VisitorResult.ForValue(queryOrdering.Expression.AcceptVisitor(this, data).Variables, NullValueStatus.Unknown);
+			}
+
+			public override VisitorResult VisitQueryGroupClause(QueryGroupClause queryGroupClause, VariableStatusInfo data)
+			{
+				var projectionResult = queryGroupClause.Projection.AcceptVisitor(this, data);
+				data = projectionResult.Variables;
+				data = queryGroupClause.Key.AcceptVisitor(this, data).Variables;
+
+				return VisitorResult.ForEnumeratedValue(data, projectionResult.NullableReturnResult);
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/NullValueStatus.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/NullValueStatus.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/NullValueStatus.cs	(revision 11807)
@@ -0,0 +1,84 @@
+// 
+// NullValueAnalysis.cs
+//  
+// Author:
+//       LuÃ­s Reis <luiscubal@gmail.com>
+// 
+// Copyright (c) 2013 LuÃ­s Reis
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	/// <summary>
+	/// Represents the null value status of a variable at a specific location.
+	/// </summary>
+	public enum NullValueStatus
+	{
+		/// <summary>
+		/// The value of the variable is unknown, possibly due to limitations
+		/// of the null value analysis.
+		/// </summary>
+		Unknown = 0,
+		/// <summary>
+		/// The value of the variable is unknown and even assigning it to a
+		/// value won't change its state, since it has been captured by a lambda
+		/// that may change it at any time (potentially even from a different thread).
+		/// Only going out of scope and creating a new variable may change the value
+		/// of this variable.
+		/// </summary>
+		CapturedUnknown,
+		/// <summary>
+		/// This variable is potentially unassigned.
+		/// </summary>
+		Unassigned,
+		/// <summary>
+		/// The value of the variable is provably null.
+		/// </summary>
+		DefinitelyNull,
+		/// <summary>
+		/// The value of the variable might or might not be null
+		/// </summary>
+		PotentiallyNull,
+		/// <summary>
+		/// The value of the variable is provably not null
+		/// </summary>
+		DefinitelyNotNull,
+		/// <summary>
+		/// The position of this node is unreachable, therefore the value
+		/// of the variable is not meaningful.
+		/// Alternatively, it might mean no local variable exists with the requested name.
+		/// </summary>
+		UnreachableOrInexistent,
+		/// <summary>
+		/// The analyser has encountered an error when attempting to find the value
+		/// of this variable.
+		/// </summary>
+		Error
+	}
+
+	public static class NullValueStatusExtensions
+	{
+		public static bool IsDefiniteValue (this NullValueStatus self) {
+			return self == NullValueStatus.DefinitelyNull || self == NullValueStatus.DefinitelyNotNull;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/ReachabilityAnalysis.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/ReachabilityAnalysis.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/ReachabilityAnalysis.cs	(revision 11807)
@@ -0,0 +1,209 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.CSharp;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	/// <summary>
+	/// Statement reachability analysis.
+	/// </summary>
+	public sealed class ReachabilityAnalysis
+	{
+		HashSet<Statement> reachableStatements = new HashSet<Statement>();
+		HashSet<Statement> reachableEndPoints = new HashSet<Statement>();
+		HashSet<ControlFlowNode> visitedNodes = new HashSet<ControlFlowNode>();
+		Stack<ControlFlowNode> stack = new Stack<ControlFlowNode>();
+		RecursiveDetectorVisitor recursiveDetectorVisitor = null;
+		
+		private ReachabilityAnalysis() {}
+		
+		public static ReachabilityAnalysis Create(Statement statement, CSharpAstResolver resolver = null, RecursiveDetectorVisitor recursiveDetectorVisitor = null, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			var cfgBuilder = new ControlFlowGraphBuilder();
+			var cfg = cfgBuilder.BuildControlFlowGraph(statement, resolver, cancellationToken);
+			return Create(cfg, recursiveDetectorVisitor, cancellationToken);
+		}
+		
+		internal static ReachabilityAnalysis Create(Statement statement, Func<AstNode, CancellationToken, ResolveResult> resolver, CSharpTypeResolveContext typeResolveContext, CancellationToken cancellationToken)
+		{
+			var cfgBuilder = new ControlFlowGraphBuilder();
+			var cfg = cfgBuilder.BuildControlFlowGraph(statement, resolver, typeResolveContext, cancellationToken);
+			return Create(cfg, null, cancellationToken);
+		}
+		
+		public static ReachabilityAnalysis Create(IList<ControlFlowNode> controlFlowGraph, RecursiveDetectorVisitor recursiveDetectorVisitor = null, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (controlFlowGraph == null)
+				throw new ArgumentNullException("controlFlowGraph");
+			ReachabilityAnalysis ra = new ReachabilityAnalysis();
+			ra.recursiveDetectorVisitor = recursiveDetectorVisitor;
+			// Analysing a null node can result in an empty control flow graph
+			if (controlFlowGraph.Count > 0) {
+				ra.stack.Push(controlFlowGraph[0]);
+				while (ra.stack.Count > 0) {
+					cancellationToken.ThrowIfCancellationRequested();
+					ra.MarkReachable(ra.stack.Pop());
+				}
+			}
+			ra.stack = null;
+			ra.visitedNodes = null;
+			return ra;
+		}
+		
+		void MarkReachable(ControlFlowNode node)
+		{
+			if (node.PreviousStatement != null) {
+				if (node.PreviousStatement is LabelStatement) {
+					reachableStatements.Add(node.PreviousStatement);
+				}
+				reachableEndPoints.Add(node.PreviousStatement);
+			}
+			if (node.NextStatement != null) {
+				reachableStatements.Add(node.NextStatement);
+				if (IsRecursive(node.NextStatement)) {
+					return;
+				}
+			}
+			foreach (var edge in node.Outgoing) {
+				if (visitedNodes.Add(edge.To))
+					stack.Push(edge.To);
+			}
+		}
+
+		bool IsRecursive(Statement statement)
+		{
+			return recursiveDetectorVisitor != null && statement.AcceptVisitor(recursiveDetectorVisitor);
+		}
+		
+		public IEnumerable<Statement> ReachableStatements {
+			get { return reachableStatements; }
+		}
+		
+		public bool IsReachable(Statement statement)
+		{
+			return reachableStatements.Contains(statement);
+		}
+		
+		public bool IsEndpointReachable(Statement statement)
+		{
+			return reachableEndPoints.Contains(statement);
+		}
+
+		public class RecursiveDetectorVisitor : DepthFirstAstVisitor<bool>
+		{
+			public override bool VisitConditionalExpression(ConditionalExpression conditionalExpression)
+			{
+				if (conditionalExpression.Condition.AcceptVisitor(this))
+					return true;
+
+				if (!conditionalExpression.TrueExpression.AcceptVisitor(this))
+					return false;
+
+				return conditionalExpression.FalseExpression.AcceptVisitor(this);
+			}
+
+			public override bool VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+			{
+				if (binaryOperatorExpression.Operator == BinaryOperatorType.NullCoalescing) {
+					return binaryOperatorExpression.Left.AcceptVisitor(this);
+				}
+				return base.VisitBinaryOperatorExpression(binaryOperatorExpression);
+			}
+
+			public override bool VisitIfElseStatement(IfElseStatement ifElseStatement)
+			{
+				if (ifElseStatement.Condition.AcceptVisitor(this))
+					return true;
+
+				if (!ifElseStatement.TrueStatement.AcceptVisitor(this))
+					return false;
+
+				//No need to worry about null ast nodes, since AcceptVisitor will just
+				//return false in those cases
+				return ifElseStatement.FalseStatement.AcceptVisitor(this);
+			}
+
+			public override bool VisitForeachStatement(ForeachStatement foreachStatement)
+			{
+				//Even if the body is always recursive, the function may stop if the collection
+				// is empty.
+				return foreachStatement.InExpression.AcceptVisitor(this);
+			}
+
+			public override bool VisitForStatement(ForStatement forStatement)
+			{
+				if (forStatement.Initializers.Any(initializer => initializer.AcceptVisitor(this)))
+					return true;
+
+				return forStatement.Condition.AcceptVisitor(this);
+			}
+
+			public override bool VisitSwitchStatement(SwitchStatement switchStatement)
+			{
+				if (switchStatement.Expression.AcceptVisitor(this)) {
+					return true;
+				}
+
+				bool foundDefault = false;
+				foreach (var section in switchStatement.SwitchSections) {
+					foundDefault = foundDefault || section.CaseLabels.Any(label => label.Expression.IsNull);
+					if (!section.AcceptVisitor(this))
+						return false;
+				}
+
+				return foundDefault;
+			}
+
+			public override bool VisitBlockStatement(BlockStatement blockStatement)
+			{
+				//If the block has a recursive statement, then that statement will be visited
+				//individually by the CFG construction algorithm later.
+				return false;
+			}
+
+			protected override bool VisitChildren(AstNode node)
+			{
+				return VisitNodeList(node.Children);
+			}
+
+			bool VisitNodeList(IEnumerable<AstNode> nodes) {
+				return nodes.Any(node => node.AcceptVisitor(this));
+			}
+
+			public override bool VisitQueryExpression(QueryExpression queryExpression)
+			{
+				//We only care about the first from clause because:
+				//in "from x in Method() select x", Method() might be recursive
+				//but in "from x in Bar() from y in Method() select x + y", even if Method() is recursive
+				//Bar might still be empty.
+				var queryFromClause = queryExpression.Clauses.OfType<QueryFromClause>().FirstOrDefault();
+				if (queryFromClause == null)
+					return true;
+				return queryFromClause.AcceptVisitor(this);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/SemanticHighlightingVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/SemanticHighlightingVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Analysis/SemanticHighlightingVisitor.cs	(revision 11807)
@@ -0,0 +1,685 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.Completion;
+using System.Collections.ObjectModel;
+
+namespace ICSharpCode.NRefactory.CSharp.Analysis
+{
+	/// <summary>
+	/// C# Semantic highlighter.
+	/// </summary>
+	public abstract class SemanticHighlightingVisitor<TColor> : DepthFirstAstVisitor
+	{
+		protected CancellationToken cancellationToken = default (CancellationToken);
+		
+		protected TColor defaultTextColor;
+		protected TColor referenceTypeColor;
+		protected TColor valueTypeColor;
+		protected TColor interfaceTypeColor;
+		protected TColor enumerationTypeColor;
+		protected TColor typeParameterTypeColor;
+		protected TColor delegateTypeColor;
+		
+		protected TColor methodCallColor;
+		protected TColor methodDeclarationColor;
+		
+		protected TColor eventDeclarationColor;
+		protected TColor eventAccessColor;
+		
+		protected TColor propertyDeclarationColor;
+		protected TColor propertyAccessColor;
+		
+		protected TColor fieldDeclarationColor;
+		protected TColor fieldAccessColor;
+		
+		protected TColor variableDeclarationColor;
+		protected TColor variableAccessColor;
+		
+		protected TColor parameterDeclarationColor;
+		protected TColor parameterAccessColor;
+		
+		protected TColor valueKeywordColor;
+		protected TColor externAliasKeywordColor;
+		protected TColor varKeywordTypeColor;
+
+		/// <summary>
+		/// Used for 'in' modifiers on type parameters.
+		/// </summary>
+		/// <remarks>
+		/// 'in' may have a different color when used with 'foreach'.
+		/// 'out' is not colored by semantic highlighting, as syntax highlighting can already detect it as a parameter modifier.
+		/// </remarks>
+		protected TColor parameterModifierColor;
+		
+		/// <summary>
+		/// Used for inactive code (excluded by preprocessor or ConditionalAttribute)
+		/// </summary>
+		protected TColor inactiveCodeColor;
+
+		protected TColor stringFormatItemColor;
+
+
+		protected TColor syntaxErrorColor;
+		
+		protected TextLocation regionStart;
+		protected TextLocation regionEnd;
+		
+		protected CSharpAstResolver resolver;
+		protected bool isInAccessorContainingValueParameter;
+		
+		protected abstract void Colorize(TextLocation start, TextLocation end, TColor color);
+		
+		#region Colorize helper methods
+		protected void Colorize(Identifier identifier, ResolveResult rr)
+		{
+			if (identifier.IsNull)
+				return;
+			if (rr.IsError) {
+				Colorize(identifier, syntaxErrorColor);
+				return;
+			}
+			if (rr is TypeResolveResult) {
+				if (blockDepth > 0 && identifier.Name == "var" && rr.Type.Kind != TypeKind.Null && rr.Type.Name != "var" ) {
+					Colorize(identifier, varKeywordTypeColor);
+					return;
+				}
+
+				TColor color;
+				if (TryGetTypeHighlighting (rr.Type.Kind, out color)) {
+					Colorize(identifier, color);
+				}
+				return;
+			}
+			var mrr = rr as MemberResolveResult;
+			if (mrr != null) {
+				TColor color;
+				if (TryGetMemberColor (mrr.Member, out color)) {
+					Colorize(identifier, color);
+					return;
+				}
+			}
+			
+			if (rr is MethodGroupResolveResult) {
+				Colorize (identifier, methodCallColor);
+				return;
+			}
+			
+			var localResult = rr as LocalResolveResult;
+			if (localResult != null) {
+				if (localResult.Variable is IParameter) {
+					Colorize (identifier, parameterAccessColor);
+				} else {
+					Colorize (identifier, variableAccessColor);
+				}
+			}
+			
+			
+			VisitIdentifier(identifier); // un-colorize contextual keywords
+		}
+		
+		protected void Colorize(AstNode node, TColor color)
+		{
+			if (node.IsNull)
+				return;
+			Colorize(node.StartLocation, node.EndLocation, color);
+		}
+		#endregion
+		
+		protected override void VisitChildren(AstNode node)
+		{
+			for (var child = node.FirstChild; child != null; child = child.NextSibling) {
+				if (child.StartLocation < regionEnd && child.EndLocation > regionStart)
+					child.AcceptVisitor(this);
+			}
+		}
+		
+		/// <summary>
+		/// Visit all children of <c>node</c> until (but excluding) <c>end</c>.
+		/// If <c>end</c> is a null node, nothing will be visited.
+		/// </summary>
+		protected void VisitChildrenUntil(AstNode node, AstNode end)
+		{
+			if (end.IsNull)
+				return;
+			Debug.Assert(node == end.Parent);
+			for (var child = node.FirstChild; child != end; child = child.NextSibling) {
+				cancellationToken.ThrowIfCancellationRequested();
+				if (child.StartLocation < regionEnd && child.EndLocation > regionStart)
+					child.AcceptVisitor(this);
+			}
+		}
+		
+		/// <summary>
+		/// Visit all children of <c>node</c> after (excluding) <c>start</c>.
+		/// If <c>start</c> is a null node, all children will be visited.
+		/// </summary>
+		protected void VisitChildrenAfter(AstNode node, AstNode start)
+		{
+			Debug.Assert(start.IsNull || start.Parent == node);
+			for (var child = (start.IsNull ? node.FirstChild : start.NextSibling); child != null; child = child.NextSibling) {
+				cancellationToken.ThrowIfCancellationRequested();
+				if (child.StartLocation < regionEnd && child.EndLocation > regionStart)
+					child.AcceptVisitor(this);
+			}
+		}
+		
+		public override void VisitIdentifier(Identifier identifier)
+		{
+			switch (identifier.Name) {
+				case "add":
+				case "async":
+				case "await":
+				case "get":
+				case "partial":
+				case "remove":
+				case "set":
+				case "where":
+				case "yield":
+				case "from":
+				case "select":
+				case "group":
+				case "into":
+				case "orderby":
+				case "join":
+				case "let":
+				case "on":
+				case "equals":
+				case "by":
+				case "ascending":
+				case "descending":
+				case "dynamic":
+				case "var":
+					// Reset color of contextual keyword to default if it's used as an identifier.
+					// Note that this method does not get called when 'var' or 'dynamic' is used as a type,
+					// because types get highlighted with valueTypeColor/referenceTypeColor instead.
+					Colorize(identifier, defaultTextColor);
+					break;
+				case "global":
+					// Reset color of 'global' keyword to default unless its used as part of 'global::'.
+					MemberType parentMemberType = identifier.Parent as MemberType;
+					if (parentMemberType == null || !parentMemberType.IsDoubleColon)
+						Colorize(identifier, defaultTextColor);
+					break;
+			}
+			// "value" is handled in VisitIdentifierExpression()
+			// "alias" is handled in VisitExternAliasDeclaration()
+		}
+		
+		public override void VisitSimpleType(SimpleType simpleType)
+		{
+			var identifierToken = simpleType.IdentifierToken;
+			VisitChildrenUntil(simpleType, identifierToken);
+			Colorize(identifierToken, resolver.Resolve(simpleType, cancellationToken));
+			VisitChildrenAfter(simpleType, identifierToken);
+		}
+		
+		public override void VisitMemberType(MemberType memberType)
+		{
+			var memberNameToken = memberType.MemberNameToken;
+			VisitChildrenUntil(memberType, memberNameToken);
+			Colorize(memberNameToken, resolver.Resolve(memberType, cancellationToken));
+			VisitChildrenAfter(memberType, memberNameToken);
+		}
+		
+		public override void VisitIdentifierExpression(IdentifierExpression identifierExpression)
+		{
+			var identifier = identifierExpression.IdentifierToken;
+			VisitChildrenUntil(identifierExpression, identifier);
+			if (isInAccessorContainingValueParameter && identifierExpression.Identifier == "value") {
+				Colorize(identifier, valueKeywordColor);
+			} else {
+				Colorize(identifier, resolver.Resolve(identifierExpression, cancellationToken));
+			}
+			VisitChildrenAfter(identifierExpression, identifier);
+		}
+		
+		public override void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			var memberNameToken = memberReferenceExpression.MemberNameToken;
+			VisitChildrenUntil(memberReferenceExpression, memberNameToken);
+			ResolveResult rr = resolver.Resolve(memberReferenceExpression, cancellationToken);
+			Colorize(memberNameToken, rr);
+			VisitChildrenAfter(memberReferenceExpression, memberNameToken);
+		}
+
+		void HighlightStringFormatItems(PrimitiveExpression expr)
+		{
+			if (!(expr.Value is string))
+				return;
+			int line = expr.StartLocation.Line;
+			int col = expr.StartLocation.Column;
+			TextLocation start = TextLocation.Empty;
+			for (int i = 0; i < expr.LiteralValue.Length; i++) {
+				char ch = expr.LiteralValue [i];
+
+				if (NewLine.GetDelimiterType(ch, i + 1 < expr.LiteralValue.Length ? expr.LiteralValue [i + 1] : '\0') != UnicodeNewline.Unknown) {
+					line++;
+					col = 1;
+					continue;
+				}
+
+
+				if (ch == '{' && start.IsEmpty) {
+					char next = i + 1 < expr.LiteralValue.Length ? expr.LiteralValue [i + 1] : '\0';
+					if (next == '{') {
+						i++;
+						col += 2;
+						continue;
+					}
+					start = new TextLocation(line, col);
+				}
+				if (ch == '}' &&!start.IsEmpty) {
+					Colorize(start, new TextLocation(line, col + 1), stringFormatItemColor);
+					start = TextLocation.Empty;
+				}
+				col++;
+			}
+
+		}
+
+		public override void VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			Expression target = invocationExpression.Target;
+			if (target is IdentifierExpression || target is MemberReferenceExpression || target is PointerReferenceExpression) {
+				var invocationRR = resolver.Resolve(invocationExpression, cancellationToken) as CSharpInvocationResolveResult;
+				if (invocationRR != null) {
+					if (invocationExpression.Parent is ExpressionStatement && (IsInactiveConditionalMethod(invocationRR.Member) || IsEmptyPartialMethod(invocationRR.Member))) {
+						// mark the whole invocation statement as inactive code
+						Colorize(invocationExpression.Parent, inactiveCodeColor);
+						return;
+					}
+
+					Expression fmtArgumets;
+					IList<Expression> args;
+					if (invocationRR.Arguments.Count > 1 && FormatStringHelper.TryGetFormattingParameters(invocationRR, invocationExpression, out fmtArgumets, out args, null)) {
+						var expr = invocationExpression.Arguments.First() as PrimitiveExpression; 
+						if (expr != null)
+							HighlightStringFormatItems(expr);
+					}
+				}
+
+				VisitChildrenUntil(invocationExpression, target);
+				
+				// highlight the method call
+				var identifier = target.GetChildByRole(Roles.Identifier);
+				VisitChildrenUntil(target, identifier);
+				if (invocationRR != null && !invocationRR.IsDelegateInvocation) {
+					Colorize(identifier, methodCallColor);
+				} else {
+					ResolveResult targetRR = resolver.Resolve(target, cancellationToken);
+					Colorize(identifier, targetRR);
+				}
+				VisitChildrenAfter(target, identifier);
+				VisitChildrenAfter(invocationExpression, target);
+			} else {
+				VisitChildren(invocationExpression);
+			}
+		}
+		
+		#region IsInactiveConditional helper methods
+		bool IsInactiveConditionalMethod(IParameterizedMember member)
+		{
+			if (member.SymbolKind != SymbolKind.Method || member.ReturnType.Kind != TypeKind.Void)
+				return false;
+			foreach (var baseMember in InheritanceHelper.GetBaseMembers(member, false)) {
+				if (IsInactiveConditional (baseMember.Attributes))
+					return true;
+			}
+			return IsInactiveConditional(member.Attributes);
+		}
+
+		static bool IsEmptyPartialMethod(IParameterizedMember member)
+		{
+			if (member.SymbolKind != SymbolKind.Method || member.ReturnType.Kind != TypeKind.Void)
+				return false;
+			var method = (IMethod)member;
+			return method.IsPartial && !method.HasBody;
+		}
+
+		bool IsInactiveConditional(IList<IAttribute> attributes)
+		{
+			bool hasConditionalAttribute = false;
+			foreach (var attr in attributes) {
+				if (attr.AttributeType.Name == "ConditionalAttribute" && attr.AttributeType.Namespace == "System.Diagnostics" && attr.PositionalArguments.Count == 1) {
+					string symbol = attr.PositionalArguments[0].ConstantValue as string;
+					if (symbol != null) {
+						hasConditionalAttribute = true;
+						var cu = this.resolver.RootNode as SyntaxTree;
+						if (cu != null) {
+							if (cu.ConditionalSymbols.Contains(symbol))
+								return false; // conditional is active
+						}
+					}
+				}
+			}
+
+			return hasConditionalAttribute;
+		}
+		#endregion
+		
+		public override void VisitExternAliasDeclaration (ExternAliasDeclaration externAliasDeclaration)
+		{
+			var aliasToken = externAliasDeclaration.AliasToken;
+			VisitChildrenUntil(externAliasDeclaration, aliasToken);
+			Colorize (aliasToken, externAliasKeywordColor);
+			VisitChildrenAfter(externAliasDeclaration, aliasToken);
+		}
+		
+		public override void VisitAccessor(Accessor accessor)
+		{
+			isInAccessorContainingValueParameter = accessor.Role != PropertyDeclaration.GetterRole;
+			try {
+				VisitChildren(accessor);
+			} finally {
+				isInAccessorContainingValueParameter = false;
+			}
+		}
+		
+		bool CheckInterfaceImplementation (EntityDeclaration entityDeclaration)
+		{
+			var result = resolver.Resolve (entityDeclaration, cancellationToken) as MemberResolveResult;
+			if (result == null)
+				return false;
+			if (result.Member.ImplementedInterfaceMembers.Count == 0) {
+				Colorize (entityDeclaration.NameToken, syntaxErrorColor);
+				return false;
+			}
+			return true;
+		}
+		
+		public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			var nameToken = methodDeclaration.NameToken;
+			VisitChildrenUntil(methodDeclaration, nameToken);
+			if (!methodDeclaration.PrivateImplementationType.IsNull) {
+				if (!CheckInterfaceImplementation (methodDeclaration)) {
+					VisitChildrenAfter(methodDeclaration, nameToken);
+					return;
+				}
+			}
+			Colorize(nameToken, methodDeclarationColor);
+			VisitChildrenAfter(methodDeclaration, nameToken);
+		}
+		
+		public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			var nameToken = parameterDeclaration.NameToken;
+			VisitChildrenUntil(parameterDeclaration, nameToken);
+			Colorize(nameToken, parameterDeclarationColor);
+			VisitChildrenAfter(parameterDeclaration, nameToken);
+		}
+		
+		public override void VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			var nameToken = eventDeclaration.NameToken;
+			VisitChildrenUntil(eventDeclaration, nameToken);
+			Colorize(nameToken, eventDeclarationColor);
+			VisitChildrenAfter(eventDeclaration, nameToken);
+		}
+		
+		public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
+		{
+			var nameToken = eventDeclaration.NameToken;
+			VisitChildrenUntil(eventDeclaration, nameToken);
+			if (!eventDeclaration.PrivateImplementationType.IsNull) {
+				if (!CheckInterfaceImplementation (eventDeclaration)) {
+					VisitChildrenAfter(eventDeclaration, nameToken);
+					return;
+				}
+			}
+			Colorize(nameToken, eventDeclarationColor);
+			VisitChildrenAfter(eventDeclaration, nameToken);
+		}
+		
+		public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			var nameToken = propertyDeclaration.NameToken;
+			VisitChildrenUntil(propertyDeclaration, nameToken);
+			if (!propertyDeclaration.PrivateImplementationType.IsNull) {
+				if (!CheckInterfaceImplementation (propertyDeclaration)) {
+					VisitChildrenAfter(propertyDeclaration, nameToken);
+					return;
+				}
+			}
+			Colorize(nameToken, propertyDeclarationColor);
+			VisitChildrenAfter(propertyDeclaration, nameToken);
+		}
+		
+		public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			base.VisitIndexerDeclaration(indexerDeclaration);
+			if (!indexerDeclaration.PrivateImplementationType.IsNull) {
+				CheckInterfaceImplementation (indexerDeclaration);
+			}
+		}
+		
+		public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			fieldDeclaration.ReturnType.AcceptVisitor (this);
+			foreach (var init in fieldDeclaration.Variables) {
+				Colorize (init.NameToken, fieldDeclarationColor);
+				init.Initializer.AcceptVisitor (this);
+			}
+		}
+		
+		public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			fixedFieldDeclaration.ReturnType.AcceptVisitor (this);
+			foreach (var init in fixedFieldDeclaration.Variables) {
+				Colorize (init.NameToken, fieldDeclarationColor);
+				init.CountExpression.AcceptVisitor (this);
+			}
+		}
+		
+		public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			HandleConstructorOrDestructor(constructorDeclaration);
+		}
+		
+		public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			HandleConstructorOrDestructor(destructorDeclaration);
+		}
+		
+		void HandleConstructorOrDestructor(AstNode constructorDeclaration)
+		{
+			Identifier nameToken = constructorDeclaration.GetChildByRole(Roles.Identifier);
+			VisitChildrenUntil(constructorDeclaration, nameToken);
+			var currentTypeDef = resolver.GetResolverStateBefore(constructorDeclaration).CurrentTypeDefinition;
+			if (currentTypeDef != null && nameToken.Name == currentTypeDef.Name) {
+				TColor color;
+				if (TryGetTypeHighlighting (currentTypeDef.Kind, out color))
+					Colorize(nameToken, color);
+			}
+			VisitChildrenAfter(constructorDeclaration, nameToken);
+		}
+		
+		bool TryGetMemberColor(IMember member, out TColor color)
+		{
+			switch (member.SymbolKind) {
+				case SymbolKind.Field:
+					color = fieldAccessColor;
+					return true;
+				case SymbolKind.Property:
+					color = propertyAccessColor;
+					return true;
+				case SymbolKind.Event:
+					color = eventAccessColor;
+					return true;
+				case SymbolKind.Method:
+					color = methodCallColor;
+					return true;
+				case SymbolKind.Constructor:
+				case SymbolKind.Destructor:
+					return TryGetTypeHighlighting (member.DeclaringType.Kind, out color);
+				default:
+					color = default (TColor);
+					return false;
+			}
+		}
+		
+		TColor GetTypeHighlighting (ClassType classType)
+		{
+			switch (classType) {
+				case ClassType.Class:
+					return referenceTypeColor;
+				case ClassType.Struct:
+					return valueTypeColor;
+				case ClassType.Interface:
+					return interfaceTypeColor;
+				case ClassType.Enum:
+					return enumerationTypeColor;
+				default:
+					throw new InvalidOperationException ("Unknown class type :" + classType);
+			}
+		}
+		
+		bool TryGetTypeHighlighting (TypeKind kind, out TColor color)
+		{
+			switch (kind) {
+				case TypeKind.Class:
+					color = referenceTypeColor;
+					return true;
+				case TypeKind.Struct:
+					color = valueTypeColor;
+					return true;
+				case TypeKind.Interface:
+					color = interfaceTypeColor;
+					return true;
+				case TypeKind.Enum:
+					color = enumerationTypeColor;
+					return true;
+				case TypeKind.TypeParameter:
+					color = typeParameterTypeColor;
+					return true;
+				case TypeKind.Delegate:
+					color = delegateTypeColor;
+					return true;
+				case TypeKind.Unknown:
+				case TypeKind.Null:
+					color = syntaxErrorColor;
+					return true;
+				default:
+					color = default (TColor);
+					return false;
+			}
+		}
+		
+		public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			var nameToken = typeDeclaration.NameToken;
+			VisitChildrenUntil(typeDeclaration, nameToken);
+			Colorize(nameToken, GetTypeHighlighting (typeDeclaration.ClassType));
+			VisitChildrenAfter(typeDeclaration, nameToken);
+		}
+		
+		public override void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
+		{
+			if (typeParameterDeclaration.Variance == VarianceModifier.Contravariant)
+				Colorize(typeParameterDeclaration.VarianceToken, parameterModifierColor);
+			
+			//			bool isValueType = false;
+			//			if (typeParameterDeclaration.Parent != null) {
+			//				foreach (var constraint in typeParameterDeclaration.Parent.GetChildrenByRole(Roles.Constraint)) {
+			//					if (constraint.TypeParameter.Identifier == typeParameterDeclaration.Name) {
+			//						isValueType = constraint.BaseTypes.OfType<PrimitiveType>().Any(p => p.Keyword == "struct");
+			//					}
+			//				}
+			//			}
+			var nameToken = typeParameterDeclaration.NameToken;
+			VisitChildrenUntil(typeParameterDeclaration, nameToken);
+			Colorize(nameToken, typeParameterTypeColor);  /*isValueType ? valueTypeColor : referenceTypeColor*/
+			VisitChildrenAfter(typeParameterDeclaration, nameToken);
+		}
+		
+		public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			var nameToken = delegateDeclaration.NameToken;
+			VisitChildrenUntil(delegateDeclaration, nameToken);
+			Colorize(nameToken, delegateTypeColor);
+			VisitChildrenAfter(delegateDeclaration, nameToken);
+		}
+		
+		public override void VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			var nameToken = variableInitializer.NameToken;
+			VisitChildrenUntil(variableInitializer, nameToken);
+			if (variableInitializer.Parent is FieldDeclaration) {
+				Colorize(nameToken, fieldDeclarationColor);
+			} else if (variableInitializer.Parent is EventDeclaration) {
+				Colorize(nameToken, eventDeclarationColor);
+			} else {
+				Colorize(nameToken, variableDeclarationColor);
+			}
+			VisitChildrenAfter(variableInitializer, nameToken);
+		}
+		
+		public override void VisitComment(Comment comment)
+		{
+			if (comment.CommentType == CommentType.InactiveCode) {
+				Colorize(comment, inactiveCodeColor);
+			}
+		}
+
+		public override void VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective)
+		{
+		}
+		
+		public override void VisitAttribute(ICSharpCode.NRefactory.CSharp.Attribute attribute)
+		{
+			ITypeDefinition attrDef = resolver.Resolve(attribute.Type, cancellationToken).Type.GetDefinition();
+			if (attrDef != null && IsInactiveConditional(attrDef.Attributes)) {
+				Colorize(attribute, inactiveCodeColor);
+			} else {
+				VisitChildren(attribute);
+			}
+		}
+		
+		public override void VisitArrayInitializerExpression (ArrayInitializerExpression arrayInitializerExpression)
+		{
+			foreach (var a in arrayInitializerExpression.Elements) {
+				var namedElement = a as NamedExpression;
+				if (namedElement != null) {
+					var result = resolver.Resolve (namedElement, cancellationToken);
+					if (result.IsError)
+						Colorize (namedElement.NameToken, syntaxErrorColor);
+					namedElement.Expression.AcceptVisitor (this);
+				} else {
+					a.AcceptVisitor (this);
+				}
+			}
+		}
+
+		int blockDepth;
+		public override void VisitBlockStatement(BlockStatement blockStatement)
+		{
+			blockDepth++;
+			base.VisitBlockStatement(blockStatement);
+			blockDepth--;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstNode.cs	(revision 11807)
@@ -0,0 +1,1042 @@
+﻿// 
+// AstNode.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public abstract class AstNode : AbstractAnnotatable, ICSharpCode.NRefactory.TypeSystem.IFreezable, PatternMatching.INode, ICloneable
+	{
+		// the Root role must be available when creating the null nodes, so we can't put it in the Roles class
+		internal static readonly Role<AstNode> RootRole = new Role<AstNode> ("Root");
+		
+		#region Null
+		public static readonly AstNode Null = new NullAstNode ();
+		
+		sealed class NullAstNode : AstNode
+		{
+			public override NodeType NodeType {
+				get {
+					return NodeType.Unknown;
+				}
+			}
+			
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+		
+		#region PatternPlaceholder
+		public static implicit operator AstNode (PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder (pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : AstNode, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder (PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder (this, child);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder (this, child);
+			}
+
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder (this, child, data);
+			}
+			
+			protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch (other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection (Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection (role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		AstNode parent;
+		AstNode prevSibling;
+		AstNode nextSibling;
+		AstNode firstChild;
+		AstNode lastChild;
+		
+		// Flags, from least significant to most significant bits:
+		// - Role.RoleIndexBits: role index
+		// - 1 bit: IsFrozen
+		protected uint flags = RootRole.Index;
+		// Derived classes may also use a few bits,
+		// for example Identifier uses 1 bit for IsVerbatim
+		
+		const uint roleIndexMask = (1u << Role.RoleIndexBits) - 1;
+		const uint frozenBit = 1u << Role.RoleIndexBits;
+		protected const int AstNodeFlagsUsedBits = Role.RoleIndexBits + 1;
+		
+		protected AstNode()
+		{
+			if (IsNull)
+				Freeze();
+		}
+		
+		public bool IsFrozen {
+			get { return (flags & frozenBit) != 0; }
+		}
+		
+		public void Freeze()
+		{
+			if (!IsFrozen) {
+				for (AstNode child = firstChild; child != null; child = child.nextSibling)
+					child.Freeze();
+				flags |= frozenBit;
+			}
+		}
+		
+		protected void ThrowIfFrozen()
+		{
+			if (IsFrozen)
+				throw new InvalidOperationException("Cannot mutate frozen " + GetType().Name);
+		}
+		
+		public abstract NodeType NodeType {
+			get;
+		}
+		
+		public virtual bool IsNull {
+			get {
+				return false;
+			}
+		}
+		
+		public virtual TextLocation StartLocation {
+			get {
+				var child = firstChild;
+				if (child == null)
+					return TextLocation.Empty;
+				return child.StartLocation;
+			}
+		}
+		
+		public virtual TextLocation EndLocation {
+			get {
+				var child = lastChild;
+				if (child == null)
+					return TextLocation.Empty;
+				return child.EndLocation;
+			}
+		}
+
+		public DomRegion Region {
+			get {
+				return new DomRegion (StartLocation, EndLocation);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the region from StartLocation to EndLocation for this node.
+		/// The file name of the region is set based on the parent SyntaxTree's file name.
+		/// If this node is not connected to a whole compilation, the file name will be null.
+		/// </summary>
+		public ICSharpCode.NRefactory.TypeSystem.DomRegion GetRegion()
+		{
+			var syntaxTree = (this.Ancestors.LastOrDefault() ?? this) as SyntaxTree;
+			string fileName = (syntaxTree != null ? syntaxTree.FileName : null);
+			return new ICSharpCode.NRefactory.TypeSystem.DomRegion(fileName, this.StartLocation, this.EndLocation);
+		}
+		
+		public AstNode Parent {
+			get { return parent; }
+		}
+		
+		public Role Role {
+			get {
+				return Role.GetByIndex(flags & roleIndexMask);
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				if (!value.IsValid(this))
+					throw new ArgumentException("This node is not valid in the new role.");
+				ThrowIfFrozen();
+				SetRole(value);
+			}
+		}
+		
+		internal uint RoleIndex {
+			get { return flags & roleIndexMask; }
+		}
+		
+		void SetRole(Role role)
+		{
+			flags = (flags & ~roleIndexMask) | role.Index;
+		}
+		
+		public AstNode NextSibling {
+			get { return nextSibling; }
+		}
+		
+		public AstNode PrevSibling {
+			get { return prevSibling; }
+		}
+		
+		public AstNode FirstChild {
+			get { return firstChild; }
+		}
+		
+		public AstNode LastChild {
+			get { return lastChild; }
+		}
+		
+		public bool HasChildren {
+			get {
+				return firstChild != null;
+			}
+		}
+		
+		public IEnumerable<AstNode> Children {
+			get {
+				AstNode next;
+				for (AstNode cur = firstChild; cur != null; cur = next) {
+					Debug.Assert (cur.parent == this);
+					// Remember next before yielding cur.
+					// This allows removing/replacing nodes while iterating through the list.
+					next = cur.nextSibling;
+					yield return cur;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the ancestors of this node (excluding this node itself)
+		/// </summary>
+		public IEnumerable<AstNode> Ancestors {
+			get {
+				for (AstNode cur = parent; cur != null; cur = cur.parent) {
+					yield return cur;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the ancestors of this node (including this node itself)
+		/// </summary>
+		public IEnumerable<AstNode> AncestorsAndSelf {
+			get {
+				for (AstNode cur = this; cur != null; cur = cur.parent) {
+					yield return cur;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets all descendants of this node (excluding this node itself) in pre-order.
+		/// </summary>
+		public IEnumerable<AstNode> Descendants {
+			get { return GetDescendantsImpl(false); }
+		}
+		
+		/// <summary>
+		/// Gets all descendants of this node (including this node itself) in pre-order.
+		/// </summary>
+		public IEnumerable<AstNode> DescendantsAndSelf {
+			get { return GetDescendantsImpl(true); }
+		}
+
+		static bool IsInsideRegion(DomRegion region, AstNode pos)
+		{
+			if (region.IsEmpty)
+				return true;
+			var nodeRegion = pos.Region;
+			return region.IntersectsWith(nodeRegion) || region.OverlapsWith(nodeRegion);
+		}
+
+		public IEnumerable<AstNode> DescendantNodes (Func<AstNode, bool> descendIntoChildren = null)
+		{
+			return GetDescendantsImpl(false, new DomRegion (), descendIntoChildren);
+		}
+
+		public IEnumerable<AstNode> DescendantNodes (DomRegion region, Func<AstNode, bool> descendIntoChildren = null)
+		{
+			return GetDescendantsImpl(false, region, descendIntoChildren);
+		}
+
+		public IEnumerable<AstNode> DescendantNodesAndSelf (Func<AstNode, bool> descendIntoChildren = null)
+		{
+			return GetDescendantsImpl(true, new DomRegion (), descendIntoChildren);
+		}
+
+		public IEnumerable<AstNode> DescendantNodesAndSelf (DomRegion region, Func<AstNode, bool> descendIntoChildren = null)
+		{
+			return GetDescendantsImpl(true, region, descendIntoChildren);
+		}
+
+		IEnumerable<AstNode> GetDescendantsImpl(bool includeSelf, DomRegion region = new DomRegion (), Func<AstNode, bool> descendIntoChildren = null)
+		{
+			if (includeSelf) {
+				if (IsInsideRegion (region, this))
+					yield return this;
+				if (descendIntoChildren != null && !descendIntoChildren(this))
+					yield break;
+			}
+
+			Stack<AstNode> nextStack = new Stack<AstNode>();
+			nextStack.Push(null);
+			AstNode pos = firstChild;
+			while (pos != null) {
+				// Remember next before yielding pos.
+				// This allows removing/replacing nodes while iterating through the list.
+				if (pos.nextSibling != null)
+					nextStack.Push(pos.nextSibling);
+				if (IsInsideRegion(region, pos))
+					yield return pos;
+				if (pos.firstChild != null && (descendIntoChildren == null || descendIntoChildren(pos)))
+					pos = pos.firstChild;
+				else
+					pos = nextStack.Pop();
+			}
+		}
+		
+		/// <summary>
+		/// Gets the first child with the specified role.
+		/// Returns the role's null object if the child is not found.
+		/// </summary>
+		public T GetChildByRole<T>(Role<T> role) where T : AstNode
+		{
+			if (role == null)
+				throw new ArgumentNullException ("role");
+			uint roleIndex = role.Index;
+			for (var cur = firstChild; cur != null; cur = cur.nextSibling) {
+				if ((cur.flags & roleIndexMask) == roleIndex)
+					return (T)cur;
+			}
+			return role.NullObject;
+		}
+		
+		public T GetParent<T>() where T : AstNode
+		{
+			return Ancestors.OfType<T>().FirstOrDefault();
+		}
+
+		public AstNode GetParent(Func<AstNode, bool> pred)
+		{
+			return Ancestors.FirstOrDefault(pred);
+		}
+
+		public AstNodeCollection<T> GetChildrenByRole<T> (Role<T> role) where T : AstNode
+		{
+			return new AstNodeCollection<T> (this, role);
+		}
+		
+		protected void SetChildByRole<T> (Role<T> role, T newChild) where T : AstNode
+		{
+			AstNode oldChild = GetChildByRole (role);
+			if (oldChild.IsNull)
+				AddChild (newChild, role);
+			else
+				oldChild.ReplaceWith (newChild);
+		}
+		
+		public void AddChild<T> (T child, Role<T> role) where T : AstNode
+		{
+			if (role == null)
+				throw new ArgumentNullException ("role");
+			if (child == null || child.IsNull)
+				return;
+			ThrowIfFrozen();
+			if (child == this)
+				throw new ArgumentException ("Cannot add a node to itself as a child.", "child");
+			if (child.parent != null)
+				throw new ArgumentException ("Node is already used in another tree.", "child");
+			if (child.IsFrozen)
+				throw new ArgumentException ("Cannot add a frozen node.", "child");
+			AddChildUnsafe (child, role);
+		}
+		
+		public void AddChildWithExistingRole (AstNode child)
+		{
+			if (child == null || child.IsNull)
+				return;
+			ThrowIfFrozen();
+			if (child == this)
+				throw new ArgumentException ("Cannot add a node to itself as a child.", "child");
+			if (child.parent != null)
+				throw new ArgumentException ("Node is already used in another tree.", "child");
+			if (child.IsFrozen)
+				throw new ArgumentException ("Cannot add a frozen node.", "child");
+			AddChildUnsafe (child, child.Role);
+		}
+		
+		/// <summary>
+		/// Adds a child without performing any safety checks.
+		/// </summary>
+		internal void AddChildUnsafe (AstNode child, Role role)
+		{
+			child.parent = this;
+			child.SetRole(role);
+			if (firstChild == null) {
+				lastChild = firstChild = child;
+			} else {
+				lastChild.nextSibling = child;
+				child.prevSibling = lastChild;
+				lastChild = child;
+			}
+		}
+
+		public void InsertChildBefore<T> (AstNode nextSibling, T child, Role<T> role) where T : AstNode
+		{
+			if (role == null)
+				throw new ArgumentNullException ("role");
+			if (nextSibling == null || nextSibling.IsNull) {
+				AddChild (child, role);
+				return;
+			}
+			
+			if (child == null || child.IsNull)
+				return;
+			ThrowIfFrozen();
+			if (child.parent != null)
+				throw new ArgumentException ("Node is already used in another tree.", "child");
+			if (child.IsFrozen)
+				throw new ArgumentException ("Cannot add a frozen node.", "child");
+			if (nextSibling.parent != this)
+				throw new ArgumentException ("NextSibling is not a child of this node.", "nextSibling");
+			// No need to test for "Cannot add children to null nodes",
+			// as there isn't any valid nextSibling in null nodes.
+			InsertChildBeforeUnsafe (nextSibling, child, role);
+		}
+		
+		internal void InsertChildBeforeUnsafe (AstNode nextSibling, AstNode child, Role role)
+		{
+			child.parent = this;
+			child.SetRole(role);
+			child.nextSibling = nextSibling;
+			child.prevSibling = nextSibling.prevSibling;
+			
+			if (nextSibling.prevSibling != null) {
+				Debug.Assert (nextSibling.prevSibling.nextSibling == nextSibling);
+				nextSibling.prevSibling.nextSibling = child;
+			} else {
+				Debug.Assert (firstChild == nextSibling);
+				firstChild = child;
+			}
+			nextSibling.prevSibling = child;
+		}
+		
+		public void InsertChildAfter<T> (AstNode prevSibling, T child, Role<T> role) where T : AstNode
+		{
+			InsertChildBefore ((prevSibling == null || prevSibling.IsNull) ? firstChild : prevSibling.nextSibling, child, role);
+		}
+		
+		/// <summary>
+		/// Removes this node from its parent.
+		/// </summary>
+		public void Remove ()
+		{
+			if (parent != null) {
+				ThrowIfFrozen();
+				if (prevSibling != null) {
+					Debug.Assert (prevSibling.nextSibling == this);
+					prevSibling.nextSibling = nextSibling;
+				} else {
+					Debug.Assert (parent.firstChild == this);
+					parent.firstChild = nextSibling;
+				}
+				if (nextSibling != null) {
+					Debug.Assert (nextSibling.prevSibling == this);
+					nextSibling.prevSibling = prevSibling;
+				} else {
+					Debug.Assert (parent.lastChild == this);
+					parent.lastChild = prevSibling;
+				}
+				parent = null;
+				prevSibling = null;
+				nextSibling = null;
+			}
+		}
+		
+		/// <summary>
+		/// Replaces this node with the new node.
+		/// </summary>
+		public void ReplaceWith (AstNode newNode)
+		{
+			if (newNode == null || newNode.IsNull) {
+				Remove ();
+				return;
+			}
+			if (newNode == this)
+				return; // nothing to do...
+			if (parent == null) {
+				throw new InvalidOperationException (this.IsNull ? "Cannot replace the null nodes" : "Cannot replace the root node");
+			}
+			ThrowIfFrozen();
+			// Because this method doesn't statically check the new node's type with the role,
+			// we perform a runtime test:
+			if (!this.Role.IsValid (newNode)) {
+				throw new ArgumentException (string.Format ("The new node '{0}' is not valid in the role {1}", newNode.GetType ().Name, this.Role.ToString ()), "newNode");
+			}
+			if (newNode.parent != null) {
+				// newNode is used within this tree?
+				if (newNode.Ancestors.Contains (this)) {
+					// e.g. "parenthesizedExpr.ReplaceWith(parenthesizedExpr.Expression);"
+					// enable automatic removal
+					newNode.Remove ();
+				} else {
+					throw new ArgumentException ("Node is already used in another tree.", "newNode");
+				}
+			}
+			if (newNode.IsFrozen)
+				throw new ArgumentException ("Cannot add a frozen node.", "newNode");
+			
+			newNode.parent = parent;
+			newNode.SetRole(this.Role);
+			newNode.prevSibling = prevSibling;
+			newNode.nextSibling = nextSibling;
+
+			if (prevSibling != null) {
+				Debug.Assert (prevSibling.nextSibling == this);
+				prevSibling.nextSibling = newNode;
+			} else {
+				Debug.Assert (parent.firstChild == this);
+				parent.firstChild = newNode;
+			}
+			if (nextSibling != null) {
+				Debug.Assert (nextSibling.prevSibling == this);
+				nextSibling.prevSibling = newNode;
+			} else {
+				Debug.Assert (parent.lastChild == this);
+				parent.lastChild = newNode;
+			}
+			parent = null;
+			prevSibling = null;
+			nextSibling = null;
+		}
+		
+		public AstNode ReplaceWith (Func<AstNode, AstNode> replaceFunction)
+		{
+			if (replaceFunction == null)
+				throw new ArgumentNullException ("replaceFunction");
+			if (parent == null) {
+				throw new InvalidOperationException (this.IsNull ? "Cannot replace the null nodes" : "Cannot replace the root node");
+			}
+			AstNode oldParent = parent;
+			AstNode oldSuccessor = nextSibling;
+			Role oldRole = this.Role;
+			Remove ();
+			AstNode replacement = replaceFunction (this);
+			if (oldSuccessor != null && oldSuccessor.parent != oldParent)
+				throw new InvalidOperationException ("replace function changed nextSibling of node being replaced?");
+			if (!(replacement == null || replacement.IsNull)) {
+				if (replacement.parent != null)
+					throw new InvalidOperationException ("replace function must return the root of a tree");
+				if (!oldRole.IsValid (replacement)) {
+					throw new InvalidOperationException (string.Format ("The new node '{0}' is not valid in the role {1}", replacement.GetType ().Name, oldRole.ToString ()));
+				}
+				
+				if (oldSuccessor != null)
+					oldParent.InsertChildBeforeUnsafe (oldSuccessor, replacement, oldRole);
+				else
+					oldParent.AddChildUnsafe (replacement, oldRole);
+			}
+			return replacement;
+		}
+		
+		/// <summary>
+		/// Clones the whole subtree starting at this AST node.
+		/// </summary>
+		/// <remarks>Annotations are copied over to the new nodes; and any annotations implementing ICloneable will be cloned.</remarks>
+		public AstNode Clone ()
+		{
+			AstNode copy = (AstNode)MemberwiseClone ();
+			// First, reset the shallow pointer copies
+			copy.parent = null;
+			copy.firstChild = null;
+			copy.lastChild = null;
+			copy.prevSibling = null;
+			copy.nextSibling = null;
+			copy.flags &= ~frozenBit; // unfreeze the copy
+			
+			// Then perform a deep copy:
+			for (AstNode cur = firstChild; cur != null; cur = cur.nextSibling) {
+				copy.AddChildUnsafe (cur.Clone (), cur.Role);
+			}
+			
+			// Finally, clone the annotation, if necessary
+			copy.CloneAnnotations();
+			
+			return copy;
+		}
+		
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+		
+		public abstract void AcceptVisitor (IAstVisitor visitor);
+		
+		public abstract T AcceptVisitor<T> (IAstVisitor<T> visitor);
+		
+		public abstract S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data);
+		
+		#region Pattern Matching
+		protected static bool MatchString (string pattern, string text)
+		{
+			return PatternMatching.Pattern.MatchString(pattern, text);
+		}
+		
+		protected internal abstract bool DoMatch (AstNode other, PatternMatching.Match match);
+		
+		bool PatternMatching.INode.DoMatch (PatternMatching.INode other, PatternMatching.Match match)
+		{
+			AstNode o = other as AstNode;
+			// try matching if other is null, or if other is an AstNode
+			return (other == null || o != null) && DoMatch (o, match);
+		}
+		
+		bool PatternMatching.INode.DoMatchCollection (Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+		{
+			AstNode o = pos as AstNode;
+			return (pos == null || o != null) && DoMatch (o, match);
+		}
+		
+		PatternMatching.INode PatternMatching.INode.NextSibling {
+			get { return nextSibling; }
+		}
+		
+		PatternMatching.INode PatternMatching.INode.FirstChild {
+			get { return firstChild; }
+		}
+
+		#endregion
+		
+		public AstNode GetNextNode ()
+		{
+			if (NextSibling != null)
+				return NextSibling;
+			if (Parent != null)
+				return Parent.GetNextNode ();
+			return null;
+		}
+
+		/// <summary>
+		/// Gets the next node which fullfills a given predicate
+		/// </summary>
+		/// <returns>The next node.</returns>
+		/// <param name="pred">The predicate.</param>
+		public AstNode GetNextNode (Func<AstNode, bool> pred)
+		{
+			var next = GetNextNode();
+			while (next != null && !pred (next))
+				next = next.GetNextNode();
+			return next;
+		}
+
+		public AstNode GetPrevNode ()
+		{
+			if (PrevSibling != null)
+				return PrevSibling;
+			if (Parent != null)
+				return Parent.GetPrevNode ();
+			return null;
+		}
+
+		/// <summary>
+		/// Gets the previous node which fullfills a given predicate
+		/// </summary>
+		/// <returns>The next node.</returns>
+		/// <param name="pred">The predicate.</param>
+		public AstNode GetPrevNode (Func<AstNode, bool> pred)
+		{
+			var prev = GetPrevNode();
+			while (prev != null && !pred (prev))
+				prev = prev.GetPrevNode();
+			return prev;
+		}
+		// filters all non c# nodes (comments, white spaces or pre processor directives)
+		public AstNode GetCSharpNodeBefore (AstNode node)
+		{
+			var n = node.PrevSibling;
+			while (n != null) {
+				if (n.Role != Roles.Comment)
+					return n;
+				n = n.GetPrevNode ();
+			}
+			return null;
+		}
+
+		/// <summary>
+		/// Gets the next sibling which fullfills a given predicate
+		/// </summary>
+		/// <returns>The next node.</returns>
+		/// <param name="pred">The predicate.</param>
+		public AstNode GetNextSibling (Func<AstNode, bool> pred)
+		{
+			var next = NextSibling;
+			while (next != null && !pred (next))
+				next = next.NextSibling;
+			return next;
+		}
+
+		/// <summary>
+		/// Gets the next sibling which fullfills a given predicate
+		/// </summary>
+		/// <returns>The next node.</returns>
+		/// <param name="pred">The predicate.</param>
+		public AstNode GetPrevSibling (Func<AstNode, bool> pred)
+		{
+			var prev = PrevSibling;
+			while (prev != null && !pred (prev))
+				prev = prev.PrevSibling;
+			return prev;
+		}
+		
+		#region GetNodeAt
+		/// <summary>
+		/// Gets the node specified by T at the location line, column. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End exclusive)
+		/// </summary>
+		public AstNode GetNodeAt (int line, int column, Predicate<AstNode> pred = null)
+		{
+			return GetNodeAt (new TextLocation (line, column), pred);
+		}
+		
+		/// <summary>
+		/// Gets the node specified by pred at location. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End exclusive)
+		/// </summary>
+		public AstNode GetNodeAt (TextLocation location, Predicate<AstNode> pred = null)
+		{
+			AstNode result = null;
+			AstNode node = this;
+			while (node.LastChild != null) {
+				var child = node.LastChild;
+				while (child != null && child.StartLocation > location)
+					child = child.prevSibling;
+				if (child != null && location < child.EndLocation) {
+					if (pred == null || pred (child))
+						result = child;
+					node = child;
+				} else {
+					// found no better child node - therefore the parent is the right one.
+					break;
+				}
+			}
+			return result;
+		}
+		
+		/// <summary>
+		/// Gets the node specified by T at the location line, column. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End exclusive)
+		/// </summary>
+		public T GetNodeAt<T> (int line, int column) where T : AstNode
+		{
+			return GetNodeAt<T> (new TextLocation (line, column));
+		}
+		
+		/// <summary>
+		/// Gets the node specified by T at location. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End exclusive)
+		/// </summary>
+		public T GetNodeAt<T> (TextLocation location) where T : AstNode
+		{
+			T result = null;
+			AstNode node = this;
+			while (node.LastChild != null) {
+				var child = node.LastChild;
+				while (child != null && child.StartLocation > location)
+					child = child.prevSibling;
+				if (child != null && location < child.EndLocation) {
+					if (child is T)
+						result = (T)child;
+					node = child;
+				} else {
+					// found no better child node - therefore the parent is the right one.
+					break;
+				}
+			}
+			return result;
+		}
+
+		#endregion
+
+		#region GetAdjacentNodeAt
+		/// <summary>
+		/// Gets the node specified by pred at the location line, column. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End inclusive)
+		/// </summary>
+		public AstNode GetAdjacentNodeAt(int line, int column, Predicate<AstNode> pred = null)
+		{
+			return GetAdjacentNodeAt (new TextLocation (line, column), pred);
+		}
+		
+		/// <summary>
+		/// Gets the node specified by pred at location. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End inclusive)
+		/// </summary>
+		public AstNode GetAdjacentNodeAt (TextLocation location, Predicate<AstNode> pred = null)
+		{
+			AstNode result = null;
+			AstNode node = this;
+			while (node.LastChild != null) {
+				var child = node.LastChild;
+				while (child != null && child.StartLocation > location)
+					child = child.prevSibling;
+				if (child != null && location <= child.EndLocation) {
+					if (pred == null || pred (child))
+						result = child;
+					node = child;
+				} else {
+					// found no better child node - therefore the parent is the right one.
+					break;
+				}
+			}
+			return result;
+		}
+		
+		/// <summary>
+		/// Gets the node specified by T at the location line, column. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End inclusive)
+		/// </summary>
+		public T GetAdjacentNodeAt<T>(int line, int column) where T : AstNode
+		{
+			return GetAdjacentNodeAt<T> (new TextLocation (line, column));
+		}
+		
+		/// <summary>
+		/// Gets the node specified by T at location. This is useful for getting a specific node from the tree. For example searching
+		/// the current method declaration.
+		/// (End inclusive)
+		/// </summary>
+		public T GetAdjacentNodeAt<T> (TextLocation location) where T : AstNode
+		{
+			T result = null;
+			AstNode node = this;
+			while (node.LastChild != null) {
+				var child = node.LastChild;
+				while (child != null && child.StartLocation > location)
+					child = child.prevSibling;
+				if (child != null && location <= child.EndLocation) {
+					if (child is T)
+						result = (T)child;
+					node = child;
+				} else {
+					// found no better child node - therefore the parent is the right one.
+					break;
+				}
+			}
+			return result;
+		}
+		#endregion
+
+
+		/// <summary>
+		/// Gets the node that fully contains the range from startLocation to endLocation.
+		/// </summary>
+		public AstNode GetNodeContaining(TextLocation startLocation, TextLocation endLocation)
+		{
+			for (AstNode child = firstChild; child != null; child = child.nextSibling) {
+				if (child.StartLocation <= startLocation && endLocation <= child.EndLocation)
+					return child.GetNodeContaining(startLocation, endLocation);
+			}
+			return this;
+		}
+		
+		/// <summary>
+		/// Returns the root nodes of all subtrees that are fully contained in the specified region.
+		/// </summary>
+		public IEnumerable<AstNode> GetNodesBetween (int startLine, int startColumn, int endLine, int endColumn)
+		{
+			return GetNodesBetween (new TextLocation (startLine, startColumn), new TextLocation (endLine, endColumn));
+		}
+		
+		/// <summary>
+		/// Returns the root nodes of all subtrees that are fully contained between <paramref name="start"/> and <paramref name="end"/> (inclusive).
+		/// </summary>
+		public IEnumerable<AstNode> GetNodesBetween (TextLocation start, TextLocation end)
+		{
+			AstNode node = this;
+			while (node != null) {
+				AstNode next;
+				if (start <= node.StartLocation && node.EndLocation <= end) {
+					// Remember next before yielding node.
+					// This allows iteration to continue when the caller removes/replaces the node.
+					next = node.GetNextNode();
+					yield return node;
+				} else {
+					if (node.EndLocation <= start) {
+						next = node.GetNextNode();
+					} else {
+						next = node.FirstChild;
+					}
+				}
+				
+				if (next != null && next.StartLocation > end)
+					yield break;
+				node = next;
+			}
+		}
+		[Obsolete("Use ToString(options).")]
+		public string GetText (CSharpFormattingOptions formattingOptions = null)
+		{
+			return ToString(formattingOptions);
+		}
+
+		/// <summary>
+		/// Gets the node as formatted C# output.
+		/// </summary>
+		/// <param name='formattingOptions'>
+		/// Formatting options.
+		/// </param>
+		public virtual string ToString (CSharpFormattingOptions formattingOptions)
+		{
+			if (IsNull)
+				return "";
+			var w = new StringWriter ();
+			AcceptVisitor (new CSharpOutputVisitor (w, formattingOptions ?? FormattingOptionsFactory.CreateMono ()));
+			return w.ToString ();
+		}
+
+		public sealed override string ToString()
+		{
+			return ToString(null);
+		}
+
+		/// <summary>
+		/// Returns true, if the given coordinates (line, column) are in the node.
+		/// </summary>
+		/// <returns>
+		/// True, if the given coordinates are between StartLocation and EndLocation (exclusive); otherwise, false.
+		/// </returns>
+		public bool Contains (int line, int column)
+		{
+			return Contains (new TextLocation (line, column));
+		}
+		
+		/// <summary>
+		/// Returns true, if the given coordinates are in the node.
+		/// </summary>
+		/// <returns>
+		/// True, if location is between StartLocation and EndLocation (exclusive); otherwise, false.
+		/// </returns>
+		public bool Contains (TextLocation location)
+		{
+			return this.StartLocation <= location && location < this.EndLocation;
+		}
+		
+		/// <summary>
+		/// Returns true, if the given coordinates (line, column) are in the node.
+		/// </summary>
+		/// <returns>
+		/// True, if the given coordinates are between StartLocation and EndLocation (inclusive); otherwise, false.
+		/// </returns>
+		public bool IsInside (int line, int column)
+		{
+			return IsInside (new TextLocation (line, column));
+		}
+		
+		/// <summary>
+		/// Returns true, if the given coordinates are in the node.
+		/// </summary>
+		/// <returns>
+		/// True, if location is between StartLocation and EndLocation (inclusive); otherwise, false.
+		/// </returns>
+		public bool IsInside (TextLocation location)
+		{
+			return this.StartLocation <= location && location <= this.EndLocation;
+		}
+		
+		public override void AddAnnotation (object annotation)
+		{
+			if (this.IsNull)
+				throw new InvalidOperationException ("Cannot add annotations to the null node");
+			base.AddAnnotation (annotation);
+		}
+		
+		internal string DebugToString()
+		{
+			if (IsNull)
+				return "Null";
+			string text = ToString();
+			text = text.TrimEnd().Replace("\t", "").Replace(Environment.NewLine, " ");
+			if (text.Length > 100)
+				return text.Substring(0, 97) + "...";
+			else
+				return text;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstNodeCollection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstNodeCollection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstNodeCollection.cs	(revision 11807)
@@ -0,0 +1,231 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.PatternMatching;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents the children of an AstNode that have a specific role.
+	/// </summary>
+	public class AstNodeCollection<T> : ICollection<T>
+		#if NET_4_5
+		, IReadOnlyCollection<T>
+		#endif
+		where T : AstNode
+	{
+		readonly AstNode node;
+		readonly Role<T> role;
+		
+		public AstNodeCollection(AstNode node, Role<T> role)
+		{
+			if (node == null)
+				throw new ArgumentNullException("node");
+			if (role == null)
+				throw new ArgumentNullException("role");
+			this.node = node;
+			this.role = role;
+		}
+		
+		public int Count {
+			get {
+				int count = 0;
+				uint roleIndex = role.Index;
+				for (AstNode cur = node.FirstChild; cur != null; cur = cur.NextSibling) {
+					if (cur.RoleIndex == roleIndex)
+						count++;
+				}
+				return count;
+			}
+		}
+		
+		public void Add(T element)
+		{
+			node.AddChild(element, role);
+		}
+		
+		public void AddRange(IEnumerable<T> nodes)
+		{
+			// Evaluate 'nodes' first, since it might change when we add the new children
+			// Example: collection.AddRange(collection);
+			if (nodes != null) {
+				foreach (T node in nodes.ToList())
+					Add(node);
+			}
+		}
+		
+		public void AddRange(T[] nodes)
+		{
+			// Fast overload for arrays - we don't need to create a copy
+			if (nodes != null) {
+				foreach (T node in nodes)
+					Add(node);
+			}
+		}
+		
+		public void ReplaceWith(IEnumerable<T> nodes)
+		{
+			// Evaluate 'nodes' first, since it might change when we call Clear()
+			// Example: collection.ReplaceWith(collection);
+			if (nodes != null)
+				nodes = nodes.ToList();
+			Clear();
+			if (nodes != null) {
+				foreach (T node in nodes)
+					Add(node);
+			}
+		}
+		
+		public void MoveTo(ICollection<T> targetCollection)
+		{
+			if (targetCollection == null)
+				throw new ArgumentNullException("targetCollection");
+			foreach (T node in this) {
+				node.Remove();
+				targetCollection.Add(node);
+			}
+		}
+		
+		public bool Contains(T element)
+		{
+			return element != null && element.Parent == node && element.RoleIndex == role.Index;
+		}
+		
+		public bool Remove(T element)
+		{
+			if (Contains(element)) {
+				element.Remove();
+				return true;
+			} else {
+				return false;
+			}
+		}
+		
+		public void CopyTo(T[] array, int arrayIndex)
+		{
+			foreach (T item in this)
+				array[arrayIndex++] = item;
+		}
+		
+		public void Clear()
+		{
+			foreach (T item in this)
+				item.Remove();
+		}
+		
+		/// <summary>
+		/// Returns the first element for which the predicate returns true,
+		/// or the null node (AstNode with IsNull=true) if no such object is found.
+		/// </summary>
+		public T FirstOrNullObject(Func<T, bool> predicate = null)
+		{
+			foreach (T item in this)
+				if (predicate == null || predicate(item))
+					return item;
+			return role.NullObject;
+		}
+		
+		/// <summary>
+		/// Returns the last element for which the predicate returns true,
+		/// or the null node (AstNode with IsNull=true) if no such object is found.
+		/// </summary>
+		public T LastOrNullObject(Func<T, bool> predicate = null)
+		{
+			T result = role.NullObject;
+			foreach (T item in this)
+				if (predicate == null || predicate(item))
+					result = item;
+			return result;
+		}
+		
+		bool ICollection<T>.IsReadOnly {
+			get { return false; }
+		}
+		
+		public IEnumerator<T> GetEnumerator()
+		{
+			uint roleIndex = role.Index;
+			AstNode next;
+			for (AstNode cur = node.FirstChild; cur != null; cur = next) {
+				Debug.Assert(cur.Parent == node);
+				// Remember next before yielding cur.
+				// This allows removing/replacing nodes while iterating through the list.
+				next = cur.NextSibling;
+				if (cur.RoleIndex == roleIndex)
+					yield return (T)cur;
+			}
+		}
+		
+		IEnumerator IEnumerable.GetEnumerator()
+		{
+			return GetEnumerator();
+		}
+		
+		#region Equals and GetHashCode implementation
+		public override int GetHashCode()
+		{
+			return node.GetHashCode() ^ role.GetHashCode();
+		}
+		
+		public override bool Equals(object obj)
+		{
+			AstNodeCollection<T> other = obj as AstNodeCollection<T>;
+			if (other == null)
+				return false;
+			return this.node == other.node && this.role == other.role;
+		}
+		#endregion
+		
+		internal bool DoMatch(AstNodeCollection<T> other, Match match)
+		{
+			return Pattern.DoMatchCollection(role, node.FirstChild, other.node.FirstChild, match);
+		}
+		
+		public void InsertAfter(T existingItem, T newItem)
+		{
+			node.InsertChildAfter(existingItem, newItem, role);
+		}
+		
+		public void InsertBefore(T existingItem, T newItem)
+		{
+			node.InsertChildBefore(existingItem, newItem, role);
+		}
+		
+		/// <summary>
+		/// Applies the <paramref name="visitor"/> to all nodes in this collection.
+		/// </summary>
+		public void AcceptVisitor(IAstVisitor visitor)
+		{
+			uint roleIndex = role.Index;
+			AstNode next;
+			for (AstNode cur = node.FirstChild; cur != null; cur = next) {
+				Debug.Assert(cur.Parent == node);
+				// Remember next before yielding cur.
+				// This allows removing/replacing nodes while iterating through the list.
+				next = cur.NextSibling;
+				if (cur.RoleIndex == roleIndex)
+					cur.AcceptVisitor(visitor);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/AstType.cs	(revision 11807)
@@ -0,0 +1,280 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// A type reference in the C# AST.
+	/// </summary>
+	public abstract class AstType : AstNode
+	{
+		#region Null
+		public new static readonly AstType Null = new NullAstType ();
+		
+		sealed class NullAstType : AstType
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+			
+			public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider)
+			{
+				return SpecialType.UnknownType;
+			}
+		}
+		#endregion
+		
+		#region PatternPlaceholder
+		public static implicit operator AstType(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : AstType, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder (this, child);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder (this, child);
+			}
+			
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder (this, child, data);
+			}
+			
+			public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider)
+			{
+				throw new NotSupportedException();
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public override NodeType NodeType {
+			get { return NodeType.TypeReference; }
+		}
+		
+		public new AstType Clone()
+		{
+			return (AstType)base.Clone();
+		}
+		
+		/// <summary>
+		/// Gets whether this type is a SimpleType "var".
+		/// </summary>
+		public bool IsVar()
+		{
+			SimpleType st = this as SimpleType;
+			return st != null && st.Identifier == "var" && st.TypeArguments.Count == 0;
+		}
+		
+		/// <summary>
+		/// Create an ITypeReference for this AstType.
+		/// Uses the context (ancestors of this node) to determine the correct <see cref="NameLookupMode"/>.
+		/// </summary>
+		/// <remarks>
+		/// The resulting type reference will read the context information from the
+		/// <see cref="ITypeResolveContext"/>:
+		/// For resolving type parameters, the CurrentTypeDefinition/CurrentMember is used.
+		/// For resolving simple names, the current namespace and usings from the CurrentUsingScope
+		/// (on CSharpTypeResolveContext only) is used.
+		/// </remarks>
+		public ITypeReference ToTypeReference(InterningProvider interningProvider = null)
+		{
+			return ToTypeReference(GetNameLookupMode(), interningProvider);
+		}
+		
+		/// <summary>
+		/// Create an ITypeReference for this AstType.
+		/// </summary>
+		/// <remarks>
+		/// The resulting type reference will read the context information from the
+		/// <see cref="ITypeResolveContext"/>:
+		/// For resolving type parameters, the CurrentTypeDefinition/CurrentMember is used.
+		/// For resolving simple names, the current namespace and usings from the CurrentUsingScope
+		/// (on CSharpTypeResolveContext only) is used.
+		/// </remarks>
+		public abstract ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null);
+		
+		/// <summary>
+		/// Gets the name lookup mode from the context (looking at the ancestors of this <see cref="AstType"/>).
+		/// </summary>
+		public NameLookupMode GetNameLookupMode()
+		{
+			AstType outermostType = this;
+			while (outermostType.Parent is AstType)
+				outermostType = (AstType)outermostType.Parent;
+			
+			if (outermostType.Parent is UsingDeclaration || outermostType.Parent is UsingAliasDeclaration) {
+				return NameLookupMode.TypeInUsingDeclaration;
+			} else if (outermostType.Role == Roles.BaseType) {
+				// Use BaseTypeReference for a type's base type, and for a constraint on a type.
+				// Do not use it for a constraint on a method.
+				if (outermostType.Parent is TypeDeclaration || (outermostType.Parent is Constraint && outermostType.Parent.Parent is TypeDeclaration))
+					return NameLookupMode.BaseTypeReference;
+			}
+			return NameLookupMode.Type;
+		}
+		
+		/// <summary>
+		/// Creates a pointer type from this type by nesting it in a <see cref="ComposedType"/>.
+		/// If this type already is a pointer type, this method just increases the PointerRank of the existing pointer type.
+		/// </summary>
+		public virtual AstType MakePointerType()
+		{
+			return new ComposedType { BaseType = this }.MakePointerType();
+		}
+		
+		/// <summary>
+		/// Creates an array type from this type by nesting it in a <see cref="ComposedType"/>.
+		/// If this type already is an array type, the additional rank is prepended to the existing array specifier list.
+		/// Thus, <c>new SimpleType("T").MakeArrayType(1).MakeArrayType(2)</c> will result in "T[,][]".
+		/// </summary>
+		public virtual AstType MakeArrayType(int rank = 1)
+		{
+			return new ComposedType { BaseType = this }.MakeArrayType(rank);
+		}
+		
+		/// <summary>
+		/// Creates a nullable type from this type by nesting it in a <see cref="ComposedType"/>.
+		/// </summary>
+		public AstType MakeNullableType()
+		{
+			return new ComposedType { BaseType = this, HasNullableSpecifier = true };
+		}
+		
+		/// <summary>
+		/// Builds an expression that can be used to access a static member on this type.
+		/// </summary>
+		public MemberReferenceExpression Member(string memberName)
+		{
+			return new TypeReferenceExpression { Type = this }.Member(memberName);
+		}
+		
+		/// <summary>
+		/// Builds an expression that can be used to access a static member on this type.
+		/// </summary>
+		public MemberType MemberType(string memberName, params AstType[] typeArguments)
+		{
+			var memberType = new MemberType(this, memberName);
+			memberType.TypeArguments.AddRange(typeArguments);
+			return memberType;
+		}
+		
+		/// <summary>
+		/// Builds an expression that can be used to access a static member on this type.
+		/// </summary>
+		public MemberType MemberType(string memberName, IEnumerable<AstType> typeArguments)
+		{
+			var memberType = new MemberType(this, memberName);
+			memberType.TypeArguments.AddRange(typeArguments);
+			return memberType;
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this type as target.
+		/// </summary>
+		public InvocationExpression Invoke(string methodName, IEnumerable<Expression> arguments)
+		{
+			return new TypeReferenceExpression { Type = this }.Invoke(methodName, arguments);
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this type as target.
+		/// </summary>
+		public InvocationExpression Invoke(string methodName, params Expression[] arguments)
+		{
+			return new TypeReferenceExpression { Type = this }.Invoke(methodName, arguments);
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this type as target.
+		/// </summary>
+		public InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			return new TypeReferenceExpression { Type = this }.Invoke(methodName, typeArguments, arguments);
+		}
+		
+		/// <summary>
+		/// Creates a simple AstType from a dotted name.
+		/// Does not support generics, arrays, etc. - just simple dotted names,
+		/// e.g. namespace names.
+		/// </summary>
+		public static AstType Create(string dottedName)
+		{
+			string[] parts = dottedName.Split('.');
+			AstType type = new SimpleType(parts[0]);
+			for (int i = 1; i < parts.Length; i++) {
+				type = new MemberType(type, parts[i]);
+			}
+			return type;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpModifierToken.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpModifierToken.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpModifierToken.cs	(revision 11807)
@@ -0,0 +1,218 @@
+﻿// 
+// CSharpModifierToken.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class CSharpModifierToken : CSharpTokenNode
+	{
+		Modifiers modifier;
+		
+		public Modifiers Modifier {
+			get { return modifier; }
+			set { 
+				ThrowIfFrozen();
+				this.modifier = value; 
+			}
+		}
+
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (StartLocation.Line, StartLocation.Column + GetModifierLength (Modifier));
+			}
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			return GetModifierName (Modifier);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CSharpModifierToken o = other as CSharpModifierToken;
+			return o != null && this.modifier == o.modifier;
+		}
+		
+		// Not worth using a dictionary for such few elements.
+		// This table is sorted in the order that modifiers should be output when generating code.
+		static readonly Modifiers[] allModifiers = {
+			Modifiers.Public, Modifiers.Protected, Modifiers.Private, Modifiers.Internal,
+			Modifiers.New,
+			Modifiers.Unsafe,
+			Modifiers.Abstract, Modifiers.Virtual, Modifiers.Sealed, Modifiers.Static, Modifiers.Override,
+			Modifiers.Readonly, Modifiers.Volatile,
+			Modifiers.Extern, Modifiers.Partial, Modifiers.Const,
+			Modifiers.Async,
+			Modifiers.Any
+		};
+		
+		public static IEnumerable<Modifiers> AllModifiers {
+			get { return allModifiers; }
+		}
+		
+		public CSharpModifierToken (TextLocation location, Modifiers modifier) : base (location, null)
+		{
+			this.Modifier = modifier;
+		}
+		
+		public static string GetModifierName(Modifiers modifier)
+		{
+			switch (modifier) {
+				case Modifiers.Private:
+					return "private";
+				case Modifiers.Internal:
+					return "internal";
+				case Modifiers.Protected:
+					return "protected";
+				case Modifiers.Public:
+					return "public";
+				case Modifiers.Abstract:
+					return "abstract";
+				case Modifiers.Virtual:
+					return "virtual";
+				case Modifiers.Sealed:
+					return "sealed";
+				case Modifiers.Static:
+					return "static";
+				case Modifiers.Override:
+					return "override";
+				case Modifiers.Readonly:
+					return "readonly";
+				case Modifiers.Const:
+					return "const";
+				case Modifiers.New:
+					return "new";
+				case Modifiers.Partial:
+					return "partial";
+				case Modifiers.Extern:
+					return "extern";
+				case Modifiers.Volatile:
+					return "volatile";
+				case Modifiers.Unsafe:
+					return "unsafe";
+				case Modifiers.Async:
+					return "async";
+				case Modifiers.Any:
+					// even though it's used for pattern matching only, 'any' needs to be in this list to be usable in the AST
+					return "any";
+				default:
+					throw new NotSupportedException("Invalid value for Modifiers");
+			}
+		}
+
+		public static int GetModifierLength(Modifiers modifier)
+		{
+			switch (modifier) {
+				case Modifiers.Private:
+					return "private".Length;
+				case Modifiers.Internal:
+					return "internal".Length;
+				case Modifiers.Protected:
+					return "protected".Length;
+				case Modifiers.Public:
+					return "public".Length;
+				case Modifiers.Abstract:
+					return "abstract".Length;
+				case Modifiers.Virtual:
+					return "virtual".Length;
+				case Modifiers.Sealed:
+					return "sealed".Length;
+				case Modifiers.Static:
+					return "static".Length;
+				case Modifiers.Override:
+					return "override".Length;
+				case Modifiers.Readonly:
+					return "readonly".Length;
+				case Modifiers.Const:
+					return "const".Length;
+				case Modifiers.New:
+					return "new".Length;
+				case Modifiers.Partial:
+					return "partial".Length;
+				case Modifiers.Extern:
+					return "extern".Length;
+				case Modifiers.Volatile:
+					return "volatile".Length;
+				case Modifiers.Unsafe:
+					return "unsafe".Length;
+				case Modifiers.Async:
+					return "async".Length;
+				case Modifiers.Any:
+					// even though it's used for pattern matching only, 'any' needs to be in this list to be usable in the AST
+					return "any".Length;
+				default:
+					throw new NotSupportedException("Invalid value for Modifiers");
+			}
+		}
+		
+		public static Modifiers GetModifierValue(string modifier)
+		{
+			switch (modifier) {
+				case "private":
+					return Modifiers.Private;
+				case "internal":
+					return Modifiers.Internal;
+				case "protected":
+					return Modifiers.Protected;
+				case "public":
+					return Modifiers.Public;
+				case "abstract":
+					return Modifiers.Abstract;
+				case "virtual":
+					return Modifiers.Virtual;
+				case "sealed":
+					return Modifiers.Sealed;
+				case "static":
+					return Modifiers.Static;
+				case "override":
+					return Modifiers.Override;
+				case "readonly":
+					return Modifiers.Readonly;
+				case "const":
+					return Modifiers.Const;
+				case "new":
+					return Modifiers.New;
+				case "partial":
+					return Modifiers.Partial;
+				case "extern":
+					return Modifiers.Extern;
+				case "volatile":
+					return Modifiers.Volatile;
+				case "unsafe":
+					return Modifiers.Unsafe;
+				case "async":
+					return Modifiers.Async;
+				case "any":
+					// even though it's used for pattern matching only, 'any' needs to be in this list to be usable in the AST
+					return Modifiers.Any;
+				default:
+					throw new NotSupportedException("Invalid value for Modifiers");
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpTokenNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpTokenNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpTokenNode.cs	(revision 11807)
@@ -0,0 +1,131 @@
+﻿// 
+// TokenNode.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents a token in C#. Note that the type of the token is defined through the TokenRole.
+	/// </summary>
+	/// <remarks>
+	/// In all non null c# token nodes the Role of a CSharpToken must be a TokenRole.
+	/// </remarks>
+	public class CSharpTokenNode : AstNode
+	{
+		public static new readonly CSharpTokenNode Null = new NullCSharpTokenNode ();
+		class NullCSharpTokenNode : CSharpTokenNode
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public NullCSharpTokenNode () : base (TextLocation.Empty, null)
+			{
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Token;
+			}
+		}
+		
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get {
+				return startLocation;
+			}
+		}
+
+		int TokenLength {
+			get {
+				return TokenRole.TokenLengths [(int)(this.flags >> AstNodeFlagsUsedBits)];
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (StartLocation.Line, StartLocation.Column + TokenLength);
+			}
+		}
+
+		public CSharpTokenNode (TextLocation location, TokenRole role)
+		{
+			this.startLocation = location;
+			if (role != null)
+				this.flags |= role.TokenIndex << AstNodeFlagsUsedBits;
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			return TokenRole.Tokens [(int)(this.flags >> AstNodeFlagsUsedBits)];
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCSharpTokenNode (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCSharpTokenNode (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCSharpTokenNode (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CSharpTokenNode o = other as CSharpTokenNode;
+			return o != null && !o.IsNull && !(o is CSharpModifierToken);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpUtil.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpUtil.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/CSharpUtil.cs	(revision 11807)
@@ -0,0 +1,180 @@
+// 
+// CSharpUtil.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.PatternMatching;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public static class CSharpUtil
+	{
+		/// <summary>
+		/// Inverts a boolean condition. Note: The condition object can be frozen (from AST) it's cloned internally.
+		/// </summary>
+		/// <param name="condition">The condition to invert.</param>
+		public static Expression InvertCondition(Expression condition)
+		{
+			return InvertConditionInternal(condition);
+		}
+		
+		static Expression InvertConditionInternal(Expression condition)
+		{
+			if (condition is ParenthesizedExpression) {
+				return new ParenthesizedExpression(InvertCondition(((ParenthesizedExpression)condition).Expression));
+			}
+			
+			if (condition is UnaryOperatorExpression) {
+				var uOp = (UnaryOperatorExpression)condition;
+				if (uOp.Operator == UnaryOperatorType.Not) {
+					if (!(uOp.Parent is Expression))
+						return GetInnerMostExpression(uOp.Expression).Clone();
+					return uOp.Expression.Clone();
+				}
+				return new UnaryOperatorExpression(UnaryOperatorType.Not, uOp.Clone());
+			}
+			
+			if (condition is BinaryOperatorExpression) {
+				var bOp = (BinaryOperatorExpression)condition;
+
+				if ((bOp.Operator == BinaryOperatorType.ConditionalAnd) || (bOp.Operator == BinaryOperatorType.ConditionalOr)) {
+					return new BinaryOperatorExpression(InvertCondition(bOp.Left), NegateConditionOperator(bOp.Operator), InvertCondition(bOp.Right));
+				} else if ((bOp.Operator == BinaryOperatorType.Equality) || (bOp.Operator == BinaryOperatorType.InEquality) || (bOp.Operator == BinaryOperatorType.GreaterThan)
+					|| (bOp.Operator == BinaryOperatorType.GreaterThanOrEqual) || (bOp.Operator == BinaryOperatorType.LessThan) || 
+					(bOp.Operator == BinaryOperatorType.LessThanOrEqual)) {
+					return new BinaryOperatorExpression(bOp.Left.Clone(), NegateRelationalOperator(bOp.Operator), bOp.Right.Clone());
+				} else {
+					var negatedOp = NegateRelationalOperator(bOp.Operator);
+					if (negatedOp == BinaryOperatorType.Any)
+						return new UnaryOperatorExpression(UnaryOperatorType.Not, new ParenthesizedExpression(condition.Clone()));
+					bOp = (BinaryOperatorExpression)bOp.Clone();
+					bOp.Operator = negatedOp;
+					return bOp;
+				}
+			}
+			if (condition is ConditionalExpression) {
+				var cEx = condition.Clone() as ConditionalExpression;
+				cEx.Condition = InvertCondition(cEx.Condition);
+				return cEx;
+			}
+			if (condition is PrimitiveExpression) {
+				var pex = condition as PrimitiveExpression;
+				if (pex.Value is bool) {
+					return new PrimitiveExpression(!((bool)pex.Value)); 
+				}
+			}
+			
+			return new UnaryOperatorExpression(UnaryOperatorType.Not, AddParensForUnaryExpressionIfRequired(condition.Clone()));
+		}
+
+		/// <summary>
+		/// When negating an expression this is required, otherwise you would end up with
+		/// a or b -> !a or b
+		/// </summary>
+		internal static Expression AddParensForUnaryExpressionIfRequired(Expression expression)
+		{
+			if ((expression is BinaryOperatorExpression) ||
+			    (expression is AssignmentExpression) ||
+			    (expression is CastExpression) ||
+			    (expression is AsExpression) ||
+			    (expression is IsExpression) ||
+			    (expression is LambdaExpression) ||
+			    (expression is ConditionalExpression)) {
+				return new ParenthesizedExpression(expression);
+			}
+
+			return expression;
+		}
+
+		/// <summary>
+		/// Get negation of the specified relational operator
+		/// </summary>
+		/// <returns>
+		/// negation of the specified relational operator, or BinaryOperatorType.Any if it's not a relational operator
+		/// </returns>
+		public static BinaryOperatorType NegateRelationalOperator(BinaryOperatorType op)
+		{
+			switch (op) {
+				case BinaryOperatorType.GreaterThan:
+					return BinaryOperatorType.LessThanOrEqual;
+				case BinaryOperatorType.GreaterThanOrEqual:
+					return BinaryOperatorType.LessThan;
+				case BinaryOperatorType.Equality:
+					return BinaryOperatorType.InEquality;
+				case BinaryOperatorType.InEquality:
+					return BinaryOperatorType.Equality;
+				case BinaryOperatorType.LessThan:
+					return BinaryOperatorType.GreaterThanOrEqual;
+				case BinaryOperatorType.LessThanOrEqual:
+					return BinaryOperatorType.GreaterThan;
+				case BinaryOperatorType.ConditionalOr:
+					return BinaryOperatorType.ConditionalAnd;
+				case BinaryOperatorType.ConditionalAnd:
+					return BinaryOperatorType.ConditionalOr;
+			}
+			return BinaryOperatorType.Any;
+		}
+
+		/// <summary>
+		/// Returns true, if the specified operator is a relational operator
+		/// </summary>
+		public static bool IsRelationalOperator(BinaryOperatorType op)
+		{
+			return NegateRelationalOperator(op) != BinaryOperatorType.Any;
+		}
+
+		/// <summary>
+		/// Get negation of the condition operator
+		/// </summary>
+		/// <returns>
+		/// negation of the specified condition operator, or BinaryOperatorType.Any if it's not a condition operator
+		/// </returns>
+		public static BinaryOperatorType NegateConditionOperator(BinaryOperatorType op)
+		{
+			switch (op) {
+				case BinaryOperatorType.ConditionalOr:
+					return BinaryOperatorType.ConditionalAnd;
+				case BinaryOperatorType.ConditionalAnd:
+					return BinaryOperatorType.ConditionalOr;
+			}
+			return BinaryOperatorType.Any;
+		}
+
+		public static bool AreConditionsEqual(Expression cond1, Expression cond2)
+		{
+			if (cond1 == null || cond2 == null)
+				return false;
+			return GetInnerMostExpression(cond1).IsMatch(GetInnerMostExpression(cond2));
+		}
+
+		public static Expression GetInnerMostExpression(Expression target)
+		{
+			while (target is ParenthesizedExpression)
+				target = ((ParenthesizedExpression)target).Expression;
+			return target;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ComposedType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ComposedType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ComposedType.cs	(revision 11807)
@@ -0,0 +1,230 @@
+﻿// 
+// ComposedType.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class ComposedType : AstType
+	{
+		public static readonly TokenRole NullableRole = new TokenRole("?");
+		public static readonly TokenRole PointerRole = new TokenRole("*");
+		public static readonly Role<ArraySpecifier> ArraySpecifierRole = new Role<ArraySpecifier>("ArraySpecifier");
+		
+		public AstType BaseType {
+			get { return GetChildByRole(Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public bool HasNullableSpecifier {
+			get {
+				return !GetChildByRole(NullableRole).IsNull;
+			}
+			set {
+				SetChildByRole(NullableRole, value ? new CSharpTokenNode(TextLocation.Empty, null) : null);
+			}
+		}
+
+		public CSharpTokenNode NullableSpecifierToken {
+			get {
+				return GetChildByRole(NullableRole);
+			}
+		}
+		
+		public int PointerRank {
+			get {
+				return GetChildrenByRole(PointerRole).Count;
+			}
+			set {
+				if (value < 0)
+					throw new ArgumentOutOfRangeException();
+				int d = this.PointerRank;
+				while (d > value) {
+					GetChildByRole(PointerRole).Remove();
+					d--;
+				}
+				while (d < value) {
+					InsertChildBefore(GetChildByRole(PointerRole), new CSharpTokenNode(TextLocation.Empty, PointerRole), PointerRole);
+					d++;
+				}
+			}
+		}
+		
+		public AstNodeCollection<ArraySpecifier> ArraySpecifiers {
+			get { return GetChildrenByRole (ArraySpecifierRole); }
+		}
+
+		public AstNodeCollection<CSharpTokenNode> PointerTokens {
+			get { return GetChildrenByRole (PointerRole); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitComposedType (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitComposedType (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitComposedType (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ComposedType o = other as ComposedType;
+			return o != null && this.HasNullableSpecifier == o.HasNullableSpecifier && this.PointerRank == o.PointerRank
+				&& this.BaseType.DoMatch(o.BaseType, match)
+				&& this.ArraySpecifiers.DoMatch(o.ArraySpecifiers, match);
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			StringBuilder b = new StringBuilder();
+			b.Append(this.BaseType.ToString());
+			if (this.HasNullableSpecifier)
+				b.Append('?');
+			b.Append('*', this.PointerRank);
+			foreach (var arraySpecifier in this.ArraySpecifiers) {
+				b.Append('[');
+				b.Append(',', arraySpecifier.Dimensions - 1);
+				b.Append(']');
+			}
+			return b.ToString();
+		}
+		
+		public override AstType MakePointerType()
+		{
+			if (ArraySpecifiers.Any()) {
+				return base.MakePointerType();
+			} else {
+				this.PointerRank++;
+				return this;
+			}
+		}
+		
+		public override AstType MakeArrayType(int dimensions)
+		{
+			InsertChildBefore(this.ArraySpecifiers.FirstOrDefault(), new ArraySpecifier(dimensions), ArraySpecifierRole);
+			return this;
+		}
+		
+		public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null)
+		{
+			if (interningProvider == null)
+				interningProvider = InterningProvider.Dummy;
+			ITypeReference t = this.BaseType.ToTypeReference(lookupMode, interningProvider);
+			if (this.HasNullableSpecifier) {
+				t = interningProvider.Intern(NullableType.Create(t));
+			}
+			int pointerRank = this.PointerRank;
+			for (int i = 0; i < pointerRank; i++) {
+				t = interningProvider.Intern(new PointerTypeReference(t));
+			}
+			foreach (var a in this.ArraySpecifiers.Reverse()) {
+				t = interningProvider.Intern(new ArrayTypeReference(t, a.Dimensions));
+			}
+			return t;
+		}
+	}
+	
+	/// <summary>
+	/// [,,,]
+	/// </summary>
+	public class ArraySpecifier : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public ArraySpecifier()
+		{
+		}
+		
+		public ArraySpecifier(int dimensions)
+		{
+			this.Dimensions = dimensions;
+		}
+		
+		public CSharpTokenNode LBracketToken {
+			get { return GetChildByRole (Roles.LBracket); }
+		}
+		
+		public int Dimensions {
+			get { return 1 + GetChildrenByRole(Roles.Comma).Count; }
+			set {
+				int d = this.Dimensions;
+				while (d > value) {
+					GetChildByRole(Roles.Comma).Remove();
+					d--;
+				}
+				while (d < value) {
+					InsertChildBefore(GetChildByRole(Roles.Comma), new CSharpTokenNode(TextLocation.Empty, Roles.Comma), Roles.Comma);
+					d++;
+				}
+			}
+		}
+		
+		public CSharpTokenNode RBracketToken {
+			get { return GetChildByRole (Roles.RBracket); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitArraySpecifier (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitArraySpecifier (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitArraySpecifier(this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ArraySpecifier o = other as ArraySpecifier;
+			return o != null && this.Dimensions == o.Dimensions;
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			return "[" + new string(',', this.Dimensions - 1) + "]";
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/DepthFirstAstVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/DepthFirstAstVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/DepthFirstAstVisitor.cs	(revision 11807)
@@ -0,0 +1,1849 @@
+﻿// 
+// IAstVisitor.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// AST visitor with a default implementation that visits all node depth-first.
+	/// </summary>
+	public abstract class DepthFirstAstVisitor : IAstVisitor
+	{
+		protected virtual void VisitChildren (AstNode node)
+		{
+			AstNode next;
+			for (var child = node.FirstChild; child != null; child = next) {
+				// Store next to allow the loop to continue
+				// if the visitor removes/replaces child.
+				next = child.NextSibling;
+				child.AcceptVisitor (this);
+			}
+		}
+		
+		public virtual void VisitNullNode(AstNode nullNode)
+		{
+			// Should we call VisitChildren here?
+			// We usually want to ignore null nodes.
+			// Older NR versions (before VisitNullNode was introduced) didn't call VisitChildren() with null nodes;
+			// so changing this might break VisitChildren() overrides that expect the node to be part of the AST.
+		}
+		
+		public virtual void VisitSyntaxTree (SyntaxTree syntaxTree)
+		{
+			VisitChildren (syntaxTree);
+		}
+		
+		public virtual void VisitComment(Comment comment)
+		{
+			VisitChildren(comment);
+		}
+
+		public virtual void VisitNewLine(NewLineNode newLineNode)
+		{
+			VisitChildren(newLineNode);
+		}
+
+		public virtual void VisitWhitespace(WhitespaceNode whitespaceNode)
+		{
+			VisitChildren(whitespaceNode);
+		}
+
+		public virtual void VisitText(TextNode textNode)
+		{
+			VisitChildren(textNode);
+		}
+
+		public virtual void VisitDocumentationReference (DocumentationReference documentationReference)
+		{
+			VisitChildren (documentationReference);
+		}
+		
+		public virtual void VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective)
+		{
+			VisitChildren (preProcessorDirective);
+		}
+
+		public virtual void VisitIdentifier (Identifier identifier)
+		{
+			VisitChildren (identifier);
+		}
+		
+		public virtual void VisitCSharpTokenNode (CSharpTokenNode token)
+		{
+			VisitChildren (token);
+		}
+		
+		public virtual void VisitPrimitiveType (PrimitiveType primitiveType)
+		{
+			VisitChildren (primitiveType);
+		}
+		
+		public virtual void VisitComposedType (ComposedType composedType)
+		{
+			VisitChildren (composedType);
+		}
+		
+		public virtual void VisitSimpleType(SimpleType simpleType)
+		{
+			VisitChildren (simpleType);
+		}
+		
+		public virtual void VisitMemberType(MemberType memberType)
+		{
+			VisitChildren (memberType);
+		}
+		
+		public virtual void VisitAttribute (Attribute attribute)
+		{
+			VisitChildren (attribute);
+		}
+		
+		public virtual void VisitAttributeSection (AttributeSection attributeSection)
+		{
+			VisitChildren (attributeSection);
+		}
+		
+		public virtual void VisitDelegateDeclaration (DelegateDeclaration delegateDeclaration)
+		{
+			VisitChildren (delegateDeclaration);
+		}
+		
+		public virtual void VisitNamespaceDeclaration (NamespaceDeclaration namespaceDeclaration)
+		{
+			VisitChildren (namespaceDeclaration);
+		}
+		
+		public virtual void VisitTypeDeclaration (TypeDeclaration typeDeclaration)
+		{
+			VisitChildren (typeDeclaration);
+		}
+		
+		public virtual void VisitTypeParameterDeclaration (TypeParameterDeclaration typeParameterDeclaration)
+		{
+			VisitChildren (typeParameterDeclaration);
+		}
+		
+		public virtual void VisitEnumMemberDeclaration (EnumMemberDeclaration enumMemberDeclaration)
+		{
+			VisitChildren (enumMemberDeclaration);
+		}
+		
+		public virtual void VisitUsingDeclaration (UsingDeclaration usingDeclaration)
+		{
+			VisitChildren (usingDeclaration);
+		}
+		
+		public virtual void VisitUsingAliasDeclaration (UsingAliasDeclaration usingDeclaration)
+		{
+			VisitChildren (usingDeclaration);
+		}
+		
+		public virtual void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			VisitChildren (externAliasDeclaration);
+		}
+		
+		public virtual void VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration)
+		{
+			VisitChildren (constructorDeclaration);
+		}
+		
+		public virtual void VisitConstructorInitializer (ConstructorInitializer constructorInitializer)
+		{
+			VisitChildren (constructorInitializer);
+		}
+		
+		public virtual void VisitDestructorDeclaration (DestructorDeclaration destructorDeclaration)
+		{
+			VisitChildren (destructorDeclaration);
+		}
+		
+		public virtual void VisitEventDeclaration (EventDeclaration eventDeclaration)
+		{
+			VisitChildren (eventDeclaration);
+		}
+		
+		public virtual void VisitCustomEventDeclaration (CustomEventDeclaration eventDeclaration)
+		{
+			VisitChildren (eventDeclaration);
+		}
+		
+		public virtual void VisitFieldDeclaration (FieldDeclaration fieldDeclaration)
+		{
+			VisitChildren (fieldDeclaration);
+		}
+		
+		public virtual void VisitFixedFieldDeclaration (FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			VisitChildren (fixedFieldDeclaration);
+		}
+		
+		public virtual void VisitFixedVariableInitializer (FixedVariableInitializer fixedVariableInitializer)
+		{
+			VisitChildren (fixedVariableInitializer);
+		}
+		
+		public virtual void VisitIndexerDeclaration (IndexerDeclaration indexerDeclaration)
+		{
+			VisitChildren (indexerDeclaration);
+		}
+		
+		public virtual void VisitMethodDeclaration (MethodDeclaration methodDeclaration)
+		{
+			VisitChildren (methodDeclaration);
+		}
+		
+		public virtual void VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration)
+		{
+			VisitChildren (operatorDeclaration);
+		}
+		
+		public virtual void VisitPropertyDeclaration (PropertyDeclaration propertyDeclaration)
+		{
+			VisitChildren (propertyDeclaration);
+		}
+		
+		public virtual void VisitAccessor (Accessor accessor)
+		{
+			VisitChildren (accessor);
+		}
+		
+		public virtual void VisitVariableInitializer (VariableInitializer variableInitializer)
+		{
+			VisitChildren (variableInitializer);
+		}
+		
+		public virtual void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration)
+		{
+			VisitChildren (parameterDeclaration);
+		}
+		
+		public virtual void VisitConstraint (Constraint constraint)
+		{
+			VisitChildren (constraint);
+		}
+		
+		public virtual void VisitBlockStatement (BlockStatement blockStatement)
+		{
+			VisitChildren (blockStatement);
+		}
+		
+		public virtual void VisitExpressionStatement (ExpressionStatement expressionStatement)
+		{
+			VisitChildren (expressionStatement);
+		}
+		
+		public virtual void VisitBreakStatement (BreakStatement breakStatement)
+		{
+			VisitChildren (breakStatement);
+		}
+		
+		public virtual void VisitCheckedStatement (CheckedStatement checkedStatement)
+		{
+			VisitChildren (checkedStatement);
+		}
+		
+		public virtual void VisitContinueStatement (ContinueStatement continueStatement)
+		{
+			VisitChildren (continueStatement);
+		}
+		
+		public virtual void VisitDoWhileStatement (DoWhileStatement doWhileStatement)
+		{
+			VisitChildren (doWhileStatement);
+		}
+		
+		public virtual void VisitEmptyStatement (EmptyStatement emptyStatement)
+		{
+			VisitChildren (emptyStatement);
+		}
+		
+		public virtual void VisitFixedStatement (FixedStatement fixedStatement)
+		{
+			VisitChildren (fixedStatement);
+		}
+		
+		public virtual void VisitForeachStatement (ForeachStatement foreachStatement)
+		{
+			VisitChildren (foreachStatement);
+		}
+		
+		public virtual void VisitForStatement (ForStatement forStatement)
+		{
+			VisitChildren (forStatement);
+		}
+		
+		public virtual void VisitGotoCaseStatement (GotoCaseStatement gotoCaseStatement)
+		{
+			VisitChildren (gotoCaseStatement);
+		}
+		
+		public virtual void VisitGotoDefaultStatement (GotoDefaultStatement gotoDefaultStatement)
+		{
+			VisitChildren (gotoDefaultStatement);
+		}
+		
+		public virtual void VisitGotoStatement (GotoStatement gotoStatement)
+		{
+			VisitChildren (gotoStatement);
+		}
+		
+		public virtual void VisitIfElseStatement (IfElseStatement ifElseStatement)
+		{
+			VisitChildren (ifElseStatement);
+		}
+		
+		public virtual void VisitLabelStatement (LabelStatement labelStatement)
+		{
+			VisitChildren (labelStatement);
+		}
+		
+		public virtual void VisitLockStatement (LockStatement lockStatement)
+		{
+			VisitChildren (lockStatement);
+		}
+		
+		public virtual void VisitReturnStatement (ReturnStatement returnStatement)
+		{
+			VisitChildren (returnStatement);
+		}
+		
+		public virtual void VisitSwitchStatement (SwitchStatement switchStatement)
+		{
+			VisitChildren (switchStatement);
+		}
+		
+		public virtual void VisitSwitchSection (SwitchSection switchSection)
+		{
+			VisitChildren (switchSection);
+		}
+		
+		public virtual void VisitCaseLabel (CaseLabel caseLabel)
+		{
+			VisitChildren (caseLabel);
+		}
+		
+		public virtual void VisitThrowStatement (ThrowStatement throwStatement)
+		{
+			VisitChildren (throwStatement);
+		}
+		
+		public virtual void VisitTryCatchStatement (TryCatchStatement tryCatchStatement)
+		{
+			VisitChildren (tryCatchStatement);
+		}
+		
+		public virtual void VisitCatchClause (CatchClause catchClause)
+		{
+			VisitChildren (catchClause);
+		}
+		
+		public virtual void VisitUncheckedStatement (UncheckedStatement uncheckedStatement)
+		{
+			VisitChildren (uncheckedStatement);
+		}
+		
+		public virtual void VisitUnsafeStatement (UnsafeStatement unsafeStatement)
+		{
+			VisitChildren (unsafeStatement);
+		}
+		
+		public virtual void VisitUsingStatement (UsingStatement usingStatement)
+		{
+			VisitChildren (usingStatement);
+		}
+		
+		public virtual void VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement)
+		{
+			VisitChildren (variableDeclarationStatement);
+		}
+		
+		public virtual void VisitWhileStatement (WhileStatement whileStatement)
+		{
+			VisitChildren (whileStatement);
+		}
+		
+		public virtual void VisitYieldBreakStatement (YieldBreakStatement yieldBreakStatement)
+		{
+			VisitChildren (yieldBreakStatement);
+		}
+		
+		public virtual void VisitYieldReturnStatement (YieldReturnStatement yieldReturnStatement)
+		{
+			VisitChildren (yieldReturnStatement);
+		}
+		
+		public virtual void VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression)
+		{
+			VisitChildren (anonymousMethodExpression);
+		}
+		
+		public virtual void VisitLambdaExpression (LambdaExpression lambdaExpression)
+		{
+			VisitChildren (lambdaExpression);
+		}
+		
+		public virtual void VisitAssignmentExpression (AssignmentExpression assignmentExpression)
+		{
+			VisitChildren (assignmentExpression);
+		}
+		
+		public virtual void VisitBaseReferenceExpression (BaseReferenceExpression baseReferenceExpression)
+		{
+			VisitChildren (baseReferenceExpression);
+		}
+		
+		public virtual void VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression)
+		{
+			VisitChildren (binaryOperatorExpression);
+		}
+		
+		public virtual void VisitCastExpression (CastExpression castExpression)
+		{
+			VisitChildren (castExpression);
+		}
+		
+		public virtual void VisitCheckedExpression (CheckedExpression checkedExpression)
+		{
+			VisitChildren (checkedExpression);
+		}
+		
+		public virtual void VisitConditionalExpression (ConditionalExpression conditionalExpression)
+		{
+			VisitChildren (conditionalExpression);
+		}
+		
+		public virtual void VisitIdentifierExpression (IdentifierExpression identifierExpression)
+		{
+			VisitChildren (identifierExpression);
+		}
+		
+		public virtual void VisitIndexerExpression (IndexerExpression indexerExpression)
+		{
+			VisitChildren (indexerExpression);
+		}
+		
+		public virtual void VisitInvocationExpression (InvocationExpression invocationExpression)
+		{
+			VisitChildren (invocationExpression);
+		}
+		
+		public virtual void VisitDirectionExpression (DirectionExpression directionExpression)
+		{
+			VisitChildren (directionExpression);
+		}
+		
+		public virtual void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression)
+		{
+			VisitChildren (memberReferenceExpression);
+		}
+		
+		public virtual void VisitNullReferenceExpression (NullReferenceExpression nullReferenceExpression)
+		{
+			VisitChildren (nullReferenceExpression);
+		}
+		
+		public virtual void VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression)
+		{
+			VisitChildren (objectCreateExpression);
+		}
+		
+		public virtual void VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+		{
+			VisitChildren (anonymousTypeCreateExpression);
+		}
+		
+		public virtual void VisitArrayCreateExpression (ArrayCreateExpression arrayCreateExpression)
+		{
+			VisitChildren (arrayCreateExpression);
+		}
+		
+		public virtual void VisitParenthesizedExpression (ParenthesizedExpression parenthesizedExpression)
+		{
+			VisitChildren (parenthesizedExpression);
+		}
+		
+		public virtual void VisitPointerReferenceExpression (PointerReferenceExpression pointerReferenceExpression)
+		{
+			VisitChildren (pointerReferenceExpression);
+		}
+		
+		public virtual void VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+		{
+			VisitChildren (primitiveExpression);
+		}
+		
+		public virtual void VisitSizeOfExpression (SizeOfExpression sizeOfExpression)
+		{
+			VisitChildren (sizeOfExpression);
+		}
+		
+		public virtual void VisitStackAllocExpression (StackAllocExpression stackAllocExpression)
+		{
+			VisitChildren (stackAllocExpression);
+		}
+		
+		public virtual void VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
+		{
+			VisitChildren (thisReferenceExpression);
+		}
+		
+		public virtual void VisitTypeOfExpression (TypeOfExpression typeOfExpression)
+		{
+			VisitChildren (typeOfExpression);
+		}
+		
+		public virtual void VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
+		{
+			VisitChildren (typeReferenceExpression);
+		}
+		
+		public virtual void VisitUnaryOperatorExpression (UnaryOperatorExpression unaryOperatorExpression)
+		{
+			VisitChildren (unaryOperatorExpression);
+		}
+		
+		public virtual void VisitUncheckedExpression (UncheckedExpression uncheckedExpression)
+		{
+			VisitChildren (uncheckedExpression);
+		}
+		
+		public virtual void VisitQueryExpression(QueryExpression queryExpression)
+		{
+			VisitChildren (queryExpression);
+		}
+		
+		public virtual void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			VisitChildren (queryContinuationClause);
+		}
+		
+		public virtual void VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			VisitChildren (queryFromClause);
+		}
+		
+		public virtual void VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			VisitChildren (queryLetClause);
+		}
+		
+		public virtual void VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			VisitChildren (queryWhereClause);
+		}
+		
+		public virtual void VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			VisitChildren (queryJoinClause);
+		}
+		
+		public virtual void VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			VisitChildren (queryOrderClause);
+		}
+		
+		public virtual void VisitQueryOrdering(QueryOrdering queryOrdering)
+		{
+			VisitChildren (queryOrdering);
+		}
+		
+		public virtual void VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			VisitChildren (querySelectClause);
+		}
+		
+		public virtual void VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			VisitChildren (queryGroupClause);
+		}
+		
+		public virtual void VisitAsExpression (AsExpression asExpression)
+		{
+			VisitChildren (asExpression);
+		}
+		
+		public virtual void VisitIsExpression (IsExpression isExpression)
+		{
+			VisitChildren (isExpression);
+		}
+		
+		public virtual void VisitDefaultValueExpression (DefaultValueExpression defaultValueExpression)
+		{
+			VisitChildren (defaultValueExpression);
+		}
+		
+		public virtual void VisitUndocumentedExpression (UndocumentedExpression undocumentedExpression)
+		{
+			VisitChildren (undocumentedExpression);
+		}
+		
+		public virtual void VisitArrayInitializerExpression (ArrayInitializerExpression arrayInitializerExpression)
+		{
+			VisitChildren (arrayInitializerExpression);
+		}
+		
+		public virtual void VisitArraySpecifier (ArraySpecifier arraySpecifier)
+		{
+			VisitChildren (arraySpecifier);
+		}
+		
+		public virtual void VisitNamedArgumentExpression (NamedArgumentExpression namedArgumentExpression)
+		{
+			VisitChildren (namedArgumentExpression);
+		}
+		
+		public virtual void VisitNamedExpression (NamedExpression namedExpression)
+		{
+			VisitChildren (namedExpression);
+		}
+
+		public virtual void VisitErrorNode(AstNode errorNode)
+		{
+			VisitChildren(errorNode);
+		}
+
+		public virtual void VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern)
+		{
+			VisitChildren (placeholder);
+		}
+	}
+	
+	/// <summary>
+	/// AST visitor with a default implementation that visits all node depth-first.
+	/// </summary>
+	public abstract class DepthFirstAstVisitor<T> : IAstVisitor<T>
+	{
+		protected virtual T VisitChildren (AstNode node)
+		{
+			AstNode next;
+			for (var child = node.FirstChild; child != null; child = next) {
+				// Store next to allow the loop to continue
+				// if the visitor removes/replaces child.
+				next = child.NextSibling;
+				child.AcceptVisitor (this);
+			}
+			return default (T);
+		}
+		
+		public virtual T VisitNullNode(AstNode nullNode)
+		{
+			// Should we call VisitChildren here?
+			// We usually want to ignore null nodes.
+			// Older NR versions (before VisitNullNode was introduced) didn't call VisitChildren() with null nodes;
+			// so changing this might break VisitChildren() overrides that expect the node to be part of the AST.
+			return default (T);
+		}
+		
+		public virtual T VisitSyntaxTree (SyntaxTree unit)
+		{
+			return VisitChildren (unit);
+		}
+		
+		public virtual T VisitComment (Comment comment)
+		{
+			return VisitChildren (comment);
+		}
+		
+		public virtual T VisitNewLine(NewLineNode newLineNode)
+		{
+			return VisitChildren(newLineNode);
+		}
+		
+		public virtual T VisitWhitespace(WhitespaceNode whitespaceNode)
+		{
+			return VisitChildren(whitespaceNode);
+		}
+
+		public virtual T VisitText(TextNode textNode)
+		{
+			return VisitChildren(textNode);
+		}
+
+		public virtual T VisitDocumentationReference (DocumentationReference documentationReference)
+		{
+			return VisitChildren (documentationReference);
+		}
+		
+		public virtual T VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective)
+		{
+			return VisitChildren (preProcessorDirective);
+		}
+
+		public virtual T VisitIdentifier (Identifier identifier)
+		{
+			return VisitChildren (identifier);
+		}
+		
+		public virtual T VisitCSharpTokenNode (CSharpTokenNode token)
+		{
+			return VisitChildren (token);
+		}
+		
+		public virtual T VisitPrimitiveType (PrimitiveType primitiveType)
+		{
+			return VisitChildren (primitiveType);
+		}
+		
+		public virtual T VisitComposedType (ComposedType composedType)
+		{
+			return VisitChildren (composedType);
+		}
+		
+		public virtual T VisitSimpleType(SimpleType simpleType)
+		{
+			return VisitChildren (simpleType);
+		}
+		
+		public virtual T VisitMemberType(MemberType memberType)
+		{
+			return VisitChildren (memberType);
+		}
+		
+		public virtual T VisitAttribute (Attribute attribute)
+		{
+			return VisitChildren (attribute);
+		}
+		
+		public virtual T VisitAttributeSection (AttributeSection attributeSection)
+		{
+			return VisitChildren (attributeSection);
+		}
+		
+		public virtual T VisitDelegateDeclaration (DelegateDeclaration delegateDeclaration)
+		{
+			return VisitChildren (delegateDeclaration);
+		}
+		
+		public virtual T VisitNamespaceDeclaration (NamespaceDeclaration namespaceDeclaration)
+		{
+			return VisitChildren (namespaceDeclaration);
+		}
+		
+		public virtual T VisitTypeDeclaration (TypeDeclaration typeDeclaration)
+		{
+			return VisitChildren (typeDeclaration);
+		}
+		
+		public virtual T VisitTypeParameterDeclaration (TypeParameterDeclaration typeParameterDeclaration)
+		{
+			return VisitChildren (typeParameterDeclaration);
+		}
+		
+		public virtual T VisitEnumMemberDeclaration (EnumMemberDeclaration enumMemberDeclaration)
+		{
+			return VisitChildren (enumMemberDeclaration);
+		}
+		
+		public virtual T VisitUsingDeclaration (UsingDeclaration usingDeclaration)
+		{
+			return VisitChildren (usingDeclaration);
+		}
+		
+		public virtual T VisitUsingAliasDeclaration (UsingAliasDeclaration usingDeclaration)
+		{
+			return VisitChildren (usingDeclaration);
+		}
+		
+		public virtual T VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			return VisitChildren (externAliasDeclaration);
+		}
+		
+		public virtual T VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration)
+		{
+			return VisitChildren (constructorDeclaration);
+		}
+		
+		public virtual T VisitConstructorInitializer (ConstructorInitializer constructorInitializer)
+		{
+			return VisitChildren (constructorInitializer);
+		}
+		
+		public virtual T VisitDestructorDeclaration (DestructorDeclaration destructorDeclaration)
+		{
+			return VisitChildren (destructorDeclaration);
+		}
+		
+		public virtual T VisitEventDeclaration (EventDeclaration eventDeclaration)
+		{
+			return VisitChildren (eventDeclaration);
+		}
+		
+		public virtual T VisitCustomEventDeclaration (CustomEventDeclaration eventDeclaration)
+		{
+			return VisitChildren (eventDeclaration);
+		}
+		
+		public virtual T VisitFieldDeclaration (FieldDeclaration fieldDeclaration)
+		{
+			return VisitChildren (fieldDeclaration);
+		}
+		
+		public virtual T VisitFixedFieldDeclaration (FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			return VisitChildren (fixedFieldDeclaration);
+		}
+		
+		public virtual T VisitFixedVariableInitializer (FixedVariableInitializer fixedVariableInitializer)
+		{
+			return VisitChildren (fixedVariableInitializer);
+		}
+		
+		public virtual T VisitIndexerDeclaration (IndexerDeclaration indexerDeclaration)
+		{
+			return VisitChildren (indexerDeclaration);
+		}
+		
+		public virtual T VisitMethodDeclaration (MethodDeclaration methodDeclaration)
+		{
+			return VisitChildren (methodDeclaration);
+		}
+		
+		public virtual T VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration)
+		{
+			return VisitChildren (operatorDeclaration);
+		}
+		
+		public virtual T VisitPropertyDeclaration (PropertyDeclaration propertyDeclaration)
+		{
+			return VisitChildren (propertyDeclaration);
+		}
+		
+		public virtual T VisitAccessor (Accessor accessor)
+		{
+			return VisitChildren (accessor);
+		}
+		
+		public virtual T VisitVariableInitializer (VariableInitializer variableInitializer)
+		{
+			return VisitChildren (variableInitializer);
+		}
+		
+		public virtual T VisitParameterDeclaration (ParameterDeclaration parameterDeclaration)
+		{
+			return VisitChildren (parameterDeclaration);
+		}
+		
+		public virtual T VisitConstraint (Constraint constraint)
+		{
+			return VisitChildren (constraint);
+		}
+		
+		public virtual T VisitBlockStatement (BlockStatement blockStatement)
+		{
+			return VisitChildren (blockStatement);
+		}
+		
+		public virtual T VisitExpressionStatement (ExpressionStatement expressionStatement)
+		{
+			return VisitChildren (expressionStatement);
+		}
+		
+		public virtual T VisitBreakStatement (BreakStatement breakStatement)
+		{
+			return VisitChildren (breakStatement);
+		}
+		
+		public virtual T VisitCheckedStatement (CheckedStatement checkedStatement)
+		{
+			return VisitChildren (checkedStatement);
+		}
+		
+		public virtual T VisitContinueStatement (ContinueStatement continueStatement)
+		{
+			return VisitChildren (continueStatement);
+		}
+		
+		public virtual T VisitDoWhileStatement (DoWhileStatement doWhileStatement)
+		{
+			return VisitChildren (doWhileStatement);
+		}
+		
+		public virtual T VisitEmptyStatement (EmptyStatement emptyStatement)
+		{
+			return VisitChildren (emptyStatement);
+		}
+		
+		public virtual T VisitFixedStatement (FixedStatement fixedStatement)
+		{
+			return VisitChildren (fixedStatement);
+		}
+		
+		public virtual T VisitForeachStatement (ForeachStatement foreachStatement)
+		{
+			return VisitChildren (foreachStatement);
+		}
+		
+		public virtual T VisitForStatement (ForStatement forStatement)
+		{
+			return VisitChildren (forStatement);
+		}
+		
+		public virtual T VisitGotoCaseStatement (GotoCaseStatement gotoCaseStatement)
+		{
+			return VisitChildren (gotoCaseStatement);
+		}
+		
+		public virtual T VisitGotoDefaultStatement (GotoDefaultStatement gotoDefaultStatement)
+		{
+			return VisitChildren (gotoDefaultStatement);
+		}
+		
+		public virtual T VisitGotoStatement (GotoStatement gotoStatement)
+		{
+			return VisitChildren (gotoStatement);
+		}
+		
+		public virtual T VisitIfElseStatement (IfElseStatement ifElseStatement)
+		{
+			return VisitChildren (ifElseStatement);
+		}
+		
+		public virtual T VisitLabelStatement (LabelStatement labelStatement)
+		{
+			return VisitChildren (labelStatement);
+		}
+		
+		public virtual T VisitLockStatement (LockStatement lockStatement)
+		{
+			return VisitChildren (lockStatement);
+		}
+		
+		public virtual T VisitReturnStatement (ReturnStatement returnStatement)
+		{
+			return VisitChildren (returnStatement);
+		}
+		
+		public virtual T VisitSwitchStatement (SwitchStatement switchStatement)
+		{
+			return VisitChildren (switchStatement);
+		}
+		
+		public virtual T VisitSwitchSection (SwitchSection switchSection)
+		{
+			return VisitChildren (switchSection);
+		}
+		
+		public virtual T VisitCaseLabel (CaseLabel caseLabel)
+		{
+			return VisitChildren (caseLabel);
+		}
+		
+		public virtual T VisitThrowStatement (ThrowStatement throwStatement)
+		{
+			return VisitChildren (throwStatement);
+		}
+		
+		public virtual T VisitTryCatchStatement (TryCatchStatement tryCatchStatement)
+		{
+			return VisitChildren (tryCatchStatement);
+		}
+		
+		public virtual T VisitCatchClause (CatchClause catchClause)
+		{
+			return VisitChildren (catchClause);
+		}
+		
+		public virtual T VisitUncheckedStatement (UncheckedStatement uncheckedStatement)
+		{
+			return VisitChildren (uncheckedStatement);
+		}
+		
+		public virtual T VisitUnsafeStatement (UnsafeStatement unsafeStatement)
+		{
+			return VisitChildren (unsafeStatement);
+		}
+		
+		public virtual T VisitUsingStatement (UsingStatement usingStatement)
+		{
+			return VisitChildren (usingStatement);
+		}
+		
+		public virtual T VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement)
+		{
+			return VisitChildren (variableDeclarationStatement);
+		}
+		
+		public virtual T VisitWhileStatement (WhileStatement whileStatement)
+		{
+			return VisitChildren (whileStatement);
+		}
+		
+		public virtual T VisitYieldBreakStatement (YieldBreakStatement yieldBreakStatement)
+		{
+			return VisitChildren (yieldBreakStatement);
+		}
+		
+		public virtual T VisitYieldReturnStatement (YieldReturnStatement yieldReturnStatement)
+		{
+			return VisitChildren (yieldReturnStatement);
+		}
+		
+		public virtual T VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression)
+		{
+			return VisitChildren (anonymousMethodExpression);
+		}
+		
+		public virtual T VisitLambdaExpression (LambdaExpression lambdaExpression)
+		{
+			return VisitChildren (lambdaExpression);
+		}
+		
+		public virtual T VisitAssignmentExpression (AssignmentExpression assignmentExpression)
+		{
+			return VisitChildren (assignmentExpression);
+		}
+		
+		public virtual T VisitBaseReferenceExpression (BaseReferenceExpression baseReferenceExpression)
+		{
+			return VisitChildren (baseReferenceExpression);
+		}
+		
+		public virtual T VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression)
+		{
+			return VisitChildren (binaryOperatorExpression);
+		}
+		
+		public virtual T VisitCastExpression (CastExpression castExpression)
+		{
+			return VisitChildren (castExpression);
+		}
+		
+		public virtual T VisitCheckedExpression (CheckedExpression checkedExpression)
+		{
+			return VisitChildren (checkedExpression);
+		}
+		
+		public virtual T VisitConditionalExpression (ConditionalExpression conditionalExpression)
+		{
+			return VisitChildren (conditionalExpression);
+		}
+		
+		public virtual T VisitIdentifierExpression (IdentifierExpression identifierExpression)
+		{
+			return VisitChildren (identifierExpression);
+		}
+		
+		public virtual T VisitIndexerExpression (IndexerExpression indexerExpression)
+		{
+			return VisitChildren (indexerExpression);
+		}
+		
+		public virtual T VisitInvocationExpression (InvocationExpression invocationExpression)
+		{
+			return VisitChildren (invocationExpression);
+		}
+		
+		public virtual T VisitDirectionExpression (DirectionExpression directionExpression)
+		{
+			return VisitChildren (directionExpression);
+		}
+		
+		public virtual T VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression)
+		{
+			return VisitChildren (memberReferenceExpression);
+		}
+		
+		public virtual T VisitNullReferenceExpression (NullReferenceExpression nullReferenceExpression)
+		{
+			return VisitChildren (nullReferenceExpression);
+		}
+		
+		public virtual T VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression)
+		{
+			return VisitChildren (objectCreateExpression);
+		}
+		
+		public virtual T VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+		{
+			return VisitChildren (anonymousTypeCreateExpression);
+		}
+		
+		public virtual T VisitArrayCreateExpression (ArrayCreateExpression arrayCreateExpression)
+		{
+			return VisitChildren (arrayCreateExpression);
+		}
+		
+		public virtual T VisitParenthesizedExpression (ParenthesizedExpression parenthesizedExpression)
+		{
+			return VisitChildren (parenthesizedExpression);
+		}
+		
+		public virtual T VisitPointerReferenceExpression (PointerReferenceExpression pointerReferenceExpression)
+		{
+			return VisitChildren (pointerReferenceExpression);
+		}
+		
+		public virtual T VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+		{
+			return VisitChildren (primitiveExpression);
+		}
+		
+		public virtual T VisitSizeOfExpression (SizeOfExpression sizeOfExpression)
+		{
+			return VisitChildren (sizeOfExpression);
+		}
+		
+		public virtual T VisitStackAllocExpression (StackAllocExpression stackAllocExpression)
+		{
+			return VisitChildren (stackAllocExpression);
+		}
+		
+		public virtual T VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
+		{
+			return VisitChildren (thisReferenceExpression);
+		}
+		
+		public virtual T VisitTypeOfExpression (TypeOfExpression typeOfExpression)
+		{
+			return VisitChildren (typeOfExpression);
+		}
+		
+		public virtual T VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
+		{
+			return VisitChildren (typeReferenceExpression);
+		}
+		
+		public virtual T VisitUnaryOperatorExpression (UnaryOperatorExpression unaryOperatorExpression)
+		{
+			return VisitChildren (unaryOperatorExpression);
+		}
+		
+		public virtual T VisitUncheckedExpression (UncheckedExpression uncheckedExpression)
+		{
+			return VisitChildren (uncheckedExpression);
+		}
+		
+		public virtual T VisitQueryExpression(QueryExpression queryExpression)
+		{
+			return VisitChildren (queryExpression);
+		}
+		
+		public virtual T VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			return VisitChildren (queryContinuationClause);
+		}
+		
+		public virtual T VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			return VisitChildren (queryFromClause);
+		}
+		
+		public virtual T VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			return VisitChildren (queryLetClause);
+		}
+		
+		public virtual T VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			return VisitChildren (queryWhereClause);
+		}
+		
+		public virtual T VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			return VisitChildren (queryJoinClause);
+		}
+		
+		public virtual T VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			return VisitChildren (queryOrderClause);
+		}
+		
+		public virtual T VisitQueryOrdering(QueryOrdering queryOrdering)
+		{
+			return VisitChildren (queryOrdering);
+		}
+		
+		public virtual T VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			return VisitChildren (querySelectClause);
+		}
+		
+		public virtual T VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			return VisitChildren (queryGroupClause);
+		}
+		
+		public virtual T VisitAsExpression (AsExpression asExpression)
+		{
+			return VisitChildren (asExpression);
+		}
+		
+		public virtual T VisitIsExpression (IsExpression isExpression)
+		{
+			return VisitChildren (isExpression);
+		}
+		
+		public virtual T VisitDefaultValueExpression (DefaultValueExpression defaultValueExpression)
+		{
+			return VisitChildren (defaultValueExpression);
+		}
+		
+		public virtual T VisitUndocumentedExpression (UndocumentedExpression undocumentedExpression)
+		{
+			return VisitChildren (undocumentedExpression);
+		}
+		
+		public virtual T VisitArrayInitializerExpression (ArrayInitializerExpression arrayInitializerExpression)
+		{
+			return VisitChildren (arrayInitializerExpression);
+		}
+		
+		public virtual T VisitArraySpecifier (ArraySpecifier arraySpecifier)
+		{
+			return VisitChildren (arraySpecifier);
+		}
+		
+		public virtual T VisitNamedArgumentExpression (NamedArgumentExpression namedArgumentExpression)
+		{
+			return VisitChildren (namedArgumentExpression);
+		}
+		
+		public virtual T VisitNamedExpression (NamedExpression namedExpression)
+		{
+			return VisitChildren (namedExpression);
+		}
+
+		public virtual T VisitErrorNode(AstNode errorNode)
+		{
+			return VisitChildren(errorNode);
+		}
+
+		public virtual T VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern)
+		{
+			return VisitChildren (placeholder);
+		}
+	}
+	
+	/// <summary>
+	/// AST visitor with a default implementation that visits all node depth-first.
+	/// </summary>
+	public abstract class DepthFirstAstVisitor<T, S> : IAstVisitor<T, S>
+	{
+		protected virtual S VisitChildren (AstNode node, T data)
+		{
+			AstNode next;
+			for (var child = node.FirstChild; child != null; child = next) {
+				// Store next to allow the loop to continue
+				// if the visitor removes/replaces child.
+				next = child.NextSibling;
+				child.AcceptVisitor (this, data);
+			}
+			return default (S);
+		}
+		
+		public virtual S VisitNullNode(AstNode nullNode, T data)
+		{
+			// Should we call VisitChildren here?
+			// We usually want to ignore null nodes.
+			// Older NR versions (before VisitNullNode was introduced) didn't call VisitChildren() with null nodes;
+			// so changing this might break VisitChildren() overrides that expect the node to be part of the AST.
+			return default (S);
+		}
+		
+		public virtual S VisitSyntaxTree (SyntaxTree unit, T data)
+		{
+			return VisitChildren (unit, data);
+		}
+		
+		public virtual S VisitComment (Comment comment, T data)
+		{
+			return VisitChildren (comment, data);
+		}
+		
+		public virtual S VisitNewLine(NewLineNode newLineNode, T data)
+		{
+			return VisitChildren(newLineNode, data);
+		}
+
+		public virtual S VisitWhitespace(WhitespaceNode whitespaceNode, T data)
+		{
+			return VisitChildren(whitespaceNode, data);
+		}
+
+		public virtual S VisitText(TextNode textNode, T data)
+		{
+			return VisitChildren(textNode, data);
+		}
+
+		public virtual S VisitDocumentationReference (DocumentationReference documentationReference, T data)
+		{
+			return VisitChildren (documentationReference, data);
+		}
+		
+		public virtual S VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective, T data)
+		{
+			return VisitChildren (preProcessorDirective, data);
+		}
+
+		public virtual S VisitIdentifier (Identifier identifier, T data)
+		{
+			return VisitChildren (identifier, data);
+		}
+		
+		public virtual S VisitCSharpTokenNode (CSharpTokenNode token, T data)
+		{
+			return VisitChildren (token, data);
+		}
+		
+		public virtual S VisitPrimitiveType (PrimitiveType primitiveType, T data)
+		{
+			return VisitChildren (primitiveType, data);
+		}
+		
+		public virtual S VisitComposedType (ComposedType composedType, T data)
+		{
+			return VisitChildren (composedType, data);
+		}
+		
+		public virtual S VisitSimpleType(SimpleType simpleType, T data)
+		{
+			return VisitChildren (simpleType, data);
+		}
+		
+		public virtual S VisitMemberType(MemberType memberType, T data)
+		{
+			return VisitChildren (memberType, data);
+		}
+		
+		public virtual S VisitAttribute (Attribute attribute, T data)
+		{
+			return VisitChildren (attribute, data);
+		}
+		
+		public virtual S VisitAttributeSection (AttributeSection attributeSection, T data)
+		{
+			return VisitChildren (attributeSection, data);
+		}
+		
+		public virtual S VisitDelegateDeclaration (DelegateDeclaration delegateDeclaration, T data)
+		{
+			return VisitChildren (delegateDeclaration, data);
+		}
+		
+		public virtual S VisitNamespaceDeclaration (NamespaceDeclaration namespaceDeclaration, T data)
+		{
+			return VisitChildren (namespaceDeclaration, data);
+		}
+		
+		public virtual S VisitTypeDeclaration (TypeDeclaration typeDeclaration, T data)
+		{
+			return VisitChildren (typeDeclaration, data);
+		}
+		
+		public virtual S VisitTypeParameterDeclaration (TypeParameterDeclaration typeParameterDeclaration, T data)
+		{
+			return VisitChildren (typeParameterDeclaration, data);
+		}
+		
+		public virtual S VisitEnumMemberDeclaration (EnumMemberDeclaration enumMemberDeclaration, T data)
+		{
+			return VisitChildren (enumMemberDeclaration, data);
+		}
+		
+		public virtual S VisitUsingDeclaration (UsingDeclaration usingDeclaration, T data)
+		{
+			return VisitChildren (usingDeclaration, data);
+		}
+		
+		public virtual S VisitUsingAliasDeclaration (UsingAliasDeclaration usingDeclaration, T data)
+		{
+			return VisitChildren (usingDeclaration, data);
+		}
+		
+		public virtual S VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, T data)
+		{
+			return VisitChildren (externAliasDeclaration, data);
+		}
+		
+		public virtual S VisitConstructorDeclaration (ConstructorDeclaration constructorDeclaration, T data)
+		{
+			return VisitChildren (constructorDeclaration, data);
+		}
+		
+		public virtual S VisitConstructorInitializer (ConstructorInitializer constructorInitializer, T data)
+		{
+			return VisitChildren (constructorInitializer, data);
+		}
+		
+		public virtual S VisitDestructorDeclaration (DestructorDeclaration destructorDeclaration, T data)
+		{
+			return VisitChildren (destructorDeclaration, data);
+		}
+		
+		public virtual S VisitEventDeclaration (EventDeclaration eventDeclaration, T data)
+		{
+			return VisitChildren (eventDeclaration, data);
+		}
+		
+		public virtual S VisitCustomEventDeclaration (CustomEventDeclaration eventDeclaration, T data)
+		{
+			return VisitChildren (eventDeclaration, data);
+		}
+		
+		public virtual S VisitFieldDeclaration (FieldDeclaration fieldDeclaration, T data)
+		{
+			return VisitChildren (fieldDeclaration, data);
+		}
+		
+		public virtual S VisitFixedFieldDeclaration (FixedFieldDeclaration fixedFieldDeclaration, T data)
+		{
+			return VisitChildren (fixedFieldDeclaration, data);
+		}
+		
+		public virtual S VisitFixedVariableInitializer (FixedVariableInitializer fixedVariableInitializer, T data)
+		{
+			return VisitChildren (fixedVariableInitializer, data);
+		}
+		
+		public virtual S VisitIndexerDeclaration (IndexerDeclaration indexerDeclaration, T data)
+		{
+			return VisitChildren (indexerDeclaration, data);
+		}
+		
+		public virtual S VisitMethodDeclaration (MethodDeclaration methodDeclaration, T data)
+		{
+			return VisitChildren (methodDeclaration, data);
+		}
+		
+		public virtual S VisitOperatorDeclaration (OperatorDeclaration operatorDeclaration, T data)
+		{
+			return VisitChildren (operatorDeclaration, data);
+		}
+		
+		public virtual S VisitPropertyDeclaration (PropertyDeclaration propertyDeclaration, T data)
+		{
+			return VisitChildren (propertyDeclaration, data);
+		}
+		
+		public virtual S VisitAccessor (Accessor accessor, T data)
+		{
+			return VisitChildren (accessor, data);
+		}
+		
+		public virtual S VisitVariableInitializer (VariableInitializer variableInitializer, T data)
+		{
+			return VisitChildren (variableInitializer, data);
+		}
+		
+		public virtual S VisitParameterDeclaration (ParameterDeclaration parameterDeclaration, T data)
+		{
+			return VisitChildren (parameterDeclaration, data);
+		}
+		
+		public virtual S VisitConstraint (Constraint constraint, T data)
+		{
+			return VisitChildren (constraint, data);
+		}
+		
+		public virtual S VisitBlockStatement (BlockStatement blockStatement, T data)
+		{
+			return VisitChildren (blockStatement, data);
+		}
+		
+		public virtual S VisitExpressionStatement (ExpressionStatement expressionStatement, T data)
+		{
+			return VisitChildren (expressionStatement, data);
+		}
+		
+		public virtual S VisitBreakStatement (BreakStatement breakStatement, T data)
+		{
+			return VisitChildren (breakStatement, data);
+		}
+		
+		public virtual S VisitCheckedStatement (CheckedStatement checkedStatement, T data)
+		{
+			return VisitChildren (checkedStatement, data);
+		}
+		
+		public virtual S VisitContinueStatement (ContinueStatement continueStatement, T data)
+		{
+			return VisitChildren (continueStatement, data);
+		}
+		
+		public virtual S VisitDoWhileStatement (DoWhileStatement doWhileStatement, T data)
+		{
+			return VisitChildren (doWhileStatement, data);
+		}
+		
+		public virtual S VisitEmptyStatement (EmptyStatement emptyStatement, T data)
+		{
+			return VisitChildren (emptyStatement, data);
+		}
+		
+		public virtual S VisitFixedStatement (FixedStatement fixedStatement, T data)
+		{
+			return VisitChildren (fixedStatement, data);
+		}
+		
+		public virtual S VisitForeachStatement (ForeachStatement foreachStatement, T data)
+		{
+			return VisitChildren (foreachStatement, data);
+		}
+		
+		public virtual S VisitForStatement (ForStatement forStatement, T data)
+		{
+			return VisitChildren (forStatement, data);
+		}
+		
+		public virtual S VisitGotoCaseStatement (GotoCaseStatement gotoCaseStatement, T data)
+		{
+			return VisitChildren (gotoCaseStatement, data);
+		}
+		
+		public virtual S VisitGotoDefaultStatement (GotoDefaultStatement gotoDefaultStatement, T data)
+		{
+			return VisitChildren (gotoDefaultStatement, data);
+		}
+		
+		public virtual S VisitGotoStatement (GotoStatement gotoStatement, T data)
+		{
+			return VisitChildren (gotoStatement, data);
+		}
+		
+		public virtual S VisitIfElseStatement (IfElseStatement ifElseStatement, T data)
+		{
+			return VisitChildren (ifElseStatement, data);
+		}
+		
+		public virtual S VisitLabelStatement (LabelStatement labelStatement, T data)
+		{
+			return VisitChildren (labelStatement, data);
+		}
+		
+		public virtual S VisitLockStatement (LockStatement lockStatement, T data)
+		{
+			return VisitChildren (lockStatement, data);
+		}
+		
+		public virtual S VisitReturnStatement (ReturnStatement returnStatement, T data)
+		{
+			return VisitChildren (returnStatement, data);
+		}
+		
+		public virtual S VisitSwitchStatement (SwitchStatement switchStatement, T data)
+		{
+			return VisitChildren (switchStatement, data);
+		}
+		
+		public virtual S VisitSwitchSection (SwitchSection switchSection, T data)
+		{
+			return VisitChildren (switchSection, data);
+		}
+		
+		public virtual S VisitCaseLabel (CaseLabel caseLabel, T data)
+		{
+			return VisitChildren (caseLabel, data);
+		}
+		
+		public virtual S VisitThrowStatement (ThrowStatement throwStatement, T data)
+		{
+			return VisitChildren (throwStatement, data);
+		}
+		
+		public virtual S VisitTryCatchStatement (TryCatchStatement tryCatchStatement, T data)
+		{
+			return VisitChildren (tryCatchStatement, data);
+		}
+		
+		public virtual S VisitCatchClause (CatchClause catchClause, T data)
+		{
+			return VisitChildren (catchClause, data);
+		}
+		
+		public virtual S VisitUncheckedStatement (UncheckedStatement uncheckedStatement, T data)
+		{
+			return VisitChildren (uncheckedStatement, data);
+		}
+		
+		public virtual S VisitUnsafeStatement (UnsafeStatement unsafeStatement, T data)
+		{
+			return VisitChildren (unsafeStatement, data);
+		}
+		
+		public virtual S VisitUsingStatement (UsingStatement usingStatement, T data)
+		{
+			return VisitChildren (usingStatement, data);
+		}
+		
+		public virtual S VisitVariableDeclarationStatement (VariableDeclarationStatement variableDeclarationStatement, T data)
+		{
+			return VisitChildren (variableDeclarationStatement, data);
+		}
+		
+		public virtual S VisitWhileStatement (WhileStatement whileStatement, T data)
+		{
+			return VisitChildren (whileStatement, data);
+		}
+		
+		public virtual S VisitYieldBreakStatement (YieldBreakStatement yieldBreakStatement, T data)
+		{
+			return VisitChildren (yieldBreakStatement, data);
+		}
+		
+		public virtual S VisitYieldReturnStatement (YieldReturnStatement yieldReturnStatement, T data)
+		{
+			return VisitChildren (yieldReturnStatement, data);
+		}
+		
+		public virtual S VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression, T data)
+		{
+			return VisitChildren (anonymousMethodExpression, data);
+		}
+		
+		public virtual S VisitLambdaExpression (LambdaExpression lambdaExpression, T data)
+		{
+			return VisitChildren (lambdaExpression, data);
+		}
+		
+		public virtual S VisitAssignmentExpression (AssignmentExpression assignmentExpression, T data)
+		{
+			return VisitChildren (assignmentExpression, data);
+		}
+		
+		public virtual S VisitBaseReferenceExpression (BaseReferenceExpression baseReferenceExpression, T data)
+		{
+			return VisitChildren (baseReferenceExpression, data);
+		}
+		
+		public virtual S VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression, T data)
+		{
+			return VisitChildren (binaryOperatorExpression, data);
+		}
+		
+		public virtual S VisitCastExpression (CastExpression castExpression, T data)
+		{
+			return VisitChildren (castExpression, data);
+		}
+		
+		public virtual S VisitCheckedExpression (CheckedExpression checkedExpression, T data)
+		{
+			return VisitChildren (checkedExpression, data);
+		}
+		
+		public virtual S VisitConditionalExpression (ConditionalExpression conditionalExpression, T data)
+		{
+			return VisitChildren (conditionalExpression, data);
+		}
+		
+		public virtual S VisitIdentifierExpression (IdentifierExpression identifierExpression, T data)
+		{
+			return VisitChildren (identifierExpression, data);
+		}
+		
+		public virtual S VisitIndexerExpression (IndexerExpression indexerExpression, T data)
+		{
+			return VisitChildren (indexerExpression, data);
+		}
+		
+		public virtual S VisitInvocationExpression (InvocationExpression invocationExpression, T data)
+		{
+			return VisitChildren (invocationExpression, data);
+		}
+		
+		public virtual S VisitDirectionExpression (DirectionExpression directionExpression, T data)
+		{
+			return VisitChildren (directionExpression, data);
+		}
+		
+		public virtual S VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression, T data)
+		{
+			return VisitChildren (memberReferenceExpression, data);
+		}
+		
+		public virtual S VisitNullReferenceExpression (NullReferenceExpression nullReferenceExpression, T data)
+		{
+			return VisitChildren (nullReferenceExpression, data);
+		}
+		
+		public virtual S VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression, T data)
+		{
+			return VisitChildren (objectCreateExpression, data);
+		}
+		
+		public virtual S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data)
+		{
+			return VisitChildren (anonymousTypeCreateExpression, data);
+		}
+		
+		public virtual S VisitArrayCreateExpression (ArrayCreateExpression arrayCreateExpression, T data)
+		{
+			return VisitChildren (arrayCreateExpression, data);
+		}
+		
+		public virtual S VisitParenthesizedExpression (ParenthesizedExpression parenthesizedExpression, T data)
+		{
+			return VisitChildren (parenthesizedExpression, data);
+		}
+		
+		public virtual S VisitPointerReferenceExpression (PointerReferenceExpression pointerReferenceExpression, T data)
+		{
+			return VisitChildren (pointerReferenceExpression, data);
+		}
+		
+		public virtual S VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, T data)
+		{
+			return VisitChildren (primitiveExpression, data);
+		}
+		
+		public virtual S VisitSizeOfExpression (SizeOfExpression sizeOfExpression, T data)
+		{
+			return VisitChildren (sizeOfExpression, data);
+		}
+		
+		public virtual S VisitStackAllocExpression (StackAllocExpression stackAllocExpression, T data)
+		{
+			return VisitChildren (stackAllocExpression, data);
+		}
+		
+		public virtual S VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, T data)
+		{
+			return VisitChildren (thisReferenceExpression, data);
+		}
+		
+		public virtual S VisitTypeOfExpression (TypeOfExpression typeOfExpression, T data)
+		{
+			return VisitChildren (typeOfExpression, data);
+		}
+		
+		public virtual S VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, T data)
+		{
+			return VisitChildren (typeReferenceExpression, data);
+		}
+		
+		public virtual S VisitUnaryOperatorExpression (UnaryOperatorExpression unaryOperatorExpression, T data)
+		{
+			return VisitChildren (unaryOperatorExpression, data);
+		}
+		
+		public virtual S VisitUncheckedExpression (UncheckedExpression uncheckedExpression, T data)
+		{
+			return VisitChildren (uncheckedExpression, data);
+		}
+		
+		public virtual S VisitQueryExpression(QueryExpression queryExpression, T data)
+		{
+			return VisitChildren (queryExpression, data);
+		}
+		
+		public virtual S VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, T data)
+		{
+			return VisitChildren (queryContinuationClause, data);
+		}
+		
+		public virtual S VisitQueryFromClause(QueryFromClause queryFromClause, T data)
+		{
+			return VisitChildren (queryFromClause, data);
+		}
+		
+		public virtual S VisitQueryLetClause(QueryLetClause queryLetClause, T data)
+		{
+			return VisitChildren (queryLetClause, data);
+		}
+		
+		public virtual S VisitQueryWhereClause(QueryWhereClause queryWhereClause, T data)
+		{
+			return VisitChildren (queryWhereClause, data);
+		}
+		
+		public virtual S VisitQueryJoinClause(QueryJoinClause queryJoinClause, T data)
+		{
+			return VisitChildren (queryJoinClause, data);
+		}
+		
+		public virtual S VisitQueryOrderClause(QueryOrderClause queryOrderClause, T data)
+		{
+			return VisitChildren (queryOrderClause, data);
+		}
+		
+		public virtual S VisitQueryOrdering(QueryOrdering queryOrdering, T data)
+		{
+			return VisitChildren (queryOrdering, data);
+		}
+		
+		public virtual S VisitQuerySelectClause(QuerySelectClause querySelectClause, T data)
+		{
+			return VisitChildren (querySelectClause, data);
+		}
+		
+		public virtual S VisitQueryGroupClause(QueryGroupClause queryGroupClause, T data)
+		{
+			return VisitChildren (queryGroupClause, data);
+		}
+		
+		public virtual S VisitAsExpression (AsExpression asExpression, T data)
+		{
+			return VisitChildren (asExpression, data);
+		}
+		
+		public virtual S VisitIsExpression (IsExpression isExpression, T data)
+		{
+			return VisitChildren (isExpression, data);
+		}
+		
+		public virtual S VisitDefaultValueExpression (DefaultValueExpression defaultValueExpression, T data)
+		{
+			return VisitChildren (defaultValueExpression, data);
+		}
+		
+		public virtual S VisitUndocumentedExpression (UndocumentedExpression undocumentedExpression, T data)
+		{
+			return VisitChildren (undocumentedExpression, data);
+		}
+		
+		public virtual S VisitArrayInitializerExpression (ArrayInitializerExpression arrayInitializerExpression, T data)
+		{
+			return VisitChildren (arrayInitializerExpression, data);
+		}
+		
+		public virtual S VisitArraySpecifier (ArraySpecifier arraySpecifier, T data)
+		{
+			return VisitChildren (arraySpecifier, data);
+		}
+		
+		public virtual S VisitNamedArgumentExpression (NamedArgumentExpression namedArgumentExpression, T data)
+		{
+			return VisitChildren (namedArgumentExpression, data);
+		}
+		
+		public virtual S VisitNamedExpression (NamedExpression namedExpression, T data)
+		{
+			return VisitChildren (namedExpression, data);
+		}
+
+		public virtual S VisitErrorNode(AstNode errorNode, T data)
+		{
+			return VisitChildren(errorNode, data);
+		}
+
+		public virtual S VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern, T data)
+		{
+			return VisitChildren (placeholder, data);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/DocumentationReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/DocumentationReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/DocumentationReference.cs	(revision 11807)
@@ -0,0 +1,149 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents a 'cref' reference in XML documentation.
+	/// </summary>
+	public class DocumentationReference : AstNode
+	{
+		public static readonly Role<AstType> DeclaringTypeRole = new Role<AstType>("DeclaringType", AstType.Null);
+		public static readonly Role<AstType> ConversionOperatorReturnTypeRole = new Role<AstType>("ConversionOperatorReturnType", AstType.Null);
+		
+		SymbolKind symbolKind;
+		OperatorType operatorType;
+		bool hasParameterList;
+		
+		/// <summary>
+		/// Gets/Sets the entity type.
+		/// Possible values are:
+		///   <c>SymbolKind.Operator</c> for operators,
+		///   <c>SymbolKind.Indexer</c> for indexers,
+		///   <c>SymbolKind.TypeDefinition</c> for references to primitive types,
+		///   and <c>SymbolKind.None</c> for everything else.
+		/// </summary>
+		public SymbolKind SymbolKind {
+			get { return symbolKind; }
+			set {
+				ThrowIfFrozen();
+				symbolKind = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets the operator type.
+		/// This property is only used when SymbolKind==Operator.
+		/// </summary>
+		public OperatorType OperatorType {
+			get { return operatorType; }
+			set {
+				ThrowIfFrozen();
+				operatorType = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets whether a parameter list was provided.
+		/// </summary>
+		public bool HasParameterList {
+			get { return hasParameterList; }
+			set {
+				ThrowIfFrozen();
+				hasParameterList = value;
+			}
+		}
+		
+		public override NodeType NodeType {
+			get { return NodeType.Unknown; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the declaring type.
+		/// </summary>
+		public AstType DeclaringType {
+			get { return GetChildByRole(DeclaringTypeRole); }
+			set { SetChildByRole(DeclaringTypeRole, value); }
+		}
+		
+		/// <summary>
+		/// Gets/sets the member name.
+		/// This property is only used when SymbolKind==None.
+		/// </summary>
+		public string MemberName {
+			get { return GetChildByRole(Roles.Identifier).Name; }
+			set { SetChildByRole(Roles.Identifier, Identifier.Create(value)); }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the return type of conversion operators.
+		/// This property is only used when SymbolKind==Operator and OperatorType is explicit or implicit.
+		/// </summary>
+		public AstType ConversionOperatorReturnType {
+			get { return GetChildByRole(ConversionOperatorReturnTypeRole); }
+			set { SetChildByRole(ConversionOperatorReturnTypeRole, value); }
+		}
+		
+		public AstNodeCollection<AstType> TypeArguments {
+			get { return GetChildrenByRole (Roles.TypeArgument); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
+		{
+			DocumentationReference o = other as DocumentationReference;
+			if (!(o != null && this.SymbolKind == o.SymbolKind && this.HasParameterList == o.HasParameterList))
+				return false;
+			if (this.SymbolKind == SymbolKind.Operator) {
+				if (this.OperatorType != o.OperatorType)
+					return false;
+				if (this.OperatorType == OperatorType.Implicit || this.OperatorType == OperatorType.Explicit) {
+					if (!this.ConversionOperatorReturnType.DoMatch(o.ConversionOperatorReturnType, match))
+						return false;
+				}
+			} else if (this.SymbolKind == SymbolKind.None) {
+				if (!MatchString(this.MemberName, o.MemberName))
+					return false;
+				if (!this.TypeArguments.DoMatch(o.TypeArguments, match))
+					return false;
+			}
+			return this.Parameters.DoMatch(o.Parameters, match);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitDocumentationReference (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitDocumentationReference (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitDocumentationReference (this, data);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ErrorNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ErrorNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ErrorNode.cs	(revision 11807)
@@ -0,0 +1,88 @@
+﻿// 
+// ErrorNode.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Xamarin (http://www.xamarin.com);
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents a parsing error in the ast. At the moment it only represents missing closing bracket.
+	/// This closing bracket is replaced by a node at the highest possible position.
+	/// (To make GetAstNodeAt (line, col) working).
+	/// </summary>
+	public class ErrorNode : AstNode
+	{
+		static TextLocation maxLoc = new TextLocation (int.MaxValue, int.MaxValue);
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+				
+		public override TextLocation StartLocation {
+			get {
+				return maxLoc;
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return maxLoc;
+			}
+		}
+		
+		public ErrorNode ()
+		{
+		}
+
+		public override void AcceptVisitor(IAstVisitor visitor)
+		{
+			visitor.VisitErrorNode(this);
+		}
+
+		public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
+		{
+			return visitor.VisitErrorNode(this);
+		}
+
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitErrorNode(this, data);
+		}
+
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			var o = other as ErrorNode;
+			return o != null;
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			return "[ErrorNode]";
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AnonymousMethodExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AnonymousMethodExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AnonymousMethodExpression.cs	(revision 11807)
@@ -0,0 +1,117 @@
+﻿// 
+// AnonymousMethodExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// [async] delegate(Parameters) {Body}
+	/// </summary>
+	public class AnonymousMethodExpression : Expression
+	{
+		public readonly static TokenRole DelegateKeywordRole = new TokenRole ("delegate");
+		public readonly static TokenRole AsyncModifierRole = LambdaExpression.AsyncModifierRole;
+		
+		bool isAsync;
+		
+		public bool IsAsync {
+			get { return isAsync; }
+			set { ThrowIfFrozen(); isAsync = value; }
+		}
+		
+		// used to tell the difference between delegate {} and delegate () {}
+		bool hasParameterList;
+		
+		public bool HasParameterList {
+			get { return hasParameterList || Parameters.Any(); }
+			set { ThrowIfFrozen(); hasParameterList = value; }
+		}
+		
+		public CSharpTokenNode DelegateToken {
+			get { return GetChildByRole (DelegateKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public AnonymousMethodExpression ()
+		{
+		}
+		
+		public AnonymousMethodExpression (BlockStatement body, IEnumerable<ParameterDeclaration> parameters = null)
+		{
+			if (parameters != null) {
+				hasParameterList = true;
+				foreach (var parameter in parameters) {
+					AddChild (parameter, Roles.Parameter);
+				}
+			}
+			AddChild (body, Roles.Body);
+		}
+		
+		public AnonymousMethodExpression (BlockStatement body, params ParameterDeclaration[] parameters) : this (body, (IEnumerable<ParameterDeclaration>)parameters)
+		{
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAnonymousMethodExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAnonymousMethodExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAnonymousMethodExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			AnonymousMethodExpression o = other as AnonymousMethodExpression;
+			return o != null && this.IsAsync == o.IsAsync && this.HasParameterList == o.HasParameterList
+				&& this.Parameters.DoMatch(o.Parameters, match) && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AnonymousTypeCreateExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AnonymousTypeCreateExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AnonymousTypeCreateExpression.cs	(revision 11807)
@@ -0,0 +1,91 @@
+﻿// 
+// AnonymousTypeCreateExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// new { [ExpressionList] }
+	/// </summary>
+	public class AnonymousTypeCreateExpression : Expression
+	{
+		public readonly static TokenRole NewKeywordRole = new TokenRole ("new");
+		
+		public CSharpTokenNode NewToken {
+			get { return GetChildByRole (NewKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<Expression> Initializers {
+			get { return GetChildrenByRole (Roles.Expression); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public AnonymousTypeCreateExpression ()
+		{
+		}
+		
+		public AnonymousTypeCreateExpression (IEnumerable<Expression> initializers)
+		{
+			foreach (var ini in initializers) {
+				AddChild (ini, Roles.Expression);
+			}
+		}
+		
+		public AnonymousTypeCreateExpression (params Expression[] initializer) : this ((IEnumerable<Expression>)initializer)
+		{
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAnonymousTypeCreateExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAnonymousTypeCreateExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAnonymousTypeCreateExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			var o = other as AnonymousTypeCreateExpression;
+			return o != null && this.Initializers.DoMatch(o.Initializers, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ArrayCreateExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ArrayCreateExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ArrayCreateExpression.cs	(revision 11807)
@@ -0,0 +1,80 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// new Type[Dimensions]
+	/// </summary>
+	public class ArrayCreateExpression : Expression
+	{
+		public readonly static TokenRole NewKeywordRole = new TokenRole ("new");
+		public readonly static Role<ArraySpecifier> AdditionalArraySpecifierRole = new Role<ArraySpecifier>("AdditionalArraySpecifier");
+		public readonly static Role<ArrayInitializerExpression> InitializerRole = new Role<ArrayInitializerExpression>("Initializer", ArrayInitializerExpression.Null);
+		
+		public CSharpTokenNode NewToken {
+			get { return GetChildByRole (NewKeywordRole); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public AstNodeCollection<Expression> Arguments {
+			get { return GetChildrenByRole (Roles.Argument); }
+		}
+		
+		/// <summary>
+		/// Gets additional array ranks (those without size info).
+		/// Empty for "new int[5,1]"; will contain a single element for "new int[5][]".
+		/// </summary>
+		public AstNodeCollection<ArraySpecifier> AdditionalArraySpecifiers {
+			get { return GetChildrenByRole(AdditionalArraySpecifierRole); }
+		}
+		
+		public ArrayInitializerExpression Initializer {
+			get { return GetChildByRole (InitializerRole); }
+			set { SetChildByRole (InitializerRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitArrayCreateExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitArrayCreateExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitArrayCreateExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ArrayCreateExpression o = other as ArrayCreateExpression;
+			return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match) && this.AdditionalArraySpecifiers.DoMatch(o.AdditionalArraySpecifiers, match) && this.Initializer.DoMatch(o.Initializer, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ArrayInitializerExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ArrayInitializerExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ArrayInitializerExpression.cs	(revision 11807)
@@ -0,0 +1,192 @@
+﻿// 
+// ArrayInitializerExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// { Elements }
+	/// </summary>
+	public class ArrayInitializerExpression : Expression
+	{
+		/// <summary>
+		/// For ease of use purposes in the resolver the ast representation
+		/// of { a, b, c }  is { {a}, {b}, {c} }.
+		/// If IsSingleElement is true then this array initializer expression is a generated one.
+		/// That has no meaning in the source code (and contains no brace tokens).
+		/// </summary>
+		public virtual bool IsSingleElement {
+			get {
+				return false;
+			}
+		}
+
+		public ArrayInitializerExpression()
+		{
+		}
+		
+		public ArrayInitializerExpression(IEnumerable<Expression> elements)
+		{
+			this.Elements.AddRange(elements);
+		}
+		
+		public ArrayInitializerExpression(params Expression[] elements)
+		{
+			this.Elements.AddRange(elements);
+		}
+		
+		#region Null
+		public new static readonly ArrayInitializerExpression Null = new NullArrayInitializerExpression ();
+		
+		sealed class NullArrayInitializerExpression : ArrayInitializerExpression
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+		
+		public AstNodeCollection<Expression> Elements {
+			get { return GetChildrenByRole(Roles.Expression); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitArrayInitializerExpression (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitArrayInitializerExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitArrayInitializerExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ArrayInitializerExpression o = other as ArrayInitializerExpression;
+			return o != null && this.Elements.DoMatch(o.Elements, match);
+		}
+
+		public static ArrayInitializerExpression CreateSingleElementInitializer ()
+		{
+			return new SingleArrayInitializerExpression();
+		}
+		/// <summary>
+		/// Single elements in array initializers are represented with this special class.
+		/// </summary>
+		class SingleArrayInitializerExpression : ArrayInitializerExpression
+		{
+			public override bool IsSingleElement {
+				get {
+					return true;
+				}
+			}
+			
+		}
+		
+		#region PatternPlaceholder
+		public static implicit operator ArrayInitializerExpression(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : ArrayInitializerExpression, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder(this, child);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder(this, child);
+			}
+
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AsExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AsExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AsExpression.cs	(revision 11807)
@@ -0,0 +1,150 @@
+﻿// 
+// AsExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Expression as TypeReference
+	/// </summary>
+	public class AsExpression : Expression
+	{
+		public readonly static TokenRole AsKeywordRole = new TokenRole ("as");
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole(Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode AsToken {
+			get { return GetChildByRole (AsKeywordRole); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public AsExpression ()
+		{
+		}
+		
+		public AsExpression (Expression expression, AstType type)
+		{
+			AddChild (expression, Roles.Expression);
+			AddChild (type, Roles.Type);
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAsExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAsExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAsExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			AsExpression o = other as AsExpression;
+			return o != null && this.Expression.DoMatch(o.Expression, match) && this.Type.DoMatch(o.Type, match);
+		}
+
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AssignmentExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AssignmentExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/AssignmentExpression.cs	(revision 11807)
@@ -0,0 +1,304 @@
+﻿// 
+// AssignmentExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq.Expressions;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Left Operator= Right
+	/// </summary>
+	public class AssignmentExpression : Expression
+	{
+		// reuse roles from BinaryOperatorExpression
+		public readonly static Role<Expression> LeftRole = BinaryOperatorExpression.LeftRole;
+		public readonly static Role<Expression> RightRole = BinaryOperatorExpression.RightRole;
+		
+		public readonly static TokenRole AssignRole = new TokenRole ("=");
+		public readonly static TokenRole AddRole = new TokenRole ("+=");
+		public readonly static TokenRole SubtractRole = new TokenRole ("-=");
+		public readonly static TokenRole MultiplyRole = new TokenRole ("*=");
+		public readonly static TokenRole DivideRole = new TokenRole ("/=");
+		public readonly static TokenRole ModulusRole = new TokenRole ("%=");
+		public readonly static TokenRole ShiftLeftRole = new TokenRole ("<<=");
+		public readonly static TokenRole ShiftRightRole = new TokenRole (">>=");
+		public readonly static TokenRole BitwiseAndRole = new TokenRole ("&=");
+		public readonly static TokenRole BitwiseOrRole = new TokenRole ("|=");
+		public readonly static TokenRole ExclusiveOrRole = new TokenRole ("^=");
+		
+		public AssignmentExpression()
+		{
+		}
+		
+		public AssignmentExpression(Expression left, Expression right)
+		{
+			this.Left = left;
+			this.Right = right;
+		}
+		
+		public AssignmentExpression(Expression left, AssignmentOperatorType op, Expression right)
+		{
+			this.Left = left;
+			this.Operator = op;
+			this.Right = right;
+		}
+		
+		public AssignmentOperatorType Operator {
+			get;
+			set;
+		}
+		
+		public Expression Left {
+			get { return GetChildByRole (LeftRole); }
+			set { SetChildByRole(LeftRole, value); }
+		}
+		
+		public CSharpTokenNode OperatorToken {
+			get { return GetChildByRole (GetOperatorRole(Operator)); }
+		}
+		
+		public Expression Right {
+			get { return GetChildByRole (RightRole); }
+			set { SetChildByRole(RightRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAssignmentExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAssignmentExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAssignmentExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			AssignmentExpression o = other as AssignmentExpression;
+			return o != null && (this.Operator == AssignmentOperatorType.Any || this.Operator == o.Operator)
+				&& this.Left.DoMatch(o.Left, match) && this.Right.DoMatch(o.Right, match);
+		}
+		
+		public static TokenRole GetOperatorRole(AssignmentOperatorType op)
+		{
+			switch (op) {
+				case AssignmentOperatorType.Assign:
+					return AssignRole;
+				case AssignmentOperatorType.Add:
+					return AddRole;
+				case AssignmentOperatorType.Subtract:
+					return SubtractRole;
+				case AssignmentOperatorType.Multiply:
+					return MultiplyRole;
+				case AssignmentOperatorType.Divide:
+					return DivideRole;
+				case AssignmentOperatorType.Modulus:
+					return ModulusRole;
+				case AssignmentOperatorType.ShiftLeft:
+					return ShiftLeftRole;
+				case AssignmentOperatorType.ShiftRight:
+					return ShiftRightRole;
+				case AssignmentOperatorType.BitwiseAnd:
+					return BitwiseAndRole;
+				case AssignmentOperatorType.BitwiseOr:
+					return BitwiseOrRole;
+				case AssignmentOperatorType.ExclusiveOr:
+					return ExclusiveOrRole;
+				default:
+					throw new NotSupportedException("Invalid value for AssignmentOperatorType");
+			}
+		}
+		
+		/// <summary>
+		/// Gets the binary operator for the specified compound assignment operator.
+		/// Returns null if 'op' is not a compound assignment.
+		/// </summary>
+		public static BinaryOperatorType? GetCorrespondingBinaryOperator(AssignmentOperatorType op)
+		{
+			switch (op) {
+				case AssignmentOperatorType.Assign:
+					return null;
+				case AssignmentOperatorType.Add:
+					return BinaryOperatorType.Add;
+				case AssignmentOperatorType.Subtract:
+					return BinaryOperatorType.Subtract;
+				case AssignmentOperatorType.Multiply:
+					return BinaryOperatorType.Multiply;
+				case AssignmentOperatorType.Divide:
+					return BinaryOperatorType.Divide;
+				case AssignmentOperatorType.Modulus:
+					return BinaryOperatorType.Modulus;
+				case AssignmentOperatorType.ShiftLeft:
+					return BinaryOperatorType.ShiftLeft;
+				case AssignmentOperatorType.ShiftRight:
+					return BinaryOperatorType.ShiftRight;
+				case AssignmentOperatorType.BitwiseAnd:
+					return BinaryOperatorType.BitwiseAnd;
+				case AssignmentOperatorType.BitwiseOr:
+					return BinaryOperatorType.BitwiseOr;
+				case AssignmentOperatorType.ExclusiveOr:
+					return BinaryOperatorType.ExclusiveOr;
+				default:
+					throw new NotSupportedException("Invalid value for AssignmentOperatorType");
+			}
+		}
+		
+		public static ExpressionType GetLinqNodeType(AssignmentOperatorType op, bool checkForOverflow)
+		{
+			switch (op) {
+				case AssignmentOperatorType.Assign:
+					return ExpressionType.Assign;
+				case AssignmentOperatorType.Add:
+					return checkForOverflow ? ExpressionType.AddAssignChecked : ExpressionType.AddAssign;
+				case AssignmentOperatorType.Subtract:
+					return checkForOverflow ? ExpressionType.SubtractAssignChecked : ExpressionType.SubtractAssign;
+				case AssignmentOperatorType.Multiply:
+					return checkForOverflow ? ExpressionType.MultiplyAssignChecked : ExpressionType.MultiplyAssign;
+				case AssignmentOperatorType.Divide:
+					return ExpressionType.DivideAssign;
+				case AssignmentOperatorType.Modulus:
+					return ExpressionType.ModuloAssign;
+				case AssignmentOperatorType.ShiftLeft:
+					return ExpressionType.LeftShiftAssign;
+				case AssignmentOperatorType.ShiftRight:
+					return ExpressionType.RightShiftAssign;
+				case AssignmentOperatorType.BitwiseAnd:
+					return ExpressionType.AndAssign;
+				case AssignmentOperatorType.BitwiseOr:
+					return ExpressionType.OrAssign;
+				case AssignmentOperatorType.ExclusiveOr:
+					return ExpressionType.ExclusiveOrAssign;
+				default:
+					throw new NotSupportedException("Invalid value for AssignmentOperatorType");
+			}
+		}
+
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+	
+	public enum AssignmentOperatorType
+	{
+		/// <summary>left = right</summary>
+		Assign,
+		
+		/// <summary>left += right</summary>
+		Add,
+		/// <summary>left -= right</summary>
+		Subtract,
+		/// <summary>left *= right</summary>
+		Multiply,
+		/// <summary>left /= right</summary>
+		Divide,
+		/// <summary>left %= right</summary>
+		Modulus,
+		
+		/// <summary>left <<= right</summary>
+		ShiftLeft,
+		/// <summary>left >>= right</summary>
+		ShiftRight,
+		
+		/// <summary>left &= right</summary>
+		BitwiseAnd,
+		/// <summary>left |= right</summary>
+		BitwiseOr,
+		/// <summary>left ^= right</summary>
+		ExclusiveOr,
+		
+		/// <summary>Any operator (for pattern matching)</summary>
+		Any
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/BaseReferenceExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/BaseReferenceExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/BaseReferenceExpression.cs	(revision 11807)
@@ -0,0 +1,71 @@
+﻿// 
+// BaseReferenceExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// base
+	/// </summary>
+	public class BaseReferenceExpression : Expression
+	{
+		public TextLocation Location {
+			get;
+			set;
+		}
+		
+		public override TextLocation StartLocation {
+			get {
+				return Location;
+			}
+		}
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (Location.Line, Location.Column + "base".Length);
+			}
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitBaseReferenceExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitBaseReferenceExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitBaseReferenceExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			BaseReferenceExpression o = other as BaseReferenceExpression;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/BinaryOperatorExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/BinaryOperatorExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/BinaryOperatorExpression.cs	(revision 11807)
@@ -0,0 +1,325 @@
+﻿// 
+// BinaryOperatorExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq.Expressions;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Left Operator Right
+	/// </summary>
+	public class BinaryOperatorExpression : Expression
+	{
+		public readonly static TokenRole BitwiseAndRole = new TokenRole ("&");
+		public readonly static TokenRole BitwiseOrRole = new TokenRole ("|");
+		public readonly static TokenRole ConditionalAndRole = new TokenRole ("&&");
+		public readonly static TokenRole ConditionalOrRole = new TokenRole ("||");
+		public readonly static TokenRole ExclusiveOrRole = new TokenRole ("^");
+		public readonly static TokenRole GreaterThanRole = new TokenRole (">");
+		public readonly static TokenRole GreaterThanOrEqualRole = new TokenRole (">=");
+		public readonly static TokenRole EqualityRole = new TokenRole ("==");
+		public readonly static TokenRole InEqualityRole = new TokenRole ("!=");
+		public readonly static TokenRole LessThanRole = new TokenRole ("<");
+		public readonly static TokenRole LessThanOrEqualRole = new TokenRole ("<=");
+		public readonly static TokenRole AddRole = new TokenRole ("+");
+		public readonly static TokenRole SubtractRole = new TokenRole ("-");
+		public readonly static TokenRole MultiplyRole = new TokenRole ("*");
+		public readonly static TokenRole DivideRole = new TokenRole ("/");
+		public readonly static TokenRole ModulusRole = new TokenRole ("%");
+		public readonly static TokenRole ShiftLeftRole = new TokenRole ("<<");
+		public readonly static TokenRole ShiftRightRole = new TokenRole (">>");
+		public readonly static TokenRole NullCoalescingRole = new TokenRole ("??");
+		
+		public readonly static Role<Expression> LeftRole = new Role<Expression>("Left", Expression.Null);
+		public readonly static Role<Expression> RightRole = new Role<Expression>("Right", Expression.Null);
+		
+		public BinaryOperatorExpression()
+		{
+		}
+		
+		public BinaryOperatorExpression(Expression left, BinaryOperatorType op, Expression right)
+		{
+			this.Left = left;
+			this.Operator = op;
+			this.Right = right;
+		}
+		
+		public BinaryOperatorType Operator {
+			get;
+			set;
+		}
+		
+		public Expression Left {
+			get { return GetChildByRole (LeftRole); }
+			set { SetChildByRole(LeftRole, value); }
+		}
+		
+		public CSharpTokenNode OperatorToken {
+			get { return GetChildByRole (GetOperatorRole (Operator)); }
+		}
+		
+		public Expression Right {
+			get { return GetChildByRole (RightRole); }
+			set { SetChildByRole (RightRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitBinaryOperatorExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitBinaryOperatorExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitBinaryOperatorExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			BinaryOperatorExpression o = other as BinaryOperatorExpression;
+			return o != null && (this.Operator == BinaryOperatorType.Any || this.Operator == o.Operator)
+				&& this.Left.DoMatch(o.Left, match) && this.Right.DoMatch(o.Right, match);
+		}
+		
+		public static TokenRole GetOperatorRole (BinaryOperatorType op)
+		{
+			switch (op) {
+				case BinaryOperatorType.BitwiseAnd:
+					return BitwiseAndRole;
+				case BinaryOperatorType.BitwiseOr:
+					return BitwiseOrRole;
+				case BinaryOperatorType.ConditionalAnd:
+					return ConditionalAndRole;
+				case BinaryOperatorType.ConditionalOr:
+					return ConditionalOrRole;
+				case BinaryOperatorType.ExclusiveOr:
+					return ExclusiveOrRole;
+				case BinaryOperatorType.GreaterThan:
+					return GreaterThanRole;
+				case BinaryOperatorType.GreaterThanOrEqual:
+					return GreaterThanOrEqualRole;
+				case BinaryOperatorType.Equality:
+					return EqualityRole;
+				case BinaryOperatorType.InEquality:
+					return InEqualityRole;
+				case BinaryOperatorType.LessThan:
+					return LessThanRole;
+				case BinaryOperatorType.LessThanOrEqual:
+					return LessThanOrEqualRole;
+				case BinaryOperatorType.Add:
+					return AddRole;
+				case BinaryOperatorType.Subtract:
+					return SubtractRole;
+				case BinaryOperatorType.Multiply:
+					return MultiplyRole;
+				case BinaryOperatorType.Divide:
+					return DivideRole;
+				case BinaryOperatorType.Modulus:
+					return ModulusRole;
+				case BinaryOperatorType.ShiftLeft:
+					return ShiftLeftRole;
+				case BinaryOperatorType.ShiftRight:
+					return ShiftRightRole;
+				case BinaryOperatorType.NullCoalescing:
+					return NullCoalescingRole;
+				default:
+					throw new NotSupportedException("Invalid value for BinaryOperatorType");
+			}
+		}
+		
+		public static ExpressionType GetLinqNodeType(BinaryOperatorType op, bool checkForOverflow)
+		{
+			switch (op) {
+				case BinaryOperatorType.BitwiseAnd:
+					return ExpressionType.And;
+				case BinaryOperatorType.BitwiseOr:
+					return ExpressionType.Or;
+				case BinaryOperatorType.ConditionalAnd:
+					return ExpressionType.AndAlso;
+				case BinaryOperatorType.ConditionalOr:
+					return ExpressionType.OrElse;
+				case BinaryOperatorType.ExclusiveOr:
+					return ExpressionType.ExclusiveOr;
+				case BinaryOperatorType.GreaterThan:
+					return ExpressionType.GreaterThan;
+				case BinaryOperatorType.GreaterThanOrEqual:
+					return ExpressionType.GreaterThanOrEqual;
+				case BinaryOperatorType.Equality:
+					return ExpressionType.Equal;
+				case BinaryOperatorType.InEquality:
+					return ExpressionType.NotEqual;
+				case BinaryOperatorType.LessThan:
+					return ExpressionType.LessThan;
+				case BinaryOperatorType.LessThanOrEqual:
+					return ExpressionType.LessThanOrEqual;
+				case BinaryOperatorType.Add:
+					return checkForOverflow ? ExpressionType.AddChecked : ExpressionType.Add;
+				case BinaryOperatorType.Subtract:
+					return checkForOverflow ? ExpressionType.SubtractChecked : ExpressionType.Subtract;
+				case BinaryOperatorType.Multiply:
+					return checkForOverflow ? ExpressionType.MultiplyChecked : ExpressionType.Multiply;
+				case BinaryOperatorType.Divide:
+					return ExpressionType.Divide;
+				case BinaryOperatorType.Modulus:
+					return ExpressionType.Modulo;
+				case BinaryOperatorType.ShiftLeft:
+					return ExpressionType.LeftShift;
+				case BinaryOperatorType.ShiftRight:
+					return ExpressionType.RightShift;
+				case BinaryOperatorType.NullCoalescing:
+					return ExpressionType.Coalesce;
+				default:
+					throw new NotSupportedException("Invalid value for BinaryOperatorType");
+			}
+		}
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+	
+	public enum BinaryOperatorType
+	{
+		/// <summary>
+		/// Any binary operator (used in pattern matching)
+		/// </summary>
+		Any,
+		
+		// We avoid 'logical or' on purpose, because it's not clear if that refers to the bitwise
+		// or to the short-circuiting (conditional) operator:
+		// MCS and old NRefactory used bitwise='|', logical='||'
+		// but the C# spec uses logical='|', conditional='||'
+		/// <summary>left &amp; right</summary>
+		BitwiseAnd,
+		/// <summary>left | right</summary>
+		BitwiseOr,
+		/// <summary>left &amp;&amp; right</summary>
+		ConditionalAnd,
+		/// <summary>left || right</summary>
+		ConditionalOr,
+		/// <summary>left ^ right</summary>
+		ExclusiveOr,
+		
+		/// <summary>left &gt; right</summary>
+		GreaterThan,
+		/// <summary>left &gt;= right</summary>
+		GreaterThanOrEqual,
+		/// <summary>left == right</summary>
+		Equality,
+		/// <summary>left != right</summary>
+		InEquality,
+		/// <summary>left &lt; right</summary>
+		LessThan,
+		/// <summary>left &lt;= right</summary>
+		LessThanOrEqual,
+		
+		/// <summary>left + right</summary>
+		Add,
+		/// <summary>left - right</summary>
+		Subtract,
+		/// <summary>left * right</summary>
+		Multiply,
+		/// <summary>left / right</summary>
+		Divide,
+		/// <summary>left % right</summary>
+		Modulus,
+		
+		/// <summary>left &lt;&lt; right</summary>
+		ShiftLeft,
+		/// <summary>left &gt;&gt; right</summary>
+		ShiftRight,
+		
+		/// <summary>left ?? right</summary>
+		NullCoalescing
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/CastExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/CastExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/CastExpression.cs	(revision 11807)
@@ -0,0 +1,152 @@
+﻿// 
+// CastExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// (CastTo)Expression
+	/// </summary>
+	public class CastExpression : Expression
+	{
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CastExpression ()
+		{
+		}
+
+		public CastExpression (AstType castToType, Expression expression)
+		{
+			AddChild (castToType, Roles.Type);
+			AddChild (expression, Roles.Expression);
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCastExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCastExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCastExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CastExpression o = other as CastExpression;
+			return o != null && this.Type.DoMatch(o.Type, match) && this.Expression.DoMatch(o.Expression, match);
+		}
+
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/CheckedExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/CheckedExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/CheckedExpression.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// 
+// CheckedExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// checked(Expression)
+	/// </summary>
+	public class CheckedExpression : Expression
+	{
+		public readonly static TokenRole CheckedKeywordRole = new TokenRole ("checked");
+		
+		public CSharpTokenNode CheckedToken {
+			get { return GetChildByRole (CheckedKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole(Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public CheckedExpression ()
+		{
+		}
+		
+		public CheckedExpression (Expression expression)
+		{
+			AddChild (expression, Roles.Expression);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCheckedExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCheckedExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCheckedExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CheckedExpression o = other as CheckedExpression;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ConditionalExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ConditionalExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ConditionalExpression.cs	(revision 11807)
@@ -0,0 +1,162 @@
+﻿// 
+// ConditionalExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Condition ? TrueExpression : FalseExpression
+	/// </summary>
+	public class ConditionalExpression : Expression
+	{
+		public readonly static Role<Expression> ConditionRole = Roles.Condition;
+		public readonly static TokenRole QuestionMarkRole = new TokenRole("?");
+		public readonly static Role<Expression> TrueRole = new Role<Expression>("True", Expression.Null);
+		public readonly static TokenRole ColonRole = Roles.Colon;
+		public readonly static Role<Expression> FalseRole = new Role<Expression>("False", Expression.Null);
+		
+		public Expression Condition {
+			get { return GetChildByRole(ConditionRole); }
+			set { SetChildByRole(ConditionRole, value); }
+		}
+		
+		public CSharpTokenNode QuestionMarkToken {
+			get { return GetChildByRole (QuestionMarkRole); }
+		}
+		
+		public Expression TrueExpression {
+			get { return GetChildByRole(TrueRole); }
+			set { SetChildByRole(TrueRole, value); }
+		}
+		
+		public CSharpTokenNode ColonToken {
+			get { return GetChildByRole (ColonRole); }
+		}
+		
+		public Expression FalseExpression {
+			get { return GetChildByRole(FalseRole); }
+			set { SetChildByRole(FalseRole, value); }
+		}
+		
+		public ConditionalExpression ()
+		{
+		}
+		
+		public ConditionalExpression (Expression condition, Expression trueExpression, Expression falseExpression)
+		{
+			AddChild (condition, ConditionRole);
+			AddChild (trueExpression, TrueRole);
+			AddChild (falseExpression, FalseRole);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitConditionalExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitConditionalExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitConditionalExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ConditionalExpression o = other as ConditionalExpression;
+			return o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueExpression.DoMatch(o.TrueExpression, match) && this.FalseExpression.DoMatch(o.FalseExpression, match);
+		}
+
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/DefaultValueExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/DefaultValueExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/DefaultValueExpression.cs	(revision 11807)
@@ -0,0 +1,84 @@
+﻿// 
+// DefaultValueExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// default(Type)
+	/// </summary>
+	public class DefaultValueExpression : Expression
+	{
+		public readonly static TokenRole DefaultKeywordRole = new TokenRole ("default");
+
+		public CSharpTokenNode DefaultToken {
+			get { return GetChildByRole (DefaultKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public DefaultValueExpression ()
+		{
+		}
+		
+		public DefaultValueExpression (AstType type)
+		{
+			AddChild (type, Roles.Type);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitDefaultValueExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitDefaultValueExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitDefaultValueExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			DefaultValueExpression o = other as DefaultValueExpression;
+			return o != null && this.Type.DoMatch(o.Type, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/DirectionExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/DirectionExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/DirectionExpression.cs	(revision 11807)
@@ -0,0 +1,89 @@
+﻿// 
+// DirectionExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum FieldDirection
+	{
+		None,
+		Out,
+		Ref
+	}
+	
+	/// <summary>
+	/// ref Expression
+	/// </summary>
+	public class DirectionExpression : Expression
+	{
+		public readonly static TokenRole RefKeywordRole = new TokenRole ("ref");
+		public readonly static TokenRole OutKeywordRole = new TokenRole ("out");
+		
+		public FieldDirection FieldDirection {
+			get;
+			set;
+		}
+		
+		public CSharpTokenNode FieldDirectionToken {
+			get { return FieldDirection == ICSharpCode.NRefactory.CSharp.FieldDirection.Ref ? GetChildByRole (RefKeywordRole) : GetChildByRole (OutKeywordRole); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public DirectionExpression ()
+		{
+		}
+		
+		public DirectionExpression (FieldDirection direction, Expression expression)
+		{
+			this.FieldDirection = direction;
+			AddChild (expression, Roles.Expression);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitDirectionExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitDirectionExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitDirectionExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			DirectionExpression o = other as DirectionExpression;
+			return o != null && this.FieldDirection == o.FieldDirection && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ErrorExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ErrorExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ErrorExpression.cs	(revision 11807)
@@ -0,0 +1,129 @@
+﻿// 
+// ErrorExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc.
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[Obsolete("This class is obsolete. Remove all referencing code.")]
+	public class EmptyExpression : AstNode
+	{
+		#region implemented abstract members of AstNode
+
+		public override void AcceptVisitor(IAstVisitor visitor)
+		{
+			throw new NotImplementedException();
+		}
+
+		public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
+		{
+			throw new NotImplementedException();
+		}
+
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			throw new NotImplementedException();
+		}
+
+		protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
+		{
+			throw new NotImplementedException();
+		}
+
+		public override NodeType NodeType {
+			get {
+				throw new NotImplementedException();
+			}
+		}
+
+		#endregion
+
+
+	}
+
+	public class ErrorExpression : Expression
+	{
+		TextLocation location;
+
+		public override TextLocation StartLocation {
+			get {
+				return location;
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return location;
+			}
+		}
+
+		public string Error {
+			get;
+			private set;
+		}
+
+		public ErrorExpression ()
+		{
+		}
+
+		public ErrorExpression (TextLocation location)
+		{
+			this.location = location;
+		}
+
+		public ErrorExpression (string error)
+		{
+			this.Error = error;
+		}
+
+		public ErrorExpression (string error, TextLocation location)
+		{
+			this.location = location;
+			this.Error = error;
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitErrorNode(this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitErrorNode(this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitErrorNode(this, data);
+		}
+
+		protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+		{
+			var o = other as ErrorExpression;
+			return o != null;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/Expression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/Expression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/Expression.cs	(revision 11807)
@@ -0,0 +1,230 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Base class for expressions.
+	/// </summary>
+	/// <remarks>
+	/// This class is useful even though it doesn't provide any additional functionality:
+	/// It can be used to communicate more information in APIs, e.g. "this subnode will always be an expression"
+	/// </remarks>
+	public abstract class Expression : AstNode
+	{
+		#region Null
+		public new static readonly Expression Null = new NullExpression ();
+		
+		sealed class NullExpression : Expression
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+		
+		#region PatternPlaceholder
+		public static implicit operator Expression(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : Expression, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder(this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder(this, child);
+			}
+			
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Expression;
+			}
+		}
+		
+		public new Expression Clone()
+		{
+			return (Expression)base.Clone();
+		}
+
+		public Expression ReplaceWith(Func<Expression, Expression> replaceFunction)
+		{
+			if (replaceFunction == null)
+				throw new ArgumentNullException("replaceFunction");
+			return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node));
+		}
+		
+		#region Builder methods
+		/// <summary>
+		/// Builds an member reference expression using this expression as target.
+		/// </summary>
+		public virtual MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+		
+		/// <summary>
+		/// Builds an indexer expression using this expression as target.
+		/// </summary>
+		public virtual IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = this;
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+		
+		/// <summary>
+		/// Builds an indexer expression using this expression as target.
+		/// </summary>
+		public virtual IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = this;
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this expression as target.
+		/// </summary>
+		public virtual InvocationExpression Invoke(string methodName, IEnumerable<Expression> arguments)
+		{
+			return Invoke(methodName, null, arguments);
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this expression as target.
+		/// </summary>
+		public virtual InvocationExpression Invoke(string methodName, params Expression[] arguments)
+		{
+			return Invoke(methodName, null, arguments);
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this expression as target.
+		/// </summary>
+		public virtual InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = this;
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this expression as target.
+		/// </summary>
+		public virtual InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = this;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+		
+		/// <summary>
+		/// Builds an invocation expression using this expression as target.
+		/// </summary>
+		public virtual InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = this;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+		
+		public virtual CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = this };
+		}
+		
+		public virtual AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = this };
+		}
+		
+		public virtual IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = this };
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IdentifierExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IdentifierExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IdentifierExpression.cs	(revision 11807)
@@ -0,0 +1,93 @@
+﻿// 
+// IdentifierExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class IdentifierExpression : Expression
+	{
+		public IdentifierExpression()
+		{
+		}
+		
+		public IdentifierExpression(string identifier)
+		{
+			this.Identifier = identifier;
+		}
+		
+		public IdentifierExpression(string identifier, TextLocation location)
+		{
+			SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (identifier, location));
+		}
+		
+//		public Identifier IdentifierToken {
+//			get { return GetChildByRole (Roles.Identifier); }
+//		}
+		
+		public string Identifier {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+
+		public Identifier IdentifierToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+
+		public AstNodeCollection<AstType> TypeArguments {
+			get { return GetChildrenByRole (Roles.TypeArgument); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitIdentifierExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitIdentifierExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitIdentifierExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			IdentifierExpression o = other as IdentifierExpression;
+			return o != null && MatchString(this.Identifier, o.Identifier) && this.TypeArguments.DoMatch(o.TypeArguments, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IndexerExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IndexerExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IndexerExpression.cs	(revision 11807)
@@ -0,0 +1,92 @@
+﻿// 
+// IndexerExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Target[Arguments]
+	/// </summary>
+	public class IndexerExpression : Expression
+	{
+		public Expression Target {
+			get { return GetChildByRole (Roles.TargetExpression); }
+			set { SetChildByRole(Roles.TargetExpression, value); }
+		}
+		
+		public CSharpTokenNode LBracketToken {
+			get { return GetChildByRole (Roles.LBracket); }
+		}
+		
+		public AstNodeCollection<Expression> Arguments {
+			get { return GetChildrenByRole<Expression>(Roles.Argument); }
+		}
+		
+		public CSharpTokenNode RBracketToken {
+			get { return GetChildByRole (Roles.RBracket); }
+		}
+		
+		public IndexerExpression ()
+		{
+		}
+		
+		public IndexerExpression (Expression target, IEnumerable<Expression> arguments)
+		{
+			AddChild (target, Roles.TargetExpression);
+			if (arguments != null) {
+				foreach (var arg in arguments) {
+					AddChild (arg, Roles.Argument);
+				}
+			}
+		}
+		
+		public IndexerExpression (Expression target, params Expression[] arguments) : this (target, (IEnumerable<Expression>)arguments)
+		{
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitIndexerExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitIndexerExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitIndexerExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			IndexerExpression o = other as IndexerExpression;
+			return o != null && this.Target.DoMatch(o.Target, match) && this.Arguments.DoMatch(o.Arguments, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/InvocationExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/InvocationExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/InvocationExpression.cs	(revision 11807)
@@ -0,0 +1,92 @@
+﻿// 
+// InvocationExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Target(Arguments)
+	/// </summary>
+	public class InvocationExpression : Expression
+	{
+		public Expression Target {
+			get { return GetChildByRole (Roles.TargetExpression); }
+			set { SetChildByRole(Roles.TargetExpression, value); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<Expression> Arguments {
+			get { return GetChildrenByRole<Expression>(Roles.Argument); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitInvocationExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitInvocationExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitInvocationExpression (this, data);
+		}
+		
+		public InvocationExpression ()
+		{
+		}
+		
+		public InvocationExpression (Expression target, IEnumerable<Expression> arguments)
+		{
+			AddChild (target, Roles.TargetExpression);
+			if (arguments != null) {
+				foreach (var arg in arguments) {
+					AddChild (arg, Roles.Argument);
+				}
+			}
+		}
+		
+		public InvocationExpression (Expression target, params Expression[] arguments) : this (target, (IEnumerable<Expression>)arguments)
+		{
+		}	
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			InvocationExpression o = other as InvocationExpression;
+			return o != null && this.Target.DoMatch(o.Target, match) && this.Arguments.DoMatch(o.Arguments, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IsExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IsExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/IsExpression.cs	(revision 11807)
@@ -0,0 +1,150 @@
+﻿// 
+// TypeOfIsExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Expression is Type
+	/// </summary>
+	public class IsExpression : Expression
+	{
+		public readonly static TokenRole IsKeywordRole = new TokenRole ("is");
+		
+		public Expression Expression {
+			get { return GetChildByRole(Roles.Expression); }
+			set { SetChildByRole(Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode IsToken {
+			get { return GetChildByRole (IsKeywordRole); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole(Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+
+		public IsExpression()
+		{
+		}
+
+		public IsExpression (Expression expression, AstType type)
+		{
+			AddChild (expression, Roles.Expression);
+			AddChild (type, Roles.Type);
+		}
+
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitIsExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitIsExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitIsExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			IsExpression o = other as IsExpression;
+			return o != null && this.Expression.DoMatch(o.Expression, match) && this.Type.DoMatch(o.Type, match);
+		}
+
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/LambdaExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/LambdaExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/LambdaExpression.cs	(revision 11807)
@@ -0,0 +1,89 @@
+﻿// 
+// LambdaExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// [async] Parameters => Body
+	/// </summary>
+	public class LambdaExpression : Expression
+	{
+		public readonly static TokenRole AsyncModifierRole = new TokenRole ("async");
+		public readonly static TokenRole ArrowRole = new TokenRole ("=>");
+		public static readonly Role<AstNode> BodyRole = new Role<AstNode>("Body", AstNode.Null);
+		
+		bool isAsync;
+		
+		public bool IsAsync {
+			get { return isAsync; }
+			set { ThrowIfFrozen(); isAsync = value; }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+
+		public CSharpTokenNode ArrowToken {
+			get { return GetChildByRole (ArrowRole); }
+		}
+		
+		public AstNode Body {
+			get { return GetChildByRole (BodyRole); }
+			set { SetChildByRole (BodyRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitLambdaExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitLambdaExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitLambdaExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			LambdaExpression o = other as LambdaExpression;
+			return o != null && this.IsAsync == o.IsAsync && this.Parameters.DoMatch(o.Parameters, match) && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/MemberReferenceExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/MemberReferenceExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/MemberReferenceExpression.cs	(revision 11807)
@@ -0,0 +1,119 @@
+﻿// 
+// MemberReferenceExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Target.MemberName
+	/// </summary>
+	public class MemberReferenceExpression : Expression
+	{
+		public Expression Target {
+			get {
+				return GetChildByRole(Roles.TargetExpression);
+			}
+			set {
+				SetChildByRole(Roles.TargetExpression, value);
+			}
+		}
+
+		public CSharpTokenNode DotToken {
+			get { return GetChildByRole (Roles.Dot); }
+		}
+		
+		public string MemberName {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier MemberNameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode LChevronToken {
+			get { return GetChildByRole (Roles.LChevron); }
+		}
+		
+		public AstNodeCollection<AstType> TypeArguments {
+			get { return GetChildrenByRole (Roles.TypeArgument); }
+		}
+		
+		public CSharpTokenNode RChevronToken {
+			get { return GetChildByRole (Roles.RChevron); }
+		}
+		
+		public MemberReferenceExpression ()
+		{
+		}
+		
+		public MemberReferenceExpression (Expression target, string memberName, IEnumerable<AstType> arguments = null)
+		{
+			AddChild (target, Roles.TargetExpression);
+			MemberName = memberName;
+			if (arguments != null) {
+				foreach (var arg in arguments) {
+					AddChild (arg, Roles.TypeArgument);
+				}
+			}
+		}
+		
+		public MemberReferenceExpression (Expression target, string memberName, params AstType[] arguments) : this (target, memberName, (IEnumerable<AstType>)arguments)
+		{
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitMemberReferenceExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitMemberReferenceExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitMemberReferenceExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			MemberReferenceExpression o = other as MemberReferenceExpression;
+			return o != null && this.Target.DoMatch(o.Target, match) && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NamedArgumentExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NamedArgumentExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NamedArgumentExpression.cs	(revision 11807)
@@ -0,0 +1,87 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents a named argument passed to a method or attribute.
+	/// name: expression
+	/// </summary>
+	public class NamedArgumentExpression : Expression
+	{
+		public NamedArgumentExpression()
+		{
+		}
+		
+		public NamedArgumentExpression(string name, Expression expression)
+		{
+			this.Name = name;
+			this.Expression = expression;
+		}
+		
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole(Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode ColonToken {
+			get { return GetChildByRole (Roles.Colon); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitNamedArgumentExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitNamedArgumentExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitNamedArgumentExpression(this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			NamedArgumentExpression o = other as NamedArgumentExpression;
+			return o != null && MatchString(this.Name, o.Name) && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NamedExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NamedExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NamedExpression.cs	(revision 11807)
@@ -0,0 +1,97 @@
+﻿// 
+// NamedExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// name = expression
+	/// This isn't the same as 'assign' even though it has the same syntax.
+	/// This expression is used in object initializers and for named attribute arguments [Attr(FieldName = value)].
+	/// </summary>
+	public class NamedExpression : Expression
+	{
+		public NamedExpression()
+		{
+		}
+		
+		public NamedExpression (string name, Expression expression)
+		{
+			this.Name = name;
+			this.Expression = expression;
+		}
+		
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole(Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode AssignToken {
+			get { return GetChildByRole (Roles.Assign); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitNamedExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitNamedExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitNamedExpression(this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			var o = other as NamedExpression;
+			return o != null && MatchString(this.Name, o.Name) && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NullReferenceExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NullReferenceExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/NullReferenceExpression.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// 
+// NullReferenceExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// null
+	/// </summary>
+	public class NullReferenceExpression : Expression
+	{
+		TextLocation location;
+		public override TextLocation StartLocation {
+			get {
+				return location;
+			}
+		}
+		
+		internal void SetStartLocation(TextLocation value)
+		{
+			ThrowIfFrozen();
+			this.location = value;
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (location.Line, location.Column + "null".Length);
+			}
+		}
+		
+		public NullReferenceExpression ()
+		{
+		}
+		
+		public NullReferenceExpression (TextLocation location)
+		{
+			this.location = location;
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitNullReferenceExpression (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitNullReferenceExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitNullReferenceExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			NullReferenceExpression o = other as NullReferenceExpression;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ObjectCreateExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ObjectCreateExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ObjectCreateExpression.cs	(revision 11807)
@@ -0,0 +1,104 @@
+﻿// 
+// ObjectCreateExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// new Type(Arguments) { Initializer }
+	/// </summary>
+	public class ObjectCreateExpression : Expression
+	{
+		public readonly static TokenRole NewKeywordRole = new TokenRole ("new");
+		public readonly static Role<ArrayInitializerExpression> InitializerRole = ArrayCreateExpression.InitializerRole;
+		
+		public CSharpTokenNode NewToken {
+			get { return GetChildByRole (NewKeywordRole); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<Expression> Arguments {
+			get { return GetChildrenByRole (Roles.Argument); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public ArrayInitializerExpression Initializer {
+			get { return GetChildByRole (InitializerRole); }
+			set { SetChildByRole (InitializerRole, value); }
+		}
+		
+		public ObjectCreateExpression ()
+		{
+		}
+		
+		public ObjectCreateExpression (AstType type, IEnumerable<Expression> arguments = null)
+		{
+			AddChild (type, Roles.Type);
+			if (arguments != null) {
+				foreach (var arg in arguments) {
+					AddChild (arg, Roles.Argument);
+				}
+			}
+		}
+		
+		public ObjectCreateExpression (AstType type, params Expression[] arguments) : this (type, (IEnumerable<Expression>)arguments)
+		{
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitObjectCreateExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitObjectCreateExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitObjectCreateExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ObjectCreateExpression o = other as ObjectCreateExpression;
+			return o != null && this.Type.DoMatch(o.Type, match) && this.Arguments.DoMatch(o.Arguments, match) && this.Initializer.DoMatch(o.Initializer, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ParenthesizedExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ParenthesizedExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ParenthesizedExpression.cs	(revision 11807)
@@ -0,0 +1,98 @@
+﻿// 
+// ParenthesizedExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// ( Expression )
+	/// </summary>
+	public class ParenthesizedExpression : Expression
+	{
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public ParenthesizedExpression()
+		{
+		}
+		
+		public ParenthesizedExpression(Expression expr)
+		{
+			Expression = expr;
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitParenthesizedExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitParenthesizedExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitParenthesizedExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ParenthesizedExpression o = other as ParenthesizedExpression;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+		
+		/// <summary>
+		/// Gets whether the expression acts like a parenthesized expression,
+		/// i.e. whether information about the expected type (for lambda type inference) flows
+		/// into the inner expression.
+		/// </summary>
+		/// <returns>Returns true for ParenthesizedExpression, CheckedExpression or UncheckedExpression; false otherwise.</returns>
+		public static bool ActsAsParenthesizedExpression(AstNode expression)
+		{
+			return expression is ParenthesizedExpression || expression is CheckedExpression || expression is UncheckedExpression;
+		}
+		
+		/// <summary>
+		/// Unpacks the given expression if it is a ParenthesizedExpression, CheckedExpression or UncheckedExpression.
+		/// </summary>
+		public static Expression UnpackParenthesizedExpression(Expression expr)
+		{
+			while (ActsAsParenthesizedExpression(expr))
+				expr = expr.GetChildByRole(Roles.Expression);
+			return expr;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/PointerReferenceExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/PointerReferenceExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/PointerReferenceExpression.cs	(revision 11807)
@@ -0,0 +1,90 @@
+﻿// 
+// PointerReferenceExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Target->MemberName
+	/// </summary>
+	public class PointerReferenceExpression : Expression
+	{
+		public readonly static TokenRole ArrowRole = new TokenRole ("->");
+		
+		public Expression Target {
+			get { return GetChildByRole (Roles.TargetExpression); }
+			set { SetChildByRole(Roles.TargetExpression, value); }
+		}
+		
+		public CSharpTokenNode ArrowToken {
+			get { return GetChildByRole (ArrowRole); }
+		}
+		
+		public string MemberName {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier MemberNameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public AstNodeCollection<AstType> TypeArguments {
+			get { return GetChildrenByRole (Roles.TypeArgument); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitPointerReferenceExpression (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitPointerReferenceExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitPointerReferenceExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			PointerReferenceExpression o = other as PointerReferenceExpression;
+			return o != null && MatchString(this.MemberName, o.MemberName) && this.TypeArguments.DoMatch(o.TypeArguments, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/PrimitiveExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/PrimitiveExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/PrimitiveExpression.cs	(revision 11807)
@@ -0,0 +1,162 @@
+﻿// 
+// PrimitiveExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents a literal value.
+	/// </summary>
+	public class PrimitiveExpression : Expression
+	{
+		public static readonly object AnyValue = new object();
+		
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get {
+				return startLocation;
+			}
+		}
+		
+		internal void SetStartLocation(TextLocation value)
+		{
+			ThrowIfFrozen();
+			this.startLocation = value;
+			this.endLocation = null;
+		}
+		
+		string literalValue;
+		TextLocation? endLocation;
+		public override TextLocation EndLocation {
+			get {
+				if (!endLocation.HasValue) {
+					endLocation = value is string ? AdvanceLocation (StartLocation, literalValue ?? "") :
+						new TextLocation (StartLocation.Line, StartLocation.Column + (literalValue ?? "").Length);
+				}
+				return endLocation.Value;
+			}
+		}
+		
+		object value;
+		
+		public object Value {
+			get { return this.value; }
+			set {
+				ThrowIfFrozen();
+				this.value = value;
+				literalValue = null;
+			}
+		}
+		
+		/// <remarks>Never returns null.</remarks>
+		public string LiteralValue {
+			get { return literalValue ?? ""; }
+		}
+		
+		/// <remarks>Can be null.</remarks>
+		public string UnsafeLiteralValue {
+			get { return literalValue; }
+		}
+		
+		public void SetValue(object value, string literalValue)
+		{
+			if (value == null)
+				throw new ArgumentNullException();
+			ThrowIfFrozen();
+			this.value = value;
+			this.literalValue = literalValue;
+		}
+		
+		public PrimitiveExpression (object value)
+		{
+			this.Value = value;
+			this.literalValue = null;
+		}
+		
+		public PrimitiveExpression (object value, string literalValue)
+		{
+			this.Value = value;
+			this.literalValue = literalValue;
+		}
+		
+		public PrimitiveExpression (object value, TextLocation startLocation, string literalValue)
+		{
+			this.Value = value;
+			this.startLocation = startLocation;
+			this.literalValue = literalValue;
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitPrimitiveExpression (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitPrimitiveExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitPrimitiveExpression (this, data);
+		}
+
+		unsafe static TextLocation AdvanceLocation(TextLocation startLocation, string str)
+		{
+			int line = startLocation.Line;
+			int col  = startLocation.Column;
+			fixed (char* start = str) {
+				char* p = start;
+				char* endPtr = start + str.Length;
+				while (p < endPtr) {
+					var nl = NewLine.GetDelimiterLength(*p, () => {
+						char* nextp = p + 1;
+						if (nextp < endPtr)
+							return *nextp;
+						return '\0';
+					});
+					if (nl > 0) {
+						line++;
+						col = 1;
+						if (nl == 2)
+							p++;
+					} else {
+						col++;
+					}
+					p++;
+				}
+			}
+			return new TextLocation (line, col);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			PrimitiveExpression o = other as PrimitiveExpression;
+			return o != null && (this.Value == AnyValue || object.Equals(this.Value, o.Value));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/QueryExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/QueryExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/QueryExpression.cs	(revision 11807)
@@ -0,0 +1,655 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class QueryExpression : Expression
+	{
+		public static readonly Role<QueryClause> ClauseRole = new Role<QueryClause>("Clause");
+		
+		#region Null
+		public new static readonly QueryExpression Null = new NullQueryExpression ();
+		
+		sealed class NullQueryExpression : QueryExpression
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+		
+		public AstNodeCollection<QueryClause> Clauses {
+			get { return GetChildrenByRole(ClauseRole); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryExpression o = other as QueryExpression;
+			return o != null && !o.IsNull && this.Clauses.DoMatch(o.Clauses, match);
+		}
+
+		#region Builder methods
+		public override MemberReferenceExpression Member(string memberName)
+		{
+			return new MemberReferenceExpression { Target = this, MemberName = memberName };
+		}
+
+		public override IndexerExpression Indexer(IEnumerable<Expression> arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override IndexerExpression Indexer(params Expression[] arguments)
+		{
+			IndexerExpression expr = new IndexerExpression();
+			expr.Target = new ParenthesizedExpression(this);
+			expr.Arguments.AddRange(arguments);
+			return expr;
+		}
+
+		public override InvocationExpression Invoke(string methodName, IEnumerable<AstType> typeArguments, IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			MemberReferenceExpression mre = new MemberReferenceExpression();
+			mre.Target = new ParenthesizedExpression(this);
+			mre.MemberName = methodName;
+			mre.TypeArguments.AddRange(typeArguments);
+			ie.Target = mre;
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(IEnumerable<Expression> arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override InvocationExpression Invoke(params Expression[] arguments)
+		{
+			InvocationExpression ie = new InvocationExpression();
+			ie.Target = new ParenthesizedExpression(this);
+			ie.Arguments.AddRange(arguments);
+			return ie;
+		}
+
+		public override CastExpression CastTo(AstType type)
+		{
+			return new CastExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override AsExpression CastAs(AstType type)
+		{
+			return new AsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+
+		public override IsExpression IsType(AstType type)
+		{
+			return new IsExpression { Type = type,  Expression = new ParenthesizedExpression(this) };
+		}
+		#endregion
+	}
+	
+	public abstract class QueryClause : AstNode
+	{
+		public override NodeType NodeType {
+			get { return NodeType.QueryClause; }
+		}
+	}
+	
+	/// <summary>
+	/// Represents a query continuation.
+	/// "(from .. select ..) into Identifier" or "(from .. group .. by ..) into Identifier"
+	/// Note that "join .. into .." is not a query continuation!
+	/// 
+	/// This is always the first(!!) clause in a query expression.
+	/// The tree for "from a in b select c into d select e" looks like this:
+	/// new QueryExpression {
+	/// 	new QueryContinuationClause {
+	/// 		PrecedingQuery = new QueryExpression {
+	/// 			new QueryFromClause(a in b),
+	/// 			new QuerySelectClause(c)
+	/// 		},
+	/// 		Identifier = d
+	/// 	},
+	/// 	new QuerySelectClause(e)
+	/// }
+	/// </summary>
+	public class QueryContinuationClause : QueryClause
+	{
+		public static readonly Role<QueryExpression> PrecedingQueryRole = new Role<QueryExpression>("PrecedingQuery", QueryExpression.Null);
+		public static readonly TokenRole IntoKeywordRole = new TokenRole ("into");
+		
+		public QueryExpression PrecedingQuery {
+			get { return GetChildByRole(PrecedingQueryRole); }
+			set { SetChildByRole(PrecedingQueryRole, value); }
+		}
+		
+		public CSharpTokenNode IntoKeyword {
+			get { return GetChildByRole (IntoKeywordRole); }
+		}
+
+		public string Identifier {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier IdentifierToken {
+			get { return GetChildByRole (Roles.Identifier); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryContinuationClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryContinuationClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryContinuationClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryContinuationClause o = other as QueryContinuationClause;
+			return o != null && MatchString(this.Identifier, o.Identifier) && this.PrecedingQuery.DoMatch(o.PrecedingQuery, match);
+		}
+	}
+	
+	public class QueryFromClause : QueryClause
+	{
+		public static readonly TokenRole FromKeywordRole =  new TokenRole ("from");
+		public static readonly TokenRole InKeywordRole =  new TokenRole ("in");
+		
+		public CSharpTokenNode FromKeyword {
+			get { return GetChildByRole (FromKeywordRole); }
+		}
+
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public string Identifier {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier IdentifierToken {
+			get { return GetChildByRole(Roles.Identifier); }
+		}
+		
+		public CSharpTokenNode InKeyword {
+			get { return GetChildByRole (InKeywordRole); }
+		}
+
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryFromClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryFromClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryFromClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryFromClause o = other as QueryFromClause;
+			return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.Identifier, o.Identifier)
+				&& this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+	
+	public class QueryLetClause : QueryClause
+	{
+		public readonly static TokenRole LetKeywordRole = new TokenRole ("let");
+		
+		public CSharpTokenNode LetKeyword {
+			get { return GetChildByRole(LetKeywordRole); }
+		}
+		
+		public string Identifier {
+			get {
+				return GetChildByRole(Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier IdentifierToken {
+			get { return GetChildByRole(Roles.Identifier); }
+		}
+		
+		public CSharpTokenNode AssignToken {
+			get { return GetChildByRole(Roles.Assign); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole(Roles.Expression); }
+			set { SetChildByRole(Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryLetClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryLetClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryLetClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryLetClause o = other as QueryLetClause;
+			return o != null && MatchString(this.Identifier, o.Identifier) && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+	
+	
+	public class QueryWhereClause : QueryClause
+	{
+		public readonly static TokenRole WhereKeywordRole = new TokenRole ("where");
+
+		public CSharpTokenNode WhereKeyword {
+			get { return GetChildByRole (WhereKeywordRole); }
+		}
+		
+		public Expression Condition {
+			get { return GetChildByRole (Roles.Condition); }
+			set { SetChildByRole (Roles.Condition, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryWhereClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryWhereClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryWhereClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryWhereClause o = other as QueryWhereClause;
+			return o != null && this.Condition.DoMatch(o.Condition, match);
+		}
+	}
+	
+	/// <summary>
+	/// Represents a join or group join clause.
+	/// </summary>
+	public class QueryJoinClause : QueryClause
+	{
+		public static readonly TokenRole JoinKeywordRole = new TokenRole ("join");
+		public static readonly Role<AstType> TypeRole = Roles.Type;
+		public static readonly Role<Identifier> JoinIdentifierRole = Roles.Identifier;
+		public static readonly TokenRole InKeywordRole =  new TokenRole ("in");
+		public static readonly Role<Expression> InExpressionRole = Roles.Expression;
+		public static readonly TokenRole OnKeywordRole =  new TokenRole ("on");
+		public static readonly Role<Expression> OnExpressionRole = new Role<Expression>("OnExpression", Expression.Null);
+		public static readonly TokenRole EqualsKeywordRole =  new TokenRole ("equals");
+		public static readonly Role<Expression> EqualsExpressionRole = new Role<Expression>("EqualsExpression", Expression.Null);
+		public static readonly TokenRole IntoKeywordRole =  new TokenRole ("into");
+		public static readonly Role<Identifier> IntoIdentifierRole = new Role<Identifier>("IntoIdentifier", Identifier.Null);
+		
+		public bool IsGroupJoin {
+			get { return !string.IsNullOrEmpty(this.IntoIdentifier); }
+		}
+		
+		public CSharpTokenNode JoinKeyword {
+			get { return GetChildByRole (JoinKeywordRole); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (TypeRole); }
+			set { SetChildByRole (TypeRole, value); }
+		}
+		
+		public string JoinIdentifier {
+			get {
+				return GetChildByRole(JoinIdentifierRole).Name;
+			}
+			set {
+				SetChildByRole(JoinIdentifierRole, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier JoinIdentifierToken {
+			get { return GetChildByRole(JoinIdentifierRole); }
+		}
+		
+		public CSharpTokenNode InKeyword {
+			get { return GetChildByRole (InKeywordRole); }
+		}
+		
+		public Expression InExpression {
+			get { return GetChildByRole (InExpressionRole); }
+			set { SetChildByRole (InExpressionRole, value); }
+		}
+		
+		public CSharpTokenNode OnKeyword {
+			get { return GetChildByRole (OnKeywordRole); }
+		}
+		
+		public Expression OnExpression {
+			get { return GetChildByRole (OnExpressionRole); }
+			set { SetChildByRole (OnExpressionRole, value); }
+		}
+		
+		public CSharpTokenNode EqualsKeyword {
+			get { return GetChildByRole (EqualsKeywordRole); }
+		}
+		
+		public Expression EqualsExpression {
+			get { return GetChildByRole (EqualsExpressionRole); }
+			set { SetChildByRole (EqualsExpressionRole, value); }
+		}
+		
+		public CSharpTokenNode IntoKeyword {
+			get { return GetChildByRole (IntoKeywordRole); }
+		}
+		
+		public string IntoIdentifier {
+			get {
+				return GetChildByRole (IntoIdentifierRole).Name;
+			}
+			set {
+				SetChildByRole(IntoIdentifierRole, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier IntoIdentifierToken {
+			get { return GetChildByRole(IntoIdentifierRole); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryJoinClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryJoinClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryJoinClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryJoinClause o = other as QueryJoinClause;
+			return o != null && this.IsGroupJoin == o.IsGroupJoin
+				&& this.Type.DoMatch(o.Type, match) && MatchString(this.JoinIdentifier, o.JoinIdentifier)
+				&& this.InExpression.DoMatch(o.InExpression, match) && this.OnExpression.DoMatch(o.OnExpression, match)
+				&& this.EqualsExpression.DoMatch(o.EqualsExpression, match)
+				&& MatchString(this.IntoIdentifier, o.IntoIdentifier);
+		}
+	}
+	
+	public class QueryOrderClause : QueryClause
+	{
+		public static readonly TokenRole OrderbyKeywordRole = new TokenRole ("orderby");
+		public static readonly Role<QueryOrdering> OrderingRole = new Role<QueryOrdering>("Ordering");
+		
+		public CSharpTokenNode OrderbyToken {
+			get { return GetChildByRole (OrderbyKeywordRole); }
+		}
+		
+		public AstNodeCollection<QueryOrdering> Orderings {
+			get { return GetChildrenByRole (OrderingRole); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryOrderClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryOrderClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryOrderClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryOrderClause o = other as QueryOrderClause;
+			return o != null && this.Orderings.DoMatch(o.Orderings, match);
+		}
+	}
+	
+	public class QueryOrdering : AstNode
+	{
+		public readonly static TokenRole AscendingKeywordRole = new TokenRole ("ascending");
+		public readonly static TokenRole DescendingKeywordRole = new TokenRole ("descending");
+
+		public override NodeType NodeType {
+			get { return NodeType.Unknown; }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public QueryOrderingDirection Direction {
+			get;
+			set;
+		}
+		
+		public CSharpTokenNode DirectionToken {
+			get { return Direction == QueryOrderingDirection.Ascending ? GetChildByRole (AscendingKeywordRole) : GetChildByRole (DescendingKeywordRole); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryOrdering (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryOrdering (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryOrdering (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryOrdering o = other as QueryOrdering;
+			return o != null && this.Direction == o.Direction && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+	
+	public enum QueryOrderingDirection
+	{
+		None,
+		Ascending,
+		Descending
+	}
+	
+	public class QuerySelectClause : QueryClause
+	{
+		public readonly static TokenRole SelectKeywordRole = new TokenRole ("select");
+
+		public CSharpTokenNode SelectKeyword {
+			get { return GetChildByRole (SelectKeywordRole); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQuerySelectClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQuerySelectClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQuerySelectClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QuerySelectClause o = other as QuerySelectClause;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+	
+	public class QueryGroupClause : QueryClause
+	{
+		public static readonly TokenRole GroupKeywordRole = new TokenRole ("group");
+		public static readonly Role<Expression> ProjectionRole = new Role<Expression>("Projection", Expression.Null);
+		public static readonly TokenRole ByKeywordRole = new TokenRole ("by");
+		public static readonly Role<Expression> KeyRole = new Role<Expression>("Key", Expression.Null);
+		
+		public CSharpTokenNode GroupKeyword {
+			get { return GetChildByRole (GroupKeywordRole); }
+		}
+		
+		public Expression Projection {
+			get { return GetChildByRole (ProjectionRole); }
+			set { SetChildByRole (ProjectionRole, value); }
+		}
+		
+		public CSharpTokenNode ByKeyword {
+			get { return GetChildByRole (ByKeywordRole); }
+		}
+		
+		public Expression Key {
+			get { return GetChildByRole (KeyRole); }
+			set { SetChildByRole (KeyRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitQueryGroupClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitQueryGroupClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitQueryGroupClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			QueryGroupClause o = other as QueryGroupClause;
+			return o != null && this.Projection.DoMatch(o.Projection, match) && this.Key.DoMatch(o.Key, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/SizeOfExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/SizeOfExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/SizeOfExpression.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// 
+// SizeOfExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// sizeof(Type)
+	/// </summary>
+	public class SizeOfExpression : Expression
+	{
+		public readonly static TokenRole SizeofKeywordRole = new TokenRole ("sizeof");
+		
+		public CSharpTokenNode SizeOfToken {
+			get { return GetChildByRole (SizeofKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public SizeOfExpression ()
+		{
+		}
+		
+		public SizeOfExpression (AstType type)
+		{
+			AddChild (type, Roles.Type);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitSizeOfExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitSizeOfExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitSizeOfExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			SizeOfExpression o = other as SizeOfExpression;
+			return o != null && this.Type.DoMatch(o.Type, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/StackAllocExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/StackAllocExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/StackAllocExpression.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// 
+// StackAllocExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// stackalloc Type[Count]
+	/// </summary>
+	public class StackAllocExpression : Expression
+	{
+		public readonly static TokenRole StackallocKeywordRole = new TokenRole ("stackalloc");
+		
+		public CSharpTokenNode StackAllocToken {
+			get { return GetChildByRole (StackallocKeywordRole); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public CSharpTokenNode LBracketToken {
+			get { return GetChildByRole (Roles.LBracket); }
+		}
+		
+		public Expression CountExpression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RBracketToken {
+			get { return GetChildByRole (Roles.RBracket); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitStackAllocExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitStackAllocExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitStackAllocExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			StackAllocExpression o = other as StackAllocExpression;
+			return o != null && this.Type.DoMatch(o.Type, match) && this.CountExpression.DoMatch(o.CountExpression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ThisReferenceExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ThisReferenceExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/ThisReferenceExpression.cs	(revision 11807)
@@ -0,0 +1,71 @@
+﻿// 
+// ThisReferenceExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// this
+	/// </summary>
+	public class ThisReferenceExpression : Expression
+	{
+		public TextLocation Location {
+			get;
+			set;
+		}
+		
+		public override TextLocation StartLocation {
+			get {
+				return Location;
+			}
+		}
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (Location.Line, Location.Column + "this".Length);
+			}
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitThisReferenceExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitThisReferenceExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitThisReferenceExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ThisReferenceExpression o = other as ThisReferenceExpression;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/TypeOfExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/TypeOfExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/TypeOfExpression.cs	(revision 11807)
@@ -0,0 +1,84 @@
+﻿// 
+// TypeOfExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// typeof(Type)
+	/// </summary>
+	public class TypeOfExpression : Expression
+	{
+		public readonly static TokenRole TypeofKeywordRole = new TokenRole ("typeof");
+		
+		public CSharpTokenNode TypeOfToken {
+			get { return GetChildByRole (TypeofKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public TypeOfExpression ()
+		{
+		}
+		
+		public TypeOfExpression (AstType type)
+		{
+			AddChild (type, Roles.Type);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitTypeOfExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitTypeOfExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitTypeOfExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			TypeOfExpression o = other as TypeOfExpression;
+			return o != null && this.Type.DoMatch(o.Type, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/TypeReferenceExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/TypeReferenceExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/TypeReferenceExpression.cs	(revision 11807)
@@ -0,0 +1,64 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Represents an AstType as an expression.
+	/// This is used when calling a method on a primitive type: "int.Parse()"
+	/// </summary>
+	public class TypeReferenceExpression : Expression
+	{
+		public AstType Type {
+			get { return GetChildByRole(Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitTypeReferenceExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitTypeReferenceExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitTypeReferenceExpression(this, data);
+		}
+		
+		public TypeReferenceExpression ()
+		{
+		}
+		
+		public TypeReferenceExpression (AstType type)
+		{
+			AddChild (type, Roles.Type);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			TypeReferenceExpression o = other as TypeReferenceExpression;
+			return o != null && this.Type.DoMatch(o.Type, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UnaryOperatorExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UnaryOperatorExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UnaryOperatorExpression.cs	(revision 11807)
@@ -0,0 +1,181 @@
+﻿// 
+// UnaryOperatorExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq.Expressions;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Operator Expression
+	/// </summary>
+	public class UnaryOperatorExpression : Expression
+	{
+		public readonly static TokenRole NotRole = new TokenRole ("!");
+		public readonly static TokenRole BitNotRole = new TokenRole ("~");
+		public readonly static TokenRole MinusRole = new TokenRole ("-");
+		public readonly static TokenRole PlusRole = new TokenRole ("+");
+		public readonly static TokenRole IncrementRole = new TokenRole ("++");
+		public readonly static TokenRole DecrementRole = new TokenRole ("--");
+		public readonly static TokenRole DereferenceRole = new TokenRole ("*");
+		public readonly static TokenRole AddressOfRole = new TokenRole ("&");
+		public readonly static TokenRole AwaitRole = new TokenRole ("await");
+		
+		public UnaryOperatorExpression()
+		{
+		}
+		
+		public UnaryOperatorExpression(UnaryOperatorType op, Expression expression)
+		{
+			this.Operator = op;
+			this.Expression = expression;
+		}
+		
+		public UnaryOperatorType Operator {
+			get;
+			set;
+		}
+		
+		public CSharpTokenNode OperatorToken {
+			get { return GetChildByRole (GetOperatorRole (Operator)); }
+		}
+
+		static Expression NoUnaryExpressionError = new ErrorExpression ("No unary expression");
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression) ?? NoUnaryExpressionError; }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUnaryOperatorExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUnaryOperatorExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUnaryOperatorExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UnaryOperatorExpression o = other as UnaryOperatorExpression;
+			return o != null && (this.Operator == UnaryOperatorType.Any || this.Operator == o.Operator)
+				&& this.Expression.DoMatch(o.Expression, match);
+		}
+		
+		public static TokenRole GetOperatorRole(UnaryOperatorType op)
+		{
+			switch (op) {
+				case UnaryOperatorType.Not:
+					return NotRole;
+				case UnaryOperatorType.BitNot:
+					return BitNotRole;
+				case UnaryOperatorType.Minus:
+					return MinusRole;
+				case UnaryOperatorType.Plus:
+					return PlusRole;
+				case UnaryOperatorType.Increment:
+				case UnaryOperatorType.PostIncrement:
+					return IncrementRole;
+				case UnaryOperatorType.PostDecrement:
+				case UnaryOperatorType.Decrement:
+					return DecrementRole;
+				case UnaryOperatorType.Dereference:
+					return DereferenceRole;
+				case UnaryOperatorType.AddressOf:
+					return AddressOfRole;
+				case UnaryOperatorType.Await:
+					return AwaitRole;
+				default:
+					throw new NotSupportedException("Invalid value for UnaryOperatorType");
+			}
+		}
+		
+		public static ExpressionType GetLinqNodeType(UnaryOperatorType op, bool checkForOverflow)
+		{
+			switch (op) {
+				case UnaryOperatorType.Not:
+					return ExpressionType.Not;
+				case UnaryOperatorType.BitNot:
+					return ExpressionType.OnesComplement;
+				case UnaryOperatorType.Minus:
+					return checkForOverflow ? ExpressionType.NegateChecked : ExpressionType.Negate;
+				case UnaryOperatorType.Plus:
+					return ExpressionType.UnaryPlus;
+				case UnaryOperatorType.Increment:
+					return ExpressionType.PreIncrementAssign;
+				case UnaryOperatorType.Decrement:
+					return ExpressionType.PreDecrementAssign;
+				case UnaryOperatorType.PostIncrement:
+					return ExpressionType.PostIncrementAssign;
+				case UnaryOperatorType.PostDecrement:
+					return ExpressionType.PostDecrementAssign;
+				case UnaryOperatorType.Dereference:
+				case UnaryOperatorType.AddressOf:
+				case UnaryOperatorType.Await:
+					return ExpressionType.Extension;
+				default:
+					throw new NotSupportedException("Invalid value for UnaryOperatorType");
+			}
+		}
+	}
+	
+	public enum UnaryOperatorType
+	{
+		/// <summary>
+		/// Any unary operator (used in pattern matching)
+		/// </summary>
+		Any,
+		
+		/// <summary>Logical not (!a)</summary>
+		Not,
+		/// <summary>Bitwise not (~a)</summary>
+		BitNot,
+		/// <summary>Unary minus (-a)</summary>
+		Minus,
+		/// <summary>Unary plus (+a)</summary>
+		Plus,
+		/// <summary>Pre increment (++a)</summary>
+		Increment,
+		/// <summary>Pre decrement (--a)</summary>
+		Decrement,
+		/// <summary>Post increment (a++)</summary>
+		PostIncrement,
+		/// <summary>Post decrement (a--)</summary>
+		PostDecrement,
+		/// <summary>Dereferencing (*a)</summary>
+		Dereference,
+		/// <summary>Get address (&a)</summary>
+		AddressOf,
+		/// <summary>C# 5.0 await</summary>
+		Await
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UncheckedExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UncheckedExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UncheckedExpression.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// 
+// UncheckedExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// unchecked(Expression)
+	/// </summary>
+	public class UncheckedExpression : Expression
+	{
+		public readonly static TokenRole UncheckedKeywordRole = new TokenRole ("unchecked");
+
+		public CSharpTokenNode UncheckedToken {
+			get { return GetChildByRole (UncheckedKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole(Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public UncheckedExpression ()
+		{
+		}
+		
+		public UncheckedExpression (Expression expression)
+		{
+			AddChild (expression, Roles.Expression);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUncheckedExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUncheckedExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUncheckedExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UncheckedExpression o = other as UncheckedExpression;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UndocumentedExpression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UndocumentedExpression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Expressions/UndocumentedExpression.cs	(revision 11807)
@@ -0,0 +1,105 @@
+﻿// 
+// UndocumentedExpression.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum UndocumentedExpressionType
+	{
+		ArgListAccess, // __arglist
+		ArgList, // __arglist (a1, a2, ..., an)
+		RefValue, // __refvalue (expr , type)
+		RefType, // __reftype (expr)
+		MakeRef // __makeref (expr)
+	}
+	
+	/// <summary>
+	/// Represents undocumented expressions.
+	/// </summary>
+	public class UndocumentedExpression : Expression
+	{
+		public readonly static TokenRole ArglistKeywordRole = new TokenRole ("__arglist");
+		public readonly static TokenRole RefvalueKeywordRole = new TokenRole ("__refvalue");
+		public readonly static TokenRole ReftypeKeywordRole = new TokenRole ("__reftype");
+		public readonly static TokenRole MakerefKeywordRole = new TokenRole ("__makeref");
+		
+		public UndocumentedExpressionType UndocumentedExpressionType {
+			get; set;
+		}
+		
+		public CSharpTokenNode UndocumentedToken {
+			get {
+				switch (UndocumentedExpressionType) {
+				case ICSharpCode.NRefactory.CSharp.UndocumentedExpressionType.ArgListAccess:
+				case ICSharpCode.NRefactory.CSharp.UndocumentedExpressionType.ArgList:
+					return GetChildByRole (ArglistKeywordRole);
+				case ICSharpCode.NRefactory.CSharp.UndocumentedExpressionType.RefValue:
+					return GetChildByRole (RefvalueKeywordRole);
+				case ICSharpCode.NRefactory.CSharp.UndocumentedExpressionType.RefType:
+					return GetChildByRole (ReftypeKeywordRole);
+				case ICSharpCode.NRefactory.CSharp.UndocumentedExpressionType.MakeRef:
+					return GetChildByRole (MakerefKeywordRole);
+				}
+				return CSharpTokenNode.Null;
+			}
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<Expression> Arguments {
+			get { return GetChildrenByRole(Roles.Argument); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUndocumentedExpression (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUndocumentedExpression (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUndocumentedExpression (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UndocumentedExpression o = other as UndocumentedExpression;
+			return o != null && this.UndocumentedExpressionType == o.UndocumentedExpressionType && this.Arguments.DoMatch(o.Arguments, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Attribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Attribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Attribute.cs	(revision 11807)
@@ -0,0 +1,93 @@
+﻿// 
+// Attribute.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Attribute(Arguments)
+	/// </summary>
+	public class Attribute : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+
+		public AstNodeCollection<Expression> Arguments {
+			get { return base.GetChildrenByRole (Roles.Argument); }
+		}
+
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+
+		// HasArgumentList == false: [Empty]
+		public bool HasArgumentList {
+			get;
+			set;
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAttribute (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAttribute (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAttribute (this, data);
+		}
+		
+		protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+		{
+			Attribute o = other as Attribute;
+			return o != null && this.Type.DoMatch (o.Type, match) && this.Arguments.DoMatch (o.Arguments, match);
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			if (IsNull)
+				return "Null";
+			return base.ToString(formattingOptions);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/AttributeSection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/AttributeSection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/AttributeSection.cs	(revision 11807)
@@ -0,0 +1,174 @@
+﻿// 
+// AttributeSection.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// [AttributeTarget: Attributes]
+	/// </summary>
+	public class AttributeSection : AstNode
+	{
+		#region PatternPlaceholder
+		public static implicit operator AttributeSection(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : AttributeSection, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder (this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder (this, child);
+			}
+			
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public CSharpTokenNode LBracketToken {
+			get { return GetChildByRole (Roles.LBracket); }
+		}
+		
+		public string AttributeTarget {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier AttributeTargetToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public AstNodeCollection<Attribute> Attributes {
+			get { return base.GetChildrenByRole (Roles.Attribute); }
+		}
+		
+		public CSharpTokenNode RBracketToken {
+			get { return GetChildByRole (Roles.RBracket); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAttributeSection (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAttributeSection (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAttributeSection (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			AttributeSection o = other as AttributeSection;
+			return o != null && MatchString(this.AttributeTarget, o.AttributeTarget) && this.Attributes.DoMatch(o.Attributes, match);
+		}
+		
+		public AttributeSection()
+		{
+		}
+		
+		public AttributeSection(Attribute attr)
+		{
+			this.Attributes.Add(attr);
+		}
+		
+//		public static string GetAttributeTargetName(AttributeTarget attributeTarget)
+//		{
+//			switch (attributeTarget) {
+//				case AttributeTarget.None:
+//					return null;
+//				case AttributeTarget.Assembly:
+//					return "assembly";
+//				case AttributeTarget.Module:
+//					return "module";
+//				case AttributeTarget.Type:
+//					return "type";
+//				case AttributeTarget.Param:
+//					return "param";
+//				case AttributeTarget.Field:
+//					return "field";
+//				case AttributeTarget.Return:
+//					return "return";
+//				case AttributeTarget.Method:
+//					return "method";
+//				default:
+//					throw new NotSupportedException("Invalid value for AttributeTarget");
+//			}
+//		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Comment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Comment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Comment.cs	(revision 11807)
@@ -0,0 +1,140 @@
+﻿// 
+// Comment.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum CommentType 
+	{
+		/// <summary>
+		/// "//" comment
+		/// </summary>
+		SingleLine,
+		/// <summary>
+		/// "/* */" comment
+		/// </summary>
+		MultiLine,
+		/// <summary>
+		/// "///" comment
+		/// </summary>
+		Documentation,
+		/// <summary>
+		/// Inactive code (code in non-taken "#if")
+		/// </summary>
+		InactiveCode,
+		/// <summary>
+		/// "/** */" comment
+		/// </summary>
+		MultiLineDocumentation
+	}
+	
+	public class Comment : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Whitespace;
+			}
+		}
+		
+		CommentType commentType;
+		
+		public CommentType CommentType {
+			get { return commentType; }
+			set { ThrowIfFrozen(); commentType = value; }
+		}
+		
+		/// <summary>
+		/// Returns true if the <see cref="CommentType"/> is Documentation or MultiLineDocumentation.
+		/// </summary>
+		public bool IsDocumentation {
+			get {
+				return commentType == CommentType.Documentation || commentType == CommentType.MultiLineDocumentation;
+			}
+		}
+		
+		bool startsLine;
+		
+		public bool StartsLine {
+			get { return startsLine; }
+			set { ThrowIfFrozen(); startsLine = value; }
+		}
+		
+		string content;
+		
+		public string Content {
+			get { return content; }
+			set { ThrowIfFrozen(); content = value; }
+		}
+		
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get { 
+				return startLocation;
+			}
+		}
+		
+		TextLocation endLocation;
+		public override TextLocation EndLocation {
+			get {
+				return endLocation;
+			}
+		}
+		
+		public Comment (string content, CommentType type = CommentType.SingleLine)
+		{
+			this.CommentType = type;
+			this.Content = content;
+		}
+		
+		public Comment (CommentType commentType, TextLocation startLocation, TextLocation endLocation)
+		{
+			this.CommentType = commentType;
+			this.startLocation = startLocation;
+			this.endLocation = endLocation;
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitComment (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitComment (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitComment (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			Comment o = other as Comment;
+			return o != null && this.CommentType == o.CommentType && MatchString(this.Content, o.Content);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Constraint.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Constraint.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/Constraint.cs	(revision 11807)
@@ -0,0 +1,85 @@
+﻿// 
+// Constraint.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// where TypeParameter : BaseTypes
+	/// </summary>
+	/// <remarks>
+	/// new(), struct and class constraints are represented using a PrimitiveType "new", "struct" or "class"
+	/// </remarks>
+	public class Constraint : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+
+		public CSharpTokenNode WhereKeyword {
+			get { return GetChildByRole (Roles.WhereKeyword); }
+		}
+
+		public SimpleType TypeParameter {
+			get {
+				return GetChildByRole (Roles.ConstraintTypeParameter);
+			}
+			set {
+				SetChildByRole(Roles.ConstraintTypeParameter, value);
+			}
+		}
+		
+		public AstNodeCollection<AstType> BaseTypes {
+			get {
+				return GetChildrenByRole(Roles.BaseType); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitConstraint (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitConstraint (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitConstraint (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			Constraint o = other as Constraint;
+			return o != null && this.TypeParameter.DoMatch (o.TypeParameter, match) && this.BaseTypes.DoMatch(o.BaseTypes, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/DelegateDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/DelegateDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/DelegateDeclaration.cs	(revision 11807)
@@ -0,0 +1,92 @@
+﻿// 
+// DelegateDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// delegate ReturnType Name&lt;TypeParameters&gt;(Parameters) where Constraints;
+	/// </summary>
+	public class DelegateDeclaration : EntityDeclaration
+	{
+		public override NodeType NodeType {
+			get { return NodeType.TypeDeclaration; }
+		}
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.TypeDefinition; }
+		}
+		
+		public CSharpTokenNode DelegateToken {
+			get { return GetChildByRole(Roles.DelegateKeyword); }
+		}
+
+		public AstNodeCollection<TypeParameterDeclaration> TypeParameters {
+			get { return GetChildrenByRole (Roles.TypeParameter); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public AstNodeCollection<Constraint> Constraints {
+			get { return GetChildrenByRole (Roles.Constraint); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitDelegateDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitDelegateDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitDelegateDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			DelegateDeclaration o = other as DelegateDeclaration;
+			return o != null && MatchString(this.Name, o.Name) 
+				&& this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match)
+				&& this.TypeParameters.DoMatch(o.TypeParameters, match) && this.Parameters.DoMatch(o.Parameters, match)
+				&& this.Constraints.DoMatch(o.Constraints, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/ExternAliasDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/ExternAliasDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/ExternAliasDeclaration.cs	(revision 11807)
@@ -0,0 +1,91 @@
+﻿// 
+// ExternAliasDeclaration.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// extern alias <Identifier>;
+	/// </summary>
+	public class ExternAliasDeclaration : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+
+		public CSharpTokenNode ExternToken {
+			get { return GetChildByRole (Roles.ExternKeyword); }
+		}
+
+		public CSharpTokenNode AliasToken {
+			get { return GetChildByRole (Roles.AliasKeyword); }
+		}
+
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitExternAliasDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitExternAliasDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitExternAliasDeclaration (this, data);
+		}
+
+		protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+		{
+			var o = other as ExternAliasDeclaration;
+			return o != null && MatchString (this.Name, o.Name);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/NamespaceDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/NamespaceDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/NamespaceDeclaration.cs	(revision 11807)
@@ -0,0 +1,158 @@
+﻿// 
+// NamespaceDeclaration.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// namespace Name { Members }
+	/// </summary>
+	public class NamespaceDeclaration : AstNode
+	{
+		public static readonly Role<AstNode> MemberRole = SyntaxTree.MemberRole;
+		public static readonly Role<AstType> NamespaceNameRole = new Role<AstType>("NamespaceName", AstType.Null);
+
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+
+		public CSharpTokenNode NamespaceToken {
+			get { return GetChildByRole(Roles.NamespaceKeyword); }
+		}
+
+		public AstType NamespaceName {
+			get { return GetChildByRole(NamespaceNameRole) ?? AstType.Null; }
+			set { SetChildByRole(NamespaceNameRole, value); }
+		}
+
+		public string Name {
+			get {
+				return UsingDeclaration.ConstructNamespace(NamespaceName);
+			}
+			set {
+				var arr = value.Split('.');
+				NamespaceName = ConstructType(arr, arr.Length - 1);
+			}
+		}
+
+		static AstType ConstructType(string[] arr, int i)
+		{
+			if (i < 0 || i >= arr.Length)
+				throw new ArgumentOutOfRangeException("i");
+			if (i == 0)
+				return new SimpleType(arr[i]);
+			return new MemberType(ConstructType(arr, i - 1), arr[i]);
+		}
+
+		/// <summary>
+		/// Gets the full namespace name (including any parent namespaces)
+		/// </summary>
+		public string FullName {
+			get {
+				NamespaceDeclaration parentNamespace = Parent as NamespaceDeclaration;
+				if (parentNamespace != null)
+					return BuildQualifiedName(parentNamespace.FullName, Name);
+				return Name;
+			}
+		}
+
+		public IEnumerable<string> Identifiers {
+			get {
+				var result = new Stack<string>();
+				AstType type = NamespaceName;
+				while (type is MemberType) {
+					var mt = (MemberType)type;
+					result.Push(mt.MemberName);
+					type = mt.Target;
+				}
+				if (type is SimpleType)
+					result.Push(((SimpleType)type).Identifier);
+				return result;
+			}
+		}
+
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole(Roles.LBrace); }
+		}
+
+		public AstNodeCollection<AstNode> Members {
+			get { return GetChildrenByRole(MemberRole); }
+		}
+
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole(Roles.RBrace); }
+		}
+
+		public NamespaceDeclaration()
+		{
+		}
+
+		public NamespaceDeclaration(string name)
+		{
+			this.Name = name;
+		}
+
+		public static string BuildQualifiedName(string name1, string name2)
+		{
+			if (string.IsNullOrEmpty(name1))
+				return name2;
+			if (string.IsNullOrEmpty(name2))
+				return name1;
+			return name1 + "." + name2;
+		}
+
+		public void AddMember(AstNode child)
+		{
+			AddChild(child, MemberRole);
+		}
+
+		public override void AcceptVisitor(IAstVisitor visitor)
+		{
+			visitor.VisitNamespaceDeclaration(this);
+		}
+
+		public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
+		{
+			return visitor.VisitNamespaceDeclaration(this);
+		}
+
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitNamespaceDeclaration(this, data);
+		}
+
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			NamespaceDeclaration o = other as NamespaceDeclaration;
+			return o != null && MatchString(this.Name, o.Name) && this.Members.DoMatch(o.Members, match);
+		}
+	}
+}			;
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/NewLineNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/NewLineNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/NewLineNode.cs	(revision 11807)
@@ -0,0 +1,91 @@
+using System;
+namespace ICSharpCode.NRefactory.CSharp
+{
+
+	/// <summary>
+	/// A New line node represents a line break in the text.
+	/// </summary>
+	public sealed class NewLineNode : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Whitespace;
+			}
+		}
+
+		const uint newLineMask = 0xfu << AstNodeFlagsUsedBits;
+		static readonly UnicodeNewline[] newLineTypes = {
+			UnicodeNewline.Unknown,
+			UnicodeNewline.LF,
+			UnicodeNewline.CRLF,
+			UnicodeNewline.CR,
+			UnicodeNewline.NEL,
+			UnicodeNewline.VT,
+			UnicodeNewline.FF,
+			UnicodeNewline.LS,
+			UnicodeNewline.PS
+		};
+		
+		public UnicodeNewline NewLineType {
+			get {
+				return newLineTypes[(flags & newLineMask) >> AstNodeFlagsUsedBits];
+			}
+			set {
+				ThrowIfFrozen();
+				int pos = Array.IndexOf(newLineTypes, value);
+				if (pos < 0)
+					pos = 0;
+				flags &= ~newLineMask; // clear old newline type
+				flags |= (uint)pos << AstNodeFlagsUsedBits;
+			}
+		}
+
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get { 
+				return startLocation;
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (startLocation.Line + 1, 1);
+			}
+		}
+
+		public NewLineNode() : this (TextLocation.Empty)
+		{
+		}
+
+		public NewLineNode(TextLocation startLocation)
+		{
+			this.startLocation = startLocation;
+		}
+
+		public sealed override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			return NewLine.GetString (NewLineType);
+		}
+
+		public override void AcceptVisitor(IAstVisitor visitor)
+		{
+			visitor.VisitNewLine (this);
+		}
+			
+		public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
+		{
+			return visitor.VisitNewLine (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitNewLine (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
+		{
+			return other is NewLineNode;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/PreProcessorDirective.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/PreProcessorDirective.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/PreProcessorDirective.cs	(revision 11807)
@@ -0,0 +1,205 @@
+﻿// 
+// PreProcessorDirective.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc.
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum PreProcessorDirectiveType : byte
+	{
+		Invalid = 0,
+		Region = 1,
+		Endregion = 2,
+		
+		If = 3,
+		Endif = 4,
+		Elif = 5,
+		Else = 6,
+		
+		Define = 7,
+		Undef = 8,
+		Error = 9,
+		Warning = 10,
+		Pragma = 11,
+		Line = 12
+	}
+
+	public class LinePreprocessorDirective : PreProcessorDirective
+	{
+		public int LineNumber {
+			get;
+			set;
+		}
+
+		public string FileName {
+			get;
+			set;
+		}
+
+		public LinePreprocessorDirective(TextLocation startLocation, TextLocation endLocation) : base (PreProcessorDirectiveType.Line, startLocation, endLocation)
+		{
+		}
+
+		public LinePreprocessorDirective(string argument = null) : base (PreProcessorDirectiveType.Line, argument)
+		{
+		}
+	}
+
+	public class PragmaWarningPreprocessorDirective : PreProcessorDirective
+	{
+		public static readonly Role<PrimitiveExpression>  WarningRole = new Role<PrimitiveExpression> ("Warning");
+
+		public static readonly TokenRole PragmaKeywordRole = new TokenRole ("#pragma");
+		public static readonly TokenRole WarningKeywordRole = new TokenRole ("warning");
+		public static readonly TokenRole DisableKeywordRole = new TokenRole ("disable");
+		public static readonly TokenRole RestoreKeywordRole = new TokenRole ("restore");
+
+		public bool Disable {
+			get {
+				return !DisableToken.IsNull;
+			}
+		}
+
+		public CSharpTokenNode PragmaToken {
+			get { return GetChildByRole (PragmaKeywordRole); }
+		}
+
+		public CSharpTokenNode WarningToken {
+			get { return GetChildByRole (WarningKeywordRole); }
+		}
+
+		public CSharpTokenNode DisableToken {
+			get { return GetChildByRole (DisableKeywordRole); }
+		}
+
+		public CSharpTokenNode RestoreToken {
+			get { return GetChildByRole (RestoreKeywordRole); }
+		}
+
+		public AstNodeCollection<PrimitiveExpression> Warnings {
+			get { return GetChildrenByRole(WarningRole); }
+		}
+
+		public override TextLocation EndLocation {
+			get {
+				var child = LastChild;
+				if (child == null)
+					return base.EndLocation;
+				return child.EndLocation;
+			}
+		}
+
+		public PragmaWarningPreprocessorDirective(TextLocation startLocation, TextLocation endLocation) : base (PreProcessorDirectiveType.Pragma, startLocation, endLocation)
+		{
+		}
+
+		public PragmaWarningPreprocessorDirective(string argument = null) : base (PreProcessorDirectiveType.Pragma, argument)
+		{
+		}
+
+		public bool IsDefined(int pragmaWarning)
+		{
+			return Warnings.Select(w => (int)w.Value).Any(n => n == pragmaWarning);
+		}
+	}
+	
+	public class PreProcessorDirective : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Whitespace;
+			}
+		}
+		
+		public PreProcessorDirectiveType Type {
+			get;
+			set;
+		}
+		
+		public string Argument {
+			get;
+			set;
+		}
+		
+		/// <summary>
+		/// For an '#if' directive, specifies whether the condition evaluated to true.
+		/// </summary>
+		public bool Take {
+			get;
+			set;
+		}
+		
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get { 
+				return startLocation;
+			}
+		}
+		
+		TextLocation endLocation;
+		public override TextLocation EndLocation {
+			get {
+				return endLocation;
+			}
+		}
+		
+		public PreProcessorDirective(PreProcessorDirectiveType type, TextLocation startLocation, TextLocation endLocation)
+		{
+			this.Type = type;
+			this.startLocation = startLocation;
+			this.endLocation = endLocation;
+		}
+
+		public PreProcessorDirective(PreProcessorDirectiveType type, string argument = null)
+		{
+			this.Type = type;
+			this.Argument = argument;
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitPreProcessorDirective (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitPreProcessorDirective (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitPreProcessorDirective (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			PreProcessorDirective o = other as PreProcessorDirective;
+			return o != null && Type == o.Type && MatchString(Argument, o.Argument);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TextNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TextNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TextNode.cs	(revision 11807)
@@ -0,0 +1,94 @@
+// 
+// TextNode.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// A text node contains text without syntactic or semantic information.
+	/// (non parseable part of a text)
+	/// </summary>
+	public class TextNode : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Whitespace;
+			}
+		}
+
+		public string Text {
+			get;
+			set;
+		}
+
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get { 
+				return startLocation;
+			}
+		}
+		
+		TextLocation endLocation;
+		public override TextLocation EndLocation {
+			get {
+				return endLocation;
+			}
+		}
+
+		public TextNode(string text) : this (text, TextLocation.Empty, TextLocation.Empty)
+		{
+		}
+
+		public TextNode(string text, TextLocation startLocation, TextLocation endLocation)
+		{
+			this.Text = text;
+			this.startLocation = startLocation;
+			this.endLocation = endLocation;
+		}
+
+		public override void AcceptVisitor(IAstVisitor visitor)
+		{
+			visitor.VisitText (this);
+		}
+
+		public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
+		{
+			return visitor.VisitText (this);
+		}
+
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitText (this, data);
+		}
+
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			var o = other as TextNode;
+			return o != null && o.Text == Text;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TypeDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TypeDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TypeDeclaration.cs	(revision 11807)
@@ -0,0 +1,145 @@
+﻿// 
+// TypeDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum ClassType
+	{
+		Class,
+		Struct,
+		Interface,
+		Enum
+	}
+	
+	/// <summary>
+	/// class Name&lt;TypeParameters&gt; : BaseTypes where Constraints;
+	/// </summary>
+	public class TypeDeclaration : EntityDeclaration
+	{
+		public override NodeType NodeType {
+			get { return NodeType.TypeDeclaration; }
+		}
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.TypeDefinition; }
+		}
+		
+		ClassType classType;
+
+		public CSharpTokenNode TypeKeyword {
+			get {
+				switch (classType) {
+					case ClassType.Class:
+						return GetChildByRole(Roles.ClassKeyword);
+					case ClassType.Struct:
+						return GetChildByRole(Roles.StructKeyword);
+					case ClassType.Interface:
+						return GetChildByRole(Roles.InterfaceKeyword);
+					case ClassType.Enum:
+						return GetChildByRole(Roles.EnumKeyword);
+					default:
+						return CSharpTokenNode.Null;
+				}
+			}
+		}
+		
+		public ClassType ClassType {
+			get { return classType; }
+			set {
+				ThrowIfFrozen();
+				classType = value;
+			}
+		}
+
+		public CSharpTokenNode LChevronToken {
+			get { return GetChildByRole (Roles.LChevron); }
+		}
+
+		public AstNodeCollection<TypeParameterDeclaration> TypeParameters {
+			get { return GetChildrenByRole (Roles.TypeParameter); }
+		}
+
+		public CSharpTokenNode RChevronToken {
+			get { return GetChildByRole (Roles.RChevron); }
+		}
+
+
+
+		public CSharpTokenNode ColonToken {
+			get {
+				return GetChildByRole(Roles.Colon);
+			}
+		}
+		
+		public AstNodeCollection<AstType> BaseTypes {
+			get { return GetChildrenByRole(Roles.BaseType); }
+		}
+		
+		public AstNodeCollection<Constraint> Constraints {
+			get { return GetChildrenByRole(Roles.Constraint); }
+		}
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+
+		public AstNodeCollection<EntityDeclaration> Members {
+			get { return GetChildrenByRole (Roles.TypeMemberRole); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitTypeDeclaration (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitTypeDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitTypeDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			TypeDeclaration o = other as TypeDeclaration;
+			return o != null && this.ClassType == o.ClassType && MatchString(this.Name, o.Name)
+				&& this.MatchAttributesAndModifiers(o, match) && this.TypeParameters.DoMatch(o.TypeParameters, match)
+				&& this.BaseTypes.DoMatch(o.BaseTypes, match) && this.Constraints.DoMatch(o.Constraints, match)
+				&& this.Members.DoMatch(o.Members, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TypeParameterDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TypeParameterDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/TypeParameterDeclaration.cs	(revision 11807)
@@ -0,0 +1,113 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// [in|out] Name
+	/// 
+	/// Represents a type parameter.
+	/// Note: mirroring the C# syntax, constraints are not part of the type parameter declaration, but belong
+	/// to the parent type or method.
+	/// </summary>
+	public class TypeParameterDeclaration : AstNode
+	{
+		public static readonly Role<AttributeSection> AttributeRole = EntityDeclaration.AttributeRole;
+		public static readonly TokenRole OutVarianceKeywordRole = new TokenRole ("out");
+		public static readonly TokenRole InVarianceKeywordRole = new TokenRole ("in");
+		
+		public override NodeType NodeType {
+			get { return NodeType.Unknown; }
+		}
+		
+		public AstNodeCollection<AttributeSection> Attributes {
+			get { return GetChildrenByRole (AttributeRole); }
+		}
+		
+		VarianceModifier variance;
+		
+		public VarianceModifier Variance {
+			get { return variance; }
+			set { ThrowIfFrozen(); variance = value; }
+		}
+		
+		public CSharpTokenNode VarianceToken {
+			get {
+				switch (Variance) {
+					case VarianceModifier.Covariant:
+						return GetChildByRole(OutVarianceKeywordRole);
+					case VarianceModifier.Contravariant:
+						return GetChildByRole(InVarianceKeywordRole);
+					default:
+						return CSharpTokenNode.Null;
+				}
+			}
+		}
+		
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+
+		public TypeParameterDeclaration ()
+		{
+		}
+
+		public TypeParameterDeclaration (string name)
+		{
+			Name = name;
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitTypeParameterDeclaration (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitTypeParameterDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitTypeParameterDeclaration(this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			TypeParameterDeclaration o = other as TypeParameterDeclaration;
+			return o != null && this.Variance == o.Variance && MatchString(this.Name, o.Name) && this.Attributes.DoMatch(o.Attributes, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/UsingAliasDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/UsingAliasDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/UsingAliasDeclaration.cs	(revision 11807)
@@ -0,0 +1,107 @@
+﻿// 
+// UsingAliasDeclaration.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// using Alias = Import;
+	/// </summary>
+	public class UsingAliasDeclaration : AstNode
+	{
+		public static readonly TokenRole UsingKeywordRole = new TokenRole ("using");
+		public static readonly Role<Identifier> AliasRole = new Role<Identifier>("Alias", Identifier.Null);
+		public static readonly Role<AstType> ImportRole = UsingDeclaration.ImportRole;
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public CSharpTokenNode UsingToken {
+			get { return GetChildByRole (UsingKeywordRole); }
+		}
+		
+		public string Alias {
+			get {
+				return GetChildByRole (AliasRole).Name;
+			}
+			set {
+				SetChildByRole(AliasRole, Identifier.Create (value));
+			}
+		}
+		
+		public CSharpTokenNode AssignToken {
+			get { return GetChildByRole (Roles.Assign); }
+		}
+		
+		public AstType Import {
+			get { return GetChildByRole (ImportRole); }
+			set { SetChildByRole (ImportRole, value); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public UsingAliasDeclaration ()
+		{
+		}
+		
+		public UsingAliasDeclaration (string alias, string nameSpace)
+		{
+			AddChild (Identifier.Create (alias), AliasRole);
+			AddChild (new SimpleType (nameSpace), ImportRole);
+		}
+		
+		public UsingAliasDeclaration (string alias, AstType import)
+		{
+			AddChild (Identifier.Create (alias), AliasRole);
+			AddChild (import, ImportRole);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUsingAliasDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUsingAliasDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUsingAliasDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UsingAliasDeclaration o = other as UsingAliasDeclaration;
+			return o != null && MatchString(this.Alias, o.Alias) && this.Import.DoMatch(o.Import, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/UsingDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/UsingDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/UsingDeclaration.cs	(revision 11807)
@@ -0,0 +1,122 @@
+﻿// 
+// UsingDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Text;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// using Import;
+	/// </summary>
+	public class UsingDeclaration : AstNode
+	{
+		public static readonly TokenRole UsingKeywordRole = new TokenRole ("using");
+		public static readonly Role<AstType> ImportRole = new Role<AstType>("Import", AstType.Null);
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public CSharpTokenNode UsingToken {
+			get { return GetChildByRole (UsingKeywordRole); }
+		}
+		
+		public AstType Import {
+			get { return GetChildByRole (ImportRole); }
+			set { SetChildByRole (ImportRole, value); }
+		}
+		
+		public string Namespace {
+			get { return ConstructNamespace (Import); }
+		}
+
+		internal static string ConstructNamespace (AstType type)
+		{
+			var stack = new Stack<string>();
+			while (type is MemberType) {
+				var mt = (MemberType)type;
+				stack.Push(mt.MemberName);
+				type = mt.Target;
+				if (mt.IsDoubleColon) {
+					stack.Push("::");
+				} else {
+					stack.Push("."); 
+				}
+			}
+			if (type is SimpleType)
+				stack.Push(((SimpleType)type).Identifier);
+
+			var result = new StringBuilder();
+			while (stack.Count > 0)
+				result.Append(stack.Pop());
+			return result.ToString();
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public UsingDeclaration ()
+		{
+		}
+		
+		public UsingDeclaration (string nameSpace)
+		{
+			AddChild (AstType.Create (nameSpace), ImportRole);
+		}
+		
+		public UsingDeclaration (AstType import)
+		{
+			AddChild (import, ImportRole);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUsingDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUsingDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUsingDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UsingDeclaration o = other as UsingDeclaration;
+			return o != null && this.Import.DoMatch(o.Import, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/WhitespaceNode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/WhitespaceNode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/GeneralScope/WhitespaceNode.cs	(revision 11807)
@@ -0,0 +1,91 @@
+// 
+// WhitespaceNode.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// A Whitespace node contains only whitespaces.
+	/// </summary>
+	public class WhitespaceNode : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Whitespace;
+			}
+		}
+
+		public string WhiteSpaceText {
+			get;
+			set;
+		}
+
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get { 
+				return startLocation;
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (startLocation.Line, startLocation.Column + WhiteSpaceText.Length);
+			}
+		}
+
+		public WhitespaceNode(string whiteSpaceText) : this (whiteSpaceText, TextLocation.Empty)
+		{
+		}
+
+		public WhitespaceNode(string whiteSpaceText, TextLocation startLocation)
+		{
+			this.WhiteSpaceText = WhiteSpaceText;
+			this.startLocation = startLocation;
+		}
+
+		public override void AcceptVisitor(IAstVisitor visitor)
+		{
+			visitor.VisitWhitespace (this);
+		}
+
+		public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
+		{
+			return visitor.VisitWhitespace (this);
+		}
+
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitWhitespace (this, data);
+		}
+
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			var o = other as WhitespaceNode;
+			return o != null && o.WhiteSpaceText == WhiteSpaceText;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/IAstVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/IAstVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/IAstVisitor.cs	(revision 11807)
@@ -0,0 +1,418 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// AST visitor.
+	/// </summary>
+	public interface IAstVisitor
+	{
+		void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression);
+		void VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression);
+		void VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression);
+		void VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression);
+		void VisitAsExpression(AsExpression asExpression);
+		void VisitAssignmentExpression(AssignmentExpression assignmentExpression);
+		void VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression);
+		void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression);
+		void VisitCastExpression(CastExpression castExpression);
+		void VisitCheckedExpression(CheckedExpression checkedExpression);
+		void VisitConditionalExpression(ConditionalExpression conditionalExpression);
+		void VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression);
+		void VisitDirectionExpression(DirectionExpression directionExpression);
+		void VisitIdentifierExpression(IdentifierExpression identifierExpression);
+		void VisitIndexerExpression(IndexerExpression indexerExpression);
+		void VisitInvocationExpression(InvocationExpression invocationExpression);
+		void VisitIsExpression(IsExpression isExpression);
+		void VisitLambdaExpression(LambdaExpression lambdaExpression);
+		void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression);
+		void VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression);
+		void VisitNamedExpression(NamedExpression namedExpression);
+		void VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression);
+		void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression);
+		void VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression);
+		void VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression);
+		void VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression);
+		void VisitPrimitiveExpression(PrimitiveExpression primitiveExpression);
+		void VisitSizeOfExpression(SizeOfExpression sizeOfExpression);
+		void VisitStackAllocExpression(StackAllocExpression stackAllocExpression);
+		void VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression);
+		void VisitTypeOfExpression(TypeOfExpression typeOfExpression);
+		void VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression);
+		void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression);
+		void VisitUncheckedExpression(UncheckedExpression uncheckedExpression);
+
+		void VisitQueryExpression(QueryExpression queryExpression);
+		void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause);
+		void VisitQueryFromClause(QueryFromClause queryFromClause);
+		void VisitQueryLetClause(QueryLetClause queryLetClause);
+		void VisitQueryWhereClause(QueryWhereClause queryWhereClause);
+		void VisitQueryJoinClause(QueryJoinClause queryJoinClause);
+		void VisitQueryOrderClause(QueryOrderClause queryOrderClause);
+		void VisitQueryOrdering(QueryOrdering queryOrdering);
+		void VisitQuerySelectClause(QuerySelectClause querySelectClause);
+		void VisitQueryGroupClause(QueryGroupClause queryGroupClause);
+		
+		void VisitAttribute(Attribute attribute);
+		void VisitAttributeSection(AttributeSection attributeSection);
+		void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration);
+		void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration);
+		void VisitTypeDeclaration(TypeDeclaration typeDeclaration);
+		void VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration);
+		void VisitUsingDeclaration(UsingDeclaration usingDeclaration);
+		void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration);
+		
+		void VisitBlockStatement(BlockStatement blockStatement);
+		void VisitBreakStatement(BreakStatement breakStatement);
+		void VisitCheckedStatement(CheckedStatement checkedStatement);
+		void VisitContinueStatement(ContinueStatement continueStatement);
+		void VisitDoWhileStatement(DoWhileStatement doWhileStatement);
+		void VisitEmptyStatement(EmptyStatement emptyStatement);
+		void VisitExpressionStatement(ExpressionStatement expressionStatement);
+		void VisitFixedStatement(FixedStatement fixedStatement);
+		void VisitForeachStatement(ForeachStatement foreachStatement);
+		void VisitForStatement(ForStatement forStatement);
+		void VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement);
+		void VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement);
+		void VisitGotoStatement(GotoStatement gotoStatement);
+		void VisitIfElseStatement(IfElseStatement ifElseStatement);
+		void VisitLabelStatement(LabelStatement labelStatement);
+		void VisitLockStatement(LockStatement lockStatement);
+		void VisitReturnStatement(ReturnStatement returnStatement);
+		void VisitSwitchStatement(SwitchStatement switchStatement);
+		void VisitSwitchSection(SwitchSection switchSection);
+		void VisitCaseLabel(CaseLabel caseLabel);
+		void VisitThrowStatement(ThrowStatement throwStatement);
+		void VisitTryCatchStatement(TryCatchStatement tryCatchStatement);
+		void VisitCatchClause(CatchClause catchClause);
+		void VisitUncheckedStatement(UncheckedStatement uncheckedStatement);
+		void VisitUnsafeStatement(UnsafeStatement unsafeStatement);
+		void VisitUsingStatement(UsingStatement usingStatement);
+		void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement);
+		void VisitWhileStatement(WhileStatement whileStatement);
+		void VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement);
+		void VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement);
+		
+		void VisitAccessor(Accessor accessor);
+		void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration);
+		void VisitConstructorInitializer(ConstructorInitializer constructorInitializer);
+		void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration);
+		void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration);
+		void VisitEventDeclaration(EventDeclaration eventDeclaration);
+		void VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration);
+		void VisitFieldDeclaration(FieldDeclaration fieldDeclaration);
+		void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration);
+		void VisitMethodDeclaration(MethodDeclaration methodDeclaration);
+		void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration);
+		void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration);
+		void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration);
+		void VisitVariableInitializer(VariableInitializer variableInitializer);
+		void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration);
+		void VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer);
+		
+		void VisitSyntaxTree(SyntaxTree syntaxTree);
+		void VisitSimpleType(SimpleType simpleType);
+		void VisitMemberType(MemberType memberType);
+		void VisitComposedType(ComposedType composedType);
+		void VisitArraySpecifier(ArraySpecifier arraySpecifier);
+		void VisitPrimitiveType(PrimitiveType primitiveType);
+		
+		void VisitComment(Comment comment);
+		void VisitNewLine(NewLineNode newLineNode);
+		void VisitWhitespace(WhitespaceNode whitespaceNode);
+		void VisitText(TextNode textNode);
+		void VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective);
+		void VisitDocumentationReference(DocumentationReference documentationReference);
+		
+		void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration);
+		void VisitConstraint(Constraint constraint);
+		void VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode);
+		void VisitIdentifier(Identifier identifier);
+		
+		void VisitNullNode(AstNode nullNode);
+		void VisitErrorNode(AstNode errorNode);
+		void VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern);
+	}
+	
+	/// <summary>
+	/// AST visitor.
+	/// </summary>
+	public interface IAstVisitor<out S>
+	{
+		S VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression);
+		S VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression);
+		S VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression);
+		S VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression);
+		S VisitAsExpression(AsExpression asExpression);
+		S VisitAssignmentExpression(AssignmentExpression assignmentExpression);
+		S VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression);
+		S VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression);
+		S VisitCastExpression(CastExpression castExpression);
+		S VisitCheckedExpression(CheckedExpression checkedExpression);
+		S VisitConditionalExpression(ConditionalExpression conditionalExpression);
+		S VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression);
+		S VisitDirectionExpression(DirectionExpression directionExpression);
+		S VisitIdentifierExpression(IdentifierExpression identifierExpression);
+		S VisitIndexerExpression(IndexerExpression indexerExpression);
+		S VisitInvocationExpression(InvocationExpression invocationExpression);
+		S VisitIsExpression(IsExpression isExpression);
+		S VisitLambdaExpression(LambdaExpression lambdaExpression);
+		S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression);
+		S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression);
+		S VisitNamedExpression(NamedExpression namedExpression);
+		S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression);
+		S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression);
+		S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression);
+		S VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression);
+		S VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression);
+		S VisitPrimitiveExpression(PrimitiveExpression primitiveExpression);
+		S VisitSizeOfExpression(SizeOfExpression sizeOfExpression);
+		S VisitStackAllocExpression(StackAllocExpression stackAllocExpression);
+		S VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression);
+		S VisitTypeOfExpression(TypeOfExpression typeOfExpression);
+		S VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression);
+		S VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression);
+		S VisitUncheckedExpression(UncheckedExpression uncheckedExpression);
+
+		S VisitQueryExpression(QueryExpression queryExpression);
+		S VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause);
+		S VisitQueryFromClause(QueryFromClause queryFromClause);
+		S VisitQueryLetClause(QueryLetClause queryLetClause);
+		S VisitQueryWhereClause(QueryWhereClause queryWhereClause);
+		S VisitQueryJoinClause(QueryJoinClause queryJoinClause);
+		S VisitQueryOrderClause(QueryOrderClause queryOrderClause);
+		S VisitQueryOrdering(QueryOrdering queryOrdering);
+		S VisitQuerySelectClause(QuerySelectClause querySelectClause);
+		S VisitQueryGroupClause(QueryGroupClause queryGroupClause);
+		
+		S VisitAttribute(Attribute attribute);
+		S VisitAttributeSection(AttributeSection attributeSection);
+		S VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration);
+		S VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration);
+		S VisitTypeDeclaration(TypeDeclaration typeDeclaration);
+		S VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration);
+		S VisitUsingDeclaration(UsingDeclaration usingDeclaration);
+		S VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration);
+		
+		S VisitBlockStatement(BlockStatement blockStatement);
+		S VisitBreakStatement(BreakStatement breakStatement);
+		S VisitCheckedStatement(CheckedStatement checkedStatement);
+		S VisitContinueStatement(ContinueStatement continueStatement);
+		S VisitDoWhileStatement(DoWhileStatement doWhileStatement);
+		S VisitEmptyStatement(EmptyStatement emptyStatement);
+		S VisitExpressionStatement(ExpressionStatement expressionStatement);
+		S VisitFixedStatement(FixedStatement fixedStatement);
+		S VisitForeachStatement(ForeachStatement foreachStatement);
+		S VisitForStatement(ForStatement forStatement);
+		S VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement);
+		S VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement);
+		S VisitGotoStatement(GotoStatement gotoStatement);
+		S VisitIfElseStatement(IfElseStatement ifElseStatement);
+		S VisitLabelStatement(LabelStatement labelStatement);
+		S VisitLockStatement(LockStatement lockStatement);
+		S VisitReturnStatement(ReturnStatement returnStatement);
+		S VisitSwitchStatement(SwitchStatement switchStatement);
+		S VisitSwitchSection(SwitchSection switchSection);
+		S VisitCaseLabel(CaseLabel caseLabel);
+		S VisitThrowStatement(ThrowStatement throwStatement);
+		S VisitTryCatchStatement(TryCatchStatement tryCatchStatement);
+		S VisitCatchClause(CatchClause catchClause);
+		S VisitUncheckedStatement(UncheckedStatement uncheckedStatement);
+		S VisitUnsafeStatement(UnsafeStatement unsafeStatement);
+		S VisitUsingStatement(UsingStatement usingStatement);
+		S VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement);
+		S VisitWhileStatement(WhileStatement whileStatement);
+		S VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement);
+		S VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement);
+		
+		S VisitAccessor(Accessor accessor);
+		S VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration);
+		S VisitConstructorInitializer(ConstructorInitializer constructorInitializer);
+		S VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration);
+		S VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration);
+		S VisitEventDeclaration(EventDeclaration eventDeclaration);
+		S VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration);
+		S VisitFieldDeclaration(FieldDeclaration fieldDeclaration);
+		S VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration);
+		S VisitMethodDeclaration(MethodDeclaration methodDeclaration);
+		S VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration);
+		S VisitParameterDeclaration(ParameterDeclaration parameterDeclaration);
+		S VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration);
+		S VisitVariableInitializer(VariableInitializer variableInitializer);
+		S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration);
+		S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer);
+		
+		S VisitSyntaxTree(SyntaxTree syntaxTree);
+		S VisitSimpleType(SimpleType simpleType);
+		S VisitMemberType(MemberType memberType);
+		S VisitComposedType(ComposedType composedType);
+		S VisitArraySpecifier(ArraySpecifier arraySpecifier);
+		S VisitPrimitiveType(PrimitiveType primitiveType);
+		
+		S VisitComment(Comment comment);
+		S VisitWhitespace(WhitespaceNode whitespaceNode);
+		S VisitText(TextNode textNode);
+		S VisitNewLine(NewLineNode newLineNode);
+		S VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective);
+		S VisitDocumentationReference(DocumentationReference documentationReference);
+		
+		S VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration);
+		S VisitConstraint(Constraint constraint);
+		S VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode);
+		S VisitIdentifier(Identifier identifier);
+		
+		S VisitNullNode(AstNode nullNode);
+		S VisitErrorNode(AstNode errorNode);
+		S VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern);
+	}
+	
+	/// <summary>
+	/// AST visitor.
+	/// </summary>
+	public interface IAstVisitor<in T, out S>
+	{
+		S VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression, T data);
+		S VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression, T data);
+		S VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, T data);
+		S VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, T data);
+		S VisitAsExpression(AsExpression asExpression, T data);
+		S VisitAssignmentExpression(AssignmentExpression assignmentExpression, T data);
+		S VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression, T data);
+		S VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, T data);
+		S VisitCastExpression(CastExpression castExpression, T data);
+		S VisitCheckedExpression(CheckedExpression checkedExpression, T data);
+		S VisitConditionalExpression(ConditionalExpression conditionalExpression, T data);
+		S VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression, T data);
+		S VisitDirectionExpression(DirectionExpression directionExpression, T data);
+		S VisitIdentifierExpression(IdentifierExpression identifierExpression, T data);
+		S VisitIndexerExpression(IndexerExpression indexerExpression, T data);
+		S VisitInvocationExpression(InvocationExpression invocationExpression, T data);
+		S VisitIsExpression(IsExpression isExpression, T data);
+		S VisitLambdaExpression(LambdaExpression lambdaExpression, T data);
+		S VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression, T data);
+		S VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, T data);
+		S VisitNamedExpression(NamedExpression namedExpression, T data);
+		S VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression, T data);
+		S VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression, T data);
+		S VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, T data);
+		S VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, T data);
+		S VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression, T data);
+		S VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, T data);
+		S VisitSizeOfExpression(SizeOfExpression sizeOfExpression, T data);
+		S VisitStackAllocExpression(StackAllocExpression stackAllocExpression, T data);
+		S VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression, T data);
+		S VisitTypeOfExpression(TypeOfExpression typeOfExpression, T data);
+		S VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, T data);
+		S VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, T data);
+		S VisitUncheckedExpression(UncheckedExpression uncheckedExpression, T data);
+
+		S VisitQueryExpression(QueryExpression queryExpression, T data);
+		S VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause, T data);
+		S VisitQueryFromClause(QueryFromClause queryFromClause, T data);
+		S VisitQueryLetClause(QueryLetClause queryLetClause, T data);
+		S VisitQueryWhereClause(QueryWhereClause queryWhereClause, T data);
+		S VisitQueryJoinClause(QueryJoinClause queryJoinClause, T data);
+		S VisitQueryOrderClause(QueryOrderClause queryOrderClause, T data);
+		S VisitQueryOrdering(QueryOrdering queryOrdering, T data);
+		S VisitQuerySelectClause(QuerySelectClause querySelectClause, T data);
+		S VisitQueryGroupClause(QueryGroupClause queryGroupClause, T data);
+		
+		S VisitAttribute(Attribute attribute, T data);
+		S VisitAttributeSection(AttributeSection attributeSection, T data);
+		S VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, T data);
+		S VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, T data);
+		S VisitTypeDeclaration(TypeDeclaration typeDeclaration, T data);
+		S VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration, T data);
+		S VisitUsingDeclaration(UsingDeclaration usingDeclaration, T data);
+		S VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, T data);
+		
+		S VisitBlockStatement(BlockStatement blockStatement, T data);
+		S VisitBreakStatement(BreakStatement breakStatement, T data);
+		S VisitCheckedStatement(CheckedStatement checkedStatement, T data);
+		S VisitContinueStatement(ContinueStatement continueStatement, T data);
+		S VisitDoWhileStatement(DoWhileStatement doWhileStatement, T data);
+		S VisitEmptyStatement(EmptyStatement emptyStatement, T data);
+		S VisitExpressionStatement(ExpressionStatement expressionStatement, T data);
+		S VisitFixedStatement(FixedStatement fixedStatement, T data);
+		S VisitForeachStatement(ForeachStatement foreachStatement, T data);
+		S VisitForStatement(ForStatement forStatement, T data);
+		S VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement, T data);
+		S VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement, T data);
+		S VisitGotoStatement(GotoStatement gotoStatement, T data);
+		S VisitIfElseStatement(IfElseStatement ifElseStatement, T data);
+		S VisitLabelStatement(LabelStatement labelStatement, T data);
+		S VisitLockStatement(LockStatement lockStatement, T data);
+		S VisitReturnStatement(ReturnStatement returnStatement, T data);
+		S VisitSwitchStatement(SwitchStatement switchStatement, T data);
+		S VisitSwitchSection(SwitchSection switchSection, T data);
+		S VisitCaseLabel(CaseLabel caseLabel, T data);
+		S VisitThrowStatement(ThrowStatement throwStatement, T data);
+		S VisitTryCatchStatement(TryCatchStatement tryCatchStatement, T data);
+		S VisitCatchClause(CatchClause catchClause, T data);
+		S VisitUncheckedStatement(UncheckedStatement uncheckedStatement, T data);
+		S VisitUnsafeStatement(UnsafeStatement unsafeStatement, T data);
+		S VisitUsingStatement(UsingStatement usingStatement, T data);
+		S VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement, T data);
+		S VisitWhileStatement(WhileStatement whileStatement, T data);
+		S VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement, T data);
+		S VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement, T data);
+		
+		S VisitAccessor(Accessor accessor, T data);
+		S VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, T data);
+		S VisitConstructorInitializer(ConstructorInitializer constructorInitializer, T data);
+		S VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, T data);
+		S VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, T data);
+		S VisitEventDeclaration(EventDeclaration eventDeclaration, T data);
+		S VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration, T data);
+		S VisitFieldDeclaration(FieldDeclaration fieldDeclaration, T data);
+		S VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, T data);
+		S VisitMethodDeclaration(MethodDeclaration methodDeclaration, T data);
+		S VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, T data);
+		S VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, T data);
+		S VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, T data);
+		S VisitVariableInitializer(VariableInitializer variableInitializer, T data);
+		S VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, T data);
+		S VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer, T data);
+		
+		S VisitSyntaxTree(SyntaxTree syntaxTree, T data);
+		S VisitSimpleType(SimpleType simpleType, T data);
+		S VisitMemberType(MemberType memberType, T data);
+		S VisitComposedType(ComposedType composedType, T data);
+		S VisitArraySpecifier(ArraySpecifier arraySpecifier, T data);
+		S VisitPrimitiveType(PrimitiveType primitiveType, T data);
+		
+		S VisitComment(Comment comment, T data);
+		S VisitNewLine(NewLineNode newLineNode, T data);
+		S VisitWhitespace(WhitespaceNode whitespaceNode, T data);
+		S VisitText(TextNode textNode, T data);
+		S VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective, T data);
+		S VisitDocumentationReference(DocumentationReference documentationReference, T data);
+		
+		S VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, T data);
+		S VisitConstraint(Constraint constraint, T data);
+		S VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode, T data);
+		S VisitIdentifier(Identifier identifier, T data);
+		
+		S VisitNullNode(AstNode nullNode, T data);
+		S VisitErrorNode(AstNode errorNode, T data);
+		S VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern, T data);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Identifier.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Identifier.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Identifier.cs	(revision 11807)
@@ -0,0 +1,173 @@
+﻿// 
+// Identifier.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class Identifier : AstNode
+	{
+		public new static readonly Identifier Null = new NullIdentifier ();
+		sealed class NullIdentifier : Identifier
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Token;
+			}
+		}
+		
+		string name;
+		public string Name {
+			get { return this.name; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException("value");
+				ThrowIfFrozen();
+				this.name = value;
+			}
+		}
+		
+		TextLocation startLocation;
+		public override TextLocation StartLocation {
+			get {
+				return startLocation;
+			}
+		}
+		
+		internal void SetStartLocation(TextLocation value)
+		{
+			ThrowIfFrozen();
+			this.startLocation = value;
+		}
+		
+		const uint verbatimBit = 1u << AstNodeFlagsUsedBits;
+		
+		public bool IsVerbatim {
+			get {
+				return (flags & verbatimBit) != 0;
+			}
+			set {
+				ThrowIfFrozen();
+				if (value)
+					flags |= verbatimBit;
+				else
+					flags &= ~verbatimBit;
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (StartLocation.Line, StartLocation.Column + (Name ?? "").Length + (IsVerbatim ? 1 : 0));
+			}
+		}
+		
+		Identifier ()
+		{
+			this.name = string.Empty;
+		}
+		
+		protected Identifier (string name, TextLocation location)
+		{
+			if (name == null)
+				throw new ArgumentNullException("name");
+			this.Name = name;
+			this.startLocation = location;
+		}
+
+		public static Identifier Create (string name)
+		{
+			return Create (name, TextLocation.Empty);
+		}
+
+		public static Identifier Create (string name, TextLocation location)
+		{
+			if (string.IsNullOrEmpty(name))
+				return Identifier.Null;
+			if (name[0] == '@')
+				return new Identifier (name.Substring (1), new TextLocation (location.Line, location.Column + 1)) { IsVerbatim = true };
+			else
+				return new Identifier (name, location);
+		}
+		
+		public static Identifier Create (string name, TextLocation location, bool isVerbatim)
+		{
+			if (string.IsNullOrEmpty (name))
+				return Identifier.Null;
+			
+			if (isVerbatim)
+				return new Identifier (name, location) { IsVerbatim = true };
+			return new Identifier (name, location);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitIdentifier (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitIdentifier (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitIdentifier (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			Identifier o = other as Identifier;
+			return o != null && !o.IsNull && MatchString(this.Name, o.Name);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/IdentifierExpressionBackreference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/IdentifierExpressionBackreference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/IdentifierExpressionBackreference.cs	(revision 11807)
@@ -0,0 +1,54 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using ICSharpCode.NRefactory.PatternMatching;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Matches identifier expressions that have the same identifier as the referenced variable/type definition/method definition.
+	/// </summary>
+	public class IdentifierExpressionBackreference : Pattern
+	{
+		readonly string referencedGroupName;
+		
+		public string ReferencedGroupName {
+			get { return referencedGroupName; }
+		}
+		
+		public IdentifierExpressionBackreference(string referencedGroupName)
+		{
+			if (referencedGroupName == null)
+				throw new ArgumentNullException("referencedGroupName");
+			this.referencedGroupName = referencedGroupName;
+		}
+		
+		public override bool DoMatch(INode other, Match match)
+		{
+			CSharp.IdentifierExpression ident = other as CSharp.IdentifierExpression;
+			if (ident == null || ident.TypeArguments.Any())
+				return false;
+			CSharp.AstNode referenced = (CSharp.AstNode)match.Get(referencedGroupName).Last();
+			if (referenced == null)
+				return false;
+			return ident.Identifier == referenced.GetChildByRole(CSharp.Roles.Identifier).Name;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/MemberType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/MemberType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/MemberType.cs	(revision 11807)
@@ -0,0 +1,150 @@
+﻿// 
+// FullTypeName.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class MemberType : AstType
+	{
+		public static readonly Role<AstType> TargetRole = new Role<AstType>("Target", AstType.Null);
+		
+		bool isDoubleColon;
+		
+		public bool IsDoubleColon {
+			get { return isDoubleColon; }
+			set {
+				ThrowIfFrozen();
+				isDoubleColon = value;
+			}
+		}
+		
+		public AstType Target {
+			get { return GetChildByRole(TargetRole); }
+			set { SetChildByRole(TargetRole, value); }
+		}
+		
+		public string MemberName {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier MemberNameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public AstNodeCollection<AstType> TypeArguments {
+			get { return GetChildrenByRole (Roles.TypeArgument); }
+		}
+		
+		public MemberType ()
+		{
+		}
+		
+		public MemberType (AstType target, string memberName)
+		{
+			this.Target = target;
+			this.MemberName = memberName;
+		}
+		
+		public MemberType (AstType target, string memberName, IEnumerable<AstType> typeArguments)
+		{
+			this.Target = target;
+			this.MemberName = memberName;
+			foreach (var arg in typeArguments) {
+				AddChild (arg, Roles.TypeArgument);
+			}
+		}
+		
+		public MemberType (AstType target, string memberName, params AstType[] typeArguments) : this (target, memberName, (IEnumerable<AstType>)typeArguments)
+		{
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitMemberType (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitMemberType (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitMemberType (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			MemberType o = other as MemberType;
+			return o != null && this.IsDoubleColon == o.IsDoubleColon
+				&& MatchString(this.MemberName, o.MemberName) && this.Target.DoMatch(o.Target, match)
+				&& this.TypeArguments.DoMatch(o.TypeArguments, match);
+		}
+
+		public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null)
+		{
+			if (interningProvider == null)
+				interningProvider = InterningProvider.Dummy;
+			
+			TypeOrNamespaceReference t;
+			if (this.IsDoubleColon) {
+				SimpleType st = this.Target as SimpleType;
+				if (st != null) {
+					t = interningProvider.Intern(new AliasNamespaceReference(interningProvider.Intern(st.Identifier)));
+				} else {
+					t = null;
+				}
+			} else {
+				t = this.Target.ToTypeReference(lookupMode, interningProvider) as TypeOrNamespaceReference;
+			}
+			if (t == null)
+				return SpecialType.UnknownType;
+			var typeArguments = new List<ITypeReference>();
+			foreach (var ta in this.TypeArguments) {
+				typeArguments.Add(ta.ToTypeReference(lookupMode, interningProvider));
+			}
+			string memberName = interningProvider.Intern(this.MemberName);
+			return interningProvider.Intern(new MemberTypeOrNamespaceReference(t, memberName, interningProvider.InternList(typeArguments), lookupMode));
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Modifiers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Modifiers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Modifiers.cs	(revision 11807)
@@ -0,0 +1,65 @@
+﻿//
+// Modifiers.cs
+//
+// Author:
+//   Mike Krüger <mkrueger@novell.com>
+//
+// Copyright (C) 2008 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[Flags]
+	public enum Modifiers
+	{
+		None       = 0,
+		
+		Private   = 0x0001,
+		Internal  = 0x0002,
+		Protected = 0x0004,
+		Public    = 0x0008,
+		
+		Abstract  = 0x0010,
+		Virtual   = 0x0020,
+		Sealed    = 0x0040,
+		Static    = 0x0080,
+		Override  = 0x0100,
+		Readonly  = 0x0200,
+		Const     = 0x0400,
+		New       = 0x0800,
+		Partial   = 0x1000,
+		
+		Extern    = 0x2000,
+		Volatile  = 0x4000,
+		Unsafe    = 0x8000,
+		Async     = 0x10000,
+		
+		VisibilityMask = Private | Internal | Protected | Public,
+		
+		/// <summary>
+		/// Special value used to match any modifiers during pattern matching.
+		/// </summary>
+		Any = unchecked((int)0x80000000)
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/NodeType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/NodeType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/NodeType.cs	(revision 11807)
@@ -0,0 +1,56 @@
+﻿// 
+// NodeType.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum NodeType
+	{
+		Unknown,
+		/// <summary>
+		/// AstType
+		/// </summary>
+		TypeReference,
+		/// <summary>
+		/// Type or delegate declaration
+		/// </summary>
+		TypeDeclaration,
+		Member,
+		Statement,
+		Expression,
+		Token,
+		QueryClause,
+		/// <summary>
+		/// Comment or whitespace or pre-processor directive 
+		/// </summary>
+		Whitespace,
+		/// <summary>
+		/// Placeholder for a pattern
+		/// </summary>
+		Pattern
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ObservableAstVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ObservableAstVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/ObservableAstVisitor.cs	(revision 11807)
@@ -0,0 +1,857 @@
+﻿// 
+// ObservableAstVisitor.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class ObservableAstVisitor : IAstVisitor
+	{
+		void Visit<T>(Action<T> enter, Action<T> leave, T node) where T : AstNode
+		{
+			if (enter != null)
+				enter(node);
+			AstNode next;
+			for (var child = node.FirstChild; child != null; child = next) {
+				// Store next to allow the loop to continue
+				// if the visitor removes/replaces children.
+				next = child.NextSibling;
+				child.AcceptVisitor (this);
+			}
+			if (leave != null)
+				leave(node);
+		}
+
+		void IAstVisitor.VisitNullNode(AstNode nullNode)
+		{
+		}
+
+		void IAstVisitor.VisitErrorNode(AstNode nullNode)
+		{
+		}
+
+		public event Action<SyntaxTree> EnterSyntaxTree, LeaveSyntaxTree;
+		
+		void IAstVisitor.VisitSyntaxTree(SyntaxTree unit)
+		{
+			Visit(EnterSyntaxTree, LeaveSyntaxTree, unit);
+		}
+		
+		public event Action<Comment> EnterComment, LeaveComment;
+		
+		void IAstVisitor.VisitComment(Comment comment)
+		{
+			Visit(EnterComment, LeaveComment, comment);
+		}
+		
+		public event Action<NewLineNode> EnterNewLine, LeaveNewLine;
+		
+		void IAstVisitor.VisitNewLine(NewLineNode newLineNode)
+		{
+			Visit(EnterNewLine, LeaveNewLine, newLineNode);
+		}
+		
+		public event Action<WhitespaceNode> EnterWhitespace, LeaveWhitespace;
+		
+		void IAstVisitor.VisitWhitespace(WhitespaceNode whitespace)
+		{
+			Visit(EnterWhitespace, LeaveWhitespace, whitespace);
+		}
+		
+		public event Action<TextNode> EnterText, LeaveText;
+		
+		void IAstVisitor.VisitText(TextNode textNode)
+		{
+			Visit(EnterText, LeaveText, textNode);
+		}
+		
+		public event Action<PreProcessorDirective> EnterPreProcessorDirective, LeavePreProcessorDirective;
+		void IAstVisitor.VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective)
+		{
+			Visit(EnterPreProcessorDirective, LeavePreProcessorDirective, preProcessorDirective);
+		}
+		
+		public event Action<DocumentationReference> EnterDocumentationReference, LeaveDocumentationReference;
+		
+		void IAstVisitor.VisitDocumentationReference(DocumentationReference documentationReference)
+		{
+			Visit(EnterDocumentationReference, LeaveDocumentationReference, documentationReference);
+		}
+		
+		public event Action<Identifier> EnterIdentifier, LeaveIdentifier;
+		
+		void IAstVisitor.VisitIdentifier(Identifier identifier)
+		{
+			Visit(EnterIdentifier, LeaveIdentifier, identifier);
+		}
+		
+		public event Action<CSharpTokenNode> EnterCSharpTokenNode, LeaveCSharpTokenNode;
+		
+		void IAstVisitor.VisitCSharpTokenNode(CSharpTokenNode token)
+		{
+			Visit(EnterCSharpTokenNode, LeaveCSharpTokenNode, token);
+		}
+		
+		public event Action<PrimitiveType> EnterPrimitiveType, LeavePrimitiveType;
+		
+		void IAstVisitor.VisitPrimitiveType(PrimitiveType primitiveType)
+		{
+			Visit(EnterPrimitiveType, LeavePrimitiveType, primitiveType);
+		}
+		
+		public event Action<ComposedType> EnterComposedType, LeaveComposedType;
+		
+		void IAstVisitor.VisitComposedType(ComposedType composedType)
+		{
+			Visit(EnterComposedType, LeaveComposedType, composedType);
+		}
+		
+		public event Action<SimpleType> EnterSimpleType, LeaveSimpleType;
+		
+		void IAstVisitor.VisitSimpleType(SimpleType simpleType)
+		{
+			Visit(EnterSimpleType, LeaveSimpleType, simpleType);
+		}
+		
+		public event Action<MemberType> EnterMemberType, LeaveMemberType;
+		
+		void IAstVisitor.VisitMemberType(MemberType memberType)
+		{
+			Visit(EnterMemberType, LeaveMemberType, memberType);
+		}
+		
+		public event Action<Attribute> EnterAttribute, LeaveAttribute;
+		
+		void IAstVisitor.VisitAttribute(Attribute attribute)
+		{
+			Visit(EnterAttribute, LeaveAttribute, attribute);
+		}
+		
+		public event Action<AttributeSection> EnterAttributeSection, LeaveAttributeSection;
+		
+		void IAstVisitor.VisitAttributeSection(AttributeSection attributeSection)
+		{
+			Visit(EnterAttributeSection, LeaveAttributeSection, attributeSection);
+		}
+		
+		public event Action<DelegateDeclaration> EnterDelegateDeclaration, LeaveDelegateDeclaration;
+		
+		void IAstVisitor.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			Visit(EnterDelegateDeclaration, LeaveDelegateDeclaration, delegateDeclaration);
+		}
+		
+		public event Action<NamespaceDeclaration> EnterNamespaceDeclaration, LeaveNamespaceDeclaration;
+		
+		void IAstVisitor.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+		{
+			Visit(EnterNamespaceDeclaration, LeaveNamespaceDeclaration, namespaceDeclaration);
+		}
+		
+		public event Action<TypeDeclaration> EnterTypeDeclaration, LeaveTypeDeclaration;
+		
+		void IAstVisitor.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			Visit(EnterTypeDeclaration, LeaveTypeDeclaration, typeDeclaration);
+		}
+		
+		public event Action<TypeParameterDeclaration> EnterTypeParameterDeclaration, LeaveTypeParameterDeclaration;
+		
+		void IAstVisitor.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
+		{
+			Visit(EnterTypeParameterDeclaration, LeaveTypeParameterDeclaration, typeParameterDeclaration);
+		}
+		
+		public event Action<EnumMemberDeclaration> EnterEnumMemberDeclaration, LeaveEnumMemberDeclaration;
+		
+		void IAstVisitor.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
+		{
+			Visit(EnterEnumMemberDeclaration, LeaveEnumMemberDeclaration, enumMemberDeclaration);
+		}
+		
+		public event Action<UsingDeclaration> EnterUsingDeclaration, LeaveUsingDeclaration;
+		
+		void IAstVisitor.VisitUsingDeclaration(UsingDeclaration usingDeclaration)
+		{
+			Visit(EnterUsingDeclaration, LeaveUsingDeclaration, usingDeclaration);
+		}
+		
+		public event Action<UsingAliasDeclaration> EnterUsingAliasDeclaration, LeaveUsingAliasDeclaration;
+		
+		void IAstVisitor.VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration)
+		{
+			Visit(EnterUsingAliasDeclaration, LeaveUsingAliasDeclaration, usingDeclaration);
+		}
+		
+		public event Action<ExternAliasDeclaration> EnterExternAliasDeclaration, LeaveExternAliasDeclaration;
+		
+		void IAstVisitor.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			Visit(EnterExternAliasDeclaration, LeaveExternAliasDeclaration, externAliasDeclaration);
+		}
+		
+		public event Action<ConstructorDeclaration> EnterConstructorDeclaration, LeaveConstructorDeclaration;
+		
+		void IAstVisitor.VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			Visit(EnterConstructorDeclaration, LeaveConstructorDeclaration, constructorDeclaration);
+		}
+		
+		public event Action<ConstructorInitializer> EnterConstructorInitializer, LeaveConstructorInitializer;
+		
+		void IAstVisitor.VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
+		{
+			Visit(EnterConstructorInitializer, LeaveConstructorInitializer, constructorInitializer);
+		}
+		
+		public event Action<DestructorDeclaration> EnterDestructorDeclaration, LeaveDestructorDeclaration;
+		
+		void IAstVisitor.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			Visit(EnterDestructorDeclaration, LeaveDestructorDeclaration, destructorDeclaration);
+		}
+		
+		public event Action<EventDeclaration> EnterEventDeclaration, LeaveEventDeclaration;
+		
+		void IAstVisitor.VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			Visit(EnterEventDeclaration, LeaveEventDeclaration, eventDeclaration);
+		}
+		
+		public event Action<CustomEventDeclaration> EnterCustomEventDeclaration, LeaveCustomEventDeclaration;
+		
+		void IAstVisitor.VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
+		{
+			Visit(EnterCustomEventDeclaration, LeaveCustomEventDeclaration, eventDeclaration);
+		}
+		
+		public event Action<FieldDeclaration> EnterFieldDeclaration, LeaveFieldDeclaration;
+		
+		void IAstVisitor.VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			Visit(EnterFieldDeclaration, LeaveFieldDeclaration, fieldDeclaration);
+		}
+		
+		public event Action<FixedFieldDeclaration> EnterFixedFieldDeclaration, LeaveFixedFieldDeclaration;
+		
+		void IAstVisitor.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			Visit(EnterFixedFieldDeclaration, LeaveFixedFieldDeclaration, fixedFieldDeclaration);
+		}
+		
+		public event Action<FixedVariableInitializer> EnterFixedVariableInitializer, LeaveFixedVariableInitializer;
+		
+		void IAstVisitor.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
+		{
+			Visit(EnterFixedVariableInitializer, LeaveFixedVariableInitializer, fixedVariableInitializer);
+		}
+		
+		public event Action<IndexerDeclaration> EnterIndexerDeclaration, LeaveIndexerDeclaration;
+		
+		void IAstVisitor.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			Visit(EnterIndexerDeclaration, LeaveIndexerDeclaration, indexerDeclaration);
+		}
+		
+		public event Action<MethodDeclaration> EnterMethodDeclaration, LeaveMethodDeclaration;
+		
+		void IAstVisitor.VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			Visit(EnterMethodDeclaration, LeaveMethodDeclaration, methodDeclaration);
+		}
+		
+		public event Action<OperatorDeclaration> EnterOperatorDeclaration, LeaveOperatorDeclaration;
+		
+		void IAstVisitor.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+		{
+			Visit(EnterOperatorDeclaration, LeaveOperatorDeclaration, operatorDeclaration);
+		}
+		
+		public event Action<PropertyDeclaration> EnterPropertyDeclaration, LeavePropertyDeclaration;
+		
+		void IAstVisitor.VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			Visit(EnterPropertyDeclaration, LeavePropertyDeclaration, propertyDeclaration);
+		}
+		
+		public event Action<Accessor> EnterAccessor, LeaveAccessor;
+		
+		void IAstVisitor.VisitAccessor(Accessor accessor)
+		{
+			Visit(EnterAccessor, LeaveAccessor, accessor);
+		}
+		
+		public event Action<VariableInitializer> EnterVariableInitializer, LeaveVariableInitializer;
+		
+		void IAstVisitor.VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			Visit(EnterVariableInitializer, LeaveVariableInitializer, variableInitializer);
+		}
+		
+		public event Action<ParameterDeclaration> EnterParameterDeclaration, LeaveParameterDeclaration;
+		
+		void IAstVisitor.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			Visit(EnterParameterDeclaration, LeaveParameterDeclaration, parameterDeclaration);
+		}
+		
+		public event Action<Constraint> EnterConstraint, LeaveConstraint;
+		
+		void IAstVisitor.VisitConstraint(Constraint constraint)
+		{
+			Visit(EnterConstraint, LeaveConstraint, constraint);
+		}
+		
+		public event Action<BlockStatement> EnterBlockStatement, LeaveBlockStatement;
+		
+		void IAstVisitor.VisitBlockStatement(BlockStatement blockStatement)
+		{
+			Visit(EnterBlockStatement, LeaveBlockStatement, blockStatement);
+		}
+		
+		public event Action<ExpressionStatement> EnterExpressionStatement, LeaveExpressionStatement;
+		
+		void IAstVisitor.VisitExpressionStatement(ExpressionStatement expressionStatement)
+		{
+			Visit(EnterExpressionStatement, LeaveExpressionStatement, expressionStatement);
+		}
+		
+		public event Action<BreakStatement> EnterBreakStatement, LeaveBreakStatement;
+		
+		void IAstVisitor.VisitBreakStatement(BreakStatement breakStatement)
+		{
+			Visit(EnterBreakStatement, LeaveBreakStatement, breakStatement);
+		}
+		
+		public event Action<CheckedStatement> EnterCheckedStatement, LeaveCheckedStatement;
+		
+		void IAstVisitor.VisitCheckedStatement(CheckedStatement checkedStatement)
+		{
+			Visit(EnterCheckedStatement, LeaveCheckedStatement, checkedStatement);
+		}
+		
+		public event Action<ContinueStatement> EnterContinueStatement, LeaveContinueStatement;
+		
+		void IAstVisitor.VisitContinueStatement(ContinueStatement continueStatement)
+		{
+			Visit(EnterContinueStatement, LeaveContinueStatement, continueStatement);
+		}
+		
+		public event Action<DoWhileStatement> EnterDoWhileStatement, LeaveDoWhileStatement;
+		
+		void IAstVisitor.VisitDoWhileStatement(DoWhileStatement doWhileStatement)
+		{
+			Visit(EnterDoWhileStatement, LeaveDoWhileStatement, doWhileStatement);
+		}
+		
+		public event Action<EmptyStatement> EnterEmptyStatement, LeaveEmptyStatement;
+		
+		void IAstVisitor.VisitEmptyStatement(EmptyStatement emptyStatement)
+		{
+			Visit(EnterEmptyStatement, LeaveEmptyStatement, emptyStatement);
+		}
+		
+		public event Action<FixedStatement> EnterFixedStatement, LeaveFixedStatement;
+		
+		void IAstVisitor.VisitFixedStatement(FixedStatement fixedStatement)
+		{
+			Visit(EnterFixedStatement, LeaveFixedStatement, fixedStatement);
+		}
+		
+		public event Action<ForeachStatement> EnterForeachStatement, LeaveForeachStatement;
+		
+		void IAstVisitor.VisitForeachStatement(ForeachStatement foreachStatement)
+		{
+			Visit(EnterForeachStatement, LeaveForeachStatement, foreachStatement);
+		}
+		
+		public event Action<ForStatement> EnterForStatement, LeaveForStatement;
+		
+		void IAstVisitor.VisitForStatement(ForStatement forStatement)
+		{
+			Visit(EnterForStatement, LeaveForStatement, forStatement);
+		}
+		
+		public event Action<GotoCaseStatement> EnterGotoCaseStatement, LeaveGotoCaseStatement;
+		
+		void IAstVisitor.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
+		{
+			Visit(EnterGotoCaseStatement, LeaveGotoCaseStatement, gotoCaseStatement);
+		}
+		
+		public event Action<GotoDefaultStatement> EnterGotoDefaultStatement, LeaveGotoDefaultStatement;
+		
+		void IAstVisitor.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
+		{
+			Visit(EnterGotoDefaultStatement, LeaveGotoDefaultStatement, gotoDefaultStatement);
+		}
+		
+		public event Action<GotoStatement> EnterGotoStatement, LeaveGotoStatement;
+		
+		void IAstVisitor.VisitGotoStatement(GotoStatement gotoStatement)
+		{
+			Visit(EnterGotoStatement, LeaveGotoStatement, gotoStatement);
+		}
+		
+		public event Action<IfElseStatement> EnterIfElseStatement, LeaveIfElseStatement;
+		
+		void IAstVisitor.VisitIfElseStatement(IfElseStatement ifElseStatement)
+		{
+			Visit(EnterIfElseStatement, LeaveIfElseStatement, ifElseStatement);
+		}
+		
+		public event Action<LabelStatement> EnterLabelStatement, LeaveLabelStatement;
+		
+		void IAstVisitor.VisitLabelStatement(LabelStatement labelStatement)
+		{
+			Visit(EnterLabelStatement, LeaveLabelStatement, labelStatement);
+		}
+		
+		public event Action<LockStatement> EnterLockStatement, LeaveLockStatement;
+		
+		void IAstVisitor.VisitLockStatement(LockStatement lockStatement)
+		{
+			Visit(EnterLockStatement, LeaveLockStatement, lockStatement);
+		}
+		
+		public event Action<ReturnStatement> EnterReturnStatement, LeaveReturnStatement;
+		
+		void IAstVisitor.VisitReturnStatement(ReturnStatement returnStatement)
+		{
+			Visit(EnterReturnStatement, LeaveReturnStatement, returnStatement);
+		}
+		
+		public event Action<SwitchStatement> EnterSwitchStatement, LeaveSwitchStatement;
+		
+		void IAstVisitor.VisitSwitchStatement(SwitchStatement switchStatement)
+		{
+			Visit(EnterSwitchStatement, LeaveSwitchStatement, switchStatement);
+		}
+		
+		public event Action<SwitchSection> EnterSwitchSection, LeaveSwitchSection;
+		
+		void IAstVisitor.VisitSwitchSection(SwitchSection switchSection)
+		{
+			Visit(EnterSwitchSection, LeaveSwitchSection, switchSection);
+		}
+		
+		public event Action<CaseLabel> EnterCaseLabel, LeaveCaseLabel;
+		
+		void IAstVisitor.VisitCaseLabel(CaseLabel caseLabel)
+		{
+			Visit(EnterCaseLabel, LeaveCaseLabel, caseLabel);
+		}
+		
+		public event Action<ThrowStatement> EnterThrowStatement, LeaveThrowStatement;
+		
+		void IAstVisitor.VisitThrowStatement(ThrowStatement throwStatement)
+		{
+			Visit(EnterThrowStatement, LeaveThrowStatement, throwStatement);
+		}
+		
+		public event Action<TryCatchStatement> EnterTryCatchStatement, LeaveTryCatchStatement;
+		
+		void IAstVisitor.VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
+		{
+			Visit(EnterTryCatchStatement, LeaveTryCatchStatement, tryCatchStatement);
+		}
+		
+		public event Action<CatchClause> EnterCatchClause, LeaveCatchClause;
+		
+		void IAstVisitor.VisitCatchClause(CatchClause catchClause)
+		{
+			Visit(EnterCatchClause, LeaveCatchClause, catchClause);
+		}
+		
+		public event Action<UncheckedStatement> EnterUncheckedStatement, LeaveUncheckedStatement;
+		
+		void IAstVisitor.VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
+		{
+			Visit(EnterUncheckedStatement, LeaveUncheckedStatement, uncheckedStatement);
+		}
+		
+		public event Action<UnsafeStatement> EnterUnsafeStatement, LeaveUnsafeStatement;
+		
+		void IAstVisitor.VisitUnsafeStatement(UnsafeStatement unsafeStatement)
+		{
+			Visit(EnterUnsafeStatement, LeaveUnsafeStatement, unsafeStatement);
+		}
+		
+		public event Action<UsingStatement> EnterUsingStatement, LeaveUsingStatement;
+		
+		void IAstVisitor.VisitUsingStatement(UsingStatement usingStatement)
+		{
+			Visit(EnterUsingStatement, LeaveUsingStatement, usingStatement);
+		}
+		
+		public event Action<VariableDeclarationStatement> EnterVariableDeclarationStatement, LeaveVariableDeclarationStatement;
+		
+		void IAstVisitor.VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
+		{
+			Visit(EnterVariableDeclarationStatement, LeaveVariableDeclarationStatement, variableDeclarationStatement);
+		}
+		
+		public event Action<WhileStatement> EnterWhileStatement, LeaveWhileStatement;
+		
+		void IAstVisitor.VisitWhileStatement(WhileStatement whileStatement)
+		{
+			Visit(EnterWhileStatement, LeaveWhileStatement, whileStatement);
+		}
+		
+		public event Action<YieldBreakStatement> EnterYieldBreakStatement, LeaveYieldBreakStatement;
+		
+		void IAstVisitor.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
+		{
+			Visit(EnterYieldBreakStatement, LeaveYieldBreakStatement, yieldBreakStatement);
+		}
+		
+		public event Action<YieldReturnStatement> EnterYieldReturnStatement, LeaveYieldReturnStatement;
+		
+		void IAstVisitor.VisitYieldReturnStatement(YieldReturnStatement yieldStatement)
+		{
+			Visit(EnterYieldReturnStatement, LeaveYieldReturnStatement, yieldStatement);
+		}
+		
+		public event Action<AnonymousMethodExpression> EnterAnonymousMethodExpression, LeaveAnonymousMethodExpression;
+		
+		void IAstVisitor.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
+		{
+			Visit(EnterAnonymousMethodExpression, LeaveAnonymousMethodExpression, anonymousMethodExpression);
+		}
+		
+		public event Action<LambdaExpression> EnterLambdaExpression, LeaveLambdaExpression;
+		
+		void IAstVisitor.VisitLambdaExpression(LambdaExpression lambdaExpression)
+		{
+			Visit(EnterLambdaExpression, LeaveLambdaExpression, lambdaExpression);
+		}
+		
+		public event Action<AssignmentExpression> EnterAssignmentExpression, LeaveAssignmentExpression;
+		
+		void IAstVisitor.VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+		{
+			Visit(EnterAssignmentExpression, LeaveAssignmentExpression, assignmentExpression);
+		}
+		
+		public event Action<BaseReferenceExpression> EnterBaseReferenceExpression, LeaveBaseReferenceExpression;
+		
+		void IAstVisitor.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
+		{
+			Visit(EnterBaseReferenceExpression, LeaveBaseReferenceExpression, baseReferenceExpression);
+		}
+		
+		public event Action<BinaryOperatorExpression> EnterBinaryOperatorExpression, LeaveBinaryOperatorExpression;
+		
+		void IAstVisitor.VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+		{
+			Visit(EnterBinaryOperatorExpression, LeaveBinaryOperatorExpression, binaryOperatorExpression);
+		}
+		
+		public event Action<CastExpression> EnterCastExpression, LeaveCastExpression;
+		
+		void IAstVisitor.VisitCastExpression(CastExpression castExpression)
+		{
+			Visit(EnterCastExpression, LeaveCastExpression, castExpression);
+		}
+		
+		public event Action<CheckedExpression> EnterCheckedExpression, LeaveCheckedExpression;
+		
+		void IAstVisitor.VisitCheckedExpression(CheckedExpression checkedExpression)
+		{
+			Visit(EnterCheckedExpression, LeaveCheckedExpression, checkedExpression);
+		}
+		
+		public event Action<ConditionalExpression> EnterConditionalExpression, LeaveConditionalExpression;
+		
+		void IAstVisitor.VisitConditionalExpression(ConditionalExpression conditionalExpression)
+		{
+			Visit(EnterConditionalExpression, LeaveConditionalExpression, conditionalExpression);
+		}
+		
+		public event Action<IdentifierExpression> EnterIdentifierExpression, LeaveIdentifierExpression;
+		
+		void IAstVisitor.VisitIdentifierExpression(IdentifierExpression identifierExpression)
+		{
+			Visit(EnterIdentifierExpression, LeaveIdentifierExpression, identifierExpression);
+		}
+		
+		public event Action<IndexerExpression> EnterIndexerExpression, LeaveIndexerExpression;
+		
+		void IAstVisitor.VisitIndexerExpression(IndexerExpression indexerExpression)
+		{
+			Visit(EnterIndexerExpression, LeaveIndexerExpression, indexerExpression);
+		}
+		
+		public event Action<InvocationExpression> EnterInvocationExpression, LeaveInvocationExpression;
+		
+		void IAstVisitor.VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			Visit(EnterInvocationExpression, LeaveInvocationExpression, invocationExpression);
+		}
+		
+		public event Action<DirectionExpression> EnterDirectionExpression, LeaveDirectionExpression;
+		
+		void IAstVisitor.VisitDirectionExpression(DirectionExpression directionExpression)
+		{
+			Visit(EnterDirectionExpression, LeaveDirectionExpression, directionExpression);
+		}
+
+		public event Action<MemberReferenceExpression> EnterMemberReferenceExpression, LeaveMemberReferenceExpression;
+		
+		void IAstVisitor.VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			Visit(EnterMemberReferenceExpression, LeaveMemberReferenceExpression, memberReferenceExpression);
+		}
+		
+		public event Action<NullReferenceExpression> EnterNullReferenceExpression, LeaveNullReferenceExpression;
+		
+		void IAstVisitor.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
+		{
+			Visit(EnterNullReferenceExpression, LeaveNullReferenceExpression, nullReferenceExpression);
+		}
+		
+		public event Action<ObjectCreateExpression> EnterObjectCreateExpression, LeaveObjectCreateExpression;
+		
+		void IAstVisitor.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
+		{
+			Visit(EnterObjectCreateExpression, LeaveObjectCreateExpression, objectCreateExpression);
+		}
+		
+		public event Action<AnonymousTypeCreateExpression> EnterAnonymousTypeCreateExpression, LeaveAnonymousTypeCreateExpression;
+		
+		void IAstVisitor.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+		{
+			Visit(EnterAnonymousTypeCreateExpression, LeaveAnonymousTypeCreateExpression, anonymousTypeCreateExpression);
+		}
+		
+		public event Action<ArrayCreateExpression> EnterArrayCreateExpression, LeaveArrayCreateExpression;
+		
+		void IAstVisitor.VisitArrayCreateExpression(ArrayCreateExpression arraySCreateExpression)
+		{
+			Visit(EnterArrayCreateExpression, LeaveArrayCreateExpression, arraySCreateExpression);
+		}
+		
+		public event Action<ParenthesizedExpression> EnterParenthesizedExpression, LeaveParenthesizedExpression;
+		
+		void IAstVisitor.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
+		{
+			Visit(EnterParenthesizedExpression, LeaveParenthesizedExpression, parenthesizedExpression);
+		}
+		
+		public event Action<PointerReferenceExpression> EnterPointerReferenceExpression, LeavePointerReferenceExpression;
+		
+		void IAstVisitor.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
+		{
+			Visit(EnterPointerReferenceExpression, LeavePointerReferenceExpression, pointerReferenceExpression);
+		}
+		
+		public event Action<PrimitiveExpression> EnterPrimitiveExpression, LeavePrimitiveExpression;
+		
+		void IAstVisitor.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+		{
+			Visit(EnterPrimitiveExpression, LeavePrimitiveExpression, primitiveExpression);
+		}
+		
+		public event Action<SizeOfExpression> EnterSizeOfExpression, LeaveSizeOfExpression;
+		
+		void IAstVisitor.VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
+		{
+			Visit(EnterSizeOfExpression, LeaveSizeOfExpression, sizeOfExpression);
+		}
+		
+		public event Action<StackAllocExpression> EnterStackAllocExpression, LeaveStackAllocExpression;
+		
+		void IAstVisitor.VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
+		{
+			Visit(EnterStackAllocExpression, LeaveStackAllocExpression, stackAllocExpression);
+		}
+		
+		public event Action<ThisReferenceExpression> EnterThisReferenceExpression, LeaveThisReferenceExpression;
+		
+		void IAstVisitor.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
+		{
+			Visit(EnterThisReferenceExpression, LeaveThisReferenceExpression, thisReferenceExpression);
+		}
+		
+		public event Action<TypeOfExpression> EnterTypeOfExpression, LeaveTypeOfExpression;
+		
+		void IAstVisitor.VisitTypeOfExpression(TypeOfExpression typeOfExpression)
+		{
+			Visit(EnterTypeOfExpression, LeaveTypeOfExpression, typeOfExpression);
+		}
+		
+		public event Action<TypeReferenceExpression> EnterTypeReferenceExpression, LeaveTypeReferenceExpression;
+		
+		void IAstVisitor.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
+		{
+			Visit(EnterTypeReferenceExpression, LeaveTypeReferenceExpression, typeReferenceExpression);
+		}
+		
+		public event Action<UnaryOperatorExpression> EnterUnaryOperatorExpression, LeaveUnaryOperatorExpression;
+		
+		void IAstVisitor.VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+		{
+			Visit(EnterUnaryOperatorExpression, LeaveUnaryOperatorExpression, unaryOperatorExpression);
+		}
+		
+		public event Action<UncheckedExpression> EnterUncheckedExpression, LeaveUncheckedExpression;
+		
+		void IAstVisitor.VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
+		{
+			Visit(EnterUncheckedExpression, LeaveUncheckedExpression, uncheckedExpression);
+		}
+		
+		public event Action<QueryExpression> EnterQueryExpression, LeaveQueryExpression;
+		
+		void IAstVisitor.VisitQueryExpression(QueryExpression queryExpression)
+		{
+			Visit(EnterQueryExpression, LeaveQueryExpression, queryExpression);
+		}
+		
+		public event Action<QueryContinuationClause> EnterQueryContinuationClause, LeaveQueryContinuationClause;
+		
+		void IAstVisitor.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			Visit(EnterQueryContinuationClause, LeaveQueryContinuationClause, queryContinuationClause);
+		}
+		
+		public event Action<QueryFromClause> EnterQueryFromClause, LeaveQueryFromClause;
+		
+		void IAstVisitor.VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			Visit(EnterQueryFromClause, LeaveQueryFromClause, queryFromClause);
+		}
+		
+		public event Action<QueryLetClause> EnterQueryLetClause, LeaveQueryLetClause;
+		
+		void IAstVisitor.VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			Visit(EnterQueryLetClause, LeaveQueryLetClause, queryLetClause);
+		}
+		
+		public event Action<QueryWhereClause> EnterQueryWhereClause, LeaveQueryWhereClause;
+		
+		void IAstVisitor.VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			Visit(EnterQueryWhereClause, LeaveQueryWhereClause, queryWhereClause);
+		}
+		
+		public event Action<QueryJoinClause> EnterQueryJoinClause, LeaveQueryJoinClause;
+		
+		void IAstVisitor.VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			Visit(EnterQueryJoinClause, LeaveQueryJoinClause, queryJoinClause);
+		}
+		
+		public event Action<QueryOrderClause> EnterQueryOrderClause, LeaveQueryOrderClause;
+		
+		void IAstVisitor.VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			Visit(EnterQueryOrderClause, LeaveQueryOrderClause, queryOrderClause);
+		}
+		
+		public event Action<QueryOrdering> EnterQueryOrdering, LeaveQueryOrdering;
+		
+		void IAstVisitor.VisitQueryOrdering(QueryOrdering queryOrdering)
+		{
+			Visit(EnterQueryOrdering, LeaveQueryOrdering, queryOrdering);
+		}
+		
+		public event Action<QuerySelectClause> EnterQuerySelectClause, LeaveQuerySelectClause;
+		
+		void IAstVisitor.VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			Visit(EnterQuerySelectClause, LeaveQuerySelectClause, querySelectClause);
+		}
+		
+		public event Action<QueryGroupClause> EnterQueryGroupClause, LeaveQueryGroupClause;
+		
+		void IAstVisitor.VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			Visit(EnterQueryGroupClause, LeaveQueryGroupClause, queryGroupClause);
+		}
+		
+		public event Action<AsExpression> EnterAsExpression, LeaveAsExpression;
+		
+		void IAstVisitor.VisitAsExpression(AsExpression asExpression)
+		{
+			Visit(EnterAsExpression, LeaveAsExpression, asExpression);
+		}
+		
+		public event Action<IsExpression> EnterIsExpression, LeaveIsExpression;
+		
+		void IAstVisitor.VisitIsExpression(IsExpression isExpression)
+		{
+			Visit(EnterIsExpression, LeaveIsExpression, isExpression);
+		}
+		
+		public event Action<DefaultValueExpression> EnterDefaultValueExpression, LeaveDefaultValueExpression;
+		
+		void IAstVisitor.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
+		{
+			Visit(EnterDefaultValueExpression, LeaveDefaultValueExpression, defaultValueExpression);
+		}
+		
+		public event Action<UndocumentedExpression> EnterUndocumentedExpression, LeaveUndocumentedExpression;
+		
+		void IAstVisitor.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
+		{
+			Visit(EnterUndocumentedExpression, LeaveUndocumentedExpression, undocumentedExpression);
+		}
+		
+		public event Action<ArrayInitializerExpression> EnterArrayInitializerExpression, LeaveArrayInitializerExpression;
+		
+		void IAstVisitor.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
+		{
+			Visit(EnterArrayInitializerExpression, LeaveArrayInitializerExpression, arrayInitializerExpression);
+		}
+		
+		public event Action<ArraySpecifier> EnterArraySpecifier, LeaveArraySpecifier;
+		
+		void IAstVisitor.VisitArraySpecifier(ArraySpecifier arraySpecifier)
+		{
+			Visit(EnterArraySpecifier, LeaveArraySpecifier, arraySpecifier);
+		}
+		
+		public event Action<NamedArgumentExpression> EnterNamedArgumentExpression, LeaveNamedArgumentExpression;
+		
+		void IAstVisitor.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
+		{
+			Visit(EnterNamedArgumentExpression, LeaveNamedArgumentExpression, namedArgumentExpression);
+		}
+		
+		public event Action<NamedExpression> EnterNamedExpression, LeaveNamedExpression;
+		
+		void IAstVisitor.VisitNamedExpression(NamedExpression namedExpression)
+		{
+			Visit(EnterNamedExpression, LeaveNamedExpression, namedExpression);
+		}
+		
+		void IAstVisitor.VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/PrimitiveType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/PrimitiveType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/PrimitiveType.cs	(revision 11807)
@@ -0,0 +1,163 @@
+﻿// 
+// FullTypeName.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class PrimitiveType : AstType
+	{
+		TextLocation location;
+		string keyword = string.Empty;
+		
+		public string Keyword {
+			get { return keyword; }
+			set { 
+				if (value == null)
+					throw new ArgumentNullException();
+				ThrowIfFrozen();
+				keyword = value; 
+			}
+		}
+		
+		public KnownTypeCode KnownTypeCode {
+			get { return GetTypeCodeForPrimitiveType(this.Keyword); }
+		}
+		
+		public PrimitiveType()
+		{
+		}
+		
+		public PrimitiveType(string keyword)
+		{
+			this.Keyword = keyword;
+		}
+		
+		public PrimitiveType(string keyword, TextLocation location)
+		{
+			this.Keyword = keyword;
+			this.location = location;
+		}
+		
+		public override TextLocation StartLocation {
+			get {
+				return location;
+			}
+		}
+		
+		internal void SetStartLocation(TextLocation value)
+		{
+			ThrowIfFrozen();
+			this.location = value;
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (location.Line, location.Column + keyword.Length);
+			}
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitPrimitiveType (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitPrimitiveType (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitPrimitiveType (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			PrimitiveType o = other as PrimitiveType;
+			return o != null && MatchString(this.Keyword, o.Keyword);
+		}
+
+		public override string ToString(CSharpFormattingOptions formattingOptions)
+		{
+			return Keyword;
+		}
+		
+		public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null)
+		{
+			KnownTypeCode typeCode = GetTypeCodeForPrimitiveType(this.Keyword);
+			if (typeCode == KnownTypeCode.None)
+				return new UnknownType(null, this.Keyword);
+			else
+				return KnownTypeReference.Get(typeCode);
+		}
+		
+		public static KnownTypeCode GetTypeCodeForPrimitiveType(string keyword)
+		{
+			switch (keyword) {
+				case "string":
+					return KnownTypeCode.String;
+				case "int":
+					return KnownTypeCode.Int32;
+				case "uint":
+					return KnownTypeCode.UInt32;
+				case "object":
+					return KnownTypeCode.Object;
+				case "bool":
+					return KnownTypeCode.Boolean;
+				case "sbyte":
+					return KnownTypeCode.SByte;
+				case "byte":
+					return KnownTypeCode.Byte;
+				case "short":
+					return KnownTypeCode.Int16;
+				case "ushort":
+					return KnownTypeCode.UInt16;
+				case "long":
+					return KnownTypeCode.Int64;
+				case "ulong":
+					return KnownTypeCode.UInt64;
+				case "float":
+					return KnownTypeCode.Single;
+				case "double":
+					return KnownTypeCode.Double;
+				case "decimal":
+					return KnownTypeCode.Decimal;
+				case "char":
+					return KnownTypeCode.Char;
+				case "void":
+					return KnownTypeCode.Void;
+				default:
+					return KnownTypeCode.None;
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Roles.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Roles.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Roles.cs	(revision 11807)
@@ -0,0 +1,96 @@
+﻿// 
+// Roles.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin <http://xamarin.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public static class Roles
+	{
+		public static readonly Role<AstNode> Root = AstNode.RootRole;
+		
+		// some pre defined constants for common roles
+		public static readonly Role<Identifier> Identifier = new Role<Identifier> ("Identifier", CSharp.Identifier.Null);
+		public static readonly Role<BlockStatement> Body = new Role<BlockStatement> ("Body", CSharp.BlockStatement.Null);
+		public static readonly Role<ParameterDeclaration> Parameter = new Role<ParameterDeclaration> ("Parameter");
+		public static readonly Role<Expression> Argument = new Role<Expression> ("Argument", CSharp.Expression.Null);
+		public static readonly Role<AstType> Type = new Role<AstType> ("Type", CSharp.AstType.Null);
+		public static readonly Role<Expression> Expression = new Role<Expression> ("Expression", CSharp.Expression.Null);
+		public static readonly Role<Expression> TargetExpression = new Role<Expression> ("Target", CSharp.Expression.Null);
+		public readonly static Role<Expression> Condition = new Role<Expression> ("Condition", CSharp.Expression.Null);
+		public static readonly Role<TypeParameterDeclaration> TypeParameter = new Role<TypeParameterDeclaration> ("TypeParameter");
+		public static readonly Role<AstType> TypeArgument = new Role<AstType> ("TypeArgument", CSharp.AstType.Null);
+		public readonly static Role<Constraint> Constraint = new Role<Constraint> ("Constraint");
+		public static readonly Role<VariableInitializer> Variable = new Role<VariableInitializer> ("Variable", VariableInitializer.Null);
+		public static readonly Role<Statement> EmbeddedStatement = new Role<Statement> ("EmbeddedStatement", CSharp.Statement.Null);
+		public readonly static Role<EntityDeclaration> TypeMemberRole = new Role<EntityDeclaration> ("TypeMember");
+		
+
+		//			public static readonly TokenRole Keyword = new TokenRole ("Keyword", CSharpTokenNode.Null);
+//			public static readonly TokenRole InKeyword = new TokenRole ("InKeyword", CSharpTokenNode.Null);
+			
+		// some pre defined constants for most used punctuation
+		public static readonly TokenRole LPar = new TokenRole ("(");
+		public static readonly TokenRole RPar = new TokenRole (")");
+		public static readonly TokenRole LBracket = new TokenRole ("[");
+		public static readonly TokenRole RBracket = new TokenRole ("]");
+		public static readonly TokenRole LBrace = new TokenRole ("{");
+		public static readonly TokenRole RBrace = new TokenRole ("}");
+		public static readonly TokenRole LChevron = new TokenRole ("<");
+		public static readonly TokenRole RChevron = new TokenRole (">");
+		public static readonly TokenRole Comma = new TokenRole (",");
+		public static readonly TokenRole Dot = new TokenRole (".");
+		public static readonly TokenRole Semicolon = new TokenRole (";");
+		public static readonly TokenRole Assign = new TokenRole ("=");
+		public static readonly TokenRole Colon = new TokenRole (":");
+		public static readonly TokenRole DoubleColon = new TokenRole ("::");
+		public static readonly Role<Comment> Comment = new Role<Comment> ("Comment");
+		public static readonly Role<NewLineNode> NewLine = new Role<NewLineNode> ("NewLine");
+		public static readonly Role<WhitespaceNode> Whitespace = new Role<WhitespaceNode> ("Whitespace");
+		public static readonly Role<TextNode> Text = new Role<TextNode> ("Text");
+		public static readonly Role<PreProcessorDirective> PreProcessorDirective = new Role<PreProcessorDirective> ("PreProcessorDirective");
+		public static readonly Role<ErrorNode> Error = new Role<ErrorNode> ("Error");
+			
+		public readonly static Role<AstType> BaseType = new Role<AstType> ("BaseType", AstType.Null);
+
+		public static readonly Role<Attribute> Attribute = new Role<Attribute> ("Attribute");
+		public static readonly Role<CSharpTokenNode> AttributeTargetRole = new Role<CSharpTokenNode> ("AttributeTarget", CSharpTokenNode.Null);
+
+		public readonly static TokenRole WhereKeyword = new TokenRole ("where");
+		public readonly static Role<SimpleType> ConstraintTypeParameter = new Role<SimpleType> ("TypeParameter", SimpleType.Null);
+		public readonly static TokenRole DelegateKeyword = new TokenRole ("delegate");
+		public static readonly TokenRole ExternKeyword = new TokenRole ("extern");
+		public static readonly TokenRole AliasKeyword = new TokenRole ("alias");
+		public static readonly TokenRole NamespaceKeyword = new TokenRole ("namespace");
+
+		public static readonly TokenRole EnumKeyword = new TokenRole ("enum");
+		public static readonly TokenRole InterfaceKeyword = new TokenRole ("interface");
+		public static readonly TokenRole StructKeyword = new TokenRole ("struct");
+		public static readonly TokenRole ClassKeyword = new TokenRole ("class");
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SimpleType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SimpleType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SimpleType.cs	(revision 11807)
@@ -0,0 +1,169 @@
+﻿// 
+// FullTypeName.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class SimpleType : AstType
+	{
+		#region Null
+		public new static readonly SimpleType Null = new NullSimpleType ();
+		
+		sealed class NullSimpleType : SimpleType
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+			
+			public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider)
+			{
+				return SpecialType.UnknownType;
+			}
+		}
+		#endregion
+		
+		public SimpleType()
+		{
+		}
+		
+		public SimpleType(string identifier)
+		{
+			this.Identifier = identifier;
+		}
+		
+		public SimpleType (Identifier identifier)
+		{
+			this.IdentifierToken = identifier;
+		}
+		
+		public SimpleType(string identifier, TextLocation location)
+		{
+			SetChildByRole (Roles.Identifier, CSharp.Identifier.Create (identifier, location));
+		}
+		
+		public SimpleType (string identifier, IEnumerable<AstType> typeArguments)
+		{
+			this.Identifier = identifier;
+			foreach (var arg in typeArguments) {
+				AddChild (arg, Roles.TypeArgument);
+			}
+		}
+		
+		public SimpleType (string identifier, params AstType[] typeArguments) : this (identifier, (IEnumerable<AstType>)typeArguments)
+		{
+		}
+		
+		public string Identifier {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, CSharp.Identifier.Create (value));
+			}
+		}
+		
+		public Identifier IdentifierToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public AstNodeCollection<AstType> TypeArguments {
+			get { return GetChildrenByRole (Roles.TypeArgument); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitSimpleType (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitSimpleType (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitSimpleType (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			SimpleType o = other as SimpleType;
+			return o != null && MatchString(this.Identifier, o.Identifier) && this.TypeArguments.DoMatch(o.TypeArguments, match);
+		}
+		
+		public override ITypeReference ToTypeReference(NameLookupMode lookupMode, InterningProvider interningProvider = null)
+		{
+			if (interningProvider == null)
+				interningProvider = InterningProvider.Dummy;
+			var typeArguments = new List<ITypeReference>();
+			foreach (var ta in this.TypeArguments) {
+				typeArguments.Add(ta.ToTypeReference(lookupMode, interningProvider));
+			}
+			string identifier = interningProvider.Intern(this.Identifier);
+			if (typeArguments.Count == 0 && string.IsNullOrEmpty(identifier)) {
+				// empty SimpleType is used for typeof(List<>).
+				return SpecialType.UnboundTypeArgument;
+			}
+			var t = new SimpleTypeOrNamespaceReference(identifier, interningProvider.InternList(typeArguments), lookupMode);
+			return interningProvider.Intern(t);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/BlockStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/BlockStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/BlockStatement.cs	(revision 11807)
@@ -0,0 +1,164 @@
+﻿// 
+// BlockStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// { Statements }
+	/// </summary>
+	public class BlockStatement : Statement, IEnumerable<Statement>
+	{
+		public static readonly Role<Statement> StatementRole = new Role<Statement>("Statement", Statement.Null);
+		
+		#region Null
+		public static readonly new BlockStatement Null = new NullBlockStatement ();
+		sealed class NullBlockStatement : BlockStatement
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+		
+		#region PatternPlaceholder
+		public static implicit operator BlockStatement(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : BlockStatement, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder(this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder(this, child);
+			}
+			
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+		
+		public AstNodeCollection<Statement> Statements {
+			get { return GetChildrenByRole (StatementRole); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitBlockStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitBlockStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitBlockStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			BlockStatement o = other as BlockStatement;
+			return o != null && !o.IsNull && this.Statements.DoMatch(o.Statements, match);
+		}
+		
+		public void Add(Statement statement)
+		{
+			AddChild(statement, StatementRole);
+		}
+		
+		IEnumerator<Statement> IEnumerable<Statement>.GetEnumerator()
+		{
+			return this.Statements.GetEnumerator();
+		}
+		
+		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+		{
+			return this.Statements.GetEnumerator();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/BreakStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/BreakStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/BreakStatement.cs	(revision 11807)
@@ -0,0 +1,65 @@
+﻿// 
+// BreakStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// break;
+	/// </summary>
+	public class BreakStatement : Statement
+	{
+		public static readonly TokenRole BreakKeywordRole = new TokenRole ("break");
+		
+		public CSharpTokenNode BreakToken {
+			get { return GetChildByRole (BreakKeywordRole); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitBreakStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitBreakStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitBreakStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			BreakStatement o = other as BreakStatement;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/CheckedStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/CheckedStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/CheckedStatement.cs	(revision 11807)
@@ -0,0 +1,75 @@
+﻿// 
+// CheckedStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// checked BodyBlock
+	/// </summary>
+	public class CheckedStatement : Statement
+	{
+		public static readonly TokenRole CheckedKeywordRole = new TokenRole ("checked");
+		
+		public CSharpTokenNode CheckedToken {
+			get { return GetChildByRole (CheckedKeywordRole); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public CheckedStatement ()
+		{
+		}
+		
+		public CheckedStatement (BlockStatement body)
+		{
+			AddChild (body, Roles.Body);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCheckedStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCheckedStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCheckedStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CheckedStatement o = other as CheckedStatement;
+			return o != null && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ContinueStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ContinueStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ContinueStatement.cs	(revision 11807)
@@ -0,0 +1,65 @@
+﻿// 
+// ContinueStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// continue;
+	/// </summary>
+	public class ContinueStatement : Statement
+	{
+		public static readonly TokenRole ContinueKeywordRole = new TokenRole ("continue");
+		
+		public CSharpTokenNode ContinueToken {
+			get { return GetChildByRole (ContinueKeywordRole); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitContinueStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitContinueStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitContinueStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ContinueStatement o = other as ContinueStatement;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/DoWhileStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/DoWhileStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/DoWhileStatement.cs	(revision 11807)
@@ -0,0 +1,99 @@
+﻿// 
+// DoWhileStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// "do EmbeddedStatement while(Condition);"
+	/// </summary>
+	public class DoWhileStatement : Statement
+	{
+		public static readonly TokenRole DoKeywordRole = new TokenRole ("do");
+		public static readonly TokenRole WhileKeywordRole = new TokenRole ("while");
+		
+		public CSharpTokenNode DoToken {
+			get { return GetChildByRole (DoKeywordRole); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public CSharpTokenNode WhileToken {
+			get { return GetChildByRole (WhileKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Condition {
+			get { return GetChildByRole (Roles.Condition); }
+			set { SetChildByRole (Roles.Condition, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitDoWhileStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitDoWhileStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitDoWhileStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			DoWhileStatement o = other as DoWhileStatement;
+			return o != null && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match) && this.Condition.DoMatch(o.Condition, match);
+		}
+
+		public DoWhileStatement()
+		{
+		}
+
+		public DoWhileStatement(Expression condition, Statement embeddedStatement)
+		{
+			this.Condition = condition;
+			this.EmbeddedStatement = embeddedStatement;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/EmptyStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/EmptyStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/EmptyStatement.cs	(revision 11807)
@@ -0,0 +1,72 @@
+﻿// 
+// EmptyStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// ;
+	/// </summary>
+	public class EmptyStatement : Statement
+	{
+		public TextLocation Location {
+			get;
+			set;
+		}
+		
+		public override TextLocation StartLocation {
+			get {
+				return Location;
+			}
+		}
+		
+		public override TextLocation EndLocation {
+			get {
+				return new TextLocation (Location.Line, Location.Column + 1);
+			}
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitEmptyStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitEmptyStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitEmptyStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			EmptyStatement o = other as EmptyStatement;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ExpressionStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ExpressionStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ExpressionStatement.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// 
+// ExpressionStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Expression;
+	/// </summary>
+	public class ExpressionStatement : Statement
+	{
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitExpressionStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitExpressionStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitExpressionStatement (this, data);
+		}
+		
+		public ExpressionStatement()
+		{
+		}
+		
+		public ExpressionStatement(Expression expression)
+		{
+			this.Expression = expression;
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ExpressionStatement o = other as ExpressionStatement;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/FixedStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/FixedStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/FixedStatement.cs	(revision 11807)
@@ -0,0 +1,85 @@
+﻿// 
+// FixedStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// fixed (Type Variables) EmbeddedStatement
+	/// </summary>
+	public class FixedStatement : Statement
+	{
+		public static readonly TokenRole FixedKeywordRole = new TokenRole ("fixed");
+		
+		public CSharpTokenNode FixedToken {
+			get { return GetChildByRole (FixedKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public AstNodeCollection<VariableInitializer> Variables {
+			get { return GetChildrenByRole (Roles.Variable); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitFixedStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitFixedStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitFixedStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			FixedStatement o = other as FixedStatement;
+			return o != null && this.Type.DoMatch(o.Type, match) && this.Variables.DoMatch(o.Variables, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ForStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ForStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ForStatement.cs	(revision 11807)
@@ -0,0 +1,97 @@
+﻿// 
+// ForStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// for (Initializers; Condition; Iterators) EmbeddedStatement
+	/// </summary>
+	public class ForStatement : Statement
+	{
+		public static readonly TokenRole ForKeywordRole = new TokenRole ("for");
+		public readonly static Role<Statement> InitializerRole = new Role<Statement>("Initializer", Statement.Null);
+		public readonly static Role<Statement> IteratorRole = new Role<Statement>("Iterator", Statement.Null);
+		
+		public CSharpTokenNode ForToken {
+			get { return GetChildByRole (ForKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		/// <summary>
+		/// Gets the list of initializer statements.
+		/// Note: this contains multiple statements for "for (a = 2, b = 1; a > b; a--)", but contains
+		/// only a single statement for "for (int a = 2, b = 1; a > b; a--)" (a single VariableDeclarationStatement with two variables)
+		/// </summary>
+		public AstNodeCollection<Statement> Initializers {
+			get { return GetChildrenByRole (InitializerRole); }
+		}
+		
+		public Expression Condition {
+			get { return GetChildByRole (Roles.Condition); }
+			set { SetChildByRole (Roles.Condition, value); }
+		}
+		
+		public AstNodeCollection<Statement> Iterators {
+			get { return GetChildrenByRole (IteratorRole); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitForStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitForStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitForStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ForStatement o = other as ForStatement;
+			return o != null && this.Initializers.DoMatch(o.Initializers, match) && this.Condition.DoMatch(o.Condition, match)
+				&& this.Iterators.DoMatch(o.Iterators, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ForeachStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ForeachStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ForeachStatement.cs	(revision 11807)
@@ -0,0 +1,108 @@
+﻿// 
+// ForeachStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// foreach (Type VariableName in InExpression) EmbeddedStatement
+	/// </summary>
+	public class ForeachStatement : Statement
+	{
+		public static readonly TokenRole ForeachKeywordRole = new TokenRole ("foreach");
+		public static readonly TokenRole InKeywordRole = new TokenRole ("in");
+		
+		public CSharpTokenNode ForeachToken {
+			get { return GetChildByRole (ForeachKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType VariableType {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public string VariableName {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier VariableNameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole(Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode InToken {
+			get { return GetChildByRole (InKeywordRole); }
+		}
+		
+		public Expression InExpression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitForeachStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitForeachStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitForeachStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ForeachStatement o = other as ForeachStatement;
+			return o != null && this.VariableType.DoMatch(o.VariableType, match) && MatchString(this.VariableName, o.VariableName)
+				&& this.InExpression.DoMatch(o.InExpression, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/GotoStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/GotoStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/GotoStatement.cs	(revision 11807)
@@ -0,0 +1,178 @@
+﻿// 
+// GotoStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// "goto Label;"
+	/// </summary>
+	public class GotoStatement : Statement
+	{
+		public static readonly TokenRole GotoKeywordRole = new TokenRole ("goto");
+		
+		public GotoStatement ()
+		{
+		}
+		
+		public GotoStatement (string label)
+		{
+			this.Label = label;
+		}
+		
+		public CSharpTokenNode GotoToken {
+			get { return GetChildByRole (GotoKeywordRole); }
+		}
+		
+		public string Label {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				if (string.IsNullOrEmpty(value))
+					SetChildByRole(Roles.Identifier, null);
+				else
+					SetChildByRole(Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitGotoStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitGotoStatement (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitGotoStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			GotoStatement o = other as GotoStatement;
+			return o != null && MatchString(this.Label, o.Label);
+		}
+	}
+	
+	/// <summary>
+	/// or "goto case LabelExpression;"
+	/// </summary>
+	public class GotoCaseStatement : Statement
+	{
+		public static readonly TokenRole GotoKeywordRole = new TokenRole ("goto");
+		public static readonly TokenRole CaseKeywordRole = new TokenRole ("case");
+		
+		public CSharpTokenNode GotoToken {
+			get { return GetChildByRole (GotoKeywordRole); }
+		}
+		
+		public CSharpTokenNode CaseToken {
+			get { return GetChildByRole (CaseKeywordRole); }
+		}
+		
+		/// <summary>
+		/// Used for "goto case LabelExpression;"
+		/// </summary>
+		public Expression LabelExpression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitGotoCaseStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitGotoCaseStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitGotoCaseStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			GotoCaseStatement o = other as GotoCaseStatement;
+			return o != null && this.LabelExpression.DoMatch(o.LabelExpression, match);
+		}
+	}
+	
+	/// <summary>
+	/// or "goto default;"
+	/// </summary>
+	public class GotoDefaultStatement : Statement
+	{
+		public static readonly TokenRole GotoKeywordRole = new TokenRole ("goto");
+		public static readonly TokenRole DefaultKeywordRole = new TokenRole ("default");
+		
+		public CSharpTokenNode GotoToken {
+			get { return GetChildByRole (GotoKeywordRole); }
+		}
+		
+		public CSharpTokenNode DefaultToken {
+			get { return GetChildByRole (DefaultKeywordRole); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitGotoDefaultStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitGotoDefaultStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitGotoDefaultStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			GotoDefaultStatement o = other as GotoDefaultStatement;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/IfElseStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/IfElseStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/IfElseStatement.cs	(revision 11807)
@@ -0,0 +1,103 @@
+﻿// 
+// IfElseStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// if (Condition) TrueStatement else FalseStatement
+	/// </summary>
+	public class IfElseStatement : Statement
+	{
+		public readonly static TokenRole IfKeywordRole = new TokenRole ("if");
+		public readonly static Role<Expression> ConditionRole = Roles.Condition;
+		public readonly static Role<Statement> TrueRole = new Role<Statement>("True", Statement.Null);
+		public readonly static TokenRole ElseKeywordRole = new TokenRole ("else");
+		public readonly static Role<Statement> FalseRole = new Role<Statement>("False", Statement.Null);
+		
+		public CSharpTokenNode IfToken {
+			get { return GetChildByRole (IfKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Condition {
+			get { return GetChildByRole (ConditionRole); }
+			set { SetChildByRole (ConditionRole, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement TrueStatement {
+			get { return GetChildByRole (TrueRole); }
+			set { SetChildByRole (TrueRole, value); }
+		}
+		
+		public CSharpTokenNode ElseToken {
+			get { return GetChildByRole (ElseKeywordRole); }
+		}
+		
+		public Statement FalseStatement {
+			get { return GetChildByRole (FalseRole); }
+			set { SetChildByRole (FalseRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitIfElseStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitIfElseStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitIfElseStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			IfElseStatement o = other as IfElseStatement;
+			return o != null && this.Condition.DoMatch(o.Condition, match) && this.TrueStatement.DoMatch(o.TrueStatement, match) && this.FalseStatement.DoMatch(o.FalseStatement, match);
+		}
+		
+		public IfElseStatement()
+		{
+		}
+		
+		public IfElseStatement(Expression condition, Statement trueStatement, Statement falseStatement = null)
+		{
+			this.Condition = condition;
+			this.TrueStatement = trueStatement;
+			this.FalseStatement = falseStatement;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/LabelStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/LabelStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/LabelStatement.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// 
+// LabelStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Label:
+	/// </summary>
+	public class LabelStatement : Statement
+	{
+		public string Label {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole(Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier LabelToken {
+			get { return GetChildByRole (Roles.Identifier); }
+			set { SetChildByRole (Roles.Identifier, value); }
+		}
+
+		public CSharpTokenNode ColonToken {
+			get { return GetChildByRole (Roles.Colon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitLabelStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitLabelStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitLabelStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			LabelStatement o = other as LabelStatement;
+			return o != null && MatchString(this.Label, o.Label);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/LockStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/LockStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/LockStatement.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// 
+// LockStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// lock (Expression) EmbeddedStatement;
+	/// </summary>
+	public class LockStatement : Statement
+	{
+		public static readonly TokenRole LockKeywordRole = new TokenRole ("lock");
+		
+		public CSharpTokenNode LockToken {
+			get { return GetChildByRole (LockKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitLockStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitLockStatement (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitLockStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			LockStatement o = other as LockStatement;
+			return o != null && this.Expression.DoMatch(o.Expression, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ReturnStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ReturnStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ReturnStatement.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// 
+// ReturnStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// return Expression;
+	/// </summary>
+	public class ReturnStatement : Statement
+	{
+		public static readonly TokenRole ReturnKeywordRole = new TokenRole ("return");
+
+		public CSharpTokenNode ReturnToken {
+			get { return GetChildByRole (ReturnKeywordRole); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public ReturnStatement ()
+		{
+		}
+		
+		public ReturnStatement (Expression returnExpression)
+		{
+			AddChild (returnExpression, Roles.Expression);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitReturnStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitReturnStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitReturnStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ReturnStatement o = other as ReturnStatement;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/Statement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/Statement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/Statement.cs	(revision 11807)
@@ -0,0 +1,132 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Base class for statements.
+	/// </summary>
+	/// <remarks>
+	/// This class is useful even though it doesn't provide any additional functionality:
+	/// It can be used to communicate more information in APIs, e.g. "this subnode will always be a statement"
+	/// </remarks>
+	public abstract class Statement : AstNode
+	{
+		#region Null
+		public new static readonly Statement Null = new NullStatement ();
+		
+		sealed class NullStatement : Statement
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+		
+		#region PatternPlaceholder
+		public static implicit operator Statement(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : Statement, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder(this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder(this, child);
+			}
+
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public new Statement Clone()
+		{
+			return (Statement)base.Clone();
+		}
+		
+		public Statement ReplaceWith(Func<Statement, Statement> replaceFunction)
+		{
+			if (replaceFunction == null)
+				throw new ArgumentNullException("replaceFunction");
+			return (Statement)base.ReplaceWith(node => replaceFunction((Statement)node));
+		}
+		
+		public override NodeType NodeType {
+			get { return NodeType.Statement; }
+		}
+
+		public static implicit operator Statement (Expression type)
+		{
+			return new ExpressionStatement(type);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/SwitchStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/SwitchStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/SwitchStatement.cs	(revision 11807)
@@ -0,0 +1,230 @@
+﻿// 
+// SwitchStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// switch (Expression) { SwitchSections }
+	/// </summary>
+	public class SwitchStatement : Statement
+	{
+		public static readonly TokenRole SwitchKeywordRole = new TokenRole ("switch");
+		public static readonly Role<SwitchSection> SwitchSectionRole = new Role<SwitchSection>("SwitchSection");
+		
+		public CSharpTokenNode SwitchToken {
+			get { return GetChildByRole (SwitchKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+		
+		public AstNodeCollection<SwitchSection> SwitchSections {
+			get { return GetChildrenByRole (SwitchSectionRole); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitSwitchStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitSwitchStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitSwitchStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			SwitchStatement o = other as SwitchStatement;
+			return o != null && this.Expression.DoMatch(o.Expression, match) && this.SwitchSections.DoMatch(o.SwitchSections, match);
+		}
+	}
+	
+	public class SwitchSection : AstNode
+	{
+		#region PatternPlaceholder
+		public static implicit operator SwitchSection(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : SwitchSection, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder(this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder(this, child);
+			}
+			
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public static readonly Role<CaseLabel> CaseLabelRole = new Role<CaseLabel>("CaseLabel");
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public AstNodeCollection<CaseLabel> CaseLabels {
+			get { return GetChildrenByRole (CaseLabelRole); }
+		}
+		
+		public AstNodeCollection<Statement> Statements {
+			get { return GetChildrenByRole (Roles.EmbeddedStatement); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitSwitchSection (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitSwitchSection (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitSwitchSection (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			SwitchSection o = other as SwitchSection;
+			return o != null && this.CaseLabels.DoMatch(o.CaseLabels, match) && this.Statements.DoMatch(o.Statements, match);
+		}
+	}
+	
+	public class CaseLabel : AstNode
+	{
+		public static readonly TokenRole CaseKeywordRole = new TokenRole ("case");
+		public static readonly TokenRole DefaultKeywordRole = new TokenRole ("default");
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		/// <summary>
+		/// Gets or sets the expression. The expression can be null - if the expression is null, it's the default switch section.
+		/// </summary>
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+
+		public CSharpTokenNode ColonToken {
+			get { return GetChildByRole (Roles.Colon); }
+		}
+
+		public CaseLabel ()
+		{
+		}
+		
+		public CaseLabel (Expression expression)
+		{
+			this.Expression = expression;
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCaseLabel (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCaseLabel (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCaseLabel (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CaseLabel o = other as CaseLabel;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ThrowStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ThrowStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/ThrowStatement.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// 
+// ThrowStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// throw Expression;
+	/// </summary>
+	public class ThrowStatement : Statement
+	{
+		public static readonly TokenRole ThrowKeywordRole = new TokenRole ("throw");
+		
+		public CSharpTokenNode ThrowToken {
+			get { return GetChildByRole (ThrowKeywordRole); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public ThrowStatement ()
+		{
+		}
+		
+		public ThrowStatement (Expression expression)
+		{
+			AddChild (expression, Roles.Expression);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitThrowStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitThrowStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitThrowStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ThrowStatement o = other as ThrowStatement;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/TryCatchStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/TryCatchStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/TryCatchStatement.cs	(revision 11807)
@@ -0,0 +1,241 @@
+﻿// 
+// TryCatchStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// try TryBlock CatchClauses finally FinallyBlock
+	/// </summary>
+	public class TryCatchStatement : Statement
+	{
+		public static readonly TokenRole TryKeywordRole = new TokenRole ("try");
+		public static readonly Role<BlockStatement> TryBlockRole = new Role<BlockStatement>("TryBlock", BlockStatement.Null);
+		public static readonly Role<CatchClause> CatchClauseRole = new Role<CatchClause>("CatchClause", CatchClause.Null);
+		public static readonly TokenRole FinallyKeywordRole = new TokenRole ("finally");
+		public static readonly Role<BlockStatement> FinallyBlockRole = new Role<BlockStatement>("FinallyBlock", BlockStatement.Null);
+		
+		public CSharpTokenNode TryToken {
+			get { return GetChildByRole (TryKeywordRole); }
+		}
+		
+		public BlockStatement TryBlock {
+			get { return GetChildByRole (TryBlockRole); }
+			set { SetChildByRole (TryBlockRole, value); }
+		}
+		
+		public AstNodeCollection<CatchClause> CatchClauses {
+			get { return GetChildrenByRole (CatchClauseRole); }
+		}
+		
+		public CSharpTokenNode FinallyToken {
+			get { return GetChildByRole (FinallyKeywordRole); }
+		}
+		
+		public BlockStatement FinallyBlock {
+			get { return GetChildByRole (FinallyBlockRole); }
+			set { SetChildByRole (FinallyBlockRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitTryCatchStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitTryCatchStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitTryCatchStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			TryCatchStatement o = other as TryCatchStatement;
+			return o != null && this.TryBlock.DoMatch(o.TryBlock, match) && this.CatchClauses.DoMatch(o.CatchClauses, match) && this.FinallyBlock.DoMatch(o.FinallyBlock, match);
+		}
+	}
+	
+	/// <summary>
+	/// catch (Type VariableName) { Body }
+	/// </summary>
+	public class CatchClause : AstNode
+	{
+		public static readonly TokenRole CatchKeywordRole = new TokenRole ("catch");
+
+		#region Null
+		public new static readonly CatchClause Null = new NullCatchClause ();
+		
+		sealed class NullCatchClause : CatchClause
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+
+		#region PatternPlaceholder
+		public static implicit operator CatchClause(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : CatchClause, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder(this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder(this, child);
+			}
+
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public CSharpTokenNode CatchToken {
+			get { return GetChildByRole (CatchKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public string VariableName {
+			get { return GetChildByRole (Roles.Identifier).Name; }
+			set {
+				if (string.IsNullOrEmpty(value))
+					SetChildByRole (Roles.Identifier, null);
+				else
+					SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier VariableNameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole(Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCatchClause (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCatchClause (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCatchClause (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CatchClause o = other as CatchClause;
+			return o != null && this.Type.DoMatch(o.Type, match) && MatchString(this.VariableName, o.VariableName) && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UncheckedStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UncheckedStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UncheckedStatement.cs	(revision 11807)
@@ -0,0 +1,75 @@
+﻿// 
+// UncheckedStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// unchecked BodyBlock
+	/// </summary>
+	public class UncheckedStatement : Statement
+	{
+		public static readonly TokenRole UncheckedKeywordRole = new TokenRole ("unchecked");
+		
+		public CSharpTokenNode UncheckedToken {
+			get { return GetChildByRole (UncheckedKeywordRole); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public UncheckedStatement ()
+		{
+		}
+		
+		public UncheckedStatement (BlockStatement body)
+		{
+			AddChild (body, Roles.Body);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUncheckedStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUncheckedStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUncheckedStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UncheckedStatement o = other as UncheckedStatement;
+			return o != null && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UnsafeStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UnsafeStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UnsafeStatement.cs	(revision 11807)
@@ -0,0 +1,66 @@
+﻿// 
+// UnsafeStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// unsafe { Body }
+	/// </summary>
+	public class UnsafeStatement : Statement
+	{
+		public static readonly TokenRole UnsafeKeywordRole = new TokenRole ("unsafe");
+		
+		public CSharpTokenNode UnsafeToken {
+			get { return GetChildByRole (UnsafeKeywordRole); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUnsafeStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUnsafeStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUnsafeStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UnsafeStatement o = other as UnsafeStatement;
+			return o != null && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UsingStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UsingStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/UsingStatement.cs	(revision 11807)
@@ -0,0 +1,83 @@
+﻿// 
+// UsingStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// using (ResourceAcquisition) EmbeddedStatement
+	/// </summary>
+	public class UsingStatement : Statement
+	{
+		public static readonly TokenRole UsingKeywordRole = new TokenRole ("using");
+		public static readonly Role<AstNode> ResourceAcquisitionRole = new Role<AstNode>("ResourceAcquisition", AstNode.Null);
+		
+		public CSharpTokenNode UsingToken {
+			get { return GetChildByRole (UsingKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		/// <summary>
+		/// Either a VariableDeclarationStatement, or an Expression.
+		/// </summary>
+		public AstNode ResourceAcquisition {
+			get { return GetChildByRole (ResourceAcquisitionRole); }
+			set { SetChildByRole (ResourceAcquisitionRole, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitUsingStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitUsingStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitUsingStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			UsingStatement o = other as UsingStatement;
+			return o != null && this.ResourceAcquisition.DoMatch(o.ResourceAcquisition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/VariableDeclarationStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/VariableDeclarationStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/VariableDeclarationStatement.cs	(revision 11807)
@@ -0,0 +1,90 @@
+﻿// 
+// VariableDeclarationStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class VariableDeclarationStatement : Statement
+	{
+		public static readonly Role<CSharpModifierToken> ModifierRole = EntityDeclaration.ModifierRole;
+		
+		public VariableDeclarationStatement()
+		{
+		}
+		
+		public VariableDeclarationStatement(AstType type, string name, Expression initializer = null)
+		{
+			this.Type = type;
+			this.Variables.Add(new VariableInitializer(name, initializer));
+		}
+		
+		public Modifiers Modifiers {
+			get { return EntityDeclaration.GetModifiers(this); }
+			set { EntityDeclaration.SetModifiers(this, value); }
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public AstNodeCollection<VariableInitializer> Variables {
+			get { return GetChildrenByRole (Roles.Variable); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public VariableInitializer GetVariable (string name)
+		{
+			return Variables.FirstOrNullObject (vi => vi.Name == name);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitVariableDeclarationStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitVariableDeclarationStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitVariableDeclarationStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			VariableDeclarationStatement o = other as VariableDeclarationStatement;
+			return o != null && this.Modifiers == o.Modifiers && this.Type.DoMatch(o.Type, match) && this.Variables.DoMatch(o.Variables, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/WhileStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/WhileStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/WhileStatement.cs	(revision 11807)
@@ -0,0 +1,89 @@
+﻿// 
+// WhileStatement.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// "while (Condition) EmbeddedStatement"
+	/// </summary>
+	public class WhileStatement : Statement
+	{
+		public static readonly TokenRole WhileKeywordRole = new TokenRole ("while");
+		
+		public CSharpTokenNode WhileToken {
+			get { return GetChildByRole (WhileKeywordRole); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public Expression Condition {
+			get { return GetChildByRole (Roles.Condition); }
+			set { SetChildByRole (Roles.Condition, value); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public Statement EmbeddedStatement {
+			get { return GetChildByRole (Roles.EmbeddedStatement); }
+			set { SetChildByRole (Roles.EmbeddedStatement, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitWhileStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitWhileStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitWhileStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			WhileStatement o = other as WhileStatement;
+			return o != null && this.Condition.DoMatch(o.Condition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
+		}
+
+		public WhileStatement()
+		{
+		}
+
+		public WhileStatement(Expression condition, Statement embeddedStatement)
+		{
+			this.Condition = condition;
+			this.EmbeddedStatement = embeddedStatement;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/YieldBreakStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/YieldBreakStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/YieldBreakStatement.cs	(revision 11807)
@@ -0,0 +1,70 @@
+﻿// 
+// YieldBreakStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// yield break;
+	/// </summary>
+	public class YieldBreakStatement : Statement
+	{
+		public static readonly TokenRole YieldKeywordRole = new TokenRole ("yield");
+		public static readonly TokenRole BreakKeywordRole = new TokenRole ("break");
+		
+		public CSharpTokenNode YieldToken {
+			get { return GetChildByRole (YieldKeywordRole); }
+		}
+		
+		public CSharpTokenNode BreakToken {
+			get { return GetChildByRole (BreakKeywordRole); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitYieldBreakStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitYieldBreakStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitYieldBreakStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			YieldBreakStatement o = other as YieldBreakStatement;
+			return o != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/YieldReturnStatement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/YieldReturnStatement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/Statements/YieldReturnStatement.cs	(revision 11807)
@@ -0,0 +1,75 @@
+﻿// 
+// YieldStatement.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// yield return Expression;
+	/// </summary>
+	public class YieldReturnStatement : Statement
+	{
+		public static readonly TokenRole YieldKeywordRole = new TokenRole ("yield");
+		public static readonly TokenRole ReturnKeywordRole = new TokenRole ("return");
+		
+		public CSharpTokenNode YieldToken {
+			get { return GetChildByRole (YieldKeywordRole); }
+		}
+		
+		public CSharpTokenNode ReturnToken {
+			get { return GetChildByRole (ReturnKeywordRole); }
+		}
+		
+		public Expression Expression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitYieldReturnStatement (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitYieldReturnStatement (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitYieldReturnStatement (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			YieldReturnStatement o = other as YieldReturnStatement;
+			return o != null && this.Expression.DoMatch(o.Expression, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SyntaxExtensions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SyntaxExtensions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SyntaxExtensions.cs	(revision 11807)
@@ -0,0 +1,45 @@
+﻿// Copyright (c) 2013 Daniel Grunwald
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Extension methods for the syntax tree.
+	/// </summary>
+	public static class SyntaxExtensions
+	{
+		public static bool IsComparisonOperator(this OperatorType operatorType)
+		{
+			switch (operatorType) {
+				case OperatorType.Equality:
+				case OperatorType.Inequality:
+				case OperatorType.GreaterThan:
+				case OperatorType.LessThan:
+				case OperatorType.GreaterThanOrEqual:
+				case OperatorType.LessThanOrEqual:
+					return true;
+				default:
+					return false;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SyntaxTree.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SyntaxTree.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/SyntaxTree.cs	(revision 11807)
@@ -0,0 +1,193 @@
+﻿// 
+// SyntaxTree.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Threading;
+using Mono.CSharp;
+using System.IO;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[Obsolete("CompilationUnit was renamed to SyntaxTree", true)]
+	public class CompilationUnit {}
+	
+	public class SyntaxTree : AstNode
+	{
+		public static readonly Role<AstNode> MemberRole = new Role<AstNode>("Member", AstNode.Null);
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		string fileName;
+		
+		/// <summary>
+		/// Gets/Sets the file name of this syntax tree.
+		/// </summary>
+		public string FileName {
+			get { return fileName; }
+			set {
+				ThrowIfFrozen();
+				fileName = value;
+			}
+		}
+		
+		public AstNodeCollection<AstNode> Members {
+			get { return GetChildrenByRole(MemberRole); }
+		}
+
+		IList<string> conditionalSymbols = null;
+
+		List<Error> errors = new List<Error> ();
+		
+		public List<Error> Errors {
+			get { return errors; }
+		}
+
+
+		/// <summary>
+		/// Gets the conditional symbols used to parse the source file. Note that this list contains
+		/// the conditional symbols at the start of the first token in the file - including the ones defined
+		/// in the source file.
+		/// </summary>
+		public IList<string> ConditionalSymbols {
+			get {
+				return conditionalSymbols ?? EmptyList<string>.Instance;
+			}
+			internal set {
+				conditionalSymbols = value;
+			}
+		}
+
+		/// <summary>
+		/// Gets the expression that was on top of the parse stack.
+		/// This is the only way to get an expression that isn't part of a statment.
+		/// (eg. when an error follows an expression).
+		/// 
+		/// This is used for code completion to 'get the expression before a token - like ., &lt;, ('.
+		/// </summary>
+		public AstNode TopExpression {
+			get;
+			internal set;
+		}
+		
+		public SyntaxTree ()
+		{
+		}
+		
+		/// <summary>
+		/// Gets all defined types in this syntax tree.
+		/// </summary>
+		/// <returns>
+		/// A list containing <see cref="TypeDeclaration"/> or <see cref="DelegateDeclaration"/> nodes.
+		/// </returns>
+		public IEnumerable<EntityDeclaration> GetTypes(bool includeInnerTypes = false)
+		{
+			Stack<AstNode> nodeStack = new Stack<AstNode> ();
+			nodeStack.Push(this);
+			while (nodeStack.Count > 0) {
+				var curNode = nodeStack.Pop();
+				if (curNode is TypeDeclaration || curNode is DelegateDeclaration) {
+					yield return (EntityDeclaration)curNode;
+				}
+				foreach (var child in curNode.Children) {
+					if (!(child is Statement || child is Expression) &&
+					    (child.Role != Roles.TypeMemberRole || ((child is TypeDeclaration || child is DelegateDeclaration) && includeInnerTypes)))
+						nodeStack.Push (child);
+				}
+			}
+		}
+
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			SyntaxTree o = other as SyntaxTree;
+			return o != null && this.Members.DoMatch(o.Members, match);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitSyntaxTree (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitSyntaxTree (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitSyntaxTree (this, data);
+		}
+		
+		/// <summary>
+		/// Converts this syntax tree into a parsed file that can be stored in the type system.
+		/// </summary>
+		public CSharpUnresolvedFile ToTypeSystem ()
+		{
+			if (string.IsNullOrEmpty (this.FileName))
+				throw new InvalidOperationException ("Cannot use ToTypeSystem() on a syntax tree without file name.");
+			var v = new TypeSystemConvertVisitor (this.FileName);
+			v.VisitSyntaxTree (this);
+			return v.UnresolvedFile;
+		}
+		
+		public static SyntaxTree Parse (string program, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+			var parser = new CSharpParser (settings);
+			return parser.Parse (program, fileName);
+		}
+		
+		public static SyntaxTree Parse (TextReader reader, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+			var parser = new CSharpParser (settings);
+			return parser.Parse (reader, fileName);
+		}
+		
+		public static SyntaxTree Parse (Stream stream, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+			var parser = new CSharpParser (settings);
+			return parser.Parse (stream, fileName);
+		}
+		
+		public static SyntaxTree Parse (ITextSource textSource, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))
+		{
+			cancellationToken.ThrowIfCancellationRequested();
+			var parser = new CSharpParser (settings);
+			return parser.Parse (textSource, fileName);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TokenRole.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TokenRole.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TokenRole.cs	(revision 11807)
@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// A specific role only used for C# tokens
+	/// </summary>
+	public sealed class TokenRole : Role<CSharpTokenNode>
+	{
+		internal readonly static List<string> Tokens = new List<string> ();
+		internal readonly static List<int>    TokenLengths = new List<int> ();
+		internal readonly uint TokenIndex;
+
+		static TokenRole ()
+		{
+			// null token
+			Tokens.Add ("");
+			TokenLengths.Add (0);
+		}
+
+		/// <summary>
+		/// Gets the token as string. Note that the token Name and Token value may differ.
+		/// </summary>
+		public string Token {
+			get;
+			private set;
+		}
+		
+		/// <summary>
+		/// Gets the char length of the token.
+		/// </summary>
+		public int Length {
+			get;
+			private set;
+		}
+
+
+		public TokenRole(string token) : base (token, CSharpTokenNode.Null)
+		{
+			this.Token = token;
+			this.Length = token.Length;
+
+			bool found = false;
+			for (int i = 0; i < Tokens.Count; i++) {
+				var existingToken = Tokens [i];
+				if (existingToken == token) {
+					TokenIndex = (uint)i;
+					found = true;
+					break;
+				}
+			}
+			if (!found) {
+				TokenIndex = (uint)Tokens.Count;
+				Tokens.Add (token);
+				TokenLengths.Add (this.Length);
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/Accessor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/Accessor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/Accessor.cs	(revision 11807)
@@ -0,0 +1,117 @@
+﻿// 
+// PropertyDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// get/set/add/remove
+	/// </summary>
+	public class Accessor : EntityDeclaration
+	{
+		public static readonly new Accessor Null = new NullAccessor ();
+		sealed class NullAccessor : Accessor
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		
+		public override NodeType NodeType {
+			get { return NodeType.Unknown; }
+		}
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Method; }
+		}
+		
+		/// <summary>
+		/// Gets the 'get'/'set'/'add'/'remove' keyword
+		/// </summary>
+		public CSharpTokenNode Keyword {
+			get {
+				for (AstNode child = this.FirstChild; child != null; child = child.NextSibling) {
+					if (child.Role == PropertyDeclaration.GetKeywordRole || child.Role == PropertyDeclaration.SetKeywordRole
+					    || child.Role == CustomEventDeclaration.AddKeywordRole || child.Role == CustomEventDeclaration.RemoveKeywordRole)
+					{
+						return (CSharpTokenNode)child;
+					}
+				}
+				return CSharpTokenNode.Null;
+			}
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitAccessor (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitAccessor (this);
+		}
+		
+		public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitAccessor (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			Accessor o = other as Accessor;
+			return o != null && !o.IsNull && this.MatchAttributesAndModifiers(o, match) && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/ConstructorDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/ConstructorDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/ConstructorDeclaration.cs	(revision 11807)
@@ -0,0 +1,190 @@
+﻿// 
+// ConstructorDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class ConstructorDeclaration : EntityDeclaration
+	{
+		public static readonly Role<ConstructorInitializer> InitializerRole = new Role<ConstructorInitializer>("Initializer", ConstructorInitializer.Null);
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Constructor; }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public CSharpTokenNode ColonToken {
+			get { return GetChildByRole (Roles.Colon); }
+		}
+		
+		public ConstructorInitializer Initializer {
+			get { return GetChildByRole (InitializerRole); }
+			set { SetChildByRole( InitializerRole, value); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitConstructorDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitConstructorDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitConstructorDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ConstructorDeclaration o = other as ConstructorDeclaration;
+			return o != null && this.MatchAttributesAndModifiers(o, match) && this.Parameters.DoMatch(o.Parameters, match)
+				&& this.Initializer.DoMatch(o.Initializer, match) && this.Body.DoMatch(o.Body, match);
+		}
+	}
+	
+	public enum ConstructorInitializerType {
+		Any,
+		Base,
+		This
+	}
+	
+	public class ConstructorInitializer : AstNode
+	{
+		public static readonly TokenRole BaseKeywordRole = new TokenRole ("base");
+		public static readonly TokenRole ThisKeywordRole = new TokenRole ("this");
+		
+		public static readonly new ConstructorInitializer Null = new NullConstructorInitializer ();
+		class NullConstructorInitializer : ConstructorInitializer
+		{
+			public override NodeType NodeType {
+				get {
+					return NodeType.Unknown;
+				}
+			}
+			
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public ConstructorInitializerType ConstructorInitializerType {
+			get;
+			set;
+		}
+		
+		public CSharpTokenNode Keyword {
+			get {
+				if (ConstructorInitializerType == ConstructorInitializerType.Base)
+					return GetChildByRole(BaseKeywordRole);
+				else
+					return GetChildByRole(ThisKeywordRole);
+			}
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<Expression> Arguments {
+			get { return GetChildrenByRole (Roles.Argument); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitConstructorInitializer (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitConstructorInitializer (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitConstructorInitializer (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ConstructorInitializer o = other as ConstructorInitializer;
+			return o != null && !o.IsNull 
+				&& (this.ConstructorInitializerType == ConstructorInitializerType.Any || this.ConstructorInitializerType == o.ConstructorInitializerType)
+				&& this.Arguments.DoMatch(o.Arguments, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/DestructorDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/DestructorDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/DestructorDeclaration.cs	(revision 11807)
@@ -0,0 +1,76 @@
+﻿// 
+// DestructorDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class DestructorDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole TildeRole = new TokenRole ("~");
+		
+		public CSharpTokenNode TildeToken {
+			get { return GetChildByRole (TildeRole); }
+		}
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Destructor; }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitDestructorDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitDestructorDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitDestructorDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			DestructorDeclaration o = other as DestructorDeclaration;
+			return o != null && this.MatchAttributesAndModifiers(o, match) && this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EntityDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EntityDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EntityDeclaration.cs	(revision 11807)
@@ -0,0 +1,117 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public abstract class EntityDeclaration : AstNode
+	{
+		public static readonly Role<AttributeSection> AttributeRole = new Role<AttributeSection>("Attribute");
+		public static readonly Role<AttributeSection> UnattachedAttributeRole = new Role<AttributeSection>("UnattachedAttribute");
+		public static readonly Role<CSharpModifierToken> ModifierRole = new Role<CSharpModifierToken>("Modifier");
+		public static readonly Role<AstType> PrivateImplementationTypeRole = new Role<AstType>("PrivateImplementationType", AstType.Null);
+		
+		public override NodeType NodeType {
+			get { return NodeType.Member; }
+		}
+		
+		public abstract NRefactory.TypeSystem.SymbolKind SymbolKind { get; }
+		
+		public AstNodeCollection<AttributeSection> Attributes {
+			get { return base.GetChildrenByRole (AttributeRole); }
+		}
+		
+		public Modifiers Modifiers {
+			get { return GetModifiers(this); }
+			set { SetModifiers(this, value); }
+		}
+		
+		public bool HasModifier (Modifiers mod)
+		{
+			return (Modifiers & mod) == mod;
+		}
+		
+		public IEnumerable<CSharpModifierToken> ModifierTokens {
+			get { return GetChildrenByRole (ModifierRole); }
+		}
+		
+		public virtual string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value, TextLocation.Empty));
+			}
+		}
+		
+		public virtual Identifier NameToken {
+			get { return GetChildByRole (Roles.Identifier); }
+			set { SetChildByRole (Roles.Identifier, value); }
+		}
+		
+		public virtual AstType ReturnType {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole(Roles.Type, value); }
+		}
+
+		public CSharpTokenNode SemicolonToken {
+			get { return GetChildByRole (Roles.Semicolon); }
+		}
+
+		internal static Modifiers GetModifiers(AstNode node)
+		{
+			Modifiers m = 0;
+			foreach (CSharpModifierToken t in node.GetChildrenByRole (ModifierRole)) {
+				m |= t.Modifier;
+			}
+			return m;
+		}
+		
+		internal static void SetModifiers(AstNode node, Modifiers newValue)
+		{
+			Modifiers oldValue = GetModifiers(node);
+			AstNode insertionPos = node.GetChildrenByRole(AttributeRole).LastOrDefault();
+			foreach (Modifiers m in CSharpModifierToken.AllModifiers) {
+				if ((m & newValue) != 0) {
+					if ((m & oldValue) == 0) {
+						// Modifier was added
+						var newToken = new CSharpModifierToken(TextLocation.Empty, m);
+						node.InsertChildAfter(insertionPos, newToken, ModifierRole);
+						insertionPos = newToken;
+					} else {
+						// Modifier already exists
+						insertionPos = node.GetChildrenByRole(ModifierRole).First(t => t.Modifier == m);
+					}
+				} else {
+					if ((m & oldValue) != 0) {
+						// Modifier was removed
+						node.GetChildrenByRole (ModifierRole).First(t => t.Modifier == m).Remove();
+					}
+				}
+			}
+		}
+		
+		protected bool MatchAttributesAndModifiers (EntityDeclaration o, PatternMatching.Match match)
+		{
+			return (this.Modifiers == Modifiers.Any || this.Modifiers == o.Modifiers) && this.Attributes.DoMatch (o.Attributes, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EnumMemberDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EnumMemberDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EnumMemberDeclaration.cs	(revision 11807)
@@ -0,0 +1,72 @@
+﻿// 
+// EnumMemberDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class EnumMemberDeclaration : EntityDeclaration
+	{
+		public static readonly Role<Expression> InitializerRole = new Role<Expression>("Initializer", Expression.Null);
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Field; }
+		}
+
+		public CSharpTokenNode AssignToken {
+			get { return GetChildByRole (Roles.Assign); }
+		}
+
+		public Expression Initializer {
+			get { return GetChildByRole (InitializerRole); }
+			set { SetChildByRole (InitializerRole, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitEnumMemberDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitEnumMemberDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitEnumMemberDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			EnumMemberDeclaration o = other as EnumMemberDeclaration;
+			return o != null && this.MatchAttributesAndModifiers(o, match)
+				&& MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EventDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EventDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/EventDeclaration.cs	(revision 11807)
@@ -0,0 +1,152 @@
+﻿// 
+// EventDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class EventDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole EventKeywordRole = new TokenRole ("event");
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Event; }
+		}
+
+		public CSharpTokenNode EventToken {
+			get { return GetChildByRole (EventKeywordRole); }
+		}
+
+		public AstNodeCollection<VariableInitializer> Variables {
+			get { return GetChildrenByRole (Roles.Variable); }
+		}
+		
+		// Hide .Name and .NameToken from users; the actual field names
+		// are stored in the VariableInitializer.
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		public override string Name {
+			get { return string.Empty; }
+			set { throw new NotSupportedException(); }
+		}
+		
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		public override Identifier NameToken {
+			get { return Identifier.Null; }
+			set { throw new NotSupportedException(); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitEventDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitEventDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitEventDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			EventDeclaration o = other as EventDeclaration;
+			return o != null && this.MatchAttributesAndModifiers(o, match)
+				&& this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match);
+		}
+	}
+	
+	public class CustomEventDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole EventKeywordRole = new TokenRole ("event");
+		public static readonly TokenRole AddKeywordRole = new TokenRole ("add");
+		public static readonly TokenRole RemoveKeywordRole = new TokenRole ("remove");
+		
+		public static readonly Role<Accessor> AddAccessorRole = new Role<Accessor>("AddAccessor", Accessor.Null);
+		public static readonly Role<Accessor> RemoveAccessorRole = new Role<Accessor>("RemoveAccessor", Accessor.Null);
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Event; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the type reference of the interface that is explicitly implemented.
+		/// Null node if this member is not an explicit interface implementation.
+		/// </summary>
+		public AstType PrivateImplementationType {
+			get { return GetChildByRole (PrivateImplementationTypeRole); }
+			set { SetChildByRole (PrivateImplementationTypeRole, value); }
+		}
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+		
+		public Accessor AddAccessor {
+			get { return GetChildByRole (AddAccessorRole); }
+			set { SetChildByRole (AddAccessorRole, value); }
+		}
+		
+		public Accessor RemoveAccessor {
+			get { return GetChildByRole (RemoveAccessorRole); }
+			set { SetChildByRole (RemoveAccessorRole, value); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitCustomEventDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitCustomEventDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitCustomEventDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			CustomEventDeclaration o = other as CustomEventDeclaration;
+			return o != null && MatchString(this.Name, o.Name)
+				&& this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match)
+				&& this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match)
+				&& this.AddAccessor.DoMatch(o.AddAccessor, match) && this.RemoveAccessor.DoMatch(o.RemoveAccessor, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FieldDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FieldDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FieldDeclaration.cs	(revision 11807)
@@ -0,0 +1,79 @@
+﻿// 
+// FieldDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class FieldDeclaration : EntityDeclaration
+	{
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Field; }
+		}
+		
+		public AstNodeCollection<VariableInitializer> Variables {
+			get { return GetChildrenByRole (Roles.Variable); }
+		}
+		
+		// Hide .Name and .NameToken from users; the actual field names
+		// are stored in the VariableInitializer.
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		public override string Name {
+			get { return string.Empty; }
+			set { throw new NotSupportedException(); }
+		}
+		
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		public override Identifier NameToken {
+			get { return Identifier.Null; }
+			set { throw new NotSupportedException(); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitFieldDeclaration (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitFieldDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitFieldDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			FieldDeclaration o = other as FieldDeclaration;
+			return o != null && this.MatchAttributesAndModifiers(o, match)
+				&& this.ReturnType.DoMatch(o.ReturnType, match) && this.Variables.DoMatch(o.Variables, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FixedFieldDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FixedFieldDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FixedFieldDeclaration.cs	(revision 11807)
@@ -0,0 +1,71 @@
+﻿// 
+// FixedFieldDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class FixedFieldDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole FixedKeywordRole = new TokenRole ("fixed");
+		public static readonly Role<FixedVariableInitializer> VariableRole = new Role<FixedVariableInitializer> ("FixedVariable");
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Field; }
+		}
+		
+		public CSharpTokenNode FixedToken {
+			get { return GetChildByRole (FixedKeywordRole); }
+		}
+
+		public AstNodeCollection<FixedVariableInitializer> Variables {
+			get { return GetChildrenByRole (VariableRole); }
+		}
+
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitFixedFieldDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitFixedFieldDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitFixedFieldDeclaration (this, data);
+		}
+
+		protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+		{
+			var o = other as FixedFieldDeclaration;
+			return o != null && this.MatchAttributesAndModifiers (o, match)
+				&& this.ReturnType.DoMatch (o.ReturnType, match) && this.Variables.DoMatch (o.Variables, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FixedVariableInitializer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FixedVariableInitializer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/FixedVariableInitializer.cs	(revision 11807)
@@ -0,0 +1,105 @@
+﻿// 
+// FixedFieldDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Name [ CountExpression ]
+	/// </summary>
+	public class FixedVariableInitializer : AstNode
+	{
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public FixedVariableInitializer()
+		{
+		}
+		
+		public FixedVariableInitializer (string name, Expression initializer = null)
+		{
+			this.Name = name;
+			this.CountExpression = initializer;
+		}
+
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode LBracketToken {
+			get { return GetChildByRole (Roles.LBracket); }
+		}
+
+		public Expression CountExpression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+
+		public CSharpTokenNode RBracketToken {
+			get { return GetChildByRole (Roles.RBracket); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitFixedVariableInitializer (this);
+		}
+				
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitFixedVariableInitializer (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitFixedVariableInitializer (this, data);
+		}
+		
+		protected internal override bool DoMatch (AstNode other, ICSharpCode.NRefactory.PatternMatching.Match match)
+		{
+			var o = other as FixedVariableInitializer;
+			return o != null && MatchString (this.Name, o.Name) && this.CountExpression.DoMatch (o.CountExpression, match);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/IndexerDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/IndexerDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/IndexerDeclaration.cs	(revision 11807)
@@ -0,0 +1,122 @@
+﻿// 
+// IndexerDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class IndexerDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole ThisKeywordRole = new TokenRole ("this");
+		public static readonly Role<Accessor> GetterRole = PropertyDeclaration.GetterRole;
+		public static readonly Role<Accessor> SetterRole = PropertyDeclaration.SetterRole;
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Indexer; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the type reference of the interface that is explicitly implemented.
+		/// Null node if this member is not an explicit interface implementation.
+		/// </summary>
+		public AstType PrivateImplementationType {
+			get { return GetChildByRole (PrivateImplementationTypeRole); }
+			set { SetChildByRole (PrivateImplementationTypeRole, value); }
+		}
+		
+		public override string Name {
+			get { return "Item"; }
+			set { throw new NotSupportedException(); }
+		}
+		
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		public override Identifier NameToken {
+			get { return Identifier.Null; }
+			set { throw new NotSupportedException(); }
+		}
+
+		public CSharpTokenNode LBracketToken {
+			get { return GetChildByRole (Roles.LBracket); }
+		}
+
+		public CSharpTokenNode ThisToken {
+			get { return GetChildByRole (ThisKeywordRole); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RBracketToken {
+			get { return GetChildByRole (Roles.RBracket); }
+		}
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+		
+		public Accessor Getter {
+			get { return GetChildByRole(GetterRole); }
+			set { SetChildByRole(GetterRole, value); }
+		}
+		
+		public Accessor Setter {
+			get { return GetChildByRole(SetterRole); }
+			set { SetChildByRole(SetterRole, value); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitIndexerDeclaration (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitIndexerDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitIndexerDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			IndexerDeclaration o = other as IndexerDeclaration;
+			return o != null
+				&& this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match)
+				&& this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match)
+				&& this.Parameters.DoMatch(o.Parameters, match)
+				&& this.Getter.DoMatch(o.Getter, match) && this.Setter.DoMatch(o.Setter, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/MethodDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/MethodDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/MethodDeclaration.cs	(revision 11807)
@@ -0,0 +1,104 @@
+﻿// 
+// MethodDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class MethodDeclaration : EntityDeclaration
+	{
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Method; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the type reference of the interface that is explicitly implemented.
+		/// Null node if this member is not an explicit interface implementation.
+		/// </summary>
+		public AstType PrivateImplementationType {
+			get { return GetChildByRole (PrivateImplementationTypeRole); }
+			set { SetChildByRole (PrivateImplementationTypeRole, value); }
+		}
+		
+		public AstNodeCollection<TypeParameterDeclaration> TypeParameters {
+			get { return GetChildrenByRole (Roles.TypeParameter); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public AstNodeCollection<Constraint> Constraints {
+			get { return GetChildrenByRole (Roles.Constraint); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		public bool IsExtensionMethod {
+			get {
+				ParameterDeclaration pd = (ParameterDeclaration)GetChildByRole (Roles.Parameter);
+				return pd != null && pd.ParameterModifier == ParameterModifier.This;
+			}
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitMethodDeclaration (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitMethodDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitMethodDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			MethodDeclaration o = other as MethodDeclaration;
+			return o != null && MatchString(this.Name, o.Name)
+				&& this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match)
+				&& this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match)
+				&& this.TypeParameters.DoMatch(o.TypeParameters, match)
+				&& this.Parameters.DoMatch(o.Parameters, match) && this.Constraints.DoMatch(o.Constraints, match)
+				&& this.Body.DoMatch(o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/OperatorDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/OperatorDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/OperatorDeclaration.cs	(revision 11807)
@@ -0,0 +1,268 @@
+﻿// 
+// OperatorDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.ComponentModel;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum OperatorType
+	{
+		// Values must correspond to Mono.CSharp.Operator.OpType
+		// due to the casts used in OperatorDeclaration.
+		
+		// Unary operators
+		LogicalNot = Mono.CSharp.Operator.OpType.LogicalNot,
+		OnesComplement = Mono.CSharp.Operator.OpType.OnesComplement,
+		Increment = Mono.CSharp.Operator.OpType.Increment,
+		Decrement = Mono.CSharp.Operator.OpType.Decrement,
+		True = Mono.CSharp.Operator.OpType.True,
+		False = Mono.CSharp.Operator.OpType.False,
+
+		// Unary and Binary operators
+		Addition = Mono.CSharp.Operator.OpType.Addition,
+		Subtraction = Mono.CSharp.Operator.OpType.Subtraction,
+
+		UnaryPlus = Mono.CSharp.Operator.OpType.UnaryPlus,
+		UnaryNegation = Mono.CSharp.Operator.OpType.UnaryNegation,
+		
+		// Binary operators
+		Multiply = Mono.CSharp.Operator.OpType.Multiply,
+		Division = Mono.CSharp.Operator.OpType.Division,
+		Modulus = Mono.CSharp.Operator.OpType.Modulus,
+		BitwiseAnd = Mono.CSharp.Operator.OpType.BitwiseAnd,
+		BitwiseOr = Mono.CSharp.Operator.OpType.BitwiseOr,
+		ExclusiveOr = Mono.CSharp.Operator.OpType.ExclusiveOr,
+		LeftShift = Mono.CSharp.Operator.OpType.LeftShift,
+		RightShift = Mono.CSharp.Operator.OpType.RightShift,
+		Equality = Mono.CSharp.Operator.OpType.Equality,
+		Inequality = Mono.CSharp.Operator.OpType.Inequality,
+		GreaterThan = Mono.CSharp.Operator.OpType.GreaterThan,
+		LessThan = Mono.CSharp.Operator.OpType.LessThan,
+		GreaterThanOrEqual = Mono.CSharp.Operator.OpType.GreaterThanOrEqual,
+		LessThanOrEqual = Mono.CSharp.Operator.OpType.LessThanOrEqual,
+
+		// Implicit and Explicit
+		Implicit = Mono.CSharp.Operator.OpType.Implicit,
+		Explicit = Mono.CSharp.Operator.OpType.Explicit
+	}
+	
+	public class OperatorDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole OperatorKeywordRole = new TokenRole ("operator");
+		
+		// Unary operators
+		public static readonly TokenRole LogicalNotRole = new TokenRole ("!");
+		public static readonly TokenRole OnesComplementRole = new TokenRole ("~");
+		public static readonly TokenRole IncrementRole = new TokenRole ("++");
+		public static readonly TokenRole DecrementRole = new TokenRole ("--");
+		public static readonly TokenRole TrueRole = new TokenRole ("true");
+		public static readonly TokenRole FalseRole = new TokenRole ("false");
+
+		// Unary and Binary operators
+		public static readonly TokenRole AdditionRole = new TokenRole ("+");
+		public static readonly TokenRole SubtractionRole = new TokenRole ("-");
+
+		// Binary operators
+		public static readonly TokenRole MultiplyRole = new TokenRole ("*");
+		public static readonly TokenRole DivisionRole = new TokenRole ("/");
+		public static readonly TokenRole ModulusRole = new TokenRole ("%");
+		public static readonly TokenRole BitwiseAndRole = new TokenRole ("&");
+		public static readonly TokenRole BitwiseOrRole = new TokenRole ("|");
+		public static readonly TokenRole ExclusiveOrRole = new TokenRole ("^");
+		public static readonly TokenRole LeftShiftRole = new TokenRole ("<<");
+		public static readonly TokenRole RightShiftRole = new TokenRole (">>");
+		public static readonly TokenRole EqualityRole = new TokenRole ("==");
+		public static readonly TokenRole InequalityRole = new TokenRole ("!=");
+		public static readonly TokenRole GreaterThanRole = new TokenRole (">");
+		public static readonly TokenRole LessThanRole = new TokenRole ("<");
+		public static readonly TokenRole GreaterThanOrEqualRole = new TokenRole (">=");
+		public static readonly TokenRole LessThanOrEqualRole = new TokenRole ("<=");
+		
+		public static readonly TokenRole ExplicitRole = new TokenRole ("explicit");
+		public static readonly TokenRole ImplicitRole = new TokenRole ("implicit");
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Operator; }
+		}
+		
+		OperatorType operatorType;
+		
+		public OperatorType OperatorType {
+			get { return operatorType; }
+			set {
+				ThrowIfFrozen();
+				operatorType = value;
+			}
+		}
+		
+		public CSharpTokenNode OperatorToken {
+			get { return GetChildByRole (OperatorKeywordRole); }
+		}
+		
+		public CSharpTokenNode OperatorTypeToken {
+			get { return GetChildByRole (GetRole (OperatorType)); }
+		}
+		
+		public CSharpTokenNode LParToken {
+			get { return GetChildByRole (Roles.LPar); }
+		}
+		
+		public AstNodeCollection<ParameterDeclaration> Parameters {
+			get { return GetChildrenByRole (Roles.Parameter); }
+		}
+		
+		public CSharpTokenNode RParToken {
+			get { return GetChildByRole (Roles.RPar); }
+		}
+		
+		public BlockStatement Body {
+			get { return GetChildByRole (Roles.Body); }
+			set { SetChildByRole (Roles.Body, value); }
+		}
+		
+		/// <summary>
+		/// Gets the operator type from the method name, or null, if the method does not represent one of the known operator types.
+		/// </summary>
+		public static OperatorType? GetOperatorType(string methodName)
+		{
+			return (OperatorType?)Mono.CSharp.Operator.GetType(methodName);
+		}
+		
+		public static TokenRole GetRole (OperatorType type)
+		{
+			switch (type) {
+			case OperatorType.LogicalNot:
+				return LogicalNotRole;
+			case OperatorType.OnesComplement:
+				return OnesComplementRole;
+			case OperatorType.Increment:
+				return IncrementRole;
+			case OperatorType.Decrement:
+				return DecrementRole;
+			case OperatorType.True:
+				return TrueRole;
+			case OperatorType.False:
+				return FalseRole;
+			
+			case OperatorType.Addition:
+			case OperatorType.UnaryPlus:
+				return AdditionRole;
+			case OperatorType.Subtraction:
+			case OperatorType.UnaryNegation:
+				return SubtractionRole;
+			
+			case OperatorType.Multiply:
+				return MultiplyRole;
+			case OperatorType.Division:
+				return DivisionRole;
+			case OperatorType.Modulus:
+				return ModulusRole;
+			case OperatorType.BitwiseAnd:
+				return BitwiseAndRole;
+			case OperatorType.BitwiseOr:
+				return BitwiseOrRole;
+			case OperatorType.ExclusiveOr:
+				return ExclusiveOrRole;
+			case OperatorType.LeftShift:
+				return LeftShiftRole;
+			case OperatorType.RightShift:
+				return RightShiftRole;
+			case OperatorType.Equality:
+				return EqualityRole;
+			case OperatorType.Inequality:
+				return InequalityRole;
+			case OperatorType.GreaterThan:
+				return GreaterThanRole;
+			case OperatorType.LessThan:
+				return LessThanRole;
+			case OperatorType.GreaterThanOrEqual:
+				return GreaterThanOrEqualRole;
+			case OperatorType.LessThanOrEqual:
+				return LessThanOrEqualRole;
+			
+			case OperatorType.Implicit:
+				return ImplicitRole;
+			case OperatorType.Explicit:
+				return ExplicitRole;
+			
+			default:
+				throw new System.ArgumentOutOfRangeException ();
+			}
+		}
+		
+		/// <summary>
+		/// Gets the method name for the operator type. ("op_Addition", "op_Implicit", etc.)
+		/// </summary>
+		public static string GetName (OperatorType type)
+		{
+			return Mono.CSharp.Operator.GetMetadataName ((Mono.CSharp.Operator.OpType)type);
+		}
+		
+		/// <summary>
+		/// Gets the token for the operator type ("+", "implicit", etc.)
+		/// </summary>
+		public static string GetToken (OperatorType type)
+		{
+			return Mono.CSharp.Operator.GetName ((Mono.CSharp.Operator.OpType)type);
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitOperatorDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitOperatorDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitOperatorDeclaration (this, data);
+		}
+		
+		public override string Name {
+			get { return GetName (this.OperatorType); }
+			set { throw new NotSupportedException(); }
+		}
+		
+		[EditorBrowsable(EditorBrowsableState.Never)]
+		public override Identifier NameToken {
+			get { return Identifier.Null; }
+			set { throw new NotSupportedException(); }
+		}
+		
+		protected internal override bool DoMatch (AstNode other, PatternMatching.Match match)
+		{
+			OperatorDeclaration o = other as OperatorDeclaration;
+			return o != null && this.MatchAttributesAndModifiers (o, match) && this.OperatorType == o.OperatorType
+				&& this.ReturnType.DoMatch (o.ReturnType, match)
+				&& this.Parameters.DoMatch (o.Parameters, match) && this.Body.DoMatch (o.Body, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/ParameterDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/ParameterDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/ParameterDeclaration.cs	(revision 11807)
@@ -0,0 +1,147 @@
+﻿// 
+// ParameterDeclarationExpression.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum ParameterModifier {
+		None,
+		Ref,
+		Out,
+		Params,
+		This
+	}
+	
+	public class ParameterDeclaration : AstNode
+	{
+		public static readonly Role<AttributeSection> AttributeRole = EntityDeclaration.AttributeRole;
+		public static readonly TokenRole RefModifierRole = new TokenRole("ref");
+		public static readonly TokenRole OutModifierRole = new TokenRole("out");
+		public static readonly TokenRole ParamsModifierRole = new TokenRole("params");
+		public static readonly TokenRole ThisModifierRole = new TokenRole("this");
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public AstNodeCollection<AttributeSection> Attributes {
+			get { return GetChildrenByRole (AttributeRole); }
+		}
+		
+		ParameterModifier parameterModifier;
+		
+		public ParameterModifier ParameterModifier {
+			get { return parameterModifier; }
+			set {
+				ThrowIfFrozen();
+				parameterModifier = value;
+			}
+		}
+		
+		public AstType Type {
+			get { return GetChildByRole (Roles.Type); }
+			set { SetChildByRole (Roles.Type, value); }
+		}
+		
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+
+		public CSharpTokenNode AssignToken {
+			get { return GetChildByRole (Roles.Assign); }
+		}
+
+		public Expression DefaultExpression {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitParameterDeclaration (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitParameterDeclaration (this);
+		}
+
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitParameterDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			ParameterDeclaration o = other as ParameterDeclaration;
+			return o != null && this.Attributes.DoMatch(o.Attributes, match) && this.ParameterModifier == o.ParameterModifier
+				&& this.Type.DoMatch(o.Type, match) && MatchString(this.Name, o.Name)
+				&& this.DefaultExpression.DoMatch(o.DefaultExpression, match);
+		}
+		
+		public ParameterDeclaration()
+		{
+		}
+		
+		public ParameterDeclaration(AstType type, string name, ParameterModifier modifier = ParameterModifier.None)
+		{
+			Type = type;
+			Name = name;
+			ParameterModifier = modifier;
+		}
+
+		public ParameterDeclaration(string name, ParameterModifier modifier = ParameterModifier.None)
+		{
+			Name = name;
+			ParameterModifier = modifier;
+		}
+
+		public new ParameterDeclaration Clone()
+		{
+			return (ParameterDeclaration)base.Clone();
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/PropertyDeclaration.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/PropertyDeclaration.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/PropertyDeclaration.cs	(revision 11807)
@@ -0,0 +1,92 @@
+﻿// 
+// PropertyDeclaration.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class PropertyDeclaration : EntityDeclaration
+	{
+		public static readonly TokenRole GetKeywordRole = new TokenRole ("get");
+		public static readonly TokenRole SetKeywordRole = new TokenRole ("set");
+		public static readonly Role<Accessor> GetterRole = new Role<Accessor>("Getter", Accessor.Null);
+		public static readonly Role<Accessor> SetterRole = new Role<Accessor>("Setter", Accessor.Null);
+		
+		public override SymbolKind SymbolKind {
+			get { return SymbolKind.Property; }
+		}
+		
+		/// <summary>
+		/// Gets/Sets the type reference of the interface that is explicitly implemented.
+		/// Null node if this member is not an explicit interface implementation.
+		/// </summary>
+		public AstType PrivateImplementationType {
+			get { return GetChildByRole (PrivateImplementationTypeRole); }
+			set { SetChildByRole (PrivateImplementationTypeRole, value); }
+		}
+		
+		public CSharpTokenNode LBraceToken {
+			get { return GetChildByRole (Roles.LBrace); }
+		}
+		
+		public Accessor Getter {
+			get { return GetChildByRole(GetterRole); }
+			set { SetChildByRole(GetterRole, value); }
+		}
+		
+		public Accessor Setter {
+			get { return GetChildByRole(SetterRole); }
+			set { SetChildByRole(SetterRole, value); }
+		}
+		
+		public CSharpTokenNode RBraceToken {
+			get { return GetChildByRole (Roles.RBrace); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitPropertyDeclaration (this);
+		}
+		
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitPropertyDeclaration (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitPropertyDeclaration (this, data);
+		}
+		
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			PropertyDeclaration o = other as PropertyDeclaration;
+			return o != null && MatchString(this.Name, o.Name)
+				&& this.MatchAttributesAndModifiers(o, match) && this.ReturnType.DoMatch(o.ReturnType, match)
+				&& this.PrivateImplementationType.DoMatch(o.PrivateImplementationType, match)
+				&& this.Getter.DoMatch(o.Getter, match) && this.Setter.DoMatch(o.Setter, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/VariableInitializer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/VariableInitializer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Ast/TypeMembers/VariableInitializer.cs	(revision 11807)
@@ -0,0 +1,174 @@
+﻿// 
+// VariableInitializer.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class VariableInitializer : AstNode
+	{
+		#region Null
+		public new static readonly VariableInitializer Null = new NullVariableInitializer ();
+		
+		sealed class NullVariableInitializer : VariableInitializer
+		{
+			public override bool IsNull {
+				get {
+					return true;
+				}
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitNullNode(this);
+			}
+			
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitNullNode(this);
+			}
+			
+			public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitNullNode(this, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return other == null || other.IsNull;
+			}
+		}
+		#endregion
+
+		#region PatternPlaceholder
+		public static implicit operator VariableInitializer(PatternMatching.Pattern pattern)
+		{
+			return pattern != null ? new PatternPlaceholder(pattern) : null;
+		}
+		
+		sealed class PatternPlaceholder : VariableInitializer, PatternMatching.INode
+		{
+			readonly PatternMatching.Pattern child;
+			
+			public PatternPlaceholder(PatternMatching.Pattern child)
+			{
+				this.child = child;
+			}
+			
+			public override NodeType NodeType {
+				get { return NodeType.Pattern; }
+			}
+			
+			public override void AcceptVisitor (IAstVisitor visitor)
+			{
+				visitor.VisitPatternPlaceholder (this, child);
+			}
+				
+			public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+			{
+				return visitor.VisitPatternPlaceholder (this, child);
+			}
+			
+			public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
+			{
+				return visitor.VisitPatternPlaceholder(this, child, data);
+			}
+			
+			protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+			{
+				return child.DoMatch(other, match);
+			}
+			
+			bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
+			{
+				return child.DoMatchCollection(role, pos, match, backtrackingInfo);
+			}
+		}
+		#endregion
+		
+		public override NodeType NodeType {
+			get {
+				return NodeType.Unknown;
+			}
+		}
+		
+		public VariableInitializer()
+		{
+		}
+		
+		public VariableInitializer(string name, Expression initializer = null)
+		{
+			this.Name = name;
+			this.Initializer = initializer;
+		}
+
+		public string Name {
+			get {
+				return GetChildByRole (Roles.Identifier).Name;
+			}
+			set {
+				SetChildByRole (Roles.Identifier, Identifier.Create (value));
+			}
+		}
+		
+		public Identifier NameToken {
+			get {
+				return GetChildByRole (Roles.Identifier);
+			}
+			set {
+				SetChildByRole (Roles.Identifier, value);
+			}
+		}
+		
+		public CSharpTokenNode AssignToken {
+			get { return GetChildByRole (Roles.Assign); }
+		}
+		
+		public Expression Initializer {
+			get { return GetChildByRole (Roles.Expression); }
+			set { SetChildByRole (Roles.Expression, value); }
+		}
+		
+		public override void AcceptVisitor (IAstVisitor visitor)
+		{
+			visitor.VisitVariableInitializer (this);
+		}
+			
+		public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
+		{
+			return visitor.VisitVariableInitializer (this);
+		}
+		
+		public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
+		{
+			return visitor.VisitVariableInitializer (this, data);
+		}
+
+		protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
+		{
+			VariableInitializer o = other as VariableInitializer;
+			return o != null && MatchString(this.Name, o.Name) && this.Initializer.DoMatch(o.Initializer, match);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/CSharpProjectContent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/CSharpProjectContent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/CSharpProjectContent.cs	(revision 11807)
@@ -0,0 +1,289 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[Serializable]
+	public class CSharpProjectContent : IProjectContent
+	{
+		string assemblyName;
+		string fullAssemblyName;
+		string projectFileName;
+		string location;
+		Dictionary<string, IUnresolvedFile> unresolvedFiles;
+		List<IAssemblyReference> assemblyReferences;
+		CompilerSettings compilerSettings;
+		
+		public CSharpProjectContent()
+		{
+			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(Platform.FileNameComparer);
+			this.assemblyReferences = new List<IAssemblyReference>();
+			this.compilerSettings = new CompilerSettings();
+			compilerSettings.Freeze();
+		}
+		
+		protected CSharpProjectContent(CSharpProjectContent pc)
+		{
+			this.assemblyName = pc.assemblyName;
+			this.fullAssemblyName = pc.fullAssemblyName;
+			this.projectFileName = pc.projectFileName;
+			this.location = pc.location;
+			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
+			this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
+			this.compilerSettings = pc.compilerSettings;
+		}
+		
+		public IEnumerable<IUnresolvedFile> Files {
+			get { return unresolvedFiles.Values; }
+		}
+		
+		public IEnumerable<IAssemblyReference> AssemblyReferences {
+			get { return assemblyReferences; }
+		}
+		
+		public string ProjectFileName {
+			get { return projectFileName; }
+		}
+		
+		public string AssemblyName {
+			get { return assemblyName; }
+		}
+
+		public string FullAssemblyName {
+			get { return fullAssemblyName; }
+		}
+
+		public string Location {
+			get { return location; }
+		}
+
+		public CompilerSettings CompilerSettings {
+			get { return compilerSettings; }
+		}
+		
+		object IProjectContent.CompilerSettings {
+			get { return compilerSettings; }
+		}
+		
+		public IEnumerable<IUnresolvedAttribute> AssemblyAttributes {
+			get {
+				return this.Files.SelectMany(f => f.AssemblyAttributes);
+			}
+		}
+		
+		public IEnumerable<IUnresolvedAttribute> ModuleAttributes {
+			get {
+				return this.Files.SelectMany(f => f.ModuleAttributes);
+			}
+		}
+		
+		public IEnumerable<IUnresolvedTypeDefinition> TopLevelTypeDefinitions {
+			get {
+				return this.Files.SelectMany(f => f.TopLevelTypeDefinitions);
+			}
+		}
+		
+		public IUnresolvedFile GetFile(string fileName)
+		{
+			IUnresolvedFile file;
+			if (unresolvedFiles.TryGetValue(fileName, out file))
+				return file;
+			else
+				return null;
+		}
+		
+		public virtual ICompilation CreateCompilation()
+		{
+			var solutionSnapshot = new DefaultSolutionSnapshot();
+			ICompilation compilation = new SimpleCompilation(solutionSnapshot, this, assemblyReferences);
+			solutionSnapshot.AddCompilation(this, compilation);
+			return compilation;
+		}
+		
+		public virtual ICompilation CreateCompilation(ISolutionSnapshot solutionSnapshot)
+		{
+			return new SimpleCompilation(solutionSnapshot, this, assemblyReferences);
+		}
+		
+		protected virtual CSharpProjectContent Clone()
+		{
+			return new CSharpProjectContent(this);
+		}
+		
+		/// <summary>
+		/// Sets both the short and the full assembly names.
+		/// </summary>
+		/// <param name="newAssemblyName">New full assembly name.</param>
+		public IProjectContent SetAssemblyName(string newAssemblyName)
+		{
+			CSharpProjectContent pc = Clone();
+			pc.fullAssemblyName = newAssemblyName;
+			int pos = newAssemblyName != null ? newAssemblyName.IndexOf(',') : -1;
+			pc.assemblyName = pos < 0 ? newAssemblyName : newAssemblyName.Substring(0, pos);
+			return pc;
+		}
+		
+		public IProjectContent SetProjectFileName(string newProjectFileName)
+		{
+			CSharpProjectContent pc = Clone();
+			pc.projectFileName = newProjectFileName;
+			return pc;
+		}
+
+		public IProjectContent SetLocation(string newLocation)
+		{
+			CSharpProjectContent pc = Clone();
+			pc.location = newLocation;
+			return pc;
+		}
+		
+		public IProjectContent SetCompilerSettings(object compilerSettings)
+		{
+			if (!(compilerSettings is CompilerSettings))
+				throw new ArgumentException("Settings must be an instance of " + typeof(CompilerSettings).FullName, "compilerSettings");
+			CSharpProjectContent pc = Clone();
+			pc.compilerSettings = (CompilerSettings)compilerSettings;
+			pc.compilerSettings.Freeze();
+			return pc;
+		}
+		
+		public IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references)
+		{
+			return AddAssemblyReferences(references.ToArray());
+		}
+		
+		public IProjectContent AddAssemblyReferences(params IAssemblyReference[] references)
+		{
+			CSharpProjectContent pc = Clone();
+			pc.assemblyReferences.AddRange(references);
+			return pc;
+		}
+		
+		public IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references)
+		{
+			return RemoveAssemblyReferences(references.ToArray());
+		}
+		
+		public IProjectContent RemoveAssemblyReferences(params IAssemblyReference[] references)
+		{
+			CSharpProjectContent pc = Clone();
+			foreach (var r in references)
+				pc.assemblyReferences.Remove(r);
+			return pc;
+		}
+		
+		/// <summary>
+		/// Adds the specified files to the project content.
+		/// If a file with the same name already exists, updated the existing file.
+		/// </summary>
+		public IProjectContent AddOrUpdateFiles(IEnumerable<IUnresolvedFile> newFiles)
+		{
+			CSharpProjectContent pc = Clone();
+			foreach (var file in newFiles) {
+				pc.unresolvedFiles[file.FileName] = file;
+			}
+			return pc;
+		}
+		
+		/// <summary>
+		/// Adds the specified files to the project content.
+		/// If a file with the same name already exists, this method updates the existing file.
+		/// </summary>
+		public IProjectContent AddOrUpdateFiles(params IUnresolvedFile[] newFiles)
+		{
+			return AddOrUpdateFiles((IEnumerable<IUnresolvedFile>)newFiles);
+		}
+		
+		/// <summary>
+		/// Removes the files with the specified names.
+		/// </summary>
+		public IProjectContent RemoveFiles(IEnumerable<string> fileNames)
+		{
+			CSharpProjectContent pc = Clone();
+			foreach (var fileName in fileNames) {
+				pc.unresolvedFiles.Remove(fileName);
+			}
+			return pc;
+		}
+		
+		/// <summary>
+		/// Removes the files with the specified names.
+		/// </summary>
+		public IProjectContent RemoveFiles(params string[] fileNames)
+		{
+			return RemoveFiles((IEnumerable<string>)fileNames);
+		}
+		
+		[Obsolete("Use RemoveFiles/AddOrUpdateFiles instead")]
+		public IProjectContent UpdateProjectContent(IUnresolvedFile oldFile, IUnresolvedFile newFile)
+		{
+			if (oldFile == null && newFile == null)
+				return this;
+			if (oldFile != null && newFile != null) {
+				if (!Platform.FileNameComparer.Equals(oldFile.FileName, newFile.FileName))
+					throw new ArgumentException("When both oldFile and newFile are specified, they must use the same file name.");
+			}
+			CSharpProjectContent pc = Clone();
+			if (newFile == null)
+				pc.unresolvedFiles.Remove(oldFile.FileName);
+			else
+				pc.unresolvedFiles[newFile.FileName] = newFile;
+			return pc;
+		}
+		
+		[Obsolete("Use RemoveFiles/AddOrUpdateFiles instead")]
+		public IProjectContent UpdateProjectContent(IEnumerable<IUnresolvedFile> oldFiles, IEnumerable<IUnresolvedFile> newFiles)
+		{
+			CSharpProjectContent pc = Clone();
+			if (oldFiles != null) {
+				foreach (var oldFile in oldFiles) {
+					pc.unresolvedFiles.Remove(oldFile.FileName);
+				}
+			}
+			if (newFiles != null) {
+				foreach (var newFile in newFiles) {
+					pc.unresolvedFiles.Add(newFile.FileName, newFile);
+				}
+			}
+			return pc;
+		}
+		
+		IAssembly IAssemblyReference.Resolve(ITypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			var cache = context.Compilation.CacheManager;
+			IAssembly asm = (IAssembly)cache.GetShared(this);
+			if (asm != null) {
+				return asm;
+			} else {
+				asm = new CSharpAssembly(context.Compilation, this);
+				return (IAssembly)cache.GetOrAddShared(this, asm);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/CombineQueryExpressions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/CombineQueryExpressions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/CombineQueryExpressions.cs	(revision 11807)
@@ -0,0 +1,216 @@
+//
+// CombineQueryExpressions.cs
+//
+// Modified by LuÃ­s Reis <luiscubal@gmail.com> (Copyright (C) 2013)
+//
+// Copyright header of the original version follows:
+//
+// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.PatternMatching;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Combines query expressions and removes transparent identifiers.
+	/// </summary>
+	public class CombineQueryExpressions
+	{
+		static readonly InvocationExpression castPattern = new InvocationExpression {
+			Target = new MemberReferenceExpression {
+				Target = new AnyNode("inExpr"),
+				MemberName = "Cast",
+				TypeArguments = { new AnyNode("targetType") }
+			}};
+
+		public string CombineQuery(AstNode node, AstNode rootQuery = null)
+		{
+			if (rootQuery == null) {
+				rootQuery = node;
+			}
+
+			QueryExpression query = node as QueryExpression;
+			if (query != null) {
+				string continuationIdentifier = null;
+
+				foreach (var clause in query.Clauses) {
+					var continuation = clause as QueryContinuationClause;
+					if (continuation != null) {
+						CombineQuery(continuation.PrecedingQuery);
+					}
+
+					var from = clause as QueryFromClause;
+					if (from != null) {
+						continuationIdentifier = CombineQuery(from.Expression, rootQuery);
+					}
+				}
+
+				QueryFromClause fromClause = (QueryFromClause)query.Clauses.First();
+				QueryExpression innerQuery = fromClause.Expression as QueryExpression;
+				if (innerQuery != null) {
+					continuationIdentifier = continuationIdentifier ?? ((QueryFromClause)innerQuery.Clauses.First()).Identifier;
+
+					string transparentIdentifier;
+					if (TryRemoveTransparentIdentifier(query, fromClause, innerQuery, continuationIdentifier, out transparentIdentifier)) {
+						RemoveTransparentIdentifierReferences(rootQuery, transparentIdentifier);
+					} else if (fromClause.Type.IsNull) {
+						QueryContinuationClause continuation = new QueryContinuationClause();
+						continuation.PrecedingQuery = innerQuery.Detach();
+						continuation.Identifier = fromClause.Identifier;
+						fromClause.ReplaceWith(continuation);
+					}
+
+					return transparentIdentifier;
+				} else {
+					Match m = castPattern.Match(fromClause.Expression);
+					if (m.Success) {
+						fromClause.Type = m.Get<AstType>("targetType").Single().Detach();
+						fromClause.Expression = m.Get<Expression>("inExpr").Single().Detach();
+					}
+				}
+			}
+
+			return null;
+		}
+
+		static readonly QuerySelectClause selectTransparentIdentifierPattern = new QuerySelectClause {
+			Expression = new AnonymousTypeCreateExpression {
+					Initializers = {
+						new AnyNode("nae1"),
+						new AnyNode("nae2")
+					}
+				}
+			};
+
+		bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromClause, QueryExpression innerQuery, string continuationIdentifier, out string transparentIdentifier)
+		{
+			transparentIdentifier = fromClause.Identifier;
+
+			Match match = selectTransparentIdentifierPattern.Match(innerQuery.Clauses.Last());
+			if (!match.Success)
+				return false;
+			QuerySelectClause selectClause = (QuerySelectClause)innerQuery.Clauses.Last();
+			Expression nae1 = match.Get<Expression>("nae1").SingleOrDefault();
+			string nae1Name = ExtractExpressionName(ref nae1);
+			if (nae1Name == null)
+				return false;
+
+			Expression nae2 = match.Get<Expression>("nae2").SingleOrDefault();
+			string nae2Name = ExtractExpressionName(ref nae2);
+			if (nae1Name == null)
+				return false;
+
+			bool introduceLetClause = true;
+			var nae1Identifier = nae1 as IdentifierExpression;
+			var nae2Identifier = nae2 as IdentifierExpression;
+			if (nae1Identifier != null && nae2Identifier != null && nae1Identifier.Identifier == nae1Name && nae2Identifier.Identifier == nae2Name) {
+				introduceLetClause = false;
+			}
+
+			if (nae1Name != continuationIdentifier) {
+				if (nae2Name == continuationIdentifier) {
+					//Members are in reversed order
+					string tempName = nae1Name;
+					Expression tempNae = nae1;
+
+					nae1Name = nae2Name;
+					nae1 = nae2;
+					nae2Name = tempName;
+					nae2 = tempNae;
+				} else {
+					return false;
+				}
+			}
+
+			if (introduceLetClause && innerQuery.Clauses.OfType<QueryFromClause>().Any(from => from.Identifier == nae2Name)) {
+				return false;
+			}
+			if (introduceLetClause && innerQuery.Clauses.OfType<QueryJoinClause>().Any(join => join.JoinIdentifier == nae2Name)) {
+				return false;
+			}
+
+			// from * in (from x in ... select new { x = x, y = expr }) ...
+			// =>
+			// from x in ... let y = expr ...
+			fromClause.Remove();
+			selectClause.Remove();
+			// Move clauses from innerQuery to query
+			QueryClause insertionPos = null;
+			foreach (var clause in innerQuery.Clauses) {
+				query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach());
+			}
+			if (introduceLetClause) {
+				query.Clauses.InsertAfter(insertionPos, new QueryLetClause { Identifier = nae2Name, Expression = nae2.Detach() });
+			}
+			return true;
+		}
+
+		/// <summary>
+		/// Removes all occurrences of transparent identifiers
+		/// </summary>
+		void RemoveTransparentIdentifierReferences(AstNode node, string transparentIdentifier)
+		{
+			foreach (AstNode child in node.Children) {
+				RemoveTransparentIdentifierReferences(child, transparentIdentifier);
+			}
+			MemberReferenceExpression mre = node as MemberReferenceExpression;
+			if (mre != null) {
+				IdentifierExpression ident = mre.Target as IdentifierExpression;
+				if (ident != null && ident.Identifier == transparentIdentifier) {
+					IdentifierExpression newIdent = new IdentifierExpression(mre.MemberName);
+					mre.TypeArguments.MoveTo(newIdent.TypeArguments);
+					newIdent.CopyAnnotationsFrom(mre);
+					newIdent.RemoveAnnotations<PropertyDeclaration>(); // remove the reference to the property of the anonymous type
+					mre.ReplaceWith(newIdent);
+					return;
+				} else if (mre.MemberName == transparentIdentifier) {
+					var newVar = mre.Target.Detach();
+					newVar.CopyAnnotationsFrom(mre);
+					newVar.RemoveAnnotations<PropertyDeclaration>(); // remove the reference to the property of the anonymous type
+					mre.ReplaceWith(newVar);
+					return;
+				}
+			}
+		}
+
+		string ExtractExpressionName(ref Expression expr)
+		{
+			NamedExpression namedExpr = expr as NamedExpression;
+			if (namedExpr != null) {
+				expr = namedExpr.Expression;
+				return namedExpr.Name;
+			}
+
+			IdentifierExpression identifier = expr as IdentifierExpression;
+			if (identifier != null) {
+				return identifier.Identifier;
+			}
+
+			MemberReferenceExpression memberRef = expr as MemberReferenceExpression;
+			if (memberRef != null) {
+				return memberRef.MemberName;
+			}
+
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpCompletionEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpCompletionEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpCompletionEngine.cs	(revision 11807)
@@ -0,0 +1,3807 @@
+// 
+// CSharpCompletionEngine.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	public enum EditorBrowsableBehavior
+	{
+		Ignore,
+		Normal,
+		IncludeAdvanced
+	}
+
+	public class CompletionEngineCache
+	{
+		public List<INamespace>  namespaces;
+		public ICompletionData[] importCompletion;
+	}
+
+	public class CSharpCompletionEngine : CSharpCompletionEngineBase
+	{
+		internal ICompletionDataFactory factory;
+
+		#region Additional input properties
+
+		public CSharpFormattingOptions FormattingPolicy { get; set; }
+
+		public string EolMarker { get; set; }
+
+		public string IndentString { get; set; }
+
+		public bool AutomaticallyAddImports { get; set; }
+
+		public bool IncludeKeywordsInCompletionList { get; set; }
+
+		public EditorBrowsableBehavior EditorBrowsableBehavior { get; set; }
+
+		public CompletionEngineCache CompletionEngineCache { get; set; }
+
+		#endregion
+
+		#region Result properties
+
+		public bool AutoCompleteEmptyMatch;
+		/// <summary>
+		/// The auto complete empty match on curly bracket. (only taken into account when AutoCompleteEmptyMatch is true )
+		/// </summary>
+		public bool AutoCompleteEmptyMatchOnCurlyBracket = true;
+		public bool AutoSelect;
+		public string DefaultCompletionString;
+		public bool CloseOnSquareBrackets;
+		public readonly List<IMethod> PossibleDelegates = new List<IMethod>();
+
+		#endregion
+
+		public CSharpCompletionEngine(IDocument document, ICompletionContextProvider completionContextProvider, ICompletionDataFactory factory, IProjectContent content, CSharpTypeResolveContext ctx) : base(content, completionContextProvider, ctx)
+		{
+			if (document == null) {
+				throw new ArgumentNullException("document");
+			}
+			if (factory == null) {
+				throw new ArgumentNullException("factory");
+			}
+			this.document = document;
+			this.factory = factory;
+			// Set defaults for additional input properties
+			this.FormattingPolicy = FormattingOptionsFactory.CreateMono();
+			this.EolMarker = Environment.NewLine;
+			this.IncludeKeywordsInCompletionList = true;
+			EditorBrowsableBehavior = EditorBrowsableBehavior.IncludeAdvanced;
+			this.IndentString = "\t";
+		}
+
+		public bool TryGetCompletionWord(int offset, out int startPos, out int wordLength)
+		{
+			startPos = wordLength = 0;
+			int pos = offset - 1;
+			while (pos >= 0) {
+				char c = document.GetCharAt(pos);
+				if (!char.IsLetterOrDigit(c) && c != '_')
+					break;
+				pos--;
+			}
+			if (pos == -1)
+				return false;
+
+			pos++;
+			startPos = pos;
+
+			while (pos < document.TextLength) {
+				char c = document.GetCharAt(pos);
+				if (!char.IsLetterOrDigit(c) && c != '_')
+					break;
+				pos++;
+			}
+			wordLength = pos - startPos;
+			return true;
+		}
+
+		public IEnumerable<ICompletionData> GetCompletionData(int offset, bool controlSpace)
+		{
+			this.AutoCompleteEmptyMatch = true;
+			this.AutoSelect = true;
+			this.DefaultCompletionString = null;
+			SetOffset(offset);
+			if (offset > 0) {
+				char lastChar = document.GetCharAt(offset - 1);
+				bool isComplete = false;
+				var result = MagicKeyCompletion(lastChar, controlSpace, out isComplete) ?? Enumerable.Empty<ICompletionData>();
+				if (!isComplete && controlSpace && char.IsWhiteSpace(lastChar)) {
+					offset -= 2;
+					while (offset >= 0 && char.IsWhiteSpace(document.GetCharAt(offset))) {
+						offset--;
+					}
+					if (offset > 0) {
+						var nonWsResult = MagicKeyCompletion(
+							document.GetCharAt(offset),
+							controlSpace,
+							out isComplete
+						);
+						if (nonWsResult != null) {
+							var text = new HashSet<string>(result.Select(r => r.CompletionText));
+							result = result.Concat(nonWsResult.Where(r => !text.Contains(r.CompletionText)));
+						}
+					}
+				}
+
+				return result;
+			}
+			return Enumerable.Empty<ICompletionData>();
+		}
+
+		/// <summary>
+		/// Gets the types that needs to be imported via using or full type name.
+		/// </summary>
+		public IEnumerable<ICompletionData> GetImportCompletionData(int offset)
+		{
+			var generalLookup = new MemberLookup(null, Compilation.MainAssembly);
+			SetOffset(offset);
+
+			// flatten usings
+			var namespaces = new List<INamespace>();
+			for (var n = ctx.CurrentUsingScope; n != null; n = n.Parent) {
+				namespaces.Add(n.Namespace);
+				foreach (var u in n.Usings)
+					namespaces.Add(u);
+			}
+
+			foreach (var type in Compilation.GetAllTypeDefinitions ()) {
+				if (!generalLookup.IsAccessible(type, false))
+					continue;	
+				if (namespaces.Any(n => n.FullName == type.Namespace))
+					continue;
+				bool useFullName = false;
+				foreach (var ns in namespaces) {
+					if (ns.GetTypeDefinition(type.Name, type.TypeParameterCount) != null) {
+						useFullName = true;
+						break;
+					}
+				}
+				yield return factory.CreateImportCompletionData(type, useFullName, false);
+			}
+		}
+
+		IEnumerable<string> GenerateNameProposals(AstType type)
+		{
+			if (type is PrimitiveType) {
+				var pt = (PrimitiveType)type;
+				switch (pt.Keyword) {
+					case "object":
+						yield return "o";
+						yield return "obj";
+						break;
+					case "bool":
+						yield return "b";
+						yield return "pred";
+						break;
+					case "double":
+					case "float":
+					case "decimal":
+						yield return "d";
+						yield return "f";
+						yield return "m";
+						break;
+					default:
+						yield return "i";
+						yield return "j";
+						yield return "k";
+						break;
+				}
+				yield break;
+			}
+			string name;
+			if (type is SimpleType) {
+				name = ((SimpleType)type).Identifier;
+			} else if (type is MemberType) {
+				name = ((MemberType)type).MemberName;
+			} else {
+				yield break;
+			}
+
+			var names = WordParser.BreakWords(name);
+
+			var possibleName = new StringBuilder();
+			for (int i = 0; i < names.Count; i++) {
+				possibleName.Length = 0;
+				for (int j = i; j < names.Count; j++) {
+					if (string.IsNullOrEmpty(names [j])) {
+						continue;
+					}
+					if (j == i) { 
+						names [j] = Char.ToLower(names [j] [0]) + names [j].Substring(1);
+					}
+					possibleName.Append(names [j]);
+				}
+				yield return possibleName.ToString();
+			}
+		}
+
+		IEnumerable<ICompletionData> HandleMemberReferenceCompletion(ExpressionResult expr)
+		{
+			if (expr == null)
+				return null;
+
+			// do not auto select <number>. (but <number>.<number>.) (0.ToString() is valid)
+			if (expr.Node is PrimitiveExpression) {
+				var pexpr = (PrimitiveExpression)expr.Node;
+				if (!(pexpr.Value is string || pexpr.Value is char) && !pexpr.LiteralValue.Contains('.')) {
+					AutoSelect = false;
+				}
+			}
+			var resolveResult = ResolveExpression(expr);
+
+			if (resolveResult == null) {
+				return null;
+			}
+			if (expr.Node is AstType) {
+
+				// check for namespace names
+				if (expr.Node.AncestorsAndSelf
+					.TakeWhile(n => n is AstType)
+					.Any(m => m.Role == NamespaceDeclaration.NamespaceNameRole))
+					return null;
+
+				// need to look at paren.parent because of "catch (<Type>.A" expression
+				if (expr.Node.Parent != null && expr.Node.Parent.Parent is CatchClause)
+					return HandleCatchClauseType(expr);
+				return CreateTypeAndNamespaceCompletionData(
+					location,
+					resolveResult.Result,
+					expr.Node,
+					resolveResult.Resolver
+				);
+			}
+
+
+			return CreateCompletionData(
+				location,
+				resolveResult.Result,
+				expr.Node,
+				resolveResult.Resolver
+			);
+		}
+
+		bool IsInPreprocessorDirective()
+		{
+			var text = GetMemberTextToCaret().Item1;
+			var miniLexer = new MiniLexer(text);
+			miniLexer.Parse();
+			return miniLexer.IsInPreprocessorDirective;
+		}
+
+		IEnumerable<ICompletionData> HandleObjectInitializer(SyntaxTree unit, AstNode n)
+		{
+			var p = n.Parent;
+			while (p != null && !(p is ObjectCreateExpression)) {
+				p = p.Parent;
+			}
+			var parent = n.Parent as ArrayInitializerExpression;
+			if (parent == null)
+				return null;
+			if (parent.IsSingleElement)
+				parent = (ArrayInitializerExpression)parent.Parent;
+			if (p != null) {
+				var contextList = new CompletionDataWrapper(this);
+				var initializerResult = ResolveExpression(p);
+				IType initializerType = null;
+
+				if (initializerResult.Result is DynamicInvocationResolveResult) {
+					var dr = (DynamicInvocationResolveResult)initializerResult.Result;
+					var constructor = (dr.Target as MethodGroupResolveResult).Methods.FirstOrDefault();
+					if (constructor != null)
+						initializerType = constructor.DeclaringType;
+				} else {
+					initializerType = initializerResult != null ? initializerResult.Result.Type : null;
+				}
+
+
+				if (initializerType != null && initializerType.Kind != TypeKind.Unknown) {
+					// check 3 cases:
+					// 1) New initalizer { xpr
+					// 2) Object initializer { prop = val1, field = val2, xpr
+					// 3) Array initializer { new Foo (), a, xpr
+					// in case 1 all object/array initializer options should be given - in the others not.
+
+					AstNode prev = null;
+					if (parent.Elements.Count > 1) {
+						prev = parent.Elements.First();
+						if (prev is ArrayInitializerExpression && ((ArrayInitializerExpression)prev).IsSingleElement)
+							prev = ((ArrayInitializerExpression)prev).Elements.FirstOrDefault();
+					}
+
+					if (prev != null && !(prev is NamedExpression)) {
+						AddContextCompletion(contextList, GetState(), n);
+						// case 3)
+						return contextList.Result;
+					}
+					var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
+					var list = typeof(System.Collections.IList).ToTypeReference().Resolve(Compilation);
+					var list1 = typeof(System.Collections.Generic.IList<>).ToTypeReference().Resolve(Compilation);
+					bool isProtectedAllowed = ctx.CurrentTypeDefinition != null && initializerType.GetDefinition() != null ? 
+						ctx.CurrentTypeDefinition.IsDerivedFrom(initializerType.GetDefinition()) : 
+						false;
+					foreach (var m in initializerType.GetMembers (m => m.SymbolKind == SymbolKind.Field)) {
+						var f = m as IField;
+						if (f != null && (f.IsReadOnly || f.IsConst))
+							continue;
+						if (lookup.IsAccessible(m, isProtectedAllowed)) {
+							var data = contextList.AddMember(m);
+							if (data != null)
+								data.DisplayFlags |= DisplayFlags.NamedArgument;
+						}
+					}
+
+					foreach (IProperty m in initializerType.GetMembers (m => m.SymbolKind == SymbolKind.Property)) {
+						if (m.CanSet && lookup.IsAccessible(m.Setter, isProtectedAllowed)  || 
+							m.CanGet && lookup.IsAccessible(m.Getter, isProtectedAllowed) && m.ReturnType.GetDefinition() != null && 
+							(m.ReturnType.GetDefinition().IsDerivedFrom(list.GetDefinition()) || m.ReturnType.GetDefinition().IsDerivedFrom(list1.GetDefinition()))) {
+							var data = contextList.AddMember(m);
+							if (data != null)
+								data.DisplayFlags |= DisplayFlags.NamedArgument;
+						}
+					}
+
+					if (prev != null && (prev is NamedExpression)) {
+						// case 2)
+						return contextList.Result;
+					}
+
+					// case 1)
+
+					// check if the object is a list, if not only provide object initalizers
+					if (initializerType.Kind != TypeKind.Array && list != null) {
+						var def = initializerType.GetDefinition(); 
+						if (def != null && !def.IsDerivedFrom(list.GetDefinition()) && !def.IsDerivedFrom(list1.GetDefinition()))
+							return contextList.Result;
+					}
+
+					AddContextCompletion(contextList, GetState(), n);
+					return contextList.Result;
+				}
+			}
+			return null;
+		}
+
+		static readonly DateTime curDate = DateTime.Now;
+
+		IEnumerable<ICompletionData> GenerateNumberFormatitems(bool isFloatingPoint)
+		{
+			yield return factory.CreateFormatItemCompletionData("D", "decimal", 123);
+			yield return factory.CreateFormatItemCompletionData("D5", "decimal", 123);
+			yield return factory.CreateFormatItemCompletionData("C", "currency", 123);
+			yield return factory.CreateFormatItemCompletionData("C0", "currency", 123);
+			yield return factory.CreateFormatItemCompletionData("E", "exponential", 1.23E4);
+			yield return factory.CreateFormatItemCompletionData("E2", "exponential", 1.234);
+			yield return factory.CreateFormatItemCompletionData("e2", "exponential", 1.234);
+			yield return factory.CreateFormatItemCompletionData("F", "fixed-point", 123.45);
+			yield return factory.CreateFormatItemCompletionData("F1", "fixed-point", 123.45);
+			yield return factory.CreateFormatItemCompletionData("G", "general", 1.23E+56);
+			yield return factory.CreateFormatItemCompletionData("g2", "general", 1.23E+56);
+			yield return factory.CreateFormatItemCompletionData("N", "number", 12345.68);
+			yield return factory.CreateFormatItemCompletionData("N1", "number", 12345.68);
+			yield return factory.CreateFormatItemCompletionData("P", "percent", 12.34);
+			yield return factory.CreateFormatItemCompletionData("P1", "percent", 12.34);
+			yield return factory.CreateFormatItemCompletionData("R", "round-trip", 0.1230000001);
+			yield return factory.CreateFormatItemCompletionData("X", "hexadecimal", 1234);
+			yield return factory.CreateFormatItemCompletionData("x8", "hexadecimal", 1234);
+			yield return factory.CreateFormatItemCompletionData("0000", "custom", 123);
+			yield return factory.CreateFormatItemCompletionData("####", "custom", 123);
+			yield return factory.CreateFormatItemCompletionData("##.###", "custom", 1.23);
+			yield return factory.CreateFormatItemCompletionData("##.000", "custom", 1.23);
+			yield return factory.CreateFormatItemCompletionData("## 'items'", "custom", 12);
+		}
+
+		IEnumerable<ICompletionData> GenerateDateTimeFormatitems()
+		{
+			yield return factory.CreateFormatItemCompletionData("D", "long date", curDate);
+			yield return factory.CreateFormatItemCompletionData("d", "short date", curDate);
+			yield return factory.CreateFormatItemCompletionData("F", "full date long", curDate);
+			yield return factory.CreateFormatItemCompletionData("f", "full date short", curDate);
+			yield return factory.CreateFormatItemCompletionData("G", "general long", curDate);
+			yield return factory.CreateFormatItemCompletionData("g", "general short", curDate);
+			yield return factory.CreateFormatItemCompletionData("M", "month", curDate);
+			yield return factory.CreateFormatItemCompletionData("O", "ISO 8601", curDate);
+			yield return factory.CreateFormatItemCompletionData("R", "RFC 1123", curDate);
+			yield return factory.CreateFormatItemCompletionData("s", "sortable", curDate);
+			yield return factory.CreateFormatItemCompletionData("T", "long time", curDate);
+			yield return factory.CreateFormatItemCompletionData("t", "short time", curDate);
+			yield return factory.CreateFormatItemCompletionData("U", "universal full", curDate);
+			yield return factory.CreateFormatItemCompletionData("u", "universal sortable", curDate);
+			yield return factory.CreateFormatItemCompletionData("Y", "year month", curDate);
+			yield return factory.CreateFormatItemCompletionData("yy-MM-dd", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("yyyy MMMMM dd", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("yy-MMM-dd ddd", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("yyyy-M-d dddd", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("hh:mm:ss t z", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("hh:mm:ss tt zz", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("HH:mm:ss tt zz", "custom", curDate);
+			yield return factory.CreateFormatItemCompletionData("HH:m:s tt zz", "custom", curDate);
+
+		}
+
+		[Flags]
+		enum TestEnum
+		{
+			EnumCaseName = 0,
+			Flag1 = 1,
+			Flag2 = 2,
+			Flags
+
+		}
+
+		IEnumerable<ICompletionData> GenerateEnumFormatitems()
+		{
+			yield return factory.CreateFormatItemCompletionData("G", "string value", TestEnum.EnumCaseName);
+			yield return factory.CreateFormatItemCompletionData("F", "flags value", TestEnum.Flags);
+			yield return factory.CreateFormatItemCompletionData("D", "integer value", TestEnum.Flags);
+			yield return factory.CreateFormatItemCompletionData("X", "hexadecimal", TestEnum.Flags);
+		}
+
+		IEnumerable<ICompletionData> GenerateTimeSpanFormatitems()
+		{
+			yield return factory.CreateFormatItemCompletionData("c", "invariant", new TimeSpan(0, 1, 23, 456));
+			yield return factory.CreateFormatItemCompletionData("G", "general long", new TimeSpan(0, 1, 23, 456));
+			yield return factory.CreateFormatItemCompletionData("g", "general short", new TimeSpan(0, 1, 23, 456));
+		}
+
+		static Guid defaultGuid = Guid.NewGuid();
+
+		IEnumerable<ICompletionData> GenerateGuidFormatitems()
+		{
+			yield return factory.CreateFormatItemCompletionData("N", "digits", defaultGuid);
+			yield return factory.CreateFormatItemCompletionData("D", "hypens", defaultGuid);
+			yield return factory.CreateFormatItemCompletionData("B", "braces", defaultGuid);
+			yield return factory.CreateFormatItemCompletionData("P", "parentheses", defaultGuid);
+		}
+
+		int GetFormatItemNumber()
+		{
+			int number = 0;
+			var o = offset - 2;
+			while (o > 0) {
+				char ch = document.GetCharAt(o);
+				if (ch == '{')
+					return number;
+				if (!char.IsDigit(ch))
+					break;
+				number = number * 10 + ch - '0';
+				o--;
+			}
+			return -1;
+		}
+
+		IEnumerable<ICompletionData> HandleStringFormatItems()
+		{
+			var formatArgument = GetFormatItemNumber();
+			if (formatArgument < 0)
+				return Enumerable.Empty<ICompletionData>();
+			var followUp = new StringBuilder();
+
+			var o = offset;
+			while (o < document.TextLength) {
+				char ch = document.GetCharAt(o);
+				followUp.Append(ch); 
+				o++;
+				if (ch == ';')
+					break;
+			}
+			var unit = ParseStub(followUp.ToString(), false);
+
+			var invoke = unit.GetNodeAt<InvocationExpression>(location);
+
+			if (invoke != null) {
+				var resolveResult = ResolveExpression(new ExpressionResult(invoke, unit));
+				var invokeResult = resolveResult.Result as InvocationResolveResult;
+				if (invokeResult != null) {
+					var arg = formatArgument + 1; // First argument is the format string
+					if (arg < invoke.Arguments.Count) {
+						var invokeArgument = ResolveExpression(new ExpressionResult(invoke.Arguments.ElementAt(arg), unit));
+						if (invokeArgument != null) {
+							var provider = GetFormatCompletionData(invokeArgument.Result.Type);
+							if (provider != null)
+								return provider;
+							if (!invokeArgument.Result.Type.IsKnownType(KnownTypeCode.Object))
+								return Enumerable.Empty<ICompletionData>();
+						}
+					}
+				}
+			}
+			return HandleStringFormatItemsFallback();
+		}
+
+		IEnumerable<ICompletionData> HandleStringFormatItemsFallback()
+		{
+			var unit = ParseStub("a}\");", false);
+
+			var invoke = unit.GetNodeAt<InvocationExpression>(location);
+
+			if (invoke == null)
+				return Enumerable.Empty<ICompletionData>();
+
+			var resolveResult = ResolveExpression(new ExpressionResult(invoke, unit));
+			var invokeResult = resolveResult.Result as CSharpInvocationResolveResult;
+			if (invokeResult == null)
+				return Enumerable.Empty<ICompletionData>();
+
+			Expression fmtArgumets;
+			IList<Expression> args;
+			if (FormatStringHelper.TryGetFormattingParameters(invokeResult, invoke, out fmtArgumets, out args, null)) {
+				return GenerateNumberFormatitems(false)
+					.Concat(GenerateDateTimeFormatitems())
+					.Concat(GenerateTimeSpanFormatitems())
+					.Concat(GenerateEnumFormatitems())
+					.Concat(GenerateGuidFormatitems());
+			}
+			return Enumerable.Empty<ICompletionData>();
+
+		}
+
+		IEnumerable<ICompletionData> GetFormatCompletionData(IType type)
+		{
+			if (type.Namespace != "System")
+				return null;
+			switch (type.Name) {
+				case "Int64":
+				case "UInt64":
+				case "Int32":
+				case "UInt32":
+				case "Int16":
+				case "UInt16":
+				case "Byte":
+				case "SByte":
+					return GenerateNumberFormatitems(false);
+				case "Single":
+				case "Double":
+				case "Decimal":
+					return GenerateNumberFormatitems(true);
+				case "Enum":
+					return GenerateEnumFormatitems();
+				case "DateTime":
+					return GenerateDateTimeFormatitems();
+				case "TimeSpan":
+					return GenerateTimeSpanFormatitems();
+				case "Guid":
+					return GenerateGuidFormatitems();
+			}
+			return null;
+		}
+
+		IEnumerable<ICompletionData> HandleToStringFormatItems()
+		{
+			var unit = ParseStub("\");", false);
+
+			var invoke = unit.GetNodeAt<InvocationExpression>(location);
+			if (invoke == null)
+				return Enumerable.Empty<ICompletionData>();
+
+			var resolveResult = ResolveExpression(new ExpressionResult(invoke, unit));
+			var invokeResult = resolveResult.Result as InvocationResolveResult;
+			if (invokeResult == null)
+				return Enumerable.Empty<ICompletionData>();
+			if (invokeResult.Member.Name == "ToString")
+				return GetFormatCompletionData(invokeResult.Member.DeclaringType) ?? Enumerable.Empty<ICompletionData>();
+			return Enumerable.Empty<ICompletionData>();
+		}
+
+		IEnumerable<ICompletionData> MagicKeyCompletion(char completionChar, bool controlSpace, out bool isComplete)
+		{
+			isComplete = false;
+			ExpressionResolveResult resolveResult;
+			switch (completionChar) {
+				// Magic key completion
+				case ':':
+					var text = GetMemberTextToCaret();
+					var lexer = new MiniLexer(text.Item1);
+					lexer.Parse();
+					if (lexer.IsInSingleComment ||
+						lexer.IsInChar ||
+						lexer.IsInMultiLineComment ||
+						lexer.IsInPreprocessorDirective) {
+						return Enumerable.Empty<ICompletionData>();
+					}
+
+					if (lexer.IsInString || lexer.IsInVerbatimString)
+						return HandleStringFormatItems();
+					return HandleMemberReferenceCompletion(GetExpressionBeforeCursor());
+				case '"':
+					text = GetMemberTextToCaret();
+					lexer = new MiniLexer(text.Item1);
+					lexer.Parse();
+					if (lexer.IsInSingleComment ||
+						lexer.IsInChar ||
+						lexer.IsInMultiLineComment ||
+						lexer.IsInPreprocessorDirective) {
+						return Enumerable.Empty<ICompletionData>();
+					}
+
+					if (lexer.IsInString || lexer.IsInVerbatimString)
+						return HandleToStringFormatItems();
+					return Enumerable.Empty<ICompletionData>();
+				case '.':
+					if (IsInsideCommentStringOrDirective()) {
+						return Enumerable.Empty<ICompletionData>();
+					}
+					return HandleMemberReferenceCompletion(GetExpressionBeforeCursor());
+				case '#':
+					if (!IsInPreprocessorDirective())
+						return null;
+					return GetDirectiveCompletionData();
+					// XML doc completion
+				case '<':
+					if (IsInsideDocComment()) {
+						return GetXmlDocumentationCompletionData();
+					}
+					if (controlSpace) {
+						return DefaultControlSpaceItems(ref isComplete);
+					}
+					return null;
+				case '>':
+					if (!IsInsideDocComment()) {
+						if (offset > 2 && document.GetCharAt(offset - 2) == '-' && !IsInsideCommentStringOrDirective()) {
+							return HandleMemberReferenceCompletion(GetExpressionBeforeCursor());
+						}
+						return null;
+					}
+					return null;
+
+					// Parameter completion
+				case '(':
+					if (IsInsideCommentStringOrDirective()) {
+						return null;
+					}
+					var invoke = GetInvocationBeforeCursor(true);
+					if (invoke == null) {
+						if (controlSpace)
+							return DefaultControlSpaceItems(ref isComplete, invoke);
+						return null;
+					}
+					if (invoke.Node is TypeOfExpression) {
+						return CreateTypeList();
+					}
+					var invocationResult = ResolveExpression(invoke);
+					if (invocationResult == null) {
+						return null;
+					}
+					var methodGroup = invocationResult.Result as MethodGroupResolveResult;
+					if (methodGroup != null) {
+						return CreateParameterCompletion(
+							methodGroup,
+							invocationResult.Resolver,
+							invoke.Node,
+							invoke.Unit,
+							0,
+							controlSpace
+						);
+					}
+
+					if (controlSpace) {
+						return DefaultControlSpaceItems(ref isComplete, invoke);
+					}
+					return null;
+				case '=':
+					return controlSpace ? DefaultControlSpaceItems(ref isComplete) : null;
+				case ',':
+					int cpos2;
+					if (!GetParameterCompletionCommandOffset(out cpos2)) { 
+						return null;
+					}
+					//	completionContext = CompletionWidget.CreateCodeCompletionContext (cpos2);
+					//	int currentParameter2 = MethodParameterDataProvider.GetCurrentParameterIndex (CompletionWidget, completionContext) - 1;
+					//				return CreateParameterCompletion (CreateResolver (), location, ExpressionContext.MethodBody, provider.Methods, currentParameter);	
+					break;
+
+					// Completion on space:
+				case ' ':
+					int tokenIndex = offset;
+					string token = GetPreviousToken(ref tokenIndex, false);
+					if (IsInsideCommentStringOrDirective()) {
+						return null;
+					}
+					// check propose name, for context <variable name> <ctrl+space> (but only in control space context)
+					//IType isAsType = null;
+					var isAsExpression = GetExpressionAt(offset);
+					if (controlSpace && isAsExpression != null && isAsExpression.Node is VariableDeclarationStatement && token != "new") {
+						var parent = isAsExpression.Node as VariableDeclarationStatement;
+						var proposeNameList = new CompletionDataWrapper(this);
+						if (parent.Variables.Count != 1)
+							return DefaultControlSpaceItems(ref isComplete, isAsExpression, controlSpace);
+
+						foreach (var possibleName in GenerateNameProposals (parent.Type)) {
+							if (possibleName.Length > 0) {
+								proposeNameList.Result.Add(factory.CreateLiteralCompletionData(possibleName.ToString()));
+							}
+						}
+
+						AutoSelect = false;
+						AutoCompleteEmptyMatch = false;
+						isComplete = true;
+						return proposeNameList.Result;
+					}
+					//				int tokenIndex = offset;
+					//				string token = GetPreviousToken (ref tokenIndex, false);
+					//				if (result.ExpressionContext == ExpressionContext.ObjectInitializer) {
+					//					resolver = CreateResolver ();
+					//					ExpressionContext exactContext = new NewCSharpExpressionFinder (dom).FindExactContextForObjectInitializer (document, resolver.Unit, Document.FileName, resolver.CallingType);
+					//					IReturnType objectInitializer = ((ExpressionContext.TypeExpressionContext)exactContext).UnresolvedType;
+					//					if (objectInitializer != null && objectInitializer.ArrayDimensions == 0 && objectInitializer.PointerNestingLevel == 0 && (token == "{" || token == ","))
+					//						return CreateCtrlSpaceCompletionData (completionContext, result); 
+					//				}
+					if (token == "=") {
+						int j = tokenIndex;
+						string prevToken = GetPreviousToken(ref j, false);
+						if (prevToken == "=" || prevToken == "+" || prevToken == "-" || prevToken == "!") {
+							token = prevToken + token;
+							tokenIndex = j;
+						}
+					}
+					switch (token) {
+						case "(":
+						case ",":
+							int cpos;
+							if (!GetParameterCompletionCommandOffset(out cpos)) { 
+								break;
+							}
+							int currentParameter = GetCurrentParameterIndex(cpos - 1, this.offset) - 1;
+							if (currentParameter < 0) {
+								return null;
+							}
+							invoke = GetInvocationBeforeCursor(token == "(");
+							if (invoke == null) {
+								return null;
+							}
+							invocationResult = ResolveExpression(invoke);
+							if (invocationResult == null) {
+								return null;
+							}
+							methodGroup = invocationResult.Result as MethodGroupResolveResult;
+							if (methodGroup != null) {
+								return CreateParameterCompletion(
+									methodGroup,
+									invocationResult.Resolver,
+									invoke.Node,
+									invoke.Unit,
+									currentParameter,
+									controlSpace);
+							}
+							return null;
+						case "=":
+						case "==":
+						case "!=":
+							GetPreviousToken(ref tokenIndex, false);
+							var expressionOrVariableDeclaration = GetExpressionAt(tokenIndex);
+							if (expressionOrVariableDeclaration == null) {
+								return null;
+							}
+							resolveResult = ResolveExpression(expressionOrVariableDeclaration);
+							if (resolveResult == null) {
+								return null;
+							}
+							if (resolveResult.Result.Type.Kind == TypeKind.Enum) {
+								var wrapper = new CompletionDataWrapper(this);
+								AddContextCompletion(
+									wrapper,
+									resolveResult.Resolver,
+									expressionOrVariableDeclaration.Node);
+								AddEnumMembers(wrapper, resolveResult.Result.Type, resolveResult.Resolver);
+								AutoCompleteEmptyMatch = false;
+								return wrapper.Result;
+							}
+							//				
+							//					if (resolvedType.FullName == DomReturnType.Bool.FullName) {
+							//						CompletionDataList completionList = new ProjectDomCompletionDataList ();
+							//						CompletionDataCollector cdc = new CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, resolver.CallingType, location);
+							//						completionList.AutoCompleteEmptyMatch = false;
+							//						cdc.Add ("true", "md-keyword");
+							//						cdc.Add ("false", "md-keyword");
+							//						resolver.AddAccessibleCodeCompletionData (result.ExpressionContext, cdc);
+							//						return completionList;
+							//					}
+							//					if (resolvedType.ClassType == ClassType.Delegate && token == "=") {
+							//						CompletionDataList completionList = new ProjectDomCompletionDataList ();
+							//						string parameterDefinition = AddDelegateHandlers (completionList, resolvedType);
+							//						string varName = GetPreviousMemberReferenceExpression (tokenIndex);
+							//						completionList.Add (new EventCreationCompletionData (document, varName, resolvedType, null, parameterDefinition, resolver.CallingMember, resolvedType));
+							//						
+							//						CompletionDataCollector cdc = new CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, resolver.CallingType, location);
+							//						resolver.AddAccessibleCodeCompletionData (result.ExpressionContext, cdc);
+							//						foreach (var data in completionList) {
+							//							if (data is MemberCompletionData) 
+							//								((MemberCompletionData)data).IsDelegateExpected = true;
+							//						}
+							//						return completionList;
+							//					}
+							return null;
+						case "+=":
+						case "-=":
+							var curTokenIndex = tokenIndex;
+							GetPreviousToken(ref tokenIndex, false);
+
+							expressionOrVariableDeclaration = GetExpressionAt(tokenIndex);
+							if (expressionOrVariableDeclaration == null) {
+								return null;
+							}
+
+							resolveResult = ResolveExpression(expressionOrVariableDeclaration);
+							if (resolveResult == null) {
+								return null;
+							}
+
+
+							var mrr = resolveResult.Result as MemberResolveResult;
+							if (mrr != null) {
+								var evt = mrr.Member as IEvent;
+								if (evt == null) {
+									return null;
+								}
+								var delegateType = evt.ReturnType;
+								if (delegateType.Kind != TypeKind.Delegate) {
+									return null;
+								}
+
+								var wrapper = new CompletionDataWrapper(this);
+								if (currentType != null) {
+									//							bool includeProtected = DomType.IncludeProtected (dom, typeFromDatabase, resolver.CallingType);
+									foreach (var method in ctx.CurrentTypeDefinition.Methods) {
+										if (MatchDelegate(delegateType, method) /*										&& method.IsAccessibleFrom (dom, resolver.CallingType, resolver.CallingMember, includeProtected) &&*/) {
+											wrapper.AddMember(method);
+											//									data.SetText (data.CompletionText + ";");
+										}
+									}
+								}
+								if (token == "+=") {
+									string parameterDefinition = AddDelegateHandlers(
+										wrapper,
+										delegateType,
+										optDelegateName: GuessEventHandlerMethodName(curTokenIndex, (currentType == null) ? null : currentType.Name)
+									);
+								}
+
+								return wrapper.Result;
+							}
+							return null;
+						case ":":
+							if (currentMember == null) {
+								token = GetPreviousToken(ref tokenIndex, false);
+								token = GetPreviousToken(ref tokenIndex, false);
+								if (token == "enum")
+									return HandleEnumContext();
+								var wrapper = new CompletionDataWrapper(this);
+								AddTypesAndNamespaces(
+									wrapper,
+									GetState(),
+									null,
+									t =>  {
+										if (currentType != null && currentType.ReflectionName.Equals(t.ReflectionName))
+											return null;
+										var def = t.GetDefinition();
+										if (def != null && t.Kind != TypeKind.Interface && (def.IsSealed ||def.IsStatic))
+											return null;
+										return t;
+									}
+								);
+								return wrapper.Result;
+							}
+							return null;
+					}
+
+					var keywordCompletion = HandleKeywordCompletion(tokenIndex, token);
+					if (keywordCompletion == null && controlSpace) {
+						goto default;
+					}
+					return keywordCompletion;
+					// Automatic completion
+				default:
+					if (IsInsideCommentStringOrDirective()) {
+						tokenIndex = offset;
+						token = GetPreviousToken(ref tokenIndex, false);
+						if (IsInPreprocessorDirective() && (token.Length == 1 && char.IsLetter(completionChar) || controlSpace)) {
+							while (token != null && document.GetCharAt(tokenIndex - 1) != '#') {
+								token = GetPreviousToken(ref tokenIndex, false);
+							}
+							if (token != null)
+								return HandleKeywordCompletion(tokenIndex, token);
+						}
+						return null;
+					}
+					char prevCh = offset > 2 ? document.GetCharAt(offset - 2) : ';';
+					char nextCh = offset < document.TextLength ? document.GetCharAt(offset) : ' ';
+					const string allowedChars = ";,.[](){}+-*/%^?:&|~!<>=";
+
+					if ((!Char.IsWhiteSpace(nextCh) && allowedChars.IndexOf(nextCh) < 0) || !(Char.IsWhiteSpace(prevCh) || allowedChars.IndexOf(prevCh) >= 0)) {
+						if (!controlSpace)
+							return null;
+					}
+
+					if (IsInLinqContext(offset)) {
+						if (!controlSpace && !(char.IsLetter(completionChar) || completionChar == '_')) {
+							return null;
+						}
+						tokenIndex = offset;
+						token = GetPreviousToken(ref tokenIndex, false);
+						// token last typed
+						if (!char.IsWhiteSpace(completionChar) && !linqKeywords.Contains(token)) {
+							token = GetPreviousToken(ref tokenIndex, false);
+						}
+						// token last typed
+
+						if (linqKeywords.Contains(token)) {
+							if (token == "from") {
+								// after from no auto code completion.
+								return null;
+							}
+							return DefaultControlSpaceItems(ref isComplete);
+						}
+						var dataList = new CompletionDataWrapper(this);
+						AddKeywords(dataList, linqKeywords);
+						return dataList.Result;
+					}
+					if (currentType != null && currentType.Kind == TypeKind.Enum) {
+						if (!char.IsLetter(completionChar))
+							return null;
+						return HandleEnumContext();
+					}
+					var contextList = new CompletionDataWrapper(this);
+					var identifierStart = GetExpressionAtCursor();
+					if (!(char.IsLetter(completionChar) || completionChar == '_') && (!controlSpace || identifierStart == null)) {
+						return controlSpace ? HandleAccessorContext() ?? DefaultControlSpaceItems(ref isComplete, identifierStart) : null;
+					}
+
+					if (identifierStart != null) {
+						if (identifierStart.Node is TypeParameterDeclaration) {
+							return null;
+						}
+
+						if (identifierStart.Node is MemberReferenceExpression) {
+							return HandleMemberReferenceCompletion(
+								new ExpressionResult(
+									((MemberReferenceExpression)identifierStart.Node).Target,
+									identifierStart.Unit
+								)
+							);
+						}
+
+						if (identifierStart.Node is Identifier) {
+							if (identifierStart.Node.Parent is GotoStatement)
+								return null;
+
+							// May happen in variable names
+							return controlSpace ? DefaultControlSpaceItems(ref isComplete, identifierStart) : null;
+						}
+						if (identifierStart.Node is VariableInitializer && location <= ((VariableInitializer)identifierStart.Node).NameToken.EndLocation) {
+							return controlSpace ? HandleAccessorContext() ?? DefaultControlSpaceItems(ref isComplete, identifierStart) : null;
+						}
+						if (identifierStart.Node is CatchClause) {
+							if (((CatchClause)identifierStart.Node).VariableNameToken.IsInside(location)) {
+								return null;
+							}
+						}
+						if (identifierStart.Node is AstType && identifierStart.Node.Parent is CatchClause) {
+							return HandleCatchClauseType(identifierStart);
+						}
+
+						var pDecl = identifierStart.Node as ParameterDeclaration;
+						if (pDecl != null && pDecl.Parent is LambdaExpression) {
+							return null;
+						}
+					}
+
+
+					// Do not pop up completion on identifier identifier (should be handled by keyword completion).
+					tokenIndex = offset - 1;
+					token = GetPreviousToken(ref tokenIndex, false);
+					if (token == "class" || token == "interface" || token == "struct" || token == "enum" || token == "namespace") {
+						// after these always follows a name
+						return null;
+					}
+					var keywordresult = HandleKeywordCompletion(tokenIndex, token);
+					if (keywordresult != null) {
+						return keywordresult;
+					}
+
+					if ((!Char.IsWhiteSpace(nextCh) && allowedChars.IndexOf(nextCh) < 0) || !(Char.IsWhiteSpace(prevCh) || allowedChars.IndexOf(prevCh) >= 0)) {
+						if (controlSpace)
+							return DefaultControlSpaceItems(ref isComplete, identifierStart);
+					}
+
+					int prevTokenIndex = tokenIndex;
+					var prevToken2 = GetPreviousToken(ref prevTokenIndex, false);
+					if (prevToken2 == "delegate") {
+						// after these always follows a name
+						return null;
+					}
+
+					if (identifierStart == null && !string.IsNullOrEmpty(token) && !IsInsideCommentStringOrDirective() && (prevToken2 == ";" || prevToken2 == "{" || prevToken2 == "}")) {
+						char last = token [token.Length - 1];
+						if (char.IsLetterOrDigit(last) || last == '_' || token == ">") {
+							return HandleKeywordCompletion(tokenIndex, token);
+						}
+					}
+					if (identifierStart == null) {
+						var accCtx = HandleAccessorContext();
+						if (accCtx != null) {
+							return accCtx;
+						}
+						return DefaultControlSpaceItems(ref isComplete, null, controlSpace);
+					}
+					CSharpResolver csResolver;
+					AstNode n = identifierStart.Node;
+					if (n.Parent is NamedArgumentExpression)
+						n = n.Parent;
+
+					if (n != null && n.Parent is AnonymousTypeCreateExpression) {
+						AutoSelect = false;
+					}
+
+					// new { b$ } 
+					if (n is IdentifierExpression && n.Parent is AnonymousTypeCreateExpression)
+						return null;
+
+					// Handle foreach (type name _
+					if (n is IdentifierExpression) {
+						var prev = n.GetPrevNode() as ForeachStatement;
+						while (prev != null && prev.EmbeddedStatement is ForeachStatement)
+							prev = (ForeachStatement)prev.EmbeddedStatement;
+						if (prev != null && prev.InExpression.IsNull) {
+							if (IncludeKeywordsInCompletionList)
+								contextList.AddCustom("in");
+							return contextList.Result;
+						}
+					}
+					// Handle object/enumerable initialzer expressions: "new O () { P$"
+					if (n is IdentifierExpression && n.Parent is ArrayInitializerExpression && !(n.Parent.Parent is ArrayCreateExpression)) {
+						var result = HandleObjectInitializer(identifierStart.Unit, n);
+						if (result != null)
+							return result;
+					}
+
+					if (n != null && n.Parent is InvocationExpression ||
+						n.Parent is ParenthesizedExpression && n.Parent.Parent is InvocationExpression) {
+						if (n.Parent is ParenthesizedExpression)
+							n = n.Parent;
+						var invokeParent = (InvocationExpression)n.Parent;
+						var invokeResult = ResolveExpression(
+							invokeParent.Target
+						);
+						var mgr = invokeResult != null ? invokeResult.Result as MethodGroupResolveResult : null;
+						if (mgr != null) {
+							int idx = 0;
+							foreach (var arg in invokeParent.Arguments) {
+								if (arg == n) {
+									break;
+								}
+								idx++;
+							}
+
+							foreach (var method in mgr.Methods) {
+								if (idx < method.Parameters.Count && method.Parameters [idx].Type.Kind == TypeKind.Delegate) {
+									AutoSelect = false;
+									AutoCompleteEmptyMatch = false;
+								}
+								foreach (var p in method.Parameters) {
+									contextList.AddNamedParameterVariable(p);
+								}
+							}
+							idx++;
+							foreach (var list in mgr.GetEligibleExtensionMethods (true)) {
+								foreach (var method in list) {
+									if (idx < method.Parameters.Count && method.Parameters [idx].Type.Kind == TypeKind.Delegate) {
+										AutoSelect = false;
+										AutoCompleteEmptyMatch = false;
+									}
+								}
+							}
+						}
+					}
+
+					if (n != null && n.Parent is ObjectCreateExpression) {
+						var invokeResult = ResolveExpression(n.Parent);
+						var mgr = invokeResult != null ? invokeResult.Result as ResolveResult : null;
+						if (mgr != null) {
+							foreach (var constructor in mgr.Type.GetConstructors ()) {
+								foreach (var p in constructor.Parameters) {
+									contextList.AddVariable(p);
+								}
+							}
+						}
+					}
+
+					if (n is IdentifierExpression) {
+						var bop = n.Parent as BinaryOperatorExpression;
+						Expression evaluationExpr = null;
+
+						if (bop != null && bop.Right == n && (bop.Operator == BinaryOperatorType.Equality || bop.Operator == BinaryOperatorType.InEquality)) {
+							evaluationExpr = bop.Left;
+						}
+						// check for compare to enum case 
+						if (evaluationExpr != null) {
+							resolveResult = ResolveExpression(evaluationExpr);
+							if (resolveResult != null && resolveResult.Result.Type.Kind == TypeKind.Enum) {
+								var wrapper = new CompletionDataWrapper(this);
+								AddContextCompletion(
+									wrapper,
+									resolveResult.Resolver,
+									evaluationExpr
+								);
+								AddEnumMembers(wrapper, resolveResult.Result.Type, resolveResult.Resolver);
+								AutoCompleteEmptyMatch = false;
+								return wrapper.Result;
+							}
+						}
+					}
+
+					if (n is Identifier && n.Parent is ForeachStatement) {
+						if (controlSpace) {
+							return DefaultControlSpaceItems(ref isComplete);
+						}
+						return null;
+					}
+
+					if (n is ArrayInitializerExpression) {
+						// check for new [] {...} expression -> no need to resolve the type there
+						var parent = n.Parent as ArrayCreateExpression;
+						if (parent != null && parent.Type.IsNull) {
+							return DefaultControlSpaceItems(ref isComplete);
+						}
+
+						var initalizerResult = ResolveExpression(n.Parent);
+
+						var concreteNode = identifierStart.Unit.GetNodeAt<IdentifierExpression>(location);
+						// check if we're on the right side of an initializer expression
+						if (concreteNode != null && concreteNode.Parent != null && concreteNode.Parent.Parent != null && concreteNode.Identifier != "a" && concreteNode.Parent.Parent is NamedExpression) {
+							return DefaultControlSpaceItems(ref isComplete);
+						}
+						if (initalizerResult != null && initalizerResult.Result.Type.Kind != TypeKind.Unknown) { 
+
+							foreach (var property in initalizerResult.Result.Type.GetProperties ()) {
+								if (!property.IsPublic) {
+									continue;
+								}
+								var data = contextList.AddMember(property);
+								if (data != null)
+									data.DisplayFlags |= DisplayFlags.NamedArgument;
+							}
+							foreach (var field in initalizerResult.Result.Type.GetFields ()) {       
+								if (!field.IsPublic) {
+									continue;
+								}
+								var data = contextList.AddMember(field);
+								if (data != null)
+									data.DisplayFlags |= DisplayFlags.NamedArgument;
+							}
+							return contextList.Result;
+						}
+						return DefaultControlSpaceItems(ref isComplete);
+					}
+
+					if (IsAttributeContext(n)) {
+						// add attribute targets
+						if (currentType == null) {
+							contextList.AddCustom("assembly");
+							contextList.AddCustom("module");
+							contextList.AddCustom("type");
+						} else {
+							contextList.AddCustom("param");
+							contextList.AddCustom("field");
+							contextList.AddCustom("property");
+							contextList.AddCustom("method");
+							contextList.AddCustom("event");
+						}
+						contextList.AddCustom("return");
+					}
+					if (n is MemberType) {
+						resolveResult = ResolveExpression(
+							((MemberType)n).Target
+						);
+						return CreateTypeAndNamespaceCompletionData(
+							location,
+							resolveResult.Result,
+							((MemberType)n).Target,
+							resolveResult.Resolver
+						);
+					}
+					if (n != null/*					 && !(identifierStart.Item2 is TypeDeclaration)*/) {
+						csResolver = new CSharpResolver(ctx);
+						var nodes = new List<AstNode>();
+						nodes.Add(n);
+						if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute) {
+							nodes.Add(n.Parent);
+						}
+						var astResolver = CompletionContextProvider.GetResolver(csResolver, identifierStart.Unit);
+						astResolver.ApplyNavigator(new NodeListResolveVisitorNavigator(nodes));
+						try {
+							csResolver = astResolver.GetResolverStateBefore(n);
+						} catch (Exception) {
+							csResolver = GetState();
+						}
+						// add attribute properties.
+						if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute) {
+							var rr = ResolveExpression(n.Parent);
+							if (rr != null)
+								AddAttributeProperties(contextList, rr.Result);
+						}
+					} else {
+						csResolver = GetState();
+					}
+					// identifier has already started with the first letter
+					offset--;
+					AddContextCompletion(
+						contextList,
+						csResolver,
+						identifierStart.Node
+					);
+					return contextList.Result;
+					//				if (stub.Parent is BlockStatement)
+
+					//				result = FindExpression (dom, completionContext, -1);
+					//				if (result == null)
+					//					return null;
+					//				 else if (result.ExpressionContext != ExpressionContext.IdentifierExpected) {
+					//					triggerWordLength = 1;
+					//					bool autoSelect = true;
+					//					IType returnType = null;
+					//					if ((prevCh == ',' || prevCh == '(') && GetParameterCompletionCommandOffset (out cpos)) {
+					//						ctx = CompletionWidget.CreateCodeCompletionContext (cpos);
+					//						NRefactoryParameterDataProvider dataProvider = ParameterCompletionCommand (ctx) as NRefactoryParameterDataProvider;
+					//						if (dataProvider != null) {
+					//							int i = dataProvider.GetCurrentParameterIndex (CompletionWidget, ctx) - 1;
+					//							foreach (var method in dataProvider.Methods) {
+					//								if (i < method.Parameters.Count) {
+					//									returnType = dom.GetType (method.Parameters [i].ReturnType);
+					//									autoSelect = returnType == null || returnType.ClassType != ClassType.Delegate;
+					//									break;
+					//								}
+					//							}
+					//						}
+					//					}
+					//					// Bug 677531 - Auto-complete doesn't always highlight generic parameter in method signature
+					//					//if (result.ExpressionContext == ExpressionContext.TypeName)
+					//					//	autoSelect = false;
+					//					CompletionDataList dataList = CreateCtrlSpaceCompletionData (completionContext, result);
+					//					AddEnumMembers (dataList, returnType);
+					//					dataList.AutoSelect = autoSelect;
+					//					return dataList;
+					//				} else {
+					//					result = FindExpression (dom, completionContext, 0);
+					//					tokenIndex = offset;
+					//					
+					//					// check foreach case, unfortunately the expression finder is too dumb to handle full type names
+					//					// should be overworked if the expression finder is replaced with a mcs ast based analyzer.
+					//					var possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // starting letter
+					//					possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // varname
+					//				
+					//					// read return types to '(' token
+					//					possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // varType
+					//					if (possibleForeachToken == ">") {
+					//						while (possibleForeachToken != null && possibleForeachToken != "(") {
+					//							possibleForeachToken = GetPreviousToken (ref tokenIndex, false);
+					//						}
+					//					} else {
+					//						possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // (
+					//						if (possibleForeachToken == ".")
+					//							while (possibleForeachToken != null && possibleForeachToken != "(")
+					//								possibleForeachToken = GetPreviousToken (ref tokenIndex, false);
+					//					}
+					//					possibleForeachToken = GetPreviousToken (ref tokenIndex, false); // foreach
+					//				
+					//					if (possibleForeachToken == "foreach") {
+					//						result.ExpressionContext = ExpressionContext.ForeachInToken;
+					//					} else {
+					//						return null;
+					//						//								result.ExpressionContext = ExpressionContext.IdentifierExpected;
+					//					}
+					//					result.Expression = "";
+					//					result.Region = DomRegion.Empty;
+					//				
+					//					return CreateCtrlSpaceCompletionData (completionContext, result);
+					//				}
+					//				break;
+			}
+			return null;
+
+		}
+
+		IEnumerable<ICompletionData> HandleCatchClauseType(ExpressionResult identifierStart)
+		{
+			Func<IType, IType> typePred = delegate (IType type) {
+				if (type.GetAllBaseTypes().Any(t => t.ReflectionName == "System.Exception"))
+					return type;
+				return null;
+			};
+			if (identifierStart.Node.Parent is CatchClause) {
+				var wrapper = new CompletionDataWrapper(this);
+				AddTypesAndNamespaces(
+					wrapper,
+					GetState(),
+					identifierStart.Node,
+					typePred,
+					m => false
+				);
+				return wrapper.Result;
+			}
+
+			var resolveResult = ResolveExpression(identifierStart);
+			return CreateCompletionData(
+				location,
+				resolveResult.Result,
+				identifierStart.Node,
+				resolveResult.Resolver,
+				typePred
+			);
+		}
+
+		string[] validEnumBaseTypes = {
+			"byte",
+			"sbyte",
+			"short",
+			"int",
+			"long",
+			"ushort",
+			"uint",
+			"ulong"
+		};
+
+		IEnumerable<ICompletionData> HandleEnumContext()
+		{
+			var syntaxTree = ParseStub("a", false);
+			if (syntaxTree == null) {
+				return null;
+			}
+
+			var curType = syntaxTree.GetNodeAt<TypeDeclaration>(location);
+			if (curType == null || curType.ClassType != ClassType.Enum) {
+				syntaxTree = ParseStub("a {}", false);
+				var node = syntaxTree.GetNodeAt<AstType>(location);
+				if (node != null) {
+					var wrapper = new CompletionDataWrapper(this);
+					AddKeywords(wrapper, validEnumBaseTypes);
+					return wrapper.Result;
+				}
+			}
+
+			var member = syntaxTree.GetNodeAt<EnumMemberDeclaration>(location);
+			if (member != null && member.NameToken.EndLocation < location) {
+				if (currentMember == null && currentType != null) {
+					foreach (var a in currentType.Members)
+						if (a.Region.Begin < location && (currentMember == null || a.Region.Begin > currentMember.Region.Begin))
+							currentMember = a;
+				}
+				bool isComplete = false;
+				return DefaultControlSpaceItems(ref isComplete);
+			}
+
+			var attribute = syntaxTree.GetNodeAt<Attribute>(location);
+			if (attribute != null) {
+				var contextList = new CompletionDataWrapper(this);
+				var astResolver = CompletionContextProvider.GetResolver(GetState(), syntaxTree);
+				var csResolver = astResolver.GetResolverStateBefore(attribute);
+				AddContextCompletion(
+					contextList,
+					csResolver,
+					attribute
+				);
+				return contextList.Result;
+			}
+			return null;
+		}
+
+		bool IsInLinqContext(int offset)
+		{
+			string token;
+			while (null != (token = GetPreviousToken(ref offset, true)) && !IsInsideCommentStringOrDirective()) {
+
+				if (token == "from") {
+					return !IsInsideCommentStringOrDirective(offset);
+				}
+				if (token == ";" || token == "{") {
+					return false;
+				}
+			}
+			return false;
+		}
+
+		IEnumerable<ICompletionData> HandleAccessorContext()
+		{
+			var unit = ParseStub("get; }", false);
+			var node = unit.GetNodeAt(location, cn => !(cn is CSharpTokenNode));
+			if (node is Accessor) {
+				node = node.Parent;
+			}
+			var contextList = new CompletionDataWrapper(this);
+			if (node is PropertyDeclaration || node is IndexerDeclaration) {
+				if (IncludeKeywordsInCompletionList) {
+					contextList.AddCustom("get");
+					contextList.AddCustom("set");
+					AddKeywords(contextList, accessorModifierKeywords);
+				}
+			} else if (node is CustomEventDeclaration) {
+				if (IncludeKeywordsInCompletionList) {
+					contextList.AddCustom("add");
+					contextList.AddCustom("remove");
+				}
+			} else {
+				return null;
+			}
+
+			return contextList.Result;
+		}
+
+		class IfVisitor :DepthFirstAstVisitor
+		{
+			TextLocation loc;
+			ICompletionContextProvider completionContextProvider;
+			public bool IsValid;
+
+			public IfVisitor(TextLocation loc, ICompletionContextProvider completionContextProvider)
+			{
+				this.loc = loc;
+				this.completionContextProvider = completionContextProvider;
+
+				this.IsValid = true;
+			}
+
+			void Check(string argument)
+			{
+				// TODO: evaluate #if epressions
+				if (argument.Any(c => !(char.IsLetterOrDigit(c) || c == '_')))
+					return;
+				IsValid &= completionContextProvider.ConditionalSymbols.Contains(argument);
+			}
+
+			Stack<PreProcessorDirective> ifStack = new Stack<PreProcessorDirective>();
+
+			public override void VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective)
+			{
+				if (preProcessorDirective.Type == PreProcessorDirectiveType.If) {
+					ifStack.Push(preProcessorDirective);
+				} else if (preProcessorDirective.Type == PreProcessorDirectiveType.Endif) {
+					if (ifStack.Count == 0)
+						return;
+					var ifDirective = ifStack.Pop();
+					if (ifDirective.StartLocation < loc && loc < preProcessorDirective.EndLocation) {
+						Check(ifDirective.Argument);
+					}
+
+				}
+
+				base.VisitPreProcessorDirective(preProcessorDirective);
+			}
+
+			public void End()
+			{
+				while (ifStack.Count > 0) {
+					Check(ifStack.Pop().Argument);
+				}
+			}
+		}
+
+		IEnumerable<ICompletionData> DefaultControlSpaceItems(ref bool isComplete, ExpressionResult xp = null, bool controlSpace = true)
+		{
+			var wrapper = new CompletionDataWrapper(this);
+			if (offset >= document.TextLength) {
+				offset = document.TextLength - 1;
+			}
+			while (offset > 1 && char.IsWhiteSpace(document.GetCharAt(offset))) {
+				offset--;
+			}
+			location = document.GetLocation(offset);
+
+			if (xp == null) {
+				xp = GetExpressionAtCursor();
+			}
+			AstNode node;
+			SyntaxTree unit;
+			ExpressionResolveResult rr;
+			if (xp != null) {
+				node = xp.Node;
+				rr = ResolveExpression(node);
+				unit = xp.Unit;
+			} else {
+				unit = ParseStub("foo", false);
+				node = unit.GetNodeAt(
+					location.Line,
+					location.Column + 2,
+					n => n is Expression || n is AstType || n is NamespaceDeclaration || n is Attribute
+				);
+				rr = ResolveExpression(node);
+			}
+			var ifvisitor = new IfVisitor(location, CompletionContextProvider);
+			unit.AcceptVisitor(ifvisitor);
+			ifvisitor.End();
+			if (!ifvisitor.IsValid)
+				return null;
+			// namespace name case
+			var ns = node as NamespaceDeclaration;
+			if (ns != null) {
+				var last = ns.NamespaceName;
+				if (last != null && location < last.EndLocation)
+					return null;
+			}
+			if (node is Identifier && node.Parent is ForeachStatement) {
+				var foreachStmt = (ForeachStatement)node.Parent;
+				foreach (var possibleName in GenerateNameProposals (foreachStmt.VariableType)) {
+					if (possibleName.Length > 0) {
+						wrapper.Result.Add(factory.CreateLiteralCompletionData(possibleName.ToString()));
+					}
+				}
+
+				AutoSelect = false;
+				AutoCompleteEmptyMatch = false;
+				isComplete = true;
+				return wrapper.Result;
+			}
+
+			if (node is Identifier && node.Parent is ParameterDeclaration) {
+				if (!controlSpace) {
+					return null;
+				}
+				// Try Parameter name case 
+				var param = node.Parent as ParameterDeclaration;
+				if (param != null) {
+					foreach (var possibleName in GenerateNameProposals (param.Type)) {
+						if (possibleName.Length > 0) {
+							wrapper.Result.Add(factory.CreateLiteralCompletionData(possibleName.ToString()));
+						}
+					}
+					AutoSelect = false;
+					AutoCompleteEmptyMatch = false;
+					isComplete = true;
+					return wrapper.Result;
+				}
+			}
+			var pDecl = node as ParameterDeclaration;
+			if (pDecl != null && pDecl.Parent is LambdaExpression) {
+				return null;
+			}
+			/*						if (Unit != null && (node == null || node is TypeDeclaration)) {
+				var constructor = Unit.GetNodeAt<ConstructorDeclaration>(
+					location.Line,
+					location.Column - 3
+				);
+				if (constructor != null && !constructor.ColonToken.IsNull && constructor.Initializer.IsNull) {
+					wrapper.AddCustom("this");
+					wrapper.AddCustom("base");
+					return wrapper.Result;
+				}
+			}*/
+
+			var initializer = node != null ? node.Parent as ArrayInitializerExpression : null;
+			if (initializer != null) {
+				var result = HandleObjectInitializer(unit, initializer);
+				if (result != null)
+					return result;
+			}
+			CSharpResolver csResolver = null;
+			if (rr != null) {
+				csResolver = rr.Resolver;
+			}
+
+			if (csResolver == null) {
+				if (node != null) {
+					csResolver = GetState();
+					//var astResolver = new CSharpAstResolver (csResolver, node, xp != null ? xp.Item1 : CSharpUnresolvedFile);
+
+					try {
+						//csResolver = astResolver.GetResolverStateBefore (node);
+						Console.WriteLine(csResolver.LocalVariables.Count());
+					} catch (Exception  e) {
+						Console.WriteLine("E!!!" + e);
+					}
+
+				} else {
+					csResolver = GetState();
+				}
+			}
+
+			if (node is Attribute) {
+				// add attribute properties.
+				var astResolver = CompletionContextProvider.GetResolver(csResolver, unit);
+				var resolved = astResolver.Resolve(node);
+				AddAttributeProperties(wrapper, resolved);
+			}
+
+
+			if (node == null) {
+				// try lambda
+				unit = ParseStub("foo) => {}", true);
+				var pd = unit.GetNodeAt<ParameterDeclaration>(
+					location.Line,
+					location.Column
+				);
+				if (pd != null) {
+					var astResolver = unit != null ? CompletionContextProvider.GetResolver(GetState(), unit) : null;
+					var parameterType = astResolver.Resolve(pd.Type);
+					// Type <name> is always a name context -> return null
+					if (parameterType != null && !parameterType.IsError)
+						return null;
+				}
+			}
+
+			AddContextCompletion(wrapper, csResolver, node);
+
+			return wrapper.Result;
+		}
+
+		static void AddAttributeProperties(CompletionDataWrapper wrapper, ResolveResult resolved)
+		{
+			if (resolved == null || resolved.Type.Kind == TypeKind.Unknown)
+				return;
+
+			foreach (var property in resolved.Type.GetProperties (p => p.Accessibility == Accessibility.Public)) {
+				var data = wrapper.AddMember(property);
+				if (data != null)
+					data.DisplayFlags |= DisplayFlags.NamedArgument;
+			}
+			foreach (var field in resolved.Type.GetFields (p => p.Accessibility == Accessibility.Public)) {
+				var data = wrapper.AddMember(field);
+				if (data != null)
+					data.DisplayFlags |= DisplayFlags.NamedArgument;
+			}
+			foreach (var constructor in resolved.Type.GetConstructors (p => p.Accessibility == Accessibility.Public)) {
+				foreach (var p in constructor.Parameters) {
+					wrapper.AddNamedParameterVariable(p);
+				}
+			}
+		}
+
+		void AddContextCompletion(CompletionDataWrapper wrapper, CSharpResolver state, AstNode node)
+		{
+			int i = offset - 1;
+			var isInGlobalDelegate = node == null && state.CurrentTypeDefinition == null && GetPreviousToken(ref i, true) == "delegate";
+
+			if (state != null && !(node is AstType)) {
+				foreach (var variable in state.LocalVariables) {
+					if (variable.Region.IsInside(location.Line, location.Column - 1)) {
+						continue;
+					}
+					wrapper.AddVariable(variable);
+				}
+			}
+
+			if (state.CurrentMember is IParameterizedMember && !(node is AstType)) {
+				var param = (IParameterizedMember)state.CurrentMember;
+				foreach (var p in param.Parameters) {
+					wrapper.AddVariable(p);
+				}
+			}
+
+			if (state.CurrentMember is IMethod) {
+				var method = (IMethod)state.CurrentMember;
+				foreach (var p in method.TypeParameters) {
+					wrapper.AddTypeParameter(p);
+				}
+			}
+
+			Func<IType, IType> typePred = null;
+			if (IsAttributeContext(node)) {
+				var attribute = Compilation.FindType(KnownTypeCode.Attribute);
+				typePred = t => t.GetAllBaseTypeDefinitions().Any(bt => bt.Equals(attribute)) ? t : null;
+			}
+			if (node != null && node.Role == Roles.BaseType) {
+				typePred = t => {
+					var def = t.GetDefinition();
+					if (def != null && t.Kind != TypeKind.Interface && (def.IsSealed || def.IsStatic))
+						return null;
+					return t;
+				};
+			}
+
+			if (node != null && !(node is NamespaceDeclaration) || state.CurrentTypeDefinition != null || isInGlobalDelegate) {
+				AddTypesAndNamespaces(wrapper, state, node, typePred);
+
+				wrapper.Result.Add(factory.CreateLiteralCompletionData("global"));
+			}
+
+			if (!(node is AstType)) {
+				if (currentMember != null || node is Expression) {
+					AddKeywords(wrapper, statementStartKeywords);
+					if (LanguageVersion.Major >= 5)
+						AddKeywords(wrapper, new [] { "await" });
+					AddKeywords(wrapper, expressionLevelKeywords);
+					if (node == null || node is TypeDeclaration)
+						AddKeywords(wrapper, typeLevelKeywords);
+				} else if (currentType != null) {
+					AddKeywords(wrapper, typeLevelKeywords);
+				} else {
+					if (!isInGlobalDelegate && !(node is Attribute))
+						AddKeywords(wrapper, globalLevelKeywords);
+				}
+				var prop = currentMember as IUnresolvedProperty;
+				if (prop != null && prop.Setter != null && prop.Setter.Region.IsInside(location)) {
+					wrapper.AddCustom("value");
+				} 
+				if (currentMember is IUnresolvedEvent) {
+					wrapper.AddCustom("value");
+				} 
+
+				if (IsInSwitchContext(node)) {
+					if (IncludeKeywordsInCompletionList)
+						wrapper.AddCustom("case"); 
+				}
+			} else {
+				if (((AstType)node).Parent is ParameterDeclaration) {
+					AddKeywords(wrapper, parameterTypePredecessorKeywords);
+				}
+			}
+
+			if (node != null || state.CurrentTypeDefinition != null || isInGlobalDelegate)
+				AddKeywords(wrapper, primitiveTypesKeywords);
+			if (currentMember != null && (node is IdentifierExpression || node is SimpleType) && (node.Parent is ExpressionStatement || node.Parent is ForeachStatement || node.Parent is UsingStatement)) {
+				if (IncludeKeywordsInCompletionList) {
+					wrapper.AddCustom("var");
+					wrapper.AddCustom("dynamic");
+				}
+			} 
+			wrapper.Result.AddRange(factory.CreateCodeTemplateCompletionData());
+			if (node != null && node.Role == Roles.Argument) {
+				var resolved = ResolveExpression(node.Parent);
+				var invokeResult = resolved != null ? resolved.Result as CSharpInvocationResolveResult : null;
+				if (invokeResult != null) {
+					int argNum = 0;
+					foreach (var arg in node.Parent.Children.Where (c => c.Role == Roles.Argument)) {
+						if (arg == node) {
+							break;
+						}
+						argNum++;
+					}
+					var param = argNum < invokeResult.Member.Parameters.Count ? invokeResult.Member.Parameters [argNum] : null;
+					if (param != null && param.Type.Kind == TypeKind.Enum) {
+						AddEnumMembers(wrapper, param.Type, state);
+					}
+				}
+			}
+
+			if (node is Expression) {
+				var root = node;
+				while (root.Parent != null)
+					root = root.Parent;
+				var astResolver = CompletionContextProvider.GetResolver(state, root);
+				foreach (var type in TypeGuessing.GetValidTypes(astResolver, (Expression)node)) {
+					if (type.Kind == TypeKind.Enum) {
+						AddEnumMembers(wrapper, type, state);
+					} else if (type.Kind == TypeKind.Delegate) {
+						AddDelegateHandlers(wrapper, type, false, true);
+						AutoSelect = false;
+						AutoCompleteEmptyMatch = false;
+					}
+				}
+			}
+
+			// Add 'this' keyword for first parameter (extension method case)
+			if (node != null && node.Parent is ParameterDeclaration &&
+				node.Parent.PrevSibling != null && node.Parent.PrevSibling.Role == Roles.LPar && IncludeKeywordsInCompletionList) {
+				wrapper.AddCustom("this");
+			}
+		}
+
+		static bool IsInSwitchContext(AstNode node)
+		{
+			var n = node;
+			while (n != null && !(n is EntityDeclaration)) {
+				if (n is SwitchStatement) {
+					return true;
+				}
+				if (n is BlockStatement) {
+					return false;
+				}
+				n = n.Parent;
+			}
+			return false;
+		}
+
+		static bool ListEquals(List<INamespace> curNamespaces, List<INamespace> oldNamespaces)
+		{
+			if (oldNamespaces == null || curNamespaces.Count != oldNamespaces.Count)
+				return false;
+			for (int i = 0; i < curNamespaces.Count; i++) {
+				if (curNamespaces [i].FullName != oldNamespaces [i].FullName) {
+					return false;
+				}
+			}
+			return true;
+		}
+
+		void AddTypesAndNamespaces(CompletionDataWrapper wrapper, CSharpResolver state, AstNode node, Func<IType, IType> typePred = null, Predicate<IMember> memberPred = null, Action<ICompletionData, IType> callback = null, bool onlyAddConstructors = false)
+		{
+			var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
+
+			if (currentType != null) {
+				for (var ct = ctx.CurrentTypeDefinition; ct != null; ct = ct.DeclaringTypeDefinition) {
+					foreach (var nestedType in ct.GetNestedTypes ()) {
+						if (!lookup.IsAccessible(nestedType.GetDefinition(), true))
+							continue;
+						if (onlyAddConstructors) {
+							if (!nestedType.GetConstructors().Any(c => lookup.IsAccessible(c, true)))
+								continue;
+						}
+
+						if (typePred == null) {
+							if (onlyAddConstructors)
+								wrapper.AddConstructors(nestedType, false, IsAttributeContext(node));
+							else
+								wrapper.AddType(nestedType, false, IsAttributeContext(node));
+							continue;
+						}
+
+						var type = typePred(nestedType);
+						if (type != null) {
+							var a2 = onlyAddConstructors ? wrapper.AddConstructors(type, false, IsAttributeContext(node)) : wrapper.AddType(type, false, IsAttributeContext(node));
+							if (a2 != null && callback != null) {
+								callback(a2, type);
+							}
+						}
+						continue;
+					}
+				}
+
+				if (this.currentMember != null && !(node is AstType)) {
+					var def = ctx.CurrentTypeDefinition;
+					if (def == null && currentType != null)
+						def = Compilation.MainAssembly.GetTypeDefinition(currentType.FullTypeName);
+					if (def != null) {
+						bool isProtectedAllowed = true;
+
+						foreach (var member in def.GetMembers (m => currentMember.IsStatic ? m.IsStatic : true)) {
+							if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") {
+								continue;
+							}
+							if (member.SymbolKind == SymbolKind.Operator) {
+								continue;
+							}
+							if (member.IsExplicitInterfaceImplementation) {
+								continue;
+							}
+							if (!lookup.IsAccessible(member, isProtectedAllowed)) {
+								continue;
+							}
+							if (memberPred == null || memberPred(member)) {
+								wrapper.AddMember(member);
+							}
+						}
+						var declaring = def.DeclaringTypeDefinition;
+						while (declaring != null) {
+							foreach (var member in declaring.GetMembers (m => m.IsStatic)) {
+								if (memberPred == null || memberPred(member)) {
+									wrapper.AddMember(member);
+								}
+							}
+							declaring = declaring.DeclaringTypeDefinition;
+						}
+					}
+				}
+				if (ctx.CurrentTypeDefinition != null) {
+					foreach (var p in ctx.CurrentTypeDefinition.TypeParameters) {
+						wrapper.AddTypeParameter(p);
+					}
+				}
+			}
+			var scope = ctx.CurrentUsingScope;
+
+			for (var n = scope; n != null; n = n.Parent) {
+				foreach (var pair in n.UsingAliases) {
+					wrapper.AddAlias(pair.Key);
+				}
+				foreach (var alias in n.ExternAliases) {
+					wrapper.AddAlias(alias);
+				}
+				foreach (var u in n.Usings) {
+					foreach (var type in u.Types) {
+						if (!lookup.IsAccessible(type, false))
+							continue;
+
+						IType addType = typePred != null ? typePred(type) : type;
+
+						if (onlyAddConstructors && addType != null) {
+							if (!addType.GetConstructors().Any(c => lookup.IsAccessible(c, true)))
+								continue;
+						}
+
+						if (addType != null) {
+							var a = onlyAddConstructors ? wrapper.AddConstructors(addType, false, IsAttributeContext(node)) : wrapper.AddType(addType, false, IsAttributeContext(node));
+							if (a != null && callback != null) {
+								callback(a, type);
+							}
+						}
+					}
+				}
+
+				foreach (var type in n.Namespace.Types) {
+					if (!lookup.IsAccessible(type, false))
+						continue;
+					IType addType = typePred != null ? typePred(type) : type;
+					if (onlyAddConstructors && addType != null) {
+						if (!addType.GetConstructors().Any(c => lookup.IsAccessible(c, true)))
+							continue;
+					}
+
+					if (addType != null) {
+						var a2 = onlyAddConstructors ? wrapper.AddConstructors(addType, false, IsAttributeContext(node)) : wrapper.AddType(addType, false);
+						if (a2 != null && callback != null) {
+							callback(a2, type);
+						}
+					}
+				}
+			}
+
+			for (var n = scope; n != null; n = n.Parent) {
+				foreach (var curNs in n.Namespace.ChildNamespaces) {
+					wrapper.AddNamespace(lookup, curNs);
+				}
+			}
+
+			if (node is AstType && node.Parent is Constraint && IncludeKeywordsInCompletionList) {
+				wrapper.AddCustom("new()");
+			}
+
+			if (AutomaticallyAddImports) {
+				state = GetState();
+				ICompletionData[] importData;
+
+				var namespaces = new List<INamespace>();
+				for (var n = ctx.CurrentUsingScope; n != null; n = n.Parent) {
+					namespaces.Add(n.Namespace);
+					foreach (var u in n.Usings)
+						namespaces.Add(u);
+				}
+
+				if (this.CompletionEngineCache != null && ListEquals(namespaces, CompletionEngineCache.namespaces)) {
+					importData = CompletionEngineCache.importCompletion;
+				} else {
+					// flatten usings
+					var importList = new List<ICompletionData>();
+					var dict = new Dictionary<string, Dictionary<string, ICompletionData>>();
+					foreach (var type in Compilation.GetTopLevelTypeDefinitons ()) {
+						if (!lookup.IsAccessible(type, false))
+							continue;
+						if (namespaces.Any(n => n.FullName == type.Namespace))
+							continue;
+						bool useFullName = false;
+						foreach (var ns in namespaces) {
+							if (ns.GetTypeDefinition(type.Name, type.TypeParameterCount) != null) {
+								useFullName = true;
+								break;
+							}
+						}
+
+						if (onlyAddConstructors) {
+							if (!type.GetConstructors().Any(c => lookup.IsAccessible(c, true)))
+								continue;
+						}
+						var data = factory.CreateImportCompletionData(type, useFullName, onlyAddConstructors);
+						Dictionary<string, ICompletionData> createdDict;
+						if (!dict.TryGetValue(type.Name, out createdDict)) {
+							createdDict = new Dictionary<string, ICompletionData>();
+							dict.Add(type.Name, createdDict);
+						}
+						ICompletionData oldData;
+						if (!createdDict.TryGetValue(type.Namespace, out oldData)) {
+							importList.Add(data);
+							createdDict.Add(type.Namespace, data);
+						} else {
+							oldData.AddOverload(data); 
+						}
+					}
+
+					importData = importList.ToArray();
+					if (CompletionEngineCache != null) {
+						CompletionEngineCache.namespaces = namespaces;
+						CompletionEngineCache.importCompletion = importData;
+					}
+				}
+				foreach (var data in importData) {
+					wrapper.Result.Add(data);
+				}
+
+
+			}
+
+		}
+
+		IEnumerable<ICompletionData> HandleKeywordCompletion(int wordStart, string word)
+		{
+			if (IsInsideCommentStringOrDirective()) {
+				if (IsInPreprocessorDirective()) {
+					if (word == "if" || word == "elif") {
+						if (wordStart > 0 && document.GetCharAt(wordStart - 1) == '#') {
+							return factory.CreatePreProcessorDefinesCompletionData();
+						}
+					}
+				}
+				return null;
+			}
+			switch (word) {
+				case "namespace":
+					return null;
+				case "using":
+					if (currentType != null) {
+						return null;
+					}
+					var wrapper = new CompletionDataWrapper(this);
+					AddTypesAndNamespaces(wrapper, GetState(), null, t => null);
+					return wrapper.Result;
+				case "case":
+					return CreateCaseCompletionData(location);
+					//				case ",":
+					//				case ":":
+					//					if (result.ExpressionContext == ExpressionContext.InheritableType) {
+					//						IType cls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new TextLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
+					//						CompletionDataList completionList = new ProjectDomCompletionDataList ();
+					//						List<string > namespaceList = GetUsedNamespaces ();
+					//						var col = new CSharpTextEditorCompletion.CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, null, location);
+					//						bool isInterface = false;
+					//						HashSet<string > baseTypeNames = new HashSet<string> ();
+					//						if (cls != null) {
+					//							baseTypeNames.Add (cls.Name);
+					//							if (cls.ClassType == ClassType.Struct)
+					//								isInterface = true;
+					//						}
+					//						int tokenIndex = offset;
+					//	
+					//						// Search base types " : [Type1, ... ,TypeN,] <Caret>"
+					//						string token = null;
+					//						do {
+					//							token = GetPreviousToken (ref tokenIndex, false);
+					//							if (string.IsNullOrEmpty (token))
+					//								break;
+					//							token = token.Trim ();
+					//							if (Char.IsLetterOrDigit (token [0]) || token [0] == '_') {
+					//								IType baseType = dom.SearchType (Document.CompilationUnit, cls, result.Region.Start, token);
+					//								if (baseType != null) {
+					//									if (baseType.ClassType != ClassType.Interface)
+					//										isInterface = true;
+					//									baseTypeNames.Add (baseType.Name);
+					//								}
+					//							}
+					//						} while (token != ":");
+					//						foreach (object o in dom.GetNamespaceContents (namespaceList, true, true)) {
+					//							IType type = o as IType;
+					//							if (type != null && (type.IsStatic || type.IsSealed || baseTypeNames.Contains (type.Name) || isInterface && type.ClassType != ClassType.Interface)) {
+					//								continue;
+					//							}
+					//							if (o is Namespace && !namespaceList.Any (ns => ns.StartsWith (((Namespace)o).FullName)))
+					//								continue;
+					//							col.Add (o);
+					//						}
+					//						// Add inner classes
+					//						Stack<IType > innerStack = new Stack<IType> ();
+					//						innerStack.Push (cls);
+					//						while (innerStack.Count > 0) {
+					//							IType curType = innerStack.Pop ();
+					//							if (curType == null)
+					//								continue;
+					//							foreach (IType innerType in curType.InnerTypes) {
+					//								if (innerType != cls)
+					//									// don't add the calling class as possible base type
+					//									col.Add (innerType);
+					//							}
+					//							if (curType.DeclaringType != null)
+					//								innerStack.Push (curType.DeclaringType);
+					//						}
+					//						return completionList;
+					//					}
+					//					break;
+				case "is":
+				case "as":
+					if (currentType == null) {
+						return null;
+					}
+					IType isAsType = null;
+					var isAsExpression = GetExpressionAt(wordStart);
+					if (isAsExpression != null) {
+						var parent = isAsExpression.Node.Parent;
+						if (parent is VariableInitializer) {
+							parent = parent.Parent;
+						}
+						var varDecl = parent as VariableDeclarationStatement;
+						if (varDecl != null) {
+							ExpressionResolveResult resolved;
+							if (varDecl.Type.IsVar()) {
+								resolved = null;
+							} else {
+								resolved = ResolveExpression(parent);
+							}
+							if (resolved != null) {
+								isAsType = resolved.Result.Type;
+							}
+						}
+					}
+					var isAsWrapper = new CompletionDataWrapper(this);
+					var def = isAsType != null ? isAsType.GetDefinition() : null;
+					AddTypesAndNamespaces(
+						isAsWrapper,
+						GetState(),
+						null,
+						t => t.GetDefinition() == null || def == null || t.GetDefinition().IsDerivedFrom(def) ? t : null,
+						m => false);
+					AddKeywords(isAsWrapper, primitiveTypesKeywords);
+					return isAsWrapper.Result;
+					//					{
+					//						CompletionDataList completionList = new ProjectDomCompletionDataList ();
+					//						ExpressionResult expressionResult = FindExpression (dom, completionContext, wordStart - document.Caret.Offset);
+					//						NRefactoryResolver resolver = CreateResolver ();
+					//						ResolveResult resolveResult = resolver.Resolve (expressionResult, new TextLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
+					//						if (resolveResult != null && resolveResult.ResolvedType != null) {
+					//							CompletionDataCollector col = new CompletionDataCollector (this, dom, completionList, Document.CompilationUnit, resolver.CallingType, location);
+					//							IType foundType = null;
+					//							if (word == "as") {
+					//								ExpressionContext exactContext = new NewCSharpExpressionFinder (dom).FindExactContextForAsCompletion (document, Document.CompilationUnit, Document.FileName, resolver.CallingType);
+					//								if (exactContext is ExpressionContext.TypeExpressionContext) {
+					//									foundType = resolver.SearchType (((ExpressionContext.TypeExpressionContext)exactContext).Type);
+					//									AddAsCompletionData (col, foundType);
+					//								}
+					//							}
+					//						
+					//							if (foundType == null)
+					//								foundType = resolver.SearchType (resolveResult.ResolvedType);
+					//						
+					//							if (foundType != null) {
+					//								if (foundType.ClassType == ClassType.Interface)
+					//									foundType = resolver.SearchType (DomReturnType.Object);
+					//							
+					//								foreach (IType type in dom.GetSubclasses (foundType)) {
+					//									if (type.IsSpecialName || type.Name.StartsWith ("<"))
+					//										continue;
+					//									AddAsCompletionData (col, type);
+					//								}
+					//							}
+					//							List<string > namespaceList = GetUsedNamespaces ();
+					//							foreach (object o in dom.GetNamespaceContents (namespaceList, true, true)) {
+					//								if (o is IType) {
+					//									IType type = (IType)o;
+					//									if (type.ClassType != ClassType.Interface || type.IsSpecialName || type.Name.StartsWith ("<"))
+					//										continue;
+					//	//								if (foundType != null && !dom.GetInheritanceTree (foundType).Any (x => x.FullName == type.FullName))
+					//	//									continue;
+					//									AddAsCompletionData (col, type);
+					//									continue;
+					//								}
+					//								if (o is Namespace)
+					//									continue;
+					//								col.Add (o);
+					//							}
+					//							return completionList;
+					//						}
+					//						result.ExpressionContext = ExpressionContext.TypeName;
+					//						return CreateCtrlSpaceCompletionData (completionContext, result);
+					//					}
+				case "override":
+					// Look for modifiers, in order to find the beginning of the declaration
+					int firstMod = wordStart;
+					int i = wordStart;
+					for (int n = 0; n < 3; n++) {
+						string mod = GetPreviousToken(ref i, true);
+						if (mod == "public" || mod == "protected" || mod == "private" || mod == "internal" || mod == "sealed") {
+							firstMod = i;
+						} else if (mod == "static") {
+							// static methods are not overridable
+							return null;
+						} else {
+							break;
+						}
+					}
+					if (!IsLineEmptyUpToEol()) {
+						return null;
+					}
+					if (currentType != null && (currentType.Kind == TypeKind.Class || currentType.Kind == TypeKind.Struct)) {
+						string modifiers = document.GetText(firstMod, wordStart - firstMod);
+						return GetOverrideCompletionData(currentType, modifiers);
+					}
+					return null;
+				case "partial":
+					// Look for modifiers, in order to find the beginning of the declaration
+					firstMod = wordStart;
+					i = wordStart;
+					for (int n = 0; n < 3; n++) {
+						string mod = GetPreviousToken(ref i, true);
+						if (mod == "public" || mod == "protected" || mod == "private" || mod == "internal" || mod == "sealed") {
+							firstMod = i;
+						} else if (mod == "static") {
+							// static methods are not overridable
+							return null;
+						} else {
+							break;
+						}
+					}
+					if (!IsLineEmptyUpToEol()) {
+						return null;
+					}
+					var state = GetState();
+
+					if (state.CurrentTypeDefinition != null && (state.CurrentTypeDefinition.Kind == TypeKind.Class || state.CurrentTypeDefinition.Kind == TypeKind.Struct)) {
+						string modifiers = document.GetText(firstMod, wordStart - firstMod);
+						return GetPartialCompletionData(state.CurrentTypeDefinition, modifiers);
+					}
+					return null;
+
+				case "public":
+				case "protected":
+				case "private":
+				case "internal":
+				case "sealed":
+				case "static":
+					var accessorContext = HandleAccessorContext();
+					if (accessorContext != null) {
+						return accessorContext;
+					}
+					return null;
+				case "new":
+					int j = offset - 4;
+					//				string token = GetPreviousToken (ref j, true);
+
+					IType hintType = null;
+					var expressionOrVariableDeclaration = GetNewExpressionAt(j);
+					if (expressionOrVariableDeclaration == null)
+						return null;
+					var astResolver = CompletionContextProvider.GetResolver(GetState(), expressionOrVariableDeclaration.Node.Ancestors.FirstOrDefault(n => n is EntityDeclaration || n is SyntaxTree));
+					hintType = TypeGuessing.GetValidTypes(
+						astResolver,
+						expressionOrVariableDeclaration.Node
+					).FirstOrDefault();
+
+					return CreateConstructorCompletionData(hintType);
+				case "yield":
+					var yieldDataList = new CompletionDataWrapper(this);
+					DefaultCompletionString = "return";
+					if (IncludeKeywordsInCompletionList) {
+						yieldDataList.AddCustom("break");
+						yieldDataList.AddCustom("return");
+					}
+					return yieldDataList.Result;
+				case "in":
+					var inList = new CompletionDataWrapper(this);
+
+					var expr = GetExpressionAtCursor();
+					if (expr == null)
+						return null;
+					var rr = ResolveExpression(expr);
+
+					AddContextCompletion(
+						inList,
+						rr != null ? rr.Resolver : GetState(),
+						expr.Node
+					);
+					return inList.Result;
+			}
+			return null;
+		}
+
+		bool IsLineEmptyUpToEol()
+		{
+			var line = document.GetLineByNumber(location.Line);
+			for (int j = offset; j < line.EndOffset; j++) {
+				char ch = document.GetCharAt(j);
+				if (!char.IsWhiteSpace(ch)) {
+					return false;
+				}
+			}
+			return true;
+		}
+
+		string GetLineIndent(int lineNr)
+		{
+			var line = document.GetLineByNumber(lineNr);
+			for (int j = line.Offset; j < line.EndOffset; j++) {
+				char ch = document.GetCharAt(j);
+				if (!char.IsWhiteSpace(ch)) {
+					return document.GetText(line.Offset, j - line.Offset);
+				}
+			}
+			return "";
+		}
+		//		static CSharpAmbience amb = new CSharpAmbience();
+		class Category : CompletionCategory
+		{
+			public Category(string displayText, string icon) : base(displayText, icon)
+			{
+			}
+
+			public override int CompareTo(CompletionCategory other)
+			{
+				return 0;
+			}
+		}
+
+		IEnumerable<ICompletionData> CreateConstructorCompletionData(IType hintType)
+		{
+			var wrapper = new CompletionDataWrapper(this);
+			var state = GetState();
+			Func<IType, IType> pred = null;
+			Action<ICompletionData, IType> typeCallback = null;
+			var inferredTypesCategory = new Category("Inferred Types", null);
+			var derivedTypesCategory = new Category("Derived Types", null);
+
+			if (hintType != null && (hintType.Kind != TypeKind.TypeParameter || IsTypeParameterInScope(hintType))) {
+				if (hintType.Kind != TypeKind.Unknown) {
+					var lookup = new MemberLookup(
+						ctx.CurrentTypeDefinition,
+						Compilation.MainAssembly
+					);
+					typeCallback = (data, t) => {
+						//check if type is in inheritance tree.
+						if (hintType.GetDefinition() != null &&
+							t.GetDefinition() != null &&
+							t.GetDefinition().IsDerivedFrom(hintType.GetDefinition())) {
+							data.CompletionCategory = derivedTypesCategory;
+						}
+					};
+					pred = t => {
+						if (t.Kind == TypeKind.Interface && hintType.Kind != TypeKind.Array) {
+							return null;
+						}
+						// check for valid constructors
+						if (t.GetConstructors().Any()) {
+							bool isProtectedAllowed = currentType != null ? 
+								currentType.Resolve(ctx).GetDefinition().IsDerivedFrom(t.GetDefinition()) : false;
+							if (!t.GetConstructors().Any(m => lookup.IsAccessible(m, isProtectedAllowed))) {
+								return null;
+							}
+						}
+
+						// check derived types
+						var typeDef = t.GetDefinition();
+						var hintDef = hintType.GetDefinition();
+						if (typeDef != null && hintDef != null && typeDef.IsDerivedFrom(hintDef)) {
+							var newType = wrapper.AddType(t, true);
+							if (newType != null) {
+								newType.CompletionCategory = inferredTypesCategory;
+							}
+						}
+
+						// check type inference
+						var typeInference = new TypeInference(Compilation);
+						typeInference.Algorithm = TypeInferenceAlgorithm.ImprovedReturnAllResults;
+
+						var inferedType = typeInference.FindTypeInBounds(new [] { t }, new [] { hintType });
+						if (inferedType != SpecialType.UnknownType) {
+							var newType = wrapper.AddType(inferedType, true);
+							if (newType != null) {
+								newType.CompletionCategory = inferredTypesCategory;
+							}
+							return null;
+						}
+						return t;
+					};
+					if (!(hintType.Kind == TypeKind.Interface && hintType.Kind != TypeKind.Array)) {
+						var hint = wrapper.AddType(hintType, true);
+						if (hint != null) {
+							DefaultCompletionString = hint.DisplayText;
+							hint.CompletionCategory = derivedTypesCategory;
+						}
+					}
+					if (hintType is ParameterizedType && hintType.TypeParameterCount == 1 && hintType.FullName == "System.Collections.Generic.IEnumerable") {
+						var arg = ((ParameterizedType)hintType).TypeArguments.FirstOrDefault();
+						if (arg.Kind != TypeKind.TypeParameter) {
+							var array = new ArrayType(ctx.Compilation, arg, 1);
+							wrapper.AddType(array, true);
+						}
+					}
+				} else {
+					var hint = wrapper.AddType(hintType, true);
+					if (hint != null) {
+						DefaultCompletionString = hint.DisplayText;
+						hint.CompletionCategory = derivedTypesCategory;
+					}
+				}
+			} 
+			AddTypesAndNamespaces(wrapper, state, null, pred, m => false, typeCallback, true);
+			if (hintType == null || hintType == SpecialType.UnknownType) {
+				AddKeywords(wrapper, primitiveTypesKeywords.Where(k => k != "void"));
+			}
+
+			CloseOnSquareBrackets = true;
+			AutoCompleteEmptyMatch = true;
+			AutoCompleteEmptyMatchOnCurlyBracket = false;
+			return wrapper.Result;
+		}
+
+		bool IsTypeParameterInScope(IType hintType)
+		{
+			var tp = hintType as ITypeParameter;
+			var ownerName = tp.Owner.ReflectionName;
+			if (currentMember != null && ownerName == currentMember.ReflectionName)
+				return true;
+			var ot = currentType;
+			while (ot != null) {
+				if (ownerName == ot.ReflectionName)
+					return true;
+				ot = ot.DeclaringTypeDefinition;
+			}
+			return false;
+		}
+
+		IEnumerable<ICompletionData> GetOverrideCompletionData(IUnresolvedTypeDefinition type, string modifiers)
+		{
+			var wrapper = new CompletionDataWrapper(this);
+			var alreadyInserted = new List<IMember>();
+			//bool addedVirtuals = false;
+
+			int declarationBegin = offset;
+			int j = declarationBegin;
+			for (int i = 0; i < 3; i++) {
+				switch (GetPreviousToken(ref j, true)) {
+					case "public":
+					case "protected":
+					case "private":
+					case "internal":
+					case "sealed":
+					case "override":
+					case "partial":
+					case "async":
+						declarationBegin = j;
+						break;
+					case "static":
+						return null; // don't add override completion for static members
+				}
+			}
+			AddVirtuals(
+				alreadyInserted,
+				wrapper,
+				modifiers,
+				type.Resolve(ctx),
+				declarationBegin
+			);
+			return wrapper.Result;
+		}
+
+		IEnumerable<ICompletionData> GetPartialCompletionData(ITypeDefinition type, string modifiers)
+		{
+			var wrapper = new CompletionDataWrapper(this);
+			int declarationBegin = offset;
+			int j = declarationBegin;
+			for (int i = 0; i < 3; i++) {
+				switch (GetPreviousToken(ref j, true)) {
+					case "public":
+					case "protected":
+					case "private":
+					case "internal":
+					case "sealed":
+					case "override":
+					case "partial":
+					case "async":
+						declarationBegin = j;
+						break;
+					case "static":
+						return null; // don't add override completion for static members
+				}
+			}
+
+			var methods = new List<IUnresolvedMethod>();
+
+			foreach (var part in type.Parts) {
+				foreach (var method in part.Methods) {
+					if (method.BodyRegion.IsEmpty) {
+						if (GetImplementation(type, method) != null) {
+							continue;
+						}
+						methods.Add(method);
+					}
+				}	
+			}
+
+			foreach (var method in methods) {
+				wrapper.Add(factory.CreateNewPartialCompletionData(
+					declarationBegin,
+					method.DeclaringTypeDefinition,
+					method
+				)
+				);
+			} 
+
+			return wrapper.Result;
+		}
+
+		IMethod GetImplementation(ITypeDefinition type, IUnresolvedMethod method)
+		{
+			foreach (var cur in type.Methods) {
+				if (cur.Name == method.Name && cur.Parameters.Count == method.Parameters.Count && !cur.BodyRegion.IsEmpty) {
+					bool equal = true;
+					/*					for (int i = 0; i < cur.Parameters.Count; i++) {
+						if (!cur.Parameters [i].Type.Equals (method.Parameters [i].Type)) {
+							equal = false;
+							break;
+						}
+					}*/
+					if (equal) {
+						return cur;
+					}
+				}
+			}
+			return null;
+		}
+
+		protected virtual void AddVirtuals(List<IMember> alreadyInserted, CompletionDataWrapper col, string modifiers, IType curType, int declarationBegin)
+		{
+			if (curType == null) {
+				return;
+			}
+			foreach (var m in curType.GetMembers ().Reverse ()) {
+				if (curType.Kind != TypeKind.Interface && !m.IsOverridable) {
+					continue;
+				}
+				// filter out the "Finalize" methods, because finalizers should be done with destructors.
+				if (m is IMethod && m.Name == "Finalize") {
+					continue;
+				}
+
+				var data = factory.CreateNewOverrideCompletionData(
+					declarationBegin,
+					currentType,
+					m
+				);
+				// check if the member is already implemented
+				bool foundMember = curType.GetMembers().Any(cm => SignatureComparer.Ordinal.Equals(
+					cm,
+					m
+				) && cm.DeclaringTypeDefinition == curType.GetDefinition()
+				);
+				if (foundMember) {
+					continue;
+				}
+				if (alreadyInserted.Any(cm => SignatureComparer.Ordinal.Equals(cm, m)))
+					continue;
+				alreadyInserted.Add(m);
+				data.CompletionCategory = col.GetCompletionCategory(m.DeclaringTypeDefinition);
+				col.Add(data);
+			}
+		}
+
+		void AddKeywords(CompletionDataWrapper wrapper, IEnumerable<string> keywords)
+		{
+			if (!IncludeKeywordsInCompletionList)
+				return;
+			foreach (string keyword in keywords) {
+				if (wrapper.Result.Any(data => data.DisplayText == keyword))
+					continue;
+				wrapper.AddCustom(keyword);
+			}
+		}
+
+		public string GuessEventHandlerMethodName(int tokenIndex, string surroundingTypeName)
+		{
+			var names = new List<string>();
+			
+			string eventName = GetPreviousToken(ref tokenIndex, false);
+			string result = GetPreviousToken(ref tokenIndex, false);
+			if (result != ".") {
+				if (surroundingTypeName == null) {
+					eventName = "Handle" + eventName;
+				} else {
+					names.Add(surroundingTypeName);
+				}
+			}
+			while (result == ".") {
+				result = GetPreviousToken(ref tokenIndex, false);
+				if (result == "this") {
+					if (names.Count == 0) {
+						if (surroundingTypeName == null) {
+							eventName = "Handle" + eventName;
+						} else {
+							names.Add(surroundingTypeName);
+						}
+					}
+				} else if (result != null) {
+					string trimmedName = result.Trim();
+					if (trimmedName.Length == 0) {
+						break;
+					}
+					names.Insert(0, trimmedName);
+				}
+				result = GetPreviousToken(ref tokenIndex, false);
+			}
+			if (!string.IsNullOrEmpty(eventName)) {
+				names.Add(eventName);
+			}
+			result = String.Join("_", names.ToArray());
+			foreach (char ch in result) {
+				if (!char.IsLetterOrDigit(ch) && ch != '_') {
+					result = "";
+					break;
+				}
+			}
+			return result;
+		}
+
+		bool MatchDelegate(IType delegateType, IMethod method)
+		{
+			if (method.SymbolKind != SymbolKind.Method)
+				return false;
+			var delegateMethod = delegateType.GetDelegateInvokeMethod();
+			if (delegateMethod == null || delegateMethod.Parameters.Count != method.Parameters.Count) {
+				return false;
+			}
+
+			for (int i = 0; i < delegateMethod.Parameters.Count; i++) {
+				if (!delegateMethod.Parameters [i].Type.Equals(method.Parameters [i].Type)) {
+					return false;
+				}
+			}
+			return true;
+		}
+
+		string AddDelegateHandlers(CompletionDataWrapper completionList, IType delegateType, bool addSemicolon = true, bool addDefault = true, string optDelegateName = null)
+		{
+			IMethod delegateMethod = delegateType.GetDelegateInvokeMethod();
+			PossibleDelegates.Add(delegateMethod);
+			var thisLineIndent = GetLineIndent(location.Line);
+			string delegateEndString = EolMarker + thisLineIndent + "}" + (addSemicolon ? ";" : "");
+			//bool containsDelegateData = completionList.Result.Any(d => d.DisplayText.StartsWith("delegate("));
+			if (addDefault && !completionList.AnonymousDelegateAdded) {
+				completionList.AnonymousDelegateAdded = true;
+				var oldDelegate = completionList.Result.FirstOrDefault(cd => cd.DisplayText == "delegate");
+				if (oldDelegate != null)
+					completionList.Result.Remove(oldDelegate);
+				completionList.AddCustom(
+					"delegate",
+					"Creates anonymous delegate.",
+					"delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
+				).DisplayFlags |= DisplayFlags.MarkedBold;
+				if (LanguageVersion.Major >= 5) {
+					completionList.AddCustom(
+						"async delegate",
+						"Creates anonymous async delegate.",
+						"async delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
+					).DisplayFlags |= DisplayFlags.MarkedBold;
+				}
+			}
+			var sb = new StringBuilder("(");
+			var sbWithoutTypes = new StringBuilder("(");
+			var state = GetState();
+			var builder = new TypeSystemAstBuilder(state);
+
+			for (int k = 0; k < delegateMethod.Parameters.Count; k++) {
+
+				if (k > 0) {
+					sb.Append(", ");
+					sbWithoutTypes.Append(", ");
+				}
+				var convertedParameter = builder.ConvertParameter(delegateMethod.Parameters [k]);
+				if (convertedParameter.ParameterModifier == ParameterModifier.Params)
+					convertedParameter.ParameterModifier = ParameterModifier.None;
+				sb.Append(convertedParameter.ToString(FormattingPolicy));
+				sbWithoutTypes.Append(delegateMethod.Parameters [k].Name);
+			}
+
+			sb.Append(")");
+			sbWithoutTypes.Append(")");
+			var signature = sb.ToString();
+			if (!completionList.HasAnonymousDelegateAdded(signature)) {
+				completionList.AddAnonymousDelegateAdded(signature);
+
+				completionList.AddCustom(
+					"delegate" + signature,
+					"Creates anonymous delegate.",
+					"delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
+				).DisplayFlags |= DisplayFlags.MarkedBold;
+				if (LanguageVersion.Major >= 5) {
+					completionList.AddCustom(
+						"async delegate" + signature,
+						"Creates anonymous async delegate.",
+						"async delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
+					).DisplayFlags |= DisplayFlags.MarkedBold;
+				}
+				if (!completionList.Result.Any(data => data.DisplayText == sb.ToString())) {
+					completionList.AddCustom(
+						signature,
+						"Creates typed lambda expression.",
+						signature + " => |" + (addSemicolon ? ";" : "")
+					).DisplayFlags |= DisplayFlags.MarkedBold;
+					if (LanguageVersion.Major >= 5) {
+						completionList.AddCustom(
+							"async " + signature,
+							"Creates typed async lambda expression.",
+							"async " + signature + " => |" + (addSemicolon ? ";" : "")
+						).DisplayFlags |= DisplayFlags.MarkedBold;
+					}
+
+					if (!delegateMethod.Parameters.Any(p => p.IsOut || p.IsRef) && !completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
+						completionList.AddCustom(
+							sbWithoutTypes.ToString(),
+							"Creates lambda expression.",
+							sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
+						).DisplayFlags |= DisplayFlags.MarkedBold;
+						if (LanguageVersion.Major >= 5) {
+							completionList.AddCustom(
+								"async " + sbWithoutTypes,
+								"Creates async lambda expression.",
+								"async " + sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
+							).DisplayFlags |= DisplayFlags.MarkedBold;
+						}
+					}
+				}
+
+			}
+
+			string varName = optDelegateName ?? "Handle" + delegateType.Name;
+
+			var ecd = factory.CreateEventCreationCompletionData(varName, delegateType, null, signature, currentMember, currentType);
+			ecd.DisplayFlags |= DisplayFlags.MarkedBold;
+			completionList.Add(ecd);
+
+			return sb.ToString();
+		}
+
+		bool IsAccessibleFrom(IEntity member, ITypeDefinition calledType, IMember currentMember, bool includeProtected)
+		{
+			if (currentMember == null) {
+				return member.IsStatic || member.IsPublic;
+			}
+			//			if (currentMember is MonoDevelop.Projects.Dom.BaseResolveResult.BaseMemberDecorator) 
+			//				return member.IsPublic | member.IsProtected;
+			//		if (member.IsStatic && !IsStatic)
+			//			return false;
+			if (member.IsPublic || calledType != null && calledType.Kind == TypeKind.Interface && !member.IsProtected) {
+				return true;
+			}
+			if (member.DeclaringTypeDefinition != null) {
+				if (member.DeclaringTypeDefinition.Kind == TypeKind.Interface) { 
+					return IsAccessibleFrom(
+						member.DeclaringTypeDefinition,
+						calledType,
+						currentMember,
+						includeProtected
+					);
+				}
+
+				if (member.IsProtected && !(member.DeclaringTypeDefinition.IsProtectedOrInternal && !includeProtected)) {
+					return includeProtected;
+				}
+			}
+			if (member.IsInternal || member.IsProtectedAndInternal || member.IsProtectedOrInternal) {
+				//var type1 = member is ITypeDefinition ? (ITypeDefinition)member : member.DeclaringTypeDefinition;
+				//var type2 = currentMember is ITypeDefinition ? (ITypeDefinition)currentMember : currentMember.DeclaringTypeDefinition;
+				bool result = true;
+				// easy case, projects are the same
+				/*				//				if (type1.ProjectContent == type2.ProjectContent) {
+				//					result = true; 
+				//				} else 
+				if (type1.ProjectContent != null) {
+					// maybe type2 hasn't project dom set (may occur in some cases), check if the file is in the project
+					//TODO !!
+					//					result = type1.ProjectContent.Annotation<MonoDevelop.Projects.Project> ().GetProjectFile (type2.Region.FileName) != null;
+					result = false;
+				} else if (type2.ProjectContent != null) {
+					//TODO!!
+					//					result = type2.ProjectContent.Annotation<MonoDevelop.Projects.Project> ().GetProjectFile (type1.Region.FileName) != null;
+					result = false;
+				} else {
+					// should never happen !
+					result = true;
+				}*/
+				return member.IsProtectedAndInternal ? includeProtected && result : result;
+			}
+
+			if (!(currentMember is IType) && (currentMember.DeclaringTypeDefinition == null || member.DeclaringTypeDefinition == null)) {
+				return false;
+			}
+
+			// inner class 
+			var declaringType = currentMember.DeclaringTypeDefinition;
+			while (declaringType != null) {
+				if (declaringType.ReflectionName == currentMember.DeclaringType.ReflectionName) {
+					return true;
+				}
+				declaringType = declaringType.DeclaringTypeDefinition;
+			}
+
+
+			return currentMember.DeclaringTypeDefinition != null && member.DeclaringTypeDefinition.FullName == currentMember.DeclaringTypeDefinition.FullName;
+		}
+
+		static bool IsAttributeContext(AstNode node)
+		{
+			AstNode n = node;
+			while (n is AstType) {
+				n = n.Parent;
+			}
+			return n is Attribute;
+		}
+
+		IEnumerable<ICompletionData> CreateTypeAndNamespaceCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state)
+		{
+			if (resolveResult == null || resolveResult.IsError) {
+				return null;
+			}
+			var exprParent = resolvedNode.GetParent<Expression>();
+			var unit = exprParent != null ? exprParent.GetParent<SyntaxTree>() : null;
+
+			var astResolver = unit != null ? CompletionContextProvider.GetResolver(state, unit) : null;
+			IType hintType = exprParent != null && astResolver != null ? 
+				TypeGuessing.GetValidTypes(astResolver, exprParent).FirstOrDefault() :
+				null;
+			var result = new CompletionDataWrapper(this);
+			var lookup = new MemberLookup(
+				ctx.CurrentTypeDefinition,
+				Compilation.MainAssembly
+			);
+			if (resolveResult is NamespaceResolveResult) {
+				var nr = (NamespaceResolveResult)resolveResult;
+				if (!(resolvedNode.Parent is UsingDeclaration || resolvedNode.Parent != null && resolvedNode.Parent.Parent is UsingDeclaration)) {
+					foreach (var cl in nr.Namespace.Types) {
+						if (hintType != null && hintType.Kind != TypeKind.Array && cl.Kind == TypeKind.Interface) {
+							continue;
+						}
+						if (!lookup.IsAccessible(cl, false))
+							continue;
+						result.AddType(cl, false, IsAttributeContext(resolvedNode));
+					}
+				}
+				foreach (var ns in nr.Namespace.ChildNamespaces) {
+					result.AddNamespace(lookup, ns);
+				}
+			} else if (resolveResult is TypeResolveResult) {
+				var type = resolveResult.Type;
+				foreach (var nested in type.GetNestedTypes ()) {
+					if (hintType != null && hintType.Kind != TypeKind.Array && nested.Kind == TypeKind.Interface) {
+						continue;
+					}
+					var def = nested.GetDefinition();
+					if (def != null && !lookup.IsAccessible(def, false))
+						continue;
+					result.AddType(nested, false);
+				}
+			}
+			return result.Result;
+		}
+
+		IEnumerable<ICompletionData> CreateTypeList()
+		{
+			foreach (var cl in Compilation.RootNamespace.Types) {
+				yield return factory.CreateTypeCompletionData(cl, false, false, false);
+			}
+
+			foreach (var ns in Compilation.RootNamespace.ChildNamespaces) {
+				yield return factory.CreateNamespaceCompletionData(ns);
+			}
+		}
+
+		void CreateParameterForInvocation(CompletionDataWrapper result, IMethod method, CSharpResolver state, int parameter, HashSet<string> addedEnums, HashSet<string> addedDelegates)
+		{
+			if (method.Parameters.Count <= parameter) {
+				return;
+			}
+			var resolvedType = method.Parameters [parameter].Type;
+			if (resolvedType.Kind == TypeKind.Enum) {
+				if (addedEnums.Contains(resolvedType.ReflectionName)) {
+					return;
+				}
+				addedEnums.Add(resolvedType.ReflectionName);
+				AddEnumMembers(result, resolvedType, state);
+				return;
+			}
+
+			if (resolvedType.Kind == TypeKind.Delegate) {
+				if (addedDelegates.Contains(resolvedType.ReflectionName))
+					return;
+				AddDelegateHandlers(result, resolvedType, false, true, "Handle" + method.Parameters [parameter].Type.Name + method.Parameters [parameter].Name);
+			}
+		}
+
+		IEnumerable<ICompletionData> CreateParameterCompletion(MethodGroupResolveResult resolveResult, CSharpResolver state, AstNode invocation, SyntaxTree unit, int parameter, bool controlSpace)
+		{
+			var result = new CompletionDataWrapper(this);
+			var addedEnums = new HashSet<string>();
+			var addedDelegates = new HashSet<string>();
+
+			foreach (var method in resolveResult.Methods) {
+				CreateParameterForInvocation(result, method, state, parameter, addedEnums, addedDelegates);
+			}
+			foreach (var methods in resolveResult.GetEligibleExtensionMethods (true)) {
+				foreach (var method in methods) {
+					if (resolveResult.Methods.Contains(method))
+						continue;
+					CreateParameterForInvocation(result, new ReducedExtensionMethod(method), state, parameter, addedEnums, addedDelegates);
+				}
+			}
+
+			foreach (var method in resolveResult.Methods) {
+				if (parameter < method.Parameters.Count && method.Parameters [parameter].Type.Kind == TypeKind.Delegate) {
+					AutoSelect = false;
+					AutoCompleteEmptyMatch = false;
+				}
+				foreach (var p in method.Parameters) {
+					result.AddNamedParameterVariable(p);
+				}
+			}
+
+			if (!controlSpace) {
+				if (addedEnums.Count + addedDelegates.Count == 0) {
+					return Enumerable.Empty<ICompletionData>();
+				}
+				AutoCompleteEmptyMatch = false;
+				AutoSelect = false;
+			}
+			AddContextCompletion(result, state, invocation);
+
+			//			resolver.AddAccessibleCodeCompletionData (ExpressionContext.MethodBody, cdc);
+			//			if (addedDelegates.Count > 0) {
+			//				foreach (var data in result.Result) {
+			//					if (data is MemberCompletionData) 
+			//						((MemberCompletionData)data).IsDelegateExpected = true;
+			//				}
+			//			}
+			return result.Result;
+		}
+
+		void AddEnumMembers(CompletionDataWrapper completionList, IType resolvedType, CSharpResolver state)
+		{
+			if (resolvedType.Kind != TypeKind.Enum) {
+				return;
+			}
+			var type = completionList.AddEnumMembers(resolvedType, state);
+			if (type != null)
+				DefaultCompletionString = type.DisplayText;
+		}
+
+		IEnumerable<ICompletionData> CreateCompletionData(TextLocation location, ResolveResult resolveResult, AstNode resolvedNode, CSharpResolver state, Func<IType, IType> typePred = null)
+		{
+			if (resolveResult == null /*			|| resolveResult.IsError*/) {
+				return null;
+			}
+
+			var lookup = new MemberLookup(
+				ctx.CurrentTypeDefinition,
+				Compilation.MainAssembly
+			);
+
+			if (resolveResult is NamespaceResolveResult) {
+				var nr = (NamespaceResolveResult)resolveResult;
+				var namespaceContents = new CompletionDataWrapper(this);
+
+				foreach (var cl in nr.Namespace.Types) {
+					if (!lookup.IsAccessible(cl, false))
+						continue;
+					IType addType = typePred != null ? typePred(cl) : cl;
+					if (addType != null)
+						namespaceContents.AddType(addType, false);
+				}
+
+				foreach (var ns in nr.Namespace.ChildNamespaces) {
+					namespaceContents.AddNamespace(lookup, ns);
+				}
+				return namespaceContents.Result;
+			}
+			IType type = resolveResult.Type;
+
+			if (type.Namespace == "System" && type.Name == "Void")
+				return null;
+
+			if (resolvedNode.Parent is PointerReferenceExpression && (type is PointerType)) {
+				resolveResult = new OperatorResolveResult(((PointerType)type).ElementType, System.Linq.Expressions.ExpressionType.Extension, resolveResult);
+			}
+
+			//var typeDef = resolveResult.Type.GetDefinition();
+			var result = new CompletionDataWrapper(this);
+			bool includeStaticMembers = false;
+
+			if (resolveResult is LocalResolveResult) {
+				if (resolvedNode is IdentifierExpression) {
+					var mrr = (LocalResolveResult)resolveResult;
+					includeStaticMembers = mrr.Variable.Name == mrr.Type.Name;
+				}
+			}
+			if (resolveResult is TypeResolveResult && type.Kind == TypeKind.Enum) {
+				foreach (var field in type.GetFields ()) {
+					if (!lookup.IsAccessible(field, false))
+						continue;
+					result.AddMember(field);
+				}
+				return result.Result;
+			}
+
+			bool isProtectedAllowed = lookup.IsProtectedAccessAllowed(resolveResult);
+			bool skipNonStaticMembers = (resolveResult is TypeResolveResult);
+
+			if (resolveResult is MemberResolveResult && resolvedNode is IdentifierExpression) {
+				var mrr = (MemberResolveResult)resolveResult;
+				includeStaticMembers = mrr.Member.Name == mrr.Type.Name;
+
+				TypeResolveResult trr;
+				if (state.IsVariableReferenceWithSameType(
+					resolveResult,
+					((IdentifierExpression)resolvedNode).Identifier,
+					out trr
+				)) {
+					if (currentMember != null && mrr.Member.IsStatic ^ currentMember.IsStatic) {
+						skipNonStaticMembers = true;
+
+						if (trr.Type.Kind == TypeKind.Enum) {
+							foreach (var field in trr.Type.GetFields ()) {
+								if (lookup.IsAccessible(field, false))
+									result.AddMember(field);
+							}
+							return result.Result;
+						}
+					}
+				}
+				// ADD Aliases
+				var scope = ctx.CurrentUsingScope;
+
+				for (var n = scope; n != null; n = n.Parent) {
+					foreach (var pair in n.UsingAliases) {
+						if (pair.Key == mrr.Member.Name) {
+							foreach (var r in CreateCompletionData (location, pair.Value, resolvedNode, state)) {
+								if (r is IEntityCompletionData && ((IEntityCompletionData)r).Entity is IMember) {
+									result.AddMember((IMember)((IEntityCompletionData)r).Entity);
+								} else {
+									result.Add(r);
+								}
+							}
+						}
+					}
+				}				
+
+
+			}
+			if (resolveResult is TypeResolveResult && (resolvedNode is IdentifierExpression || resolvedNode is MemberReferenceExpression)) {
+				includeStaticMembers = true;
+			}
+
+			//			Console.WriteLine ("type:" + type +"/"+type.GetType ());
+			//			Console.WriteLine ("current:" + ctx.CurrentTypeDefinition);
+			//			Console.WriteLine ("IS PROT ALLOWED:" + isProtectedAllowed + " static: "+ includeStaticMembers);
+			//			Console.WriteLine (resolveResult);
+			//			Console.WriteLine ("node:" + resolvedNode);
+			//			Console.WriteLine (currentMember !=  null ? currentMember.IsStatic : "currentMember == null");
+
+			if (resolvedNode.Annotation<ObjectCreateExpression>() == null) {
+				//tags the created expression as part of an object create expression.
+				/*				
+				var filteredList = new List<IMember>();
+				foreach (var member in type.GetMembers ()) {
+					filteredList.Add(member);
+				}
+				
+				foreach (var member in filteredList) {
+					//					Console.WriteLine ("add:" + member + "/" + member.IsStatic);
+					result.AddMember(member);
+				}*/
+				foreach (var member in lookup.GetAccessibleMembers (resolveResult)) {
+					if (member.SymbolKind == SymbolKind.Indexer || member.SymbolKind == SymbolKind.Operator || member.SymbolKind == SymbolKind.Constructor || member.SymbolKind == SymbolKind.Destructor) {
+						continue;
+					}
+					if (resolvedNode is BaseReferenceExpression && member.IsAbstract) {
+						continue;
+					}
+					if (member is IType) {
+						if (resolveResult is TypeResolveResult || includeStaticMembers) {
+							if (!lookup.IsAccessible(member, isProtectedAllowed))
+								continue;
+							result.AddType((IType)member, false);
+							continue;
+						}
+					}
+					bool memberIsStatic = member.IsStatic;
+					if (!includeStaticMembers && memberIsStatic && !(resolveResult is TypeResolveResult)) {
+						//						Console.WriteLine ("skip static member: " + member.FullName);
+						continue;
+					}
+
+					var field = member as IField;
+					if (field != null) {
+						memberIsStatic |= field.IsConst;
+					}
+					if (!memberIsStatic && skipNonStaticMembers) {
+						continue;
+					}
+
+					if (member is IMethod && ((IMethod)member).FullName == "System.Object.Finalize") {
+						continue;
+					}
+					if (member.SymbolKind == SymbolKind.Operator) {
+						continue;
+					}
+
+					if (member is IMember) {
+						result.AddMember((IMember)member);
+					}
+				}
+			}
+
+			if (!(resolveResult is TypeResolveResult || includeStaticMembers)) {
+				foreach (var meths in state.GetExtensionMethods (type)) {
+					foreach (var m in meths) {
+						if (!lookup.IsAccessible(m, isProtectedAllowed))
+							continue;
+						result.AddMember(new ReducedExtensionMethod(m));
+					}
+				}
+			}
+
+			//			IEnumerable<object> objects = resolveResult.CreateResolveResult (dom, resolver != null ? resolver.CallingMember : null);
+			//			CompletionDataCollector col = new CompletionDataCollector (this, dom, result, Document.CompilationUnit, resolver != null ? resolver.CallingType : null, location);
+			//			col.HideExtensionParameter = !resolveResult.StaticResolve;
+			//			col.NamePrefix = expressionResult.Expression;
+			//			bool showOnlyTypes = expressionResult.Contexts.Any (ctx => ctx == ExpressionContext.InheritableType || ctx == ExpressionContext.Constraints);
+			//			if (objects != null) {
+			//				foreach (object obj in objects) {
+			//					if (expressionResult.ExpressionContext != null && expressionResult.ExpressionContext.FilterEntry (obj))
+			//						continue;
+			//					if (expressionResult.ExpressionContext == ExpressionContext.NamespaceNameExcepted && !(obj is Namespace))
+			//						continue;
+			//					if (showOnlyTypes && !(obj is IType))
+			//						continue;
+			//					CompletionData data = col.Add (obj);
+			//					if (data != null && expressionResult.ExpressionContext == ExpressionContext.Attribute && data.CompletionText != null && data.CompletionText.EndsWith ("Attribute")) {
+			//						string newText = data.CompletionText.Substring (0, data.CompletionText.Length - "Attribute".Length);
+			//						data.SetText (newText);
+			//					}
+			//				}
+			//			}
+
+			return result.Result;
+		}
+
+		IEnumerable<ICompletionData> CreateCaseCompletionData(TextLocation location)
+		{
+			var unit = ParseStub("a: break;");
+			if (unit == null) {
+				return null;
+			}
+			var s = unit.GetNodeAt<SwitchStatement>(location);
+			if (s == null) {
+				return null;
+			}
+
+			var offset = document.GetOffset(s.Expression.StartLocation);
+			var expr = GetExpressionAt(offset);
+			if (expr == null) {
+				return null;
+			}
+
+			var resolveResult = ResolveExpression(expr);
+			if (resolveResult == null || resolveResult.Result.Type.Kind != TypeKind.Enum) { 
+				return null;
+			}
+			var wrapper = new CompletionDataWrapper(this);
+			AddEnumMembers(wrapper, resolveResult.Result.Type, resolveResult.Resolver);
+			AutoCompleteEmptyMatch = false;
+			return wrapper.Result;
+		}
+
+		#region Parsing methods
+
+		ExpressionResult GetExpressionBeforeCursor()
+		{
+			SyntaxTree baseUnit;
+			if (currentMember == null) {
+				baseUnit = ParseStub("a", false);
+				var type = baseUnit.GetNodeAt<MemberType>(location);
+				if (type == null) {
+					baseUnit = ParseStub("a;", false);
+					type = baseUnit.GetNodeAt<MemberType>(location);
+				}
+
+				if (type == null) {
+					baseUnit = ParseStub("A a;", false);
+					type = baseUnit.GetNodeAt<MemberType>(location);
+				}
+				if (type != null) {
+					return new ExpressionResult((AstNode)type.Target, baseUnit);
+				}
+			}
+
+			baseUnit = ParseStub("ToString()", false);
+			var curNode = baseUnit.GetNodeAt(location);
+			// hack for local variable declaration missing ';' issue - remove that if it works.
+			if (curNode is EntityDeclaration || baseUnit.GetNodeAt<Expression>(location) == null && baseUnit.GetNodeAt<MemberType>(location) == null) {
+				baseUnit = ParseStub("a");
+				curNode = baseUnit.GetNodeAt(location);
+			}
+
+			// Hack for handle object initializer continuation expressions
+			if (curNode is EntityDeclaration || baseUnit.GetNodeAt<Expression>(location) == null && baseUnit.GetNodeAt<MemberType>(location) == null) {
+				baseUnit = ParseStub("a};");
+			}
+			var mref = baseUnit.GetNodeAt<MemberReferenceExpression>(location); 
+			if (currentMember == null && currentType == null) {
+				if (mref != null) {
+					return new ExpressionResult((AstNode)mref.Target, baseUnit);
+				}
+				return null;
+			}
+
+			//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
+			if (mref == null) {
+				var type = baseUnit.GetNodeAt<MemberType>(location); 
+				if (type != null) {
+					return new ExpressionResult((AstNode)type.Target, baseUnit);
+				}
+
+				var pref = baseUnit.GetNodeAt<PointerReferenceExpression>(location); 
+				if (pref != null) {
+					return new ExpressionResult((AstNode)pref.Target, baseUnit);
+				}
+			}
+
+			if (mref == null) {
+				baseUnit = ParseStub("A a;", false);
+				var type = baseUnit.GetNodeAt<MemberType>(location);
+				if (type != null) {
+					return new ExpressionResult((AstNode)type.Target, baseUnit);
+				}
+			}
+
+			AstNode expr = null;
+			if (mref != null) {
+				expr = mref.Target;
+			} else {
+				Expression tref = baseUnit.GetNodeAt<TypeReferenceExpression>(location); 
+				MemberType memberType = tref != null ? ((TypeReferenceExpression)tref).Type as MemberType : null;
+				if (memberType == null) {
+					memberType = baseUnit.GetNodeAt<MemberType>(location); 
+					if (memberType != null) {
+						if (memberType.Parent is ObjectCreateExpression) {
+							var mt = memberType.Target.Clone();
+							memberType.ReplaceWith(mt);
+							expr = mt;
+							goto exit;
+						} else {
+							tref = baseUnit.GetNodeAt<Expression>(location); 
+							if (tref == null) {
+								tref = new TypeReferenceExpression(memberType.Clone());
+								memberType.Parent.AddChild(tref, Roles.Expression);
+							}
+							if (tref is ObjectCreateExpression) {
+								expr = memberType.Target.Clone();
+								expr.AddAnnotation(new ObjectCreateExpression());
+							}
+						}
+					}
+				}
+
+				if (memberType == null) {
+					return null;
+				}
+				if (expr == null) {
+					expr = memberType.Target.Clone();
+				}
+				tref.ReplaceWith(expr);
+			}
+			exit:
+			return new ExpressionResult((AstNode)expr, baseUnit);
+		}
+
+		ExpressionResult GetExpressionAtCursor()
+		{
+			//			TextLocation memberLocation;
+			//			if (currentMember != null) {
+			//				memberLocation = currentMember.Region.Begin;
+			//			} else if (currentType != null) {
+			//				memberLocation = currentType.Region.Begin;
+			//			} else {
+			//				memberLocation = location;
+			//			}
+			var baseUnit = ParseStub("a");
+			var tmpUnit = baseUnit;
+			AstNode expr = baseUnit.GetNodeAt(
+				location,
+				n => n is IdentifierExpression || n is MemberReferenceExpression
+			);
+
+			if (expr == null) {
+				expr = baseUnit.GetNodeAt<AstType>(location.Line, location.Column - 1);
+			}
+			if (expr == null)
+				expr = baseUnit.GetNodeAt<Identifier>(location.Line, location.Column - 1);
+			// try insertStatement
+			if (expr == null && baseUnit.GetNodeAt<EmptyStatement>(location.Line, location.Column) != null) {
+				tmpUnit = baseUnit = ParseStub("a();", false);
+				expr = baseUnit.GetNodeAt<InvocationExpression>(
+					location.Line,
+					location.Column + 1
+				); 
+			}
+
+			if (expr == null) {
+				baseUnit = ParseStub("()");
+				expr = baseUnit.GetNodeAt<IdentifierExpression>(
+					location.Line,
+					location.Column - 1
+				); 
+				if (expr == null) {
+					expr = baseUnit.GetNodeAt<MemberType>(location.Line, location.Column - 1); 
+				}
+			}
+
+			if (expr == null) {
+				baseUnit = ParseStub("a", false);
+				expr = baseUnit.GetNodeAt(
+					location,
+					n => n is IdentifierExpression || n is MemberReferenceExpression || n is CatchClause
+				);
+			}
+
+			// try statement 
+			if (expr == null) {
+				expr = tmpUnit.GetNodeAt<SwitchStatement>(
+					location.Line,
+					location.Column - 1
+				); 
+				baseUnit = tmpUnit;
+			}
+
+			if (expr == null) {
+				var block = tmpUnit.GetNodeAt<BlockStatement>(location); 
+				var node = block != null ? block.Statements.LastOrDefault() : null;
+
+				var forStmt = node != null ? node.PrevSibling as ForStatement : null;
+				if (forStmt != null && forStmt.EmbeddedStatement.IsNull) {
+					expr = forStmt;
+					var id = new IdentifierExpression("stub");
+					forStmt.EmbeddedStatement = new BlockStatement() { Statements = { new ExpressionStatement(id) } };
+					expr = id;
+					baseUnit = tmpUnit;
+				}
+			}
+
+			if (expr == null) {
+				var forStmt = tmpUnit.GetNodeAt<ForeachStatement>(
+					location.Line,
+					location.Column - 3
+				); 
+				if (forStmt != null && forStmt.EmbeddedStatement.IsNull) {
+					forStmt.VariableNameToken = Identifier.Create("stub");
+					expr = forStmt.VariableNameToken;
+					baseUnit = tmpUnit;
+				}
+			}
+			if (expr == null) {
+				expr = tmpUnit.GetNodeAt<VariableInitializer>(
+					location.Line,
+					location.Column - 1
+				);
+				baseUnit = tmpUnit;
+			}
+
+			// try parameter declaration type
+			if (expr == null) {
+				baseUnit = ParseStub(">", false, "{}");
+				expr = baseUnit.GetNodeAt<TypeParameterDeclaration>(
+					location.Line,
+					location.Column - 1
+				); 
+			}
+
+			// try parameter declaration method
+			if (expr == null) {
+				baseUnit = ParseStub("> ()", false, "{}");
+				expr = baseUnit.GetNodeAt<TypeParameterDeclaration>(
+					location.Line,
+					location.Column - 1
+				); 
+			}
+
+			// try expression in anonymous type "new { sample = x$" case
+			if (expr == null) {
+				baseUnit = ParseStub("a", false);
+				expr = baseUnit.GetNodeAt<AnonymousTypeCreateExpression>(
+					location.Line,
+					location.Column
+				); 
+				if (expr != null) {
+					expr = baseUnit.GetNodeAt<Expression>(location.Line, location.Column) ?? expr;
+				} 
+				if (expr == null) {
+					expr = baseUnit.GetNodeAt<AstType>(location.Line, location.Column);
+				} 
+			}
+
+			// try lambda 
+			if (expr == null) {
+				baseUnit = ParseStub("foo) => {}", false);
+				expr = baseUnit.GetNodeAt<ParameterDeclaration>(
+					location.Line,
+					location.Column
+				); 
+			}
+
+			if (expr == null)
+				return null;
+			return new ExpressionResult(expr, baseUnit);
+		}
+
+		ExpressionResult GetExpressionAt(int offset)
+		{
+			var parser = new CSharpParser();
+			var text = GetMemberTextToCaret(); 
+
+			int closingBrackets = 0, generatedLines = 0;
+			var sb = CreateWrapper("a;", false, "", text.Item1, text.Item2, ref closingBrackets, ref generatedLines);
+
+			var completionUnit = parser.Parse(sb.ToString());
+			var offsetLocation = document.GetLocation(offset);
+			var loc = new TextLocation(offsetLocation.Line - text.Item2.Line + generatedLines + 1, offsetLocation.Column);
+
+			var expr = completionUnit.GetNodeAt(
+				loc,
+				n => n is Expression || n is VariableDeclarationStatement
+			);
+			if (expr == null)
+				return null;
+			return new ExpressionResult(expr, completionUnit);
+		}
+
+		ExpressionResult GetNewExpressionAt(int offset)
+		{
+			var parser = new CSharpParser();
+			var text = GetMemberTextToCaret();
+			int closingBrackets = 0, generatedLines = 0;
+			var sb = CreateWrapper("a ();", false, "", text.Item1, text.Item2, ref closingBrackets, ref generatedLines);
+
+			var completionUnit = parser.Parse(sb.ToString());
+			var offsetLocation = document.GetLocation(offset);
+			var loc = new TextLocation(offsetLocation.Line - text.Item2.Line + generatedLines + 1, offsetLocation.Column);
+
+			var expr = completionUnit.GetNodeAt(loc, n => n is Expression);
+			if (expr == null) {
+				// try without ";"
+				sb = CreateWrapper("a ()", false, "", text.Item1, text.Item2, ref closingBrackets, ref generatedLines);
+				completionUnit = parser.Parse(sb.ToString());
+
+				expr = completionUnit.GetNodeAt(loc, n => n is Expression);
+				if (expr == null) {
+					return null;
+				}
+			}
+			return new ExpressionResult(expr, completionUnit);
+		}
+
+		#endregion
+
+		#region Helper methods
+
+		string GetPreviousToken(ref int i, bool allowLineChange)
+		{
+			char c;
+			if (i <= 0) {
+				return null;
+			}
+
+			do {
+				c = document.GetCharAt(--i);
+			} while (i > 0 && char.IsWhiteSpace(c) && (allowLineChange ? true : c != '\n'));
+
+			if (i == 0) {
+				return null;
+			}
+
+			if (!char.IsLetterOrDigit(c)) {
+				return new string(c, 1);
+			}
+
+			int endOffset = i + 1;
+
+			do {
+				c = document.GetCharAt(i - 1);
+				if (!(char.IsLetterOrDigit(c) || c == '_')) {
+					break;
+				}
+
+				i--;
+			} while (i > 0);
+
+			return document.GetText(i, endOffset - i);
+		}
+
+		#endregion
+
+		#region Preprocessor
+
+		IEnumerable<ICompletionData> GetDirectiveCompletionData()
+		{
+			yield return factory.CreateLiteralCompletionData("if");
+			yield return factory.CreateLiteralCompletionData("else");
+			yield return factory.CreateLiteralCompletionData("elif");
+			yield return factory.CreateLiteralCompletionData("endif");
+			yield return factory.CreateLiteralCompletionData("define");
+			yield return factory.CreateLiteralCompletionData("undef");
+			yield return factory.CreateLiteralCompletionData("warning");
+			yield return factory.CreateLiteralCompletionData("error");
+			yield return factory.CreateLiteralCompletionData("pragma");
+			yield return factory.CreateLiteralCompletionData("line");
+			yield return factory.CreateLiteralCompletionData("line hidden");
+			yield return factory.CreateLiteralCompletionData("line default");
+			yield return factory.CreateLiteralCompletionData("region");
+			yield return factory.CreateLiteralCompletionData("endregion");
+		}
+
+		#endregion
+
+		#region Xml Comments
+
+		static readonly List<string> commentTags = new List<string>(new string[] {
+			"c",
+			"code",
+			"example",
+			"exception",
+			"include",
+			"list",
+			"listheader",
+			"item",
+			"term",
+			"description",
+			"para",
+			"param",
+			"paramref",
+			"permission",
+			"remarks",
+			"returns",
+			"see",
+			"seealso",
+			"summary",
+			"value"
+		}
+		);
+
+		public static IEnumerable<string> CommentTags {
+			get {
+				return commentTags;
+			}
+		}
+
+		string GetLastClosingXmlCommentTag()
+		{
+			var line = document.GetLineByNumber(location.Line);
+
+			restart:
+			string lineText = document.GetText(line);
+			if (!lineText.Trim().StartsWith("///", StringComparison.Ordinal))
+				return null;
+			int startIndex = Math.Min(location.Column - 1, lineText.Length - 1) - 1;
+			while (startIndex > 0 && lineText [startIndex] != '<') {
+				--startIndex;
+				if (lineText [startIndex] == '/') {
+					// already closed.
+					startIndex = -1;
+					break;
+				}
+			}
+			if (startIndex < 0 && line.PreviousLine != null) {
+				line = line.PreviousLine;
+				goto restart;
+			}
+
+			if (startIndex >= 0) {
+				int endIndex = startIndex;
+				while (endIndex + 1 < lineText.Length && lineText [endIndex] != '>' && !char.IsWhiteSpace(lineText [endIndex])) {
+					endIndex++;
+				}
+				string tag = endIndex - startIndex - 1 > 0 ? lineText.Substring(
+					startIndex + 1,
+					endIndex - startIndex - 1
+				) : null;
+				if (!string.IsNullOrEmpty(tag) && commentTags.IndexOf(tag) >= 0) {
+					return tag;
+				}
+			}
+			return null;
+		}
+
+		IEnumerable<ICompletionData> GetXmlDocumentationCompletionData()
+		{
+			var closingTag = GetLastClosingXmlCommentTag();
+			if (closingTag != null) {
+				yield return factory.CreateLiteralCompletionData(
+					"/" + closingTag + ">"
+				);
+			}
+
+			yield return factory.CreateXmlDocCompletionData(
+				"c",
+				"Set text in a code-like font"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"code",
+				"Set one or more lines of source code or program output"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"example",
+				"Indicate an example"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"exception",
+				"Identifies the exceptions a method can throw",
+				"exception cref=\"|\"></exception"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"include",
+				"Includes comments from a external file",
+				"include file=\"|\" path=\"\""
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"inheritdoc",
+				"Inherit documentation from a base class or interface",
+				"inheritdoc/"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"list",
+				"Create a list or table",
+				"list type=\"|\""
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"listheader",
+				"Define the heading row"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"item",
+				"Defines list or table item"
+			);
+
+			yield return factory.CreateXmlDocCompletionData("term", "A term to define");
+			yield return factory.CreateXmlDocCompletionData(
+				"description",
+				"Describes a list item"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"para",
+				"Permit structure to be added to text"
+			);
+
+			yield return factory.CreateXmlDocCompletionData(
+				"param",
+				"Describe a parameter for a method or constructor",
+				"param name=\"|\""
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"paramref",
+				"Identify that a word is a parameter name",
+				"paramref name=\"|\"/"
+			);
+
+			yield return factory.CreateXmlDocCompletionData(
+				"permission",
+				"Document the security accessibility of a member",
+				"permission cref=\"|\""
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"remarks",
+				"Describe a type"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"returns",
+				"Describe the return value of a method"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"see",
+				"Specify a link",
+				"see cref=\"|\"/"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"seealso",
+				"Generate a See Also entry",
+				"seealso cref=\"|\"/"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"summary",
+				"Describe a member of a type"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"typeparam",
+				"Describe a type parameter for a generic type or method"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"typeparamref",
+				"Identify that a word is a type parameter name"
+			);
+			yield return factory.CreateXmlDocCompletionData(
+				"value",
+				"Describe a property"
+			);
+
+		}
+
+		#endregion
+
+		#region Keywords
+
+		static string[] expressionLevelKeywords = new string [] {
+			"as",
+			"is",
+			"else",
+			"out",
+			"ref",
+			"null",
+			"delegate",
+			"default"
+		};
+		static string[] primitiveTypesKeywords = new string [] {
+			"void",
+			"object",
+			"bool",
+			"byte",
+			"sbyte",
+			"char",
+			"short",
+			"int",
+			"long",
+			"ushort",
+			"uint",
+			"ulong",
+			"float",
+			"double",
+			"decimal",
+			"string"
+		};
+		static string[] statementStartKeywords = new string [] { "base", "new", "sizeof", "this", 
+			"true", "false", "typeof", "checked", "unchecked", "from", "break", "checked",
+			"unchecked", "const", "continue", "do", "finally", "fixed", "for", "foreach",
+			"goto", "if", "lock", "return", "stackalloc", "switch", "throw", "try", "unsafe", 
+			"using", "while", "yield",
+			"catch"
+		};
+		static string[] globalLevelKeywords = new string [] {
+			"namespace", "using", "extern", "public", "internal", 
+			"class", "interface", "struct", "enum", "delegate",
+			"abstract", "sealed", "static", "unsafe", "partial"
+		};
+		static string[] accessorModifierKeywords = new string [] {
+			"public", "internal", "protected", "private", "async"
+		};
+		static string[] typeLevelKeywords = new string [] {
+			"public", "internal", "protected", "private", "async",
+			"class", "interface", "struct", "enum", "delegate",
+			"abstract", "sealed", "static", "unsafe", "partial",
+			"const", "event", "extern", "fixed", "new", 
+			"operator", "explicit", "implicit", 
+			"override", "readonly", "virtual", "volatile"
+		};
+		static string[] linqKeywords = new string[] {
+			"from",
+			"where",
+			"select",
+			"group",
+			"into",
+			"orderby",
+			"join",
+			"let",
+			"in",
+			"on",
+			"equals",
+			"by",
+			"ascending",
+			"descending"
+		};
+		static string[] parameterTypePredecessorKeywords = new string[] {
+			"out",
+			"ref",
+			"params"
+		};
+
+		#endregion
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpCompletionEngineBase.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpCompletionEngineBase.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpCompletionEngineBase.cs	(revision 11807)
@@ -0,0 +1,907 @@
+﻿// 
+// CSharpCompletionEngineBase.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	/// <summary>
+	/// Acts as a common base between code completion and parameter completion.
+	/// </summary>
+	public class CSharpCompletionEngineBase
+	{
+		protected IDocument document;
+		protected int offset;
+		protected TextLocation location;
+		protected IUnresolvedTypeDefinition currentType;
+		protected IUnresolvedMember currentMember;
+		
+		#region Input properties
+		public CSharpTypeResolveContext ctx { get; private set; }
+
+		public IProjectContent ProjectContent { get; private set; }
+		
+		ICompilation compilation;
+
+		protected ICompilation Compilation {
+			get {
+				if (compilation == null)
+					compilation = ProjectContent.Resolve (ctx).Compilation;
+				return compilation;
+			}
+		}
+
+		Version languageVersion = new Version (5, 0);
+		public Version LanguageVersion {
+			get {
+				return languageVersion;
+			}
+			set {
+				languageVersion = value;
+			}
+		}
+		#endregion
+		
+		protected CSharpCompletionEngineBase(IProjectContent content, ICompletionContextProvider completionContextProvider, CSharpTypeResolveContext ctx)
+		{
+			if (content == null)
+				throw new ArgumentNullException("content");
+			if (ctx == null)
+				throw new ArgumentNullException("ctx");
+			if (completionContextProvider == null)
+				throw new ArgumentNullException("completionContextProvider");
+			
+			this.ProjectContent = content;
+			this.CompletionContextProvider = completionContextProvider;
+			this.ctx = ctx;
+		}
+		
+		
+		public ICompletionContextProvider CompletionContextProvider {
+			get;
+			private set;
+		}
+		
+		public void SetOffset (int offset)
+		{
+			Reset ();
+			
+			this.offset = offset;
+			this.location = document.GetLocation (offset);
+			CompletionContextProvider.GetCurrentMembers (offset, out currentType, out currentMember);
+		}
+
+		public bool GetParameterCompletionCommandOffset (out int cpos)
+		{
+			// Start calculating the parameter offset from the beginning of the
+			// current member, instead of the beginning of the file. 
+			cpos = offset - 1;
+			var mem = currentMember;
+			if (mem == null || (mem is IType) || IsInsideCommentStringOrDirective ()) {
+				return false;
+			}
+			int startPos = document.GetOffset (mem.Region.BeginLine, mem.Region.BeginColumn);
+			int parenDepth = 0;
+			int chevronDepth = 0;
+			Stack<int> indexStack = new Stack<int> ();
+			while (cpos > startPos) {
+				char c = document.GetCharAt (cpos);
+				if (c == ')') {
+					parenDepth++;
+				}
+				if (c == '>') {
+					chevronDepth++;
+				}
+				if (c == '}') {
+					if (indexStack.Count > 0) {
+						parenDepth = indexStack.Pop ();
+					} else {
+						parenDepth = 0;
+					}
+					chevronDepth = 0;
+				}
+				if (indexStack.Count == 0 && (parenDepth == 0 && c == '(' || chevronDepth == 0 && c == '<')) {
+					int p = GetCurrentParameterIndex (startPos, cpos + 1);
+					if (p != -1) {
+						cpos++;
+						return true;
+					} else {
+						return false;
+					}
+				}
+				if (c == '(') {
+					parenDepth--;
+				}
+				if (c == '<') {
+					chevronDepth--;
+				}
+				if (c == '{') {
+					indexStack.Push (parenDepth);
+					chevronDepth = 0;
+				}
+				cpos--;
+			}
+			return false;
+		}
+		
+		public int GetCurrentParameterIndex(int triggerOffset, int endOffset)
+		{
+			List<string> list;
+			return  GetCurrentParameterIndex (triggerOffset, endOffset, out list);
+		}
+
+		public int GetCurrentParameterIndex (int triggerOffset, int endOffset, out List<string> usedNamedParameters)
+		{
+			usedNamedParameters =new List<string> ();
+			var parameter = new Stack<int> ();
+			var bracketStack = new Stack<Stack<int>> ();
+			bool inSingleComment = false, inString = false, inVerbatimString = false, inChar = false, inMultiLineComment = false;
+			var word = new StringBuilder ();
+			bool foundCharAfterOpenBracket = false;
+			for (int i = triggerOffset; i < endOffset; i++) {
+				char ch = document.GetCharAt (i);
+				char nextCh = i + 1 < document.TextLength ? document.GetCharAt (i + 1) : '\0';
+				if (ch == ':') {
+					usedNamedParameters.Add (word.ToString ());
+					word.Length = 0;
+				} else if (char.IsLetterOrDigit (ch) || ch =='_') {
+					word.Append (ch);
+				} else if (char.IsWhiteSpace (ch)) {
+
+				} else {
+					word.Length = 0;
+				}
+				if (!char.IsWhiteSpace(ch) && parameter.Count > 0)
+					foundCharAfterOpenBracket = true;
+
+				switch (ch) {
+					case '{':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						bracketStack.Push (parameter);
+						parameter = new Stack<int> ();
+						break;
+					case '[':
+					case '(':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						parameter.Push (0);
+						break;
+					case '}':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						if (bracketStack.Count > 0) {
+							parameter = bracketStack.Pop ();
+						} else {
+							return -1;
+						}
+						break;
+					case ']':
+					case ')':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						if (parameter.Count > 0) {
+							parameter.Pop ();
+						} else {
+							return -1;
+						}
+						break;
+					case '<':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						parameter.Push (0);
+						break;
+					case '=':
+						if (nextCh == '>') {
+							i++;
+							continue;
+						}
+						break;
+					case '>':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						if (parameter.Count > 0) {
+							parameter.Pop ();
+						}
+						break;
+					case ',':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						if (parameter.Count > 0) {
+							parameter.Push (parameter.Pop () + 1);
+						}
+						break;
+					case '/':
+						if (inString || inChar || inVerbatimString) {
+							break;
+						}
+						if (nextCh == '/') {
+							i++;
+							inSingleComment = true;
+						}
+						if (nextCh == '*') {
+							inMultiLineComment = true;
+						}
+						break;
+					case '*':
+						if (inString || inChar || inVerbatimString || inSingleComment) {
+							break;
+						}
+						if (nextCh == '/') {
+							i++;
+							inMultiLineComment = false;
+						}
+						break;
+					case '@':
+						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment) {
+							break;
+						}
+						if (nextCh == '"') {
+							i++;
+							inVerbatimString = true;
+						}
+						break;
+					case '\\':
+						if (inString || inChar) {
+							i++;
+						}
+						break;
+					case '"':
+						if (inSingleComment || inMultiLineComment || inChar) {
+							break;
+						}
+						if (inVerbatimString) {
+							if (nextCh == '"') {
+								i++;
+								break;
+							}
+							inVerbatimString = false;
+							break;
+						}
+						inString = !inString;
+						break;
+					case '\'':
+						if (inSingleComment || inMultiLineComment || inString || inVerbatimString) {
+							break;
+						}
+						inChar = !inChar;
+						break;
+					default:
+						if (NewLine.IsNewLine(ch)) {
+							inSingleComment = false;
+							inString = false;
+							inChar = false;
+						}
+						break;
+				}
+			}
+			if (parameter.Count != 1 || bracketStack.Count > 0) {
+				return -1;
+			}
+			if (!foundCharAfterOpenBracket)
+				return 0;
+			return parameter.Pop() + 1;
+		}
+
+		#region Context helper methods
+		public class MiniLexer
+		{
+			readonly string text;
+
+			public bool IsFistNonWs               = true;
+			public bool IsInSingleComment         = false;
+			public bool IsInString                = false;
+			public bool IsInVerbatimString        = false;
+			public bool IsInChar                  = false;
+			public bool IsInMultiLineComment      = false;
+			public bool IsInPreprocessorDirective = false;
+
+			public MiniLexer(string text)
+			{
+				this.text = text;
+			}
+
+			/// <summary>
+			/// Parsing all text and calling act delegate on almost every character.
+			/// Skipping begining of comments, begining of verbatim strings and escaped characters.
+			/// </summary>
+			/// <param name="act">Return true to abort parsing. Integer argument represent offset in text.</param>
+			/// <returns>True if aborted.</returns>
+			public bool Parse(Func<char, int, bool> act = null)
+			{
+				return Parse(0, text.Length, act);
+			}
+
+
+			/// <summary>
+			/// Parsing text from start to start+length and calling act delegate on almost every character.
+			/// Skipping begining of comments, begining of verbatim strings and escaped characters.
+			/// </summary>
+			/// <param name="start">Start offset.</param>
+			/// <param name="length">Lenght to parse.</param>
+			/// <param name="act">Return true to abort parsing. Integer argument represent offset in text.</param>
+			/// <returns>True if aborted.</returns>
+			public bool Parse(int start, int length, Func<char, int, bool> act = null)
+			{
+				for (int i = start; i < length; i++) {
+					char ch = text [i];
+					char nextCh = i + 1 < text.Length ? text [i + 1] : '\0';
+					switch (ch) {
+						case '#':
+							if (IsFistNonWs)
+								IsInPreprocessorDirective = true;
+							break; 
+						case '/':
+							if (IsInString || IsInChar || IsInVerbatimString || IsInSingleComment || IsInMultiLineComment)
+								break;
+							if (nextCh == '/') {
+								i++;
+								IsInSingleComment = true;
+								IsInPreprocessorDirective = false;
+							}
+							if (nextCh == '*' && !IsInPreprocessorDirective) {
+								IsInMultiLineComment = true;
+								i++;
+							}
+							break;
+						case '*':
+							if (IsInString || IsInChar || IsInVerbatimString || IsInSingleComment)
+								break;
+							if (nextCh == '/') {
+								i++;
+								IsInMultiLineComment = false;
+							}
+							break;
+						case '@':
+							if (IsInString || IsInChar || IsInVerbatimString || IsInSingleComment || IsInMultiLineComment)
+								break;
+							if (nextCh == '"') {
+								i++;
+								IsInVerbatimString = true;
+							}
+							break;
+						case '\n':
+						case '\r':
+							IsInSingleComment = false;
+							IsInString = false;
+							IsInChar = false;
+							IsFistNonWs = true;
+							IsInPreprocessorDirective = false;
+							break;
+						case '\\':
+							if (IsInString || IsInChar)
+								i++;
+							break;
+						case '"':
+							if (IsInSingleComment || IsInMultiLineComment || IsInChar)
+								break;
+							if (IsInVerbatimString) {
+								if (nextCh == '"') {
+									i++;
+									break;
+								}
+								IsInVerbatimString = false;
+								break;
+							}
+							IsInString = !IsInString;
+							break;
+						case '\'':
+							if (IsInSingleComment || IsInMultiLineComment || IsInString || IsInVerbatimString)
+								break;
+							IsInChar = !IsInChar;
+							break;
+					}
+					if (act != null)
+					if (act (ch, i))
+						return true;
+					IsFistNonWs &= ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
+				}
+				return false;
+			}
+		}
+
+		
+		protected bool IsInsideCommentStringOrDirective(int offset)
+		{
+			var lexer = new MiniLexer(document.Text);
+			lexer.Parse(0, offset);
+			return
+				lexer.IsInSingleComment || 
+				lexer.IsInString ||
+				lexer.IsInVerbatimString ||
+				lexer.IsInChar ||
+				lexer.IsInMultiLineComment || 
+				lexer.IsInPreprocessorDirective;
+		}
+
+
+		protected bool IsInsideCommentStringOrDirective()
+		{
+			var text = GetMemberTextToCaret();
+			var lexer = new MiniLexer(text.Item1);
+			lexer.Parse();
+			return
+				lexer.IsInSingleComment || 
+					lexer.IsInString ||
+					lexer.IsInVerbatimString ||
+					lexer.IsInChar ||
+					lexer.IsInMultiLineComment || 
+					lexer.IsInPreprocessorDirective;
+		}
+
+		protected bool IsInsideDocComment ()
+		{
+			var text = GetMemberTextToCaret ();
+			bool inSingleComment = false, inString = false, inVerbatimString = false, inChar = false, inMultiLineComment = false;
+			bool singleLineIsDoc = false;
+			
+			for (int i = 0; i < text.Item1.Length - 1; i++) {
+				char ch = text.Item1 [i];
+				char nextCh = text.Item1 [i + 1];
+				
+				switch (ch) {
+				case '/':
+					if (inString || inChar || inVerbatimString)
+						break;
+					if (nextCh == '/') {
+						i++;
+						inSingleComment = true;
+						singleLineIsDoc = i + 1 < text.Item1.Length && text.Item1 [i + 1] == '/';
+						if (singleLineIsDoc) {
+							i++;
+						}
+					}
+					if (nextCh == '*')
+						inMultiLineComment = true;
+					break;
+				case '*':
+					if (inString || inChar || inVerbatimString || inSingleComment)
+						break;
+					if (nextCh == '/') {
+						i++;
+						inMultiLineComment = false;
+					}
+					break;
+				case '@':
+					if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
+						break;
+					if (nextCh == '"') {
+						i++;
+						inVerbatimString = true;
+					}
+					break;
+				case '\n':
+				case '\r':
+					inSingleComment = false;
+					inString = false;
+					inChar = false;
+					break;
+				case '\\':
+					if (inString || inChar)
+						i++;
+					break;
+				case '"':
+					if (inSingleComment || inMultiLineComment || inChar)
+						break;
+					if (inVerbatimString) {
+						if (nextCh == '"') {
+							i++;
+							break;
+						}
+						inVerbatimString = false;
+						break;
+					}
+					inString = !inString;
+					break;
+				case '\'':
+					if (inSingleComment || inMultiLineComment || inString || inVerbatimString)
+						break;
+					inChar = !inChar;
+					break;
+				}
+			}
+			
+			return inSingleComment && singleLineIsDoc;
+		}
+
+		protected CSharpResolver GetState ()
+		{
+			return new CSharpResolver (ctx);
+			/*var state = new CSharpResolver (ctx);
+			
+			state.CurrentMember = currentMember;
+			state.CurrentTypeDefinition = currentType;
+			state.CurrentUsingScope = CSharpUnresolvedFile.GetUsingScope (location);
+			if (state.CurrentMember != null) {
+				var node = Unit.GetNodeAt (location);
+				if (node == null)
+					return state;
+				var navigator = new NodeListResolveVisitorNavigator (new[] { node });
+				var visitor = new ResolveVisitor (state, CSharpUnresolvedFile, navigator);
+				Unit.AcceptVisitor (visitor, null);
+				try {
+					var newState = visitor.GetResolverStateBefore (node);
+					if (newState != null)
+						state = newState;
+				} catch (Exception) {
+				}
+			}
+			
+			return state;*/
+		}
+				#endregion
+		
+		#region Basic parsing/resolving functions
+		static Stack<Tuple<char, int>> GetBracketStack (string memberText)
+		{
+			var bracketStack = new Stack<Tuple<char, int>> ();
+			
+			bool inSingleComment = false, inString = false, inVerbatimString = false, inChar = false, inMultiLineComment = false;
+			
+			for (int i = 0; i < memberText.Length; i++) {
+				char ch = memberText [i];
+				char nextCh = i + 1 < memberText.Length ? memberText [i + 1] : '\0';
+				switch (ch) {
+				case '(':
+				case '[':
+				case '{':
+					if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
+						break;
+					bracketStack.Push (Tuple.Create (ch, i));
+					break;
+				case ')':
+				case ']':
+				case '}':
+					if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
+						break;
+					if (bracketStack.Count > 0)
+						bracketStack.Pop ();
+					break;
+				case '/':
+					if (inString || inChar || inVerbatimString)
+						break;
+					if (nextCh == '/') {
+						i++;
+						inSingleComment = true;
+					}
+					if (nextCh == '*')
+						inMultiLineComment = true;
+					break;
+				case '*':
+					if (inString || inChar || inVerbatimString || inSingleComment)
+						break;
+					if (nextCh == '/') {
+						i++;
+						inMultiLineComment = false;
+					}
+					break;
+				case '@':
+					if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
+						break;
+					if (nextCh == '"') {
+						i++;
+						inVerbatimString = true;
+					}
+					break;
+				case '\\':
+					if (inString || inChar)
+						i++;
+					break;
+				case '"':
+					if (inSingleComment || inMultiLineComment || inChar)
+						break;
+					if (inVerbatimString) {
+						if (nextCh == '"') {
+							i++;
+							break;
+						}
+						inVerbatimString = false;
+						break;
+					}
+					inString = !inString;
+					break;
+				case '\'':
+					if (inSingleComment || inMultiLineComment || inString || inVerbatimString)
+						break;
+					inChar = !inChar;
+					break;
+				default :
+					if (NewLine.IsNewLine(ch)) {
+						inSingleComment = false;
+						inString = false;
+						inChar = false;
+					}
+					break;
+				}
+			}
+			return bracketStack;
+		}
+		
+		public static void AppendMissingClosingBrackets (StringBuilder wrapper, bool appendSemicolon)
+		{
+			var memberText = wrapper.ToString();
+			var bracketStack = GetBracketStack(memberText);
+			bool didAppendSemicolon = !appendSemicolon;
+			//char lastBracket = '\0';
+			while (bracketStack.Count > 0) {
+				var t = bracketStack.Pop ();
+				switch (t.Item1) {
+				case '(':
+					wrapper.Append (')');
+					if (appendSemicolon)
+						didAppendSemicolon = false;
+					//lastBracket = ')';
+					break;
+				case '[':
+					wrapper.Append (']');
+					if (appendSemicolon)
+						didAppendSemicolon = false;
+					//lastBracket = ']';
+					break;
+				case '<':
+					wrapper.Append ('>');
+					if (appendSemicolon)
+						didAppendSemicolon = false;
+					//lastBracket = '>';
+					break;
+				case '{':
+					int o = t.Item2 - 1;
+					if (!didAppendSemicolon) {
+						didAppendSemicolon = true;
+						wrapper.Append (';');
+					}
+						
+					bool didAppendCatch = false;
+					while (o >= "try".Length) {
+						char ch = memberText [o];
+						if (!char.IsWhiteSpace (ch)) {
+								if (ch == 'y' && memberText [o - 1] == 'r' && memberText [o - 2] == 't' && (o - 3 < 0 || !char.IsLetterOrDigit(memberText [o - 3]))) {
+								wrapper.Append ("} catch {}");
+								didAppendCatch = true;
+							}
+							break;
+						}
+						o--;
+					}
+					if (!didAppendCatch)
+						wrapper.Append ('}');
+					break;
+				}
+			}
+			if (!didAppendSemicolon)
+				wrapper.Append (';');
+		}
+
+		protected StringBuilder CreateWrapper(string continuation, bool appendSemicolon, string afterContinuation, string memberText, TextLocation memberLocation, ref int closingBrackets, ref int generatedLines)
+		{
+			var wrapper = new StringBuilder();
+			bool wrapInClass = memberLocation != new TextLocation(1, 1);
+			if (wrapInClass) {
+				wrapper.Append("class Stub {");
+				wrapper.AppendLine();
+				closingBrackets++;
+				generatedLines++;
+			}
+			wrapper.Append(memberText);
+			wrapper.Append(continuation);
+			AppendMissingClosingBrackets(wrapper, appendSemicolon);
+			wrapper.Append(afterContinuation);
+			if (closingBrackets > 0) {
+				wrapper.Append(new string('}', closingBrackets));
+			}
+			return wrapper;
+		}
+
+		protected SyntaxTree ParseStub(string continuation, bool appendSemicolon = true, string afterContinuation = null)
+		{
+			var mt = GetMemberTextToCaret();
+			if (mt == null) {
+				return null;
+			}
+
+			string memberText = mt.Item1;
+			var memberLocation = mt.Item2;
+			int closingBrackets = 1;
+			int generatedLines = 0;
+			var wrapper = CreateWrapper(continuation, appendSemicolon, afterContinuation, memberText, memberLocation, ref closingBrackets, ref generatedLines);
+			var parser = new CSharpParser ();
+			foreach (var sym in CompletionContextProvider.ConditionalSymbols)
+				parser.CompilerSettings.ConditionalSymbols.Add (sym);
+			parser.InitialLocation = new TextLocation(memberLocation.Line - generatedLines, 1);
+			var result = parser.Parse(wrapper.ToString ());
+			return result;
+		}
+		
+		protected virtual void Reset ()
+		{
+			memberText = null;
+		}
+
+		Tuple<string, TextLocation> memberText;
+		protected Tuple<string, TextLocation> GetMemberTextToCaret()
+		{
+			if (memberText == null)
+				memberText = CompletionContextProvider.GetMemberTextToCaret(offset, currentType, currentMember);
+			return memberText;
+		}
+
+		protected ExpressionResult GetInvocationBeforeCursor(bool afterBracket)
+		{
+			SyntaxTree baseUnit;
+			baseUnit = ParseStub("a", false);
+
+			var section = baseUnit.GetNodeAt<AttributeSection>(location.Line, location.Column - 2);
+			var attr = section != null ? section.Attributes.LastOrDefault() : null;
+			if (attr != null) {
+				return new ExpressionResult((AstNode)attr, baseUnit);
+			}
+
+			//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
+			var mref = baseUnit.GetNodeAt(location.Line, location.Column - 1, n => n is InvocationExpression || n is ObjectCreateExpression); 
+			AstNode expr = null;
+			if (mref is InvocationExpression) {
+				expr = ((InvocationExpression)mref).Target;
+			} else if (mref is ObjectCreateExpression) {
+				expr = mref;
+			} else {
+				baseUnit = ParseStub(")};", false);
+				mref = baseUnit.GetNodeAt(location.Line, location.Column - 1, n => n is InvocationExpression || n is ObjectCreateExpression); 
+				if (mref is InvocationExpression) {
+					expr = ((InvocationExpression)mref).Target;
+				} else if (mref is ObjectCreateExpression) {
+					expr = mref;
+				}
+			}
+
+			if (expr == null) {
+				// work around for missing ';' bug in mcs:
+				baseUnit = ParseStub("a", true);
+			
+				section = baseUnit.GetNodeAt<AttributeSection>(location.Line, location.Column - 2);
+				attr = section != null ? section.Attributes.LastOrDefault() : null;
+				if (attr != null) {
+					return new ExpressionResult((AstNode)attr, baseUnit);
+				}
+	
+				//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
+				mref = baseUnit.GetNodeAt(location.Line, location.Column - 1, n => n is InvocationExpression || n is ObjectCreateExpression); 
+				expr = null;
+				if (mref is InvocationExpression) {
+					expr = ((InvocationExpression)mref).Target;
+				} else if (mref is ObjectCreateExpression) {
+					expr = mref;
+				}
+			}
+
+			if (expr == null) {
+				return null;
+			}
+			return new ExpressionResult ((AstNode)expr, baseUnit);
+		}
+		
+		public class ExpressionResult
+		{
+			public AstNode Node { get; private set; }
+			public SyntaxTree Unit  { get; private set; }
+			
+			
+			public ExpressionResult (AstNode item2, SyntaxTree item3)
+			{
+				this.Node = item2;
+				this.Unit = item3;
+			}
+			
+			public override string ToString ()
+			{
+				return string.Format ("[ExpressionResult: Node={0}, Unit={1}]", Node, Unit);
+			}
+		}
+		
+		protected ExpressionResolveResult ResolveExpression (ExpressionResult tuple)
+		{
+			return ResolveExpression (tuple.Node);
+		}
+
+		protected class ExpressionResolveResult
+		{
+			public ResolveResult Result { get; set; }
+			public CSharpResolver Resolver { get; set; }
+			public CSharpAstResolver AstResolver { get; set; }
+
+			public ExpressionResolveResult(ResolveResult item1, CSharpResolver item2, CSharpAstResolver item3)
+			{
+				this.Result = item1;
+				this.Resolver = item2;
+				this.AstResolver = item3;
+			}
+		}
+
+		protected ExpressionResolveResult ResolveExpression(AstNode expr)
+		{
+			if (expr == null) {
+				return null;
+			}
+			AstNode resolveNode;
+			if (expr is Expression || expr is AstType) {
+				resolveNode = expr;
+			} else if (expr is VariableDeclarationStatement) {
+				resolveNode = ((VariableDeclarationStatement)expr).Type;
+			} else {
+				resolveNode = expr;
+			}
+			try {
+				var root = expr.AncestorsAndSelf.FirstOrDefault(n => n is EntityDeclaration || n is SyntaxTree);
+				if (root == null) {
+					return null;
+				}
+				var curState = GetState();
+				// current member needs to be in the setter because of the 'value' parameter
+				if (root is Accessor) {
+					var prop = curState.CurrentMember as IProperty;
+					if (prop != null && prop.CanSet && (root.Role == IndexerDeclaration.SetterRole || root.Role == PropertyDeclaration.SetterRole))
+					    curState = curState.WithCurrentMember(prop.Setter);
+				}
+
+				// Rood should be the 'body' - otherwise the state -> current member isn't correct.
+				var body = root.Children.FirstOrDefault(r => r.Role == Roles.Body);
+				if (body != null && body.Contains(expr.StartLocation))
+					root = body;
+
+				var csResolver = CompletionContextProvider.GetResolver (curState, root);
+				var result = csResolver.Resolve(resolveNode);
+				var state = csResolver.GetResolverStateBefore(resolveNode);
+				if (state.CurrentMember == null)
+					state = state.WithCurrentMember(curState.CurrentMember);
+				if (state.CurrentTypeDefinition == null)
+					state = state.WithCurrentTypeDefinition(curState.CurrentTypeDefinition);
+				if (state.CurrentUsingScope == null)
+					state = state.WithCurrentUsingScope(curState.CurrentUsingScope);
+				return new ExpressionResolveResult(result, state, csResolver);
+			} catch (Exception e) {
+				Console.WriteLine(e);
+				return null;
+			}
+		}
+		
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpParameterCompletionEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpParameterCompletionEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CSharpParameterCompletionEngine.cs	(revision 11807)
@@ -0,0 +1,408 @@
+﻿// 
+// CSharpParameterCompletionEngine.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.Completion;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	public class CSharpParameterCompletionEngine : CSharpCompletionEngineBase
+	{
+		internal IParameterCompletionDataFactory factory;
+		
+		public CSharpParameterCompletionEngine(IDocument document, ICompletionContextProvider completionContextProvider, IParameterCompletionDataFactory factory, IProjectContent content, CSharpTypeResolveContext ctx) : base (content, completionContextProvider, ctx)
+		{
+			if (document == null) {
+				throw new ArgumentNullException("document");
+			}
+			if (factory == null) {
+				throw new ArgumentNullException("factory");
+			}
+			this.document = document;
+			this.factory = factory;
+		}
+
+		public ExpressionResult GetIndexerBeforeCursor()
+		{
+			SyntaxTree baseUnit;
+			if (currentMember == null && currentType == null) { 
+				return null;
+			}
+			baseUnit = ParseStub("x]");
+			
+			//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
+			var mref = baseUnit.GetNodeAt(location, n => n is IndexerExpression); 
+			AstNode expr;
+			if (mref is IndexerExpression) {
+				expr = ((IndexerExpression)mref).Target;
+			} else {
+				return null;
+			}
+			
+			return new ExpressionResult((AstNode)expr, baseUnit);
+		}
+		
+		public ExpressionResult GetConstructorInitializerBeforeCursor()
+		{
+			SyntaxTree baseUnit;
+			if (currentMember == null && currentType == null) { 
+				return null;
+			}
+			baseUnit = ParseStub("a) {}", false);
+			
+			var expr = baseUnit.GetNodeAt <ConstructorInitializer>(location); 
+			if (expr == null) {
+				return null;
+			}
+			return new ExpressionResult((AstNode)expr, baseUnit);
+		}
+		
+		public ExpressionResult GetTypeBeforeCursor()
+		{
+			SyntaxTree baseUnit;
+			if (currentMember == null && currentType == null) { 
+				return null;
+			}
+			baseUnit = ParseStub("x> a");
+			
+			//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
+			var expr = baseUnit.GetNodeAt<AstType>(location.Line, location.Column + 1);
+			if (expr == null)
+				return null;
+			// '>' position
+			return new ExpressionResult((AstNode)expr, baseUnit);
+		}
+
+		public ExpressionResult GetMethodTypeArgumentInvocationBeforeCursor()
+		{
+			SyntaxTree baseUnit;
+			if (currentMember == null && currentType == null) { 
+				return null;
+			}
+			baseUnit = ParseStub("x>.A ()");
+			
+			//var memberLocation = currentMember != null ? currentMember.Region.Begin : currentType.Region.Begin;
+			var expr = baseUnit.GetNodeAt<MemberReferenceExpression>(location.Line, location.Column + 1);
+			if (expr == null)
+				return null;
+			return new ExpressionResult((AstNode)expr, baseUnit);
+		}
+
+
+
+		IEnumerable<IMethod> CollectMethods(AstNode resolvedNode, MethodGroupResolveResult resolveResult)
+		{
+			var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
+			bool onlyStatic = false;
+			if (resolvedNode is IdentifierExpression && currentMember != null && currentMember.IsStatic || resolveResult.TargetResult is TypeResolveResult) {
+				onlyStatic = true;
+			}
+			var methods = new List<IMethod>();
+			foreach (var method in resolveResult.Methods) {
+				if (method.IsConstructor) {
+					continue;
+				}
+				if (!lookup.IsAccessible (method, true))
+					continue;
+				if (onlyStatic && !method.IsStatic) {
+					continue;
+				}
+				if (method.IsShadowing) {
+					for (int j = 0; j < methods.Count; j++) {
+						if (ParameterListComparer.Instance.Equals(methods[j].Parameters, method.Parameters)) {
+							methods.RemoveAt (j);
+							j--;
+						}
+					}
+				}
+				methods.Add (method);
+			}
+			foreach (var m in methods) {
+				yield return m;
+			}
+			foreach (var extMethods in resolveResult.GetEligibleExtensionMethods (true)) {
+				foreach (var method in extMethods) {
+					if (methods.Contains (method))
+						continue;
+					yield return new ReducedExtensionMethod (method);
+				}
+			}
+		}
+
+		IEnumerable<IProperty> GetAccessibleIndexers(IType type)
+		{
+			var lookup = new MemberLookup(ctx.CurrentTypeDefinition, Compilation.MainAssembly);
+			var properties = new List<IProperty>();
+			foreach (var property in type.GetProperties ()) {
+				if (!property.IsIndexer)
+					continue;
+				if (!lookup.IsAccessible (property, true))
+					continue;
+				if (property.IsShadowing) {
+					for (int j = 0; j < properties.Count; j++) {
+						if (ParameterListComparer.Instance.Equals(properties[j].Parameters, property.Parameters)) {
+							properties.RemoveAt (j);
+							j--;
+						}
+					}
+				}
+
+				properties.Add (property);
+			}
+			return properties;
+		}
+		
+		public IParameterDataProvider GetParameterDataProvider(int offset, char completionChar)
+		{
+			//Ignoring completionChar == '\0' because it usually means moving with arrow keys, tab or enter
+			//we don't want to trigger on those events but it probably should be handled somewhere else
+			//since our job is to resolve method and not to decide when to display tooltip or not
+			if (offset <= 0 || completionChar == '\0') {
+				return null;
+			}
+			SetOffset (offset);
+			int startOffset;
+			string text;
+			if (currentMember == null && currentType == null) {
+				//In case of attributes parse all file
+				startOffset = 0;
+				text = document.Text;
+			} else {
+				var memberText = GetMemberTextToCaret ();
+				text = memberText.Item1;
+				startOffset = document.GetOffset (memberText.Item2);
+			}
+
+			var parenStack = new Stack<int> ();
+			var chevronStack = new Stack<int> ();
+			var squareStack = new Stack<int> ();
+			var bracketStack = new Stack<int> ();
+
+			var lex = new MiniLexer (text);
+			bool failed = lex.Parse ((ch, off) => {
+				if (lex.IsInString || lex.IsInChar || lex.IsInVerbatimString || lex.IsInSingleComment || lex.IsInMultiLineComment || lex.IsInPreprocessorDirective)
+					return false;
+				switch (ch) {
+				case '(':
+					parenStack.Push (startOffset + off);
+					break;
+				case ')':
+					if (parenStack.Count == 0) {
+						return true;
+					}
+					parenStack.Pop ();
+					break;
+				case '<':
+					chevronStack.Push (startOffset + off);
+					break;
+				case '>':
+					//Don't abort if we don't have macthing '<' for '>' it could be if (i > 0) Foo($
+					if (chevronStack.Count == 0) {
+						return false;
+					}
+					chevronStack.Pop ();
+					break;
+				case '[':
+					squareStack.Push (startOffset + off);
+					break;
+				case ']':
+					if (squareStack.Count == 0) {
+						return true;
+					}
+					squareStack.Pop ();
+					break;
+				case '{':
+					bracketStack.Push (startOffset + off);
+					break;
+				case '}':
+					if (bracketStack.Count == 0) {
+						return true;
+					}
+					bracketStack.Pop ();
+					break;
+				}
+				return false;
+			});
+			if (failed)
+				return null;
+			int result = -1;
+			if (parenStack.Count > 0)
+				result = parenStack.Pop ();
+			if (squareStack.Count > 0)
+				result = Math.Max (result, squareStack.Pop ());
+			if (chevronStack.Count > 0)
+				result = Math.Max (result, chevronStack.Pop ());
+
+			//If we are inside { bracket we don't want to display anything
+			if (bracketStack.Count > 0 && bracketStack.Pop () > result)
+				return null;
+			if (result == -1)
+				return null;
+			SetOffset (result + 1);
+			ResolveResult resolveResult;
+			switch (document.GetCharAt (result)) {
+				case '(':
+					var invoke = GetInvocationBeforeCursor(true) ?? GetConstructorInitializerBeforeCursor();
+					if (invoke == null) {
+						return null;
+					}
+					if (invoke.Node is ConstructorInitializer) {
+						var init = (ConstructorInitializer)invoke.Node;
+						if (init.ConstructorInitializerType == ConstructorInitializerType.This) {
+							return factory.CreateConstructorProvider(document.GetOffset(invoke.Node.StartLocation), ctx.CurrentTypeDefinition, init);
+						} else {
+							var baseType = ctx.CurrentTypeDefinition.DirectBaseTypes.FirstOrDefault(bt => bt.Kind != TypeKind.Interface);
+							if (baseType == null) {
+								return null;
+							}
+							return factory.CreateConstructorProvider(document.GetOffset(invoke.Node.StartLocation), baseType);
+						}
+					}
+					if (invoke.Node is ObjectCreateExpression) {
+						var createType = ResolveExpression(((ObjectCreateExpression)invoke.Node).Type);
+						if (createType.Result.Type.Kind == TypeKind.Unknown)
+							return null;
+						return factory.CreateConstructorProvider(document.GetOffset(invoke.Node.StartLocation), createType.Result.Type);
+					}
+					
+					if (invoke.Node is ICSharpCode.NRefactory.CSharp.Attribute) {
+						var attribute = ResolveExpression(invoke);
+						if (attribute == null || attribute.Result == null) {
+							return null;
+						}
+						return factory.CreateConstructorProvider(document.GetOffset(invoke.Node.StartLocation), attribute.Result.Type);
+					}
+					var invocationExpression = ResolveExpression(invoke);
+					if (invocationExpression == null || invocationExpression.Result == null || invocationExpression.Result.IsError) {
+						return null;
+					}
+					resolveResult = invocationExpression.Result;
+					if (resolveResult is MethodGroupResolveResult) {
+						return factory.CreateMethodDataProvider(document.GetOffset(invoke.Node.StartLocation), CollectMethods(invoke.Node, resolveResult as MethodGroupResolveResult));
+					}
+					if (resolveResult is MemberResolveResult) {
+						var mr = resolveResult as MemberResolveResult;
+						if (mr.Member is IMethod) {
+							return factory.CreateMethodDataProvider(document.GetOffset(invoke.Node.StartLocation), new [] { (IMethod)mr.Member });
+						}
+					}
+					
+					if (resolveResult.Type.Kind == TypeKind.Delegate) {
+						return factory.CreateDelegateDataProvider(document.GetOffset(invoke.Node.StartLocation), resolveResult.Type);
+					}
+					
+					//				
+					//				if (result.ExpressionContext == ExpressionContext.BaseConstructorCall) {
+					//					if (resolveResult is ThisResolveResult)
+					//						return new NRefactoryParameterDataProvider (textEditorData, resolver, resolveResult as ThisResolveResult);
+					//					if (resolveResult is BaseResolveResult)
+					//						return new NRefactoryParameterDataProvider (textEditorData, resolver, resolveResult as BaseResolveResult);
+					//				}
+					//				IType resolvedType = resolver.SearchType (resolveResult.ResolvedType);
+					//				if (resolvedType != null && resolvedType.ClassType == ClassType.Delegate) {
+					//					return new NRefactoryParameterDataProvider (textEditorData, result.Expression, resolvedType);
+					//				}
+					break;
+				case '<':
+					invoke = GetMethodTypeArgumentInvocationBeforeCursor();
+					if (invoke != null) {
+						var tExpr2 = ResolveExpression(invoke);
+						if (tExpr2 != null && tExpr2.Result is MethodGroupResolveResult && !tExpr2.Result.IsError) {
+							return factory.CreateTypeParameterDataProvider(document.GetOffset(invoke.Node.StartLocation), CollectMethods(invoke.Node, tExpr2.Result as MethodGroupResolveResult));
+						}
+					}
+					invoke = GetTypeBeforeCursor();
+					if (invoke == null || invoke.Node.StartLocation.IsEmpty) {
+						return null;
+					}
+					var tExpr = ResolveExpression(invoke);
+					if (tExpr == null || tExpr.Result == null || tExpr.Result.IsError) {
+						return null;
+					}
+
+					return factory.CreateTypeParameterDataProvider(document.GetOffset(invoke.Node.StartLocation), CollectAllTypes(tExpr.Result.Type));
+				case '[':
+					invoke = GetIndexerBeforeCursor();
+					if (invoke == null) {
+						return null;
+					}
+					if (invoke.Node is ArrayCreateExpression) {
+						return null;
+					}
+					var indexerExpression = ResolveExpression(invoke);
+					if (indexerExpression == null || indexerExpression.Result == null || indexerExpression.Result.IsError) {
+						return null;
+					}
+					return factory.CreateIndexerParameterDataProvider(document.GetOffset(invoke.Node.StartLocation), indexerExpression.Result.Type, GetAccessibleIndexers (indexerExpression.Result.Type), invoke.Node);
+			}
+			return null;
+		}
+		
+		IEnumerable<IType> CollectAllTypes(IType baseType)
+		{
+			var state = GetState();
+			for (var n = state.CurrentUsingScope; n != null; n = n.Parent) {
+				foreach (var u in n.Usings) {
+					foreach (var type in u.Types) {
+						if (type.TypeParameterCount > 0 && type.Name == baseType.Name) {
+							yield return type;
+						}
+					}
+				}
+				
+				foreach (var type in n.Namespace.Types) {
+					if (type.TypeParameterCount > 0 && type.Name == baseType.Name) {
+						yield return type;
+					}
+				}
+			}
+		}
+		
+		List<string> GetUsedNamespaces()
+		{
+			var scope = ctx.CurrentUsingScope;
+			var result = new List<string>();
+			while (scope != null) {
+				result.Add(scope.Namespace.FullName);
+				
+				foreach (var ns in scope.Usings) {
+					result.Add(ns.FullName);
+				}
+				scope = scope.Parent;
+			}
+			return result;
+		}
+		
+		
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CompletionDataWrapper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CompletionDataWrapper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/CompletionDataWrapper.cs	(revision 11807)
@@ -0,0 +1,328 @@
+﻿// 
+// CompletionDataWrapper.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	public class CompletionDataWrapper
+	{
+		CSharpCompletionEngine completion;
+		List<ICompletionData> result = new List<ICompletionData> ();
+		
+		public List<ICompletionData> Result {
+			get {
+				return result;
+			}
+		}
+		
+		ICompletionDataFactory Factory {
+			get {
+				return completion.factory;
+			}
+		}
+
+		internal bool AnonymousDelegateAdded {
+			get;
+			set;
+		}
+		
+		public CompletionDataWrapper (CSharpCompletionEngine completion)
+		{
+			this.completion = completion;
+		}
+		
+		public void Add (ICompletionData data)
+		{
+			result.Add (data);
+		}
+
+
+		public ICompletionData AddCustom (string displayText, string description = null, string completionText = null)
+		{
+			var literalCompletionData = Factory.CreateLiteralCompletionData(displayText, description, completionText);
+			result.Add(literalCompletionData);
+			return literalCompletionData;
+		}
+		
+		HashSet<string> usedNamespaces = new HashSet<string> ();
+
+		bool IsAccessible(MemberLookup lookup, INamespace ns)
+		{
+			if (ns.Types.Any (t => lookup.IsAccessible (t, false)))
+				return true;
+			foreach (var child in ns.ChildNamespaces)
+				if (IsAccessible (lookup, child))
+					return true;
+			return false;
+		}
+		
+		public void AddNamespace (MemberLookup lookup, INamespace ns)
+		{
+			if (usedNamespaces.Contains (ns.Name))
+				return;
+			if (!IsAccessible (lookup, ns)) {
+				usedNamespaces.Add (ns.Name);
+				return;
+			}
+			usedNamespaces.Add (ns.Name);
+			result.Add (Factory.CreateNamespaceCompletionData (ns));
+		}
+
+		public void AddAlias(string alias)
+		{
+			result.Add (Factory.CreateLiteralCompletionData (alias));
+		}
+
+		Dictionary<string, ICompletionData> typeDisplayText = new Dictionary<string, ICompletionData> ();
+		Dictionary<IType, ICompletionData> addedTypes = new Dictionary<IType, ICompletionData> ();
+
+		public ICompletionData AddConstructors(IType type, bool showFullName, bool isInAttributeContext = false)
+		{
+			return InternalAddType(type, showFullName, isInAttributeContext, true);
+		}
+
+		public ICompletionData AddType(IType type, bool showFullName, bool isInAttributeContext = false)
+		{
+			return InternalAddType(type, showFullName, isInAttributeContext, false);
+		}
+
+		ICompletionData InternalAddType(IType type, bool showFullName, bool isInAttributeContext, bool addConstrurs)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (type.Name == "Void" && type.Namespace == "System" || type.Kind == TypeKind.Unknown)
+				return null;
+			if (addedTypes.ContainsKey (type))
+				return addedTypes[type];
+			usedNamespaces.Add(type.Name);
+			var def = type.GetDefinition();
+			if (def != null && def.ParentAssembly != completion.ctx.CurrentAssembly) {
+				switch (completion.EditorBrowsableBehavior) {
+					case EditorBrowsableBehavior.Ignore:
+						break;
+					case EditorBrowsableBehavior.Normal:
+						var state = def.GetEditorBrowsableState();
+						if (state != System.ComponentModel.EditorBrowsableState.Always)
+							return null;
+						break;
+					case EditorBrowsableBehavior.IncludeAdvanced:
+						if (!def.IsBrowsable())
+							return null;
+						break;
+					default:
+						throw new ArgumentOutOfRangeException();
+				}
+			}
+			ICompletionData usedType;
+			var data = Factory.CreateTypeCompletionData(type, showFullName, isInAttributeContext, addConstrurs);
+			var text = data.DisplayText;
+			if (typeDisplayText.TryGetValue(text, out usedType)) {
+				usedType.AddOverload(data);
+				return usedType;
+			} 
+			typeDisplayText [text] = data;
+			result.Add(data);
+			addedTypes[type] = data;
+			return data;
+		}
+
+		Dictionary<string, List<ICompletionData>> data = new Dictionary<string, List<ICompletionData>> ();
+		
+		public ICompletionData AddVariable(IVariable variable)
+		{
+			if (data.ContainsKey(variable.Name))
+				return null;
+			data [variable.Name] = new List<ICompletionData>();
+			var cd = Factory.CreateVariableCompletionData(variable);
+			result.Add(cd);
+			return cd;
+		}
+		
+		public ICompletionData AddNamedParameterVariable(IVariable variable)
+		{
+			var name = variable.Name + ":";
+			if (data.ContainsKey(name))
+				return null;
+			data [name] = new List<ICompletionData>();
+			
+			var cd = Factory.CreateVariableCompletionData(variable);
+			cd.CompletionText += ":";
+			cd.DisplayText += ":";
+			result.Add(cd);
+			return cd;
+		}
+		
+		public void AddTypeParameter (ITypeParameter variable)
+		{
+			if (data.ContainsKey (variable.Name))
+				return;
+			data [variable.Name] = new List<ICompletionData> ();
+			result.Add (Factory.CreateVariableCompletionData (variable));
+		}
+
+		public void AddTypeImport(ITypeDefinition type, bool useFullName, bool addForTypeCreation)
+		{
+			result.Add(Factory.CreateImportCompletionData(type, useFullName, addForTypeCreation));
+		}
+
+		public ICompletionData AddMember (IMember member)
+		{
+			var newData = Factory.CreateEntityCompletionData (member);
+			
+			if (member.ParentAssembly != completion.ctx.CurrentAssembly) {
+				switch (completion.EditorBrowsableBehavior) {
+					case EditorBrowsableBehavior.Ignore:
+						break;
+					case EditorBrowsableBehavior.Normal:
+						var state = member.GetEditorBrowsableState();
+						if (state != System.ComponentModel.EditorBrowsableState.Always)
+							return null;
+						break;
+					case EditorBrowsableBehavior.IncludeAdvanced:
+						if (!member.IsBrowsable())
+							return null;
+						break;
+					default:
+						throw new ArgumentOutOfRangeException();
+				}
+			}
+			string memberKey = newData.DisplayText;
+			if (memberKey == null)
+				return null;
+
+			newData.CompletionCategory = GetCompletionCategory (member.DeclaringTypeDefinition);
+
+			List<ICompletionData> existingData;
+			data.TryGetValue (memberKey, out existingData);
+			if (existingData != null) {
+				if (member.SymbolKind == SymbolKind.Field || member.SymbolKind == SymbolKind.Property || member.SymbolKind == SymbolKind.Event)
+					return null;
+				var a = member as IEntity;
+				foreach (var d in existingData) {
+					if (!(d is IEntityCompletionData))
+						continue;
+					var b = ((IEntityCompletionData)d).Entity;
+					if (a == null || b == null || a.SymbolKind == b.SymbolKind) {
+						d.AddOverload (newData);
+						return d;
+					} 
+				}
+				if (newData != null) {
+					result.Add (newData);
+					data [memberKey].Add (newData);
+				}
+			} else {
+				result.Add (newData);
+				data [memberKey] = new List<ICompletionData> ();
+				data [memberKey].Add (newData);
+			}
+			return newData;
+		}
+		
+		internal CompletionCategory GetCompletionCategory (IType type)
+		{
+			if (type == null)
+				return null;
+			if (!completionCategories.ContainsKey (type))
+				completionCategories [type] = new TypeCompletionCategory (type);
+			return completionCategories [type];
+		}
+		
+		Dictionary<IType, CompletionCategory> completionCategories = new Dictionary<IType, CompletionCategory> ();
+		class TypeCompletionCategory : CompletionCategory
+		{
+			public IType Type {
+				get;
+				private set;
+			}
+			
+			public TypeCompletionCategory (IType type) : base (type.FullName, null)
+			{
+				this.Type = type;
+			}
+			
+			public override int CompareTo (CompletionCategory other)
+			{
+				var compareCategory = other as TypeCompletionCategory;
+				if (compareCategory == null)
+					return -1;
+				int result;
+				if (Type.ReflectionName == compareCategory.Type.ReflectionName) {
+					result = 0;
+				} else if (Type.GetAllBaseTypes().Any(t => t.ReflectionName == compareCategory.Type.ReflectionName)) {
+					result = -1;
+				} else if (compareCategory.Type.GetAllBaseTypes().Any(t => t.ReflectionName == Type.ReflectionName)) {
+					result = 1;
+				} else {
+					var d = Type.GetDefinition ();
+					var ct = compareCategory.Type.GetDefinition();
+					if (ct.IsStatic && d.IsStatic) {
+						result = d.FullName.CompareTo (ct.FullName);
+					} else if (d.IsStatic) {
+						result = 1;
+					}else if (ct.IsStatic) {
+						result = -1;
+					} else {
+						result = 0;
+					}
+				}
+				return result;
+			}
+		}
+		HashSet<IType> addedEnums = new HashSet<IType> ();
+		public ICompletionData AddEnumMembers (IType resolvedType, CSharpResolver state)
+		{
+			if (addedEnums.Contains (resolvedType))
+				return null;
+			addedEnums.Add (resolvedType);
+			var result = AddType(resolvedType, true);
+			foreach (var field in resolvedType.GetFields ()) {
+				if (field.IsPublic && (field.IsConst || field.IsStatic)) {
+					Result.Add(Factory.CreateMemberCompletionData(resolvedType, field));
+				}
+			}
+			return result;
+		}
+		HashSet<string> anonymousSignatures = new HashSet<string> ();
+
+		public bool HasAnonymousDelegateAdded(string signature)
+		{
+			return anonymousSignatures.Contains(signature); 
+		}
+
+		public void AddAnonymousDelegateAdded(string signature)
+		{
+			anonymousSignatures.Add(signature); 
+		}
+	}
+}
+
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/ICompletionContextProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/ICompletionContextProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/ICompletionContextProvider.cs	(revision 11807)
@@ -0,0 +1,214 @@
+﻿// 
+// IMemberProvider.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc.
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	public interface ICompletionContextProvider
+	{
+		IList<string> ConditionalSymbols {
+			get;
+		}
+
+		void GetCurrentMembers (int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember);
+
+		Tuple<string, TextLocation> GetMemberTextToCaret(int caretOffset, IUnresolvedTypeDefinition currentType, IUnresolvedMember currentMember);
+
+		CSharpAstResolver GetResolver (CSharpResolver resolver, AstNode rootNode);
+	}
+
+	public class DefaultCompletionContextProvider : ICompletionContextProvider
+	{
+		readonly IDocument document;
+		readonly CSharpUnresolvedFile unresolvedFile;
+		readonly List<string> symbols = new List<string> ();
+
+		public IList<string> ConditionalSymbols {
+			get {
+				return symbols;
+			}
+		}
+
+		public DefaultCompletionContextProvider (IDocument document, CSharpUnresolvedFile unresolvedFile)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (unresolvedFile == null)
+				throw new ArgumentNullException("unresolvedFile");
+			this.document = document;
+			this.unresolvedFile = unresolvedFile;
+		}
+
+		public void AddSymbol (string sym)
+		{
+			symbols.Add (sym);
+		}
+		public void GetCurrentMembers(int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember)
+		{
+			//var document = engine.document;
+			var location = document.GetLocation(offset);
+			
+			currentType = null;
+			
+			foreach (var type in unresolvedFile.TopLevelTypeDefinitions) {
+				if (type.Region.Begin < location)
+					currentType = type;
+			}
+			currentType = FindInnerType (currentType, location);
+			
+			// location is beyond last reported end region, now we need to check, if the end region changed
+			if (currentType != null && currentType.Region.End < location) {
+				if (!IsInsideType (currentType, location))
+					currentType = null;
+			}
+			currentMember = null;
+			if (currentType != null) {
+				foreach (var member in currentType.Members) {
+					if (member.Region.Begin < location && (currentMember == null || currentMember.Region.Begin < member.Region.Begin))
+						currentMember = member;
+				}
+			}
+			
+			// location is beyond last reported end region, now we need to check, if the end region changed
+			// NOTE: Enums are a special case, there the "last" field needs to be treated as current member
+			if (currentMember != null && currentMember.Region.End < location && currentType.Kind != TypeKind.Enum) {
+				if (!IsInsideType (currentMember, location))
+					currentMember = null;
+			}/*
+			var stack = GetBracketStack (engine.GetMemberTextToCaret ().Item1);
+			if (stack.Count == 0)
+				currentMember = null;*/
+		}
+
+		IUnresolvedTypeDefinition FindInnerType (IUnresolvedTypeDefinition parent, TextLocation location)
+		{
+			if (parent == null)
+				return null;
+			var currentType = parent;
+			foreach (var type in parent.NestedTypes) {
+				if (type.Region.Begin < location  && location < type.Region.End)
+					currentType = FindInnerType (type, location);
+			}
+			
+			return currentType;
+		}
+		
+		bool IsInsideType (IUnresolvedEntity currentType, TextLocation location)
+		{
+			if (currentType.Region.IsEmpty)
+				return false;
+			int startOffset = document.GetOffset (currentType.Region.Begin);
+			int endOffset = document.GetOffset (location);
+			//bool foundEndBracket = false;
+		
+			var bracketStack = new Stack<char> ();
+		
+			bool isInString = false, isInChar = false;
+			bool isInLineComment = false, isInBlockComment = false;
+			
+			for (int i = startOffset; i < endOffset; i++) {
+				char ch = document.GetCharAt (i);
+				switch (ch) {
+					case '(':
+					case '[':
+					case '{':
+						if (!isInString && !isInChar && !isInLineComment && !isInBlockComment)
+							bracketStack.Push (ch);
+						break;
+					case ')':
+					case ']':
+					case '}':
+						if (!isInString && !isInChar && !isInLineComment && !isInBlockComment)
+						if (bracketStack.Count > 0)
+							bracketStack.Pop ();
+						break;
+					case '/':
+						if (isInBlockComment) {
+							if (i > 0 && document.GetCharAt (i - 1) == '*') 
+								isInBlockComment = false;
+						} else if (!isInString && !isInChar && i + 1 < document.TextLength) {
+							char nextChar = document.GetCharAt (i + 1);
+							if (nextChar == '/')
+								isInLineComment = true;
+							if (!isInLineComment && nextChar == '*')
+								isInBlockComment = true;
+						}
+						break;
+					case '"':
+						if (!(isInChar || isInLineComment || isInBlockComment)) 
+							isInString = !isInString;
+						break;
+					case '\'':
+						if (!(isInString || isInLineComment || isInBlockComment)) 
+							isInChar = !isInChar;
+						break;
+					default :			
+						if (NewLine.IsNewLine(ch)) {
+							isInLineComment = false;
+						}
+						break;
+					}
+				}
+			return bracketStack.Any (t => t == '{');
+		}
+	
+		public Tuple<string, TextLocation> GetMemberTextToCaret(int caretOffset, IUnresolvedTypeDefinition currentType, IUnresolvedMember currentMember)
+		{
+			int startOffset;
+			if (currentMember != null && currentType != null && currentType.Kind != TypeKind.Enum) {
+				startOffset = document.GetOffset(currentMember.Region.Begin);
+			} else if (currentType != null) {
+				startOffset = document.GetOffset(currentType.Region.Begin);
+			} else {
+				startOffset = 0;
+			}
+			while (startOffset > 0) {
+				char ch = document.GetCharAt(startOffset - 1);
+				if (ch != ' ' && ch != '\t') {
+					break;
+				}
+				--startOffset;
+			}
+
+			return Tuple.Create (document.GetText (startOffset, caretOffset - startOffset), document.GetLocation (startOffset));
+		}
+
+
+		public CSharpAstResolver GetResolver (CSharpResolver resolver, AstNode rootNode)
+		{
+			return new CSharpAstResolver (resolver, rootNode, unresolvedFile);
+		}
+
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/ICompletionDataFactory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/ICompletionDataFactory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/ICompletionDataFactory.cs	(revision 11807)
@@ -0,0 +1,89 @@
+﻿// 
+// ICompletionDataFactory.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Completion;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	public interface ICompletionDataFactory
+	{
+		ICompletionData CreateEntityCompletionData (IEntity entity);
+		ICompletionData CreateEntityCompletionData (IEntity entity, string text);
+		
+		ICompletionData CreateTypeCompletionData (IType type, bool showFullName, bool isInAttributeContext, bool addForTypeCreation);
+
+		/// <summary>
+		/// Creates the member completion data. 
+		/// Form: Type.Member
+		/// Used for generating enum members Foo.A, Foo.B where the enum 'Foo' is valid.
+		/// </summary>
+		ICompletionData CreateMemberCompletionData(IType type, IEntity member);
+
+		/// <summary>
+		/// Creates a generic completion data.
+		/// </summary>
+		/// <param name='title'>
+		/// The title of the completion data
+		/// </param>
+		/// <param name='description'>
+		/// The description of the literal.
+		/// </param>
+		/// <param name='insertText'>
+		/// The insert text. If null, title is taken.
+		/// </param>
+		ICompletionData CreateLiteralCompletionData (string title, string description = null, string insertText = null);
+		
+		ICompletionData CreateNamespaceCompletionData (INamespace name);
+		
+		ICompletionData CreateVariableCompletionData (IVariable variable);
+
+		ICompletionData CreateVariableCompletionData (ITypeParameter parameter);
+		
+		ICompletionData CreateEventCreationCompletionData (string delegateMethodName, IType delegateType, IEvent evt, string parameterDefinition, IUnresolvedMember currentMember, IUnresolvedTypeDefinition currentType);
+
+		ICompletionData CreateNewOverrideCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IMember m);
+		ICompletionData CreateNewPartialCompletionData (int declarationBegin, IUnresolvedTypeDefinition type, IUnresolvedMember m);
+		
+		IEnumerable<ICompletionData> CreateCodeTemplateCompletionData ();
+		
+		IEnumerable<ICompletionData> CreatePreProcessorDefinesCompletionData ();
+
+		/// <summary>
+		/// Creates a completion data that adds the required using for the created type.
+		/// </summary>
+		/// <param name="type">The type to import</param>
+		/// <param name="useFullName">If set to true the full name of the type needs to be used.</param>
+		/// <param name="addForTypeCreation">If true the completion data is used in 'new' context.</param>
+		ICompletionData CreateImportCompletionData(IType type, bool useFullName, bool addForTypeCreation);
+
+		ICompletionData CreateFormatItemCompletionData(string format, string description, object example);
+
+		ICompletionData CreateXmlDocCompletionData (string tag, string description = null, string tagInsertionText = null);
+
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/IParameterCompletionDataFactory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/IParameterCompletionDataFactory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Completion/IParameterCompletionDataFactory.cs	(revision 11807)
@@ -0,0 +1,54 @@
+// 
+// IParameterCopmletionFactory.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Completion;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp.Completion
+{
+	public interface IParameterCompletionDataFactory
+	{
+		IParameterDataProvider CreateConstructorProvider (int startOffset, IType type);
+
+		/// <summary>
+		/// Creates a constructor provider skipping the parent of thisInitializer.
+		/// </summary>
+		IParameterDataProvider CreateConstructorProvider (int startOffset, IType type, AstNode thisInitializer);
+
+		IParameterDataProvider CreateMethodDataProvider (int startOffset, IEnumerable<IMethod> methods);
+
+		IParameterDataProvider CreateDelegateDataProvider (int startOffset, IType type);
+		
+		IParameterDataProvider CreateIndexerParameterDataProvider (int startOffset, IType type, IEnumerable<IProperty> accessibleIndexers, AstNode resolvedNode);
+		
+		IParameterDataProvider CreateTypeParameterDataProvider (int startOffset, IEnumerable<IType> types);
+
+		IParameterDataProvider CreateTypeParameterDataProvider (int startOffset, IEnumerable<IMethod> methods);
+	}
+	
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/CSharpFormatter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/CSharpFormatter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/CSharpFormatter.cs	(revision 11807)
@@ -0,0 +1,159 @@
+//
+// CSharpFormatter.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Editor;
+using System.Threading;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum FormattingMode {
+		OnTheFly,
+		Intrusive
+	}
+
+	/// <summary>
+	/// The C# Formatter generates a set of text replace actions to format a region in a C# document.
+	/// </summary>
+	public class CSharpFormatter
+	{
+		readonly CSharpFormattingOptions policy;
+		readonly TextEditorOptions options;
+
+		/// <summary>
+		/// Gets the formatting policy the formatter uses.
+		/// </summary>
+		public CSharpFormattingOptions Policy {
+			get {
+				return policy;
+			}
+		}
+
+		/// <summary>
+		/// Gets the text editor options the formatter uses.
+		/// Note: If none was specified TextEditorOptions.Default gets used.
+		/// </summary>
+		public TextEditorOptions TextEditorOptions {
+			get {
+				return options;
+			}
+		}
+
+		List<DomRegion> formattingRegions = new List<DomRegion> ();
+		internal TextLocation lastFormattingLocation = new TextLocation(int.MaxValue, int.MaxValue);
+
+		/// <summary>
+		/// Gets the formatting regions. NOTE: Will get changed to IReadOnlyList.
+		/// </summary>
+		public IList<DomRegion> FormattingRegions {
+			get {
+				return formattingRegions;
+			}
+		}
+
+		/// <summary>
+		/// Gets or sets the formatting mode. For on the fly formatting a lightweight formatting mode
+		/// gives better results.
+		/// </summary>
+		public FormattingMode FormattingMode {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.CSharpFormatter"/> class.
+		/// </summary>
+		/// <param name="policy">The formatting policy to use.</param>
+		/// <param name="options">The text editor options (optional). Default is: TextEditorOptions.Default</param>
+		public CSharpFormatter(CSharpFormattingOptions policy, TextEditorOptions options = null)
+		{
+			if (policy == null)
+				throw new ArgumentNullException("policy");
+			this.policy = policy;
+			this.options = options ?? TextEditorOptions.Default;
+		}
+
+		/// <summary>
+		/// Format the specified document and gives back the formatted text as result.
+		/// </summary>
+		public string Format(IDocument document)
+		{
+			return InternalFormat (new StringBuilderDocument (document.Text));
+		}
+
+		/// <summary>
+		/// Format the specified text and gives back the formatted text as result.
+		/// </summary>
+		public string Format(string text)
+		{
+			return InternalFormat (new StringBuilderDocument (text));
+		}
+
+		string InternalFormat(IDocument document)
+		{
+			var syntaxTree = SyntaxTree.Parse (document, document.FileName);
+			var changes = AnalyzeFormatting(document, syntaxTree);
+			changes.ApplyChanges();
+			return document.Text;
+		}
+
+		/// <summary>
+		/// Analyzes the formatting of a given document and syntax tree.
+		/// </summary>
+		/// <param name="document">Document.</param>
+		/// <param name="syntaxTree">Syntax tree.</param>
+		/// <param name="token">The cancellation token.</param>
+		public FormattingChanges AnalyzeFormatting(IDocument document, SyntaxTree syntaxTree, CancellationToken token = default (CancellationToken))
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (syntaxTree == null)
+				throw new ArgumentNullException("syntaxTree");
+			var result = new FormattingChanges(document);
+			var visitor = new FormattingVisitor(this, document, result, token);
+			syntaxTree.AcceptVisitor(visitor);
+			return result;
+		}
+
+		/// <summary>
+		/// Adds a region in the document that should be formatted.
+		/// </summary>
+		public void AddFormattingRegion (DomRegion region)
+		{
+			formattingRegions.Add(region);
+			if (formattingRegions.Count == 1) {
+				lastFormattingLocation = region.End;
+			} else {
+				lastFormattingLocation = lastFormattingLocation < region.End ? region.End : lastFormattingLocation;
+			}
+		}
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/CSharpFormattingOptions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/CSharpFormattingOptions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/CSharpFormattingOptions.cs	(revision 11807)
@@ -0,0 +1,1039 @@
+﻿// 
+// CSharpFormattingOptions.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+//  
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Reflection;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum BraceStyle
+	{
+		DoNotChange,
+		EndOfLine,
+		EndOfLineWithoutSpace,
+		NextLine,
+		NextLineShifted,
+		NextLineShifted2,
+		BannerStyle
+	}
+
+	public enum PropertyFormatting
+	{
+		AllowOneLine,
+		ForceOneLine,
+		ForceNewLine
+	}
+
+	public enum Wrapping {
+		DoNotChange,
+		DoNotWrap,
+		WrapAlways,
+		WrapIfTooLong
+	}
+
+	public enum NewLinePlacement {
+		DoNotCare,
+		NewLine,
+		SameLine
+	}
+
+	public enum UsingPlacement {
+		TopOfFile,
+		InsideNamespace
+	}
+
+	public enum EmptyLineFormatting {
+		DoNotChange,
+		Indent,
+		DoNotIndent
+	}
+
+	public class CSharpFormattingOptions
+	{
+		public string Name {
+			get;
+			set;
+		}
+
+		public bool IsBuiltIn {
+			get;
+			set;
+		}
+
+		public CSharpFormattingOptions Clone ()
+		{
+			return (CSharpFormattingOptions)MemberwiseClone ();
+		}
+
+		#region Indentation
+		public bool IndentNamespaceBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentClassBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentInterfaceBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentStructBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentEnumBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentMethodBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentPropertyBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentEventBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentBlocks { // tested
+			get;
+			set;
+		}
+
+		public bool IndentSwitchBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentCaseBody { // tested
+			get;
+			set;
+		}
+
+		public bool IndentBreakStatements { // tested
+			get;
+			set;
+		}
+
+		public bool AlignEmbeddedStatements { // tested
+			get;
+			set;
+		}
+
+		public bool AlignElseInIfStatements {
+			get;
+			set;
+		}
+
+
+
+		public PropertyFormatting AutoPropertyFormatting { // tested
+			get;
+			set;
+		}
+
+		public PropertyFormatting SimplePropertyFormatting { // tested
+			get;
+			set;
+		}
+
+		public EmptyLineFormatting EmptyLineFormatting {
+			get;
+			set;
+		}
+
+		public bool IndentPreprocessorDirectives { // tested
+			get;
+			set;
+		}
+
+		public bool AlignToMemberReferenceDot { // TODO!
+			get;
+			set;
+		}
+
+		public bool IndentBlocksInsideExpressions {
+			get;
+			set;
+		}
+		#endregion
+		
+		#region Braces
+		public BraceStyle NamespaceBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle ClassBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle InterfaceBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle StructBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle EnumBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle MethodBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle AnonymousMethodBraceStyle {
+			get;
+			set;
+		}
+
+		public BraceStyle ConstructorBraceStyle {  // tested
+			get;
+			set;
+		}
+
+		public BraceStyle DestructorBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle PropertyBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle PropertyGetBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle PropertySetBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public PropertyFormatting SimpleGetBlockFormatting { // tested
+			get;
+			set;
+		}
+
+		public PropertyFormatting SimpleSetBlockFormatting { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle EventBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle EventAddBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle EventRemoveBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public bool AllowEventAddBlockInline { // tested
+			get;
+			set;
+		}
+
+		public bool AllowEventRemoveBlockInline { // tested
+			get;
+			set;
+		}
+
+		public BraceStyle StatementBraceStyle { // tested
+			get;
+			set;
+		}
+
+		public bool AllowIfBlockInline {
+			get;
+			set;
+		}
+
+		bool allowOneLinedArrayInitialziers = true;
+		public bool AllowOneLinedArrayInitialziers {
+			get {
+				return allowOneLinedArrayInitialziers;
+			}
+			set {
+				allowOneLinedArrayInitialziers = value;
+			}
+		}
+		#endregion
+
+		#region NewLines
+		public NewLinePlacement ElseNewLinePlacement { // tested
+			get;
+			set;
+		}
+
+		public NewLinePlacement ElseIfNewLinePlacement { // tested
+			get;
+			set;
+		}
+
+		public NewLinePlacement CatchNewLinePlacement { // tested
+			get;
+			set;
+		}
+
+		public NewLinePlacement FinallyNewLinePlacement { // tested
+			get;
+			set;
+		}
+
+		public NewLinePlacement WhileNewLinePlacement { // tested
+			get;
+			set;
+		}
+
+		NewLinePlacement embeddedStatementPlacement = NewLinePlacement.NewLine;
+		public NewLinePlacement EmbeddedStatementPlacement {
+			get {
+				return embeddedStatementPlacement;
+			}
+			set {
+				embeddedStatementPlacement = value;
+			}
+		}
+		#endregion
+		
+		#region Spaces
+		// Methods
+		public bool SpaceBeforeMethodDeclarationParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBetweenEmptyMethodDeclarationParentheses {
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeMethodDeclarationParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterMethodDeclarationParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceWithinMethodDeclarationParentheses { // tested
+			get;
+			set;
+		}
+		
+		// Method calls
+		public bool SpaceBeforeMethodCallParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBetweenEmptyMethodCallParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeMethodCallParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterMethodCallParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceWithinMethodCallParentheses { // tested
+			get;
+			set;
+		}
+		
+		// fields
+		
+		public bool SpaceBeforeFieldDeclarationComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterFieldDeclarationComma { // tested
+			get;
+			set;
+		}
+		
+		// local variables
+		
+		public bool SpaceBeforeLocalVariableDeclarationComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterLocalVariableDeclarationComma { // tested
+			get;
+			set;
+		}
+		
+		// constructors
+		
+		public bool SpaceBeforeConstructorDeclarationParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBetweenEmptyConstructorDeclarationParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeConstructorDeclarationParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterConstructorDeclarationParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceWithinConstructorDeclarationParentheses { // tested
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineBeforeConstructorInitializerColon {
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineAfterConstructorInitializerColon {
+			get;
+			set;
+		}
+		
+		// indexer
+		public bool SpaceBeforeIndexerDeclarationBracket { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceWithinIndexerDeclarationBracket { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeIndexerDeclarationParameterComma {
+			get;
+			set;
+		}
+
+		public bool SpaceAfterIndexerDeclarationParameterComma {
+			get;
+			set;
+		}
+		
+		// delegates
+		
+		public bool SpaceBeforeDelegateDeclarationParentheses {
+			get;
+			set;
+		}
+
+		public bool SpaceBetweenEmptyDelegateDeclarationParentheses {
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeDelegateDeclarationParameterComma {
+			get;
+			set;
+		}
+
+		public bool SpaceAfterDelegateDeclarationParameterComma {
+			get;
+			set;
+		}
+
+		public bool SpaceWithinDelegateDeclarationParentheses {
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeNewParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeIfParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeWhileParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeForParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeForeachParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeCatchParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeSwitchParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeLockParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeUsingParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundAssignment { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundLogicalOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundEqualityOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundRelationalOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundBitwiseOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundAdditiveOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundMultiplicativeOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundShiftOperator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundNullCoalescingOperator { // Tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterUnsafeAddressOfOperator { // Tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterUnsafeAsteriskOfOperator { // Tested
+			get;
+			set;
+		}
+
+		public bool SpaceAroundUnsafeArrowOperator { // Tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinIfParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinWhileParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinForParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinForeachParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinCatchParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinSwitchParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinLockParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinUsingParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinCastParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinSizeOfParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeSizeOfParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinTypeOfParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinNewParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesBetweenEmptyNewParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeNewParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterNewParameterComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeTypeOfParentheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesWithinCheckedExpressionParantheses { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeConditionalOperatorCondition { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterConditionalOperatorCondition { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeConditionalOperatorSeparator { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterConditionalOperatorSeparator { // tested
+			get;
+			set;
+		}
+		
+		// brackets
+		public bool SpacesWithinBrackets { // tested
+			get;
+			set;
+		}
+
+		public bool SpacesBeforeBrackets { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeBracketComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterBracketComma { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeForSemicolon { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterForSemicolon { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceAfterTypecast { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeArrayDeclarationBrackets { // tested
+			get;
+			set;
+		}
+
+		public bool SpaceInNamedArgumentAfterDoubleColon {
+			get;
+			set;
+		}
+
+		public bool RemoveEndOfLineWhiteSpace {
+			get;
+			set;
+		}
+
+		public bool SpaceBeforeSemicolon {
+			get;
+			set;
+		}
+		#endregion
+		
+		#region Blank Lines
+		public int MinimumBlankLinesBeforeUsings {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesAfterUsings {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesBeforeFirstDeclaration {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesBetweenTypes {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesBetweenFields {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesBetweenEventFields {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesBetweenMembers {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesAroundRegion {
+			get;
+			set;
+		}
+
+		public int MinimumBlankLinesInsideRegion {
+			get;
+			set;
+		}
+
+		#endregion
+
+
+		#region Keep formatting
+		public bool KeepCommentsAtFirstColumn {
+			get;
+			set;
+		}
+		#endregion
+
+		#region Wrapping
+
+		public Wrapping ArrayInitializerWrapping {
+			get;
+			set;
+		}
+
+		public BraceStyle ArrayInitializerBraceStyle {
+			get;
+			set;
+		}
+
+		public Wrapping ChainedMethodCallWrapping {
+			get;
+			set;
+		}
+
+		public Wrapping MethodCallArgumentWrapping {
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineAferMethodCallOpenParentheses {
+			get;
+			set;
+		}
+
+		public NewLinePlacement MethodCallClosingParenthesesOnNewLine {
+			get;
+			set;
+		}
+
+		public Wrapping IndexerArgumentWrapping {
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineAferIndexerOpenBracket {
+			get;
+			set;
+		}
+
+		public NewLinePlacement IndexerClosingBracketOnNewLine {
+			get;
+			set;
+		}
+
+		public Wrapping MethodDeclarationParameterWrapping {
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineAferMethodDeclarationOpenParentheses {
+			get;
+			set;
+		}
+
+		public NewLinePlacement MethodDeclarationClosingParenthesesOnNewLine {
+			get;
+			set;
+		}
+
+		public Wrapping IndexerDeclarationParameterWrapping {
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineAferIndexerDeclarationOpenBracket {
+			get;
+			set;
+		}
+
+		public NewLinePlacement IndexerDeclarationClosingBracketOnNewLine {
+			get;
+			set;
+		}
+
+		public bool AlignToFirstIndexerArgument {
+			get;
+			set;
+		}
+
+		public bool AlignToFirstIndexerDeclarationParameter {
+			get;
+			set;
+		}
+
+		public bool AlignToFirstMethodCallArgument {
+			get;
+			set;
+		}
+
+		public bool AlignToFirstMethodDeclarationParameter {
+			get;
+			set;
+		}
+
+		public NewLinePlacement NewLineBeforeNewQueryClause {
+			get;
+			set;
+		}
+
+		#endregion
+
+		#region Using Declarations
+		public UsingPlacement UsingPlacement {
+			get;
+			set;
+		}
+		#endregion
+
+		internal CSharpFormattingOptions()
+		{
+		}
+
+		/*public static CSharpFormattingOptions Load (FilePath selectedFile)
+		{
+			using (var stream = System.IO.File.OpenRead (selectedFile)) {
+				return Load (stream);
+			}
+		}
+
+		public static CSharpFormattingOptions Load (System.IO.Stream input)
+		{
+			CSharpFormattingOptions result = FormattingOptionsFactory.CreateMonoOptions ();
+			result.Name = "noname";
+			using (XmlTextReader reader = new XmlTextReader (input)) {
+				while (reader.Read ()) {
+					if (reader.NodeType == XmlNodeType.Element) {
+						if (reader.LocalName == "Property") {
+							var info = typeof(CSharpFormattingOptions).GetProperty (reader.GetAttribute ("name"));
+							string valString = reader.GetAttribute ("value");
+							object value;
+							if (info.PropertyType == typeof(bool)) {
+								value = Boolean.Parse (valString);
+							} else if (info.PropertyType == typeof(int)) {
+								value = Int32.Parse (valString);
+							} else {
+								value = Enum.Parse (info.PropertyType, valString);
+							}
+							info.SetValue (result, value, null);
+						} else if (reader.LocalName == "FormattingProfile") {
+							result.Name = reader.GetAttribute ("name");
+						}
+					} else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "FormattingProfile") {
+						//Console.WriteLine ("result:" + result.Name);
+						return result;
+					}
+				}
+			}
+			return result;
+		}
+
+		public void Save (string fileName)
+		{
+			using (var writer = new XmlTextWriter (fileName, Encoding.Default)) {
+				writer.Formatting = System.Xml.Formatting.Indented;
+				writer.Indentation = 1;
+				writer.IndentChar = '\t';
+				writer.WriteStartElement ("FormattingProfile");
+				writer.WriteAttributeString ("name", Name);
+				foreach (PropertyInfo info in typeof (CSharpFormattingOptions).GetProperties ()) {
+					if (info.GetCustomAttributes (false).Any (o => o.GetType () == typeof(ItemPropertyAttribute))) {
+						writer.WriteStartElement ("Property");
+						writer.WriteAttributeString ("name", info.Name);
+						writer.WriteAttributeString ("value", info.GetValue (this, null).ToString ());
+						writer.WriteEndElement ();
+					}
+				}
+				writer.WriteEndElement ();
+			}
+		}
+
+		public bool Equals (CSharpFormattingOptions other)
+		{
+			foreach (PropertyInfo info in typeof (CSharpFormattingOptions).GetProperties ()) {
+				if (info.GetCustomAttributes (false).Any (o => o.GetType () == typeof(ItemPropertyAttribute))) {
+					object val = info.GetValue (this, null);
+					object otherVal = info.GetValue (other, null);
+					if (val == null) {
+						if (otherVal == null)
+							continue;
+						return false;
+					}
+					if (!val.Equals (otherVal)) {
+						//Console.WriteLine ("!equal");
+						return false;
+					}
+				}
+			}
+			//Console.WriteLine ("== equal");
+			return true;
+		}*/
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/ConstructFixer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/ConstructFixer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/ConstructFixer.cs	(revision 11807)
@@ -0,0 +1,514 @@
+﻿//
+// ConstructFixer.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Editor;
+using System.Text;
+using System.Reflection;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	abstract class ConstructCompleter
+	{
+		public abstract bool TryFix (ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset);
+
+		protected AstNode GetLastNonErrorChild (AstNode node)
+		{
+			var lastNode = node.LastChild;
+
+			while (lastNode is ErrorNode) {
+				lastNode = lastNode.GetPrevNode(FormattingVisitor.NoWhitespacePredicate);
+			}
+			return lastNode;
+		}
+	}
+
+	class TypeDeclarationCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var typeDeclaration = syntaxTree.GetNodeAt<TypeDeclaration>(location); 
+			if (typeDeclaration != null) {
+				if (typeDeclaration.LBraceToken.IsNull && typeDeclaration.RBraceToken.IsNull) {
+					if (typeDeclaration.Members.Any())
+						return false;
+					var lastNode = GetLastNonErrorChild (typeDeclaration);
+					if (lastNode == null)
+						return false;
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (typeDeclaration, fixer.Options.ClassBraceStyle, false, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class DelegateDeclarationCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var typeDeclaration = syntaxTree.GetNodeAt<DelegateDeclaration>(location); 
+			if (typeDeclaration != null) {
+				if (typeDeclaration.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (typeDeclaration);
+					if (lastNode == null)
+						return false;
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, ");\n");
+					newOffset += ");\n".Length;
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class MethodDeclarationCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var methodDeclaration = syntaxTree.GetNodeAt<MethodDeclaration>(location); 
+			if (methodDeclaration != null) {
+				if (!methodDeclaration.LParToken.IsNull && methodDeclaration.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (methodDeclaration);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, ")\n\t{\t\t\n\t}");
+					newOffset += ")\n\t{\t\t".Length;
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class IfStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var ifStatement = syntaxTree.GetNodeAt<IfElseStatement>(location); 
+			if (ifStatement != null) {
+				if (!ifStatement.LParToken.IsNull && ifStatement.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (ifStatement);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (ifStatement, fixer.Options.StatementBraceStyle, true, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class ForeachStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var ifStatement = syntaxTree.GetNodeAt<ForeachStatement>(location); 
+			if (ifStatement != null) {
+				if (!ifStatement.LParToken.IsNull && ifStatement.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (ifStatement);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (ifStatement, fixer.Options.StatementBraceStyle, true, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class WhileStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var ifStatement = syntaxTree.GetNodeAt<WhileStatement>(location); 
+			if (ifStatement != null) {
+				if (!ifStatement.LParToken.IsNull && ifStatement.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (ifStatement);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (ifStatement, fixer.Options.StatementBraceStyle, true, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class DoWhileStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<DoWhileStatement>(location); 
+			if (stmt != null) {
+				if (!stmt.LParToken.IsNull && stmt.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (stmt);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, ");");
+					newOffset = insertionOffset + 2;
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class FixedStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<FixedStatement>(location); 
+			if (stmt != null) {
+				if (!stmt.LParToken.IsNull && stmt.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (stmt);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (stmt, fixer.Options.StatementBraceStyle, true, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class SwitchStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var switchStatement = syntaxTree.GetNodeAt<SwitchStatement>(location); 
+			if (switchStatement != null) {
+				if (!switchStatement.LParToken.IsNull && switchStatement.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (switchStatement);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (switchStatement, fixer.Options.StatementBraceStyle, true, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class InvocationCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var invocationExpression = syntaxTree.GetNodeAt<InvocationExpression>(location); 
+
+			if (invocationExpression != null) {
+				if (!invocationExpression.LParToken.IsNull && invocationExpression.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (invocationExpression);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+
+					newOffset = insertionOffset;
+
+
+					var text = ")";
+					newOffset++;
+					var expressionStatement = invocationExpression.Parent as ExpressionStatement;
+					if (expressionStatement != null) {
+						if (expressionStatement.SemicolonToken.IsNull)
+							text = ");";
+						newOffset ++;
+					}
+					document.Insert(insertionOffset, text);
+
+
+					return true;
+				}
+
+			}
+			return false;
+		}
+	}
+
+	class BreakStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<BreakStatement>(location); 
+
+			if (stmt != null && stmt.SemicolonToken.IsNull) {
+				// TODO !!!!
+				return true;
+			}
+			return false;
+		}
+	}
+
+	class CheckedStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<CheckedExpression>(location); 
+
+			if (stmt != null && stmt.Parent is ExpressionStatement) {
+				var insertionOffset = document.GetOffset(stmt.EndLocation);
+				document.Insert(insertionOffset, fixer.GenerateBody (stmt, fixer.Options.StatementBraceStyle, false, ref newOffset));
+				return true;
+			}
+			return false;
+		}
+	}
+
+	class UncheckedStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<UncheckedExpression>(location); 
+
+			if (stmt != null && stmt.Parent is ExpressionStatement) {
+				var insertionOffset = document.GetOffset(stmt.EndLocation);
+				document.Insert(insertionOffset, fixer.GenerateBody (stmt, fixer.Options.StatementBraceStyle, false, ref newOffset));
+				return true;
+			}
+			return false;
+		}
+	}
+
+	class ExpressionStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var expressionStatement = syntaxTree.GetNodeAt<ExpressionStatement>(location); 
+
+			if (expressionStatement != null) {
+				int offset = document.GetOffset(expressionStatement.Expression.EndLocation);
+				if (expressionStatement.SemicolonToken.IsNull) {
+					document.Insert(offset, ";");
+					newOffset = offset + 1;
+				}
+				return true;
+			}
+			return false;
+		}
+	}
+
+	class LockStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<LockStatement>(location); 
+			if (stmt != null) {
+				if (!stmt.LParToken.IsNull && stmt.RParToken.IsNull) {
+					var lastNode = GetLastNonErrorChild (stmt);
+					if (lastNode == null)
+						return false;
+
+					var insertionOffset = document.GetOffset(lastNode.EndLocation);
+					document.Insert(insertionOffset, fixer.GenerateBody (stmt, fixer.Options.StatementBraceStyle, true, ref newOffset));
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+
+	class ReturnStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<ReturnStatement>(location); 
+
+			if (stmt != null && stmt.SemicolonToken.IsNull) {
+				var insertionOffset = document.GetOffset(stmt.EndLocation);
+				document.Insert(insertionOffset, ";");
+				newOffset = insertionOffset + 1;
+				return true;
+			}
+			return false;
+		}
+	}
+
+	class YieldReturnStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<YieldReturnStatement>(location); 
+
+			if (stmt != null && stmt.SemicolonToken.IsNull) {
+				var insertionOffset = document.GetOffset(stmt.EndLocation);
+				document.Insert(insertionOffset, ";");
+				newOffset = insertionOffset + 1;
+				return true;
+			}
+			return false;
+		}
+	}
+
+	class ThrowStatementCompleter : ConstructCompleter
+	{
+		public override bool TryFix(ConstructFixer fixer, SyntaxTree syntaxTree, IDocument document, TextLocation location, ref int newOffset)
+		{
+			var stmt = syntaxTree.GetNodeAt<ThrowStatement>(location); 
+
+			if (stmt != null && stmt.SemicolonToken.IsNull) {
+				var insertionOffset = document.GetOffset(stmt.EndLocation);
+				document.Insert(insertionOffset, ";");
+				newOffset = insertionOffset + 1;
+				return true;
+			}
+			return false;
+		}
+	}
+
+
+	public class ConstructFixer
+	{
+		static readonly ConstructCompleter[] completer = {
+			new TypeDeclarationCompleter(),
+			new DelegateDeclarationCompleter (),
+			new MethodDeclarationCompleter (),
+			new IfStatementCompleter (),
+			new ForeachStatementCompleter (),
+			new WhileStatementCompleter (),
+			new LockStatementCompleter (),
+			new FixedStatementCompleter (),
+			new DoWhileStatementCompleter (),
+			new SwitchStatementCompleter (),
+			new BreakStatementCompleter (),
+			new ThrowStatementCompleter (),
+			new ReturnStatementCompleter (),
+			new YieldReturnStatementCompleter (),
+			new CheckedStatementCompleter (),
+			new UncheckedStatementCompleter (),
+
+			new InvocationCompleter (),
+			new ExpressionStatementCompleter ()
+		};
+
+		readonly CSharpFormattingOptions options;
+		readonly TextEditorOptions textEditorOptions;
+
+		public CSharpFormattingOptions Options {
+			get {
+				return options;
+			}
+		}
+
+		public ConstructFixer(CSharpFormattingOptions options, TextEditorOptions textEditorOptions)
+		{
+			this.options = options;
+			this.textEditorOptions = textEditorOptions;
+		}
+		
+
+		string GetIndent(AstNode node)
+		{
+			if (node == null || node is SyntaxTree)
+				return "";
+			if (node is BlockStatement || node is TypeDeclaration || node is NamespaceDeclaration)
+				return "\t" + GetIndent(node.Parent);
+			return GetIndent(node.Parent);
+		}
+
+		internal string GenerateBody(AstNode node, BraceStyle braceStyle, bool addClosingBracket, ref int newOffset)
+		{
+			StringBuilder result = new StringBuilder();
+			if (addClosingBracket)
+				result.Append(")");
+			var nodeIndent = GetIndent(node.Parent);
+			switch (braceStyle) {
+				case BraceStyle.DoNotChange:
+				case BraceStyle.BannerStyle:
+				case BraceStyle.EndOfLine:
+					result.Append(" ");
+					result.Append("{");
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t");
+					break;
+				case BraceStyle.EndOfLineWithoutSpace:
+					result.Append("{");
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t");
+					break;
+				case BraceStyle.NextLine:
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent);
+					result.Append("{");
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t");
+					break;
+				case BraceStyle.NextLineShifted:
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t");
+					result.Append("{");
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t");
+					break;
+				case BraceStyle.NextLineShifted2:
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t");
+					result.Append("{");
+					result.Append(textEditorOptions.EolMarker);
+					result.Append(nodeIndent + "\t" + "\t");
+					break;
+			}
+
+			newOffset += result.Length;
+			result.Append(textEditorOptions.EolMarker);
+			result.Append(nodeIndent);
+			result.Append("}");
+
+			return result.ToString();
+		}
+
+		public bool TryFix (IDocument document, int offset, out int newOffset)
+		{
+			newOffset = offset;
+
+			var syntaxTree = SyntaxTree.Parse(document, "a.cs"); 
+			var location = document.GetLocation(offset - 1);
+			foreach (var c in completer) {
+				if (c.TryFix(this, syntaxTree, document, location, ref newOffset)) {
+					return true;
+				}
+			}
+			return false;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingChanges.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingChanges.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingChanges.cs	(revision 11807)
@@ -0,0 +1,169 @@
+//
+// CSharpFormatter.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Editor;
+using System.Threading;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// The formatting changes are used to format a specific region inside a document and apply a minimal formatting
+	/// changeset to a given document. This is useful for a text editor environment.
+	/// </summary>
+	public class FormattingChanges
+	{
+		readonly IDocument document;
+		readonly internal List<TextReplaceAction> changes = new List<TextReplaceAction> ();
+
+		internal FormattingChanges (IDocument document)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			this.document = document;
+		}
+
+		public int Count {
+			get {
+				return changes.Count;
+			}
+		}
+
+		/// <summary>
+		/// Applies the changes to the input document.
+		/// </summary>
+		public void ApplyChanges()
+		{
+			ApplyChanges(0, document.TextLength, document.Replace, (o, l, v) => document.GetText(o, l) == v);
+		}
+
+		public void ApplyChanges(int startOffset, int length)
+		{
+			ApplyChanges(startOffset, length, document.Replace, (o, l, v) => document.GetText(o, l) == v);
+		}
+
+		/// <summary>
+		/// Applies the changes to the given Script instance.
+		/// </summary>
+		public void ApplyChanges(Script script)
+		{
+			ApplyChanges(0, document.TextLength, script.Replace);
+		}
+
+		public void ApplyChanges(int startOffset, int length, Script script)
+		{
+			ApplyChanges(startOffset, length, script.Replace);
+		}
+
+		public void ApplyChanges(int startOffset, int length, Action<int, int, string> documentReplace, Func<int, int, string, bool> filter = null)
+		{
+			int endOffset = startOffset + length;
+			//			Console.WriteLine ("apply:"+ startOffset + "->" + endOffset);
+			//			Console.WriteLine (document.Text.Substring (0, startOffset) + new string ('x',length) + document.Text.Substring (startOffset+ length));
+
+			TextReplaceAction previousChange = null;
+			int delta = 0;
+			var depChanges = new List<TextReplaceAction> ();
+			foreach (var change in changes.OrderBy(c => c.Offset)) {
+				if (previousChange != null) {
+					if (change.Equals(previousChange)) {
+						// ignore duplicate changes
+						continue;
+					}
+					if (change.Offset < previousChange.Offset + previousChange.RemovalLength) {
+						throw new InvalidOperationException ("Detected overlapping changes " + change + "/" + previousChange);
+					}
+				}
+				previousChange = change;
+				bool skipChange = change.Offset + change.RemovalLength < startOffset || change.Offset > endOffset;
+				skipChange |= filter != null && filter(change.Offset + delta, change.RemovalLength, change.NewText);
+				skipChange &= !depChanges.Contains(change);
+				if (!skipChange) {
+					documentReplace(change.Offset + delta, change.RemovalLength, change.NewText);
+					delta += change.NewText.Length - change.RemovalLength;
+					if (change.DependsOn != null) {
+						depChanges.Add(change.DependsOn);
+					}
+				}
+			}
+			changes.Clear();
+		}
+
+		internal TextReplaceAction AddChange(int offset, int removedChars, string insertedText)
+		{
+			if (offset < 0)
+				throw new ArgumentOutOfRangeException("offset", "Should be >= 0");
+			if (offset >= document.TextLength)
+				throw new ArgumentOutOfRangeException("offset", "Should be < document.TextLength");
+			if (removedChars < 0)
+				throw new ArgumentOutOfRangeException("removedChars", "Should be >= 0");
+			if (removedChars > offset + document.TextLength)
+				throw new ArgumentOutOfRangeException("removedChars", "Tried to remove beyond end of text");
+			if (removedChars == 0 && string.IsNullOrEmpty (insertedText))
+				return null;
+			var action = new TextReplaceAction (offset, removedChars, insertedText);
+			changes.Add(action);
+			return action;
+		}
+		
+		internal sealed class TextReplaceAction
+		{
+			internal readonly int Offset;
+			internal readonly int RemovalLength;
+			internal readonly string NewText;
+			internal TextReplaceAction DependsOn;
+
+			public TextReplaceAction (int offset, int removalLength, string newText)
+			{
+				this.Offset = offset;
+				this.RemovalLength = removalLength;
+				this.NewText = newText ?? string.Empty;
+			}
+
+			public override bool Equals(object obj)
+			{
+				TextReplaceAction other = obj as TextReplaceAction;
+				if (other == null) {
+					return false;
+				}
+				return this.Offset == other.Offset && this.RemovalLength == other.RemovalLength && this.NewText == other.NewText;
+			}
+
+			public override int GetHashCode()
+			{
+				return 0;
+			}
+
+			public override string ToString()
+			{
+				return string.Format("[TextReplaceAction: Offset={0}, RemovalLength={1}, NewText={2}]", Offset, RemovalLength, NewText);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingOptionsFactory.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingOptionsFactory.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingOptionsFactory.cs	(revision 11807)
@@ -0,0 +1,446 @@
+﻿// 
+// FormattingOptionsFactory.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// The formatting options factory creates pre defined formatting option styles.
+	/// </summary>
+	public static class FormattingOptionsFactory
+	{
+		/// <summary>
+		/// Creates empty CSharpFormatting options.
+		/// </summary>
+		public static CSharpFormattingOptions CreateEmpty()
+		{
+			return new CSharpFormattingOptions();
+		}
+
+		/// <summary>
+		/// Creates mono indent style CSharpFormatting options.
+		/// </summary>
+		public static CSharpFormattingOptions CreateMono()
+		{
+			return new CSharpFormattingOptions {
+				IndentNamespaceBody = true,
+				IndentClassBody = true,
+				IndentInterfaceBody = true,
+				IndentStructBody = true,
+				IndentEnumBody = true,
+				IndentMethodBody = true,
+				IndentPropertyBody = true,
+				IndentEventBody = true,
+				IndentBlocks = true,
+				IndentSwitchBody = false,
+				IndentCaseBody = true,
+				IndentBreakStatements = true,
+				IndentPreprocessorDirectives = true,
+				IndentBlocksInsideExpressions = false,
+				NamespaceBraceStyle = BraceStyle.NextLine,
+				ClassBraceStyle = BraceStyle.NextLine,
+				InterfaceBraceStyle = BraceStyle.NextLine,
+				StructBraceStyle = BraceStyle.NextLine,
+				EnumBraceStyle = BraceStyle.NextLine,
+				MethodBraceStyle = BraceStyle.NextLine,
+				ConstructorBraceStyle = BraceStyle.NextLine,
+				DestructorBraceStyle = BraceStyle.NextLine,
+				AnonymousMethodBraceStyle = BraceStyle.EndOfLine,
+	
+				PropertyBraceStyle = BraceStyle.EndOfLine,
+				PropertyGetBraceStyle = BraceStyle.EndOfLine,
+				PropertySetBraceStyle = BraceStyle.EndOfLine,
+				SimpleGetBlockFormatting = PropertyFormatting.AllowOneLine,
+				SimpleSetBlockFormatting = PropertyFormatting.AllowOneLine,
+
+				EventBraceStyle = BraceStyle.EndOfLine,
+				EventAddBraceStyle = BraceStyle.EndOfLine,
+				EventRemoveBraceStyle = BraceStyle.EndOfLine,
+				AllowEventAddBlockInline = true,
+				AllowEventRemoveBlockInline = true,
+				StatementBraceStyle = BraceStyle.EndOfLine,
+	
+				ElseNewLinePlacement = NewLinePlacement.SameLine,
+				ElseIfNewLinePlacement = NewLinePlacement.SameLine,
+				CatchNewLinePlacement = NewLinePlacement.SameLine,
+				FinallyNewLinePlacement = NewLinePlacement.SameLine,
+				WhileNewLinePlacement = NewLinePlacement.SameLine,
+				ArrayInitializerWrapping = Wrapping.WrapIfTooLong,
+				ArrayInitializerBraceStyle = BraceStyle.EndOfLine,
+				AllowOneLinedArrayInitialziers = true,
+
+				SpaceBeforeMethodCallParentheses = true,
+				SpaceBeforeMethodDeclarationParentheses = true,
+				SpaceBeforeConstructorDeclarationParentheses = true,
+				SpaceBeforeDelegateDeclarationParentheses = true,
+				SpaceAfterMethodCallParameterComma = true,
+				SpaceAfterConstructorDeclarationParameterComma = true,
+
+				SpaceBeforeNewParentheses = true,
+				SpacesWithinNewParentheses = false,
+				SpacesBetweenEmptyNewParentheses = false,
+				SpaceBeforeNewParameterComma = false,
+				SpaceAfterNewParameterComma = true,
+				
+				SpaceBeforeIfParentheses = true,
+				SpaceBeforeWhileParentheses = true,
+				SpaceBeforeForParentheses = true,
+				SpaceBeforeForeachParentheses = true,
+				SpaceBeforeCatchParentheses = true,
+				SpaceBeforeSwitchParentheses = true,
+				SpaceBeforeLockParentheses = true,
+				SpaceBeforeUsingParentheses = true,
+				SpaceAroundAssignment = true,
+				SpaceAroundLogicalOperator = true,
+				SpaceAroundEqualityOperator = true,
+				SpaceAroundRelationalOperator = true,
+				SpaceAroundBitwiseOperator = true,
+				SpaceAroundAdditiveOperator = true,
+				SpaceAroundMultiplicativeOperator = true,
+				SpaceAroundShiftOperator = true,
+				SpaceAroundNullCoalescingOperator = true,
+				SpacesWithinParentheses = false,
+				SpaceWithinMethodCallParentheses = false,
+				SpaceWithinMethodDeclarationParentheses = false,
+				SpacesWithinIfParentheses = false,
+				SpacesWithinWhileParentheses = false,
+				SpacesWithinForParentheses = false,
+				SpacesWithinForeachParentheses = false,
+				SpacesWithinCatchParentheses = false,
+				SpacesWithinSwitchParentheses = false,
+				SpacesWithinLockParentheses = false,
+				SpacesWithinUsingParentheses = false,
+				SpacesWithinCastParentheses = false,
+				SpacesWithinSizeOfParentheses = false,
+				SpacesWithinTypeOfParentheses = false,
+				SpacesWithinCheckedExpressionParantheses = false,
+				SpaceBeforeConditionalOperatorCondition = true,
+				SpaceAfterConditionalOperatorCondition = true,
+				SpaceBeforeConditionalOperatorSeparator = true,
+				SpaceAfterConditionalOperatorSeparator = true,
+	
+				SpacesWithinBrackets = false,
+				SpacesBeforeBrackets = true,
+				SpaceBeforeBracketComma = false,
+				SpaceAfterBracketComma = true,
+						
+				SpaceBeforeForSemicolon = false,
+				SpaceAfterForSemicolon = true,
+				SpaceAfterTypecast = false,
+				
+				AlignEmbeddedStatements = true,
+				SimplePropertyFormatting = PropertyFormatting.AllowOneLine,
+				AutoPropertyFormatting = PropertyFormatting.AllowOneLine,
+				EmptyLineFormatting = EmptyLineFormatting.DoNotIndent,
+				SpaceBeforeMethodDeclarationParameterComma = false,
+				SpaceAfterMethodDeclarationParameterComma = true,
+				SpaceAfterDelegateDeclarationParameterComma = true,
+				SpaceBeforeFieldDeclarationComma = false,
+				SpaceAfterFieldDeclarationComma = true,
+				SpaceBeforeLocalVariableDeclarationComma = false,
+				SpaceAfterLocalVariableDeclarationComma = true,
+				
+				SpaceBeforeIndexerDeclarationBracket = true,
+				SpaceWithinIndexerDeclarationBracket = false,
+				SpaceBeforeIndexerDeclarationParameterComma = false,
+				SpaceInNamedArgumentAfterDoubleColon = true,
+				RemoveEndOfLineWhiteSpace = true,
+			
+				SpaceAfterIndexerDeclarationParameterComma = true,
+				
+				MinimumBlankLinesBeforeUsings = 0,
+				MinimumBlankLinesAfterUsings = 1,
+				UsingPlacement = UsingPlacement.TopOfFile,
+				
+				MinimumBlankLinesBeforeFirstDeclaration = 0,
+				MinimumBlankLinesBetweenTypes = 1,
+				MinimumBlankLinesBetweenFields = 0,
+				MinimumBlankLinesBetweenEventFields = 0,
+				MinimumBlankLinesBetweenMembers = 1,
+				MinimumBlankLinesAroundRegion = 1,
+				MinimumBlankLinesInsideRegion = 1,
+				AlignToFirstIndexerArgument = false,
+				AlignToFirstIndexerDeclarationParameter = true,
+				AlignToFirstMethodCallArgument = false,
+				AlignToFirstMethodDeclarationParameter = true,
+				KeepCommentsAtFirstColumn = true,
+				ChainedMethodCallWrapping = Wrapping.DoNotChange,
+				MethodCallArgumentWrapping = Wrapping.DoNotChange,
+				NewLineAferMethodCallOpenParentheses = NewLinePlacement.DoNotCare,
+				MethodCallClosingParenthesesOnNewLine = NewLinePlacement.DoNotCare,
+
+				IndexerArgumentWrapping = Wrapping.DoNotChange,
+				NewLineAferIndexerOpenBracket = NewLinePlacement.DoNotCare,
+				IndexerClosingBracketOnNewLine = NewLinePlacement.DoNotCare,
+
+				NewLineBeforeNewQueryClause = NewLinePlacement.NewLine
+			};
+		}
+
+		/// <summary>
+		/// Creates sharp develop indent style CSharpFormatting options.
+		/// </summary>
+		public static CSharpFormattingOptions CreateSharpDevelop()
+		{
+			var baseOptions = CreateKRStyle();
+			return baseOptions;
+		}
+
+		/// <summary>
+		/// The K&R style, so named because it was used in Kernighan and Ritchie's book The C Programming Language,
+		/// is commonly used in C. It is less common for C++, C#, and others.
+		/// </summary>
+		public static CSharpFormattingOptions CreateKRStyle()
+		{
+			return new CSharpFormattingOptions() {
+				IndentNamespaceBody = true,
+				IndentClassBody = true,
+				IndentInterfaceBody = true,
+				IndentStructBody = true,
+				IndentEnumBody = true,
+				IndentMethodBody = true,
+				IndentPropertyBody = true,
+				IndentEventBody = true,
+				IndentBlocks = true,
+				IndentSwitchBody = true,
+				IndentCaseBody = true,
+				IndentBreakStatements = true,
+				IndentPreprocessorDirectives = true,
+				NamespaceBraceStyle = BraceStyle.NextLine,
+				ClassBraceStyle = BraceStyle.NextLine,
+				InterfaceBraceStyle = BraceStyle.NextLine,
+				StructBraceStyle = BraceStyle.NextLine,
+				EnumBraceStyle = BraceStyle.NextLine,
+				MethodBraceStyle = BraceStyle.NextLine,
+				ConstructorBraceStyle = BraceStyle.NextLine,
+				DestructorBraceStyle = BraceStyle.NextLine,
+				AnonymousMethodBraceStyle = BraceStyle.EndOfLine,
+				PropertyBraceStyle = BraceStyle.EndOfLine,
+				PropertyGetBraceStyle = BraceStyle.EndOfLine,
+				PropertySetBraceStyle = BraceStyle.EndOfLine,
+				SimpleGetBlockFormatting = PropertyFormatting.AllowOneLine,
+				SimpleSetBlockFormatting = PropertyFormatting.AllowOneLine,
+	
+				EventBraceStyle = BraceStyle.EndOfLine,
+				EventAddBraceStyle = BraceStyle.EndOfLine,
+				EventRemoveBraceStyle = BraceStyle.EndOfLine,
+				AllowEventAddBlockInline = true,
+				AllowEventRemoveBlockInline = true,
+				StatementBraceStyle = BraceStyle.EndOfLine,
+	
+				ElseNewLinePlacement = NewLinePlacement.SameLine,
+				ElseIfNewLinePlacement = NewLinePlacement.SameLine,
+				CatchNewLinePlacement = NewLinePlacement.SameLine,
+				FinallyNewLinePlacement = NewLinePlacement.SameLine,
+				WhileNewLinePlacement = NewLinePlacement.SameLine,
+				ArrayInitializerWrapping = Wrapping.WrapIfTooLong,
+				ArrayInitializerBraceStyle = BraceStyle.EndOfLine,
+	
+				SpaceBeforeMethodCallParentheses = false,
+				SpaceBeforeMethodDeclarationParentheses = false,
+				SpaceBeforeConstructorDeclarationParentheses = false,
+				SpaceBeforeDelegateDeclarationParentheses = false,
+				SpaceBeforeIndexerDeclarationBracket = false,
+				SpaceAfterMethodCallParameterComma = true,
+				SpaceAfterConstructorDeclarationParameterComma = true,
+				NewLineBeforeConstructorInitializerColon = NewLinePlacement.NewLine,
+				NewLineAfterConstructorInitializerColon = NewLinePlacement.SameLine,
+				
+				SpaceBeforeNewParentheses = false,
+				SpacesWithinNewParentheses = false,
+				SpacesBetweenEmptyNewParentheses = false,
+				SpaceBeforeNewParameterComma = false,
+				SpaceAfterNewParameterComma = true,
+				
+				SpaceBeforeIfParentheses = true,
+				SpaceBeforeWhileParentheses = true,
+				SpaceBeforeForParentheses = true,
+				SpaceBeforeForeachParentheses = true,
+				SpaceBeforeCatchParentheses = true,
+				SpaceBeforeSwitchParentheses = true,
+				SpaceBeforeLockParentheses = true,
+				SpaceBeforeUsingParentheses = true,
+
+				SpaceAroundAssignment = true,
+				SpaceAroundLogicalOperator = true,
+				SpaceAroundEqualityOperator = true,
+				SpaceAroundRelationalOperator = true,
+				SpaceAroundBitwiseOperator = true,
+				SpaceAroundAdditiveOperator = true,
+				SpaceAroundMultiplicativeOperator = true,
+				SpaceAroundShiftOperator = true,
+				SpaceAroundNullCoalescingOperator = true,
+				SpacesWithinParentheses = false,
+				SpaceWithinMethodCallParentheses = false,
+				SpaceWithinMethodDeclarationParentheses = false,
+				SpacesWithinIfParentheses = false,
+				SpacesWithinWhileParentheses = false,
+				SpacesWithinForParentheses = false,
+				SpacesWithinForeachParentheses = false,
+				SpacesWithinCatchParentheses = false,
+				SpacesWithinSwitchParentheses = false,
+				SpacesWithinLockParentheses = false,
+				SpacesWithinUsingParentheses = false,
+				SpacesWithinCastParentheses = false,
+				SpacesWithinSizeOfParentheses = false,
+				SpacesWithinTypeOfParentheses = false,
+				SpacesWithinCheckedExpressionParantheses = false,
+				SpaceBeforeConditionalOperatorCondition = true,
+				SpaceAfterConditionalOperatorCondition = true,
+				SpaceBeforeConditionalOperatorSeparator = true,
+				SpaceAfterConditionalOperatorSeparator = true,
+				SpaceBeforeArrayDeclarationBrackets = false,
+
+				SpacesWithinBrackets = false,
+				SpacesBeforeBrackets = false,
+				SpaceBeforeBracketComma = false,
+				SpaceAfterBracketComma = true,
+						
+				SpaceBeforeForSemicolon = false,
+				SpaceAfterForSemicolon = true,
+				SpaceAfterTypecast = false,
+				
+				AlignEmbeddedStatements = true,
+				SimplePropertyFormatting = PropertyFormatting.AllowOneLine,
+				AutoPropertyFormatting = PropertyFormatting.AllowOneLine,
+				EmptyLineFormatting = EmptyLineFormatting.DoNotIndent,
+				SpaceBeforeMethodDeclarationParameterComma = false,
+				SpaceAfterMethodDeclarationParameterComma = true,
+				SpaceAfterDelegateDeclarationParameterComma = true,
+				SpaceBeforeFieldDeclarationComma = false,
+				SpaceAfterFieldDeclarationComma = true,
+				SpaceBeforeLocalVariableDeclarationComma = false,
+				SpaceAfterLocalVariableDeclarationComma = true,
+				
+				SpaceWithinIndexerDeclarationBracket = false,
+				SpaceBeforeIndexerDeclarationParameterComma = false,
+				SpaceInNamedArgumentAfterDoubleColon = true,
+			
+				SpaceAfterIndexerDeclarationParameterComma = true,
+				RemoveEndOfLineWhiteSpace = true,
+				
+				MinimumBlankLinesBeforeUsings = 0,
+				MinimumBlankLinesAfterUsings = 1,
+
+				MinimumBlankLinesBeforeFirstDeclaration = 0,
+				MinimumBlankLinesBetweenTypes = 1,
+				MinimumBlankLinesBetweenFields = 0,
+				MinimumBlankLinesBetweenEventFields = 0,
+				MinimumBlankLinesBetweenMembers = 1,
+				MinimumBlankLinesAroundRegion = 1,
+				MinimumBlankLinesInsideRegion = 1,
+	
+				KeepCommentsAtFirstColumn = true,
+				ChainedMethodCallWrapping = Wrapping.DoNotChange,
+				MethodCallArgumentWrapping = Wrapping.DoNotChange,
+				NewLineAferMethodCallOpenParentheses = NewLinePlacement.DoNotCare,
+				MethodCallClosingParenthesesOnNewLine = NewLinePlacement.DoNotCare,
+
+				IndexerArgumentWrapping = Wrapping.DoNotChange,
+				NewLineAferIndexerOpenBracket = NewLinePlacement.DoNotCare,
+				IndexerClosingBracketOnNewLine = NewLinePlacement.DoNotCare,
+
+				NewLineBeforeNewQueryClause = NewLinePlacement.NewLine
+			};
+		}
+
+		/// <summary>
+		/// Creates allman indent style CSharpFormatting options used in Visual Studio.
+		/// </summary>
+		public static CSharpFormattingOptions CreateAllman()
+		{
+			var baseOptions = CreateKRStyle();
+			baseOptions.AnonymousMethodBraceStyle = BraceStyle.NextLine;
+			baseOptions.PropertyBraceStyle = BraceStyle.NextLine;
+			baseOptions.PropertyGetBraceStyle = BraceStyle.NextLine;
+			baseOptions.PropertySetBraceStyle = BraceStyle.NextLine;
+
+			baseOptions.EventBraceStyle = BraceStyle.NextLine;
+			baseOptions.EventAddBraceStyle = BraceStyle.NextLine;
+			baseOptions.EventRemoveBraceStyle = BraceStyle.NextLine;
+			baseOptions.StatementBraceStyle = BraceStyle.NextLine;
+			baseOptions.ArrayInitializerBraceStyle = BraceStyle.NextLine;
+
+			baseOptions.CatchNewLinePlacement = NewLinePlacement.NewLine;
+			baseOptions.ElseNewLinePlacement = NewLinePlacement.NewLine;
+			baseOptions.ElseIfNewLinePlacement = NewLinePlacement.SameLine;
+
+			baseOptions.FinallyNewLinePlacement = NewLinePlacement.NewLine;
+			baseOptions.WhileNewLinePlacement = NewLinePlacement.DoNotCare;
+			baseOptions.ArrayInitializerWrapping = Wrapping.DoNotChange;
+			baseOptions.IndentBlocksInsideExpressions = true;
+
+			return baseOptions;
+		}
+
+		/// <summary>
+		/// The Whitesmiths style, also called Wishart style to a lesser extent, is less common today than the previous three. It was originally used in the documentation for the first commercial C compiler, the Whitesmiths Compiler.
+		/// </summary>
+		public static CSharpFormattingOptions CreateWhitesmiths()
+		{
+			var baseOptions = CreateKRStyle();
+				
+			baseOptions.NamespaceBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.ClassBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.InterfaceBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.StructBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.EnumBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.MethodBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.ConstructorBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.DestructorBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.AnonymousMethodBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.PropertyBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.PropertyGetBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.PropertySetBraceStyle = BraceStyle.NextLineShifted;
+	
+			baseOptions.EventBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.EventAddBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.EventRemoveBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted;
+			baseOptions.IndentBlocksInsideExpressions = true;
+			return baseOptions;
+		}
+
+		/// <summary>
+		/// Like the Allman and Whitesmiths styles, GNU style puts braces on a line by themselves, indented by 2 spaces,
+		/// except when opening a function definition, where they are not indented.
+		/// In either case, the contained code is indented by 2 spaces from the braces.
+		/// Popularised by Richard Stallman, the layout may be influenced by his background of writing Lisp code.
+		/// In Lisp the equivalent to a block (a progn) 
+		/// is a first class data entity and giving it its own indent level helps to emphasize that,
+		/// whereas in C a block is just syntax.
+		/// Although not directly related to indentation, GNU coding style also includes a space before the bracketed 
+		/// list of arguments to a function.
+		/// </summary>
+		public static CSharpFormattingOptions CreateGNU()
+		{
+			var baseOptions = CreateAllman();
+			baseOptions.StatementBraceStyle = BraceStyle.NextLineShifted2;
+			return baseOptions;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor.cs	(revision 11807)
@@ -0,0 +1,662 @@
+﻿// 
+// FormattingVisitor.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Text;
+using System.Linq;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Threading;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[Obsolete("This class was replaced by CSharpFormatter.")]
+	public class AstFormattingVisitor {}
+
+	partial class FormattingVisitor  
+	{
+		readonly CSharpFormatter formatter;
+		readonly FormattingChanges changes;
+		readonly IDocument document;
+		readonly CancellationToken token;
+
+		Indent curIndent;
+
+		public bool HadErrors {
+			get;
+			set;
+		}
+		
+
+		CSharpFormattingOptions policy {
+			get {
+				return formatter.Policy;
+			}
+		}
+
+		TextEditorOptions options {
+			get {
+				return formatter.TextEditorOptions;
+			}
+		}
+
+		FormattingChanges.TextReplaceAction AddChange(int offset, int removedChars, string insertedText)
+		{
+			return changes.AddChange(offset, removedChars, insertedText);
+		}
+
+		public FormattingVisitor(CSharpFormatter formatter, IDocument document, FormattingChanges changes, CancellationToken token)
+		{
+			if (formatter == null)
+				throw new ArgumentNullException("formatter");
+			if (document == null)
+				throw new ArgumentNullException("document");
+			if (changes == null)
+				throw new ArgumentNullException("changes");
+		
+			this.formatter = formatter;
+			this.changes = changes;
+			this.document = document;
+			this.token = token;
+
+			curIndent = new Indent(formatter.TextEditorOptions);
+		}
+		
+		void VisitChildrenToFormat (AstNode parent, Action<AstNode> callback)
+		{
+			AstNode next;
+			for (var child = parent.FirstChild; child != null; child = next) {
+				token.ThrowIfCancellationRequested();
+				// Store next to allow the loop to continue
+				// if the visitor removes/replaces child.
+				next = child.GetNextSibling(NoWhitespacePredicate);
+				
+				if (formatter.FormattingRegions.Count > 0) {
+					if (formatter.FormattingRegions.Any(r => r.IsInside(child.StartLocation) || r.IsInside(child.EndLocation))) {
+						callback(child);
+					} else {
+						var childRegion = child.Region;
+						if (formatter.FormattingRegions.Any(r => childRegion.IsInside(r.Begin) || childRegion.IsInside(r.End)))
+						    callback(child);
+					}
+					if (child.StartLocation > formatter.lastFormattingLocation)
+						break;
+				} else {
+					callback(child);
+				}
+			}
+		}
+		
+		protected override void VisitChildren (AstNode node)
+		{
+			VisitChildrenToFormat (node, n => n.AcceptVisitor (this));
+		}
+
+		#region NewLines
+
+		void AdjustNewLineBlock(AstNode startNode, int targetMinimumNewLineCount)
+		{
+			var indentString = policy.EmptyLineFormatting == EmptyLineFormatting.Indent ? curIndent.IndentString : "";
+
+			TextLocation newLineInsertPosition = startNode.EndLocation;
+			var node = startNode.NextSibling;
+			int currentNewLineCount = 0;
+			// Check the existing newlines
+			for (; currentNewLineCount < targetMinimumNewLineCount; node = node.NextSibling) {
+				if (node is WhitespaceNode)
+					continue;
+				if (!(node is NewLineNode))
+					break;
+				newLineInsertPosition = node.EndLocation;
+				currentNewLineCount++;
+				if (policy.EmptyLineFormatting == EmptyLineFormatting.DoNotChange) {
+					if (node.NextSibling == null)
+						// end of file/block etc, nothing more to do but break before assigning null to node
+						break;
+					continue;
+				}
+				var isBlankLine = IsSpacing(document.GetLineByNumber(node.StartLocation.Line));
+				if (!isBlankLine) {
+					// remove EOL whitespace if appropriate
+					if (policy.RemoveEndOfLineWhiteSpace) {
+						var offset = document.GetOffset(node.StartLocation);
+						var start = SearchWhitespaceStart(offset);
+						if (start != offset)
+							AddChange(start, offset - start, null);
+					}
+				} else {
+					var actualIndent = GetIndentation(node.StartLocation.Line);
+					if (actualIndent != indentString) {
+						var start = document.GetOffset(new TextLocation(node.StartLocation.Line, 0));
+						AddChange(start, actualIndent.Length, indentString);
+					}
+				}
+				if (node.NextSibling == null)
+					// end of file/block etc, nothing more to do but break before assigning null to node
+					break;
+			}
+			if (currentNewLineCount < targetMinimumNewLineCount) {
+				// We need to add more newlines
+				var builder = new StringBuilder();
+				for (; currentNewLineCount < targetMinimumNewLineCount; currentNewLineCount++) {
+					if (currentNewLineCount > 0)
+						// Don't indent the first line in the block since that is not an empty line.
+						builder.Append(indentString);
+					builder.Append(options.EolMarker);
+				}
+				var offset = document.GetOffset(newLineInsertPosition);
+				if (offset >= 0)
+					AddChange(offset, 0, builder.ToString());
+			} else if (currentNewLineCount == targetMinimumNewLineCount && node is NewLineNode){
+//				// Check to see if there are any newlines to remove
+//				var endNode = node.GetNextSibling(n => !(n is NewLineNode || n is WhitespaceNode));
+//				if (endNode != null) {
+//					var startOffset = document.GetOffset(newLineInsertPosition);
+//					var endOffset = document.GetOffset(new TextLocation(endNode.StartLocation.Line, 0));
+//					EnsureText(startOffset, endOffset, null);
+//				}
+			}
+		}
+
+		public void EnsureMinimumNewLinesAfter(AstNode node, int blankLines)
+		{
+			if (node is PreProcessorDirective) {
+				var directive = (PreProcessorDirective)node;
+				if (directive.Type == PreProcessorDirectiveType.Pragma)
+					return;
+			}
+			if (blankLines < 0)
+				return;
+			if (formatter.FormattingMode != FormattingMode.Intrusive)
+				blankLines = Math.Min(1, blankLines);
+			AdjustNewLineBlock(node, blankLines);
+		}
+		
+		public void EnsureMinimumBlankLinesBefore(AstNode node, int blankLines)
+		{
+			if (formatter.FormattingMode != FormattingMode.Intrusive)
+				return;
+			var loc = node.StartLocation;
+			int line = loc.Line;
+			do {
+				line--;
+			} while (line > 0 && IsSpacing(document.GetLineByNumber(line)));
+			if (line > 0 && !IsSpacing(document.GetLineByNumber(line)))
+			    line++;
+
+			if (loc.Line - line >= blankLines)
+				return;
+
+			var sb = new StringBuilder ();
+			for (int i = 0; i < blankLines; i++)
+				sb.Append(options.EolMarker);
+			int end = document.GetOffset(loc.Line, 1);
+			if (loc.Line == line) {
+				AddChange(end, 0, sb.ToString());
+				return;
+			}
+			if (line + 1 > document.LineCount)
+				return;
+			int start = document.GetOffset(line + 1, 1);
+			if (end - start <= 0 && sb.Length == 0)
+				return;
+			AddChange(start, end - start, sb.ToString());
+		}
+
+		#endregion
+
+		bool IsSimpleAccessor(Accessor accessor)
+		{
+			if (accessor.IsNull || accessor.Body.IsNull || accessor.Body.FirstChild == null) {
+				return true;
+			}
+			var firstStatement = accessor.Body.Statements.FirstOrDefault();
+			if (firstStatement == null)
+				return true;
+
+			if (!(firstStatement is ReturnStatement || firstStatement is ExpressionStatement|| firstStatement is EmptyStatement || firstStatement is ThrowStatement))
+				return false;
+
+			if (firstStatement.GetNextSibling(s => s.Role == BlockStatement.StatementRole) != null)
+				return false;
+
+			return !(accessor.Body.Statements.FirstOrDefault() is BlockStatement);
+		}
+		
+		static bool IsSpacing(char ch)
+		{
+			return ch == ' ' || ch == '\t';
+		}
+		
+		bool IsSpacing(ISegment segment)
+		{
+			int endOffset = segment.EndOffset;
+			for (int i = segment.Offset; i < endOffset; i++) {
+				if (!IsSpacing(document.GetCharAt(i))) {
+					return false;
+				}
+			}
+			return true;
+		}
+		
+		int SearchLastNonWsChar(int startOffset, int endOffset)
+		{
+			startOffset = Math.Max(0, startOffset);
+			endOffset = Math.Max(startOffset, endOffset);
+			if (startOffset >= endOffset) {
+				return startOffset;
+			}
+			int result = -1;
+			bool inComment = false;
+			
+			for (int i = startOffset; i < endOffset && i < document.TextLength; i++) {
+				char ch = document.GetCharAt(i);
+				if (IsSpacing(ch)) {
+					continue;
+				}
+				if (ch == '/' && i + 1 < document.TextLength && document.GetCharAt(i + 1) == '/') {
+					return result;
+				}
+				if (ch == '/' && i + 1 < document.TextLength && document.GetCharAt(i + 1) == '*') {
+					inComment = true;
+					i++;
+					continue;
+				}
+				if (inComment && ch == '*' && i + 1 < document.TextLength && document.GetCharAt(i + 1) == '/') {
+					inComment = false;
+					i++;
+					continue;
+				}
+				if (!inComment) {
+					result = i;
+				}
+			}
+			return result;
+		}
+		
+		void ForceSpace(int startOffset, int endOffset, bool forceSpace)
+		{
+			int lastNonWs = SearchLastNonWsChar(startOffset, endOffset);
+			if (lastNonWs < 0)
+				return;
+
+			var spaceCount = Math.Max(0, endOffset - lastNonWs - 1);
+			if (forceSpace) {
+				if (spaceCount != 1) {
+					// Here we could technically remove spaceCount - 1 chars instead
+					// and skip replacing that with new space, but we want to trigger the
+					// overlap detection if this space is changed again for some reason
+					AddChange(lastNonWs + 1, spaceCount, " ");
+				}
+			} else if (spaceCount > 0 && !forceSpace) {
+				AddChange(lastNonWs + 1, spaceCount, "");
+			}
+		}
+		
+		void ForceSpacesAfter(AstNode n, bool forceSpaces)
+		{
+			if (n == null) {
+				return;
+			}
+			TextLocation location = n.EndLocation;
+			int offset = document.GetOffset(location);
+			if (location.Column > document.GetLineByNumber(location.Line).Length) {
+				return;
+			}
+			int i = offset;
+			while (i < document.TextLength && IsSpacing (document.GetCharAt (i))) {
+				i++;
+			}
+			ForceSpace(offset - 1, i, forceSpaces);
+		}
+
+		int ForceSpacesBefore(AstNode n, bool forceSpaces)
+		{
+			if (n == null || n.IsNull) {
+				return 0;
+			}
+			TextLocation location = n.StartLocation;
+			// respect manual line breaks.
+			if (location.Column <= 1 || GetIndentation(location.Line).Length == location.Column - 1) {
+				return 0;
+			}
+			
+			int offset = document.GetOffset(location);
+			int i = offset - 1;
+			while (i >= 0 && IsSpacing (document.GetCharAt (i))) {
+				i--;
+			}
+			ForceSpace(i, offset, forceSpaces);
+			return i;
+		}
+		
+		int ForceSpacesBeforeRemoveNewLines(AstNode n, bool forceSpace = true)
+		{
+			if (n == null || n.IsNull) {
+				return 0;
+			}
+			int offset = document.GetOffset(n.StartLocation);
+			int i = offset - 1;
+			while (i >= 0) {
+				char ch = document.GetCharAt(i);
+				if (!IsSpacing(ch) && ch != '\r' && ch != '\n')
+					break;
+				i--;
+			}
+			var length = Math.Max(0, (offset - 1) - i);
+			AddChange(i + 1, length, forceSpace ? " " : "");
+			return i;
+		}
+
+		internal static bool NoWhitespacePredicate(AstNode arg)
+		{
+			return !(arg is NewLineNode || arg is WhitespaceNode);
+		}
+
+		static bool IsMember(AstNode nextSibling)
+		{
+			return nextSibling != null && nextSibling.NodeType == NodeType.Member;
+		}
+
+		static bool ShouldBreakLine(NewLinePlacement placement, CSharpTokenNode token)
+		{
+			if (placement == NewLinePlacement.NewLine)
+				return true;
+			if (placement == NewLinePlacement.SameLine)
+				return false;
+			if (token.IsNull)
+				return false;
+			var prevMeaningfulNode = token.GetPrevNode (n =>n.Role !=Roles.NewLine && n.Role != Roles.Whitespace && n.Role !=Roles.Comment);
+			return prevMeaningfulNode.EndLocation.Line != token.StartLocation.Line;
+		}
+
+		void ForceSpaceBefore(AstNode node, bool forceSpace)
+		{
+			var offset = document.GetOffset(node.StartLocation);
+			int end = offset;
+			// ForceSpace inserts a space one char after start in the case of a missing space
+			// Therefore, make sure that start < offset by starting at offset - 1
+			int start = SearchWhitespaceStart(offset - 1);
+			ForceSpace(start, end, forceSpace);
+		}
+
+		public void FixSemicolon(CSharpTokenNode semicolon)
+		{
+			if (semicolon.IsNull)
+				return;
+			int endOffset = document.GetOffset(semicolon.StartLocation);
+			int offset = endOffset;
+			while (offset - 1 > 0 && char.IsWhiteSpace (document.GetCharAt (offset - 1))) {
+				offset--;
+			}
+			if (policy.SpaceBeforeSemicolon) {
+				AddChange(offset, endOffset - offset, " ");
+			} else {
+				if (offset < endOffset)
+					AddChange(offset, endOffset - offset, null);
+			}
+		}
+		
+		void PlaceOnNewLine(NewLinePlacement newLine, AstNode keywordNode)
+		{
+			if (keywordNode == null || keywordNode.StartLocation.IsEmpty)
+				return;
+			
+			var prev = keywordNode.GetPrevNode (NoWhitespacePredicate);
+			if (prev is Comment || prev is PreProcessorDirective)
+				return;
+
+			if (newLine == NewLinePlacement.DoNotCare)
+				newLine = prev.EndLocation.Line == keywordNode.StartLocation.Line ? NewLinePlacement.SameLine : NewLinePlacement.NewLine;
+
+			int offset = document.GetOffset(keywordNode.StartLocation);
+			
+			int whitespaceStart = SearchWhitespaceStart(offset);
+			string indentString = newLine == NewLinePlacement.NewLine ? options.EolMarker + curIndent.IndentString : " ";
+			AddChange(whitespaceStart, offset - whitespaceStart, indentString);
+		}
+		
+		string nextStatementIndent;
+		
+		void FixStatementIndentation(TextLocation location)
+		{
+			if (location.Line < 1 || location.Column < 1) {
+				Console.WriteLine("invalid location!");
+				return;
+			}
+			int offset = document.GetOffset(location);
+			if (offset <= 0) {
+				Console.WriteLine("possible wrong offset");
+				Console.WriteLine(Environment.StackTrace);
+				return;
+			}
+			bool isEmpty = IsLineIsEmptyUpToEol(offset);
+			int lineStart = SearchWhitespaceLineStart(offset);
+			string indentString = nextStatementIndent ?? (isEmpty ? "" : options.EolMarker) + curIndent.IndentString;
+			nextStatementIndent = null;
+			EnsureText(lineStart, offset, indentString);
+		}
+
+		void FixIndentation (AstNode node)
+		{
+			FixIndentation(node.StartLocation, 0);
+		}
+		
+		void FixIndentation(TextLocation location, int relOffset)
+		{
+			if (location.Line < 1 || location.Line > document.LineCount) {
+				Console.WriteLine("Invalid location " + location);
+				Console.WriteLine(Environment.StackTrace);
+				return;
+			}
+			
+			string lineIndent = GetIndentation(location.Line);
+			string indentString = curIndent.IndentString;
+			if (indentString != lineIndent && location.Column - 1 + relOffset == lineIndent.Length) {
+				AddChange(document.GetOffset(location.Line, 1), lineIndent.Length, indentString);
+			}
+		}
+		
+		void FixIndentationForceNewLine(AstNode node)
+		{
+			var directive = node as PreProcessorDirective;
+			if (node.GetPrevNode () is NewLineNode) {
+				if (directive != null && !policy.IndentPreprocessorDirectives) {
+					var startNode = node.GetPrevNode ();
+					var startOffset = document.GetOffset(startNode.EndLocation);
+					int endOffset = document.GetOffset(node.StartLocation);
+					AddChange(startOffset, endOffset - startOffset, "");
+					return;
+				} else {
+					FixIndentation(node);
+				}
+			} else {
+				// if no new line preceeds an #endif directive it's excluded
+				if (directive != null) {
+					if (directive.Type == PreProcessorDirectiveType.Endif)
+						return;
+				}
+				var startNode = node.GetPrevSibling(n => !(n is WhitespaceNode)) ?? node;
+				var startOffset = document.GetOffset(startNode.EndLocation);
+				int endOffset = document.GetOffset(node.StartLocation);
+				if (startOffset >= endOffset)
+					return;
+				if (directive != null && !policy.IndentPreprocessorDirectives) {
+					AddChange(startOffset, endOffset - startOffset, "");
+					return;
+				}
+
+				AddChange(startOffset, endOffset - startOffset, curIndent.IndentString);
+			}
+		}
+
+		string GetIndentation(int lineNumber)
+		{
+			var line = document.GetLineByNumber(lineNumber);
+			var b = new StringBuilder ();
+			int endOffset = line.EndOffset;
+			for (int i = line.Offset; i < endOffset; i++) {
+				char c = document.GetCharAt(i);
+				if (!IsSpacing(c)) {
+					break;
+				}
+				b.Append(c);
+			}
+			return b.ToString();
+		}
+
+		void EnsureText(int start, int end, string replacementText)
+		{
+			var length = end - start;
+			if (length == 0 && string.IsNullOrEmpty(replacementText))
+				return;
+			if (replacementText == null || replacementText.Length != length) {
+				AddChange(start, length, replacementText);
+				return;
+			}
+			for (int i = 0; i < length; i++) {
+				if (document.GetCharAt(start + i) != replacementText[i]) {
+					AddChange(start, length, replacementText);
+					break;
+				}
+			}
+		}
+		
+		void FixOpenBrace(BraceStyle braceStyle, AstNode lbrace)
+		{
+			if (lbrace.IsNull)
+				return;
+			switch (braceStyle) {
+				case BraceStyle.DoNotChange:
+					return;
+
+				case BraceStyle.BannerStyle:
+				case BraceStyle.EndOfLine:
+					var prev = lbrace.GetPrevNode (NoWhitespacePredicate);
+					if (prev is PreProcessorDirective)
+						return;
+					int prevOffset = document.GetOffset(prev.EndLocation);
+
+					if (prev is Comment || prev is PreProcessorDirective) {
+						int next = document.GetOffset(lbrace.GetNextNode ().StartLocation);
+						EnsureText(prevOffset, next, "");
+						while (prev is Comment || prev is PreProcessorDirective)
+							prev = prev.GetPrevNode();
+						prevOffset = document.GetOffset(prev.EndLocation);
+						AddChange(prevOffset, 0, " {");
+					} else {
+						int braceOffset2 = document.GetOffset(lbrace.StartLocation);
+						EnsureText(prevOffset, braceOffset2, " ");
+					}
+					break;
+				case BraceStyle.EndOfLineWithoutSpace:
+					prev = lbrace.GetPrevNode (NoWhitespacePredicate);
+					if (prev is PreProcessorDirective)
+						return;
+					prevOffset = document.GetOffset(prev.EndLocation);
+					int braceOffset = document.GetOffset(lbrace.StartLocation);
+					EnsureText(prevOffset, braceOffset, "");
+					break;
+
+				case BraceStyle.NextLine:
+					prev = lbrace.GetPrevNode (NoWhitespacePredicate);
+					if (prev is PreProcessorDirective)
+						return;
+					prevOffset = document.GetOffset(prev.EndLocation);
+					braceOffset = document.GetOffset(lbrace.StartLocation);
+					EnsureText(prevOffset, braceOffset, options.EolMarker + curIndent.IndentString);
+					break;
+				case BraceStyle.NextLineShifted:
+					prev = lbrace.GetPrevNode (NoWhitespacePredicate);
+					if (prev is PreProcessorDirective)
+						return;
+					prevOffset = document.GetOffset(prev.EndLocation);
+					braceOffset = document.GetOffset(lbrace.StartLocation);
+					curIndent.Push(IndentType.Block);
+					EnsureText(prevOffset, braceOffset, options.EolMarker + curIndent.IndentString);
+					curIndent.Pop();
+					break;
+				case BraceStyle.NextLineShifted2:
+					prev = lbrace.GetPrevNode (NoWhitespacePredicate);
+					if (prev is PreProcessorDirective)
+						return;
+					prevOffset = document.GetOffset(prev.EndLocation);
+					braceOffset = document.GetOffset(lbrace.StartLocation);
+					curIndent.Push(IndentType.Block);
+					EnsureText(prevOffset, braceOffset, options.EolMarker + curIndent.IndentString);
+					curIndent.Pop();
+					break;
+			}
+		}
+
+		void CorrectClosingBrace (AstNode rbrace)
+		{
+			if (rbrace.IsNull)
+				return;
+			int braceOffset = document.GetOffset(rbrace.StartLocation);
+			var prevNode = rbrace.GetPrevNode();
+			int prevNodeOffset = prevNode != null ? document.GetOffset(prevNode.EndLocation) : 0;
+			if (prevNode is NewLineNode) {
+				EnsureText(prevNodeOffset, braceOffset, curIndent.IndentString);
+			} else {
+				EnsureText(prevNodeOffset, braceOffset, options.EolMarker + curIndent.IndentString);
+			}
+		}
+
+		void FixClosingBrace(BraceStyle braceStyle, AstNode rbrace)
+		{
+			if (rbrace.IsNull)
+				return;
+			switch (braceStyle) {
+				case BraceStyle.DoNotChange:
+					return;
+
+				case BraceStyle.NextLineShifted:
+				case BraceStyle.BannerStyle:
+					curIndent.Push(IndentType.Block);
+					CorrectClosingBrace (rbrace);
+					curIndent.Pop ();
+					break;
+				case BraceStyle.EndOfLineWithoutSpace:
+				case BraceStyle.EndOfLine:
+				case BraceStyle.NextLine:
+					CorrectClosingBrace (rbrace);
+					break;
+
+				case BraceStyle.NextLineShifted2:
+					curIndent.Push(IndentType.Block);
+					CorrectClosingBrace (rbrace);
+					curIndent.Pop ();
+					break;
+			}
+
+		}
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Expressions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Expressions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Expressions.cs	(revision 11807)
@@ -0,0 +1,735 @@
+//
+// AstFormattingVisitor_Expressions.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Linq;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	partial class FormattingVisitor : DepthFirstAstVisitor
+	{
+		public override void VisitComposedType(ComposedType composedType)
+		{
+			var spec = composedType.ArraySpecifiers.FirstOrDefault();
+			if (spec != null)
+				ForceSpacesBefore(spec.LBracketToken, policy.SpaceBeforeArrayDeclarationBrackets);
+
+			if (composedType.HasNullableSpecifier)
+				ForceSpacesBefore(composedType.NullableSpecifierToken, false);
+
+			if (composedType.PointerRank > 0)
+				foreach (var token in composedType.PointerTokens)
+					ForceSpacesBefore(token, false);
+
+			base.VisitComposedType(composedType);
+		}
+
+		public override void VisitAnonymousMethodExpression(AnonymousMethodExpression lambdaExpression)
+		{
+			FormatArguments(lambdaExpression);
+
+			if (!lambdaExpression.Body.IsNull) {
+				var old = curIndent;
+				this.curIndent = curIndent.GetIndentWithoutSpace ();
+				FixOpenBrace(policy.AnonymousMethodBraceStyle, lambdaExpression.Body.LBraceToken);
+				VisitBlockWithoutFixingBraces(lambdaExpression.Body, policy.IndentBlocks);
+				FixClosingBrace(policy.AnonymousMethodBraceStyle, lambdaExpression.Body.RBraceToken);
+				curIndent = old;
+			}
+
+		}
+
+		public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+		{
+			ForceSpacesAround(assignmentExpression.OperatorToken, policy.SpaceAroundAssignment);
+			base.VisitAssignmentExpression(assignmentExpression);
+		}
+
+		public override void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+		{
+			bool forceSpaces = false;
+			switch (binaryOperatorExpression.Operator) {
+				case BinaryOperatorType.Equality:
+				case BinaryOperatorType.InEquality:
+					forceSpaces = policy.SpaceAroundEqualityOperator;
+					break;
+				case BinaryOperatorType.GreaterThan:
+				case BinaryOperatorType.GreaterThanOrEqual:
+				case BinaryOperatorType.LessThan:
+				case BinaryOperatorType.LessThanOrEqual:
+					forceSpaces = policy.SpaceAroundRelationalOperator;
+					break;
+				case BinaryOperatorType.ConditionalAnd:
+				case BinaryOperatorType.ConditionalOr:
+					forceSpaces = policy.SpaceAroundLogicalOperator;
+					break;
+				case BinaryOperatorType.BitwiseAnd:
+				case BinaryOperatorType.BitwiseOr:
+				case BinaryOperatorType.ExclusiveOr:
+					forceSpaces = policy.SpaceAroundBitwiseOperator;
+					break;
+				case BinaryOperatorType.Add:
+				case BinaryOperatorType.Subtract:
+					forceSpaces = policy.SpaceAroundAdditiveOperator;
+					break;
+				case BinaryOperatorType.Multiply:
+				case BinaryOperatorType.Divide:
+				case BinaryOperatorType.Modulus:
+					forceSpaces = policy.SpaceAroundMultiplicativeOperator;
+					break;
+				case BinaryOperatorType.ShiftLeft:
+				case BinaryOperatorType.ShiftRight:
+					forceSpaces = policy.SpaceAroundShiftOperator;
+					break;
+				case BinaryOperatorType.NullCoalescing:
+					forceSpaces = policy.SpaceAroundNullCoalescingOperator;
+					break;
+			}
+			var opToken = binaryOperatorExpression.OperatorToken;
+			if (opToken.PrevSibling != null && opToken.PrevSibling.Role != Roles.NewLine) {
+				ForceSpacesBefore(opToken, forceSpaces);
+			} else {
+				ForceSpacesAfter(binaryOperatorExpression.Left, false);
+				FixIndentation(opToken);
+			}
+			ForceSpacesAfter(opToken, opToken.NextSibling != null && opToken.NextSibling.Role != Roles.NewLine && forceSpaces);
+
+			binaryOperatorExpression.Left.AcceptVisitor(this);
+			// Handle line breaks in binary opeartor expression.
+			if (binaryOperatorExpression.Left.EndLocation.Line != binaryOperatorExpression.Right.StartLocation.Line) {
+				if (opToken.StartLocation.Line == binaryOperatorExpression.Right.StartLocation.Line) {
+					FixStatementIndentation(opToken.StartLocation);
+				} else {
+					FixStatementIndentation(binaryOperatorExpression.Right.StartLocation);
+				}
+			}
+			binaryOperatorExpression.Right.AcceptVisitor(this);
+		}
+
+		public override void VisitConditionalExpression(ConditionalExpression conditionalExpression)
+		{
+			ForceSpacesBefore(conditionalExpression.QuestionMarkToken, policy.SpaceBeforeConditionalOperatorCondition);
+			ForceSpacesAfter(conditionalExpression.QuestionMarkToken, policy.SpaceAfterConditionalOperatorCondition);
+			ForceSpacesBefore(conditionalExpression.ColonToken, policy.SpaceBeforeConditionalOperatorSeparator);
+			ForceSpacesAfter(conditionalExpression.ColonToken, policy.SpaceAfterConditionalOperatorSeparator);
+			base.VisitConditionalExpression(conditionalExpression);
+		}
+
+		public override void VisitCastExpression(CastExpression castExpression)
+		{
+			if (castExpression.RParToken != null) {
+				ForceSpacesAfter(castExpression.LParToken, policy.SpacesWithinCastParentheses);
+				ForceSpacesBefore(castExpression.RParToken, policy.SpacesWithinCastParentheses);
+
+				ForceSpacesAfter(castExpression.RParToken, policy.SpaceAfterTypecast);
+			}
+			base.VisitCastExpression(castExpression);
+		}
+
+		void ForceSpacesAround(AstNode node, bool forceSpaces)
+		{
+			if (node.IsNull)
+				return;
+			ForceSpacesBefore(node, forceSpaces);
+			ForceSpacesAfter(node, forceSpaces);
+		}
+
+		void FormatCommas(AstNode parent, bool before, bool after)
+		{
+			if (parent.IsNull) {
+				return;
+			}
+			foreach (CSharpTokenNode comma in parent.Children.Where (node => node.Role == Roles.Comma)) {
+				ForceSpacesAfter(comma, after);
+				ForceSpacesBefore(comma, before);
+			}
+		}
+
+		bool DoWrap(Wrapping wrapping, AstNode wrapNode, int argumentCount)
+		{
+			return wrapping == Wrapping.WrapAlways || 
+				options.WrapLineLength > 0 && argumentCount > 1 && wrapping == Wrapping.WrapIfTooLong && wrapNode.StartLocation.Column >= options.WrapLineLength;
+		}
+
+		void FormatArguments(AstNode node)
+		{
+			Wrapping methodCallArgumentWrapping;
+			NewLinePlacement newLineAferMethodCallOpenParentheses;
+			bool doAlignToFirstArgument;
+			NewLinePlacement methodClosingParenthesesOnNewLine;
+			bool spaceWithinMethodCallParentheses;
+			bool spaceWithinEmptyParentheses;
+			bool spaceAfterMethodCallParameterComma;
+			bool spaceBeforeMethodCallParameterComma;
+
+			CSharpTokenNode rParToken, lParToken;
+			List<AstNode> arguments;
+
+			var constructorDeclaration = node as ConstructorDeclaration;
+			if (constructorDeclaration != null) {
+				methodCallArgumentWrapping = policy.MethodDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodDeclarationOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodDeclarationClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinConstructorDeclarationParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterConstructorDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeConstructorDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = constructorDeclaration.LParToken;
+				rParToken = constructorDeclaration.RParToken;
+				arguments = constructorDeclaration.Parameters.Cast<AstNode>().ToList();
+			} else if (node is IndexerDeclaration) {
+				var indexer = (IndexerDeclaration)node;
+				methodCallArgumentWrapping = policy.IndexerDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferIndexerDeclarationOpenBracket;
+				methodClosingParenthesesOnNewLine = policy.IndexerDeclarationClosingBracketOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstIndexerDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinIndexerDeclarationBracket;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterIndexerDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeIndexerDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = indexer.LBracketToken;
+				rParToken = indexer.RBracketToken;
+				arguments = indexer.Parameters.Cast<AstNode>().ToList();
+			} else if (node is OperatorDeclaration) {
+				var op = (OperatorDeclaration)node;
+				methodCallArgumentWrapping = policy.MethodDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodDeclarationOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodDeclarationClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinMethodDeclarationParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterMethodDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeMethodDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = op.LParToken;
+				rParToken = op.RParToken;
+				arguments = op.Parameters.Cast<AstNode>().ToList();
+			} else if (node is MethodDeclaration) {
+				var methodDeclaration = node as MethodDeclaration;
+				methodCallArgumentWrapping = policy.MethodDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodDeclarationOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodDeclarationClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinMethodDeclarationParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterMethodDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeMethodDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = methodDeclaration.LParToken;
+				rParToken = methodDeclaration.RParToken;
+				arguments = methodDeclaration.Parameters.Cast<AstNode>().ToList();
+			} else if (node is IndexerExpression) {
+				var indexer = (IndexerExpression)node;
+				methodCallArgumentWrapping = policy.IndexerArgumentWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferIndexerOpenBracket;
+				doAlignToFirstArgument = policy.AlignToFirstIndexerArgument;
+				methodClosingParenthesesOnNewLine = policy.IndexerClosingBracketOnNewLine;
+				spaceWithinMethodCallParentheses = policy.SpacesWithinBrackets;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterBracketComma;
+				spaceWithinEmptyParentheses = spaceWithinMethodCallParentheses;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeBracketComma;
+				rParToken = indexer.RBracketToken;
+				lParToken = indexer.LBracketToken;
+				arguments = indexer.Arguments.Cast<AstNode>().ToList();
+			} else if (node is ObjectCreateExpression) {
+				var oce = node as ObjectCreateExpression;
+				methodCallArgumentWrapping = policy.MethodCallArgumentWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodCallOpenParentheses;
+				doAlignToFirstArgument = policy.AlignToFirstMethodCallArgument;
+				methodClosingParenthesesOnNewLine = policy.MethodCallClosingParenthesesOnNewLine;
+				spaceWithinMethodCallParentheses = policy.SpacesWithinNewParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterNewParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeNewParameterComma;
+				spaceWithinEmptyParentheses = policy.SpacesBetweenEmptyNewParentheses;
+
+				rParToken = oce.RParToken;
+				lParToken = oce.LParToken;
+				arguments = oce.Arguments.Cast<AstNode>().ToList();
+			} else if (node is Attribute) {
+				var oce = node as Attribute;
+				methodCallArgumentWrapping = policy.MethodCallArgumentWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodCallOpenParentheses;
+				doAlignToFirstArgument = policy.AlignToFirstMethodCallArgument;
+				methodClosingParenthesesOnNewLine = policy.MethodCallClosingParenthesesOnNewLine;
+				spaceWithinMethodCallParentheses = policy.SpacesWithinNewParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterNewParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeNewParameterComma;
+				spaceWithinEmptyParentheses = policy.SpacesBetweenEmptyNewParentheses;
+
+				rParToken = oce.RParToken;
+				lParToken = oce.LParToken;
+				arguments = oce.Arguments.Cast<AstNode>().ToList();
+			} else if (node is LambdaExpression) {
+				var methodDeclaration = node as LambdaExpression;
+				methodCallArgumentWrapping = policy.MethodDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodDeclarationOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodDeclarationClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinMethodDeclarationParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterMethodDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeMethodDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = methodDeclaration.LParToken;
+				rParToken = methodDeclaration.RParToken;
+				arguments = methodDeclaration.Parameters.Cast<AstNode>().ToList();
+			} else if (node is AnonymousMethodExpression) {
+				var methodDeclaration = node as AnonymousMethodExpression;
+				methodCallArgumentWrapping = policy.MethodDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodDeclarationOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodDeclarationClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinMethodDeclarationParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterMethodDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeMethodDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = methodDeclaration.LParToken;
+				rParToken = methodDeclaration.RParToken;
+				arguments = methodDeclaration.Parameters.Cast<AstNode>().ToList();
+			}  else if (node is ConstructorInitializer) {
+				var constructorInitializer = node as ConstructorInitializer;
+				methodCallArgumentWrapping = policy.MethodDeclarationParameterWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodDeclarationOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodDeclarationClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodDeclarationParameter;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinMethodDeclarationParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterMethodDeclarationParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeMethodDeclarationParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodDeclarationParentheses;
+				lParToken = constructorInitializer.LParToken;
+				rParToken = constructorInitializer.RParToken;
+				arguments = constructorInitializer.Arguments.Cast<AstNode>().ToList();
+			} else {
+				InvocationExpression invocationExpression = node as InvocationExpression;
+				methodCallArgumentWrapping = policy.MethodCallArgumentWrapping;
+				newLineAferMethodCallOpenParentheses = policy.NewLineAferMethodCallOpenParentheses;
+				methodClosingParenthesesOnNewLine = policy.MethodCallClosingParenthesesOnNewLine;
+				doAlignToFirstArgument = policy.AlignToFirstMethodCallArgument;
+				spaceWithinMethodCallParentheses = policy.SpaceWithinMethodCallParentheses;
+				spaceAfterMethodCallParameterComma = policy.SpaceAfterMethodCallParameterComma;
+				spaceBeforeMethodCallParameterComma = policy.SpaceBeforeMethodCallParameterComma;
+				spaceWithinEmptyParentheses = policy.SpaceBetweenEmptyMethodCallParentheses;
+
+				rParToken = invocationExpression.RParToken;
+				lParToken = invocationExpression.LParToken;
+				arguments = invocationExpression.Arguments.Cast<AstNode>().ToList();
+			}
+
+			if (formatter.FormattingMode == ICSharpCode.NRefactory.CSharp.FormattingMode.OnTheFly)
+				methodCallArgumentWrapping = Wrapping.DoNotChange;
+			int argumentStart = 1;
+			var firstarg = arguments.FirstOrDefault();
+			if (firstarg != null && firstarg.GetPrevNode().Role == Roles.NewLine) {
+				doAlignToFirstArgument = false;
+				argumentStart = 0;
+			}
+			bool wrapMethodCall = DoWrap(methodCallArgumentWrapping, rParToken, arguments.Count);
+			if (wrapMethodCall && arguments.Any()) {
+				if (ShouldBreakLine(newLineAferMethodCallOpenParentheses, lParToken)) {
+					curIndent.Push(IndentType.Continuation);
+					foreach (var arg in arguments) {
+						FixStatementIndentation(arg.StartLocation);
+						arg.AcceptVisitor(this);
+					}
+					curIndent.Pop();
+				} else {
+					if (!doAlignToFirstArgument) {
+						curIndent.Push(IndentType.Continuation);
+						foreach (var arg in arguments.Take (argumentStart)) {
+							FixStatementIndentation(arg.StartLocation);
+							arg.AcceptVisitor(this);
+						}
+						foreach (var arg in arguments.Skip (argumentStart)) {
+							FixStatementIndentation(arg.StartLocation);
+							arg.AcceptVisitor(this);
+						}
+						curIndent.Pop();
+					} else {
+						int extraSpaces = Math.Max(0, arguments.First().StartLocation.Column - 1 - curIndent.IndentString.Length);
+						curIndent.ExtraSpaces += extraSpaces;
+						foreach (var arg in arguments.Take (argumentStart)) {
+							arg.AcceptVisitor(this);
+						}
+						foreach (var arg in arguments.Skip(argumentStart)) {
+							FixStatementIndentation(arg.StartLocation);
+							arg.AcceptVisitor(this);
+						}
+						curIndent.ExtraSpaces -= extraSpaces;
+					}
+				}
+
+				if (!rParToken.IsNull) {
+					if (ShouldBreakLine(methodClosingParenthesesOnNewLine, rParToken)) {
+						FixStatementIndentation(rParToken.StartLocation);
+					} else if (methodClosingParenthesesOnNewLine == NewLinePlacement.SameLine) {
+						ForceSpacesBeforeRemoveNewLines(rParToken, spaceWithinMethodCallParentheses);
+					}
+				}
+			} else {
+
+				foreach (var arg in arguments.Take (argumentStart)) {
+					if (policy.IndentBlocksInsideExpressions)
+						curIndent.Push(IndentType.Continuation);
+					arg.AcceptVisitor(this);
+					if (policy.IndentBlocksInsideExpressions)
+						curIndent.Pop();
+				}
+				foreach (var arg in arguments.Skip(argumentStart)) {
+					if (arg.GetPrevSibling(NoWhitespacePredicate) != null) {
+						if (methodCallArgumentWrapping == Wrapping.DoNotWrap) {
+							ForceSpacesBeforeRemoveNewLines(arg, spaceAfterMethodCallParameterComma && arg.GetPrevSibling(NoWhitespacePredicate).Role == Roles.Comma);
+							if (policy.IndentBlocksInsideExpressions)
+								curIndent.Push(IndentType.Continuation);
+							arg.AcceptVisitor(this);
+							if (policy.IndentBlocksInsideExpressions)
+								curIndent.Pop();
+						} else {
+							if (!doAlignToFirstArgument && arg.PrevSibling.Role == Roles.NewLine) {
+								curIndent.Push(IndentType.Continuation);
+								FixStatementIndentation(arg.StartLocation);
+								arg.AcceptVisitor(this);
+								curIndent.Pop();
+							} else {
+								if (arg.PrevSibling.StartLocation.Line == arg.StartLocation.Line) {
+									ForceSpacesBefore(arg, spaceAfterMethodCallParameterComma && arg.GetPrevSibling(NoWhitespacePredicate).Role == Roles.Comma);
+									if (policy.IndentBlocksInsideExpressions)
+										curIndent.Push(IndentType.Continuation);
+									arg.AcceptVisitor(this);
+									if (policy.IndentBlocksInsideExpressions)
+										curIndent.Pop();
+								} else {
+									int extraSpaces = Math.Max(0, arguments.First().StartLocation.Column - 1 - curIndent.IndentString.Length);
+									curIndent.ExtraSpaces += extraSpaces;
+									FixStatementIndentation(arg.StartLocation);
+									arg.AcceptVisitor(this);
+									curIndent.ExtraSpaces -= extraSpaces;
+								}
+							}
+						}
+					} else {
+						arg.AcceptVisitor(this);
+					}
+				}
+				if (!rParToken.IsNull) {
+					if (methodCallArgumentWrapping == Wrapping.DoNotWrap) {
+						ForceSpacesBeforeRemoveNewLines(rParToken, arguments.Any() ? spaceWithinMethodCallParentheses : spaceWithinEmptyParentheses);
+					} else {
+						bool sameLine = rParToken.GetPrevNode(n => n.Role == Roles.Argument || n.Role == Roles.Parameter || n.Role == Roles.LPar || n.Role == Roles.Comma).EndLocation.Line == rParToken.StartLocation.Line;
+						if (sameLine) {
+							ForceSpacesBeforeRemoveNewLines(rParToken, arguments.Any() ? spaceWithinMethodCallParentheses : spaceWithinEmptyParentheses);
+						} else {
+							FixStatementIndentation(rParToken.StartLocation);
+						}
+					}
+				}
+			}
+			if (!rParToken.IsNull) {
+				foreach (CSharpTokenNode comma in rParToken.Parent.Children.Where(n => n.Role == Roles.Comma)) {
+					ForceSpacesBefore(comma, spaceBeforeMethodCallParameterComma);
+				}
+			}
+		}
+
+		public override void VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			if (!invocationExpression.Target.IsNull)
+				invocationExpression.Target.AcceptVisitor(this);
+
+			ForceSpacesBefore(invocationExpression.LParToken, policy.SpaceBeforeMethodCallParentheses);
+			if (invocationExpression.Arguments.Any()) {
+				ForceSpacesAfter(invocationExpression.LParToken, policy.SpaceWithinMethodCallParentheses);
+			} else {
+				ForceSpacesAfter(invocationExpression.LParToken, policy.SpaceBetweenEmptyMethodCallParentheses);
+				ForceSpacesBefore(invocationExpression.RParToken, policy.SpaceBetweenEmptyMethodCallParentheses);
+			}
+			bool popIndent = false;
+			if (invocationExpression.Target is MemberReferenceExpression) {
+				var mt = (MemberReferenceExpression)invocationExpression.Target;
+				if (mt.Target is InvocationExpression) {
+					if (DoWrap(policy.ChainedMethodCallWrapping, mt.DotToken, 2)) {
+						curIndent.Push(IndentType.Block);
+						popIndent = true;
+						FixStatementIndentation(mt.DotToken.StartLocation);
+					} else {
+						if (policy.ChainedMethodCallWrapping == Wrapping.DoNotWrap)
+							ForceSpacesBeforeRemoveNewLines(mt.DotToken, false);
+					}
+				}
+			}
+			FormatArguments(invocationExpression);
+			if (popIndent)
+				curIndent.Pop();
+		}
+
+		public override void VisitIndexerExpression(IndexerExpression indexerExpression)
+		{
+			ForceSpacesBeforeRemoveNewLines(indexerExpression.LBracketToken, policy.SpacesBeforeBrackets);
+			ForceSpacesAfter(indexerExpression.LBracketToken, policy.SpacesWithinBrackets);
+
+			if (!indexerExpression.Target.IsNull)
+				indexerExpression.Target.AcceptVisitor(this);
+
+			FormatArguments(indexerExpression);
+
+
+
+		}
+
+		public override void VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
+		{
+			var lp = parenthesizedExpression.LParToken;
+			var expr = parenthesizedExpression.Expression;
+			int extraSpaces = 0;
+			if (lp.StartLocation.Line == expr.StartLocation.Line) {
+				ForceSpacesAfter(lp, policy.SpacesWithinParentheses);
+			} else {
+				extraSpaces += options.IndentSize;
+				curIndent.ExtraSpaces += extraSpaces;
+				FixIndentation(expr);
+			}
+
+			base.VisitParenthesizedExpression(parenthesizedExpression);
+
+			var rp = parenthesizedExpression.RParToken;
+
+			curIndent.ExtraSpaces -= extraSpaces;
+			if (rp.StartLocation.Line == expr.EndLocation.Line) {
+				ForceSpacesBefore(rp, policy.SpacesWithinParentheses);
+			} else {
+				FixIndentation(rp);
+			}
+		}
+
+		public override void VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
+		{
+			ForceSpacesBeforeRemoveNewLines(sizeOfExpression.LParToken, policy.SpaceBeforeSizeOfParentheses);
+			ForceSpacesAfter(sizeOfExpression.LParToken, policy.SpacesWithinSizeOfParentheses);
+			ForceSpacesBeforeRemoveNewLines(sizeOfExpression.RParToken, policy.SpacesWithinSizeOfParentheses);
+			base.VisitSizeOfExpression(sizeOfExpression);
+		}
+
+		public override void VisitTypeOfExpression(TypeOfExpression typeOfExpression)
+		{
+			ForceSpacesBeforeRemoveNewLines(typeOfExpression.LParToken, policy.SpaceBeforeTypeOfParentheses);
+			ForceSpacesAfter(typeOfExpression.LParToken, policy.SpacesWithinTypeOfParentheses);
+			ForceSpacesBeforeRemoveNewLines(typeOfExpression.RParToken, policy.SpacesWithinTypeOfParentheses);
+			base.VisitTypeOfExpression(typeOfExpression);
+		}
+
+		public override void VisitCheckedExpression(CheckedExpression checkedExpression)
+		{
+			ForceSpacesAfter(checkedExpression.LParToken, policy.SpacesWithinCheckedExpressionParantheses);
+			ForceSpacesBeforeRemoveNewLines(checkedExpression.RParToken, policy.SpacesWithinCheckedExpressionParantheses);
+			base.VisitCheckedExpression(checkedExpression);
+		}
+
+		public override void VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
+		{
+			ForceSpacesAfter(uncheckedExpression.LParToken, policy.SpacesWithinCheckedExpressionParantheses);
+			ForceSpacesBeforeRemoveNewLines(uncheckedExpression.RParToken, policy.SpacesWithinCheckedExpressionParantheses);
+			base.VisitUncheckedExpression(uncheckedExpression);
+		}
+
+		public override void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
+		{
+			ForceSpacesBeforeRemoveNewLines(objectCreateExpression.LParToken, policy.SpaceBeforeNewParentheses);
+
+			if (objectCreateExpression.Arguments.Any()) {
+				if (!objectCreateExpression.LParToken.IsNull)
+					ForceSpacesAfter(objectCreateExpression.LParToken, policy.SpacesWithinNewParentheses);
+			} else {
+				if (!objectCreateExpression.LParToken.IsNull)
+					ForceSpacesAfter(objectCreateExpression.LParToken, policy.SpacesBetweenEmptyNewParentheses);
+			}
+
+			if (!objectCreateExpression.Type.IsNull)
+				objectCreateExpression.Type.AcceptVisitor(this);
+			objectCreateExpression.Initializer.AcceptVisitor(this);
+			FormatArguments(objectCreateExpression);
+		}
+
+		public override void VisitArrayCreateExpression(ArrayCreateExpression arrayObjectCreateExpression)
+		{
+			FormatCommas(arrayObjectCreateExpression, policy.SpaceBeforeMethodCallParameterComma, policy.SpaceAfterMethodCallParameterComma);
+			base.VisitArrayCreateExpression(arrayObjectCreateExpression);
+		}
+
+		public override void VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
+		{
+			var old = curIndent;
+			curIndent = curIndent.Clone();
+			curIndent.ExtraSpaces = 0;
+
+			if (DoWrap(policy.ArrayInitializerWrapping, arrayInitializerExpression.RBraceToken, arrayInitializerExpression.Elements.Count)) {
+				FixOpenBrace(policy.ArrayInitializerBraceStyle, arrayInitializerExpression.LBraceToken);
+				curIndent.Push(IndentType.Block);
+				foreach (var init in arrayInitializerExpression.Elements) {
+					FixStatementIndentation(init.StartLocation);
+					init.AcceptVisitor(this);
+				}
+				curIndent.Pop();
+				FixClosingBrace(policy.ArrayInitializerBraceStyle, arrayInitializerExpression.RBraceToken);
+			} else if (policy.ArrayInitializerWrapping == Wrapping.DoNotWrap) {
+				ForceSpacesBeforeRemoveNewLines(arrayInitializerExpression.LBraceToken);
+				foreach (var init in arrayInitializerExpression.Elements) {
+					ForceSpacesBeforeRemoveNewLines(init);
+					init.AcceptVisitor(this);
+				}
+				ForceSpacesBeforeRemoveNewLines(arrayInitializerExpression.RBraceToken);
+			} else {
+				var lBrace = arrayInitializerExpression.LBraceToken;
+				var rBrace = arrayInitializerExpression.RBraceToken;
+
+				foreach (var child in arrayInitializerExpression.Children) {
+					if (child.Role == Roles.LBrace) {
+						if (lBrace.StartLocation.Line == rBrace.StartLocation.Line && policy.AllowOneLinedArrayInitialziers) {
+							ForceSpacesAfter(child, true);
+						} else {
+							FixOpenBrace(policy.ArrayInitializerBraceStyle, child);
+						}
+						curIndent.Push(IndentType.Block);
+						continue;
+					}
+					if (child.Role == Roles.RBrace) {
+						curIndent.Pop();
+						if (lBrace.StartLocation.Line == rBrace.StartLocation.Line && policy.AllowOneLinedArrayInitialziers) {
+							ForceSpaceBefore(child, true);
+
+						} else {
+							FixClosingBrace(policy.ArrayInitializerBraceStyle, child);
+						}
+						continue;
+					}
+					if (child.Role == Roles.Expression) {
+						if (child.PrevSibling != null) {
+							if (child.PrevSibling.Role == Roles.NewLine) {
+								FixIndentation(child);
+							}
+							if (child.PrevSibling.Role == Roles.Comma) {
+								ForceSpaceBefore(child, true);
+							}
+						}
+						child.AcceptVisitor(this);
+						if (child.NextSibling != null && child.NextSibling.Role == Roles.Comma)
+							ForceSpacesAfter(child, false);
+						continue;
+					}
+
+					child.AcceptVisitor(this);
+				}
+			}
+			curIndent = old;
+		}
+
+		public override void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			var assignToken = parameterDeclaration.AssignToken;
+			if (!assignToken.IsNull)
+				ForceSpacesAround(assignToken, policy.SpaceAroundAssignment);
+			base.VisitParameterDeclaration(parameterDeclaration);
+		}
+
+		public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
+		{
+			FormatArguments(lambdaExpression);
+			ForceSpacesBeforeRemoveNewLines(lambdaExpression.ArrowToken, true);
+
+			if (!lambdaExpression.Body.IsNull) {
+				var body = lambdaExpression.Body as BlockStatement;
+				if (body != null) {
+					var old = curIndent;
+					this.curIndent = curIndent.GetIndentWithoutSpace ();
+					FixOpenBrace(policy.AnonymousMethodBraceStyle, body.LBraceToken);
+					VisitBlockWithoutFixingBraces(body, policy.IndentMethodBody);
+					FixClosingBrace(policy.AnonymousMethodBraceStyle, body.RBraceToken);
+					curIndent = old;
+				} else {
+					ForceSpacesAfter(lambdaExpression.ArrowToken, true);
+					lambdaExpression.Body.AcceptVisitor(this);
+				}
+			}
+		}
+
+		public override void VisitNamedExpression(NamedExpression namedExpression)
+		{
+			ForceSpacesAround(namedExpression.AssignToken, policy.SpaceAroundAssignment);
+			base.VisitNamedExpression(namedExpression);
+		}
+
+		public override void VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
+		{
+			ForceSpacesAfter(namedArgumentExpression.ColonToken, policy.SpaceInNamedArgumentAfterDoubleColon);
+
+			base.VisitNamedArgumentExpression(namedArgumentExpression);
+		}
+
+		public override void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			var dot = memberReferenceExpression.DotToken;
+			if (dot.PrevSibling.EndLocation.Line == dot.StartLocation.Line)
+				ForceSpacesBefore(dot, false);
+			ForceSpacesAfter(dot, false);
+			base.VisitMemberReferenceExpression(memberReferenceExpression);
+		}
+
+		public override void VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
+		{
+			ForceSpacesAround(pointerReferenceExpression.ArrowToken, policy.SpaceAroundUnsafeArrowOperator);
+			base.VisitPointerReferenceExpression(pointerReferenceExpression);
+		}
+
+		public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+		{
+			base.VisitUnaryOperatorExpression(unaryOperatorExpression);
+			switch (unaryOperatorExpression.Operator) {
+				case UnaryOperatorType.Any:
+					break;
+				case UnaryOperatorType.Not:
+				case UnaryOperatorType.BitNot:
+				case UnaryOperatorType.Minus:
+				case UnaryOperatorType.Plus:
+				case UnaryOperatorType.Increment:
+				case UnaryOperatorType.Decrement:
+					ForceSpacesBeforeRemoveNewLines(unaryOperatorExpression.Expression, false);
+					break;
+				case UnaryOperatorType.PostIncrement:
+				case UnaryOperatorType.PostDecrement:
+					ForceSpacesBeforeRemoveNewLines(unaryOperatorExpression.OperatorToken, false);
+					break;
+				case UnaryOperatorType.Dereference:
+					ForceSpacesAfter(unaryOperatorExpression.OperatorToken, policy.SpaceAfterUnsafeAsteriskOfOperator);
+					break;
+				case UnaryOperatorType.AddressOf:
+					ForceSpacesAfter(unaryOperatorExpression.OperatorToken, policy.SpaceAfterUnsafeAddressOfOperator);
+					break;
+				case UnaryOperatorType.Await:
+					ForceSpacesBeforeRemoveNewLines(unaryOperatorExpression.Expression, true);
+					break;
+				default:
+					throw new ArgumentOutOfRangeException();
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Global.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Global.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Global.cs	(revision 11807)
@@ -0,0 +1,351 @@
+//
+// AstFormattingVisitor_Global.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	partial class FormattingVisitor : DepthFirstAstVisitor
+	{
+		int GetGlobalNewLinesFor(AstNode child)
+		{
+			if (child.NextSibling == null)
+				// last node in the document => no extra newlines
+				return 0;
+			if (child.NextSibling.Role == Roles.RBrace)
+				// Last node in a block => no extra newlines, it's handled later by FixClosingBrace()
+				return 0;
+
+			int newLines = 1;
+			var nextSibling = child.GetNextSibling(NoWhitespacePredicate);
+			if (nextSibling is PreProcessorDirective) {
+				var directive = (PreProcessorDirective)nextSibling;
+				if (directive.Type == PreProcessorDirectiveType.Endif)
+					return -1;
+				if (directive.Type == PreProcessorDirectiveType.Undef)
+					return -1;
+			}
+			if ((child is UsingDeclaration || child is UsingAliasDeclaration) && !(nextSibling is UsingDeclaration || nextSibling is UsingAliasDeclaration)) {
+				newLines += policy.MinimumBlankLinesAfterUsings;
+			} else if ((child is TypeDeclaration) && (nextSibling is TypeDeclaration)) {
+				newLines += policy.MinimumBlankLinesBetweenTypes;
+			}
+
+			return newLines;
+		}
+
+		public override void VisitSyntaxTree(SyntaxTree unit)
+		{
+			bool first = true;
+			VisitChildrenToFormat(unit, child => {
+				if (first && (child is UsingDeclaration || child is UsingAliasDeclaration)) {
+					EnsureMinimumBlankLinesBefore(child, policy.MinimumBlankLinesBeforeUsings);
+					first = false;
+				}
+				if (NoWhitespacePredicate(child))
+					FixIndentation(child);
+				child.AcceptVisitor(this);
+				if (NoWhitespacePredicate(child) && !first)
+					EnsureMinimumNewLinesAfter(child, GetGlobalNewLinesFor(child));
+			});
+		}
+
+		public override void VisitAttributeSection(AttributeSection attributeSection)
+		{
+			VisitChildrenToFormat(attributeSection, child => {
+				child.AcceptVisitor(this);
+				if (child.NextSibling != null && child.NextSibling.Role == Roles.RBracket) {
+					ForceSpacesAfter(child, false);
+				}
+			});
+		}
+
+		public override void VisitAttribute(Attribute attribute)
+		{
+			if (attribute.HasArgumentList) {
+				ForceSpacesBefore(attribute.LParToken, policy.SpaceBeforeMethodCallParentheses);
+				if (attribute.Arguments.Any()) {
+					ForceSpacesAfter(attribute.LParToken, policy.SpaceWithinMethodCallParentheses);
+				} else {
+					ForceSpacesAfter(attribute.LParToken, policy.SpaceBetweenEmptyMethodCallParentheses);
+					ForceSpacesBefore(attribute.RParToken, policy.SpaceBetweenEmptyMethodCallParentheses);
+				}
+				FormatArguments(attribute);
+			}
+		}
+
+		public override void VisitUsingDeclaration(UsingDeclaration usingDeclaration)
+		{
+			ForceSpacesAfter(usingDeclaration.UsingToken, true);
+			FixSemicolon(usingDeclaration.SemicolonToken);
+		}
+
+		public override void VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration)
+		{
+			ForceSpacesAfter(usingDeclaration.UsingToken, true);
+			ForceSpacesAround(usingDeclaration.AssignToken, policy.SpaceAroundAssignment);
+			FixSemicolon(usingDeclaration.SemicolonToken);
+		}
+
+		public override void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+		{
+			FixOpenBrace(policy.NamespaceBraceStyle, namespaceDeclaration.LBraceToken);
+			if (policy.IndentNamespaceBody)
+				curIndent.Push(IndentType.Block);
+
+			bool first = true;
+			bool startFormat = false;
+			VisitChildrenToFormat(namespaceDeclaration, child => {
+				if (first) {
+					startFormat = child.StartLocation > namespaceDeclaration.LBraceToken.StartLocation;
+				}
+				if (child.Role == Roles.LBrace) {
+					var next = child.GetNextSibling(NoWhitespacePredicate);
+					var blankLines = 1;
+					if (next is UsingDeclaration || next is UsingAliasDeclaration) {
+						blankLines += policy.MinimumBlankLinesBeforeUsings;
+					} else {
+						blankLines += policy.MinimumBlankLinesBeforeFirstDeclaration;
+					}
+					EnsureMinimumNewLinesAfter(child, blankLines);
+					startFormat = true;
+					return;
+				}
+				if (child.Role == Roles.RBrace) {
+					startFormat = false;
+					return;
+				}
+				if (!startFormat || !NoWhitespacePredicate (child))
+					return;
+				if (first && (child is UsingDeclaration || child is UsingAliasDeclaration)) {
+					// TODO: policy.BlankLinesBeforeUsings
+					first = false;
+				}
+				if (NoWhitespacePredicate(child))
+					FixIndentationForceNewLine(child);
+				child.AcceptVisitor(this);
+				if (NoWhitespacePredicate(child))
+					EnsureMinimumNewLinesAfter(child, GetGlobalNewLinesFor(child));
+			});
+
+			if (policy.IndentNamespaceBody)
+				curIndent.Pop();
+
+			FixClosingBrace(policy.NamespaceBraceStyle, namespaceDeclaration.RBraceToken);
+		}
+
+		void FixAttributesAndDocComment(EntityDeclaration entity)
+		{
+			var node = entity.FirstChild;
+			while (node != null && node.Role == Roles.Comment) {
+				node = node.GetNextSibling(NoWhitespacePredicate);
+				FixIndentation(node);
+			}
+			if (entity.Attributes.Count > 0) {
+				AstNode n = null;
+				entity.Attributes.First().AcceptVisitor(this);
+				foreach (var attr in entity.Attributes.Skip (1)) {
+					FixIndentation(attr);
+					attr.AcceptVisitor(this);
+					n = attr;
+				}
+				if (n != null) {
+					FixIndentation(n.GetNextNode(NoWhitespacePredicate));
+				} else {
+					FixIndentation(entity.Attributes.First().GetNextNode(NoWhitespacePredicate));
+				}
+			}
+		}
+
+		public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			FixAttributesAndDocComment(typeDeclaration);
+			BraceStyle braceStyle;
+			bool indentBody = false;
+			switch (typeDeclaration.ClassType) {
+				case ClassType.Class:
+					braceStyle = policy.ClassBraceStyle;
+					indentBody = policy.IndentClassBody;
+					break;
+				case ClassType.Struct:
+					braceStyle = policy.StructBraceStyle;
+					indentBody = policy.IndentStructBody;
+					break;
+				case ClassType.Interface:
+					braceStyle = policy.InterfaceBraceStyle;
+					indentBody = policy.IndentInterfaceBody;
+					break;
+				case ClassType.Enum:
+					braceStyle = policy.EnumBraceStyle;
+					indentBody = policy.IndentEnumBody;
+					break;
+				default:
+					throw new InvalidOperationException("unsupported class type : " + typeDeclaration.ClassType);
+			}
+			
+			foreach (var constraint in typeDeclaration.Constraints)
+				constraint.AcceptVisitor (this);
+
+			FixOpenBrace(braceStyle, typeDeclaration.LBraceToken);
+
+			if (indentBody)
+				curIndent.Push(IndentType.Block);
+			bool startFormat = true;
+			bool first = true;
+			VisitChildrenToFormat(typeDeclaration, child => {
+				if (first) {
+					startFormat = child.StartLocation > typeDeclaration.LBraceToken.StartLocation;
+					first = false;
+				}
+				if (child.Role == Roles.LBrace) {
+					startFormat = true;
+					if (braceStyle != BraceStyle.DoNotChange)
+						EnsureMinimumNewLinesAfter(child, GetTypeLevelNewLinesFor(child));
+					return;
+				}
+				if (child.Role == Roles.RBrace) {
+					startFormat = false;
+					return;
+				}
+				if (!startFormat || !NoWhitespacePredicate (child))
+					return;
+				if (child.Role == Roles.Comma) {
+					ForceSpacesBeforeRemoveNewLines (child, false);
+					EnsureMinimumNewLinesAfter(child, 1);
+					return;
+				} 
+				if (NoWhitespacePredicate(child))
+					FixIndentationForceNewLine(child);
+				child.AcceptVisitor(this);
+				if (NoWhitespacePredicate(child) && child.GetNextSibling (NoWhitespacePredicate).Role != Roles.Comma)
+					EnsureMinimumNewLinesAfter(child, GetTypeLevelNewLinesFor(child));
+			});
+
+			if (indentBody)
+				curIndent.Pop();
+
+			FixClosingBrace(braceStyle, typeDeclaration.RBraceToken);
+		}
+
+		int GetTypeLevelNewLinesFor(AstNode child)
+		{
+			var blankLines = 1;
+			var nextSibling = child.GetNextSibling(NoWhitespacePredicate);
+			if (child is PreProcessorDirective) {
+				var directive = (PreProcessorDirective)child;
+				if (directive.Type == PreProcessorDirectiveType.Region) {
+					blankLines += policy.MinimumBlankLinesInsideRegion;
+				}
+				if (directive.Type == PreProcessorDirectiveType.Endregion) {
+					if (child.GetNextSibling(NoWhitespacePredicate) is CSharpTokenNode)
+						return 1;
+					blankLines += policy.MinimumBlankLinesAroundRegion;
+				}
+				return blankLines;
+			}
+
+			if (nextSibling is PreProcessorDirective) {
+				var directive = (PreProcessorDirective)nextSibling;
+				if (directive.Type == PreProcessorDirectiveType.Region) {
+					if (child is CSharpTokenNode)
+						return 1;
+					blankLines += policy.MinimumBlankLinesAroundRegion;
+				}
+				if (directive.Type == PreProcessorDirectiveType.Endregion)
+					blankLines += policy.MinimumBlankLinesInsideRegion;
+				if (directive.Type == PreProcessorDirectiveType.Endif)
+					return -1;
+				if (directive.Type == PreProcessorDirectiveType.Undef)
+					return -1;
+				return blankLines;
+			}
+			if (child.Role == Roles.LBrace)
+				return 1;
+			if (child is Comment)
+				return 1;
+			if (child is EventDeclaration) {
+				if (nextSibling is EventDeclaration) {
+					blankLines += policy.MinimumBlankLinesBetweenEventFields;
+					return blankLines;
+				}
+			}
+
+			if (child is FieldDeclaration || child is FixedFieldDeclaration) {
+				if (nextSibling is FieldDeclaration || nextSibling is FixedFieldDeclaration) {
+					blankLines += policy.MinimumBlankLinesBetweenFields;
+					return blankLines;
+				}
+			}
+			
+			if (child is TypeDeclaration) {
+				if (nextSibling is TypeDeclaration) {
+					blankLines += policy.MinimumBlankLinesBetweenTypes;
+					return blankLines;
+				}
+			}
+
+			if (nextSibling.Role == Roles.TypeMemberRole)
+				blankLines += policy.MinimumBlankLinesBetweenMembers;
+			return blankLines;
+		}
+
+		public override void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			ForceSpacesBefore(delegateDeclaration.LParToken, policy.SpaceBeforeDelegateDeclarationParentheses);
+			if (delegateDeclaration.Parameters.Any()) {
+				ForceSpacesAfter(delegateDeclaration.LParToken, policy.SpaceWithinDelegateDeclarationParentheses);
+				ForceSpacesBefore(delegateDeclaration.RParToken, policy.SpaceWithinDelegateDeclarationParentheses);
+			} else {
+				ForceSpacesAfter(delegateDeclaration.LParToken, policy.SpaceBetweenEmptyDelegateDeclarationParentheses);
+				ForceSpacesBefore(delegateDeclaration.RParToken, policy.SpaceBetweenEmptyDelegateDeclarationParentheses);
+			}
+			FormatCommas(delegateDeclaration, policy.SpaceBeforeDelegateDeclarationParameterComma, policy.SpaceAfterDelegateDeclarationParameterComma);
+
+			base.VisitDelegateDeclaration(delegateDeclaration);
+		}
+
+		public override void VisitComment(Comment comment)
+		{
+			if (comment.StartsLine && !HadErrors && (!policy.KeepCommentsAtFirstColumn || comment.StartLocation.Column > 1))
+				FixIndentation(comment);
+		}
+
+		public override void VisitConstraint(Constraint constraint)
+		{
+			VisitChildrenToFormat (constraint, node => {
+				if (node is AstType) {
+					node.AcceptVisitor (this);
+				} else if (node.Role == Roles.LPar) {
+					ForceSpacesBefore (node, false);
+					ForceSpacesAfter (node, false);
+				} else if (node.Role ==Roles.Comma) {
+					ForceSpacesBefore (node, false);
+					ForceSpacesAfter (node, true);
+				}
+			});
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Query.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Query.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Query.cs	(revision 11807)
@@ -0,0 +1,124 @@
+//
+// AstFormattingVisitor_Query.cs
+//
+// Author:
+//       LuÃ­s Reis <luiscubal@gmail.com>
+//
+// Copyright (c) 2013 LuÃ­s Reis
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	partial class FormattingVisitor
+	{
+		int GetUpdatedStartLocation(QueryExpression queryExpression)
+		{
+			//TODO
+			return queryExpression.StartLocation.Column;
+		}
+
+		public override void VisitQueryExpression(QueryExpression queryExpression)
+		{
+			var oldIndent = curIndent.Clone();
+
+			var column = GetUpdatedStartLocation(queryExpression);
+
+			int extraSpaces = column - 1 - (curIndent.CurIndent / options.TabSize);
+			if (extraSpaces < 0) {
+				//This check should probably be removed in the future, when GetUpdatedStartLocation is implemented
+				extraSpaces = 0;
+			}
+
+			curIndent.ExtraSpaces = extraSpaces;
+			VisitChildren(queryExpression);
+
+			curIndent = oldIndent;
+		}
+
+		public override void VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			FixClauseIndentation(queryFromClause, queryFromClause.FromKeyword);
+		}
+
+		public override void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			VisitChildren(queryContinuationClause);
+		}
+
+		public override void VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			FixClauseIndentation(queryGroupClause, queryGroupClause.GroupKeyword);
+		}
+
+		public override void VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			FixClauseIndentation(queryJoinClause, queryJoinClause.JoinKeyword);
+		}
+
+		public override void VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			FixClauseIndentation(queryLetClause, queryLetClause.LetKeyword);
+		}
+
+		public override void VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			FixClauseIndentation(querySelectClause, querySelectClause.SelectKeyword);
+		}
+
+		public override void VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			FixClauseIndentation(queryOrderClause, queryOrderClause.OrderbyToken);
+		}
+
+		public override void VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			FixClauseIndentation(queryWhereClause, queryWhereClause.WhereKeyword);
+		}
+
+		void FixClauseIndentation(QueryClause clause, AstNode keyword) {
+			var parentExpression = clause.GetParent<QueryExpression>();
+			bool isFirstClause = parentExpression.Clauses.First() == clause;
+			if (!isFirstClause) {
+				PlaceOnNewLine(policy.NewLineBeforeNewQueryClause, keyword);
+			}
+
+			int extraSpaces = options.IndentSize;
+			curIndent.ExtraSpaces += extraSpaces;
+			foreach (var child in clause.Children) {
+				var expression = child as Expression;
+				if (expression != null) {
+					FixIndentation(child);
+					child.AcceptVisitor(this);
+				}
+
+				var tokenNode = child as CSharpTokenNode;
+				if (tokenNode != null) {
+					if (tokenNode.GetNextSibling(NoWhitespacePredicate).StartLocation.Line != tokenNode.EndLocation.Line) {
+						ForceSpacesAfter(tokenNode, false);
+					}
+				}
+			}
+			curIndent.ExtraSpaces -= extraSpaces;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Statements.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Statements.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_Statements.cs	(revision 11807)
@@ -0,0 +1,517 @@
+//
+// AstFormattingVisitor_Statements.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Linq;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	partial class FormattingVisitor : DepthFirstAstVisitor
+	{
+		public override void VisitExpressionStatement(ExpressionStatement expressionStatement)
+		{
+			base.VisitExpressionStatement(expressionStatement);
+			FixSemicolon(expressionStatement.SemicolonToken);
+		}
+
+		void VisitBlockWithoutFixingBraces(BlockStatement blockStatement, bool indent)
+		{
+			if (indent) {
+				curIndent.Push(IndentType.Block);
+			}
+
+			VisitChildrenToFormat (blockStatement, child => {
+				if (child.Role == Roles.LBrace || child.Role == Roles.RBrace) {
+					return;
+				}
+
+				if (child is Statement) {
+					FixStatementIndentation(child.StartLocation);
+					child.AcceptVisitor(this);
+				} else if (child is Comment) {
+					child.AcceptVisitor(this);
+				} else if (child is NewLineNode) {
+					// ignore
+				} else {
+					// pre processor directives at line start, if they are there.
+					if (child.StartLocation.Column > 1)
+						FixStatementIndentation(child.StartLocation);
+				}
+			});
+
+			if (indent) {
+				curIndent.Pop ();
+			}
+		}
+
+		public override void VisitBlockStatement(BlockStatement blockStatement)
+		{
+			FixIndentation(blockStatement);
+			VisitBlockWithoutFixingBraces(blockStatement, policy.IndentBlocks);
+			FixIndentation(blockStatement.RBraceToken);
+		}
+
+		public override void VisitBreakStatement(BreakStatement breakStatement)
+		{
+			FixSemicolon(breakStatement.SemicolonToken);
+		}
+
+		public override void VisitCheckedStatement(CheckedStatement checkedStatement)
+		{
+			FixEmbeddedStatment(policy.StatementBraceStyle, checkedStatement.Body);
+		}
+
+		public override void VisitContinueStatement(ContinueStatement continueStatement)
+		{
+			FixSemicolon(continueStatement.SemicolonToken);
+		}
+
+		public override void VisitEmptyStatement(EmptyStatement emptyStatement)
+		{
+			// Empty
+		}
+
+		public override void VisitFixedStatement(FixedStatement fixedStatement)
+		{
+			FixEmbeddedStatment(policy.StatementBraceStyle, fixedStatement.EmbeddedStatement);
+		}
+
+		public override void VisitForeachStatement(ForeachStatement foreachStatement)
+		{
+			ForceSpacesBeforeRemoveNewLines(foreachStatement.LParToken, policy.SpaceBeforeForeachParentheses);
+
+			ForceSpacesAfter(foreachStatement.LParToken, policy.SpacesWithinForeachParentheses);
+			ForceSpacesBeforeRemoveNewLines(foreachStatement.RParToken, policy.SpacesWithinForeachParentheses);
+			
+			FixEmbeddedStatment(policy.StatementBraceStyle, foreachStatement.EmbeddedStatement);
+		}
+
+		void FixEmbeddedStatment(BraceStyle braceStyle, AstNode node)
+		{
+			FixEmbeddedStatment(braceStyle, null, false, node);
+		}
+
+		void FixEmbeddedStatment(BraceStyle braceStyle, CSharpTokenNode token, bool allowInLine, AstNode node, bool statementAlreadyIndented = false)
+		{
+			if (node == null)
+				return;
+			bool isBlock = node is BlockStatement;
+			FormattingChanges.TextReplaceAction beginBraceAction = null;
+			FormattingChanges.TextReplaceAction endBraceAction = null;
+			BlockStatement closeBlockToBeFixed = null;
+			if (isBlock) {
+				BlockStatement block = node as BlockStatement;
+				if (allowInLine && block.StartLocation.Line == block.EndLocation.Line && block.Statements.Count() <= 1) {
+					if (block.Statements.Count() == 1)
+						nextStatementIndent = " ";
+				} else {
+					if (!statementAlreadyIndented)
+						FixOpenBrace(braceStyle, block.LBraceToken);
+					closeBlockToBeFixed = block;
+				}
+
+				if (braceStyle == BraceStyle.NextLineShifted2)
+					curIndent.Push(IndentType.Block);
+			} else {
+				if (allowInLine && token.StartLocation.Line == node.EndLocation.Line) {
+					nextStatementIndent = " ";
+				}
+			}
+			bool pushed = false;
+
+			if (policy.IndentBlocks && !(
+				policy.AlignEmbeddedStatements && node is IfElseStatement && node.Parent is IfElseStatement || 
+				policy.AlignEmbeddedStatements && node is UsingStatement && node.Parent is UsingStatement || 
+				policy.AlignEmbeddedStatements && node is LockStatement && node.Parent is LockStatement)) { 
+				curIndent.Push(IndentType.Block);
+				pushed = true;
+			}
+			if (isBlock) {
+				VisitBlockWithoutFixingBraces((BlockStatement)node, false);
+			} else {
+				if (!statementAlreadyIndented) {
+					PlaceOnNewLine(policy.EmbeddedStatementPlacement, node);
+					nextStatementIndent = null;
+				}
+				node.AcceptVisitor(this);
+			}
+			nextStatementIndent = null;
+			if (pushed)
+				curIndent.Pop();
+			if (beginBraceAction != null && endBraceAction != null) {
+				beginBraceAction.DependsOn = endBraceAction;
+				endBraceAction.DependsOn = beginBraceAction;
+			}
+
+			if (isBlock && braceStyle == BraceStyle.NextLineShifted2)
+				curIndent.Pop();
+			if (closeBlockToBeFixed != null) {
+				FixClosingBrace(braceStyle, closeBlockToBeFixed.RBraceToken);
+			}
+
+		}
+
+		public bool IsLineIsEmptyUpToEol(TextLocation startLocation)
+		{
+			return IsLineIsEmptyUpToEol(document.GetOffset(startLocation) - 1);
+		}
+
+		bool IsLineIsEmptyUpToEol(int startOffset)
+		{
+			for (int offset = startOffset - 1; offset >= 0; offset--) {
+				char ch = document.GetCharAt(offset);
+				if (ch != ' ' && ch != '\t') {
+					return NewLine.IsNewLine (ch);
+				}
+			}
+			return true;
+		}
+
+		int SearchWhitespaceStart(int startOffset)
+		{
+			if (startOffset < 0) {
+				throw new ArgumentOutOfRangeException ("startoffset", "value : " + startOffset);
+			}
+			for (int offset = startOffset - 1; offset >= 0; offset--) {
+				char ch = document.GetCharAt(offset);
+				if (!Char.IsWhiteSpace(ch)) {
+					return offset + 1;
+				}
+			}
+			return 0;
+		}
+
+		int SearchWhitespaceEnd(int startOffset)
+		{
+			if (startOffset > document.TextLength) {
+				throw new ArgumentOutOfRangeException ("startoffset", "value : " + startOffset);
+			}
+			for (int offset = startOffset + 1; offset < document.TextLength; offset++) {
+				char ch = document.GetCharAt(offset);
+				if (!Char.IsWhiteSpace(ch)) {
+					return offset + 1;
+				}
+			}
+			return document.TextLength - 1;
+		}
+
+		int SearchWhitespaceLineStart(int startOffset)
+		{
+			if (startOffset < 0) {
+				throw new ArgumentOutOfRangeException ("startoffset", "value : " + startOffset);
+			}
+			for (int offset = startOffset - 1; offset >= 0; offset--) {
+				char ch = document.GetCharAt(offset);
+				if (ch != ' ' && ch != '\t') {
+					return offset + 1;
+				}
+			}
+			return 0;
+		}
+
+		public override void VisitForStatement(ForStatement forStatement)
+		{
+			foreach (AstNode node in forStatement.Children) {
+				if (node.Role == Roles.Semicolon) {
+					if (node.GetNextSibling(NoWhitespacePredicate) is CSharpTokenNode || node.GetNextSibling(NoWhitespacePredicate) is EmptyStatement) {
+						continue;
+					}
+					ForceSpacesBefore(node, policy.SpaceBeforeForSemicolon);
+					ForceSpacesAfter(node, policy.SpaceAfterForSemicolon);
+				} else if (node.Role == Roles.LPar) {
+					ForceSpacesBeforeRemoveNewLines(node, policy.SpaceBeforeForParentheses);
+					ForceSpacesAfter(node, policy.SpacesWithinForParentheses);
+				} else if (node.Role == Roles.RPar) {
+					ForceSpacesBeforeRemoveNewLines(node, policy.SpacesWithinForParentheses);
+				} else if (node.Role == Roles.EmbeddedStatement) {
+					FixEmbeddedStatment(policy.StatementBraceStyle, node);
+				} else {
+					node.AcceptVisitor(this); 
+				}
+			}
+		}
+
+		public override void VisitGotoStatement(GotoStatement gotoStatement)
+		{
+			VisitChildren(gotoStatement);
+			FixSemicolon(gotoStatement.SemicolonToken);
+		}
+
+		public override void VisitIfElseStatement(IfElseStatement ifElseStatement)
+		{
+			ForceSpacesBeforeRemoveNewLines(ifElseStatement.LParToken, policy.SpaceBeforeIfParentheses);
+			Align(ifElseStatement.LParToken, ifElseStatement.Condition, policy.SpacesWithinIfParentheses);
+			ForceSpacesBeforeRemoveNewLines(ifElseStatement.RParToken, policy.SpacesWithinIfParentheses);
+
+
+			if (!ifElseStatement.TrueStatement.IsNull) {
+				FixEmbeddedStatment(policy.StatementBraceStyle, ifElseStatement.IfToken, policy.AllowIfBlockInline, ifElseStatement.TrueStatement);
+			}
+
+			if (!ifElseStatement.FalseStatement.IsNull) {
+				var placeElseOnNewLine = policy.ElseNewLinePlacement;
+				if (!(ifElseStatement.TrueStatement is BlockStatement)) {
+					placeElseOnNewLine = NewLinePlacement.NewLine;
+				}
+				PlaceOnNewLine(placeElseOnNewLine, ifElseStatement.ElseToken);
+				if (ifElseStatement.FalseStatement is IfElseStatement) {
+					PlaceOnNewLine(policy.ElseIfNewLinePlacement, ((IfElseStatement)ifElseStatement.FalseStatement).IfToken);
+				}
+				FixEmbeddedStatment(policy.StatementBraceStyle, ifElseStatement.ElseToken, policy.AllowIfBlockInline, ifElseStatement.FalseStatement, ifElseStatement.FalseStatement is IfElseStatement);
+			}
+		}
+
+		public override void VisitLabelStatement(LabelStatement labelStatement)
+		{
+			// TODO
+			VisitChildren(labelStatement);
+		}
+
+		public override void VisitLockStatement(LockStatement lockStatement)
+		{
+			ForceSpacesBeforeRemoveNewLines(lockStatement.LParToken, policy.SpaceBeforeLockParentheses);
+
+			ForceSpacesAfter(lockStatement.LParToken, policy.SpacesWithinLockParentheses);
+			ForceSpacesBeforeRemoveNewLines(lockStatement.RParToken, policy.SpacesWithinLockParentheses);
+
+			FixEmbeddedStatment(policy.StatementBraceStyle, lockStatement.EmbeddedStatement);
+		}
+
+		public override void VisitReturnStatement(ReturnStatement returnStatement)
+		{
+			VisitChildren(returnStatement);
+			FixSemicolon(returnStatement.SemicolonToken);
+		}
+
+		public override void VisitSwitchStatement(SwitchStatement switchStatement)
+		{
+			ForceSpacesBeforeRemoveNewLines(switchStatement.LParToken, policy.SpaceBeforeSwitchParentheses);
+
+			ForceSpacesAfter(switchStatement.LParToken, policy.SpacesWithinSwitchParentheses);
+			ForceSpacesBeforeRemoveNewLines(switchStatement.RParToken, policy.SpacesWithinSwitchParentheses);
+
+			FixOpenBrace(policy.StatementBraceStyle, switchStatement.LBraceToken);
+			VisitChildren(switchStatement);
+			FixClosingBrace(policy.StatementBraceStyle, switchStatement.RBraceToken);
+		}
+
+		public override void VisitSwitchSection(SwitchSection switchSection)
+		{
+			if (policy.IndentSwitchBody) {
+				curIndent.Push(IndentType.Block);
+			}
+
+			foreach (CaseLabel label in switchSection.CaseLabels) {
+				FixStatementIndentation(label.StartLocation);
+				label.AcceptVisitor(this);
+			}
+			if (policy.IndentCaseBody) {
+				curIndent.Push(IndentType.Block);
+			}
+
+			foreach (var stmt in switchSection.Statements) {
+				if (stmt is BreakStatement && !policy.IndentBreakStatements && policy.IndentCaseBody) {
+					curIndent.Pop();
+					FixStatementIndentation(stmt.StartLocation);
+					stmt.AcceptVisitor(this);
+					curIndent.Push(IndentType.Block);
+					continue;
+				}
+				FixStatementIndentation(stmt.StartLocation);
+				stmt.AcceptVisitor(this);
+			}
+			if (policy.IndentCaseBody) {
+				curIndent.Pop ();
+			}
+
+			if (policy.IndentSwitchBody) {
+				curIndent.Pop ();
+			}
+		}
+
+		public override void VisitCaseLabel(CaseLabel caseLabel)
+		{
+			ForceSpacesBefore(caseLabel.ColonToken, false);
+		}
+
+		public override void VisitThrowStatement(ThrowStatement throwStatement)
+		{
+			VisitChildren(throwStatement);
+			FixSemicolon(throwStatement.SemicolonToken);
+		}
+
+		public override void VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
+		{
+			if (!tryCatchStatement.TryBlock.IsNull) {
+				FixEmbeddedStatment(policy.StatementBraceStyle, tryCatchStatement.TryBlock);
+			}
+
+			foreach (CatchClause clause in tryCatchStatement.CatchClauses) {
+				PlaceOnNewLine(policy.CatchNewLinePlacement, clause.CatchToken);
+				if (!clause.LParToken.IsNull) {
+					ForceSpacesBeforeRemoveNewLines(clause.LParToken, policy.SpaceBeforeCatchParentheses);
+
+					ForceSpacesAfter(clause.LParToken, policy.SpacesWithinCatchParentheses);
+					ForceSpacesBeforeRemoveNewLines(clause.RParToken, policy.SpacesWithinCatchParentheses);
+				}
+				FixEmbeddedStatment(policy.StatementBraceStyle, clause.Body);
+			}
+
+			if (!tryCatchStatement.FinallyBlock.IsNull) {
+				PlaceOnNewLine(policy.FinallyNewLinePlacement, tryCatchStatement.FinallyToken);
+
+				FixEmbeddedStatment(policy.StatementBraceStyle, tryCatchStatement.FinallyBlock);
+			}
+
+		}
+
+		public override void VisitCatchClause(CatchClause catchClause)
+		{
+			// Handled in TryCatchStatement
+		}
+
+		public override void VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
+		{
+			FixEmbeddedStatment(policy.StatementBraceStyle, uncheckedStatement.Body);
+		}
+
+		public override void VisitUnsafeStatement(UnsafeStatement unsafeStatement)
+		{
+			FixEmbeddedStatment(policy.StatementBraceStyle, unsafeStatement.Body);
+		}
+
+		public override void VisitUsingStatement(UsingStatement usingStatement)
+		{
+			ForceSpacesBeforeRemoveNewLines(usingStatement.LParToken, policy.SpaceBeforeUsingParentheses);
+
+			Align(usingStatement.LParToken, usingStatement.ResourceAcquisition, policy.SpacesWithinUsingParentheses);
+
+			ForceSpacesBeforeRemoveNewLines(usingStatement.RParToken, policy.SpacesWithinUsingParentheses);
+
+			FixEmbeddedStatment(policy.StatementBraceStyle, usingStatement.EmbeddedStatement);
+		}
+
+		public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
+		{
+			var returnType = variableDeclarationStatement.Type;
+			returnType.AcceptVisitor(this);
+			if ((variableDeclarationStatement.Modifiers & Modifiers.Const) == Modifiers.Const) {
+				ForceSpacesAround(returnType, true);
+			} else {
+				ForceSpacesAfter(returnType, true);
+			}
+			var lastLoc = variableDeclarationStatement.StartLocation;
+			foreach (var initializer in variableDeclarationStatement.Variables) {
+				if (lastLoc.Line != initializer.StartLocation.Line) {
+					FixStatementIndentation(initializer.StartLocation);
+					lastLoc = initializer.StartLocation;
+				}
+				initializer.AcceptVisitor(this);
+			}
+
+			FormatCommas(variableDeclarationStatement, policy.SpaceBeforeLocalVariableDeclarationComma, policy.SpaceAfterLocalVariableDeclarationComma);
+			FixSemicolon(variableDeclarationStatement.SemicolonToken);
+		}
+
+		public override void VisitDoWhileStatement(DoWhileStatement doWhileStatement)
+		{
+			FixEmbeddedStatment(policy.StatementBraceStyle, doWhileStatement.EmbeddedStatement);
+			PlaceOnNewLine(doWhileStatement.EmbeddedStatement is BlockStatement ? policy.WhileNewLinePlacement : NewLinePlacement.NewLine, doWhileStatement.WhileToken);
+
+			Align(doWhileStatement.LParToken, doWhileStatement.Condition, policy.SpacesWithinWhileParentheses);
+			ForceSpacesBeforeRemoveNewLines(doWhileStatement.RParToken, policy.SpacesWithinWhileParentheses);
+		}
+
+		void Align(AstNode lPar, AstNode alignNode, bool space)
+		{
+			int extraSpaces = 0;
+			var useExtraSpaces = lPar.StartLocation.Line == alignNode.StartLocation.Line;
+			if (useExtraSpaces) {
+				extraSpaces = Math.Max(0, lPar.StartLocation.Column + (space ? 1 : 0) - curIndent.IndentString.Length);
+				curIndent.ExtraSpaces += extraSpaces;
+				ForceSpacesAfter(lPar, space);
+			} else {
+				curIndent.Push(IndentType.Continuation); 
+				FixIndentation(alignNode);
+			}
+			alignNode.AcceptVisitor(this);
+
+			if (useExtraSpaces) {
+				curIndent.ExtraSpaces -= extraSpaces;
+			} else {
+				curIndent.Pop();
+			}
+
+		}
+
+		public override void VisitWhileStatement(WhileStatement whileStatement)
+		{
+			ForceSpacesBeforeRemoveNewLines(whileStatement.LParToken, policy.SpaceBeforeWhileParentheses);
+			Align(whileStatement.LParToken, whileStatement.Condition, policy.SpacesWithinWhileParentheses);
+			ForceSpacesBeforeRemoveNewLines(whileStatement.RParToken, policy.SpacesWithinWhileParentheses);
+
+			FixEmbeddedStatment(policy.StatementBraceStyle, whileStatement.EmbeddedStatement);
+		}
+
+		public override void VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
+		{
+			FixSemicolon(yieldBreakStatement.SemicolonToken);
+		}
+
+		public override void VisitYieldReturnStatement(YieldReturnStatement yieldStatement)
+		{
+			yieldStatement.Expression.AcceptVisitor(this);
+			FixSemicolon(yieldStatement.SemicolonToken);
+		}
+
+		public override void VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			if (!variableInitializer.AssignToken.IsNull) {
+				ForceSpacesAround(variableInitializer.AssignToken, policy.SpaceAroundAssignment);
+			}
+			if (!variableInitializer.Initializer.IsNull) {
+				int extraSpaces = 0;
+				var useExtraSpaces = variableInitializer.AssignToken.StartLocation.Line == variableInitializer.Initializer.StartLocation.Line;
+				if (useExtraSpaces) {
+					extraSpaces = Math.Max(0, variableInitializer.AssignToken.StartLocation.Column + 1 - curIndent.IndentString.Length);
+					curIndent.ExtraSpaces += extraSpaces;
+				} else {
+					curIndent.Push(IndentType.Continuation); 
+					FixIndentation(variableInitializer.Initializer);
+				}
+				variableInitializer.Initializer.AcceptVisitor(this);
+
+				if (useExtraSpaces) {
+					curIndent.ExtraSpaces -= extraSpaces;
+				} else {
+					curIndent.Pop();
+				}
+			}
+
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_TypeMembers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_TypeMembers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/FormattingVisitor_TypeMembers.cs	(revision 11807)
@@ -0,0 +1,477 @@
+//
+// AstFormattingVisitor_TypeMembers.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	partial class FormattingVisitor : DepthFirstAstVisitor
+	{
+		public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			FixAttributesAndDocComment(propertyDeclaration);
+			bool oneLine = false;
+			bool fixClosingBrace = false;
+			PropertyFormatting propertyFormatting;
+
+			if ((propertyDeclaration.Getter.IsNull || propertyDeclaration.Getter.Body.IsNull) &&
+			    (propertyDeclaration.Setter.IsNull || propertyDeclaration.Setter.Body.IsNull)) {
+				propertyFormatting = policy.AutoPropertyFormatting;
+			} else {
+				propertyFormatting = policy.SimplePropertyFormatting;
+			}
+
+			switch (propertyFormatting) {
+				case PropertyFormatting.AllowOneLine:
+					bool isSimple = IsSimpleAccessor(propertyDeclaration.Getter) && IsSimpleAccessor(propertyDeclaration.Setter);
+					int accessorLine = propertyDeclaration.RBraceToken.StartLocation.Line;
+					if (!propertyDeclaration.Getter.IsNull && propertyDeclaration.Setter.IsNull) {
+						accessorLine = propertyDeclaration.Getter.StartLocation.Line;
+					} else if (propertyDeclaration.Getter.IsNull && !propertyDeclaration.Setter.IsNull) {
+						accessorLine = propertyDeclaration.Setter.StartLocation.Line;
+					} else {
+						var acc = propertyDeclaration.Getter.StartLocation < propertyDeclaration.Setter.StartLocation ?
+							propertyDeclaration.Getter : propertyDeclaration.Setter;
+						accessorLine = acc.StartLocation.Line;
+					}
+					if (isSimple && 
+					    Math.Min(propertyDeclaration.Getter.StartLocation.Line, propertyDeclaration.Setter.StartLocation.Line) == propertyDeclaration.LBraceToken.StartLocation.Line &&
+				        propertyDeclaration.Getter.StartLocation.Line != propertyDeclaration.Setter.StartLocation.Line)
+						goto case PropertyFormatting.ForceOneLine;
+					if (!isSimple || propertyDeclaration.LBraceToken.StartLocation.Line != accessorLine) {
+						fixClosingBrace = true;
+						FixOpenBrace(policy.PropertyBraceStyle, propertyDeclaration.LBraceToken);
+					} else {
+						ForceSpacesBefore(propertyDeclaration.Getter, true);
+						ForceSpacesBefore(propertyDeclaration.Setter, true);
+						ForceSpacesBeforeRemoveNewLines(propertyDeclaration.RBraceToken, true);
+						oneLine = true;
+					}
+					break;
+				case PropertyFormatting.ForceNewLine:
+					fixClosingBrace = true;
+					FixOpenBrace(policy.PropertyBraceStyle, propertyDeclaration.LBraceToken);
+					break;
+				case PropertyFormatting.ForceOneLine:
+					isSimple = IsSimpleAccessor(propertyDeclaration.Getter) && IsSimpleAccessor(propertyDeclaration.Setter);
+					if (isSimple) {
+						var lBraceToken = propertyDeclaration.LBraceToken;
+						var rBraceToken = propertyDeclaration.RBraceToken;
+						ForceSpacesBeforeRemoveNewLines(lBraceToken, true);
+						if (!propertyDeclaration.Getter.IsNull)
+							ForceSpacesBeforeRemoveNewLines(propertyDeclaration.Getter, true);
+						if (!propertyDeclaration.Setter.IsNull)
+							ForceSpacesBeforeRemoveNewLines(propertyDeclaration.Setter, true);
+
+						ForceSpacesBeforeRemoveNewLines(rBraceToken, true);
+						oneLine = true;
+					} else {
+						fixClosingBrace = true;
+						FixOpenBrace(policy.PropertyBraceStyle, propertyDeclaration.LBraceToken);
+					}
+					break;
+			}
+			if (policy.IndentPropertyBody)
+				curIndent.Push(IndentType.Block);
+
+			FormatAccessor(propertyDeclaration.Getter, policy.PropertyGetBraceStyle, policy.SimpleGetBlockFormatting, oneLine);
+			FormatAccessor(propertyDeclaration.Setter, policy.PropertySetBraceStyle, policy.SimpleSetBlockFormatting, oneLine);
+
+			if (policy.IndentPropertyBody) {
+				curIndent.Pop();
+			}
+			if (fixClosingBrace)
+				FixClosingBrace(policy.PropertyBraceStyle, propertyDeclaration.RBraceToken);
+
+		}
+
+		void FormatAccessor(Accessor accessor, BraceStyle braceStyle, PropertyFormatting blockFormatting, bool oneLine)
+		{
+			if (accessor.IsNull)
+				return;
+			if (!oneLine) {
+				if (!IsLineIsEmptyUpToEol(accessor.StartLocation)) {
+					int offset = this.document.GetOffset(accessor.StartLocation);
+					int start = SearchWhitespaceStart(offset);
+					string indentString = this.curIndent.IndentString;
+					AddChange(start, offset - start, this.options.EolMarker + indentString);
+				} else {
+					FixIndentation(accessor);
+				}
+			} else {
+				blockFormatting = PropertyFormatting.ForceOneLine;
+				if (!accessor.Body.IsNull) {
+					ForceSpacesBeforeRemoveNewLines(accessor.Body.LBraceToken, true);
+					ForceSpacesBeforeRemoveNewLines(accessor.Body.RBraceToken, true);
+				}
+			}
+
+		
+			if (!accessor.IsNull) {
+				if (!accessor.Body.IsNull) {
+					if (IsSimpleAccessor (accessor)) {
+						switch (blockFormatting) {
+							case PropertyFormatting.AllowOneLine:
+								if (accessor.Body.LBraceToken.StartLocation.Line != accessor.Body.RBraceToken.StartLocation.Line)
+									goto case PropertyFormatting.ForceNewLine;
+								nextStatementIndent = " ";
+								VisitBlockWithoutFixingBraces(accessor.Body, policy.IndentBlocks);
+								nextStatementIndent = null;
+								if (!oneLine)
+									ForceSpacesBeforeRemoveNewLines(accessor.Body.RBraceToken, true);
+								break;
+							case PropertyFormatting.ForceOneLine:
+								FixOpenBrace(BraceStyle.EndOfLine, accessor.Body.LBraceToken);
+
+
+								var statement = accessor.Body.Statements.FirstOrDefault();
+								if (statement != null) {
+									ForceSpacesBeforeRemoveNewLines(statement, true);
+									statement.AcceptVisitor(this);
+								}
+								if (!oneLine)
+									ForceSpacesBeforeRemoveNewLines(accessor.Body.RBraceToken, true);
+								break;
+							case PropertyFormatting.ForceNewLine:
+								FixOpenBrace(braceStyle, accessor.Body.LBraceToken);
+								VisitBlockWithoutFixingBraces(accessor.Body, policy.IndentBlocks);
+								if (!oneLine)
+									FixClosingBrace(braceStyle, accessor.Body.RBraceToken);
+								break;
+						}
+					} else {
+						FixOpenBrace(braceStyle, accessor.Body.LBraceToken);
+						VisitBlockWithoutFixingBraces(accessor.Body, policy.IndentBlocks);
+						FixClosingBrace(braceStyle, accessor.Body.RBraceToken);
+					}
+				} 
+			}
+		}
+
+		public override void VisitAccessor(Accessor accessor)
+		{
+			FixAttributesAndDocComment(accessor);
+
+			base.VisitAccessor(accessor);
+		}
+
+		public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			FixAttributesAndDocComment(indexerDeclaration);
+
+			ForceSpacesBefore(indexerDeclaration.LBracketToken, policy.SpaceBeforeIndexerDeclarationBracket);
+			ForceSpacesAfter(indexerDeclaration.LBracketToken, policy.SpaceWithinIndexerDeclarationBracket);
+
+			FormatArguments(indexerDeclaration);
+
+			bool oneLine = false;
+			bool fixClosingBrace = false;
+			switch (policy.SimplePropertyFormatting) {
+				case PropertyFormatting.AllowOneLine:
+					bool isSimple = IsSimpleAccessor(indexerDeclaration.Getter) && IsSimpleAccessor(indexerDeclaration.Setter);
+					int accessorLine = indexerDeclaration.RBraceToken.StartLocation.Line;
+					if (!indexerDeclaration.Getter.IsNull && indexerDeclaration.Setter.IsNull) {
+						accessorLine = indexerDeclaration.Getter.StartLocation.Line;
+					} else if (indexerDeclaration.Getter.IsNull && !indexerDeclaration.Setter.IsNull) {
+						accessorLine = indexerDeclaration.Setter.StartLocation.Line;
+					} else {
+						var acc = indexerDeclaration.Getter.StartLocation < indexerDeclaration.Setter.StartLocation ?
+							indexerDeclaration.Getter : indexerDeclaration.Setter;
+						accessorLine = acc.StartLocation.Line;
+					}
+					if (!isSimple || indexerDeclaration.LBraceToken.StartLocation.Line != accessorLine) {
+						fixClosingBrace = true;
+						FixOpenBrace(policy.PropertyBraceStyle, indexerDeclaration.LBraceToken);
+					} else {
+						ForceSpacesBefore(indexerDeclaration.Getter, true);
+						ForceSpacesBefore(indexerDeclaration.Setter, true);
+						ForceSpacesBeforeRemoveNewLines(indexerDeclaration.RBraceToken, true);
+						oneLine = true;
+					}
+					break;
+				case PropertyFormatting.ForceNewLine:
+					fixClosingBrace = true;
+					FixOpenBrace(policy.PropertyBraceStyle, indexerDeclaration.LBraceToken);
+					break;
+				case PropertyFormatting.ForceOneLine:
+					isSimple = IsSimpleAccessor(indexerDeclaration.Getter) && IsSimpleAccessor(indexerDeclaration.Setter);
+					if (isSimple) {
+						int offset = this.document.GetOffset(indexerDeclaration.LBraceToken.StartLocation);
+
+						int start = SearchWhitespaceStart(offset);
+						int end = SearchWhitespaceEnd(offset);
+						AddChange(start, offset - start, " ");
+						AddChange(offset + 1, end - offset - 2, " ");
+
+						offset = this.document.GetOffset(indexerDeclaration.RBraceToken.StartLocation);
+						start = SearchWhitespaceStart(offset);
+						AddChange(start, offset - start, " ");
+						oneLine = true;
+
+					} else {
+						fixClosingBrace = true;
+						FixOpenBrace(policy.PropertyBraceStyle, indexerDeclaration.LBraceToken);
+					}
+					break;
+			}
+
+			if (policy.IndentPropertyBody)
+				curIndent.Push(IndentType.Block);
+
+			FormatAccessor(indexerDeclaration.Getter, policy.PropertyGetBraceStyle, policy.SimpleGetBlockFormatting, oneLine);
+			FormatAccessor(indexerDeclaration.Setter, policy.PropertySetBraceStyle, policy.SimpleSetBlockFormatting, oneLine);
+			if (policy.IndentPropertyBody)
+				curIndent.Pop();
+
+			if (fixClosingBrace)
+				FixClosingBrace(policy.PropertyBraceStyle, indexerDeclaration.RBraceToken);
+		}
+
+		static bool IsSimpleEvent(AstNode node)
+		{
+			return node is EventDeclaration;
+		}
+
+		public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
+		{
+			FixAttributesAndDocComment(eventDeclaration);
+
+			FixOpenBrace(policy.EventBraceStyle, eventDeclaration.LBraceToken);
+			if (policy.IndentEventBody)
+				curIndent.Push(IndentType.Block);
+
+			if (!eventDeclaration.AddAccessor.IsNull) {
+				FixIndentation(eventDeclaration.AddAccessor);
+				if (!eventDeclaration.AddAccessor.Body.IsNull) {
+					if (!policy.AllowEventAddBlockInline || eventDeclaration.AddAccessor.Body.LBraceToken.StartLocation.Line != eventDeclaration.AddAccessor.Body.RBraceToken.StartLocation.Line) {
+						FixOpenBrace(policy.EventAddBraceStyle, eventDeclaration.AddAccessor.Body.LBraceToken);
+						VisitBlockWithoutFixingBraces(eventDeclaration.AddAccessor.Body, policy.IndentBlocks);
+						FixClosingBrace(policy.EventAddBraceStyle, eventDeclaration.AddAccessor.Body.RBraceToken);
+					} else {
+						nextStatementIndent = " ";
+						VisitBlockWithoutFixingBraces(eventDeclaration.AddAccessor.Body, policy.IndentBlocks);
+						nextStatementIndent = null;
+					}
+				}
+			}
+
+			if (!eventDeclaration.RemoveAccessor.IsNull) {
+				FixIndentation(eventDeclaration.RemoveAccessor);
+				if (!eventDeclaration.RemoveAccessor.Body.IsNull) {
+					if (!policy.AllowEventRemoveBlockInline || eventDeclaration.RemoveAccessor.Body.LBraceToken.StartLocation.Line != eventDeclaration.RemoveAccessor.Body.RBraceToken.StartLocation.Line) {
+						FixOpenBrace(policy.EventRemoveBraceStyle, eventDeclaration.RemoveAccessor.Body.LBraceToken);
+						VisitBlockWithoutFixingBraces(eventDeclaration.RemoveAccessor.Body, policy.IndentBlocks);
+						FixClosingBrace(policy.EventRemoveBraceStyle, eventDeclaration.RemoveAccessor.Body.RBraceToken);
+					} else {
+						nextStatementIndent = " ";
+						VisitBlockWithoutFixingBraces(eventDeclaration.RemoveAccessor.Body, policy.IndentBlocks);
+						nextStatementIndent = null;
+					}
+				}
+			}
+
+			if (policy.IndentEventBody)
+				curIndent.Pop();
+
+			FixClosingBrace(policy.EventBraceStyle, eventDeclaration.RBraceToken);
+		}
+
+		public override void VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			FixAttributesAndDocComment(eventDeclaration);
+
+			foreach (var m in eventDeclaration.ModifierTokens) {
+				ForceSpacesAfter(m, true);
+			}
+
+			ForceSpacesBeforeRemoveNewLines(eventDeclaration.EventToken.GetNextSibling(NoWhitespacePredicate), true);
+			eventDeclaration.ReturnType.AcceptVisitor(this);
+			ForceSpacesAfter(eventDeclaration.ReturnType, true);
+			/*
+			var lastLoc = eventDeclaration.StartLocation;
+			curIndent.Push(IndentType.Block);
+			foreach (var initializer in eventDeclaration.Variables) {
+				if (lastLoc.Line != initializer.StartLocation.Line) {
+					FixStatementIndentation(initializer.StartLocation);
+					lastLoc = initializer.StartLocation;
+				}
+				initializer.AcceptVisitor(this);
+			}
+			curIndent.Pop ();
+			*/
+			FixSemicolon(eventDeclaration.SemicolonToken);
+		}
+
+		public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			FixAttributesAndDocComment(fieldDeclaration);
+
+			fieldDeclaration.ReturnType.AcceptVisitor(this);
+			ForceSpacesAfter(fieldDeclaration.ReturnType, true);
+
+			FormatCommas(fieldDeclaration, policy.SpaceBeforeFieldDeclarationComma, policy.SpaceAfterFieldDeclarationComma);
+
+			var lastLoc = fieldDeclaration.ReturnType.StartLocation;
+			foreach (var initializer in fieldDeclaration.Variables) {
+				if (lastLoc.Line != initializer.StartLocation.Line) {
+					curIndent.Push(IndentType.Block);
+					FixStatementIndentation(initializer.StartLocation);
+					curIndent.Pop();
+					lastLoc = initializer.StartLocation;
+				}
+				initializer.AcceptVisitor(this);
+			}
+			FixSemicolon(fieldDeclaration.SemicolonToken);
+		}
+
+		public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			FixAttributesAndDocComment(fixedFieldDeclaration);
+
+			FormatCommas(fixedFieldDeclaration, policy.SpaceBeforeFieldDeclarationComma, policy.SpaceAfterFieldDeclarationComma);
+
+			var lastLoc = fixedFieldDeclaration.StartLocation;
+			curIndent.Push(IndentType.Block);
+			foreach (var initializer in fixedFieldDeclaration.Variables) {
+				if (lastLoc.Line != initializer.StartLocation.Line) {
+					FixStatementIndentation(initializer.StartLocation);
+					lastLoc = initializer.StartLocation;
+				}
+				initializer.AcceptVisitor(this);
+			}
+			curIndent.Pop();
+			FixSemicolon(fixedFieldDeclaration.SemicolonToken);
+		}
+
+		public override void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
+		{
+			FixAttributesAndDocComment(enumMemberDeclaration);
+			var initializer = enumMemberDeclaration.Initializer;
+			if (!initializer.IsNull) {
+				ForceSpacesAround(enumMemberDeclaration.AssignToken, policy.SpaceAroundAssignment);
+				initializer.AcceptVisitor(this);
+			}
+		}
+
+		public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			FixAttributesAndDocComment(methodDeclaration);
+
+			ForceSpacesBefore(methodDeclaration.LParToken, policy.SpaceBeforeMethodDeclarationParentheses);
+			if (methodDeclaration.Parameters.Any()) {
+				ForceSpacesAfter(methodDeclaration.LParToken, policy.SpaceWithinMethodDeclarationParentheses);
+				FormatArguments(methodDeclaration);
+			} else {
+				ForceSpacesAfter(methodDeclaration.LParToken, policy.SpaceBetweenEmptyMethodDeclarationParentheses);
+				ForceSpacesBefore(methodDeclaration.RParToken, policy.SpaceBetweenEmptyMethodDeclarationParentheses);
+			}
+			
+			foreach (var constraint in methodDeclaration.Constraints)
+				constraint.AcceptVisitor(this);
+
+			if (!methodDeclaration.Body.IsNull) {
+				FixOpenBrace(policy.MethodBraceStyle, methodDeclaration.Body.LBraceToken);
+				VisitBlockWithoutFixingBraces(methodDeclaration.Body, policy.IndentMethodBody);
+				FixClosingBrace(policy.MethodBraceStyle, methodDeclaration.Body.RBraceToken);
+			}
+		}
+
+		public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+		{
+			FixAttributesAndDocComment(operatorDeclaration);
+
+			ForceSpacesBefore(operatorDeclaration.LParToken, policy.SpaceBeforeMethodDeclarationParentheses);
+			if (operatorDeclaration.Parameters.Any()) {
+				ForceSpacesAfter(operatorDeclaration.LParToken, policy.SpaceWithinMethodDeclarationParentheses);
+				FormatArguments(operatorDeclaration);
+			} else {
+				ForceSpacesAfter(operatorDeclaration.LParToken, policy.SpaceBetweenEmptyMethodDeclarationParentheses);
+				ForceSpacesBefore(operatorDeclaration.RParToken, policy.SpaceBetweenEmptyMethodDeclarationParentheses);
+			}
+
+			if (!operatorDeclaration.Body.IsNull) {
+				FixOpenBrace(policy.MethodBraceStyle, operatorDeclaration.Body.LBraceToken);
+				VisitBlockWithoutFixingBraces(operatorDeclaration.Body, policy.IndentMethodBody);
+				FixClosingBrace(policy.MethodBraceStyle, operatorDeclaration.Body.RBraceToken);
+			}
+		}
+
+		public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			FixAttributesAndDocComment(constructorDeclaration);
+
+			ForceSpacesBefore(constructorDeclaration.LParToken, policy.SpaceBeforeConstructorDeclarationParentheses);
+			if (constructorDeclaration.Parameters.Any()) {
+				ForceSpacesAfter(constructorDeclaration.LParToken, policy.SpaceWithinConstructorDeclarationParentheses);
+				FormatArguments(constructorDeclaration);
+			} else {
+				ForceSpacesAfter(constructorDeclaration.LParToken, policy.SpaceBetweenEmptyConstructorDeclarationParentheses);
+				ForceSpacesBefore(constructorDeclaration.RParToken, policy.SpaceBetweenEmptyConstructorDeclarationParentheses);
+			}
+
+			var initializer = constructorDeclaration.Initializer;
+			if (!initializer.IsNull) {
+				curIndent.Push(IndentType.Block);
+				PlaceOnNewLine(policy.NewLineBeforeConstructorInitializerColon, constructorDeclaration.ColonToken);
+				PlaceOnNewLine(policy.NewLineAfterConstructorInitializerColon, initializer);
+				initializer.AcceptVisitor(this);
+				curIndent.Pop();
+			}
+			if (!constructorDeclaration.Body.IsNull) {
+				FixOpenBrace(policy.ConstructorBraceStyle, constructorDeclaration.Body.LBraceToken);
+				VisitBlockWithoutFixingBraces(constructorDeclaration.Body, policy.IndentMethodBody);
+				FixClosingBrace(policy.ConstructorBraceStyle, constructorDeclaration.Body.RBraceToken);
+			}
+		}
+		public override void VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
+		{
+			ForceSpacesBefore(constructorInitializer.LParToken, policy.SpaceBeforeMethodCallParentheses);
+			if (constructorInitializer.Arguments.Any()) {
+				ForceSpacesAfter(constructorInitializer.LParToken, policy.SpaceWithinMethodCallParentheses);
+			} else {
+				ForceSpacesAfter(constructorInitializer.LParToken, policy.SpaceBetweenEmptyMethodCallParentheses);
+				ForceSpacesBefore(constructorInitializer.RParToken, policy.SpaceBetweenEmptyMethodCallParentheses);
+			}
+
+			FormatArguments(constructorInitializer);
+
+		}
+		public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			FixAttributesAndDocComment(destructorDeclaration);
+
+			CSharpTokenNode lParen = destructorDeclaration.LParToken;
+			ForceSpaceBefore(lParen, policy.SpaceBeforeConstructorDeclarationParentheses);
+
+			if (!destructorDeclaration.Body.IsNull) {
+				FixOpenBrace(policy.DestructorBraceStyle, destructorDeclaration.Body.LBraceToken);
+				VisitBlockWithoutFixingBraces(destructorDeclaration.Body, policy.IndentMethodBody);
+				FixClosingBrace(policy.DestructorBraceStyle, destructorDeclaration.Body.RBraceToken);
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/GeneratedCodeSettings.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/GeneratedCodeSettings.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/GeneratedCodeSettings.cs	(revision 11807)
@@ -0,0 +1,216 @@
+﻿// 
+// GeneratedCodeSettings.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum GeneratedCodeMember
+	{
+		Unknown,
+
+		StaticFields,
+		InstanceFields,
+		StaticProperties,
+		InstanceProperties,
+		Indexer,
+		Constructors,
+		StaticMethods,
+		InstanceMethods,
+		StaticEvents,
+		InstanceEvents,
+		Operators,
+		NestedTypes
+	}
+
+	public class GeneratedCodeSettings
+	{
+		List<GeneratedCodeMember> codeMemberOrder;
+
+		public List<GeneratedCodeMember> CodeMemberOrder {
+			get {
+				return codeMemberOrder;
+			}
+			set {
+				codeMemberOrder = value;
+			}
+		}
+
+		public bool GenerateCategoryComments {
+			get;
+			set;
+		}
+
+		public bool SubOrderAlphabetical {
+			get;
+			set;
+		}
+
+		public void Apply (AstNode rootNode)
+		{
+			if (rootNode == null)
+				throw new ArgumentNullException ("rootNode");
+			rootNode.AcceptVisitor (new GenerateCodeVisitior (this));
+		}
+
+		public virtual string GetCategoryLabel(GeneratedCodeMember memberCategory)
+		{
+			switch (memberCategory) {
+				case GeneratedCodeMember.StaticFields:
+					return "Static Fields";
+				case GeneratedCodeMember.InstanceFields:
+					return "Fields";
+				case GeneratedCodeMember.StaticProperties:
+					return "Static Properties";
+				case GeneratedCodeMember.InstanceProperties:
+					return "Properties";
+				case GeneratedCodeMember.Indexer:
+					return "Indexer";
+				case GeneratedCodeMember.Constructors:
+					return "Constructors";
+				case GeneratedCodeMember.StaticMethods:
+					return "Static Methods";
+				case GeneratedCodeMember.InstanceMethods:
+					return "Methods";
+				case GeneratedCodeMember.StaticEvents:
+					return "Static Events";
+				case GeneratedCodeMember.InstanceEvents:
+					return "Events";
+				case GeneratedCodeMember.Operators:
+					return "Operators";
+				case GeneratedCodeMember.NestedTypes:
+					return "Nested Types";
+			}
+			return null;
+		}
+
+		class GenerateCodeVisitior : DepthFirstAstVisitor
+		{
+			GeneratedCodeSettings settings;
+
+			public GenerateCodeVisitior(GeneratedCodeSettings settings)
+			{
+				if (settings == null)
+					throw new ArgumentNullException("settings");
+				this.settings = settings;
+			}
+
+			GeneratedCodeMember GetCodeMemberCategory(EntityDeclaration x)
+			{
+				bool isStatic = x.HasModifier(Modifiers.Static) || x.HasModifier(Modifiers.Const);
+				if (x is FieldDeclaration)
+					return isStatic ? GeneratedCodeMember.StaticFields : GeneratedCodeMember.InstanceFields;
+				if (x is IndexerDeclaration)
+					return GeneratedCodeMember.Indexer;
+				if (x is PropertyDeclaration)
+					return isStatic ? GeneratedCodeMember.StaticProperties : GeneratedCodeMember.InstanceProperties;
+				if (x is ConstructorDeclaration || x is DestructorDeclaration)
+					return GeneratedCodeMember.Constructors;
+				if (x is MethodDeclaration)
+					return isStatic ? GeneratedCodeMember.StaticMethods : GeneratedCodeMember.InstanceMethods;
+				if (x is OperatorDeclaration)
+					return GeneratedCodeMember.Operators;
+				if (x is EventDeclaration || x is CustomEventDeclaration)
+					return isStatic ? GeneratedCodeMember.StaticEvents : GeneratedCodeMember.InstanceEvents;
+
+				if (x is TypeDeclaration)
+					return GeneratedCodeMember.NestedTypes;
+
+				return GeneratedCodeMember.Unknown;
+			}
+
+			public override void VisitTypeDeclaration (TypeDeclaration typeDeclaration)
+			{
+				if (typeDeclaration.ClassType == ClassType.Enum)
+					return;
+				var entities = new List<EntityDeclaration> (typeDeclaration.Members);
+				entities.Sort ((x, y) => {
+					int i1 = settings.CodeMemberOrder.IndexOf (GetCodeMemberCategory (x));
+					int i2 = settings.CodeMemberOrder.IndexOf (GetCodeMemberCategory (y));
+					if (i1 != i2)
+						return i1.CompareTo (i2);
+					if (settings.SubOrderAlphabetical)
+						return (x.Name ?? "").CompareTo ((y.Name ?? ""));
+					return entities.IndexOf (x).CompareTo (entities.IndexOf (y));
+				});
+				typeDeclaration.Members.Clear ();
+				typeDeclaration.Members.AddRange (entities);
+
+				if (settings.GenerateCategoryComments) {
+					var curCat = GeneratedCodeMember.Unknown;
+					foreach (var mem in entities) {
+						if (mem.NextSibling is EntityDeclaration)
+							mem.Parent.InsertChildAfter (mem, new NewLineNode (), Roles.NewLine);
+
+						var cat = GetCodeMemberCategory (mem);
+						if (cat == curCat)
+							continue;
+						curCat = cat;
+						var label = settings.GetCategoryLabel (curCat);
+						if (string.IsNullOrEmpty (label))
+							continue;
+
+						var cmt = new Comment ("", CommentType.SingleLine);
+						var cmt2 = new Comment (" " + label, CommentType.SingleLine);
+						var cmt3 = new Comment ("", CommentType.SingleLine);
+						mem.Parent.InsertChildBefore (mem, cmt, Roles.Comment);
+						mem.Parent.InsertChildBefore (mem, cmt2, Roles.Comment);
+						mem.Parent.InsertChildBefore (mem, cmt3, Roles.Comment);
+						if (cmt.PrevSibling is EntityDeclaration)
+							mem.Parent.InsertChildBefore (cmt, new NewLineNode (), Roles.NewLine);
+					}
+				}
+			}
+		}
+
+		static Lazy<GeneratedCodeSettings> defaultSettings = new Lazy<GeneratedCodeSettings>(
+			() => new GeneratedCodeSettings() {
+				CodeMemberOrder = new List<GeneratedCodeMember>() {
+					GeneratedCodeMember.StaticFields,
+					GeneratedCodeMember.InstanceFields,
+					GeneratedCodeMember.StaticProperties,
+					GeneratedCodeMember.InstanceProperties,
+					GeneratedCodeMember.Indexer,
+					GeneratedCodeMember.Constructors,
+					GeneratedCodeMember.StaticMethods,
+					GeneratedCodeMember.InstanceMethods,
+					GeneratedCodeMember.StaticEvents,
+					GeneratedCodeMember.InstanceEvents,
+					GeneratedCodeMember.Operators,
+					GeneratedCodeMember.NestedTypes
+				},
+				GenerateCategoryComments = true,
+				SubOrderAlphabetical = true
+		});
+
+		public static GeneratedCodeSettings Default {
+			get {
+				return defaultSettings.Value;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/Indent.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/Indent.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/Indent.cs	(revision 11807)
@@ -0,0 +1,246 @@
+﻿// 
+// Indent.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum IndentType
+	{
+		Block,
+		DoubleBlock,
+		Continuation,
+		Alignment,
+		Label,
+		Empty
+	}
+
+	public class Indent
+	{
+		readonly CloneableStack<IndentType> indentStack = new CloneableStack<IndentType>();
+		readonly TextEditorOptions options;
+		int curIndent;
+		int extraSpaces;
+		string indentString;
+
+		public int CurIndent {
+			get {
+				return curIndent;
+			}
+		}
+
+		public Indent(TextEditorOptions options)
+		{
+			this.options = options;
+			Reset();
+		}
+
+		Indent(Indent engine)
+		{
+			this.indentStack = engine.indentStack.Clone();
+			this.options = engine.options;
+			this.curIndent = engine.curIndent;
+			this.extraSpaces = engine.extraSpaces;
+			this.indentString = engine.indentString;
+		}
+
+		public Indent Clone()
+		{
+			return new Indent(this);
+		}
+
+		public void Reset()
+		{
+			curIndent = 0;
+			indentString = "";
+			indentStack.Clear();
+		}
+
+		public void Push(IndentType type)
+		{
+			indentStack.Push(type);
+			curIndent += GetIndent(type);
+			Update();
+		}
+
+		public void Push(Indent indent)
+		{
+			foreach (var i in indent.indentStack)
+				Push(i);
+		}
+
+		public void Pop()
+		{
+			curIndent -= GetIndent(indentStack.Pop());
+			Update();
+		}
+
+		public bool PopIf(IndentType type)
+		{
+			if (Count > 0 && Peek() == type)
+			{
+				Pop();
+				return true;
+			}
+
+			return false;
+		}
+
+		public void PopWhile(IndentType type)
+		{
+			while (Count > 0 && Peek() == type)
+			{
+				Pop();
+			}
+		}
+
+		public bool PopTry()
+		{
+			if (Count > 0)
+			{
+				Pop();
+				return true;
+			}
+
+			return false;
+		}
+
+		public int Count {
+			get {
+				return indentStack.Count;
+			}
+		}
+
+		public IndentType Peek()
+		{
+			return indentStack.Peek();
+		}
+
+		int GetIndent(IndentType indentType)
+		{
+			switch (indentType) {
+				case IndentType.Block:
+					return options.IndentSize;
+				case IndentType.DoubleBlock:
+					return options.IndentSize * 2;
+				case IndentType.Alignment:
+				case IndentType.Continuation:
+					return options.ContinuationIndent;
+				case IndentType.Label:
+					return options.LabelIndent;
+				case IndentType.Empty:
+					return 0;
+				default:
+					throw new ArgumentOutOfRangeException();
+			}
+		}
+
+		void Update()
+		{
+			if (options.TabsToSpaces) {
+				indentString = new string(' ', curIndent + ExtraSpaces);
+				return;
+			}
+			indentString = new string('\t', curIndent / options.TabSize) + new string(' ', curIndent % options.TabSize) + new string(' ', ExtraSpaces);
+		}
+
+		public int ExtraSpaces {
+			get {
+				return extraSpaces;
+			}
+			set {
+				if (value < 0)
+					throw new ArgumentOutOfRangeException("ExtraSpaces >= 0 but was " + value);
+				extraSpaces = value;
+				Update();
+			}
+		}
+
+
+		public string IndentString {
+			get {
+				return indentString;
+			}
+		}
+
+		public override string ToString()
+		{
+			return string.Format("[Indent: curIndent={0}]", curIndent);
+		}
+
+		public Indent GetIndentWithoutSpace ()
+		{
+			var result = new Indent(options);
+			foreach (var i in indentStack)
+					result.Push(i);
+			return result;
+		}
+
+		public static Indent ConvertFrom(string indentString, Indent correctIndent, TextEditorOptions options = null)
+		{
+			options = options ?? TextEditorOptions.Default;
+			var result = new Indent(options);
+
+			var indent = string.Concat(indentString.Where(c => c == ' ' || c == '\t'));
+			var indentTypes = new Stack<IndentType>(correctIndent.indentStack);
+
+			foreach (var _ in indent.TakeWhile(c => c == '\t'))
+			{
+				if (indentTypes.Count > 0)
+					result.Push(indentTypes.Pop());
+				else
+					result.Push(IndentType.Continuation);
+			}
+
+			result.ExtraSpaces = indent
+				.SkipWhile(c => c == '\t')
+				.TakeWhile(c => c == ' ')
+				.Count();
+
+			return result;
+		}
+
+		public void RemoveAlignment()
+		{
+			ExtraSpaces = 0;
+			if (Count > 0 && Peek() == IndentType.Alignment)
+				Pop();
+		}
+
+		public void SetAlignment(int i, bool forceSpaces = false)
+		{
+			var alignChars = Math.Max(0, i);
+			if (forceSpaces) {
+				ExtraSpaces = alignChars;
+				return;
+			}
+			RemoveAlignment();
+			Push(IndentType.Alignment);
+		}
+
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/TextEditorOptions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/TextEditorOptions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Formatter/TextEditorOptions.cs	(revision 11807)
@@ -0,0 +1,116 @@
+﻿// 
+// TextEditorOptions.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// The text editor options class holds basic information about the text editor settings that influences code generation and formatting beside
+	/// the CSharpFormattingOptions.
+	/// </summary>
+	public class TextEditorOptions
+	{
+		public static readonly TextEditorOptions Default = new TextEditorOptions ();
+
+		/// <summary>
+		/// Gets or sets a value indicating if tabs need to be replaced by spaces. If that is true, all indenting will be done with spaces only,
+		/// otherwise the indenting will start with tabs.
+		/// </summary>
+		public bool TabsToSpaces {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Gets or sets the size of the tab chacter as spaces.
+		/// </summary>
+		public int TabSize {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Gets or sets the size of a single indent as spaces.
+		/// </summary>
+		public int IndentSize {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Gets or sets the continuation indent. A continuation indent is the indent that will be put after an embedded statement that is no block.
+		/// </summary>
+		public int ContinuationIndent {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Gets or sets the label indent. A label indent is the indent that will be put before an label.
+		/// (Note: it may be negative -IndentSize would cause that labels are unindented)
+		/// </summary>
+		public int LabelIndent {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Gets or sets the eol marker.
+		/// </summary>
+		public string EolMarker {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// If true blank lines will be indented up to the indent level, otherwise blank lines will have the length 0.
+		/// </summary>
+		public bool IndentBlankLines {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Gets or sets the length of the desired line length. The formatting engine will wrap at wrap points set to Wrapping.WrapIfTooLong if the line length is too long.
+		/// 0 means do not wrap.
+		/// </summary>
+		public int WrapLineLength {
+			get;
+			set;
+		}
+
+		public TextEditorOptions()
+		{
+			TabsToSpaces = false;
+			TabSize = 4;
+			IndentSize = 4;
+			ContinuationIndent = 4;
+			WrapLineLength = 0;
+			EolMarker = Environment.NewLine;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
@@ -0,0 +1,17 @@
+Copyright (c) 2010-2014 AlphaSierraPapa, Xamarin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this
+software and associated documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/ICSharpCode.NRefactory.CSharp-5.5.0.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/ICSharpCode.NRefactory.CSharp-5.5.0.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/ICSharpCode.NRefactory.CSharp-5.5.0.csproj	(revision 11807)
@@ -0,0 +1,416 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{C06A9187-4E8E-4129-BDA3-91D2297682D2}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>ICSharpCode.NRefactory.CSharp</RootNamespace>
+    <AssemblyName>ICSharpCode.NRefactory.CSharp</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;FULL_AST</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;FULL_AST</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;FULL_AST</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;FULL_AST</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG;FULL_AST</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;FULL_AST</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Analysis\AnnotationNames.cs" />
+    <Compile Include="Analysis\ControlFlow.cs" />
+    <Compile Include="Analysis\DeclarationSpace\LocalDeclarationSpace.cs" />
+    <Compile Include="Analysis\DeclarationSpace\LocalDeclarationSpaceVisitor.cs" />
+    <Compile Include="Analysis\DefiniteAssignmentAnalysis.cs" />
+    <Compile Include="Analysis\NullValueAnalysis.cs" />
+    <Compile Include="Analysis\NullValueStatus.cs" />
+    <Compile Include="Analysis\ReachabilityAnalysis.cs" />
+    <Compile Include="Analysis\SemanticHighlightingVisitor.cs" />
+    <Compile Include="Ast\AstNode.cs" />
+    <Compile Include="Ast\AstNodeCollection.cs" />
+    <Compile Include="Ast\AstType.cs" />
+    <Compile Include="Ast\ComposedType.cs" />
+    <Compile Include="Ast\CSharpModifierToken.cs" />
+    <Compile Include="Ast\CSharpTokenNode.cs" />
+    <Compile Include="Ast\CSharpUtil.cs" />
+    <Compile Include="Ast\DepthFirstAstVisitor.cs" />
+    <Compile Include="Ast\DocumentationReference.cs" />
+    <Compile Include="Ast\ErrorNode.cs" />
+    <Compile Include="Ast\Expressions\AnonymousMethodExpression.cs" />
+    <Compile Include="Ast\Expressions\AnonymousTypeCreateExpression.cs" />
+    <Compile Include="Ast\Expressions\ArrayCreateExpression.cs" />
+    <Compile Include="Ast\Expressions\ArrayInitializerExpression.cs" />
+    <Compile Include="Ast\Expressions\AsExpression.cs" />
+    <Compile Include="Ast\Expressions\AssignmentExpression.cs" />
+    <Compile Include="Ast\Expressions\BaseReferenceExpression.cs" />
+    <Compile Include="Ast\Expressions\BinaryOperatorExpression.cs" />
+    <Compile Include="Ast\Expressions\CastExpression.cs" />
+    <Compile Include="Ast\Expressions\CheckedExpression.cs" />
+    <Compile Include="Ast\Expressions\ConditionalExpression.cs" />
+    <Compile Include="Ast\Expressions\DefaultValueExpression.cs" />
+    <Compile Include="Ast\Expressions\DirectionExpression.cs" />
+    <Compile Include="Ast\Expressions\ErrorExpression.cs" />
+    <Compile Include="Ast\Expressions\Expression.cs" />
+    <Compile Include="Ast\Expressions\IdentifierExpression.cs" />
+    <Compile Include="Ast\Expressions\IndexerExpression.cs" />
+    <Compile Include="Ast\Expressions\InvocationExpression.cs" />
+    <Compile Include="Ast\Expressions\IsExpression.cs" />
+    <Compile Include="Ast\Expressions\LambdaExpression.cs" />
+    <Compile Include="Ast\Expressions\MemberReferenceExpression.cs" />
+    <Compile Include="Ast\Expressions\NamedArgumentExpression.cs" />
+    <Compile Include="Ast\Expressions\NamedExpression.cs" />
+    <Compile Include="Ast\Expressions\NullReferenceExpression.cs" />
+    <Compile Include="Ast\Expressions\ObjectCreateExpression.cs" />
+    <Compile Include="Ast\Expressions\ParenthesizedExpression.cs" />
+    <Compile Include="Ast\Expressions\PointerReferenceExpression.cs" />
+    <Compile Include="Ast\Expressions\PrimitiveExpression.cs" />
+    <Compile Include="Ast\Expressions\QueryExpression.cs" />
+    <Compile Include="Ast\Expressions\SizeOfExpression.cs" />
+    <Compile Include="Ast\Expressions\StackAllocExpression.cs" />
+    <Compile Include="Ast\Expressions\ThisReferenceExpression.cs" />
+    <Compile Include="Ast\Expressions\TypeOfExpression.cs" />
+    <Compile Include="Ast\Expressions\TypeReferenceExpression.cs" />
+    <Compile Include="Ast\Expressions\UnaryOperatorExpression.cs" />
+    <Compile Include="Ast\Expressions\UncheckedExpression.cs" />
+    <Compile Include="Ast\Expressions\UndocumentedExpression.cs" />
+    <Compile Include="Ast\GeneralScope\Attribute.cs" />
+    <Compile Include="Ast\GeneralScope\AttributeSection.cs" />
+    <Compile Include="Ast\GeneralScope\Comment.cs" />
+    <Compile Include="Ast\GeneralScope\Constraint.cs" />
+    <Compile Include="Ast\GeneralScope\DelegateDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\ExternAliasDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\NamespaceDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\NewLineNode.cs" />
+    <Compile Include="Ast\GeneralScope\PreProcessorDirective.cs" />
+    <Compile Include="Ast\GeneralScope\TextNode.cs" />
+    <Compile Include="Ast\GeneralScope\TypeDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\TypeParameterDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\UsingAliasDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\UsingDeclaration.cs" />
+    <Compile Include="Ast\GeneralScope\WhitespaceNode.cs" />
+    <Compile Include="Ast\IAstVisitor.cs" />
+    <Compile Include="Ast\Identifier.cs" />
+    <Compile Include="Ast\IdentifierExpressionBackreference.cs" />
+    <Compile Include="Ast\MemberType.cs" />
+    <Compile Include="Ast\Modifiers.cs" />
+    <Compile Include="Ast\NodeType.cs" />
+    <Compile Include="Ast\ObservableAstVisitor.cs" />
+    <Compile Include="Ast\PrimitiveType.cs" />
+    <Compile Include="Ast\Roles.cs" />
+    <Compile Include="Ast\SimpleType.cs" />
+    <Compile Include="Ast\Statements\BlockStatement.cs" />
+    <Compile Include="Ast\Statements\BreakStatement.cs" />
+    <Compile Include="Ast\Statements\CheckedStatement.cs" />
+    <Compile Include="Ast\Statements\ContinueStatement.cs" />
+    <Compile Include="Ast\Statements\DoWhileStatement.cs" />
+    <Compile Include="Ast\Statements\EmptyStatement.cs" />
+    <Compile Include="Ast\Statements\ExpressionStatement.cs" />
+    <Compile Include="Ast\Statements\FixedStatement.cs" />
+    <Compile Include="Ast\Statements\ForeachStatement.cs" />
+    <Compile Include="Ast\Statements\ForStatement.cs" />
+    <Compile Include="Ast\Statements\GotoStatement.cs" />
+    <Compile Include="Ast\Statements\IfElseStatement.cs" />
+    <Compile Include="Ast\Statements\LabelStatement.cs" />
+    <Compile Include="Ast\Statements\LockStatement.cs" />
+    <Compile Include="Ast\Statements\ReturnStatement.cs" />
+    <Compile Include="Ast\Statements\Statement.cs" />
+    <Compile Include="Ast\Statements\SwitchStatement.cs" />
+    <Compile Include="Ast\Statements\ThrowStatement.cs" />
+    <Compile Include="Ast\Statements\TryCatchStatement.cs" />
+    <Compile Include="Ast\Statements\UncheckedStatement.cs" />
+    <Compile Include="Ast\Statements\UnsafeStatement.cs" />
+    <Compile Include="Ast\Statements\UsingStatement.cs" />
+    <Compile Include="Ast\Statements\VariableDeclarationStatement.cs" />
+    <Compile Include="Ast\Statements\WhileStatement.cs" />
+    <Compile Include="Ast\Statements\YieldBreakStatement.cs" />
+    <Compile Include="Ast\Statements\YieldReturnStatement.cs" />
+    <Compile Include="Ast\SyntaxExtensions.cs" />
+    <Compile Include="Ast\SyntaxTree.cs" />
+    <Compile Include="Ast\TokenRole.cs" />
+    <Compile Include="Ast\TypeMembers\Accessor.cs" />
+    <Compile Include="Ast\TypeMembers\ConstructorDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\DestructorDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\EntityDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\EnumMemberDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\EventDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\FieldDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\FixedFieldDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\FixedVariableInitializer.cs" />
+    <Compile Include="Ast\TypeMembers\IndexerDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\MethodDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\OperatorDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\ParameterDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\PropertyDeclaration.cs" />
+    <Compile Include="Ast\TypeMembers\VariableInitializer.cs" />
+    <Compile Include="CombineQueryExpressions.cs" />
+    <Compile Include="Completion\CompletionDataWrapper.cs" />
+    <Compile Include="Completion\CSharpCompletionEngine.cs" />
+    <Compile Include="Completion\CSharpCompletionEngineBase.cs" />
+    <Compile Include="Completion\CSharpParameterCompletionEngine.cs" />
+    <Compile Include="Completion\ICompletionContextProvider.cs" />
+    <Compile Include="Completion\ICompletionDataFactory.cs" />
+    <Compile Include="Completion\IParameterCompletionDataFactory.cs" />
+    <Compile Include="CSharpProjectContent.cs" />
+    <Compile Include="Formatter\ConstructFixer.cs" />
+    <Compile Include="Formatter\CSharpFormatter.cs" />
+    <Compile Include="Formatter\CSharpFormattingOptions.cs" />
+    <Compile Include="Formatter\FormattingChanges.cs" />
+    <Compile Include="Formatter\FormattingOptionsFactory.cs" />
+    <Compile Include="Formatter\FormattingVisitor.cs" />
+    <Compile Include="Formatter\FormattingVisitor_Expressions.cs" />
+    <Compile Include="Formatter\FormattingVisitor_Global.cs" />
+    <Compile Include="Formatter\FormattingVisitor_Query.cs" />
+    <Compile Include="Formatter\FormattingVisitor_Statements.cs" />
+    <Compile Include="Formatter\FormattingVisitor_TypeMembers.cs" />
+    <Compile Include="Formatter\GeneratedCodeSettings.cs" />
+    <Compile Include="Formatter\Indent.cs" />
+    <Compile Include="Formatter\TextEditorOptions.cs" />
+    <Compile Include="IndentEngine\CacheIndentEngine.cs" />
+    <Compile Include="IndentEngine\CSharpIndentEngine.cs" />
+    <Compile Include="IndentEngine\IDocumentIndentEngine.cs" />
+    <Compile Include="IndentEngine\IndentState.cs" />
+    <Compile Include="IndentEngine\IStateMachineIndentEngine.cs" />
+    <Compile Include="IndentEngine\NullIStateMachineIndentEngine.cs" />
+    <Compile Include="IndentEngine\TextPasteIndentEngine.cs" />
+    <Compile Include="IntroduceQueryExpressions.cs" />
+    <Compile Include="NameLookupMode.cs" />
+    <Compile Include="OutputVisitor\CodeDomConvertVisitor.cs" />
+    <Compile Include="OutputVisitor\CSharpAmbience.cs" />
+    <Compile Include="OutputVisitor\CSharpOutputVisitor.cs" />
+    <Compile Include="OutputVisitor\InsertMissingTokensDecorator.cs" />
+    <Compile Include="OutputVisitor\InsertParenthesesVisitor.cs" />
+    <Compile Include="OutputVisitor\InsertRequiredSpacesDecorator.cs" />
+    <Compile Include="OutputVisitor\InsertSpecialsDecorator.cs" />
+    <Compile Include="OutputVisitor\ITokenWriter.cs" />
+    <Compile Include="OutputVisitor\TextWriterOutputFormatter.cs" />
+    <Compile Include="Parser\CompilerSettings.cs" />
+    <Compile Include="Parser\CSharpParser.cs" />
+    <Compile Include="Parser\mcs\anonymous.cs" />
+    <Compile Include="Parser\mcs\argument.cs" />
+    <Compile Include="Parser\mcs\assembly.cs" />
+    <Compile Include="Parser\mcs\assign.cs" />
+    <Compile Include="Parser\mcs\async.cs" />
+    <Compile Include="Parser\mcs\attribute.cs" />
+    <Compile Include="Parser\mcs\cfold.cs" />
+    <Compile Include="Parser\mcs\class.cs" />
+    <Compile Include="Parser\mcs\codegen.cs" />
+    <Compile Include="Parser\mcs\complete.cs" />
+    <Compile Include="Parser\mcs\const.cs" />
+    <Compile Include="Parser\mcs\constant.cs" />
+    <Compile Include="Parser\mcs\context.cs" />
+    <Compile Include="Parser\mcs\convert.cs" />
+    <Compile Include="Parser\mcs\CryptoConvert.cs" />
+    <Compile Include="Parser\mcs\cs-parser.cs" />
+    <Compile Include="Parser\mcs\cs-tokenizer.cs" />
+    <Compile Include="Parser\mcs\decl.cs" />
+    <Compile Include="Parser\mcs\delegate.cs" />
+    <Compile Include="Parser\mcs\doc.cs" />
+    <Compile Include="Parser\mcs\driver.cs" />
+    <Compile Include="Parser\mcs\dynamic.cs" />
+    <Compile Include="Parser\mcs\ecore.cs" />
+    <Compile Include="Parser\mcs\enum.cs" />
+    <Compile Include="Parser\mcs\eval.cs" />
+    <Compile Include="Parser\mcs\expression.cs" />
+    <Compile Include="Parser\mcs\field.cs" />
+    <Compile Include="Parser\mcs\flowanalysis.cs" />
+    <Compile Include="Parser\mcs\generic.cs" />
+    <Compile Include="Parser\mcs\import.cs" />
+    <Compile Include="Parser\mcs\iterators.cs" />
+    <Compile Include="Parser\mcs\lambda.cs" />
+    <Compile Include="Parser\mcs\linq.cs" />
+    <Compile Include="Parser\mcs\literal.cs" />
+    <Compile Include="Parser\mcs\location.cs" />
+    <Compile Include="Parser\mcs\membercache.cs" />
+    <Compile Include="Parser\mcs\method.cs" />
+    <Compile Include="Parser\mcs\modifiers.cs" />
+    <Compile Include="Parser\mcs\module.cs" />
+    <Compile Include="Parser\mcs\MonoSymbolFile.cs" />
+    <Compile Include="Parser\mcs\MonoSymbolTable.cs" />
+    <Compile Include="Parser\mcs\MonoSymbolWriter.cs" />
+    <Compile Include="Parser\mcs\namespace.cs" />
+    <Compile Include="Parser\mcs\nullable.cs" />
+    <Compile Include="Parser\mcs\outline.cs" />
+    <Compile Include="Parser\mcs\parameter.cs" />
+    <Compile Include="Parser\mcs\pending.cs" />
+    <Compile Include="Parser\mcs\property.cs" />
+    <Compile Include="Parser\mcs\reflection.cs" />
+    <Compile Include="Parser\mcs\report.cs" />
+    <Compile Include="Parser\mcs\settings.cs" />
+    <Compile Include="Parser\mcs\SourceMethodBuilder.cs" />
+    <Compile Include="Parser\mcs\statement.cs" />
+    <Compile Include="Parser\mcs\support.cs" />
+    <Compile Include="Parser\mcs\symbolwriter.cs" />
+    <Compile Include="Parser\mcs\typemanager.cs" />
+    <Compile Include="Parser\mcs\typespec.cs" />
+    <Compile Include="Parser\mcs\visit.cs" />
+    <Compile Include="Parser\SeekableStreamReader.cs" />
+    <Compile Include="PatternMatching\AnyType.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="QueryExpressionExpander.cs" />
+    <Compile Include="Refactoring\BaseRefactoringContext.cs" />
+    <Compile Include="Refactoring\CodeAction.cs" />
+    <Compile Include="Refactoring\CodeActionProvider.cs" />
+    <Compile Include="Refactoring\CodeGenerationService.cs" />
+    <Compile Include="Refactoring\CodeIssue.cs" />
+    <Compile Include="Refactoring\CodeIssueProvider.cs" />
+    <Compile Include="Refactoring\CommonSubIssues.cs" />
+    <Compile Include="Refactoring\ContextActionAttribute.cs" />
+    <Compile Include="Refactoring\DocumentScript.cs" />
+    <Compile Include="Refactoring\FormatStringHelper.cs" />
+    <Compile Include="Refactoring\IssueAttribute.cs" />
+    <Compile Include="Refactoring\LambdaHelper.cs" />
+    <Compile Include="Refactoring\LocalReferenceFinder.cs" />
+    <Compile Include="Refactoring\NamingHelper.cs" />
+    <Compile Include="Refactoring\PatternHelper.cs" />
+    <Compile Include="Refactoring\RefactoringAstHelper.cs" />
+    <Compile Include="Refactoring\RefactoringContext.cs" />
+    <Compile Include="Refactoring\Script.cs" />
+    <Compile Include="Refactoring\TypeGuessing.cs" />
+    <Compile Include="Refactoring\TypeSystemAstBuilder.cs" />
+    <Compile Include="Refactoring\UsingHelper.cs" />
+    <Compile Include="Refactoring\VariableReferenceGraph.cs" />
+    <Compile Include="Refactoring\WordParser.cs" />
+    <Compile Include="Resolver\AliasNamespaceResolveResult.cs" />
+    <Compile Include="Resolver\AliasTypeResolveResult.cs" />
+    <Compile Include="Resolver\AwaitResolveResult.cs" />
+    <Compile Include="Resolver\CastResolveResult.cs" />
+    <Compile Include="Resolver\CompositeResolveVisitorNavigator.cs" />
+    <Compile Include="Resolver\CSharpAstResolver.cs" />
+    <Compile Include="Resolver\CSharpConversions.cs" />
+    <Compile Include="Resolver\CSharpInvocationResolveResult.cs" />
+    <Compile Include="Resolver\CSharpOperators.cs" />
+    <Compile Include="Resolver\CSharpResolver.cs" />
+    <Compile Include="Resolver\DetectSkippableNodesNavigator.cs" />
+    <Compile Include="Resolver\DynamicInvocationResolveResult.cs" />
+    <Compile Include="Resolver\DynamicMemberResolveResult.cs" />
+    <Compile Include="Resolver\FindReferencedEntities.cs" />
+    <Compile Include="Resolver\FindReferences.cs" />
+    <Compile Include="Resolver\FindReferenceSearchScope.cs" />
+    <Compile Include="Resolver\IResolveVisitorNavigator.cs" />
+    <Compile Include="Resolver\LambdaResolveResult.cs" />
+    <Compile Include="Resolver\Log.cs" />
+    <Compile Include="Resolver\MemberLookup.cs" />
+    <Compile Include="Resolver\MethodGroupResolveResult.cs" />
+    <Compile Include="Resolver\NodeListResolveVisitorNavigator.cs" />
+    <Compile Include="Resolver\OverloadResolution.cs" />
+    <Compile Include="Resolver\OverloadResolutionErrors.cs" />
+    <Compile Include="Resolver\ReducedExtensionMethod.cs" />
+    <Compile Include="Resolver\RenameCallbackArguments.cs" />
+    <Compile Include="Resolver\ResolveAtLocation.cs" />
+    <Compile Include="Resolver\ResolveVisitor.cs" />
+    <Compile Include="Resolver\TypeInference.cs" />
+    <Compile Include="TypeSystem\AliasNamespaceReference.cs" />
+    <Compile Include="TypeSystem\AttributeTypeReference.cs" />
+    <Compile Include="TypeSystem\ConstantValues.cs" />
+    <Compile Include="TypeSystem\CSharpAssembly.cs" />
+    <Compile Include="TypeSystem\CSharpAttribute.cs" />
+    <Compile Include="TypeSystem\CSharpDocumentationComment.cs" />
+    <Compile Include="TypeSystem\CSharpTypeResolveContext.cs" />
+    <Compile Include="TypeSystem\CSharpUnresolvedFile.cs" />
+    <Compile Include="TypeSystem\CSharpUnresolvedTypeDefinition.cs" />
+    <Compile Include="TypeSystem\MemberTypeOrNamespaceReference.cs" />
+    <Compile Include="TypeSystem\MethodTypeParameterWithInheritedConstraints.cs" />
+    <Compile Include="TypeSystem\ResolvedUsingScope.cs" />
+    <Compile Include="TypeSystem\SimpleTypeOrNamespaceReference.cs" />
+    <Compile Include="TypeSystem\TypeOrNamespaceReference.cs" />
+    <Compile Include="TypeSystem\TypeSystemConvertVisitor.cs" />
+    <Compile Include="TypeSystem\UsingScope.cs" />
+    <Compile Include="Util\CloneableStack.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="ICSharpCode.NRefactory License-5.5.0.txt" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+    <None Include="Parser\mcs\cs-parser.jay" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\NRefactory-5.5.0\ICSharpCode.NRefactory-5.5.0.csproj">
+      <Project>{1022483b-7cf4-4162-827f-984b64eaf8b3}</Project>
+      <Name>ICSharpCode.NRefactory-5.5.0</Name>
+      <Private>False</Private>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/CSharpIndentEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/CSharpIndentEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/CSharpIndentEngine.cs	(revision 11807)
@@ -0,0 +1,557 @@
+﻿//
+// CSharpIndentEngine.cs
+//
+// Author:
+//       Matej Miklečić <matej.miklecic@gmail.com>
+//
+// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using ICSharpCode.NRefactory.Editor;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	///     Indentation engine based on a state machine.
+	///     Supports only pushing new chars to the end.
+	/// </summary>
+	/// <remarks>
+	///     Represents the context for transitions between <see cref="IndentState"/>.
+	///     Delegates the responsibility for pushing a new char to the current 
+	///     state and changes between states depending on the pushed chars.
+	/// </remarks>
+	public class CSharpIndentEngine : IStateMachineIndentEngine
+	{
+		#region Properties
+
+		/// <summary>
+		///     Formatting options.
+		/// </summary>
+		internal readonly CSharpFormattingOptions formattingOptions;
+
+		/// <summary>
+		///     Text editor options.
+		/// </summary>
+		internal readonly TextEditorOptions textEditorOptions;
+
+		/// <summary>
+		///     A readonly reference to the document that's parsed
+		///     by the engine.
+		/// </summary>
+		internal readonly IDocument document;
+
+		/// <summary>
+		///     Represents the new line character.
+		/// </summary>
+		internal readonly char newLineChar;
+
+		/// <summary>
+		///     The current indentation state.
+		/// </summary>
+		internal IndentState currentState;
+
+		/// <summary>
+		///     Stores conditional symbols of #define directives.
+		/// </summary>
+		internal HashSet<string> conditionalSymbols;
+
+		/// <summary>
+		///     Stores custom conditional symbols.
+		/// </summary>
+		internal HashSet<string> customConditionalSymbols;
+
+		/// <summary>
+		///     Stores the results of evaluations of the preprocessor if/elif directives 
+		///     in the current block (between #if and #endif).
+		/// </summary>
+		internal CloneableStack<bool> ifDirectiveEvalResults = new CloneableStack<bool> ();
+
+		/// <summary>
+		///     Stores the indentation levels of the if directives in the current block.
+		/// </summary>
+		internal CloneableStack<Indent> ifDirectiveIndents = new CloneableStack<Indent>();
+
+		/// <summary>
+		///     Stores the last sequence of characters that can form a
+		///     valid keyword or variable name.
+		/// </summary>
+		internal StringBuilder wordToken;
+
+		/// <summary>
+		///     Stores the previous sequence of chars that formed a
+		///     valid keyword or variable name.
+		/// </summary>
+		internal string previousKeyword;
+
+		#endregion
+
+		#region IDocumentIndentEngine
+
+		/// <inheritdoc />
+		public IDocument Document
+		{
+			get { return document; }
+		}
+
+		/// <inheritdoc />
+		public string ThisLineIndent
+		{
+			get
+			{
+				// OPTION: IndentBlankLines
+				// remove the indentation of this line if isLineStart is true
+//				if (!textEditorOptions.IndentBlankLines && isLineStart)
+//				{
+//					return string.Empty;
+//				}
+
+				return currentState.ThisLineIndent.IndentString;
+			}
+		}
+
+		/// <inheritdoc />
+		public string NextLineIndent
+		{
+			get
+			{
+				return currentState.NextLineIndent.IndentString;
+			}
+		}
+
+		/// <inheritdoc />
+		public string CurrentIndent
+		{
+			get
+			{
+				return currentIndent.ToString();
+			}
+		}
+
+		/// <inheritdoc />
+		/// <remarks>
+		///     This is set depending on the current <see cref="Location"/> and
+		///     can change its value until the <see cref="newLineChar"/> char is
+		///     pushed. If this is true, that doesn't necessarily mean that the
+		///     current line has an incorrect indent (this can be determined
+		///     only at the end of the current line).
+		/// </remarks>
+		public bool NeedsReindent
+		{
+			get
+			{
+				// return true if it's the first column of the line and it has an indent
+				if (Location.Column == 1)
+				{
+					return ThisLineIndent.Length > 0;
+				}
+
+				// ignore incorrect indentations when there's only ws on this line
+				if (isLineStart)
+				{
+					return false;
+				}
+
+				return ThisLineIndent != CurrentIndent.ToString();
+			}
+		}
+
+		/// <inheritdoc />
+		public int Offset
+		{
+			get
+			{
+				return offset;
+			}
+		}
+
+		/// <inheritdoc />
+		public TextLocation Location
+		{
+			get
+			{
+				return new TextLocation(line, column);
+			}
+		}
+
+		/// <inheritdoc />
+		public bool EnableCustomIndentLevels
+		{
+			get;
+			set;
+		}
+
+		#endregion
+
+		#region Fields
+
+		/// <summary>
+		///    Represents the number of pushed chars.
+		/// </summary>
+		internal int offset = 0;
+
+		/// <summary>
+		///    The current line number.
+		/// </summary>
+		internal int line = 1;
+
+		/// <summary>
+		///    The current column number.
+		/// </summary>
+		/// <remarks>
+		///    One char can take up multiple columns (e.g. \t).
+		/// </remarks>
+		internal int column = 1;
+
+		/// <summary>
+		///    True if <see cref="char.IsWhiteSpace(char)"/> is true for all
+		///    chars at the current line.
+		/// </summary>
+		internal bool isLineStart = true;
+
+		/// <summary>
+		///    True if <see cref="isLineStart"/> was true before the current
+		///    <see cref="wordToken"/>.
+		/// </summary>
+		internal bool isLineStartBeforeWordToken = true;
+
+		/// <summary>
+		///    Current char that's being pushed.
+		/// </summary>
+		internal char currentChar = '\0';
+
+		/// <summary>
+		///    Last non-whitespace char that has been pushed.
+		/// </summary>
+		internal char previousChar = '\0';
+
+		/// <summary>
+		///    Previous new line char
+		/// </summary>
+		internal char previousNewline = '\0';
+
+		/// <summary>
+		///    Current indent level on this line.
+		/// </summary>
+		internal StringBuilder currentIndent = new StringBuilder();
+
+		/// <summary>
+		///     True if this line began in <see cref="VerbatimStringState"/>.
+		/// </summary>
+		internal bool lineBeganInsideVerbatimString = false;
+
+		/// <summary>
+		///     True if this line began in <see cref="MultiLineCommentState"/>.
+		/// </summary>
+		internal bool lineBeganInsideMultiLineComment = false;
+
+		#endregion
+
+		#region Constructors
+
+		/// <summary>
+		///     Creates a new CSharpIndentEngine instance.
+		/// </summary>
+		/// <param name="document">
+		///     An instance of <see cref="IDocument"/> which is being parsed.
+		/// </param>
+		/// <param name="formattingOptions">
+		///     C# formatting options.
+		/// </param>
+		/// <param name="textEditorOptions">
+		///    Text editor options for indentation.
+		/// </param>
+		public CSharpIndentEngine(IDocument document, TextEditorOptions textEditorOptions, CSharpFormattingOptions formattingOptions)
+		{
+			this.formattingOptions = formattingOptions;
+			this.textEditorOptions = textEditorOptions;
+			this.document = document;
+
+			this.currentState = new GlobalBodyState(this);
+
+			this.conditionalSymbols = new HashSet<string>();
+			this.customConditionalSymbols = new HashSet<string>();
+			this.wordToken = new StringBuilder();
+			this.previousKeyword = string.Empty;
+			this.newLineChar = textEditorOptions.EolMarker[0];
+		}
+
+		/// <summary>
+		///     Creates a new CSharpIndentEngine instance from the given prototype.
+		/// </summary>
+		/// <param name="prototype">
+		///     An CSharpIndentEngine instance.
+		/// </param>
+		public CSharpIndentEngine(CSharpIndentEngine prototype)
+		{
+			this.formattingOptions = prototype.formattingOptions;
+			this.textEditorOptions = prototype.textEditorOptions;
+			this.document = prototype.document;
+
+			this.newLineChar = prototype.newLineChar;
+			this.currentState = prototype.currentState.Clone(this);
+			this.conditionalSymbols = new HashSet<string>(prototype.conditionalSymbols);
+			this.customConditionalSymbols = new HashSet<string>(prototype.customConditionalSymbols);
+
+			this.wordToken = new StringBuilder(prototype.wordToken.ToString());
+			this.previousKeyword = string.Copy(prototype.previousKeyword);
+
+			this.offset = prototype.offset;
+			this.line = prototype.line;
+			this.column = prototype.column;
+			this.isLineStart = prototype.isLineStart;
+			this.isLineStartBeforeWordToken = prototype.isLineStartBeforeWordToken;
+			this.currentChar = prototype.currentChar;
+			this.previousChar = prototype.previousChar;
+			this.previousNewline = prototype.previousNewline;
+			this.currentIndent = new StringBuilder(prototype.CurrentIndent.ToString());
+			this.lineBeganInsideMultiLineComment = prototype.lineBeganInsideMultiLineComment;
+			this.lineBeganInsideVerbatimString = prototype.lineBeganInsideVerbatimString;
+			this.ifDirectiveEvalResults = prototype.ifDirectiveEvalResults.Clone();
+			this.ifDirectiveIndents = prototype.ifDirectiveIndents.Clone();
+
+			this.EnableCustomIndentLevels = prototype.EnableCustomIndentLevels;
+		}
+
+		#endregion
+
+		#region IClonable
+
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+
+		/// <inheritdoc />
+		IDocumentIndentEngine IDocumentIndentEngine.Clone()
+		{
+			return Clone();
+		}
+
+		public IStateMachineIndentEngine Clone()
+		{
+			return new CSharpIndentEngine(this);
+		}
+
+		#endregion
+
+		#region Methods
+
+		/// <inheritdoc />
+		public void Push(char ch)
+		{
+			// append this char to the wordbuf if it can form a valid keyword, otherwise check
+			// if the last sequence of chars form a valid keyword and reset the wordbuf.
+			if ((wordToken.Length == 0 ? char.IsLetter(ch) : char.IsLetterOrDigit(ch)) || ch == '_')
+			{
+				wordToken.Append(ch);
+			}
+			else if (wordToken.Length > 0)
+			{
+				currentState.CheckKeyword(wordToken.ToString());
+				previousKeyword = wordToken.ToString();
+				wordToken.Length = 0;
+				isLineStartBeforeWordToken = false;
+			}
+
+			var isNewLine = NewLine.IsNewLine(ch);
+			if (!isNewLine) {
+				currentState.Push(currentChar = ch);
+				offset++;
+				previousNewline = '\0';
+				// ignore whitespace and newline chars
+				var isWhitespace = currentChar == ' ' || currentChar == '\t';
+				if (!isWhitespace)
+				{
+					previousChar = currentChar;
+					isLineStart = false;
+				}
+
+				if (isLineStart)
+				{
+					currentIndent.Append(ch);
+				}
+
+				if (ch == '\t')
+				{
+					var nextTabStop = (column - 1 + textEditorOptions.IndentSize) / textEditorOptions.IndentSize;
+					column = 1 + nextTabStop * textEditorOptions.IndentSize;
+				}
+				else
+				{
+					column++;
+				}
+			} else {
+				if (ch == NewLine.LF && previousNewline == NewLine.CR) {
+					offset++;
+					return;
+				}
+				currentState.Push(currentChar = newLineChar);
+				offset++;
+
+				previousNewline = ch;
+				// there can be more than one chars that determine the EOL,
+				// the engine uses only one of them defined with newLineChar
+				if (currentChar != newLineChar)
+				{
+					return;
+				}
+				currentIndent.Length = 0;
+				isLineStart = true;
+				isLineStartBeforeWordToken = true;
+				column = 1;
+				line++;
+
+				lineBeganInsideMultiLineComment = IsInsideMultiLineComment;
+				lineBeganInsideVerbatimString = IsInsideVerbatimString;
+			}
+		}
+
+		/// <inheritdoc />
+		public void Reset()
+		{
+			currentState = new GlobalBodyState(this);
+			conditionalSymbols.Clear();
+			ifDirectiveEvalResults.Clear();
+			ifDirectiveIndents.Clear();
+
+			offset = 0;
+			line = 1;
+			column = 1;
+			isLineStart = true;
+			currentChar = '\0';
+			previousChar = '\0';
+			currentIndent.Length = 0;
+			lineBeganInsideMultiLineComment = false;
+			lineBeganInsideVerbatimString = false;
+		}
+
+		/// <inheritdoc />
+		public void Update(int offset)
+		{
+			if (Offset > offset)
+			{
+				Reset();
+			}
+
+			while (Offset < offset)
+			{
+				Push(Document.GetCharAt(Offset));
+			}
+		}
+
+		/// <summary>
+		/// Defines the conditional symbol.
+		/// </summary>
+		/// <param name="defineSymbol">The symbol to define.</param>
+		public void DefineSymbol(string defineSymbol)
+		{
+			if (!customConditionalSymbols.Contains(defineSymbol))
+				customConditionalSymbols.Add(defineSymbol);
+		}
+
+		/// <summary>
+		/// Removes the symbol.
+		/// </summary>
+		/// <param name="undefineSymbol">The symbol to undefine.</param>
+		public void RemoveSymbol(string undefineSymbol)
+		{
+			if (customConditionalSymbols.Contains(undefineSymbol))
+				customConditionalSymbols.Remove(undefineSymbol);
+		}
+		#endregion
+
+		#region IStateMachineIndentEngine
+
+		public bool IsInsidePreprocessorDirective
+		{
+			get { return currentState is PreProcessorState; }
+		}
+
+		public bool IsInsidePreprocessorComment
+		{
+			get { return currentState is PreProcessorCommentState; }
+		}
+
+		public bool IsInsideStringLiteral
+		{
+			get { return currentState is StringLiteralState; }
+		}
+
+		public bool IsInsideVerbatimString
+		{
+			get { return currentState is VerbatimStringState; }
+		}
+
+		public bool IsInsideCharacter
+		{
+			get { return currentState is CharacterState; }
+		}
+
+		public bool IsInsideString
+		{
+			get { return IsInsideStringLiteral || IsInsideVerbatimString || IsInsideCharacter; }
+		}
+
+		public bool IsInsideLineComment
+		{
+			get { return currentState is LineCommentState; }
+		}
+
+		public bool IsInsideMultiLineComment
+		{
+			get { return currentState is MultiLineCommentState; }
+		}
+
+		public bool IsInsideDocLineComment
+		{
+			get { return currentState is DocCommentState; }
+		}
+
+		public bool IsInsideComment
+		{
+			get { return IsInsideLineComment || IsInsideMultiLineComment || IsInsideDocLineComment; }
+		}
+
+		public bool IsInsideOrdinaryComment
+		{
+			get { return IsInsideLineComment || IsInsideMultiLineComment; }
+		}
+
+		public bool IsInsideOrdinaryCommentOrString
+		{
+			get { return IsInsideOrdinaryComment || IsInsideString; }
+		}
+
+		public bool LineBeganInsideVerbatimString
+		{
+			get { return lineBeganInsideVerbatimString; }
+		}
+
+		public bool LineBeganInsideMultiLineComment
+		{
+			get { return lineBeganInsideMultiLineComment; }
+		}
+
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/CacheIndentEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/CacheIndentEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/CacheIndentEngine.cs	(revision 11807)
@@ -0,0 +1,627 @@
+﻿//
+// CacheIndentEngine.cs
+//
+// Author:
+//       Matej Miklečić <matej.miklecic@gmail.com>
+//
+// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using ICSharpCode.NRefactory.Editor;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	///     Represents a decorator of an IStateMachineIndentEngine instance that provides
+	///     logic for reseting and updating the engine on text changed events.
+	/// </summary>
+	/// <remarks>
+	///     The decorator is based on periodical caching of the engine's state and
+	///     delegating all logic behind indentation to the currently active engine.
+	/// </remarks>
+	public class CacheIndentEngine : IStateMachineIndentEngine
+	{
+
+		#region Properties
+
+		IStateMachineIndentEngine currentEngine;
+		Stack<IStateMachineIndentEngine> cachedEngines = new Stack<IStateMachineIndentEngine>();
+
+		#endregion
+
+		#region Constructors
+
+		/// <summary>
+		///     Creates a new CacheIndentEngine instance.
+		/// </summary>
+		/// <param name="decoratedEngine">
+		///     An instance of <see cref="IStateMachineIndentEngine"/> to which the
+		///     logic for indentation will be delegated.
+		/// </param>
+		/// <param name="cacheRate">
+		///     The number of chars between caching.
+		/// </param>
+		public CacheIndentEngine(IStateMachineIndentEngine decoratedEngine, int cacheRate = 2000)
+		{
+			this.currentEngine = decoratedEngine;
+		}
+
+		/// <summary>
+		///     Creates a new CacheIndentEngine instance from the given prototype.
+		/// </summary>
+		/// <param name="prototype">
+		///     A CacheIndentEngine instance.
+		/// </param>
+		public CacheIndentEngine(CacheIndentEngine prototype)
+		{
+			this.currentEngine = prototype.currentEngine.Clone();
+		}
+
+		#endregion
+
+		#region IDocumentIndentEngine
+
+		/// <inheritdoc />
+		public IDocument Document {
+			get { return currentEngine.Document; }
+		}
+
+		/// <inheritdoc />
+		public string ThisLineIndent {
+			get { return currentEngine.ThisLineIndent; }
+		}
+
+		/// <inheritdoc />
+		public string NextLineIndent {
+			get { return currentEngine.NextLineIndent; }
+		}
+
+		/// <inheritdoc />
+		public string CurrentIndent {
+			get { return currentEngine.CurrentIndent; }
+		}
+
+		/// <inheritdoc />
+		public bool NeedsReindent {
+			get { return currentEngine.NeedsReindent; }
+		}
+
+		/// <inheritdoc />
+		public int Offset {
+			get { return currentEngine.Offset; }
+		}
+
+		/// <inheritdoc />
+		public TextLocation Location {
+			get { return currentEngine.Location; }
+		}
+
+		/// <inheritdoc />
+		public bool EnableCustomIndentLevels
+		{
+			get { return currentEngine.EnableCustomIndentLevels; }
+			set { currentEngine.EnableCustomIndentLevels = value; }
+		}
+
+		/// <inheritdoc />
+		public void Push(char ch)
+		{
+			currentEngine.Push(ch);
+		}
+
+		/// <inheritdoc />
+		public void Reset()
+		{
+			currentEngine.Reset();
+			cachedEngines.Clear();
+		}
+
+		/// <summary>
+		/// Resets the engine to offset. Clears all cached engines after the given offset.
+		/// </summary>
+		public void ResetEngineToPosition(int offset)
+		{
+			// We are already there
+			if (currentEngine.Offset <= offset)
+				return;
+			
+			bool gotCachedEngine = false;
+			while (cachedEngines.Count > 0) {
+				var topEngine = cachedEngines.Peek();
+				if (topEngine.Offset <= offset) {
+					currentEngine = topEngine.Clone();
+					gotCachedEngine = true;
+					break;
+				} else {
+					cachedEngines.Pop();
+				}
+			}
+			if (!gotCachedEngine)
+				currentEngine.Reset();
+		}
+
+		/// <inheritdoc />
+		/// <remarks>
+		///     If the <paramref name="position"/> is negative, the engine will
+		///     update to: document.TextLength + (offset % document.TextLength+1)
+		///     Otherwise it will update to: offset % document.TextLength+1
+		/// </remarks>
+		public void Update(int position)
+		{
+			const int BUFFER_SIZE = 2000;
+			
+			if (currentEngine.Offset == position) {
+				//positions match, nothing to be done
+				return;
+			} else if (currentEngine.Offset > position) {
+				//moving backwards, so reset from previous saved location
+				ResetEngineToPosition(position);
+			}
+
+			// get the engine caught up
+			int nextSave = (cachedEngines.Count == 0) ? BUFFER_SIZE : cachedEngines.Peek().Offset + BUFFER_SIZE;
+			if (currentEngine.Offset + 1 == position) {
+				char ch = currentEngine.Document.GetCharAt(currentEngine.Offset);
+				currentEngine.Push(ch);
+				if (currentEngine.Offset == nextSave)
+					cachedEngines.Push(currentEngine.Clone());
+			} else {
+				//bulk copy characters in case buffer is unmanaged 
+				//(faster if we reduce managed/unmanaged transitions)
+				while (currentEngine.Offset < position) {
+					int endCut = currentEngine.Offset + BUFFER_SIZE;
+					if (endCut > position)
+						endCut = position;
+					string buffer = currentEngine.Document.GetText(currentEngine.Offset, endCut - currentEngine.Offset);
+					foreach (char ch in buffer) {
+						currentEngine.Push(ch);
+						//ConsoleWrite ("pushing character '{0}'", ch);
+						if (currentEngine.Offset == nextSave) {
+							cachedEngines.Push(currentEngine.Clone());
+							nextSave += BUFFER_SIZE;
+						}
+					}
+				}
+			}
+		}
+
+		public IStateMachineIndentEngine GetEngine(int offset)
+		{
+			ResetEngineToPosition(offset);
+			return currentEngine;
+		}
+
+		#endregion
+
+		#region IClonable
+
+		/// <inheritdoc />
+		public IStateMachineIndentEngine Clone()
+		{
+			return new CacheIndentEngine(this);
+		}
+
+		/// <inheritdoc />
+		IDocumentIndentEngine IDocumentIndentEngine.Clone()
+		{
+			return Clone();
+		}
+
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+
+		#endregion
+
+		#region IStateMachineIndentEngine
+
+		public bool IsInsidePreprocessorDirective {
+			get { return currentEngine.IsInsidePreprocessorDirective; }
+		}
+
+		public bool IsInsidePreprocessorComment {
+			get { return currentEngine.IsInsidePreprocessorComment; }
+		}
+
+		public bool IsInsideStringLiteral {
+			get { return currentEngine.IsInsideStringLiteral; }
+		}
+
+		public bool IsInsideVerbatimString {
+			get { return currentEngine.IsInsideVerbatimString; }
+		}
+
+		public bool IsInsideCharacter {
+			get { return currentEngine.IsInsideCharacter; }
+		}
+
+		public bool IsInsideString {
+			get { return currentEngine.IsInsideString; }
+		}
+
+		public bool IsInsideLineComment {
+			get { return currentEngine.IsInsideLineComment; }
+		}
+
+		public bool IsInsideMultiLineComment {
+			get { return currentEngine.IsInsideMultiLineComment; }
+		}
+
+		public bool IsInsideDocLineComment {
+			get { return currentEngine.IsInsideDocLineComment; }
+		}
+
+		public bool IsInsideComment {
+			get { return currentEngine.IsInsideComment; }
+		}
+
+		public bool IsInsideOrdinaryComment {
+			get { return currentEngine.IsInsideOrdinaryComment; }
+		}
+
+		public bool IsInsideOrdinaryCommentOrString {
+			get { return currentEngine.IsInsideOrdinaryCommentOrString; }
+		}
+
+		public bool LineBeganInsideVerbatimString {
+			get { return currentEngine.LineBeganInsideVerbatimString; }
+		}
+
+		public bool LineBeganInsideMultiLineComment {
+			get { return currentEngine.LineBeganInsideMultiLineComment; }
+		}
+
+		#endregion
+
+	}
+	/*
+/		// <summary>
+	///     Represents a decorator of an IStateMachineIndentEngine instance that provides
+	///     logic for reseting and updating the engine on text changed events.
+	/// </summary>
+	/// <remarks>
+	///     The decorator is based on periodical caching of the engine's state and
+	///     delegating all logic behind indentation to the currently active engine.
+	/// </remarks>
+	public class CacheIndentEngine : IStateMachineIndentEngine
+	{
+		#region Properties
+		
+		/// <summary>
+		///     Represents the cache interval in number of chars pushed to the engine.
+		/// </summary>
+		/// <remarks>
+		///     When this many new chars are pushed to the engine, the currently active
+		///     engine gets cloned and added to the end of <see cref="cachedEngines"/>.
+		/// </remarks>
+		readonly int cacheRate;
+		
+		/// <summary>
+		///     Determines how much memory to reserve on initialization for the
+		///     cached engines.
+		/// </summary>
+		const int cacheCapacity = 25;
+		
+		/// <summary>
+		///     Currently active engine.
+		/// </summary>
+		/// <remarks>
+		///     Should be equal to the last engine in <see cref="cachedEngines"/>.
+		/// </remarks>
+		IStateMachineIndentEngine currentEngine;
+		
+		/// <summary>
+		///     List of cached engines sorted ascending by 
+		///     <see cref="IDocumentIndentEngine.Offset"/>.
+		/// </summary>
+		IStateMachineIndentEngine[] cachedEngines;
+		
+		/// <summary>
+		///     The index of the last cached engine in cachedEngines.
+		/// </summary>
+		/// <remarks>
+		///     Should be equal to: currentEngine.Offset / CacheRate
+		/// </remarks>
+		int lastCachedEngine;
+		
+		#endregion
+		
+		#region Constructors
+		
+		/// <summary>
+		///     Creates a new CacheIndentEngine instance.
+		/// </summary>
+		/// <param name="decoratedEngine">
+		///     An instance of <see cref="IStateMachineIndentEngine"/> to which the
+		///     logic for indentation will be delegated.
+		/// </param>
+		/// <param name="cacheRate">
+		///     The number of chars between caching.
+		/// </param>
+		public CacheIndentEngine(IStateMachineIndentEngine decoratedEngine, int cacheRate = 2000)
+		{
+			this.cachedEngines = new IStateMachineIndentEngine[cacheCapacity];
+			
+			this.cachedEngines[0] = decoratedEngine.Clone();
+			this.currentEngine = this.cachedEngines[0].Clone();
+			this.cacheRate = cacheRate;
+		}
+		
+		/// <summary>
+		///     Creates a new CacheIndentEngine instance from the given prototype.
+		/// </summary>
+		/// <param name="prototype">
+		///     A CacheIndentEngine instance.
+		/// </param>
+		public CacheIndentEngine(CacheIndentEngine prototype)
+		{
+			this.cachedEngines = new IStateMachineIndentEngine[prototype.cachedEngines.Length];
+			Array.Copy(prototype.cachedEngines, this.cachedEngines, prototype.cachedEngines.Length);
+			
+			this.lastCachedEngine = prototype.lastCachedEngine;
+			this.currentEngine = prototype.currentEngine.Clone();
+			this.cacheRate = prototype.cacheRate;
+		}
+		
+		#endregion
+		
+		#region Methods
+		
+		/// <summary>
+		///     Performs caching of the <see cref="CacheIndentEngine.currentEngine"/>.
+		/// </summary>
+		void cache()
+		{
+			if (currentEngine.Offset % cacheRate != 0)
+			{
+				throw new Exception("The current engine's offset is not divisable with the cacheRate.");
+			}
+			
+			// determine the new current engine from cachedEngines
+			lastCachedEngine = currentEngine.Offset / cacheRate;
+			
+			if (cachedEngines.Length < lastCachedEngine + 1)
+			{
+				Array.Resize(ref cachedEngines, lastCachedEngine * 2);
+			}
+			
+			cachedEngines[lastCachedEngine] = currentEngine.Clone();
+		}
+		
+		#endregion
+		
+		#region IDocumentIndentEngine
+		
+		/// <inheritdoc />
+		public IDocument Document
+		{
+			get { return currentEngine.Document; }
+		}
+		
+		/// <inheritdoc />
+		public string ThisLineIndent
+		{
+			get { return currentEngine.ThisLineIndent; }
+		}
+		
+		/// <inheritdoc />
+		public string NextLineIndent
+		{
+			get { return currentEngine.NextLineIndent; }
+		}
+		
+		/// <inheritdoc />
+		public string CurrentIndent
+		{
+			get { return currentEngine.CurrentIndent; }
+		}
+		
+		/// <inheritdoc />
+		public bool NeedsReindent
+		{
+			get { return currentEngine.NeedsReindent; }
+		}
+		
+		/// <inheritdoc />
+		public int Offset
+		{
+			get { return currentEngine.Offset; }
+		}
+		
+		/// <inheritdoc />
+		public TextLocation Location
+		{
+			get { return currentEngine.Location; }
+		}
+		
+		/// <inheritdoc />
+		public void Push(char ch)
+		{
+			currentEngine.Push(ch);
+			
+			if (currentEngine.Offset % cacheRate == 0)
+			{
+				cache();
+			}
+		}
+		
+		/// <inheritdoc />
+		public void Reset()
+		{
+			currentEngine = cachedEngines[lastCachedEngine = 0];
+		}
+		
+		/// <inheritdoc />
+		/// <remarks>
+		///     If the <paramref name="offset"/> is negative, the engine will
+		///     update to: document.TextLength + (offset % document.TextLength+1)
+		///     Otherwise it will update to: offset % document.TextLength+1
+		/// </remarks>
+		public void Update(int offset)
+		{
+			// map the given offset to the [0, document.TextLength] interval
+			// using modulo arithmetics
+			offset %= Document.TextLength + 1;
+			if (offset < 0)
+			{
+				offset += Document.TextLength + 1;
+			}
+			
+			// check if the engine has to be updated to some previous offset
+			if (currentEngine.Offset > offset)
+			{
+				// replace the currentEngine with the first one whose offset
+				// is less then the given <paramref name="offset"/>
+				lastCachedEngine =  offset / cacheRate;
+				currentEngine = cachedEngines[lastCachedEngine].Clone();
+			}
+			
+			// update the engine to the given offset
+			while (Offset < offset)
+			{
+				Push(Document.GetCharAt(Offset));
+			}
+		}
+		
+		public IStateMachineIndentEngine GetEngine(int offset)
+		{
+			// map the given offset to the [0, document.TextLength] interval
+			// using modulo arithmetics
+			offset %= Document.TextLength + 1;
+			if (offset < 0)
+			{
+				offset += Document.TextLength + 1;
+			}
+			
+			// check if the engine has to be updated to some previous offset
+			if (currentEngine.Offset > offset)
+			{
+				// replace the currentEngine with the first one whose offset
+				// is less then the given <paramref name="offset"/>
+				lastCachedEngine =  offset / cacheRate;
+				return cachedEngines[lastCachedEngine].Clone();
+			}
+			
+			return currentEngine;
+		}
+		
+		#endregion
+		
+		#region IClonable
+		
+		/// <inheritdoc />
+		public IStateMachineIndentEngine Clone()
+		{
+			return new CacheIndentEngine(this);
+		}
+		
+		/// <inheritdoc />
+		IDocumentIndentEngine IDocumentIndentEngine.Clone()
+		{
+			return Clone();
+		}
+		
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+		
+		#endregion
+		
+		#region IStateMachineIndentEngine
+		
+		public bool IsInsidePreprocessorDirective
+		{
+			get { return currentEngine.IsInsidePreprocessorDirective; }
+		}
+		
+		public bool IsInsidePreprocessorComment
+		{
+			get { return currentEngine.IsInsidePreprocessorComment; }
+		}
+		
+		public bool IsInsideStringLiteral
+		{
+			get { return currentEngine.IsInsideStringLiteral; }
+		}
+		
+		public bool IsInsideVerbatimString
+		{
+			get { return currentEngine.IsInsideVerbatimString; }
+		}
+		
+		public bool IsInsideCharacter
+		{
+			get { return currentEngine.IsInsideCharacter; }
+		}
+		
+		public bool IsInsideString
+		{
+			get { return currentEngine.IsInsideString; }
+		}
+		
+		public bool IsInsideLineComment
+		{
+			get { return currentEngine.IsInsideLineComment; }
+		}
+		
+		public bool IsInsideMultiLineComment
+		{
+			get { return currentEngine.IsInsideMultiLineComment; }
+		}
+		
+		public bool IsInsideDocLineComment
+		{
+			get { return currentEngine.IsInsideDocLineComment; }
+		}
+		
+		public bool IsInsideComment
+		{
+			get { return currentEngine.IsInsideComment; }
+		}
+		
+		public bool IsInsideOrdinaryComment
+		{
+			get { return currentEngine.IsInsideOrdinaryComment; }
+		}
+		
+		public bool IsInsideOrdinaryCommentOrString
+		{
+			get { return currentEngine.IsInsideOrdinaryCommentOrString; }
+		}
+		
+		public bool LineBeganInsideVerbatimString
+		{
+			get { return currentEngine.LineBeganInsideVerbatimString; }
+		}
+		
+		public bool LineBeganInsideMultiLineComment
+		{
+			get { return currentEngine.LineBeganInsideMultiLineComment; }
+		}
+		
+		#endregion
+	}
+	
+	*/
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IDocumentIndentEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IDocumentIndentEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IDocumentIndentEngine.cs	(revision 11807)
@@ -0,0 +1,108 @@
+﻿//
+// IDocumentIndentEngine.cs
+//
+// Author:
+//       Matej Miklečić <matej.miklecic@gmail.com>
+//
+// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using ICSharpCode.NRefactory.Editor;
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	///     The base interface for all indent engines.
+	/// </summary>
+	public interface IDocumentIndentEngine : ICloneable
+	{
+		/// <summary>
+		///     A reference to the document that's parsed by the engine.
+		/// </summary>
+		IDocument Document { get; }
+
+		/// <summary>
+		///     The indentation string of the current line.
+		/// </summary>
+		string ThisLineIndent { get; }
+
+		/// <summary>
+		///     The indentation string of the next line.
+		/// </summary>
+		string NextLineIndent { get; }
+
+		/// <summary>
+		///     The indent string on the beginning of the current line.
+		/// </summary>
+		string CurrentIndent { get; }
+
+		/// <summary>
+		///     True if the current line needs to be reindented.
+		/// </summary>
+		bool NeedsReindent { get; }
+
+		/// <summary>
+		///     The current offset of the engine.
+		/// </summary>
+		int Offset { get; }
+
+		/// <summary>
+		///     The current location of the engine.
+		/// </summary>
+		TextLocation Location { get; }
+
+		/// <summary>
+		///     If this is true, the engine should try to adjust its indent 
+		///     levels to manual user's corrections, even if they are wrong.
+		/// </summary>
+		bool EnableCustomIndentLevels { get; set; }
+
+		/// <summary>
+		///     Pushes a new char into the engine which calculates the new
+		///     indentation levels.
+		/// </summary>
+		/// <param name="ch">
+		///     A new character.
+		/// </param>
+		void Push(char ch);
+
+		/// <summary>
+		///     Resets the engine.
+		/// </summary>
+		void Reset();
+
+		/// <summary>
+		///     Updates the engine to the given offset.
+		/// </summary>
+		/// <param name="offset">
+		///     Valid offset in <see cref="Document"/>.
+		/// </param>
+		void Update(int offset);
+
+		/// <summary>
+		///     Clones the engine and preserves the current state.
+		/// </summary>
+		/// <returns>
+		///     An indentical clone which can operate without interference
+		///     with this engine.
+		/// </returns>
+		new IDocumentIndentEngine Clone();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IStateMachineIndentEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IStateMachineIndentEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IStateMachineIndentEngine.cs	(revision 11807)
@@ -0,0 +1,60 @@
+﻿//
+// IStateMachineIndentEngine.cs
+//
+// Author:
+//       Matej Miklečić <matej.miklecic@gmail.com>
+//
+// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public interface IStateMachineIndentEngine : IDocumentIndentEngine
+	{
+		bool IsInsidePreprocessorDirective { get; }
+
+		bool IsInsidePreprocessorComment { get; }
+
+		bool IsInsideStringLiteral { get; }
+
+		bool IsInsideVerbatimString { get; }
+
+		bool IsInsideCharacter { get; }
+
+		bool IsInsideString { get; }
+
+		bool IsInsideLineComment { get; }
+
+		bool IsInsideMultiLineComment { get; }
+
+		bool IsInsideDocLineComment { get; }
+
+		bool IsInsideComment { get; }
+
+		bool IsInsideOrdinaryComment { get; }
+
+		bool IsInsideOrdinaryCommentOrString { get; }
+
+		bool LineBeganInsideVerbatimString { get; }
+
+		bool LineBeganInsideMultiLineComment { get; }
+
+		new IStateMachineIndentEngine Clone();
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IndentState.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IndentState.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/IndentState.cs	(revision 11807)
@@ -0,0 +1,2014 @@
+﻿//
+// IndentState.cs
+//
+// Author:
+//       Matej Miklečić <matej.miklecic@gmail.com>
+//
+// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	#region IndentState
+
+	/// <summary>
+	///     The base class for all indentation states. 
+	///     Each state defines the logic for indentation based on chars that
+	///     are pushed to it.
+	/// </summary>
+	public abstract class IndentState : ICloneable
+	{
+		#region Properties
+
+		/// <summary>
+		///     The indentation engine using this state.
+		/// </summary>
+		public CSharpIndentEngine Engine;
+
+		/// <summary>
+		///     The parent state. 
+		///     This state can use the indentation levels of its parent.
+		///     When this state exits, the engine returns to the parent.
+		/// </summary>
+		public IndentState Parent;
+
+		/// <summary>
+		///     The indentation of the current line.
+		///     This is set when the state is created and will be changed to
+		///     <see cref="NextLineIndent"/> when the <see cref="CSharpIndentEngine.newLineChar"/> 
+		///     is pushed.
+		/// </summary>
+		public Indent ThisLineIndent;
+
+		/// <summary>
+		///     The indentation of the next line.
+		///     This is set when the state is created and can change depending
+		///     on the pushed chars.
+		/// </summary>
+		public Indent NextLineIndent;
+
+		#endregion
+
+		#region Constructors
+
+		protected IndentState()
+		{
+		}
+
+		/// <summary>
+		///     Creates a new indentation state that is a copy of the given
+		///     prototype.
+		/// </summary>
+		/// <param name="prototype">
+		///     The prototype state.
+		/// </param>
+		/// <param name="engine">
+		///     The engine of the new state.
+		/// </param>
+		protected IndentState(IndentState prototype, CSharpIndentEngine engine)
+		{
+			Engine = engine;
+			Parent = prototype.Parent != null ? prototype.Parent.Clone(engine) : null;
+
+			ThisLineIndent = prototype.ThisLineIndent.Clone();
+			NextLineIndent = prototype.NextLineIndent.Clone();
+		}
+
+		#endregion
+
+		#region IClonable
+
+		object ICloneable.Clone()
+		{
+			return Clone(Engine);
+		}
+
+		public abstract IndentState Clone(CSharpIndentEngine engine);
+
+		#endregion
+
+		#region Methods
+
+		internal void Initialize (CSharpIndentEngine engine, IndentState parent = null)
+		{
+			Parent = parent;
+			Engine = engine;
+
+			InitializeState();
+		}
+
+		/// <summary>
+		///     Initializes the state:
+		///       - sets the default indentation levels.
+		/// </summary>
+		/// <remarks>
+		///     Each state can override this method if it needs a different
+		///     logic for setting up the default indentations.
+		/// </remarks>
+		public virtual void InitializeState()
+		{
+			ThisLineIndent = new Indent(Engine.textEditorOptions);
+			NextLineIndent = ThisLineIndent.Clone();
+		}
+
+		/// <summary>
+		///     Actions performed when this state exits.
+		/// </summary>
+		public virtual void OnExit()
+		{
+			if (Parent != null)
+			{
+				// if a state exits on the newline character, it has to push
+				// it back to its parent (and so on recursively if the parent 
+				// state also exits). Otherwise, the parent state wouldn't
+				// know that the engine isn't on the same line anymore.
+				if (Engine.currentChar == Engine.newLineChar)
+				{
+					Parent.Push(Engine.newLineChar);
+				}
+
+				// when a state exits the engine stays on the same line and this
+				// state has to override the Parent.ThisLineIndent.
+				Parent.ThisLineIndent = ThisLineIndent.Clone();
+			}
+		}
+
+		/// <summary>
+		///     Changes the current state of the <see cref="CSharpIndentEngine"/> using the current
+		///     state as the parent for the new one.
+		/// </summary>
+		/// <typeparam name="T">
+		///     The type of the new state. Must be assignable from <see cref="IndentState"/>.
+		/// </typeparam>
+		public void ChangeState<T>()
+			where T : IndentState, new ()
+		{
+			var t = new T();
+			t.Initialize(Engine, Engine.currentState);
+			Engine.currentState = t;
+		}
+
+		/// <summary>
+		///     Exits this state by setting the current state of the
+		///     <see cref="CSharpIndentEngine"/> to this state's parent.
+		/// </summary>
+		public void ExitState()
+		{
+			OnExit();
+			Engine.currentState = Engine.currentState.Parent ?? new GlobalBodyState(Engine);
+		}
+
+		/// <summary>
+		///     Common logic behind the push method.
+		///     Each state can override this method and implement its own logic.
+		/// </summary>
+		/// <param name="ch">
+		///     The current character that's being pushed.
+		/// </param>
+		public virtual void Push(char ch)
+		{
+			// replace ThisLineIndent with NextLineIndent if the newLineChar is pushed
+			if (ch == Engine.newLineChar)
+			{
+				var delta = Engine.textEditorOptions.ContinuationIndent;
+				while (NextLineIndent.CurIndent - ThisLineIndent.CurIndent > delta &&
+					   NextLineIndent.PopIf(IndentType.Continuation)) ;
+				ThisLineIndent = NextLineIndent.Clone();
+			}
+		}
+
+		/// <summary>
+		///     When derived, checks if the given sequence of chars form
+		///     a valid keyword or variable name, depending on the state.
+		/// </summary>
+		/// <param name="keyword">
+		///     A possible keyword.
+		/// </param>
+		public virtual void CheckKeyword(string keyword)
+		{ }
+
+		/// <summary>
+		///     When derived, checks if the given sequence of chars form
+		///     a valid keyword or variable name, depending on the state.
+		/// </summary>
+		/// <param name="keyword">
+		///     A possible keyword.
+		/// </param>
+		/// <remarks>
+		///     This method should be called from <see cref="Push(char)"/>.
+		///     It is left to derived classes to call this method because of
+		///     performance issues.
+		/// </remarks>
+		public virtual void CheckKeywordOnPush(string keyword)
+		{ }
+
+		#endregion
+	}
+
+	#endregion
+
+	#region Null state
+
+	/// <summary>
+	///     Null state.
+	/// </summary>
+	/// <remarks>
+	///     Doesn't define any transitions to new states.
+	/// </remarks>
+	public class NullState : IndentState
+	{
+		public NullState()
+		{ }
+
+		public NullState(NullState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{ }
+
+		public override void Push(char ch)
+		{ }
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new NullState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region Brackets body states
+
+	#region Brackets body base
+
+	/// <summary>
+	///     The base for all brackets body states.
+	/// </summary>
+	/// <remarks>
+	///     Represents a block of code between a pair of brackets.
+	/// </remarks>
+	public abstract class BracketsBodyBaseState : IndentState
+	{
+	
+		/// <summary>
+		///     When derived in a concrete bracket body state, represents
+		///     the closed bracket character pair.
+		/// </summary>
+		public abstract char ClosedBracket { get; }
+
+		protected BracketsBodyBaseState()
+		{ }
+
+		protected BracketsBodyBaseState(BracketsBodyBaseState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{ }
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+			switch (ch) {
+				case '#':
+					if (Engine.isLineStart)
+						ChangeState<PreProcessorState>();
+					break;
+				case '/':
+					if (Engine.previousChar == '/')
+						ChangeState<LineCommentState>();
+					break;
+				case '*':
+					if (Engine.previousChar == '/')
+						ChangeState<MultiLineCommentState>();
+					break;
+				case '"':
+					if (Engine.previousChar == '@')
+					{
+						ChangeState<VerbatimStringState>();
+					}
+					else
+					{
+						ChangeState<StringLiteralState>();
+					}
+					break;
+				case '\'':
+					ChangeState<CharacterState>();
+					break;
+				case '{':
+					ChangeState<BracesBodyState>();
+					break;
+				case '(':
+					ChangeState<ParenthesesBodyState>();
+					break;
+				case '[':
+					ChangeState<SquareBracketsBodyState>();
+					break;
+				default:
+					if (ch == ClosedBracket)
+						ExitState();
+					break;
+			}
+		}
+	}
+
+	#endregion
+
+	#region Braces body state
+
+	/// <summary>
+	///     Braces body state.
+	/// </summary>
+	/// <remarks>
+	///     Represents a block of code between { and }.
+	/// </remarks>
+	public class BracesBodyState : BracketsBodyBaseState
+	{
+		/// <summary>
+		///     Type of the current block body.
+		/// </summary>
+		public Body CurrentBody;
+
+		/// <summary>
+		///     Type of the next block body.
+		///     Same as <see cref="CurrentBody"/> if none of the
+		///     <see cref="Body"/> keywords have been read.
+		/// </summary>
+		public Body NextBody;
+
+		/// <summary>
+		///     Type of the current statement.
+		/// </summary>
+		public Statement CurrentStatement
+		{
+			get
+			{
+				return currentStatement;
+			}
+			set
+			{
+				// clear NestedIfStatementLevels if this statement breaks the sequence
+				if (currentStatement == Statement.None && value != Statement.Else)
+				{
+					NestedIfStatementLevels.Clear();
+				}
+
+				currentStatement = value;
+			}
+		}
+		Statement currentStatement;
+
+		/// <summary>
+		///    Contains indent levels of nested if statements.
+		/// </summary>
+		internal CloneableStack<Indent> NestedIfStatementLevels = new CloneableStack<Indent>();
+
+		/// <summary>
+		///    Contains the indent level of the last statement or body keyword.
+		/// </summary>
+		public Indent LastBlockIndent;
+
+		/// <summary>
+		///     True if the engine is on the right side of the equal operator '='.
+		/// </summary>
+		public bool IsRightHandExpression;
+
+		/// <summary>
+		///     True if the '=' char has been pushed and it's not
+		///     a part of a relational operator (&gt;=, &lt;=, !=, ==).
+		/// </summary>
+		public bool IsEqualCharPushed;
+
+		/// <summary>
+		///     The indentation of the previous line.
+		/// </summary>
+		public int PreviousLineIndent;
+
+		/// <summary>
+		///     True if the dot member (e.g. method invocation) indentation has
+		///     been handled in the current statement.
+		/// </summary>
+		public bool IsMemberReferenceDotHandled;
+
+		public override char ClosedBracket
+		{
+			get { return '}'; }
+		}
+
+		public BracesBodyState()
+		{
+		}
+
+		public BracesBodyState(BracesBodyState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			CurrentBody = prototype.CurrentBody;
+			NextBody = prototype.NextBody;
+			CurrentStatement = prototype.CurrentStatement;
+			NestedIfStatementLevels = prototype.NestedIfStatementLevels.Clone();
+			IsRightHandExpression = prototype.IsRightHandExpression;
+			IsEqualCharPushed = prototype.IsEqualCharPushed;
+			IsMemberReferenceDotHandled = prototype.IsMemberReferenceDotHandled;
+			LastBlockIndent = prototype.LastBlockIndent;
+			PreviousLineIndent = prototype.PreviousLineIndent;
+		}
+
+		public override void Push(char ch)
+		{
+			// handle IsRightHandExpression property
+			if (IsEqualCharPushed)
+			{
+				if (IsRightHandExpression)
+				{
+					if (ch == Engine.newLineChar)
+					{
+						NextLineIndent.RemoveAlignment();
+						NextLineIndent.Push(IndentType.Continuation);
+					}
+				}
+				// ignore "==" and "=>" operators
+				else if (ch != '=' && ch != '>')
+				{
+					IsRightHandExpression = true;
+
+					if (ch == Engine.newLineChar)
+					{
+						NextLineIndent.Push(IndentType.Continuation);
+					}
+					else
+					{
+						NextLineIndent.SetAlignment(Engine.column - NextLineIndent.CurIndent);
+					}
+				}
+
+				IsEqualCharPushed = ch == ' ' || ch == '\t';
+			}
+
+			if (ch == ';' || (ch == ',' && IsRightHandExpression))
+			{
+				OnStatementExit();
+			}
+			else if (ch == '=' && !(Engine.previousChar == '=' || Engine.previousChar == '<' || Engine.previousChar == '>' || Engine.previousChar == '!'))
+			{
+				IsEqualCharPushed = true;
+			}
+			else if (ch == '.' && !IsMemberReferenceDotHandled)
+			{
+				// OPTION: CSharpFormattingOptions.AlignToMemberReferenceDot
+				if (Engine.formattingOptions.AlignToMemberReferenceDot && !Engine.isLineStart)
+				{
+					IsMemberReferenceDotHandled = true;
+					NextLineIndent.RemoveAlignment();
+					NextLineIndent.SetAlignment(Engine.column - NextLineIndent.CurIndent - 1, true);
+				}
+				else if (Engine.isLineStart)
+				{
+					IsMemberReferenceDotHandled = true;
+
+					ThisLineIndent.RemoveAlignment();
+					while (ThisLineIndent.CurIndent > PreviousLineIndent && 
+					       ThisLineIndent.PopIf(IndentType.Continuation)) ;
+					ThisLineIndent.Push(IndentType.Continuation);
+					NextLineIndent = ThisLineIndent.Clone();
+				}
+			}
+			else if (ch == ':' && Engine.isLineStart && !IsRightHandExpression)
+			{
+				// try to capture ': base(...)', ': this(...)' and inherit statements when they are on a new line
+				ThisLineIndent.Push(IndentType.Continuation);
+			}
+			else if (ch == Engine.newLineChar)
+			{
+				PreviousLineIndent = ThisLineIndent.CurIndent;
+			}
+
+			if (Engine.wordToken.ToString() == "else")
+			{
+				CheckKeywordOnPush("else");
+			}
+
+			base.Push(ch);
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = Parent.NextLineIndent.Clone();
+
+			// OPTION: IDocumentIndentEngine.EnableCustomIndentLevels
+			var parent = Parent as BracesBodyState;
+			if (parent == null || parent.LastBlockIndent == null || !Engine.EnableCustomIndentLevels)
+			{
+				NextLineIndent.RemoveAlignment();
+				NextLineIndent.PopIf(IndentType.Continuation);
+			}
+			else
+			{
+				NextLineIndent = parent.LastBlockIndent.Clone();
+			}
+
+			if (Engine.isLineStart)
+			{
+				ThisLineIndent = NextLineIndent.Clone();
+			}
+
+			CurrentBody = extractBody(Parent);
+			NextBody = Body.None;
+			CurrentStatement = Statement.None;
+
+			AddIndentation(CurrentBody);
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new BracesBodyState(this, engine);
+		}
+
+		public override void OnExit()
+		{
+			if (Parent is BracesBodyState && !((BracesBodyState)Parent).IsRightHandExpression)
+			{
+				((BracesBodyState)Parent).OnStatementExit();
+			}
+
+			if (Engine.isLineStart)
+			{
+				ThisLineIndent.RemoveAlignment();
+				ThisLineIndent.PopTry();
+				BraceStyle style;
+				if (TryGetBraceStyle(this.CurrentBody, out style)) {
+					if (style == BraceStyle.NextLineShifted ||
+						style == BraceStyle.NextLineShifted2||
+						style == BraceStyle.BannerStyle) {
+						ThisLineIndent.Push(IndentType.Block);
+					}
+				}
+			}
+
+			base.OnExit();
+		}
+
+		/// <summary>
+		///     Actions performed when the current statement exits.
+		/// </summary>
+		public virtual void OnStatementExit()
+		{
+			IsRightHandExpression = false;
+			IsMemberReferenceDotHandled = false;
+
+			NextLineIndent.RemoveAlignment();
+			NextLineIndent.PopWhile(IndentType.Continuation);
+
+			CurrentStatement = Statement.None;
+			NextBody = Body.None;
+			LastBlockIndent = null;
+		}
+
+		#region Helpers
+
+		/// <summary>
+		///     Types of braces bodies.
+		/// </summary>
+		public enum Body
+		{
+			None,
+			Namespace,
+			Class,
+			Struct,
+			Interface,
+			Enum,
+			Switch,
+			Case,
+			Try,
+			Catch,
+			Finally
+		}
+
+		/// <summary>
+		///     Types of statements.
+		/// </summary>
+		public enum Statement
+		{
+			None,
+			If,
+			Else,
+			Do,
+			While,
+			For,
+			Foreach,
+			Lock,
+			Using,
+			Return
+		}
+
+		static readonly Dictionary<string, Body> bodies = new Dictionary<string, Body>
+		{
+			{ "namespace", Body.Namespace },
+			{ "class", Body.Class },
+			{ "struct", Body.Struct },
+			{ "interface", Body.Interface },
+			{ "enum", Body.Enum },
+			{ "switch", Body.Switch },
+			{ "try", Body.Try },
+			{ "catch", Body.Catch },
+			{ "finally", Body.Finally },
+		};
+
+		static readonly Dictionary<string, Statement> statements = new Dictionary<string, Statement>
+		{
+			{ "if", Statement.If },
+			// { "else", Statement.Else }, // should be handled in CheckKeywordAtPush
+			{ "do", Statement.Do },
+			{ "while", Statement.While },
+			{ "for", Statement.For },
+			{ "foreach", Statement.Foreach },
+			{ "lock", Statement.Lock },
+			{ "using", Statement.Using },
+			{ "return", Statement.Return },
+		};
+
+		static readonly HashSet<string> blocks = new HashSet<string>
+		{
+			"namespace",
+			"class",
+			"struct",
+			"interface",
+			"enum",
+			"switch",
+			"try",
+			"catch",
+			"finally",
+			"if",
+			"else",
+			"do",
+			"while",
+			"for",
+			"foreach",
+			"lock",
+			"using",
+		};
+
+		readonly string[] caseDefaultKeywords = {
+			"case",
+			"default"
+		};
+
+		readonly string[] classStructKeywords = {
+			"class",
+			"struct"
+		};
+
+		/// <summary>
+		///     Checks if the given string is a keyword and sets the
+		///     <see cref="NextBody"/> and the <see cref="CurrentStatement"/>
+		///     variables appropriately.
+		/// </summary>
+		/// <param name="keyword">
+		///     A possible keyword.
+		/// </param>
+		/// <remarks>
+		///     This method is called from <see cref="Push(char)"/>
+		/// </remarks>
+		public override void CheckKeywordOnPush(string keyword)
+		{
+			if (keyword == "else")
+			{
+				CurrentStatement = Statement.Else;
+
+				// OPTION: CSharpFormattingOptions.AlignElseInIfStatements
+				if (!Engine.formattingOptions.AlignElseInIfStatements && NestedIfStatementLevels.Count > 0)
+				{
+					ThisLineIndent = NestedIfStatementLevels.Pop().Clone();
+					NextLineIndent = ThisLineIndent.Clone();
+				}
+
+				NextLineIndent.Push(IndentType.Continuation);
+			}
+
+			if (blocks.Contains(keyword) && Engine.NeedsReindent)
+			{
+				LastBlockIndent = Indent.ConvertFrom(Engine.CurrentIndent, ThisLineIndent, Engine.textEditorOptions);
+			}
+		}
+
+		/// <summary>
+		///     Checks if the given string is a keyword and sets the
+		///     <see cref="NextBody"/> and the <see cref="CurrentStatement"/>
+		///     variables appropriately.
+		/// </summary>
+		/// <param name="keyword">
+		///     A possible keyword.
+		/// </param>
+		public override void CheckKeyword(string keyword)
+		{
+			if (bodies.ContainsKey(keyword))
+			{
+				var isKeywordTemplateConstraint =
+					classStructKeywords.Contains(keyword) &&
+					(NextBody == Body.Class || NextBody == Body.Struct || NextBody == Body.Interface);
+
+				if (!isKeywordTemplateConstraint)
+				{
+					NextBody = bodies[keyword];
+				}
+			}
+			else if (caseDefaultKeywords.Contains(keyword) && CurrentBody == Body.Switch && Engine.isLineStartBeforeWordToken)
+			{
+				ChangeState<SwitchCaseState>();
+			}
+			else if (keyword == "where" && Engine.isLineStartBeforeWordToken)
+			{
+				// try to capture where (generic type constraint)
+				ThisLineIndent.Push(IndentType.Continuation);
+			}
+			else if (statements.ContainsKey(keyword))
+			{
+				Statement previousStatement = CurrentStatement;
+				CurrentStatement = statements[keyword];
+
+				// return if this is a using declaration or alias
+				if (CurrentStatement == Statement.Using &&
+				   (this is GlobalBodyState || CurrentBody == Body.Namespace))
+				{
+					return;
+				}
+
+				// OPTION: CSharpFormattingOptions.AlignEmbeddedIfStatements
+				if (Engine.formattingOptions.AlignEmbeddedStatements &&
+					previousStatement == Statement.If &&
+					CurrentStatement == Statement.If)
+				{
+					ThisLineIndent.PopIf(IndentType.Continuation);
+					NextLineIndent.PopIf(IndentType.Continuation);
+				}
+
+				// OPTION: CSharpFormattingOptions.AlignEmbeddedStatements
+				if (Engine.formattingOptions.AlignEmbeddedStatements &&
+					previousStatement == Statement.Lock &&
+					CurrentStatement == Statement.Lock)
+				{
+					ThisLineIndent.PopIf(IndentType.Continuation);
+					NextLineIndent.PopIf(IndentType.Continuation);
+				}
+
+				// OPTION: CSharpFormattingOptions.AlignEmbeddedUsingStatements
+				if (Engine.formattingOptions.AlignEmbeddedStatements &&
+					previousStatement == Statement.Using &&
+					CurrentStatement == Statement.Using)
+				{
+					ThisLineIndent.PopIf(IndentType.Continuation);
+					NextLineIndent.PopIf(IndentType.Continuation);
+				}
+
+				// only add continuation for 'else' in 'else if' statement.
+				if (!(CurrentStatement == Statement.If && previousStatement == Statement.Else && !Engine.isLineStartBeforeWordToken))
+				{
+					NextLineIndent.Push(IndentType.Continuation);
+				}
+
+				if (CurrentStatement == Statement.If)
+				{
+					NestedIfStatementLevels.Push(ThisLineIndent);
+				}
+			}
+
+			if (blocks.Contains(keyword) && Engine.NeedsReindent)
+			{
+				LastBlockIndent = Indent.ConvertFrom(Engine.CurrentIndent, ThisLineIndent, Engine.textEditorOptions);
+			}
+		}
+
+		/// <summary>
+		///     Pushes a new level of indentation depending on the given
+		///     <paramref name="braceStyle"/>.
+		/// </summary>
+		void AddIndentation(BraceStyle braceStyle)
+		{
+			switch (braceStyle)
+			{
+				case BraceStyle.NextLineShifted:
+					ThisLineIndent.Push(IndentType.Block);
+					NextLineIndent.Push(IndentType.Block);
+					break;
+				case BraceStyle.DoNotChange:
+				case BraceStyle.EndOfLine:
+				case BraceStyle.EndOfLineWithoutSpace:
+				case BraceStyle.NextLine:
+				case BraceStyle.BannerStyle:
+					NextLineIndent.Push(IndentType.Block);
+					break;
+				case BraceStyle.NextLineShifted2:
+					ThisLineIndent.Push(IndentType.Block);
+					NextLineIndent.Push(IndentType.DoubleBlock);
+					break;
+			}
+		}
+
+		bool TryGetBraceStyle (Body body, out BraceStyle style)
+		{
+			style = BraceStyle.DoNotChange;
+			switch (body)
+			{
+				case Body.None:
+					if (!Engine.formattingOptions.IndentBlocks)
+						return false;
+					style = Engine.formattingOptions.StatementBraceStyle;
+					return true;
+				case Body.Namespace:
+					if (!Engine.formattingOptions.IndentNamespaceBody)
+						return false;
+					style = Engine.formattingOptions.NamespaceBraceStyle;
+					return true;
+				case Body.Class:
+					if (!Engine.formattingOptions.IndentClassBody)
+						return false;
+					style = Engine.formattingOptions.ClassBraceStyle;
+					return true;
+				case Body.Struct:
+					if (!Engine.formattingOptions.IndentStructBody)
+						return false;
+					style = Engine.formattingOptions.StructBraceStyle;
+					return true;
+				case Body.Interface:
+					if (!Engine.formattingOptions.IndentInterfaceBody)
+						return false;
+					style = Engine.formattingOptions.InterfaceBraceStyle;
+					return true;
+				case Body.Enum:
+					if (!Engine.formattingOptions.IndentEnumBody)
+						return false;
+					style = Engine.formattingOptions.EnumBraceStyle;
+					return true;
+				case Body.Switch:
+					if (!Engine.formattingOptions.IndentSwitchBody)
+						return false;
+					style = Engine.formattingOptions.StatementBraceStyle;
+					return true;
+				case Body.Try:
+				case Body.Catch:
+				case Body.Finally:
+					style = Engine.formattingOptions.StatementBraceStyle;
+					return true;
+			}
+			return false;
+		}
+
+		/// <summary>
+		///     Pushes a new level of indentation depending on the given
+		///     <paramref name="body"/>.
+		/// </summary>
+		void AddIndentation(Body body)
+		{
+			var isExpression = Parent is ParenthesesBodyState || Parent is SquareBracketsBodyState ||
+				(Parent is BracesBodyState && ((BracesBodyState)Parent).IsRightHandExpression);
+			if (isExpression && Engine.formattingOptions.IndentBlocksInsideExpressions && Engine.isLineStart)
+			{
+				AddIndentation(BraceStyle.NextLineShifted);
+			}
+
+			BraceStyle style;
+			if (TryGetBraceStyle(body, out style))
+			{
+				AddIndentation(style);
+			} else {
+				NextLineIndent.Push(IndentType.Empty);
+			}
+		}
+
+		/// <summary>
+		///     Extracts the <see cref="CurrentBody"/> from the given state.
+		/// </summary>
+		/// <returns>
+		///     The correct <see cref="Body"/> type for this state.
+		/// </returns>
+		static Body extractBody(IndentState state)
+		{
+			if (state != null && state is BracesBodyState)
+			{
+				return ((BracesBodyState)state).NextBody;
+			}
+
+			return Body.None;
+		}
+
+		#endregion
+	}
+
+	#endregion
+
+	#region Global body state
+
+	/// <summary>
+	///     Global body state.
+	/// </summary>
+	/// <remarks>
+	///     Represents the global space of the program.
+	/// </remarks>
+	public class GlobalBodyState : BracesBodyState
+	{
+		public override char ClosedBracket
+		{
+			get { return '\0'; }
+		}
+
+		public GlobalBodyState()
+		{ }
+
+
+		public GlobalBodyState(CSharpIndentEngine engine)
+		{
+			Initialize (engine, null);
+		}
+
+		public GlobalBodyState(GlobalBodyState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{ }
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new GlobalBodyState(this, engine);
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = new Indent(Engine.textEditorOptions);
+			NextLineIndent = ThisLineIndent.Clone();
+		}
+	}
+
+	#endregion
+
+	#region Switch-case body state
+
+	/// <summary>
+	///     Switch-case statement state.
+	/// </summary>
+	/// <remarks>
+	///     Represents the block of code in one switch case (including default).
+	/// </remarks>
+	public class SwitchCaseState : BracesBodyState
+	{
+		public SwitchCaseState()
+		{ }
+
+		public SwitchCaseState(SwitchCaseState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{ }
+
+		public override void Push(char ch)
+		{
+			// on ClosedBracket both this state (a case or a default statement)
+			// and also the whole switch block (handled in the base class) must exit.
+			if (ch == ClosedBracket)
+			{
+				ExitState();
+				if (Parent is BracesBodyState)
+					Parent.OnExit();
+			}
+
+			base.Push(ch);
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = ThisLineIndent.Clone();
+
+			// remove all continuations and extra spaces
+			ThisLineIndent.RemoveAlignment(); 
+			ThisLineIndent.PopWhile(IndentType.Continuation);
+
+			NextLineIndent.RemoveAlignment();
+			NextLineIndent.PopWhile(IndentType.Continuation);
+
+			if (Engine.formattingOptions.IndentCaseBody)
+			{
+				NextLineIndent.Push(IndentType.Block);
+			}
+			else
+			{
+				NextLineIndent.Push(IndentType.Empty);
+			}
+		}
+
+		static readonly string[] caseDefaultKeywords = {
+			"case",
+			"default"
+		};
+
+		static readonly string[] breakContinueReturnGotoKeywords = {
+			"break",
+			"continue",
+			"return",
+			"goto"
+		};
+
+		public override void CheckKeyword(string keyword)
+		{
+			if (caseDefaultKeywords.Contains(keyword) && Engine.isLineStartBeforeWordToken)
+			{
+				ExitState();
+				ChangeState<SwitchCaseState>();
+			}
+			else if (breakContinueReturnGotoKeywords.Contains(keyword) && Engine.isLineStartBeforeWordToken)
+			{
+				// OPTION: Engine.formattingOptions.IndentBreakStatements
+				if (!Engine.formattingOptions.IndentBreakStatements)
+				{
+					ThisLineIndent = Parent.ThisLineIndent.Clone();
+				}
+			}
+
+			base.CheckKeyword(keyword);
+		}
+
+
+		public override void OnExit()
+		{
+			//Parent.OnExit();
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new SwitchCaseState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region Parentheses body state
+
+	/// <summary>
+	///     Parentheses body state.
+	/// </summary>
+	/// <remarks>
+	///     Represents a block of code between ( and ).
+	/// </remarks>
+	public class ParenthesesBodyState : BracketsBodyBaseState
+	{
+		/// <summary>
+		///     True if any char has been pushed.
+		/// </summary>
+		public bool IsSomethingPushed;
+
+		public override char ClosedBracket
+		{
+			get { return ')'; }
+		}
+
+		public ParenthesesBodyState()
+		{ }
+
+		public ParenthesesBodyState(ParenthesesBodyState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			IsSomethingPushed = prototype.IsSomethingPushed;
+		}
+
+		public override void Push(char ch)
+		{
+			if (ch == Engine.newLineChar)
+			{
+				if (Engine.formattingOptions.AnonymousMethodBraceStyle == BraceStyle.EndOfLine || 
+					Engine.formattingOptions.AnonymousMethodBraceStyle == BraceStyle.EndOfLineWithoutSpace) {
+					if (NextLineIndent.PopIf(IndentType.Continuation)) {
+						NextLineIndent.Push(IndentType.Block);
+					}
+				}
+			}
+			else if (!IsSomethingPushed)
+			{
+				// OPTION: CSharpFormattingOptions.AlignToFirstMethodCallArgument
+				if (Engine.formattingOptions.AlignToFirstMethodCallArgument)
+				{
+					NextLineIndent.PopTry();
+					// align the next line at the beginning of the open bracket
+					NextLineIndent.ExtraSpaces = Math.Max(0, Engine.column - NextLineIndent.CurIndent - 1);
+				}
+			}
+
+			base.Push(ch);
+			IsSomethingPushed = true;
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = ThisLineIndent.Clone();
+			NextLineIndent.Push(IndentType.Continuation);
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new ParenthesesBodyState(this, engine);
+		}
+
+		public override void OnExit()
+		{
+			if (Engine.isLineStart)
+			{
+				if (ThisLineIndent.ExtraSpaces > 0)
+				{
+					ThisLineIndent.ExtraSpaces--;
+				}
+				else
+				{
+					ThisLineIndent.PopTry();
+				}
+			}
+
+			base.OnExit();
+		}
+	}
+
+	#endregion
+
+	#region Square brackets body state
+
+	/// <summary>
+	///     Square brackets body state.
+	/// </summary>
+	/// <remarks>
+	///     Represents a block of code between [ and ].
+	/// </remarks>
+	public class SquareBracketsBodyState : BracketsBodyBaseState
+	{
+		/// <summary>
+		///     True if any char has been pushed.
+		/// </summary>
+		public bool IsSomethingPushed;
+
+		public override char ClosedBracket
+		{
+			get { return ']'; }
+		}
+
+		public SquareBracketsBodyState()
+		{ }
+
+		public SquareBracketsBodyState(SquareBracketsBodyState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			IsSomethingPushed = prototype.IsSomethingPushed;
+		}
+
+		public override void Push(char ch)
+		{
+			if (ch == Engine.newLineChar)
+			{
+				if (NextLineIndent.PopIf(IndentType.Continuation))
+				{
+					NextLineIndent.Push(IndentType.Block);
+				}
+			}
+			else if (!IsSomethingPushed)
+			{
+				// OPTION: CSharpFormattingOptions.AlignToFirstIndexerArgument
+				if (Engine.formattingOptions.AlignToFirstIndexerArgument)
+				{
+					NextLineIndent.PopTry();
+					// align the next line at the beginning of the open bracket
+					NextLineIndent.ExtraSpaces = Math.Max(0, Engine.column - NextLineIndent.CurIndent - 1);
+				}
+			}
+
+			base.Push(ch);
+			IsSomethingPushed = true;
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = ThisLineIndent.Clone();
+			NextLineIndent.Push(IndentType.Continuation);
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new SquareBracketsBodyState(this, engine);
+		}
+
+		public override void OnExit()
+		{
+			if (Engine.isLineStart)
+			{
+				if (ThisLineIndent.ExtraSpaces > 0)
+				{
+					ThisLineIndent.ExtraSpaces--;
+				}
+				else
+				{
+					ThisLineIndent.PopTry();
+				}
+			}
+
+			base.OnExit();
+		}
+	}
+
+	#endregion
+
+	#endregion
+
+	#region PreProcessor state
+
+	/// <summary>
+	///     PreProcessor directive state.
+	/// </summary>
+	/// <remarks>
+	///     Activated when the '#' char is pushed and the 
+	///     <see cref="CSharpIndentEngine.isLineStart"/> is true.
+	/// </remarks>
+	public class PreProcessorState : IndentState
+	{
+		/// <summary>
+		///     The type of the preprocessor directive.
+		/// </summary>
+		public PreProcessorDirective DirectiveType;
+
+		/// <summary>
+		///     If <see cref="DirectiveType"/> is set (not equal to 'None'), this
+		///     stores the expression of the directive.
+		/// </summary>
+		public StringBuilder DirectiveStatement;
+
+		public PreProcessorState()
+		{
+			DirectiveType = PreProcessorDirective.None;
+			DirectiveStatement = new StringBuilder();
+		}
+
+		public PreProcessorState(PreProcessorState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			DirectiveType = prototype.DirectiveType;
+			DirectiveStatement = new StringBuilder(prototype.DirectiveStatement.ToString());
+		}
+
+		public override void Push(char ch)
+		{
+			// HACK: if this change would be left for the CheckKeyword method, we will lose
+			//       it if the next pushed char is newLineChar since ThisLineIndent will be 
+			//       immediately replaced with NextLineIndent. As this most likely will
+			//       happen, we check for "endregion" on every push.
+			if (Engine.wordToken.ToString() == "endregion")
+			{
+				CheckKeywordOnPush("endregion");
+			}
+
+			base.Push(ch);
+
+			if (DirectiveType != PreProcessorDirective.None)
+			{
+				DirectiveStatement.Append(ch);
+			}
+
+			if (ch == Engine.newLineChar)
+			{
+				ExitState();
+				switch (DirectiveType)
+				{
+					case PreProcessorDirective.If:
+						Engine.ifDirectiveEvalResults.Push(eval(DirectiveStatement.ToString()));
+						if (Engine.ifDirectiveEvalResults.Peek())
+						{
+							// the if/elif directive is true -> continue with the previous state
+						}
+						else
+						{
+							// the if/elif directive is false -> change to a state that will 
+							// ignore any chars until #endif or #elif
+							ChangeState<PreProcessorCommentState>();
+						}
+						break;
+					case PreProcessorDirective.Elif:
+						if (Engine.ifDirectiveEvalResults.Count > 0)
+						{
+							if (!Engine.ifDirectiveEvalResults.Peek())
+							{
+								Engine.ifDirectiveEvalResults.Pop();
+								goto case PreProcessorDirective.If;
+							}
+						}
+						// previous if was true -> comment
+						ChangeState<PreProcessorCommentState>();
+						break;
+					case PreProcessorDirective.Else:
+						if (Engine.ifDirectiveEvalResults.Count > 0 && Engine.ifDirectiveEvalResults.Peek())
+						{
+							// some if/elif directive was true -> change to a state that will 
+							// ignore any chars until #endif
+							ChangeState<PreProcessorCommentState>();
+						}
+						else
+						{
+							// none if/elif directives were true -> continue with the previous state
+						}
+						break;
+					case PreProcessorDirective.Define:
+						var defineSymbol = DirectiveStatement.ToString().Trim();
+						if (!Engine.conditionalSymbols.Contains(defineSymbol))
+						{
+							Engine.conditionalSymbols.Add(defineSymbol);
+						}
+						break;
+					case PreProcessorDirective.Undef:
+						var undefineSymbol = DirectiveStatement.ToString().Trim();
+						if (Engine.conditionalSymbols.Contains(undefineSymbol))
+						{
+							Engine.conditionalSymbols.Remove(undefineSymbol);
+						}
+						break;
+					case PreProcessorDirective.Endif:
+						// marks the end of this block
+						Engine.ifDirectiveEvalResults.Pop();
+						Engine.ifDirectiveIndents.Pop();
+						break;
+					case PreProcessorDirective.Region:
+					case PreProcessorDirective.Pragma:
+					case PreProcessorDirective.Warning:
+					case PreProcessorDirective.Error:
+					case PreProcessorDirective.Line:
+						// continue with the previous state
+						break;
+				}
+			}
+		}
+
+		public override void InitializeState()
+		{
+			// OPTION: IndentPreprocessorStatements
+			if (Engine.formattingOptions.IndentPreprocessorDirectives)
+			{
+				if (Engine.ifDirectiveIndents.Count > 0)
+				{
+					ThisLineIndent = Engine.ifDirectiveIndents.Peek().Clone();
+				}
+				else
+				{
+					ThisLineIndent = Parent.ThisLineIndent.Clone();
+				}
+			}
+			else
+			{
+				ThisLineIndent = new Indent(Engine.textEditorOptions);
+			}
+
+			NextLineIndent = Parent.NextLineIndent.Clone();
+		}
+
+		static readonly Dictionary<string, PreProcessorDirective> preProcessorDirectives = new Dictionary<string, PreProcessorDirective>
+		{
+			{ "if", PreProcessorDirective.If },
+			{ "elif", PreProcessorDirective.Elif },
+			{ "else", PreProcessorDirective.Else },
+			{ "endif", PreProcessorDirective.Endif },
+			{ "region", PreProcessorDirective.Region },
+			{ "endregion", PreProcessorDirective.Endregion },
+			{ "pragma", PreProcessorDirective.Pragma },
+			{ "warning", PreProcessorDirective.Warning },
+			{ "error", PreProcessorDirective.Error },
+			{ "line", PreProcessorDirective.Line },
+			{ "define", PreProcessorDirective.Define },
+			{ "undef", PreProcessorDirective.Undef }
+		};
+
+		public override void CheckKeywordOnPush(string keyword)
+		{
+			if (keyword == "endregion")
+			{
+				DirectiveType = PreProcessorDirective.Endregion;
+				ThisLineIndent = Parent.NextLineIndent.Clone();
+			}
+		}
+
+		public override void CheckKeyword(string keyword)
+		{
+			// check if the directive type has already been set
+			if (DirectiveType != PreProcessorDirective.None)
+			{
+				return;
+			}
+
+			if (preProcessorDirectives.ContainsKey(keyword))
+			{
+				DirectiveType = preProcessorDirectives[keyword];
+
+				// adjust the indentation for the region directive
+				if (DirectiveType == PreProcessorDirective.Region)
+				{
+					ThisLineIndent = Parent.NextLineIndent.Clone();
+				}
+				else if (DirectiveType == PreProcessorDirective.If)
+				{
+					Engine.ifDirectiveIndents.Push(ThisLineIndent.Clone());
+				}
+			}
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new PreProcessorState(this, engine);
+		}
+
+		/// <summary>
+		///     Types of preprocessor directives.
+		/// </summary>
+		public enum PreProcessorDirective
+		{
+			None,
+			If,
+			Elif,
+			Else,
+			Endif,
+			Region,
+			Endregion,
+			Pragma,
+			Warning,
+			Error,
+			Line,
+			Define,
+			Undef
+		}
+
+		#region Pre processor evaluation (from cs-tokenizer.cs)
+
+		static bool is_identifier_start_character(int c)
+		{
+			return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter((char)c);
+		}
+
+		static bool is_identifier_part_character(char c)
+		{
+			if (c >= 'a' && c <= 'z')
+				return true;
+
+			if (c >= 'A' && c <= 'Z')
+				return true;
+
+			if (c == '_' || (c >= '0' && c <= '9'))
+				return true;
+
+			if (c < 0x80)
+				return false;
+
+			return Char.IsLetter(c) || Char.GetUnicodeCategory(c) == UnicodeCategory.ConnectorPunctuation;
+		}
+
+		bool eval_val(string s)
+		{
+			if (s == "true")
+				return true;
+			if (s == "false")
+				return false;
+
+			return Engine.conditionalSymbols != null && Engine.conditionalSymbols.Contains(s) ||
+				Engine.customConditionalSymbols != null && Engine.customConditionalSymbols.Contains(s);
+		}
+
+		bool pp_primary(ref string s)
+		{
+			s = s.Trim();
+			int len = s.Length;
+
+			if (len > 0)
+			{
+				char c = s[0];
+
+				if (c == '(')
+				{
+					s = s.Substring(1);
+					bool val = pp_expr(ref s, false);
+					if (s.Length > 0 && s[0] == ')')
+					{
+						s = s.Substring(1);
+						return val;
+					}
+					return false;
+				}
+
+				if (is_identifier_start_character(c))
+				{
+					int j = 1;
+
+					while (j < len)
+					{
+						c = s[j];
+
+						if (is_identifier_part_character(c))
+						{
+							j++;
+							continue;
+						}
+						bool v = eval_val(s.Substring(0, j));
+						s = s.Substring(j);
+						return v;
+					}
+					bool vv = eval_val(s);
+					s = "";
+					return vv;
+				}
+			}
+			return false;
+		}
+
+		bool pp_unary(ref string s)
+		{
+			s = s.Trim();
+			int len = s.Length;
+
+			if (len > 0)
+			{
+				if (s[0] == '!')
+				{
+					if (len > 1 && s[1] == '=')
+					{
+						return false;
+					}
+					s = s.Substring(1);
+					return !pp_primary(ref s);
+				}
+				else
+					return pp_primary(ref s);
+			}
+			else
+			{
+				return false;
+			}
+		}
+
+		bool pp_eq(ref string s)
+		{
+			bool va = pp_unary(ref s);
+
+			s = s.Trim();
+			int len = s.Length;
+			if (len > 0)
+			{
+				if (s[0] == '=')
+				{
+					if (len > 2 && s[1] == '=')
+					{
+						s = s.Substring(2);
+						return va == pp_unary(ref s);
+					}
+					else
+					{
+						return false;
+					}
+				}
+				else if (s[0] == '!' && len > 1 && s[1] == '=')
+				{
+					s = s.Substring(2);
+
+					return va != pp_unary(ref s);
+
+				}
+			}
+
+			return va;
+
+		}
+
+		bool pp_and(ref string s)
+		{
+			bool va = pp_eq(ref s);
+
+			s = s.Trim();
+			int len = s.Length;
+			if (len > 0)
+			{
+				if (s[0] == '&')
+				{
+					if (len > 2 && s[1] == '&')
+					{
+						s = s.Substring(2);
+						return (va & pp_and(ref s));
+					}
+					else
+					{
+						return false;
+					}
+				}
+			}
+			return va;
+		}
+
+		//
+		// Evaluates an expression for `#if' or `#elif'
+		//
+		bool pp_expr(ref string s, bool isTerm)
+		{
+			bool va = pp_and(ref s);
+			s = s.Trim();
+			int len = s.Length;
+			if (len > 0)
+			{
+				char c = s[0];
+
+				if (c == '|')
+				{
+					if (len > 2 && s[1] == '|')
+					{
+						s = s.Substring(2);
+						return va | pp_expr(ref s, isTerm);
+					}
+					else
+					{
+
+						return false;
+					}
+				}
+				if (isTerm)
+				{
+					return false;
+				}
+			}
+
+			return va;
+		}
+
+		bool eval(string s)
+		{
+			bool v = pp_expr(ref s, true);
+			s = s.Trim();
+			if (s.Length != 0)
+			{
+				return false;
+			}
+
+			return v;
+		}
+
+		#endregion
+	}
+
+	#endregion
+
+	#region PreProcessorComment state
+
+	/// <summary>
+	///     PreProcessor comment state.
+	/// </summary>
+	/// <remarks>
+	///     Activates when the #if or #elif directive is false and ignores
+	///     all pushed chars until the next '#'.
+	/// </remarks>
+	public class PreProcessorCommentState : IndentState
+	{
+		public PreProcessorCommentState()
+		{ }
+
+		public PreProcessorCommentState(PreProcessorCommentState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{ }
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (ch == '#' && Engine.isLineStart)
+			{
+				// TODO: Return back only on #if/#elif/#else/#endif
+				// Ignore any of the other directives (especially #define/#undef)
+				ExitState();
+				ChangeState<PreProcessorState>();
+			}
+		}
+
+		public override void InitializeState()
+		{
+			if (Engine.formattingOptions.IndentPreprocessorDirectives &&
+			    Engine.ifDirectiveIndents.Count > 0)
+			{
+				ThisLineIndent = Engine.ifDirectiveIndents.Peek().Clone();
+				NextLineIndent = ThisLineIndent.Clone();
+			}
+			else
+			{
+				ThisLineIndent = Parent.NextLineIndent.Clone();
+				NextLineIndent = ThisLineIndent.Clone();
+			}
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new PreProcessorCommentState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region LineComment state
+
+	/// <summary>
+	///     Single-line comment state.
+	/// </summary>
+	public class LineCommentState : IndentState
+	{
+		/// <summary>
+		///     It's possible that this should be the DocComment state:
+		///         check if the first next pushed char is equal to '/'.
+		/// </summary>
+		public bool CheckForDocComment = true;
+
+		public LineCommentState()
+		{
+			/*			if (engine.formattingOptions.KeepCommentsAtFirstColumn && engine.column == 2)
+				ThisLineIndent.Reset();*/
+		}
+
+		public LineCommentState(LineCommentState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			CheckForDocComment = prototype.CheckForDocComment;
+		}
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (ch == Engine.newLineChar)
+			{
+				// to handle cases like //\n/*
+				// Otherwise line 2 would be treated as line comment.
+				Engine.previousChar = '\0';
+				ExitState();
+			}
+			else if (ch == '/' && CheckForDocComment)
+			{
+				// wrong state, should be DocComment.
+				ExitState();
+				ChangeState<DocCommentState>();
+			}
+
+			CheckForDocComment = false;
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = Parent.NextLineIndent.Clone();
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new LineCommentState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region DocComment state
+
+	/// <summary>
+	///     XML documentation comment state.
+	/// </summary>
+	public class DocCommentState : IndentState
+	{
+		public DocCommentState()
+		{ }
+
+		public DocCommentState(DocCommentState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{ }
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (ch == Engine.newLineChar)
+			{
+				ExitState();
+			}
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = Parent.NextLineIndent.Clone();
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new DocCommentState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region MultiLineComment state
+
+	/// <summary>
+	///     Multi-line comment state.
+	/// </summary>
+	public class MultiLineCommentState : IndentState
+	{
+		/// <summary>
+		///     True if any char has been pushed to this state.
+		/// </summary>
+		/// <remarks>
+		///     Needed to resolve an issue when the first pushed char is '/'.
+		///     The state would falsely exit on this sequence of chars '/*/',
+		///     since it only checks if the last two chars are '/' and '*'.
+		/// </remarks>
+		public bool IsAnyCharPushed;
+
+		public MultiLineCommentState()
+		{ }
+
+		public MultiLineCommentState(MultiLineCommentState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			IsAnyCharPushed = prototype.IsAnyCharPushed;
+		}
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (ch == '/' && Engine.previousChar == '*' && IsAnyCharPushed)
+			{
+				ExitState();
+			}
+
+			IsAnyCharPushed = true;
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = ThisLineIndent.Clone();
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new MultiLineCommentState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region StringLiteral state
+
+	/// <summary>
+	///     StringLiteral state.
+	/// </summary>
+	public class StringLiteralState : IndentState
+	{
+		/// <summary>
+		///     True if the next char is escaped with '\'.
+		/// </summary>
+		public bool IsEscaped;
+
+		public StringLiteralState()
+		{ }
+
+		public StringLiteralState(StringLiteralState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			IsEscaped = prototype.IsEscaped;
+		}
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (ch == Engine.newLineChar || (!IsEscaped && ch == '"')) {
+				ExitState();
+			} else {
+				IsEscaped = ch == '\\' && !IsEscaped;
+			}
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = Parent.NextLineIndent.Clone();
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new StringLiteralState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region Verbatim string state
+
+	/// <summary>
+	///     Verbatim string state.
+	/// </summary>
+	public class VerbatimStringState : IndentState
+	{
+		/// <summary>
+		///     True if there is an odd number of '"' in a row.
+		/// </summary>
+		public bool IsEscaped;
+
+		public VerbatimStringState()
+		{ }
+
+		public VerbatimStringState(VerbatimStringState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			IsEscaped = prototype.IsEscaped;
+		}
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (IsEscaped && ch != '"')
+			{
+				ExitState();
+				// the char has been pushed to the wrong state, push it back
+				Engine.currentState.Push(ch);
+			}
+
+			IsEscaped = ch == '"' && !IsEscaped;
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = new Indent(Engine.textEditorOptions);
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new VerbatimStringState(this, engine);
+		}
+	}
+
+	#endregion
+
+	#region Character state
+
+	/// <summary>
+	///     Character state.
+	/// </summary>
+	public class CharacterState : IndentState
+	{
+		/// <summary>
+		///     True if the next char is escaped with '\'.
+		/// </summary>
+		public bool IsEscaped;
+
+		public CharacterState()
+		{ }
+
+		public CharacterState(CharacterState prototype, CSharpIndentEngine engine)
+			: base(prototype, engine)
+		{
+			IsEscaped = prototype.IsEscaped;
+		}
+
+		public override void Push(char ch)
+		{
+			base.Push(ch);
+
+			if (ch == Engine.newLineChar)
+			{
+				ExitState();
+			}
+			else if (!IsEscaped && ch == '\'')
+			{
+				ExitState();
+			}
+
+			IsEscaped = ch == '\\' && !IsEscaped;
+		}
+
+		public override void InitializeState()
+		{
+			ThisLineIndent = Parent.ThisLineIndent.Clone();
+			NextLineIndent = Parent.NextLineIndent.Clone();
+		}
+
+		public override IndentState Clone(CSharpIndentEngine engine)
+		{
+			return new CharacterState(this, engine);
+		}
+	}
+
+	#endregion
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/NullIStateMachineIndentEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/NullIStateMachineIndentEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/NullIStateMachineIndentEngine.cs	(revision 11807)
@@ -0,0 +1,215 @@
+//
+// NullIStateMachineIndentEngine.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// An empty IStateMachineIndentEngine implementation that does nothing.
+	/// </summary>
+	public sealed class NullIStateMachineIndentEngine : IStateMachineIndentEngine
+	{
+		readonly ICSharpCode.NRefactory.Editor.IDocument document;
+		int offset;
+
+		public NullIStateMachineIndentEngine(ICSharpCode.NRefactory.Editor.IDocument document)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			this.document = document;
+		}
+
+		#region IStateMachineIndentEngine implementation
+		public IStateMachineIndentEngine Clone()
+		{
+			return new NullIStateMachineIndentEngine(document) { offset = this.offset };
+		}
+
+		bool IStateMachineIndentEngine.IsInsidePreprocessorDirective {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsidePreprocessorComment {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideStringLiteral {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideVerbatimString {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideCharacter {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideString {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideLineComment {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideMultiLineComment {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideDocLineComment {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideComment {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideOrdinaryComment {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.IsInsideOrdinaryCommentOrString {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.LineBeganInsideVerbatimString {
+			get {
+				return false;
+			}
+		}
+
+		bool IStateMachineIndentEngine.LineBeganInsideMultiLineComment {
+			get {
+				return false;
+			}
+		}
+		#endregion
+
+		#region IDocumentIndentEngine implementation
+		void IDocumentIndentEngine.Push(char ch)
+		{
+			offset++;
+		}
+
+		void IDocumentIndentEngine.Reset()
+		{
+			this.offset = 0;
+		}
+
+		void IDocumentIndentEngine.Update(int offset)
+		{
+			this.offset = offset;
+		}
+
+		IDocumentIndentEngine IDocumentIndentEngine.Clone()
+		{
+			return Clone();
+		}
+
+		ICSharpCode.NRefactory.Editor.IDocument IDocumentIndentEngine.Document {
+			get {
+				return document;
+			}
+		}
+
+		string IDocumentIndentEngine.ThisLineIndent {
+			get {
+				return "";
+			}
+		}
+
+		string IDocumentIndentEngine.NextLineIndent {
+			get {
+				return "";
+			}
+		}
+
+		string IDocumentIndentEngine.CurrentIndent {
+			get {
+				return "";
+			}
+		}
+
+		bool IDocumentIndentEngine.NeedsReindent {
+			get {
+				return false;
+			}
+		}
+
+		int IDocumentIndentEngine.Offset {
+			get {
+				return offset;
+			}
+		}
+		TextLocation IDocumentIndentEngine.Location {
+			get {
+				return TextLocation.Empty;
+			}
+		}
+
+		/// <inheritdoc />
+		public bool EnableCustomIndentLevels
+		{
+			get { return false; }
+			set { }
+		}
+
+		#endregion
+
+		#region ICloneable implementation
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/TextPasteIndentEngine.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/TextPasteIndentEngine.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IndentEngine/TextPasteIndentEngine.cs	(revision 11807)
@@ -0,0 +1,632 @@
+﻿//
+// TextPasteIndentEngine.cs
+//
+// Author:
+//       Matej Miklečić <matej.miklecic@gmail.com>
+//
+// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using ICSharpCode.NRefactory.Editor;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	///     Represents a decorator of an IStateMachineIndentEngine instance
+	///     that provides logic for text paste events.
+	/// </summary>
+	public class TextPasteIndentEngine : IDocumentIndentEngine, ITextPasteHandler
+	{
+
+		#region Properties
+
+		/// <summary>
+		///     An instance of IStateMachineIndentEngine which handles
+		///     the indentation logic.
+		/// </summary>
+		IStateMachineIndentEngine engine;
+		/// <summary>
+		///     Text editor options.
+		/// </summary>
+		internal readonly TextEditorOptions textEditorOptions;
+		internal readonly CSharpFormattingOptions formattingOptions;
+		#endregion
+
+		#region Constructors
+
+		/// <summary>
+		///     Creates a new TextPasteIndentEngine instance.
+		/// </summary>
+		/// <param name="decoratedEngine">
+		///     An instance of <see cref="IStateMachineIndentEngine"/> to which the
+		///     logic for indentation will be delegated.
+		/// </param>
+		/// <param name="textEditorOptions">
+		///    Text editor options for indentation.
+		/// </param>
+		/// <param name="formattingOptions">
+		///     C# formatting options.
+		/// </param>
+		public TextPasteIndentEngine(IStateMachineIndentEngine decoratedEngine, TextEditorOptions textEditorOptions, CSharpFormattingOptions formattingOptions)
+		{
+			this.engine = decoratedEngine;
+			this.textEditorOptions = textEditorOptions;
+			this.formattingOptions = formattingOptions;
+
+			this.engine.EnableCustomIndentLevels = false;
+		}
+
+		#endregion
+
+		#region ITextPasteHandler
+
+		/// <inheritdoc />
+		string ITextPasteHandler.FormatPlainText(int offset, string text, byte[] copyData)
+		{
+			if (copyData != null && copyData.Length == 1) {
+				var strategy = TextPasteUtils.Strategies [(PasteStrategy)copyData [0]];
+				text = strategy.Decode(text);
+			}
+			engine.Update(offset);
+			if (engine.IsInsideStringLiteral) {
+				int idx = text.IndexOf('"');
+				if (idx > 0) {
+					var o = offset;
+					while (o < engine.Document.TextLength) {
+						char ch = engine.Document.GetCharAt(o);
+						engine.Push(ch); 
+						if (NewLine.IsNewLine(ch))
+							break;
+						o++;
+						if (!engine.IsInsideStringLiteral)
+							return TextPasteUtils.StringLiteralStrategy.Encode(text);
+					}
+					return TextPasteUtils.StringLiteralStrategy.Encode(text.Substring(0, idx)) + text.Substring(idx);
+				}
+				return TextPasteUtils.StringLiteralStrategy.Encode(text);
+
+			} else if (engine.IsInsideVerbatimString) {
+
+				int idx = text.IndexOf('"');
+				if (idx > 0) {
+					var o = offset;
+					while (o < engine.Document.TextLength) {
+						char ch = engine.Document.GetCharAt(o);
+						engine.Push(ch); 
+						o++;
+						if (!engine.IsInsideVerbatimString)
+							return TextPasteUtils.VerbatimStringStrategy.Encode(text);
+					}
+					return TextPasteUtils.VerbatimStringStrategy.Encode(text.Substring(0, idx)) + text.Substring(idx);
+				}
+
+				return TextPasteUtils.VerbatimStringStrategy.Encode(text);
+			}
+			var line = engine.Document.GetLineByOffset(offset);
+			var pasteAtLineStart = line.Offset == offset;
+			var indentedText = new StringBuilder();
+			var curLine = new StringBuilder();
+			var clonedEngine = engine.Clone();
+			bool isNewLine = false, gotNewLine = false;
+			for (int i = 0; i < text.Length; i++) {
+				var ch = text [i];
+				if (clonedEngine.IsInsideVerbatimString || clonedEngine.IsInsideMultiLineComment) {
+					clonedEngine.Push(ch);
+					curLine.Append(ch);
+					continue;
+				}
+
+				var delimiterLength = NewLine.GetDelimiterLength(ch, i + 1 < text.Length ? text[i + 1] : ' ');
+				if (delimiterLength > 0) {
+					isNewLine = true;
+					if (gotNewLine || pasteAtLineStart) {
+						if (curLine.Length > 0 || formattingOptions.EmptyLineFormatting == EmptyLineFormatting.Indent)
+							indentedText.Append(clonedEngine.ThisLineIndent);
+					}
+					indentedText.Append(curLine);
+					indentedText.Append(textEditorOptions.EolMarker);
+					curLine.Length = 0;
+					gotNewLine = true;
+					i += delimiterLength - 1;
+					// textEditorOptions.EolMarker[0] is the newLineChar used by the indentation engine.
+					clonedEngine.Push(textEditorOptions.EolMarker[0]);
+				} else {
+					if (isNewLine) {
+						if (ch == '\t' || ch == ' ') {
+							clonedEngine.Push(ch);
+							continue;
+						}
+						isNewLine = false;
+					}
+					curLine.Append(ch);
+					clonedEngine.Push(ch);
+				}
+				if (clonedEngine.IsInsideVerbatimString || clonedEngine.IsInsideMultiLineComment && 
+				    !(clonedEngine.LineBeganInsideVerbatimString || clonedEngine.LineBeganInsideMultiLineComment)) {
+					if (gotNewLine) {
+						if (curLine.Length > 0 || formattingOptions.EmptyLineFormatting == EmptyLineFormatting.Indent)
+							indentedText.Append(clonedEngine.ThisLineIndent);
+					}
+					pasteAtLineStart = false;
+					indentedText.Append(curLine);
+					curLine.Length = 0;
+					gotNewLine = false;
+					continue;
+				}
+			}
+			if (gotNewLine && (!pasteAtLineStart || curLine.Length > 0)) {
+				indentedText.Append(clonedEngine.ThisLineIndent);
+			}
+			if (curLine.Length > 0) {
+				indentedText.Append(curLine);
+			}
+			return indentedText.ToString();
+		}
+
+		/// <inheritdoc />
+		byte[] ITextPasteHandler.GetCopyData(ISegment segment)
+		{
+			engine.Update(segment.Offset);
+			
+			if (engine.IsInsideStringLiteral) {
+				return new[] { (byte)PasteStrategy.StringLiteral };
+			} else if (engine.IsInsideVerbatimString) {
+				return new[] { (byte)PasteStrategy.VerbatimString };
+			}
+			
+			return null;
+		}
+
+		#endregion
+
+		#region IDocumentIndentEngine
+
+		/// <inheritdoc />
+		public IDocument Document {
+			get { return engine.Document; }
+		}
+
+		/// <inheritdoc />
+		public string ThisLineIndent {
+			get { return engine.ThisLineIndent; }
+		}
+
+		/// <inheritdoc />
+		public string NextLineIndent {
+			get { return engine.NextLineIndent; }
+		}
+
+		/// <inheritdoc />
+		public string CurrentIndent {
+			get { return engine.CurrentIndent; }
+		}
+
+		/// <inheritdoc />
+		public bool NeedsReindent {
+			get { return engine.NeedsReindent; }
+		}
+
+		/// <inheritdoc />
+		public int Offset {
+			get { return engine.Offset; }
+		}
+
+		/// <inheritdoc />
+		public TextLocation Location {
+			get { return engine.Location; }
+		}
+
+		/// <inheritdoc />
+		public bool EnableCustomIndentLevels {
+			get { return engine.EnableCustomIndentLevels; }
+			set { engine.EnableCustomIndentLevels = value; }
+		}
+		
+		/// <inheritdoc />
+		public void Push(char ch)
+		{
+			engine.Push(ch);
+		}
+
+		/// <inheritdoc />
+		public void Reset()
+		{
+			engine.Reset();
+		}
+
+		/// <inheritdoc />
+		public void Update(int offset)
+		{
+			engine.Update(offset);
+		}
+
+		#endregion
+
+		#region IClonable
+
+		public IDocumentIndentEngine Clone()
+		{
+			return new TextPasteIndentEngine(engine, textEditorOptions, formattingOptions);
+		}
+
+		object ICloneable.Clone()
+		{
+			return Clone();
+		}
+
+		#endregion
+
+	}
+
+	/// <summary>
+	///     Types of text-paste strategies.
+	/// </summary>
+	public enum PasteStrategy : byte
+	{
+		PlainText = 0,
+		StringLiteral = 1,
+		VerbatimString = 2
+	}
+
+	/// <summary>
+	///     Defines some helper methods for dealing with text-paste events.
+	/// </summary>
+	public static class TextPasteUtils
+	{
+		/// <summary>
+		///     Collection of text-paste strategies.
+		/// </summary>
+		public static TextPasteStrategies Strategies = new TextPasteStrategies();
+
+		/// <summary>
+		///     The interface for a text-paste strategy.
+		/// </summary>
+		public interface IPasteStrategy
+		{
+			/// <summary>
+			///     Formats the given text according with this strategy rules.
+			/// </summary>
+			/// <param name="text">
+			///    The text to format.
+			/// </param>
+			/// <returns>
+			///     Formatted text.
+			/// </returns>
+			string Encode(string text);
+
+			/// <summary>
+			///     Converts text formatted according with this strategy rules
+			///     to its original form.
+			/// </summary>
+			/// <param name="text">
+			///     Formatted text to convert.
+			/// </param>
+			/// <returns>
+			///     Original form of the given formatted text.
+			/// </returns>
+			string Decode(string text);
+
+			/// <summary>
+			///     Type of this strategy.
+			/// </summary>
+			PasteStrategy Type { get; }
+		}
+
+		/// <summary>
+		///     Wrapper that discovers all defined text-paste strategies and defines a way
+		///     to easily access them through their <see cref="PasteStrategy"/> type.
+		/// </summary>
+		public sealed class TextPasteStrategies
+		{
+			/// <summary>
+			///     Collection of discovered text-paste strategies.
+			/// </summary>
+			IDictionary<PasteStrategy, IPasteStrategy> strategies;
+
+			/// <summary>
+			///     Uses reflection to find all types derived from <see cref="IPasteStrategy"/>
+			///     and adds an instance of each strategy to <see cref="strategies"/>.
+			/// </summary>
+			public TextPasteStrategies()
+			{
+				strategies = Assembly.GetExecutingAssembly()
+				     .GetTypes()
+				.Where(t => typeof(IPasteStrategy).IsAssignableFrom(t) && t.IsClass)
+				.Select(t => (IPasteStrategy)t.GetProperty("Instance").GetValue(null, null))
+				.ToDictionary(s => s.Type);
+			}
+
+			/// <summary>
+			///     Checks if there is a strategy of the given type and returns it.
+			/// </summary>
+			/// <param name="strategy">
+			///     Type of the strategy instance.
+			/// </param>
+			/// <returns>
+			///     A strategy instance of the requested type,
+			///     or <see cref="DefaultStrategy"/> if it wasn't found.
+			/// </returns>
+			public IPasteStrategy this [PasteStrategy strategy] {
+				get {
+					if (strategies.ContainsKey(strategy)) {
+						return strategies [strategy];
+					}
+					
+					return DefaultStrategy;
+				}
+			}
+		}
+
+		/// <summary>
+		///     Doesn't do any formatting. Serves as the default strategy.
+		/// </summary>
+		public class PlainTextPasteStrategy : IPasteStrategy
+		{
+
+			#region Singleton
+
+			public static IPasteStrategy Instance {
+				get {
+					return instance ?? (instance = new PlainTextPasteStrategy());
+				}
+			}
+
+			static PlainTextPasteStrategy instance;
+
+			protected PlainTextPasteStrategy()
+			{
+			}
+
+			#endregion
+
+			/// <inheritdoc />
+			public string Encode(string text)
+			{
+				return text;
+			}
+
+			/// <inheritdoc />
+			public string Decode(string text)
+			{
+				return text;
+			}
+
+			/// <inheritdoc />
+			public PasteStrategy Type {
+				get { return PasteStrategy.PlainText; }
+			}
+		}
+
+		/// <summary>
+		///     Escapes chars in the given text so that they don't
+		///     break a valid string literal.
+		/// </summary>
+		public class StringLiteralPasteStrategy : IPasteStrategy
+		{
+
+			#region Singleton
+
+			public static IPasteStrategy Instance {
+				get {
+					return instance ?? (instance = new StringLiteralPasteStrategy());
+				}
+			}
+
+			static StringLiteralPasteStrategy instance;
+
+			protected StringLiteralPasteStrategy()
+			{
+			}
+
+			#endregion
+
+			/// <inheritdoc />
+			public string Encode(string text)
+			{
+				return CSharpOutputVisitor.ConvertString(text);
+			}
+
+			/// <inheritdoc />
+			public string Decode(string text)
+			{
+				var result = new StringBuilder();
+				bool isEscaped = false;
+
+				for (int i = 0; i < text.Length; i++) {
+					var ch = text[i];
+					if (isEscaped) {
+						switch (ch) {
+							case 'a':
+								result.Append('\a');
+								break;
+							case 'b':
+								result.Append('\b');
+								break;
+							case 'n':
+								result.Append('\n');
+								break;
+							case 't':
+								result.Append('\t');
+								break;
+							case 'v':
+								result.Append('\v');
+								break;
+							case 'r':
+								result.Append('\r');
+								break;
+							case '\\':
+								result.Append('\\');
+								break;
+							case 'f':
+								result.Append('\f');
+								break;
+							case '0':
+								result.Append(0);
+								break;
+							case '"':
+								result.Append('"');
+								break;
+							case '\'':
+								result.Append('\'');
+								break;
+							case 'x':
+								char r;
+								if (TryGetHex(text, -1, ref i, out r)) {
+									result.Append(r);
+									break;
+								}
+								goto default;
+							case 'u':
+								if (TryGetHex(text, 4, ref i, out r)) {
+									result.Append(r);
+									break;
+								}
+								goto default;
+							case 'U':
+								if (TryGetHex(text, 8, ref i, out r)) {
+									result.Append(r);
+									break;
+								}
+								goto default;
+							default:
+								result.Append('\\');
+								result.Append(ch);
+								break;
+						}
+						isEscaped = false;
+						continue;
+					}
+					if (ch != '\\') {
+						result.Append(ch);
+					}
+					else {
+						isEscaped = true;
+					}
+				}
+
+				return result.ToString();
+			}
+
+			static bool TryGetHex(string text, int count, ref int idx, out char r)
+			{
+				int i;
+				int total = 0;
+				int top = count != -1 ? count : 4;
+
+				for (i = 0; i < top; i++) {
+					int c = text[idx + 1 + i];
+
+					if (c >= '0' && c <= '9')
+						c = (int) c - (int) '0';
+					else if (c >= 'A' && c <= 'F')
+						c = (int) c - (int) 'A' + 10;
+					else if (c >= 'a' && c <= 'f')
+						c = (int) c - (int) 'a' + 10;
+					else {
+						r = '\0';
+						return false;
+					}
+					total = (total * 16) + c;
+				}
+
+				if (top == 8) {
+					if (total > 0x0010FFFF) {
+						r = '\0';
+						return false;
+					}
+
+					if (total >= 0x00010000)
+						total = ((total - 0x00010000) / 0x0400 + 0xD800);
+				}
+				r = (char)total;
+				idx += top;
+				return true;
+			}
+
+			/// <inheritdoc />
+			public PasteStrategy Type {
+				get { return PasteStrategy.StringLiteral; }
+			}
+		}
+
+		/// <summary>
+		///     Escapes chars in the given text so that they don't
+		///     break a valid verbatim string.
+		/// </summary>
+		public class VerbatimStringPasteStrategy : IPasteStrategy
+		{
+
+			#region Singleton
+
+			public static IPasteStrategy Instance {
+				get {
+					return instance ?? (instance = new VerbatimStringPasteStrategy());
+				}
+			}
+
+			static VerbatimStringPasteStrategy instance;
+
+			protected VerbatimStringPasteStrategy()
+			{
+			}
+
+			#endregion
+
+			static readonly Dictionary<char, IEnumerable<char>> encodeReplace = new Dictionary<char, IEnumerable<char>> {
+				{ '\"', "\"\"" },
+			};
+
+			/// <inheritdoc />
+			public string Encode(string text)
+			{
+				return string.Concat(text.SelectMany(c => encodeReplace.ContainsKey(c) ? encodeReplace [c] : new[] { c }));
+			}
+
+			/// <inheritdoc />
+			public string Decode(string text)
+			{
+				bool isEscaped = false;
+				return string.Concat(text.Where(c => !(isEscaped = !isEscaped && c == '"')));
+			}
+
+			/// <inheritdoc />
+			public PasteStrategy Type {
+				get { return PasteStrategy.VerbatimString; }
+			}
+		}
+
+		/// <summary>
+		///     The default text-paste strategy.
+		/// </summary>
+		public static IPasteStrategy DefaultStrategy = PlainTextPasteStrategy.Instance;
+		/// <summary>
+		///     String literal text-paste strategy.
+		/// </summary>
+		public static IPasteStrategy StringLiteralStrategy = StringLiteralPasteStrategy.Instance;
+		/// <summary>
+		///     Verbatim string text-paste strategy.
+		/// </summary>
+		public static IPasteStrategy VerbatimStringStrategy = VerbatimStringPasteStrategy.Instance;
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IntroduceQueryExpressions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IntroduceQueryExpressions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/IntroduceQueryExpressions.cs	(revision 11807)
@@ -0,0 +1,386 @@
+//
+// IntroduceQueryExpressions.cs
+//
+// Modified by LuÃ­s Reis <luiscubal@gmail.com> (Copyright (C) 2013)
+//
+// Copyright header of the original version follows:
+//
+// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.PatternMatching;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	static class NRefactoryExtensions
+	{
+		public static T Detach<T>(this T node) where T : AstNode
+		{
+			node.Remove();
+			return node;
+		}
+
+		public static T CopyAnnotationsFrom<T>(this T node, AstNode other) where T : AstNode
+		{
+			foreach (object annotation in other.Annotations) {
+				node.AddAnnotation(annotation);
+			}
+			return node;
+		}
+
+		public static Expression WithName(this Expression node, string patternGroupName)
+		{
+			return new NamedNode(patternGroupName, node);
+		}
+	}
+
+	/// <summary>
+	/// Decompiles query expressions.
+	/// Based on C# 4.0 spec, Â§7.16.2 Query expression translation
+	/// </summary>
+	public class IntroduceQueryExpressions
+	{
+		static readonly InvocationExpression castPattern = new InvocationExpression {
+			Target = new MemberReferenceExpression {
+				Target = new AnyNode("inExpr"),
+				MemberName = "Cast",
+				TypeArguments = { new AnyNode("targetType") }
+			}};
+
+		public Expression ConvertFluentToQuery(Expression node)
+		{
+			node = node.Clone();
+
+			var artificialParent = new ExpressionStatement();
+			artificialParent.Expression = node;
+
+			DecompileQueries(node);
+			// After all queries were decompiled, detect degenerate queries (queries not property terminated with 'select' or 'group')
+			// and fix them, either by adding a degenerate select, or by combining them with another query.
+			foreach (QueryExpression query in artificialParent.Descendants.OfType<QueryExpression>()) {
+				QueryFromClause fromClause = (QueryFromClause)query.Clauses.First();
+				if (IsDegenerateQuery(query)) {
+					string identifierName = fromClause.Identifier;
+
+					// introduce select for degenerate query
+					query.Clauses.Add(new QuerySelectClause { Expression = new IdentifierExpression(identifierName) });
+				}
+
+				if (fromClause.Type.IsNull) {
+					// See if the data source of this query is a degenerate query,
+					// and combine the queries if possible.
+					QueryExpression innerQuery = fromClause.Expression as QueryExpression;
+					while (IsDegenerateQuery(innerQuery)) {
+						QueryFromClause innerFromClause = (QueryFromClause)innerQuery.Clauses.First();
+						if (fromClause.Identifier != innerFromClause.Identifier && !innerFromClause.Identifier.StartsWith("<>"))
+							break;
+						// Replace the fromClause with all clauses from the inner query
+						fromClause.Remove();
+						foreach (var identifierChild in innerQuery.Descendants.OfType<Identifier>().Where(identifier => identifier.Name == innerFromClause.Identifier)) {
+							//When the identifier is "<>X", then replace it with the outer one
+							identifierChild.ReplaceWith(fromClause.IdentifierToken.Clone());
+						}
+						QueryClause insertionPos = null;
+						foreach (var clause in innerQuery.Clauses) {
+							query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach());
+						}
+						fromClause = innerFromClause;
+						innerQuery = fromClause.Expression as QueryExpression;
+					}
+				}
+			}
+
+			return artificialParent.Expression.Clone();
+		}
+
+		bool IsDegenerateQuery(QueryExpression query)
+		{
+			if (query == null)
+				return false;
+			var lastClause = query.Clauses.LastOrDefault();
+			return !(lastClause is QuerySelectClause || lastClause is QueryGroupClause);
+		}
+
+		void DecompileQueries(AstNode node)
+		{
+			QueryExpression query = DecompileQuery(node as InvocationExpression);
+			if (query != null)
+				node.ReplaceWith(query);
+		}
+
+		Expression ExtractQuery(MemberReferenceExpression mre)
+		{
+			var inExpression = mre.Target.Clone();
+			var inContent = DecompileQuery(inExpression as InvocationExpression) ?? inExpression;
+			return inContent;
+		}
+
+		QueryExpression DecompileQuery(InvocationExpression invocation)
+		{
+			if (invocation == null)
+				return null;
+			MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression;
+			if (mre == null)
+				return null;
+
+			switch (mre.MemberName) {
+				case "Select":
+					{
+						if (invocation.Arguments.Count != 1)
+							return null;
+						string parameterName;
+						Expression body;
+						if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) {
+							QueryExpression query = new QueryExpression();
+							query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = ExtractQuery(mre) });
+							query.Clauses.Add(new QuerySelectClause { Expression = body.Detach() });
+							return query;
+						}
+						return null;
+					}
+				case "Cast":
+					{
+						if (invocation.Arguments.Count == 0 && mre.TypeArguments.Count == 1) {
+							var typeArgument = mre.TypeArguments.First();
+
+							QueryExpression query = new QueryExpression();
+							string varName = GenerateVariableName();
+							query.Clauses.Add(new QueryFromClause {
+								Identifier = varName,
+								Expression = ExtractQuery(mre),
+								Type = typeArgument.Detach()
+							});
+							return query;
+
+						}
+						return null;
+					}
+				case "GroupBy":
+					{
+						if (invocation.Arguments.Count == 2) {
+							string parameterName1, parameterName2;
+							Expression keySelector, elementSelector;
+							if (MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameterName1, out keySelector)
+								&& MatchSimpleLambda(invocation.Arguments.ElementAt(1), out parameterName2, out elementSelector)
+								&& parameterName1 == parameterName2) {
+								QueryExpression query = new QueryExpression();
+								query.Clauses.Add(new QueryFromClause { Identifier = parameterName1, Expression = ExtractQuery(mre) });
+								query.Clauses.Add(new QueryGroupClause { Projection = elementSelector.Detach(), Key = keySelector.Detach() });
+								return query;
+							}
+						} else if (invocation.Arguments.Count == 1) {
+							string parameterName;
+							Expression keySelector;
+							if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out keySelector)) {
+								QueryExpression query = new QueryExpression();
+								query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = ExtractQuery(mre) });
+								query.Clauses.Add(new QueryGroupClause {
+									Projection = new IdentifierExpression(parameterName),
+									Key = keySelector.Detach()
+								});
+								return query;
+							}
+						}
+						return null;
+					}
+				case "SelectMany":
+					{
+						if (invocation.Arguments.Count != 2)
+							return null;
+						string parameterName;
+						Expression collectionSelector;
+						if (!MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameterName, out collectionSelector))
+							return null;
+						LambdaExpression lambda = invocation.Arguments.ElementAt(1) as LambdaExpression;
+						if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) {
+							ParameterDeclaration p1 = lambda.Parameters.ElementAt(0);
+							ParameterDeclaration p2 = lambda.Parameters.ElementAt(1);
+							QueryExpression query = new QueryExpression();
+							query.Clauses.Add(new QueryFromClause { Identifier = p1.Name, Expression = ExtractQuery(mre) });
+							query.Clauses.Add(new QueryFromClause { Identifier = p2.Name, Expression = collectionSelector.Detach() });
+							query.Clauses.Add(new QuerySelectClause { Expression = ((Expression)lambda.Body).Detach() });
+							return query;
+						}
+						return null;
+					}
+				case "Where":
+					{
+						if (invocation.Arguments.Count != 1)
+							return null;
+						string parameterName;
+						Expression body;
+						if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) {
+							QueryExpression query = new QueryExpression();
+							query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = ExtractQuery(mre) });
+							query.Clauses.Add(new QueryWhereClause { Condition = body.Detach() });
+							return query;
+						}
+						return null;
+					}
+				case "OrderBy":
+				case "OrderByDescending":
+				case "ThenBy":
+				case "ThenByDescending":
+					{
+						if (invocation.Arguments.Count != 1)
+							return null;
+						string parameterName;
+						Expression orderExpression;
+						if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out orderExpression)) {
+							if (ValidateThenByChain(invocation, parameterName)) {
+								QueryOrderClause orderClause = new QueryOrderClause();
+								InvocationExpression tmp = invocation;
+								while (mre.MemberName == "ThenBy" || mre.MemberName == "ThenByDescending") {
+									// insert new ordering at beginning
+									orderClause.Orderings.InsertAfter(
+										null, new QueryOrdering {
+										Expression = orderExpression.Detach(),
+										Direction = (mre.MemberName == "ThenBy" ? QueryOrderingDirection.None : QueryOrderingDirection.Descending)
+									});
+
+									tmp = (InvocationExpression)mre.Target;
+									mre = (MemberReferenceExpression)tmp.Target;
+									MatchSimpleLambda(tmp.Arguments.Single(), out parameterName, out orderExpression);
+								}
+								// insert new ordering at beginning
+								orderClause.Orderings.InsertAfter(
+									null, new QueryOrdering {
+									Expression = orderExpression.Detach(),
+									Direction = (mre.MemberName == "OrderBy" ? QueryOrderingDirection.None : QueryOrderingDirection.Descending)
+								});
+
+								QueryExpression query = new QueryExpression();
+								query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = ExtractQuery(mre) });
+								query.Clauses.Add(orderClause);
+								return query;
+							}
+						}
+						return null;
+					}
+				case "Join":
+				case "GroupJoin":
+					{
+						if (invocation.Arguments.Count != 4)
+							return null;
+						Expression source1 = mre.Target;
+						Expression source2 = invocation.Arguments.ElementAt(0);
+						string elementName1, elementName2;
+						Expression key1, key2;
+						if (!MatchSimpleLambda(invocation.Arguments.ElementAt(1), out elementName1, out key1))
+							return null;
+						if (!MatchSimpleLambda(invocation.Arguments.ElementAt(2), out elementName2, out key2))
+							return null;
+						LambdaExpression lambda = invocation.Arguments.ElementAt(3) as LambdaExpression;
+						if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) {
+							ParameterDeclaration p1 = lambda.Parameters.ElementAt(0);
+							ParameterDeclaration p2 = lambda.Parameters.ElementAt(1);
+							QueryExpression query = new QueryExpression();
+							query.Clauses.Add(new QueryFromClause { Identifier = elementName1, Expression = source1.Detach() });
+							QueryJoinClause joinClause = new QueryJoinClause();
+							
+							joinClause.JoinIdentifier = elementName2;    // join elementName2
+							joinClause.InExpression = source2.Detach();  // in source2
+
+							Match castMatch = castPattern.Match(source2);
+							if (castMatch.Success) {
+								Expression target = castMatch.Get<Expression>("inExpr").Single().Detach();
+								joinClause.Type = castMatch.Get<AstType>("targetType").Single().Detach();
+								joinClause.InExpression = target;
+							}
+							
+							joinClause.OnExpression = key1.Detach();     // on key1
+							joinClause.EqualsExpression = key2.Detach(); // equals key2
+							if (mre.MemberName == "GroupJoin") {
+								joinClause.IntoIdentifier = p2.Name; // into p2.Name
+							}
+							query.Clauses.Add(joinClause);
+							Expression resultExpr = ((Expression)lambda.Body).Detach();
+							if (p1.Name != elementName1) {
+								foreach (var identifier in resultExpr.Descendants.OfType<Identifier>().Where(id => id.Name == p1.Name))
+								{
+									identifier.Name = elementName1;
+								}
+							}
+							if (p2.Name != elementName2 && mre.MemberName != "GroupJoin") {
+								foreach (var identifier in resultExpr.Descendants.OfType<Identifier>().Where(id => id.Name == p2.Name))
+								{
+									identifier.Name = elementName2;
+								}
+							}
+							query.Clauses.Add(new QuerySelectClause { Expression = resultExpr });
+							return query;
+						}
+						return null;
+					}
+				default:
+					return null;
+			}
+		}
+
+		int id = 1;
+		string GenerateVariableName()
+		{
+			return "<>" + id++;
+		}
+
+		/// <summary>
+		/// Ensure that all ThenBy's are correct, and that the list of ThenBy's is terminated by an 'OrderBy' invocation.
+		/// </summary>
+		bool ValidateThenByChain(InvocationExpression invocation, string expectedParameterName)
+		{
+			if (invocation == null || invocation.Arguments.Count != 1)
+				return false;
+			MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression;
+			if (mre == null)
+				return false;
+			string parameterName;
+			Expression body;
+			if (!MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body))
+				return false;
+			if (parameterName != expectedParameterName)
+				return false;
+
+			if (mre.MemberName == "OrderBy" || mre.MemberName == "OrderByDescending")
+				return true;
+			else if (mre.MemberName == "ThenBy" || mre.MemberName == "ThenByDescending")
+				return ValidateThenByChain(mre.Target as InvocationExpression, expectedParameterName);
+			else
+				return false;
+		}
+
+		/// <summary>Matches simple lambdas of the form "a => b"</summary>
+		bool MatchSimpleLambda(Expression expr, out string parameterName, out Expression body)
+		{
+			LambdaExpression lambda = expr as LambdaExpression;
+			if (lambda != null && lambda.Parameters.Count == 1 && lambda.Body is Expression) {
+				ParameterDeclaration p = lambda.Parameters.Single();
+				if (p.ParameterModifier == ParameterModifier.None) {
+					parameterName = p.Name;
+					body = (Expression)lambda.Body;
+					return true;
+				}
+			}
+			parameterName = null;
+			body = null;
+			return false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/NameLookupMode.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/NameLookupMode.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/NameLookupMode.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public enum NameLookupMode
+	{
+		/// <summary>
+		/// Normal name lookup in expressions
+		/// </summary>
+		Expression,
+		/// <summary>
+		/// Name lookup in expression, where the expression is the target of an invocation.
+		/// Such a lookup will only return methods and delegate-typed fields.
+		/// </summary>
+		InvocationTarget,
+		/// <summary>
+		/// Normal name lookup in type references.
+		/// </summary>
+		Type,
+		/// <summary>
+		/// Name lookup in the type reference inside a using declaration.
+		/// </summary>
+		TypeInUsingDeclaration,
+		/// <summary>
+		/// Name lookup for base type references.
+		/// </summary>
+		BaseTypeReference
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CSharpAmbience.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CSharpAmbience.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CSharpAmbience.cs	(revision 11807)
@@ -0,0 +1,312 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// C# ambience. Used to convert type system symbols to text (usually for displaying the symbol to the user; e.g. in editor tooltips)
+	/// </summary>
+	public class CSharpAmbience : IAmbience
+	{
+		public ConversionFlags ConversionFlags { get; set; }
+		
+		#region ConvertSymbol
+		[Obsolete("Use ConvertSymbol() instead")]
+		public string ConvertEntity(IEntity entity)
+		{
+			return ConvertSymbol(entity);
+		}
+		
+		public string ConvertSymbol(ISymbol symbol)
+		{
+			if (symbol == null)
+				throw new ArgumentNullException("symbol");
+			
+			StringWriter writer = new StringWriter();
+			ConvertSymbol(symbol, new TextWriterTokenWriter(writer), FormattingOptionsFactory.CreateMono ());
+			return writer.ToString();
+		}
+		
+		[Obsolete("Use ConvertSymbol() instead")]
+		public void ConvertEntity(IEntity entity, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			ConvertSymbol(entity, writer, formattingPolicy);
+		}
+		
+		public void ConvertSymbol(ISymbol symbol, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			if (symbol == null)
+				throw new ArgumentNullException("symbol");
+			if (writer == null)
+				throw new ArgumentNullException("writer");
+			if (formattingPolicy == null)
+				throw new ArgumentNullException("formattingPolicy");
+			
+			TypeSystemAstBuilder astBuilder = CreateAstBuilder();
+			AstNode node = astBuilder.ConvertSymbol(symbol);
+			EntityDeclaration entityDecl = node as EntityDeclaration;
+			if (entityDecl != null)
+				PrintModifiers(entityDecl.Modifiers, writer);
+			
+			if ((ConversionFlags & ConversionFlags.ShowDefinitionKeyword) == ConversionFlags.ShowDefinitionKeyword) {
+				if (node is TypeDeclaration) {
+					switch (((TypeDeclaration)node).ClassType) {
+						case ClassType.Class:
+							writer.WriteKeyword(Roles.ClassKeyword, "class");
+							break;
+						case ClassType.Struct:
+							writer.WriteKeyword(Roles.StructKeyword, "struct");
+							break;
+						case ClassType.Interface:
+							writer.WriteKeyword(Roles.InterfaceKeyword, "interface");
+							break;
+						case ClassType.Enum:
+							writer.WriteKeyword(Roles.EnumKeyword, "enum");
+							break;
+						default:
+							throw new Exception("Invalid value for ClassType");
+					}
+					writer.Space();
+				} else if (node is DelegateDeclaration) {
+					writer.WriteKeyword(Roles.DelegateKeyword, "delegate");
+					writer.Space();
+				} else if (node is EventDeclaration) {
+					writer.WriteKeyword(EventDeclaration.EventKeywordRole, "event");
+					writer.Space();
+				} else if (node is NamespaceDeclaration) {
+					writer.WriteKeyword(Roles.NamespaceKeyword, "namespace");
+					writer.Space();
+				}
+			}
+			
+			if ((ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) {
+				var rt = node.GetChildByRole(Roles.Type);
+				if (!rt.IsNull) {
+					rt.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
+					writer.Space();
+				}
+			}
+			
+			if (symbol is ITypeDefinition)
+				WriteTypeDeclarationName((ITypeDefinition)symbol, writer, formattingPolicy);
+			else if (symbol is IMember)
+				WriteMemberDeclarationName((IMember)symbol, writer, formattingPolicy);
+			else
+				writer.WriteIdentifier(Identifier.Create(symbol.Name));
+			
+			if ((ConversionFlags & ConversionFlags.ShowParameterList) == ConversionFlags.ShowParameterList && HasParameters(symbol)) {
+				writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.LBracket : Roles.LPar, symbol.SymbolKind == SymbolKind.Indexer ? "[" : "(");
+				bool first = true;
+				foreach (var param in node.GetChildrenByRole(Roles.Parameter)) {
+					if (first) {
+						first = false;
+					} else {
+						writer.WriteToken(Roles.Comma, ",");
+						writer.Space();
+					}
+					param.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
+				}
+				writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.RBracket : Roles.RPar, symbol.SymbolKind == SymbolKind.Indexer ? "]" : ")");
+			}
+			
+			if ((ConversionFlags & ConversionFlags.ShowBody) == ConversionFlags.ShowBody && !(node is TypeDeclaration)) {
+				IProperty property = symbol as IProperty;
+				if (property != null) {
+					writer.Space();
+					writer.WriteToken(Roles.LBrace, "{");
+					writer.Space();
+					if (property.CanGet) {
+						writer.WriteKeyword(PropertyDeclaration.GetKeywordRole, "get");
+						writer.WriteToken(Roles.Semicolon, ";");
+						writer.Space();
+					}
+					if (property.CanSet) {
+						writer.WriteKeyword(PropertyDeclaration.SetKeywordRole, "set");
+						writer.WriteToken(Roles.Semicolon, ";");
+						writer.Space();
+					}
+					writer.WriteToken(Roles.RBrace, "}");
+				} else {
+					writer.WriteToken(Roles.Semicolon, ";");
+				}
+			}
+		}
+		
+		static bool HasParameters(ISymbol e)
+		{
+			switch (e.SymbolKind) {
+				case SymbolKind.TypeDefinition:
+					return ((ITypeDefinition)e).Kind == TypeKind.Delegate;
+				case SymbolKind.Indexer:
+				case SymbolKind.Method:
+				case SymbolKind.Operator:
+				case SymbolKind.Constructor:
+				case SymbolKind.Destructor:
+					return true;
+				default:
+					return false;
+			}
+		}
+		
+		TypeSystemAstBuilder CreateAstBuilder()
+		{
+			TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder();
+			astBuilder.AddAnnotations = true;
+			astBuilder.ShowModifiers = (ConversionFlags & ConversionFlags.ShowModifiers) == ConversionFlags.ShowModifiers;
+			astBuilder.ShowAccessibility = (ConversionFlags & ConversionFlags.ShowAccessibility) == ConversionFlags.ShowAccessibility;
+			astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedTypeNames) != ConversionFlags.UseFullyQualifiedTypeNames;
+			astBuilder.ShowParameterNames = (ConversionFlags & ConversionFlags.ShowParameterNames) == ConversionFlags.ShowParameterNames;
+			return astBuilder;
+		}
+		
+		void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			TypeSystemAstBuilder astBuilder = CreateAstBuilder();
+			EntityDeclaration node = astBuilder.ConvertEntity(typeDef);
+			if (typeDef.DeclaringTypeDefinition != null) {
+				WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, writer, formattingPolicy);
+				writer.WriteToken(Roles.Dot, ".");
+			} else if ((ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) == ConversionFlags.UseFullyQualifiedEntityNames) {
+				if (!string.IsNullOrEmpty(typeDef.Namespace)) {
+					WriteQualifiedName(typeDef.Namespace, writer, formattingPolicy);
+					writer.WriteToken(Roles.Dot, ".");
+				}
+			}
+			writer.WriteIdentifier(node.NameToken);
+			if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList) {
+				var outputVisitor = new CSharpOutputVisitor(writer, formattingPolicy);
+				outputVisitor.WriteTypeParameters(node.GetChildrenByRole(Roles.TypeParameter));
+			}
+		}
+		
+		void WriteMemberDeclarationName(IMember member, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			TypeSystemAstBuilder astBuilder = CreateAstBuilder();
+			EntityDeclaration node = astBuilder.ConvertEntity(member);
+			if ((ConversionFlags & ConversionFlags.ShowDeclaringType) == ConversionFlags.ShowDeclaringType) {
+				ConvertType(member.DeclaringType, writer, formattingPolicy);
+				writer.WriteToken(Roles.Dot, ".");
+			}
+			switch (member.SymbolKind) {
+				case SymbolKind.Indexer:
+					writer.WriteKeyword(Roles.Identifier, "this");
+					break;
+				case SymbolKind.Constructor:
+					WriteQualifiedName(member.DeclaringType.Name, writer, formattingPolicy);
+					break;
+				case SymbolKind.Destructor:
+					writer.WriteToken(DestructorDeclaration.TildeRole, "~");
+					WriteQualifiedName(member.DeclaringType.Name, writer, formattingPolicy);
+					break;
+				case SymbolKind.Operator:
+					switch (member.Name) {
+						case "op_Implicit":
+							writer.WriteKeyword(OperatorDeclaration.ImplicitRole, "implicit");
+							writer.Space();
+							writer.WriteKeyword(OperatorDeclaration.OperatorKeywordRole, "operator");
+							writer.Space();
+							ConvertType(member.ReturnType, writer, formattingPolicy);
+							break;
+						case "op_Explicit":
+							writer.WriteKeyword(OperatorDeclaration.ExplicitRole, "explicit");
+							writer.Space();
+							writer.WriteKeyword(OperatorDeclaration.OperatorKeywordRole, "operator");
+							writer.Space();
+							ConvertType(member.ReturnType, writer, formattingPolicy);
+							break;
+						default:
+							writer.WriteKeyword(OperatorDeclaration.OperatorKeywordRole, "operator");
+							writer.Space();
+							var operatorType = OperatorDeclaration.GetOperatorType(member.Name);
+							if (operatorType.HasValue)
+								writer.WriteToken(OperatorDeclaration.GetRole(operatorType.Value), OperatorDeclaration.GetToken(operatorType.Value));
+							else
+								writer.WriteIdentifier(node.NameToken);
+							break;
+					}
+					break;
+				default:
+					writer.WriteIdentifier(Identifier.Create(member.Name));
+					break;
+			}
+			if ((ConversionFlags & ConversionFlags.ShowTypeParameterList) == ConversionFlags.ShowTypeParameterList && member.SymbolKind == SymbolKind.Method) {
+				var outputVisitor = new CSharpOutputVisitor(writer, formattingPolicy);
+				outputVisitor.WriteTypeParameters(node.GetChildrenByRole(Roles.TypeParameter));
+			}
+		}
+		
+		void PrintModifiers(Modifiers modifiers, TokenWriter writer)
+		{
+			foreach (var m in CSharpModifierToken.AllModifiers) {
+				if ((modifiers & m) == m) {
+					writer.WriteKeyword(EntityDeclaration.ModifierRole, CSharpModifierToken.GetModifierName(m));
+					writer.Space();
+				}
+			}
+		}
+		
+		void WriteQualifiedName(string name, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			var node = AstType.Create(name);
+			var outputVisitor = new CSharpOutputVisitor(writer, formattingPolicy);
+			node.AcceptVisitor(outputVisitor);
+		}
+		#endregion
+		
+		public string ConvertVariable(IVariable v)
+		{
+			TypeSystemAstBuilder astBuilder = CreateAstBuilder();
+			AstNode astNode = astBuilder.ConvertVariable(v);
+			return astNode.ToString().TrimEnd(';', '\r', '\n', (char)8232);
+		}
+		
+		public string ConvertType(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			
+			TypeSystemAstBuilder astBuilder = CreateAstBuilder();
+			astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) != ConversionFlags.UseFullyQualifiedEntityNames;
+			AstType astType = astBuilder.ConvertType(type);
+			return astType.ToString();
+		}
+		
+		public void ConvertType(IType type, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			TypeSystemAstBuilder astBuilder = CreateAstBuilder();
+			astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) != ConversionFlags.UseFullyQualifiedEntityNames;
+			AstType astType = astBuilder.ConvertType(type);
+			astType.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
+		}
+		
+		public string ConvertConstantValue(object constantValue)
+		{
+			return TextWriterTokenWriter.PrintPrimitiveValue(constantValue);
+		}
+		
+		public string WrapComment(string comment)
+		{
+			return "// " + comment;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CSharpOutputVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CSharpOutputVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CSharpOutputVisitor.cs	(revision 11807)
@@ -0,0 +1,2396 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using ICSharpCode.NRefactory.PatternMatching;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Outputs the AST.
+	/// </summary>
+	public class CSharpOutputVisitor : IAstVisitor
+	{
+		readonly TokenWriter writer;
+		readonly CSharpFormattingOptions policy;
+		readonly Stack<AstNode> containerStack = new Stack<AstNode> ();
+		
+		public CSharpOutputVisitor (TextWriter textWriter, CSharpFormattingOptions formattingPolicy)
+		{
+			if (textWriter == null) {
+				throw new ArgumentNullException ("textWriter");
+			}
+			if (formattingPolicy == null) {
+				throw new ArgumentNullException ("formattingPolicy");
+			}
+			this.writer = TokenWriter.Create(textWriter);
+			this.policy = formattingPolicy;
+		}
+		
+		public CSharpOutputVisitor (TokenWriter writer, CSharpFormattingOptions formattingPolicy)
+		{
+			if (writer == null) {
+				throw new ArgumentNullException ("writer");
+			}
+			if (formattingPolicy == null) {
+				throw new ArgumentNullException ("formattingPolicy");
+			}
+			this.writer = new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(writer));
+			this.policy = formattingPolicy;
+		}
+		
+		#region StartNode/EndNode
+		void StartNode(AstNode node)
+		{
+			// Ensure that nodes are visited in the proper nested order.
+			// Jumps to different subtrees are allowed only for the child of a placeholder node.
+			Debug.Assert(containerStack.Count == 0 || node.Parent == containerStack.Peek() || containerStack.Peek().NodeType == NodeType.Pattern);
+			containerStack.Push(node);
+			writer.StartNode(node);
+		}
+		
+		void EndNode(AstNode node)
+		{
+			Debug.Assert(node == containerStack.Peek());
+			containerStack.Pop();
+			writer.EndNode(node);
+		}
+		#endregion
+		
+		#region Comma
+		/// <summary>
+		/// Writes a comma.
+		/// </summary>
+		/// <param name="nextNode">The next node after the comma.</param>
+		/// <param name="noSpaceAfterComma">When set prevents printing a space after comma.</param>
+		void Comma(AstNode nextNode, bool noSpaceAfterComma = false)
+		{
+			Space(policy.SpaceBeforeBracketComma);
+			// TODO: Comma policy has changed.
+			writer.WriteToken(Roles.Comma, ",");
+			Space(!noSpaceAfterComma && policy.SpaceAfterBracketComma);
+			// TODO: Comma policy has changed.
+		}
+		
+		/// <summary>
+		/// Writes an optional comma, e.g. at the end of an enum declaration or in an array initializer
+		/// </summary>
+		void OptionalComma(AstNode pos)
+		{
+			// Look if there's a comma after the current node, and insert it if it exists.
+			while (pos != null && pos.NodeType == NodeType.Whitespace) {
+				pos = pos.NextSibling;
+			}
+			if (pos != null && pos.Role == Roles.Comma) {
+				Comma(null, noSpaceAfterComma: true);
+			}
+		}
+		
+		/// <summary>
+		/// Writes an optional semicolon, e.g. at the end of a type or namespace declaration.
+		/// </summary>
+		void OptionalSemicolon(AstNode pos)
+		{
+			// Look if there's a semicolon after the current node, and insert it if it exists.
+			while (pos != null && pos.NodeType == NodeType.Whitespace) {
+				pos = pos.PrevSibling;
+			}
+			if (pos != null && pos.Role == Roles.Semicolon) {
+				Semicolon();
+			}
+		}
+		
+		void WriteCommaSeparatedList(IEnumerable<AstNode> list)
+		{
+			bool isFirst = true;
+			foreach (AstNode node in list) {
+				if (isFirst) {
+					isFirst = false;
+				} else {
+					Comma(node);
+				}
+				node.AcceptVisitor(this);
+			}
+		}
+		
+		void WriteCommaSeparatedListInParenthesis(IEnumerable<AstNode> list, bool spaceWithin)
+		{
+			LPar();
+			if (list.Any()) {
+				Space(spaceWithin);
+				WriteCommaSeparatedList(list);
+				Space(spaceWithin);
+			}
+			RPar();
+		}
+		
+		#if DOTNET35
+		void WriteCommaSeparatedList(IEnumerable<VariableInitializer> list)
+		{
+			WriteCommaSeparatedList(list.SafeCast<VariableInitializer, AstNode>());
+		}
+		
+		void WriteCommaSeparatedList(IEnumerable<AstType> list)
+		{
+			WriteCommaSeparatedList(list.SafeCast<AstType, AstNode>());
+		}
+		
+		void WriteCommaSeparatedListInParenthesis(IEnumerable<Expression> list, bool spaceWithin)
+		{
+			WriteCommaSeparatedListInParenthesis(list.SafeCast<Expression, AstNode>(), spaceWithin);
+		}
+		
+		void WriteCommaSeparatedListInParenthesis(IEnumerable<ParameterDeclaration> list, bool spaceWithin)
+		{
+			WriteCommaSeparatedListInParenthesis(list.SafeCast<ParameterDeclaration, AstNode>(), spaceWithin);
+		}
+
+		#endif
+
+		void WriteCommaSeparatedListInBrackets(IEnumerable<ParameterDeclaration> list, bool spaceWithin)
+		{
+			WriteToken(Roles.LBracket);
+			if (list.Any()) {
+				Space(spaceWithin);
+				WriteCommaSeparatedList(list);
+				Space(spaceWithin);
+			}
+			WriteToken(Roles.RBracket);
+		}
+
+		void WriteCommaSeparatedListInBrackets(IEnumerable<Expression> list)
+		{
+			WriteToken(Roles.LBracket);
+			if (list.Any()) {
+				Space(policy.SpacesWithinBrackets);
+				WriteCommaSeparatedList(list);
+				Space(policy.SpacesWithinBrackets);
+			}
+			WriteToken(Roles.RBracket);
+		}
+		#endregion
+		
+		#region Write tokens
+		bool isAtStartOfLine = true;
+		
+		/// <summary>
+		/// Writes a keyword, and all specials up to
+		/// </summary>
+		void WriteKeyword(TokenRole tokenRole)
+		{
+			WriteKeyword(tokenRole.Token, tokenRole);
+		}
+		
+		void WriteKeyword(string token, Role tokenRole = null)
+		{
+			writer.WriteKeyword(tokenRole, token);
+			isAtStartOfLine = false;
+		}
+		
+		void WriteIdentifier(Identifier identifier)
+		{
+			writer.WriteIdentifier(identifier);
+			isAtStartOfLine = false;
+		}
+		
+		void WriteIdentifier(string identifier)
+		{
+			AstType.Create(identifier).AcceptVisitor(this);
+			isAtStartOfLine = false;
+		}
+		
+		void WriteToken(TokenRole tokenRole)
+		{
+			WriteToken(tokenRole.Token, tokenRole);
+		}
+		
+		void WriteToken(string token, Role tokenRole)
+		{
+			writer.WriteToken(tokenRole, token);
+			isAtStartOfLine = false;
+		}
+		
+		void LPar()
+		{
+			WriteToken(Roles.LPar);
+		}
+		
+		void RPar()
+		{
+			WriteToken(Roles.RPar);
+		}
+		
+		/// <summary>
+		/// Marks the end of a statement
+		/// </summary>
+		void Semicolon()
+		{
+			Role role = containerStack.Peek().Role;
+			// get the role of the current node
+			if (!(role == ForStatement.InitializerRole || role == ForStatement.IteratorRole || role == UsingStatement.ResourceAcquisitionRole)) {
+				WriteToken(Roles.Semicolon);
+				NewLine();
+			}
+		}
+		
+		/// <summary>
+		/// Writes a space depending on policy.
+		/// </summary>
+		void Space(bool addSpace = true)
+		{
+			if (addSpace) {
+				writer.Space();
+			}
+		}
+		
+		void NewLine()
+		{
+			writer.NewLine();
+			isAtStartOfLine = true;
+		}
+		
+		void OpenBrace(BraceStyle style)
+		{
+			switch (style) {
+				case BraceStyle.DoNotChange:
+				case BraceStyle.EndOfLine:
+				case BraceStyle.BannerStyle:
+					if (!isAtStartOfLine)
+						writer.Space();
+					writer.WriteToken(Roles.LBrace, "{");
+					break;
+				case BraceStyle.EndOfLineWithoutSpace:
+					writer.WriteToken(Roles.LBrace, "{");
+					break;
+				case BraceStyle.NextLine:
+					if (!isAtStartOfLine)
+						NewLine();
+					writer.WriteToken(Roles.LBrace, "{");
+					break;
+				case BraceStyle.NextLineShifted:
+					NewLine();
+					writer.Indent();
+					writer.WriteToken(Roles.LBrace, "{");
+					NewLine();
+					return;
+				case BraceStyle.NextLineShifted2:
+					NewLine();
+					writer.Indent();
+					writer.WriteToken(Roles.LBrace, "{");
+					break;
+				default:
+					throw new ArgumentOutOfRangeException ();
+			}
+			writer.Indent();
+			NewLine();
+		}
+		
+		void CloseBrace(BraceStyle style)
+		{
+			switch (style) {
+				case BraceStyle.DoNotChange:
+				case BraceStyle.EndOfLine:
+				case BraceStyle.EndOfLineWithoutSpace:
+				case BraceStyle.NextLine:
+					writer.Unindent();
+					writer.WriteToken(Roles.RBrace, "}");
+					isAtStartOfLine = false;
+					break;
+				case BraceStyle.BannerStyle:
+				case BraceStyle.NextLineShifted:
+					writer.WriteToken(Roles.RBrace, "}");
+					isAtStartOfLine = false;
+					writer.Unindent();
+					break;
+				case BraceStyle.NextLineShifted2:
+					writer.Unindent();
+					writer.WriteToken(Roles.RBrace, "}");
+					isAtStartOfLine = false;
+					writer.Unindent();
+					break;
+				default:
+					throw new ArgumentOutOfRangeException();
+			}
+		}
+
+		#endregion
+		
+		#region IsKeyword Test
+		static readonly HashSet<string> unconditionalKeywords = new HashSet<string> {
+			"abstract", "as", "base", "bool", "break", "byte", "case", "catch",
+			"char", "checked", "class", "const", "continue", "decimal", "default", "delegate",
+			"do", "double", "else", "enum", "event", "explicit", "extern", "false",
+			"finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit",
+			"in", "int", "interface", "internal", "is", "lock", "long", "namespace",
+			"new", "null", "object", "operator", "out", "override", "params", "private",
+			"protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short",
+			"sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
+			"true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort",
+			"using", "virtual", "void", "volatile", "while"
+		};
+		static readonly HashSet<string> queryKeywords = new HashSet<string> {
+			"from", "where", "join", "on", "equals", "into", "let", "orderby",
+			"ascending", "descending", "select", "group", "by"
+		};
+		
+		/// <summary>
+		/// Determines whether the specified identifier is a keyword in the given context.
+		/// </summary>
+		public static bool IsKeyword(string identifier, AstNode context)
+		{
+			if (unconditionalKeywords.Contains(identifier)) {
+				return true;
+			}
+			foreach (AstNode ancestor in context.Ancestors) {
+				if (ancestor is QueryExpression && queryKeywords.Contains(identifier)) {
+					return true;
+				}
+				if (identifier == "await") {
+					// with lambdas/anonymous methods,
+					if (ancestor is LambdaExpression) {
+						return ((LambdaExpression)ancestor).IsAsync;
+					}
+					if (ancestor is AnonymousMethodExpression) {
+						return ((AnonymousMethodExpression)ancestor).IsAsync;
+					}
+					if (ancestor is EntityDeclaration) {
+						return (((EntityDeclaration)ancestor).Modifiers & Modifiers.Async) == Modifiers.Async;
+					}
+				}
+			}
+			return false;
+		}
+		#endregion
+		
+		#region Write constructs
+		void WriteTypeArguments(IEnumerable<AstType> typeArguments)
+		{
+			if (typeArguments.Any()) {
+				WriteToken(Roles.LChevron);
+				WriteCommaSeparatedList(typeArguments);
+				WriteToken(Roles.RChevron);
+			}
+		}
+		
+		public void WriteTypeParameters(IEnumerable<TypeParameterDeclaration> typeParameters)
+		{
+			if (typeParameters.Any()) {
+				WriteToken(Roles.LChevron);
+				WriteCommaSeparatedList(typeParameters);
+				WriteToken(Roles.RChevron);
+			}
+		}
+		
+		void WriteModifiers(IEnumerable<CSharpModifierToken> modifierTokens)
+		{
+			foreach (CSharpModifierToken modifier in modifierTokens) {
+				modifier.AcceptVisitor(this);
+			}
+		}
+		
+		void WriteQualifiedIdentifier(IEnumerable<Identifier> identifiers)
+		{
+			bool first = true;
+			foreach (Identifier ident in identifiers) {
+				if (first) {
+					first = false;
+				} else {
+					writer.WriteToken(Roles.Dot, ".");
+				}
+				writer.WriteIdentifier(ident);
+			}
+		}
+		
+		void WriteEmbeddedStatement(Statement embeddedStatement)
+		{
+			if (embeddedStatement.IsNull) {
+				NewLine();
+				return;
+			}
+			BlockStatement block = embeddedStatement as BlockStatement;
+			if (block != null) {
+				VisitBlockStatement(block);
+			} else {
+				NewLine();
+				writer.Indent();
+				embeddedStatement.AcceptVisitor(this);
+				writer.Unindent();
+			}
+		}
+		
+		void WriteMethodBody(BlockStatement body)
+		{
+			if (body.IsNull) {
+				Semicolon();
+			} else {
+				VisitBlockStatement(body);
+			}
+		}
+		
+		void WriteAttributes(IEnumerable<AttributeSection> attributes)
+		{
+			foreach (AttributeSection attr in attributes) {
+				attr.AcceptVisitor(this);
+			}
+		}
+		
+		void WritePrivateImplementationType(AstType privateImplementationType)
+		{
+			if (!privateImplementationType.IsNull) {
+				privateImplementationType.AcceptVisitor(this);
+				WriteToken(Roles.Dot);
+			}
+		}
+
+		#endregion
+		
+		#region Expressions
+		public void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
+		{
+			StartNode(anonymousMethodExpression);
+			if (anonymousMethodExpression.IsAsync) {
+				WriteKeyword(AnonymousMethodExpression.AsyncModifierRole);
+				Space();
+			}
+			WriteKeyword(AnonymousMethodExpression.DelegateKeywordRole);
+			if (anonymousMethodExpression.HasParameterList) {
+				Space(policy.SpaceBeforeMethodDeclarationParentheses);
+				WriteCommaSeparatedListInParenthesis(anonymousMethodExpression.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			}
+			anonymousMethodExpression.Body.AcceptVisitor(this);
+			EndNode(anonymousMethodExpression);
+		}
+		
+		public void VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
+		{
+			StartNode(undocumentedExpression);
+			switch (undocumentedExpression.UndocumentedExpressionType) {
+				case UndocumentedExpressionType.ArgList:
+				case UndocumentedExpressionType.ArgListAccess:
+					WriteKeyword(UndocumentedExpression.ArglistKeywordRole);
+					break;
+				case UndocumentedExpressionType.MakeRef:
+					WriteKeyword(UndocumentedExpression.MakerefKeywordRole);
+					break;
+				case UndocumentedExpressionType.RefType:
+					WriteKeyword(UndocumentedExpression.ReftypeKeywordRole);
+					break;
+				case UndocumentedExpressionType.RefValue:
+					WriteKeyword(UndocumentedExpression.RefvalueKeywordRole);
+					break;
+			}
+			if (undocumentedExpression.Arguments.Count > 0) {
+				Space(policy.SpaceBeforeMethodCallParentheses);
+				WriteCommaSeparatedListInParenthesis(undocumentedExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
+			}
+			EndNode(undocumentedExpression);
+		}
+		
+		public void VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
+		{
+			StartNode(arrayCreateExpression);
+			WriteKeyword(ArrayCreateExpression.NewKeywordRole);
+			arrayCreateExpression.Type.AcceptVisitor(this);
+			if (arrayCreateExpression.Arguments.Count > 0) {
+				WriteCommaSeparatedListInBrackets(arrayCreateExpression.Arguments);
+			}
+			foreach (var specifier in arrayCreateExpression.AdditionalArraySpecifiers) {
+				specifier.AcceptVisitor(this);
+			}
+			arrayCreateExpression.Initializer.AcceptVisitor(this);
+			EndNode(arrayCreateExpression);
+		}
+		
+		public void VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
+		{
+			StartNode(arrayInitializerExpression);
+			// "new List<int> { { 1 } }" and "new List<int> { 1 }" are the same semantically.
+			// We also use the same AST for both: we always use two nested ArrayInitializerExpressions
+			// for collection initializers, even if the user did not write nested brackets.
+			// The output visitor will output nested braces only if they are necessary,
+			// or if the braces tokens exist in the AST.
+			bool bracesAreOptional = arrayInitializerExpression.Elements.Count == 1
+				&& IsObjectOrCollectionInitializer(arrayInitializerExpression.Parent)
+				&& !CanBeConfusedWithObjectInitializer(arrayInitializerExpression.Elements.Single());
+			if (bracesAreOptional && arrayInitializerExpression.LBraceToken.IsNull) {
+				arrayInitializerExpression.Elements.Single().AcceptVisitor(this);
+			} else {
+				PrintInitializerElements(arrayInitializerExpression.Elements);
+			}
+			EndNode(arrayInitializerExpression);
+		}
+		
+		bool CanBeConfusedWithObjectInitializer(Expression expr)
+		{
+			// "int a; new List<int> { a = 1 };" is an object initalizers and invalid, but
+			// "int a; new List<int> { { a = 1 } };" is a valid collection initializer.
+			AssignmentExpression ae = expr as AssignmentExpression;
+			return ae != null && ae.Operator == AssignmentOperatorType.Assign;
+		}
+		
+		bool IsObjectOrCollectionInitializer(AstNode node)
+		{
+			if (!(node is ArrayInitializerExpression)) {
+				return false;
+			}
+			if (node.Parent is ObjectCreateExpression) {
+				return node.Role == ObjectCreateExpression.InitializerRole;
+			}
+			if (node.Parent is NamedExpression) {
+				return node.Role == Roles.Expression;
+			}
+			return false;
+		}
+		
+		void PrintInitializerElements(AstNodeCollection<Expression> elements)
+		{
+			BraceStyle style;
+			if (policy.ArrayInitializerWrapping == Wrapping.WrapAlways) {
+				style = BraceStyle.NextLine;
+			} else {
+				style = BraceStyle.EndOfLine;
+			}
+			OpenBrace(style);
+			bool isFirst = true;
+			AstNode last = null;
+			foreach (AstNode node in elements) {
+				if (isFirst) {
+					isFirst = false;
+				} else {
+					Comma(node, noSpaceAfterComma: true);
+					NewLine();
+				}
+				last = node;
+				node.AcceptVisitor(this);
+			}
+			if (last != null)
+				OptionalComma(last.NextSibling);
+			NewLine();
+			CloseBrace(style);
+		}
+		
+		public void VisitAsExpression(AsExpression asExpression)
+		{
+			StartNode(asExpression);
+			asExpression.Expression.AcceptVisitor(this);
+			Space();
+			WriteKeyword(AsExpression.AsKeywordRole);
+			Space();
+			asExpression.Type.AcceptVisitor(this);
+			EndNode(asExpression);
+		}
+		
+		public void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+		{
+			StartNode(assignmentExpression);
+			assignmentExpression.Left.AcceptVisitor(this);
+			Space(policy.SpaceAroundAssignment);
+			WriteToken(AssignmentExpression.GetOperatorRole(assignmentExpression.Operator));
+			Space(policy.SpaceAroundAssignment);
+			assignmentExpression.Right.AcceptVisitor(this);
+			EndNode(assignmentExpression);
+		}
+		
+		public void VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
+		{
+			StartNode(baseReferenceExpression);
+			WriteKeyword("base", baseReferenceExpression.Role);
+			EndNode(baseReferenceExpression);
+		}
+		
+		public void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+		{
+			StartNode(binaryOperatorExpression);
+			binaryOperatorExpression.Left.AcceptVisitor(this);
+			bool spacePolicy;
+			switch (binaryOperatorExpression.Operator) {
+				case BinaryOperatorType.BitwiseAnd:
+				case BinaryOperatorType.BitwiseOr:
+				case BinaryOperatorType.ExclusiveOr:
+					spacePolicy = policy.SpaceAroundBitwiseOperator;
+					break;
+				case BinaryOperatorType.ConditionalAnd:
+				case BinaryOperatorType.ConditionalOr:
+					spacePolicy = policy.SpaceAroundLogicalOperator;
+					break;
+				case BinaryOperatorType.GreaterThan:
+				case BinaryOperatorType.GreaterThanOrEqual:
+				case BinaryOperatorType.LessThanOrEqual:
+				case BinaryOperatorType.LessThan:
+					spacePolicy = policy.SpaceAroundRelationalOperator;
+					break;
+				case BinaryOperatorType.Equality:
+				case BinaryOperatorType.InEquality:
+					spacePolicy = policy.SpaceAroundEqualityOperator;
+					break;
+				case BinaryOperatorType.Add:
+				case BinaryOperatorType.Subtract:
+					spacePolicy = policy.SpaceAroundAdditiveOperator;
+					break;
+				case BinaryOperatorType.Multiply:
+				case BinaryOperatorType.Divide:
+				case BinaryOperatorType.Modulus:
+					spacePolicy = policy.SpaceAroundMultiplicativeOperator;
+					break;
+				case BinaryOperatorType.ShiftLeft:
+				case BinaryOperatorType.ShiftRight:
+					spacePolicy = policy.SpaceAroundShiftOperator;
+					break;
+				case BinaryOperatorType.NullCoalescing:
+					spacePolicy = true;
+					break;
+				default:
+					throw new NotSupportedException ("Invalid value for BinaryOperatorType");
+			}
+			Space(spacePolicy);
+			WriteToken(BinaryOperatorExpression.GetOperatorRole(binaryOperatorExpression.Operator));
+			Space(spacePolicy);
+			binaryOperatorExpression.Right.AcceptVisitor(this);
+			EndNode(binaryOperatorExpression);
+		}
+		
+		public void VisitCastExpression(CastExpression castExpression)
+		{
+			StartNode(castExpression);
+			LPar();
+			Space(policy.SpacesWithinCastParentheses);
+			castExpression.Type.AcceptVisitor(this);
+			Space(policy.SpacesWithinCastParentheses);
+			RPar();
+			Space(policy.SpaceAfterTypecast);
+			castExpression.Expression.AcceptVisitor(this);
+			EndNode(castExpression);
+		}
+		
+		public void VisitCheckedExpression(CheckedExpression checkedExpression)
+		{
+			StartNode(checkedExpression);
+			WriteKeyword(CheckedExpression.CheckedKeywordRole);
+			LPar();
+			Space(policy.SpacesWithinCheckedExpressionParantheses);
+			checkedExpression.Expression.AcceptVisitor(this);
+			Space(policy.SpacesWithinCheckedExpressionParantheses);
+			RPar();
+			EndNode(checkedExpression);
+		}
+		
+		public void VisitConditionalExpression(ConditionalExpression conditionalExpression)
+		{
+			StartNode(conditionalExpression);
+			conditionalExpression.Condition.AcceptVisitor(this);
+			
+			Space(policy.SpaceBeforeConditionalOperatorCondition);
+			WriteToken(ConditionalExpression.QuestionMarkRole);
+			Space(policy.SpaceAfterConditionalOperatorCondition);
+			
+			conditionalExpression.TrueExpression.AcceptVisitor(this);
+			
+			Space(policy.SpaceBeforeConditionalOperatorSeparator);
+			WriteToken(ConditionalExpression.ColonRole);
+			Space(policy.SpaceAfterConditionalOperatorSeparator);
+			
+			conditionalExpression.FalseExpression.AcceptVisitor(this);
+			
+			EndNode(conditionalExpression);
+		}
+		
+		public void VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
+		{
+			StartNode(defaultValueExpression);
+			
+			WriteKeyword(DefaultValueExpression.DefaultKeywordRole);
+			LPar();
+			Space(policy.SpacesWithinTypeOfParentheses);
+			defaultValueExpression.Type.AcceptVisitor(this);
+			Space(policy.SpacesWithinTypeOfParentheses);
+			RPar();
+			
+			EndNode(defaultValueExpression);
+		}
+		
+		public void VisitDirectionExpression(DirectionExpression directionExpression)
+		{
+			StartNode(directionExpression);
+			
+			switch (directionExpression.FieldDirection) {
+				case FieldDirection.Out:
+					WriteKeyword(DirectionExpression.OutKeywordRole);
+					break;
+				case FieldDirection.Ref:
+					WriteKeyword(DirectionExpression.RefKeywordRole);
+					break;
+				default:
+					throw new NotSupportedException ("Invalid value for FieldDirection");
+			}
+			Space();
+			directionExpression.Expression.AcceptVisitor(this);
+			
+			EndNode(directionExpression);
+		}
+		
+		public void VisitIdentifierExpression(IdentifierExpression identifierExpression)
+		{
+			StartNode(identifierExpression);
+			WriteIdentifier(identifierExpression.IdentifierToken);
+			WriteTypeArguments(identifierExpression.TypeArguments);
+			EndNode(identifierExpression);
+		}
+		
+		public void VisitIndexerExpression(IndexerExpression indexerExpression)
+		{
+			StartNode(indexerExpression);
+			indexerExpression.Target.AcceptVisitor(this);
+			Space(policy.SpaceBeforeMethodCallParentheses);
+			WriteCommaSeparatedListInBrackets(indexerExpression.Arguments);
+			EndNode(indexerExpression);
+		}
+		
+		public void VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			StartNode(invocationExpression);
+			invocationExpression.Target.AcceptVisitor(this);
+			Space(policy.SpaceBeforeMethodCallParentheses);
+			WriteCommaSeparatedListInParenthesis(invocationExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
+			EndNode(invocationExpression);
+		}
+		
+		public void VisitIsExpression(IsExpression isExpression)
+		{
+			StartNode(isExpression);
+			isExpression.Expression.AcceptVisitor(this);
+			Space();
+			WriteKeyword(IsExpression.IsKeywordRole);
+			isExpression.Type.AcceptVisitor(this);
+			EndNode(isExpression);
+		}
+		
+		public void VisitLambdaExpression(LambdaExpression lambdaExpression)
+		{
+			StartNode(lambdaExpression);
+			if (lambdaExpression.IsAsync) {
+				WriteKeyword(LambdaExpression.AsyncModifierRole);
+				Space();
+			}
+			if (LambdaNeedsParenthesis(lambdaExpression)) {
+				WriteCommaSeparatedListInParenthesis(lambdaExpression.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			} else {
+				lambdaExpression.Parameters.Single().AcceptVisitor(this);
+			}
+			Space();
+			WriteToken(LambdaExpression.ArrowRole);
+			Space();
+			lambdaExpression.Body.AcceptVisitor(this);
+			EndNode(lambdaExpression);
+		}
+		
+		bool LambdaNeedsParenthesis(LambdaExpression lambdaExpression)
+		{
+			if (lambdaExpression.Parameters.Count != 1) {
+				return true;
+			}
+			var p = lambdaExpression.Parameters.Single();
+			return !(p.Type.IsNull && p.ParameterModifier == ParameterModifier.None);
+		}
+		
+		public void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			StartNode(memberReferenceExpression);
+			memberReferenceExpression.Target.AcceptVisitor(this);
+			WriteToken(Roles.Dot);
+			WriteIdentifier(memberReferenceExpression.MemberNameToken);
+			WriteTypeArguments(memberReferenceExpression.TypeArguments);
+			EndNode(memberReferenceExpression);
+		}
+		
+		public void VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
+		{
+			StartNode(namedArgumentExpression);
+			WriteIdentifier(namedArgumentExpression.NameToken);
+			WriteToken(Roles.Colon);
+			Space();
+			namedArgumentExpression.Expression.AcceptVisitor(this);
+			EndNode(namedArgumentExpression);
+		}
+		
+		public void VisitNamedExpression(NamedExpression namedExpression)
+		{
+			StartNode(namedExpression);
+			WriteIdentifier(namedExpression.NameToken);
+			Space();
+			WriteToken(Roles.Assign);
+			Space();
+			namedExpression.Expression.AcceptVisitor(this);
+			EndNode(namedExpression);
+		}
+		
+		public void VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
+		{
+			StartNode(nullReferenceExpression);
+			writer.WritePrimitiveValue(null);
+			EndNode(nullReferenceExpression);
+		}
+		
+		public void VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
+		{
+			StartNode(objectCreateExpression);
+			WriteKeyword(ObjectCreateExpression.NewKeywordRole);
+			objectCreateExpression.Type.AcceptVisitor(this);
+			bool useParenthesis = objectCreateExpression.Arguments.Any() || objectCreateExpression.Initializer.IsNull;
+			// also use parenthesis if there is an '(' token
+			if (!objectCreateExpression.LParToken.IsNull) {
+				useParenthesis = true;
+			}
+			if (useParenthesis) {
+				Space(policy.SpaceBeforeMethodCallParentheses);
+				WriteCommaSeparatedListInParenthesis(objectCreateExpression.Arguments, policy.SpaceWithinMethodCallParentheses);
+			}
+			objectCreateExpression.Initializer.AcceptVisitor(this);
+			EndNode(objectCreateExpression);
+		}
+		
+		public void VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+		{
+			StartNode(anonymousTypeCreateExpression);
+			WriteKeyword(AnonymousTypeCreateExpression.NewKeywordRole);
+			PrintInitializerElements(anonymousTypeCreateExpression.Initializers);
+			EndNode(anonymousTypeCreateExpression);
+		}
+
+		public void VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
+		{
+			StartNode(parenthesizedExpression);
+			LPar();
+			Space(policy.SpacesWithinParentheses);
+			parenthesizedExpression.Expression.AcceptVisitor(this);
+			Space(policy.SpacesWithinParentheses);
+			RPar();
+			EndNode(parenthesizedExpression);
+		}
+		
+		public void VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
+		{
+			StartNode(pointerReferenceExpression);
+			pointerReferenceExpression.Target.AcceptVisitor(this);
+			WriteToken(PointerReferenceExpression.ArrowRole);
+			WriteIdentifier(pointerReferenceExpression.MemberNameToken);
+			WriteTypeArguments(pointerReferenceExpression.TypeArguments);
+			EndNode(pointerReferenceExpression);
+		}
+		
+		#region VisitPrimitiveExpression
+		public void VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+		{
+			StartNode(primitiveExpression);
+			writer.WritePrimitiveValue(primitiveExpression.Value, primitiveExpression.UnsafeLiteralValue);
+			EndNode(primitiveExpression);
+		}
+		#endregion
+		
+		public void VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
+		{
+			StartNode(sizeOfExpression);
+			
+			WriteKeyword(SizeOfExpression.SizeofKeywordRole);
+			LPar();
+			Space(policy.SpacesWithinSizeOfParentheses);
+			sizeOfExpression.Type.AcceptVisitor(this);
+			Space(policy.SpacesWithinSizeOfParentheses);
+			RPar();
+			
+			EndNode(sizeOfExpression);
+		}
+		
+		public void VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
+		{
+			StartNode(stackAllocExpression);
+			WriteKeyword(StackAllocExpression.StackallocKeywordRole);
+			stackAllocExpression.Type.AcceptVisitor(this);
+			WriteCommaSeparatedListInBrackets(new[] { stackAllocExpression.CountExpression });
+			EndNode(stackAllocExpression);
+		}
+		
+		public void VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
+		{
+			StartNode(thisReferenceExpression);
+			WriteKeyword("this", thisReferenceExpression.Role);
+			EndNode(thisReferenceExpression);
+		}
+		
+		public void VisitTypeOfExpression(TypeOfExpression typeOfExpression)
+		{
+			StartNode(typeOfExpression);
+			
+			WriteKeyword(TypeOfExpression.TypeofKeywordRole);
+			LPar();
+			Space(policy.SpacesWithinTypeOfParentheses);
+			typeOfExpression.Type.AcceptVisitor(this);
+			Space(policy.SpacesWithinTypeOfParentheses);
+			RPar();
+			
+			EndNode(typeOfExpression);
+		}
+		
+		public void VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
+		{
+			StartNode(typeReferenceExpression);
+			typeReferenceExpression.Type.AcceptVisitor(this);
+			EndNode(typeReferenceExpression);
+		}
+		
+		public void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+		{
+			StartNode(unaryOperatorExpression);
+			UnaryOperatorType opType = unaryOperatorExpression.Operator;
+			var opSymbol = UnaryOperatorExpression.GetOperatorRole(opType);
+			if (opType == UnaryOperatorType.Await) {
+				WriteKeyword(opSymbol);
+			} else if (!(opType == UnaryOperatorType.PostIncrement || opType == UnaryOperatorType.PostDecrement)) {
+				WriteToken(opSymbol);
+			}
+			unaryOperatorExpression.Expression.AcceptVisitor(this);
+			if (opType == UnaryOperatorType.PostIncrement || opType == UnaryOperatorType.PostDecrement) {
+				WriteToken(opSymbol);
+			}
+			EndNode(unaryOperatorExpression);
+		}
+		
+		public void VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
+		{
+			StartNode(uncheckedExpression);
+			WriteKeyword(UncheckedExpression.UncheckedKeywordRole);
+			LPar();
+			Space(policy.SpacesWithinCheckedExpressionParantheses);
+			uncheckedExpression.Expression.AcceptVisitor(this);
+			Space(policy.SpacesWithinCheckedExpressionParantheses);
+			RPar();
+			EndNode(uncheckedExpression);
+		}
+
+		#endregion
+		
+		#region Query Expressions
+		public void VisitQueryExpression(QueryExpression queryExpression)
+		{
+			StartNode(queryExpression);
+			bool indent = queryExpression.Parent is QueryClause && !(queryExpression.Parent is QueryContinuationClause);
+			if (indent) {
+				writer.Indent();
+				NewLine();
+			}
+			bool first = true;
+			foreach (var clause in queryExpression.Clauses) {
+				if (first) {
+					first = false;
+				} else {
+					if (!(clause is QueryContinuationClause)) {
+						NewLine();
+					}
+				}
+				clause.AcceptVisitor(this);
+			}
+			if (indent) {
+				writer.Unindent();
+			}
+			EndNode(queryExpression);
+		}
+		
+		public void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			StartNode(queryContinuationClause);
+			queryContinuationClause.PrecedingQuery.AcceptVisitor(this);
+			Space();
+			WriteKeyword(QueryContinuationClause.IntoKeywordRole);
+			Space();
+			WriteIdentifier(queryContinuationClause.IdentifierToken);
+			EndNode(queryContinuationClause);
+		}
+		
+		public void VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			StartNode(queryFromClause);
+			WriteKeyword(QueryFromClause.FromKeywordRole);
+			queryFromClause.Type.AcceptVisitor(this);
+			Space();
+			WriteIdentifier(queryFromClause.IdentifierToken);
+			Space();
+			WriteKeyword(QueryFromClause.InKeywordRole);
+			Space();
+			queryFromClause.Expression.AcceptVisitor(this);
+			EndNode(queryFromClause);
+		}
+		
+		public void VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			StartNode(queryLetClause);
+			WriteKeyword(QueryLetClause.LetKeywordRole);
+			Space();
+			WriteIdentifier(queryLetClause.IdentifierToken);
+			Space(policy.SpaceAroundAssignment);
+			WriteToken(Roles.Assign);
+			Space(policy.SpaceAroundAssignment);
+			queryLetClause.Expression.AcceptVisitor(this);
+			EndNode(queryLetClause);
+		}
+		
+		public void VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			StartNode(queryWhereClause);
+			WriteKeyword(QueryWhereClause.WhereKeywordRole);
+			Space();
+			queryWhereClause.Condition.AcceptVisitor(this);
+			EndNode(queryWhereClause);
+		}
+		
+		public void VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			StartNode(queryJoinClause);
+			WriteKeyword(QueryJoinClause.JoinKeywordRole);
+			queryJoinClause.Type.AcceptVisitor(this);
+			Space();
+			WriteIdentifier(queryJoinClause.JoinIdentifierToken);
+			Space();
+			WriteKeyword(QueryJoinClause.InKeywordRole);
+			Space();
+			queryJoinClause.InExpression.AcceptVisitor(this);
+			Space();
+			WriteKeyword(QueryJoinClause.OnKeywordRole);
+			Space();
+			queryJoinClause.OnExpression.AcceptVisitor(this);
+			Space();
+			WriteKeyword(QueryJoinClause.EqualsKeywordRole);
+			Space();
+			queryJoinClause.EqualsExpression.AcceptVisitor(this);
+			if (queryJoinClause.IsGroupJoin) {
+				Space();
+				WriteKeyword(QueryJoinClause.IntoKeywordRole);
+				WriteIdentifier(queryJoinClause.IntoIdentifierToken);
+			}
+			EndNode(queryJoinClause);
+		}
+		
+		public void VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			StartNode(queryOrderClause);
+			WriteKeyword(QueryOrderClause.OrderbyKeywordRole);
+			Space();
+			WriteCommaSeparatedList(queryOrderClause.Orderings);
+			EndNode(queryOrderClause);
+		}
+		
+		public void VisitQueryOrdering(QueryOrdering queryOrdering)
+		{
+			StartNode(queryOrdering);
+			queryOrdering.Expression.AcceptVisitor(this);
+			switch (queryOrdering.Direction) {
+				case QueryOrderingDirection.Ascending:
+					Space();
+					WriteKeyword(QueryOrdering.AscendingKeywordRole);
+					break;
+				case QueryOrderingDirection.Descending:
+					Space();
+					WriteKeyword(QueryOrdering.DescendingKeywordRole);
+					break;
+			}
+			EndNode(queryOrdering);
+		}
+		
+		public void VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			StartNode(querySelectClause);
+			WriteKeyword(QuerySelectClause.SelectKeywordRole);
+			Space();
+			querySelectClause.Expression.AcceptVisitor(this);
+			EndNode(querySelectClause);
+		}
+		
+		public void VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			StartNode(queryGroupClause);
+			WriteKeyword(QueryGroupClause.GroupKeywordRole);
+			Space();
+			queryGroupClause.Projection.AcceptVisitor(this);
+			Space();
+			WriteKeyword(QueryGroupClause.ByKeywordRole);
+			Space();
+			queryGroupClause.Key.AcceptVisitor(this);
+			EndNode(queryGroupClause);
+		}
+
+		#endregion
+		
+		#region GeneralScope
+		public void VisitAttribute(Attribute attribute)
+		{
+			StartNode(attribute);
+			attribute.Type.AcceptVisitor(this);
+			if (attribute.Arguments.Count != 0 || !attribute.GetChildByRole(Roles.LPar).IsNull) {
+				Space(policy.SpaceBeforeMethodCallParentheses);
+				WriteCommaSeparatedListInParenthesis(attribute.Arguments, policy.SpaceWithinMethodCallParentheses);
+			}
+			EndNode(attribute);
+		}
+		
+		public void VisitAttributeSection(AttributeSection attributeSection)
+		{
+			StartNode(attributeSection);
+			WriteToken(Roles.LBracket);
+			if (!string.IsNullOrEmpty(attributeSection.AttributeTarget)) {
+				WriteIdentifier(attributeSection.AttributeTargetToken);
+				WriteToken(Roles.Colon);
+				Space();
+			}
+			WriteCommaSeparatedList(attributeSection.Attributes);
+			WriteToken(Roles.RBracket);
+			if (attributeSection.Parent is ParameterDeclaration || attributeSection.Parent is TypeParameterDeclaration) {
+				Space();
+			} else {
+				NewLine();
+			}
+			EndNode(attributeSection);
+		}
+		
+		public void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			StartNode(delegateDeclaration);
+			WriteAttributes(delegateDeclaration.Attributes);
+			WriteModifiers(delegateDeclaration.ModifierTokens);
+			WriteKeyword(Roles.DelegateKeyword);
+			delegateDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WriteIdentifier(delegateDeclaration.NameToken);
+			WriteTypeParameters(delegateDeclaration.TypeParameters);
+			Space(policy.SpaceBeforeDelegateDeclarationParentheses);
+			WriteCommaSeparatedListInParenthesis(delegateDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			foreach (Constraint constraint in delegateDeclaration.Constraints) {
+				constraint.AcceptVisitor(this);
+			}
+			Semicolon();
+			EndNode(delegateDeclaration);
+		}
+		
+		public void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+		{
+			StartNode(namespaceDeclaration);
+			WriteKeyword(Roles.NamespaceKeyword);
+			namespaceDeclaration.NamespaceName.AcceptVisitor (this);
+			OpenBrace(policy.NamespaceBraceStyle);
+			foreach (var member in namespaceDeclaration.Members) {
+				member.AcceptVisitor(this);
+				MaybeNewLinesAfterUsings(member);
+			}
+			CloseBrace(policy.NamespaceBraceStyle);
+			OptionalSemicolon(namespaceDeclaration.LastChild);
+			NewLine();
+			EndNode(namespaceDeclaration);
+		}
+		
+		public void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			StartNode(typeDeclaration);
+			WriteAttributes(typeDeclaration.Attributes);
+			WriteModifiers(typeDeclaration.ModifierTokens);
+			BraceStyle braceStyle;
+			switch (typeDeclaration.ClassType) {
+				case ClassType.Enum:
+					WriteKeyword(Roles.EnumKeyword);
+					braceStyle = policy.EnumBraceStyle;
+					break;
+				case ClassType.Interface:
+					WriteKeyword(Roles.InterfaceKeyword);
+					braceStyle = policy.InterfaceBraceStyle;
+					break;
+				case ClassType.Struct:
+					WriteKeyword(Roles.StructKeyword);
+					braceStyle = policy.StructBraceStyle;
+					break;
+				default:
+					WriteKeyword(Roles.ClassKeyword);
+					braceStyle = policy.ClassBraceStyle;
+					break;
+			}
+			WriteIdentifier(typeDeclaration.NameToken);
+			WriteTypeParameters(typeDeclaration.TypeParameters);
+			if (typeDeclaration.BaseTypes.Any()) {
+				Space();
+				WriteToken(Roles.Colon);
+				Space();
+				WriteCommaSeparatedList(typeDeclaration.BaseTypes);
+			}
+			foreach (Constraint constraint in typeDeclaration.Constraints) {
+				constraint.AcceptVisitor(this);
+			}
+			OpenBrace(braceStyle);
+			if (typeDeclaration.ClassType == ClassType.Enum) {
+				bool first = true;
+				AstNode last = null;
+				foreach (var member in typeDeclaration.Members) {
+					if (first) {
+						first = false;
+					} else {
+						Comma(member, noSpaceAfterComma: true);
+						NewLine();
+					}
+					last = member;
+					member.AcceptVisitor(this);
+				}
+				if (last != null)
+					OptionalComma(last.NextSibling);
+				NewLine();
+			} else {
+				bool first = true;
+				foreach (var member in typeDeclaration.Members) {
+					if (!first) {
+						for (int i = 0; i < policy.MinimumBlankLinesBetweenMembers; i++)
+							NewLine();
+					}
+					first = false;
+					member.AcceptVisitor(this);
+				}
+			}
+			CloseBrace(braceStyle);
+			OptionalSemicolon(typeDeclaration.LastChild);
+			NewLine();
+			EndNode(typeDeclaration);
+		}
+		
+		public void VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration)
+		{
+			StartNode(usingAliasDeclaration);
+			WriteKeyword(UsingAliasDeclaration.UsingKeywordRole);
+			WriteIdentifier(usingAliasDeclaration.GetChildByRole(UsingAliasDeclaration.AliasRole));
+			Space(policy.SpaceAroundEqualityOperator);
+			WriteToken(Roles.Assign);
+			Space(policy.SpaceAroundEqualityOperator);
+			usingAliasDeclaration.Import.AcceptVisitor(this);
+			Semicolon();
+			EndNode(usingAliasDeclaration);
+		}
+		
+		public void VisitUsingDeclaration(UsingDeclaration usingDeclaration)
+		{
+			StartNode(usingDeclaration);
+			WriteKeyword(UsingDeclaration.UsingKeywordRole);
+			usingDeclaration.Import.AcceptVisitor(this);
+			Semicolon();
+			EndNode(usingDeclaration);
+		}
+		
+		public void VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			StartNode(externAliasDeclaration);
+			WriteKeyword(Roles.ExternKeyword);
+			Space();
+			WriteKeyword(Roles.AliasKeyword);
+			Space();
+			WriteIdentifier(externAliasDeclaration.NameToken);
+			Semicolon();
+			EndNode(externAliasDeclaration);
+		}
+
+		#endregion
+		
+		#region Statements
+		public void VisitBlockStatement(BlockStatement blockStatement)
+		{
+			StartNode(blockStatement);
+			BraceStyle style;
+			if (blockStatement.Parent is AnonymousMethodExpression || blockStatement.Parent is LambdaExpression) {
+				style = policy.AnonymousMethodBraceStyle;
+			} else if (blockStatement.Parent is ConstructorDeclaration) {
+				style = policy.ConstructorBraceStyle;
+			} else if (blockStatement.Parent is DestructorDeclaration) {
+				style = policy.DestructorBraceStyle;
+			} else if (blockStatement.Parent is MethodDeclaration) {
+				style = policy.MethodBraceStyle;
+			} else if (blockStatement.Parent is Accessor) {
+				if (blockStatement.Parent.Role == PropertyDeclaration.GetterRole) {
+					style = policy.PropertyGetBraceStyle;
+				} else if (blockStatement.Parent.Role == PropertyDeclaration.SetterRole) {
+					style = policy.PropertySetBraceStyle;
+				} else if (blockStatement.Parent.Role == CustomEventDeclaration.AddAccessorRole) {
+					style = policy.EventAddBraceStyle;
+				} else if (blockStatement.Parent.Role == CustomEventDeclaration.RemoveAccessorRole) {
+					style = policy.EventRemoveBraceStyle;
+				} else {
+					style = policy.StatementBraceStyle;
+				}
+			} else {
+				style = policy.StatementBraceStyle;
+			}
+			OpenBrace(style);
+			foreach (var node in blockStatement.Statements) {
+				node.AcceptVisitor(this);
+			}
+			EndNode(blockStatement);
+			CloseBrace(style);
+			if (!(blockStatement.Parent is Expression))
+				NewLine();
+		}
+		
+		public void VisitBreakStatement(BreakStatement breakStatement)
+		{
+			StartNode(breakStatement);
+			WriteKeyword("break", BreakStatement.BreakKeywordRole);
+			Semicolon();
+			EndNode(breakStatement);
+		}
+		
+		public void VisitCheckedStatement(CheckedStatement checkedStatement)
+		{
+			StartNode(checkedStatement);
+			WriteKeyword(CheckedStatement.CheckedKeywordRole);
+			checkedStatement.Body.AcceptVisitor(this);
+			EndNode(checkedStatement);
+		}
+		
+		public void VisitContinueStatement(ContinueStatement continueStatement)
+		{
+			StartNode(continueStatement);
+			WriteKeyword("continue", ContinueStatement.ContinueKeywordRole);
+			Semicolon();
+			EndNode(continueStatement);
+		}
+		
+		public void VisitDoWhileStatement(DoWhileStatement doWhileStatement)
+		{
+			StartNode(doWhileStatement);
+			WriteKeyword(DoWhileStatement.DoKeywordRole);
+			WriteEmbeddedStatement(doWhileStatement.EmbeddedStatement);
+			WriteKeyword(DoWhileStatement.WhileKeywordRole);
+			Space(policy.SpaceBeforeWhileParentheses);
+			LPar();
+			Space(policy.SpacesWithinWhileParentheses);
+			doWhileStatement.Condition.AcceptVisitor(this);
+			Space(policy.SpacesWithinWhileParentheses);
+			RPar();
+			Semicolon();
+			EndNode(doWhileStatement);
+		}
+		
+		public void VisitEmptyStatement(EmptyStatement emptyStatement)
+		{
+			StartNode(emptyStatement);
+			Semicolon();
+			EndNode(emptyStatement);
+		}
+		
+		public void VisitExpressionStatement(ExpressionStatement expressionStatement)
+		{
+			StartNode(expressionStatement);
+			expressionStatement.Expression.AcceptVisitor(this);
+			Semicolon();
+			EndNode(expressionStatement);
+		}
+		
+		public void VisitFixedStatement(FixedStatement fixedStatement)
+		{
+			StartNode(fixedStatement);
+			WriteKeyword(FixedStatement.FixedKeywordRole);
+			Space(policy.SpaceBeforeUsingParentheses);
+			LPar();
+			Space(policy.SpacesWithinUsingParentheses);
+			fixedStatement.Type.AcceptVisitor(this);
+			Space();
+			WriteCommaSeparatedList(fixedStatement.Variables);
+			Space(policy.SpacesWithinUsingParentheses);
+			RPar();
+			WriteEmbeddedStatement(fixedStatement.EmbeddedStatement);
+			EndNode(fixedStatement);
+		}
+		
+		public void VisitForeachStatement(ForeachStatement foreachStatement)
+		{
+			StartNode(foreachStatement);
+			WriteKeyword(ForeachStatement.ForeachKeywordRole);
+			Space(policy.SpaceBeforeForeachParentheses);
+			LPar();
+			Space(policy.SpacesWithinForeachParentheses);
+			foreachStatement.VariableType.AcceptVisitor(this);
+			Space();
+			WriteIdentifier(foreachStatement.VariableNameToken);
+			WriteKeyword(ForeachStatement.InKeywordRole);
+			Space();
+			foreachStatement.InExpression.AcceptVisitor(this);
+			Space(policy.SpacesWithinForeachParentheses);
+			RPar();
+			WriteEmbeddedStatement(foreachStatement.EmbeddedStatement);
+			EndNode(foreachStatement);
+		}
+		
+		public void VisitForStatement(ForStatement forStatement)
+		{
+			StartNode(forStatement);
+			WriteKeyword(ForStatement.ForKeywordRole);
+			Space(policy.SpaceBeforeForParentheses);
+			LPar();
+			Space(policy.SpacesWithinForParentheses);
+			
+			WriteCommaSeparatedList(forStatement.Initializers);
+			Space(policy.SpaceBeforeForSemicolon);
+			WriteToken(Roles.Semicolon);
+			Space(policy.SpaceAfterForSemicolon);
+			
+			forStatement.Condition.AcceptVisitor(this);
+			Space(policy.SpaceBeforeForSemicolon);
+			WriteToken(Roles.Semicolon);
+			if (forStatement.Iterators.Any()) {
+				Space(policy.SpaceAfterForSemicolon);
+				WriteCommaSeparatedList(forStatement.Iterators);
+			}
+			
+			Space(policy.SpacesWithinForParentheses);
+			RPar();
+			WriteEmbeddedStatement(forStatement.EmbeddedStatement);
+			EndNode(forStatement);
+		}
+		
+		public void VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
+		{
+			StartNode(gotoCaseStatement);
+			WriteKeyword(GotoCaseStatement.GotoKeywordRole);
+			WriteKeyword(GotoCaseStatement.CaseKeywordRole);
+			Space();
+			gotoCaseStatement.LabelExpression.AcceptVisitor(this);
+			Semicolon();
+			EndNode(gotoCaseStatement);
+		}
+		
+		public void VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
+		{
+			StartNode(gotoDefaultStatement);
+			WriteKeyword(GotoDefaultStatement.GotoKeywordRole);
+			WriteKeyword(GotoDefaultStatement.DefaultKeywordRole);
+			Semicolon();
+			EndNode(gotoDefaultStatement);
+		}
+		
+		public void VisitGotoStatement(GotoStatement gotoStatement)
+		{
+			StartNode(gotoStatement);
+			WriteKeyword(GotoStatement.GotoKeywordRole);
+			WriteIdentifier(gotoStatement.GetChildByRole(Roles.Identifier));
+			Semicolon();
+			EndNode(gotoStatement);
+		}
+		
+		public void VisitIfElseStatement(IfElseStatement ifElseStatement)
+		{
+			StartNode(ifElseStatement);
+			WriteKeyword(IfElseStatement.IfKeywordRole);
+			Space(policy.SpaceBeforeIfParentheses);
+			LPar();
+			Space(policy.SpacesWithinIfParentheses);
+			ifElseStatement.Condition.AcceptVisitor(this);
+			Space(policy.SpacesWithinIfParentheses);
+			RPar();
+			WriteEmbeddedStatement(ifElseStatement.TrueStatement);
+			if (!ifElseStatement.FalseStatement.IsNull) {
+				WriteKeyword(IfElseStatement.ElseKeywordRole);
+				WriteEmbeddedStatement(ifElseStatement.FalseStatement);
+			}
+			EndNode(ifElseStatement);
+		}
+		
+		public void VisitLabelStatement(LabelStatement labelStatement)
+		{
+			StartNode(labelStatement);
+			WriteIdentifier(labelStatement.GetChildByRole(Roles.Identifier));
+			WriteToken(Roles.Colon);
+			bool foundLabelledStatement = false;
+			for (AstNode tmp = labelStatement.NextSibling; tmp != null; tmp = tmp.NextSibling) {
+				if (tmp.Role == labelStatement.Role) {
+					foundLabelledStatement = true;
+				}
+			}
+			if (!foundLabelledStatement) {
+				// introduce an EmptyStatement so that the output becomes syntactically valid
+				WriteToken(Roles.Semicolon);
+			}
+			NewLine();
+			EndNode(labelStatement);
+		}
+		
+		public void VisitLockStatement(LockStatement lockStatement)
+		{
+			StartNode(lockStatement);
+			WriteKeyword(LockStatement.LockKeywordRole);
+			Space(policy.SpaceBeforeLockParentheses);
+			LPar();
+			Space(policy.SpacesWithinLockParentheses);
+			lockStatement.Expression.AcceptVisitor(this);
+			Space(policy.SpacesWithinLockParentheses);
+			RPar();
+			WriteEmbeddedStatement(lockStatement.EmbeddedStatement);
+			EndNode(lockStatement);
+		}
+		
+		public void VisitReturnStatement(ReturnStatement returnStatement)
+		{
+			StartNode(returnStatement);
+			WriteKeyword(ReturnStatement.ReturnKeywordRole);
+			if (!returnStatement.Expression.IsNull) {
+				Space();
+				returnStatement.Expression.AcceptVisitor(this);
+			}
+			Semicolon();
+			EndNode(returnStatement);
+		}
+		
+		public void VisitSwitchStatement(SwitchStatement switchStatement)
+		{
+			StartNode(switchStatement);
+			WriteKeyword(SwitchStatement.SwitchKeywordRole);
+			Space(policy.SpaceBeforeSwitchParentheses);
+			LPar();
+			Space(policy.SpacesWithinSwitchParentheses);
+			switchStatement.Expression.AcceptVisitor(this);
+			Space(policy.SpacesWithinSwitchParentheses);
+			RPar();
+			OpenBrace(policy.StatementBraceStyle);
+			if (!policy.IndentSwitchBody) {
+				writer.Unindent();
+			}
+			
+			foreach (var section in switchStatement.SwitchSections) {
+				section.AcceptVisitor(this);
+			}
+			
+			if (!policy.IndentSwitchBody) {
+				writer.Indent();
+			}
+			CloseBrace(policy.StatementBraceStyle);
+			NewLine();
+			EndNode(switchStatement);
+		}
+		
+		public void VisitSwitchSection(SwitchSection switchSection)
+		{
+			StartNode(switchSection);
+			bool first = true;
+			foreach (var label in switchSection.CaseLabels) {
+				if (!first) {
+					NewLine();
+				}
+				label.AcceptVisitor(this);
+				first = false;
+			}
+			bool isBlock = switchSection.Statements.Count == 1 && switchSection.Statements.Single() is BlockStatement;
+			if (policy.IndentCaseBody && !isBlock) {
+				writer.Indent();
+			}
+			
+			if (!isBlock)
+				NewLine();
+			
+			foreach (var statement in switchSection.Statements) {
+				statement.AcceptVisitor(this);
+			}
+			
+			if (policy.IndentCaseBody && !isBlock) {
+				writer.Unindent();
+			}
+			
+			EndNode(switchSection);
+		}
+		
+		public void VisitCaseLabel(CaseLabel caseLabel)
+		{
+			StartNode(caseLabel);
+			if (caseLabel.Expression.IsNull) {
+				WriteKeyword(CaseLabel.DefaultKeywordRole);
+			} else {
+				WriteKeyword(CaseLabel.CaseKeywordRole);
+				Space();
+				caseLabel.Expression.AcceptVisitor(this);
+			}
+			WriteToken(Roles.Colon);
+			EndNode(caseLabel);
+		}
+		
+		public void VisitThrowStatement(ThrowStatement throwStatement)
+		{
+			StartNode(throwStatement);
+			WriteKeyword(ThrowStatement.ThrowKeywordRole);
+			if (!throwStatement.Expression.IsNull) {
+				Space();
+				throwStatement.Expression.AcceptVisitor(this);
+			}
+			Semicolon();
+			EndNode(throwStatement);
+		}
+		
+		public void VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
+		{
+			StartNode(tryCatchStatement);
+			WriteKeyword(TryCatchStatement.TryKeywordRole);
+			tryCatchStatement.TryBlock.AcceptVisitor(this);
+			foreach (var catchClause in tryCatchStatement.CatchClauses) {
+				catchClause.AcceptVisitor(this);
+			}
+			if (!tryCatchStatement.FinallyBlock.IsNull) {
+				WriteKeyword(TryCatchStatement.FinallyKeywordRole);
+				tryCatchStatement.FinallyBlock.AcceptVisitor(this);
+			}
+			EndNode(tryCatchStatement);
+		}
+		
+		public void VisitCatchClause(CatchClause catchClause)
+		{
+			StartNode(catchClause);
+			WriteKeyword(CatchClause.CatchKeywordRole);
+			if (!catchClause.Type.IsNull) {
+				Space(policy.SpaceBeforeCatchParentheses);
+				LPar();
+				Space(policy.SpacesWithinCatchParentheses);
+				catchClause.Type.AcceptVisitor(this);
+				if (!string.IsNullOrEmpty(catchClause.VariableName)) {
+					Space();
+					WriteIdentifier(catchClause.VariableNameToken);
+				}
+				Space(policy.SpacesWithinCatchParentheses);
+				RPar();
+			}
+			catchClause.Body.AcceptVisitor(this);
+			EndNode(catchClause);
+		}
+		
+		public void VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
+		{
+			StartNode(uncheckedStatement);
+			WriteKeyword(UncheckedStatement.UncheckedKeywordRole);
+			uncheckedStatement.Body.AcceptVisitor(this);
+			EndNode(uncheckedStatement);
+		}
+		
+		public void VisitUnsafeStatement(UnsafeStatement unsafeStatement)
+		{
+			StartNode(unsafeStatement);
+			WriteKeyword(UnsafeStatement.UnsafeKeywordRole);
+			unsafeStatement.Body.AcceptVisitor(this);
+			EndNode(unsafeStatement);
+		}
+		
+		public void VisitUsingStatement(UsingStatement usingStatement)
+		{
+			StartNode(usingStatement);
+			WriteKeyword(UsingStatement.UsingKeywordRole);
+			Space(policy.SpaceBeforeUsingParentheses);
+			LPar();
+			Space(policy.SpacesWithinUsingParentheses);
+			
+			usingStatement.ResourceAcquisition.AcceptVisitor(this);
+			
+			Space(policy.SpacesWithinUsingParentheses);
+			RPar();
+			
+			WriteEmbeddedStatement(usingStatement.EmbeddedStatement);
+			
+			EndNode(usingStatement);
+		}
+		
+		public void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
+		{
+			StartNode(variableDeclarationStatement);
+			WriteModifiers(variableDeclarationStatement.GetChildrenByRole(VariableDeclarationStatement.ModifierRole));
+			variableDeclarationStatement.Type.AcceptVisitor(this);
+			Space();
+			WriteCommaSeparatedList(variableDeclarationStatement.Variables);
+			Semicolon();
+			EndNode(variableDeclarationStatement);
+		}
+		
+		public void VisitWhileStatement(WhileStatement whileStatement)
+		{
+			StartNode(whileStatement);
+			WriteKeyword(WhileStatement.WhileKeywordRole);
+			Space(policy.SpaceBeforeWhileParentheses);
+			LPar();
+			Space(policy.SpacesWithinWhileParentheses);
+			whileStatement.Condition.AcceptVisitor(this);
+			Space(policy.SpacesWithinWhileParentheses);
+			RPar();
+			WriteEmbeddedStatement(whileStatement.EmbeddedStatement);
+			EndNode(whileStatement);
+		}
+		
+		public void VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
+		{
+			StartNode(yieldBreakStatement);
+			WriteKeyword(YieldBreakStatement.YieldKeywordRole);
+			WriteKeyword(YieldBreakStatement.BreakKeywordRole);
+			Semicolon();
+			EndNode(yieldBreakStatement);
+		}
+		
+		public void VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement)
+		{
+			StartNode(yieldReturnStatement);
+			WriteKeyword(YieldReturnStatement.YieldKeywordRole);
+			WriteKeyword(YieldReturnStatement.ReturnKeywordRole);
+			Space();
+			yieldReturnStatement.Expression.AcceptVisitor(this);
+			Semicolon();
+			EndNode(yieldReturnStatement);
+		}
+
+		#endregion
+		
+		#region TypeMembers
+		public void VisitAccessor(Accessor accessor)
+		{
+			StartNode(accessor);
+			WriteAttributes(accessor.Attributes);
+			WriteModifiers(accessor.ModifierTokens);
+			if (accessor.Role == PropertyDeclaration.GetterRole) {
+				WriteKeyword("get", PropertyDeclaration.GetKeywordRole);
+			} else if (accessor.Role == PropertyDeclaration.SetterRole) {
+				WriteKeyword("set", PropertyDeclaration.SetKeywordRole);
+			} else if (accessor.Role == CustomEventDeclaration.AddAccessorRole) {
+				WriteKeyword("add", CustomEventDeclaration.AddKeywordRole);
+			} else if (accessor.Role == CustomEventDeclaration.RemoveAccessorRole) {
+				WriteKeyword("remove", CustomEventDeclaration.RemoveKeywordRole);
+			}
+			WriteMethodBody(accessor.Body);
+			EndNode(accessor);
+		}
+		
+		public void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			StartNode(constructorDeclaration);
+			WriteAttributes(constructorDeclaration.Attributes);
+			WriteModifiers(constructorDeclaration.ModifierTokens);
+			TypeDeclaration type = constructorDeclaration.Parent as TypeDeclaration;
+			if (type != null && type.Name != constructorDeclaration.Name)
+				WriteIdentifier((Identifier)type.NameToken.Clone());
+			else
+				WriteIdentifier(constructorDeclaration.NameToken);
+			Space(policy.SpaceBeforeConstructorDeclarationParentheses);
+			WriteCommaSeparatedListInParenthesis(constructorDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			if (!constructorDeclaration.Initializer.IsNull) {
+				Space();
+				constructorDeclaration.Initializer.AcceptVisitor(this);
+			}
+			WriteMethodBody(constructorDeclaration.Body);
+			EndNode(constructorDeclaration);
+		}
+		
+		public void VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
+		{
+			StartNode(constructorInitializer);
+			WriteToken(Roles.Colon);
+			Space();
+			if (constructorInitializer.ConstructorInitializerType == ConstructorInitializerType.This) {
+				WriteKeyword(ConstructorInitializer.ThisKeywordRole);
+			} else {
+				WriteKeyword(ConstructorInitializer.BaseKeywordRole);
+			}
+			Space(policy.SpaceBeforeMethodCallParentheses);
+			WriteCommaSeparatedListInParenthesis(constructorInitializer.Arguments, policy.SpaceWithinMethodCallParentheses);
+			EndNode(constructorInitializer);
+		}
+		
+		public void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			StartNode(destructorDeclaration);
+			WriteAttributes(destructorDeclaration.Attributes);
+			WriteModifiers(destructorDeclaration.ModifierTokens);
+			WriteToken(DestructorDeclaration.TildeRole);
+			TypeDeclaration type = destructorDeclaration.Parent as TypeDeclaration;
+			if (type != null && type.Name != destructorDeclaration.Name)
+				WriteIdentifier((Identifier)type.NameToken.Clone());
+			else
+				WriteIdentifier(destructorDeclaration.NameToken);
+			Space(policy.SpaceBeforeConstructorDeclarationParentheses);
+			LPar();
+			RPar();
+			WriteMethodBody(destructorDeclaration.Body);
+			EndNode(destructorDeclaration);
+		}
+		
+		public void VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
+		{
+			StartNode(enumMemberDeclaration);
+			WriteAttributes(enumMemberDeclaration.Attributes);
+			WriteModifiers(enumMemberDeclaration.ModifierTokens);
+			WriteIdentifier(enumMemberDeclaration.NameToken);
+			if (!enumMemberDeclaration.Initializer.IsNull) {
+				Space(policy.SpaceAroundAssignment);
+				WriteToken(Roles.Assign);
+				Space(policy.SpaceAroundAssignment);
+				enumMemberDeclaration.Initializer.AcceptVisitor(this);
+			}
+			EndNode(enumMemberDeclaration);
+		}
+		
+		public void VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			StartNode(eventDeclaration);
+			WriteAttributes(eventDeclaration.Attributes);
+			WriteModifiers(eventDeclaration.ModifierTokens);
+			WriteKeyword(EventDeclaration.EventKeywordRole);
+			eventDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WriteCommaSeparatedList(eventDeclaration.Variables);
+			Semicolon();
+			EndNode(eventDeclaration);
+		}
+		
+		public void VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration)
+		{
+			StartNode(customEventDeclaration);
+			WriteAttributes(customEventDeclaration.Attributes);
+			WriteModifiers(customEventDeclaration.ModifierTokens);
+			WriteKeyword(CustomEventDeclaration.EventKeywordRole);
+			customEventDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WritePrivateImplementationType(customEventDeclaration.PrivateImplementationType);
+			WriteIdentifier(customEventDeclaration.NameToken);
+			OpenBrace(policy.EventBraceStyle);
+			// output add/remove in their original order
+			foreach (AstNode node in customEventDeclaration.Children) {
+				if (node.Role == CustomEventDeclaration.AddAccessorRole || node.Role == CustomEventDeclaration.RemoveAccessorRole) {
+					node.AcceptVisitor(this);
+				}
+			}
+			CloseBrace(policy.EventBraceStyle);
+			NewLine();
+			EndNode(customEventDeclaration);
+		}
+		
+		public void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			StartNode(fieldDeclaration);
+			WriteAttributes(fieldDeclaration.Attributes);
+			WriteModifiers(fieldDeclaration.ModifierTokens);
+			fieldDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WriteCommaSeparatedList(fieldDeclaration.Variables);
+			Semicolon();
+			EndNode(fieldDeclaration);
+		}
+		
+		public void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			StartNode(fixedFieldDeclaration);
+			WriteAttributes(fixedFieldDeclaration.Attributes);
+			WriteModifiers(fixedFieldDeclaration.ModifierTokens);
+			WriteKeyword(FixedFieldDeclaration.FixedKeywordRole);
+			Space();
+			fixedFieldDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WriteCommaSeparatedList(fixedFieldDeclaration.Variables);
+			Semicolon();
+			EndNode(fixedFieldDeclaration);
+		}
+		
+		public void VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
+		{
+			StartNode(fixedVariableInitializer);
+			WriteIdentifier(fixedVariableInitializer.NameToken);
+			if (!fixedVariableInitializer.CountExpression.IsNull) {
+				WriteToken(Roles.LBracket);
+				Space(policy.SpacesWithinBrackets);
+				fixedVariableInitializer.CountExpression.AcceptVisitor(this);
+				Space(policy.SpacesWithinBrackets);
+				WriteToken(Roles.RBracket);
+			}
+			EndNode(fixedVariableInitializer);
+		}
+		
+		public void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			StartNode(indexerDeclaration);
+			WriteAttributes(indexerDeclaration.Attributes);
+			WriteModifiers(indexerDeclaration.ModifierTokens);
+			indexerDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WritePrivateImplementationType(indexerDeclaration.PrivateImplementationType);
+			WriteKeyword(IndexerDeclaration.ThisKeywordRole);
+			Space(policy.SpaceBeforeMethodDeclarationParentheses);
+			WriteCommaSeparatedListInBrackets(indexerDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			OpenBrace(policy.PropertyBraceStyle);
+			// output get/set in their original order
+			foreach (AstNode node in indexerDeclaration.Children) {
+				if (node.Role == IndexerDeclaration.GetterRole || node.Role == IndexerDeclaration.SetterRole) {
+					node.AcceptVisitor(this);
+				}
+			}
+			CloseBrace(policy.PropertyBraceStyle);
+			NewLine();
+			EndNode(indexerDeclaration);
+		}
+		
+		public void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			StartNode(methodDeclaration);
+			WriteAttributes(methodDeclaration.Attributes);
+			WriteModifiers(methodDeclaration.ModifierTokens);
+			methodDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WritePrivateImplementationType(methodDeclaration.PrivateImplementationType);
+			WriteIdentifier(methodDeclaration.NameToken);
+			WriteTypeParameters(methodDeclaration.TypeParameters);
+			Space(policy.SpaceBeforeMethodDeclarationParentheses);
+			WriteCommaSeparatedListInParenthesis(methodDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			foreach (Constraint constraint in methodDeclaration.Constraints) {
+				constraint.AcceptVisitor(this);
+			}
+			WriteMethodBody(methodDeclaration.Body);
+			EndNode(methodDeclaration);
+		}
+		
+		public void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+		{
+			StartNode(operatorDeclaration);
+			WriteAttributes(operatorDeclaration.Attributes);
+			WriteModifiers(operatorDeclaration.ModifierTokens);
+			if (operatorDeclaration.OperatorType == OperatorType.Explicit) {
+				WriteKeyword(OperatorDeclaration.ExplicitRole);
+			} else if (operatorDeclaration.OperatorType == OperatorType.Implicit) {
+				WriteKeyword(OperatorDeclaration.ImplicitRole);
+			} else {
+				operatorDeclaration.ReturnType.AcceptVisitor(this);
+			}
+			WriteKeyword(OperatorDeclaration.OperatorKeywordRole);
+			Space();
+			if (operatorDeclaration.OperatorType == OperatorType.Explicit
+			    || operatorDeclaration.OperatorType == OperatorType.Implicit) {
+				operatorDeclaration.ReturnType.AcceptVisitor(this);
+			} else {
+				WriteToken(OperatorDeclaration.GetToken(operatorDeclaration.OperatorType), OperatorDeclaration.GetRole(operatorDeclaration.OperatorType));
+			}
+			Space(policy.SpaceBeforeMethodDeclarationParentheses);
+			WriteCommaSeparatedListInParenthesis(operatorDeclaration.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+			WriteMethodBody(operatorDeclaration.Body);
+			EndNode(operatorDeclaration);
+		}
+		
+		public void VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			StartNode(parameterDeclaration);
+			WriteAttributes(parameterDeclaration.Attributes);
+			switch (parameterDeclaration.ParameterModifier) {
+				case ParameterModifier.Ref:
+					WriteKeyword(ParameterDeclaration.RefModifierRole);
+					break;
+				case ParameterModifier.Out:
+					WriteKeyword(ParameterDeclaration.OutModifierRole);
+					break;
+				case ParameterModifier.Params:
+					WriteKeyword(ParameterDeclaration.ParamsModifierRole);
+					break;
+				case ParameterModifier.This:
+					WriteKeyword(ParameterDeclaration.ThisModifierRole);
+					break;
+			}
+			parameterDeclaration.Type.AcceptVisitor(this);
+			if (!parameterDeclaration.Type.IsNull && !string.IsNullOrEmpty(parameterDeclaration.Name)) {
+				Space();
+			}
+			if (!string.IsNullOrEmpty(parameterDeclaration.Name)) {
+				WriteIdentifier(parameterDeclaration.NameToken);
+			}
+			if (!parameterDeclaration.DefaultExpression.IsNull) {
+				Space(policy.SpaceAroundAssignment);
+				WriteToken(Roles.Assign);
+				Space(policy.SpaceAroundAssignment);
+				parameterDeclaration.DefaultExpression.AcceptVisitor(this);
+			}
+			EndNode(parameterDeclaration);
+		}
+		
+		public void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			StartNode(propertyDeclaration);
+			WriteAttributes(propertyDeclaration.Attributes);
+			WriteModifiers(propertyDeclaration.ModifierTokens);
+			propertyDeclaration.ReturnType.AcceptVisitor(this);
+			Space();
+			WritePrivateImplementationType(propertyDeclaration.PrivateImplementationType);
+			WriteIdentifier(propertyDeclaration.NameToken);
+			OpenBrace(policy.PropertyBraceStyle);
+			// output get/set in their original order
+			foreach (AstNode node in propertyDeclaration.Children) {
+				if (node.Role == IndexerDeclaration.GetterRole || node.Role == IndexerDeclaration.SetterRole) {
+					node.AcceptVisitor(this);
+				}
+			}
+			CloseBrace(policy.PropertyBraceStyle);
+			NewLine();
+			EndNode(propertyDeclaration);
+		}
+
+		#endregion
+		
+		#region Other nodes
+		public void VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			StartNode(variableInitializer);
+			WriteIdentifier(variableInitializer.NameToken);
+			if (!variableInitializer.Initializer.IsNull) {
+				Space(policy.SpaceAroundAssignment);
+				WriteToken(Roles.Assign);
+				Space(policy.SpaceAroundAssignment);
+				variableInitializer.Initializer.AcceptVisitor(this);
+			}
+			EndNode(variableInitializer);
+		}
+
+		void MaybeNewLinesAfterUsings(AstNode node)
+		{
+			var nextSibling = node.NextSibling;
+			while (nextSibling is WhitespaceNode || nextSibling is NewLineNode)
+				nextSibling = nextSibling.NextSibling;
+
+			if ((node is UsingDeclaration || node is UsingAliasDeclaration) && !(nextSibling is UsingDeclaration || nextSibling is UsingAliasDeclaration)) {
+				for (int i = 0; i < policy.MinimumBlankLinesAfterUsings; i++)
+					NewLine();
+			}
+		}
+		
+		public void VisitSyntaxTree(SyntaxTree syntaxTree)
+		{
+			// don't do node tracking as we visit all children directly
+			foreach (AstNode node in syntaxTree.Children) {
+				node.AcceptVisitor(this);
+				MaybeNewLinesAfterUsings(node);
+			}
+		}
+		
+		public void VisitSimpleType(SimpleType simpleType)
+		{
+			StartNode(simpleType);
+			WriteIdentifier(simpleType.IdentifierToken);
+			WriteTypeArguments(simpleType.TypeArguments);
+			EndNode(simpleType);
+		}
+		
+		public void VisitMemberType(MemberType memberType)
+		{
+			StartNode(memberType);
+			memberType.Target.AcceptVisitor(this);
+			if (memberType.IsDoubleColon) {
+				WriteToken(Roles.DoubleColon);
+			} else {
+				WriteToken(Roles.Dot);
+			}
+			WriteIdentifier(memberType.MemberNameToken);
+			WriteTypeArguments(memberType.TypeArguments);
+			EndNode(memberType);
+		}
+		
+		public void VisitComposedType(ComposedType composedType)
+		{
+			StartNode(composedType);
+			composedType.BaseType.AcceptVisitor(this);
+			if (composedType.HasNullableSpecifier) {
+				WriteToken(ComposedType.NullableRole);
+			}
+			for (int i = 0; i < composedType.PointerRank; i++) {
+				WriteToken(ComposedType.PointerRole);
+			}
+			foreach (var node in composedType.ArraySpecifiers) {
+				node.AcceptVisitor(this);
+			}
+			EndNode(composedType);
+		}
+		
+		public void VisitArraySpecifier(ArraySpecifier arraySpecifier)
+		{
+			StartNode(arraySpecifier);
+			WriteToken(Roles.LBracket);
+			foreach (var comma in arraySpecifier.GetChildrenByRole(Roles.Comma)) {
+				writer.WriteToken(Roles.Comma, ",");
+			}
+			WriteToken(Roles.RBracket);
+			EndNode(arraySpecifier);
+		}
+		
+		public void VisitPrimitiveType(PrimitiveType primitiveType)
+		{
+			StartNode(primitiveType);
+			writer.WritePrimitiveType(primitiveType.Keyword);
+			EndNode(primitiveType);
+		}
+		
+		public void VisitComment(Comment comment)
+		{
+			writer.StartNode(comment);
+			writer.WriteComment(comment.CommentType, comment.Content);
+			writer.EndNode(comment);
+		}
+
+		public void VisitNewLine(NewLineNode newLineNode)
+		{
+//			formatter.StartNode(newLineNode);
+//			formatter.NewLine();
+//			formatter.EndNode(newLineNode);
+		}
+
+		public void VisitWhitespace(WhitespaceNode whitespaceNode)
+		{
+			// unused
+		}
+
+		public void VisitText(TextNode textNode)
+		{
+			// unused
+		}
+
+		public void VisitPreProcessorDirective(PreProcessorDirective preProcessorDirective)
+		{
+			writer.StartNode(preProcessorDirective);
+			writer.WritePreProcessorDirective(preProcessorDirective.Type, preProcessorDirective.Argument);
+			writer.EndNode(preProcessorDirective);
+		}
+		
+		public void VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
+		{
+			StartNode(typeParameterDeclaration);
+			WriteAttributes(typeParameterDeclaration.Attributes);
+			switch (typeParameterDeclaration.Variance) {
+				case VarianceModifier.Invariant:
+					break;
+				case VarianceModifier.Covariant:
+					WriteKeyword(TypeParameterDeclaration.OutVarianceKeywordRole);
+					break;
+				case VarianceModifier.Contravariant:
+					WriteKeyword(TypeParameterDeclaration.InVarianceKeywordRole);
+					break;
+				default:
+					throw new NotSupportedException ("Invalid value for VarianceModifier");
+			}
+			WriteIdentifier(typeParameterDeclaration.NameToken);
+			EndNode(typeParameterDeclaration);
+		}
+		
+		public void VisitConstraint(Constraint constraint)
+		{
+			StartNode(constraint);
+			Space();
+			WriteKeyword(Roles.WhereKeyword);
+			constraint.TypeParameter.AcceptVisitor(this);
+			Space();
+			WriteToken(Roles.Colon);
+			Space();
+			WriteCommaSeparatedList(constraint.BaseTypes);
+			EndNode(constraint);
+		}
+		
+		public void VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode)
+		{
+			CSharpModifierToken mod = cSharpTokenNode as CSharpModifierToken;
+			if (mod != null) {
+				// ITokenWriter assumes that each node processed between a
+				// StartNode(parentNode)-EndNode(parentNode)-pair is a child of parentNode.
+				WriteKeyword(CSharpModifierToken.GetModifierName(mod.Modifier), cSharpTokenNode.Role);
+			} else {
+				throw new NotSupportedException ("Should never visit individual tokens");
+			}
+		}
+		
+		public void VisitIdentifier(Identifier identifier)
+		{
+			// Do not call StartNode and EndNode for Identifier, because they are handled by the ITokenWriter.
+			// ITokenWriter assumes that each node processed between a
+			// StartNode(parentNode)-EndNode(parentNode)-pair is a child of parentNode.
+			WriteIdentifier(identifier);
+		}
+
+		void IAstVisitor.VisitNullNode(AstNode nullNode)
+		{
+		}
+
+		void IAstVisitor.VisitErrorNode(AstNode errorNode)
+		{
+			StartNode(errorNode);
+			EndNode(errorNode);
+		}
+		#endregion
+
+		#region Pattern Nodes
+		public void VisitPatternPlaceholder(AstNode placeholder, PatternMatching.Pattern pattern)
+		{
+			StartNode(placeholder);
+			VisitNodeInPattern(pattern);
+			EndNode(placeholder);
+		}
+		
+		void VisitAnyNode(AnyNode anyNode)
+		{
+			if (!string.IsNullOrEmpty(anyNode.GroupName)) {
+				WriteIdentifier(anyNode.GroupName);
+				WriteToken(Roles.Colon);
+			}
+		}
+		
+		void VisitBackreference(Backreference backreference)
+		{
+			WriteKeyword("backreference");
+			LPar();
+			WriteIdentifier(backreference.ReferencedGroupName);
+			RPar();
+		}
+		
+		void VisitIdentifierExpressionBackreference(IdentifierExpressionBackreference identifierExpressionBackreference)
+		{
+			WriteKeyword("identifierBackreference");
+			LPar();
+			WriteIdentifier(identifierExpressionBackreference.ReferencedGroupName);
+			RPar();
+		}
+		
+		void VisitChoice(Choice choice)
+		{
+			WriteKeyword("choice");
+			Space();
+			LPar();
+			NewLine();
+			writer.Indent();
+			foreach (INode alternative in choice) {
+				VisitNodeInPattern(alternative);
+				if (alternative != choice.Last()) {
+					WriteToken(Roles.Comma);
+				}
+				NewLine();
+			}
+			writer.Unindent();
+			RPar();
+		}
+		
+		void VisitNamedNode(NamedNode namedNode)
+		{
+			if (!string.IsNullOrEmpty(namedNode.GroupName)) {
+				WriteIdentifier(namedNode.GroupName);
+				WriteToken(Roles.Colon);
+			}
+			VisitNodeInPattern(namedNode.ChildNode);
+		}
+		
+		void VisitRepeat(Repeat repeat)
+		{
+			WriteKeyword("repeat");
+			LPar();
+			if (repeat.MinCount != 0 || repeat.MaxCount != int.MaxValue) {
+				WriteIdentifier(repeat.MinCount.ToString());
+				WriteToken(Roles.Comma);
+				WriteIdentifier(repeat.MaxCount.ToString());
+				WriteToken(Roles.Comma);
+			}
+			VisitNodeInPattern(repeat.ChildNode);
+			RPar();
+		}
+		
+		void VisitOptionalNode(OptionalNode optionalNode)
+		{
+			WriteKeyword("optional");
+			LPar();
+			VisitNodeInPattern(optionalNode.ChildNode);
+			RPar();
+		}
+		
+		void VisitNodeInPattern(INode childNode)
+		{
+			if (childNode is AstNode) {
+				((AstNode)childNode).AcceptVisitor(this);
+			} else if (childNode is IdentifierExpressionBackreference) {
+				VisitIdentifierExpressionBackreference((IdentifierExpressionBackreference)childNode);
+			} else if (childNode is Choice) {
+				VisitChoice((Choice)childNode);
+			} else if (childNode is AnyNode) {
+				VisitAnyNode((AnyNode)childNode);
+			} else if (childNode is Backreference) {
+				VisitBackreference((Backreference)childNode);
+			} else if (childNode is NamedNode) {
+				VisitNamedNode((NamedNode)childNode);
+			} else if (childNode is OptionalNode) {
+				VisitOptionalNode((OptionalNode)childNode);
+			} else if (childNode is Repeat) {
+				VisitRepeat((Repeat)childNode);
+			} else {
+				TextWriterTokenWriter.PrintPrimitiveValue(childNode);
+			}
+		}
+		#endregion
+		
+		#region Documentation Reference
+		public void VisitDocumentationReference(DocumentationReference documentationReference)
+		{
+			StartNode(documentationReference);
+			if (!documentationReference.DeclaringType.IsNull) {
+				documentationReference.DeclaringType.AcceptVisitor(this);
+				if (documentationReference.SymbolKind != SymbolKind.TypeDefinition) {
+					WriteToken(Roles.Dot);
+				}
+			}
+			switch (documentationReference.SymbolKind) {
+				case SymbolKind.TypeDefinition:
+					// we already printed the DeclaringType
+					break;
+				case SymbolKind.Indexer:
+					WriteKeyword(IndexerDeclaration.ThisKeywordRole);
+					break;
+				case SymbolKind.Operator:
+					var opType = documentationReference.OperatorType;
+					if (opType == OperatorType.Explicit) {
+						WriteKeyword(OperatorDeclaration.ExplicitRole);
+					} else if (opType == OperatorType.Implicit) {
+						WriteKeyword(OperatorDeclaration.ImplicitRole);
+					}
+					WriteKeyword(OperatorDeclaration.OperatorKeywordRole);
+					Space();
+					if (opType == OperatorType.Explicit || opType == OperatorType.Implicit) {
+						documentationReference.ConversionOperatorReturnType.AcceptVisitor(this);
+					} else {
+						WriteToken(OperatorDeclaration.GetToken(opType), OperatorDeclaration.GetRole(opType));
+					}
+					break;
+				default:
+					WriteIdentifier(documentationReference.GetChildByRole(Roles.Identifier));
+					break;
+			}
+			WriteTypeArguments(documentationReference.TypeArguments);
+			if (documentationReference.HasParameterList) {
+				Space(policy.SpaceBeforeMethodDeclarationParentheses);
+				if (documentationReference.SymbolKind == SymbolKind.Indexer) {
+					WriteCommaSeparatedListInBrackets(documentationReference.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+				} else {
+					WriteCommaSeparatedListInParenthesis(documentationReference.Parameters, policy.SpaceWithinMethodDeclarationParentheses);
+				}
+			}
+			EndNode(documentationReference);
+		}
+		#endregion
+		
+		/// <summary>
+		/// Converts special characters to escape sequences within the given string.
+		/// </summary>
+		public static string ConvertString(string text)
+		{
+			return TextWriterTokenWriter.ConvertString(text);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CodeDomConvertVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CodeDomConvertVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/CodeDomConvertVisitor.cs	(revision 11807)
@@ -0,0 +1,1429 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.CodeDom;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.PatternMatching;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Converts from C# AST to CodeDom.
+	/// </summary>
+	/// <remarks>
+	/// The conversion is intended for use in the SharpDevelop forms designer.
+	/// </remarks>
+	public class CodeDomConvertVisitor : IAstVisitor<CodeObject>
+	{
+		CSharpAstResolver resolver;
+		
+		/// <summary>
+		/// Gets/Sets whether the visitor should convert short type names into
+		/// fully qualified type names.
+		/// The default is <c>false</c>.
+		/// </summary>
+		public bool UseFullyQualifiedTypeNames { get; set; }
+		
+		/// <summary>
+		/// Gets whether the visitor is allowed to produce snippet nodes for
+		/// code that cannot be converted.
+		/// The default is <c>true</c>. If this property is set to <c>false</c>,
+		/// unconvertible code will throw a NotSupportedException.
+		/// </summary>
+		public bool AllowSnippetNodes { get; set; }
+		
+		public CodeDomConvertVisitor()
+		{
+			this.AllowSnippetNodes = true;
+		}
+		
+		/// <summary>
+		/// Converts a syntax tree to CodeDom.
+		/// </summary>
+		/// <param name="syntaxTree">The input syntax tree.</param>
+		/// <param name="compilation">The current compilation.</param>
+		/// <param name="unresolvedFile">CSharpUnresolvedFile, used for resolving.</param>
+		/// <returns>Converted CodeCompileUnit</returns>
+		/// <remarks>
+		/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
+		/// </remarks>
+		public CodeCompileUnit Convert(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile)
+		{
+			if (syntaxTree == null)
+				throw new ArgumentNullException("syntaxTree");
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			
+			CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
+			return (CodeCompileUnit)Convert(syntaxTree, resolver);
+		}
+		
+		/// <summary>
+		/// Converts a C# AST node to CodeDom.
+		/// </summary>
+		/// <param name="node">The input node.</param>
+		/// <param name="resolver">The AST resolver.</param>
+		/// <returns>The node converted into CodeDom</returns>
+		/// <remarks>
+		/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
+		/// </remarks>
+		public CodeObject Convert(AstNode node, CSharpAstResolver resolver)
+		{
+			if (node == null)
+				throw new ArgumentNullException("node");
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			try {
+				this.resolver = resolver;
+				return node.AcceptVisitor(this);
+			} finally {
+				this.resolver = null;
+			}
+		}
+		
+		ResolveResult Resolve(AstNode node)
+		{
+			if (resolver == null)
+				return ErrorResolveResult.UnknownError;
+			else
+				return resolver.Resolve(node);
+		}
+		
+		CodeExpression Convert(Expression expr)
+		{
+			return (CodeExpression)expr.AcceptVisitor(this);
+		}
+		
+		CodeExpression[] Convert(IEnumerable<Expression> expressions)
+		{
+			List<CodeExpression> result = new List<CodeExpression>();
+			foreach (Expression expr in expressions) {
+				CodeExpression e = Convert(expr);
+				if (e != null)
+					result.Add(e);
+			}
+			return result.ToArray();
+		}
+		
+		CodeTypeReference Convert(AstType type)
+		{
+			return (CodeTypeReference)type.AcceptVisitor(this);
+		}
+		
+		CodeTypeReference[] Convert(IEnumerable<AstType> types)
+		{
+			List<CodeTypeReference> result = new List<CodeTypeReference>();
+			foreach (AstType type in types) {
+				CodeTypeReference e = Convert(type);
+				if (e != null)
+					result.Add(e);
+			}
+			return result.ToArray();
+		}
+		
+		public CodeTypeReference Convert(IType type)
+		{
+			if (type.Kind == TypeKind.Array) {
+				ArrayType a = (ArrayType)type;
+				return new CodeTypeReference(Convert(a.ElementType), a.Dimensions);
+			} else if (type is ParameterizedType) {
+				var pt = (ParameterizedType)type;
+				return new CodeTypeReference(pt.GetDefinition().ReflectionName, pt.TypeArguments.Select(Convert).ToArray());
+			} else {
+				return new CodeTypeReference(type.ReflectionName);
+			}
+		}
+		
+		CodeStatement Convert(Statement stmt)
+		{
+			return (CodeStatement)stmt.AcceptVisitor(this);
+		}
+		
+		CodeStatement[] ConvertBlock(BlockStatement block)
+		{
+			List<CodeStatement> result = new List<CodeStatement>();
+			foreach (Statement stmt in block.Statements) {
+				if (stmt is EmptyStatement)
+					continue;
+				CodeStatement s = Convert(stmt);
+				if (s != null)
+					result.Add(s);
+			}
+			return result.ToArray();
+		}
+		
+		CodeStatement[] ConvertEmbeddedStatement(Statement embeddedStatement)
+		{
+			BlockStatement block = embeddedStatement as BlockStatement;
+			if (block != null) {
+				return ConvertBlock(block);
+			} else if (embeddedStatement is EmptyStatement) {
+				return new CodeStatement[0];
+			}
+			CodeStatement s = Convert(embeddedStatement);
+			if (s != null)
+				return new CodeStatement[] { s };
+			else
+				return new CodeStatement[0];
+		}
+		
+		string MakeSnippet(AstNode node)
+		{
+			if (!AllowSnippetNodes)
+				throw new NotSupportedException();
+			StringWriter w = new StringWriter();
+			CSharpOutputVisitor v = new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateMono ());
+			node.AcceptVisitor(v);
+			return w.ToString();
+		}
+		
+		/// <summary>
+		/// Converts an expression by storing it as C# snippet.
+		/// This is used for expressions that cannot be represented in CodeDom.
+		/// </summary>
+		CodeSnippetExpression MakeSnippetExpression(Expression expr)
+		{
+			return new CodeSnippetExpression(MakeSnippet(expr));
+		}
+		
+		CodeSnippetStatement MakeSnippetStatement(Statement stmt)
+		{
+			return new CodeSnippetStatement(MakeSnippet(stmt));
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitNullNode(AstNode nullNode)
+		{
+			return null;
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitErrorNode(AstNode errorNode)
+		{
+			return null;
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
+		{
+			return MakeSnippetExpression(anonymousMethodExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
+		{
+			return MakeSnippetExpression(undocumentedExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
+		{
+			CodeArrayCreateExpression ace = new CodeArrayCreateExpression();
+			int dimensions = arrayCreateExpression.Arguments.Count;
+			int nestingDepth = arrayCreateExpression.AdditionalArraySpecifiers.Count;
+			if (dimensions > 0)
+				nestingDepth++;
+			if (nestingDepth > 1 || dimensions > 1) {
+				// CodeDom does not support jagged or multi-dimensional arrays
+				return MakeSnippetExpression(arrayCreateExpression);
+			}
+			if (arrayCreateExpression.Type.IsNull) {
+				ace.CreateType = Convert(Resolve(arrayCreateExpression).Type);
+			} else {
+				ace.CreateType = Convert(arrayCreateExpression.Type);
+			}
+			if (arrayCreateExpression.Arguments.Count == 1) {
+				ace.SizeExpression = Convert(arrayCreateExpression.Arguments.Single());
+			}
+			ace.Initializers.AddRange(Convert(arrayCreateExpression.Initializer.Elements));
+			return ace;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
+		{
+			// Array initializers should be handled by the parent node
+			return MakeSnippetExpression(arrayInitializerExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitAsExpression(AsExpression asExpression)
+		{
+			return MakeSnippetExpression(asExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+		{
+			// assignments are only supported as statements, not as expressions
+			return MakeSnippetExpression(assignmentExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
+		{
+			return new CodeBaseReferenceExpression();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+		{
+			CodeBinaryOperatorType op;
+			switch (binaryOperatorExpression.Operator) {
+				case BinaryOperatorType.BitwiseAnd:
+					op = CodeBinaryOperatorType.BitwiseAnd;
+					break;
+				case BinaryOperatorType.BitwiseOr:
+					op = CodeBinaryOperatorType.BitwiseOr;
+					break;
+				case BinaryOperatorType.ConditionalAnd:
+					op = CodeBinaryOperatorType.BooleanAnd;
+					break;
+				case BinaryOperatorType.ConditionalOr:
+					op = CodeBinaryOperatorType.BooleanOr;
+					break;
+				case BinaryOperatorType.GreaterThan:
+					op = CodeBinaryOperatorType.GreaterThan;
+					break;
+				case BinaryOperatorType.GreaterThanOrEqual:
+					op = CodeBinaryOperatorType.GreaterThanOrEqual;
+					break;
+				case BinaryOperatorType.LessThan:
+					op = CodeBinaryOperatorType.LessThan;
+					break;
+				case BinaryOperatorType.LessThanOrEqual:
+					op = CodeBinaryOperatorType.LessThanOrEqual;
+					break;
+				case BinaryOperatorType.Add:
+					op = CodeBinaryOperatorType.Add;
+					break;
+				case BinaryOperatorType.Subtract:
+					op = CodeBinaryOperatorType.Subtract;
+					break;
+				case BinaryOperatorType.Multiply:
+					op = CodeBinaryOperatorType.Multiply;
+					break;
+				case BinaryOperatorType.Divide:
+					op = CodeBinaryOperatorType.Divide;
+					break;
+				case BinaryOperatorType.Modulus:
+					op = CodeBinaryOperatorType.Modulus;
+					break;
+				case BinaryOperatorType.Equality:
+				case BinaryOperatorType.InEquality:
+					OperatorResolveResult rr = Resolve(binaryOperatorExpression) as OperatorResolveResult;
+					if (rr != null && rr.GetChildResults().Any(cr => cr.Type.IsReferenceType == true)) {
+						if (binaryOperatorExpression.Operator == BinaryOperatorType.Equality)
+							op = CodeBinaryOperatorType.IdentityEquality;
+						else
+							op = CodeBinaryOperatorType.IdentityInequality;
+					} else {
+						if (binaryOperatorExpression.Operator == BinaryOperatorType.Equality) {
+							op = CodeBinaryOperatorType.ValueEquality;
+						} else {
+							// CodeDom is retarded and does not support ValueInequality, so we'll simulate it using
+							// ValueEquality and Not... but CodeDom doesn't have Not either, so we use
+							// '(a == b) == false'
+							return new CodeBinaryOperatorExpression(
+								new CodeBinaryOperatorExpression(
+									Convert(binaryOperatorExpression.Left),
+									CodeBinaryOperatorType.ValueEquality,
+									Convert(binaryOperatorExpression.Right)
+								),
+								CodeBinaryOperatorType.ValueEquality,
+								new CodePrimitiveExpression(false)
+							);
+						}
+					}
+					break;
+				default:
+					// not supported: xor, shift, null coalescing
+					return MakeSnippetExpression(binaryOperatorExpression);
+			}
+			return new CodeBinaryOperatorExpression(Convert(binaryOperatorExpression.Left), op, Convert(binaryOperatorExpression.Right));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCastExpression(CastExpression castExpression)
+		{
+			return new CodeCastExpression(Convert(castExpression.Type), Convert(castExpression.Expression));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCheckedExpression(CheckedExpression checkedExpression)
+		{
+			return MakeSnippetExpression(checkedExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitConditionalExpression(ConditionalExpression conditionalExpression)
+		{
+			return MakeSnippetExpression(conditionalExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
+		{
+			return new CodeDefaultValueExpression(Convert(defaultValueExpression.Type));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitDirectionExpression(DirectionExpression directionExpression)
+		{
+			System.CodeDom.FieldDirection direction;
+			if (directionExpression.FieldDirection == FieldDirection.Out) {
+				direction = System.CodeDom.FieldDirection.Out;
+			} else {
+				direction = System.CodeDom.FieldDirection.Ref;
+			}
+			return new CodeDirectionExpression(direction, Convert(directionExpression.Expression));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitIdentifierExpression(IdentifierExpression identifierExpression)
+		{
+			ResolveResult rr = Resolve(identifierExpression);
+			LocalResolveResult lrr = rr as LocalResolveResult;
+			if (lrr != null && lrr.IsParameter) {
+				if (lrr.Variable.Name == "value" && identifierExpression.Ancestors.Any(a => a is Accessor)) {
+					return new CodePropertySetValueReferenceExpression();
+				} else {
+					return new CodeArgumentReferenceExpression(lrr.Variable.Name);
+				}
+			}
+			MemberResolveResult mrr = rr as MemberResolveResult;
+			if (mrr != null) {
+				return HandleMemberReference(null, identifierExpression.Identifier, identifierExpression.TypeArguments, mrr);
+			}
+			TypeResolveResult trr = rr as TypeResolveResult;
+			if (trr != null) {
+				CodeTypeReference typeRef;
+				if (UseFullyQualifiedTypeNames) {
+					typeRef = Convert(trr.Type);
+				} else {
+					typeRef = new CodeTypeReference(identifierExpression.Identifier);
+					typeRef.TypeArguments.AddRange(Convert(identifierExpression.TypeArguments));
+				}
+				return new CodeTypeReferenceExpression(typeRef);
+			}
+			MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult;
+			if (mgrr != null || identifierExpression.TypeArguments.Any()) {
+				return new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), identifierExpression.Identifier, Convert(identifierExpression.TypeArguments));
+			}
+			return new CodeVariableReferenceExpression(identifierExpression.Identifier);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitIndexerExpression(IndexerExpression indexerExpression)
+		{
+			if (Resolve(indexerExpression) is ArrayAccessResolveResult)
+				return new CodeArrayIndexerExpression(Convert(indexerExpression.Target), Convert(indexerExpression.Arguments));
+			else
+				return new CodeIndexerExpression(Convert(indexerExpression.Target), Convert(indexerExpression.Arguments));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			MemberResolveResult rr = Resolve(invocationExpression) as MemberResolveResult;
+			CSharpInvocationResolveResult csRR = rr as CSharpInvocationResolveResult;
+			if (csRR != null && csRR.IsDelegateInvocation) {
+				return new CodeDelegateInvokeExpression(Convert(invocationExpression.Target), Convert(invocationExpression.Arguments));
+			}
+			
+			Expression methodExpr = invocationExpression.Target;
+			while (methodExpr is ParenthesizedExpression)
+				methodExpr = ((ParenthesizedExpression)methodExpr).Expression;
+			CodeMethodReferenceExpression mr = null;
+			MemberReferenceExpression mre = methodExpr as MemberReferenceExpression;
+			if (mre != null) {
+				mr = new CodeMethodReferenceExpression(Convert(mre.Target), mre.MemberName, Convert(mre.TypeArguments));
+			}
+			IdentifierExpression id = methodExpr as IdentifierExpression;
+			if (id != null) {
+				CodeExpression target;
+				if (rr != null && rr.Member.IsStatic)
+					target = new CodeTypeReferenceExpression(Convert(rr.Member.DeclaringType));
+				else
+					target = new CodeThisReferenceExpression();
+				
+				mr = new CodeMethodReferenceExpression(target, id.Identifier, Convert(id.TypeArguments));
+			}
+			if (mr != null)
+				return new CodeMethodInvokeExpression(mr, Convert(invocationExpression.Arguments));
+			else
+				return MakeSnippetExpression(invocationExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitIsExpression(IsExpression isExpression)
+		{
+			return MakeSnippetExpression(isExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitLambdaExpression(LambdaExpression lambdaExpression)
+		{
+			return MakeSnippetExpression(lambdaExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			CodeExpression target = Convert(memberReferenceExpression.Target);
+			ResolveResult rr = Resolve(memberReferenceExpression);
+			MemberResolveResult mrr = rr as MemberResolveResult;
+			TypeResolveResult trr = rr as TypeResolveResult;
+			if (mrr != null) {
+				return HandleMemberReference(target, memberReferenceExpression.MemberName, memberReferenceExpression.TypeArguments, mrr);
+			} else if (trr != null) {
+				return new CodeTypeReferenceExpression(Convert(trr.Type));
+			} else {
+				if (memberReferenceExpression.TypeArguments.Any() || rr is MethodGroupResolveResult) {
+					return new CodeMethodReferenceExpression(target, memberReferenceExpression.MemberName, Convert(memberReferenceExpression.TypeArguments));
+				} else {
+					return new CodePropertyReferenceExpression(target, memberReferenceExpression.MemberName);
+				}
+			}
+		}
+		
+		CodeExpression HandleMemberReference(CodeExpression target, string identifier, AstNodeCollection<AstType> typeArguments, MemberResolveResult mrr)
+		{
+			if (target == null) {
+				if (mrr.Member.IsStatic)
+					target = new CodeTypeReferenceExpression(Convert(mrr.Member.DeclaringType));
+				else
+					target = new CodeThisReferenceExpression();
+			}
+			if (mrr.Member is IField) {
+				return new CodeFieldReferenceExpression(target, identifier);
+			} else if (mrr.Member is IMethod) {
+				return new CodeMethodReferenceExpression(target, identifier, Convert(typeArguments));
+			} else if (mrr.Member is IEvent) {
+				return new CodeEventReferenceExpression(target, identifier);
+			} else {
+				return new CodePropertyReferenceExpression(target, identifier);
+			}
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
+		{
+			return MakeSnippetExpression(namedArgumentExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitNamedExpression(NamedExpression namedExpression)
+		{
+			return MakeSnippetExpression(namedExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
+		{
+			return new CodePrimitiveExpression(null);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
+		{
+			if (!objectCreateExpression.Initializer.IsNull)
+				return MakeSnippetExpression(objectCreateExpression);
+			return new CodeObjectCreateExpression(Convert(objectCreateExpression.Type), Convert(objectCreateExpression.Arguments));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+		{
+			return MakeSnippetExpression(anonymousTypeCreateExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
+		{
+			// CodeDom generators will insert parentheses where necessary
+			return Convert(parenthesizedExpression.Expression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
+		{
+			return MakeSnippetExpression(pointerReferenceExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+		{
+			return new CodePrimitiveExpression(primitiveExpression.Value);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
+		{
+			return MakeSnippetExpression(sizeOfExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
+		{
+			return MakeSnippetExpression(stackAllocExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
+		{
+			return new CodeThisReferenceExpression();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitTypeOfExpression(TypeOfExpression typeOfExpression)
+		{
+			return new CodeTypeOfExpression(Convert(typeOfExpression.Type));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
+		{
+			return new CodeTypeReferenceExpression(Convert(typeReferenceExpression.Type));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+		{
+			switch (unaryOperatorExpression.Operator) {
+				case UnaryOperatorType.Not:
+					return new CodeBinaryOperatorExpression(
+						Convert(unaryOperatorExpression.Expression),
+						CodeBinaryOperatorType.ValueEquality,
+						new CodePrimitiveExpression(false));
+				case UnaryOperatorType.Minus:
+					return new CodeBinaryOperatorExpression(
+						new CodePrimitiveExpression(0),
+						CodeBinaryOperatorType.Subtract,
+						Convert(unaryOperatorExpression.Expression));
+				case UnaryOperatorType.Plus:
+					return Convert(unaryOperatorExpression.Expression);
+				default:
+					return MakeSnippetExpression(unaryOperatorExpression);
+			}
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
+		{
+			return MakeSnippetExpression(uncheckedExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryExpression(QueryExpression queryExpression)
+		{
+			return MakeSnippetExpression(queryExpression);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryOrdering(QueryOrdering queryOrdering)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitAttribute(Attribute attribute)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitAttributeSection(AttributeSection attributeSection)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeAttributeDeclaration Convert(Attribute attribute)
+		{
+			var attr = new CodeAttributeDeclaration(Convert(attribute.Type));
+			foreach (Expression expr in attribute.Arguments) {
+				NamedExpression ne = expr as NamedExpression;
+				if (ne != null)
+					attr.Arguments.Add(new CodeAttributeArgument(ne.Name, Convert(ne.Expression)));
+				else
+					attr.Arguments.Add(new CodeAttributeArgument(Convert(expr)));
+			}
+			return attr;
+		}
+		
+		CodeAttributeDeclaration[] Convert(IEnumerable<AttributeSection> attributeSections)
+		{
+			List<CodeAttributeDeclaration> result = new List<CodeAttributeDeclaration>();
+			foreach (AttributeSection section in attributeSections) {
+				foreach (Attribute attr in section.Attributes) {
+					CodeAttributeDeclaration attrDecl = Convert(attr);
+					if (attrDecl != null)
+						result.Add(attrDecl);
+				}
+			}
+			return result.ToArray();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			CodeTypeDelegate d = new CodeTypeDelegate(delegateDeclaration.Name);
+			d.Attributes = ConvertMemberAttributes(delegateDeclaration.Modifiers, SymbolKind.TypeDefinition);
+			d.CustomAttributes.AddRange(Convert(delegateDeclaration.Attributes));
+			d.ReturnType = Convert(delegateDeclaration.ReturnType);
+			d.Parameters.AddRange(Convert(delegateDeclaration.Parameters));
+			d.TypeParameters.AddRange(ConvertTypeParameters(delegateDeclaration.TypeParameters, delegateDeclaration.Constraints));
+			return d;
+		}
+		
+		MemberAttributes ConvertMemberAttributes(Modifiers modifiers, SymbolKind symbolKind)
+		{
+			MemberAttributes a = 0;
+			if ((modifiers & Modifiers.Abstract) != 0)
+				a |= MemberAttributes.Abstract;
+			if ((modifiers & Modifiers.Sealed) != 0)
+				a |= MemberAttributes.Final;
+			if (symbolKind != SymbolKind.TypeDefinition && (modifiers & (Modifiers.Abstract | Modifiers.Override | Modifiers.Virtual)) == 0)
+				a |= MemberAttributes.Final;
+			if ((modifiers & Modifiers.Static) != 0)
+				a |= MemberAttributes.Static;
+			if ((modifiers & Modifiers.Override) != 0)
+				a |= MemberAttributes.Override;
+			if ((modifiers & Modifiers.Const) != 0)
+				a |= MemberAttributes.Const;
+			if ((modifiers & Modifiers.New) != 0)
+				a |= MemberAttributes.New;
+			
+			if ((modifiers & Modifiers.Public) != 0)
+				a |= MemberAttributes.Public;
+			else if ((modifiers & (Modifiers.Protected | Modifiers.Internal)) == (Modifiers.Protected | Modifiers.Internal))
+				a |= MemberAttributes.FamilyOrAssembly;
+			else if ((modifiers & Modifiers.Protected) != 0)
+				a |= MemberAttributes.Family;
+			else if ((modifiers & Modifiers.Internal) != 0)
+				a |= MemberAttributes.Assembly;
+			else if ((modifiers & Modifiers.Private) != 0)
+				a |= MemberAttributes.Private;
+			
+			return a;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+		{
+			CodeNamespace ns = new CodeNamespace(namespaceDeclaration.Name);
+			foreach (AstNode node in namespaceDeclaration.Members) {
+				CodeObject r = node.AcceptVisitor(this);
+				
+				CodeNamespaceImport import = r as CodeNamespaceImport;
+				if (import != null)
+					ns.Imports.Add(import);
+				
+				CodeTypeDeclaration typeDecl = r as CodeTypeDeclaration;
+				if (typeDecl != null)
+					ns.Types.Add(typeDecl);
+			}
+			return ns;
+		}
+		
+		Stack<CodeTypeDeclaration> typeStack = new Stack<CodeTypeDeclaration>();
+		
+		CodeObject IAstVisitor<CodeObject>.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			//bool isNestedType = typeStack.Count > 0;
+			CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(typeDeclaration.Name);
+			typeDecl.Attributes = ConvertMemberAttributes(typeDeclaration.Modifiers, SymbolKind.TypeDefinition);
+			typeDecl.CustomAttributes.AddRange(Convert(typeDeclaration.Attributes));
+			
+			switch (typeDeclaration.ClassType) {
+				case ClassType.Struct:
+					typeDecl.IsStruct = true;
+					break;
+				case ClassType.Interface:
+					typeDecl.IsInterface = true;
+					break;
+				case ClassType.Enum:
+					typeDecl.IsEnum = true;
+					break;
+				default:
+					typeDecl.IsClass = true;
+					break;
+			}
+			typeDecl.IsPartial = (typeDeclaration.Modifiers & Modifiers.Partial) == Modifiers.Partial;
+			
+			typeDecl.BaseTypes.AddRange(Convert(typeDeclaration.BaseTypes));
+			typeDecl.TypeParameters.AddRange(ConvertTypeParameters(typeDeclaration.TypeParameters, typeDeclaration.Constraints));
+			
+			typeStack.Push(typeDecl);
+			foreach (var member in typeDeclaration.Members) {
+				CodeTypeMember m = member.AcceptVisitor(this) as CodeTypeMember;
+				if (m != null)
+					typeDecl.Members.Add(m);
+			}
+			typeStack.Pop();
+			return typeDecl;
+		}
+		
+		void AddTypeMember(CodeTypeMember member)
+		{
+			if (typeStack.Count != 0)
+				typeStack.Peek().Members.Add(member);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUsingAliasDeclaration(UsingAliasDeclaration usingAliasDeclaration)
+		{
+			return new CodeSnippetTypeMember(MakeSnippet(usingAliasDeclaration));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUsingDeclaration(UsingDeclaration usingDeclaration)
+		{
+			return new CodeNamespaceImport(usingDeclaration.Namespace);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			return new CodeSnippetTypeMember(MakeSnippet(externAliasDeclaration));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitBlockStatement(BlockStatement blockStatement)
+		{
+			return new CodeConditionStatement(new CodePrimitiveExpression(true), ConvertBlock(blockStatement));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitBreakStatement(BreakStatement breakStatement)
+		{
+			return MakeSnippetStatement(breakStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCheckedStatement(CheckedStatement checkedStatement)
+		{
+			return MakeSnippetStatement(checkedStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitContinueStatement(ContinueStatement continueStatement)
+		{
+			return MakeSnippetStatement(continueStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitDoWhileStatement(DoWhileStatement doWhileStatement)
+		{
+			// do { } while (expr);
+			//
+			// emulate with:
+			//  for (bool _do = true; _do; _do = expr) {}
+			string varName = "_do" + doWhileStatement.Ancestors.OfType<DoWhileStatement>().Count();
+			return new CodeIterationStatement(
+				new CodeVariableDeclarationStatement(typeof(bool), varName, new CodePrimitiveExpression(true)),
+				new CodeVariableReferenceExpression(varName),
+				new CodeAssignStatement(new CodeVariableReferenceExpression(varName), Convert(doWhileStatement.Condition)),
+				ConvertEmbeddedStatement(doWhileStatement.EmbeddedStatement)
+			);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitEmptyStatement(EmptyStatement emptyStatement)
+		{
+			return EmptyStatement();
+		}
+		
+		CodeStatement EmptyStatement()
+		{
+			return new CodeExpressionStatement(new CodeObjectCreateExpression(new CodeTypeReference(typeof(object))));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitExpressionStatement(ExpressionStatement expressionStatement)
+		{
+			AssignmentExpression assignment = expressionStatement.Expression as AssignmentExpression;
+			if (assignment != null && assignment.Operator == AssignmentOperatorType.Assign) {
+				return new CodeAssignStatement(Convert(assignment.Left), Convert(assignment.Right));
+			} else if (assignment != null && CanBeDuplicatedForCompoundAssignment(assignment.Left)) {
+				CodeBinaryOperatorType op;
+				switch (assignment.Operator) {
+					case AssignmentOperatorType.Add:
+						op = CodeBinaryOperatorType.Add;
+						break;
+					case AssignmentOperatorType.Subtract:
+						op = CodeBinaryOperatorType.Subtract;
+						break;
+					case AssignmentOperatorType.Multiply:
+						op = CodeBinaryOperatorType.Multiply;
+						break;
+					case AssignmentOperatorType.Divide:
+						op = CodeBinaryOperatorType.Divide;
+						break;
+					case AssignmentOperatorType.Modulus:
+						op = CodeBinaryOperatorType.Modulus;
+						break;
+					case AssignmentOperatorType.BitwiseAnd:
+						op = CodeBinaryOperatorType.BitwiseAnd;
+						break;
+					case AssignmentOperatorType.BitwiseOr:
+						op = CodeBinaryOperatorType.BitwiseOr;
+						break;
+					default:
+						return MakeSnippetStatement(expressionStatement);
+				}
+				var cboe = new CodeBinaryOperatorExpression(Convert(assignment.Left), op, Convert(assignment.Right));
+				return new CodeAssignStatement(Convert(assignment.Left), cboe);
+			}
+			UnaryOperatorExpression unary = expressionStatement.Expression as UnaryOperatorExpression;
+			if (unary != null && CanBeDuplicatedForCompoundAssignment(unary.Expression)) {
+				var op = unary.Operator;
+				if (op == UnaryOperatorType.Increment || op == UnaryOperatorType.PostIncrement) {
+					var cboe = new CodeBinaryOperatorExpression(Convert(unary.Expression), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1));
+					return new CodeAssignStatement(Convert(unary.Expression), cboe);
+				} else if (op == UnaryOperatorType.Decrement || op == UnaryOperatorType.PostDecrement) {
+					var cboe = new CodeBinaryOperatorExpression(Convert(unary.Expression), CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1));
+					return new CodeAssignStatement(Convert(unary.Expression), cboe);
+				}
+			}
+			if (assignment != null && assignment.Operator == AssignmentOperatorType.Add) {
+				var rr = Resolve(assignment.Left);
+				if (!rr.IsError && rr.Type.Kind == TypeKind.Delegate) {
+					var expr = (MemberReferenceExpression)assignment.Left;
+					var memberRef = (CodeEventReferenceExpression)HandleMemberReference(Convert(expr.Target), expr.MemberName, expr.TypeArguments, (MemberResolveResult)rr);
+					return new CodeAttachEventStatement(memberRef, Convert(assignment.Right));
+				}
+			}
+			return new CodeExpressionStatement(Convert(expressionStatement.Expression));
+		}
+		
+		bool CanBeDuplicatedForCompoundAssignment(Expression expr)
+		{
+			return expr is IdentifierExpression;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitFixedStatement(FixedStatement fixedStatement)
+		{
+			return MakeSnippetStatement(fixedStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitForeachStatement(ForeachStatement foreachStatement)
+		{
+			return MakeSnippetStatement(foreachStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitForStatement(ForStatement forStatement)
+		{
+			if (forStatement.Initializers.Count != 1 || forStatement.Iterators.Count != 1)
+				return MakeSnippetStatement(forStatement);
+			return new CodeIterationStatement(
+				Convert(forStatement.Initializers.Single()),
+				Convert(forStatement.Condition),
+				Convert(forStatement.Iterators.Single()),
+				ConvertEmbeddedStatement(forStatement.EmbeddedStatement)
+			);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
+		{
+			return MakeSnippetStatement(gotoCaseStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
+		{
+			return MakeSnippetStatement(gotoDefaultStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitGotoStatement(GotoStatement gotoStatement)
+		{
+			return new CodeGotoStatement(gotoStatement.Label);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitIfElseStatement(IfElseStatement ifElseStatement)
+		{
+			return new CodeConditionStatement(
+				Convert(ifElseStatement.Condition),
+				ConvertEmbeddedStatement(ifElseStatement.TrueStatement),
+				ConvertEmbeddedStatement(ifElseStatement.FalseStatement));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitLabelStatement(LabelStatement labelStatement)
+		{
+			return new CodeLabeledStatement(labelStatement.Label);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitLockStatement(LockStatement lockStatement)
+		{
+			return MakeSnippetStatement(lockStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitReturnStatement(ReturnStatement returnStatement)
+		{
+			return new CodeMethodReturnStatement(Convert(returnStatement.Expression));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitSwitchStatement(SwitchStatement switchStatement)
+		{
+			return MakeSnippetStatement(switchStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitSwitchSection(SwitchSection switchSection)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCaseLabel(CaseLabel caseLabel)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitThrowStatement(ThrowStatement throwStatement)
+		{
+			return new CodeThrowExceptionStatement(Convert(throwStatement.Expression));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
+		{
+			List<CodeCatchClause> catchClauses = new List<CodeCatchClause>();
+			foreach (var catchClause in tryCatchStatement.CatchClauses) {
+				catchClauses.Add(new CodeCatchClause(catchClause.VariableName, Convert(catchClause.Type), ConvertBlock(catchClause.Body)));
+			}
+			return new CodeTryCatchFinallyStatement(
+				ConvertBlock(tryCatchStatement.TryBlock),
+				catchClauses.ToArray(),
+				ConvertBlock(tryCatchStatement.FinallyBlock));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCatchClause(CatchClause catchClause)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
+		{
+			return MakeSnippetStatement(uncheckedStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUnsafeStatement(UnsafeStatement unsafeStatement)
+		{
+			return MakeSnippetStatement(unsafeStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitUsingStatement(UsingStatement usingStatement)
+		{
+			return MakeSnippetStatement(usingStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
+		{
+			if (variableDeclarationStatement.Variables.Count != 1)
+				return MakeSnippetStatement(variableDeclarationStatement);
+			VariableInitializer vi = variableDeclarationStatement.Variables.Single();
+			return new CodeVariableDeclarationStatement(
+				Convert(variableDeclarationStatement.Type),
+				vi.Name,
+				ConvertVariableInitializer(vi.Initializer, variableDeclarationStatement.Type));
+		}
+		
+		CodeExpression ConvertVariableInitializer(Expression expr, AstType type)
+		{
+			ArrayInitializerExpression aie = expr as ArrayInitializerExpression;
+			if (aie != null) {
+				return new CodeArrayCreateExpression(Convert(type), Convert(aie.Elements));
+			} else {
+				return Convert(expr);
+			}
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitWhileStatement(WhileStatement whileStatement)
+		{
+			return new CodeIterationStatement(EmptyStatement(), Convert(whileStatement.Condition), EmptyStatement(), ConvertEmbeddedStatement(whileStatement.EmbeddedStatement));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
+		{
+			return MakeSnippetStatement(yieldBreakStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitYieldReturnStatement(YieldReturnStatement yieldStatement)
+		{
+			return MakeSnippetStatement(yieldStatement);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitAccessor(Accessor accessor)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			CodeConstructor ctor = new CodeConstructor();
+			ctor.Attributes = ConvertMemberAttributes(constructorDeclaration.Modifiers, SymbolKind.Constructor);
+			ctor.CustomAttributes.AddRange(Convert(constructorDeclaration.Attributes));
+			if (constructorDeclaration.Initializer.ConstructorInitializerType == ConstructorInitializerType.This) {
+				ctor.ChainedConstructorArgs.AddRange(Convert(constructorDeclaration.Initializer.Arguments));
+			} else {
+				ctor.BaseConstructorArgs.AddRange(Convert(constructorDeclaration.Initializer.Arguments));
+			}
+			ctor.Parameters.AddRange(Convert(constructorDeclaration.Parameters));
+			
+			ctor.Statements.AddRange(ConvertBlock(constructorDeclaration.Body));
+			return ctor;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			return new CodeSnippetTypeMember(MakeSnippet(destructorDeclaration));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
+		{
+			TypeDeclaration td = enumMemberDeclaration.Parent as TypeDeclaration;
+			CodeMemberField f = new CodeMemberField(td != null ? td.Name : "Enum", enumMemberDeclaration.Name);
+			f.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+			f.CustomAttributes.AddRange(Convert(enumMemberDeclaration.Attributes));
+			f.InitExpression = Convert(enumMemberDeclaration.Initializer);
+			return f;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			foreach (VariableInitializer vi in eventDeclaration.Variables) {
+				if (!vi.Initializer.IsNull) {
+					AddTypeMember(new CodeSnippetTypeMember(MakeSnippet(eventDeclaration)));
+					continue;
+				}
+				
+				CodeMemberEvent e = new CodeMemberEvent();
+				e.Attributes = ConvertMemberAttributes(eventDeclaration.Modifiers, SymbolKind.Event);
+				e.CustomAttributes.AddRange(Convert(eventDeclaration.Attributes));
+				e.Name = vi.Name;
+				e.Type = Convert(eventDeclaration.ReturnType);
+				AddTypeMember(e);
+			}
+			return null;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCustomEventDeclaration(CustomEventDeclaration customEventDeclaration)
+		{
+			return new CodeSnippetTypeMember(MakeSnippet(customEventDeclaration));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			foreach (VariableInitializer vi in fieldDeclaration.Variables) {
+				CodeMemberField f = new CodeMemberField(Convert(fieldDeclaration.ReturnType), vi.Name);
+				f.Attributes = ConvertMemberAttributes(fieldDeclaration.Modifiers, SymbolKind.Field);
+				f.CustomAttributes.AddRange(Convert(fieldDeclaration.Attributes));
+				f.InitExpression = ConvertVariableInitializer(vi.Initializer, fieldDeclaration.ReturnType);
+				AddTypeMember(f);
+			}
+			return null;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			CodeMemberProperty p = new CodeMemberProperty();
+			p.Attributes = ConvertMemberAttributes(indexerDeclaration.Modifiers, SymbolKind.Indexer);
+			p.CustomAttributes.AddRange(Convert(indexerDeclaration.Attributes));
+			p.Name = "Items";
+			p.PrivateImplementationType = Convert(indexerDeclaration.PrivateImplementationType);
+			p.Parameters.AddRange(Convert(indexerDeclaration.Parameters));
+			p.Type = Convert(indexerDeclaration.ReturnType);
+			
+			if (!indexerDeclaration.Getter.IsNull) {
+				p.HasGet = true;
+				p.GetStatements.AddRange(ConvertBlock(indexerDeclaration.Getter.Body));
+			}
+			if (!indexerDeclaration.Setter.IsNull) {
+				p.HasSet = true;
+				p.SetStatements.AddRange(ConvertBlock(indexerDeclaration.Setter.Body));
+			}
+			return p;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			CodeMemberMethod m = new CodeMemberMethod();
+			m.Attributes = ConvertMemberAttributes(methodDeclaration.Modifiers, SymbolKind.Method);
+			
+			m.CustomAttributes.AddRange(Convert(methodDeclaration.Attributes.Where(a => a.AttributeTarget != "return")));
+			m.ReturnTypeCustomAttributes.AddRange(Convert(methodDeclaration.Attributes.Where(a => a.AttributeTarget == "return")));
+			
+			m.ReturnType = Convert(methodDeclaration.ReturnType);
+			m.PrivateImplementationType = Convert(methodDeclaration.PrivateImplementationType);
+			m.Name = methodDeclaration.Name;
+			m.TypeParameters.AddRange(ConvertTypeParameters(methodDeclaration.TypeParameters, methodDeclaration.Constraints));
+			m.Parameters.AddRange(Convert(methodDeclaration.Parameters));
+			
+			m.Statements.AddRange(ConvertBlock(methodDeclaration.Body));
+			return m;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+		{
+			CodeMemberMethod m = new CodeMemberMethod();
+			m.Attributes = ConvertMemberAttributes(operatorDeclaration.Modifiers, SymbolKind.Method);
+			
+			m.CustomAttributes.AddRange(Convert(operatorDeclaration.Attributes.Where(a => a.AttributeTarget != "return")));
+			m.ReturnTypeCustomAttributes.AddRange(Convert(operatorDeclaration.Attributes.Where(a => a.AttributeTarget == "return")));
+			
+			m.ReturnType = Convert(operatorDeclaration.ReturnType);
+			m.Name = operatorDeclaration.Name;
+			m.Parameters.AddRange(Convert(operatorDeclaration.Parameters));
+			
+			m.Statements.AddRange(ConvertBlock(operatorDeclaration.Body));
+			return m;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			var p = new CodeParameterDeclarationExpression(Convert(parameterDeclaration.Type), parameterDeclaration.Name);
+			p.CustomAttributes.AddRange(Convert(parameterDeclaration.Attributes));
+			switch (parameterDeclaration.ParameterModifier) {
+				case ParameterModifier.Ref:
+					p.Direction = System.CodeDom.FieldDirection.Ref;
+					break;
+				case ParameterModifier.Out:
+					p.Direction = System.CodeDom.FieldDirection.Out;
+					break;
+			}
+			return p;
+		}
+		
+		CodeParameterDeclarationExpression[] Convert(IEnumerable<ParameterDeclaration> parameters)
+		{
+			List<CodeParameterDeclarationExpression> result = new List<CodeParameterDeclarationExpression>();
+			foreach (ParameterDeclaration pd in parameters) {
+				CodeParameterDeclarationExpression pde = pd.AcceptVisitor(this) as CodeParameterDeclarationExpression;
+				if (pde != null)
+					result.Add(pde);
+			}
+			return result.ToArray();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			CodeMemberProperty p = new CodeMemberProperty();
+			p.Attributes = ConvertMemberAttributes(propertyDeclaration.Modifiers, SymbolKind.Property);
+			p.CustomAttributes.AddRange(Convert(propertyDeclaration.Attributes));
+			p.Name = propertyDeclaration.Name;
+			p.PrivateImplementationType = Convert(propertyDeclaration.PrivateImplementationType);
+			p.Type = Convert(propertyDeclaration.ReturnType);
+			
+			if (!propertyDeclaration.Getter.IsNull) {
+				p.HasGet = true;
+				p.GetStatements.AddRange(ConvertBlock(propertyDeclaration.Getter.Body));
+			}
+			if (!propertyDeclaration.Setter.IsNull) {
+				p.HasSet = true;
+				p.SetStatements.AddRange(ConvertBlock(propertyDeclaration.Setter.Body));
+			}
+			return p;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			throw new NotSupportedException(); // should be handled by the parent node
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			return new CodeSnippetTypeMember(MakeSnippet(fixedFieldDeclaration));
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
+		{
+			throw new NotSupportedException(); // should be handled by the parent node
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitSyntaxTree(SyntaxTree syntaxTree)
+		{
+			CodeCompileUnit cu = new CodeCompileUnit();
+			var globalImports = new List<CodeNamespaceImport> ();
+			foreach (AstNode node in syntaxTree.Children) {
+				CodeObject o = node.AcceptVisitor(this);
+				
+				CodeNamespace ns = o as CodeNamespace;
+				if (ns != null) {
+					cu.Namespaces.Add(ns);
+				}
+				CodeTypeDeclaration td = o as CodeTypeDeclaration;
+				if (td != null) {
+					cu.Namespaces.Add(new CodeNamespace() { Types = { td } });
+				}
+				
+				var import = o as CodeNamespaceImport;
+				if (import != null)
+					globalImports.Add (import);
+			}
+			foreach (var gi in globalImports) {
+				for (int j = 0; j < cu.Namespaces.Count; j++) {
+					var cn = cu.Namespaces [j];
+					bool found = cn.Imports
+						.Cast<CodeNamespaceImport> ()
+						.Any (ns => ns.Namespace == gi.Namespace);
+					if (!found)
+						cn.Imports.Add (gi);
+				}
+			}
+			return cu;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitSimpleType(SimpleType simpleType)
+		{
+			if (UseFullyQualifiedTypeNames) {
+				IType type = Resolve(simpleType).Type;
+				if (type.Kind != TypeKind.Unknown)
+					return Convert(type);
+			}
+			var tr = new CodeTypeReference(simpleType.Identifier);
+			tr.TypeArguments.AddRange(Convert(simpleType.TypeArguments));
+			return tr;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitMemberType(MemberType memberType)
+		{
+			if (memberType.IsDoubleColon && new SimpleType("global").IsMatch(memberType.Target)) {
+				var tr = new CodeTypeReference(memberType.MemberName, CodeTypeReferenceOptions.GlobalReference);
+				tr.TypeArguments.AddRange(Convert(memberType.TypeArguments));
+				return tr;
+			}
+			if (UseFullyQualifiedTypeNames || memberType.IsDoubleColon) {
+				IType type = Resolve(memberType).Type;
+				if (type.Kind != TypeKind.Unknown)
+					return Convert(type);
+			}
+			CodeTypeReference target = Convert(memberType.Target);
+			if (target == null)
+				return null;
+			target.BaseType = target.BaseType + "." + memberType.MemberName;
+			target.TypeArguments.AddRange(Convert(memberType.TypeArguments));
+			return target;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitComposedType(ComposedType composedType)
+		{
+			CodeTypeReference typeRef = Convert(composedType.BaseType);
+			if (typeRef == null)
+				return null;
+			if (composedType.HasNullableSpecifier) {
+				typeRef = new CodeTypeReference("System.Nullable") { TypeArguments = { typeRef } };
+			}
+			foreach (ArraySpecifier s in composedType.ArraySpecifiers.Reverse()) {
+				typeRef = new CodeTypeReference(typeRef, s.Dimensions);
+			}
+			return typeRef;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitArraySpecifier(ArraySpecifier arraySpecifier)
+		{
+			throw new NotSupportedException(); // handled by parent node
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitPrimitiveType(PrimitiveType primitiveType)
+		{
+			KnownTypeCode typeCode = primitiveType.KnownTypeCode;
+			if (typeCode != KnownTypeCode.None) {
+				KnownTypeReference ktr = KnownTypeReference.Get(typeCode);
+				return new CodeTypeReference(ktr.Namespace + "." + ktr.Name);
+			}
+			return new CodeTypeReference(primitiveType.Keyword);
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitComment (Comment comment)
+		{
+			return new CodeComment (comment.Content, comment.CommentType == CommentType.Documentation);
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitNewLine(NewLineNode newLineNode)
+		{
+			return null;
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitWhitespace(WhitespaceNode whitespaceNode)
+		{
+			return null;
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitText(TextNode textNode)
+		{
+			throw new NotSupportedException();
+		}
+
+		CodeObject IAstVisitor<CodeObject>.VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective)
+		{
+			return new CodeComment ("#" + preProcessorDirective.Type.ToString ().ToLowerInvariant ());
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
+		{
+			throw new NotSupportedException(); // type parameters and constraints are handled together
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitConstraint(Constraint constraint)
+		{
+			throw new NotSupportedException();
+		}
+		
+		CodeTypeParameter[] ConvertTypeParameters(IEnumerable<TypeParameterDeclaration> typeParameters, IEnumerable<Constraint> constraints)
+		{
+			List<CodeTypeParameter> result = new List<CodeTypeParameter>();
+			foreach (TypeParameterDeclaration tpDecl in typeParameters) {
+				CodeTypeParameter tp = new CodeTypeParameter(tpDecl.Name);
+				tp.CustomAttributes.AddRange(Convert(tpDecl.Attributes));
+				foreach (Constraint constraint in constraints) {
+					if (constraint.TypeParameter.Identifier == tp.Name) {
+						foreach (AstType baseType in constraint.BaseTypes) {
+							if (baseType is PrimitiveType && ((PrimitiveType)baseType).Keyword == "new") {
+								tp.HasConstructorConstraint = true;
+							} else {
+								CodeTypeReference tr = Convert(baseType);
+								if (tr != null)
+									tp.Constraints.Add(tr);
+							}
+						}
+					}
+				}
+				result.Add(tp);
+			}
+			return result.ToArray();
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode)
+		{
+			return null;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitIdentifier(Identifier identifier)
+		{
+			return null;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitPatternPlaceholder(AstNode placeholder, Pattern pattern)
+		{
+			return null;
+		}
+		
+		CodeObject IAstVisitor<CodeObject>.VisitDocumentationReference(DocumentationReference documentationReference)
+		{
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/ITokenWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/ITokenWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/ITokenWriter.cs	(revision 11807)
@@ -0,0 +1,161 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public abstract class TokenWriter
+	{
+		public abstract void StartNode(AstNode node);
+		public abstract void EndNode(AstNode node);
+		
+		/// <summary>
+		/// Writes an identifier.
+		/// </summary>
+		public abstract void WriteIdentifier(Identifier identifier);
+		
+		/// <summary>
+		/// Writes a keyword to the output.
+		/// </summary>
+		public abstract void WriteKeyword(Role role, string keyword);
+		
+		/// <summary>
+		/// Writes a token to the output.
+		/// </summary>
+		public abstract void WriteToken(Role role, string token);
+		
+		/// <summary>
+		/// Writes a primitive/literal value
+		/// </summary>
+		public abstract void WritePrimitiveValue(object value, string literalValue = null);
+		
+		public abstract void WritePrimitiveType(string type);
+		
+		public abstract void Space();
+		public abstract void Indent();
+		public abstract void Unindent();
+		public abstract void NewLine();
+		
+		public abstract void WriteComment(CommentType commentType, string content);
+		public abstract void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument);
+		
+		public static TokenWriter Create(TextWriter writer, string indentation = "\t")
+		{
+			return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new TextWriterTokenWriter(writer) { IndentationString = indentation }));
+		}
+		
+		public static TokenWriter CreateWriterThatSetsLocationsInAST(TextWriter writer, string indentation = "\t")
+		{
+			var target = new TextWriterTokenWriter(writer) { IndentationString = indentation };
+			return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new InsertMissingTokensDecorator(target, target)));
+		}
+		
+		public static TokenWriter WrapInWriterThatSetsLocationsInAST(TokenWriter writer)
+		{
+			if (!(writer is ILocatable))
+				throw new InvalidOperationException("writer does not provide locations!");
+			return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new InsertMissingTokensDecorator(writer, (ILocatable)writer)));
+		}
+	}
+	
+	public interface ILocatable
+	{
+		TextLocation Location { get; }
+	}
+	
+	public abstract class DecoratingTokenWriter : TokenWriter
+	{
+		TokenWriter decoratedWriter;
+		
+		protected DecoratingTokenWriter(TokenWriter decoratedWriter)
+		{
+			if (decoratedWriter == null)
+				throw new ArgumentNullException("decoratedWriter");
+			this.decoratedWriter = decoratedWriter;
+		}
+		
+		public override void StartNode(AstNode node)
+		{
+			decoratedWriter.StartNode(node);
+		}
+		
+		public override void EndNode(AstNode node)
+		{
+			decoratedWriter.EndNode(node);
+		}
+		
+		public override void WriteIdentifier(Identifier identifier)
+		{
+			decoratedWriter.WriteIdentifier(identifier);
+		}
+		
+		public override void WriteKeyword(Role role, string keyword)
+		{
+			decoratedWriter.WriteKeyword(role, keyword);
+		}
+		
+		public override void WriteToken(Role role, string token)
+		{
+			decoratedWriter.WriteToken(role, token);
+		}
+		
+		public override void WritePrimitiveValue(object value, string literalValue = null)
+		{
+			decoratedWriter.WritePrimitiveValue(value, literalValue);
+		}
+		
+		public override void WritePrimitiveType(string type)
+		{
+			decoratedWriter.WritePrimitiveType(type);
+		}
+		
+		public override void Space()
+		{
+			decoratedWriter.Space();
+		}
+		
+		public override void Indent()
+		{
+			decoratedWriter.Indent();
+		}
+		
+		public override void Unindent()
+		{
+			decoratedWriter.Unindent();
+		}
+		
+		public override void NewLine()
+		{
+			decoratedWriter.NewLine();
+		}
+		
+		public override void WriteComment(CommentType commentType, string content)
+		{
+			decoratedWriter.WriteComment(commentType, content);
+		}
+		
+		public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
+		{
+			decoratedWriter.WritePreProcessorDirective(type, argument);
+		}
+	}
+}
+
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertMissingTokensDecorator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertMissingTokensDecorator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertMissingTokensDecorator.cs	(revision 11807)
@@ -0,0 +1,123 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	class InsertMissingTokensDecorator : DecoratingTokenWriter
+	{
+		readonly Stack<List<AstNode>> nodes = new Stack<List<AstNode>>();
+		List<AstNode> currentList;
+		readonly ILocatable locationProvider;
+		
+		public InsertMissingTokensDecorator(TokenWriter writer, ILocatable locationProvider)
+			: base(writer)
+		{
+			this.locationProvider = locationProvider;
+			currentList = new List<AstNode>();
+		}
+		
+		public override void StartNode(AstNode node)
+		{
+			currentList.Add(node);
+			nodes.Push(currentList);
+			currentList = new List<AstNode>();
+			base.StartNode(node);
+		}
+		
+		public override void EndNode(AstNode node)
+		{
+			System.Diagnostics.Debug.Assert(currentList != null);
+			foreach (var removable in node.Children.Where(n => n is CSharpTokenNode)) {
+				removable.Remove();
+			}
+			foreach (var child in currentList) {
+				System.Diagnostics.Debug.Assert(child.Parent == null || node == child.Parent);
+				child.Remove();
+				node.AddChildWithExistingRole(child);
+			}
+			currentList = nodes.Pop();
+			base.EndNode(node);
+		}
+		
+		public override void WriteToken(Role role, string token)
+		{
+			CSharpTokenNode t = new CSharpTokenNode(locationProvider.Location, (TokenRole)role);
+			t.Role = role;
+			EmptyStatement node = nodes.Peek().LastOrDefault() as EmptyStatement;
+			if (node == null)
+				currentList.Add(t);
+			else {
+				node.Location = locationProvider.Location;
+			}
+			base.WriteToken(role, token);
+		}
+		
+		public override void WriteKeyword(Role role, string keyword)
+		{
+			TextLocation start = locationProvider.Location;
+			CSharpTokenNode t = null;
+			if (role is TokenRole)
+				t = new CSharpTokenNode(start, (TokenRole)role);
+			else if (role == EntityDeclaration.ModifierRole)
+				t = new CSharpModifierToken(start, CSharpModifierToken.GetModifierValue(keyword));
+			else if (keyword == "this") {
+				ThisReferenceExpression node = nodes.Peek().LastOrDefault() as ThisReferenceExpression;
+				if (node != null)
+					node.Location = start;
+			} else if (keyword == "base") {
+				BaseReferenceExpression node = nodes.Peek().LastOrDefault() as BaseReferenceExpression;
+				if (node != null)
+					node.Location = start;
+			}
+			if (t != null) currentList.Add(t);
+			base.WriteKeyword(role, keyword);
+		}
+		
+		public override void WriteIdentifier(Identifier identifier)
+		{
+			if (!identifier.IsNull)
+				identifier.SetStartLocation(locationProvider.Location);
+			currentList.Add(identifier);
+			base.WriteIdentifier(identifier);
+		}
+		
+		public override void WritePrimitiveValue(object value, string literalValue = null)
+		{
+			Expression node = nodes.Peek().LastOrDefault() as Expression;
+			if (node is PrimitiveExpression) {
+				((PrimitiveExpression)node).SetStartLocation(locationProvider.Location);
+			}
+			if (node is NullReferenceExpression) {
+				((NullReferenceExpression)node).SetStartLocation(locationProvider.Location);
+			}
+			base.WritePrimitiveValue(value, literalValue);
+		}
+		
+		public override void WritePrimitiveType(string type)
+		{
+			PrimitiveType node = nodes.Peek().LastOrDefault() as PrimitiveType;
+			if (node != null)
+				node.SetStartLocation(locationProvider.Location);
+			base.WritePrimitiveType(type);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertParenthesesVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertParenthesesVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertParenthesesVisitor.cs	(revision 11807)
@@ -0,0 +1,345 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Inserts the parentheses into the AST that are needed to ensure the AST can be printed correctly.
+	/// For example, if the AST contains
+	/// BinaryOperatorExpresson(2, Mul, BinaryOperatorExpression(1, Add, 1))); printing that AST
+	/// would incorrectly result in "2 * 1 + 1". By running InsertParenthesesVisitor, the necessary
+	/// parentheses are inserted: "2 * (1 + 1)".
+	/// </summary>
+	public class InsertParenthesesVisitor : DepthFirstAstVisitor
+	{
+		/// <summary>
+		/// Gets/Sets whether the visitor should insert parentheses to make the code better looking.
+		/// If this property is false, it will insert parentheses only where strictly required by the language spec.
+		/// </summary>
+		public bool InsertParenthesesForReadability { get; set; }
+		
+		const int Primary = 16;
+		const int QueryOrLambda = 15;
+		const int Unary = 14;
+		const int RelationalAndTypeTesting = 10;
+		const int Equality = 9;
+		const int Conditional = 2;
+		const int Assignment = 1;
+		
+		/// <summary>
+		/// Gets the row number in the C# 4.0 spec operator precedence table.
+		/// </summary>
+		static int GetPrecedence(Expression expr)
+		{
+			// Note: the operator precedence table on MSDN is incorrect
+			if (expr is QueryExpression) {
+				// Not part of the table in the C# spec, but we need to ensure that queries within
+				// primary expressions get parenthesized.
+				return QueryOrLambda;
+			}
+			UnaryOperatorExpression uoe = expr as UnaryOperatorExpression;
+			if (uoe != null) {
+				if (uoe.Operator == UnaryOperatorType.PostDecrement || uoe.Operator == UnaryOperatorType.PostIncrement)
+					return Primary;
+				else
+					return Unary;
+			}
+			if (expr is CastExpression)
+				return Unary;
+			BinaryOperatorExpression boe = expr as BinaryOperatorExpression;
+			if (boe != null) {
+				switch (boe.Operator) {
+					case BinaryOperatorType.Multiply:
+					case BinaryOperatorType.Divide:
+					case BinaryOperatorType.Modulus:
+						return 13; // multiplicative
+					case BinaryOperatorType.Add:
+					case BinaryOperatorType.Subtract:
+						return 12; // additive
+					case BinaryOperatorType.ShiftLeft:
+					case BinaryOperatorType.ShiftRight:
+						return 11;
+					case BinaryOperatorType.GreaterThan:
+					case BinaryOperatorType.GreaterThanOrEqual:
+					case BinaryOperatorType.LessThan:
+					case BinaryOperatorType.LessThanOrEqual:
+						return RelationalAndTypeTesting;
+					case BinaryOperatorType.Equality:
+					case BinaryOperatorType.InEquality:
+						return Equality;
+					case BinaryOperatorType.BitwiseAnd:
+						return 8;
+					case BinaryOperatorType.ExclusiveOr:
+						return 7;
+					case BinaryOperatorType.BitwiseOr:
+						return 6;
+					case BinaryOperatorType.ConditionalAnd:
+						return 5;
+					case BinaryOperatorType.ConditionalOr:
+						return 4;
+					case BinaryOperatorType.NullCoalescing:
+						return 3;
+					default:
+						throw new NotSupportedException("Invalid value for BinaryOperatorType");
+				}
+			}
+			if (expr is IsExpression || expr is AsExpression)
+				return RelationalAndTypeTesting;
+			if (expr is ConditionalExpression)
+				return Conditional;
+			if (expr is AssignmentExpression || expr is LambdaExpression)
+				return Assignment;
+			// anything else: primary expression
+			return Primary;
+		}
+		
+		/// <summary>
+		/// Parenthesizes the expression if it does not have the minimum required precedence.
+		/// </summary>
+		static void ParenthesizeIfRequired(Expression expr, int minimumPrecedence)
+		{
+			if (GetPrecedence(expr) < minimumPrecedence) {
+				Parenthesize(expr);
+			}
+		}
+
+		static void Parenthesize(Expression expr)
+		{
+			expr.ReplaceWith(e => new ParenthesizedExpression { Expression = e });
+		}
+		
+		// Primary expressions
+		public override void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			ParenthesizeIfRequired(memberReferenceExpression.Target, Primary);
+			base.VisitMemberReferenceExpression(memberReferenceExpression);
+		}
+		
+		public override void VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
+		{
+			ParenthesizeIfRequired(pointerReferenceExpression.Target, Primary);
+			base.VisitPointerReferenceExpression(pointerReferenceExpression);
+		}
+		
+		public override void VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			ParenthesizeIfRequired(invocationExpression.Target, Primary);
+			base.VisitInvocationExpression(invocationExpression);
+		}
+		
+		public override void VisitIndexerExpression(IndexerExpression indexerExpression)
+		{
+			ParenthesizeIfRequired(indexerExpression.Target, Primary);
+			ArrayCreateExpression ace = indexerExpression.Target as ArrayCreateExpression;
+			if (ace != null && (InsertParenthesesForReadability || ace.Initializer.IsNull)) {
+				// require parentheses for "(new int[1])[0]"
+				Parenthesize(indexerExpression.Target);
+			}
+			base.VisitIndexerExpression(indexerExpression);
+		}
+		
+		// Unary expressions
+		public override void VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+		{
+			ParenthesizeIfRequired(unaryOperatorExpression.Expression, GetPrecedence(unaryOperatorExpression));
+			UnaryOperatorExpression child = unaryOperatorExpression.Expression as UnaryOperatorExpression;
+			if (child != null && InsertParenthesesForReadability)
+				Parenthesize(child);
+			base.VisitUnaryOperatorExpression(unaryOperatorExpression);
+		}
+		
+		public override void VisitCastExpression(CastExpression castExpression)
+		{
+			ParenthesizeIfRequired(castExpression.Expression, InsertParenthesesForReadability ? Primary : Unary);
+			// There's a nasty issue in the C# grammar: cast expressions including certain operators are ambiguous in some cases
+			// "(int)-1" is fine, but "(A)-b" is not a cast.
+			UnaryOperatorExpression uoe = castExpression.Expression as UnaryOperatorExpression;
+			if (uoe != null && !(uoe.Operator == UnaryOperatorType.BitNot || uoe.Operator == UnaryOperatorType.Not)) {
+				if (TypeCanBeMisinterpretedAsExpression(castExpression.Type)) {
+					Parenthesize(castExpression.Expression);
+				}
+			}
+			// The above issue can also happen with PrimitiveExpressions representing negative values:
+			PrimitiveExpression pe = castExpression.Expression as PrimitiveExpression;
+			if (pe != null && pe.Value != null && TypeCanBeMisinterpretedAsExpression(castExpression.Type)) {
+				TypeCode typeCode = Type.GetTypeCode(pe.Value.GetType());
+				switch (typeCode) {
+					case TypeCode.SByte:
+						if ((sbyte)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+					case TypeCode.Int16:
+						if ((short)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+					case TypeCode.Int32:
+						if ((int)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+					case TypeCode.Int64:
+						if ((long)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+					case TypeCode.Single:
+						if ((float)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+					case TypeCode.Double:
+						if ((double)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+					case TypeCode.Decimal:
+						if ((decimal)pe.Value < 0)
+							Parenthesize(castExpression.Expression);
+						break;
+				}
+			}
+			base.VisitCastExpression(castExpression);
+		}
+		
+		static bool TypeCanBeMisinterpretedAsExpression(AstType type)
+		{
+			// SimpleTypes can always be misinterpreted as IdentifierExpressions
+			// MemberTypes can be misinterpreted as MemberReferenceExpressions if they don't use double colon
+			// PrimitiveTypes or ComposedTypes can never be misinterpreted as expressions.
+			MemberType mt = type as MemberType;
+			if (mt != null)
+				return !mt.IsDoubleColon;
+			else
+				return type is SimpleType;
+		}
+		
+		// Binary Operators
+		public override void VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+		{
+			int precedence = GetPrecedence(binaryOperatorExpression);
+			if (binaryOperatorExpression.Operator == BinaryOperatorType.NullCoalescing) {
+				if (InsertParenthesesForReadability) {
+					ParenthesizeIfRequired(binaryOperatorExpression.Left, Primary);
+					ParenthesizeIfRequired(binaryOperatorExpression.Right, Primary);
+				} else {
+					// ?? is right-associative
+					ParenthesizeIfRequired(binaryOperatorExpression.Left, precedence + 1);
+					ParenthesizeIfRequired(binaryOperatorExpression.Right, precedence);
+				}
+			} else {
+				if (InsertParenthesesForReadability && precedence < Equality) {
+					// In readable mode, boost the priority of the left-hand side if the operator
+					// there isn't the same as the operator on this expression.
+					if (GetBinaryOperatorType(binaryOperatorExpression.Left) == binaryOperatorExpression.Operator) {
+						ParenthesizeIfRequired(binaryOperatorExpression.Left, precedence);
+					} else {
+						ParenthesizeIfRequired(binaryOperatorExpression.Left, Equality);
+					}
+					ParenthesizeIfRequired(binaryOperatorExpression.Right, Equality);
+				} else {
+					// all other binary operators are left-associative
+					ParenthesizeIfRequired(binaryOperatorExpression.Left, precedence);
+					ParenthesizeIfRequired(binaryOperatorExpression.Right, precedence + 1);
+				}
+			}
+			base.VisitBinaryOperatorExpression(binaryOperatorExpression);
+		}
+		
+		BinaryOperatorType? GetBinaryOperatorType(Expression expr)
+		{
+			BinaryOperatorExpression boe = expr as BinaryOperatorExpression;
+			if (boe != null)
+				return boe.Operator;
+			else
+				return null;
+		}
+		
+		public override void VisitIsExpression(IsExpression isExpression)
+		{
+			if (InsertParenthesesForReadability) {
+				// few people know the precedence of 'is', so always put parentheses in nice-looking mode.
+				ParenthesizeIfRequired(isExpression.Expression, Primary);
+			} else {
+				ParenthesizeIfRequired(isExpression.Expression, RelationalAndTypeTesting);
+			}
+			base.VisitIsExpression(isExpression);
+		}
+		
+		public override void VisitAsExpression(AsExpression asExpression)
+		{
+			if (InsertParenthesesForReadability) {
+				// few people know the precedence of 'as', so always put parentheses in nice-looking mode.
+				ParenthesizeIfRequired(asExpression.Expression, Primary);
+			} else {
+				ParenthesizeIfRequired(asExpression.Expression, RelationalAndTypeTesting);
+			}
+			base.VisitAsExpression(asExpression);
+		}
+		
+		// Conditional operator
+		public override void VisitConditionalExpression(ConditionalExpression conditionalExpression)
+		{
+			// Associativity here is a bit tricky:
+			// (a ? b : c ? d : e) == (a ? b : (c ? d : e))
+			// (a ? b ? c : d : e) == (a ? (b ? c : d) : e)
+			// Only ((a ? b : c) ? d : e) strictly needs the additional parentheses
+			if (InsertParenthesesForReadability) {
+				// Precedence of ?: can be confusing; so always put parentheses in nice-looking mode.
+				ParenthesizeIfRequired(conditionalExpression.Condition, Primary);
+				ParenthesizeIfRequired(conditionalExpression.TrueExpression, Primary);
+				ParenthesizeIfRequired(conditionalExpression.FalseExpression, Primary);
+			} else {
+				ParenthesizeIfRequired(conditionalExpression.Condition, Conditional + 1);
+				ParenthesizeIfRequired(conditionalExpression.TrueExpression, Conditional);
+				ParenthesizeIfRequired(conditionalExpression.FalseExpression, Conditional);
+			}
+			base.VisitConditionalExpression(conditionalExpression);
+		}
+		
+		public override void VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+		{
+			// assignment is right-associative
+			ParenthesizeIfRequired(assignmentExpression.Left, Assignment + 1);
+			if (InsertParenthesesForReadability) {
+				ParenthesizeIfRequired(assignmentExpression.Right, RelationalAndTypeTesting + 1);
+			} else {
+				ParenthesizeIfRequired(assignmentExpression.Right, Assignment);
+			}
+			base.VisitAssignmentExpression(assignmentExpression);
+		}
+		
+		// don't need to handle lambdas, they have lowest precedence and unambiguous associativity
+		
+		public override void VisitQueryExpression(QueryExpression queryExpression)
+		{
+			// Query expressions are strange beasts:
+			// "var a = -from b in c select d;" is valid, so queries bind stricter than unary expressions.
+			// However, the end of the query is greedy. So their start sort of has a high precedence,
+			// while their end has a very low precedence. We handle this by checking whether a query is used
+			// as left part of a binary operator, and parenthesize it if required.
+			if (queryExpression.Role == BinaryOperatorExpression.LeftRole)
+				Parenthesize(queryExpression);
+			if (queryExpression.Parent is IsExpression || queryExpression.Parent is AsExpression)
+				Parenthesize(queryExpression);
+			if (InsertParenthesesForReadability) {
+				// when readability is desired, always parenthesize query expressions within unary or binary operators
+				if (queryExpression.Parent is UnaryOperatorExpression || queryExpression.Parent is BinaryOperatorExpression)
+					Parenthesize(queryExpression);
+			}
+			base.VisitQueryExpression(queryExpression);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertRequiredSpacesDecorator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertRequiredSpacesDecorator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertRequiredSpacesDecorator.cs	(revision 11807)
@@ -0,0 +1,184 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using ICSharpCode.NRefactory.PatternMatching;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	class InsertRequiredSpacesDecorator : DecoratingTokenWriter
+	{
+		/// <summary>
+		/// Used to insert the minimal amount of spaces so that the lexer recognizes the tokens that were written.
+		/// </summary>
+		LastWritten lastWritten;
+		
+		enum LastWritten
+		{
+			Whitespace,
+			Other,
+			KeywordOrIdentifier,
+			Plus,
+			Minus,
+			Ampersand,
+			QuestionMark,
+			Division
+		}
+		
+		public InsertRequiredSpacesDecorator(TokenWriter writer)
+			: base(writer)
+		{
+		}
+		
+		public override void WriteIdentifier(Identifier identifier)
+		{
+			if (identifier.IsVerbatim || CSharpOutputVisitor.IsKeyword(identifier.Name, identifier)) {
+				if (lastWritten == LastWritten.KeywordOrIdentifier) {
+					// this space is not strictly required, so we call Space()
+					Space();
+				}
+			} else if (lastWritten == LastWritten.KeywordOrIdentifier) {
+				// this space is strictly required, so we directly call the formatter
+				base.Space();
+			}
+			base.WriteIdentifier(identifier);
+			lastWritten = LastWritten.KeywordOrIdentifier;
+		}
+		
+		public override void WriteKeyword(Role role, string keyword)
+		{
+			if (lastWritten == LastWritten.KeywordOrIdentifier) {
+				Space();
+			}
+			base.WriteKeyword(role, keyword);
+			lastWritten = LastWritten.KeywordOrIdentifier;
+		}
+		
+		public override void WriteToken(Role role, string token)
+		{
+			// Avoid that two +, - or ? tokens are combined into a ++, -- or ?? token.
+			// Note that we don't need to handle tokens like = because there's no valid
+			// C# program that contains the single token twice in a row.
+			// (for +, - and &, this can happen with unary operators;
+			// for ?, this can happen in "a is int? ? b : c" or "a as int? ?? 0";
+			// and for /, this can happen with "1/ *ptr" or "1/ //comment".)
+			if (lastWritten == LastWritten.Plus && token[0] == '+' ||
+			    lastWritten == LastWritten.Minus && token[0] == '-' ||
+			    lastWritten == LastWritten.Ampersand && token[0] == '&' ||
+			    lastWritten == LastWritten.QuestionMark && token[0] == '?' ||
+			    lastWritten == LastWritten.Division && token[0] == '*') {
+				base.Space();
+			}
+			base.WriteToken(role, token);
+			if (token == "+") {
+				lastWritten = LastWritten.Plus;
+			} else if (token == "-") {
+				lastWritten = LastWritten.Minus;
+			} else if (token == "&") {
+				lastWritten = LastWritten.Ampersand;
+			} else if (token == "?") {
+				lastWritten = LastWritten.QuestionMark;
+			} else if (token == "/") {
+				lastWritten = LastWritten.Division;
+			} else {
+				lastWritten = LastWritten.Other;
+			}
+		}
+		
+		public override void Space()
+		{
+			base.Space();
+			lastWritten = LastWritten.Whitespace;
+		}
+		
+		public override void NewLine()
+		{
+			base.NewLine();
+			lastWritten = LastWritten.Whitespace;
+		}
+		
+		public override void WriteComment(CommentType commentType, string content)
+		{
+			if (lastWritten == LastWritten.Division) {
+				// When there's a comment starting after a division operator
+				// "1.0 / /*comment*/a", then we need to insert a space in front of the comment.
+				base.Space();
+			}
+			base.WriteComment(commentType, content);
+			lastWritten = LastWritten.Whitespace;
+		}
+		
+		public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
+		{
+			base.WritePreProcessorDirective(type, argument);
+			lastWritten = LastWritten.Whitespace;
+		}
+		
+		public override void WritePrimitiveValue(object value, string literalValue = null)
+		{
+			base.WritePrimitiveValue(value, literalValue);
+			if (value == null || value is bool)
+				return;
+			if (value is string) {
+				lastWritten = LastWritten.Other;
+			} else if (value is char) {
+				lastWritten = LastWritten.Other;
+			} else if (value is decimal) {
+				lastWritten = LastWritten.Other;
+			} else if (value is float) {
+				float f = (float)value;
+				if (float.IsInfinity(f) || float.IsNaN(f)) return;
+				lastWritten = LastWritten.Other;
+			} else if (value is double) {
+				double f = (double)value;
+				if (double.IsInfinity(f) || double.IsNaN(f)) return;
+				// needs space if identifier follows number;
+				// this avoids mistaking the following identifier as type suffix
+				lastWritten = LastWritten.KeywordOrIdentifier;
+			} else if (value is IFormattable) {
+				// needs space if identifier follows number;
+				// this avoids mistaking the following identifier as type suffix
+				lastWritten = LastWritten.KeywordOrIdentifier;
+			} else {
+				lastWritten = LastWritten.Other;
+			}
+		}
+		
+		public override void WritePrimitiveType(string type)
+		{
+			if (lastWritten == LastWritten.KeywordOrIdentifier) {
+				Space();
+			}
+			base.WritePrimitiveType(type);
+			if (type == "new") {
+				lastWritten = LastWritten.Other;
+			} else {
+				lastWritten = LastWritten.KeywordOrIdentifier;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertSpecialsDecorator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertSpecialsDecorator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/InsertSpecialsDecorator.cs	(revision 11807)
@@ -0,0 +1,157 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	class InsertSpecialsDecorator : DecoratingTokenWriter
+	{
+		readonly Stack<AstNode> positionStack = new Stack<AstNode>();
+		int visitorWroteNewLine = 0;
+		
+		public InsertSpecialsDecorator(TokenWriter writer) : base(writer)
+		{
+		}
+		
+		public override void StartNode(AstNode node)
+		{
+			if (positionStack.Count > 0) {
+				WriteSpecialsUpToNode(node);
+			}
+			positionStack.Push(node.FirstChild);
+			base.StartNode(node);
+		}
+		
+		public override void EndNode(AstNode node)
+		{
+			base.EndNode(node);
+			AstNode pos = positionStack.Pop();
+			Debug.Assert(pos == null || pos.Parent == node);
+			WriteSpecials(pos, null);
+		}
+		
+		public override void WriteKeyword(Role role, string keyword)
+		{
+			if (role != null) {
+				WriteSpecialsUpToRole(role);
+			}
+			base.WriteKeyword(role, keyword);
+		}
+		
+		public override void WriteIdentifier(Identifier identifier)
+		{
+			WriteSpecialsUpToRole(identifier.Role ?? Roles.Identifier);
+			base.WriteIdentifier(identifier);
+		}
+		
+		public override void WriteToken(Role role, string token)
+		{
+			WriteSpecialsUpToRole(role);
+			base.WriteToken(role, token);
+		}
+		
+		public override void NewLine()
+		{
+			if (visitorWroteNewLine >= 0)
+				base.NewLine();
+			visitorWroteNewLine++;
+		}
+		
+		#region WriteSpecials
+		/// <summary>
+		/// Writes all specials from start to end (exclusive). Does not touch the positionStack.
+		/// </summary>
+		void WriteSpecials(AstNode start, AstNode end)
+		{
+			for (AstNode pos = start; pos != end; pos = pos.NextSibling) {
+				if (pos.Role == Roles.Comment) {
+					var node = (Comment)pos;
+					base.WriteComment(node.CommentType, node.Content);
+				}
+				// see CSharpOutputVisitor.VisitNewLine()
+				//				if (pos.Role == Roles.NewLine) {
+				//					if (visitorWroteNewLine <= 0)
+				//						base.NewLine();
+				//					visitorWroteNewLine--;
+				//				}
+				if (pos.Role == Roles.PreProcessorDirective) {
+					var node = (PreProcessorDirective)pos;
+					base.WritePreProcessorDirective(node.Type, node.Argument);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Writes all specials between the current position (in the positionStack) and the next
+		/// node with the specified role. Advances the current position.
+		/// </summary>
+		void WriteSpecialsUpToRole(Role role)
+		{
+			WriteSpecialsUpToRole(role, null);
+		}
+		
+		void WriteSpecialsUpToRole(Role role, AstNode nextNode)
+		{
+			if (positionStack.Count == 0) {
+				return;
+			}
+			// Look for the role between the current position and the nextNode.
+			for (AstNode pos = positionStack.Peek(); pos != null && pos != nextNode; pos = pos.NextSibling) {
+				if (pos.Role == role) {
+					WriteSpecials(positionStack.Pop(), pos);
+					// Push the next sibling because the node matching the role is not a special,
+					// and should be considered to be already handled.
+					positionStack.Push(pos.NextSibling);
+					// This is necessary for OptionalComma() to work correctly.
+					break;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Writes all specials between the current position (in the positionStack) and the specified node.
+		/// Advances the current position.
+		/// </summary>
+		void WriteSpecialsUpToNode(AstNode node)
+		{
+			if (positionStack.Count == 0) {
+				return;
+			}
+			for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) {
+				if (pos == node) {
+					WriteSpecials(positionStack.Pop(), pos);
+					// Push the next sibling because the node itself is not a special,
+					// and should be considered to be already handled.
+					positionStack.Push(pos.NextSibling);
+					// This is necessary for OptionalComma() to work correctly.
+					break;
+				}
+			}
+		}
+		#endregion
+	}
+}
+
+
+
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/TextWriterOutputFormatter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/TextWriterOutputFormatter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/OutputVisitor/TextWriterOutputFormatter.cs	(revision 11807)
@@ -0,0 +1,419 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// Writes C# code into a TextWriter.
+	/// </summary>
+	public class TextWriterTokenWriter : TokenWriter, ILocatable
+	{
+		readonly TextWriter textWriter;
+		int indentation;
+		bool needsIndent = true;
+		bool isAtStartOfLine = true;
+		int line, column;
+
+		public int Indentation {
+			get { return this.indentation; }
+			set { this.indentation = value; }
+		}
+		
+		public TextLocation Location {
+			get { return new TextLocation(line, column + (needsIndent ? indentation * IndentationString.Length : 0)); }
+		}
+		
+		public string IndentationString { get; set; }
+		
+		public TextWriterTokenWriter(TextWriter textWriter)
+		{
+			if (textWriter == null)
+				throw new ArgumentNullException("textWriter");
+			this.textWriter = textWriter;
+			this.IndentationString = "\t";
+			this.line = 1;
+			this.column = 1;
+		}
+		
+		public override void WriteIdentifier(Identifier identifier)
+		{
+			WriteIndentation();
+			if (identifier.IsVerbatim || CSharpOutputVisitor.IsKeyword(identifier.Name, identifier)) {
+				textWriter.Write('@');
+				column++;
+			}
+			textWriter.Write(identifier.Name);
+			column += identifier.Name.Length;
+			isAtStartOfLine = false;
+		}
+		
+		public override void WriteKeyword(Role role, string keyword)
+		{
+			WriteIndentation();
+			column += keyword.Length;
+			textWriter.Write(keyword);
+			isAtStartOfLine = false;
+		}
+		
+		public override void WriteToken(Role role, string token)
+		{
+			WriteIndentation();
+			column += token.Length;
+			textWriter.Write(token);
+			isAtStartOfLine = false;
+		}
+		
+		public override void Space()
+		{
+			WriteIndentation();
+			column++;
+			textWriter.Write(' ');
+		}
+		
+		protected void WriteIndentation()
+		{
+			if (needsIndent) {
+				needsIndent = false;
+				for (int i = 0; i < indentation; i++) {
+					textWriter.Write(this.IndentationString);
+				}
+				column += indentation * IndentationString.Length;
+			}
+		}
+		
+		public override void NewLine()
+		{
+			textWriter.WriteLine();
+			column = 1;
+			line++;
+			needsIndent = true;
+			isAtStartOfLine = true;
+		}
+		
+		public override void Indent()
+		{
+			indentation++;
+		}
+		
+		public override void Unindent()
+		{
+			indentation--;
+		}
+		
+		public override void WriteComment(CommentType commentType, string content)
+		{
+			WriteIndentation();
+			switch (commentType) {
+				case CommentType.SingleLine:
+					textWriter.Write("//");
+					textWriter.WriteLine(content);
+					column += 2 + content.Length;
+					needsIndent = true;
+					isAtStartOfLine = true;
+					break;
+				case CommentType.MultiLine:
+					textWriter.Write("/*");
+					textWriter.Write(content);
+					textWriter.Write("*/");
+					column += 2;
+					UpdateEndLocation(content, ref line, ref column);
+					column += 2;
+					isAtStartOfLine = false;
+					break;
+				case CommentType.Documentation:
+					textWriter.Write("///");
+					textWriter.WriteLine(content);
+					column += 3 + content.Length;
+					needsIndent = true;
+					isAtStartOfLine = true;
+					break;
+				case CommentType.MultiLineDocumentation:
+					textWriter.Write("/**");
+					textWriter.Write(content);
+					textWriter.Write("*/");
+					column += 3;
+					UpdateEndLocation(content, ref line, ref column);
+					column += 2;
+					isAtStartOfLine = false;
+					break;
+				default:
+					textWriter.Write(content);
+					column += content.Length;
+					break;
+			}
+		}
+		
+		static void UpdateEndLocation(string content, ref int line, ref int column)
+		{
+			if (string.IsNullOrEmpty(content))
+				return;
+			for (int i = 0; i < content.Length; i++) {
+				char ch = content[i];
+				switch (ch) {
+					case '\r':
+						if (i + 1 < content.Length && content[i + 1] == '\n')
+							i++;
+						goto case '\n';
+					case '\n':
+						line++;
+						column = 0;
+						break;
+				}
+				column++;
+			}
+		}
+		
+		public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
+		{
+			// pre-processor directive must start on its own line
+			if (!isAtStartOfLine)
+				NewLine();
+			WriteIndentation();
+			textWriter.Write('#');
+			string directive = type.ToString().ToLowerInvariant();
+			textWriter.Write(directive);
+			column += 1 + directive.Length;
+			if (!string.IsNullOrEmpty(argument)) {
+				textWriter.Write(' ');
+				textWriter.Write(argument);
+				column += 1 + argument.Length;
+			}
+			NewLine();
+		}
+		
+		public static string PrintPrimitiveValue(object value)
+		{
+			TextWriter writer = new StringWriter();
+			TextWriterTokenWriter tokenWriter = new TextWriterTokenWriter(writer);
+			tokenWriter.WritePrimitiveValue(value);
+			return writer.ToString();
+		}
+		
+		public override void WritePrimitiveValue(object value, string literalValue = null)
+		{
+			if (literalValue != null) {
+				textWriter.Write(literalValue);
+				column += literalValue.Length;
+				return;
+			}
+			
+			if (value == null) {
+				// usually NullReferenceExpression should be used for this, but we'll handle it anyways
+				textWriter.Write("null");
+				column += 4;
+				return;
+			}
+			
+			if (value is bool) {
+				if ((bool)value) {
+					textWriter.Write("true");
+					column += 4;
+				} else {
+					textWriter.Write("false");
+					column += 5;
+				}
+				return;
+			}
+			
+			if (value is string) {
+				string tmp = "\"" + ConvertString(value.ToString()) + "\"";
+				column += tmp.Length;
+				textWriter.Write(tmp);
+			} else if (value is char) {
+				string tmp = "'" + ConvertCharLiteral((char)value) + "'";
+				column += tmp.Length;
+				textWriter.Write(tmp);
+			} else if (value is decimal) {
+				string str = ((decimal)value).ToString(NumberFormatInfo.InvariantInfo) + "m";
+				column += str.Length;
+				textWriter.Write(str);
+			} else if (value is float) {
+				float f = (float)value;
+				if (float.IsInfinity(f) || float.IsNaN(f)) {
+					// Strictly speaking, these aren't PrimitiveExpressions;
+					// but we still support writing these to make life easier for code generators.
+					textWriter.Write("float");
+					column += 5;
+					WriteToken(Roles.Dot, ".");
+					if (float.IsPositiveInfinity(f)) {
+						textWriter.Write("PositiveInfinity");
+						column += "PositiveInfinity".Length;
+					} else if (float.IsNegativeInfinity(f)) {
+						textWriter.Write("NegativeInfinity");
+						column += "NegativeInfinity".Length;
+					} else {
+						textWriter.Write("NaN");
+						column += 3;
+					}
+					return;
+				}
+				if (f == 0 && 1 / f == float.NegativeInfinity) {
+					// negative zero is a special case
+					// (again, not a primitive expression, but it's better to handle
+					// the special case here than to do it in all code generators)
+					textWriter.Write("-");
+					column++;
+				}
+				var str = f.ToString("R", NumberFormatInfo.InvariantInfo) + "f";
+				column += str.Length;
+				textWriter.Write(str);
+			} else if (value is double) {
+				double f = (double)value;
+				if (double.IsInfinity(f) || double.IsNaN(f)) {
+					// Strictly speaking, these aren't PrimitiveExpressions;
+					// but we still support writing these to make life easier for code generators.
+					textWriter.Write("double");
+					column += 6;
+					WriteToken(Roles.Dot, ".");
+					if (double.IsPositiveInfinity(f)) {
+						textWriter.Write("PositiveInfinity");
+						column += "PositiveInfinity".Length;
+					} else if (double.IsNegativeInfinity(f)) {
+						textWriter.Write("NegativeInfinity");
+						column += "NegativeInfinity".Length;
+					} else {
+						textWriter.Write("NaN");
+						column += 3;
+					}
+					return;
+				}
+				if (f == 0 && 1 / f == double.NegativeInfinity) {
+					// negative zero is a special case
+					// (again, not a primitive expression, but it's better to handle
+					// the special case here than to do it in all code generators)
+					textWriter.Write("-");
+				}
+				string number = f.ToString("R", NumberFormatInfo.InvariantInfo);
+				if (number.IndexOf('.') < 0 && number.IndexOf('E') < 0) {
+					number += ".0";
+				}
+				textWriter.Write(number);
+			} else if (value is IFormattable) {
+				StringBuilder b = new StringBuilder ();
+//				if (primitiveExpression.LiteralFormat == LiteralFormat.HexadecimalNumber) {
+//					b.Append("0x");
+//					b.Append(((IFormattable)val).ToString("x", NumberFormatInfo.InvariantInfo));
+//				} else {
+					b.Append(((IFormattable)value).ToString(null, NumberFormatInfo.InvariantInfo));
+//				}
+				if (value is uint || value is ulong) {
+					b.Append("u");
+				}
+				if (value is long || value is ulong) {
+					b.Append("L");
+				}
+				textWriter.Write(b.ToString());
+				column += b.Length;
+			} else {
+				textWriter.Write(value.ToString());
+				column += value.ToString().Length;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the escape sequence for the specified character within a char literal.
+		/// Does not include the single quotes surrounding the char literal.
+		/// </summary>
+		public static string ConvertCharLiteral(char ch)
+		{
+			if (ch == '\'') {
+				return "\\'";
+			}
+			return ConvertChar(ch);
+		}
+		
+		/// <summary>
+		/// Gets the escape sequence for the specified character.
+		/// </summary>
+		/// <remarks>This method does not convert ' or ".</remarks>
+		static string ConvertChar(char ch)
+		{
+			switch (ch) {
+				case '\\':
+					return "\\\\";
+				case '\0':
+					return "\\0";
+				case '\a':
+					return "\\a";
+				case '\b':
+					return "\\b";
+				case '\f':
+					return "\\f";
+				case '\n':
+					return "\\n";
+				case '\r':
+					return "\\r";
+				case '\t':
+					return "\\t";
+				case '\v':
+					return "\\v";
+				default:
+					if (char.IsControl(ch) || char.IsSurrogate(ch) ||
+					    // print all uncommon white spaces as numbers
+					    (char.IsWhiteSpace(ch) && ch != ' ')) {
+						return "\\u" + ((int)ch).ToString("x4");
+					} else {
+						return ch.ToString();
+					}
+			}
+		}
+		
+		/// <summary>
+		/// Converts special characters to escape sequences within the given string.
+		/// </summary>
+		public static string ConvertString(string str)
+		{
+			StringBuilder sb = new StringBuilder ();
+			foreach (char ch in str) {
+				if (ch == '"') {
+					sb.Append("\\\"");
+				} else {
+					sb.Append(ConvertChar(ch));
+				}
+			}
+			return sb.ToString();
+		}
+		
+		public override void WritePrimitiveType(string type)
+		{
+			textWriter.Write(type);
+			column += type.Length;
+			if (type == "new") {
+				textWriter.Write("()");
+				column += 2;
+			}
+		}
+		
+		public override void StartNode(AstNode node)
+		{
+			// Write out the indentation, so that overrides of this method
+			// can rely use the current output length to identify the position of the node
+			// in the output.
+			WriteIndentation();
+		}
+		
+		public override void EndNode(AstNode node)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/CSharpParser.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/CSharpParser.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/CSharpParser.cs	(revision 11807)
@@ -0,0 +1,4096 @@
+// 
+// CSharpParser.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@novell.com>
+// 
+// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.IO;
+using ICSharpCode.NRefactory.Editor;
+using Mono.CSharp;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public class CSharpParser
+	{
+		CompilerSettings compilerSettings;
+
+		class ConversionVisitor : StructuralVisitor
+		{
+			SyntaxTree unit = new SyntaxTree();
+			internal bool convertTypeSystemMode;
+
+			public SyntaxTree Unit {
+				get {
+					return unit;
+				}
+				set {
+					unit = value;
+				}
+			}
+
+			public LocationsBag LocationsBag {
+				get;
+				private set;
+			}
+
+			public ConversionVisitor(bool convertTypeSystemMode, LocationsBag locationsBag)
+			{
+				this.convertTypeSystemMode = convertTypeSystemMode;
+				this.LocationsBag = locationsBag;
+			}
+
+			public static TextLocation Convert(Location loc)
+			{
+				return new TextLocation(loc.Row, loc.Column);
+			}
+
+			public override void Visit(ModuleContainer mc)
+			{
+				bool first = true;
+				foreach (var container in mc.Containers) {
+					var nspace = container as NamespaceContainer;
+					if (nspace == null) {
+						container.Accept(this);
+						continue;
+					}
+					NamespaceDeclaration nDecl = null;
+					var loc = LocationsBag.GetLocations(nspace);
+					
+					if (nspace.NS != null && !string.IsNullOrEmpty(nspace.NS.Name)) {
+						nDecl = new NamespaceDeclaration();
+						if (loc != null) {
+							nDecl.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.NamespaceKeyword), Roles.NamespaceKeyword);
+						}
+						nDecl.AddChild(ConvertNamespaceName(nspace.RealMemberName), NamespaceDeclaration.NamespaceNameRole);
+						if (loc != null && loc.Count > 1) {
+							nDecl.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.LBrace), Roles.LBrace);
+						}
+						AddToNamespace(nDecl);
+						namespaceStack.Push(nDecl);
+					}
+					
+					if (nspace.Usings != null) {
+						foreach (var us in nspace.Usings) {
+							us.Accept(this);
+						}
+					}
+					
+					if (first) {
+						first = false;
+						if (mc.OptAttributes != null) {
+							foreach (var attr in mc.OptAttributes.Sections) {
+								var section = ConvertAttributeSection(attr);
+								if (section !=	null)
+									unit.AddChild(section, SyntaxTree.MemberRole);
+							}
+						}
+					}
+					
+					if (nspace.Containers != null) {
+						foreach (var subContainer in nspace.Containers) {
+							subContainer.Accept(this);
+						}
+					}
+					if (nDecl != null) {
+						AddAttributeSection(nDecl, nspace.UnattachedAttributes, EntityDeclaration.UnattachedAttributeRole);
+						if (loc != null && loc.Count > 2)
+							nDecl.AddChild(new CSharpTokenNode(Convert(loc [2]), Roles.RBrace), Roles.RBrace);
+						if (loc != null && loc.Count > 3)
+							nDecl.AddChild(new CSharpTokenNode(Convert(loc [3]), Roles.Semicolon), Roles.Semicolon);
+						
+						namespaceStack.Pop();
+					} else {
+						AddAttributeSection(unit, nspace.UnattachedAttributes, EntityDeclaration.UnattachedAttributeRole);
+					}
+				}
+				AddAttributeSection(unit, mc.UnattachedAttributes, EntityDeclaration.UnattachedAttributeRole);
+			}
+
+			#region Global
+
+			readonly Stack<NamespaceDeclaration> namespaceStack = new Stack<NamespaceDeclaration>();
+
+			void AddTypeArguments(ATypeNameExpression texpr, AstType result)
+			{
+				var unbound = texpr.TypeArguments as UnboundTypeArguments;
+				if (unbound != null) { 
+					var loc2 = LocationsBag.GetLocations(texpr.TypeArguments);
+					if (loc2 == null)
+						return;
+					int j = 0;
+					if (j < loc2.Count)
+						result.AddChild(new CSharpTokenNode(Convert(loc2 [j++]), Roles.LChevron), Roles.LChevron);
+					while (j < loc2.Count - 1) {
+						result.AddChild (new SimpleType (), Roles.TypeArgument);
+						result.AddChild(new CSharpTokenNode(Convert(loc2 [j++]), Roles.LChevron), Roles.Comma);
+					}
+					if (j < loc2.Count) {
+						result.AddChild (new SimpleType (), Roles.TypeArgument);
+						result.AddChild(new CSharpTokenNode(Convert(loc2 [j++]), Roles.RChevron), Roles.RChevron);
+					}
+					return;
+				}
+				if (texpr.TypeArguments == null || texpr.TypeArguments.Args == null)
+					return;
+				var loc = LocationsBag.GetLocations(texpr.TypeArguments);
+				if (loc != null && loc.Count >= 2)
+					result.AddChild(new CSharpTokenNode(Convert(loc [loc.Count - 2]), Roles.LChevron), Roles.LChevron);
+				int i = 0;
+				foreach (var arg in texpr.TypeArguments.Args) {
+					result.AddChild(ConvertToType(arg), Roles.TypeArgument);
+					if (loc != null && i < loc.Count - 2)
+						result.AddChild(new CSharpTokenNode(Convert(loc [i++]), Roles.Comma), Roles.Comma);
+				}
+				if (loc != null && loc.Count >= 2)
+					result.AddChild(new CSharpTokenNode(Convert(loc [loc.Count - 1]), Roles.RChevron), Roles.RChevron);
+			}
+
+			static AstType ConvertToType(TypeParameter spec)
+			{
+				AstType result;
+				result = new SimpleType { IdentifierToken = Identifier.Create(spec.Name, Convert(spec.Location)) };
+				return result;
+			}
+
+			AstType ConvertToType(MemberName memberName)
+			{
+				AstType result;
+				if (memberName.Left != null) {
+					result = new MemberType();
+					result.AddChild(ConvertToType(memberName.Left), MemberType.TargetRole);
+					var loc = LocationsBag.GetLocations(memberName);
+					if (loc != null)
+						result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot);
+					result.AddChild(Identifier.Create(memberName.Name, Convert(memberName.Location)), Roles.Identifier);
+				} else {
+					result = new SimpleType { IdentifierToken = Identifier.Create(memberName.Name, Convert(memberName.Location)) };
+				}
+				if (memberName.TypeParameters != null) {
+					var chevronLocs = LocationsBag.GetLocations(memberName.TypeParameters);
+					if (chevronLocs != null)
+						result.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 2]), Roles.LChevron), Roles.LChevron);
+					for (int i = 0; i < memberName.TypeParameters.Count; i++) {
+						var param = memberName.TypeParameters [i];
+						result.AddChild(new SimpleType(Identifier.Create(param.Name, Convert(param.Location))), Roles.TypeArgument);
+						if (chevronLocs != null && i < chevronLocs.Count - 2)
+							result.AddChild(new CSharpTokenNode(Convert(chevronLocs [i]), Roles.Comma), Roles.Comma);
+					}
+					if (chevronLocs != null)
+						result.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 1]), Roles.RChevron), Roles.RChevron);
+				}
+				return result;
+			}
+
+			AstType ConvertToType(Mono.CSharp.Expression typeName)
+			{
+				if (typeName == null) // may happen in typeof(Generic<,,,,>)
+					return new SimpleType();
+				
+				var typeExpr = typeName as TypeExpression;
+				if (typeExpr != null) {
+					return new PrimitiveType(typeExpr.GetSignatureForError(), Convert(typeExpr.Location));
+				}
+				
+				var qam = typeName as QualifiedAliasMember;
+				if (qam != null) {
+					var loc = LocationsBag.GetLocations(typeName);
+					var memberType = new MemberType();
+					memberType.Target = new SimpleType(qam.alias, Convert(qam.Location));
+					memberType.IsDoubleColon = true;
+
+					if (loc != null && loc.Count > 0)
+						memberType.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.DoubleColon), Roles.DoubleColon);
+
+					memberType.MemberNameToken = Identifier.Create(qam.Name, loc != null ? Convert(loc [1]) : TextLocation.Empty);
+					AddTypeArguments(qam, memberType);
+					return memberType;
+				}
+				
+				var ma = typeName as MemberAccess;
+				if (ma != null) {
+					var memberType = new MemberType();
+					memberType.AddChild(ConvertToType(ma.LeftExpression), MemberType.TargetRole);
+					var loc = LocationsBag.GetLocations(ma);
+					if (loc != null)
+						memberType.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot);
+
+					memberType.MemberNameToken = Identifier.Create(ma.Name, Convert(ma.Location));
+					
+					AddTypeArguments(ma, memberType);
+					return memberType;
+				}
+				
+				var sn = typeName as SimpleName;
+				if (sn != null) {
+					var result = new SimpleType(sn.Name, Convert(sn.Location));
+					AddTypeArguments(sn, result);
+					return result;
+				}
+				
+				var cc = typeName as ComposedCast;
+				if (cc != null) {
+					var baseType = ConvertToType(cc.Left);
+					var result = new ComposedType { BaseType = baseType };
+					var ccSpec = cc.Spec;
+					while (ccSpec != null) {
+						if (ccSpec.IsNullable) {
+							result.AddChild(new CSharpTokenNode(Convert(ccSpec.Location), ComposedType.NullableRole), ComposedType.NullableRole);
+						} else if (ccSpec.IsPointer) {
+							result.AddChild(new CSharpTokenNode(Convert(ccSpec.Location), ComposedType.PointerRole), ComposedType.PointerRole);
+						} else {
+							var location = LocationsBag.GetLocations(ccSpec);
+							var spec = new ArraySpecifier { Dimensions = ccSpec.Dimension };
+							spec.AddChild(new CSharpTokenNode(Convert(ccSpec.Location), Roles.LBracket), Roles.LBracket);
+							if (location != null)
+								spec.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.RBracket), Roles.RBracket);
+							
+							result.ArraySpecifiers.Add(spec);
+						}
+						ccSpec = ccSpec.Next;
+					}
+					return result;
+				}
+				
+				var sce = typeName as SpecialContraintExpr;
+				if (sce != null) {
+					switch (sce.Constraint) {
+						case SpecialConstraint.Class:
+							return new PrimitiveType("class", Convert(sce.Location));
+						case SpecialConstraint.Struct:
+							return new PrimitiveType("struct", Convert(sce.Location));
+						case SpecialConstraint.Constructor:
+							return new PrimitiveType("new", Convert(sce.Location));
+					}
+				}
+				return new SimpleType("unknown");
+			}
+
+			IEnumerable<Attribute> GetAttributes(IEnumerable<Mono.CSharp.Attribute> optAttributes)
+			{
+				if (optAttributes == null)
+					yield break;
+				foreach (var attr in optAttributes) {
+					var result = new Attribute();
+					result.Type = ConvertToType(attr.TypeNameExpression);
+					var loc = LocationsBag.GetLocations(attr);
+					result.HasArgumentList = loc != null;
+					int pos = 0;
+					if (loc != null)
+						result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.LPar), Roles.LPar);
+					
+					if (attr.PositionalArguments != null) {
+						foreach (var arg in attr.PositionalArguments) {
+							if (arg == null)
+								continue;
+							var na = arg as NamedArgument;
+							if (na != null) {
+								var newArg = new NamedArgumentExpression();
+								newArg.AddChild(Identifier.Create(na.Name, Convert(na.Location)), Roles.Identifier);
+								
+								var argLoc = LocationsBag.GetLocations(na);
+								if (argLoc != null)
+									newArg.AddChild(new CSharpTokenNode(Convert(argLoc [0]), Roles.Colon), Roles.Colon);
+								if (na.Expr != null)
+									newArg.AddChild((Expression)na.Expr.Accept(this), Roles.Expression);
+								result.AddChild(newArg, Roles.Argument);
+							} else {
+								if (arg.Expr != null)
+									result.AddChild((Expression)arg.Expr.Accept(this), Roles.Argument);
+							}
+							if (loc != null && pos + 1 < loc.Count)
+								result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma);
+						}
+					}
+					if (attr.NamedArguments != null) {
+						foreach (var arg in attr.NamedArguments) {
+							var na = (NamedArgument)arg;
+							var newArg = new NamedExpression();
+							newArg.AddChild(Identifier.Create(na.Name, Convert(na.Location)), Roles.Identifier);
+							
+							var argLoc = LocationsBag.GetLocations(na);
+							if (argLoc != null)
+								newArg.AddChild(new CSharpTokenNode(Convert(argLoc [0]), Roles.Assign), Roles.Assign);
+							if (na.Expr != null)
+								newArg.AddChild((Expression)na.Expr.Accept(this), Roles.Expression);
+							result.AddChild(newArg, Roles.Argument);
+							if (loc != null && pos + 1 < loc.Count)
+								result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma);
+						}
+					}
+					if (loc != null && pos < loc.Count)
+						result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.RPar), Roles.RPar);
+					
+					yield return result;
+				}
+			}
+
+			AttributeSection ConvertAttributeSection(IEnumerable<Mono.CSharp.Attribute> optAttributes)
+			{
+				if (optAttributes == null)
+					return null;
+				var result = new AttributeSection();
+				var loc = LocationsBag.GetLocations(optAttributes);
+				int pos = 0;
+				if (loc != null)
+					result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.LBracket), Roles.LBracket);
+				var first = optAttributes.FirstOrDefault();
+				string target = first != null ? first.ExplicitTarget : null;
+				
+				if (!string.IsNullOrEmpty(target)) {
+					if (loc != null && pos < loc.Count - 1) {
+						result.AddChild(Identifier.Create(target, Convert(loc [pos++])), Roles.Identifier);
+					} else {
+						result.AddChild(Identifier.Create(target), Roles.Identifier);
+					}
+					if (loc != null && pos < loc.Count)
+						result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Colon), Roles.Colon);
+				}
+
+				int attributeCount = 0;
+				foreach (var attr in GetAttributes (optAttributes)) {
+					result.AddChild(attr, Roles.Attribute);
+					if (loc != null && pos + 1 < loc.Count)
+						result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma);
+
+					attributeCount++;
+				}
+				if (attributeCount == 0)
+					return null;
+				// Left and right bracket + commas between the attributes
+				int locCount = 2 + attributeCount - 1;
+				// optional comma
+				if (loc != null && pos < loc.Count - 1 && loc.Count == locCount + 1)
+					result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.Comma), Roles.Comma);
+				if (loc != null && pos < loc.Count)
+					result.AddChild(new CSharpTokenNode(Convert(loc [pos++]), Roles.RBracket), Roles.RBracket);
+				return result;
+			}
+
+			public override void Visit(NamespaceContainer ns)
+			{
+				NamespaceDeclaration nDecl = null;
+				var loc = LocationsBag.GetLocations(ns);
+				// <invalid> is caused by the parser - see Bug 12383 - [AST] Non existing namespaces generated
+				if (ns.NS != null && !string.IsNullOrEmpty(ns.NS.Name) && !ns.NS.Name.EndsWith("<invalid>", StringComparison.Ordinal)) {
+					nDecl = new NamespaceDeclaration();
+					if (loc != null) {
+						nDecl.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.NamespaceKeyword), Roles.NamespaceKeyword);
+					}
+					nDecl.AddChild(ConvertNamespaceName(ns.RealMemberName), NamespaceDeclaration.NamespaceNameRole);
+					if (loc != null && loc.Count > 1) {
+						nDecl.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.LBrace), Roles.LBrace);
+					}
+
+					AddToNamespace(nDecl);
+					namespaceStack.Push(nDecl);
+				}
+				
+				if (ns.Usings != null) {
+					foreach (var us in ns.Usings) {
+						us.Accept(this);
+					}
+				}
+				
+				if (ns.Containers != null) {
+					foreach (var container in ns.Containers) {
+						container.Accept(this);
+					}
+				}
+				
+				if (nDecl != null) {
+					AddAttributeSection(nDecl, ns.UnattachedAttributes, EntityDeclaration.UnattachedAttributeRole);
+					if (loc != null && loc.Count > 2)
+						nDecl.AddChild(new CSharpTokenNode(Convert(loc [2]), Roles.RBrace), Roles.RBrace);
+					if (loc != null && loc.Count > 3)
+						nDecl.AddChild(new CSharpTokenNode(Convert(loc [3]), Roles.Semicolon), Roles.Semicolon);
+					
+					namespaceStack.Pop();
+				}
+			}
+			//			public override void Visit (UsingsBag.Namespace nspace)
+			//			{
+			//
+			//
+			//				VisitNamespaceUsings (nspace);
+			//				VisitNamespaceBody (nspace);
+			//
+			//			}
+			//
+			AstType ConvertNamespaceName(MemberName memberName)
+			{
+				// HACK for a parser 'bug' - sometimes it generates "<invalid>" identifiers in namespace names (on certain bugs in the input file)
+				if (memberName.Name == "<invalid>")
+					return AstType.Null;
+				return ConvertToType(memberName);
+			}
+
+			public override void Visit(UsingNamespace un)
+			{
+				var ud = new UsingDeclaration();
+				var loc = LocationsBag.GetLocations(un);
+				ud.AddChild(new CSharpTokenNode(Convert(un.Location), UsingDeclaration.UsingKeywordRole), UsingDeclaration.UsingKeywordRole);
+				if (un.NamespaceExpression != null)
+					ud.AddChild(ConvertToType(un.NamespaceExpression), UsingDeclaration.ImportRole);
+				if (loc != null)
+					ud.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Semicolon), Roles.Semicolon);
+				AddToNamespace(ud);
+			}
+
+			public override void Visit(UsingAliasNamespace uan)
+			{
+				var ud = new UsingAliasDeclaration();
+				var loc = LocationsBag.GetLocations(uan);
+				
+				ud.AddChild(new CSharpTokenNode(Convert(uan.Location), UsingAliasDeclaration.UsingKeywordRole), UsingAliasDeclaration.UsingKeywordRole);
+				ud.AddChild(Identifier.Create(uan.Alias.Value, Convert(uan.Alias.Location)), UsingAliasDeclaration.AliasRole);
+				if (loc != null)
+					ud.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Assign), Roles.Assign);
+				if (uan.NamespaceExpression != null)
+					ud.AddChild(ConvertToType(uan.NamespaceExpression), UsingAliasDeclaration.ImportRole);
+				if (loc != null && loc.Count > 1)
+					ud.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.Semicolon), Roles.Semicolon);
+				AddToNamespace(ud);
+			}
+
+			public override void Visit(UsingExternAlias uea)
+			{
+				var ud = new ExternAliasDeclaration();
+				var loc = LocationsBag.GetLocations(uea);
+				ud.AddChild(new CSharpTokenNode(Convert(uea.Location), Roles.ExternKeyword), Roles.ExternKeyword);
+				if (loc != null)
+					ud.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.AliasKeyword), Roles.AliasKeyword);
+				ud.AddChild(Identifier.Create(uea.Alias.Value, Convert(uea.Alias.Location)), Roles.Identifier);
+				if (loc != null && loc.Count > 1)
+					ud.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.Semicolon), Roles.Semicolon);
+				AddToNamespace(ud);
+			}
+
+			AstType ConvertImport(MemberName memberName)
+			{
+				if (memberName.Left != null) {
+					// left.name
+					var t = new MemberType();
+//					t.IsDoubleColon = memberName.IsDoubleColon;
+					t.AddChild(ConvertImport(memberName.Left), MemberType.TargetRole);
+					var loc = LocationsBag.GetLocations(memberName);
+					if (loc != null)
+						t.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot);
+					
+					t.AddChild(Identifier.Create(memberName.Name, Convert(memberName.Location)), Roles.Identifier);
+					AddTypeArguments(t, memberName);
+					return t;
+				} else {
+					var t = new SimpleType();
+					t.AddChild(Identifier.Create(memberName.Name, Convert(memberName.Location)), Roles.Identifier);
+					AddTypeArguments(t, memberName);
+					return t;
+				}
+			}
+
+			public override void Visit(MemberCore member)
+			{
+				Console.WriteLine("Unknown member:");
+				Console.WriteLine(member.GetType() + "-> Member {0}", member.GetSignatureForError());
+			}
+
+			readonly Stack<TypeDeclaration> typeStack = new Stack<TypeDeclaration>();
+
+			public override void Visit(Class c)
+			{
+				var newType = new TypeDeclaration();
+				newType.ClassType = ClassType.Class;
+				AddAttributeSection(newType, c);
+				var location = LocationsBag.GetMemberLocation(c);
+				AddModifiers(newType, location);
+				int curLoc = 0;
+				if (location != null && location.Count > 0)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.ClassKeyword), Roles.ClassKeyword);
+				
+				newType.AddChild(Identifier.Create(c.MemberName.Name, Convert(c.MemberName.Location)), Roles.Identifier);
+				AddTypeParameters(newType, c.MemberName);
+				
+				if (c.TypeBaseExpressions != null) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Colon), Roles.Colon);
+					
+					var commaLocations = LocationsBag.GetLocations(c.TypeBaseExpressions);
+					int i = 0;
+					foreach (var baseTypes in c.TypeBaseExpressions) {
+						newType.AddChild(ConvertToType(baseTypes), Roles.BaseType);
+						if (commaLocations != null && i < commaLocations.Count) {
+							newType.AddChild(new CSharpTokenNode(Convert(commaLocations [i]), Roles.Comma), Roles.Comma);
+							i++;
+						}
+					}
+				}
+				
+				AddConstraints(newType, c.CurrentTypeParameters);
+				if (location != null && curLoc < location.Count)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.LBrace), Roles.LBrace);
+				typeStack.Push(newType);
+				base.Visit(c);
+				AddAttributeSection(newType, c.UnattachedAttributes, EntityDeclaration.UnattachedAttributeRole);
+
+				if (location != null && curLoc < location.Count) {
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.RBrace), Roles.RBrace);
+					
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Semicolon), Roles.Semicolon);
+					
+				} else {
+					// parser error, set end node to max value.
+					newType.AddChild(new ErrorNode(), Roles.Error);
+				}
+				typeStack.Pop();
+				AddType(newType);
+			}
+
+			public override void Visit(Struct s)
+			{
+				var newType = new TypeDeclaration();
+				newType.ClassType = ClassType.Struct;
+				AddAttributeSection(newType, s);
+				var location = LocationsBag.GetMemberLocation(s);
+				AddModifiers(newType, location);
+				int curLoc = 0;
+				if (location != null && location.Count > 0)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.StructKeyword), Roles.StructKeyword);
+				newType.AddChild(Identifier.Create(s.MemberName.Name, Convert(s.MemberName.Location)), Roles.Identifier);
+				AddTypeParameters(newType, s.MemberName);
+				
+				if (s.TypeBaseExpressions != null) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Colon), Roles.Colon);
+					var commaLocations = LocationsBag.GetLocations(s.TypeBaseExpressions);
+					int i = 0;
+					foreach (var baseTypes in s.TypeBaseExpressions) {
+						newType.AddChild(ConvertToType(baseTypes), Roles.BaseType);
+						if (commaLocations != null && i < commaLocations.Count) {
+							newType.AddChild(new CSharpTokenNode(Convert(commaLocations [i]), Roles.Comma), Roles.Comma);
+							i++;
+						}
+					}
+				}
+				
+				AddConstraints(newType, s.CurrentTypeParameters);
+				if (location != null && curLoc < location.Count)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.LBrace), Roles.LBrace);
+				typeStack.Push(newType);
+				base.Visit(s);
+				if (location != null && location.Count > 2) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.RBrace), Roles.RBrace);
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Semicolon), Roles.Semicolon);
+				} else {
+					// parser error, set end node to max value.
+					newType.AddChild(new ErrorNode(), Roles.Error);
+				}
+				typeStack.Pop();
+				AddType(newType);
+			}
+
+			public override void Visit(Interface i)
+			{
+				var newType = new TypeDeclaration();
+				newType.ClassType = ClassType.Interface;
+				AddAttributeSection(newType, i);
+				var location = LocationsBag.GetMemberLocation(i);
+				AddModifiers(newType, location);
+				int curLoc = 0;
+				if (location != null && location.Count > 0)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.InterfaceKeyword), Roles.InterfaceKeyword);
+				newType.AddChild(Identifier.Create(i.MemberName.Name, Convert(i.MemberName.Location)), Roles.Identifier);
+				AddTypeParameters(newType, i.MemberName);
+				
+				if (i.TypeBaseExpressions != null) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Colon), Roles.Colon);
+					var commaLocations = LocationsBag.GetLocations(i.TypeBaseExpressions);
+					int j = 0;
+					foreach (var baseTypes in i.TypeBaseExpressions) {
+						newType.AddChild(ConvertToType(baseTypes), Roles.BaseType);
+						if (commaLocations != null && j < commaLocations.Count) {
+							newType.AddChild(new CSharpTokenNode(Convert(commaLocations [j]), Roles.Comma), Roles.Comma);
+							j++;
+						}
+					}
+				}
+				
+				AddConstraints(newType, i.CurrentTypeParameters);
+				if (location != null && curLoc < location.Count)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.LBrace), Roles.LBrace);
+				typeStack.Push(newType);
+				base.Visit(i);
+				if (location != null && location.Count > 2) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.RBrace), Roles.RBrace);
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Semicolon), Roles.Semicolon);
+				} else {
+					// parser error, set end node to max value.
+					newType.AddChild(new ErrorNode(), Roles.Error);
+				}
+				typeStack.Pop();
+				AddType(newType);
+			}
+
+			public override void Visit(Mono.CSharp.Delegate d)
+			{
+				var newDelegate = new DelegateDeclaration();
+				var location = LocationsBag.GetMemberLocation(d);
+				AddAttributeSection(newDelegate, d);
+				AddModifiers(newDelegate, location);
+				if (location != null && location.Count > 0) {
+					newDelegate.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.DelegateKeyword), Roles.DelegateKeyword);
+				}
+				if (d.ReturnType != null)
+					newDelegate.AddChild(ConvertToType(d.ReturnType), Roles.Type);
+				newDelegate.AddChild(Identifier.Create(d.MemberName.Name, Convert(d.MemberName.Location)), Roles.Identifier);
+				AddTypeParameters(newDelegate, d.MemberName);
+				
+				if (location != null && location.Count > 1)
+					newDelegate.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.LPar), Roles.LPar);
+				AddParameter(newDelegate, d.Parameters);
+				
+				if (location != null && location.Count > 2) {
+					newDelegate.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.RPar), Roles.RPar);
+				}
+				AddConstraints(newDelegate, d.CurrentTypeParameters);
+				if (location != null && location.Count > 3) {
+					newDelegate.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.Semicolon), Roles.Semicolon);
+				}
+				AddType(newDelegate);
+			}
+
+			void AddType(EntityDeclaration child)
+			{
+				if (typeStack.Count > 0) {
+					typeStack.Peek().AddChild(child, Roles.TypeMemberRole);
+				} else {
+					AddToNamespace(child);
+				}
+			}
+
+			void AddToNamespace(AstNode child)
+			{
+				if (namespaceStack.Count > 0) {
+					namespaceStack.Peek().AddChild(child, NamespaceDeclaration.MemberRole);
+				} else {
+					unit.AddChild(child, SyntaxTree.MemberRole);
+				}
+			}
+
+			public override void Visit(Mono.CSharp.Enum e)
+			{
+				var newType = new TypeDeclaration();
+				newType.ClassType = ClassType.Enum;
+				AddAttributeSection(newType, e);
+				var location = LocationsBag.GetMemberLocation(e);
+				
+				AddModifiers(newType, location);
+				int curLoc = 0;
+				if (location != null && location.Count > 0)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.EnumKeyword), Roles.EnumKeyword);
+				newType.AddChild(Identifier.Create(e.MemberName.Name, Convert(e.MemberName.Location)), Roles.Identifier);
+				
+				if (e.BaseTypeExpression != null) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Colon), Roles.Colon);
+					newType.AddChild(ConvertToType(e.BaseTypeExpression), Roles.BaseType);
+				}
+
+				if (location != null && curLoc < location.Count)
+					newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.LBrace), Roles.LBrace);
+				typeStack.Push(newType);
+				
+				foreach (var m in e.Members) {
+					var member = m as EnumMember;
+					if (member == null) {
+						Console.WriteLine("WARNING - ENUM MEMBER: " + m);
+						continue;
+					}
+					Visit(member);
+					if (location != null && curLoc < location.Count - 1) //last one is closing brace
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Comma), Roles.Comma);
+				}
+				
+				if (location != null && location.Count > 2) {
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.RBrace), Roles.RBrace);
+					if (location != null && curLoc < location.Count)
+						newType.AddChild(new CSharpTokenNode(Convert(location [curLoc++]), Roles.Semicolon), Roles.Semicolon);
+				} else {
+					// parser error, set end node to max value.
+					newType.AddChild(new ErrorNode(), Roles.Error);
+				}
+
+				AddAttributeSection(newType, e.UnattachedAttributes, EntityDeclaration.UnattachedAttributeRole);
+				typeStack.Pop();
+				AddType(newType);
+			}
+
+			public override void Visit(EnumMember em)
+			{
+				var newField = new EnumMemberDeclaration();
+				AddAttributeSection(newField, em);
+				newField.AddChild(Identifier.Create(em.Name, Convert(em.Location)), Roles.Identifier);
+				if (em.Initializer != null) {
+					newField.AddChild(new CSharpTokenNode(Convert(em.Initializer.Location), Roles.Assign), Roles.Assign);
+					newField.AddChild((Expression)em.Initializer.Accept(this), EnumMemberDeclaration.InitializerRole);
+				}
+				//Console.WriteLine (newField.StartLocation +"-" + newField.EndLocation);
+				
+				typeStack.Peek().AddChild(newField, Roles.TypeMemberRole);
+			}
+
+			#endregion
+
+			#region Type members
+
+			public override void Visit(FixedField f)
+			{
+				var location = LocationsBag.GetMemberLocation(f);
+				int locationIdx = 0;
+				
+				var newField = new FixedFieldDeclaration();
+				AddAttributeSection(newField, f);
+				AddModifiers(newField, location);
+				if (location != null && location.Count > 0)
+					newField.AddChild(new CSharpTokenNode(Convert(location [locationIdx++]), FixedFieldDeclaration.FixedKeywordRole), FixedFieldDeclaration.FixedKeywordRole);
+
+				if (f.TypeExpression != null)
+					newField.AddChild(ConvertToType(f.TypeExpression), Roles.Type);
+				
+				var variable = new FixedVariableInitializer();
+				variable.AddChild(Identifier.Create(f.MemberName.Name, Convert(f.MemberName.Location)), Roles.Identifier);
+				if (f.Initializer != null && !f.Initializer.IsNull) {
+					variable.AddChild(new CSharpTokenNode(Convert(f.Initializer.Location), Roles.LBracket), Roles.LBracket);
+					
+					variable.AddChild((Expression)f.Initializer.Accept(this), Roles.Expression);
+					var bracketLocations = LocationsBag.GetLocations(f.Initializer);
+					if (bracketLocations != null)
+						variable.AddChild(new CSharpTokenNode(Convert(bracketLocations [0]), Roles.RBracket), Roles.RBracket);
+				}
+				newField.AddChild(variable, FixedFieldDeclaration.VariableRole);
+				
+				if (f.Declarators != null) {
+					foreach (var decl in f.Declarators) {
+						var declLoc = LocationsBag.GetLocations(decl);
+						if (declLoc != null)
+							newField.AddChild(new CSharpTokenNode(Convert(declLoc [0]), Roles.Comma), Roles.Comma);
+						
+						variable = new FixedVariableInitializer();
+						variable.AddChild(Identifier.Create(decl.Name.Value, Convert(decl.Name.Location)), Roles.Identifier);
+						variable.AddChild(new CSharpTokenNode(Convert(decl.Initializer.Location), Roles.LBracket), Roles.LBracket);
+						variable.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+						var bracketLocations = LocationsBag.GetLocations(decl.Initializer);
+						if (bracketLocations != null)
+							variable.AddChild(new CSharpTokenNode(Convert(bracketLocations [0]), Roles.RBracket), Roles.RBracket);
+
+						newField.AddChild(variable, FixedFieldDeclaration.VariableRole);
+					}
+				}
+				if (location != null && location.Count > locationIdx)
+					newField.AddChild(new CSharpTokenNode(Convert(location [locationIdx]), Roles.Semicolon), Roles.Semicolon);
+				typeStack.Peek().AddChild(newField, Roles.TypeMemberRole);
+				
+			}
+
+			public override void Visit(Field f)
+			{
+				var location = LocationsBag.GetMemberLocation(f);
+				
+				var newField = new FieldDeclaration();
+				AddAttributeSection(newField, f);
+				AddModifiers(newField, location);
+				newField.AddChild(ConvertToType(f.TypeExpression), Roles.Type);
+				
+				var variable = new VariableInitializer();
+				variable.AddChild(Identifier.Create(f.MemberName.Name, Convert(f.MemberName.Location)), Roles.Identifier);
+				int locationIdx = 0;
+				if (f.Initializer != null) {
+					if (location != null)
+						variable.AddChild(new CSharpTokenNode(Convert(location [locationIdx++]), Roles.Assign), Roles.Assign);
+					variable.AddChild((Expression)f.Initializer.Accept(this), Roles.Expression);
+				}
+				newField.AddChild(variable, Roles.Variable);
+				if (f.Declarators != null) {
+					foreach (var decl in f.Declarators) {
+						var declLoc = LocationsBag.GetLocations(decl);
+						if (declLoc != null)
+							newField.AddChild(new CSharpTokenNode(Convert(declLoc [0]), Roles.Comma), Roles.Comma);
+						
+						variable = new VariableInitializer();
+						variable.AddChild(Identifier.Create(decl.Name.Value, Convert(decl.Name.Location)), Roles.Identifier);
+						if (decl.Initializer != null) {
+							if (declLoc != null)
+								variable.AddChild(new CSharpTokenNode(Convert(declLoc [1]), Roles.Assign), Roles.Assign);
+							variable.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+						}
+						newField.AddChild(variable, Roles.Variable);
+					}
+				}
+				if (location != null && location.Count > locationIdx)
+					newField.AddChild(new CSharpTokenNode(Convert(location [locationIdx++]), Roles.Semicolon), Roles.Semicolon);
+
+				typeStack.Peek().AddChild(newField, Roles.TypeMemberRole);
+			}
+
+			public override void Visit(Const c)
+			{
+				var location = LocationsBag.GetMemberLocation(c);
+				
+				var newField = new FieldDeclaration();
+				AddAttributeSection(newField, c);
+				AddModifiers(newField, location);
+				if (location != null)
+					newField.AddChild(new CSharpModifierToken(Convert(location [0]), Modifiers.Const), EntityDeclaration.ModifierRole);
+				newField.AddChild(ConvertToType(c.TypeExpression), Roles.Type);
+				
+				var variable = new VariableInitializer();
+				variable.AddChild(Identifier.Create(c.MemberName.Name, Convert(c.MemberName.Location)), Roles.Identifier);
+				
+				if (c.Initializer != null) {
+					variable.AddChild(new CSharpTokenNode(Convert(c.Initializer.Location), Roles.Assign), Roles.Assign);
+					variable.AddChild((Expression)c.Initializer.Accept(this), Roles.Expression);
+				}
+				newField.AddChild(variable, Roles.Variable);
+				if (c.Declarators != null) {
+					foreach (var decl in c.Declarators) {
+						var declLoc = LocationsBag.GetLocations(decl);
+						if (declLoc != null)
+							newField.AddChild(new CSharpTokenNode(Convert(declLoc [0]), Roles.Comma), Roles.Comma);
+						
+						variable = new VariableInitializer();
+						variable.AddChild(Identifier.Create(decl.Name.Value, Convert(decl.Name.Location)), Roles.Identifier);
+						if (decl.Initializer != null) {
+							variable.AddChild(new CSharpTokenNode(Convert(decl.Initializer.Location), Roles.Assign), Roles.Assign);
+							variable.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+						}
+						newField.AddChild(variable, Roles.Variable);
+					}
+				}
+				if (location != null)
+					newField.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				
+				typeStack.Peek().AddChild(newField, Roles.TypeMemberRole);
+
+				
+			}
+
+			public override void Visit(Operator o)
+			{
+				var newOperator = new OperatorDeclaration();
+				newOperator.OperatorType = (OperatorType)o.OperatorType;
+				
+				var location = LocationsBag.GetMemberLocation(o);
+				AddAttributeSection(newOperator, o);
+				AddModifiers(newOperator, location);
+				
+				
+				if (o.OperatorType == Operator.OpType.Implicit) {
+					if (location != null && location.Count > 0) {
+						newOperator.AddChild(new CSharpTokenNode(Convert(location [0]), OperatorDeclaration.ImplicitRole), OperatorDeclaration.ImplicitRole);
+						if (location.Count > 1)
+							newOperator.AddChild(new CSharpTokenNode(Convert(location [1]), OperatorDeclaration.OperatorKeywordRole), OperatorDeclaration.OperatorKeywordRole);
+					}
+					newOperator.AddChild(ConvertToType(o.TypeExpression), Roles.Type);
+				} else if (o.OperatorType == Operator.OpType.Explicit) {
+					if (location != null && location.Count > 0) {
+						newOperator.AddChild(new CSharpTokenNode(Convert(location [0]), OperatorDeclaration.ExplicitRole), OperatorDeclaration.ExplicitRole);
+						if (location.Count > 1)
+							newOperator.AddChild(new CSharpTokenNode(Convert(location [1]), OperatorDeclaration.OperatorKeywordRole), OperatorDeclaration.OperatorKeywordRole);
+					}
+					newOperator.AddChild(ConvertToType(o.TypeExpression), Roles.Type);
+				} else {
+					newOperator.AddChild(ConvertToType(o.TypeExpression), Roles.Type);
+
+					if (location != null && location.Count > 0)
+						newOperator.AddChild(new CSharpTokenNode(Convert(location [0]), OperatorDeclaration.OperatorKeywordRole), OperatorDeclaration.OperatorKeywordRole);
+					
+					if (location != null && location.Count > 1) {
+						var r = OperatorDeclaration.GetRole(newOperator.OperatorType);
+						newOperator.AddChild(new CSharpTokenNode(Convert(location [1]), r), r);
+					}
+				}
+				if (location != null && location.Count > 2)
+					newOperator.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.LPar), Roles.LPar);
+				AddParameter(newOperator, o.ParameterInfo);
+				if (location != null && location.Count > 3)
+					newOperator.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.RPar), Roles.RPar);
+				
+				if (o.Block != null) {
+					newOperator.AddChild((BlockStatement)o.Block.Accept(this), Roles.Body);
+				} else {
+					if (location != null && location.Count >= 5)
+						newOperator.AddChild(new CSharpTokenNode(Convert(location [4]), Roles.Semicolon), Roles.Semicolon);
+				}
+				typeStack.Peek().AddChild(newOperator, Roles.TypeMemberRole);
+			}
+
+			public void AddAttributeSection(AstNode parent, Attributable a)
+			{
+				if (a == null || a.OptAttributes == null)
+					return;
+				AddAttributeSection(parent, a.OptAttributes);
+			}
+
+			public void AddAttributeSection(AstNode parent, Attributes attrs, Role<AttributeSection> role)
+			{
+				if (attrs == null)
+					return;
+				foreach (var attr in attrs.Sections) {
+					var section = ConvertAttributeSection(attr);
+					if (section == null)
+						continue;
+					parent.AddChild(section, role);
+				}
+			}
+
+			public void AddAttributeSection(AstNode parent, Attributes attrs)
+			{
+				AddAttributeSection(parent, attrs, EntityDeclaration.AttributeRole);
+			}
+
+			public override void Visit(Indexer i)
+			{
+				var newIndexer = new IndexerDeclaration();
+				AddAttributeSection(newIndexer, i);
+				var location = LocationsBag.GetMemberLocation(i);
+				AddModifiers(newIndexer, location);
+				newIndexer.AddChild(ConvertToType(i.TypeExpression), Roles.Type);
+				AddExplicitInterface(newIndexer, i.MemberName);
+				var name = i.MemberName;
+				newIndexer.AddChild(new CSharpTokenNode(Convert(name.Location), IndexerDeclaration.ThisKeywordRole), IndexerDeclaration.ThisKeywordRole);
+				
+				if (location != null && location.Count > 0)
+					newIndexer.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LBracket), Roles.LBracket);
+				AddParameter(newIndexer, i.ParameterInfo);
+				if (location != null && location.Count > 1)
+					newIndexer.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RBracket), Roles.RBracket);
+				
+				if (location != null && location.Count > 2)
+					newIndexer.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.LBrace), Roles.LBrace);
+				if (i.Get != null) {
+					var getAccessor = new Accessor();
+					var getLocation = LocationsBag.GetMemberLocation(i.Get);
+					AddAttributeSection(getAccessor, i.Get);
+					AddModifiers(getAccessor, getLocation);
+					if (getLocation != null)
+						getAccessor.AddChild(new CSharpTokenNode(Convert(i.Get.Location), PropertyDeclaration.GetKeywordRole), PropertyDeclaration.GetKeywordRole);
+					if (i.Get.Block != null) {
+						getAccessor.AddChild((BlockStatement)i.Get.Block.Accept(this), Roles.Body);
+					} else {
+						if (getLocation != null && getLocation.Count > 0)
+							newIndexer.AddChild(new CSharpTokenNode(Convert(getLocation [0]), Roles.Semicolon), Roles.Semicolon);
+					}
+					newIndexer.AddChild(getAccessor, PropertyDeclaration.GetterRole);
+				}
+				
+				if (i.Set != null) {
+					var setAccessor = new Accessor();
+					var setLocation = LocationsBag.GetMemberLocation(i.Set);
+					AddAttributeSection(setAccessor, i.Set);
+					AddModifiers(setAccessor, setLocation);
+					if (setLocation != null)
+						setAccessor.AddChild(new CSharpTokenNode(Convert(i.Set.Location), PropertyDeclaration.SetKeywordRole), PropertyDeclaration.SetKeywordRole);
+					
+					if (i.Set.Block != null) {
+						setAccessor.AddChild((BlockStatement)i.Set.Block.Accept(this), Roles.Body);
+					} else {
+						if (setLocation != null && setLocation.Count > 0)
+							newIndexer.AddChild(new CSharpTokenNode(Convert(setLocation [0]), Roles.Semicolon), Roles.Semicolon);
+					}
+					newIndexer.AddChild(setAccessor, PropertyDeclaration.SetterRole);
+				}
+				
+				if (location != null) {
+					if (location.Count > 3)
+						newIndexer.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.RBrace), Roles.RBrace);
+				} else {
+					// parser error, set end node to max value.
+					newIndexer.AddChild(new ErrorNode(), Roles.Error);
+				}
+				typeStack.Peek().AddChild(newIndexer, Roles.TypeMemberRole);
+			}
+
+			public override void Visit(Method m)
+			{
+				var newMethod = new MethodDeclaration();
+				AddAttributeSection(newMethod, m);
+				var location = LocationsBag.GetMemberLocation(m);
+				AddModifiers(newMethod, location);
+				newMethod.AddChild(ConvertToType(m.TypeExpression), Roles.Type);
+				AddExplicitInterface(newMethod, m.MethodName);
+				newMethod.AddChild(Identifier.Create(m.MethodName.Name, Convert(m.Location)), Roles.Identifier);
+				
+				AddTypeParameters(newMethod, m.MemberName);
+				
+				if (location != null && location.Count > 0)
+					newMethod.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				AddParameter(newMethod, m.ParameterInfo);
+				
+				if (location != null && location.Count > 1)
+					newMethod.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				
+				AddConstraints(newMethod, m.CurrentTypeParameters);
+				
+				if (m.Block != null) {
+					var bodyBlock = (BlockStatement)m.Block.Accept(this);
+//					if (m.Block is ToplevelBlock) {
+//						newMethod.AddChild (bodyBlock.FirstChild.NextSibling, Roles.Body);
+//					} else {
+					newMethod.AddChild(bodyBlock, Roles.Body);
+//					}
+				} else if (location != null) {
+					if (location.Count < 3) {
+						// parser error, set end node to max value.
+						newMethod.AddChild(new ErrorNode(), Roles.Error);
+					} else {
+						newMethod.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.Semicolon), Roles.Semicolon);
+					}
+				}
+				typeStack.Peek().AddChild(newMethod, Roles.TypeMemberRole);
+			}
+
+			static readonly Dictionary<Mono.CSharp.Modifiers, Modifiers> modifierTable = new Dictionary<Mono.CSharp.Modifiers, Modifiers>();
+			static readonly string[] keywordTable;
+
+			static ConversionVisitor()
+			{
+				modifierTable [Mono.CSharp.Modifiers.NEW] = Modifiers.New;
+				modifierTable [Mono.CSharp.Modifiers.PUBLIC] = Modifiers.Public;
+				modifierTable [Mono.CSharp.Modifiers.PROTECTED] = Modifiers.Protected;
+				modifierTable [Mono.CSharp.Modifiers.PRIVATE] = Modifiers.Private;
+				modifierTable [Mono.CSharp.Modifiers.INTERNAL] = Modifiers.Internal;
+				modifierTable [Mono.CSharp.Modifiers.ABSTRACT] = Modifiers.Abstract;
+				modifierTable [Mono.CSharp.Modifiers.VIRTUAL] = Modifiers.Virtual;
+				modifierTable [Mono.CSharp.Modifiers.SEALED] = Modifiers.Sealed;
+				modifierTable [Mono.CSharp.Modifiers.STATIC] = Modifiers.Static;
+				modifierTable [Mono.CSharp.Modifiers.OVERRIDE] = Modifiers.Override;
+				modifierTable [Mono.CSharp.Modifiers.READONLY] = Modifiers.Readonly;
+				modifierTable [Mono.CSharp.Modifiers.PARTIAL] = Modifiers.Partial;
+				modifierTable [Mono.CSharp.Modifiers.EXTERN] = Modifiers.Extern;
+				modifierTable [Mono.CSharp.Modifiers.VOLATILE] = Modifiers.Volatile;
+				modifierTable [Mono.CSharp.Modifiers.UNSAFE] = Modifiers.Unsafe;
+				modifierTable [Mono.CSharp.Modifiers.ASYNC] = Modifiers.Async;
+				
+				keywordTable = new string[255];
+				for (int i = 0; i< keywordTable.Length; i++)
+					keywordTable [i] = "unknown";
+				
+				keywordTable [(int)BuiltinTypeSpec.Type.Other] = "void";
+				keywordTable [(int)BuiltinTypeSpec.Type.String] = "string";
+				keywordTable [(int)BuiltinTypeSpec.Type.Int] = "int";
+				keywordTable [(int)BuiltinTypeSpec.Type.Object] = "object";
+				keywordTable [(int)BuiltinTypeSpec.Type.Float] = "float";
+				keywordTable [(int)BuiltinTypeSpec.Type.Double] = "double";
+				keywordTable [(int)BuiltinTypeSpec.Type.Long] = "long";
+				keywordTable [(int)BuiltinTypeSpec.Type.Byte] = "byte";
+				keywordTable [(int)BuiltinTypeSpec.Type.UInt] = "uint";
+				keywordTable [(int)BuiltinTypeSpec.Type.ULong] = "ulong";
+				keywordTable [(int)BuiltinTypeSpec.Type.Short] = "short";
+				keywordTable [(int)BuiltinTypeSpec.Type.UShort] = "ushort";
+				keywordTable [(int)BuiltinTypeSpec.Type.SByte] = "sbyte";
+				keywordTable [(int)BuiltinTypeSpec.Type.Decimal] = "decimal";
+				keywordTable [(int)BuiltinTypeSpec.Type.Char] = "char";
+				keywordTable [(int)BuiltinTypeSpec.Type.Bool] = "bool";
+			}
+
+			static void AddModifiers(EntityDeclaration parent, LocationsBag.MemberLocations location)
+			{
+				if (location == null || location.Modifiers == null)
+					return;
+				foreach (var modifier in location.Modifiers) {
+					Modifiers mod;
+					if (!modifierTable.TryGetValue(modifier.Item1, out mod)) {
+						Console.WriteLine("modifier " + modifier.Item1 + " can't be converted,");
+					}
+					
+					parent.AddChild(new CSharpModifierToken(Convert(modifier.Item2), mod), EntityDeclaration.ModifierRole);
+				}
+			}
+
+			public override void Visit(Property p)
+			{
+				var newProperty = new PropertyDeclaration();
+				AddAttributeSection(newProperty, p);
+				var location = LocationsBag.GetMemberLocation(p);
+				AddModifiers(newProperty, location);
+				newProperty.AddChild(ConvertToType(p.TypeExpression), Roles.Type);
+				AddExplicitInterface(newProperty, p.MemberName);
+				newProperty.AddChild(Identifier.Create(p.MemberName.Name, Convert(p.Location)), Roles.Identifier);
+				
+				if (location != null && location.Count > 0)
+					newProperty.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LBrace), Roles.LBrace);
+				
+				Accessor getAccessor = null;
+				if (p.Get != null) {
+					getAccessor = new Accessor();
+					AddAttributeSection(getAccessor, p.Get);
+					var getLocation = LocationsBag.GetMemberLocation(p.Get);
+					AddModifiers(getAccessor, getLocation);
+					getAccessor.AddChild(new CSharpTokenNode(Convert(p.Get.Location), PropertyDeclaration.GetKeywordRole), PropertyDeclaration.GetKeywordRole);
+					
+					if (p.Get.Block != null) {
+						getAccessor.AddChild((BlockStatement)p.Get.Block.Accept(this), Roles.Body);
+					} else {
+						if (getLocation != null && getLocation.Count > 0)
+							getAccessor.AddChild(new CSharpTokenNode(Convert(getLocation [0]), Roles.Semicolon), Roles.Semicolon);
+					}
+				}
+				
+				Accessor setAccessor = null;
+				if (p.Set != null) {
+					setAccessor = new Accessor();
+					AddAttributeSection(setAccessor, p.Set);
+					var setLocation = LocationsBag.GetMemberLocation(p.Set);
+					AddModifiers(setAccessor, setLocation);
+					setAccessor.AddChild(new CSharpTokenNode(Convert(p.Set.Location), PropertyDeclaration.SetKeywordRole), PropertyDeclaration.SetKeywordRole);
+					
+					if (p.Set.Block != null) {
+						setAccessor.AddChild((BlockStatement)p.Set.Block.Accept(this), Roles.Body);
+					} else {
+						if (setLocation != null && setLocation.Count > 0)
+							setAccessor.AddChild(new CSharpTokenNode(Convert(setLocation [0]), Roles.Semicolon), Roles.Semicolon);
+					}
+				}
+				if (getAccessor != null && setAccessor != null) {
+					if (getAccessor.StartLocation < setAccessor.StartLocation) {
+						newProperty.AddChild(getAccessor, PropertyDeclaration.GetterRole);
+						newProperty.AddChild(setAccessor, PropertyDeclaration.SetterRole);
+					} else {
+						newProperty.AddChild(setAccessor, PropertyDeclaration.SetterRole);
+						newProperty.AddChild(getAccessor, PropertyDeclaration.GetterRole);
+					}
+				} else {
+					if (getAccessor != null)
+						newProperty.AddChild(getAccessor, PropertyDeclaration.GetterRole);
+					if (setAccessor != null)
+						newProperty.AddChild(setAccessor, PropertyDeclaration.SetterRole);
+				}
+				
+				if (location != null && location.Count > 1) {
+					newProperty.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RBrace), Roles.RBrace);
+				} else {
+					// parser error, set end node to max value.
+					newProperty.AddChild(new ErrorNode(), Roles.Error);
+				}
+				
+				typeStack.Peek().AddChild(newProperty, Roles.TypeMemberRole);
+			}
+
+			public override void Visit(Constructor c)
+			{
+				var newConstructor = new ConstructorDeclaration();
+				AddAttributeSection(newConstructor, c);
+				var location = LocationsBag.GetMemberLocation(c);
+				AddModifiers(newConstructor, location);
+				newConstructor.AddChild(Identifier.Create(c.MemberName.Name, Convert(c.MemberName.Location)), Roles.Identifier);
+				if (location != null && location.Count > 0)
+					newConstructor.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				AddParameter(newConstructor, c.ParameterInfo);
+				if (location != null && location.Count > 1)
+					newConstructor.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				
+				if (c.Initializer != null) {
+					var initializer = new ConstructorInitializer();
+					initializer.ConstructorInitializerType = c.Initializer is ConstructorBaseInitializer ? ConstructorInitializerType.Base : ConstructorInitializerType.This;
+					var initializerLocation = LocationsBag.GetLocations(c.Initializer);
+					
+					if (initializerLocation != null)
+						newConstructor.AddChild(new CSharpTokenNode(Convert(initializerLocation [0]), Roles.Colon), Roles.Colon);
+					
+					if (initializerLocation != null && initializerLocation.Count > 1) {
+						// this and base has the same length
+						var r = initializer.ConstructorInitializerType == ConstructorInitializerType.This ? ConstructorInitializer.ThisKeywordRole : ConstructorInitializer.BaseKeywordRole;
+						initializer.AddChild(new CSharpTokenNode(Convert(c.Initializer.Location), r), r);
+						initializer.AddChild(new CSharpTokenNode(Convert(initializerLocation [1]), Roles.LPar), Roles.LPar);
+						AddArguments(initializer, c.Initializer.Arguments);
+						initializer.AddChild(new CSharpTokenNode(Convert(initializerLocation [2]), Roles.RPar), Roles.RPar);
+						newConstructor.AddChild(initializer, ConstructorDeclaration.InitializerRole);
+					}
+				}
+				
+				if (c.Block != null)
+					newConstructor.AddChild((BlockStatement)c.Block.Accept(this), Roles.Body);
+				typeStack.Peek().AddChild(newConstructor, Roles.TypeMemberRole);
+			}
+
+			public override void Visit(Destructor d)
+			{
+				var newDestructor = new DestructorDeclaration();
+				AddAttributeSection(newDestructor, d);
+				var location = LocationsBag.GetMemberLocation(d);
+				AddModifiers(newDestructor, location);
+				if (location != null && location.Count > 0)
+					newDestructor.AddChild(new CSharpTokenNode(Convert(location [0]), DestructorDeclaration.TildeRole), DestructorDeclaration.TildeRole);
+				newDestructor.AddChild(Identifier.Create(d.Identifier, Convert(d.MemberName.Location)), Roles.Identifier);
+				
+				if (location != null && location.Count > 1) {
+					newDestructor.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.LPar), Roles.LPar);
+					
+					if (location.Count > 2)
+						newDestructor.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.RPar), Roles.RPar);
+				}
+				
+				if (d.Block != null)
+					newDestructor.AddChild((BlockStatement)d.Block.Accept(this), Roles.Body);
+				
+				typeStack.Peek().AddChild(newDestructor, Roles.TypeMemberRole);
+			}
+
+			public override void Visit(EventField e)
+			{
+				var newEvent = new EventDeclaration();
+				AddAttributeSection(newEvent, e);
+				var location = LocationsBag.GetMemberLocation(e);
+				int l = 0;
+				AddModifiers(newEvent, location);
+				
+				if (location != null && location.Count > 0)
+					newEvent.AddChild(new CSharpTokenNode(Convert(location [l++]), EventDeclaration.EventKeywordRole), EventDeclaration.EventKeywordRole);
+				newEvent.AddChild(ConvertToType(e.TypeExpression), Roles.Type);
+				
+				var variable = new VariableInitializer();
+				variable.AddChild(Identifier.Create(e.MemberName.Name, Convert(e.MemberName.Location)), Roles.Identifier);
+				
+				if (e.Initializer != null) {
+					if (location != null && location.Count > l)
+						variable.AddChild(new CSharpTokenNode(Convert(location [l++]), Roles.Assign), Roles.Assign);
+					variable.AddChild((Expression)e.Initializer.Accept(this), Roles.Expression);
+				}
+				newEvent.AddChild(variable, Roles.Variable);
+				if (e.Declarators != null) {
+					foreach (var decl in e.Declarators) {
+						var declLoc = LocationsBag.GetLocations(decl);
+						if (declLoc != null)
+							newEvent.AddChild(new CSharpTokenNode(Convert(declLoc [0]), Roles.Comma), Roles.Comma);
+						
+						variable = new VariableInitializer();
+						variable.AddChild(Identifier.Create(decl.Name.Value, Convert(decl.Name.Location)), Roles.Identifier);
+
+						if (decl.Initializer != null) {
+							if (declLoc != null)
+								variable.AddChild(new CSharpTokenNode(Convert(declLoc [1]), Roles.Assign), Roles.Assign);
+							variable.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+						}
+						newEvent.AddChild(variable, Roles.Variable);
+					}
+				}
+				
+				if (location != null && location.Count > l)
+					newEvent.AddChild(new CSharpTokenNode(Convert(location [l++]), Roles.Semicolon), Roles.Semicolon);
+				
+				typeStack.Peek().AddChild(newEvent, Roles.TypeMemberRole);
+			}
+
+			void AddExplicitInterface(AstNode parent, MemberName memberName)
+			{
+				if (memberName == null || memberName.ExplicitInterface == null)
+					return;
+				
+				parent.AddChild(ConvertToType(memberName.ExplicitInterface), EntityDeclaration.PrivateImplementationTypeRole);
+				var privateImplTypeLoc = LocationsBag.GetLocations(memberName.ExplicitInterface);
+				if (privateImplTypeLoc != null)
+					parent.AddChild(new CSharpTokenNode(Convert(privateImplTypeLoc [0]), Roles.Dot), Roles.Dot);
+			}
+
+			public override void Visit(EventProperty ep)
+			{
+				var newEvent = new CustomEventDeclaration();
+				AddAttributeSection(newEvent, ep);
+				var location = LocationsBag.GetMemberLocation(ep);
+				AddModifiers(newEvent, location);
+				
+				if (location != null && location.Count > 0)
+					newEvent.AddChild(new CSharpTokenNode(Convert(location [0]), CustomEventDeclaration.EventKeywordRole), CustomEventDeclaration.EventKeywordRole);
+				newEvent.AddChild(ConvertToType(ep.TypeExpression), Roles.Type);
+				
+				AddExplicitInterface(newEvent, ep.MemberName);
+				
+				newEvent.AddChild(Identifier.Create(ep.MemberName.Name, Convert(ep.Location)), Roles.Identifier);
+
+				if (location != null && location.Count >= 2)
+					newEvent.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.LBrace), Roles.LBrace);
+				
+				if (ep.Add != null) {
+					var addAccessor = new Accessor();
+					AddAttributeSection(addAccessor, ep.Add);
+					var addLocation = LocationsBag.GetMemberLocation(ep.Add);
+					AddModifiers(addAccessor, addLocation);
+					addAccessor.AddChild(new CSharpTokenNode(Convert(ep.Add.Location), CustomEventDeclaration.AddKeywordRole), CustomEventDeclaration.AddKeywordRole);
+					if (ep.Add.Block != null)
+						addAccessor.AddChild((BlockStatement)ep.Add.Block.Accept(this), Roles.Body);
+					newEvent.AddChild(addAccessor, CustomEventDeclaration.AddAccessorRole);
+				}
+				
+				if (ep.Remove != null) {
+					var removeAccessor = new Accessor();
+					AddAttributeSection(removeAccessor, ep.Remove);
+					var removeLocation = LocationsBag.GetMemberLocation(ep.Remove);
+					AddModifiers(removeAccessor, removeLocation);
+					removeAccessor.AddChild(new CSharpTokenNode(Convert(ep.Remove.Location), CustomEventDeclaration.RemoveKeywordRole), CustomEventDeclaration.RemoveKeywordRole);
+					
+					if (ep.Remove.Block != null)
+						removeAccessor.AddChild((BlockStatement)ep.Remove.Block.Accept(this), Roles.Body);
+					newEvent.AddChild(removeAccessor, CustomEventDeclaration.RemoveAccessorRole);
+				}
+				if (location != null && location.Count >= 3) {
+					newEvent.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.RBrace), Roles.RBrace);
+				} else {
+					// parser error, set end node to max value.
+					newEvent.AddChild(new ErrorNode(), Roles.Error);
+				}
+				
+				typeStack.Peek().AddChild(newEvent, Roles.TypeMemberRole);
+			}
+
+			#endregion
+
+			#region Statements
+
+			public override object Visit(Mono.CSharp.Statement stmt)
+			{
+				Console.WriteLine("unknown statement:" + stmt);
+				return null;
+			}
+
+			public override object Visit(BlockVariable blockVariableDeclaration)
+			{
+				var result = new VariableDeclarationStatement();
+				result.AddChild(ConvertToType(blockVariableDeclaration.TypeExpression), Roles.Type);
+				
+				var varInit = new VariableInitializer();
+				var location = LocationsBag.GetLocations(blockVariableDeclaration);
+				varInit.AddChild(Identifier.Create(blockVariableDeclaration.Variable.Name, Convert(blockVariableDeclaration.Variable.Location)), Roles.Identifier);
+				if (blockVariableDeclaration.Initializer != null) {
+					if (location != null && location.Count > 0)
+						varInit.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Assign), Roles.Assign);
+					varInit.AddChild((Expression)blockVariableDeclaration.Initializer.Accept(this), Roles.Expression);
+				}
+				
+				result.AddChild(varInit, Roles.Variable);
+				
+				if (blockVariableDeclaration.Declarators != null) {
+					foreach (var decl in blockVariableDeclaration.Declarators) {
+						var loc = LocationsBag.GetLocations(decl);
+						var init = new VariableInitializer();
+						if (loc != null && loc.Count > 0)
+							result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Comma), Roles.Comma);
+						init.AddChild(Identifier.Create(decl.Variable.Name, Convert(decl.Variable.Location)), Roles.Identifier);
+						if (decl.Initializer != null) {
+							if (loc != null && loc.Count > 1)
+								init.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.Assign), Roles.Assign);
+							init.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+						}
+						result.AddChild(init, Roles.Variable);
+					}
+				}
+				if (location != null && (blockVariableDeclaration.Initializer == null || location.Count > 1))
+					result.AddChild(new CSharpTokenNode(Convert(location [location.Count - 1]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(BlockConstant blockConstantDeclaration)
+			{
+				var result = new VariableDeclarationStatement();
+				
+				var location = LocationsBag.GetLocations(blockConstantDeclaration);
+				if (location != null && location.Count > 0)
+					result.AddChild(new CSharpModifierToken(Convert(location [0]), Modifiers.Const), VariableDeclarationStatement.ModifierRole);
+				
+				result.AddChild(ConvertToType(blockConstantDeclaration.TypeExpression), Roles.Type);
+				
+				var varInit = new VariableInitializer();
+				varInit.AddChild(Identifier.Create(blockConstantDeclaration.Variable.Name, Convert(blockConstantDeclaration.Variable.Location)), Roles.Identifier);
+				if (blockConstantDeclaration.Initializer != null) {
+					if (location != null && location.Count > 1)
+						varInit.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Assign), Roles.Assign);
+					varInit.AddChild((Expression)blockConstantDeclaration.Initializer.Accept(this), Roles.Expression);
+				}
+				
+				result.AddChild(varInit, Roles.Variable);
+				
+				if (blockConstantDeclaration.Declarators != null) {
+					foreach (var decl in blockConstantDeclaration.Declarators) {
+						var loc = LocationsBag.GetLocations(decl);
+						var init = new VariableInitializer();
+						init.AddChild(Identifier.Create(decl.Variable.Name, Convert(decl.Variable.Location)), Roles.Identifier);
+						if (decl.Initializer != null) {
+							if (loc != null)
+								init.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Assign), Roles.Assign);
+							init.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+							if (loc != null && loc.Count > 1)
+								result.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.Comma), Roles.Comma);
+						} else {
+							if (loc != null && loc.Count > 0)
+								result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Comma), Roles.Comma);
+						}
+						result.AddChild(init, Roles.Variable);
+					}
+				}
+				if (location != null) {
+					result.AddChild(new CSharpTokenNode(Convert(location [location.Count - 1]), Roles.Semicolon), Roles.Semicolon);
+				} else {
+					// parser error, set end node to max value.
+					result.AddChild(new ErrorNode(), Roles.Error);
+				}
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.EmptyStatement emptyStatement)
+			{
+				var result = new EmptyStatement();
+				result.Location = Convert(emptyStatement.loc);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.ErrorExpression errorExpression)
+			{
+				return new ErrorExpression(Convert(errorExpression.Location));
+			}
+
+			public override object Visit(EmptyExpressionStatement emptyExpressionStatement)
+			{
+				// Should never happen.
+				throw new NotSupportedException();
+			}
+
+			public override object Visit(If ifStatement)
+			{
+				var result = new IfElseStatement();
+				
+				var location = LocationsBag.GetLocations(ifStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(ifStatement.loc), IfElseStatement.IfKeywordRole), IfElseStatement.IfKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (ifStatement.Expr != null)
+					result.AddChild((Expression)ifStatement.Expr.Accept(this), Roles.Condition);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				
+				if (ifStatement.TrueStatement != null)
+					result.AddChild((Statement)ifStatement.TrueStatement.Accept(this), IfElseStatement.TrueRole);
+				
+				if (ifStatement.FalseStatement != null) {
+					if (location != null && location.Count > 2)
+						result.AddChild(new CSharpTokenNode(Convert(location [2]), IfElseStatement.ElseKeywordRole), IfElseStatement.ElseKeywordRole);
+					result.AddChild((Statement)ifStatement.FalseStatement.Accept(this), IfElseStatement.FalseRole);
+				}
+				
+				return result;
+			}
+
+			public override object Visit(Do doStatement)
+			{
+				var result = new DoWhileStatement();
+				var location = LocationsBag.GetLocations(doStatement);
+				result.AddChild(new CSharpTokenNode(Convert(doStatement.loc), DoWhileStatement.DoKeywordRole), DoWhileStatement.DoKeywordRole);
+				if (doStatement.Statement != null)
+					result.AddChild((Statement)doStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), DoWhileStatement.WhileKeywordRole), DoWhileStatement.WhileKeywordRole);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.LPar), Roles.LPar);
+				if (doStatement.expr != null)
+					result.AddChild((Expression)doStatement.expr.Accept(this), Roles.Condition);
+				if (location != null && location.Count > 2) {
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.RPar), Roles.RPar);
+					if (location.Count > 3)
+						result.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.Semicolon), Roles.Semicolon);
+				}
+				
+				return result;
+			}
+
+			public override object Visit(While whileStatement)
+			{
+				var result = new WhileStatement();
+				var location = LocationsBag.GetLocations(whileStatement);
+				result.AddChild(new CSharpTokenNode(Convert(whileStatement.loc), WhileStatement.WhileKeywordRole), WhileStatement.WhileKeywordRole);
+				
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (whileStatement.expr != null)
+					result.AddChild((Expression)whileStatement.expr.Accept(this), Roles.Condition);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				if (whileStatement.Statement != null)
+					result.AddChild((Statement)whileStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				return result;
+			}
+
+			void AddStatementOrList(ForStatement forStatement, Mono.CSharp.Statement init, Role<Statement> role)
+			{
+				if (init == null)
+					return;
+				var stmtList = init as StatementList;
+				if (stmtList != null) {
+					foreach (var stmt in stmtList.Statements) {
+						forStatement.AddChild((Statement)stmt.Accept(this), role);
+					}
+				} else if (init is Mono.CSharp.EmptyStatement) {
+					
+				} else {
+					forStatement.AddChild((Statement)init.Accept(this), role);
+				}
+			}
+
+			public override object Visit(For forStatement)
+			{
+				var result = new ForStatement();
+				
+				var location = LocationsBag.GetLocations(forStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(forStatement.loc), ForStatement.ForKeywordRole), ForStatement.ForKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				AddStatementOrList(result, forStatement.Initializer, ForStatement.InitializerRole);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				if (forStatement.Condition != null)
+					result.AddChild((Expression)forStatement.Condition.Accept(this), Roles.Condition);
+				if (location != null && location.Count >= 3)
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.Semicolon), Roles.Semicolon);
+				
+				AddStatementOrList(result, forStatement.Iterator, ForStatement.IteratorRole);
+				
+				if (location != null && location.Count >= 4)
+					result.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.RPar), Roles.RPar);
+				
+				if (forStatement.Statement != null)
+					result.AddChild((Statement)forStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				
+				return result;
+			}
+
+			public override object Visit(StatementExpression statementExpression)
+			{
+				var result = new ExpressionStatement();
+				var expr = statementExpression.Expr.Accept(this) as Expression;
+				if (expr != null)
+					result.AddChild(expr, Roles.Expression);
+				var location = LocationsBag.GetLocations(statementExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(StatementErrorExpression errorStatement)
+			{
+				var result = new ExpressionStatement();
+				var expr = errorStatement.Expr.Accept(this) as Expression;
+				if (expr != null)
+					result.AddChild(expr, Roles.Expression);
+				var location = LocationsBag.GetLocations(errorStatement);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(InvalidStatementExpression invalidStatementExpression)
+			{
+				var result = new ExpressionStatement();
+				if (invalidStatementExpression.Expression == null)
+					return result;
+				var expr = invalidStatementExpression.Expression.Accept(this) as Expression;
+				if (expr != null)
+					result.AddChild(expr, Roles.Expression);
+				var location = LocationsBag.GetLocations(invalidStatementExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(Return returnStatement)
+			{
+				var result = new ReturnStatement();
+				
+				result.AddChild(new CSharpTokenNode(Convert(returnStatement.loc), ReturnStatement.ReturnKeywordRole), ReturnStatement.ReturnKeywordRole);
+				if (returnStatement.Expr != null)
+					result.AddChild((Expression)returnStatement.Expr.Accept(this), Roles.Expression);
+				
+				var location = LocationsBag.GetLocations(returnStatement);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				
+				return result;
+			}
+
+			public override object Visit(Goto gotoStatement)
+			{
+				var result = new GotoStatement();
+				var location = LocationsBag.GetLocations(gotoStatement);
+				result.AddChild(new CSharpTokenNode(Convert(gotoStatement.loc), GotoStatement.GotoKeywordRole), GotoStatement.GotoKeywordRole);
+				var loc = location != null ? Convert(location [0]) : TextLocation.Empty;
+				result.AddChild(Identifier.Create(gotoStatement.Target, loc), Roles.Identifier);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				
+				return result;
+			}
+
+			public override object Visit(LabeledStatement labeledStatement)
+			{
+				var result = new LabelStatement();
+				result.AddChild(Identifier.Create(labeledStatement.Name, Convert(labeledStatement.loc)), Roles.Identifier);
+				var location = LocationsBag.GetLocations(labeledStatement);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Colon), Roles.Colon);
+				return result;
+			}
+
+			public override object Visit(GotoDefault gotoDefault)
+			{
+				var result = new GotoDefaultStatement();
+				result.AddChild(new CSharpTokenNode(Convert(gotoDefault.loc), GotoDefaultStatement.GotoKeywordRole), GotoDefaultStatement.GotoKeywordRole);
+				var location = LocationsBag.GetLocations(gotoDefault);
+				if (location != null) {
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), GotoDefaultStatement.DefaultKeywordRole), GotoDefaultStatement.DefaultKeywordRole);
+					if (location.Count > 1)
+						result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				}
+				
+				return result;
+			}
+
+			public override object Visit(GotoCase gotoCase)
+			{
+				var result = new GotoCaseStatement();
+				result.AddChild(new CSharpTokenNode(Convert(gotoCase.loc), GotoCaseStatement.GotoKeywordRole), GotoCaseStatement.GotoKeywordRole);
+				
+				var location = LocationsBag.GetLocations(gotoCase);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), GotoCaseStatement.CaseKeywordRole), GotoCaseStatement.CaseKeywordRole);
+				if (gotoCase.Expr != null)
+					result.AddChild((Expression)gotoCase.Expr.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(Throw throwStatement)
+			{
+				var result = new ThrowStatement();
+				var location = LocationsBag.GetLocations(throwStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(throwStatement.loc), ThrowStatement.ThrowKeywordRole), ThrowStatement.ThrowKeywordRole);
+				if (throwStatement.Expr != null)
+					result.AddChild((Expression)throwStatement.Expr.Accept(this), Roles.Expression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(Break breakStatement)
+			{
+				var result = new BreakStatement();
+				var location = LocationsBag.GetLocations(breakStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(breakStatement.loc), BreakStatement.BreakKeywordRole), BreakStatement.BreakKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public override object Visit(Continue continueStatement)
+			{
+				var result = new ContinueStatement();
+				var location = LocationsBag.GetLocations(continueStatement);
+				result.AddChild(new CSharpTokenNode(Convert(continueStatement.loc), ContinueStatement.ContinueKeywordRole), ContinueStatement.ContinueKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Semicolon), Roles.Semicolon);
+				return result;
+			}
+
+			public static bool IsLower(Location left, Location right)
+			{
+				return left.Row < right.Row || left.Row == right.Row && left.Column < right.Column;
+			}
+
+			public UsingStatement CreateUsingStatement(Block blockStatement)
+			{
+				var usingResult = new UsingStatement();
+				Mono.CSharp.Statement cur = blockStatement.Statements [0];
+				var u = cur as Using;
+				if (u != null) {
+					usingResult.AddChild(new CSharpTokenNode(Convert(u.loc), UsingStatement.UsingKeywordRole), UsingStatement.UsingKeywordRole);
+					usingResult.AddChild(new CSharpTokenNode(Convert(blockStatement.StartLocation), Roles.LPar), Roles.LPar);
+					if (u.Variables != null) {
+						var initializer = new VariableInitializer {
+							NameToken = Identifier.Create(u.Variables.Variable.Name, Convert(u.Variables.Variable.Location)),
+						};
+						
+						var loc = LocationsBag.GetLocations(u.Variables);
+						if (loc != null)
+							initializer.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Assign), Roles.Assign);
+						if (u.Variables.Initializer != null)
+							initializer.Initializer = u.Variables.Initializer.Accept(this) as Expression;
+						
+						
+						var varDec = new VariableDeclarationStatement {
+							Type = ConvertToType(u.Variables.TypeExpression),
+							Variables = { initializer }
+						};
+						
+						if (u.Variables.Declarators != null) {
+							foreach (var decl in u.Variables.Declarators) {
+								var declLoc = LocationsBag.GetLocations(decl);
+								var init = new VariableInitializer();
+								if (declLoc != null && declLoc.Count > 0)
+									varDec.AddChild(new CSharpTokenNode(Convert(declLoc [0]), Roles.Comma), Roles.Comma);
+								init.AddChild(Identifier.Create(decl.Variable.Name, Convert(decl.Variable.Location)), Roles.Identifier);
+								if (decl.Initializer != null) {
+									if (declLoc != null && declLoc.Count > 1)
+										init.AddChild(new CSharpTokenNode(Convert(declLoc [1]), Roles.Assign), Roles.Assign);
+									init.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+								}
+								varDec.AddChild(init, Roles.Variable);
+							}
+						}
+						usingResult.AddChild(varDec, UsingStatement.ResourceAcquisitionRole);
+					}
+					cur = u.Statement;
+					usingResult.AddChild(new CSharpTokenNode(Convert(blockStatement.EndLocation), Roles.RPar), Roles.RPar);
+					if (cur != null)
+						usingResult.AddChild((Statement)cur.Accept(this), Roles.EmbeddedStatement);
+				}
+				return usingResult;
+			}
+
+			void AddBlockChildren(BlockStatement result, Block blockStatement, ref int curLocal)
+			{
+				if (convertTypeSystemMode) {
+					return;
+				}
+				foreach (Mono.CSharp.Statement stmt in blockStatement.Statements) {
+					if (stmt == null)
+						continue;
+					/*					if (curLocal < localVariables.Count && IsLower (localVariables[curLocal].Location, stmt.loc)) {
+						result.AddChild (CreateVariableDeclaration (localVariables[curLocal]), Roles.Statement);
+						curLocal++;
+					}*/
+					if (stmt is Block && !(stmt is ToplevelBlock || stmt is ExplicitBlock)) {
+						AddBlockChildren(result, (Block)stmt, ref curLocal);
+					} else {
+						result.AddChild((Statement)stmt.Accept(this), BlockStatement.StatementRole);
+					}
+				}
+			}
+
+			public override object Visit(Block blockStatement)
+			{
+				if (blockStatement.IsCompilerGenerated && blockStatement.Statements.Any()) {
+					if (blockStatement.Statements.First() is Using)
+						return CreateUsingStatement(blockStatement);
+					return blockStatement.Statements.Last().Accept(this);
+				}
+				var result = new BlockStatement();
+				result.AddChild(new CSharpTokenNode(Convert(blockStatement.StartLocation), Roles.LBrace), Roles.LBrace);
+				int curLocal = 0;
+				AddBlockChildren(result, blockStatement, ref curLocal);
+				
+				result.AddChild(new CSharpTokenNode(Convert(blockStatement.EndLocation), Roles.RBrace), Roles.RBrace);
+				return result;
+			}
+
+			public override object Visit(Switch switchStatement)
+			{
+				var result = new SwitchStatement();
+				
+				var location = LocationsBag.GetLocations(switchStatement);
+				result.AddChild(new CSharpTokenNode(Convert(switchStatement.loc), SwitchStatement.SwitchKeywordRole), SwitchStatement.SwitchKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (switchStatement.Expr != null)
+					result.AddChild((Expression)switchStatement.Expr.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				if (location != null && location.Count > 2)
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.LBrace), Roles.LBrace);
+				SwitchSection newSection = null;
+				bool lastWasCase = false, added = true;
+				if (switchStatement.Block != null) {
+					foreach (var child in switchStatement.Block.Statements) {
+						var statement = child.Accept(this);
+						var caseLabel = statement as CaseLabel;
+						if (caseLabel != null) {
+							if (!lastWasCase) {
+								newSection = new SwitchSection();
+								added = false;
+							}
+							newSection.AddChild(caseLabel, SwitchSection.CaseLabelRole);
+							lastWasCase = true;
+						} else {
+							if (lastWasCase) {
+								result.AddChild(newSection, SwitchStatement.SwitchSectionRole);
+								lastWasCase = false;
+								added = true;
+							}
+							newSection.AddChild((Statement)statement, Roles.EmbeddedStatement);
+						}
+					}
+				}
+				if (!added)
+					result.AddChild(newSection, SwitchStatement.SwitchSectionRole);
+
+				if (location != null && location.Count > 3) {
+					result.AddChild(new CSharpTokenNode(Convert(location [3]), Roles.RBrace), Roles.RBrace);
+				} else {
+					// parser error, set end node to max value.
+					result.AddChild(new ErrorNode(), Roles.Error);
+				}
+				
+				return result;
+			}
+
+			public override object Visit(SwitchLabel switchLabel)
+			{
+				var newLabel = new CaseLabel();
+				if (!switchLabel.IsDefault) {
+					newLabel.AddChild(new CSharpTokenNode(Convert(switchLabel.Location), CaseLabel.CaseKeywordRole), CaseLabel.CaseKeywordRole);
+					if (switchLabel.Label != null)
+						newLabel.AddChild((Expression)switchLabel.Label.Accept(this), Roles.Expression);
+					var colonLocation = LocationsBag.GetLocations(switchLabel);
+					if (colonLocation != null)
+						newLabel.AddChild(new CSharpTokenNode(Convert(colonLocation [0]), Roles.Colon), Roles.Colon);
+				} else {
+					newLabel.AddChild(new CSharpTokenNode(Convert(switchLabel.Location), CaseLabel.DefaultKeywordRole), CaseLabel.DefaultKeywordRole);
+					newLabel.AddChild(new CSharpTokenNode(new TextLocation(switchLabel.Location.Row, switchLabel.Location.Column + "default".Length), Roles.Colon), Roles.Colon);
+				}
+				return newLabel;
+			}
+
+			public override object Visit(Lock lockStatement)
+			{
+				var result = new LockStatement();
+				var location = LocationsBag.GetLocations(lockStatement);
+				result.AddChild(new CSharpTokenNode(Convert(lockStatement.loc), LockStatement.LockKeywordRole), LockStatement.LockKeywordRole);
+				
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (lockStatement.Expr != null)
+					result.AddChild((Expression)lockStatement.Expr.Accept(this), Roles.Expression);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				if (lockStatement.Statement != null)
+					result.AddChild((Statement)lockStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				
+				return result;
+			}
+
+			public override object Visit(Unchecked uncheckedStatement)
+			{
+				var result = new UncheckedStatement();
+				result.AddChild(new CSharpTokenNode(Convert(uncheckedStatement.loc), UncheckedStatement.UncheckedKeywordRole), UncheckedStatement.UncheckedKeywordRole);
+				if (uncheckedStatement.Block != null)
+					result.AddChild((BlockStatement)uncheckedStatement.Block.Accept(this), Roles.Body);
+				return result;
+			}
+
+			public override object Visit(Checked checkedStatement)
+			{
+				var result = new CheckedStatement();
+				result.AddChild(new CSharpTokenNode(Convert(checkedStatement.loc), CheckedStatement.CheckedKeywordRole), CheckedStatement.CheckedKeywordRole);
+				if (checkedStatement.Block != null)
+					result.AddChild((BlockStatement)checkedStatement.Block.Accept(this), Roles.Body);
+				return result;
+			}
+
+			public override object Visit(Unsafe unsafeStatement)
+			{
+				var result = new UnsafeStatement();
+				result.AddChild(new CSharpTokenNode(Convert(unsafeStatement.loc), UnsafeStatement.UnsafeKeywordRole), UnsafeStatement.UnsafeKeywordRole);
+				if (unsafeStatement.Block != null)
+					result.AddChild((BlockStatement)unsafeStatement.Block.Accept(this), Roles.Body);
+				return result;
+			}
+
+			public override object Visit(Fixed fixedStatement)
+			{
+				var result = new FixedStatement();
+				var location = LocationsBag.GetLocations(fixedStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(fixedStatement.loc), FixedStatement.FixedKeywordRole), FixedStatement.FixedKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				if (fixedStatement.Variables != null) {
+					var blockVariableDeclaration = fixedStatement.Variables;
+					result.AddChild(ConvertToType(blockVariableDeclaration.TypeExpression), Roles.Type);
+					var varInit = new VariableInitializer();
+					var initLocation = LocationsBag.GetLocations(blockVariableDeclaration);
+					varInit.AddChild(Identifier.Create(blockVariableDeclaration.Variable.Name, Convert(blockVariableDeclaration.Variable.Location)), Roles.Identifier);
+					if (blockVariableDeclaration.Initializer != null) {
+						if (initLocation != null)
+							varInit.AddChild(new CSharpTokenNode(Convert(initLocation [0]), Roles.Assign), Roles.Assign);
+						varInit.AddChild((Expression)blockVariableDeclaration.Initializer.Accept(this), Roles.Expression);
+					}
+					
+					result.AddChild(varInit, Roles.Variable);
+					
+					if (blockVariableDeclaration.Declarators != null) {
+						foreach (var decl in blockVariableDeclaration.Declarators) {
+							var loc = LocationsBag.GetLocations(decl);
+							var init = new VariableInitializer();
+							if (loc != null && loc.Count > 0)
+								result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Comma), Roles.Comma);
+							init.AddChild(Identifier.Create(decl.Variable.Name, Convert(decl.Variable.Location)), Roles.Identifier);
+							if (decl.Initializer != null) {
+								if (loc != null && loc.Count > 1)
+									init.AddChild(new CSharpTokenNode(Convert(loc [1]), Roles.Assign), Roles.Assign);
+								init.AddChild((Expression)decl.Initializer.Accept(this), Roles.Expression);
+							}
+							result.AddChild(init, Roles.Variable);
+						}
+					}
+				}
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				if (fixedStatement.Statement != null)
+					result.AddChild((Statement)fixedStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				return result;
+			}
+
+			public override object Visit(TryFinally tryFinallyStatement)
+			{
+				TryCatchStatement result;
+				var location = LocationsBag.GetLocations(tryFinallyStatement);
+				
+				if (tryFinallyStatement.Stmt is TryCatch) {
+					result = (TryCatchStatement)tryFinallyStatement.Stmt.Accept(this);
+				} else {
+					result = new TryCatchStatement();
+					result.AddChild(new CSharpTokenNode(Convert(tryFinallyStatement.loc), TryCatchStatement.TryKeywordRole), TryCatchStatement.TryKeywordRole);
+					if (tryFinallyStatement.Stmt != null)
+						result.AddChild((BlockStatement)tryFinallyStatement.Stmt.Accept(this), TryCatchStatement.TryBlockRole);
+				}
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), TryCatchStatement.FinallyKeywordRole), TryCatchStatement.FinallyKeywordRole);
+				if (tryFinallyStatement.Fini != null)
+					result.AddChild((BlockStatement)tryFinallyStatement.Fini.Accept(this), TryCatchStatement.FinallyBlockRole);
+				
+				return result;
+			}
+
+			CatchClause ConvertCatch(Catch ctch)
+			{
+				var result = new CatchClause();
+				var location = LocationsBag.GetLocations(ctch);
+				result.AddChild(new CSharpTokenNode(Convert(ctch.loc), CatchClause.CatchKeywordRole), CatchClause.CatchKeywordRole);
+				if (ctch.TypeExpression != null) {
+					if (location != null)
+						result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+					
+					if (ctch.TypeExpression != null)
+						result.AddChild(ConvertToType(ctch.TypeExpression), Roles.Type);
+					if (ctch.Variable != null && !string.IsNullOrEmpty(ctch.Variable.Name))
+						result.AddChild(Identifier.Create(ctch.Variable.Name, Convert(ctch.Variable.Location)), Roles.Identifier);
+					
+					if (location != null && location.Count > 1)
+						result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				}
+
+				if (ctch.Block != null)
+					result.AddChild((BlockStatement)ctch.Block.Accept(this), Roles.Body);
+				
+				return result;
+			}
+
+			public override object Visit(TryCatch tryCatchStatement)
+			{
+				var result = new TryCatchStatement();
+				result.AddChild(new CSharpTokenNode(Convert(tryCatchStatement.loc), TryCatchStatement.TryKeywordRole), TryCatchStatement.TryKeywordRole);
+				if (tryCatchStatement.Block != null)
+					result.AddChild((BlockStatement)tryCatchStatement.Block.Accept(this), TryCatchStatement.TryBlockRole);
+				if (tryCatchStatement.Clauses != null) {
+					foreach (var ctch in tryCatchStatement.Clauses) {
+						result.AddChild(ConvertCatch(ctch), TryCatchStatement.CatchClauseRole);
+					}
+				}
+//				if (tryCatchStatement.General != null)
+//					result.AddChild (ConvertCatch (tryCatchStatement.General), TryCatchStatement.CatchClauseRole);
+				
+				return result;
+			}
+
+			public override object Visit(Using usingStatement)
+			{
+				var result = new UsingStatement();
+				var location = LocationsBag.GetLocations(usingStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(usingStatement.loc), UsingStatement.UsingKeywordRole), UsingStatement.UsingKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (usingStatement.Expr != null)
+					result.AddChild((AstNode)usingStatement.Expr.Accept(this), UsingStatement.ResourceAcquisitionRole);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				
+				if (usingStatement.Statement != null)
+					result.AddChild((Statement)usingStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				return result;
+			}
+
+			public override object Visit(Foreach foreachStatement)
+			{
+				var result = new ForeachStatement();
+				
+				var location = LocationsBag.GetLocations(foreachStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(foreachStatement.loc), ForeachStatement.ForeachKeywordRole), ForeachStatement.ForeachKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				if (foreachStatement.TypeExpression != null)
+					result.AddChild(ConvertToType(foreachStatement.TypeExpression), Roles.Type);
+				
+				if (foreachStatement.Variable != null)
+					result.AddChild(Identifier.Create(foreachStatement.Variable.Name, Convert(foreachStatement.Variable.Location)), Roles.Identifier);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), ForeachStatement.InKeywordRole), ForeachStatement.InKeywordRole);
+				
+				if (foreachStatement.Expr != null)
+					result.AddChild((Expression)foreachStatement.Expr.Accept(this), Roles.Expression);
+				
+				if (location != null && location.Count > 2)
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.RPar), Roles.RPar);
+				
+				if (foreachStatement.Statement != null)
+					result.AddChild((Statement)foreachStatement.Statement.Accept(this), Roles.EmbeddedStatement);
+				
+				return result;
+			}
+
+			public override object Visit(Yield yieldStatement)
+			{
+				var result = new YieldReturnStatement();
+				var location = LocationsBag.GetLocations(yieldStatement);
+				
+				result.AddChild(new CSharpTokenNode(Convert(yieldStatement.loc), YieldReturnStatement.YieldKeywordRole), YieldReturnStatement.YieldKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), YieldReturnStatement.ReturnKeywordRole), YieldReturnStatement.ReturnKeywordRole);
+				if (yieldStatement.Expr != null)
+					result.AddChild((Expression)yieldStatement.Expr.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				
+				return result;
+			}
+
+			public override object Visit(YieldBreak yieldBreakStatement)
+			{
+				var result = new YieldBreakStatement();
+				var location = LocationsBag.GetLocations(yieldBreakStatement);
+				result.AddChild(new CSharpTokenNode(Convert(yieldBreakStatement.loc), YieldBreakStatement.YieldKeywordRole), YieldBreakStatement.YieldKeywordRole);
+				if (location != null) {
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), YieldBreakStatement.BreakKeywordRole), YieldBreakStatement.BreakKeywordRole);
+					if (location.Count > 1)
+						result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Semicolon), Roles.Semicolon);
+				}
+				return result;
+			}
+
+			#endregion
+
+			#region Expression
+
+			public override object Visit(Mono.CSharp.Expression expression)
+			{
+				Console.WriteLine("Visit unknown expression:" + expression);
+				Console.WriteLine(Environment.StackTrace);
+				return null;
+			}
+
+			public override object Visit(DefaultParameterValueExpression defaultParameterValueExpression)
+			{
+				return defaultParameterValueExpression.Child.Accept(this);
+			}
+
+			public override object Visit(TypeExpression typeExpression)
+			{
+				return new TypeReferenceExpression(new PrimitiveType(keywordTable [(int)typeExpression.Type.BuiltinType], Convert(typeExpression.Location)));
+			}
+
+			public override object Visit(LocalVariableReference localVariableReference)
+			{
+				return Identifier.Create(localVariableReference.Name, Convert(localVariableReference.Location));
+			}
+
+			public override object Visit(MemberAccess memberAccess)
+			{
+				Expression result;
+				var ind = memberAccess.LeftExpression as Indirection;
+				if (ind != null) {
+					result = new PointerReferenceExpression();
+					result.AddChild((Expression)ind.Expr.Accept(this), Roles.TargetExpression);
+					result.AddChild(new CSharpTokenNode(Convert(ind.Location), PointerReferenceExpression.ArrowRole), PointerReferenceExpression.ArrowRole);
+				} else {
+					result = new MemberReferenceExpression();
+					if (memberAccess.LeftExpression != null) {
+						var leftExpr = memberAccess.LeftExpression.Accept(this);
+						result.AddChild((Expression)leftExpr, Roles.TargetExpression);
+					}
+					var loc = LocationsBag.GetLocations(memberAccess);
+
+					if (loc != null) {
+						result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Dot), Roles.Dot);
+					}
+				}
+				
+				result.AddChild(Identifier.Create(memberAccess.Name, Convert(memberAccess.Location)), Roles.Identifier);
+				
+				AddTypeArguments(result, memberAccess);
+				return result;
+			}
+
+			public override object Visit(QualifiedAliasMember qualifiedAliasMember)
+			{
+				var result = new MemberType();
+				result.Target = new SimpleType(qualifiedAliasMember.alias, Convert(qualifiedAliasMember.Location));
+				result.IsDoubleColon = true;
+				var location = LocationsBag.GetLocations(qualifiedAliasMember);
+				if (location != null && location.Count > 0)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.DoubleColon), Roles.DoubleColon);
+
+				AddTypeArguments(result, qualifiedAliasMember);
+				result.AddChild(Identifier.Create(qualifiedAliasMember.Name, location != null && location.Count > 1 ? Convert(location [1]) : TextLocation.Empty), Roles.Identifier);
+				return  new TypeReferenceExpression { Type = result };
+			}
+
+			public override object Visit(Constant constant)
+			{
+				if (constant.GetValue() == null)
+					return new NullReferenceExpression(Convert(constant.Location));
+				string literalValue;
+				var literalConstant = constant as ILiteralConstant;
+				literalValue = literalConstant != null ? new string(literalConstant.ParsedValue) : constant.GetValueAsLiteral();
+				object val = constant.GetValue();
+				if (val is bool)
+					literalValue = (bool)val ? "true" : "false";
+				var result = new PrimitiveExpression(val, Convert(constant.Location), literalValue);
+				return result;
+			}
+
+			public override object Visit(SimpleName simpleName)
+			{
+				var result = new IdentifierExpression();
+				result.AddChild(Identifier.Create(simpleName.Name, Convert(simpleName.Location)), Roles.Identifier);
+				AddTypeArguments(result, simpleName);
+				return result;
+			}
+
+			public override object Visit(BooleanExpression booleanExpression)
+			{
+				return booleanExpression.Expr.Accept(this);
+			}
+
+			public override object Visit(Mono.CSharp.ParenthesizedExpression parenthesizedExpression)
+			{
+				var result = new ParenthesizedExpression();
+				var location = LocationsBag.GetLocations(parenthesizedExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (parenthesizedExpression.Expr != null)
+					result.AddChild((Expression)parenthesizedExpression.Expr.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(Unary unaryExpression)
+			{
+				var result = new UnaryOperatorExpression();
+				switch (unaryExpression.Oper) {
+					case Unary.Operator.UnaryPlus:
+						result.Operator = UnaryOperatorType.Plus;
+						break;
+					case Unary.Operator.UnaryNegation:
+						result.Operator = UnaryOperatorType.Minus;
+						break;
+					case Unary.Operator.LogicalNot:
+						result.Operator = UnaryOperatorType.Not;
+						break;
+					case Unary.Operator.OnesComplement:
+						result.Operator = UnaryOperatorType.BitNot;
+						break;
+					case Unary.Operator.AddressOf:
+						result.Operator = UnaryOperatorType.AddressOf;
+						break;
+				}
+				var r = UnaryOperatorExpression.GetOperatorRole(result.Operator);
+				result.AddChild(new CSharpTokenNode(Convert(unaryExpression.Location), r), r);
+				if (unaryExpression.Expr != null)
+					result.AddChild((Expression)unaryExpression.Expr.Accept(this), Roles.Expression);
+				return result;
+			}
+
+			public override object Visit(UnaryMutator unaryMutatorExpression)
+			{
+				var result = new UnaryOperatorExpression();
+				if (unaryMutatorExpression.Expr == null)
+					return result;
+				var expression = (Expression)unaryMutatorExpression.Expr.Accept(this);
+				switch (unaryMutatorExpression.UnaryMutatorMode) {
+					case UnaryMutator.Mode.PostDecrement:
+						result.Operator = UnaryOperatorType.PostDecrement;
+						result.AddChild(expression, Roles.Expression);
+						result.AddChild(new CSharpTokenNode(Convert(unaryMutatorExpression.Location), UnaryOperatorExpression.DecrementRole), UnaryOperatorExpression.DecrementRole);
+						break;
+					case UnaryMutator.Mode.PostIncrement:
+						result.Operator = UnaryOperatorType.PostIncrement;
+						result.AddChild(expression, Roles.Expression);
+						result.AddChild(new CSharpTokenNode(Convert(unaryMutatorExpression.Location), UnaryOperatorExpression.IncrementRole), UnaryOperatorExpression.IncrementRole);
+						break;
+						
+					case UnaryMutator.Mode.PreIncrement:
+						result.Operator = UnaryOperatorType.Increment;
+						result.AddChild(new CSharpTokenNode(Convert(unaryMutatorExpression.Location), UnaryOperatorExpression.IncrementRole), UnaryOperatorExpression.IncrementRole);
+						result.AddChild(expression, Roles.Expression);
+						break;
+					case UnaryMutator.Mode.PreDecrement:
+						result.Operator = UnaryOperatorType.Decrement;
+						result.AddChild(new CSharpTokenNode(Convert(unaryMutatorExpression.Location), UnaryOperatorExpression.DecrementRole), UnaryOperatorExpression.DecrementRole);
+						result.AddChild(expression, Roles.Expression);
+						break;
+				}
+				
+				return result;
+			}
+
+			public override object Visit(Indirection indirectionExpression)
+			{
+				var result = new UnaryOperatorExpression();
+				result.Operator = UnaryOperatorType.Dereference;
+				result.AddChild(new CSharpTokenNode(Convert(indirectionExpression.Location), UnaryOperatorExpression.DereferenceRole), UnaryOperatorExpression.DereferenceRole);
+				if (indirectionExpression.Expr != null)
+					result.AddChild((Expression)indirectionExpression.Expr.Accept(this), Roles.Expression);
+				return result;
+			}
+
+			public override object Visit(Is isExpression)
+			{
+				var result = new IsExpression();
+				if (isExpression.Expr != null)
+					result.AddChild((Expression)isExpression.Expr.Accept(this), Roles.Expression);
+				result.AddChild(new CSharpTokenNode(Convert(isExpression.Location), IsExpression.IsKeywordRole), IsExpression.IsKeywordRole);
+				
+				if (isExpression.ProbeType != null)
+					result.AddChild(ConvertToType(isExpression.ProbeType), Roles.Type);
+				return result;
+			}
+
+			public override object Visit(As asExpression)
+			{
+				var result = new AsExpression();
+				if (asExpression.Expr != null)
+					result.AddChild((Expression)asExpression.Expr.Accept(this), Roles.Expression);
+				result.AddChild(new CSharpTokenNode(Convert(asExpression.Location), AsExpression.AsKeywordRole), AsExpression.AsKeywordRole);
+				if (asExpression.ProbeType != null)
+					result.AddChild(ConvertToType(asExpression.ProbeType), Roles.Type);
+				return result;
+			}
+
+			public override object Visit(Cast castExpression)
+			{
+				var result = new CastExpression();
+				var location = LocationsBag.GetLocations(castExpression);
+				
+				result.AddChild(new CSharpTokenNode(Convert(castExpression.Location), Roles.LPar), Roles.LPar);
+				if (castExpression.TargetType != null)
+					result.AddChild(ConvertToType(castExpression.TargetType), Roles.Type);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.RPar), Roles.RPar);
+				if (castExpression.Expr != null)
+					result.AddChild((Expression)castExpression.Expr.Accept(this), Roles.Expression);
+				return result;
+			}
+
+			public override object Visit(ComposedCast composedCast)
+			{
+				var result = new ComposedType();
+				result.AddChild(ConvertToType(composedCast.Left), Roles.Type);
+				
+				var spec = composedCast.Spec;
+				while (spec != null) {
+					if (spec.IsNullable) {
+						result.AddChild(new CSharpTokenNode(Convert(spec.Location), ComposedType.NullableRole), ComposedType.NullableRole);
+					} else if (spec.IsPointer) {
+						result.AddChild(new CSharpTokenNode(Convert(spec.Location), ComposedType.PointerRole), ComposedType.PointerRole);
+					} else {
+						var aSpec = new ArraySpecifier();
+						aSpec.AddChild(new CSharpTokenNode(Convert(spec.Location), Roles.LBracket), Roles.LBracket);
+						var location = LocationsBag.GetLocations(spec);
+						if (location != null)
+							aSpec.AddChild(new CSharpTokenNode(Convert(spec.Location), Roles.RBracket), Roles.RBracket);
+						result.AddChild(aSpec, ComposedType.ArraySpecifierRole);
+					}
+					spec = spec.Next;
+				}
+				
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.DefaultValueExpression defaultValueExpression)
+			{
+				var result = new DefaultValueExpression();
+				result.AddChild(new CSharpTokenNode(Convert(defaultValueExpression.Location), DefaultValueExpression.DefaultKeywordRole), DefaultValueExpression.DefaultKeywordRole);
+				var location = LocationsBag.GetLocations(defaultValueExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				result.AddChild(ConvertToType(defaultValueExpression.Expr), Roles.Type);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(Binary binaryExpression)
+			{
+				var result = new BinaryOperatorExpression();
+				switch (binaryExpression.Oper) {
+					case Binary.Operator.Multiply:
+						result.Operator = BinaryOperatorType.Multiply;
+						break;
+					case Binary.Operator.Division:
+						result.Operator = BinaryOperatorType.Divide;
+						break;
+					case Binary.Operator.Modulus:
+						result.Operator = BinaryOperatorType.Modulus;
+						break;
+					case Binary.Operator.Addition:
+						result.Operator = BinaryOperatorType.Add;
+						break;
+					case Binary.Operator.Subtraction:
+						result.Operator = BinaryOperatorType.Subtract;
+						break;
+					case Binary.Operator.LeftShift:
+						result.Operator = BinaryOperatorType.ShiftLeft;
+						break;
+					case Binary.Operator.RightShift:
+						result.Operator = BinaryOperatorType.ShiftRight;
+						break;
+					case Binary.Operator.LessThan:
+						result.Operator = BinaryOperatorType.LessThan;
+						break;
+					case Binary.Operator.GreaterThan:
+						result.Operator = BinaryOperatorType.GreaterThan;
+						break;
+					case Binary.Operator.LessThanOrEqual:
+						result.Operator = BinaryOperatorType.LessThanOrEqual;
+						break;
+					case Binary.Operator.GreaterThanOrEqual:
+						result.Operator = BinaryOperatorType.GreaterThanOrEqual;
+						break;
+					case Binary.Operator.Equality:
+						result.Operator = BinaryOperatorType.Equality;
+						break;
+					case Binary.Operator.Inequality:
+						result.Operator = BinaryOperatorType.InEquality;
+						break;
+					case Binary.Operator.BitwiseAnd:
+						result.Operator = BinaryOperatorType.BitwiseAnd;
+						break;
+					case Binary.Operator.ExclusiveOr:
+						result.Operator = BinaryOperatorType.ExclusiveOr;
+						break;
+					case Binary.Operator.BitwiseOr:
+						result.Operator = BinaryOperatorType.BitwiseOr;
+						break;
+					case Binary.Operator.LogicalAnd:
+						result.Operator = BinaryOperatorType.ConditionalAnd;
+						break;
+					case Binary.Operator.LogicalOr:
+						result.Operator = BinaryOperatorType.ConditionalOr;
+						break;
+				}
+				
+				if (binaryExpression.Left != null)
+					result.AddChild((Expression)binaryExpression.Left.Accept(this), BinaryOperatorExpression.LeftRole);
+				var location = LocationsBag.GetLocations(binaryExpression);
+				if (location != null) {
+					var r = BinaryOperatorExpression.GetOperatorRole(result.Operator);
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), r), r);
+				}
+				if (binaryExpression.Right != null)
+					result.AddChild((Expression)binaryExpression.Right.Accept(this), BinaryOperatorExpression.RightRole);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Nullable.NullCoalescingOperator nullCoalescingOperator)
+			{
+				var result = new BinaryOperatorExpression();
+				result.Operator = BinaryOperatorType.NullCoalescing;
+				if (nullCoalescingOperator.LeftExpression != null)
+					result.AddChild((Expression)nullCoalescingOperator.LeftExpression.Accept(this), BinaryOperatorExpression.LeftRole);
+				var location = LocationsBag.GetLocations(nullCoalescingOperator);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), BinaryOperatorExpression.NullCoalescingRole), BinaryOperatorExpression.NullCoalescingRole);
+				if (nullCoalescingOperator.RightExpression != null)
+					result.AddChild((Expression)nullCoalescingOperator.RightExpression.Accept(this), BinaryOperatorExpression.RightRole);
+				return result;
+			}
+
+			public override object Visit(Conditional conditionalExpression)
+			{
+				var result = new ConditionalExpression();
+				
+				if (conditionalExpression.Expr != null)
+					result.AddChild((Expression)conditionalExpression.Expr.Accept(this), Roles.Condition);
+				var location = LocationsBag.GetLocations(conditionalExpression);
+				
+				result.AddChild(new CSharpTokenNode(Convert(conditionalExpression.Location), ConditionalExpression.QuestionMarkRole), ConditionalExpression.QuestionMarkRole);
+				if (conditionalExpression.TrueExpr != null)
+					result.AddChild((Expression)conditionalExpression.TrueExpr.Accept(this), ConditionalExpression.TrueRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), ConditionalExpression.ColonRole), ConditionalExpression.ColonRole);
+				if (conditionalExpression.FalseExpr != null)
+					result.AddChild((Expression)conditionalExpression.FalseExpr.Accept(this), ConditionalExpression.FalseRole);
+				return result;
+			}
+
+			void AddParameter(AstNode parent, AParametersCollection parameters)
+			{
+				if (parameters == null)
+					return;
+				var paramLocation = LocationsBag.GetLocations(parameters);
+				
+				for (int i = 0; i < parameters.Count; i++) {
+					var p = (Parameter)parameters.FixedParameters [i];
+					if (p == null)
+						continue;
+					var location = LocationsBag.GetLocations(p);
+					var parameterDeclarationExpression = new ParameterDeclaration();
+					AddAttributeSection(parameterDeclarationExpression, p);
+					switch (p.ModFlags) {
+						case Parameter.Modifier.OUT:
+							parameterDeclarationExpression.ParameterModifier = ParameterModifier.Out;
+							if (location != null)
+								parameterDeclarationExpression.AddChild(new CSharpTokenNode(Convert(location [0]), ParameterDeclaration.OutModifierRole), ParameterDeclaration.OutModifierRole);
+							break;
+						case Parameter.Modifier.REF:
+							parameterDeclarationExpression.ParameterModifier = ParameterModifier.Ref;
+							if (location != null)
+								parameterDeclarationExpression.AddChild(new CSharpTokenNode(Convert(location [0]), ParameterDeclaration.RefModifierRole), ParameterDeclaration.RefModifierRole);
+							break;
+						case Parameter.Modifier.PARAMS:
+							parameterDeclarationExpression.ParameterModifier = ParameterModifier.Params;
+							if (location != null)
+								parameterDeclarationExpression.AddChild(new CSharpTokenNode(Convert(location [0]), ParameterDeclaration.ParamsModifierRole), ParameterDeclaration.ParamsModifierRole);
+							break;
+						default:
+							if (p.HasExtensionMethodModifier) {
+								parameterDeclarationExpression.ParameterModifier = ParameterModifier.This;
+								if (location != null) {
+									parameterDeclarationExpression.AddChild(new CSharpTokenNode(Convert(location [0]), ParameterDeclaration.ThisModifierRole), ParameterDeclaration.ThisModifierRole);
+								}
+							}
+							break;
+					}
+					if (p.TypeExpression != null) // lambdas may have no types (a, b) => ...
+						parameterDeclarationExpression.AddChild(ConvertToType(p.TypeExpression), Roles.Type);
+					if (p.Name != null)
+						parameterDeclarationExpression.AddChild(Identifier.Create(p.Name, Convert(p.Location)), Roles.Identifier);
+					if (p.HasDefaultValue) {
+						if (location != null && location.Count > 1)
+							parameterDeclarationExpression.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.Assign), Roles.Assign);
+						parameterDeclarationExpression.AddChild((Expression)p.DefaultValue.Accept(this), Roles.Expression);
+					}
+					parent.AddChild(parameterDeclarationExpression, Roles.Parameter);
+					if (paramLocation != null && i < paramLocation.Count) {
+						parent.AddChild(new CSharpTokenNode(Convert(paramLocation [i]), Roles.Comma), Roles.Comma);
+					}
+				}
+			}
+
+			void AddTypeParameters(AstNode parent, MemberName memberName)
+			{
+				if (memberName == null || memberName.TypeParameters == null)
+					return;
+				var chevronLocs = LocationsBag.GetLocations(memberName.TypeParameters);
+				if (chevronLocs != null)
+					parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 2]), Roles.LChevron), Roles.LChevron);
+				for (int i = 0; i < memberName.TypeParameters.Count; i++) {
+					if (chevronLocs != null && i > 0 && i - 1 < chevronLocs.Count)
+						parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [i - 1]), Roles.Comma), Roles.Comma);
+					var arg = memberName.TypeParameters [i];
+					if (arg == null)
+						continue;
+					var tp = new TypeParameterDeclaration();
+					
+					List<Location> varianceLocation;
+					switch (arg.Variance) {
+						case Variance.Contravariant:
+							tp.Variance = VarianceModifier.Contravariant;
+							varianceLocation = LocationsBag.GetLocations(arg);
+							if (varianceLocation != null)
+								tp.AddChild(new CSharpTokenNode(Convert(varianceLocation [0]), TypeParameterDeclaration.InVarianceKeywordRole), TypeParameterDeclaration.InVarianceKeywordRole);
+							break;
+						case Variance.Covariant:
+							tp.Variance = VarianceModifier.Covariant;
+							varianceLocation = LocationsBag.GetLocations(arg);
+							if (varianceLocation != null)
+								tp.AddChild(new CSharpTokenNode(Convert(varianceLocation [0]), TypeParameterDeclaration.OutVarianceKeywordRole), TypeParameterDeclaration.OutVarianceKeywordRole);
+							break;
+						default:
+							tp.Variance = VarianceModifier.Invariant;
+							break;
+							
+					}
+					
+					AddAttributeSection(tp, arg.OptAttributes);
+
+					switch (arg.Variance) {
+						case Variance.Covariant:
+							tp.Variance = VarianceModifier.Covariant;
+							break;
+						case Variance.Contravariant:
+							tp.Variance = VarianceModifier.Contravariant;
+							break;
+					}
+					tp.AddChild(Identifier.Create(arg.Name, Convert(arg.Location)), Roles.Identifier);
+					parent.AddChild(tp, Roles.TypeParameter);
+				}
+				if (chevronLocs != null)
+					parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 1]), Roles.RChevron), Roles.RChevron);
+			}
+
+			void AddTypeArguments(AstNode parent, MemberName memberName)
+			{
+				if (memberName == null || memberName.TypeParameters == null)
+					return;
+				var chevronLocs = LocationsBag.GetLocations(memberName.TypeParameters);
+				if (chevronLocs != null)
+					parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 2]), Roles.LChevron), Roles.LChevron);
+				
+				for (int i = 0; i < memberName.TypeParameters.Count; i++) {
+					var arg = memberName.TypeParameters [i];
+					if (arg == null)
+						continue;
+					parent.AddChild(ConvertToType(arg), Roles.TypeArgument);
+					if (chevronLocs != null && i < chevronLocs.Count - 2)
+						parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [i]), Roles.Comma), Roles.Comma);
+				}
+				
+				if (chevronLocs != null)
+					parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 1]), Roles.RChevron), Roles.RChevron);
+			}
+
+			void AddTypeArguments(AstNode parent, ATypeNameExpression memberName)
+			{
+				if (memberName == null || !memberName.HasTypeArguments)
+					return;
+				var chevronLocs = LocationsBag.GetLocations(memberName.TypeArguments);
+				if (chevronLocs != null)
+					parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 2]), Roles.LChevron), Roles.LChevron);
+				
+				for (int i = 0; i < memberName.TypeArguments.Count; i++) {
+					var arg = memberName.TypeArguments.Args [i];
+					if (arg == null)
+						continue;
+					parent.AddChild(ConvertToType(arg), Roles.TypeArgument);
+					if (chevronLocs != null && i < chevronLocs.Count - 2)
+						parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [i]), Roles.Comma), Roles.Comma);
+				}
+				
+				if (chevronLocs != null)
+					parent.AddChild(new CSharpTokenNode(Convert(chevronLocs [chevronLocs.Count - 1]), Roles.RChevron), Roles.RChevron);
+			}
+
+			void AddConstraints(AstNode parent, TypeParameters d)
+			{
+				if (d == null)
+					return;
+				for (int i = 0; i < d.Count; i++) {
+					var typeParameter = d [i];
+					if (typeParameter == null)
+						continue;
+					var c = typeParameter.Constraints;
+					if (c == null)
+						continue;
+					var location = LocationsBag.GetLocations(c);
+					var constraint = new Constraint();
+					constraint.AddChild(new CSharpTokenNode(Convert(c.Location), Roles.WhereKeyword), Roles.WhereKeyword);
+					constraint.AddChild(new SimpleType(Identifier.Create(c.TypeParameter.Value, Convert(c.TypeParameter.Location))), Roles.ConstraintTypeParameter);
+					if (location != null)
+						constraint.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Colon), Roles.Colon);
+					var commaLocs = LocationsBag.GetLocations(c.ConstraintExpressions);
+					int curComma = 0;
+					if (c.ConstraintExpressions != null) {
+						foreach (var expr in c.ConstraintExpressions) {
+							constraint.AddChild(ConvertToType(expr), Roles.BaseType);
+							var sce = expr as SpecialContraintExpr;
+							if (sce != null) {
+								switch (sce.Constraint) {
+									case SpecialConstraint.Class:
+										break;
+									case SpecialConstraint.Struct:
+										break;
+									case SpecialConstraint.Constructor:
+										var bl = LocationsBag.GetLocations(expr);
+										if (bl != null) {
+											constraint.AddChild(new CSharpTokenNode(Convert(bl [0]), Roles.LPar), Roles.LPar);
+											constraint.AddChild(new CSharpTokenNode(Convert(bl [1]), Roles.RPar), Roles.RPar);
+										}
+										break;
+								}
+							}
+
+							if (commaLocs != null && curComma < commaLocs.Count)
+								constraint.AddChild(new CSharpTokenNode(Convert(commaLocs [curComma++]), Roles.Comma), Roles.Comma);
+						}
+					}
+					
+					// We need to sort the constraints by position; as they might be in a different order than the type parameters
+					AstNode prevSibling = parent.LastChild;
+					while (prevSibling.StartLocation > constraint.StartLocation && prevSibling.PrevSibling != null)
+						prevSibling = prevSibling.PrevSibling;
+					parent.InsertChildAfter(prevSibling, constraint, Roles.Constraint);
+				}
+			}
+
+			Expression ConvertArgument(Argument arg)
+			{
+				var na = arg as NamedArgument;
+				if (na != null) {
+					var newArg = new NamedArgumentExpression();
+					newArg.AddChild(Identifier.Create(na.Name, Convert(na.Location)), Roles.Identifier);
+					
+					var loc = LocationsBag.GetLocations(na);
+					if (loc != null)
+						newArg.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.Colon), Roles.Colon);
+					
+					if (arg.ArgType == Argument.AType.Out || arg.ArgType == Argument.AType.Ref) {
+						var direction = new DirectionExpression();
+						direction.FieldDirection = arg.ArgType == Argument.AType.Out ? FieldDirection.Out : FieldDirection.Ref;
+						var argLocation = LocationsBag.GetLocations(arg);
+						if (argLocation != null) {
+							var r = arg.ArgType == Argument.AType.Out ? DirectionExpression.OutKeywordRole : DirectionExpression.RefKeywordRole;
+							direction.AddChild(new CSharpTokenNode(Convert(argLocation [0]), r), r);
+						}
+						direction.AddChild((Expression)arg.Expr.Accept(this), Roles.Expression);
+						newArg.AddChild(direction, Roles.Expression);
+					} else {
+						newArg.AddChild(na.Expr != null ? (Expression)na.Expr.Accept(this) : new ErrorExpression("Named argument expression parse error"), Roles.Expression);
+					}
+					return newArg;
+				}
+				
+				if (arg.ArgType == Argument.AType.Out || arg.ArgType == Argument.AType.Ref) {
+					var direction = new DirectionExpression();
+					direction.FieldDirection = arg.ArgType == Argument.AType.Out ? FieldDirection.Out : FieldDirection.Ref;
+					var argLocation = LocationsBag.GetLocations(arg);
+					if (argLocation != null) {
+						var r = arg.ArgType == Argument.AType.Out ? DirectionExpression.OutKeywordRole : DirectionExpression.RefKeywordRole;
+						direction.AddChild(new CSharpTokenNode(Convert(argLocation [0]), r), r);
+					}
+					direction.AddChild((Expression)arg.Expr.Accept(this), Roles.Expression);
+					return direction;
+				}
+				
+				return (Expression)arg.Expr.Accept(this);
+			}
+
+			void AddArguments(AstNode parent, Arguments args)
+			{
+				if (args == null)
+					return;
+				
+				var commaLocations = LocationsBag.GetLocations(args);
+				for (int i = 0; i < args.Count; i++) {
+					parent.AddChild(ConvertArgument(args [i]), Roles.Argument);
+					if (commaLocations != null && i < commaLocations.Count) {
+						parent.AddChild(new CSharpTokenNode(Convert(commaLocations [i]), Roles.Comma), Roles.Comma);
+					}
+				}
+				if (commaLocations != null && commaLocations.Count > args.Count)
+					parent.AddChild(new CSharpTokenNode(Convert(commaLocations [args.Count]), Roles.Comma), Roles.Comma);
+			}
+
+			public override object Visit(Invocation invocationExpression)
+			{
+				var result = new InvocationExpression();
+				var location = LocationsBag.GetLocations(invocationExpression);
+				if (invocationExpression.Exp != null)
+					result.AddChild((Expression)invocationExpression.Exp.Accept(this), Roles.TargetExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				AddArguments(result, invocationExpression.Arguments);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(New newExpression)
+			{
+				var result = new ObjectCreateExpression();
+				var location = LocationsBag.GetLocations(newExpression);
+				result.AddChild(new CSharpTokenNode(Convert(newExpression.Location), ObjectCreateExpression.NewKeywordRole), ObjectCreateExpression.NewKeywordRole);
+				
+				if (newExpression.TypeRequested != null)
+					result.AddChild(ConvertToType(newExpression.TypeRequested), Roles.Type);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				AddArguments(result, newExpression.Arguments);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				
+				return result;
+			}
+
+			public override object Visit(NewAnonymousType newAnonymousType)
+			{
+				var result = new AnonymousTypeCreateExpression();
+				var location = LocationsBag.GetLocations(newAnonymousType);
+				result.AddChild(new CSharpTokenNode(Convert(newAnonymousType.Location), ObjectCreateExpression.NewKeywordRole), ObjectCreateExpression.NewKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LBrace), Roles.LBrace);
+				if (newAnonymousType.Parameters != null) {
+					foreach (var par in newAnonymousType.Parameters) {
+						if (par == null)
+							continue;
+						var parLocation = LocationsBag.GetLocations(par);
+						
+						if (parLocation == null) {
+							if (par.Expr != null)
+								result.AddChild((Expression)par.Expr.Accept(this), Roles.Expression);
+						} else {
+							var namedExpression = new NamedExpression();
+							namedExpression.AddChild(Identifier.Create(par.Name, Convert(par.Location)), Roles.Identifier);
+							namedExpression.AddChild(new CSharpTokenNode(Convert(parLocation [0]), Roles.Assign), Roles.Assign);
+							if (par.Expr != null)
+								namedExpression.AddChild((Expression)par.Expr.Accept(this), Roles.Expression);
+							result.AddChild(namedExpression, Roles.Expression);
+						}
+					}
+				}
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RBrace), Roles.RBrace);
+				return result;
+			}
+
+			ArrayInitializerExpression ConvertCollectionOrObjectInitializers(CollectionOrObjectInitializers minit)
+			{
+				if (minit == null)
+					return null;
+				var init = new ArrayInitializerExpression();
+				AddConvertCollectionOrObjectInitializers(init, minit);
+				return init;
+			}
+
+			void AddConvertCollectionOrObjectInitializers(Expression init, CollectionOrObjectInitializers minit)
+			{
+				var initLoc = LocationsBag.GetLocations(minit);
+				var commaLoc = LocationsBag.GetLocations(minit.Initializers);
+				int curComma = 0;
+				init.AddChild(new CSharpTokenNode(Convert(minit.Location), Roles.LBrace), Roles.LBrace);
+				foreach (var expr in minit.Initializers) {
+					var collectionInit = expr as CollectionElementInitializer;
+					if (collectionInit != null) {
+						AstNode parent;
+						// For ease of use purposes in the resolver the ast representation
+						// of { a, b, c }  is { {a}, {b}, {c} } - but the generated ArrayInitializerExpression
+						// can be identified by expr.IsSingleElement.
+						if (!collectionInit.IsSingle) {
+							parent = new ArrayInitializerExpression();
+							parent.AddChild(new CSharpTokenNode(Convert(collectionInit.Location), Roles.LBrace), Roles.LBrace);
+						} else {
+							parent = ArrayInitializerExpression.CreateSingleElementInitializer();
+						}
+
+						if (collectionInit.Arguments != null) {
+							for (int i = 0; i < collectionInit.Arguments.Count; i++) {
+								var arg = collectionInit.Arguments [i] as CollectionElementInitializer.ElementInitializerArgument;
+								if (arg == null || arg.Expr == null)
+									continue;
+								parent.AddChild(
+									(Expression)arg.Expr.Accept(this),
+									Roles.Expression
+								);
+							}
+						}
+
+						if (!collectionInit.IsSingle) {
+							var braceLocs = LocationsBag.GetLocations(expr);
+							if (braceLocs != null)
+								parent.AddChild(new CSharpTokenNode(Convert(braceLocs [0]), Roles.RBrace), Roles.RBrace);
+						}
+						init.AddChild((ArrayInitializerExpression)parent, Roles.Expression);
+					} else {
+						var eleInit = expr as ElementInitializer;
+						if (eleInit != null) {
+							var nexpr = new NamedExpression();
+							nexpr.AddChild(
+								Identifier.Create(eleInit.Name, Convert(eleInit.Location)),
+								Roles.Identifier
+							);
+							var assignLoc = LocationsBag.GetLocations(eleInit);
+							if (assignLoc != null)
+								nexpr.AddChild(new CSharpTokenNode(Convert(assignLoc [0]), Roles.Assign), Roles.Assign);
+							if (eleInit.Source != null) {
+								var colInit = eleInit.Source as CollectionOrObjectInitializers;
+								if (colInit != null) {
+									var arrInit = new ArrayInitializerExpression();
+									AddConvertCollectionOrObjectInitializers(
+										arrInit,
+										colInit
+									);
+									nexpr.AddChild(arrInit, Roles.Expression);
+								} else {
+									nexpr.AddChild((Expression)eleInit.Source.Accept(this), Roles.Expression);
+								}
+							}
+
+							init.AddChild(nexpr, Roles.Expression);
+						}
+					}
+					if (commaLoc != null && curComma < commaLoc.Count)
+						init.AddChild(new CSharpTokenNode(Convert(commaLoc [curComma++]), Roles.Comma), Roles.Comma);
+				}
+
+				if (initLoc != null) {
+					if (initLoc.Count == 2) // optional comma
+						init.AddChild(new CSharpTokenNode(Convert(initLoc [0]), Roles.Comma), Roles.Comma);
+					init.AddChild(new CSharpTokenNode(Convert(initLoc [initLoc.Count - 1]), Roles.RBrace), Roles.RBrace);
+				}
+			}
+
+			public override object Visit(NewInitialize newInitializeExpression)
+			{
+				var result = new ObjectCreateExpression();
+				result.AddChild(new CSharpTokenNode(Convert(newInitializeExpression.Location), ObjectCreateExpression.NewKeywordRole), ObjectCreateExpression.NewKeywordRole);
+				
+				if (newInitializeExpression.TypeRequested != null)
+					result.AddChild(ConvertToType(newInitializeExpression.TypeRequested), Roles.Type);
+				
+				var location = LocationsBag.GetLocations(newInitializeExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				AddArguments(result, newInitializeExpression.Arguments);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				
+				var init = ConvertCollectionOrObjectInitializers(newInitializeExpression.Initializers);
+				if (init != null)
+					result.AddChild(init, ObjectCreateExpression.InitializerRole);
+				
+				return result;
+			}
+
+			public override object Visit(ArrayCreation arrayCreationExpression)
+			{
+				var result = new ArrayCreateExpression();
+				
+				var location = LocationsBag.GetLocations(arrayCreationExpression);
+				result.AddChild(new CSharpTokenNode(Convert(arrayCreationExpression.Location), ArrayCreateExpression.NewKeywordRole), ArrayCreateExpression.NewKeywordRole);
+				if (arrayCreationExpression.TypeExpression != null)
+					result.AddChild(ConvertToType(arrayCreationExpression.TypeExpression), Roles.Type);
+				
+				var next = arrayCreationExpression.Rank;
+				if (arrayCreationExpression.Arguments != null) {
+					// skip first array rank.
+					next = next.Next;
+					
+					if (location != null)
+						result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LBracket), Roles.LBracket);
+					
+					var commaLocations = LocationsBag.GetLocations(arrayCreationExpression.Arguments);
+					for (int i = 0; i < arrayCreationExpression.Arguments.Count; i++) {
+						var arg = arrayCreationExpression.Arguments [i];
+						if (arg != null)
+							result.AddChild((Expression)arg.Accept(this), Roles.Argument);
+						if (commaLocations != null && i < commaLocations.Count)
+							result.AddChild(new CSharpTokenNode(Convert(commaLocations [i]), Roles.Comma), Roles.Comma);
+					}
+					if (location != null && location.Count > 1)
+						result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RBracket), Roles.RBracket);
+					
+				}
+				
+				while (next != null) {
+					var spec = new ArraySpecifier(next.Dimension);
+					var loc = LocationsBag.GetLocations(next);
+					spec.AddChild(new CSharpTokenNode(Convert(next.Location), Roles.LBracket), Roles.LBracket);
+					result.AddChild(spec, ArrayCreateExpression.AdditionalArraySpecifierRole);
+					if (loc != null)
+						result.AddChild(new CSharpTokenNode(Convert(loc [0]), Roles.RBracket), Roles.RBracket);
+					next = next.Next;
+				}
+				
+				if (arrayCreationExpression.Initializers != null) {
+					var initLocation = LocationsBag.GetLocations(arrayCreationExpression.Initializers);
+					var initializer = new ArrayInitializerExpression();
+					
+					initializer.AddChild(new CSharpTokenNode(Convert(arrayCreationExpression.Initializers.Location), Roles.LBrace), Roles.LBrace);
+					var commaLocations = LocationsBag.GetLocations(arrayCreationExpression.Initializers.Elements);
+					for (int i = 0; i < arrayCreationExpression.Initializers.Count; i++) {
+						var init = arrayCreationExpression.Initializers [i];
+						if (init == null)
+							continue;
+						initializer.AddChild((Expression)init.Accept(this), Roles.Expression);
+						if (commaLocations != null && i < commaLocations.Count) {
+							initializer.AddChild(new CSharpTokenNode(Convert(commaLocations [i]), Roles.Comma), Roles.Comma);
+						}
+					}
+					if (initLocation != null) {
+						if (initLocation.Count == 2) // optional comma
+							initializer.AddChild(new CSharpTokenNode(Convert(initLocation [0]), Roles.Comma), Roles.Comma);
+						initializer.AddChild(new CSharpTokenNode(Convert(initLocation [initLocation.Count - 1]), Roles.RBrace), Roles.RBrace);
+					}
+					result.AddChild(initializer, ArrayCreateExpression.InitializerRole);
+				}
+				
+				return result;
+			}
+
+			public override object Visit(This thisExpression)
+			{
+				var result = new ThisReferenceExpression();
+				result.Location = Convert(thisExpression.Location);
+				return result;
+			}
+
+			public override object Visit(ArglistAccess argListAccessExpression)
+			{
+				var result = new UndocumentedExpression {
+					UndocumentedExpressionType = UndocumentedExpressionType.ArgListAccess
+				};
+				result.AddChild(new CSharpTokenNode(Convert(argListAccessExpression.Location), UndocumentedExpression.ArglistKeywordRole), UndocumentedExpression.ArglistKeywordRole);
+				return result;
+			}
+
+			#region Undocumented expressions
+
+			public override object Visit(Arglist argListExpression)
+			{
+				var result = new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.ArgList };
+				result.AddChild(new CSharpTokenNode(Convert(argListExpression.Location), UndocumentedExpression.ArglistKeywordRole), UndocumentedExpression.ArglistKeywordRole);
+				var location = LocationsBag.GetLocations(argListExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				AddArguments(result, argListExpression.Arguments);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(MakeRefExpr makeRefExpr)
+			{
+				var result = new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.MakeRef };
+				result.AddChild(new CSharpTokenNode(Convert(makeRefExpr.Location), UndocumentedExpression.MakerefKeywordRole), UndocumentedExpression.MakerefKeywordRole);
+				var location = LocationsBag.GetLocations(makeRefExpr);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (makeRefExpr.Expr != null)
+					result.AddChild((Expression)makeRefExpr.Expr.Accept(this), Roles.Argument);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(RefTypeExpr refTypeExpr)
+			{
+				var result = new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefType };
+				result.AddChild(new CSharpTokenNode(Convert(refTypeExpr.Location), UndocumentedExpression.ReftypeKeywordRole), UndocumentedExpression.ReftypeKeywordRole);
+				var location = LocationsBag.GetLocations(refTypeExpr);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				if (refTypeExpr.Expr != null)
+					result.AddChild((Expression)refTypeExpr.Expr.Accept(this), Roles.Argument);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(RefValueExpr refValueExpr)
+			{
+				var result = new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.RefValue };
+				result.AddChild(new CSharpTokenNode(Convert(refValueExpr.Location), UndocumentedExpression.RefvalueKeywordRole), UndocumentedExpression.RefvalueKeywordRole);
+				var location = LocationsBag.GetLocations(refValueExpr);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				
+				
+				if (refValueExpr.Expr != null)
+					result.AddChild((Expression)refValueExpr.Expr.Accept(this), Roles.Argument);
+
+				if (refValueExpr.FullNamedExpression != null)
+					result.AddChild((Expression)refValueExpr.FullNamedExpression.Accept(this), Roles.Argument);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			#endregion
+
+			public override object Visit(TypeOf typeOfExpression)
+			{
+				var result = new TypeOfExpression();
+				var location = LocationsBag.GetLocations(typeOfExpression);
+				result.AddChild(new CSharpTokenNode(Convert(typeOfExpression.Location), TypeOfExpression.TypeofKeywordRole), TypeOfExpression.TypeofKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (typeOfExpression.TypeExpression != null)
+					result.AddChild(ConvertToType(typeOfExpression.TypeExpression), Roles.Type);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(SizeOf sizeOfExpression)
+			{
+				var result = new SizeOfExpression();
+				var location = LocationsBag.GetLocations(sizeOfExpression);
+				result.AddChild(new CSharpTokenNode(Convert(sizeOfExpression.Location), SizeOfExpression.SizeofKeywordRole), SizeOfExpression.SizeofKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (sizeOfExpression.TypeExpression != null)
+					result.AddChild(ConvertToType(sizeOfExpression.TypeExpression), Roles.Type);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(CheckedExpr checkedExpression)
+			{
+				var result = new CheckedExpression();
+				var location = LocationsBag.GetLocations(checkedExpression);
+				result.AddChild(new CSharpTokenNode(Convert(checkedExpression.Location), CheckedExpression.CheckedKeywordRole), CheckedExpression.CheckedKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (checkedExpression.Expr != null)
+					result.AddChild((Expression)checkedExpression.Expr.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(UnCheckedExpr uncheckedExpression)
+			{
+				var result = new UncheckedExpression();
+				var location = LocationsBag.GetLocations(uncheckedExpression);
+				result.AddChild(new CSharpTokenNode(Convert(uncheckedExpression.Location), UncheckedExpression.UncheckedKeywordRole), UncheckedExpression.UncheckedKeywordRole);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.LPar), Roles.LPar);
+				if (uncheckedExpression.Expr != null)
+					result.AddChild((Expression)uncheckedExpression.Expr.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.RPar), Roles.RPar);
+				return result;
+			}
+
+			public override object Visit(ElementAccess elementAccessExpression)
+			{
+				var result = new IndexerExpression();
+				var location = LocationsBag.GetLocations(elementAccessExpression);
+				
+				if (elementAccessExpression.Expr != null)
+					result.AddChild((Expression)elementAccessExpression.Expr.Accept(this), Roles.TargetExpression);
+				result.AddChild(new CSharpTokenNode(Convert(elementAccessExpression.Location), Roles.LBracket), Roles.LBracket);
+				AddArguments(result, elementAccessExpression.Arguments);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.RBracket), Roles.RBracket);
+				return result;
+			}
+
+			public override object Visit(BaseThis baseAccessExpression)
+			{
+				var result = new BaseReferenceExpression();
+				result.Location = Convert(baseAccessExpression.Location);
+				return result;
+			}
+
+			public override object Visit(StackAlloc stackAllocExpression)
+			{
+				var result = new StackAllocExpression();
+				
+				var location = LocationsBag.GetLocations(stackAllocExpression);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), StackAllocExpression.StackallocKeywordRole), StackAllocExpression.StackallocKeywordRole);
+				if (stackAllocExpression.TypeExpression != null)
+					result.AddChild(ConvertToType(stackAllocExpression.TypeExpression), Roles.Type);
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), Roles.LBracket), Roles.LBracket);
+				if (stackAllocExpression.CountExpression != null)
+					result.AddChild((Expression)stackAllocExpression.CountExpression.Accept(this), Roles.Expression);
+				if (location != null && location.Count > 2)
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), Roles.RBracket), Roles.RBracket);
+				return result;
+			}
+
+			public override object Visit(SimpleAssign simpleAssign)
+			{
+				var result = new AssignmentExpression();
+				
+				result.Operator = AssignmentOperatorType.Assign;
+				if (simpleAssign.Target != null)
+					result.AddChild((Expression)simpleAssign.Target.Accept(this), AssignmentExpression.LeftRole);
+				var location = LocationsBag.GetLocations(simpleAssign);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), AssignmentExpression.AssignRole), AssignmentExpression.AssignRole);
+				if (simpleAssign.Source != null) {
+					result.AddChild((Expression)simpleAssign.Source.Accept(this), AssignmentExpression.RightRole);
+				}
+				return result;
+			}
+
+			public override object Visit(CompoundAssign compoundAssign)
+			{
+				var result = new AssignmentExpression();
+				switch (compoundAssign.Op) {
+					case Binary.Operator.Multiply:
+						result.Operator = AssignmentOperatorType.Multiply;
+						break;
+					case Binary.Operator.Division:
+						result.Operator = AssignmentOperatorType.Divide;
+						break;
+					case Binary.Operator.Modulus:
+						result.Operator = AssignmentOperatorType.Modulus;
+						break;
+					case Binary.Operator.Addition:
+						result.Operator = AssignmentOperatorType.Add;
+						break;
+					case Binary.Operator.Subtraction:
+						result.Operator = AssignmentOperatorType.Subtract;
+						break;
+					case Binary.Operator.LeftShift:
+						result.Operator = AssignmentOperatorType.ShiftLeft;
+						break;
+					case Binary.Operator.RightShift:
+						result.Operator = AssignmentOperatorType.ShiftRight;
+						break;
+					case Binary.Operator.BitwiseAnd:
+						result.Operator = AssignmentOperatorType.BitwiseAnd;
+						break;
+					case Binary.Operator.BitwiseOr:
+						result.Operator = AssignmentOperatorType.BitwiseOr;
+						break;
+					case Binary.Operator.ExclusiveOr:
+						result.Operator = AssignmentOperatorType.ExclusiveOr;
+						break;
+				}
+				
+				if (compoundAssign.Target != null)
+					result.AddChild((Expression)compoundAssign.Target.Accept(this), AssignmentExpression.LeftRole);
+				var location = LocationsBag.GetLocations(compoundAssign);
+				if (location != null) {
+					var r = AssignmentExpression.GetOperatorRole(result.Operator);
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), r), r);
+				}
+				if (compoundAssign.Source != null)
+					result.AddChild((Expression)compoundAssign.Source.Accept(this), AssignmentExpression.RightRole);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.AnonymousMethodExpression anonymousMethodExpression)
+			{
+				var result = new AnonymousMethodExpression();
+				var location = LocationsBag.GetLocations(anonymousMethodExpression);
+				int l = 0;
+				if (anonymousMethodExpression.IsAsync) {
+					result.IsAsync = true;
+					result.AddChild(new CSharpTokenNode(Convert(location [l++]), AnonymousMethodExpression.AsyncModifierRole), AnonymousMethodExpression.AsyncModifierRole);
+				}
+				if (location != null) {
+					result.AddChild(new CSharpTokenNode(Convert(location [l++]), AnonymousMethodExpression.DelegateKeywordRole), AnonymousMethodExpression.DelegateKeywordRole);
+					
+					if (location.Count > l) {
+						result.HasParameterList = true;
+						result.AddChild(new CSharpTokenNode(Convert(location [l++]), Roles.LPar), Roles.LPar);
+						AddParameter(result, anonymousMethodExpression.Parameters);
+						result.AddChild(new CSharpTokenNode(Convert(location [l++]), Roles.RPar), Roles.RPar);
+					}
+				}
+				if (anonymousMethodExpression.Block != null)
+					result.AddChild((BlockStatement)anonymousMethodExpression.Block.Accept(this), Roles.Body);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.LambdaExpression lambdaExpression)
+			{
+				var result = new LambdaExpression();
+				var location = LocationsBag.GetLocations(lambdaExpression);
+				int l = 0;
+				if (lambdaExpression.IsAsync) {
+					result.IsAsync = true;
+					result.AddChild(new CSharpTokenNode(Convert(location [l++]), LambdaExpression.AsyncModifierRole), LambdaExpression.AsyncModifierRole);
+				}
+				if (location == null || location.Count == l + 1) {
+					if (lambdaExpression.Block != null)
+						AddParameter(result, lambdaExpression.Parameters);
+					if (location != null)
+						result.AddChild(new CSharpTokenNode(Convert(location [l++]), LambdaExpression.ArrowRole), LambdaExpression.ArrowRole);
+				} else {
+					result.AddChild(new CSharpTokenNode(Convert(location [l++]), Roles.LPar), Roles.LPar);
+					if (lambdaExpression.Block != null)
+						AddParameter(result, lambdaExpression.Parameters);
+					if (location != null) {
+						result.AddChild(new CSharpTokenNode(Convert(location [l++]), Roles.RPar), Roles.RPar);
+						result.AddChild(new CSharpTokenNode(Convert(location [l++]), LambdaExpression.ArrowRole), LambdaExpression.ArrowRole);
+					}
+				}
+				if (lambdaExpression.Block != null) {
+					if (lambdaExpression.Block.IsCompilerGenerated) {
+						var generatedReturn = (ContextualReturn)lambdaExpression.Block.Statements [0];
+						result.AddChild((AstNode)generatedReturn.Expr.Accept(this), LambdaExpression.BodyRole);
+					} else {
+						result.AddChild((AstNode)lambdaExpression.Block.Accept(this), LambdaExpression.BodyRole);
+					}
+				}
+				return result;
+			}
+
+			public override object Visit(ConstInitializer constInitializer)
+			{
+				return constInitializer.Expr.Accept(this);
+			}
+
+			public override object Visit(ArrayInitializer arrayInitializer)
+			{
+				var result = new ArrayInitializerExpression();
+				var location = LocationsBag.GetLocations(arrayInitializer);
+				result.AddChild(new CSharpTokenNode(Convert(arrayInitializer.Location), Roles.LBrace), Roles.LBrace);
+				var commaLocations = LocationsBag.GetLocations(arrayInitializer.Elements);
+				for (int i = 0; i < arrayInitializer.Count; i++) {
+					var init = arrayInitializer [i];
+					if (init == null)
+						continue;
+					result.AddChild((Expression)init.Accept(this), Roles.Expression);
+					if (commaLocations != null && i < commaLocations.Count)
+						result.AddChild(new CSharpTokenNode(Convert(commaLocations [i]), Roles.Comma), Roles.Comma);
+				}
+				
+				if (location != null) {
+					if (location.Count == 2) // optional comma
+						result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Comma), Roles.Comma);
+					result.AddChild(new CSharpTokenNode(Convert(location [location.Count - 1]), Roles.RBrace), Roles.RBrace);
+				}
+				return result;
+			}
+
+			#endregion
+
+			#region LINQ expressions
+
+			QueryOrderClause currentQueryOrderClause;
+
+			public override object Visit(Mono.CSharp.Linq.QueryExpression queryExpression)
+			{
+				var oldQueryOrderClause = currentQueryOrderClause;
+				try {
+					currentQueryOrderClause = null;
+					var result = new QueryExpression();
+					
+					var currentClause = queryExpression.next;
+					
+					while (currentClause != null) {
+						var clause = (QueryClause)currentClause.Accept(this);
+						if (clause is QueryContinuationClause) {
+							// insert preceding query at beginning of QueryContinuationClause
+							clause.InsertChildAfter(null, result, QueryContinuationClause.PrecedingQueryRole);
+							// create a new QueryExpression for the remaining query
+							result = new QueryExpression();
+						}
+						if (clause != null) {
+							result.AddChild(clause, QueryExpression.ClauseRole);
+						}
+						currentClause = currentClause.next;
+					}
+					
+					return result;
+				} finally {
+					currentQueryOrderClause = oldQueryOrderClause;
+				}
+			}
+
+			public override object Visit(Mono.CSharp.Linq.QueryStartClause queryExpression)
+			{
+				if (queryExpression.Expr == null) {
+					var intoClause = new QueryContinuationClause();
+					intoClause.AddChild(new CSharpTokenNode(Convert(queryExpression.Location), QueryContinuationClause.IntoKeywordRole), QueryContinuationClause.IntoKeywordRole);
+					intoClause.AddChild(Identifier.Create(queryExpression.IntoVariable.Name, Convert(queryExpression.IntoVariable.Location)), Roles.Identifier);
+					return intoClause;
+				}
+				
+				var fromClause = new QueryFromClause();
+
+				fromClause.AddChild(new CSharpTokenNode(Convert(queryExpression.Location), QueryFromClause.FromKeywordRole), QueryFromClause.FromKeywordRole);
+				
+				if (queryExpression.IdentifierType != null)
+					fromClause.AddChild(ConvertToType(queryExpression.IdentifierType), Roles.Type);
+				
+				fromClause.AddChild(Identifier.Create(queryExpression.IntoVariable.Name, Convert(queryExpression.IntoVariable.Location)), Roles.Identifier);
+				
+				var location = LocationsBag.GetLocations(queryExpression);
+				if (location != null)
+					fromClause.AddChild(new CSharpTokenNode(Convert(location [0]), QueryFromClause.InKeywordRole), QueryFromClause.InKeywordRole);
+
+				if (queryExpression.Expr != null)
+					fromClause.AddChild((Expression)queryExpression.Expr.Accept(this), Roles.Expression);
+				return fromClause;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.SelectMany selectMany)
+			{
+				var fromClause = new QueryFromClause();
+
+				fromClause.AddChild(new CSharpTokenNode(Convert(selectMany.Location), QueryFromClause.FromKeywordRole), QueryFromClause.FromKeywordRole);
+				
+				if (selectMany.IdentifierType != null)
+					fromClause.AddChild(ConvertToType(selectMany.IdentifierType), Roles.Type);
+				
+				fromClause.AddChild(Identifier.Create(selectMany.IntoVariable.Name, Convert(selectMany.IntoVariable.Location)), Roles.Identifier);
+				
+				var location = LocationsBag.GetLocations(selectMany);
+				if (location != null)
+					fromClause.AddChild(new CSharpTokenNode(Convert(location [0]), QueryFromClause.InKeywordRole), QueryFromClause.InKeywordRole);
+
+				if (selectMany.Expr != null)
+					fromClause.AddChild((Expression)selectMany.Expr.Accept(this), Roles.Expression);
+				return fromClause;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.Select select)
+			{
+				var result = new QuerySelectClause();
+				result.AddChild(new CSharpTokenNode(Convert(select.Location), QuerySelectClause.SelectKeywordRole), QuerySelectClause.SelectKeywordRole);
+				if (select.Expr != null)
+					result.AddChild((Expression)select.Expr.Accept(this), Roles.Expression);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.GroupBy groupBy)
+			{
+				var result = new QueryGroupClause();
+				var location = LocationsBag.GetLocations(groupBy);
+				result.AddChild(new CSharpTokenNode(Convert(groupBy.Location), QueryGroupClause.GroupKeywordRole), QueryGroupClause.GroupKeywordRole);
+				if (groupBy.ElementSelector != null)
+					result.AddChild((Expression)groupBy.ElementSelector.Accept(this), QueryGroupClause.ProjectionRole);
+				if (location != null) {
+					var byLoc = Convert(location[0]);
+					if (byLoc.Line > 1 || byLoc.Column > 1)
+						result.AddChild(new CSharpTokenNode(byLoc, QueryGroupClause.ByKeywordRole), QueryGroupClause.ByKeywordRole);
+				}
+				if (groupBy.Expr != null)
+					result.AddChild((Expression)groupBy.Expr.Accept(this), QueryGroupClause.KeyRole);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.Let let)
+			{
+				var result = new QueryLetClause();
+				var location = LocationsBag.GetLocations(let);
+				
+				result.AddChild(new CSharpTokenNode(Convert(let.Location), QueryLetClause.LetKeywordRole), QueryLetClause.LetKeywordRole);
+				result.AddChild(Identifier.Create(let.IntoVariable.Name, Convert(let.IntoVariable.Location)), Roles.Identifier);
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), Roles.Assign), Roles.Assign);
+				if (let.Expr != null)
+					result.AddChild((Expression)let.Expr.Accept(this), Roles.Expression);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.Where where)
+			{
+				var result = new QueryWhereClause();
+				result.AddChild(new CSharpTokenNode(Convert(where.Location), QueryWhereClause.WhereKeywordRole), QueryWhereClause.WhereKeywordRole);
+				if (where.Expr != null)
+					result.AddChild((Expression)where.Expr.Accept(this), Roles.Condition);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.Join join)
+			{
+				var result = new QueryJoinClause();
+				var location = LocationsBag.GetLocations(join);
+				result.AddChild(new CSharpTokenNode(Convert(join.Location), QueryJoinClause.JoinKeywordRole), QueryJoinClause.JoinKeywordRole);
+
+				if (join.IdentifierType != null)
+					result.AddChild(ConvertToType(join.IdentifierType), QueryJoinClause.TypeRole);
+
+				result.AddChild(Identifier.Create(join.JoinVariable.Name, Convert(join.JoinVariable.Location)), QueryJoinClause.JoinIdentifierRole);
+
+				if (join.IdentifierType != null)
+					result.AddChild(ConvertToType(join.IdentifierType), QueryJoinClause.TypeRole);
+
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), QueryJoinClause.InKeywordRole), QueryJoinClause.InKeywordRole);
+
+				if (join.Expr != null)
+					result.AddChild((Expression)join.Expr.Accept(this), QueryJoinClause.InExpressionRole);
+				
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), QueryJoinClause.OnKeywordRole), QueryJoinClause.OnKeywordRole);
+				
+				var outer = join.OuterSelector.Statements.FirstOrDefault() as ContextualReturn;
+				if (outer != null)
+					result.AddChild((Expression)outer.Expr.Accept(this), QueryJoinClause.OnExpressionRole);
+				
+				if (location != null && location.Count > 2)
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), QueryJoinClause.EqualsKeywordRole), QueryJoinClause.EqualsKeywordRole);
+				
+				var inner = join.InnerSelector.Statements.FirstOrDefault() as ContextualReturn;
+				if (inner != null)
+					result.AddChild((Expression)inner.Expr.Accept(this), QueryJoinClause.EqualsExpressionRole);
+				
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.GroupJoin groupJoin)
+			{
+				var result = new QueryJoinClause();
+				var location = LocationsBag.GetLocations(groupJoin);
+				result.AddChild(new CSharpTokenNode(Convert(groupJoin.Location), QueryJoinClause.JoinKeywordRole), QueryJoinClause.JoinKeywordRole);
+				
+				// mcs seems to have swapped IntoVariable with JoinVariable, so we'll swap it back here
+				result.AddChild(Identifier.Create(groupJoin.IntoVariable.Name, Convert(groupJoin.IntoVariable.Location)), QueryJoinClause.JoinIdentifierRole);
+				
+				if (location != null)
+					result.AddChild(new CSharpTokenNode(Convert(location [0]), QueryJoinClause.InKeywordRole), QueryJoinClause.InKeywordRole);
+
+				if (groupJoin.Expr != null)
+					result.AddChild((Expression)groupJoin.Expr.Accept(this), QueryJoinClause.InExpressionRole);
+
+				if (location != null && location.Count > 1)
+					result.AddChild(new CSharpTokenNode(Convert(location [1]), QueryJoinClause.OnKeywordRole), QueryJoinClause.OnKeywordRole);
+
+				var outer = groupJoin.OuterSelector.Statements.FirstOrDefault() as ContextualReturn;
+				if (outer != null)
+					result.AddChild((Expression)outer.Expr.Accept(this), QueryJoinClause.OnExpressionRole);
+				
+
+				if (location != null && location.Count > 2)
+					result.AddChild(new CSharpTokenNode(Convert(location [2]), QueryJoinClause.EqualsKeywordRole), QueryJoinClause.EqualsKeywordRole);
+				var inner = groupJoin.InnerSelector.Statements.FirstOrDefault() as ContextualReturn;
+				if (inner != null)
+					result.AddChild((Expression)inner.Expr.Accept(this), QueryJoinClause.EqualsExpressionRole);
+				
+				if (location != null && location.Count > 3)
+					result.AddChild(new CSharpTokenNode(Convert(location [3]), QueryJoinClause.IntoKeywordRole), QueryJoinClause.IntoKeywordRole);
+				
+				result.AddChild(Identifier.Create(groupJoin.JoinVariable.Name, Convert(groupJoin.JoinVariable.Location)), QueryJoinClause.IntoIdentifierRole);
+				return result;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.OrderByAscending orderByAscending)
+			{
+				currentQueryOrderClause = new QueryOrderClause();
+				var location2 = LocationsBag.GetLocations(orderByAscending.block);
+				if (location2 != null)
+					currentQueryOrderClause.AddChild(new CSharpTokenNode(Convert(location2 [0]), QueryOrderClause.OrderbyKeywordRole), QueryOrderClause.OrderbyKeywordRole);
+				var ordering = new QueryOrdering();
+				if (orderByAscending.Expr != null)
+					ordering.AddChild((Expression)orderByAscending.Expr.Accept(this), Roles.Expression);
+				var location = LocationsBag.GetLocations(orderByAscending);
+				if (location != null) {
+					ordering.Direction = QueryOrderingDirection.Ascending;
+					ordering.AddChild(new CSharpTokenNode(Convert(location [0]), QueryOrdering.AscendingKeywordRole), QueryOrdering.AscendingKeywordRole);
+				}
+				currentQueryOrderClause.AddChild(ordering, QueryOrderClause.OrderingRole);
+				return currentQueryOrderClause;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.OrderByDescending orderByDescending)
+			{
+				currentQueryOrderClause = new QueryOrderClause();
+				
+				var ordering = new QueryOrdering();
+				if (orderByDescending.Expr != null)
+					ordering.AddChild((Expression)orderByDescending.Expr.Accept(this), Roles.Expression);
+				var location = LocationsBag.GetLocations(orderByDescending);
+				if (location != null) {
+					ordering.Direction = QueryOrderingDirection.Descending;
+					ordering.AddChild(new CSharpTokenNode(Convert(location [0]), QueryOrdering.DescendingKeywordRole), QueryOrdering.DescendingKeywordRole);
+				}
+				currentQueryOrderClause.AddChild(ordering, QueryOrderClause.OrderingRole);
+				return currentQueryOrderClause;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.ThenByAscending thenByAscending)
+			{
+				var ordering = new QueryOrdering();
+				if (thenByAscending.Expr != null)
+					ordering.AddChild((Expression)thenByAscending.Expr.Accept(this), Roles.Expression);
+				var location = LocationsBag.GetLocations(thenByAscending);
+				if (location != null) {
+					ordering.Direction = QueryOrderingDirection.Ascending;
+					ordering.AddChild(new CSharpTokenNode(Convert(location [0]), QueryOrdering.AscendingKeywordRole), QueryOrdering.AscendingKeywordRole);
+				}
+				currentQueryOrderClause.AddChild(ordering, QueryOrderClause.OrderingRole);
+				return null;
+			}
+
+			public override object Visit(Mono.CSharp.Linq.ThenByDescending thenByDescending)
+			{
+				var ordering = new QueryOrdering();
+				if (thenByDescending.Expr != null)
+					ordering.AddChild((Expression)thenByDescending.Expr.Accept(this), Roles.Expression);
+				var location = LocationsBag.GetLocations(thenByDescending);
+				if (location != null) {
+					ordering.Direction = QueryOrderingDirection.Descending;
+					ordering.AddChild(new CSharpTokenNode(Convert(location [0]), QueryOrdering.DescendingKeywordRole), QueryOrdering.DescendingKeywordRole);
+				}
+				currentQueryOrderClause.AddChild(ordering, QueryOrderClause.OrderingRole);
+				return null;
+			}
+
+			public override object Visit(Await awaitExpr)
+			{
+				var result = new UnaryOperatorExpression();
+				result.Operator = UnaryOperatorType.Await;
+				result.AddChild(new CSharpTokenNode(Convert(awaitExpr.Location), UnaryOperatorExpression.AwaitRole), UnaryOperatorExpression.AwaitRole);
+				if (awaitExpr.Expression != null)
+					result.AddChild((Expression)awaitExpr.Expression.Accept(this), Roles.Expression);
+				return result;
+			}
+
+			#endregion
+
+			#region XmlDoc
+
+			public DocumentationReference ConvertXmlDoc(DocumentationBuilder doc)
+			{
+				var result = new DocumentationReference();
+				if (doc.ParsedName != null) {
+					if (doc.ParsedName.Name == "<this>") {
+						result.SymbolKind = SymbolKind.Indexer;
+					} else {
+						result.MemberName = doc.ParsedName.Name;
+					}
+					if (doc.ParsedName.Left != null) {
+						result.DeclaringType = ConvertToType(doc.ParsedName.Left);
+					} else if (doc.ParsedBuiltinType != null) {
+						result.DeclaringType = ConvertToType(doc.ParsedBuiltinType);
+					}
+					if (doc.ParsedName.TypeParameters != null) {
+						for (int i = 0; i < doc.ParsedName.TypeParameters.Count; i++) {
+							result.TypeArguments.Add(ConvertToType(doc.ParsedName.TypeParameters [i]));
+						}
+					}
+				} else if (doc.ParsedBuiltinType != null) {
+					result.SymbolKind = SymbolKind.TypeDefinition;
+					result.DeclaringType = ConvertToType(doc.ParsedBuiltinType);
+				}
+				if (doc.ParsedParameters != null) {
+					result.HasParameterList = true;
+					result.Parameters.AddRange(doc.ParsedParameters.Select(ConvertXmlDocParameter));
+				}
+				if (doc.ParsedOperator != null) {
+					result.SymbolKind = SymbolKind.Operator;
+					result.OperatorType = (OperatorType)doc.ParsedOperator;
+					if (result.OperatorType == OperatorType.Implicit || result.OperatorType == OperatorType.Explicit) {
+						var returnTypeParam = result.Parameters.LastOrNullObject();
+						returnTypeParam.Remove(); // detach from parameter list
+						var returnType = returnTypeParam.Type;
+						returnType.Remove();
+						result.ConversionOperatorReturnType = returnType;
+					}
+					if (result.Parameters.Count == 0) {
+						// reset HasParameterList if necessary
+						result.HasParameterList = false;
+					}
+				}
+				return result;
+			}
+
+			ParameterDeclaration ConvertXmlDocParameter(DocumentationParameter p)
+			{
+				var result = new ParameterDeclaration();
+				switch (p.Modifier) {
+					case Parameter.Modifier.OUT:
+						result.ParameterModifier = ParameterModifier.Out;
+						break;
+					case Parameter.Modifier.REF:
+						result.ParameterModifier = ParameterModifier.Ref;
+						break;
+					case Parameter.Modifier.PARAMS:
+						result.ParameterModifier = ParameterModifier.Params;
+						break;
+				}
+				if (p.Type != null) {
+					result.Type = ConvertToType(p.Type);
+				}
+				return result;
+			}
+
+			#endregion
+
+		}
+
+		public CSharpParser()
+		{
+			compilerSettings = new CompilerSettings();
+		}
+
+		public CSharpParser(CompilerSettings args)
+		{
+			compilerSettings = args ?? new CompilerSettings();
+		}
+
+		void InsertComments(CompilerCompilationUnit top, ConversionVisitor conversionVisitor)
+		{
+			AstNode insertionPoint = conversionVisitor.Unit.FirstChild;
+			foreach (var special in top.SpecialsBag.Specials) {
+				AstNode newLeaf = null;
+				Role role = null;
+				bool isDocumentationComment = false;
+				var comment = special as SpecialsBag.Comment;
+				if (comment != null) {
+					// HACK: multiline documentation comment detection; better move this logic into the mcs tokenizer
+					bool isMultilineDocumentationComment = (comment.CommentType == SpecialsBag.CommentType.Multi && comment.Content.StartsWith("*", StringComparison.Ordinal) && !comment.Content.StartsWith("**", StringComparison.Ordinal));
+					isDocumentationComment = comment.CommentType == SpecialsBag.CommentType.Documentation || isMultilineDocumentationComment;
+					if (conversionVisitor.convertTypeSystemMode && !isDocumentationComment)
+						continue;
+					var type = isMultilineDocumentationComment ? CommentType.MultiLineDocumentation : (CommentType)comment.CommentType;
+					var start = new TextLocation(comment.Line, comment.Col);
+					var end = new TextLocation(comment.EndLine, comment.EndCol);
+					newLeaf = new Comment(type, start, end) {
+						StartsLine = comment.StartsLine,
+						Content = isMultilineDocumentationComment ? comment.Content.Substring(1) : comment.Content
+					};
+					role = Roles.Comment;
+				} else if (!GenerateTypeSystemMode) {
+					var pragmaDirective = special as SpecialsBag.PragmaPreProcessorDirective;
+					if (pragmaDirective != null) {
+						var pragma = new PragmaWarningPreprocessorDirective(new TextLocation(pragmaDirective.Line, pragmaDirective.Col), new TextLocation(pragmaDirective.EndLine, pragmaDirective.EndCol));
+						pragma.AddChild(new CSharpTokenNode(new TextLocation(pragmaDirective.Line, pragmaDirective.Col), PragmaWarningPreprocessorDirective.PragmaKeywordRole), PragmaWarningPreprocessorDirective.PragmaKeywordRole);
+						pragma.AddChild(new CSharpTokenNode(new TextLocation(pragmaDirective.Line, pragmaDirective.WarningColumn), PragmaWarningPreprocessorDirective.WarningKeywordRole), PragmaWarningPreprocessorDirective.WarningKeywordRole);
+						var pragmaRole = pragmaDirective.Disalbe ? PragmaWarningPreprocessorDirective.DisableKeywordRole : PragmaWarningPreprocessorDirective.RestoreKeywordRole;
+						pragma.AddChild(new CSharpTokenNode(new TextLocation(pragmaDirective.Line, pragmaDirective.DisableRestoreColumn), pragmaRole), pragmaRole);
+						foreach (var code in pragmaDirective.Codes) {
+							pragma.AddChild((PrimitiveExpression)conversionVisitor.Visit(code), PragmaWarningPreprocessorDirective.WarningRole);
+						}
+						newLeaf = pragma;
+						role = Roles.PreProcessorDirective;
+						goto end;
+					}
+					var lineDirective = special as SpecialsBag.LineProcessorDirective;
+					if (lineDirective != null) {
+						var pragma = new LinePreprocessorDirective(new TextLocation(lineDirective.Line, lineDirective.Col), new TextLocation(lineDirective.EndLine, lineDirective.EndCol));
+						pragma.LineNumber = lineDirective.LineNumber;
+						pragma.FileName = lineDirective.FileName;
+						newLeaf = pragma;
+						role = Roles.PreProcessorDirective;
+						goto end;
+					}
+					var directive = special as SpecialsBag.PreProcessorDirective;
+					if (directive != null) {
+						newLeaf = new PreProcessorDirective((PreProcessorDirectiveType)((int)directive.Cmd & 0xF), new TextLocation(directive.Line, directive.Col), new TextLocation(directive.EndLine, directive.EndCol)) {
+							Argument = directive.Arg,
+							Take = directive.Take
+						};
+						role = Roles.PreProcessorDirective;
+					}
+					end:
+					;
+				}
+				if (newLeaf != null) {
+					InsertComment(ref insertionPoint, newLeaf, role, isDocumentationComment, conversionVisitor.Unit);
+				}
+			}
+			if (!GenerateTypeSystemMode) {
+				// We cannot insert newlines in the same loop as comments/preprocessor directives
+				// because they are not correctly ordered in the specials bag
+				insertionPoint = conversionVisitor.Unit.FirstChild;
+				for (int i = 0; i < top.SpecialsBag.Specials.Count; i++) {
+					var newLine = top.SpecialsBag.Specials [i] as SpecialsBag.NewLineToken;
+					if (newLine != null) {
+						var newLeaf = new NewLineNode(new TextLocation(newLine.Line, newLine.Col + 1));
+						newLeaf.NewLineType = newLine.NewLine == SpecialsBag.NewLine.Unix ? UnicodeNewline.LF : UnicodeNewline.CRLF;
+						InsertComment(ref insertionPoint, newLeaf, Roles.NewLine, false, conversionVisitor.Unit);
+					}
+				}
+			}
+		}
+
+		static void InsertComment(ref AstNode insertionPoint, AstNode newNode, Role role, bool isDocumentationComment, AstNode rootNode)
+		{
+			TextLocation insertAt = newNode.StartLocation;
+			// Advance insertionPoint to the first node that has a start location >= insertAt
+			while (insertionPoint != null && insertionPoint.StartLocation < insertAt) {
+				// Enter the current node if insertAt is within
+				while (insertAt < insertionPoint.EndLocation && insertionPoint.FirstChild != null) {
+					insertionPoint = insertionPoint.FirstChild;
+				}
+				// Go to next node (insertionPoint.NextSibling if it exists; otherwise the next sibling of the parent node etc.)
+				insertionPoint = insertionPoint.GetNextNode();
+			}
+			// As a special case, XmlDoc gets inserted at the beginning of the entity declaration
+			if (isDocumentationComment && insertionPoint is EntityDeclaration && insertionPoint.FirstChild != null) {
+				insertionPoint = insertionPoint.FirstChild;
+			}
+			if (insertionPoint == null) {
+				// we're at the end of the compilation unit
+				rootNode.AddChildUnsafe(newNode, role);
+			} else {
+				insertionPoint.Parent.InsertChildBeforeUnsafe(insertionPoint, newNode, role);
+			}
+		}
+
+		public class ErrorReportPrinter : ReportPrinter
+		{
+			readonly string fileName;
+			public readonly List<Error> Errors = new List<Error>();
+
+			public ErrorReportPrinter(string fileName)
+			{
+				this.fileName = fileName;
+			}
+
+			public override void Print(AbstractMessage msg, bool showFullPath)
+			{
+				base.Print(msg, showFullPath);
+				var newError = new Error(msg.IsWarning ? ErrorType.Warning : ErrorType.Error, msg.Text, new DomRegion(fileName, msg.Location.Row, msg.Location.Column));
+				Errors.Add(newError);
+			}
+		}
+
+		ErrorReportPrinter errorReportPrinter = new ErrorReportPrinter(null);
+
+		[Obsolete("Use the Errors/Warnings/ErrorsAndWarnings properties instead")]
+		public ErrorReportPrinter ErrorPrinter {
+			get {
+				return errorReportPrinter;
+			}
+		}
+
+		public bool HasErrors {
+			get {
+				return errorReportPrinter.ErrorsCount > 0;
+			}
+		}
+
+		public bool HasWarnings {
+			get {
+				return errorReportPrinter.WarningsCount > 0;
+			}
+		}
+
+		public IEnumerable<Error> Errors {
+			get {
+				return errorReportPrinter.Errors.Where(e => e.ErrorType == ErrorType.Error);
+			}
+		}
+
+		public IEnumerable<Error> Warnings {
+			get {
+				return errorReportPrinter.Errors.Where(e => e.ErrorType == ErrorType.Warning);
+			}
+		}
+
+		public IEnumerable<Error> ErrorsAndWarnings {
+			get { return errorReportPrinter.Errors; }
+		}
+
+		/// <summary>
+		/// Parses a C# code file.
+		/// </summary>
+		/// <param name="program">The source code to parse.</param>
+		/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
+		/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
+		/// <returns>Returns the syntax tree.</returns>
+		public SyntaxTree Parse(string program, string fileName = "")
+		{
+			return Parse(new StringTextSource(program), fileName);
+		}
+
+		/// <summary>
+		/// Parses a C# code file.
+		/// </summary>
+		/// <param name="reader">The text reader containing the source code to parse.</param>
+		/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
+		/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
+		/// <returns>Returns the syntax tree.</returns>
+		public SyntaxTree Parse(TextReader reader, string fileName = "")
+		{
+			return Parse(new StringTextSource(reader.ReadToEnd()), fileName);
+		}
+
+		/// <summary>
+		/// Converts a Mono.CSharp syntax tree into an NRefactory syntax tree.
+		/// </summary>
+		public SyntaxTree Parse(CompilerCompilationUnit top, string fileName)
+		{
+			if (top == null) {
+				return null;
+			}
+			CSharpParser.ConversionVisitor conversionVisitor = new ConversionVisitor(GenerateTypeSystemMode, top.LocationsBag);
+			top.ModuleCompiled.Accept(conversionVisitor);
+			InsertComments(top, conversionVisitor);
+			if (CompilationUnitCallback != null) {
+				CompilationUnitCallback(top);
+			}
+			var expr = top.LastYYValue as Mono.CSharp.Expression;
+			if (expr != null)
+				conversionVisitor.Unit.TopExpression = expr.Accept(conversionVisitor) as AstNode;
+
+			conversionVisitor.Unit.FileName = fileName;
+			var conditionals = new List<string>();
+			foreach (var settings in compilerSettings.ConditionalSymbols) {
+				if (top.Conditionals.ContainsKey(settings) && !top.Conditionals [settings])
+					continue;
+				conditionals.Add(settings);
+			}
+			foreach (var kv in top.Conditionals) {
+				if (!kv.Value || compilerSettings.ConditionalSymbols.Contains(kv.Key))
+					continue;
+				conditionals.Add(kv.Key);
+			}
+			conversionVisitor.Unit.ConditionalSymbols = conditionals;
+			return conversionVisitor.Unit;
+		}
+
+		public CompilerSettings CompilerSettings {
+			get { return compilerSettings; }
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				compilerSettings = value;
+			}
+		}
+
+		/// <summary>
+		/// Callback that gets called with the Mono.CSharp syntax tree whenever some code is parsed.
+		/// </summary>
+		public Action<CompilerCompilationUnit> CompilationUnitCallback {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Specifies whether to run the parser in a special mode for generating the type system.
+		/// If this property is true, the syntax tree will only contain nodes relevant for the
+		/// <see cref="SyntaxTree.ToTypeSystem()"/> call and might be missing other nodes (e.g. method bodies).
+		/// The default is false.
+		/// </summary>
+		public bool GenerateTypeSystemMode {
+			get;
+			set;
+		}
+
+		TextLocation initialLocation = new TextLocation(1, 1);
+
+		/// <summary>
+		/// Specifies the text location where parsing starts.
+		/// This property can be used when parsing a part of a file to make the locations of the AstNodes
+		/// refer to the position in the whole file.
+		/// The default is (1,1).
+		/// </summary>
+		public TextLocation InitialLocation {
+			get { return initialLocation; }
+			set { initialLocation = value; }
+		}
+
+		internal static object parseLock = new object();
+
+		/// <summary>
+		/// Parses a C# code file.
+		/// </summary>
+		/// <param name="stream">The stream containing the source code to parse.</param>
+		/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
+		/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
+		/// <returns>Returns the syntax tree.</returns>
+		public SyntaxTree Parse(Stream stream, string fileName = "")
+		{
+			return Parse(new StreamReader(stream), fileName);
+		}
+
+		/// <summary>
+		/// Parses a C# code file.
+		/// </summary>
+		/// <param name="program">The source code to parse.</param>
+		/// <param name="fileName">The file name. Used to identify the file (e.g. when building a type system).
+		/// This can be an arbitrary identifier, NRefactory never tries to access the file on disk.</param>
+		/// <returns>Returns the syntax tree.</returns>
+		public SyntaxTree Parse(ITextSource program, string fileName = "")
+		{
+			return Parse(program, fileName, initialLocation.Line, initialLocation.Column);
+		}
+
+		SyntaxTree Parse(ITextSource program, string fileName, int initialLine, int initialColumn)
+		{
+			lock (parseLock) {
+				errorReportPrinter = new ErrorReportPrinter("");
+				var ctx = new CompilerContext(compilerSettings.ToMono(), errorReportPrinter);
+				ctx.Settings.TabSize = 1;
+				var reader = new SeekableStreamReader(program);
+				var file = new SourceFile(fileName, fileName, 0);
+				Location.Initialize(new List<SourceFile>(new [] { file }));
+				var module = new ModuleContainer(ctx);
+				var session = new ParserSession();
+				session.LocationsBag = new LocationsBag();
+				var report = new Report(ctx, errorReportPrinter);
+				var parser = Driver.Parse(reader, file, module, session, report, initialLine - 1, initialColumn - 1);
+				var top = new CompilerCompilationUnit {
+					ModuleCompiled = module,
+					LocationsBag = session.LocationsBag,
+					SpecialsBag = parser.Lexer.sbag,
+					Conditionals = parser.Lexer.SourceFile.Conditionals
+				};
+				var unit = Parse(top, fileName);
+				unit.Errors.AddRange(errorReportPrinter.Errors);
+				CompilerCallableEntryPoint.Reset();
+				return unit;
+			}
+		}
+
+		public IEnumerable<EntityDeclaration> ParseTypeMembers(string code)
+		{
+			return ParseTypeMembers(code, initialLocation.Line, initialLocation.Column);
+		}
+
+		IEnumerable<EntityDeclaration> ParseTypeMembers(string code, int initialLine, int initialColumn)
+		{
+			const string prefix = "unsafe partial class MyClass { ";
+			var syntaxTree = Parse(new StringTextSource(prefix + code + "}"), "parsed.cs", initialLine, initialColumn - prefix.Length);
+			if (syntaxTree == null)
+				return Enumerable.Empty<EntityDeclaration>();
+			var td = syntaxTree.FirstChild as TypeDeclaration;
+			if (td != null) {
+				var members = td.Members.ToArray();
+				// detach members from parent
+				foreach (var m in members)
+					m.Remove();
+				return members;
+			}
+			return Enumerable.Empty<EntityDeclaration>();
+		}
+
+		public IEnumerable<Statement> ParseStatements(string code)
+		{
+			return ParseStatements(code, initialLocation.Line, initialLocation.Column);
+		}
+
+		IEnumerable<Statement> ParseStatements(string code, int initialLine, int initialColumn)
+		{
+			// the dummy method is async so that 'await' expressions are parsed as expected
+			const string prefix = "async void M() { ";
+			var members = ParseTypeMembers(prefix + code + "}", initialLine, initialColumn - prefix.Length);
+			var method = members.FirstOrDefault() as MethodDeclaration;
+			if (method != null && method.Body != null) {
+				var statements = method.Body.Statements.ToArray();
+				// detach statements from parent
+				foreach (var st in statements)
+					st.Remove();
+				return statements;
+			}
+			return Enumerable.Empty<Statement>();
+		}
+
+		public AstType ParseTypeReference(string code)
+		{
+			var members = ParseTypeMembers(code + " a;");
+			var field = members.FirstOrDefault() as FieldDeclaration;
+			if (field != null) {
+				AstType type = field.ReturnType;
+				type.Remove();
+				return type;
+			}
+			return AstType.Null;
+		}
+
+		public Expression ParseExpression(string code)
+		{
+			const string prefix = "tmp = ";
+			var statements = ParseStatements(prefix + code + ";", initialLocation.Line, initialLocation.Column - prefix.Length);
+			var es = statements.FirstOrDefault() as ExpressionStatement;
+			if (es != null) {
+				var ae = es.Expression as AssignmentExpression;
+				if (ae != null) {
+					Expression expr = ae.Right;
+					expr.Remove();
+					return expr;
+				}
+			}
+			return Expression.Null;
+		}
+		/*
+		/// <summary>
+		/// Parses a file snippet; guessing what the code snippet represents (whole file, type members, block, type reference, expression).
+		/// </summary>
+		public AstNode ParseSnippet (string code)
+		{
+			// TODO: add support for parsing a part of a file
+			throw new NotImplementedException ();
+		}
+		 */
+		public DocumentationReference ParseDocumentationReference(string cref)
+		{
+			// see Mono.CSharp.DocumentationBuilder.HandleXrefCommon
+			if (cref == null)
+				throw new ArgumentNullException("cref");
+			
+			// Additional symbols for < and > are allowed for easier XML typing
+			cref = cref.Replace('{', '<').Replace('}', '>');
+			
+			lock (parseLock) {
+				errorReportPrinter = new ErrorReportPrinter("");
+				var ctx = new CompilerContext(compilerSettings.ToMono(), errorReportPrinter);
+				ctx.Settings.TabSize = 1;
+				var reader = new SeekableStreamReader(new StringTextSource(cref));
+				var file = new SourceFile("", "", 0);
+				Location.Initialize(new List<SourceFile>(new [] { file }));
+				var module = new ModuleContainer(ctx);
+				module.DocumentationBuilder = new DocumentationBuilder(module);
+				var source_file = new CompilationSourceFile(module);
+				var report = new Report(ctx, errorReportPrinter);
+				var session = new ParserSession();
+				session.LocationsBag = new LocationsBag();
+				var parser = new Mono.CSharp.CSharpParser(reader, source_file, report, session);
+				parser.Lexer.Line += initialLocation.Line - 1;
+				parser.Lexer.Column += initialLocation.Column - 1;
+				parser.Lexer.putback_char = Tokenizer.DocumentationXref;
+				parser.Lexer.parsing_generic_declaration_doc = true;
+				parser.parse();
+				if (report.Errors > 0) {
+//					Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
+//					                mc.GetSignatureForError (), cref);
+				}
+				
+				var conversionVisitor = new ConversionVisitor(false, session.LocationsBag);
+				var docRef = conversionVisitor.ConvertXmlDoc(module.DocumentationBuilder);
+				CompilerCallableEntryPoint.Reset();
+				return docRef;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/CompilerSettings.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/CompilerSettings.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/CompilerSettings.cs	(revision 11807)
@@ -0,0 +1,151 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// C# compiler settings.
+	/// </summary>
+	[Serializable]
+	public class CompilerSettings : AbstractFreezable
+	{
+		protected override void FreezeInternal()
+		{
+			conditionalSymbols = FreezableHelper.FreezeList(conditionalSymbols);
+			specificWarningsAsErrors = FreezableHelper.FreezeList(specificWarningsAsErrors);
+			disabledWarnings = FreezableHelper.FreezeList(disabledWarnings);
+			base.FreezeInternal();
+		}
+		
+		/// <summary>
+		/// Creates a new CompilerSettings instance.
+		/// </summary>
+		public CompilerSettings()
+		{
+		}
+		
+		bool allowUnsafeBlocks = true;
+		
+		/// <summary>
+		/// Gets/Sets whether <c>unsafe</c> code is allowed.
+		/// The default is <c>true</c>. If set to false, parsing unsafe code will result in parser errors.
+		/// </summary>
+		public bool AllowUnsafeBlocks {
+			get { return allowUnsafeBlocks; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				allowUnsafeBlocks = value;
+			}
+		}
+		
+		bool checkForOverflow;
+		
+		/// <summary>
+		/// Gets/Sets whether overflow checking is enabled.
+		/// The default is <c>false</c>. This setting effects semantic analysis.
+		/// </summary>
+		public bool CheckForOverflow {
+			get { return checkForOverflow; }
+			set { checkForOverflow = value; }
+		}
+		
+		Version languageVersion = new Version((int)Mono.CSharp.LanguageVersion.Default, 0);
+		
+		/// <summary>
+		/// Gets/Sets the language version used by the parser.
+		/// Using language constructs newer than the supplied version will result in parser errors.
+		/// </summary>
+		public Version LanguageVersion {
+			get { return languageVersion; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				if (value == null)
+					throw new ArgumentNullException();
+				languageVersion = value;
+			}
+		}
+		
+		IList<string> conditionalSymbols = new List<string>();
+		
+		/// <summary>
+		/// Gets/Sets the list of conditional symbols that are defined project-wide.
+		/// </summary>
+		public IList<string> ConditionalSymbols {
+			get { return conditionalSymbols; }
+		}
+		
+		bool treatWarningsAsErrors;
+		
+		public bool TreatWarningsAsErrors {
+			get { return treatWarningsAsErrors; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				treatWarningsAsErrors = value;
+			}
+		}
+		
+		IList<int> specificWarningsAsErrors = new List<int>();
+		
+		/// <summary>
+		/// Allows treating specific warnings as errors without setting <see cref="TreatWarningsAsErrors"/> to true.
+		/// </summary>
+		public IList<int> SpecificWarningsAsErrors {
+			get { return specificWarningsAsErrors; }
+		}
+		
+		int warningLevel = 4;
+		
+		public int WarningLevel {
+			get { return warningLevel; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				warningLevel = value;
+			}
+		}
+		
+		IList<int> disabledWarnings = new List<int>();
+		
+		/// <summary>
+		/// Disables the specified warnings.
+		/// </summary>
+		public IList<int> DisabledWarnings {
+			get { return disabledWarnings; }
+		}
+		
+		internal Mono.CSharp.CompilerSettings ToMono()
+		{
+			var s = new Mono.CSharp.CompilerSettings();
+			s.Unsafe = allowUnsafeBlocks;
+			s.Checked = checkForOverflow;
+			s.Version = (Mono.CSharp.LanguageVersion)languageVersion.Major;
+			s.WarningsAreErrors = treatWarningsAsErrors;
+			s.WarningLevel = warningLevel;
+			foreach (int code in disabledWarnings)
+				s.SetIgnoreWarning(code);
+			foreach (int code in specificWarningsAsErrors)
+				s.AddWarningAsError(code);
+			foreach (string sym in conditionalSymbols)
+				s.AddConditionalSymbol(sym);
+			return s;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/SeekableStreamReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/SeekableStreamReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/SeekableStreamReader.cs	(revision 11807)
@@ -0,0 +1,103 @@
+//
+// SeekableStreamReader.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Editor;
+using System.IO;
+using System.Text;
+
+namespace Mono.CSharp
+{
+	public class SeekableStreamReader : IDisposable
+	{
+		public const int DefaultReadAheadSize = 2048;
+
+		readonly ITextSource textSource;
+
+		int pos;
+
+		static string GetAllText(Stream stream, Encoding encoding) {
+			using (var rdr = new StreamReader(stream, encoding)) {
+				return rdr.ReadToEnd();
+			}
+		}
+
+		public SeekableStreamReader (Stream stream, Encoding encoding, char[] sharedBuffer = null) : this(new StringTextSource(GetAllText(stream, encoding)))
+		{
+		}
+
+		public SeekableStreamReader (ITextSource source)
+		{
+			this.textSource = source;
+		}
+
+
+		public void Dispose ()
+		{
+		}
+		
+		/// <remarks>
+		///   This value corresponds to the current position in a stream of characters.
+		///   The StreamReader hides its manipulation of the underlying byte stream and all
+		///   character set/decoding issues.  Thus, we cannot use this position to guess at
+		///   the corresponding position in the underlying byte stream even though there is
+		///   a correlation between them.
+		/// </remarks>
+		public int Position {
+			get {
+				return pos;
+			}
+			
+			set {
+				pos = value;
+			}
+		}
+
+		public char GetChar (int position)
+		{
+			return textSource.GetCharAt (position);
+		}
+		
+		public char[] ReadChars (int fromPosition, int toPosition)
+		{
+			return textSource.GetText (fromPosition, toPosition - fromPosition).ToCharArray ();
+		}
+		
+		public int Peek ()
+		{
+			if (pos >= textSource.TextLength)
+				return -1;
+			return textSource.GetCharAt (pos);
+		}
+		
+		public int Read ()
+		{
+			if (pos >= textSource.TextLength)
+				return -1;
+			return textSource.GetCharAt (pos++);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/CryptoConvert.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/CryptoConvert.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/CryptoConvert.cs	(revision 11807)
@@ -0,0 +1,754 @@
+//
+// CryptoConvert.cs - Crypto Convertion Routines
+//
+// Author:
+//	Sebastien Pouliot  <sebastien@ximian.com>
+//
+// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
+// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Mono.Security.Cryptography {
+
+#if INSIDE_CORLIB
+	internal
+#else
+	public
+#endif
+	sealed class CryptoConvert {
+
+		private CryptoConvert () 
+		{
+		}
+
+		static private int ToInt32LE (byte [] bytes, int offset)
+		{
+			return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset];
+		}
+
+		static private uint ToUInt32LE (byte [] bytes, int offset)
+		{
+			return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]);
+		}
+
+		static private byte [] GetBytesLE (int val)
+		{
+			return new byte [] { 
+				(byte) (val & 0xff), 
+				(byte) ((val >> 8) & 0xff), 
+				(byte) ((val >> 16) & 0xff), 
+				(byte) ((val >> 24) & 0xff)
+			};
+                }
+
+		static private byte[] Trim (byte[] array) 
+		{
+			for (int i=0; i < array.Length; i++) {
+				if (array [i] != 0x00) {
+					byte[] result = new byte [array.Length - i];
+					Buffer.BlockCopy (array, i, result, 0, result.Length);
+					return result;
+				}
+			}
+			return null;
+		}
+
+		// convert the key from PRIVATEKEYBLOB to RSA
+		// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/security/Security/private_key_blobs.asp
+		// e.g. SNK files, PVK files
+		static public RSA FromCapiPrivateKeyBlob (byte[] blob) 
+		{
+			return FromCapiPrivateKeyBlob (blob, 0);
+		}
+
+		static public RSA FromCapiPrivateKeyBlob (byte[] blob, int offset) 
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			RSAParameters rsap = new RSAParameters ();
+			try {
+				if ((blob [offset]   != 0x07) ||				// PRIVATEKEYBLOB (0x07)
+				    (blob [offset+1] != 0x02) ||				// Version (0x02)
+				    (blob [offset+2] != 0x00) ||				// Reserved (word)
+				    (blob [offset+3] != 0x00) ||
+				    (ToUInt32LE (blob, offset+8) != 0x32415352))	// DWORD magic = RSA2
+					throw new CryptographicException ("Invalid blob header");
+				
+				// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
+				// int algId = ToInt32LE (blob, offset+4);
+
+				// DWORD bitlen
+				int bitLen = ToInt32LE (blob, offset+12);
+
+				// DWORD public exponent
+				byte[] exp = new byte [4];
+				Buffer.BlockCopy (blob, offset+16, exp, 0, 4);
+				Array.Reverse (exp);
+				rsap.Exponent = Trim (exp);
+			
+				int pos = offset+20;
+				// BYTE modulus[rsapubkey.bitlen/8];
+				int byteLen = (bitLen >> 3);
+				rsap.Modulus = new byte [byteLen];
+				Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
+				Array.Reverse (rsap.Modulus);
+				pos += byteLen;
+
+				// BYTE prime1[rsapubkey.bitlen/16];
+				int byteHalfLen = (byteLen >> 1);
+				rsap.P = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen);
+				Array.Reverse (rsap.P);
+				pos += byteHalfLen;
+
+				// BYTE prime2[rsapubkey.bitlen/16];
+				rsap.Q = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen);
+				Array.Reverse (rsap.Q);
+				pos += byteHalfLen;
+
+				// BYTE exponent1[rsapubkey.bitlen/16];
+				rsap.DP = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen);
+				Array.Reverse (rsap.DP);
+				pos += byteHalfLen;
+
+				// BYTE exponent2[rsapubkey.bitlen/16];
+				rsap.DQ = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen);
+				Array.Reverse (rsap.DQ);
+				pos += byteHalfLen;
+
+				// BYTE coefficient[rsapubkey.bitlen/16];
+				rsap.InverseQ = new byte [byteHalfLen];
+				Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen);
+				Array.Reverse (rsap.InverseQ);
+				pos += byteHalfLen;
+
+				// ok, this is hackish but CryptoAPI support it so...
+				// note: only works because CRT is used by default
+				// http://bugzilla.ximian.com/show_bug.cgi?id=57941
+				rsap.D = new byte [byteLen]; // must be allocated
+				if (pos + byteLen + offset <= blob.Length) {
+					// BYTE privateExponent[rsapubkey.bitlen/8];
+					Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen);
+					Array.Reverse (rsap.D);
+				}
+			}
+			catch (Exception e) {
+				throw new CryptographicException ("Invalid blob.", e);
+			}
+
+#if NET_2_1
+			RSA rsa = RSA.Create ();
+			rsa.ImportParameters (rsap);
+#else
+			RSA rsa = null;
+			try {
+				rsa = RSA.Create ();
+				rsa.ImportParameters (rsap);
+			}
+			catch (CryptographicException ce) {
+				// this may cause problem when this code is run under
+				// the SYSTEM identity on Windows (e.g. ASP.NET). See
+				// http://bugzilla.ximian.com/show_bug.cgi?id=77559
+				try {
+					CspParameters csp = new CspParameters ();
+					csp.Flags = CspProviderFlags.UseMachineKeyStore;
+					rsa = new RSACryptoServiceProvider (csp);
+					rsa.ImportParameters (rsap);
+				}
+				catch {
+					// rethrow original, not the later, exception if this fails
+					throw ce;
+				}
+			}
+#endif
+			return rsa;
+		}
+
+		static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob)
+		{
+			return FromCapiPrivateKeyBlobDSA (blob, 0);
+		}
+
+		static public DSA FromCapiPrivateKeyBlobDSA (byte[] blob, int offset)
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			DSAParameters dsap = new DSAParameters ();
+			try {
+				if ((blob [offset] != 0x07) ||				// PRIVATEKEYBLOB (0x07)
+				    (blob [offset + 1] != 0x02) ||			// Version (0x02)
+				    (blob [offset + 2] != 0x00) ||			// Reserved (word)
+				    (blob [offset + 3] != 0x00) ||
+				    (ToUInt32LE (blob, offset + 8) != 0x32535344))	// DWORD magic
+					throw new CryptographicException ("Invalid blob header");
+
+				int bitlen = ToInt32LE (blob, offset + 12);
+				int bytelen = bitlen >> 3;
+				int pos = offset + 16;
+
+				dsap.P = new byte [bytelen];
+				Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
+				Array.Reverse (dsap.P);
+				pos += bytelen;
+
+				dsap.Q = new byte [20];
+				Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
+				Array.Reverse (dsap.Q);
+				pos += 20;
+
+				dsap.G = new byte [bytelen];
+				Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
+				Array.Reverse (dsap.G);
+				pos += bytelen;
+
+				dsap.X = new byte [20];
+				Buffer.BlockCopy (blob, pos, dsap.X, 0, 20);
+				Array.Reverse (dsap.X);
+				pos += 20;
+
+				dsap.Counter = ToInt32LE (blob, pos);
+				pos += 4;
+
+				dsap.Seed = new byte [20];
+				Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
+				Array.Reverse (dsap.Seed);
+				pos += 20;
+			}
+			catch (Exception e) {
+				throw new CryptographicException ("Invalid blob.", e);
+			}
+
+#if NET_2_1
+			DSA dsa = (DSA)DSA.Create ();
+			dsa.ImportParameters (dsap);
+#else
+			DSA dsa = null;
+			try {
+				dsa = (DSA)DSA.Create ();
+				dsa.ImportParameters (dsap);
+			}
+			catch (CryptographicException ce) {
+				// this may cause problem when this code is run under
+				// the SYSTEM identity on Windows (e.g. ASP.NET). See
+				// http://bugzilla.ximian.com/show_bug.cgi?id=77559
+				try {
+					CspParameters csp = new CspParameters ();
+					csp.Flags = CspProviderFlags.UseMachineKeyStore;
+					dsa = new DSACryptoServiceProvider (csp);
+					dsa.ImportParameters (dsap);
+				}
+				catch {
+					// rethrow original, not the later, exception if this fails
+					throw ce;
+				}
+			}
+#endif
+			return dsa;
+		}
+
+		static public byte[] ToCapiPrivateKeyBlob (RSA rsa) 
+		{
+			RSAParameters p = rsa.ExportParameters (true);
+			int keyLength = p.Modulus.Length; // in bytes
+			byte[] blob = new byte [20 + (keyLength << 2) + (keyLength >> 1)];
+
+			blob [0] = 0x07;	// Type - PRIVATEKEYBLOB (0x07)
+			blob [1] = 0x02;	// Version - Always CUR_BLOB_VERSION (0x02)
+			// [2], [3]		// RESERVED - Always 0
+			blob [5] = 0x24;	// ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
+			blob [8] = 0x52;	// Magic - RSA2 (ASCII in hex)
+			blob [9] = 0x53;
+			blob [10] = 0x41;
+			blob [11] = 0x32;
+
+			byte[] bitlen = GetBytesLE (keyLength << 3);
+			blob [12] = bitlen [0];	// bitlen
+			blob [13] = bitlen [1];	
+			blob [14] = bitlen [2];	
+			blob [15] = bitlen [3];
+
+			// public exponent (DWORD)
+			int pos = 16;
+			int n = p.Exponent.Length;
+			while (n > 0)
+				blob [pos++] = p.Exponent [--n];
+			// modulus
+			pos = 20;
+			byte[] part = p.Modulus;
+			int len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+			// private key
+			part = p.P;
+			len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+
+			part = p.Q;
+			len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+
+			part = p.DP;
+			len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+
+			part = p.DQ;
+			len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+
+			part = p.InverseQ;
+			len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+
+			part = p.D;
+			len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+
+			return blob;
+		}
+
+		static public byte[] ToCapiPrivateKeyBlob (DSA dsa)
+		{
+			DSAParameters p = dsa.ExportParameters (true);
+			int keyLength = p.P.Length; // in bytes
+
+			// header + P + Q + G + X + count + seed
+			byte[] blob = new byte [16 + keyLength + 20 + keyLength + 20 + 4 + 20];
+
+			blob [0] = 0x07;	// Type - PRIVATEKEYBLOB (0x07)
+			blob [1] = 0x02;	// Version - Always CUR_BLOB_VERSION (0x02)
+			// [2], [3]		// RESERVED - Always 0
+			blob [5] = 0x22;	// ALGID
+			blob [8] = 0x44;	// Magic
+			blob [9] = 0x53;
+			blob [10] = 0x53;
+			blob [11] = 0x32;
+
+			byte[] bitlen = GetBytesLE (keyLength << 3);
+			blob [12] = bitlen [0];
+			blob [13] = bitlen [1];
+			blob [14] = bitlen [2];
+			blob [15] = bitlen [3];
+
+			int pos = 16;
+			byte[] part = p.P;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, keyLength);
+			pos += keyLength;
+
+			part = p.Q;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, 20);
+			pos += 20;
+
+			part = p.G;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, keyLength);
+			pos += keyLength;
+
+			part = p.X;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, 20);
+			pos += 20;
+
+			Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
+			pos += 4;
+
+			part = p.Seed;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, 20);
+
+			return blob;
+		}
+
+		static public RSA FromCapiPublicKeyBlob (byte[] blob) 
+		{
+			return FromCapiPublicKeyBlob (blob, 0);
+		}
+
+		static public RSA FromCapiPublicKeyBlob (byte[] blob, int offset) 
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			try {
+				if ((blob [offset]   != 0x06) ||				// PUBLICKEYBLOB (0x06)
+				    (blob [offset+1] != 0x02) ||				// Version (0x02)
+				    (blob [offset+2] != 0x00) ||				// Reserved (word)
+				    (blob [offset+3] != 0x00) || 
+				    (ToUInt32LE (blob, offset+8) != 0x31415352))	// DWORD magic = RSA1
+					throw new CryptographicException ("Invalid blob header");
+
+				// ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...)
+				// int algId = ToInt32LE (blob, offset+4);
+
+				// DWORD bitlen
+				int bitLen = ToInt32LE (blob, offset+12);
+
+				// DWORD public exponent
+				RSAParameters rsap = new RSAParameters ();
+				rsap.Exponent = new byte [3];
+				rsap.Exponent [0] = blob [offset+18];
+				rsap.Exponent [1] = blob [offset+17];
+				rsap.Exponent [2] = blob [offset+16];
+			
+				int pos = offset+20;
+				// BYTE modulus[rsapubkey.bitlen/8];
+				int byteLen = (bitLen >> 3);
+				rsap.Modulus = new byte [byteLen];
+				Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen);
+				Array.Reverse (rsap.Modulus);
+#if NET_2_1
+				RSA rsa = RSA.Create ();
+				rsa.ImportParameters (rsap);
+#else
+				RSA rsa = null;
+				try {
+					rsa = RSA.Create ();
+					rsa.ImportParameters (rsap);
+				}
+				catch (CryptographicException) {
+					// this may cause problem when this code is run under
+					// the SYSTEM identity on Windows (e.g. ASP.NET). See
+					// http://bugzilla.ximian.com/show_bug.cgi?id=77559
+					CspParameters csp = new CspParameters ();
+					csp.Flags = CspProviderFlags.UseMachineKeyStore;
+					rsa = new RSACryptoServiceProvider (csp);
+					rsa.ImportParameters (rsap);
+				}
+#endif
+				return rsa;
+			}
+			catch (Exception e) {
+				throw new CryptographicException ("Invalid blob.", e);
+			}
+		}
+
+		static public DSA FromCapiPublicKeyBlobDSA (byte[] blob)
+		{
+			return FromCapiPublicKeyBlobDSA (blob, 0);
+		}
+
+		static public DSA FromCapiPublicKeyBlobDSA (byte[] blob, int offset)
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			try {
+				if ((blob [offset] != 0x06) ||				// PUBLICKEYBLOB (0x06)
+				    (blob [offset + 1] != 0x02) ||			// Version (0x02)
+				    (blob [offset + 2] != 0x00) ||			// Reserved (word)
+				    (blob [offset + 3] != 0x00) ||
+				    (ToUInt32LE (blob, offset + 8) != 0x31535344))	// DWORD magic
+					throw new CryptographicException ("Invalid blob header");
+
+				int bitlen = ToInt32LE (blob, offset + 12);
+				DSAParameters dsap = new DSAParameters ();
+				int bytelen = bitlen >> 3;
+				int pos = offset + 16;
+
+				dsap.P = new byte [bytelen];
+				Buffer.BlockCopy (blob, pos, dsap.P, 0, bytelen);
+				Array.Reverse (dsap.P);
+				pos += bytelen;
+
+				dsap.Q = new byte [20];
+				Buffer.BlockCopy (blob, pos, dsap.Q, 0, 20);
+				Array.Reverse (dsap.Q);
+				pos += 20;
+
+				dsap.G = new byte [bytelen];
+				Buffer.BlockCopy (blob, pos, dsap.G, 0, bytelen);
+				Array.Reverse (dsap.G);
+				pos += bytelen;
+
+				dsap.Y = new byte [bytelen];
+				Buffer.BlockCopy (blob, pos, dsap.Y, 0, bytelen);
+				Array.Reverse (dsap.Y);
+				pos += bytelen;
+
+				dsap.Counter = ToInt32LE (blob, pos);
+				pos += 4;
+
+				dsap.Seed = new byte [20];
+				Buffer.BlockCopy (blob, pos, dsap.Seed, 0, 20);
+				Array.Reverse (dsap.Seed);
+				pos += 20;
+
+				DSA dsa = (DSA)DSA.Create ();
+				dsa.ImportParameters (dsap);
+				return dsa;
+			}
+			catch (Exception e) {
+				throw new CryptographicException ("Invalid blob.", e);
+			}
+		}
+
+		static public byte[] ToCapiPublicKeyBlob (RSA rsa) 
+		{
+			RSAParameters p = rsa.ExportParameters (false);
+			int keyLength = p.Modulus.Length; // in bytes
+			byte[] blob = new byte [20 + keyLength];
+
+			blob [0] = 0x06;	// Type - PUBLICKEYBLOB (0x06)
+			blob [1] = 0x02;	// Version - Always CUR_BLOB_VERSION (0x02)
+			// [2], [3]		// RESERVED - Always 0
+			blob [5] = 0x24;	// ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
+			blob [8] = 0x52;	// Magic - RSA1 (ASCII in hex)
+			blob [9] = 0x53;
+			blob [10] = 0x41;
+			blob [11] = 0x31;
+
+			byte[] bitlen = GetBytesLE (keyLength << 3);
+			blob [12] = bitlen [0];	// bitlen
+			blob [13] = bitlen [1];	
+			blob [14] = bitlen [2];	
+			blob [15] = bitlen [3];
+
+			// public exponent (DWORD)
+			int pos = 16;
+			int n = p.Exponent.Length;
+			while (n > 0)
+				blob [pos++] = p.Exponent [--n];
+			// modulus
+			pos = 20;
+			byte[] part = p.Modulus;
+			int len = part.Length;
+			Array.Reverse (part, 0, len);
+			Buffer.BlockCopy (part, 0, blob, pos, len);
+			pos += len;
+			return blob;
+		}
+
+		static public byte[] ToCapiPublicKeyBlob (DSA dsa)
+		{
+			DSAParameters p = dsa.ExportParameters (false);
+			int keyLength = p.P.Length; // in bytes
+
+			// header + P + Q + G + Y + count + seed
+			byte[] blob = new byte [16 + keyLength + 20 + keyLength + keyLength + 4 + 20];
+
+			blob [0] = 0x06;	// Type - PUBLICKEYBLOB (0x06)
+			blob [1] = 0x02;	// Version - Always CUR_BLOB_VERSION (0x02)
+			// [2], [3]		// RESERVED - Always 0
+			blob [5] = 0x22;	// ALGID
+			blob [8] = 0x44;	// Magic
+			blob [9] = 0x53;
+			blob [10] = 0x53;
+			blob [11] = 0x31;
+
+			byte[] bitlen = GetBytesLE (keyLength << 3);
+			blob [12] = bitlen [0];
+			blob [13] = bitlen [1];
+			blob [14] = bitlen [2];
+			blob [15] = bitlen [3];
+
+			int pos = 16;
+			byte[] part;
+
+			part = p.P;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, keyLength);
+			pos += keyLength;
+
+			part = p.Q;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, 20);
+			pos += 20;
+
+			part = p.G;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, keyLength);
+			pos += keyLength;
+
+			part = p.Y;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, keyLength);
+			pos += keyLength;
+
+			Buffer.BlockCopy (GetBytesLE (p.Counter), 0, blob, pos, 4);
+			pos += 4;
+
+			part = p.Seed;
+			Array.Reverse (part);
+			Buffer.BlockCopy (part, 0, blob, pos, 20);
+
+			return blob;
+		}
+
+		// PRIVATEKEYBLOB
+		// PUBLICKEYBLOB
+		static public RSA FromCapiKeyBlob (byte[] blob) 
+		{
+			return FromCapiKeyBlob (blob, 0);
+		}
+
+		static public RSA FromCapiKeyBlob (byte[] blob, int offset) 
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			switch (blob [offset]) {
+				case 0x00:
+					// this could be a public key inside an header
+					// like "sn -e" would produce
+					if (blob [offset + 12] == 0x06) {
+						return FromCapiPublicKeyBlob (blob, offset + 12);
+					}
+					break;
+				case 0x06:
+					return FromCapiPublicKeyBlob (blob, offset);
+				case 0x07:
+					return FromCapiPrivateKeyBlob (blob, offset);
+			}
+			throw new CryptographicException ("Unknown blob format.");
+		}
+
+		static public DSA FromCapiKeyBlobDSA (byte[] blob)
+		{
+			return FromCapiKeyBlobDSA (blob, 0);
+		}
+
+		static public DSA FromCapiKeyBlobDSA (byte[] blob, int offset)
+		{
+			if (blob == null)
+				throw new ArgumentNullException ("blob");
+			if (offset >= blob.Length)
+				throw new ArgumentException ("blob is too small.");
+
+			switch (blob [offset]) {
+				case 0x06:
+					return FromCapiPublicKeyBlobDSA (blob, offset);
+				case 0x07:
+					return FromCapiPrivateKeyBlobDSA (blob, offset);
+			}
+			throw new CryptographicException ("Unknown blob format.");
+		}
+
+		static public byte[] ToCapiKeyBlob (AsymmetricAlgorithm keypair, bool includePrivateKey) 
+		{
+			if (keypair == null)
+				throw new ArgumentNullException ("keypair");
+
+			// check between RSA and DSA (and potentially others like DH)
+			if (keypair is RSA)
+				return ToCapiKeyBlob ((RSA)keypair, includePrivateKey);
+			else if (keypair is DSA)
+				return ToCapiKeyBlob ((DSA)keypair, includePrivateKey);
+			else
+				return null;	// TODO
+		}
+
+		static public byte[] ToCapiKeyBlob (RSA rsa, bool includePrivateKey) 
+		{
+			if (rsa == null)
+				throw new ArgumentNullException ("rsa");
+
+			if (includePrivateKey)
+				return ToCapiPrivateKeyBlob (rsa);
+			else
+				return ToCapiPublicKeyBlob (rsa);
+		}
+
+		static public byte[] ToCapiKeyBlob (DSA dsa, bool includePrivateKey)
+		{
+			if (dsa == null)
+				throw new ArgumentNullException ("dsa");
+
+			if (includePrivateKey)
+				return ToCapiPrivateKeyBlob (dsa);
+			else
+				return ToCapiPublicKeyBlob (dsa);
+		}
+
+		static public string ToHex (byte[] input) 
+		{
+			if (input == null)
+				return null;
+
+			StringBuilder sb = new StringBuilder (input.Length * 2);
+			foreach (byte b in input) {
+				sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
+			}
+			return sb.ToString ();
+		}
+
+		static private byte FromHexChar (char c) 
+		{
+			if ((c >= 'a') && (c <= 'f'))
+				return (byte) (c - 'a' + 10);
+			if ((c >= 'A') && (c <= 'F'))
+				return (byte) (c - 'A' + 10);
+			if ((c >= '0') && (c <= '9'))
+				return (byte) (c - '0');
+			throw new ArgumentException ("invalid hex char");
+		}
+
+		static public byte[] FromHex (string hex) 
+		{
+			if (hex == null)
+				return null;
+			if ((hex.Length & 0x1) == 0x1)
+				throw new ArgumentException ("Length must be a multiple of 2");
+
+			byte[] result = new byte [hex.Length >> 1];
+			int n = 0;
+			int i = 0;
+			while (n < result.Length) {
+				result [n] = (byte) (FromHexChar (hex [i++]) << 4);
+				result [n++] += FromHexChar (hex [i++]);
+			}
+			return result;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolFile.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolFile.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolFile.cs	(revision 11807)
@@ -0,0 +1,637 @@
+//
+// MonoSymbolFile.cs
+//
+// Authors:
+//   Martin Baulig (martin@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// (C) 2003 Ximian, Inc.  http://www.ximian.com
+// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
+//
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Collections.Generic;
+using System.IO;
+	
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class MonoSymbolFileException : Exception
+	{
+		public MonoSymbolFileException ()
+			: base ()
+		{ }
+
+		public MonoSymbolFileException (string message, params object[] args)
+			: base (String.Format (message, args))
+		{
+		}
+
+		public MonoSymbolFileException (string message, Exception innerException)
+			: base (message, innerException)
+		{
+		}
+	}
+
+	sealed class MyBinaryWriter : BinaryWriter
+	{
+		public MyBinaryWriter (Stream stream)
+			: base (stream)
+		{ }
+
+		public void WriteLeb128 (int value)
+		{
+			base.Write7BitEncodedInt (value);
+		}
+	}
+
+	internal class MyBinaryReader : BinaryReader
+	{
+		public MyBinaryReader (Stream stream)
+			: base (stream)
+		{ }
+
+		public int ReadLeb128 ()
+		{
+			return base.Read7BitEncodedInt ();
+		}
+
+		public string ReadString (int offset)
+		{
+			long old_pos = BaseStream.Position;
+			BaseStream.Position = offset;
+
+			string text = ReadString ();
+
+			BaseStream.Position = old_pos;
+			return text;
+		}
+	}
+
+	public interface ISourceFile
+	{
+		SourceFileEntry Entry {
+			get;
+		}
+	}
+
+	public interface ICompileUnit
+	{
+		CompileUnitEntry Entry {
+			get;
+		}
+	}
+
+	public interface IMethodDef
+	{
+		string Name {
+			get;
+		}
+
+		int Token {
+			get;
+		}
+	}
+
+	public class MonoSymbolFile : IDisposable
+	{
+		List<MethodEntry> methods = new List<MethodEntry> ();
+		List<SourceFileEntry> sources = new List<SourceFileEntry> ();
+		List<CompileUnitEntry> comp_units = new List<CompileUnitEntry> ();
+		Dictionary<int, AnonymousScopeEntry> anonymous_scopes;
+
+		OffsetTable ot;
+		int last_type_index;
+		int last_method_index;
+		int last_namespace_index;
+
+		public readonly int MajorVersion = OffsetTable.MajorVersion;
+		public readonly int MinorVersion = OffsetTable.MinorVersion;
+
+		public int NumLineNumbers;
+
+		public MonoSymbolFile ()
+		{
+			ot = new OffsetTable ();
+		}
+
+		public int AddSource (SourceFileEntry source)
+		{
+			sources.Add (source);
+			return sources.Count;
+		}
+
+		public int AddCompileUnit (CompileUnitEntry entry)
+		{
+			comp_units.Add (entry);
+			return comp_units.Count;
+		}
+
+		public void AddMethod (MethodEntry entry)
+		{
+			methods.Add (entry);
+		}
+
+		public MethodEntry DefineMethod (CompileUnitEntry comp_unit, int token,
+						 ScopeVariable[] scope_vars, LocalVariableEntry[] locals,
+						 LineNumberEntry[] lines, CodeBlockEntry[] code_blocks,
+						 string real_name, MethodEntry.Flags flags,
+						 int namespace_id)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			MethodEntry method = new MethodEntry (
+				this, comp_unit, token, scope_vars, locals, lines, code_blocks, 
+				real_name, flags, namespace_id);
+			AddMethod (method);
+			return method;
+		}
+
+		internal void DefineAnonymousScope (int id)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			if (anonymous_scopes == null)
+				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>  ();
+
+			anonymous_scopes.Add (id, new AnonymousScopeEntry (id));
+		}
+
+		internal void DefineCapturedVariable (int scope_id, string name, string captured_name,
+						      CapturedVariable.CapturedKind kind)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			AnonymousScopeEntry scope = anonymous_scopes [scope_id];
+			scope.AddCapturedVariable (name, captured_name, kind);
+		}
+
+		internal void DefineCapturedScope (int scope_id, int id, string captured_name)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			AnonymousScopeEntry scope = anonymous_scopes [scope_id];
+			scope.AddCapturedScope (id, captured_name);
+		}
+
+		internal int GetNextTypeIndex ()
+		{
+			return ++last_type_index;
+		}
+
+		internal int GetNextMethodIndex ()
+		{
+			return ++last_method_index;
+		}
+
+		internal int GetNextNamespaceIndex ()
+		{
+			return ++last_namespace_index;
+		}
+		
+		void Write (MyBinaryWriter bw, Guid guid)
+		{
+			// Magic number and file version.
+			bw.Write (OffsetTable.Magic);
+			bw.Write (MajorVersion);
+			bw.Write (MinorVersion);
+
+			bw.Write (guid.ToByteArray ());
+
+			//
+			// Offsets of file sections; we must write this after we're done
+			// writing the whole file, so we just reserve the space for it here.
+			//
+			long offset_table_offset = bw.BaseStream.Position;
+			ot.Write (bw, MajorVersion, MinorVersion);
+
+			//
+			// Sort the methods according to their tokens and update their index.
+			//
+			methods.Sort ();
+			for (int i = 0; i < methods.Count; i++)
+				methods [i].Index = i + 1;
+
+			//
+			// Write data sections.
+			//
+			ot.DataSectionOffset = (int) bw.BaseStream.Position;
+			foreach (SourceFileEntry source in sources)
+				source.WriteData (bw);
+			foreach (CompileUnitEntry comp_unit in comp_units)
+				comp_unit.WriteData (bw);
+			foreach (MethodEntry method in methods)
+				method.WriteData (this, bw);
+			ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset;
+
+			//
+			// Write the method index table.
+			//
+			ot.MethodTableOffset = (int) bw.BaseStream.Position;
+			for (int i = 0; i < methods.Count; i++) {
+				MethodEntry entry = methods [i];
+				entry.Write (bw);
+			}
+			ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset;
+
+			//
+			// Write source table.
+			//
+			ot.SourceTableOffset = (int) bw.BaseStream.Position;
+			for (int i = 0; i < sources.Count; i++) {
+				SourceFileEntry source = sources [i];
+				source.Write (bw);
+			}
+			ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset;
+
+			//
+			// Write compilation unit table.
+			//
+			ot.CompileUnitTableOffset = (int) bw.BaseStream.Position;
+			for (int i = 0; i < comp_units.Count; i++) {
+				CompileUnitEntry unit = comp_units [i];
+				unit.Write (bw);
+			}
+			ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset;
+
+			//
+			// Write anonymous scope table.
+			//
+			ot.AnonymousScopeCount = anonymous_scopes != null ? anonymous_scopes.Count : 0;
+			ot.AnonymousScopeTableOffset = (int) bw.BaseStream.Position;
+			if (anonymous_scopes != null) {
+				foreach (AnonymousScopeEntry scope in anonymous_scopes.Values)
+					scope.Write (bw);
+			}
+			ot.AnonymousScopeTableSize = (int) bw.BaseStream.Position - ot.AnonymousScopeTableOffset;
+
+			//
+			// Fixup offset table.
+			//
+			ot.TypeCount = last_type_index;
+			ot.MethodCount = methods.Count;
+			ot.SourceCount = sources.Count;
+			ot.CompileUnitCount = comp_units.Count;
+
+			//
+			// Write offset table.
+			//
+			ot.TotalFileSize = (int) bw.BaseStream.Position;
+			bw.Seek ((int) offset_table_offset, SeekOrigin.Begin);
+			ot.Write (bw, MajorVersion, MinorVersion);
+			bw.Seek (0, SeekOrigin.End);
+
+#if false
+			Console.WriteLine ("TOTAL: {0} line numbes, {1} bytes, extended {2} bytes, " +
+					   "{3} methods.", NumLineNumbers, LineNumberSize,
+					   ExtendedLineNumberSize, methods.Count);
+#endif
+		}
+
+		public void CreateSymbolFile (Guid guid, FileStream fs)
+		{
+			if (reader != null)
+				throw new InvalidOperationException ();
+
+			Write (new MyBinaryWriter (fs), guid);
+		}
+
+		MyBinaryReader reader;
+		Dictionary<int, SourceFileEntry> source_file_hash;
+		Dictionary<int, CompileUnitEntry> compile_unit_hash;
+
+		List<MethodEntry> method_list;
+		Dictionary<int, MethodEntry> method_token_hash;
+		Dictionary<string, int> source_name_hash;
+
+		Guid guid;
+
+		MonoSymbolFile (Stream stream)
+		{
+			reader = new MyBinaryReader (stream);
+
+			try {
+				long magic = reader.ReadInt64 ();
+				int major_version = reader.ReadInt32 ();
+				int minor_version = reader.ReadInt32 ();
+
+				if (magic != OffsetTable.Magic)
+					throw new MonoSymbolFileException ("Symbol file is not a valid");
+				if (major_version != OffsetTable.MajorVersion)
+					throw new MonoSymbolFileException (
+						"Symbol file has version {0} but expected {1}", major_version, OffsetTable.MajorVersion);
+				if (minor_version != OffsetTable.MinorVersion)
+					throw new MonoSymbolFileException ("Symbol file has version {0}.{1} but expected {2}.{3}",
+						major_version, minor_version,
+						OffsetTable.MajorVersion, OffsetTable.MinorVersion);
+
+				MajorVersion = major_version;
+				MinorVersion = minor_version;
+				guid = new Guid (reader.ReadBytes (16));
+
+				ot = new OffsetTable (reader, major_version, minor_version);
+			} catch (Exception e) {
+				throw new MonoSymbolFileException ("Cannot read symbol file", e);
+			}
+
+			source_file_hash = new Dictionary<int, SourceFileEntry> ();
+			compile_unit_hash = new Dictionary<int, CompileUnitEntry> ();
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (Assembly assembly)
+		{
+			string filename = assembly.Location;
+			string name = filename + ".mdb";
+
+			Module[] modules = assembly.GetModules ();
+			Guid assembly_guid = modules[0].ModuleVersionId;
+
+			return ReadSymbolFile (name, assembly_guid);
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (string mdbFilename)
+		{
+			return ReadSymbolFile (new FileStream (mdbFilename, FileMode.Open, FileAccess.Read));
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (string mdbFilename, Guid assemblyGuid)
+		{
+			var sf = ReadSymbolFile (mdbFilename);
+			if (assemblyGuid != sf.guid)
+				throw new MonoSymbolFileException ("Symbol file `{0}' does not match assembly", mdbFilename);
+
+			return sf;
+		}
+
+		public static MonoSymbolFile ReadSymbolFile (Stream stream)
+		{
+			return new MonoSymbolFile (stream);
+		}
+
+		public int CompileUnitCount {
+			get { return ot.CompileUnitCount; }
+		}
+
+		public int SourceCount {
+			get { return ot.SourceCount; }
+		}
+
+		public int MethodCount {
+			get { return ot.MethodCount; }
+		}
+
+		public int TypeCount {
+			get { return ot.TypeCount; }
+		}
+
+		public int AnonymousScopeCount {
+			get { return ot.AnonymousScopeCount; }
+		}
+
+		public int NamespaceCount {
+			get { return last_namespace_index; }
+		}
+
+		public Guid Guid {
+			get { return guid; }
+		}
+
+		public OffsetTable OffsetTable {
+			get { return ot; }
+		}
+
+		internal int LineNumberCount = 0;
+		internal int LocalCount = 0;
+		internal int StringSize = 0;
+
+		internal int LineNumberSize = 0;
+		internal int ExtendedLineNumberSize = 0;
+
+		public SourceFileEntry GetSourceFile (int index)
+		{
+			if ((index < 1) || (index > ot.SourceCount))
+				throw new ArgumentException ();
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				SourceFileEntry source;
+				if (source_file_hash.TryGetValue (index, out source))
+					return source;
+
+				long old_pos = reader.BaseStream.Position;
+
+				reader.BaseStream.Position = ot.SourceTableOffset +
+					SourceFileEntry.Size * (index - 1);
+				source = new SourceFileEntry (this, reader);
+				source_file_hash.Add (index, source);
+
+				reader.BaseStream.Position = old_pos;
+				return source;
+			}
+		}
+
+		public SourceFileEntry[] Sources {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				SourceFileEntry[] retval = new SourceFileEntry [SourceCount];
+				for (int i = 0; i < SourceCount; i++)
+					retval [i] = GetSourceFile (i + 1);
+				return retval;
+			}
+		}
+
+		public CompileUnitEntry GetCompileUnit (int index)
+		{
+			if ((index < 1) || (index > ot.CompileUnitCount))
+				throw new ArgumentException ();
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				CompileUnitEntry unit;
+				if (compile_unit_hash.TryGetValue (index, out unit))
+					return unit;
+
+				long old_pos = reader.BaseStream.Position;
+
+				reader.BaseStream.Position = ot.CompileUnitTableOffset +
+					CompileUnitEntry.Size * (index - 1);
+				unit = new CompileUnitEntry (this, reader);
+				compile_unit_hash.Add (index, unit);
+
+				reader.BaseStream.Position = old_pos;
+				return unit;
+			}
+		}
+
+		public CompileUnitEntry[] CompileUnits {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				CompileUnitEntry[] retval = new CompileUnitEntry [CompileUnitCount];
+				for (int i = 0; i < CompileUnitCount; i++)
+					retval [i] = GetCompileUnit (i + 1);
+				return retval;
+			}
+		}
+
+		void read_methods ()
+		{
+			lock (this) {
+				if (method_token_hash != null)
+					return;
+
+				method_token_hash = new Dictionary<int, MethodEntry> ();
+				method_list = new List<MethodEntry> ();
+
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = ot.MethodTableOffset;
+
+				for (int i = 0; i < MethodCount; i++) {
+					MethodEntry entry = new MethodEntry (this, reader, i + 1);
+					method_token_hash.Add (entry.Token, entry);
+					method_list.Add (entry);
+				}
+
+				reader.BaseStream.Position = old_pos;
+			}
+		}
+
+		public MethodEntry GetMethodByToken (int token)
+		{
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				read_methods ();
+				MethodEntry me;
+				method_token_hash.TryGetValue (token, out me);
+				return me;
+			}
+		}
+
+		public MethodEntry GetMethod (int index)
+		{
+			if ((index < 1) || (index > ot.MethodCount))
+				throw new ArgumentException ();
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				read_methods ();
+				return method_list [index - 1];
+			}
+		}
+
+		public MethodEntry[] Methods {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				lock (this) {
+					read_methods ();
+					MethodEntry[] retval = new MethodEntry [MethodCount];
+					method_list.CopyTo (retval, 0);
+					return retval;
+				}
+			}
+		}
+
+		public int FindSource (string file_name)
+		{
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			lock (this) {
+				if (source_name_hash == null) {
+					source_name_hash = new Dictionary<string, int> ();
+
+					for (int i = 0; i < ot.SourceCount; i++) {
+						SourceFileEntry source = GetSourceFile (i + 1);
+						source_name_hash.Add (source.FileName, i);
+					}
+				}
+
+				int value;
+				if (!source_name_hash.TryGetValue (file_name, out value))
+					return -1;
+				return value;
+			}
+		}
+
+		public AnonymousScopeEntry GetAnonymousScope (int id)
+		{
+			if (reader == null)
+				throw new InvalidOperationException ();
+
+			AnonymousScopeEntry scope;
+			lock (this) {
+				if (anonymous_scopes != null) {
+					anonymous_scopes.TryGetValue (id, out scope);
+					return scope;
+				}
+
+				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> ();
+				reader.BaseStream.Position = ot.AnonymousScopeTableOffset;
+				for (int i = 0; i < ot.AnonymousScopeCount; i++) {
+					scope = new AnonymousScopeEntry (reader);
+					anonymous_scopes.Add (scope.ID, scope);
+				}
+
+				return anonymous_scopes [id];
+			}
+		}
+
+		internal MyBinaryReader BinaryReader {
+			get {
+				if (reader == null)
+					throw new InvalidOperationException ();
+
+				return reader;
+			}
+		}
+
+		public void Dispose ()
+		{
+			Dispose (true);
+		}
+
+		protected virtual void Dispose (bool disposing)
+		{
+			if (disposing) {
+				if (reader != null) {
+					reader.Close ();
+					reader = null;
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolTable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolTable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolTable.cs	(revision 11807)
@@ -0,0 +1,1437 @@
+//
+// Mono.CSharp.Debugger/MonoSymbolTable.cs
+//
+// Author:
+//   Martin Baulig (martin@ximian.com)
+//
+// (C) 2002 Ximian, Inc.  http://www.ximian.com
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Security.Cryptography;
+using System.Collections.Generic;
+using System.Text;
+using System.IO;
+
+//
+// Parts which are actually written into the symbol file are marked with
+//
+//         #region This is actually written to the symbol file
+//         #endregion
+//
+// Please do not modify these regions without previously talking to me.
+//
+// All changes to the file format must be synchronized in several places:
+//
+// a) The fields in these regions (and their order) must match the actual
+//    contents of the symbol file.
+//
+//    This helps people to understand the symbol file format without reading
+//    too much source code, ie. you look at the appropriate region and then
+//    you know what's actually in the file.
+//
+//    It is also required to help me enforce b).
+//
+// b) The regions must be kept in sync with the unmanaged code in
+//    mono/metadata/debug-mono-symfile.h
+//
+// When making changes to the file format, you must also increase two version
+// numbers:
+//
+// i)  OffsetTable.Version in this file.
+// ii) MONO_SYMBOL_FILE_VERSION in mono/metadata/debug-mono-symfile.h
+//
+// After doing so, recompile everything, including the debugger.  Symbol files
+// with different versions are incompatible to each other and the debugger and
+// the runtime enfore this, so you need to recompile all your assemblies after
+// changing the file format.
+//
+
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class OffsetTable
+	{
+		public const int  MajorVersion = 50;
+		public const int  MinorVersion = 0;
+		public const long Magic        = 0x45e82623fd7fa614;
+
+		#region This is actually written to the symbol file
+		public int TotalFileSize;
+		public int DataSectionOffset;
+		public int DataSectionSize;
+		public int CompileUnitCount;
+		public int CompileUnitTableOffset;
+		public int CompileUnitTableSize;
+		public int SourceCount;
+		public int SourceTableOffset;
+		public int SourceTableSize;
+		public int MethodCount;
+		public int MethodTableOffset;
+		public int MethodTableSize;
+		public int TypeCount;
+		public int AnonymousScopeCount;
+		public int AnonymousScopeTableOffset;
+		public int AnonymousScopeTableSize;
+
+		[Flags]
+		public enum Flags
+		{
+			IsAspxSource		= 1,
+			WindowsFileNames	= 2
+		}
+
+		public Flags FileFlags;
+
+		public int LineNumberTable_LineBase = LineNumberTable.Default_LineBase;
+		public int LineNumberTable_LineRange = LineNumberTable.Default_LineRange;
+		public int LineNumberTable_OpcodeBase = LineNumberTable.Default_OpcodeBase;
+		#endregion
+
+		internal OffsetTable ()
+		{
+			int platform = (int) Environment.OSVersion.Platform;
+			if ((platform != 4) && (platform != 128))
+				FileFlags |= Flags.WindowsFileNames;
+		}
+
+		internal OffsetTable (BinaryReader reader, int major_version, int minor_version)
+		{
+			TotalFileSize = reader.ReadInt32 ();
+			DataSectionOffset = reader.ReadInt32 ();
+			DataSectionSize = reader.ReadInt32 ();
+			CompileUnitCount = reader.ReadInt32 ();
+			CompileUnitTableOffset = reader.ReadInt32 ();
+			CompileUnitTableSize = reader.ReadInt32 ();
+			SourceCount = reader.ReadInt32 ();
+			SourceTableOffset = reader.ReadInt32 ();
+			SourceTableSize = reader.ReadInt32 ();
+			MethodCount = reader.ReadInt32 ();
+			MethodTableOffset = reader.ReadInt32 ();
+			MethodTableSize = reader.ReadInt32 ();
+			TypeCount = reader.ReadInt32 ();
+
+			AnonymousScopeCount = reader.ReadInt32 ();
+			AnonymousScopeTableOffset = reader.ReadInt32 ();
+			AnonymousScopeTableSize = reader.ReadInt32 ();
+
+			LineNumberTable_LineBase = reader.ReadInt32 ();
+			LineNumberTable_LineRange = reader.ReadInt32 ();
+			LineNumberTable_OpcodeBase = reader.ReadInt32 ();
+
+			FileFlags = (Flags) reader.ReadInt32 ();
+		}
+
+		internal void Write (BinaryWriter bw, int major_version, int minor_version)
+		{
+			bw.Write (TotalFileSize);
+			bw.Write (DataSectionOffset);
+			bw.Write (DataSectionSize);
+			bw.Write (CompileUnitCount);
+			bw.Write (CompileUnitTableOffset);
+			bw.Write (CompileUnitTableSize);
+			bw.Write (SourceCount);
+			bw.Write (SourceTableOffset);
+			bw.Write (SourceTableSize);
+			bw.Write (MethodCount);
+			bw.Write (MethodTableOffset);
+			bw.Write (MethodTableSize);
+			bw.Write (TypeCount);
+
+			bw.Write (AnonymousScopeCount);
+			bw.Write (AnonymousScopeTableOffset);
+			bw.Write (AnonymousScopeTableSize);
+
+			bw.Write (LineNumberTable_LineBase);
+			bw.Write (LineNumberTable_LineRange);
+			bw.Write (LineNumberTable_OpcodeBase);
+
+			bw.Write ((int) FileFlags);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format (
+				"OffsetTable [{0} - {1}:{2} - {3}:{4}:{5} - {6}:{7}:{8} - {9}]",
+				TotalFileSize, DataSectionOffset, DataSectionSize, SourceCount,
+				SourceTableOffset, SourceTableSize, MethodCount, MethodTableOffset,
+				MethodTableSize, TypeCount);
+		}
+	}
+
+	public class LineNumberEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int Row;
+		public int Column;
+		public int EndRow, EndColumn;
+		public readonly int File;
+		public readonly int Offset;
+		public readonly bool IsHidden;	// Obsolete is never used
+		#endregion
+
+		public sealed class LocationComparer : IComparer<LineNumberEntry>
+		{
+			public static readonly LocationComparer Default = new LocationComparer ();
+
+			public int Compare (LineNumberEntry l1, LineNumberEntry l2)
+			{
+				return l1.Row == l2.Row ?
+					l1.Column.CompareTo (l2.Column) :
+					l1.Row.CompareTo (l2.Row);
+			}
+		}
+
+		public static readonly LineNumberEntry Null = new LineNumberEntry (0, 0, 0, 0);
+
+		public LineNumberEntry (int file, int row, int column, int offset)
+			: this (file, row, offset, column, false)
+		{
+		}
+
+		public LineNumberEntry (int file, int row, int offset)
+			: this (file, row, -1, offset, false)
+		{
+		}
+
+		public LineNumberEntry (int file, int row, int column, int offset, bool is_hidden)
+		: this (file, row, column, -1, -1, offset, is_hidden)
+		{
+		}
+
+		public LineNumberEntry (int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden)
+		{
+			this.File = file;
+			this.Row = row;
+			this.Column = column;
+			this.EndRow = end_row;
+			this.EndColumn = end_column;
+			this.Offset = offset;
+			this.IsHidden = is_hidden;
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[Line {0}:{1,2}-{3,4}:{5}]", File, Row, Column, EndRow, EndColumn, Offset);
+		}
+	}
+
+	public class CodeBlockEntry
+	{
+		public int Index;
+		#region This is actually written to the symbol file
+		public int Parent;
+		public Type BlockType;
+		public int StartOffset;
+		public int EndOffset;
+		#endregion
+
+		public enum Type {
+			Lexical			= 1,
+			CompilerGenerated	= 2,
+			IteratorBody		= 3,
+			IteratorDispatcher	= 4
+		}
+
+		public CodeBlockEntry (int index, int parent, Type type, int start_offset)
+		{
+			this.Index = index;
+			this.Parent = parent;
+			this.BlockType = type;
+			this.StartOffset = start_offset;
+		}
+
+		internal CodeBlockEntry (int index, MyBinaryReader reader)
+		{
+			this.Index = index;
+			int type_flag = reader.ReadLeb128 ();
+			BlockType = (Type) (type_flag & 0x3f);
+			this.Parent = reader.ReadLeb128 ();
+			this.StartOffset = reader.ReadLeb128 ();
+			this.EndOffset = reader.ReadLeb128 ();
+
+			/* Reserved for future extensions. */
+			if ((type_flag & 0x40) != 0) {
+				int data_size = reader.ReadInt16 ();
+				reader.BaseStream.Position += data_size;
+			}				
+		}
+
+		public void Close (int end_offset)
+		{
+			this.EndOffset = end_offset;
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 ((int) BlockType);
+			bw.WriteLeb128 (Parent);
+			bw.WriteLeb128 (StartOffset);
+			bw.WriteLeb128 (EndOffset);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[CodeBlock {0}:{1}:{2}:{3}:{4}]",
+					      Index, Parent, BlockType, StartOffset, EndOffset);
+		}
+	}
+
+	public struct LocalVariableEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int Index;
+		public readonly string Name;
+		public readonly int BlockIndex;
+		#endregion
+
+		public LocalVariableEntry (int index, string name, int block)
+		{
+			this.Index = index;
+			this.Name = name;
+			this.BlockIndex = block;
+		}
+
+		internal LocalVariableEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			Index = reader.ReadLeb128 ();
+			Name = reader.ReadString ();
+			BlockIndex = reader.ReadLeb128 ();
+		}
+
+		internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (Index);
+			bw.Write (Name);
+			bw.WriteLeb128 (BlockIndex);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[LocalVariable {0}:{1}:{2}]",
+					      Name, Index, BlockIndex - 1);
+		}
+	}
+
+	public struct CapturedVariable
+	{
+		#region This is actually written to the symbol file
+		public readonly string Name;
+		public readonly string CapturedName;
+		public readonly CapturedKind Kind;
+		#endregion
+
+		public enum CapturedKind : byte
+		{
+			Local,
+			Parameter,
+			This
+		}
+
+		public CapturedVariable (string name, string captured_name,
+					 CapturedKind kind)
+		{
+			this.Name = name;
+			this.CapturedName = captured_name;
+			this.Kind = kind;
+		}
+
+		internal CapturedVariable (MyBinaryReader reader)
+		{
+			Name = reader.ReadString ();
+			CapturedName = reader.ReadString ();
+			Kind = (CapturedKind) reader.ReadByte ();
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.Write (Name);
+			bw.Write (CapturedName);
+			bw.Write ((byte) Kind);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[CapturedVariable {0}:{1}:{2}]",
+					      Name, CapturedName, Kind);
+		}
+	}
+
+	public struct CapturedScope
+	{
+		#region This is actually written to the symbol file
+		public readonly int Scope;
+		public readonly string CapturedName;
+		#endregion
+
+		public CapturedScope (int scope, string captured_name)
+		{
+			this.Scope = scope;
+			this.CapturedName = captured_name;
+		}
+
+		internal CapturedScope (MyBinaryReader reader)
+		{
+			Scope = reader.ReadLeb128 ();
+			CapturedName = reader.ReadString ();
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (Scope);
+			bw.Write (CapturedName);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[CapturedScope {0}:{1}]",
+					      Scope, CapturedName);
+		}
+	}
+
+	public struct ScopeVariable
+	{
+		#region This is actually written to the symbol file
+		public readonly int Scope;
+		public readonly int Index;
+		#endregion
+
+		public ScopeVariable (int scope, int index)
+		{
+			this.Scope = scope;
+			this.Index = index;
+		}
+
+		internal ScopeVariable (MyBinaryReader reader)
+		{
+			Scope = reader.ReadLeb128 ();
+			Index = reader.ReadLeb128 ();
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (Scope);
+			bw.WriteLeb128 (Index);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[ScopeVariable {0}:{1}]", Scope, Index);
+		}
+	}
+
+	public class AnonymousScopeEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int ID;
+		#endregion
+
+		List<CapturedVariable> captured_vars = new List<CapturedVariable> ();
+		List<CapturedScope> captured_scopes = new List<CapturedScope> ();
+
+		public AnonymousScopeEntry (int id)
+		{
+			this.ID = id;
+		}
+
+		internal AnonymousScopeEntry (MyBinaryReader reader)
+		{
+			ID = reader.ReadLeb128 ();
+
+			int num_captured_vars = reader.ReadLeb128 ();
+			for (int i = 0; i < num_captured_vars; i++)
+				captured_vars.Add (new CapturedVariable (reader));
+
+			int num_captured_scopes = reader.ReadLeb128 ();
+			for (int i = 0; i < num_captured_scopes; i++)
+				captured_scopes.Add (new CapturedScope (reader));
+		}
+
+		internal void AddCapturedVariable (string name, string captured_name,
+						   CapturedVariable.CapturedKind kind)
+		{
+			captured_vars.Add (new CapturedVariable (name, captured_name, kind));
+		}
+
+		public CapturedVariable[] CapturedVariables {
+			get {
+				CapturedVariable[] retval = new CapturedVariable [captured_vars.Count];
+				captured_vars.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		internal void AddCapturedScope (int scope, string captured_name)
+		{
+			captured_scopes.Add (new CapturedScope (scope, captured_name));
+		}
+
+		public CapturedScope[] CapturedScopes {
+			get {
+				CapturedScope[] retval = new CapturedScope [captured_scopes.Count];
+				captured_scopes.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			bw.WriteLeb128 (ID);
+
+			bw.WriteLeb128 (captured_vars.Count);
+			foreach (CapturedVariable cv in captured_vars)
+				cv.Write (bw);
+
+			bw.WriteLeb128 (captured_scopes.Count);
+			foreach (CapturedScope cs in captured_scopes)
+				cs.Write (bw);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[AnonymousScope {0}]", ID);
+		}
+	}
+
+	public class CompileUnitEntry : ICompileUnit
+	{
+		#region This is actually written to the symbol file
+		public readonly int Index;
+		int DataOffset;
+		#endregion
+
+		MonoSymbolFile file;
+		SourceFileEntry source;
+		List<SourceFileEntry> include_files;
+		List<NamespaceEntry> namespaces;
+
+		bool creating;
+
+		public static int Size {
+			get { return 8; }
+		}
+
+		CompileUnitEntry ICompileUnit.Entry {
+			get { return this; }
+		}
+
+		public CompileUnitEntry (MonoSymbolFile file, SourceFileEntry source)
+		{
+			this.file = file;
+			this.source = source;
+
+			this.Index = file.AddCompileUnit (this);
+
+			creating = true;
+			namespaces = new List<NamespaceEntry> ();
+		}
+
+		public void AddFile (SourceFileEntry file)
+		{
+			if (!creating)
+				throw new InvalidOperationException ();
+
+			if (include_files == null)
+				include_files = new List<SourceFileEntry> ();
+
+			include_files.Add (file);
+		}
+
+		public SourceFileEntry SourceFile {
+			get {
+				if (creating)
+					return source;
+
+				ReadData ();
+				return source;
+			}
+		}
+
+		public int DefineNamespace (string name, string[] using_clauses, int parent)
+		{
+			if (!creating)
+				throw new InvalidOperationException ();
+
+			int index = file.GetNextNamespaceIndex ();
+			NamespaceEntry ns = new NamespaceEntry (name, index, using_clauses, parent);
+			namespaces.Add (ns);
+			return index;
+		}
+
+		internal void WriteData (MyBinaryWriter bw)
+		{
+			DataOffset = (int) bw.BaseStream.Position;
+			bw.WriteLeb128 (source.Index);
+
+			int count_includes = include_files != null ? include_files.Count : 0;
+			bw.WriteLeb128 (count_includes);
+			if (include_files != null) {
+				foreach (SourceFileEntry entry in include_files)
+					bw.WriteLeb128 (entry.Index);
+			}
+
+			bw.WriteLeb128 (namespaces.Count);
+			foreach (NamespaceEntry ns in namespaces)
+				ns.Write (file, bw);
+		}
+
+		internal void Write (BinaryWriter bw)
+		{
+			bw.Write (Index);
+			bw.Write (DataOffset);
+		}
+
+		internal CompileUnitEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			this.file = file;
+
+			Index = reader.ReadInt32 ();
+			DataOffset = reader.ReadInt32 ();
+		}
+
+		public void ReadAll ()
+		{
+			ReadData ();
+		}
+
+		void ReadData ()
+		{
+			if (creating)
+				throw new InvalidOperationException ();
+
+			lock (file) {
+				if (namespaces != null)
+					return;
+
+				MyBinaryReader reader = file.BinaryReader;
+				int old_pos = (int) reader.BaseStream.Position;
+
+				reader.BaseStream.Position = DataOffset;
+
+				int source_idx = reader.ReadLeb128 ();
+				source = file.GetSourceFile (source_idx);
+
+				int count_includes = reader.ReadLeb128 ();
+				if (count_includes > 0) {
+					include_files = new List<SourceFileEntry> ();
+					for (int i = 0; i < count_includes; i++)
+						include_files.Add (file.GetSourceFile (reader.ReadLeb128 ()));
+				}
+
+				int count_ns = reader.ReadLeb128 ();
+				namespaces = new List<NamespaceEntry> ();
+				for (int i = 0; i < count_ns; i ++)
+					namespaces.Add (new NamespaceEntry (file, reader));
+
+				reader.BaseStream.Position = old_pos;
+			}
+		}
+
+		public NamespaceEntry[] Namespaces {
+			get {
+				ReadData ();
+				NamespaceEntry[] retval = new NamespaceEntry [namespaces.Count];
+				namespaces.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		public SourceFileEntry[] IncludeFiles {
+			get {
+				ReadData ();
+				if (include_files == null)
+					return new SourceFileEntry [0];
+
+				SourceFileEntry[] retval = new SourceFileEntry [include_files.Count];
+				include_files.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+	}
+
+	public class SourceFileEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly int Index;
+		int DataOffset;
+		#endregion
+
+		MonoSymbolFile file;
+		string file_name;
+		byte[] guid;
+		byte[] hash;
+		bool creating;
+		bool auto_generated;
+
+		public static int Size {
+			get { return 8; }
+		}
+
+		public SourceFileEntry (MonoSymbolFile file, string file_name)
+		{
+			this.file = file;
+			this.file_name = file_name;
+			this.Index = file.AddSource (this);
+
+			creating = true;
+		}
+
+		public SourceFileEntry (MonoSymbolFile file, string file_name, byte[] guid, byte[] checksum)
+			: this (file, file_name)
+		{
+			this.guid = guid;
+			this.hash = checksum;
+		}
+
+		public byte[] Checksum {
+			get {
+				return hash;
+			}
+		}
+
+		internal void WriteData (MyBinaryWriter bw)
+		{
+			DataOffset = (int) bw.BaseStream.Position;
+			bw.Write (file_name);
+
+			if (guid == null)
+				guid = new byte[16];
+
+			if (hash == null) {
+				try {
+				    using (FileStream fs = new FileStream (file_name, FileMode.Open, FileAccess.Read)) {
+				        MD5 md5 = MD5.Create ();
+				        hash = md5.ComputeHash (fs);
+				    }
+				} catch {
+					hash = new byte [16];
+				}
+			}
+
+			bw.Write (guid);
+			bw.Write (hash);
+			bw.Write ((byte) (auto_generated ? 1 : 0));
+		}
+
+		internal void Write (BinaryWriter bw)
+		{
+			bw.Write (Index);
+			bw.Write (DataOffset);
+		}
+
+		internal SourceFileEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			this.file = file;
+
+			Index = reader.ReadInt32 ();
+			DataOffset = reader.ReadInt32 ();
+
+			int old_pos = (int) reader.BaseStream.Position;
+			reader.BaseStream.Position = DataOffset;
+
+			file_name = reader.ReadString ();
+			guid = reader.ReadBytes (16);
+			hash = reader.ReadBytes (16);
+			auto_generated = reader.ReadByte () == 1;
+
+			reader.BaseStream.Position = old_pos;
+		}
+
+		public string FileName {
+			get { return file_name; }
+			set { file_name = value; }
+		}
+
+		public bool AutoGenerated {
+			get { return auto_generated; }
+		}
+
+		public void SetAutoGenerated ()
+		{
+			if (!creating)
+				throw new InvalidOperationException ();
+
+			auto_generated = true;
+			file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource;
+		}
+
+		public bool CheckChecksum ()
+		{
+			try {
+				using (FileStream fs = new FileStream (file_name, FileMode.Open)) {
+					MD5 md5 = MD5.Create ();
+					byte[] data = md5.ComputeHash (fs);
+					for (int i = 0; i < 16; i++)
+						if (data [i] != hash [i])
+							return false;
+					return true;
+				}
+			} catch {
+				return false;
+			}
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("SourceFileEntry ({0}:{1})", Index, DataOffset);
+		}
+	}
+
+	public class LineNumberTable
+	{
+		protected LineNumberEntry[] _line_numbers;
+		public LineNumberEntry[] LineNumbers {
+			get { return _line_numbers; }
+		}
+
+		public readonly int LineBase;
+		public readonly int LineRange;
+		public readonly byte OpcodeBase;
+		public readonly int MaxAddressIncrement;
+
+#region Configurable constants
+		public const int Default_LineBase = -1;
+		public const int Default_LineRange = 8;
+		public const byte Default_OpcodeBase = 9;
+
+#endregion
+
+		public const byte DW_LNS_copy = 1;
+		public const byte DW_LNS_advance_pc = 2;
+		public const byte DW_LNS_advance_line = 3;
+		public const byte DW_LNS_set_file = 4;
+		public const byte DW_LNS_const_add_pc = 8;
+
+		public const byte DW_LNE_end_sequence = 1;
+
+		// MONO extensions.
+		public const byte DW_LNE_MONO_negate_is_hidden = 0x40;
+
+		internal const byte DW_LNE_MONO__extensions_start = 0x40;
+		internal const byte DW_LNE_MONO__extensions_end   = 0x7f;
+
+		protected LineNumberTable (MonoSymbolFile file)
+		{
+			this.LineBase = file.OffsetTable.LineNumberTable_LineBase;
+			this.LineRange = file.OffsetTable.LineNumberTable_LineRange;
+			this.OpcodeBase = (byte) file.OffsetTable.LineNumberTable_OpcodeBase;
+			this.MaxAddressIncrement = (255 - OpcodeBase) / LineRange;
+		}
+
+		internal LineNumberTable (MonoSymbolFile file, LineNumberEntry[] lines)
+			: this (file)
+		{
+			this._line_numbers = lines;
+		}
+
+		internal void Write (MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo)
+		{
+			int start = (int) bw.BaseStream.Position;
+
+			bool last_is_hidden = false;
+			int last_line = 1, last_offset = 0, last_file = 1;
+			for (int i = 0; i < LineNumbers.Length; i++) {
+				int line_inc = LineNumbers [i].Row - last_line;
+				int offset_inc = LineNumbers [i].Offset - last_offset;
+
+				if (LineNumbers [i].File != last_file) {
+					bw.Write (DW_LNS_set_file);
+					bw.WriteLeb128 (LineNumbers [i].File);
+					last_file = LineNumbers [i].File;
+				}
+
+				if (LineNumbers [i].IsHidden != last_is_hidden) {
+					bw.Write ((byte) 0);
+					bw.Write ((byte) 1);
+					bw.Write (DW_LNE_MONO_negate_is_hidden);
+					last_is_hidden = LineNumbers [i].IsHidden;
+				}
+
+				if (offset_inc >= MaxAddressIncrement) {
+					if (offset_inc < 2 * MaxAddressIncrement) {
+						bw.Write (DW_LNS_const_add_pc);
+						offset_inc -= MaxAddressIncrement;
+					} else {
+						bw.Write (DW_LNS_advance_pc);
+						bw.WriteLeb128 (offset_inc);
+						offset_inc = 0;
+					}
+				}
+
+				if ((line_inc < LineBase) || (line_inc >= LineBase + LineRange)) {
+					bw.Write (DW_LNS_advance_line);
+					bw.WriteLeb128 (line_inc);
+					if (offset_inc != 0) {
+						bw.Write (DW_LNS_advance_pc);
+						bw.WriteLeb128 (offset_inc);
+					}
+					bw.Write (DW_LNS_copy);
+				} else {
+					byte opcode;
+					opcode = (byte) (line_inc - LineBase + (LineRange * offset_inc) +
+							 OpcodeBase);
+					bw.Write (opcode);
+				}
+
+				last_line = LineNumbers [i].Row;
+				last_offset = LineNumbers [i].Offset;
+			}
+
+			bw.Write ((byte) 0);
+			bw.Write ((byte) 1);
+			bw.Write (DW_LNE_end_sequence);
+
+			if (hasColumnsInfo) {
+				for (int i = 0; i < LineNumbers.Length; i++) {
+					var ln = LineNumbers [i];
+					if (ln.Row >= 0)
+						bw.WriteLeb128 (ln.Column);
+				}
+			}
+
+			if (hasEndInfo) {
+				for (int i = 0; i < LineNumbers.Length; i++) {
+					var ln = LineNumbers [i];
+					if (ln.EndRow == -1 || ln.EndColumn == -1 || ln.Row > ln.EndRow) {
+						bw.WriteLeb128 (0xffffff);
+					} else {
+						bw.WriteLeb128 (ln.EndRow - ln.Row);
+						bw.WriteLeb128 (ln.EndColumn);
+					}
+				}
+			}
+
+			file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start;
+		}
+
+		internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo)
+		{
+			LineNumberTable lnt = new LineNumberTable (file);
+			lnt.DoRead (file, br, readColumnsInfo, readEndInfo);
+			return lnt;
+		}
+
+		void DoRead (MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds)
+		{
+			var lines = new List<LineNumberEntry> ();
+
+			bool is_hidden = false, modified = false;
+			int stm_line = 1, stm_offset = 0, stm_file = 1;
+			while (true) {
+				byte opcode = br.ReadByte ();
+
+				if (opcode == 0) {
+					byte size = br.ReadByte ();
+					long end_pos = br.BaseStream.Position + size;
+					opcode = br.ReadByte ();
+
+					if (opcode == DW_LNE_end_sequence) {
+						if (modified)
+							lines.Add (new LineNumberEntry (
+								stm_file, stm_line, -1, stm_offset, is_hidden));
+						break;
+					} else if (opcode == DW_LNE_MONO_negate_is_hidden) {
+						is_hidden = !is_hidden;
+						modified = true;
+					} else if ((opcode >= DW_LNE_MONO__extensions_start) &&
+						   (opcode <= DW_LNE_MONO__extensions_end)) {
+						; // reserved for future extensions
+					} else {
+						throw new MonoSymbolFileException ("Unknown extended opcode {0:x}", opcode);
+					}
+
+					br.BaseStream.Position = end_pos;
+					continue;
+				} else if (opcode < OpcodeBase) {
+					switch (opcode) {
+					case DW_LNS_copy:
+						lines.Add (new LineNumberEntry (
+							stm_file, stm_line, -1, stm_offset, is_hidden));
+						modified = false;
+						break;
+					case DW_LNS_advance_pc:
+						stm_offset += br.ReadLeb128 ();
+						modified = true;
+						break;
+					case DW_LNS_advance_line:
+						stm_line += br.ReadLeb128 ();
+						modified = true;
+						break;
+					case DW_LNS_set_file:
+						stm_file = br.ReadLeb128 ();
+						modified = true;
+						break;
+					case DW_LNS_const_add_pc:
+						stm_offset += MaxAddressIncrement;
+						modified = true;
+						break;
+					default:
+						throw new MonoSymbolFileException (
+							"Unknown standard opcode {0:x} in LNT",
+							opcode);
+					}
+				} else {
+					opcode -= OpcodeBase;
+
+					stm_offset += opcode / LineRange;
+					stm_line += LineBase + (opcode % LineRange);
+					lines.Add (new LineNumberEntry (
+						stm_file, stm_line, -1, stm_offset, is_hidden));
+					modified = false;
+				}
+			}
+
+			_line_numbers = lines.ToArray ();
+
+			if (includesColumns) {
+				for (int i = 0; i < _line_numbers.Length; ++i) {
+					var ln = _line_numbers[i];
+					if (ln.Row >= 0)
+						ln.Column = br.ReadLeb128 ();
+				}
+			}
+			if (includesEnds) {
+				for (int i = 0; i < _line_numbers.Length; ++i) {
+					var ln = _line_numbers[i];
+
+					int row = br.ReadLeb128 ();
+					if (row == 0xffffff) {
+						ln.EndRow = -1;
+						ln.EndColumn = -1;
+					} else {
+						ln.EndRow = ln.Row + row;
+						ln.EndColumn = br.ReadLeb128 ();
+					}
+				}
+			}
+		}
+
+		public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end)
+		{
+			if (_line_numbers.Length > 1) {
+				start = _line_numbers [0];
+				end = _line_numbers [_line_numbers.Length - 1];
+				return true;
+			}
+
+			start = LineNumberEntry.Null;
+			end = LineNumberEntry.Null;
+			return false;
+		}
+	}
+
+	public class MethodEntry : IComparable
+	{
+		#region This is actually written to the symbol file
+		public readonly int CompileUnitIndex;
+		public readonly int Token;
+		public readonly int NamespaceID;
+
+		int DataOffset;
+		int LocalVariableTableOffset;
+		int LineNumberTableOffset;
+		int CodeBlockTableOffset;
+		int ScopeVariableTableOffset;
+		int RealNameOffset;
+		Flags flags;
+		#endregion
+
+		int index;
+
+		public Flags MethodFlags {
+			get { return flags; }
+		}
+
+		public readonly CompileUnitEntry CompileUnit;
+
+		LocalVariableEntry[] locals;
+		CodeBlockEntry[] code_blocks;
+		ScopeVariable[] scope_vars;
+		LineNumberTable lnt;
+		string real_name;
+
+		public readonly MonoSymbolFile SymbolFile;
+
+		public int Index {
+			get { return index; }
+			set { index = value; }
+		}
+
+		[Flags]
+		public enum Flags
+		{
+			LocalNamesAmbiguous	= 1,
+			ColumnsInfoIncluded = 1 << 1,
+			EndInfoIncluded = 1 << 2
+		}
+
+		public const int Size = 12;
+
+		internal MethodEntry (MonoSymbolFile file, MyBinaryReader reader, int index)
+		{
+			this.SymbolFile = file;
+			this.index = index;
+
+			Token = reader.ReadInt32 ();
+			DataOffset = reader.ReadInt32 ();
+			LineNumberTableOffset = reader.ReadInt32 ();
+
+			long old_pos = reader.BaseStream.Position;
+			reader.BaseStream.Position = DataOffset;
+
+			CompileUnitIndex = reader.ReadLeb128 ();
+			LocalVariableTableOffset = reader.ReadLeb128 ();
+			NamespaceID = reader.ReadLeb128 ();
+
+			CodeBlockTableOffset = reader.ReadLeb128 ();
+			ScopeVariableTableOffset = reader.ReadLeb128 ();
+
+			RealNameOffset = reader.ReadLeb128 ();
+
+			flags = (Flags) reader.ReadLeb128 ();
+
+			reader.BaseStream.Position = old_pos;
+
+			CompileUnit = file.GetCompileUnit (CompileUnitIndex);
+		}
+
+		internal MethodEntry (MonoSymbolFile file, CompileUnitEntry comp_unit,
+				      int token, ScopeVariable[] scope_vars,
+				      LocalVariableEntry[] locals, LineNumberEntry[] lines,
+				      CodeBlockEntry[] code_blocks, string real_name,
+				      Flags flags, int namespace_id)
+		{
+			this.SymbolFile = file;
+			this.real_name = real_name;
+			this.locals = locals;
+			this.code_blocks = code_blocks;
+			this.scope_vars = scope_vars;
+			this.flags = flags;
+
+			index = -1;
+
+			Token = token;
+			CompileUnitIndex = comp_unit.Index;
+			CompileUnit = comp_unit;
+			NamespaceID = namespace_id;
+
+			CheckLineNumberTable (lines);
+			lnt = new LineNumberTable (file, lines);
+			file.NumLineNumbers += lines.Length;
+
+			int num_locals = locals != null ? locals.Length : 0;
+
+			if (num_locals <= 32) {
+				// Most of the time, the O(n^2) factor is actually
+				// less than the cost of allocating the hash table,
+				// 32 is a rough number obtained through some testing.
+				
+				for (int i = 0; i < num_locals; i ++) {
+					string nm = locals [i].Name;
+					
+					for (int j = i + 1; j < num_locals; j ++) {
+						if (locals [j].Name == nm) {
+							flags |= Flags.LocalNamesAmbiguous;
+							goto locals_check_done;
+						}
+					}
+				}
+			locals_check_done :
+				;
+			} else {
+				var local_names = new Dictionary<string, LocalVariableEntry> ();
+				foreach (LocalVariableEntry local in locals) {
+					if (local_names.ContainsKey (local.Name)) {
+						flags |= Flags.LocalNamesAmbiguous;
+						break;
+					}
+					local_names.Add (local.Name, local);
+				}
+			}
+		}
+		
+		static void CheckLineNumberTable (LineNumberEntry[] line_numbers)
+		{
+			int last_offset = -1;
+			int last_row = -1;
+
+			if (line_numbers == null)
+				return;
+			
+			for (int i = 0; i < line_numbers.Length; i++) {
+				LineNumberEntry line = line_numbers [i];
+
+				if (line.Equals (LineNumberEntry.Null))
+					throw new MonoSymbolFileException ();
+
+				if (line.Offset < last_offset)
+					throw new MonoSymbolFileException ();
+
+				if (line.Offset > last_offset) {
+					last_row = line.Row;
+					last_offset = line.Offset;
+				} else if (line.Row > last_row) {
+					last_row = line.Row;
+				}
+			}
+		}
+
+		internal void Write (MyBinaryWriter bw)
+		{
+			if ((index <= 0) || (DataOffset == 0))
+				throw new InvalidOperationException ();
+
+			bw.Write (Token);
+			bw.Write (DataOffset);
+			bw.Write (LineNumberTableOffset);
+		}
+
+		internal void WriteData (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			if (index <= 0)
+				throw new InvalidOperationException ();
+
+			LocalVariableTableOffset = (int) bw.BaseStream.Position;
+			int num_locals = locals != null ? locals.Length : 0;
+			bw.WriteLeb128 (num_locals);
+			for (int i = 0; i < num_locals; i++)
+				locals [i].Write (file, bw);
+			file.LocalCount += num_locals;
+
+			CodeBlockTableOffset = (int) bw.BaseStream.Position;
+			int num_code_blocks = code_blocks != null ? code_blocks.Length : 0;
+			bw.WriteLeb128 (num_code_blocks);
+			for (int i = 0; i < num_code_blocks; i++)
+				code_blocks [i].Write (bw);
+
+			ScopeVariableTableOffset = (int) bw.BaseStream.Position;
+			int num_scope_vars = scope_vars != null ? scope_vars.Length : 0;
+			bw.WriteLeb128 (num_scope_vars);
+			for (int i = 0; i < num_scope_vars; i++)
+				scope_vars [i].Write (bw);
+
+			if (real_name != null) {
+				RealNameOffset = (int) bw.BaseStream.Position;
+				bw.Write (real_name);
+			}
+
+			foreach (var lne in lnt.LineNumbers) {
+				if (lne.EndRow != -1 || lne.EndColumn != -1)
+					flags |= Flags.EndInfoIncluded;
+			}
+
+			LineNumberTableOffset = (int) bw.BaseStream.Position;
+			lnt.Write (file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
+
+			DataOffset = (int) bw.BaseStream.Position;
+
+			bw.WriteLeb128 (CompileUnitIndex);
+			bw.WriteLeb128 (LocalVariableTableOffset);
+			bw.WriteLeb128 (NamespaceID);
+
+			bw.WriteLeb128 (CodeBlockTableOffset);
+			bw.WriteLeb128 (ScopeVariableTableOffset);
+
+			bw.WriteLeb128 (RealNameOffset);
+			bw.WriteLeb128 ((int) flags);
+		}
+
+		public void ReadAll ()
+		{
+			GetLineNumberTable ();
+			GetLocals ();
+			GetCodeBlocks ();
+			GetScopeVariables ();
+			GetRealName ();
+		}
+
+		public LineNumberTable GetLineNumberTable ()
+		{
+			lock (SymbolFile) {
+				if (lnt != null)
+					return lnt;
+
+				if (LineNumberTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = LineNumberTableOffset;
+
+				lnt = LineNumberTable.Read (SymbolFile, reader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
+
+				reader.BaseStream.Position = old_pos;
+				return lnt;
+			}
+		}
+
+		public LocalVariableEntry[] GetLocals ()
+		{
+			lock (SymbolFile) {
+				if (locals != null)
+					return locals;
+
+				if (LocalVariableTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = LocalVariableTableOffset;
+
+				int num_locals = reader.ReadLeb128 ();
+				locals = new LocalVariableEntry [num_locals];
+
+				for (int i = 0; i < num_locals; i++)
+					locals [i] = new LocalVariableEntry (SymbolFile, reader);
+
+				reader.BaseStream.Position = old_pos;
+				return locals;
+			}
+		}
+
+		public CodeBlockEntry[] GetCodeBlocks ()
+		{
+			lock (SymbolFile) {
+				if (code_blocks != null)
+					return code_blocks;
+
+				if (CodeBlockTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = CodeBlockTableOffset;
+
+				int num_code_blocks = reader.ReadLeb128 ();
+				code_blocks = new CodeBlockEntry [num_code_blocks];
+
+				for (int i = 0; i < num_code_blocks; i++)
+					code_blocks [i] = new CodeBlockEntry (i, reader);
+
+				reader.BaseStream.Position = old_pos;
+				return code_blocks;
+			}
+		}
+
+		public ScopeVariable[] GetScopeVariables ()
+		{
+			lock (SymbolFile) {
+				if (scope_vars != null)
+					return scope_vars;
+
+				if (ScopeVariableTableOffset == 0)
+					return null;
+
+				MyBinaryReader reader = SymbolFile.BinaryReader;
+				long old_pos = reader.BaseStream.Position;
+				reader.BaseStream.Position = ScopeVariableTableOffset;
+
+				int num_scope_vars = reader.ReadLeb128 ();
+				scope_vars = new ScopeVariable [num_scope_vars];
+
+				for (int i = 0; i < num_scope_vars; i++)
+					scope_vars [i] = new ScopeVariable (reader);
+
+				reader.BaseStream.Position = old_pos;
+				return scope_vars;
+			}
+		}
+
+		public string GetRealName ()
+		{
+			lock (SymbolFile) {
+				if (real_name != null)
+					return real_name;
+
+				if (RealNameOffset == 0)
+					return null;
+
+				real_name = SymbolFile.BinaryReader.ReadString (RealNameOffset);
+				return real_name;
+			}
+		}
+
+		public int CompareTo (object obj)
+		{
+			MethodEntry method = (MethodEntry) obj;
+
+			if (method.Token < Token)
+				return 1;
+			else if (method.Token > Token)
+				return -1;
+			else
+				return 0;
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[Method {0}:{1:x}:{2}:{3}]",
+					      index, Token, CompileUnitIndex, CompileUnit);
+		}
+	}
+
+	public struct NamespaceEntry
+	{
+		#region This is actually written to the symbol file
+		public readonly string Name;
+		public readonly int Index;
+		public readonly int Parent;
+		public readonly string[] UsingClauses;
+		#endregion
+
+		public NamespaceEntry (string name, int index, string[] using_clauses, int parent)
+		{
+			this.Name = name;
+			this.Index = index;
+			this.Parent = parent;
+			this.UsingClauses = using_clauses != null ? using_clauses : new string [0];
+		}
+
+		internal NamespaceEntry (MonoSymbolFile file, MyBinaryReader reader)
+		{
+			Name = reader.ReadString ();
+			Index = reader.ReadLeb128 ();
+			Parent = reader.ReadLeb128 ();
+
+			int count = reader.ReadLeb128 ();
+			UsingClauses = new string [count];
+			for (int i = 0; i < count; i++)
+				UsingClauses [i] = reader.ReadString ();
+		}
+
+		internal void Write (MonoSymbolFile file, MyBinaryWriter bw)
+		{
+			bw.Write (Name);
+			bw.WriteLeb128 (Index);
+			bw.WriteLeb128 (Parent);
+			bw.WriteLeb128 (UsingClauses.Length);
+			foreach (string uc in UsingClauses)
+				bw.Write (uc);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("[Namespace {0}:{1}:{2}]", Name, Index, Parent);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolWriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolWriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/MonoSymbolWriter.cs	(revision 11807)
@@ -0,0 +1,238 @@
+//
+// Mono.CSharp.Debugger/MonoSymbolWriter.cs
+//
+// Author:
+//   Martin Baulig (martin@ximian.com)
+//
+// This is the default implementation of the System.Diagnostics.SymbolStore.ISymbolWriter
+// interface.
+//
+// (C) 2002 Ximian, Inc.  http://www.ximian.com
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Collections.Generic;
+using System.IO;
+	
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class MonoSymbolWriter
+	{
+		List<SourceMethodBuilder> methods;
+		List<SourceFileEntry> sources;
+		List<CompileUnitEntry> comp_units;
+		protected readonly MonoSymbolFile file;
+		string filename;
+		
+		private SourceMethodBuilder current_method;
+		Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder> ();
+
+		public MonoSymbolWriter (string filename)
+		{
+			this.methods = new List<SourceMethodBuilder> ();
+			this.sources = new List<SourceFileEntry> ();
+			this.comp_units = new List<CompileUnitEntry> ();
+			this.file = new MonoSymbolFile ();
+
+			this.filename = filename + ".mdb";
+		}
+
+		public MonoSymbolFile SymbolFile {
+			get { return file; }
+		}
+
+		public void CloseNamespace ()
+		{ }
+
+		public void DefineLocalVariable (int index, string name)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.AddLocal (index, name);
+		}
+
+		public void DefineCapturedLocal (int scope_id, string name, string captured_name)
+		{
+			file.DefineCapturedVariable (scope_id, name, captured_name,
+						     CapturedVariable.CapturedKind.Local);
+		}
+
+		public void DefineCapturedParameter (int scope_id, string name, string captured_name)
+		{
+			file.DefineCapturedVariable (scope_id, name, captured_name,
+						     CapturedVariable.CapturedKind.Parameter);
+		}
+
+		public void DefineCapturedThis (int scope_id, string captured_name)
+		{
+			file.DefineCapturedVariable (scope_id, "this", captured_name,
+						     CapturedVariable.CapturedKind.This);
+		}
+
+		public void DefineCapturedScope (int scope_id, int id, string captured_name)
+		{
+			file.DefineCapturedScope (scope_id, id, captured_name);
+		}
+
+		public void DefineScopeVariable (int scope, int index)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.AddScopeVariable (scope, index);
+		}
+
+		public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column,
+					       bool is_hidden)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.MarkSequencePoint (offset, file, line, column, is_hidden);
+		}
+
+		public SourceMethodBuilder OpenMethod (ICompileUnit file, int ns_id, IMethodDef method)
+		{
+			SourceMethodBuilder builder = new SourceMethodBuilder (file, ns_id, method);
+			current_method_stack.Push (current_method);
+			current_method = builder;
+			methods.Add (current_method);
+			return builder;
+		}
+
+		public void CloseMethod ()
+		{
+			current_method = (SourceMethodBuilder) current_method_stack.Pop ();
+		}
+
+		public SourceFileEntry DefineDocument (string url)
+		{
+			SourceFileEntry entry = new SourceFileEntry (file, url);
+			sources.Add (entry);
+			return entry;
+		}
+
+		public SourceFileEntry DefineDocument (string url, byte[] guid, byte[] checksum)
+		{
+			SourceFileEntry entry = new SourceFileEntry (file, url, guid, checksum);
+			sources.Add (entry);
+			return entry;
+		}
+
+		public CompileUnitEntry DefineCompilationUnit (SourceFileEntry source)
+		{
+			CompileUnitEntry entry = new CompileUnitEntry (file, source);
+			comp_units.Add (entry);
+			return entry;
+		}
+
+		public int DefineNamespace (string name, CompileUnitEntry unit,
+					    string[] using_clauses, int parent)
+		{
+			if ((unit == null) || (using_clauses == null))
+				throw new NullReferenceException ();
+
+			return unit.DefineNamespace (name, using_clauses, parent);
+		}
+
+		public int OpenScope (int start_offset)
+		{
+			if (current_method == null)
+				return 0;
+
+			current_method.StartBlock (CodeBlockEntry.Type.Lexical, start_offset);
+			return 0;
+		}
+
+		public void CloseScope (int end_offset)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.EndBlock (end_offset);
+		}
+
+		public void OpenCompilerGeneratedBlock (int start_offset)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.StartBlock (CodeBlockEntry.Type.CompilerGenerated,
+						   start_offset);
+		}
+
+		public void CloseCompilerGeneratedBlock (int end_offset)
+		{
+			if (current_method == null)
+				return;
+
+			current_method.EndBlock (end_offset);
+		}
+
+		public void StartIteratorBody (int start_offset)
+		{
+			current_method.StartBlock (CodeBlockEntry.Type.IteratorBody,
+						   start_offset);
+		}
+
+		public void EndIteratorBody (int end_offset)
+		{
+			current_method.EndBlock (end_offset);
+		}
+
+		public void StartIteratorDispatcher (int start_offset)
+		{
+			current_method.StartBlock (CodeBlockEntry.Type.IteratorDispatcher,
+						   start_offset);
+		}
+
+		public void EndIteratorDispatcher (int end_offset)
+		{
+			current_method.EndBlock (end_offset);
+		}
+
+		public void DefineAnonymousScope (int id)
+		{
+			file.DefineAnonymousScope (id);
+		}
+
+		public void WriteSymbolFile (Guid guid)
+		{
+			foreach (SourceMethodBuilder method in methods)
+				method.DefineMethod (file);
+
+			try {
+				// We mmap the file, so unlink the previous version since it may be in use
+				File.Delete (filename);
+			} catch {
+				// We can safely ignore
+			}
+			using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
+				file.CreateSymbolFile (guid, fs);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/SourceMethodBuilder.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/SourceMethodBuilder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/SourceMethodBuilder.cs	(revision 11807)
@@ -0,0 +1,190 @@
+//
+// SourceMethodBuilder.cs
+//
+// Authors:
+//   Martin Baulig (martin@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// (C) 2002 Ximian, Inc.  http://www.ximian.com
+// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Generic;
+
+namespace Mono.CompilerServices.SymbolWriter
+{
+	public class SourceMethodBuilder
+	{
+		List<LocalVariableEntry> _locals;
+		List<CodeBlockEntry> _blocks;
+		List<ScopeVariable> _scope_vars;
+		Stack<CodeBlockEntry> _block_stack;
+		readonly List<LineNumberEntry> method_lines;
+
+		readonly ICompileUnit _comp_unit;
+		readonly int ns_id;
+		readonly IMethodDef method;
+
+		public SourceMethodBuilder (ICompileUnit comp_unit)
+		{
+			this._comp_unit = comp_unit;
+			method_lines = new List<LineNumberEntry> ();
+		}
+
+		public SourceMethodBuilder (ICompileUnit comp_unit, int ns_id, IMethodDef method)
+			: this (comp_unit)
+		{
+			this.ns_id = ns_id;
+			this.method = method;
+		}
+
+		public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, bool is_hidden)
+		{
+			MarkSequencePoint (offset, file, line, column, -1, -1, is_hidden);
+		}
+
+		public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden)
+		{
+			int file_idx = file != null ? file.Index : 0;
+			var lne = new LineNumberEntry (file_idx, line, column, end_line, end_column, offset, is_hidden);
+
+			if (method_lines.Count > 0) {
+				var prev = method_lines[method_lines.Count - 1];
+
+				//
+				// Same offset cannot be used for multiple lines
+				// 
+				if (prev.Offset == offset) {
+					//
+					// Use the new location because debugger will adjust
+					// the breakpoint to next line with sequence point
+					//
+					if (LineNumberEntry.LocationComparer.Default.Compare (lne, prev) > 0)
+						method_lines[method_lines.Count - 1] = lne;
+
+					return;
+				}
+			}
+
+			method_lines.Add (lne);
+		}
+
+		public void StartBlock (CodeBlockEntry.Type type, int start_offset)
+		{
+			if (_block_stack == null) {
+				_block_stack = new Stack<CodeBlockEntry> ();
+			}
+			
+			if (_blocks == null)
+				_blocks = new List<CodeBlockEntry> ();
+
+			int parent = CurrentBlock != null ? CurrentBlock.Index : -1;
+
+			CodeBlockEntry block = new CodeBlockEntry (
+				_blocks.Count + 1, parent, type, start_offset);
+
+			_block_stack.Push (block);
+			_blocks.Add (block);
+		}
+
+		public void EndBlock (int end_offset)
+		{
+			CodeBlockEntry block = (CodeBlockEntry) _block_stack.Pop ();
+			block.Close (end_offset);
+		}
+
+		public CodeBlockEntry[] Blocks {
+			get {
+				if (_blocks == null)
+					return new CodeBlockEntry [0];
+
+				CodeBlockEntry[] retval = new CodeBlockEntry [_blocks.Count];
+				_blocks.CopyTo (retval, 0);
+				return retval;
+			}
+		}
+
+		public CodeBlockEntry CurrentBlock {
+			get {
+				if ((_block_stack != null) && (_block_stack.Count > 0))
+					return (CodeBlockEntry) _block_stack.Peek ();
+				else
+					return null;
+			}
+		}
+
+		public LocalVariableEntry[] Locals {
+			get {
+				if (_locals == null)
+					return new LocalVariableEntry [0];
+				else {
+					return _locals.ToArray ();
+				}
+			}
+		}
+
+		public ICompileUnit SourceFile {
+			get {
+				return _comp_unit;
+			}
+		}
+
+		public void AddLocal (int index, string name)
+		{
+			if (_locals == null)
+				_locals = new List<LocalVariableEntry> ();
+			int block_idx = CurrentBlock != null ? CurrentBlock.Index : 0;
+			_locals.Add (new LocalVariableEntry (index, name, block_idx));
+		}
+
+		public ScopeVariable[] ScopeVariables {
+			get {
+				if (_scope_vars == null)
+					return new ScopeVariable [0];
+
+				return _scope_vars.ToArray ();
+			}
+		}
+
+		public void AddScopeVariable (int scope, int index)
+		{
+			if (_scope_vars == null)
+				_scope_vars = new List<ScopeVariable> ();
+			_scope_vars.Add (
+				new ScopeVariable (scope, index));
+		}
+
+		public void DefineMethod (MonoSymbolFile file)
+		{
+			DefineMethod (file, method.Token);
+		}
+
+		public void DefineMethod (MonoSymbolFile file, int token)
+		{
+			MethodEntry entry = new MethodEntry (
+				file, _comp_unit.Entry, token, ScopeVariables,
+				Locals, method_lines.ToArray (), Blocks, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id);
+
+			file.AddMethod (entry);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/anonymous.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/anonymous.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/anonymous.cs	(revision 11807)
@@ -0,0 +1,2292 @@
+//
+// anonymous.cs: Support for anonymous methods and types
+//
+// Author:
+//   Miguel de Icaza (miguel@ximain.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+// Copyright 2003-2011 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
+using System.Diagnostics;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+using System.Diagnostics;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	public abstract class CompilerGeneratedContainer : ClassOrStruct
+	{
+		protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod)
+			: this (parent, name, mod, MemberKind.Class)
+		{
+		}
+
+		protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod, MemberKind kind)
+			: base (parent, name, null, kind)
+		{
+			Debug.Assert ((mod & Modifiers.AccessibilityMask) != 0);
+
+			ModFlags = mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED;
+			spec = new TypeSpec (Kind, null, this, null, ModFlags);
+		}
+
+		protected void CheckMembersDefined ()
+		{
+			if (HasMembersDefined)
+				throw new InternalErrorException ("Helper class already defined!");
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			if (Kind == MemberKind.Class && !IsStatic && !PartialContainer.HasInstanceConstructor) {
+				DefineDefaultConstructor (false);
+			}
+
+			return base.DoDefineMembers ();
+		}
+
+		protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameters tparams, Location loc)
+		{
+			string host_name = host == null ? null : host is InterfaceMemberBase ? ((InterfaceMemberBase)host).GetFullName (host.MemberName) : host.MemberName.Name;
+			string tname = MakeName (host_name, "c", name, unique_id);
+			TypeParameters args = null;
+			if (tparams != null) {
+				args = new TypeParameters (tparams.Count);
+
+				// Type parameters will be filled later when we have TypeContainer
+				// instance, for now we need only correct arity to create valid name
+				for (int i = 0; i < tparams.Count; ++i)
+					args.Add ((TypeParameter) null);
+			}
+
+			return new MemberName (tname, args, loc);
+		}
+
+		public static string MakeName (string host, string typePrefix, string name, int id)
+		{
+			return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			base_type = Compiler.BuiltinTypes.Object;
+
+			base_class = null;
+			return null;
+		}
+	}
+
+	public class HoistedStoreyClass : CompilerGeneratedContainer
+	{
+		public sealed class HoistedField : Field
+		{
+			public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
+				  Attributes attrs, Location loc)
+				: base (parent, type, mod, new MemberName (name, loc), attrs)
+			{
+			}
+
+			protected override bool ResolveMemberType ()
+			{
+				if (!base.ResolveMemberType ())
+					return false;
+
+				HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
+				if (parent != null && parent.Mutator != null)
+					member_type = parent.Mutator.Mutate (MemberType);
+
+				return true;
+			}
+		}
+
+		protected TypeParameterMutator mutator;
+
+		public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mods, MemberKind kind)
+			: base (parent, name, mods | Modifiers.PRIVATE, kind)
+		{
+
+			if (tparams != null) {
+				var type_params = name.TypeParameters;
+				var src = new TypeParameterSpec[tparams.Count];
+				var dst = new TypeParameterSpec[tparams.Count];
+
+				for (int i = 0; i < tparams.Count; ++i) {
+					type_params[i] = tparams[i].CreateHoistedCopy (spec);
+
+					src[i] = tparams[i].Type;
+					dst[i] = type_params[i].Type;
+				}
+
+				// A copy is not enough, inflate any type parameter constraints
+				// using a new type parameters
+				var inflator = new TypeParameterInflator (this, null, src, dst);
+				for (int i = 0; i < tparams.Count; ++i) {
+					src[i].InflateConstraints (inflator, dst[i]);
+				}
+
+				mutator = new TypeParameterMutator (tparams, type_params);
+			}
+		}
+
+		#region Properties
+
+		public TypeParameterMutator Mutator {
+			get {
+				return mutator;
+			}
+			set {
+				mutator = value;
+			}
+		}
+
+		#endregion
+
+		public HoistedStoreyClass GetGenericStorey ()
+		{
+			TypeContainer storey = this;
+			while (storey != null && storey.CurrentTypeParameters == null)
+				storey = storey.Parent;
+
+			return storey as HoistedStoreyClass;
+		}
+	}
+
+
+	//
+	// Anonymous method storey is created when an anonymous method uses
+	// variable or parameter from outer scope. They are then hoisted to
+	// anonymous method storey (captured)
+	//
+	public class AnonymousMethodStorey : HoistedStoreyClass
+	{
+		struct StoreyFieldPair
+		{
+			public readonly AnonymousMethodStorey Storey;
+			public readonly Field Field;
+
+			public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
+			{
+				this.Storey = storey;
+				this.Field = field;
+			}
+		}
+
+		//
+		// Needed to delay hoisted _this_ initialization. When an anonymous
+		// method is used inside ctor and _this_ is hoisted, base ctor has to
+		// be called first, otherwise _this_ will be initialized with 
+		// uninitialized value.
+		//
+		sealed class ThisInitializer : Statement
+		{
+			readonly HoistedThis hoisted_this;
+			readonly AnonymousMethodStorey parent;
+
+			public ThisInitializer (HoistedThis hoisted_this, AnonymousMethodStorey parent)
+			{
+				this.hoisted_this = hoisted_this;
+				this.parent = parent;
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				Expression source;
+
+				if (parent == null)
+					source = new CompilerGeneratedThis (ec.CurrentType, loc);
+				else {
+					source = new FieldExpr (parent.HoistedThis.Field, Location.Null) {
+						InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location.Null)
+					};
+				}
+
+				hoisted_this.EmitAssign (ec, source, false, false);
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				return false;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+				// Nothing to clone
+			}
+		}
+
+		// Unique storey ID
+		public readonly int ID;
+
+		public readonly ExplicitBlock OriginalSourceBlock;
+
+		// A list of StoreyFieldPair with local field keeping parent storey instance
+		List<StoreyFieldPair> used_parent_storeys;
+		List<ExplicitBlock> children_references;
+
+		// A list of hoisted parameters
+		protected List<HoistedParameter> hoisted_params;
+		List<HoistedParameter> hoisted_local_params;
+		protected List<HoistedVariable> hoisted_locals;
+
+		// Hoisted this
+		protected HoistedThis hoisted_this;
+
+		// Local variable which holds this storey instance
+		public Expression Instance;
+
+		bool initialize_hoisted_this;
+		AnonymousMethodStorey hoisted_this_parent;
+
+		public AnonymousMethodStorey (ExplicitBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
+			: base (parent, MakeMemberName (host, name, parent.PartialContainer.CounterAnonymousContainers, tparams, block.StartLocation),
+				tparams, 0, kind)
+		{
+			OriginalSourceBlock = block;
+			ID = parent.PartialContainer.CounterAnonymousContainers++;
+		}
+
+		public void AddCapturedThisField (EmitContext ec, AnonymousMethodStorey parent)
+		{
+			TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
+			Field f = AddCompilerGeneratedField ("$this", type_expr);
+			hoisted_this = new HoistedThis (this, f);
+
+			initialize_hoisted_this = true;
+			hoisted_this_parent = parent;
+		}
+
+		public Field AddCapturedVariable (string name, TypeSpec type)
+		{
+			CheckMembersDefined ();
+
+			FullNamedExpression field_type = new TypeExpression (type, Location);
+			if (!spec.IsGenericOrParentIsGeneric)
+				return AddCompilerGeneratedField (name, field_type);
+
+			const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
+			Field f = new HoistedField (this, field_type, mod, name, null, Location);
+			AddField (f);
+			return f;
+		}
+
+		protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
+		{
+			return AddCompilerGeneratedField (name, type, false);
+		}
+
+		protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
+		{
+			Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
+			Field f = new Field (this, type, mod, new MemberName (name, Location), null);
+			AddField (f);
+			return f;
+		}
+
+		//
+		// Creates a link between hoisted variable block and the anonymous method storey
+		//
+		// An anonymous method can reference variables from any outer block, but they are
+		// hoisted in their own ExplicitBlock. When more than one block is referenced we
+		// need to create another link between those variable storeys
+		//
+		public void AddReferenceFromChildrenBlock (ExplicitBlock block)
+		{
+			if (children_references == null)
+				children_references = new List<ExplicitBlock> ();
+
+			if (!children_references.Contains (block))
+				children_references.Add (block);
+		}
+
+		public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
+		{
+			CheckMembersDefined ();
+
+			if (used_parent_storeys == null)
+				used_parent_storeys = new List<StoreyFieldPair> ();
+			else if (used_parent_storeys.Exists (i => i.Storey == storey))
+				return;
+
+			TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
+			Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
+			used_parent_storeys.Add (new StoreyFieldPair (storey, f));
+		}
+
+		public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
+		{
+			if (this is StateMachine) {
+				if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
+					ec.CurrentBlock.Explicit.HasCapturedVariable = true;
+			} else {
+				ec.CurrentBlock.Explicit.HasCapturedVariable = true;
+			}
+
+			var hoisted = localVariable.HoistedVariant;
+			if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
+				//
+				// Variable is already hoisted but we need it in storey which can be shared
+				//
+				hoisted.Storey.hoisted_locals.Remove (hoisted);
+				hoisted.Storey.Members.Remove (hoisted.Field);
+				hoisted = null;
+			}
+
+			if (hoisted == null) {
+				hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
+				localVariable.HoistedVariant = hoisted;
+
+				if (hoisted_locals == null)
+					hoisted_locals = new List<HoistedVariable> ();
+
+				hoisted_locals.Add (hoisted);
+			}
+
+			if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit && !(hoisted.Storey is StateMachine))
+				hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
+		}
+
+		public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
+		{
+			if (!(this is StateMachine)) {
+				ec.CurrentBlock.Explicit.HasCapturedVariable = true;
+			}
+
+			var hoisted = parameterInfo.Parameter.HoistedVariant;
+
+			if (parameterInfo.Block.StateMachine != null) {
+				//
+				// Another storey in same block exists but state machine does not
+				// have parameter captured. We need to add it there as well to
+				// proxy parameter value correctly.
+				//
+				if (hoisted == null && parameterInfo.Block.StateMachine != this) {
+					var storey = parameterInfo.Block.StateMachine;
+
+					hoisted = new HoistedParameter (storey, parameterReference);
+					parameterInfo.Parameter.HoistedVariant = hoisted;
+
+					if (storey.hoisted_params == null)
+						storey.hoisted_params = new List<HoistedParameter> ();
+
+					storey.hoisted_params.Add (hoisted);
+				}
+
+				//
+				// Lift captured parameter from value type storey to reference type one. Otherwise
+				// any side effects would be done on a copy
+				//
+				if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
+					if (hoisted_local_params == null)
+						hoisted_local_params = new List<HoistedParameter> ();
+
+					hoisted_local_params.Add (hoisted);
+					hoisted = null;
+				}
+			}
+
+			if (hoisted == null) {
+				hoisted = new HoistedParameter (this, parameterReference);
+				parameterInfo.Parameter.HoistedVariant = hoisted;
+
+				if (hoisted_params == null)
+					hoisted_params = new List<HoistedParameter> ();
+
+				hoisted_params.Add (hoisted);
+			}
+
+			//
+			// Register link between current block and parameter storey. It will
+			// be used when setting up storey definition to deploy storey reference
+			// when parameters are used from multiple blocks
+			//
+			if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
+				hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
+			}
+		}
+
+		TypeExpr CreateStoreyTypeExpression (EmitContext ec)
+		{
+			//
+			// Create an instance of storey type
+			//
+			TypeExpr storey_type_expr;
+			if (CurrentTypeParameters != null) {
+				//
+				// Use current method type parameter (MVAR) for top level storey only. All
+				// nested storeys use class type parameter (VAR)
+				//
+				var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
+					ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
+					ec.CurrentTypeParameters;
+
+				TypeArguments targs = new TypeArguments ();
+
+				//
+				// Use type parameter name instead of resolved type parameter
+				// specification to resolve to correctly nested type parameters
+				//
+				for (int i = 0; i < tparams.Count; ++i)
+					targs.Add (new SimpleName (tparams [i].Name, Location)); //  new TypeParameterExpr (tparams[i], Location));
+
+				storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
+			} else {
+				storey_type_expr = new TypeExpression (CurrentType, Location);
+			}
+
+			return storey_type_expr;
+		}
+
+		public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
+		{
+			Parent = parentStorey;
+			spec.IsGeneric = false;
+			spec.DeclaringType = parentStorey.CurrentType;
+			MemberName.TypeParameters = null;
+		}
+
+		protected override bool DoResolveTypeParameters ()
+		{
+			// Although any storey can have type parameters they are all clones of method type
+			// parameters therefore have to mutate MVAR references in any of cloned constraints
+			if (CurrentTypeParameters != null) {
+				for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+					var spec = CurrentTypeParameters[i].Type;
+					spec.BaseType = mutator.Mutate (spec.BaseType);
+					if (spec.InterfacesDefined != null) {
+						var mutated = new TypeSpec[spec.InterfacesDefined.Length];
+						for (int ii = 0; ii < mutated.Length; ++ii) {
+							mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
+						}
+
+						spec.InterfacesDefined = mutated;
+					}
+
+					if (spec.TypeArguments != null) {
+						spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
+					}
+				}
+			}
+
+			//
+			// Update parent cache as we most likely passed the point
+			// where the cache was constructed
+			//
+			Parent.CurrentType.MemberCache.AddMember (this.spec);
+
+			return true;
+		}
+
+		//
+		// Initializes all hoisted variables
+		//
+		public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
+		{
+			// There can be only one instance variable for each storey type
+			if (Instance != null)
+				throw new InternalErrorException ();
+
+			//
+			// Create an instance of this storey
+			//
+			ResolveContext rc = new ResolveContext (ec.MemberContext);
+			rc.CurrentBlock = block;
+
+			var storey_type_expr = CreateStoreyTypeExpression (ec);
+			var source = new New (storey_type_expr, null, Location).Resolve (rc);
+
+			//
+			// When the current context is async (or iterator) lift local storey
+			// instantiation to the currect storey
+			//
+			if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
+				//
+				// Unfortunately, normal capture mechanism could not be used because we are
+				// too late in the pipeline and standart assign cannot be used either due to
+				// recursive nature of GetStoreyInstanceExpression
+				//
+				var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
+					LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
+
+				field.Define ();
+				field.Emit ();
+
+				var fexpr = new FieldExpr (field, Location);
+				fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
+				fexpr.EmitAssign (ec, source, false, false);
+				Instance = fexpr;
+			} else {
+				var local = TemporaryVariableReference.Create (source.Type, block, Location);
+				if (source.Type.IsStruct) {
+					local.LocalInfo.CreateBuilder (ec);
+				} else {
+					local.EmitAssign (ec, source);
+				}
+
+				Instance = local;
+			}
+
+			EmitHoistedFieldsInitialization (rc, ec);
+
+			// TODO: Implement properly
+			//SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
+		}
+
+		void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
+		{
+			//
+			// Initialize all storey reference fields by using local or hoisted variables
+			//
+			if (used_parent_storeys != null) {
+				foreach (StoreyFieldPair sf in used_parent_storeys) {
+					//
+					// Get instance expression of storey field
+					//
+					Expression instace_expr = GetStoreyInstanceExpression (ec);
+					var fs = sf.Field.Spec;
+					if (TypeManager.IsGenericType (instace_expr.Type))
+						fs = MemberCache.GetMember (instace_expr.Type, fs);
+
+					FieldExpr f_set_expr = new FieldExpr (fs, Location);
+					f_set_expr.InstanceExpression = instace_expr;
+
+					// TODO: CompilerAssign expression
+					SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
+					if (a.Resolve (rc) != null)
+						a.EmitStatement (ec);
+				}
+			}
+
+			//
+			// Initialize hoisted `this' only once, everywhere else will be
+			// referenced indirectly
+			//
+			if (initialize_hoisted_this) {
+				rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this, hoisted_this_parent));
+			}
+
+			//
+			// Setting currect anonymous method to null blocks any further variable hoisting
+			//
+			AnonymousExpression ae = ec.CurrentAnonymousMethod;
+			ec.CurrentAnonymousMethod = null;
+
+			if (hoisted_params != null) {
+				EmitHoistedParameters (ec, hoisted_params);
+			}
+
+			ec.CurrentAnonymousMethod = ae;
+		}
+
+		protected virtual void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
+		{
+			foreach (HoistedParameter hp in hoisted) {
+				if (hp == null)
+					continue;
+
+				//
+				// Parameters could be proxied via local fields for value type storey
+				//
+				if (hoisted_local_params != null) {
+					var local_param = hoisted_local_params.Find (l => l.Parameter.Parameter == hp.Parameter.Parameter);
+					var source = new FieldExpr (local_param.Field, Location);
+					source.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
+					hp.EmitAssign (ec, source, false, false);
+					continue;
+				}
+
+				hp.EmitHoistingAssignment (ec);
+			}
+		}
+
+		//
+		// Returns a field which holds referenced storey instance
+		//
+		Field GetReferencedStoreyField (AnonymousMethodStorey storey)
+		{
+			if (used_parent_storeys == null)
+				return null;
+
+			foreach (StoreyFieldPair sf in used_parent_storeys) {
+				if (sf.Storey == storey)
+					return sf.Field;
+			}
+
+			return null;
+		}
+
+		//
+		// Creates storey instance expression regardless of currect IP
+		//
+		public Expression GetStoreyInstanceExpression (EmitContext ec)
+		{
+			AnonymousExpression am = ec.CurrentAnonymousMethod;
+
+			//
+			// Access from original block -> storey
+			//
+			if (am == null)
+				return Instance;
+
+			//
+			// Access from anonymous method implemented as a static -> storey
+			//
+			if (am.Storey == null)
+				return Instance;
+
+			Field f = am.Storey.GetReferencedStoreyField (this);
+			if (f == null) {
+				if (am.Storey == this) {
+					//
+					// Access from inside of same storey (S -> S)
+					//
+					return new CompilerGeneratedThis (CurrentType, Location);
+				}
+
+				//
+				// External field access
+				//
+				return Instance;
+			}
+
+			//
+			// Storey was cached to local field
+			//
+			FieldExpr f_ind = new FieldExpr (f, Location);
+			f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
+			return f_ind;
+		}
+
+		protected virtual string GetVariableMangledName (LocalVariable local_info)
+		{
+			//
+			// No need to mangle anonymous method hoisted variables cause they
+			// are hoisted in their own scopes
+			//
+			return local_info.Name;
+		}
+
+		public HoistedThis HoistedThis {
+			get {
+				return hoisted_this;
+			}
+			set {
+				hoisted_this = value;
+			}
+		}
+
+		public IList<ExplicitBlock> ReferencesFromChildrenBlock {
+			get { return children_references; }
+		}
+	}
+
+	public abstract class HoistedVariable
+	{
+		//
+		// Hoisted version of variable references used in expression
+		// tree has to be delayed until we know its location. The variable
+		// doesn't know its location until all stories are calculated
+		//
+		class ExpressionTreeVariableReference : Expression
+		{
+			readonly HoistedVariable hv;
+
+			public ExpressionTreeVariableReference (HoistedVariable hv)
+			{
+				this.hv = hv;
+			}
+
+			public override bool ContainsEmitWithAwait ()
+			{
+				return false;
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				return hv.CreateExpressionTree ();
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				eclass = ExprClass.Value;
+				type = ec.Module.PredefinedTypes.Expression.Resolve ();
+				return this;
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				ResolveContext rc = new ResolveContext (ec.MemberContext);
+				Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc, false);
+				// This should never fail
+				e = e.Resolve (rc);
+				if (e != null)
+					e.Emit (ec);
+			}
+		}
+	
+		protected readonly AnonymousMethodStorey storey;
+		protected Field field;
+		Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
+		FieldExpr cached_outer_access;
+
+		protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
+			: this (storey, storey.AddCapturedVariable (name, type))
+		{
+		}
+
+		protected HoistedVariable (AnonymousMethodStorey storey, Field field)
+		{
+			this.storey = storey;
+			this.field = field;
+		}
+
+		public Field Field {
+			get {
+				return field;
+			}
+		}
+
+		public AnonymousMethodStorey Storey {
+			get {
+				return storey;
+			}
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			GetFieldExpression (ec).AddressOf (ec, mode);
+		}
+
+		public Expression CreateExpressionTree ()
+		{
+			return new ExpressionTreeVariableReference (this);
+		}
+
+		public void Emit (EmitContext ec)
+		{
+			GetFieldExpression (ec).Emit (ec);
+		}
+
+		public Expression EmitToField (EmitContext ec)
+		{
+			return GetFieldExpression (ec);
+		}
+
+		//
+		// Creates field access expression for hoisted variable
+		//
+		protected virtual FieldExpr GetFieldExpression (EmitContext ec)
+		{
+			if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
+				if (cached_outer_access != null)
+					return cached_outer_access;
+
+				//
+				// When setting top-level hoisted variable in generic storey
+				// change storey generic types to method generic types (VAR -> MVAR)
+				//
+				if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
+					var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
+					cached_outer_access = new FieldExpr (fs, field.Location);
+				} else {
+					cached_outer_access = new FieldExpr (field, field.Location);
+				}
+
+				cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
+				return cached_outer_access;
+			}
+
+			FieldExpr inner_access;
+			if (cached_inner_access != null) {
+				if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
+					inner_access = null;
+			} else {
+				inner_access = null;
+				cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
+			}
+
+			if (inner_access == null) {
+				if (field.Parent.IsGenericOrParentIsGeneric) {
+					var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
+					inner_access = new FieldExpr (fs, field.Location);
+				} else {
+					inner_access = new FieldExpr (field, field.Location);
+				}
+
+				inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
+				cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
+			}
+
+			return inner_access;
+		}
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			GetFieldExpression (ec).Emit (ec, leave_copy);
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
+		}
+	}
+
+	public class HoistedParameter : HoistedVariable
+	{
+		sealed class HoistedFieldAssign : CompilerAssign
+		{
+			public HoistedFieldAssign (Expression target, Expression source)
+				: base (target, source, target.Location)
+			{
+			}
+
+			protected override Expression ResolveConversions (ResolveContext ec)
+			{
+				//
+				// Implicit conversion check fails for hoisted type arguments
+				// as they are of different types (!!0 x !0)
+				//
+				return this;
+			}
+		}
+
+		readonly ParameterReference parameter;
+
+		public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
+			: base (scope, par.Name, par.Type)
+		{
+			this.parameter = par;
+		}
+
+		public HoistedParameter (HoistedParameter hp, string name)
+			: base (hp.storey, name, hp.parameter.Type)
+		{
+			this.parameter = hp.parameter;
+		}
+
+		#region Properties
+
+		public bool IsAssigned { get; set; }
+
+		public ParameterReference Parameter {
+			get {
+				return parameter;
+			}
+		}
+
+		#endregion
+
+		public void EmitHoistingAssignment (EmitContext ec)
+		{
+			//
+			// Remove hoisted redirection to emit assignment from original parameter
+			//
+			var temp = parameter.Parameter.HoistedVariant;
+			parameter.Parameter.HoistedVariant = null;
+
+			var a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
+			a.EmitStatement (ec);
+
+			parameter.Parameter.HoistedVariant = temp;
+		}
+	}
+
+	class HoistedLocalVariable : HoistedVariable
+	{
+		public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
+			: base (storey, name, local.Type)
+		{
+		}
+	}
+
+	public class HoistedThis : HoistedVariable
+	{
+		public HoistedThis (AnonymousMethodStorey storey, Field field)
+			: base (storey, field)
+		{
+		}
+	}
+
+	//
+	// Anonymous method expression as created by parser
+	//
+	public class AnonymousMethodExpression : Expression
+	{
+		//
+		// Special conversion for nested expression tree lambdas
+		//
+		class Quote : ShimExpression
+		{
+			public Quote (Expression expr)
+				: base (expr)
+			{
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				var args = new Arguments (1);
+				args.Add (new Argument (expr.CreateExpressionTree (ec)));
+				return CreateExpressionFactoryCall (ec, "Quote", args);
+			}
+
+			protected override Expression DoResolve (ResolveContext rc)
+			{
+				expr = expr.Resolve (rc);
+				if (expr == null)
+					return null;
+
+				eclass = expr.eclass;
+				type = expr.Type;
+				return this;
+			}
+		}
+
+		readonly Dictionary<TypeSpec, Expression> compatibles;
+
+		public ParametersBlock Block;
+
+		public AnonymousMethodExpression (Location loc)
+		{
+			this.loc = loc;
+			this.compatibles = new Dictionary<TypeSpec, Expression> ();
+		}
+
+		#region Properties
+
+		public override string ExprClassName {
+			get {
+				return "anonymous method";
+			}
+		}
+
+		public virtual bool HasExplicitParameters {
+			get {
+				return Parameters != ParametersCompiled.Undefined;
+			}
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		public ParametersCompiled Parameters {
+			get {
+				return Block.Parameters;
+			}
+		}
+
+		public bool IsAsync {
+			get;
+			internal set;
+		}
+
+		public ReportPrinter TypeInferenceReportPrinter {
+			get; set;
+		}
+
+		#endregion
+
+		//
+		// Returns true if the body of lambda expression can be implicitly
+		// converted to the delegate of type `delegate_type'
+		//
+		public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
+		{
+			using (ec.With (ResolveContext.Options.InferReturnType, false)) {
+				using (ec.Set (ResolveContext.Options.ProbingMode)) {
+					var prev = ec.Report.SetPrinter (TypeInferenceReportPrinter ?? new NullReportPrinter ());
+
+					var res = Compatible (ec, delegate_type) != null;
+
+					ec.Report.SetPrinter (prev);
+
+					return res;
+				}
+			}
+		}
+
+		TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
+		{
+			if (delegate_type.IsDelegate)
+				return delegate_type;
+
+			if (delegate_type.IsExpressionTreeType) {
+				delegate_type = delegate_type.TypeArguments [0];
+				if (delegate_type.IsDelegate)
+					return delegate_type;
+
+				ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
+					GetSignatureForError (), delegate_type.GetSignatureForError ());
+				return null;
+			}
+
+			ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
+				      GetSignatureForError (), delegate_type.GetSignatureForError ());
+			return null;
+		}
+
+		protected bool VerifyExplicitParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type, AParametersCollection parameters)
+		{
+			if (VerifyParameterCompatibility (ec, tic, delegate_type, parameters, ec.IsInProbingMode))
+				return true;
+
+			if (!ec.IsInProbingMode)
+				ec.Report.Error (1661, loc,
+					"Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
+					GetSignatureForError (), delegate_type.GetSignatureForError ());
+
+			return false;
+		}
+
+		protected bool VerifyParameterCompatibility (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
+		{
+			if (Parameters.Count != invoke_pd.Count) {
+				if (ignore_errors)
+					return false;
+				
+				ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
+					      delegate_type.GetSignatureForError (), Parameters.Count.ToString ());
+				return false;
+			}
+
+			bool has_implicit_parameters = !HasExplicitParameters;
+			bool error = false;
+
+			for (int i = 0; i < Parameters.Count; ++i) {
+				Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
+				if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
+					if (ignore_errors)
+						return false;
+					
+					if (p_mod == Parameter.Modifier.NONE)
+						ec.Report.Error (1677, Parameters[i].Location, "Parameter `{0}' should not be declared with the `{1}' keyword",
+							      (i + 1).ToString (), Parameter.GetModifierSignature (Parameters [i].ModFlags));
+					else
+						ec.Report.Error (1676, Parameters[i].Location, "Parameter `{0}' must be declared with the `{1}' keyword",
+							      (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
+					error = true;
+				}
+
+				if (has_implicit_parameters)
+					continue;
+
+				TypeSpec type = invoke_pd.Types [i];
+
+				if (tic != null)
+					type = tic.InflateGenericArgument (ec, type);
+				
+				if (!TypeSpecComparer.IsEqual (type, Parameters.Types [i])) {
+					if (ignore_errors)
+						return false;
+					
+					ec.Report.Error (1678, Parameters [i].Location, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
+						      (i+1).ToString (),
+						      Parameters.Types [i].GetSignatureForError (),
+						      invoke_pd.Types [i].GetSignatureForError ());
+					error = true;
+				}
+			}
+
+			return !error;
+		}
+
+		//
+		// Infers type arguments based on explicit arguments
+		//
+		public bool ExplicitTypeInference (TypeInferenceContext type_inference, TypeSpec delegate_type)
+		{
+			if (!HasExplicitParameters)
+				return false;
+
+			if (!delegate_type.IsDelegate) {
+				if (!delegate_type.IsExpressionTreeType)
+					return false;
+
+				delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
+				if (!delegate_type.IsDelegate)
+					return false;
+			}
+			
+			AParametersCollection d_params = Delegate.GetParameters (delegate_type);
+			if (d_params.Count != Parameters.Count)
+				return false;
+
+			var ptypes = Parameters.Types;
+			var dtypes = d_params.Types;
+			for (int i = 0; i < Parameters.Count; ++i) {
+				if (type_inference.ExactInference (ptypes[i], dtypes[i]) == 0) {
+					//
+					// Continue when 0 (quick path) does not mean inference failure. Checking for
+					// same type handles cases like int -> int
+					//
+					if (ptypes[i] == dtypes[i])
+						continue;
+
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
+		{
+			Expression expr;
+			AnonymousExpression am;
+
+			if (compatibles.TryGetValue (delegate_type, out expr)) {
+				am = expr as AnonymousExpression;
+				return am == null ? null : am.ReturnType;
+			}
+
+			using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
+				ReportPrinter prev;
+				if (TypeInferenceReportPrinter != null) {
+					prev = ec.Report.SetPrinter (TypeInferenceReportPrinter);
+				} else {
+					prev = null;
+				}
+
+				var body = CompatibleMethodBody (ec, tic, null, delegate_type);
+				if (body != null) {
+					am = body.Compatible (ec, body);
+				} else {
+					am = null;
+				}
+
+				if (TypeInferenceReportPrinter != null) {
+					ec.Report.SetPrinter (prev);
+				}
+			}
+
+			if (am == null)
+				return null;
+
+//			compatibles.Add (delegate_type, am);
+			return am.ReturnType;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		//
+		// Returns AnonymousMethod container if this anonymous method
+		// expression can be implicitly converted to the delegate type `delegate_type'
+		//
+		public Expression Compatible (ResolveContext ec, TypeSpec type)
+		{
+			Expression am;
+			if (compatibles.TryGetValue (type, out am))
+				return am;
+
+			TypeSpec delegate_type = CompatibleChecks (ec, type);
+			if (delegate_type == null)
+				return null;
+
+			//
+			// At this point its the first time we know the return type that is 
+			// needed for the anonymous method.  We create the method here.
+			//
+
+			var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
+			TypeSpec return_type = invoke_mb.ReturnType;
+
+			//
+			// Second: the return type of the delegate must be compatible with 
+			// the anonymous type.   Instead of doing a pass to examine the block
+			// we satisfy the rule by setting the return type on the EmitContext
+			// to be the delegate type return type.
+			//
+
+			var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
+			if (body == null)
+				return null;
+
+			bool etree_conversion = delegate_type != type;
+
+			try {
+				if (etree_conversion) {
+					if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
+						//
+						// Nested expression tree lambda use same scope as parent
+						// lambda, this also means no variable capturing between this
+						// and parent scope
+						//
+						am = body.Compatible (ec, ec.CurrentAnonymousMethod);
+
+						//
+						// Quote nested expression tree
+						//
+						if (am != null)
+							am = new Quote (am);
+					} else {
+						int errors = ec.Report.Errors;
+
+						if (Block.IsAsync) {
+							ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
+						}
+
+						using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
+							am = body.Compatible (ec);
+						}
+
+						//
+						// Rewrite expressions into expression tree when targeting Expression<T>
+						//
+						if (am != null && errors == ec.Report.Errors)
+							am = CreateExpressionTree (ec, delegate_type);
+					}
+				} else {
+					am = body.Compatible (ec);
+
+					if (body.DirectMethodGroupConversion != null) {
+						var errors_printer = new SessionReportPrinter ();
+						var old = ec.Report.SetPrinter (errors_printer);
+						var expr = new ImplicitDelegateCreation (delegate_type, body.DirectMethodGroupConversion, loc) {
+							AllowSpecialMethodsInvocation = true
+						}.Resolve (ec);
+						ec.Report.SetPrinter (old);
+						if (expr != null && errors_printer.ErrorsCount == 0)
+							am = expr;
+					}
+				}
+			} catch (CompletionResult) {
+				throw;
+			} catch (FatalException) {
+				throw;
+			} catch (Exception e) {
+				throw new InternalErrorException (e, loc);
+			}
+
+			if (!ec.IsInProbingMode && !etree_conversion) {
+				compatibles.Add (type, am ?? EmptyExpression.Null);
+			}
+
+			return am;
+		}
+
+		protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
+		{
+			return CreateExpressionTree (ec);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
+			return null;
+		}
+
+		protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
+		{
+			var delegate_parameters = Delegate.GetParameters (delegate_type);
+
+			if (Parameters == ParametersCompiled.Undefined) {
+				//
+				// We provide a set of inaccessible parameters
+				//
+				Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
+
+				for (int i = 0; i < delegate_parameters.Count; i++) {
+					Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
+					if ((i_mod & Parameter.Modifier.OUT) != 0) {
+						if (!ec.IsInProbingMode) {
+							ec.Report.Error (1688, loc,
+								"Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
+								delegate_type.GetSignatureForError ());
+						}
+
+						return null;
+					}
+					fixedpars[i] = new Parameter (
+						new TypeExpression (delegate_parameters.Types [i], loc), null,
+						delegate_parameters.FixedParameters [i].ModFlags, null, loc);
+				}
+
+				return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
+			}
+
+			if (!VerifyExplicitParameters (ec, tic, delegate_type, delegate_parameters)) {
+				return null;
+			}
+
+			return Parameters;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			if (rc.HasSet (ResolveContext.Options.ConstantScope)) {
+				rc.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
+				return null;
+			}
+
+			//
+			// Update top-level block generated duting parsing with actual top-level block
+			//
+			if (rc.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer) && rc.CurrentMemberDefinition.Parent.PartialContainer.PrimaryConstructorParameters != null) {
+				var tb = rc.ConstructorBlock.ParametersBlock.TopBlock;
+				if (Block.TopBlock != tb) {
+					Block b = Block;
+					while (b.Parent != Block.TopBlock && b != Block.TopBlock)
+						b = b.Parent;
+
+					b.Parent = tb;
+					tb.IncludeBlock (Block, Block.TopBlock);
+					b.ParametersBlock.TopBlock = tb;
+				}
+			}
+
+			eclass = ExprClass.Value;
+
+			//
+			// This hack means `The type is not accessible
+			// anywhere', we depend on special conversion
+			// rules.
+			// 
+			type = InternalType.AnonymousMethod;
+
+			if (!DoResolveParameters (rc))
+				return null;
+
+			return this;
+		}
+
+		protected virtual bool DoResolveParameters (ResolveContext rc)
+		{
+			return Parameters.Resolve (rc);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// nothing, as we only exist to not do anything.
+		}
+
+		public static void Error_AddressOfCapturedVar (ResolveContext rc, IVariableReference var, Location loc)
+		{
+			if (rc.CurrentAnonymousMethod is AsyncInitializer)
+				return;
+
+			rc.Report.Error (1686, loc,
+				"Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
+				var.Name);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return ExprClassName;
+		}
+
+		AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
+		{
+			ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
+			if (p == null)
+				return null;
+
+			ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
+
+			if (b.IsAsync) {
+				var rt = return_type;
+				if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
+					ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
+						GetSignatureForError (), delegate_type.GetSignatureForError ());
+
+					return null;
+				}
+
+				b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, delegate_type, loc);
+			}
+
+			return CompatibleMethodFactory (return_type ?? InternalType.ErrorType, delegate_type, p, b);
+		}
+
+		protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
+		{
+			return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			AnonymousMethodExpression target = (AnonymousMethodExpression) t;
+
+			target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// Abstract expression for any block which requires variables hoisting
+	//
+	public abstract class AnonymousExpression : ExpressionStatement
+	{
+		protected class AnonymousMethodMethod : Method
+		{
+			public readonly AnonymousExpression AnonymousMethod;
+			public readonly AnonymousMethodStorey Storey;
+
+			public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
+							  TypeExpr return_type,
+							  Modifiers mod, MemberName name,
+							  ParametersCompiled parameters)
+				: base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
+						name, parameters, null)
+			{
+				this.AnonymousMethod = am;
+				this.Storey = storey;
+
+				Parent.PartialContainer.Members.Add (this);
+				Block = new ToplevelBlock (am.block, parameters);
+			}
+
+			public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
+			{
+				EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
+				ec.CurrentAnonymousMethod = AnonymousMethod;
+				return ec;
+			}
+
+			protected override void DefineTypeParameters ()
+			{
+				// Type parameters were cloned
+			}
+
+			protected override bool ResolveMemberType ()
+			{
+				if (!base.ResolveMemberType ())
+					return false;
+
+				if (Storey != null && Storey.Mutator != null) {
+					if (!parameters.IsEmpty) {
+						var mutated = Storey.Mutator.Mutate (parameters.Types);
+						if (mutated != parameters.Types)
+							parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
+					}
+
+					member_type = Storey.Mutator.Mutate (member_type);
+				}
+
+				return true;
+			}
+
+			public override void Emit ()
+			{
+				if (MethodBuilder == null) {
+					Define ();
+				}
+
+				base.Emit ();
+			}
+		}
+
+		protected readonly ParametersBlock block;
+
+		public TypeSpec ReturnType;
+
+		protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
+		{
+			this.ReturnType = return_type;
+			this.block = block;
+			this.loc = loc;
+		}
+
+		public abstract string ContainerType { get; }
+		public abstract bool IsIterator { get; }
+		public abstract AnonymousMethodStorey Storey { get; }
+
+		//
+		// The block that makes up the body for the anonymous method
+		//
+		public ParametersBlock Block {
+			get {
+				return block;
+			}
+		}
+
+		public AnonymousExpression Compatible (ResolveContext ec)
+		{
+			return Compatible (ec, this);
+		}
+
+		public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
+		{
+			if (block.Resolved)
+				return this;
+
+			// TODO: Implement clone
+			BlockContext aec = new BlockContext (ec, block, ReturnType);
+			aec.CurrentAnonymousMethod = ae;
+
+			var am = this as AnonymousMethodBody;
+
+			if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
+				am.ReturnTypeInference = new TypeInferenceContext ();
+			}
+
+			var bc = ec as BlockContext;
+
+			if (bc != null) {
+				aec.AssignmentInfoOffset = bc.AssignmentInfoOffset;
+				aec.EnclosingLoop = bc.EnclosingLoop;
+				aec.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
+				aec.Switch = bc.Switch;
+			}
+
+			var errors = ec.Report.Errors;
+
+			bool res = Block.Resolve (aec);
+
+			if (res && errors == ec.Report.Errors) {
+				MarkReachable (new Reachability ());
+
+				if (!CheckReachableExit (ec.Report)) {
+					return null;
+				}
+
+				if (bc != null)
+					bc.AssignmentInfoOffset = aec.AssignmentInfoOffset;
+			}
+
+			if (am != null && am.ReturnTypeInference != null) {
+				am.ReturnTypeInference.FixAllTypes (ec);
+				ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
+				am.ReturnTypeInference = null;
+
+				//
+				// If e is synchronous the inferred return type is T
+				// If e is asynchronous and the body of F is either an expression classified as nothing
+				// or a statement block where no return statements have expressions, the inferred return type is Task
+				// If e is async and has an inferred result type T, the inferred return type is Task<T>
+				//
+				if (block.IsAsync && ReturnType != null) {
+					ReturnType = ReturnType.Kind == MemberKind.Void ?
+						ec.Module.PredefinedTypes.Task.TypeSpec :
+						ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
+				}
+			}
+
+			if (res && errors != ec.Report.Errors)
+				return null;
+
+			return res ? this : null;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		bool CheckReachableExit (Report report)
+		{
+			if (block.HasReachableClosingBrace && ReturnType.Kind != MemberKind.Void) {
+				// FIXME: Flow-analysis on MoveNext generated code
+				if (!IsIterator) {
+					report.Error (1643, StartLocation,
+							"Not all code paths return a value in anonymous method of type `{0}'", GetSignatureForError ());
+
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			// We are reachable, mark block body reachable too
+			MarkReachable (new Reachability ());
+
+			CheckReachableExit (fc.Report);
+
+			var das = fc.BranchDefiniteAssignment ();
+			var prev_pb = fc.ParametersBlock;
+			fc.ParametersBlock = Block;
+			var da_ontrue = fc.DefiniteAssignmentOnTrue;
+			var da_onfalse = fc.DefiniteAssignmentOnFalse;
+
+			fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = null;
+			block.FlowAnalysis (fc);
+
+			fc.ParametersBlock = prev_pb;
+			fc.DefiniteAssignment = das;
+			fc.DefiniteAssignmentOnTrue = da_ontrue;
+			fc.DefiniteAssignmentOnFalse = da_onfalse;
+		}
+
+		public override void MarkReachable (Reachability rc)
+		{
+			block.MarkReachable (rc);
+		}
+
+		public void SetHasThisAccess ()
+		{
+			ExplicitBlock b = block;
+			do {
+				if (b.HasCapturedThis)
+					return;
+
+				b.HasCapturedThis = true;
+				b = b.Parent == null ? null : b.Parent.Explicit;
+			} while (b != null);
+		}
+	}
+
+	public class AnonymousMethodBody : AnonymousExpression
+	{
+		protected readonly ParametersCompiled parameters;
+		AnonymousMethodStorey storey;
+
+		AnonymousMethodMethod method;
+		Field am_cache;
+		string block_name;
+		TypeInferenceContext return_inference;
+
+		public AnonymousMethodBody (ParametersCompiled parameters,
+					ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
+					Location loc)
+			: base (block, return_type, loc)
+		{
+			this.type = delegate_type;
+			this.parameters = parameters;
+		}
+
+		#region Properties
+
+		public override string ContainerType {
+			get { return "anonymous method"; }
+		}
+
+		//
+		// Method-group instance for lambdas which can be replaced with
+		// simple method group call
+		//
+		public MethodGroupExpr DirectMethodGroupConversion {
+			get; set;
+		}
+
+		public override bool IsIterator {
+			get {
+				return false;
+			}
+		}
+
+		public ParametersCompiled Parameters {
+			get {
+				return parameters;
+			}
+		}
+
+		public TypeInferenceContext ReturnTypeInference {
+			get {
+				return return_inference;
+			}
+			set {
+				return_inference = value;
+			}
+		}
+
+		public override AnonymousMethodStorey Storey {
+			get {
+				return storey;
+			}
+		}
+
+		#endregion
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
+			return null;
+		}
+
+		bool Define (ResolveContext ec)
+		{
+			if (!Block.Resolved && Compatible (ec) == null)
+				return false;
+
+			if (block_name == null) {
+				MemberCore mc = (MemberCore) ec.MemberContext;
+				block_name = mc.MemberName.Basename;
+			}
+
+			return true;
+		}
+
+		//
+		// Creates a host for the anonymous method
+		//
+		AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
+		{
+			//
+			// Anonymous method body can be converted to
+			//
+			// 1, an instance method in current scope when only `this' is hoisted
+			// 2, a static method in current scope when neither `this' nor any variable is hoisted
+			// 3, an instance method in compiler generated storey when any hoisted variable exists
+			//
+
+			Modifiers modifiers;
+			TypeDefinition parent = null;
+			TypeParameters hoisted_tparams = null;
+			ParametersCompiled method_parameters = parameters;
+
+			var src_block = Block.Original.Explicit;
+			if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
+				parent = storey = FindBestMethodStorey ();
+
+				if (storey == null) {
+					var top_block = src_block.ParametersBlock.TopBlock;
+					var sm = top_block.StateMachine;
+
+					if (src_block.HasCapturedThis) {
+						//
+						// Remove hoisted 'this' request when simple instance method is
+						// enough. No hoisted variables only 'this' and don't need to
+						// propagate this to value type state machine.
+						//
+						StateMachine sm_parent;
+						var pb = src_block.ParametersBlock;
+						do {
+							sm_parent = pb.StateMachine;
+							pb = pb.Parent == null ? null : pb.Parent.ParametersBlock;
+						} while (sm_parent == null && pb != null);
+
+						if (sm_parent == null) {
+							top_block.RemoveThisReferenceFromChildrenBlock (src_block);
+						} else if (sm_parent.Kind == MemberKind.Struct) {
+							//
+							// Special case where parent class is used to emit instance method
+							// because currect storey is of value type (async host) and we cannot
+							// use ldftn on non-boxed instances either to share mutated state
+							//
+							parent = sm_parent.Parent.PartialContainer;
+							hoisted_tparams = sm_parent.OriginalTypeParameters;
+						} else if (sm is IteratorStorey) {
+							//
+							// For iterators we can host everything in one class
+							//
+							parent = storey = sm;
+						}
+					}
+				}
+
+				modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+			} else {
+				if (ec.CurrentAnonymousMethod != null)
+					parent = storey = ec.CurrentAnonymousMethod.Storey;
+
+				modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
+
+				//
+				// Convert generated method to closed delegate method where unused
+				// this argument is generated during compilation which speeds up dispatch
+				// by about 25%
+				//
+				method_parameters = ParametersCompiled.Prefix (method_parameters,
+					new Parameter (null, null, 0, null, loc), ec.Module.Compiler.BuiltinTypes.Object);
+			}
+
+			if (storey == null && hoisted_tparams == null)
+				hoisted_tparams = ec.CurrentTypeParameters;
+
+			if (parent == null)
+				parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
+
+			string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
+				"m", null, parent.PartialContainer.CounterAnonymousMethods++);
+
+			MemberName member_name;
+			if (hoisted_tparams != null) {
+				var type_params = new TypeParameters (hoisted_tparams.Count);
+				for (int i = 0; i < hoisted_tparams.Count; ++i) {
+				    type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
+				}
+
+				member_name = new MemberName (name, type_params, Location);
+			} else {
+				member_name = new MemberName (name, Location);
+			}
+
+			return new AnonymousMethodMethod (parent,
+				this, storey, new TypeExpression (ReturnType, Location), modifiers,
+				member_name, method_parameters);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (!Define (ec))
+				return null;
+
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// Use same anonymous method implementation for scenarios where same
+			// code is used from multiple blocks, e.g. field initializers
+			//
+			if (method == null) {
+				//
+				// Delay an anonymous method definition to avoid emitting unused code
+				// for unreachable blocks or expression trees
+				//
+				method = DoCreateMethodHost (ec);
+				method.Define ();
+				method.PrepareEmit ();
+			}
+
+			bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
+			if (is_static && am_cache == null && !ec.IsStaticConstructor) {
+				//
+				// Creates a field cache to store delegate instance if it's not generic
+				//
+				if (!method.MemberName.IsGeneric) {
+					var parent = method.Parent.PartialContainer;
+					int id = parent.AnonymousMethodsCounter++;
+					var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
+
+					am_cache = new Field (parent, new TypeExpression (cache_type, loc),
+						Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
+						new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
+					am_cache.Define ();
+					parent.AddField (am_cache);
+				} else {
+					// TODO: Implement caching of generated generic static methods
+					//
+					// Idea:
+					//
+					// Some extra class is needed to capture variable generic type
+					// arguments. Maybe we could re-use anonymous types, with a unique
+					// anonymous method id, but they are quite heavy.
+					//
+					// Consider : "() => typeof(T);"
+					//
+					// We need something like
+					// static class Wrap<Tn, Tm, DelegateType> {
+					//		public static DelegateType cache;
+					// }
+					//
+					// We then specialize local variable to capture all generic parameters
+					// and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
+					//
+				}
+			}
+
+			Label l_initialized = ec.DefineLabel ();
+
+			if (am_cache != null) {
+				ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
+				ec.Emit (OpCodes.Brtrue_S, l_initialized);
+			}
+
+			//
+			// Load method delegate implementation
+			//
+
+			if (is_static) {
+				ec.EmitNull ();
+			} else if (storey != null) {
+				Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
+				if (e != null) {
+					e.Emit (ec);
+				}
+			} else {
+				ec.EmitThis ();
+
+				//
+				// Special case for value type storey where this is not lifted but
+				// droped off to parent class
+				//
+				if (ec.CurrentAnonymousMethod != null && ec.AsyncTaskStorey != null)
+					ec.Emit (OpCodes.Ldfld, ec.AsyncTaskStorey.HoistedThis.Field.Spec);
+			}
+
+			var delegate_method = method.Spec;
+			if (storey != null && storey.MemberName.IsGeneric) {
+				TypeSpec t = storey.Instance.Type;
+
+				//
+				// Mutate anonymous method instance type if we are in nested
+				// hoisted generic anonymous method storey
+				//
+				if (ec.IsAnonymousStoreyMutateRequired) {
+					t = storey.Mutator.Mutate (t);
+				}
+
+				ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
+			} else {
+				if (delegate_method.IsGeneric) {
+					TypeParameterSpec[] tparams;
+					var sm = ec.CurrentAnonymousMethod == null ? null : ec.CurrentAnonymousMethod.Storey as StateMachine;
+					if (sm != null && sm.OriginalTypeParameters != null) {
+						tparams = sm.CurrentTypeParameters.Types;
+					} else {
+						tparams = method.TypeParameters;
+					}
+
+					delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, tparams);
+				}
+
+				ec.Emit (OpCodes.Ldftn, delegate_method);
+			}
+
+			var constructor_method = Delegate.GetConstructor (type);
+			ec.Emit (OpCodes.Newobj, constructor_method);
+
+			if (am_cache != null) {
+				ec.Emit (OpCodes.Stsfld, am_cache.Spec);
+				ec.MarkLabel (l_initialized);
+				ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
+			}
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			throw new NotImplementedException ();
+		}
+
+		//
+		// Look for the best storey for this anonymous method
+		//
+		AnonymousMethodStorey FindBestMethodStorey ()
+		{
+			//
+			// Use the nearest parent block which has a storey
+			//
+			for (Block b = Block.Parent; b != null; b = b.Parent) {
+				AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
+				if (s != null)
+					return s;
+			}
+					
+			return null;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return type.GetSignatureForError ();
+		}
+	}
+
+	//
+	// Anonymous type container
+	//
+	public class AnonymousTypeClass : CompilerGeneratedContainer
+	{
+		public const string ClassNamePrefix = "<>__AnonType";
+		public const string SignatureForError = "anonymous type";
+		
+		readonly IList<AnonymousTypeParameter> parameters;
+
+		private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
+			: base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
+		{
+			this.parameters = parameters;
+		}
+
+		public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
+		{
+			string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
+
+			ParametersCompiled all_parameters;
+			TypeParameters tparams = null;
+			SimpleName[] t_args;
+
+			if (parameters.Count == 0) {
+				all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+				t_args = null;
+			} else {
+				t_args = new SimpleName[parameters.Count];
+				tparams = new TypeParameters ();
+				Parameter[] ctor_params = new Parameter[parameters.Count];
+				for (int i = 0; i < parameters.Count; ++i) {
+					AnonymousTypeParameter p = parameters[i];
+					for (int ii = 0; ii < i; ++ii) {
+						if (parameters[ii].Name == p.Name) {
+							parent.Compiler.Report.Error (833, parameters[ii].Location,
+								"`{0}': An anonymous type cannot have multiple properties with the same name",
+									p.Name);
+
+							p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
+							parameters[i] = p;
+							break;
+						}
+					}
+
+					t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
+					tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
+					ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
+				}
+
+				all_parameters = new ParametersCompiled (ctor_params);
+			}
+
+			//
+			// Create generic anonymous type host with generic arguments
+			// named upon properties names
+			//
+			AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
+
+			Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
+				null, all_parameters, loc);
+			c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
+
+			// 
+			// Create fields and constructor body with field initialization
+			//
+			bool error = false;
+			for (int i = 0; i < parameters.Count; ++i) {
+				AnonymousTypeParameter p = parameters [i];
+
+				Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
+					new MemberName ("<" + p.Name + ">", p.Location), null);
+
+				if (!a_type.AddField (f)) {
+					error = true;
+					continue;
+				}
+
+				c.Block.AddStatement (new StatementExpression (
+					new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
+						c.Block.GetParameterReference (i, p.Location))));
+
+				ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
+				get_block.AddStatement (new Return (
+					new MemberAccess (new This (p.Location), f.Name), p.Location));
+
+				Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
+					new MemberName (p.Name, p.Location), null);
+				prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
+				prop.Get.Block = get_block;
+				a_type.AddMember (prop);
+			}
+
+			if (error)
+				return null;
+
+			a_type.AddConstructor (c);
+			return a_type;
+		}
+		
+		protected override bool DoDefineMembers ()
+		{
+			if (!base.DoDefineMembers ())
+				return false;
+
+			Location loc = Location;
+
+			var equals_parameters = ParametersCompiled.CreateFullyResolved (
+				new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
+
+			Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
+				Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
+				equals_parameters, null);
+
+			equals_parameters[0].Resolve (equals, 0);
+
+			Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
+				Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
+				ParametersCompiled.EmptyReadOnlyParameters, null);
+
+			ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
+
+			TypeExpr current_type;
+			if (CurrentTypeParameters != null) {
+				var targs = new TypeArguments ();
+				for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+					targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
+				}
+
+				current_type = new GenericTypeExpr (Definition, targs, loc);
+			} else {
+				current_type = new TypeExpression (Definition, loc);
+			}
+
+			var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
+			equals_block.AddStatement (new BlockVariable (new TypeExpression (li_other.Type, loc), li_other));
+			var other_variable = new LocalVariableReference (li_other, loc);
+
+			MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
+				new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
+
+			Expression rs_equals = null;
+			Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
+			Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
+			for (int i = 0; i < parameters.Count; ++i) {
+				var p = parameters [i];
+				var f = (Field) Members [i * 2];
+
+				MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
+					system_collections_generic, "EqualityComparer",
+						new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
+						"Default", loc);
+
+				Arguments arguments_equal = new Arguments (2);
+				arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
+				arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
+
+				Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
+					"Equals", loc), arguments_equal);
+
+				Arguments arguments_hashcode = new Arguments (1);
+				arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
+				Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
+					"GetHashCode", loc), arguments_hashcode);
+
+				IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);				
+				rs_hashcode = new Binary (Binary.Operator.Multiply,
+					new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
+					FNV_prime);
+
+				Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
+					new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
+					new Invocation (new MemberAccess (
+						new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
+					new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
+
+				if (rs_equals == null) {
+					rs_equals = field_equal;
+					string_concat = new Binary (Binary.Operator.Addition,
+						string_concat,
+						new Binary (Binary.Operator.Addition,
+							new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
+							field_to_string));
+					continue;
+				}
+
+				//
+				// Implementation of ToString () body using string concatenation
+				//				
+				string_concat = new Binary (Binary.Operator.Addition,
+					new Binary (Binary.Operator.Addition,
+						string_concat,
+						new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc)),
+					field_to_string);
+
+				rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
+			}
+
+			string_concat = new Binary (Binary.Operator.Addition,
+				string_concat,
+				new StringConstant (Compiler.BuiltinTypes, " }", loc));
+
+			//
+			// Equals (object obj) override
+			//		
+			var other_variable_assign = new TemporaryVariableReference (li_other, loc);
+			equals_block.AddStatement (new StatementExpression (
+				new SimpleAssign (other_variable_assign,
+					new As (equals_block.GetParameterReference (0, loc),
+						current_type, loc), loc)));
+
+			Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
+			if (rs_equals != null)
+				equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
+			equals_block.AddStatement (new Return (equals_test, loc));
+
+			equals.Block = equals_block;
+			equals.Define ();
+			Members.Add (equals);
+
+			//
+			// GetHashCode () override
+			//
+			Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
+				Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
+				new MemberName ("GetHashCode", loc),
+				ParametersCompiled.EmptyReadOnlyParameters, null);
+
+			//
+			// Modified FNV with good avalanche behavior and uniform
+			// distribution with larger hash sizes.
+			//
+			// const int FNV_prime = 16777619;
+			// int hash = (int) 2166136261;
+			// foreach (int d in data)
+			//     hash = (hash ^ d) * FNV_prime;
+			// hash += hash << 13;
+			// hash ^= hash >> 7;
+			// hash += hash << 3;
+			// hash ^= hash >> 17;
+			// hash += hash << 5;
+
+			ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
+			Block hashcode_block = new Block (hashcode_top, loc, loc);
+			hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
+
+			var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
+			hashcode_block.AddStatement (new BlockVariable (new TypeExpression (li_hash.Type, loc), li_hash));
+			LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
+			hashcode_block.AddStatement (new StatementExpression (
+				new SimpleAssign (hash_variable_assign, rs_hashcode)));
+
+			var hash_variable = new LocalVariableReference (li_hash, loc);
+			hashcode_block.AddStatement (new StatementExpression (
+				new CompoundAssign (Binary.Operator.Addition, hash_variable,
+					new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc)))));
+			hashcode_block.AddStatement (new StatementExpression (
+				new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
+					new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc)))));
+			hashcode_block.AddStatement (new StatementExpression (
+				new CompoundAssign (Binary.Operator.Addition, hash_variable,
+					new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc)))));
+			hashcode_block.AddStatement (new StatementExpression (
+				new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
+					new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc)))));
+			hashcode_block.AddStatement (new StatementExpression (
+				new CompoundAssign (Binary.Operator.Addition, hash_variable,
+					new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc)))));
+
+			hashcode_block.AddStatement (new Return (hash_variable, loc));
+			hashcode.Block = hashcode_top;
+			hashcode.Define ();
+			Members.Add (hashcode);
+
+			//
+			// ToString () override
+			//
+
+			ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
+			tostring_block.AddStatement (new Return (string_concat, loc));
+			tostring.Block = tostring_block;
+			tostring.Define ();
+			Members.Add (tostring);
+
+			return true;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return SignatureForError;
+		}
+
+		public override CompilationSourceFile GetCompilationSourceFile ()
+		{
+			return null;
+		}
+
+		public IList<AnonymousTypeParameter> Parameters {
+			get {
+				return parameters;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/argument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/argument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/argument.cs	(revision 11807)
@@ -0,0 +1,674 @@
+﻿//
+// argument.cs: Argument expressions
+//
+// Author:
+//   Miguel de Icaza (miguel@ximain.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+// Copyright 2003-2011 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	//
+	// Argument expression used for invocation
+	//
+	public class Argument
+	{
+		public enum AType : byte
+		{
+			None = 0,
+			Ref = 1,			// ref modifier used
+			Out = 2,			// out modifier used
+			Default = 3,		// argument created from default parameter value
+			DynamicTypeName = 4,	// System.Type argument for dynamic binding
+			ExtensionType = 5,	// Instance expression inserted as the first argument
+
+			// Conditional instance expression inserted as the first argument
+			ExtensionTypeConditionalAccess = 5 | ConditionalAccessFlag,
+
+			ConditionalAccessFlag = 1 << 7
+		}
+
+		public readonly AType ArgType;
+		public Expression Expr;
+
+		public Argument (Expression expr, AType type)
+		{
+			this.Expr = expr;
+			this.ArgType = type;
+		}
+
+		public Argument (Expression expr)
+		{
+			this.Expr = expr;
+		}
+
+		#region Properties
+
+		public bool IsByRef {
+			get { return ArgType == AType.Ref || ArgType == AType.Out; }
+		}
+
+		public bool IsDefaultArgument {
+			get { return ArgType == AType.Default; }
+		}
+
+		public bool IsExtensionType {
+			get {
+				return (ArgType & AType.ExtensionType) == AType.ExtensionType;
+			}
+		}
+
+		public Parameter.Modifier Modifier {
+			get {
+				switch (ArgType) {
+				case AType.Out:
+					return Parameter.Modifier.OUT;
+
+				case AType.Ref:
+					return Parameter.Modifier.REF;
+
+				default:
+					return Parameter.Modifier.NONE;
+				}
+			}
+		}
+
+		public TypeSpec Type {
+			get { return Expr.Type; }
+		}
+
+		#endregion
+
+		public Argument Clone (Expression expr)
+		{
+			Argument a = (Argument) MemberwiseClone ();
+			a.Expr = expr;
+			return a;
+		}
+
+		public Argument Clone (CloneContext clonectx)
+		{
+			return Clone (Expr.Clone (clonectx));
+		}
+
+		public virtual Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (ArgType == AType.Default)
+				ec.Report.Error (854, Expr.Location, "An expression tree cannot contain an invocation which uses optional parameter");
+
+			return Expr.CreateExpressionTree (ec);
+		}
+
+
+		public virtual void Emit (EmitContext ec)
+		{
+			if (!IsByRef) {
+				if (ArgType == AType.ExtensionTypeConditionalAccess) {
+					var ie = new InstanceEmitter (Expr, false);
+					ie.Emit (ec, true);
+				} else {
+					Expr.Emit (ec);
+				}
+
+				return;
+			}
+
+			AddressOp mode = AddressOp.Store;
+			if (ArgType == AType.Ref)
+				mode |= AddressOp.Load;
+
+			IMemoryLocation ml = (IMemoryLocation) Expr;
+			ml.AddressOf (ec, mode);
+		}
+
+		public Argument EmitToField (EmitContext ec, bool cloneResult)
+		{
+			var res = Expr.EmitToField (ec);
+			if (cloneResult && res != Expr)
+				return new Argument (res, ArgType);
+
+			Expr = res;
+			return this;
+		}
+
+		public void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (ArgType == AType.Out) {
+				var vr = Expr as VariableReference;
+				if (vr != null) {
+					if (vr.VariableInfo != null)
+						fc.SetVariableAssigned (vr.VariableInfo);
+
+					return;
+				}
+
+				var fe = Expr as FieldExpr;
+				if (fe != null) {
+					fe.SetFieldAssigned (fc);
+					return;
+				}
+
+				return;
+			}
+
+			Expr.FlowAnalysis (fc);
+		}
+
+		public string GetSignatureForError ()
+		{
+			if (Expr.eclass == ExprClass.MethodGroup)
+				return Expr.ExprClassName;
+
+			return Expr.Type.GetSignatureForError ();
+		}
+
+		public bool ResolveMethodGroup (ResolveContext ec)
+		{
+			SimpleName sn = Expr as SimpleName;
+			if (sn != null)
+				Expr = sn.GetMethodGroup ();
+
+			// FIXME: csc doesn't report any error if you try to use `ref' or
+			//        `out' in a delegate creation expression.
+			Expr = Expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
+			if (Expr == null)
+				return false;
+
+			return true;
+		}
+
+		public void Resolve (ResolveContext ec)
+		{
+			// Verify that the argument is readable
+			if (ArgType != AType.Out)
+				Expr = Expr.Resolve (ec);
+
+			// Verify that the argument is writeable
+			if (Expr != null && IsByRef)
+				Expr = Expr.ResolveLValue (ec, EmptyExpression.OutAccess);
+
+			if (Expr == null)
+				Expr = ErrorExpression.Instance;
+		}
+	}
+
+	public class MovableArgument : Argument
+	{
+		LocalTemporary variable;
+
+		public MovableArgument (Argument arg)
+			: this (arg.Expr, arg.ArgType)
+		{
+		}
+
+		protected MovableArgument (Expression expr, AType modifier)
+			: base (expr, modifier)
+		{
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// TODO: Should guard against multiple emits
+			base.Emit (ec);
+
+			// Release temporary variable when used
+			if (variable != null)
+				variable.Release (ec);
+		}
+
+		public void EmitToVariable (EmitContext ec)
+		{
+			var type = Expr.Type;
+			if (IsByRef) {
+				var ml = (IMemoryLocation) Expr;
+				ml.AddressOf (ec, AddressOp.LoadStore);
+				type = ReferenceContainer.MakeType (ec.Module, type);
+			} else {
+				Expr.Emit (ec);
+			}
+
+			variable = new LocalTemporary (type);
+			variable.Store (ec);
+
+			Expr = variable;
+		}
+	}
+
+	public class NamedArgument : MovableArgument
+	{
+		public readonly string Name;
+		readonly Location loc;
+
+		public NamedArgument (string name, Location loc, Expression expr)
+			: this (name, loc, expr, AType.None)
+		{
+		}
+
+		public NamedArgument (string name, Location loc, Expression expr, AType modifier)
+			: base (expr, modifier)
+		{
+			this.Name = name;
+			this.loc = loc;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (853, loc, "An expression tree cannot contain named argument");
+			return base.CreateExpressionTree (ec);
+		}
+
+		public Location Location {
+			get { return loc; }
+		}
+	}
+	
+	public class Arguments
+	{
+		sealed class ArgumentsOrdered : Arguments
+		{
+			readonly List<MovableArgument> ordered;
+
+			public ArgumentsOrdered (Arguments args)
+				: base (args.Count)
+			{
+				AddRange (args);
+				ordered = new List<MovableArgument> ();
+			}
+
+			public void AddOrdered (MovableArgument arg)
+			{
+				ordered.Add (arg);
+			}
+
+			public override void FlowAnalysis (FlowAnalysisContext fc, List<MovableArgument> movable = null)
+			{
+				foreach (var arg in ordered) {
+					if (arg.ArgType != Argument.AType.Out)
+						arg.FlowAnalysis (fc);
+				}
+
+				base.FlowAnalysis (fc, ordered);
+			}
+
+			public override Arguments Emit (EmitContext ec, bool dup_args, bool prepareAwait)
+			{
+				foreach (var a in ordered) {
+					if (prepareAwait)
+						a.EmitToField (ec, false);
+					else
+						a.EmitToVariable (ec);
+				}
+
+				return base.Emit (ec, dup_args, prepareAwait);
+			}
+		}
+
+		// Try not to add any more instances to this class, it's allocated a lot
+		List<Argument> args;
+
+		public Arguments (int capacity)
+		{
+			args = new List<Argument> (capacity);
+		}
+
+		private Arguments (List<Argument> args)
+		{
+			this.args = args;
+		}
+
+		public void Add (Argument arg)
+		{
+			args.Add (arg);
+		}
+
+		public void AddRange (Arguments args)
+		{
+			this.args.AddRange (args.args);
+		}
+
+		public bool ContainsEmitWithAwait ()
+		{
+			foreach (var arg in args) {
+				if (arg.Expr.ContainsEmitWithAwait ())
+					return true;
+			}
+
+			return false;
+		}
+
+		public ArrayInitializer CreateDynamicBinderArguments (ResolveContext rc)
+		{
+			Location loc = Location.Null;
+			var all = new ArrayInitializer (args.Count, loc);
+
+			MemberAccess binder = DynamicExpressionStatement.GetBinderNamespace (loc);
+
+			foreach (Argument a in args) {
+				Arguments dargs = new Arguments (2);
+
+				// CSharpArgumentInfoFlags.None = 0
+				const string info_flags_enum = "CSharpArgumentInfoFlags";
+				Expression info_flags = new IntLiteral (rc.BuiltinTypes, 0, loc);
+
+				if (a.Expr is Constant) {
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "Constant", loc));
+				} else if (a.ArgType == Argument.AType.Ref) {
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsRef", loc));
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
+				} else if (a.ArgType == Argument.AType.Out) {
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsOut", loc));
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
+				} else if (a.ArgType == Argument.AType.DynamicTypeName) {
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "IsStaticType", loc));
+				}
+
+				var arg_type = a.Expr.Type;
+
+				if (arg_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && arg_type != InternalType.NullLiteral) {
+					MethodGroupExpr mg = a.Expr as MethodGroupExpr;
+					if (mg != null) {
+						rc.Report.Error (1976, a.Expr.Location,
+							"The method group `{0}' cannot be used as an argument of dynamic operation. Consider using parentheses to invoke the method",
+							mg.Name);
+					} else if (arg_type == InternalType.AnonymousMethod) {
+						rc.Report.Error (1977, a.Expr.Location,
+							"An anonymous method or lambda expression cannot be used as an argument of dynamic operation. Consider using a cast");
+					} else if (arg_type.Kind == MemberKind.Void || arg_type == InternalType.Arglist || arg_type.IsPointer) {
+						rc.Report.Error (1978, a.Expr.Location,
+							"An expression of type `{0}' cannot be used as an argument of dynamic operation",
+							arg_type.GetSignatureForError ());
+					}
+
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "UseCompileTimeType", loc));
+				}
+
+				string named_value;
+				NamedArgument na = a as NamedArgument;
+				if (na != null) {
+					info_flags = new Binary (Binary.Operator.BitwiseOr, info_flags,
+						new MemberAccess (new MemberAccess (binder, info_flags_enum, loc), "NamedArgument", loc));
+
+					named_value = na.Name;
+				} else {
+					named_value = null;
+				}
+
+				dargs.Add (new Argument (info_flags));
+				dargs.Add (new Argument (new StringLiteral (rc.BuiltinTypes, named_value, loc)));
+				all.Add (new Invocation (new MemberAccess (new MemberAccess (binder, "CSharpArgumentInfo", loc), "Create", loc), dargs));
+			}
+
+			return all;
+		}
+
+		public static Arguments CreateForExpressionTree (ResolveContext ec, Arguments args, params Expression[] e)
+		{
+			Arguments all = new Arguments ((args == null ? 0 : args.Count) + e.Length);
+			for (int i = 0; i < e.Length; ++i) {
+				if (e [i] != null)
+					all.Add (new Argument (e[i]));
+			}
+
+			if (args != null) {
+				foreach (Argument a in args.args) {
+					Expression tree_arg = a.CreateExpressionTree (ec);
+					if (tree_arg != null)
+						all.Add (new Argument (tree_arg));
+				}
+			}
+
+			return all;
+		}
+
+		public void CheckArrayAsAttribute (CompilerContext ctx)
+		{
+			foreach (Argument arg in args) {
+				// Type is undefined (was error 246)
+				if (arg.Type == null)
+					continue;
+
+				if (arg.Type.IsArray)
+					ctx.Report.Warning (3016, 1, arg.Expr.Location, "Arrays as attribute arguments are not CLS-compliant");
+			}
+		}
+
+		public Arguments Clone (CloneContext ctx)
+		{
+			Arguments cloned = new Arguments (args.Count);
+			foreach (Argument a in args)
+				cloned.Add (a.Clone (ctx));
+
+			return cloned;
+		}
+
+		public int Count {
+			get { return args.Count; }
+		}
+
+		//
+		// Emits a list of resolved Arguments
+		// 
+		public void Emit (EmitContext ec)
+		{
+			Emit (ec, false, false);
+		}
+
+		//
+		// if `dup_args' is true or any of arguments contains await.
+		// A copy of all arguments will be returned to the caller
+		//
+		public virtual Arguments Emit (EmitContext ec, bool dup_args, bool prepareAwait)
+		{
+			List<Argument> dups;
+
+			if ((dup_args && Count != 0) || prepareAwait)
+				dups = new List<Argument> (Count);
+			else
+				dups = null;
+
+			LocalTemporary lt;
+			foreach (Argument a in args) {
+				if (prepareAwait) {
+					dups.Add (a.EmitToField (ec, true));
+					continue;
+				}
+				
+				a.Emit (ec);
+
+				if (!dup_args) {
+					continue;
+				}
+
+				if (a.Expr.IsSideEffectFree) {
+					//
+					// No need to create a temporary variable for side effect free expressions. I assume
+					// all side-effect free expressions are cheap, this has to be tweaked when we become
+					// more aggressive on detection
+					//
+					dups.Add (a);
+				} else {
+					ec.Emit (OpCodes.Dup);
+
+					// TODO: Release local temporary on next Emit
+					// Need to add a flag to argument to indicate this
+					lt = new LocalTemporary (a.Type);
+					lt.Store (ec);
+
+					dups.Add (new Argument (lt, a.ArgType));
+				}
+			}
+
+			if (dups != null)
+				return new Arguments (dups);
+
+			return null;
+		}
+
+		public virtual void FlowAnalysis (FlowAnalysisContext fc, List<MovableArgument> movable = null)
+		{
+			bool has_out = false;
+			foreach (var arg in args) {
+				if (arg.ArgType == Argument.AType.Out) {
+					has_out = true;
+					continue;
+				}
+
+				if (movable == null) {
+					arg.FlowAnalysis (fc);
+					continue;
+				}
+
+				var ma = arg as MovableArgument;
+				if (ma != null && !movable.Contains (ma))
+					arg.FlowAnalysis (fc);
+			}
+
+			if (!has_out)
+				return;
+
+			foreach (var arg in args) {
+				if (arg.ArgType != Argument.AType.Out)
+					continue;
+
+				arg.FlowAnalysis (fc);
+			}
+		}
+
+		public List<Argument>.Enumerator GetEnumerator ()
+		{
+			return args.GetEnumerator ();
+		}
+
+		//
+		// At least one argument is of dynamic type
+		//
+		public bool HasDynamic {
+			get {
+				foreach (Argument a in args) {
+					if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef)
+						return true;
+				}
+				
+				return false;
+			}
+		}
+
+		//
+		// At least one argument is named argument
+		//
+		public bool HasNamed {
+			get {
+				foreach (Argument a in args) {
+					if (a is NamedArgument)
+						return true;
+				}
+				
+				return false;
+			}
+		}
+
+
+		public void Insert (int index, Argument arg)
+		{
+			args.Insert (index, arg);
+		}
+
+		public static System.Linq.Expressions.Expression[] MakeExpression (Arguments args, BuilderContext ctx)
+		{
+			if (args == null || args.Count == 0)
+				return null;
+
+			var exprs = new System.Linq.Expressions.Expression [args.Count];
+			for (int i = 0; i < exprs.Length; ++i) {
+				Argument a = args.args [i];
+				exprs[i] = a.Expr.MakeExpression (ctx);
+			}
+
+			return exprs;
+		}
+
+		//
+		// For named arguments when the order of execution is different
+		// to order of invocation
+		//
+		public Arguments MarkOrderedArgument (NamedArgument a)
+		{
+			//
+			// An expression has no effect on left-to-right execution
+			//
+			if (a.Expr.IsSideEffectFree)
+				return this;
+
+			ArgumentsOrdered ra = this as ArgumentsOrdered;
+			if (ra == null) {
+				ra = new ArgumentsOrdered (this);
+
+				for (int i = 0; i < args.Count; ++i) {
+					var la = args [i];
+					if (la == a)
+						break;
+
+					//
+					// When the argument is filled later by default expression
+					//
+					if (la == null)
+						continue;
+
+					var ma = la as MovableArgument;
+					if (ma == null) {
+						ma = new MovableArgument (la);
+						ra.args[i] = ma;
+					}
+
+					ra.AddOrdered (ma);
+				}
+			}
+
+			ra.AddOrdered (a);
+			return ra;
+		}
+
+		//
+		// Returns dynamic when at least one argument is of dynamic type
+		//
+		public void Resolve (ResolveContext ec, out bool dynamic)
+		{
+			dynamic = false;
+			foreach (Argument a in args) {
+				a.Resolve (ec);
+				if (a.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && !a.IsByRef)
+					dynamic = true;
+			}
+		}
+
+		public void RemoveAt (int index)
+		{
+			args.RemoveAt (index);
+		}
+
+		public Argument this [int index] {
+			get { return args [index]; }
+			set { args [index] = value; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/assembly.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/assembly.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/assembly.cs	(revision 11807)
@@ -0,0 +1,1257 @@
+//
+// assembly.cs: Assembly declaration and specifications
+//
+// Authors:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2004-2011 Novell, Inc.
+// Copyright 2011-2013 Xamarin Inc
+//
+
+
+using System;
+using System.IO;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Security;
+using System.Security.Cryptography;
+using System.Security.Permissions;
+using Mono.Security.Cryptography;
+using Mono.CompilerServices.SymbolWriter;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
+#else
+using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	public interface IAssemblyDefinition
+	{
+		string FullName { get; }
+		bool IsCLSCompliant { get; }
+		bool IsMissing { get; }
+		string Name { get; }
+
+		byte[] GetPublicKeyToken ();
+		bool IsFriendAssemblyTo (IAssemblyDefinition assembly);
+	}
+                
+	public abstract class AssemblyDefinition : IAssemblyDefinition
+	{
+		// TODO: make it private and move all builder based methods here
+		public AssemblyBuilder Builder;
+		protected AssemblyBuilderExtension builder_extra;
+		MonoSymbolFile symbol_writer;
+
+		bool is_cls_compliant;
+		bool wrap_non_exception_throws;
+		bool wrap_non_exception_throws_custom;
+		bool has_user_debuggable;
+
+		protected ModuleContainer module;
+		readonly string name;
+		protected readonly string file_name;
+
+		byte[] public_key, public_key_token;
+		bool delay_sign;
+
+		// Holds private/public key pair when private key
+		// was available
+		StrongNameKeyPair private_key;	
+
+		Attribute cls_attribute;
+		Method entry_point;
+
+		protected List<ImportedModuleDefinition> added_modules;
+		SecurityType declarative_security;
+		Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
+		AssemblyAttributesPlaceholder module_target_attrs;
+
+		// Win32 version info values
+		string vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark;
+
+		protected AssemblyDefinition (ModuleContainer module, string name)
+		{
+			this.module = module;
+			this.name = Path.GetFileNameWithoutExtension (name);
+
+			wrap_non_exception_throws = true;
+
+			delay_sign = Compiler.Settings.StrongNameDelaySign;
+
+			//
+			// Load strong name key early enough for assembly importer to be able to
+			// use the keys for InternalsVisibleTo
+			// This should go somewhere close to ReferencesLoading but don't have the place yet
+			//
+			if (Compiler.Settings.HasKeyFileOrContainer) {
+				LoadPublicKey (Compiler.Settings.StrongNameKeyFile, Compiler.Settings.StrongNameKeyContainer);
+			}
+		}
+
+		protected AssemblyDefinition (ModuleContainer module, string name, string fileName)
+			: this (module, name)
+		{
+			this.file_name = fileName;
+		}
+
+		#region Properties
+
+		public Attribute CLSCompliantAttribute {
+			get {
+				return cls_attribute;
+			}
+		}
+
+		public CompilerContext Compiler {
+			get {
+				return module.Compiler;
+			}
+		}
+
+		//
+		// Assembly entry point, aka Main method
+		//
+		public Method EntryPoint {
+			get {
+				return entry_point;
+			}
+			set {
+				entry_point = value;
+			}
+		}
+
+		public string FullName {
+			get {
+				return Builder.FullName;
+			}
+		}
+
+		public bool HasCLSCompliantAttribute {
+			get {
+				return cls_attribute != null;
+			}
+		}
+
+		// TODO: This should not exist here but will require more changes
+		public MetadataImporter Importer {
+		    get; set;
+		}
+
+		public bool IsCLSCompliant {
+			get {
+				return is_cls_compliant;
+			}
+		}
+
+		bool IAssemblyDefinition.IsMissing {
+			get {
+				return false;
+			}
+		}
+
+		public bool IsSatelliteAssembly { get; private set; }
+
+		public string Name {
+			get {
+				return name;
+			}
+		}
+
+		public bool WrapNonExceptionThrows {
+			get {
+				return wrap_non_exception_throws;
+			}
+		}
+
+		protected Report Report {
+			get {
+				return Compiler.Report;
+			}
+		}
+
+		public MonoSymbolFile SymbolWriter {
+			get {
+				return symbol_writer;
+			}
+		}
+
+		#endregion
+
+		public void AddModule (ImportedModuleDefinition module)
+		{
+			if (added_modules == null) {
+				added_modules = new List<ImportedModuleDefinition> ();
+				added_modules.Add (module);
+			}
+		}
+
+		public void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.IsValidSecurityAttribute ()) {
+				a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
+				return;
+			}
+
+			if (a.Type == pa.AssemblyCulture) {
+				string value = a.GetString ();
+				if (value == null || value.Length == 0)
+					return;
+
+				if (Compiler.Settings.Target == Target.Exe) {
+					Report.Error (7059, a.Location, "Executables cannot be satellite assemblies. Remove the attribute or keep it empty");
+					return;
+				}
+
+				if (value == "neutral")
+					value = "";
+
+				if (Compiler.Settings.Target == Target.Module) {
+					SetCustomAttribute (ctor, cdata);
+				} else {
+					builder_extra.SetCulture (value, a.Location);
+				}
+
+				IsSatelliteAssembly = true;
+				return;
+			}
+
+			if (a.Type == pa.AssemblyVersion) {
+				string value = a.GetString ();
+				if (value == null || value.Length == 0)
+					return;
+
+				var vinfo = IsValidAssemblyVersion (value, true);
+				if (vinfo == null) {
+					Report.Error (7034, a.Location, "The specified version string `{0}' does not conform to the required format - major[.minor[.build[.revision]]]",
+						value);
+					return;
+				}
+
+				if (Compiler.Settings.Target == Target.Module) {
+					SetCustomAttribute (ctor, cdata);
+				} else {
+					builder_extra.SetVersion (vinfo, a.Location);
+				}
+
+				return;
+			}
+
+			if (a.Type == pa.AssemblyAlgorithmId) {
+				const int pos = 2; // skip CA header
+				uint alg = (uint) cdata [pos];
+				alg |= ((uint) cdata [pos + 1]) << 8;
+				alg |= ((uint) cdata [pos + 2]) << 16;
+				alg |= ((uint) cdata [pos + 3]) << 24;
+
+				if (Compiler.Settings.Target == Target.Module) {
+					SetCustomAttribute (ctor, cdata);
+				} else {
+					builder_extra.SetAlgorithmId (alg, a.Location);
+				}
+
+				return;
+			}
+
+			if (a.Type == pa.AssemblyFlags) {
+				const int pos = 2; // skip CA header
+				uint flags = (uint) cdata[pos];
+				flags |= ((uint) cdata [pos + 1]) << 8;
+				flags |= ((uint) cdata [pos + 2]) << 16;
+				flags |= ((uint) cdata [pos + 3]) << 24;
+
+				// Ignore set PublicKey flag if assembly is not strongnamed
+				if ((flags & (uint) AssemblyNameFlags.PublicKey) != 0 && public_key == null)
+					flags &= ~(uint) AssemblyNameFlags.PublicKey;
+
+				if (Compiler.Settings.Target == Target.Module) {
+					SetCustomAttribute (ctor, cdata);
+				} else {
+					builder_extra.SetFlags (flags, a.Location);
+				}
+
+				return;
+			}
+
+			if (a.Type == pa.TypeForwarder) {
+				TypeSpec t = a.GetArgumentType ();
+				if (t == null || TypeManager.HasElementType (t)) {
+					Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
+					return;
+				}
+
+				if (emitted_forwarders == null) {
+					emitted_forwarders = new Dictionary<ITypeDefinition, Attribute> ();
+				} else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
+					Report.SymbolRelatedToPreviousError (emitted_forwarders[t.MemberDefinition].Location, null);
+					Report.Error (739, a.Location, "A duplicate type forward of type `{0}'",
+						t.GetSignatureForError ());
+					return;
+				}
+
+				emitted_forwarders.Add (t.MemberDefinition, a);
+
+				if (t.MemberDefinition.DeclaringAssembly == this) {
+					Report.SymbolRelatedToPreviousError (t);
+					Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
+						t.GetSignatureForError ());
+					return;
+				}
+
+				if (t.IsNested) {
+					Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
+						t.GetSignatureForError ());
+					return;
+				}
+
+				builder_extra.AddTypeForwarder (t.GetDefinition (), a.Location);
+				return;
+			}
+
+			if (a.Type == pa.Extension) {
+				a.Error_MisusedExtensionAttribute ();
+				return;
+			}
+
+			if (a.Type == pa.InternalsVisibleTo) {
+				string assembly_name = a.GetString ();
+				if (assembly_name == null) {
+					Report.Error (7030, a.Location, "Friend assembly reference cannot have `null' value");
+					return;
+				}
+
+				if (assembly_name.Length == 0)
+					return;
+#if STATIC
+				ParsedAssemblyName aname;
+				ParseAssemblyResult r = Fusion.ParseAssemblyName (assembly_name, out aname);
+				if (r != ParseAssemblyResult.OK) {
+					Report.Warning (1700, 3, a.Location, "Friend assembly reference `{0}' is invalid and cannot be resolved",
+						assembly_name);
+					return;
+				}
+
+				if (aname.Version != null || aname.Culture != null || aname.ProcessorArchitecture != ProcessorArchitecture.None) {
+					Report.Error (1725, a.Location,
+						"Friend assembly reference `{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture or processor architecture specified",
+						assembly_name);
+
+					return;
+				}
+
+				if (public_key != null && !aname.HasPublicKey) {
+					Report.Error (1726, a.Location,
+						"Friend assembly reference `{0}' is invalid. Strong named assemblies must specify a public key in their InternalsVisibleTo declarations",
+						assembly_name);
+					return;
+				}
+#endif
+			} else if (a.Type == pa.RuntimeCompatibility) {
+				wrap_non_exception_throws_custom = true;
+			} else if (a.Type == pa.AssemblyFileVersion) {
+				vi_product_version = a.GetString ();
+				if (string.IsNullOrEmpty (vi_product_version) || IsValidAssemblyVersion (vi_product_version, false) == null) {
+					Report.Warning (7035, 1, a.Location, "The specified version string `{0}' does not conform to the recommended format major.minor.build.revision",
+						vi_product_version, a.Name);
+					return;
+				}
+
+				// File version info decoding from blob is not supported
+				var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), new object[] { vi_product_version });
+				Builder.SetCustomAttribute (cab);
+				return;
+			} else if (a.Type == pa.AssemblyProduct) {
+				vi_product = a.GetString ();
+			} else if (a.Type == pa.AssemblyCompany) {
+				vi_company = a.GetString ();
+			} else if (a.Type == pa.AssemblyDescription) {
+				// TODO: Needs extra api
+			} else if (a.Type == pa.AssemblyCopyright) {
+				vi_copyright = a.GetString ();
+			} else if (a.Type == pa.AssemblyTrademark) {
+				vi_trademark = a.GetString ();
+			} else if (a.Type == pa.Debuggable) {
+				has_user_debuggable = true;
+			}
+
+			SetCustomAttribute (ctor, cdata);
+		}
+
+		//
+		// When using assembly public key attributes InternalsVisibleTo key
+		// was not checked, we have to do it later when we actually know what
+		// our public key token is
+		//
+		void CheckReferencesPublicToken ()
+		{
+			// TODO: It should check only references assemblies but there is
+			// no working SRE API
+			foreach (var entry in Importer.Assemblies) {
+				var a = entry as ImportedAssemblyDefinition;
+				if (a == null || a.IsMissing)
+					continue;
+
+				if (public_key != null && !a.HasStrongName) {
+					Report.Error (1577, "Referenced assembly `{0}' does not have a strong name",
+						a.FullName);
+				}
+
+				var ci = a.Assembly.GetName ().CultureInfo;
+				if (!ci.Equals (CultureInfo.InvariantCulture)) {
+					Report.Warning (8009, 1, "Referenced assembly `{0}' has different culture setting of `{1}'",
+						a.Name, ci.Name);
+				}
+
+				if (!a.IsFriendAssemblyTo (this))
+					continue;
+
+				var attr = a.GetAssemblyVisibleToName (this);
+				var atoken = attr.GetPublicKeyToken ();
+
+				if (ArrayComparer.IsEqual (GetPublicKeyToken (), atoken))
+					continue;
+
+				Report.SymbolRelatedToPreviousError (a.Location);
+				Report.Error (281,
+					"Friend access was granted to `{0}', but the output assembly is named `{1}'. Try adding a reference to `{0}' or change the output assembly name to match it",
+					attr.FullName, FullName);
+			}
+		}
+
+		protected AssemblyName CreateAssemblyName ()
+		{
+			var an = new AssemblyName (name);
+
+			if (public_key != null && Compiler.Settings.Target != Target.Module) {
+				if (delay_sign) {
+					an.SetPublicKey (public_key);
+				} else {
+					if (public_key.Length == 16) {
+						Report.Error (1606, "Could not sign the assembly. ECMA key can only be used to delay-sign assemblies");
+					} else if (private_key == null) {
+						Error_AssemblySigning ("The specified key file does not have a private key");
+					} else {
+						an.KeyPair = private_key;
+					}
+				}
+			}
+
+			return an;
+		}
+
+		public virtual ModuleBuilder CreateModuleBuilder ()
+		{
+			if (file_name == null)
+				throw new NotSupportedException ("transient module in static assembly");
+
+			var module_name = Path.GetFileName (file_name);
+
+			// Always initialize module without symbolInfo. We could be framework dependent
+			// but returned ISymbolWriter does not have all what we need therefore some
+			// adaptor will be needed for now we alwayas emit MDB format when generating
+			// debug info
+			return Builder.DefineDynamicModule (module_name, module_name, false);
+		}
+
+		public virtual void Emit ()
+		{
+			if (Compiler.Settings.Target == Target.Module) {
+				module_target_attrs = new AssemblyAttributesPlaceholder (module, name);
+				module_target_attrs.CreateContainer ();
+				module_target_attrs.DefineContainer ();
+				module_target_attrs.Define ();
+				module.AddCompilerGeneratedClass (module_target_attrs);
+			} else if (added_modules != null) {
+				ReadModulesAssemblyAttributes ();
+			}
+
+			if (Compiler.Settings.GenerateDebugInfo) {
+				symbol_writer = new MonoSymbolFile ();
+			}
+
+			module.EmitContainer ();
+
+			if (module.HasExtensionMethod) {
+				var pa = module.PredefinedAttributes.Extension;
+				if (pa.IsDefined) {
+					SetCustomAttribute (pa.Constructor, AttributeEncoder.Empty);
+				}
+			}
+
+			if (!IsSatelliteAssembly) {
+				if (!has_user_debuggable && Compiler.Settings.GenerateDebugInfo) {
+					var pa = module.PredefinedAttributes.Debuggable;
+					if (pa.IsDefined) {
+						var modes = System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;
+						if (!Compiler.Settings.Optimize)
+							modes |= System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations;
+
+						pa.EmitAttribute (Builder, modes);
+					}
+				}
+
+				if (!wrap_non_exception_throws_custom) {
+					PredefinedAttribute pa = module.PredefinedAttributes.RuntimeCompatibility;
+					if (pa.IsDefined && pa.ResolveBuilder ()) {
+						var prop = module.PredefinedMembers.RuntimeCompatibilityWrapNonExceptionThrows.Get ();
+						if (prop != null) {
+							AttributeEncoder encoder = new AttributeEncoder ();
+							encoder.EncodeNamedPropertyArgument (prop, new BoolLiteral (Compiler.BuiltinTypes, true, Location.Null));
+							SetCustomAttribute (pa.Constructor, encoder.ToArray ());
+						}
+					}
+				}
+
+				if (declarative_security != null) {
+#if STATIC
+					foreach (var entry in declarative_security) {
+						Builder.__AddDeclarativeSecurity (entry);
+					}
+#else
+					throw new NotSupportedException ("Assembly-level security");
+#endif
+				}
+			}
+
+			CheckReferencesPublicToken ();
+
+			SetEntryPoint ();
+		}
+
+		public byte[] GetPublicKeyToken ()
+		{
+			if (public_key == null || public_key_token != null)
+				return public_key_token;
+
+			HashAlgorithm ha = SHA1.Create ();
+			byte[] hash = ha.ComputeHash (public_key);
+			// we need the last 8 bytes in reverse order
+			public_key_token = new byte[8];
+			Buffer.BlockCopy (hash, hash.Length - 8, public_key_token, 0, 8);
+			Array.Reverse (public_key_token, 0, 8);
+			return public_key_token;
+		}
+
+		//
+		// Either keyFile or keyContainer has to be non-null
+		//
+		void LoadPublicKey (string keyFile, string keyContainer)
+		{
+			if (keyContainer != null) {
+				try {
+					private_key = new StrongNameKeyPair (keyContainer);
+					public_key = private_key.PublicKey;
+				} catch {
+					Error_AssemblySigning ("The specified key container `" + keyContainer + "' does not exist");
+				}
+
+				return;
+			}
+
+			bool key_file_exists = File.Exists (keyFile);
+
+			//
+			// For attribute based KeyFile do additional lookup
+			// in output assembly path
+			//
+			if (!key_file_exists && Compiler.Settings.StrongNameKeyFile == null) {
+				//
+				// The key file can be relative to output assembly
+				//
+				string test_path = Path.Combine (Path.GetDirectoryName (file_name), keyFile);
+				key_file_exists = File.Exists (test_path);
+				if (key_file_exists)
+					keyFile = test_path;
+			}
+
+			if (!key_file_exists) {
+				Error_AssemblySigning ("The specified key file `" + keyFile + "' does not exist");
+				return;
+			}
+
+			using (FileStream fs = new FileStream (keyFile, FileMode.Open, FileAccess.Read)) {
+				byte[] snkeypair = new byte[fs.Length];
+				fs.Read (snkeypair, 0, snkeypair.Length);
+
+				// check for ECMA key
+				if (snkeypair.Length == 16) {
+					public_key = snkeypair;
+					return;
+				}
+
+				try {
+					// take it, with or without, a private key
+					RSA rsa = CryptoConvert.FromCapiKeyBlob (snkeypair);
+					// and make sure we only feed the public part to Sys.Ref
+					byte[] publickey = CryptoConvert.ToCapiPublicKeyBlob (rsa);
+
+					// AssemblyName.SetPublicKey requires an additional header
+					byte[] publicKeyHeader = new byte[8] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00 };
+
+					// Encode public key
+					public_key = new byte[12 + publickey.Length];
+					Buffer.BlockCopy (publicKeyHeader, 0, public_key, 0, publicKeyHeader.Length);
+
+					// Length of Public Key (in bytes)
+					int lastPart = public_key.Length - 12;
+					public_key[8] = (byte) (lastPart & 0xFF);
+					public_key[9] = (byte) ((lastPart >> 8) & 0xFF);
+					public_key[10] = (byte) ((lastPart >> 16) & 0xFF);
+					public_key[11] = (byte) ((lastPart >> 24) & 0xFF);
+
+					Buffer.BlockCopy (publickey, 0, public_key, 12, publickey.Length);
+				} catch {
+					Error_AssemblySigning ("The specified key file `" + keyFile + "' has incorrect format");
+					return;
+				}
+
+				if (delay_sign)
+					return;
+
+				try {
+					// TODO: Is there better way to test for a private key presence ?
+					CryptoConvert.FromCapiPrivateKeyBlob (snkeypair);
+					private_key = new StrongNameKeyPair (snkeypair);
+				} catch { }
+			}
+		}
+
+		void ReadModulesAssemblyAttributes ()
+		{
+			foreach (var m in added_modules) {
+				var cattrs = m.ReadAssemblyAttributes ();
+				if (cattrs == null)
+					continue;
+
+				module.OptAttributes.AddAttributes (cattrs);
+			}
+		}
+
+		public void Resolve ()
+		{
+			if (Compiler.Settings.Unsafe && module.PredefinedTypes.SecurityAction.Define ()) {
+				//
+				// Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
+				// when -unsafe option was specified
+				//
+				Location loc = Location.Null;
+
+				MemberAccess system_security_permissions = new MemberAccess (new MemberAccess (
+					new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Security", loc), "Permissions", loc);
+
+				var req_min = module.PredefinedMembers.SecurityActionRequestMinimum.Resolve (loc);
+
+				Arguments pos = new Arguments (1);
+				pos.Add (new Argument (req_min.GetConstant (null)));
+
+				Arguments named = new Arguments (1);
+				named.Add (new NamedArgument ("SkipVerification", loc, new BoolLiteral (Compiler.BuiltinTypes, true, loc)));
+
+				Attribute g = new Attribute ("assembly",
+					new MemberAccess (system_security_permissions, "SecurityPermissionAttribute"),
+					new Arguments[] { pos, named }, loc, false);
+				g.AttachTo (module, module);
+
+				// Disable no-location warnings (e.g. obsolete) for compiler generated attribute
+				Compiler.Report.DisableReporting ();
+				try {
+					var ctor = g.Resolve ();
+					if (ctor != null) {
+						g.ExtractSecurityPermissionSet (ctor, ref declarative_security);
+					}
+				} finally {
+					Compiler.Report.EnableReporting ();
+				}
+			}
+
+			if (module.OptAttributes == null)
+				return;
+
+			// Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
+			if (!module.OptAttributes.CheckTargets())
+				return;
+
+			cls_attribute = module.ResolveAssemblyAttribute (module.PredefinedAttributes.CLSCompliant);
+
+			if (cls_attribute != null) {
+				is_cls_compliant = cls_attribute.GetClsCompliantAttributeValue ();
+			}
+
+			if (added_modules != null && Compiler.Settings.VerifyClsCompliance && is_cls_compliant) {
+				foreach (var m in added_modules) {
+					if (!m.IsCLSCompliant) {
+						Report.Error (3013,
+							"Added modules must be marked with the CLSCompliant attribute to match the assembly",
+							m.Name);
+					}
+				}
+			}
+
+			Attribute a = module.ResolveAssemblyAttribute (module.PredefinedAttributes.RuntimeCompatibility);
+			if (a != null) {
+				var val = a.GetNamedValue ("WrapNonExceptionThrows") as BoolConstant;
+				if (val != null)
+					wrap_non_exception_throws = val.Value;
+			}
+		}
+
+		protected void ResolveAssemblySecurityAttributes ()
+		{
+			string key_file = null;
+			string key_container = null;
+
+			if (module.OptAttributes != null) {
+				foreach (Attribute a in module.OptAttributes.Attrs) {
+					// cannot rely on any resolve-based members before you call Resolve
+					if (a.ExplicitTarget != "assembly")
+						continue;
+
+					// TODO: This code is buggy: comparing Attribute name without resolving is wrong.
+					//       However, this is invoked by CodeGen.Init, when none of the namespaces
+					//       are loaded yet.
+					// TODO: Does not handle quoted attributes properly
+					switch (a.Name) {
+					case "AssemblyKeyFile":
+					case "AssemblyKeyFileAttribute":
+					case "System.Reflection.AssemblyKeyFileAttribute":
+						if (Compiler.Settings.StrongNameKeyFile != null) {
+							Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
+							Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
+									"keyfile", "System.Reflection.AssemblyKeyFileAttribute");
+						} else {
+							string value = a.GetString ();
+							if (!string.IsNullOrEmpty (value)) {
+								Error_ObsoleteSecurityAttribute (a, "keyfile");
+								key_file = value;
+							}
+						}
+						break;
+					case "AssemblyKeyName":
+					case "AssemblyKeyNameAttribute":
+					case "System.Reflection.AssemblyKeyNameAttribute":
+						if (Compiler.Settings.StrongNameKeyContainer != null) {
+							Report.SymbolRelatedToPreviousError (a.Location, a.GetSignatureForError ());
+							Report.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
+									"keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
+						} else {
+							string value = a.GetString ();
+							if (!string.IsNullOrEmpty (value)) {
+								Error_ObsoleteSecurityAttribute (a, "keycontainer");
+								key_container = value;
+							}
+						}
+						break;
+					case "AssemblyDelaySign":
+					case "AssemblyDelaySignAttribute":
+					case "System.Reflection.AssemblyDelaySignAttribute":
+						bool b = a.GetBoolean ();
+						if (b) {
+							Error_ObsoleteSecurityAttribute (a, "delaysign");
+						}
+
+						delay_sign = b;
+						break;
+					}
+				}
+			}
+
+			// We came here only to report assembly attributes warnings
+			if (public_key != null)
+				return;
+
+			//
+			// Load the strong key file found in attributes when no
+			// command line key was given
+			//
+			if (key_file != null || key_container != null) {
+				LoadPublicKey (key_file, key_container);
+			} else if (delay_sign) {
+				Report.Warning (1607, 1, "Delay signing was requested but no key file was given");
+			}
+		}
+
+		public void EmbedResources ()
+		{
+			//
+			// Add Win32 resources
+			//
+			if (Compiler.Settings.Win32ResourceFile != null) {
+				Builder.DefineUnmanagedResource (Compiler.Settings.Win32ResourceFile);
+			} else {
+				Builder.DefineVersionInfoResource (vi_product, vi_product_version, vi_company, vi_copyright, vi_trademark);
+			}
+
+			if (Compiler.Settings.Win32IconFile != null) {
+				builder_extra.DefineWin32IconResource (Compiler.Settings.Win32IconFile);
+			}
+
+			if (Compiler.Settings.Resources != null) {
+				if (Compiler.Settings.Target == Target.Module) {
+					Report.Error (1507, "Cannot link resource file when building a module");
+				} else {
+					int counter = 0;
+					foreach (var res in Compiler.Settings.Resources) {
+						if (!File.Exists (res.FileName)) {
+							Report.Error (1566, "Error reading resource file `{0}'", res.FileName);
+							continue;
+						}
+
+						if (res.IsEmbeded) {
+							Stream stream;
+							if (counter++ < 10) {
+								stream = File.OpenRead (res.FileName);
+							} else {
+								// TODO: SRE API requires resource stream to be available during AssemblyBuilder::Save
+								// we workaround it by reading everything into memory to compile projects with
+								// many embedded resource (over 3500) references
+								stream = new MemoryStream (File.ReadAllBytes (res.FileName));
+							}
+
+							module.Builder.DefineManifestResource (res.Name, stream, res.Attributes);
+						} else {
+							Builder.AddResourceFile (res.Name, Path.GetFileName (res.FileName), res.Attributes);
+						}
+					}
+				}
+			}
+		}
+
+		public void Save ()
+		{
+			PortableExecutableKinds pekind = PortableExecutableKinds.ILOnly;
+			ImageFileMachine machine;
+
+			switch (Compiler.Settings.Platform) {
+			case Platform.X86:
+				pekind |= PortableExecutableKinds.Required32Bit;
+				machine = ImageFileMachine.I386;
+				break;
+			case Platform.X64:
+				pekind |= PortableExecutableKinds.PE32Plus;
+				machine = ImageFileMachine.AMD64;
+				break;
+			case Platform.IA64:
+				machine = ImageFileMachine.IA64;
+				break;
+			case Platform.AnyCPU32Preferred:
+#if STATIC
+				pekind |= PortableExecutableKinds.Preferred32Bit;
+				machine = ImageFileMachine.I386;
+				break;
+#else
+				throw new NotSupportedException ();
+#endif
+			case Platform.Arm:
+#if STATIC
+				machine = ImageFileMachine.ARM;
+				break;
+#else
+				throw new NotSupportedException ();
+#endif
+			case Platform.AnyCPU:
+			default:
+				machine = ImageFileMachine.I386;
+				break;
+			}
+
+			Compiler.TimeReporter.Start (TimeReporter.TimerType.OutputSave);
+			try {
+				if (Compiler.Settings.Target == Target.Module) {
+					SaveModule (pekind, machine);
+				} else {
+					Builder.Save (module.Builder.ScopeName, pekind, machine);
+				}
+			} catch (Exception e) {
+				Report.Error (16, "Could not write to file `" + name + "', cause: " + e.Message);
+			}
+			Compiler.TimeReporter.Stop (TimeReporter.TimerType.OutputSave);
+
+			// Save debug symbols file
+			if (symbol_writer != null && Compiler.Report.Errors == 0) {
+				// TODO: it should run in parallel
+				Compiler.TimeReporter.Start (TimeReporter.TimerType.DebugSave);
+
+				var filename = file_name + ".mdb";
+				try {
+					// We mmap the file, so unlink the previous version since it may be in use
+					File.Delete (filename);
+				} catch {
+					// We can safely ignore
+				}
+
+				module.WriteDebugSymbol (symbol_writer);
+
+				using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) {
+					symbol_writer.CreateSymbolFile (module.Builder.ModuleVersionId, fs);
+				}
+
+				Compiler.TimeReporter.Stop (TimeReporter.TimerType.DebugSave);
+			}
+		}
+
+		protected virtual void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
+		{
+			Report.RuntimeMissingSupport (Location.Null, "-target:module");
+		}
+
+		void SetCustomAttribute (MethodSpec ctor, byte[] data)
+		{
+			if (module_target_attrs != null)
+				module_target_attrs.AddAssemblyAttribute (ctor, data);
+			else
+				Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
+		}
+
+		void SetEntryPoint ()
+		{
+			if (!Compiler.Settings.NeedsEntryPoint) {
+				if (Compiler.Settings.MainClass != null)
+					Report.Error (2017, "Cannot specify -main if building a module or library");
+
+				return;
+			}
+
+			PEFileKinds file_kind;
+
+			switch (Compiler.Settings.Target) {
+			case Target.Library:
+			case Target.Module:
+				file_kind = PEFileKinds.Dll;
+				break;
+			case Target.WinExe:
+				file_kind = PEFileKinds.WindowApplication;
+				break;
+			default:
+				file_kind = PEFileKinds.ConsoleApplication;
+				break;
+			}
+
+			if (entry_point == null) {
+				string main_class = Compiler.Settings.MainClass;
+				if (main_class != null) {
+					// TODO: Handle dotted names
+					var texpr = module.GlobalRootNamespace.LookupType (module, main_class, 0, LookupMode.Probing, Location.Null);
+					if (texpr == null) {
+						Report.Error (1555, "Could not find `{0}' specified for Main method", main_class);
+						return;
+					}
+
+					var mtype = texpr.MemberDefinition as ClassOrStruct;
+					if (mtype == null) {
+						Report.Error (1556, "`{0}' specified for Main method must be a valid class or struct", main_class);
+						return;
+					}
+
+					Report.Error (1558, mtype.Location, "`{0}' does not have a suitable static Main method", mtype.GetSignatureForError ());
+				} else {
+					string pname = file_name == null ? name : Path.GetFileName (file_name);
+					Report.Error (5001, "Program `{0}' does not contain a static `Main' method suitable for an entry point",
+						pname);
+				}
+
+				return;
+			}
+
+			Builder.SetEntryPoint (entry_point.MethodBuilder, file_kind);
+		}
+
+		void Error_ObsoleteSecurityAttribute (Attribute a, string option)
+		{
+			Report.Warning (1699, 1, a.Location,
+				"Use compiler option `{0}' or appropriate project settings instead of `{1}' attribute",
+				option, a.Name);
+		}
+
+		void Error_AssemblySigning (string text)
+		{
+			Report.Error (1548, "Error during assembly signing. " + text);
+		}
+
+		public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
+		{
+			return false;
+		}
+
+		static Version IsValidAssemblyVersion (string version, bool allowGenerated)
+		{
+			string[] parts = version.Split ('.');
+			if (parts.Length < 1 || parts.Length > 4)
+				return null;
+
+			var values = new int[4];
+			for (int i = 0; i < parts.Length; ++i) {
+				if (!int.TryParse (parts[i], out values[i])) {
+					if (parts[i].Length == 1 && parts[i][0] == '*' && allowGenerated) {
+						if (i == 2) {
+							// Nothing can follow *
+							if (parts.Length > 3)
+								return null;
+
+							// Generate Build value based on days since 1/1/2000
+							TimeSpan days = DateTime.Today - new DateTime (2000, 1, 1);
+							values[i] = System.Math.Max (days.Days, 0);
+							i = 3;
+						}
+
+						if (i == 3) {
+							// Generate Revision value based on every other second today
+							var seconds = DateTime.Now - DateTime.Today;
+							values[i] = (int) seconds.TotalSeconds / 2;
+							continue;
+						}
+					}
+
+					return null;
+				}
+
+				if (values[i] > ushort.MaxValue)
+					return null;
+			}
+
+			return new Version (values[0], values[1], values[2], values[3]);
+		}
+	}
+
+	public class AssemblyResource : IEquatable<AssemblyResource>
+	{
+		public AssemblyResource (string fileName, string name)
+			: this (fileName, name, false)
+		{
+		}
+
+		public AssemblyResource (string fileName, string name, bool isPrivate)
+		{
+			FileName = fileName;
+			Name = name;
+			Attributes = isPrivate ? ResourceAttributes.Private : ResourceAttributes.Public;
+		}
+
+		public ResourceAttributes Attributes { get; private set; }
+		public string Name { get; private set; }
+		public string FileName { get; private set; }
+		public bool IsEmbeded { get; set; }
+
+		#region IEquatable<AssemblyResource> Members
+
+		public bool Equals (AssemblyResource other)
+		{
+			return Name == other.Name;
+		}
+
+		#endregion
+	}
+
+	//
+	// A placeholder class for assembly attributes when emitting module
+	//
+	class AssemblyAttributesPlaceholder : CompilerGeneratedContainer
+	{
+		static readonly string TypeNamePrefix = "<$AssemblyAttributes${0}>";
+		public static readonly string AssemblyFieldName = "attributes";
+
+		Field assembly;
+
+		public AssemblyAttributesPlaceholder (ModuleContainer parent, string outputName)
+			: base (parent, new MemberName (GetGeneratedName (outputName)), Modifiers.STATIC | Modifiers.INTERNAL)
+		{
+			assembly = new Field (this, new TypeExpression (parent.Compiler.BuiltinTypes.Object, Location), Modifiers.PUBLIC | Modifiers.STATIC,
+				new MemberName (AssemblyFieldName), null);
+
+			AddField (assembly);
+		}
+
+		public void AddAssemblyAttribute (MethodSpec ctor, byte[] data)
+		{
+			assembly.SetCustomAttribute (ctor, data);
+		}
+
+		public static string GetGeneratedName (string outputName)
+		{
+			return string.Format (TypeNamePrefix, outputName);
+		}
+	}
+
+	//
+	// Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
+	// compiler. This is a default implementation for framework System.Reflection.Emit
+	// which does not implement any of the methods
+	//
+	public class AssemblyBuilderExtension
+	{
+		readonly CompilerContext ctx;
+
+		public AssemblyBuilderExtension (CompilerContext ctx)
+		{
+			this.ctx = ctx;
+		}
+
+		public virtual System.Reflection.Module AddModule (string module)
+		{
+			ctx.Report.RuntimeMissingSupport (Location.Null, "-addmodule");
+			return null;
+		}
+
+		public virtual void AddPermissionRequests (PermissionSet[] permissions)
+		{
+			ctx.Report.RuntimeMissingSupport (Location.Null, "assembly declarative security");
+		}
+
+		public virtual void AddTypeForwarder (TypeSpec type, Location loc)
+		{
+			ctx.Report.RuntimeMissingSupport (loc, "TypeForwardedToAttribute");
+		}
+
+		public virtual void DefineWin32IconResource (string fileName)
+		{
+			ctx.Report.RuntimeMissingSupport (Location.Null, "-win32icon");
+		}
+
+		public virtual void SetAlgorithmId (uint value, Location loc)
+		{
+			ctx.Report.RuntimeMissingSupport (loc, "AssemblyAlgorithmIdAttribute");
+		}
+
+		public virtual void SetCulture (string culture, Location loc)
+		{
+			ctx.Report.RuntimeMissingSupport (loc, "AssemblyCultureAttribute");
+		}
+
+		public virtual void SetFlags (uint flags, Location loc)
+		{
+			ctx.Report.RuntimeMissingSupport (loc, "AssemblyFlagsAttribute");
+		}
+
+		public virtual void SetVersion (Version version, Location loc)
+		{
+			ctx.Report.RuntimeMissingSupport (loc, "AssemblyVersionAttribute");
+		}
+	}
+
+	abstract class AssemblyReferencesLoader<T> where T : class
+	{
+		protected readonly CompilerContext compiler;
+
+		protected readonly List<string> paths;
+
+		protected AssemblyReferencesLoader (CompilerContext compiler)
+		{
+			this.compiler = compiler;
+
+			paths = new List<string> ();
+			paths.Add (Directory.GetCurrentDirectory ());
+			paths.AddRange (compiler.Settings.ReferencesLookupPaths);
+		}
+
+		public abstract bool HasObjectType (T assembly);
+		protected abstract string[] GetDefaultReferences ();
+		public abstract T LoadAssemblyFile (string fileName, bool isImplicitReference);
+		public abstract void LoadReferences (ModuleContainer module);
+
+		protected void Error_FileNotFound (string fileName)
+		{
+			compiler.Report.Error (6, "Metadata file `{0}' could not be found", fileName);
+		}
+
+		protected void Error_FileCorrupted (string fileName)
+		{
+			compiler.Report.Error (9, "Metadata file `{0}' does not contain valid metadata", fileName);
+		}
+
+		protected void Error_AssemblyIsModule (string fileName)
+		{
+			compiler.Report.Error (1509,
+				"Referenced assembly file `{0}' is a module. Consider using `-addmodule' option to add the module",
+				fileName);
+		}
+
+		protected void Error_ModuleIsAssembly (string fileName)
+		{
+			compiler.Report.Error (1542,
+				"Added module file `{0}' is an assembly. Consider using `-r' option to reference the file",
+				fileName);
+		}
+
+		protected void LoadReferencesCore (ModuleContainer module, out T corlib_assembly, out List<Tuple<RootNamespace, T>> loaded)
+		{
+			compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesLoading);
+
+			loaded = new List<Tuple<RootNamespace, T>> ();
+
+			//
+			// Load mscorlib.dll as the first
+			//
+			if (module.Compiler.Settings.StdLib) {
+				corlib_assembly = LoadAssemblyFile ("mscorlib.dll", true);
+			} else {
+				corlib_assembly = default (T);
+			}
+
+			T a;
+			foreach (string r in module.Compiler.Settings.AssemblyReferences) {
+				a = LoadAssemblyFile (r, false);
+				if (a == null || EqualityComparer<T>.Default.Equals (a, corlib_assembly))
+					continue;
+
+				var key = Tuple.Create (module.GlobalRootNamespace, a);
+				if (loaded.Contains (key))
+					continue;
+
+				loaded.Add (key);
+			}
+
+			if (corlib_assembly == null) {
+				//
+				// Requires second pass because HasObjectType can trigger assembly load event
+				//
+				for (int i = 0; i < loaded.Count; ++i) {
+					var assembly = loaded [i];
+
+					//
+					// corlib assembly is the first referenced assembly which contains System.Object
+					//
+					if (HasObjectType (assembly.Item2)) {
+						corlib_assembly = assembly.Item2;
+						loaded.RemoveAt (i);
+						break;
+					}
+				}
+			}
+
+			foreach (var entry in module.Compiler.Settings.AssemblyReferencesAliases) {
+				a = LoadAssemblyFile (entry.Item2, false);
+				if (a == null)
+					continue;
+
+				var key = Tuple.Create (module.CreateRootNamespace (entry.Item1), a);
+				if (loaded.Contains (key))
+					continue;
+
+				loaded.Add (key);
+			}
+
+			if (compiler.Settings.LoadDefaultReferences) {
+				foreach (string r in GetDefaultReferences ()) {
+					a = LoadAssemblyFile (r, true);
+					if (a == null)
+						continue;
+
+					var key = Tuple.Create (module.GlobalRootNamespace, a);
+					if (loaded.Contains (key))
+						continue;
+
+					loaded.Add (key);
+				}
+			}
+
+			compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesLoading);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/assign.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/assign.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/assign.cs	(revision 11807)
@@ -0,0 +1,956 @@
+//
+// assign.cs: Assignments.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Martin Baulig (martin@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)	
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+using System;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	/// <summary>
+	///   This interface is implemented by expressions that can be assigned to.
+	/// </summary>
+	/// <remarks>
+	///   This interface is implemented by Expressions whose values can not
+	///   store the result on the top of the stack.
+	///
+	///   Expressions implementing this (Properties, Indexers and Arrays) would
+	///   perform an assignment of the Expression "source" into its final
+	///   location.
+	///
+	///   No values on the top of the stack are expected to be left by
+	///   invoking this method.
+	/// </remarks>
+	public interface IAssignMethod {
+		//
+		// This is an extra version of Emit. If leave_copy is `true'
+		// A copy of the expression will be left on the stack at the
+		// end of the code generated for EmitAssign
+		//
+		void Emit (EmitContext ec, bool leave_copy);
+
+		//
+		// This method does the assignment
+		// `source' will be stored into the location specified by `this'
+		// if `leave_copy' is true, a copy of `source' will be left on the stack
+		// if `prepare_for_load' is true, when `source' is emitted, there will
+		// be data on the stack that it can use to compuatate its value. This is
+		// for expressions like a [f ()] ++, where you can't call `f ()' twice.
+		//
+		void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound);
+
+		/*
+		For simple assignments, this interface is very simple, EmitAssign is called with source
+		as the source expression and leave_copy and prepare_for_load false.
+
+		For compound assignments it gets complicated.
+
+		EmitAssign will be called as before, however, prepare_for_load will be
+		true. The @source expression will contain an expression
+		which calls Emit. So, the calls look like:
+
+		this.EmitAssign (ec, source, false, true) ->
+			source.Emit (ec); ->
+				[...] ->
+					this.Emit (ec, false); ->
+					end this.Emit (ec, false); ->
+				end [...]
+			end source.Emit (ec);
+		end this.EmitAssign (ec, source, false, true)
+
+
+		When prepare_for_load is true, EmitAssign emits a `token' on the stack that
+		Emit will use for its state.
+
+		Let's take FieldExpr as an example. assume we are emitting f ().y += 1;
+
+		Here is the call tree again. This time, each call is annotated with the IL
+		it produces:
+
+		this.EmitAssign (ec, source, false, true)
+			call f
+			dup
+
+			Binary.Emit ()
+				this.Emit (ec, false);
+				ldfld y
+				end this.Emit (ec, false);
+
+				IntConstant.Emit ()
+				ldc.i4.1
+				end IntConstant.Emit
+
+				add
+			end Binary.Emit ()
+
+			stfld
+		end this.EmitAssign (ec, source, false, true)
+
+		Observe two things:
+			1) EmitAssign left a token on the stack. It was the result of f ().
+			2) This token was used by Emit
+
+		leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy
+		of the expression at that point in evaluation. This is used for pre/post inc/dec
+		and for a = x += y. Let's do the above example with leave_copy true in EmitAssign
+
+		this.EmitAssign (ec, source, true, true)
+			call f
+			dup
+
+			Binary.Emit ()
+				this.Emit (ec, false);
+				ldfld y
+				end this.Emit (ec, false);
+
+				IntConstant.Emit ()
+				ldc.i4.1
+				end IntConstant.Emit
+
+				add
+			end Binary.Emit ()
+
+			dup
+			stloc temp
+			stfld
+			ldloc temp
+		end this.EmitAssign (ec, source, true, true)
+
+		And with it true in Emit
+
+		this.EmitAssign (ec, source, false, true)
+			call f
+			dup
+
+			Binary.Emit ()
+				this.Emit (ec, true);
+				ldfld y
+				dup
+				stloc temp
+				end this.Emit (ec, true);
+
+				IntConstant.Emit ()
+				ldc.i4.1
+				end IntConstant.Emit
+
+				add
+			end Binary.Emit ()
+
+			stfld
+			ldloc temp
+		end this.EmitAssign (ec, source, false, true)
+
+		Note that these two examples are what happens for ++x and x++, respectively.
+		*/
+	}
+
+	/// <summary>
+	///   An Expression to hold a temporary value.
+	/// </summary>
+	/// <remarks>
+	///   The LocalTemporary class is used to hold temporary values of a given
+	///   type to "simulate" the expression semantics. The local variable is
+	///   never captured.
+	///
+	///   The local temporary is used to alter the normal flow of code generation
+	///   basically it creates a local variable, and its emit instruction generates
+	///   code to access this value, return its address or save its value.
+	///
+	///   If `is_address' is true, then the value that we store is the address to the
+	///   real value, and not the value itself.
+	///
+	///   This is needed for a value type, because otherwise you just end up making a
+	///   copy of the value on the stack and modifying it. You really need a pointer
+	///   to the origional value so that you can modify it in that location. This
+	///   Does not happen with a class because a class is a pointer -- so you always
+	///   get the indirection.
+	///
+	/// </remarks>
+	public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
+		LocalBuilder builder;
+
+		public LocalTemporary (TypeSpec t)
+		{
+			type = t;
+			eclass = ExprClass.Value;
+		}
+
+		public LocalTemporary (LocalBuilder b, TypeSpec t)
+			: this (t)
+		{
+			builder = b;
+		}
+
+		public void Release (EmitContext ec)
+		{
+			ec.FreeTemporaryLocal (builder, type);
+			builder = null;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (1);
+			args.Add (new Argument (this));
+			return CreateExpressionFactoryCall (ec, "Constant", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (builder == null)
+				throw new InternalErrorException ("Emit without Store, or after Release");
+
+			ec.Emit (OpCodes.Ldloc, builder);
+		}
+
+		#region IAssignMethod Members
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			Emit (ec);
+
+			if (leave_copy)
+				Emit (ec);
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			if (isCompound)
+				throw new NotImplementedException ();
+
+			source.Emit (ec);
+
+			Store (ec);
+
+			if (leave_copy)
+				Emit (ec);
+		}
+
+		#endregion
+
+		public LocalBuilder Builder {
+			get { return builder; }
+		}
+
+		public void Store (EmitContext ec)
+		{
+			if (builder == null)
+				builder = ec.GetTemporaryLocal (type);
+
+			ec.Emit (OpCodes.Stloc, builder);
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			if (builder == null)
+				builder = ec.GetTemporaryLocal (type);
+
+			if (builder.LocalType.IsByRef) {
+				//
+				// if is_address, than this is just the address anyways,
+				// so we just return this.
+				//
+				ec.Emit (OpCodes.Ldloc, builder);
+			} else {
+				ec.Emit (OpCodes.Ldloca, builder);
+			}
+		}
+	}
+
+	/// <summary>
+	///   The Assign node takes care of assigning the value of source into
+	///   the expression represented by target.
+	/// </summary>
+	public abstract class Assign : ExpressionStatement {
+		protected Expression target, source;
+
+		protected Assign (Expression target, Expression source, Location loc)
+		{
+			this.target = target;
+			this.source = source;
+			this.loc = loc;
+		}
+		
+		public Expression Target {
+			get { return target; }
+		}
+
+		public Expression Source {
+			get {
+				return source;
+			}
+		}
+
+		public override Location StartLocation {
+			get {
+				return target.StartLocation;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return target.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator");
+			return null;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			bool ok = true;
+			source = source.Resolve (ec);
+						
+			if (source == null) {
+				ok = false;
+				source = ErrorExpression.Instance;
+			}
+
+			target = target.ResolveLValue (ec, source);
+
+			if (target == null || !ok)
+				return null;
+
+			TypeSpec target_type = target.Type;
+			TypeSpec source_type = source.Type;
+
+			eclass = ExprClass.Value;
+			type = target_type;
+
+			if (!(target is IAssignMethod)) {
+				target.Error_ValueAssignment (ec, source);
+				return null;
+			}
+
+			if (target_type != source_type) {
+				Expression resolved = ResolveConversions (ec);
+
+				if (resolved != this)
+					return resolved;
+			}
+
+			return this;
+		}
+
+#if NET_4_0 || MOBILE_DYNAMIC
+		public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
+		{
+			var tassign = target as IDynamicAssign;
+			if (tassign == null)
+				throw new InternalErrorException (target.GetType () + " does not support dynamic assignment");
+
+			var target_object = tassign.MakeAssignExpression (ctx, source);
+
+			//
+			// Some hacking is needed as DLR does not support void type and requires
+			// always have object convertible return type to support caching and chaining
+			//
+			// We do this by introducing an explicit block which returns RHS value when
+			// available or null
+			//
+			if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block)
+				return target_object;
+
+			System.Linq.Expressions.UnaryExpression source_object;
+			if (ctx.HasSet (BuilderContext.Options.CheckedScope)) {
+				source_object = System.Linq.Expressions.Expression.ConvertChecked (source.MakeExpression (ctx), target_object.Type);
+			} else {
+				source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type);
+			}
+
+			return System.Linq.Expressions.Expression.Assign (target_object, source_object);
+		}
+#endif
+		protected virtual Expression ResolveConversions (ResolveContext ec)
+		{
+			source = Convert.ImplicitConversionRequired (ec, source, target.Type, source.Location);
+			if (source == null)
+				return null;
+
+			return this;
+		}
+
+		void Emit (EmitContext ec, bool is_statement)
+		{
+			IAssignMethod t = (IAssignMethod) target;
+			t.EmitAssign (ec, source, !is_statement, this is CompoundAssign);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Emit (ec, false);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			Emit (ec, true);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			source.FlowAnalysis (fc);
+
+			if (target is ArrayAccess || target is IndexerExpr || target is PropertyExpr)
+				target.FlowAnalysis (fc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Assign _target = (Assign) t;
+
+			_target.target = target.Clone (clonectx);
+			_target.source = source.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class SimpleAssign : Assign
+	{
+		public SimpleAssign (Expression target, Expression source)
+			: this (target, source, target.Location)
+		{
+		}
+
+		public SimpleAssign (Expression target, Expression source, Location loc)
+			: base (target, source, loc)
+		{
+		}
+
+		bool CheckEqualAssign (Expression t)
+		{
+			if (source is Assign) {
+				Assign a = (Assign) source;
+				if (t.Equals (a.Target))
+					return true;
+				return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t);
+			}
+			return t.Equals (source);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			Expression e = base.DoResolve (ec);
+			if (e == null || e != this)
+				return e;
+
+			if (CheckEqualAssign (target))
+				ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?");
+
+			return this;
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.FlowAnalysis (fc);
+
+			var vr = target as VariableReference;
+			if (vr != null) {
+				if (vr.VariableInfo != null)
+					fc.SetVariableAssigned (vr.VariableInfo);
+
+				return;
+			}
+
+			var fe = target as FieldExpr;
+			if (fe != null) {
+				fe.SetFieldAssigned (fc);
+				return;
+			}
+		}
+
+		public override void MarkReachable (Reachability rc)
+		{
+			var es = source as ExpressionStatement;
+			if (es != null)
+				es.MarkReachable (rc);
+		}
+	}
+
+	public class RuntimeExplicitAssign : Assign
+	{
+		public RuntimeExplicitAssign (Expression target, Expression source)
+			: base (target, source, target.Location)
+		{
+		}
+
+		protected override Expression ResolveConversions (ResolveContext ec)
+		{
+			source = EmptyCast.Create (source, target.Type);
+			return this;
+		}
+	}
+
+	//
+	// Compiler generated assign
+	//
+	class CompilerAssign : Assign
+	{
+		public CompilerAssign (Expression target, Expression source, Location loc)
+			: base (target, source, loc)
+		{
+			if (target.Type != null) {
+				type = target.Type;
+				eclass = ExprClass.Value;
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			var expr = base.DoResolve (ec);
+			var vr = target as VariableReference;
+			if (vr != null && vr.VariableInfo != null)
+				vr.VariableInfo.IsEverAssigned = false;
+
+			return expr;
+		}
+
+		public void UpdateSource (Expression source)
+		{
+			base.source = source;
+		}
+	}
+
+	//
+	// Implements fields and events class initializers
+	//
+	public class FieldInitializer : Assign
+	{
+		//
+		// Field initializers are tricky for partial classes. They have to
+		// share same constructor (block) for expression trees resolve but
+		// they have they own resolve scope
+		//
+		sealed class FieldInitializerContext : BlockContext
+		{
+			readonly ExplicitBlock ctor_block;
+
+			public FieldInitializerContext (IMemberContext mc, BlockContext constructorContext)
+				: base (mc, null, constructorContext.ReturnType)
+			{
+				flags |= Options.FieldInitializerScope | Options.ConstructorScope;
+				this.ctor_block = constructorContext.CurrentBlock.Explicit;
+
+				if (ctor_block.IsCompilerGenerated)
+					CurrentBlock = ctor_block;
+			}
+
+			public override ExplicitBlock ConstructorBlock {
+			    get {
+			        return ctor_block;
+			    }
+			}
+		}
+
+		//
+		// Keep resolved value because field initializers have their own rules
+		//
+		ExpressionStatement resolved;
+		FieldBase mc;
+
+		public FieldInitializer (FieldBase mc, Expression expression, Location loc)
+			: base (new FieldExpr (mc.Spec, expression.Location), expression, loc)
+		{
+			this.mc = mc;
+			if (!mc.IsStatic)
+				((FieldExpr)target).InstanceExpression = new CompilerGeneratedThis (mc.CurrentType, expression.Location);
+		}
+
+		public int AssignmentOffset { get; private set; }
+
+		public FieldBase Field {
+			get {
+				return mc;
+			}
+		}
+
+		public override Location StartLocation {
+			get {
+				return loc;
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			// Field initializer can be resolved (fail) many times
+			if (source == null)
+				return null;
+
+			if (resolved == null) {
+				var bc = (BlockContext) rc;
+				var ctx = new FieldInitializerContext (mc, bc);
+				resolved = base.DoResolve (ctx) as ExpressionStatement;
+				AssignmentOffset = ctx.AssignmentInfoOffset - bc.AssignmentInfoOffset;
+			}
+
+			return resolved;
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			if (resolved == null)
+				return;
+
+			//
+			// Emit sequence symbol info even if we are in compiler generated
+			// block to allow debugging field initializers when constructor is
+			// compiler generated
+			//
+			if (ec.HasSet (BuilderContext.Options.OmitDebugInfo) && ec.HasMethodSymbolBuilder) {
+				using (ec.With (BuilderContext.Options.OmitDebugInfo, false)) {
+					ec.Mark (loc);
+				}
+			}
+
+			if (resolved != this)
+				resolved.EmitStatement (ec);
+			else
+				base.EmitStatement (ec);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			source.FlowAnalysis (fc);
+			((FieldExpr) target).SetFieldAssigned (fc);
+		}
+		
+		public bool IsDefaultInitializer {
+			get {
+				Constant c = source as Constant;
+				if (c == null)
+					return false;
+				
+				FieldExpr fe = (FieldExpr)target;
+				return c.IsDefaultInitializer (fe.Type);
+			}
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return source.IsSideEffectFree;
+			}
+		}
+	}
+
+	class PrimaryConstructorAssign : SimpleAssign
+	{
+		readonly Field field;
+		readonly Parameter parameter;
+
+		public PrimaryConstructorAssign (Field field, Parameter parameter)
+			: base (null, null, parameter.Location)
+		{
+			this.field = field;
+			this.parameter = parameter;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			target = new FieldExpr (field, loc);
+			source = rc.CurrentBlock.ParametersBlock.GetParameterInfo (parameter).CreateReferenceExpression (rc, loc);
+			return base.DoResolve (rc);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				base.EmitStatement (ec);
+			}
+		}
+	}
+
+	//
+	// This class is used for compound assignments.
+	//
+	public class CompoundAssign : Assign
+	{
+		// This is just a hack implemented for arrays only
+		public sealed class TargetExpression : Expression
+		{
+			readonly Expression child;
+
+			public TargetExpression (Expression child)
+			{
+				this.child = child;
+				this.loc = child.Location;
+			}
+
+			public override bool ContainsEmitWithAwait ()
+			{
+				return child.ContainsEmitWithAwait ();
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				throw new NotSupportedException ("ET");
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				type = child.Type;
+				eclass = ExprClass.Value;
+				return this;
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				child.Emit (ec);
+			}
+
+			public override Expression EmitToField (EmitContext ec)
+			{
+				return child.EmitToField (ec);
+			}
+		}
+
+		// Used for underlying binary operator
+		readonly Binary.Operator op;
+		Expression right;
+		Expression left;
+		
+		public Binary.Operator Op {
+			get {
+				return op;
+			}
+		}
+
+		public CompoundAssign (Binary.Operator op, Expression target, Expression source)
+			: base (target, source, target.Location)
+		{
+			right = source;
+			this.op = op;
+		}
+
+		public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left)
+			: this (op, target, source)
+		{
+			this.left = left;
+		}
+
+		public Binary.Operator Operator {
+			get {
+				return op;
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			right = right.Resolve (ec);
+			if (right == null)
+				return null;
+
+			MemberAccess ma = target as MemberAccess;
+			using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) {
+				target = target.Resolve (ec);
+			}
+			
+			if (target == null)
+				return null;
+
+			if (target is MethodGroupExpr){
+				ec.Report.Error (1656, loc,
+					"Cannot assign to `{0}' because it is a `{1}'",
+					((MethodGroupExpr)target).Name, target.ExprClassName);
+				return null;
+			}
+
+			var event_expr = target as EventExpr;
+			if (event_expr != null) {
+				source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc);
+				if (source == null)
+					return null;
+
+				Expression rside;
+				if (op == Binary.Operator.Addition)
+					rside = EmptyExpression.EventAddition;
+				else if (op == Binary.Operator.Subtraction)
+					rside = EmptyExpression.EventSubtraction;
+				else
+					rside = null;
+
+				target = target.ResolveLValue (ec, rside);
+				if (target == null)
+					return null;
+
+				eclass = ExprClass.Value;
+				type = event_expr.Operator.ReturnType;
+				return this;
+			}
+
+			//
+			// Only now we can decouple the original source/target
+			// into a tree, to guarantee that we do not have side
+			// effects.
+			//
+			if (left == null)
+				left = new TargetExpression (target);
+
+			source = new Binary (op, left, right, true);
+
+			if (target is DynamicMemberAssignable) {
+				Arguments targs = ((DynamicMemberAssignable) target).Arguments;
+				source = source.Resolve (ec);
+
+				Arguments args = new Arguments (targs.Count + 1);
+				args.AddRange (targs);
+				args.Add (new Argument (source));
+
+				var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment;
+
+				//
+				// Compound assignment does target conversion using additional method
+				// call, set checked context as the binary operation can overflow
+				//
+				if (ec.HasSet (ResolveContext.Options.CheckedScope))
+					binder_flags |= CSharpBinderFlags.CheckedContext;
+
+				if (target is DynamicMemberBinder) {
+					source = new DynamicMemberBinder (ma.Name, binder_flags, args, loc).Resolve (ec);
+
+					// Handles possible event addition/subtraction
+					if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) {
+						args = new Arguments (targs.Count + 1);
+						args.AddRange (targs);
+						args.Add (new Argument (right));
+						string method_prefix = op == Binary.Operator.Addition ?
+							Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;
+
+						var invoke = DynamicInvocation.CreateSpecialNameInvoke (
+							new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec);
+
+						args = new Arguments (targs.Count);
+						args.AddRange (targs);
+						source = new DynamicEventCompoundAssign (ma.Name, args,
+							(ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec);
+					}
+				} else {
+					source = new DynamicIndexBinder (binder_flags, args, loc).Resolve (ec);
+				}
+
+				return source;
+			}
+
+			return base.DoResolve (ec);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			target.FlowAnalysis (fc);
+			source.FlowAnalysis (fc);
+		}
+
+		protected override Expression ResolveConversions (ResolveContext ec)
+		{
+			//
+			// LAMESPEC: Under dynamic context no target conversion is happening
+			// This allows more natual dynamic behaviour but breaks compatibility
+			// with static binding
+			//
+			if (target is RuntimeValueExpression)
+				return this;
+
+			TypeSpec target_type = target.Type;
+
+			//
+			// 1. the return type is implicitly convertible to the type of target
+			//
+			if (Convert.ImplicitConversionExists (ec, source, target_type)) {
+				source = Convert.ImplicitConversion (ec, source, target_type, loc);
+				return this;
+			}
+
+			//
+			// Otherwise, if the selected operator is a predefined operator
+			//
+			Binary b = source as Binary;
+			if (b == null) {
+				if (source is ReducedExpression)
+					b = ((ReducedExpression) source).OriginalExpression as Binary;
+				else if (source is ReducedExpression.ReducedConstantExpression) {
+					b = ((ReducedExpression.ReducedConstantExpression) source).OriginalExpression as Binary;
+				} else if (source is Nullable.LiftedBinaryOperator) {
+					var po = ((Nullable.LiftedBinaryOperator) source);
+					if (po.UserOperator == null)
+						b = po.Binary;
+				} else if (source is TypeCast) {
+					b = ((TypeCast) source).Child as Binary;
+				}
+			}
+
+			if (b != null) {
+				//
+				// 2a. the operator is a shift operator
+				//
+				// 2b. the return type is explicitly convertible to the type of x, and
+				// y is implicitly convertible to the type of x
+				//
+				if ((b.Oper & Binary.Operator.ShiftMask) != 0 ||
+					Convert.ImplicitConversionExists (ec, right, target_type)) {
+					source = Convert.ExplicitConversion (ec, source, target_type, loc);
+					return this;
+				}
+			}
+
+			if (source.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Arguments arg = new Arguments (1);
+				arg.Add (new Argument (source));
+				return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec);
+			}
+
+			right.Error_ValueCannotBeConverted (ec, target_type, false);
+			return null;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			CompoundAssign ctarget = (CompoundAssign) t;
+
+			ctarget.right = ctarget.source = source.Clone (clonectx);
+			ctarget.target = target.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/async.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/async.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/async.cs	(revision 11807)
@@ -0,0 +1,1005 @@
+//
+// async.cs: Asynchronous functions
+//
+// Author:
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2011 Novell, Inc.
+// Copyright 2011-2012 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Collections;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	public class Await : ExpressionStatement
+	{
+		Expression expr;
+		AwaitStatement stmt;
+		
+		public Expression Expression {
+			get {
+				return expr;
+			}
+		}
+		
+		public Await (Expression expr, Location loc)
+		{
+			this.expr = expr;
+			this.loc = loc;
+		}
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		public AwaitStatement Statement {
+			get {
+				return stmt;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			var t = (Await) target;
+
+			t.expr = expr.Clone (clonectx);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotImplementedException ("ET");
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return true;
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			stmt.Expr.FlowAnalysis (fc);
+
+			stmt.RegisterResumePoint ();
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			if (rc.HasSet (ResolveContext.Options.LockScope)) {
+				rc.Report.Error (1996, loc,
+					"The `await' operator cannot be used in the body of a lock statement");
+			}
+
+			if (rc.IsUnsafe) {
+				rc.Report.Error (4004, loc,
+					"The `await' operator cannot be used in an unsafe context");
+			}
+
+			var bc = (BlockContext) rc;
+
+			stmt = new AwaitStatement (expr, loc);
+			if (!stmt.Resolve (bc))
+				return null;
+
+			type = stmt.ResultType;
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			stmt.EmitPrologue (ec);
+
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				stmt.Emit (ec);
+			}
+		}
+		
+		public override Expression EmitToField (EmitContext ec)
+		{
+			stmt.EmitPrologue (ec);
+			return stmt.GetResultExpression (ec);
+		}
+		
+		public void EmitAssign (EmitContext ec, FieldExpr field)
+		{
+			stmt.EmitPrologue (ec);
+			field.InstanceExpression.Emit (ec);
+			stmt.Emit (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			stmt.EmitStatement (ec);
+		}
+
+		public override void MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			stmt.MarkReachable (rc);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class AwaitStatement : YieldStatement<AsyncInitializer>
+	{
+		public sealed class AwaitableMemberAccess : MemberAccess
+		{
+			public AwaitableMemberAccess (Expression expr)
+				: base (expr, "GetAwaiter")
+			{
+			}
+
+			public bool ProbingMode { get; set; }
+
+			protected override void Error_TypeDoesNotContainDefinition (ResolveContext rc, TypeSpec type, string name)
+			{
+				Error_OperatorCannotBeApplied (rc, type);
+			}
+
+			protected override void Error_OperatorCannotBeApplied (ResolveContext rc, TypeSpec type)
+			{
+				if (ProbingMode)
+					return;
+
+				var invocation = LeftExpression as Invocation;
+				if (invocation != null && invocation.MethodGroup != null && (invocation.MethodGroup.BestCandidate.Modifiers & Modifiers.ASYNC) != 0) {
+					rc.Report.Error (4008, loc, "Cannot await void method `{0}'. Consider changing method return type to `Task'",
+						invocation.GetSignatureForError ());
+				} else {
+					rc.Report.Error (4001, loc, "Cannot await `{0}' expression", type.GetSignatureForError ());
+				}
+			}
+		}
+
+		sealed class GetResultInvocation : Invocation
+		{
+			public GetResultInvocation (MethodGroupExpr mge, Arguments arguments)
+				: base (null, arguments)
+			{
+				mg = mge;
+				type = mg.BestCandidateReturnType;
+			}
+
+			public override Expression EmitToField (EmitContext ec)
+			{
+				return this;
+			}
+		}
+
+		Field awaiter;
+		AwaiterDefinition awaiter_definition;
+		TypeSpec type;
+		TypeSpec result_type;
+
+		public AwaitStatement (Expression expr, Location loc)
+			: base (expr, loc)
+		{
+			unwind_protect = true;
+		}
+
+		#region Properties
+
+		bool IsDynamic {
+			get {
+				return awaiter_definition == null;
+			}
+		}
+
+		public TypeSpec ResultType {
+			get {
+				return result_type;
+			}
+		}
+
+		#endregion
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				GetResultExpression (ec).Emit (ec);
+			}
+		}
+
+		public Expression GetResultExpression (EmitContext ec)
+		{
+			var fe_awaiter = new FieldExpr (awaiter, loc);
+			fe_awaiter.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
+
+			//
+			// result = awaiter.GetResult ();
+			//
+			if (IsDynamic) {
+				var rc = new ResolveContext (ec.MemberContext);
+				return new Invocation (new MemberAccess (fe_awaiter, "GetResult"), new Arguments (0)).Resolve (rc);
+			}
+			
+			var mg_result = MethodGroupExpr.CreatePredefined (awaiter_definition.GetResult, fe_awaiter.Type, loc);
+			mg_result.InstanceExpression = fe_awaiter;
+
+			return new GetResultInvocation (mg_result, new Arguments (0));
+		}
+
+		public void EmitPrologue (EmitContext ec)
+		{
+			awaiter = ((AsyncTaskStorey) machine_initializer.Storey).AddAwaiter (expr.Type);
+
+			var fe_awaiter = new FieldExpr (awaiter, loc);
+			fe_awaiter.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
+
+			Label skip_continuation = ec.DefineLabel ();
+
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				//
+				// awaiter = expr.GetAwaiter ();
+				//
+				fe_awaiter.EmitAssign (ec, expr, false, false);
+
+				Expression completed_expr;
+				if (IsDynamic) {
+					var rc = new ResolveContext (ec.MemberContext);
+
+					Arguments dargs = new Arguments (1);
+					dargs.Add (new Argument (fe_awaiter));
+					completed_expr = new DynamicMemberBinder ("IsCompleted", dargs, loc).Resolve (rc);
+
+					dargs = new Arguments (1);
+					dargs.Add (new Argument (completed_expr));
+					completed_expr = new DynamicConversion (ec.Module.Compiler.BuiltinTypes.Bool, 0, dargs, loc).Resolve (rc);
+				} else {
+					var pe = PropertyExpr.CreatePredefined (awaiter_definition.IsCompleted, loc);
+					pe.InstanceExpression = fe_awaiter;
+					completed_expr = pe;
+				}
+
+				completed_expr.EmitBranchable (ec, skip_continuation, true);
+			}
+
+			base.DoEmit (ec);
+
+			//
+			// The stack has to be empty before calling await continuation. We handle this
+			// by lifting values which would be left on stack into class fields. The process
+			// is quite complicated and quite hard to test because any expression can possibly
+			// leave a value on the stack.
+			//
+			// Following assert fails when some of expression called before is missing EmitToField
+			// or parent expression fails to find await in children expressions
+			//
+			ec.AssertEmptyStack ();
+
+			var storey = (AsyncTaskStorey) machine_initializer.Storey;
+			if (IsDynamic) {
+				storey.EmitAwaitOnCompletedDynamic (ec, fe_awaiter);
+			} else {
+				storey.EmitAwaitOnCompleted (ec, fe_awaiter);
+			}
+
+			// Return ok
+			machine_initializer.EmitLeave (ec, unwind_protect);
+
+			ec.MarkLabel (resume_point);
+			ec.MarkLabel (skip_continuation);
+		}
+
+		public void EmitStatement (EmitContext ec)
+		{
+			EmitPrologue (ec);
+			DoEmit (ec);
+
+			awaiter.IsAvailableForReuse = true;
+
+			if (ResultType.Kind != MemberKind.Void)
+				ec.Emit (OpCodes.Pop);
+		}
+
+		void Error_WrongAwaiterPattern (ResolveContext rc, TypeSpec awaiter)
+		{
+			rc.Report.Error (4011, loc, "The awaiter type `{0}' must have suitable IsCompleted and GetResult members",
+				awaiter.GetSignatureForError ());
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			if (bc.CurrentBlock is Linq.QueryBlock) {
+				bc.Report.Error (1995, loc,
+					"The `await' operator may only be used in a query expression within the first collection expression of the initial `from' clause or within the collection expression of a `join' clause");
+				return false;
+			}
+
+			if (!base.Resolve (bc))
+				return false;
+
+			type = expr.Type;
+			Arguments args = new Arguments (0);
+
+			//
+			// The await expression is of dynamic type
+			//
+			if (type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				result_type = type;
+				expr = new Invocation (new MemberAccess (expr, "GetAwaiter"), args).Resolve (bc);
+				return true;
+			}
+
+			//
+			// Check whether the expression is awaitable
+			//
+			Expression ama = new AwaitableMemberAccess (expr).Resolve (bc);
+			if (ama == null)
+				return false;
+
+			var errors_printer = new SessionReportPrinter ();
+			var old = bc.Report.SetPrinter (errors_printer);
+			ama = new Invocation (ama, args).Resolve (bc);
+			bc.Report.SetPrinter (old);
+
+			if (errors_printer.ErrorsCount > 0 || !MemberAccess.IsValidDotExpression (ama.Type)) {
+				bc.Report.Error (1986, expr.Location,
+					"The `await' operand type `{0}' must have suitable GetAwaiter method",
+					expr.Type.GetSignatureForError ());
+
+				return false;
+			}
+
+			var awaiter_type = ama.Type;
+
+			awaiter_definition = bc.Module.GetAwaiter (awaiter_type);
+
+			if (!awaiter_definition.IsValidPattern) {
+				Error_WrongAwaiterPattern (bc, awaiter_type);
+				return false;
+			}
+
+			if (!awaiter_definition.INotifyCompletion) {
+				bc.Report.Error (4027, loc, "The awaiter type `{0}' must implement interface `{1}'",
+					awaiter_type.GetSignatureForError (), bc.Module.PredefinedTypes.INotifyCompletion.GetSignatureForError ());
+				return false;
+			}
+
+			expr = ama;
+			result_type = awaiter_definition.GetResult.ReturnType;
+
+			return true;
+		}
+	}
+
+	class AsyncInitializerStatement : StatementExpression
+	{
+		public AsyncInitializerStatement (AsyncInitializer expr)
+			: base (expr)
+		{
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.DoFlowAnalysis (fc);
+
+			var init = (AsyncInitializer) Expr;
+			var res = !init.Block.HasReachableClosingBrace;
+			var storey = (AsyncTaskStorey) init.Storey;
+
+			if (storey.ReturnType.IsGenericTask)
+				return res;
+
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (!rc.IsUnreachable)
+				reachable = true;
+
+			var init = (AsyncInitializer) Expr;
+			rc = init.Block.MarkReachable (rc);
+
+			var storey = (AsyncTaskStorey) init.Storey;
+
+			//
+			// Explicit return is required for Task<T> state machine
+			//
+			if (storey.ReturnType != null && storey.ReturnType.IsGenericTask)
+				return rc;
+
+		    return Reachability.CreateUnreachable ();
+		}
+	}
+
+	public class AsyncInitializer : StateMachineInitializer
+	{
+		TypeInferenceContext return_inference;
+
+		public AsyncInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
+			: base (block, host, returnType)
+		{
+		}
+
+		#region Properties
+
+		public override string ContainerType {
+			get {
+				return "async state machine block";
+			}
+		}
+
+		public TypeSpec DelegateType {
+			get; set;
+		}
+
+		public StackFieldExpr HoistedReturnState {
+			get; set;
+		}
+
+		public override bool IsIterator {
+			get {
+				return false;
+			}
+		}
+
+		public TypeInferenceContext ReturnTypeInference {
+			get {
+				return return_inference;
+			}
+		}
+
+		#endregion
+
+		protected override BlockContext CreateBlockContext (BlockContext bc)
+		{
+			var ctx = base.CreateBlockContext (bc);
+			var am = bc.CurrentAnonymousMethod as AnonymousMethodBody;
+			if (am != null)
+				return_inference = am.ReturnTypeInference;
+
+			ctx.Set (ResolveContext.Options.TryScope);
+
+			return ctx;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void EmitCatchBlock (EmitContext ec)
+		{
+			var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
+
+			ec.BeginCatchBlock (catch_value.Type);
+			catch_value.EmitAssign (ec);
+
+			ec.EmitThis ();
+			ec.EmitInt ((int) IteratorStorey.State.After);
+			ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+			((AsyncTaskStorey) Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
+
+			ec.Emit (OpCodes.Leave, move_next_ok);
+			ec.EndExceptionBlock ();
+
+		}
+
+		protected override void EmitMoveNextEpilogue (EmitContext ec)
+		{
+			var storey = (AsyncTaskStorey) Storey;
+			storey.EmitSetResult (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			var storey = (AsyncTaskStorey) Storey;
+			storey.EmitInitializer (ec);
+			ec.Emit (OpCodes.Ret);
+		}
+
+		public override void MarkReachable (Reachability rc)
+		{
+			//
+			// Reachability has been done in AsyncInitializerStatement
+			//
+		}
+	}
+
+	class AsyncTaskStorey : StateMachine
+	{
+		int awaiters;
+		Field builder;
+		readonly TypeSpec return_type;
+		MethodSpec set_result;
+		MethodSpec set_exception;
+		MethodSpec builder_factory;
+		MethodSpec builder_start;
+		PropertySpec task;
+		int locals_captured;
+		Dictionary<TypeSpec, List<Field>> stack_fields;
+		Dictionary<TypeSpec, List<Field>> awaiter_fields;
+
+		public AsyncTaskStorey (ParametersBlock block, IMemberContext context, AsyncInitializer initializer, TypeSpec type)
+			: base (block, initializer.Host, context.CurrentMemberDefinition as MemberBase, context.CurrentTypeParameters, "async", MemberKind.Struct)
+		{
+			return_type = type;
+			awaiter_fields = new Dictionary<TypeSpec, List<Field>> ();
+		}
+
+		#region Properties
+
+		public Expression HoistedReturnValue { get; set; }
+
+		public TypeSpec ReturnType {
+			get {
+				return return_type;
+			}
+		}
+
+		public PropertySpec Task {
+			get {
+				return task;
+			}
+		}
+
+		protected override TypeAttributes TypeAttr {
+			get {
+				return base.TypeAttr & ~TypeAttributes.SequentialLayout;
+			}
+		}
+
+		#endregion
+
+		public Field AddAwaiter (TypeSpec type)
+		{
+			if (mutator != null)
+				type = mutator.Mutate (type);
+
+			List<Field> existing_fields;
+			if (awaiter_fields.TryGetValue (type, out existing_fields)) {
+				foreach (var f in existing_fields) {
+					if (f.IsAvailableForReuse) {
+						f.IsAvailableForReuse = false;
+						return f;
+					}
+				}
+			}
+
+			var field = AddCompilerGeneratedField ("$awaiter" + awaiters++.ToString ("X"), new TypeExpression (type, Location), true);
+			field.Define ();
+
+			if (existing_fields == null) {
+				existing_fields = new List<Field> ();
+				awaiter_fields.Add (type, existing_fields);
+			}
+
+			existing_fields.Add (field);
+			return field;
+		}
+
+		public Field AddCapturedLocalVariable (TypeSpec type, bool requiresUninitialized = false)
+		{
+			if (mutator != null)
+				type = mutator.Mutate (type);
+
+			List<Field> existing_fields = null;
+			if (stack_fields == null) {
+				stack_fields = new Dictionary<TypeSpec, List<Field>> ();
+			} else if (stack_fields.TryGetValue (type, out existing_fields) && !requiresUninitialized) {
+				foreach (var f in existing_fields) {
+					if (f.IsAvailableForReuse) {
+						f.IsAvailableForReuse = false;
+						return f;
+					}
+				}
+			}
+
+			var field = AddCompilerGeneratedField ("$stack" + locals_captured++.ToString ("X"), new TypeExpression (type, Location), true);
+			field.Define ();
+
+			if (existing_fields == null) {
+				existing_fields = new List<Field> ();
+				stack_fields.Add (type, existing_fields);
+			}
+
+			existing_fields.Add (field);
+
+			return field;
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			PredefinedType builder_type;
+			PredefinedMember<MethodSpec> bf;
+			PredefinedMember<MethodSpec> bs;
+			PredefinedMember<MethodSpec> sr;
+			PredefinedMember<MethodSpec> se;
+			PredefinedMember<MethodSpec> sm;
+			bool has_task_return_type = false;
+			var pred_members = Module.PredefinedMembers;
+
+			if (return_type.Kind == MemberKind.Void) {
+				builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder;
+				bf = pred_members.AsyncVoidMethodBuilderCreate;
+				bs = pred_members.AsyncVoidMethodBuilderStart;
+				sr = pred_members.AsyncVoidMethodBuilderSetResult;
+				se = pred_members.AsyncVoidMethodBuilderSetException;
+				sm = pred_members.AsyncVoidMethodBuilderSetStateMachine;
+			} else if (return_type == Module.PredefinedTypes.Task.TypeSpec) {
+				builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder;
+				bf = pred_members.AsyncTaskMethodBuilderCreate;
+				bs = pred_members.AsyncTaskMethodBuilderStart;
+				sr = pred_members.AsyncTaskMethodBuilderSetResult;
+				se = pred_members.AsyncTaskMethodBuilderSetException;
+				sm = pred_members.AsyncTaskMethodBuilderSetStateMachine;
+				task = pred_members.AsyncTaskMethodBuilderTask.Get ();
+			} else {
+				builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric;
+				bf = pred_members.AsyncTaskMethodBuilderGenericCreate;
+				bs = pred_members.AsyncTaskMethodBuilderGenericStart;
+				sr = pred_members.AsyncTaskMethodBuilderGenericSetResult;
+				se = pred_members.AsyncTaskMethodBuilderGenericSetException;
+				sm = pred_members.AsyncTaskMethodBuilderGenericSetStateMachine;
+				task = pred_members.AsyncTaskMethodBuilderGenericTask.Get ();
+				has_task_return_type = true;
+			}
+
+			set_result = sr.Get ();
+			set_exception = se.Get ();
+			builder_factory = bf.Get ();
+			builder_start = bs.Get ();
+
+			var istate_machine = Module.PredefinedTypes.IAsyncStateMachine;
+			var set_statemachine = sm.Get ();
+
+			if (!builder_type.Define () || !istate_machine.Define () || set_result == null || builder_factory == null ||
+				set_exception == null || set_statemachine == null || builder_start == null ||
+				!Module.PredefinedTypes.INotifyCompletion.Define ()) {
+				Report.Error (1993, Location,
+					"Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?");
+				return base.DoDefineMembers ();
+			}
+
+			var bt = builder_type.TypeSpec;
+
+			//
+			// Inflate generic Task types
+			//
+			if (has_task_return_type) {
+				var task_return_type = return_type.TypeArguments;
+				if (mutator != null)
+					task_return_type = mutator.Mutate (task_return_type);
+
+				bt = bt.MakeGenericType (Module, task_return_type);
+				set_result = MemberCache.GetMember (bt, set_result);
+				set_exception = MemberCache.GetMember (bt, set_exception);
+				set_statemachine = MemberCache.GetMember (bt, set_statemachine);
+
+				if (task != null)
+					task = MemberCache.GetMember (bt, task);
+			}
+
+			builder = AddCompilerGeneratedField ("$builder", new TypeExpression (bt, Location));
+
+			var set_state_machine = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
+				Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PUBLIC,
+				new MemberName ("SetStateMachine"),
+				ParametersCompiled.CreateFullyResolved (
+					new Parameter (new TypeExpression (istate_machine.TypeSpec, Location), "stateMachine", Parameter.Modifier.NONE, null, Location),
+					istate_machine.TypeSpec),
+				null);
+
+			ToplevelBlock block = new ToplevelBlock (Compiler, set_state_machine.ParameterInfo, Location);
+			block.IsCompilerGenerated = true;
+			set_state_machine.Block = block;
+
+			Members.Add (set_state_machine);
+
+			if (!base.DoDefineMembers ())
+				return false;
+
+			//
+			// Fabricates SetStateMachine method
+			//
+			// public void SetStateMachine (IAsyncStateMachine stateMachine)
+			// {
+			//    $builder.SetStateMachine (stateMachine);
+			// }
+			//
+			var mg = MethodGroupExpr.CreatePredefined (set_statemachine, bt, Location);
+			mg.InstanceExpression = new FieldExpr (builder, Location);
+
+			var param_reference = block.GetParameterReference (0, Location);
+			param_reference.Type = istate_machine.TypeSpec;
+			param_reference.eclass = ExprClass.Variable;
+
+			var args = new Arguments (1);
+			args.Add (new Argument (param_reference));
+			set_state_machine.Block.AddStatement (new StatementExpression (new Invocation (mg, args)));
+
+			if (has_task_return_type) {
+				HoistedReturnValue = TemporaryVariableReference.Create (bt.TypeArguments [0], StateMachineMethod.Block, Location);
+			}
+
+			return true;
+		}
+
+		public void EmitAwaitOnCompletedDynamic (EmitContext ec, FieldExpr awaiter)
+		{
+			var critical = Module.PredefinedTypes.ICriticalNotifyCompletion;
+			if (!critical.Define ()) {
+				throw new NotImplementedException ();
+			}
+
+			var temp_critical = new LocalTemporary (critical.TypeSpec);
+			var label_critical = ec.DefineLabel ();
+			var label_end = ec.DefineLabel ();
+
+			//
+			// Special path for dynamic awaiters
+			//
+			// var awaiter = this.$awaiter as ICriticalNotifyCompletion;
+			// if (awaiter == null) {
+			//    var completion = (INotifyCompletion) this.$awaiter;
+			//    this.$builder.AwaitOnCompleted (ref completion, ref this);
+			// } else {
+			//    this.$builder.AwaitUnsafeOnCompleted (ref awaiter, ref this);
+			// }
+			//
+			awaiter.Emit (ec);
+			ec.Emit (OpCodes.Isinst, critical.TypeSpec);
+			temp_critical.Store (ec);
+			temp_critical.Emit (ec);
+			ec.Emit (OpCodes.Brtrue_S, label_critical);
+
+			var temp = new LocalTemporary (Module.PredefinedTypes.INotifyCompletion.TypeSpec);
+			awaiter.Emit (ec);
+			ec.Emit (OpCodes.Castclass, temp.Type);
+			temp.Store (ec);
+			EmitOnCompleted (ec, temp, false);
+			temp.Release (ec);
+			ec.Emit (OpCodes.Br_S, label_end);
+
+			ec.MarkLabel (label_critical);
+
+			EmitOnCompleted (ec, temp_critical, true);
+
+			ec.MarkLabel (label_end);
+
+			temp_critical.Release (ec);
+		}
+
+		public void EmitAwaitOnCompleted (EmitContext ec, FieldExpr awaiter)
+		{
+			bool unsafe_version = false;
+			if (Module.PredefinedTypes.ICriticalNotifyCompletion.Define ()) {
+				unsafe_version = awaiter.Type.ImplementsInterface (Module.PredefinedTypes.ICriticalNotifyCompletion.TypeSpec, false);
+			}
+
+			EmitOnCompleted (ec, awaiter, unsafe_version);
+		}
+
+		void EmitOnCompleted (EmitContext ec, Expression awaiter, bool unsafeVersion)
+		{
+			var pm = Module.PredefinedMembers;
+			PredefinedMember<MethodSpec> predefined;
+			bool has_task_return_type = false;
+			if (return_type.Kind == MemberKind.Void) {
+				predefined = unsafeVersion ? pm.AsyncVoidMethodBuilderOnCompletedUnsafe : pm.AsyncVoidMethodBuilderOnCompleted;
+			} else if (return_type == Module.PredefinedTypes.Task.TypeSpec) {
+				predefined = unsafeVersion ? pm.AsyncTaskMethodBuilderOnCompletedUnsafe : pm.AsyncTaskMethodBuilderOnCompleted;
+			} else {
+				predefined = unsafeVersion ? pm.AsyncTaskMethodBuilderGenericOnCompletedUnsafe : pm.AsyncTaskMethodBuilderGenericOnCompleted;
+				has_task_return_type = true;
+			}
+
+			var on_completed = predefined.Resolve (Location);
+			if (on_completed == null)
+				return;
+
+			if (has_task_return_type)
+				on_completed = MemberCache.GetMember<MethodSpec> (set_result.DeclaringType, on_completed);
+
+			on_completed = on_completed.MakeGenericMethod (this, awaiter.Type, ec.CurrentType);
+
+			var mg = MethodGroupExpr.CreatePredefined (on_completed, on_completed.DeclaringType, Location);
+			mg.InstanceExpression = new FieldExpr (builder, Location) {
+				InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location)
+			};
+
+			var args = new Arguments (2);
+			args.Add (new Argument (awaiter, Argument.AType.Ref));
+			args.Add (new Argument (new CompilerGeneratedThis (CurrentType, Location), Argument.AType.Ref));
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				mg.EmitCall (ec, args, true);
+			}
+		}
+
+		public void EmitInitializer (EmitContext ec)
+		{
+			//
+			// Some predefined types are missing
+			//
+			if (builder == null)
+				return;
+
+			var instance = (TemporaryVariableReference) Instance;
+			var builder_field = builder.Spec;
+			if (MemberName.Arity > 0) {
+				builder_field = MemberCache.GetMember (instance.Type, builder_field);
+			}
+
+			//
+			// Inflated factory method when task is of generic type
+			//
+			if (builder_factory.DeclaringType.IsGeneric) {
+				var task_return_type = return_type.TypeArguments;
+				var bt = builder_factory.DeclaringType.MakeGenericType (Module, task_return_type);
+				builder_factory = MemberCache.GetMember (bt, builder_factory);
+				builder_start = MemberCache.GetMember (bt, builder_start);
+			}
+
+			//
+			// stateMachine.$builder = AsyncTaskMethodBuilder<{task-type}>.Create();
+			//
+			instance.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Call, builder_factory);
+			ec.Emit (OpCodes.Stfld, builder_field);
+
+			//
+			// stateMachine.$builder.Start<{storey-type}>(ref stateMachine);
+			//
+			instance.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Ldflda, builder_field);
+			if (Task != null)
+				ec.Emit (OpCodes.Dup);
+			instance.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Call, builder_start.MakeGenericMethod (Module, instance.Type));
+
+			//
+			// Emits return stateMachine.$builder.Task;
+			//
+			if (Task != null) {
+				var task_get = Task.Get;
+
+				if (MemberName.Arity > 0) {
+					task_get = MemberCache.GetMember (builder_field.MemberType, task_get);
+				}
+
+				var pe_task = new PropertyExpr (Task, Location) {
+					InstanceExpression = EmptyExpression.Null,	// Comes from the dup above
+					Getter = task_get
+				};
+
+				pe_task.Emit (ec);
+			}
+		}
+
+		public void EmitSetException (EmitContext ec, LocalVariableReference exceptionVariable)
+		{
+			//
+			// $builder.SetException (Exception)
+			//
+			var mg = MethodGroupExpr.CreatePredefined (set_exception, set_exception.DeclaringType, Location);
+			mg.InstanceExpression = new FieldExpr (builder, Location) {
+				InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location)
+			};
+
+			Arguments args = new Arguments (1);
+			args.Add (new Argument (exceptionVariable));
+
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				mg.EmitCall (ec, args, true);
+			}
+		}
+
+		public void EmitSetResult (EmitContext ec)
+		{
+			//
+			// $builder.SetResult ();
+			// $builder.SetResult<return-type> (value);
+			//
+			var mg = MethodGroupExpr.CreatePredefined (set_result, set_result.DeclaringType, Location);
+			mg.InstanceExpression = new FieldExpr (builder, Location) {
+				InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location)
+			};
+
+			Arguments args;
+			if (HoistedReturnValue == null) {
+				args = new Arguments (0);
+			} else {
+				args = new Arguments (1);
+				args.Add (new Argument (HoistedReturnValue));
+			}
+
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				mg.EmitCall (ec, args, true);
+			}
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			base_type = Compiler.BuiltinTypes.ValueType;
+			base_class = null;
+
+			var istate_machine = Module.PredefinedTypes.IAsyncStateMachine;
+			if (istate_machine.Define ()) {
+				return new[] { istate_machine.TypeSpec };
+			}
+
+			return null;
+		}
+	}
+
+	public class StackFieldExpr : FieldExpr, IExpressionCleanup
+	{
+		public StackFieldExpr (Field field)
+			: base (field, Location.Null)
+		{
+		}
+
+		public bool IsAvailableForReuse {
+			get {
+				var field = (Field) spec.MemberDefinition;
+				return field.IsAvailableForReuse;
+			}
+			set {
+				var field = (Field) spec.MemberDefinition;
+				field.IsAvailableForReuse = value;
+			}
+		}
+
+		public override void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			base.AddressOf (ec, mode);
+
+			if (mode == AddressOp.Load) {
+				IsAvailableForReuse = true;
+			}
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+
+			PrepareCleanup (ec);
+		}
+
+		public void EmitLoad (EmitContext ec)
+		{
+			base.Emit (ec);
+		}
+
+		public void PrepareCleanup (EmitContext ec)
+		{
+			IsAvailableForReuse = true;
+
+			//
+			// Release any captured reference type stack variables
+			// to imitate real stack behavour and help GC stuff early
+			//
+			if (TypeSpec.IsReferenceType (type)) {
+				ec.AddStatementEpilog (this);
+			}
+		}
+
+		void IExpressionCleanup.EmitCleanup (EmitContext ec)
+		{
+			EmitAssign (ec, new NullConstant (type, loc), false, false);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/attribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/attribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/attribute.cs	(revision 11807)
@@ -0,0 +1,2140 @@
+//
+// attribute.cs: Attributes handling
+//
+// Author: Ravi Pratap (ravi@ximian.com)
+//         Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011-2013 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Security; 
+using System.Security.Permissions;
+using System.Text;
+using System.IO;
+
+#if STATIC
+using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
+using BadImageFormat = IKVM.Reflection.BadImageFormatException;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
+using BadImageFormat = System.BadImageFormatException;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	/// <summary>
+	///   Base class for objects that can have Attributes applied to them.
+	/// </summary>
+	public abstract class Attributable {
+		//
+		// Holds all attributes attached to this element
+		//
+ 		protected Attributes attributes;
+
+		public void AddAttributes (Attributes attrs, IMemberContext context)
+		{
+			if (attrs == null)
+				return;
+		
+			if (attributes == null)
+				attributes = attrs;
+			else
+				attributes.AddAttributes (attrs.Attrs);
+			attrs.AttachTo (this, context);
+		}
+
+		public Attributes OptAttributes {
+			get {
+				return attributes;
+			}
+			set {
+				attributes = value;
+			}
+		}
+
+		/// <summary>
+		/// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
+		/// </summary>
+		public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
+
+		/// <summary>
+		/// Returns one AttributeTarget for this element.
+		/// </summary>
+		public abstract AttributeTargets AttributeTargets { get; }
+
+		public abstract bool IsClsComplianceRequired ();
+
+		/// <summary>
+		/// Gets list of valid attribute targets for explicit target declaration.
+		/// The first array item is default target. Don't break this rule.
+		/// </summary>
+		public abstract string[] ValidAttributeTargets { get; }
+	};
+
+	public class Attribute
+	{
+		public readonly string ExplicitTarget;
+		public AttributeTargets Target;
+		readonly ATypeNameExpression expression;
+
+		Arguments pos_args, named_args;
+
+		bool resolve_error;
+		bool arg_resolved;
+		readonly bool nameEscaped;
+		readonly Location loc;
+		public TypeSpec Type;	
+
+		//
+		// An attribute can be attached to multiple targets (e.g. multiple fields)
+		//
+		Attributable[] targets;
+
+		//
+		// A member context for the attribute, it's much easier to hold it here
+		// than trying to pull it during resolve
+		//
+		IMemberContext context;
+
+		public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
+		public static readonly object[] EmptyObject = new object [0];
+
+		List<KeyValuePair<MemberExpr, NamedArgument>> named_values;
+
+		public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
+		{
+			this.expression = expr;
+			if (args != null) {
+				pos_args = args[0];
+				named_args = args[1];
+			}
+			this.loc = loc;
+			ExplicitTarget = target;
+			this.nameEscaped = nameEscaped;
+		}
+
+		public Location Location {
+			get {
+				return loc;
+			}
+		}
+
+		public Arguments NamedArguments {
+			get {
+				return named_args;
+			}
+		}
+
+		public Arguments PositionalArguments {
+			get {
+				return pos_args;
+			}
+		}
+
+		public bool ResolveError {
+			get {
+				return resolve_error;
+			}
+		}
+
+		public ATypeNameExpression TypeExpression {
+			get {
+				return expression;
+			}
+		}
+
+		void AddModuleCharSet (ResolveContext rc)
+		{
+			const string dll_import_char_set = "CharSet";
+
+			//
+			// Only when not customized by user
+			//
+			if (HasField (dll_import_char_set))
+				return;
+
+			if (!rc.Module.PredefinedTypes.CharSet.Define ()) {
+				return;
+			}
+
+			if (NamedArguments == null)
+				named_args = new Arguments (1);
+
+			var value = Constant.CreateConstantFromValue (rc.Module.PredefinedTypes.CharSet.TypeSpec, rc.Module.DefaultCharSet, Location);
+			NamedArguments.Add (new NamedArgument (dll_import_char_set, loc, value));
+		}
+
+		public Attribute Clone ()
+		{
+			Attribute a = new Attribute (ExplicitTarget, expression, null, loc, nameEscaped);
+			a.pos_args = pos_args;
+			a.named_args = NamedArguments;
+			return a;
+		}
+
+		//
+		// When the same attribute is attached to multiple fiels
+		// we use @target field as a list of targets. The attribute
+		// has to be resolved only once but emitted for each target.
+		//
+		public void AttachTo (Attributable target, IMemberContext context)
+		{
+			if (this.targets == null) {
+				this.targets = new Attributable[] { target };
+				this.context = context;
+				return;
+			}
+
+			// When re-attaching global attributes
+			if (context is NamespaceContainer) {
+				this.targets[0] = target;
+				this.context = context;
+				return;
+			}
+
+			// Resize target array
+			Attributable[] new_array = new Attributable [this.targets.Length + 1];
+			targets.CopyTo (new_array, 0);
+			new_array [targets.Length] = target;
+			this.targets = new_array;
+
+			// No need to update context, different targets cannot have
+			// different contexts, it's enough to remove same attributes
+			// from secondary members.
+
+			target.OptAttributes = null;
+		}
+
+		public ResolveContext CreateResolveContext ()
+		{
+			return new ResolveContext (context, ResolveContext.Options.ConstantScope);
+		}
+
+		static void Error_InvalidNamedArgument (ResolveContext rc, NamedArgument name)
+		{
+			rc.Report.Error (617, name.Location, "`{0}' is not a valid named attribute argument. Named attribute arguments " +
+				      "must be fields which are not readonly, static, const or read-write properties which are " +
+				      "public and not static",
+			      name.Name);
+		}
+
+		static void Error_InvalidNamedArgumentType (ResolveContext rc, NamedArgument name)
+		{
+			rc.Report.Error (655, name.Location,
+				"`{0}' is not a valid named attribute argument because it is not a valid attribute parameter type",
+				name.Name);
+		}
+
+		public static void Error_AttributeArgumentIsDynamic (IMemberContext context, Location loc)
+		{
+			context.Module.Compiler.Report.Error (1982, loc, "An attribute argument cannot be dynamic expression");
+		}
+		
+		public void Error_MissingGuidAttribute ()
+		{
+			Report.Error (596, Location, "The Guid attribute must be specified with the ComImport attribute");
+		}
+
+		public void Error_MisusedExtensionAttribute ()
+		{
+			Report.Error (1112, Location, "Do not use `{0}' directly. Use parameter modifier `this' instead", GetSignatureForError ());
+		}
+
+		public void Error_MisusedDynamicAttribute ()
+		{
+			Report.Error (1970, loc, "Do not use `{0}' directly. Use `dynamic' keyword instead", GetSignatureForError ());
+		}
+
+		void Error_AttributeEmitError (string inner)
+		{
+			Report.Error (647, Location, "Error during emitting `{0}' attribute. The reason is `{1}'",
+				      Type.GetSignatureForError (), inner);
+		}
+
+		public void Error_InvalidArgumentValue (TypeSpec attributeType)
+		{
+			Report.Error (591, Location, "Invalid value for argument to `{0}' attribute", attributeType.GetSignatureForError ());
+		}
+
+		public void Error_InvalidSecurityParent ()
+		{
+			Report.Error (7070, Location,
+				"Security attribute `{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations",
+				Type.GetSignatureForError ());
+		}
+
+		Attributable Owner {
+			get {
+				return targets [0];
+			}
+		}
+
+		/// <summary>
+		///   Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
+		/// </summary>
+		void ResolveAttributeType (bool comparisonOnly)
+		{
+			var resolve_printer = new SessionReportPrinter ();
+			SessionReportPrinter secondary_printer = null;
+			ReportPrinter prev_recorder = Report.SetPrinter (resolve_printer);
+
+			bool t1_is_attr = false;
+			bool t2_is_attr = false;
+			TypeSpec t1, t2;
+			ATypeNameExpression expanded = null;
+
+			// TODO: Additional warnings such as CS0436 are swallowed because we don't
+			// print on success
+
+			try {
+				t1 = expression.ResolveAsType (context);
+				resolve_printer.EndSession ();
+
+				if (t1 != null && resolve_printer.ErrorsCount == 0)
+					t1_is_attr = t1.IsAttribute;
+
+				if (nameEscaped) {
+					t2 = null;
+				} else {
+					expanded = (ATypeNameExpression) expression.Clone (null);
+					expanded.Name += "Attribute";
+
+					secondary_printer = new SessionReportPrinter ();
+					Report.SetPrinter (secondary_printer);
+					t2 = expanded.ResolveAsType (context);
+					secondary_printer.EndSession ();
+					if (t2 != null && secondary_printer.ErrorsCount == 0)
+						t2_is_attr = t2.IsAttribute;
+
+					secondary_printer.EndSession ();
+				}
+			} finally {
+				context.Module.Compiler.Report.SetPrinter (prev_recorder);
+			}
+
+			if (t1_is_attr && t2_is_attr && t1 != t2) {
+				if (!comparisonOnly) {
+					Report.Error (1614, Location, "`{0}' is ambiguous between `{1}' and `{2}'. Use either `@{0}' or `{0}Attribute'",
+						GetSignatureForError (), expression.GetSignatureForError (), expanded.GetSignatureForError ());
+					resolve_error = true;
+				}
+
+				return;
+			}
+
+			if (t1_is_attr) {
+				Type = t1;
+				return;
+			}
+
+			if (t2_is_attr) {
+				Type = t2;
+				return;
+			}
+
+			if (comparisonOnly)
+				return;
+
+			resolve_error = true;
+
+			if (t1 != null) {	
+				if (resolve_printer.IsEmpty) {
+					Report.SymbolRelatedToPreviousError (t1);
+					Report.Error (616, Location, "`{0}': is not an attribute class", t1.GetSignatureForError ());
+				} else {
+					resolve_printer.Merge (prev_recorder);
+				}
+
+				return;
+			}
+
+			if (t2 != null) {
+				if (secondary_printer.IsEmpty) {
+					Report.SymbolRelatedToPreviousError (t2);
+					Report.Error (616, Location, "`{0}': is not an attribute class", t2.GetSignatureForError ());
+				} else {
+					secondary_printer.Merge (prev_recorder);
+				}
+
+				return;
+			}
+
+			resolve_printer.Merge (prev_recorder);
+		}
+
+		public TypeSpec ResolveTypeForComparison ()
+		{
+			if (Type == null && !resolve_error)
+				ResolveAttributeType (true);
+			return Type;
+		}
+
+		public string GetSignatureForError ()
+		{
+			if (Type != null)
+				return Type.GetSignatureForError ();
+
+			return expression.GetSignatureForError ();
+		}
+
+		public bool HasSecurityAttribute {
+			get {
+				PredefinedAttribute pa = context.Module.PredefinedAttributes.Security;
+				return pa.IsDefined && TypeSpec.IsBaseClass (Type, pa.TypeSpec, false);
+			}
+		}
+
+		public bool IsValidSecurityAttribute ()
+		{
+			return HasSecurityAttribute && IsSecurityActionValid ();
+		}
+
+		static bool IsValidMethodImplOption (int value)
+		{
+			//
+			// Allow to use AggressiveInlining on any runtime/corlib
+			//
+			MethodImplOptions all = (MethodImplOptions) 256;
+			foreach (MethodImplOptions v in System.Enum.GetValues (typeof (MethodImplOptions))) {
+				all |= v;
+			}
+
+			return ((MethodImplOptions) value | all) == all;
+		}
+
+		public static bool IsValidArgumentType (TypeSpec t)
+		{
+			if (t.IsArray) {
+				var ac = (ArrayContainer) t;
+				if (ac.Rank > 1)
+					return false;
+
+				t = ac.Element;
+			}
+
+			switch (t.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.Float:
+			case BuiltinTypeSpec.Type.Double:
+			case BuiltinTypeSpec.Type.Char:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.Bool:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.UShort:
+
+			case BuiltinTypeSpec.Type.String:
+			case BuiltinTypeSpec.Type.Object:
+			case BuiltinTypeSpec.Type.Dynamic:
+			case BuiltinTypeSpec.Type.Type:
+				return true;
+			}
+
+			return t.IsEnum;
+		}
+
+		// TODO: Don't use this ambiguous value
+		public string Name {
+			get { return expression.Name; }
+		}
+
+		public ATypeNameExpression TypeNameExpression {
+			get {
+				return expression;
+			}
+		}
+
+		public Report Report {
+			get { return context.Module.Compiler.Report; }
+		}
+
+		public MethodSpec Resolve ()
+		{
+			if (resolve_error)
+				return null;
+
+			resolve_error = true;
+			arg_resolved = true;
+
+			if (Type == null) {
+				ResolveAttributeType (false);
+				if (Type == null)
+					return null;
+			}
+
+			if (Type.IsAbstract) {
+				Report.Error (653, Location, "Cannot apply attribute class `{0}' because it is abstract", GetSignatureForError ());
+				return null;
+			}
+
+			ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
+			if (obsolete_attr != null) {
+				AttributeTester.Report_ObsoleteMessage (obsolete_attr, Type.GetSignatureForError (), Location, Report);
+			}
+
+			ResolveContext rc = null;
+
+			MethodSpec ctor;
+			// Try if the attribute is simple and has been resolved before
+			if (pos_args != null || !context.Module.AttributeConstructorCache.TryGetValue (Type, out ctor)) {
+				rc = CreateResolveContext ();
+				ctor = ResolveConstructor (rc);
+				if (ctor == null) {
+					return null;
+				}
+
+				if (pos_args == null && ctor.Parameters.IsEmpty)
+					context.Module.AttributeConstructorCache.Add (Type, ctor);
+			}
+
+			//
+			// Add [module: DefaultCharSet] to all DllImport import attributes
+			//
+			var module = context.Module;
+			if ((Type == module.PredefinedAttributes.DllImport || Type == module.PredefinedAttributes.UnmanagedFunctionPointer) && module.HasDefaultCharSet) {
+				if (rc == null)
+					rc = CreateResolveContext ();
+
+				AddModuleCharSet (rc);
+			}
+
+			if (NamedArguments != null) {
+				if (rc == null)
+					rc = CreateResolveContext ();
+
+				if (!ResolveNamedArguments (rc))
+					return null;
+			}
+
+			resolve_error = false;
+			return ctor;
+		}
+
+		MethodSpec ResolveConstructor (ResolveContext ec)
+		{
+			if (pos_args != null) {
+				bool dynamic;
+				pos_args.Resolve (ec, out dynamic);
+				if (dynamic) {
+					Error_AttributeArgumentIsDynamic (ec.MemberContext, loc);
+					return null;
+				}
+			}
+
+			return Expression.ConstructorLookup (ec, Type, ref pos_args, loc);
+		}
+
+		bool ResolveNamedArguments (ResolveContext ec)
+		{
+			int named_arg_count = NamedArguments.Count;
+			var seen_names = new List<string> (named_arg_count);
+
+			named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
+			
+			foreach (NamedArgument a in NamedArguments) {
+				string name = a.Name;
+				if (seen_names.Contains (name)) {
+					ec.Report.Error (643, a.Location, "Duplicate named attribute `{0}' argument", name);
+					continue;
+				}			
+	
+				seen_names.Add (name);
+
+				a.Resolve (ec);
+
+				Expression member = Expression.MemberLookup (ec, false, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
+
+				if (member == null) {
+					member = Expression.MemberLookup (ec, true, Type, name, 0, Expression.MemberLookupRestrictions.ExactArity, loc);
+
+					if (member != null) {
+						// TODO: ec.Report.SymbolRelatedToPreviousError (member);
+						Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
+						return false;
+					}
+				}
+
+				if (member == null){
+					Expression.Error_TypeDoesNotContainDefinition (ec, Location, Type, name);
+					return false;
+				}
+				
+				if (!(member is PropertyExpr || member is FieldExpr)) {
+					Error_InvalidNamedArgument (ec, a);
+					return false;
+				}
+
+				ObsoleteAttribute obsolete_attr;
+
+				if (member is PropertyExpr) {
+					var pi = ((PropertyExpr) member).PropertyInfo;
+
+					if (!pi.HasSet || !pi.HasGet || pi.IsStatic || !pi.Get.IsPublic || !pi.Set.IsPublic) {
+						ec.Report.SymbolRelatedToPreviousError (pi);
+						Error_InvalidNamedArgument (ec, a);
+						return false;
+					}
+
+					if (!IsValidArgumentType (member.Type)) {
+						ec.Report.SymbolRelatedToPreviousError (pi);
+						Error_InvalidNamedArgumentType (ec, a);
+						return false;
+					}
+
+					obsolete_attr = pi.GetAttributeObsolete ();
+					pi.MemberDefinition.SetIsAssigned ();
+				} else {
+					var fi = ((FieldExpr) member).Spec;
+
+					if (fi.IsReadOnly || fi.IsStatic || !fi.IsPublic) {
+						Error_InvalidNamedArgument (ec, a);
+						return false;
+					}
+
+					if (!IsValidArgumentType (member.Type)) {
+						ec.Report.SymbolRelatedToPreviousError (fi);
+						Error_InvalidNamedArgumentType (ec, a);
+						return false;
+					}
+
+					obsolete_attr = fi.GetAttributeObsolete ();
+					fi.MemberDefinition.SetIsAssigned ();
+				}
+
+				if (obsolete_attr != null && !context.IsObsolete)
+					AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
+
+				if (a.Type != member.Type) {
+					a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
+				}
+
+				if (a.Expr != null)
+					named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
+			}
+
+			return true;
+		}
+
+		/// <summary>
+		///   Get a string containing a list of valid targets for the attribute 'attr'
+		/// </summary>
+		public string GetValidTargets ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			AttributeTargets targets = Type.GetAttributeUsage (context.Module.PredefinedAttributes.AttributeUsage).ValidOn;
+
+			if ((targets & AttributeTargets.Assembly) != 0)
+				sb.Append ("assembly, ");
+
+			if ((targets & AttributeTargets.Module) != 0)
+				sb.Append ("module, ");
+
+			if ((targets & AttributeTargets.Class) != 0)
+				sb.Append ("class, ");
+
+			if ((targets & AttributeTargets.Struct) != 0)
+				sb.Append ("struct, ");
+
+			if ((targets & AttributeTargets.Enum) != 0)
+				sb.Append ("enum, ");
+
+			if ((targets & AttributeTargets.Constructor) != 0)
+				sb.Append ("constructor, ");
+
+			if ((targets & AttributeTargets.Method) != 0)
+				sb.Append ("method, ");
+
+			if ((targets & AttributeTargets.Property) != 0)
+				sb.Append ("property, indexer, ");
+
+			if ((targets & AttributeTargets.Field) != 0)
+				sb.Append ("field, ");
+
+			if ((targets & AttributeTargets.Event) != 0)
+				sb.Append ("event, ");
+
+			if ((targets & AttributeTargets.Interface) != 0)
+				sb.Append ("interface, ");
+
+			if ((targets & AttributeTargets.Parameter) != 0)
+				sb.Append ("parameter, ");
+
+			if ((targets & AttributeTargets.Delegate) != 0)
+				sb.Append ("delegate, ");
+
+			if ((targets & AttributeTargets.ReturnValue) != 0)
+				sb.Append ("return, ");
+
+			if ((targets & AttributeTargets.GenericParameter) != 0)
+				sb.Append ("type parameter, ");
+
+			return sb.Remove (sb.Length - 2, 2).ToString ();
+		}
+
+		public AttributeUsageAttribute GetAttributeUsageAttribute ()
+		{
+			if (!arg_resolved)
+				// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
+				// But because a lot of attribute class code must be rewritten will be better to wait...
+				Resolve ();
+
+			if (resolve_error)
+				return DefaultUsageAttribute;
+
+			AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets) ((Constant) pos_args[0].Expr).GetValue ());
+
+			var field = GetNamedValue ("AllowMultiple") as BoolConstant;
+			if (field != null)
+				usage_attribute.AllowMultiple = field.Value;
+
+			field = GetNamedValue ("Inherited") as BoolConstant;
+			if (field != null)
+				usage_attribute.Inherited = field.Value;
+
+			return usage_attribute;
+		}
+
+		/// <summary>
+		/// Returns custom name of indexer
+		/// </summary>
+		public string GetIndexerAttributeValue ()
+		{
+			if (!arg_resolved)
+				// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
+				// But because a lot of attribute class code must be rewritten will be better to wait...
+				Resolve ();
+
+			if (resolve_error || pos_args.Count != 1 || !(pos_args[0].Expr is Constant))
+				return null;
+
+			return ((Constant) pos_args[0].Expr).GetValue () as string;
+		}
+
+		/// <summary>
+		/// Returns condition of ConditionalAttribute
+		/// </summary>
+		public string GetConditionalAttributeValue ()
+		{
+			if (!arg_resolved)
+				// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
+				// But because a lot of attribute class code must be rewritten will be better to wait...
+				Resolve ();
+
+			if (resolve_error)
+				return null;
+
+			return ((Constant) pos_args[0].Expr).GetValue () as string;
+		}
+
+		/// <summary>
+		/// Creates the instance of ObsoleteAttribute from this attribute instance
+		/// </summary>
+		public ObsoleteAttribute GetObsoleteAttribute ()
+		{
+			if (!arg_resolved) {
+				// corlib only case when obsolete is used before is resolved
+				var c = Type.MemberDefinition as Class;
+				if (c != null && !c.HasMembersDefined)
+					c.Define ();
+				
+				// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
+				// But because a lot of attribute class code must be rewritten will be better to wait...
+				Resolve ();
+			}
+
+			if (resolve_error)
+				return null;
+
+			if (pos_args == null)
+				return new ObsoleteAttribute ();
+
+			string msg = ((Constant) pos_args[0].Expr).GetValue () as string;
+			if (pos_args.Count == 1)
+				return new ObsoleteAttribute (msg);
+
+			return new ObsoleteAttribute (msg, ((BoolConstant) pos_args[1].Expr).Value);
+		}
+
+		/// <summary>
+		/// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
+		/// before ApplyAttribute. We need to resolve the arguments.
+		/// This situation occurs when class deps is differs from Emit order.  
+		/// </summary>
+		public bool GetClsCompliantAttributeValue ()
+		{
+			if (!arg_resolved)
+				// TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
+				// But because a lot of attribute class code must be rewritten will be better to wait...
+				Resolve ();
+
+			if (resolve_error)
+				return false;
+
+			return ((BoolConstant) pos_args[0].Expr).Value;
+		}
+
+		public TypeSpec GetCoClassAttributeValue ()
+		{
+			if (!arg_resolved)
+				Resolve ();
+
+			if (resolve_error)
+				return null;
+
+			return GetArgumentType ();
+		}
+
+		public bool CheckTarget ()
+		{
+			string[] valid_targets = Owner.ValidAttributeTargets;
+			if (ExplicitTarget == null || ExplicitTarget == valid_targets [0]) {
+				Target = Owner.AttributeTargets;
+				return true;
+			}
+
+			// TODO: we can skip the first item
+			if (Array.Exists (valid_targets, i => i == ExplicitTarget)) {
+				switch (ExplicitTarget) {
+				case "return": Target = AttributeTargets.ReturnValue; return true;
+				case "param": Target = AttributeTargets.Parameter; return true;
+				case "field": Target = AttributeTargets.Field; return true;
+				case "method": Target = AttributeTargets.Method; return true;
+				case "property": Target = AttributeTargets.Property; return true;
+				case "module": Target = AttributeTargets.Module; return true;
+				}
+				throw new InternalErrorException ("Unknown explicit target: " + ExplicitTarget);
+			}
+				
+			StringBuilder sb = new StringBuilder ();
+			foreach (string s in valid_targets) {
+				sb.Append (s);
+				sb.Append (", ");
+			}
+			sb.Remove (sb.Length - 2, 2);
+			Report.Warning (657, 1, Location,
+				"`{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are `{1}'. All attributes in this section will be ignored",
+				ExplicitTarget, sb.ToString ());
+			return false;
+		}
+
+		/// <summary>
+		/// Tests permitted SecurityAction for assembly or other types
+		/// </summary>
+		bool IsSecurityActionValid ()
+		{
+			SecurityAction action = GetSecurityActionValue ();
+			bool for_assembly = Target == AttributeTargets.Assembly || Target == AttributeTargets.Module;
+			var c = (Constant)pos_args [0].Expr;
+
+			switch (action) {
+#pragma warning disable 618
+			case SecurityAction.Demand:
+			case SecurityAction.Assert:
+			case SecurityAction.Deny:
+			case SecurityAction.PermitOnly:
+			case SecurityAction.LinkDemand:
+			case SecurityAction.InheritanceDemand:
+				if (!for_assembly)
+					return true;
+				break;
+
+			case SecurityAction.RequestMinimum:
+			case SecurityAction.RequestOptional:
+			case SecurityAction.RequestRefuse:
+				if (for_assembly)
+					return true;
+				break;
+#pragma warning restore 618
+
+			default:
+				Report.Error (7049, c.Location, "Security attribute `{0}' has an invalid SecurityAction value `{1}'",
+					Type.GetSignatureForError (), c.GetValueAsLiteral());
+				return false;
+			}
+
+			switch (Target) {
+			case AttributeTargets.Assembly:
+				Report.Error (7050, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to an assembly",
+					c.GetSignatureForError ());
+				break;
+			default:
+				Report.Error (7051, c.Location, "SecurityAction value `{0}' is invalid for security attributes applied to a type or a method",
+					c.GetSignatureForError ());
+				break;
+			}
+
+			return false;
+		}
+
+		System.Security.Permissions.SecurityAction GetSecurityActionValue ()
+		{
+			return (SecurityAction) ((Constant) pos_args[0].Expr).GetValue ();
+		}
+
+		/// <summary>
+		/// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
+		/// </summary>
+		/// <returns></returns>
+		public void ExtractSecurityPermissionSet (MethodSpec ctor, ref SecurityType permissions)
+		{
+#if STATIC
+			object[] values = new object[pos_args.Count];
+			for (int i = 0; i < values.Length; ++i)
+				values[i] = ((Constant) pos_args[i].Expr).GetValue ();
+
+			PropertyInfo[] prop;
+			object[] prop_values;
+			if (named_values == null) {
+				prop = null;
+				prop_values = null;
+			} else {
+				prop = new PropertyInfo[named_values.Count];
+				prop_values = new object [named_values.Count];
+				for (int i = 0; i < prop.Length; ++i) {
+					prop [i] = ((PropertyExpr) named_values [i].Key).PropertyInfo.MetaInfo;
+					prop_values [i] = ((Constant) named_values [i].Value.Expr).GetValue ();
+				}
+			}
+
+			if (permissions == null)
+				permissions = new SecurityType ();
+
+			var cab = new CustomAttributeBuilder ((ConstructorInfo) ctor.GetMetaInfo (), values, prop, prop_values);
+			permissions.Add (cab);
+#else
+			throw new NotSupportedException ();
+#endif
+		}
+
+		public Constant GetNamedValue (string name)
+		{
+			if (named_values == null)
+				return null;
+
+			for (int i = 0; i < named_values.Count; ++i) {
+				if (named_values [i].Value.Name == name)
+					return named_values [i].Value.Expr as Constant;
+			}
+
+			return null;
+		}
+
+		public CharSet GetCharSetValue ()
+		{
+			return (CharSet) System.Enum.Parse (typeof (CharSet), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+		}
+
+		public bool HasField (string fieldName)
+		{
+			if (named_values == null)
+				return false;
+
+			foreach (var na in named_values) {
+				if (na.Value.Name == fieldName)
+					return true;
+			}
+
+			return false;
+		}
+
+		//
+		// Returns true for MethodImplAttribute with MethodImplOptions.InternalCall value
+		// 
+		public bool IsInternalCall ()
+		{
+			return (GetMethodImplOptions () & MethodImplOptions.InternalCall) != 0;
+		}
+
+		public MethodImplOptions GetMethodImplOptions ()
+		{
+			MethodImplOptions options = 0;
+			if (pos_args.Count == 1) {
+				options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+			} else if (HasField ("Value")) {
+				var named = GetNamedValue ("Value");
+				options = (MethodImplOptions) System.Enum.Parse (typeof (MethodImplOptions), named.GetValue ().ToString ());
+			}
+
+			return options;
+		}
+
+		//
+		// Returns true for StructLayoutAttribute with LayoutKind.Explicit value
+		// 
+		public bool IsExplicitLayoutKind ()
+		{
+			if (pos_args == null || pos_args.Count != 1)
+				return false;
+
+			var value = (LayoutKind) System.Enum.Parse (typeof (LayoutKind), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+			return value == LayoutKind.Explicit;
+		}
+
+		public Expression GetParameterDefaultValue ()
+		{
+			if (pos_args == null)
+				return null;
+
+			return pos_args[0].Expr;
+		}
+
+		public override bool Equals (object obj)
+		{
+			Attribute a = obj as Attribute;
+			if (a == null)
+				return false;
+
+			return Type == a.Type && Target == a.Target;
+		}
+
+		public override int GetHashCode ()
+		{
+			return Type.GetHashCode () ^ Target.GetHashCode ();
+		}
+
+		/// <summary>
+		/// Emit attribute for Attributable symbol
+		/// </summary>
+		public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
+		{
+			var ctor = Resolve ();
+			if (ctor == null)
+				return;
+
+			var predefined = context.Module.PredefinedAttributes;
+
+			AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (predefined.AttributeUsage);
+			if ((usage_attr.ValidOn & Target) == 0) {
+				Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
+					      "It is valid on `{1}' declarations only",
+					GetSignatureForError (), GetValidTargets ());
+				return;
+			}
+
+			byte[] cdata;
+			if (pos_args == null && named_values == null) {
+				cdata = AttributeEncoder.Empty;
+			} else {
+				AttributeEncoder encoder = new AttributeEncoder ();
+
+				if (pos_args != null) {
+					var param_types = ctor.Parameters.Types;
+					for (int j = 0; j < pos_args.Count; ++j) {
+						var pt = param_types[j];
+						var arg_expr = pos_args[j].Expr;
+						if (j == 0) {
+							if ((Type == predefined.IndexerName || Type == predefined.Conditional) && arg_expr is Constant) {
+								string v = ((Constant) arg_expr).GetValue () as string;
+								if (!Tokenizer.IsValidIdentifier (v) || (Type == predefined.IndexerName && Tokenizer.IsKeyword (v))) {
+									context.Module.Compiler.Report.Error (633, arg_expr.Location,
+										"The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
+									return;
+								}
+							} else if (Type == predefined.Guid) {
+								string v = ((StringConstant) arg_expr).Value;
+								try {
+									new Guid (v);
+								} catch {
+									Error_InvalidArgumentValue (Type);
+									return;
+								}
+							} else if (Type == predefined.AttributeUsage) {
+								int v = ((IntConstant) ((EnumConstant) arg_expr).Child).Value;
+								if (v == 0)
+									Error_InvalidArgumentValue (Type);
+							} else if (Type == predefined.MarshalAs) {
+								if (pos_args.Count == 1) {
+									var u_type = (UnmanagedType) System.Enum.Parse (typeof (UnmanagedType), ((Constant) pos_args[0].Expr).GetValue ().ToString ());
+									if (u_type == UnmanagedType.ByValArray && !(Owner is FieldBase)) {
+										Report.Error (7055, pos_args [0].Expr.Location, "Unmanaged type `ByValArray' is only valid for fields");
+									}
+								}
+							} else if (Type == predefined.DllImport) {
+								if (pos_args.Count == 1 && pos_args[0].Expr is Constant) {
+									var value = ((Constant) pos_args[0].Expr).GetValue () as string;
+									if (string.IsNullOrEmpty (value))
+										Error_InvalidArgumentValue (Type);
+								}
+							} else if (Type == predefined.MethodImpl) {
+								if (pos_args.Count == 1) {
+									var value = (int) ((Constant) arg_expr).GetValueAsLong ();
+
+									if (!IsValidMethodImplOption (value)) {
+										Error_InvalidArgumentValue (Type);
+									}
+								}
+							}
+						}
+
+						arg_expr.EncodeAttributeValue (context, encoder, pt, pt);
+					}
+				}
+
+				if (named_values != null) {
+					encoder.Encode ((ushort) named_values.Count);
+					foreach (var na in named_values) {
+						if (na.Key is FieldExpr)
+							encoder.Encode ((byte) 0x53);
+						else
+							encoder.Encode ((byte) 0x54);
+
+						encoder.Encode (na.Key.Type);
+						encoder.Encode (na.Value.Name);
+						na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type, na.Key.Type);
+					}
+				} else {
+					encoder.EncodeEmptyNamedArguments ();
+				}
+
+				cdata = encoder.ToArray ();
+			}
+
+			if (!ctor.DeclaringType.IsConditionallyExcluded (context)) {
+				try {
+					foreach (Attributable target in targets)
+						target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
+				} catch (Exception e) {
+					if (e is BadImageFormat && Report.Errors > 0)
+						return;
+
+					Error_AttributeEmitError (e.Message);
+					return;
+				}
+			}
+
+			if (!usage_attr.AllowMultiple && allEmitted != null) {
+				if (allEmitted.ContainsKey (this)) {
+					var a = allEmitted [this];
+					if (a == null) {
+						a = new List<Attribute> (2);
+						allEmitted [this] = a;
+					}
+					a.Add (this);
+				} else {
+					allEmitted.Add (this, null);
+				}
+			}
+
+			if (!context.Module.Compiler.Settings.VerifyClsCompliance)
+				return;
+
+			// Here we are testing attribute arguments for array usage (error 3016)
+			if (Owner.IsClsComplianceRequired ()) {
+				if (pos_args != null)
+					pos_args.CheckArrayAsAttribute (context.Module.Compiler);
+			
+				if (NamedArguments == null)
+					return;
+
+				NamedArguments.CheckArrayAsAttribute (context.Module.Compiler);
+			}
+		}
+
+		private Expression GetValue () 
+		{
+			if (pos_args == null || pos_args.Count < 1)
+				return null;
+
+			return pos_args[0].Expr;
+		}
+
+		public string GetString () 
+		{
+			Expression e = GetValue ();
+			if (e is StringConstant)
+				return ((StringConstant)e).Value;
+			return null;
+		}
+
+		public bool GetBoolean () 
+		{
+			Expression e = GetValue ();
+			if (e is BoolConstant)
+				return ((BoolConstant)e).Value;
+			return false;
+		}
+
+		public TypeSpec GetArgumentType ()
+		{
+			TypeOf e = GetValue () as TypeOf;
+			if (e == null)
+				return null;
+			return e.TypeArgument;
+		}
+	}
+	
+	public class Attributes
+	{
+		public readonly List<Attribute> Attrs;
+#if FULL_AST
+		public readonly List<List<Attribute>> Sections = new List<List<Attribute>> ();
+#endif
+
+		public Attributes (Attribute a)
+		{
+			Attrs = new List<Attribute> ();
+			Attrs.Add (a);
+			
+#if FULL_AST
+			Sections.Add (Attrs);
+#endif
+		}
+
+		public Attributes (List<Attribute> attrs)
+		{
+			Attrs = attrs ?? new List<Attribute> ();
+#if FULL_AST
+			Sections.Add (attrs);
+#endif
+		}
+
+		public void AddAttribute (Attribute attr)
+		{
+			Attrs.Add (attr);
+		}
+
+		public void AddAttributes (List<Attribute> attrs)
+		{
+#if FULL_AST
+			Sections.Add (attrs);
+#else
+			Attrs.AddRange (attrs);
+#endif
+		}
+
+		public void AttachTo (Attributable attributable, IMemberContext context)
+		{
+			foreach (Attribute a in Attrs)
+				a.AttachTo (attributable, context);
+		}
+
+		public Attributes Clone ()
+		{
+			var al = new List<Attribute> (Attrs.Count);
+			foreach (Attribute a in Attrs)
+				al.Add (a.Clone ());
+
+			return new Attributes (al);
+		}
+
+		/// <summary>
+		/// Checks whether attribute target is valid for the current element
+		/// </summary>
+		public bool CheckTargets ()
+		{
+			for (int i = 0; i < Attrs.Count; ++i) {
+				if (!Attrs [i].CheckTarget ())
+					Attrs.RemoveAt (i--);
+			}
+
+			return true;
+		}
+
+		public void ConvertGlobalAttributes (TypeContainer member, NamespaceContainer currentNamespace, bool isGlobal)
+		{
+			var member_explicit_targets = member.ValidAttributeTargets;
+			for (int i = 0; i < Attrs.Count; ++i) {
+				var attr = Attrs[0];
+				if (attr.ExplicitTarget == null)
+					continue;
+
+				int ii;
+				for (ii = 0; ii < member_explicit_targets.Length; ++ii) {
+					if (attr.ExplicitTarget == member_explicit_targets[ii]) {
+						ii = -1;
+						break;
+					}
+				}
+
+				if (ii < 0 || !isGlobal)
+					continue;
+
+				member.Module.AddAttribute (attr, currentNamespace);
+				Attrs.RemoveAt (i);
+				--i;
+			}
+		}
+
+		public bool HasResolveError()
+		{
+			foreach (var a in Attrs) {
+				if (a.ResolveError)
+					return true;
+			}
+
+			return false;
+		}
+
+		public Attribute Search (PredefinedAttribute t)
+		{
+			return Search (null, t);
+		}
+
+		public Attribute Search (string explicitTarget, PredefinedAttribute t)
+		{
+			foreach (Attribute a in Attrs) {
+				if (explicitTarget != null && a.ExplicitTarget != explicitTarget)
+					continue;
+
+				if (a.ResolveTypeForComparison () == t)
+					return a;
+			}
+			return null;
+		}
+
+		/// <summary>
+		/// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
+		/// </summary>
+		public Attribute[] SearchMulti (PredefinedAttribute t)
+		{
+			List<Attribute> ar = null;
+
+			foreach (Attribute a in Attrs) {
+				if (a.ResolveTypeForComparison () == t) {
+					if (ar == null)
+						ar = new List<Attribute> (Attrs.Count);
+					ar.Add (a);
+				}
+			}
+
+			return ar == null ? null : ar.ToArray ();
+		}
+
+		public void Emit ()
+		{
+			CheckTargets ();
+
+			Dictionary<Attribute, List<Attribute>> ld = Attrs.Count > 1 ? new Dictionary<Attribute, List<Attribute>> () : null;
+
+			foreach (Attribute a in Attrs)
+				a.Emit (ld);
+
+			if (ld == null || ld.Count == 0)
+				return;
+
+			foreach (var d in ld) {
+				if (d.Value == null)
+					continue;
+
+				Attribute a = d.Key;
+
+				foreach (Attribute collision in d.Value)
+					a.Report.SymbolRelatedToPreviousError (collision.Location, "");
+
+				a.Report.Error (579, a.Location, "The attribute `{0}' cannot be applied multiple times",
+					a.GetSignatureForError ());
+			}
+		}
+
+		public bool Contains (PredefinedAttribute t)
+		{
+			return Search (t) != null;
+		}
+	}
+
+	public sealed class AttributeEncoder
+	{
+		[Flags]
+		public enum EncodedTypeProperties
+		{
+			None = 0,
+			DynamicType = 1,
+			TypeParameter = 1 << 1
+		}
+
+		public static readonly byte[] Empty;
+
+		byte[] buffer;
+		int pos;
+		const ushort Version = 1;
+
+		static AttributeEncoder ()
+		{
+			Empty = new byte[4];
+			Empty[0] = (byte) Version;
+		}
+
+		public AttributeEncoder ()
+		{
+			buffer = new byte[32];
+			Encode (Version);
+		}
+
+		public void Encode (bool value)
+		{
+			Encode (value ? (byte) 1 : (byte) 0);
+		}
+
+		public void Encode (byte value)
+		{
+			if (pos == buffer.Length)
+				Grow (1);
+
+			buffer [pos++] = value;
+		}
+
+		public void Encode (sbyte value)
+		{
+			Encode ((byte) value);
+		}
+
+		public void Encode (short value)
+		{
+			if (pos + 2 > buffer.Length)
+				Grow (2);
+
+			buffer[pos++] = (byte) value;
+			buffer[pos++] = (byte) (value >> 8);
+		}
+
+		public void Encode (ushort value)
+		{
+			Encode ((short) value);
+		}
+
+		public void Encode (int value)
+		{
+			if (pos + 4 > buffer.Length)
+				Grow (4);
+
+			buffer[pos++] = (byte) value;
+			buffer[pos++] = (byte) (value >> 8);
+			buffer[pos++] = (byte) (value >> 16);
+			buffer[pos++] = (byte) (value >> 24);
+		}
+
+		public void Encode (uint value)
+		{
+			Encode ((int) value);
+		}
+
+		public void Encode (long value)
+		{
+			if (pos + 8 > buffer.Length)
+				Grow (8);
+
+			buffer[pos++] = (byte) value;
+			buffer[pos++] = (byte) (value >> 8);
+			buffer[pos++] = (byte) (value >> 16);
+			buffer[pos++] = (byte) (value >> 24);
+			buffer[pos++] = (byte) (value >> 32);
+			buffer[pos++] = (byte) (value >> 40);
+			buffer[pos++] = (byte) (value >> 48);
+			buffer[pos++] = (byte) (value >> 56);
+		}
+
+		public void Encode (ulong value)
+		{
+			Encode ((long) value);
+		}
+
+		public void Encode (float value)
+		{
+			Encode (SingleConverter.SingleToInt32Bits (value));
+		}
+
+		public void Encode (double value)
+		{
+			Encode (BitConverter.DoubleToInt64Bits (value));
+		}
+
+		public void Encode (string value)
+		{
+			if (value == null) {
+				Encode ((byte) 0xFF);
+				return;
+			}
+
+			var buf = Encoding.UTF8.GetBytes(value);
+			WriteCompressedValue (buf.Length);
+
+			if (pos + buf.Length > buffer.Length)
+				Grow (buf.Length);
+
+			Buffer.BlockCopy (buf, 0, buffer, pos, buf.Length);
+			pos += buf.Length;
+		}
+
+		public EncodedTypeProperties Encode (TypeSpec type)
+		{
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Bool:
+				Encode ((byte) 0x02);
+				break;
+			case BuiltinTypeSpec.Type.Char:
+				Encode ((byte) 0x03);
+				break;
+			case BuiltinTypeSpec.Type.SByte:
+				Encode ((byte) 0x04);
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				Encode ((byte) 0x05);
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				Encode ((byte) 0x06);
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+				Encode ((byte) 0x07);
+				break;
+			case BuiltinTypeSpec.Type.Int:
+				Encode ((byte) 0x08);
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				Encode ((byte) 0x09);
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				Encode ((byte) 0x0A);
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+				Encode ((byte) 0x0B);
+				break;
+			case BuiltinTypeSpec.Type.Float:
+				Encode ((byte) 0x0C);
+				break;
+			case BuiltinTypeSpec.Type.Double:
+				Encode ((byte) 0x0D);
+				break;
+			case BuiltinTypeSpec.Type.String:
+				Encode ((byte) 0x0E);
+				break;
+			case BuiltinTypeSpec.Type.Type:
+				Encode ((byte) 0x50);
+				break;
+			case BuiltinTypeSpec.Type.Object:
+				Encode ((byte) 0x51);
+				break;
+			case BuiltinTypeSpec.Type.Dynamic:
+				Encode ((byte) 0x51);
+				return EncodedTypeProperties.DynamicType;
+			default:
+				if (type.IsArray) {
+					Encode ((byte) 0x1D);
+					return Encode (TypeManager.GetElementType (type));
+				}
+
+				if (type.Kind == MemberKind.Enum) {
+					Encode ((byte) 0x55);
+					EncodeTypeName (type);
+				}
+
+				break;
+			}
+
+			return EncodedTypeProperties.None;
+		}
+
+		public void EncodeTypeName (TypeSpec type)
+		{
+			var old_type = type.GetMetaInfo ();
+			Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
+		}
+
+		public void EncodeTypeName (TypeContainer type)
+		{
+			Encode (type.GetSignatureForMetadata ());
+		}
+
+
+		//
+		// Encodes single property named argument per call
+		//
+		public void EncodeNamedPropertyArgument (PropertySpec property, Constant value)
+		{
+			Encode ((ushort) 1);	// length
+			Encode ((byte) 0x54); // property
+			Encode (property.MemberType);
+			Encode (property.Name);
+			value.EncodeAttributeValue (null, this, property.MemberType, property.MemberType);
+		}
+
+		//
+		// Encodes single field named argument per call
+		//
+		public void EncodeNamedFieldArgument (FieldSpec field, Constant value)
+		{
+			Encode ((ushort) 1);	// length
+			Encode ((byte) 0x53); // field
+			Encode (field.MemberType);
+			Encode (field.Name);
+			value.EncodeAttributeValue (null, this, field.MemberType, field.MemberType);
+		}
+
+		public void EncodeNamedArguments<T> (T[] members, Constant[] values) where T : MemberSpec, IInterfaceMemberSpec
+		{
+			Encode ((ushort) members.Length);
+
+			for (int i = 0; i < members.Length; ++i)
+			{
+				var member = members[i];
+
+				if (member.Kind == MemberKind.Field)
+					Encode ((byte) 0x53);
+				else if (member.Kind == MemberKind.Property)
+					Encode ((byte) 0x54);
+				else
+					throw new NotImplementedException (member.Kind.ToString ());
+
+				Encode (member.MemberType);
+				Encode (member.Name);
+				values [i].EncodeAttributeValue (null, this, member.MemberType, member.MemberType);
+			}
+		}
+
+		public void EncodeEmptyNamedArguments ()
+		{
+			Encode ((ushort) 0);
+		}
+
+		void Grow (int inc)
+		{
+			int size = System.Math.Max (pos * 4, pos + inc + 2);
+			Array.Resize (ref buffer, size);
+		}
+
+		void WriteCompressedValue (int value)
+		{
+			if (value < 0x80) {
+				Encode ((byte) value);
+				return;
+			}
+
+			if (value < 0x4000) {
+				Encode ((byte) (0x80 | (value >> 8)));
+				Encode ((byte) value);
+				return;
+			}
+
+			Encode (value);
+		}
+
+		public byte[] ToArray ()
+		{
+			byte[] buf = new byte[pos];
+			Array.Copy (buffer, buf, pos);
+			return buf;
+		}
+	}
+
+
+	/// <summary>
+	/// Helper class for attribute verification routine.
+	/// </summary>
+	static class AttributeTester
+	{
+		/// <summary>
+		/// Common method for Obsolete error/warning reporting.
+		/// </summary>
+		public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc, Report Report)
+		{
+			if (oa.IsError) {
+				Report.Error (619, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
+				return;
+			}
+
+			if (oa.Message == null || oa.Message.Length == 0) {
+				Report.Warning (612, 1, loc, "`{0}' is obsolete", member);
+				return;
+			}
+			Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
+		}
+	}
+
+	//
+	// Predefined attribute types
+	//
+	public class PredefinedAttributes
+	{
+		// Build-in attributes
+		public readonly PredefinedAttribute ParamArray;
+		public readonly PredefinedAttribute Out;
+
+		// Optional attributes
+		public readonly PredefinedAttribute Obsolete;
+		public readonly PredefinedAttribute DllImport;
+		public readonly PredefinedAttribute MethodImpl;
+		public readonly PredefinedAttribute MarshalAs;
+		public readonly PredefinedAttribute In;
+		public readonly PredefinedAttribute IndexerName;
+		public readonly PredefinedAttribute Conditional;
+		public readonly PredefinedAttribute CLSCompliant;
+		public readonly PredefinedAttribute Security;
+		public readonly PredefinedAttribute Required;
+		public readonly PredefinedAttribute Guid;
+		public readonly PredefinedAttribute AssemblyCulture;
+		public readonly PredefinedAttribute AssemblyVersion;
+		public readonly PredefinedAttribute AssemblyAlgorithmId;
+		public readonly PredefinedAttribute AssemblyFlags;
+		public readonly PredefinedAttribute AssemblyFileVersion;
+		public readonly PredefinedAttribute ComImport;
+		public readonly PredefinedAttribute CoClass;
+		public readonly PredefinedAttribute AttributeUsage;
+		public readonly PredefinedAttribute DefaultParameterValue;
+		public readonly PredefinedAttribute OptionalParameter;
+		public readonly PredefinedAttribute UnverifiableCode;
+		public readonly PredefinedAttribute DefaultCharset;
+		public readonly PredefinedAttribute TypeForwarder;
+		public readonly PredefinedAttribute FixedBuffer;
+		public readonly PredefinedAttribute CompilerGenerated;
+		public readonly PredefinedAttribute InternalsVisibleTo;
+		public readonly PredefinedAttribute RuntimeCompatibility;
+		public readonly PredefinedAttribute DebuggerHidden;
+		public readonly PredefinedAttribute UnsafeValueType;
+		public readonly PredefinedAttribute UnmanagedFunctionPointer;
+		public readonly PredefinedDebuggerBrowsableAttribute DebuggerBrowsable;
+		public readonly PredefinedAttribute DebuggerStepThrough;
+		public readonly PredefinedDebuggableAttribute Debuggable;
+
+		// New in .NET 3.5
+		public readonly PredefinedAttribute Extension;
+
+		// New in .NET 4.0
+		public readonly PredefinedDynamicAttribute Dynamic;
+
+		// New in .NET 4.5
+		public readonly PredefinedStateMachineAttribute AsyncStateMachine;
+
+		//
+		// Optional types which are used as types and for member lookup
+		//
+		public readonly PredefinedAttribute DefaultMember;
+		public readonly PredefinedDecimalAttribute DecimalConstant;
+		public readonly PredefinedAttribute StructLayout;
+		public readonly PredefinedAttribute FieldOffset;
+		public readonly PredefinedAttribute AssemblyProduct;
+		public readonly PredefinedAttribute AssemblyCompany;
+		public readonly PredefinedAttribute AssemblyDescription;
+		public readonly PredefinedAttribute AssemblyCopyright;
+		public readonly PredefinedAttribute AssemblyTrademark;
+		public readonly PredefinedAttribute CallerMemberNameAttribute;
+		public readonly PredefinedAttribute CallerLineNumberAttribute;
+		public readonly PredefinedAttribute CallerFilePathAttribute;
+
+		public PredefinedAttributes (ModuleContainer module)
+		{
+			ParamArray = new PredefinedAttribute (module, "System", "ParamArrayAttribute");
+			Out = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OutAttribute");
+			ParamArray.Resolve ();
+			Out.Resolve ();
+
+			Obsolete = new PredefinedAttribute (module, "System", "ObsoleteAttribute");
+			DllImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DllImportAttribute");
+			MethodImpl = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "MethodImplAttribute");
+			MarshalAs = new PredefinedAttribute (module, "System.Runtime.InteropServices", "MarshalAsAttribute");
+			In = new PredefinedAttribute (module, "System.Runtime.InteropServices", "InAttribute");
+			IndexerName = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "IndexerNameAttribute");
+			Conditional = new PredefinedAttribute (module, "System.Diagnostics", "ConditionalAttribute");
+			CLSCompliant = new PredefinedAttribute (module, "System", "CLSCompliantAttribute");
+			Security = new PredefinedAttribute (module, "System.Security.Permissions", "SecurityAttribute");
+			Required = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RequiredAttributeAttribute");
+			Guid = new PredefinedAttribute (module, "System.Runtime.InteropServices", "GuidAttribute");
+			AssemblyCulture = new PredefinedAttribute (module, "System.Reflection", "AssemblyCultureAttribute");
+			AssemblyVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyVersionAttribute");
+			AssemblyAlgorithmId = new PredefinedAttribute (module, "System.Reflection", "AssemblyAlgorithmIdAttribute");
+			AssemblyFlags = new PredefinedAttribute (module, "System.Reflection", "AssemblyFlagsAttribute");
+			AssemblyFileVersion = new PredefinedAttribute (module, "System.Reflection", "AssemblyFileVersionAttribute");
+			ComImport = new PredefinedAttribute (module, "System.Runtime.InteropServices", "ComImportAttribute");
+			CoClass = new PredefinedAttribute (module, "System.Runtime.InteropServices", "CoClassAttribute");
+			AttributeUsage = new PredefinedAttribute (module, "System", "AttributeUsageAttribute");
+			DefaultParameterValue = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultParameterValueAttribute");
+			OptionalParameter = new PredefinedAttribute (module, "System.Runtime.InteropServices", "OptionalAttribute");
+			UnverifiableCode = new PredefinedAttribute (module, "System.Security", "UnverifiableCodeAttribute");
+
+			DefaultCharset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "DefaultCharSetAttribute");
+			TypeForwarder = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "TypeForwardedToAttribute");
+			FixedBuffer = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "FixedBufferAttribute");
+			CompilerGenerated = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
+			InternalsVisibleTo = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute");
+			RuntimeCompatibility = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute");
+			DebuggerHidden = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerHiddenAttribute");
+			UnsafeValueType = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
+			UnmanagedFunctionPointer = new PredefinedAttribute (module, "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute");
+			DebuggerBrowsable = new PredefinedDebuggerBrowsableAttribute (module, "System.Diagnostics", "DebuggerBrowsableAttribute");
+			DebuggerStepThrough = new PredefinedAttribute (module, "System.Diagnostics", "DebuggerStepThroughAttribute");
+			Debuggable = new PredefinedDebuggableAttribute (module, "System.Diagnostics", "DebuggableAttribute");
+
+			Extension = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "ExtensionAttribute");
+
+			Dynamic = new PredefinedDynamicAttribute (module, "System.Runtime.CompilerServices", "DynamicAttribute");
+
+			DefaultMember = new PredefinedAttribute (module, "System.Reflection", "DefaultMemberAttribute");
+			DecimalConstant = new PredefinedDecimalAttribute (module, "System.Runtime.CompilerServices", "DecimalConstantAttribute");
+			StructLayout = new PredefinedAttribute (module, "System.Runtime.InteropServices", "StructLayoutAttribute");
+			FieldOffset = new PredefinedAttribute (module, "System.Runtime.InteropServices", "FieldOffsetAttribute");
+			AssemblyProduct = new PredefinedAttribute (module, "System.Reflection", "AssemblyProductAttribute");
+			AssemblyCompany = new PredefinedAttribute (module, "System.Reflection", "AssemblyCompanyAttribute");
+			AssemblyDescription = new PredefinedAttribute (module, "System.Reflection", "AssemblyDescriptionAttribute");
+			AssemblyCopyright = new PredefinedAttribute (module, "System.Reflection", "AssemblyCopyrightAttribute");
+			AssemblyTrademark = new PredefinedAttribute (module, "System.Reflection", "AssemblyTrademarkAttribute");
+
+			AsyncStateMachine = new PredefinedStateMachineAttribute (module, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute");
+
+			CallerMemberNameAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerMemberNameAttribute");
+			CallerLineNumberAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerLineNumberAttribute");
+			CallerFilePathAttribute = new PredefinedAttribute (module, "System.Runtime.CompilerServices", "CallerFilePathAttribute");
+
+			// TODO: Should define only attributes which are used for comparison
+			const System.Reflection.BindingFlags all_fields = System.Reflection.BindingFlags.Public |
+				System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;
+
+			foreach (var fi in GetType ().GetFields (all_fields)) {
+				((PredefinedAttribute) fi.GetValue (this)).Define ();
+			}
+		}
+	}
+
+	public class PredefinedAttribute : PredefinedType
+	{
+		protected MethodSpec ctor;
+
+		public PredefinedAttribute (ModuleContainer module, string ns, string name)
+			: base (module, MemberKind.Class, ns, name)
+		{
+		}
+
+		#region Properties
+
+		public MethodSpec Constructor {
+			get {
+				return ctor;
+			}
+		}
+
+		#endregion
+
+		public static bool operator == (TypeSpec type, PredefinedAttribute pa)
+		{
+			return type == pa.type && pa.type != null;
+		}
+
+		public static bool operator != (TypeSpec type, PredefinedAttribute pa)
+		{
+			return type != pa.type;
+		}
+
+		public override int GetHashCode ()
+		{
+			return base.GetHashCode ();
+		}
+
+		public override bool Equals (object obj)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public void EmitAttribute (ConstructorBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (MethodBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (PropertyBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (FieldBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (TypeBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (AssemblyBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (ModuleBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		public void EmitAttribute (ParameterBuilder builder)
+		{
+			if (ResolveBuilder ())
+				builder.SetCustomAttribute (GetCtorMetaInfo (), AttributeEncoder.Empty);
+		}
+
+		ConstructorInfo GetCtorMetaInfo ()
+		{
+			return (ConstructorInfo) ctor.GetMetaInfo ();
+		}
+
+		public bool ResolveBuilder ()
+		{
+			if (ctor != null)
+				return true;
+
+			//
+			// Handle all parameter-less attributes as optional
+			//
+			if (!Define ())
+				return false;
+
+			ctor = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters), BindingRestriction.DeclaredOnly);
+			return ctor != null;
+		}
+	}
+
+	public class PredefinedDebuggerBrowsableAttribute : PredefinedAttribute
+	{
+		public PredefinedDebuggerBrowsableAttribute (ModuleContainer module, string ns, string name)
+			: base (module, ns, name)
+		{
+		}
+
+		public void EmitAttribute (FieldBuilder builder, System.Diagnostics.DebuggerBrowsableState state)
+		{
+			var ctor = module.PredefinedMembers.DebuggerBrowsableAttributeCtor.Get ();
+			if (ctor == null)
+				return;
+
+			AttributeEncoder encoder = new AttributeEncoder ();
+			encoder.Encode ((int) state);
+			encoder.EncodeEmptyNamedArguments ();
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+	}
+
+	public class PredefinedDebuggableAttribute : PredefinedAttribute
+	{
+		public PredefinedDebuggableAttribute (ModuleContainer module, string ns, string name)
+			: base (module, ns, name)
+		{
+		}
+
+		public void EmitAttribute (AssemblyBuilder builder, System.Diagnostics.DebuggableAttribute.DebuggingModes modes)
+		{
+			var atype = module.PredefinedAttributes.Debuggable;
+			if (!atype.Define ())
+				return;
+
+			MethodSpec ctor = null;
+			foreach (MethodSpec m in MemberCache.FindMembers (atype.TypeSpec, CSharp.Constructor.ConstructorName, true)) {
+				if (m.Parameters.Count != 1)
+					continue;
+
+				if (m.Parameters.Types[0].Kind == MemberKind.Enum) {
+					ctor = m;
+				}
+			}
+
+			if (ctor == null)
+				return;
+
+			AttributeEncoder encoder = new AttributeEncoder ();
+			encoder.Encode ((int) modes);
+			encoder.EncodeEmptyNamedArguments ();
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+	}
+
+	public class PredefinedDecimalAttribute : PredefinedAttribute
+	{
+		public PredefinedDecimalAttribute (ModuleContainer module, string ns, string name)
+			: base (module, ns, name)
+		{
+		}
+
+		public void EmitAttribute (ParameterBuilder builder, decimal value, Location loc)
+		{
+			var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
+			if (ctor == null)
+				return;
+
+			int[] bits = decimal.GetBits (value);
+			AttributeEncoder encoder = new AttributeEncoder ();
+			encoder.Encode ((byte) (bits[3] >> 16));
+			encoder.Encode ((byte) (bits[3] >> 31));
+			encoder.Encode ((uint) bits[2]);
+			encoder.Encode ((uint) bits[1]);
+			encoder.Encode ((uint) bits[0]);
+			encoder.EncodeEmptyNamedArguments ();
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+
+		public void EmitAttribute (FieldBuilder builder, decimal value, Location loc)
+		{
+			var ctor = module.PredefinedMembers.DecimalConstantAttributeCtor.Resolve (loc);
+			if (ctor == null)
+				return;
+
+			int[] bits = decimal.GetBits (value);
+			AttributeEncoder encoder = new AttributeEncoder ();
+			encoder.Encode ((byte) (bits[3] >> 16));
+			encoder.Encode ((byte) (bits[3] >> 31));
+			encoder.Encode ((uint) bits[2]);
+			encoder.Encode ((uint) bits[1]);
+			encoder.Encode ((uint) bits[0]);
+			encoder.EncodeEmptyNamedArguments ();
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+	}
+
+	public class PredefinedStateMachineAttribute : PredefinedAttribute
+	{
+		public PredefinedStateMachineAttribute (ModuleContainer module, string ns, string name)
+			: base (module, ns, name)
+		{
+		}
+
+		public void EmitAttribute (MethodBuilder builder, StateMachine type)
+		{
+			var predefined_ctor = module.PredefinedMembers.AsyncStateMachineAttributeCtor;
+
+			var ctor = predefined_ctor.Get ();
+
+			if (ctor == null)
+				return;
+
+			AttributeEncoder encoder = new AttributeEncoder ();
+			encoder.EncodeTypeName (type);
+			encoder.EncodeEmptyNamedArguments ();
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+	}
+
+	public class PredefinedDynamicAttribute : PredefinedAttribute
+	{
+		MethodSpec tctor;
+
+		public PredefinedDynamicAttribute (ModuleContainer module, string ns, string name)
+			: base (module, ns, name)
+		{
+		}
+
+		public void EmitAttribute (FieldBuilder builder, TypeSpec type, Location loc)
+		{
+			if (ResolveTransformationCtor (loc)) {
+				var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+				builder.SetCustomAttribute (cab);
+			}
+		}
+
+		public void EmitAttribute (ParameterBuilder builder, TypeSpec type, Location loc)
+		{
+			if (ResolveTransformationCtor (loc)) {
+				var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+				builder.SetCustomAttribute (cab);
+			}
+		}
+
+		public void EmitAttribute (PropertyBuilder builder, TypeSpec type, Location loc)
+		{
+			if (ResolveTransformationCtor (loc)) {
+				var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+				builder.SetCustomAttribute (cab);
+			}
+		}
+
+		public void EmitAttribute (TypeBuilder builder, TypeSpec type, Location loc)
+		{
+			if (ResolveTransformationCtor (loc)) {
+				var cab = new CustomAttributeBuilder ((ConstructorInfo) tctor.GetMetaInfo (), new object[] { GetTransformationFlags (type) });
+				builder.SetCustomAttribute (cab);
+			}
+		}
+
+		//
+		// When any element of the type is a dynamic type
+		//
+		// This method builds a transformation array for dynamic types
+		// used in places where DynamicAttribute cannot be applied to.
+		// It uses bool flag when type is of dynamic type and each
+		// section always starts with "false" for some reason.
+		//
+		// LAMESPEC: This should be part of C# specification
+		// 
+		// Example: Func<dynamic, int, dynamic[]>
+		// Transformation: { false, true, false, false, true }
+		//
+		static bool[] GetTransformationFlags (TypeSpec t)
+		{
+			bool[] element;
+			var ac = t as ArrayContainer;
+			if (ac != null) {
+				element = GetTransformationFlags (ac.Element);
+				if (element == null)
+					return new bool[] { false, false };
+
+				bool[] res = new bool[element.Length + 1];
+				res[0] = false;
+				Array.Copy (element, 0, res, 1, element.Length);
+				return res;
+			}
+
+			if (t == null)
+				return null;
+
+			if (t.IsGeneric) {
+				List<bool> transform = null;
+				var targs = t.TypeArguments;
+				for (int i = 0; i < targs.Length; ++i) {
+					element = GetTransformationFlags (targs[i]);
+					if (element != null) {
+						if (transform == null) {
+							transform = new List<bool> ();
+							for (int ii = 0; ii <= i; ++ii)
+								transform.Add (false);
+						}
+
+						transform.AddRange (element);
+					} else if (transform != null) {
+						transform.Add (false);
+					}
+				}
+
+				if (transform != null)
+					return transform.ToArray ();
+			}
+
+			if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+				return new bool[] { true };
+
+			return null;
+		}
+
+		bool ResolveTransformationCtor (Location loc)
+		{
+			if (tctor != null)
+				return true;
+
+			tctor = module.PredefinedMembers.DynamicAttributeCtor.Resolve (loc);
+			return tctor != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cfold.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cfold.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cfold.cs	(revision 11807)
@@ -0,0 +1,1192 @@
+//
+// cfold.cs: Constant Folding
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@seznam.cz)
+//
+// Copyright 2002, 2003 Ximian, Inc.
+// Copyright 2003-2011, Novell, Inc.
+// 
+using System;
+
+namespace Mono.CSharp {
+
+	public static class ConstantFold
+	{
+		public static TypeSpec[] CreateBinaryPromotionsTypes (BuiltinTypes types)
+		{
+			return new TypeSpec[] { 
+				types.Decimal, types.Double, types.Float,
+				types.ULong, types.Long, types.UInt
+			};
+		}
+
+		//
+		// Performs the numeric promotions on the left and right expresions
+		// and deposits the results on `lc' and `rc'.
+		//
+		// On success, the types of `lc' and `rc' on output will always match,
+		// and the pair will be one of:
+		//
+		// TODO: BinaryFold should be called as an optimization step only,
+		// error checking here is weak
+		//		
+		static bool DoBinaryNumericPromotions (ResolveContext rc, ref Constant left, ref Constant right)
+		{
+			TypeSpec ltype = left.Type;
+			TypeSpec rtype = right.Type;
+
+			foreach (TypeSpec t in rc.BuiltinTypes.BinaryPromotionsTypes) {
+				if (t == ltype)
+					return t == rtype || ConvertPromotion (rc, ref right, ref left, t);
+
+				if (t == rtype)
+					return t == ltype || ConvertPromotion (rc, ref left, ref right, t);
+			}
+
+			left = left.ConvertImplicitly (rc.BuiltinTypes.Int);
+			right = right.ConvertImplicitly (rc.BuiltinTypes.Int);
+			return left != null && right != null;
+		}
+
+		static bool ConvertPromotion (ResolveContext rc, ref Constant prim, ref Constant second, TypeSpec type)
+		{
+			Constant c = prim.ConvertImplicitly (type);
+			if (c != null) {
+				prim = c;
+				return true;
+			}
+
+			if (type.BuiltinType == BuiltinTypeSpec.Type.UInt) {
+				type = rc.BuiltinTypes.Long;
+				prim = prim.ConvertImplicitly (type);
+				second = second.ConvertImplicitly (type);
+				return prim != null && second != null;
+			}
+
+			return false;
+		}
+
+		internal static void Error_CompileTimeOverflow (ResolveContext rc, Location loc)
+		{
+			rc.Report.Error (220, loc, "The operation overflows at compile time in checked mode");
+		}
+		
+		/// <summary>
+		///   Constant expression folder for binary operations.
+		///
+		///   Returns null if the expression can not be folded.
+		/// </summary>
+		static public Constant BinaryFold (ResolveContext ec, Binary.Operator oper,
+						     Constant left, Constant right, Location loc)
+		{
+			Constant result = null;
+
+			if (left is EmptyConstantCast)
+				return BinaryFold (ec, oper, ((EmptyConstantCast)left).child, right, loc);
+
+			if (left is SideEffectConstant) {
+				result = BinaryFold (ec, oper, ((SideEffectConstant) left).value, right, loc);
+				if (result == null)
+					return null;
+				return new SideEffectConstant (result, left, loc);
+			}
+
+			if (right is EmptyConstantCast)
+				return BinaryFold (ec, oper, left, ((EmptyConstantCast)right).child, loc);
+
+			if (right is SideEffectConstant) {
+				result = BinaryFold (ec, oper, left, ((SideEffectConstant) right).value, loc);
+				if (result == null)
+					return null;
+				return new SideEffectConstant (result, right, loc);
+			}
+
+			TypeSpec lt = left.Type;
+			TypeSpec rt = right.Type;
+			bool bool_res;
+
+			if (lt.BuiltinType == BuiltinTypeSpec.Type.Bool && lt == rt) {
+				bool lv = (bool) left.GetValue ();
+				bool rv = (bool) right.GetValue ();			
+				switch (oper) {
+				case Binary.Operator.BitwiseAnd:
+				case Binary.Operator.LogicalAnd:
+					return new BoolConstant (ec.BuiltinTypes, lv && rv, left.Location);
+				case Binary.Operator.BitwiseOr:
+				case Binary.Operator.LogicalOr:
+					return new BoolConstant (ec.BuiltinTypes, lv || rv, left.Location);
+				case Binary.Operator.ExclusiveOr:
+					return new BoolConstant (ec.BuiltinTypes, lv ^ rv, left.Location);
+				case Binary.Operator.Equality:
+					return new BoolConstant (ec.BuiltinTypes, lv == rv, left.Location);
+				case Binary.Operator.Inequality:
+					return new BoolConstant (ec.BuiltinTypes, lv != rv, left.Location);
+				}
+				return null;
+			}
+
+			//
+			// During an enum evaluation, none of the rules are valid
+			// Not sure whether it is bug in csc or in documentation
+			//
+			if (ec.HasSet (ResolveContext.Options.EnumScope)){
+				if (left is EnumConstant)
+					left = ((EnumConstant) left).Child;
+				
+				if (right is EnumConstant)
+					right = ((EnumConstant) right).Child;
+			} else if (left is EnumConstant && rt == lt) {
+				switch (oper){
+					///
+					/// E operator |(E x, E y);
+					/// E operator &(E x, E y);
+					/// E operator ^(E x, E y);
+					/// 
+					case Binary.Operator.BitwiseOr:
+					case Binary.Operator.BitwiseAnd:
+					case Binary.Operator.ExclusiveOr:
+						result = BinaryFold (ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc);
+						if (result != null)
+							result = result.Reduce (ec, lt);
+						return result;
+
+					///
+					/// U operator -(E x, E y);
+					/// 
+					case Binary.Operator.Subtraction:
+						result = BinaryFold (ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc);
+						if (result != null)
+							result = result.Reduce (ec, EnumSpec.GetUnderlyingType (lt));
+						return result;
+
+					///
+					/// bool operator ==(E x, E y);
+					/// bool operator !=(E x, E y);
+					/// bool operator <(E x, E y);
+					/// bool operator >(E x, E y);
+					/// bool operator <=(E x, E y);
+					/// bool operator >=(E x, E y);
+					/// 
+					case Binary.Operator.Equality:				
+					case Binary.Operator.Inequality:
+					case Binary.Operator.LessThan:				
+					case Binary.Operator.GreaterThan:
+					case Binary.Operator.LessThanOrEqual:				
+					case Binary.Operator.GreaterThanOrEqual:
+						return BinaryFold(ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc);
+				}
+				return null;
+			}
+
+			switch (oper){
+			case Binary.Operator.BitwiseOr:
+				//
+				// bool? operator |(bool? x, bool? y);
+				//
+				if ((lt.BuiltinType == BuiltinTypeSpec.Type.Bool && right is NullLiteral) ||
+					(rt.BuiltinType == BuiltinTypeSpec.Type.Bool && left is NullLiteral)) {
+					var b = new Binary (oper, left, right).ResolveOperator (ec);
+
+					// false | null => null
+					// null | false => null
+					if ((right is NullLiteral && left.IsDefaultValue) || (left is NullLiteral && right.IsDefaultValue))
+						return Nullable.LiftedNull.CreateFromExpression (ec, b);
+
+					// true | null => true
+					// null | true => true
+					return ReducedExpression.Create (new BoolConstant (ec.BuiltinTypes, true, loc), b);					
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				if (left is IntConstant){
+					int res = ((IntConstant) left).Value | ((IntConstant) right).Value;
+
+					return new IntConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is UIntConstant){
+					uint res = ((UIntConstant)left).Value | ((UIntConstant)right).Value;
+
+					return new UIntConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is LongConstant){
+					long res = ((LongConstant)left).Value | ((LongConstant)right).Value;
+
+					return new LongConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is ULongConstant){
+					ulong res = ((ULongConstant)left).Value |
+						((ULongConstant)right).Value;
+
+					return new ULongConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				break;
+				
+			case Binary.Operator.BitwiseAnd:
+				//
+				// bool? operator &(bool? x, bool? y);
+				//
+				if ((lt.BuiltinType == BuiltinTypeSpec.Type.Bool && right is NullLiteral) ||
+					(rt.BuiltinType == BuiltinTypeSpec.Type.Bool && left is NullLiteral)) {
+					var b = new Binary (oper, left, right).ResolveOperator (ec);
+
+					// false & null => false
+					// null & false => false
+					if ((right is NullLiteral && left.IsDefaultValue) || (left is NullLiteral && right.IsDefaultValue))
+						return ReducedExpression.Create (new BoolConstant (ec.BuiltinTypes, false, loc), b);
+
+					// true & null => null
+					// null & true => null
+					return Nullable.LiftedNull.CreateFromExpression (ec, b);
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+				
+				///
+				/// int operator &(int x, int y);
+				/// uint operator &(uint x, uint y);
+				/// long operator &(long x, long y);
+				/// ulong operator &(ulong x, ulong y);
+				///
+				if (left is IntConstant){
+					int res = ((IntConstant) left).Value & ((IntConstant) right).Value;
+					return new IntConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is UIntConstant){
+					uint res = ((UIntConstant)left).Value & ((UIntConstant)right).Value;
+					return new UIntConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is LongConstant){
+					long res = ((LongConstant)left).Value & ((LongConstant)right).Value;
+					return new LongConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is ULongConstant){
+					ulong res = ((ULongConstant)left).Value &
+						((ULongConstant)right).Value;
+
+					return new ULongConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				break;
+
+			case Binary.Operator.ExclusiveOr:
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+				
+				if (left is IntConstant){
+					int res = ((IntConstant) left).Value ^ ((IntConstant) right).Value;
+					return new IntConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is UIntConstant){
+					uint res = ((UIntConstant)left).Value ^ ((UIntConstant)right).Value;
+
+					return new UIntConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is LongConstant){
+					long res = ((LongConstant)left).Value ^ ((LongConstant)right).Value;
+
+					return new LongConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				if (left is ULongConstant){
+					ulong res = ((ULongConstant)left).Value ^
+						((ULongConstant)right).Value;
+
+					return new ULongConstant (ec.BuiltinTypes, res, left.Location);
+				}
+				break;
+
+			case Binary.Operator.Addition:
+				//
+				// If both sides are strings, then concatenate
+				//
+				// string operator + (string x, string y)
+				//
+				if (lt.BuiltinType == BuiltinTypeSpec.Type.String || rt.BuiltinType == BuiltinTypeSpec.Type.String){
+					if (lt == rt)
+						return new StringConstant (ec.BuiltinTypes, (string)left.GetValue () + (string)right.GetValue (),
+							left.Location);
+
+					if (lt == InternalType.NullLiteral || left.IsNull)
+						return new StringConstant (ec.BuiltinTypes, "" + right.GetValue (), left.Location);
+
+					if (rt == InternalType.NullLiteral || right.IsNull)
+						return new StringConstant (ec.BuiltinTypes, left.GetValue () + "", left.Location);
+
+					return null;
+				}
+
+				//
+				// string operator + (string x, object y)
+				//
+				if (lt == InternalType.NullLiteral) {
+					if (rt.BuiltinType == BuiltinTypeSpec.Type.Object)
+						return new StringConstant (ec.BuiltinTypes, "" + right.GetValue (), left.Location);
+
+					if (lt == rt) {
+						ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
+							"+", lt.GetSignatureForError (), rt.GetSignatureForError ());
+						return null;
+					}
+
+					return right;
+				}
+
+				//
+				// string operator + (object x, string y)
+				//
+				if (rt == InternalType.NullLiteral) {
+					if (lt.BuiltinType == BuiltinTypeSpec.Type.Object)
+						return new StringConstant (ec.BuiltinTypes, right.GetValue () + "", left.Location);
+	
+					return left;
+				}
+
+				//
+				// handle "E operator + (E x, U y)"
+				// handle "E operator + (Y y, E x)"
+				//
+				EnumConstant lc = left as EnumConstant;
+				EnumConstant rc = right as EnumConstant;
+				if (lc != null || rc != null){
+					if (lc == null) {
+						lc = rc;
+						lt = lc.Type;
+						right = left;
+					}
+
+					// U has to be implicitly convetible to E.base
+					right = right.ConvertImplicitly (lc.Child.Type);
+					if (right == null)
+						return null;
+
+					result = BinaryFold (ec, oper, lc.Child, right, loc);
+					if (result == null)
+						return null;
+
+					result = result.Reduce (ec, lt);
+					if (result == null || lt.IsEnum)
+						return result;
+
+					return new EnumConstant (result, lt);
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				try {
+					if (left is DoubleConstant){
+						double res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((DoubleConstant) left).Value +
+								       ((DoubleConstant) right).Value);
+						else
+							res = unchecked (((DoubleConstant) left).Value +
+									 ((DoubleConstant) right).Value);
+
+						return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
+					}
+					if (left is FloatConstant){
+						double a, b, res;
+						a = ((FloatConstant) left).DoubleValue;
+						b = ((FloatConstant) right).DoubleValue;
+
+						if (ec.ConstantCheckState)
+							res = checked (a + b);
+						else
+							res = unchecked (a + b);
+
+						result = new FloatConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is ULongConstant){
+						ulong res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((ULongConstant) left).Value +
+								       ((ULongConstant) right).Value);
+						else
+							res = unchecked (((ULongConstant) left).Value +
+									 ((ULongConstant) right).Value);
+
+						result = new ULongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is LongConstant){
+						long res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((LongConstant) left).Value +
+								       ((LongConstant) right).Value);
+						else
+							res = unchecked (((LongConstant) left).Value +
+									 ((LongConstant) right).Value);
+
+						result = new LongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is UIntConstant){
+						uint res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((UIntConstant) left).Value +
+								       ((UIntConstant) right).Value);
+						else
+							res = unchecked (((UIntConstant) left).Value +
+									 ((UIntConstant) right).Value);
+
+						result = new UIntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is IntConstant){
+						int res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((IntConstant) left).Value +
+								       ((IntConstant) right).Value);
+						else
+							res = unchecked (((IntConstant) left).Value +
+									 ((IntConstant) right).Value);
+
+						result = new IntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is DecimalConstant) {
+						decimal res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((DecimalConstant) left).Value +
+								((DecimalConstant) right).Value);
+						else
+							res = unchecked (((DecimalConstant) left).Value +
+								((DecimalConstant) right).Value);
+
+						result = new DecimalConstant (ec.BuiltinTypes, res, left.Location);
+					}
+				} catch (OverflowException){
+					Error_CompileTimeOverflow (ec, loc);
+				}
+
+				return result;
+
+			case Binary.Operator.Subtraction:
+				//
+				// handle "E operator - (E x, U y)"
+				// handle "E operator - (Y y, E x)"
+				//
+				lc = left as EnumConstant;
+				rc = right as EnumConstant;
+				if (lc != null || rc != null){
+					if (lc == null) {
+						lc = rc;
+						lt = lc.Type;
+						right = left;
+					}
+
+					// U has to be implicitly convetible to E.base
+					right = right.ConvertImplicitly (lc.Child.Type);
+					if (right == null)
+						return null;
+
+					result = BinaryFold (ec, oper, lc.Child, right, loc);
+					if (result == null)
+						return null;
+
+					result = result.Reduce (ec, lt);
+					if (result == null)
+						return null;
+
+					return new EnumConstant (result, lt);
+				}
+
+				if (left is NullLiteral && right is NullLiteral) {
+					var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+					lifted_int.ResolveAsType (ec);
+					return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				try {
+					if (left is DoubleConstant){
+						double res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((DoubleConstant) left).Value -
+								       ((DoubleConstant) right).Value);
+						else
+							res = unchecked (((DoubleConstant) left).Value -
+									 ((DoubleConstant) right).Value);
+
+						result = new DoubleConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is FloatConstant){
+						double a, b, res;
+						a = ((FloatConstant) left).DoubleValue;
+						b = ((FloatConstant) right).DoubleValue;
+
+						if (ec.ConstantCheckState)
+							res = checked (a - b);
+						else
+							res = unchecked (a - b);
+
+						result = new FloatConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is ULongConstant){
+						ulong res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((ULongConstant) left).Value -
+								       ((ULongConstant) right).Value);
+						else
+							res = unchecked (((ULongConstant) left).Value -
+									 ((ULongConstant) right).Value);
+
+						result = new ULongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is LongConstant){
+						long res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((LongConstant) left).Value -
+								       ((LongConstant) right).Value);
+						else
+							res = unchecked (((LongConstant) left).Value -
+									 ((LongConstant) right).Value);
+
+						result = new LongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is UIntConstant){
+						uint res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((UIntConstant) left).Value -
+								       ((UIntConstant) right).Value);
+						else
+							res = unchecked (((UIntConstant) left).Value -
+									 ((UIntConstant) right).Value);
+
+						result = new UIntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is IntConstant){
+						int res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((IntConstant) left).Value -
+								       ((IntConstant) right).Value);
+						else
+							res = unchecked (((IntConstant) left).Value -
+									 ((IntConstant) right).Value);
+
+						result = new IntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is DecimalConstant) {
+						decimal res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((DecimalConstant) left).Value -
+								((DecimalConstant) right).Value);
+						else
+							res = unchecked (((DecimalConstant) left).Value -
+								((DecimalConstant) right).Value);
+
+						return new DecimalConstant (ec.BuiltinTypes, res, left.Location);
+					} else {
+						throw new Exception ( "Unexepected subtraction input: " + left);
+					}
+				} catch (OverflowException){
+					Error_CompileTimeOverflow (ec, loc);
+				}
+
+				return result;
+				
+			case Binary.Operator.Multiply:
+				if (left is NullLiteral && right is NullLiteral) {
+					var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+					lifted_int.ResolveAsType (ec);
+					return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				try {
+					if (left is DoubleConstant){
+						double res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((DoubleConstant) left).Value *
+								((DoubleConstant) right).Value);
+						else
+							res = unchecked (((DoubleConstant) left).Value *
+								((DoubleConstant) right).Value);
+
+						return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is FloatConstant){
+						double a, b, res;
+						a = ((FloatConstant) left).DoubleValue;
+						b = ((FloatConstant) right).DoubleValue;
+
+						if (ec.ConstantCheckState)
+							res = checked (a * b);
+						else
+							res = unchecked (a * b);
+
+						return new FloatConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is ULongConstant){
+						ulong res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((ULongConstant) left).Value *
+								((ULongConstant) right).Value);
+						else
+							res = unchecked (((ULongConstant) left).Value *
+								((ULongConstant) right).Value);
+
+						return new ULongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is LongConstant){
+						long res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((LongConstant) left).Value *
+								((LongConstant) right).Value);
+						else
+							res = unchecked (((LongConstant) left).Value *
+								((LongConstant) right).Value);
+
+						return new LongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is UIntConstant){
+						uint res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((UIntConstant) left).Value *
+								((UIntConstant) right).Value);
+						else
+							res = unchecked (((UIntConstant) left).Value *
+								((UIntConstant) right).Value);
+
+						return new UIntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is IntConstant){
+						int res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((IntConstant) left).Value *
+								((IntConstant) right).Value);
+						else
+							res = unchecked (((IntConstant) left).Value *
+								((IntConstant) right).Value);
+
+						return new IntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is DecimalConstant) {
+						decimal res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((DecimalConstant) left).Value *
+								((DecimalConstant) right).Value);
+						else
+							res = unchecked (((DecimalConstant) left).Value *
+								((DecimalConstant) right).Value);
+
+						return new DecimalConstant (ec.BuiltinTypes, res, left.Location);
+					} else {
+						throw new Exception ( "Unexepected multiply input: " + left);
+					}
+				} catch (OverflowException){
+					Error_CompileTimeOverflow (ec, loc);
+				}
+				break;
+
+			case Binary.Operator.Division:
+				if (left is NullLiteral && right is NullLiteral) {
+					var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+					lifted_int.ResolveAsType (ec);
+					return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				try {
+					if (left is DoubleConstant){
+						double res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((DoubleConstant) left).Value /
+								((DoubleConstant) right).Value);
+						else
+							res = unchecked (((DoubleConstant) left).Value /
+								((DoubleConstant) right).Value);
+
+						return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is FloatConstant){
+						double a, b, res;
+						a = ((FloatConstant) left).DoubleValue;
+						b = ((FloatConstant) right).DoubleValue;
+
+						if (ec.ConstantCheckState)
+							res = checked (a / b);
+						else
+							res = unchecked (a / b);
+
+						return new FloatConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is ULongConstant){
+						ulong res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((ULongConstant) left).Value /
+								((ULongConstant) right).Value);
+						else
+							res = unchecked (((ULongConstant) left).Value /
+								((ULongConstant) right).Value);
+
+						return new ULongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is LongConstant){
+						long res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((LongConstant) left).Value /
+								((LongConstant) right).Value);
+						else
+							res = unchecked (((LongConstant) left).Value /
+								((LongConstant) right).Value);
+
+						return new LongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is UIntConstant){
+						uint res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((UIntConstant) left).Value /
+								((UIntConstant) right).Value);
+						else
+							res = unchecked (((UIntConstant) left).Value /
+								((UIntConstant) right).Value);
+
+						return new UIntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is IntConstant){
+						int res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((IntConstant) left).Value /
+								((IntConstant) right).Value);
+						else
+							res = unchecked (((IntConstant) left).Value /
+								((IntConstant) right).Value);
+
+						return new IntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is DecimalConstant) {
+						decimal res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((DecimalConstant) left).Value /
+								((DecimalConstant) right).Value);
+						else
+							res = unchecked (((DecimalConstant) left).Value /
+								((DecimalConstant) right).Value);
+
+						return new DecimalConstant (ec.BuiltinTypes, res, left.Location);
+					} else {
+						throw new Exception ( "Unexepected division input: " + left);
+					}
+				} catch (OverflowException){
+					Error_CompileTimeOverflow (ec, loc);
+
+				} catch (DivideByZeroException) {
+					ec.Report.Error (20, loc, "Division by constant zero");
+				}
+				
+				break;
+				
+			case Binary.Operator.Modulus:
+				if (left is NullLiteral && right is NullLiteral) {
+					var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+					lifted_int.ResolveAsType (ec);
+					return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				try {
+					if (left is DoubleConstant){
+						double res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((DoubleConstant) left).Value %
+								       ((DoubleConstant) right).Value);
+						else
+							res = unchecked (((DoubleConstant) left).Value %
+									 ((DoubleConstant) right).Value);
+
+						return new DoubleConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is FloatConstant){
+						double a, b, res;
+						a = ((FloatConstant) left).DoubleValue;
+						b = ((FloatConstant) right).DoubleValue;
+						
+						if (ec.ConstantCheckState)
+							res = checked (a % b);
+						else
+							res = unchecked (a % b);
+
+						return new FloatConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is ULongConstant){
+						ulong res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((ULongConstant) left).Value %
+								       ((ULongConstant) right).Value);
+						else
+							res = unchecked (((ULongConstant) left).Value %
+									 ((ULongConstant) right).Value);
+
+						return new ULongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is LongConstant){
+						long res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((LongConstant) left).Value %
+								       ((LongConstant) right).Value);
+						else
+							res = unchecked (((LongConstant) left).Value %
+									 ((LongConstant) right).Value);
+
+						return new LongConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is UIntConstant){
+						uint res;
+						
+						if (ec.ConstantCheckState)
+							res = checked (((UIntConstant) left).Value %
+								       ((UIntConstant) right).Value);
+						else
+							res = unchecked (((UIntConstant) left).Value %
+									 ((UIntConstant) right).Value);
+
+						return new UIntConstant (ec.BuiltinTypes, res, left.Location);
+					} else if (left is IntConstant){
+						int res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((IntConstant) left).Value %
+								       ((IntConstant) right).Value);
+						else
+							res = unchecked (((IntConstant) left).Value %
+									 ((IntConstant) right).Value);
+
+						return new IntConstant (ec.BuiltinTypes, res, left.Location);
+					}
+
+					if (left is DecimalConstant) {
+						decimal res;
+
+						if (ec.ConstantCheckState)
+							res = checked (((DecimalConstant) left).Value %
+								((DecimalConstant) right).Value);
+						else
+							res = unchecked (((DecimalConstant) left).Value %
+								((DecimalConstant) right).Value);
+
+						return new DecimalConstant (ec.BuiltinTypes, res, left.Location);
+					}
+
+					throw new Exception ( "Unexepected modulus input: " + left);
+				} catch (DivideByZeroException){
+					ec.Report.Error (20, loc, "Division by constant zero");
+				} catch (OverflowException){
+					Error_CompileTimeOverflow (ec, loc);
+				}
+				break;
+
+				//
+				// There is no overflow checking on left shift
+				//
+			case Binary.Operator.LeftShift:
+				if (left is NullLiteral && right is NullLiteral) {
+					var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+					lifted_int.ResolveAsType (ec);
+					return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+				}
+
+				IntConstant ic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant;
+				if (ic == null){
+					return null;
+				}
+
+				int lshift_val = ic.Value;
+				switch (left.Type.BuiltinType) {
+				case BuiltinTypeSpec.Type.ULong:
+					return new ULongConstant (ec.BuiltinTypes, ((ULongConstant) left).Value << lshift_val, left.Location);
+				case BuiltinTypeSpec.Type.Long:
+					return new LongConstant (ec.BuiltinTypes, ((LongConstant) left).Value << lshift_val, left.Location);
+				case BuiltinTypeSpec.Type.UInt:
+					return new UIntConstant (ec.BuiltinTypes, ((UIntConstant) left).Value << lshift_val, left.Location);
+				}
+
+				// null << value => null
+				if (left is NullLiteral)
+					return (Constant) new Binary (oper, left, right).ResolveOperator (ec);
+
+				left = left.ConvertImplicitly (ec.BuiltinTypes.Int);
+				if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
+					return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value << lshift_val, left.Location);
+
+				return null;
+
+				//
+				// There is no overflow checking on right shift
+				//
+			case Binary.Operator.RightShift:
+				if (left is NullLiteral && right is NullLiteral) {
+					var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+					lifted_int.ResolveAsType (ec);
+					return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+				}
+
+				IntConstant sic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant;
+				if (sic == null){
+					return null;
+				}
+				int rshift_val = sic.Value;
+				switch (left.Type.BuiltinType) {
+				case BuiltinTypeSpec.Type.ULong:
+					return new ULongConstant (ec.BuiltinTypes, ((ULongConstant) left).Value >> rshift_val, left.Location);
+				case BuiltinTypeSpec.Type.Long:
+					return new LongConstant (ec.BuiltinTypes, ((LongConstant) left).Value >> rshift_val, left.Location);
+				case BuiltinTypeSpec.Type.UInt:
+					return new UIntConstant (ec.BuiltinTypes, ((UIntConstant) left).Value >> rshift_val, left.Location);
+				}
+
+				// null >> value => null
+				if (left is NullLiteral)
+					return (Constant) new Binary (oper, left, right).ResolveOperator (ec);
+
+				left = left.ConvertImplicitly (ec.BuiltinTypes.Int);
+				if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
+					return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value >> rshift_val, left.Location);
+
+				return null;
+
+			case Binary.Operator.Equality:
+				if (TypeSpec.IsReferenceType (lt) && TypeSpec.IsReferenceType (rt) ||
+					(left is Nullable.LiftedNull && right.IsNull) ||
+					(right is Nullable.LiftedNull && left.IsNull)) {
+					if (left.IsNull || right.IsNull) {
+						return ReducedExpression.Create (
+							new BoolConstant (ec.BuiltinTypes, left.IsNull == right.IsNull, left.Location),
+							new Binary (oper, left, right));
+					}
+
+					if (left is StringConstant && right is StringConstant)
+						return new BoolConstant (ec.BuiltinTypes,
+							((StringConstant) left).Value == ((StringConstant) right).Value, left.Location);
+
+					return null;
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				bool_res = false;
+				if (left is DoubleConstant)
+					bool_res = ((DoubleConstant) left).Value ==
+						((DoubleConstant) right).Value;
+				else if (left is FloatConstant)
+					bool_res = ((FloatConstant) left).DoubleValue ==
+						((FloatConstant) right).DoubleValue;
+				else if (left is ULongConstant)
+					bool_res = ((ULongConstant) left).Value ==
+						((ULongConstant) right).Value;
+				else if (left is LongConstant)
+					bool_res = ((LongConstant) left).Value ==
+						((LongConstant) right).Value;
+				else if (left is UIntConstant)
+					bool_res = ((UIntConstant) left).Value ==
+						((UIntConstant) right).Value;
+				else if (left is IntConstant)
+					bool_res = ((IntConstant) left).Value ==
+						((IntConstant) right).Value;
+				else
+					return null;
+
+				return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
+
+			case Binary.Operator.Inequality:
+				if (TypeSpec.IsReferenceType (lt) && TypeSpec.IsReferenceType (rt) ||
+					(left is Nullable.LiftedNull && right.IsNull) ||
+					(right is Nullable.LiftedNull && left.IsNull)) {
+					if (left.IsNull || right.IsNull) {
+						return ReducedExpression.Create (
+							new BoolConstant (ec.BuiltinTypes, left.IsNull != right.IsNull, left.Location),
+							new Binary (oper, left, right));
+					}
+
+					if (left is StringConstant && right is StringConstant)
+						return new BoolConstant (ec.BuiltinTypes,
+							((StringConstant) left).Value != ((StringConstant) right).Value, left.Location);
+
+					return null;
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				bool_res = false;
+				if (left is DoubleConstant)
+					bool_res = ((DoubleConstant) left).Value !=
+						((DoubleConstant) right).Value;
+				else if (left is FloatConstant)
+					bool_res = ((FloatConstant) left).DoubleValue !=
+						((FloatConstant) right).DoubleValue;
+				else if (left is ULongConstant)
+					bool_res = ((ULongConstant) left).Value !=
+						((ULongConstant) right).Value;
+				else if (left is LongConstant)
+					bool_res = ((LongConstant) left).Value !=
+						((LongConstant) right).Value;
+				else if (left is UIntConstant)
+					bool_res = ((UIntConstant) left).Value !=
+						((UIntConstant) right).Value;
+				else if (left is IntConstant)
+					bool_res = ((IntConstant) left).Value !=
+						((IntConstant) right).Value;
+				else
+					return null;
+
+				return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
+
+			case Binary.Operator.LessThan:
+				if (right is NullLiteral) {
+					if (left is NullLiteral) {
+						var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+						lifted_int.ResolveAsType (ec);
+						return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+					}
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				bool_res = false;
+				if (left is DoubleConstant)
+					bool_res = ((DoubleConstant) left).Value <
+						((DoubleConstant) right).Value;
+				else if (left is FloatConstant)
+					bool_res = ((FloatConstant) left).DoubleValue <
+						((FloatConstant) right).DoubleValue;
+				else if (left is ULongConstant)
+					bool_res = ((ULongConstant) left).Value <
+						((ULongConstant) right).Value;
+				else if (left is LongConstant)
+					bool_res = ((LongConstant) left).Value <
+						((LongConstant) right).Value;
+				else if (left is UIntConstant)
+					bool_res = ((UIntConstant) left).Value <
+						((UIntConstant) right).Value;
+				else if (left is IntConstant)
+					bool_res = ((IntConstant) left).Value <
+						((IntConstant) right).Value;
+				else
+					return null;
+
+				return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
+				
+			case Binary.Operator.GreaterThan:
+				if (right is NullLiteral) {
+					if (left is NullLiteral) {
+						var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+						lifted_int.ResolveAsType (ec);
+						return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+					}
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				bool_res = false;
+				if (left is DoubleConstant)
+					bool_res = ((DoubleConstant) left).Value >
+						((DoubleConstant) right).Value;
+				else if (left is FloatConstant)
+					bool_res = ((FloatConstant) left).DoubleValue >
+						((FloatConstant) right).DoubleValue;
+				else if (left is ULongConstant)
+					bool_res = ((ULongConstant) left).Value >
+						((ULongConstant) right).Value;
+				else if (left is LongConstant)
+					bool_res = ((LongConstant) left).Value >
+						((LongConstant) right).Value;
+				else if (left is UIntConstant)
+					bool_res = ((UIntConstant) left).Value >
+						((UIntConstant) right).Value;
+				else if (left is IntConstant)
+					bool_res = ((IntConstant) left).Value >
+						((IntConstant) right).Value;
+				else
+					return null;
+
+				return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
+
+			case Binary.Operator.GreaterThanOrEqual:
+				if (right is NullLiteral) {
+					if (left is NullLiteral) {
+						var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+						lifted_int.ResolveAsType (ec);
+						return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+					}
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				bool_res = false;
+				if (left is DoubleConstant)
+					bool_res = ((DoubleConstant) left).Value >=
+						((DoubleConstant) right).Value;
+				else if (left is FloatConstant)
+					bool_res = ((FloatConstant) left).DoubleValue >=
+						((FloatConstant) right).DoubleValue;
+				else if (left is ULongConstant)
+					bool_res = ((ULongConstant) left).Value >=
+						((ULongConstant) right).Value;
+				else if (left is LongConstant)
+					bool_res = ((LongConstant) left).Value >=
+						((LongConstant) right).Value;
+				else if (left is UIntConstant)
+					bool_res = ((UIntConstant) left).Value >=
+						((UIntConstant) right).Value;
+				else if (left is IntConstant)
+					bool_res = ((IntConstant) left).Value >=
+						((IntConstant) right).Value;
+				else
+					return null;
+
+				return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
+
+			case Binary.Operator.LessThanOrEqual:
+				if (right is NullLiteral) {
+					if (left is NullLiteral) {
+						var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc);
+						lifted_int.ResolveAsType (ec);
+						return (Constant) new Binary (oper, lifted_int, right).ResolveOperator (ec);
+					}
+				}
+
+				if (!DoBinaryNumericPromotions (ec, ref left, ref right))
+					return null;
+
+				bool_res = false;
+				if (left is DoubleConstant)
+					bool_res = ((DoubleConstant) left).Value <=
+						((DoubleConstant) right).Value;
+				else if (left is FloatConstant)
+					bool_res = ((FloatConstant) left).DoubleValue <=
+						((FloatConstant) right).DoubleValue;
+				else if (left is ULongConstant)
+					bool_res = ((ULongConstant) left).Value <=
+						((ULongConstant) right).Value;
+				else if (left is LongConstant)
+					bool_res = ((LongConstant) left).Value <=
+						((LongConstant) right).Value;
+				else if (left is UIntConstant)
+					bool_res = ((UIntConstant) left).Value <=
+						((UIntConstant) right).Value;
+				else if (left is IntConstant)
+					bool_res = ((IntConstant) left).Value <=
+						((IntConstant) right).Value;
+				else
+					return null;
+
+				return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location);
+			}
+
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/class.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/class.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/class.cs	(revision 11807)
@@ -0,0 +1,3895 @@
+//
+// class.cs: Class and Struct handlers
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Martin Baulig (martin@ximian.com)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2011 Novell, Inc
+// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
+//
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Text;
+using System.Diagnostics;
+using Mono.CompilerServices.SymbolWriter;
+
+#if NET_2_1
+using XmlElement = System.Object;
+#endif
+
+#if STATIC
+using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	//
+	// General types container, used as a base class for all constructs which can hold types
+	//
+	public abstract class TypeContainer : MemberCore
+	{
+		public readonly MemberKind Kind;
+		public readonly string Basename;
+
+		protected List<TypeContainer> containers;
+
+		TypeDefinition main_container;
+
+		protected Dictionary<string, MemberCore> defined_names;
+
+		protected bool is_defined;
+
+		public int CounterAnonymousMethods { get; set; }
+		public int CounterAnonymousContainers { get; set; }
+		public int CounterSwitchTypes { get; set; }
+
+		protected TypeContainer (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
+			: base (parent, name, attrs)
+		{
+			this.Kind = kind;
+			if (name != null)
+				this.Basename = name.Basename;
+
+			defined_names = new Dictionary<string, MemberCore> ();
+		}
+
+		public override TypeSpec CurrentType {
+			get {
+				return null;
+			}
+		}
+
+		public Dictionary<string, MemberCore> DefinedNames {
+			get {
+				return defined_names;
+			}
+		}
+
+		public TypeDefinition PartialContainer {
+			get {
+				return main_container;
+			}
+			protected set {
+				main_container = value;
+			}
+		}
+
+		public IList<TypeContainer> Containers {
+			get {
+				return containers;
+			}
+		}
+
+		//
+		// Any unattached attributes during parsing get added here. User
+		// by FULL_AST mode
+		//
+		public Attributes UnattachedAttributes {
+			get; set;
+		}
+
+		public void AddCompilerGeneratedClass (CompilerGeneratedContainer c)
+		{
+			AddTypeContainerMember (c);
+		}
+
+		public virtual void AddPartial (TypeDefinition next_part)
+		{
+			MemberCore mc;
+			(PartialContainer ?? this).defined_names.TryGetValue (next_part.Basename, out mc);
+
+			AddPartial (next_part, mc as TypeDefinition);
+		}
+
+		protected void AddPartial (TypeDefinition next_part, TypeDefinition existing)
+		{
+			next_part.ModFlags |= Modifiers.PARTIAL;
+
+			if (existing == null) {
+				AddTypeContainer (next_part);
+				return;
+			}
+
+			if ((existing.ModFlags & Modifiers.PARTIAL) == 0) {
+				if (existing.Kind != next_part.Kind) {
+					AddTypeContainer (next_part);
+				} else {
+					Report.SymbolRelatedToPreviousError (next_part);
+					Error_MissingPartialModifier (existing);
+				}
+
+				return;
+			}
+
+			if (existing.Kind != next_part.Kind) {
+				Report.SymbolRelatedToPreviousError (existing);
+				Report.Error (261, next_part.Location,
+					"Partial declarations of `{0}' must be all classes, all structs or all interfaces",
+					next_part.GetSignatureForError ());
+			}
+
+			if ((existing.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
+				((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) == 0 &&
+				 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) == 0)) {
+					 Report.SymbolRelatedToPreviousError (existing);
+				Report.Error (262, next_part.Location,
+					"Partial declarations of `{0}' have conflicting accessibility modifiers",
+					next_part.GetSignatureForError ());
+			}
+
+			var tc_names = existing.CurrentTypeParameters;
+			if (tc_names != null) {
+				for (int i = 0; i < tc_names.Count; ++i) {
+					var tp = next_part.MemberName.TypeParameters[i];
+					if (tc_names[i].MemberName.Name != tp.MemberName.Name) {
+						Report.SymbolRelatedToPreviousError (existing.Location, "");
+						Report.Error (264, next_part.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
+							next_part.GetSignatureForError ());
+						break;
+					}
+
+					if (tc_names[i].Variance != tp.Variance) {
+						Report.SymbolRelatedToPreviousError (existing.Location, "");
+						Report.Error (1067, next_part.Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
+							next_part.GetSignatureForError ());
+						break;
+					}
+				}
+			}
+
+			if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0) {
+				existing.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFIER | Modifiers.AccessibilityMask);
+			} else if ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0) {
+				existing.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFIER | Modifiers.AccessibilityMask);
+				existing.ModFlags |= next_part.ModFlags;
+			} else {
+				existing.ModFlags |= next_part.ModFlags;
+			}
+
+			existing.Definition.Modifiers = existing.ModFlags;
+
+			if (next_part.attributes != null) {
+				if (existing.attributes == null)
+					existing.attributes = next_part.attributes;
+				else
+					existing.attributes.AddAttributes (next_part.attributes.Attrs);
+			}
+
+			next_part.PartialContainer = existing;
+
+			existing.AddPartialPart (next_part);
+
+			AddTypeContainerMember (next_part);
+		}
+
+		public virtual void AddTypeContainer (TypeContainer tc)
+		{
+			AddTypeContainerMember (tc);
+
+			var tparams = tc.MemberName.TypeParameters;
+			if (tparams != null && tc.PartialContainer != null) {
+				var td = (TypeDefinition) tc;
+				for (int i = 0; i < tparams.Count; ++i) {
+					var tp = tparams[i];
+					if (tp.MemberName == null)
+						continue;
+
+					td.AddNameToContainer (tp, tp.Name);
+				}
+			}
+		}
+
+		protected virtual void AddTypeContainerMember (TypeContainer tc)
+		{
+			containers.Add (tc);
+		}
+
+		public virtual void CloseContainer ()
+		{
+			if (containers != null) {
+				foreach (TypeContainer tc in containers) {
+					tc.CloseContainer ();
+				}
+			}
+		}
+
+		public virtual void CreateMetadataName (StringBuilder sb)
+		{
+			if (Parent != null && Parent.MemberName != null)
+				Parent.CreateMetadataName (sb);
+
+			MemberName.CreateMetadataName (sb);
+		}
+
+		public virtual bool CreateContainer ()
+		{
+			if (containers != null) {
+				foreach (TypeContainer tc in containers) {
+					tc.CreateContainer ();
+				}
+			}
+
+			return true;
+		}
+
+		public override bool Define ()
+		{
+			if (containers != null) {
+				foreach (TypeContainer tc in containers) {
+					tc.Define ();
+				}
+			}
+
+			// Release cache used by parser only
+			if (Module.Evaluator == null) {
+				defined_names = null;
+			} else {
+				defined_names.Clear ();
+			}
+
+			return true;
+		}
+
+		public virtual void PrepareEmit ()
+		{
+			if (containers != null) {
+				foreach (var t in containers) {
+					try {
+						t.PrepareEmit ();
+					} catch (Exception e) {
+						if (MemberName == MemberName.Null)
+							throw;
+
+						throw new InternalErrorException (t, e);
+					}
+				}
+			}
+		}
+
+		public virtual bool DefineContainer ()
+		{
+			if (is_defined)
+				return true;
+
+			is_defined = true;
+
+			DoDefineContainer ();
+
+			if (containers != null) {
+				foreach (TypeContainer tc in containers) {
+					try {
+						tc.DefineContainer ();
+					} catch (Exception e) {
+						if (MemberName == MemberName.Null)
+							throw;
+
+						throw new InternalErrorException (tc, e);
+					}
+				}
+			}
+
+			return true;
+		}
+
+		public virtual void ExpandBaseInterfaces ()
+		{
+			if (containers != null) {
+				foreach (TypeContainer tc in containers) {
+					tc.ExpandBaseInterfaces ();
+				}
+			}
+		}
+
+		protected virtual void DefineNamespace ()
+		{
+			if (containers != null) {
+				foreach (var tc in containers) {
+					try {
+						tc.DefineNamespace ();
+					} catch (Exception e) {
+						throw new InternalErrorException (tc, e);
+					}
+				}
+			}
+		}
+
+		protected virtual void DoDefineContainer ()
+		{
+		}
+
+		public virtual void EmitContainer ()
+		{
+			if (containers != null) {
+				for (int i = 0; i < containers.Count; ++i)
+					containers[i].EmitContainer ();
+			}
+		}
+
+		protected void Error_MissingPartialModifier (MemberCore type)
+		{
+			Report.Error (260, type.Location,
+				"Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
+				type.GetSignatureForError ());
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			if (Parent != null && Parent.MemberName != null)
+				return Parent.GetSignatureForDocumentation () + "." + MemberName.GetSignatureForDocumentation ();
+
+			return MemberName.GetSignatureForDocumentation ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			if (Parent != null && Parent.MemberName != null) 
+				return Parent.GetSignatureForError () + "." + MemberName.GetSignatureForError ();
+
+			return MemberName.GetSignatureForError ();
+		}
+
+		public string GetSignatureForMetadata ()
+		{
+			if (Parent is TypeDefinition) {
+				return Parent.GetSignatureForMetadata () + "+" + TypeNameParser.Escape (MemberName.Basename);
+			}
+
+			var sb = new StringBuilder ();
+			CreateMetadataName (sb);
+			return sb.ToString ();
+		}
+
+		public virtual void RemoveContainer (TypeContainer cont)
+		{
+			if (containers != null)
+				containers.Remove (cont);
+
+			var tc = Parent == Module ? Module : this;
+			tc.defined_names.Remove (cont.Basename);
+		}
+
+		public virtual void VerifyMembers ()
+		{
+			if (containers != null) {
+				foreach (TypeContainer tc in containers)
+					tc.VerifyMembers ();
+			}
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (containers != null) {
+				foreach (TypeContainer tc in containers) {
+					tc.WriteDebugSymbol (file);
+				}
+			}
+		}
+	}
+
+	public abstract class TypeDefinition : TypeContainer, ITypeDefinition
+	{
+		//
+		// Different context is needed when resolving type container base
+		// types. Type names come from the parent scope but type parameter
+		// names from the container scope.
+		//
+		public struct BaseContext : IMemberContext
+		{
+			TypeContainer tc;
+
+			public BaseContext (TypeContainer tc)
+			{
+				this.tc = tc;
+			}
+
+			#region IMemberContext Members
+
+			public CompilerContext Compiler {
+				get { return tc.Compiler; }
+			}
+
+			public TypeSpec CurrentType {
+				get { return tc.PartialContainer.CurrentType; }
+			}
+
+			public TypeParameters CurrentTypeParameters {
+				get { return tc.PartialContainer.CurrentTypeParameters; }
+			}
+
+			public MemberCore CurrentMemberDefinition {
+				get { return tc; }
+			}
+
+			public bool IsObsolete {
+				get { return tc.IsObsolete; }
+			}
+
+			public bool IsUnsafe {
+				get { return tc.IsUnsafe; }
+			}
+
+			public bool IsStatic {
+				get { return tc.IsStatic; }
+			}
+
+			public ModuleContainer Module {
+				get { return tc.Module; }
+			}
+
+			public string GetSignatureForError ()
+			{
+				return tc.GetSignatureForError ();
+			}
+
+			public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
+			{
+				return null;
+			}
+
+			public FullNamedExpression LookupNamespaceAlias (string name)
+			{
+				return tc.Parent.LookupNamespaceAlias (name);
+			}
+
+			public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+			{
+				if (arity == 0) {
+					var tp = CurrentTypeParameters;
+					if (tp != null) {
+						TypeParameter t = tp.Find (name);
+						if (t != null)
+							return new TypeParameterExpr (t, loc);
+					}
+				}
+
+				return tc.Parent.LookupNamespaceOrType (name, arity, mode, loc);
+			}
+
+			#endregion
+		}
+
+		[Flags]
+		enum CachedMethods
+		{
+			Equals				= 1,
+			GetHashCode			= 1 << 1,
+			HasStaticFieldInitializer	= 1 << 2
+		}
+
+		readonly List<MemberCore> members;
+
+		// Holds a list of fields that have initializers
+		protected List<FieldInitializer> initialized_fields;
+
+		// Holds a list of static fields that have initializers
+		protected List<FieldInitializer> initialized_static_fields;
+
+		Dictionary<MethodSpec, Method> hoisted_base_call_proxies;
+
+		Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();
+
+		//
+		// Points to the first non-static field added to the container.
+		//
+		// This is an arbitrary choice.  We are interested in looking at _some_ non-static field,
+		// and the first one's as good as any.
+		//
+		protected FieldBase first_nonstatic_field;
+
+		//
+		// This one is computed after we can distinguish interfaces
+		// from classes from the arraylist `type_bases' 
+		//
+		protected TypeSpec base_type;
+		FullNamedExpression base_type_expr;	// TODO: It's temporary variable
+		protected TypeSpec[] iface_exprs;
+
+		protected List<FullNamedExpression> type_bases;
+
+		// Partial parts for classes only
+		List<TypeDefinition> class_partial_parts;
+
+		TypeDefinition InTransit;
+
+		public TypeBuilder TypeBuilder;
+		GenericTypeParameterBuilder[] all_tp_builders;
+		//
+		// All recursive type parameters put together sharing same
+		// TypeParameter instances
+		//
+		TypeParameters all_type_parameters;
+
+		public const string DefaultIndexerName = "Item";
+
+		bool has_normal_indexers;
+		string indexer_name;
+		protected bool requires_delayed_unmanagedtype_check;
+		bool error;
+		bool members_defined;
+		bool members_defined_ok;
+		protected bool has_static_constructor;
+
+		private CachedMethods cached_method;
+
+		protected TypeSpec spec;
+		TypeSpec current_type;
+
+		public int DynamicSitesCounter;
+		public int AnonymousMethodsCounter;
+		public int MethodGroupsCounter;
+
+		static readonly string[] attribute_targets = new [] { "type" };
+		static readonly string[] attribute_targets_primary = new [] { "type", "method" };
+
+		/// <remarks>
+		///  The pending methods that need to be implemented
+		//   (interfaces or abstract methods)
+		/// </remarks>
+		PendingImplementation pending;
+
+		protected TypeDefinition (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
+			: base (parent, name, attrs, kind)
+		{
+			PartialContainer = this;
+			members = new List<MemberCore> ();
+		}
+
+		#region Properties
+
+		public List<FullNamedExpression> BaseTypeExpressions {
+			get {
+				return type_bases;
+			}
+		}
+
+		public override TypeSpec CurrentType {
+			get {
+				if (current_type == null) {
+					if (IsGenericOrParentIsGeneric) {
+						//
+						// Switch to inflated version as it's used by all expressions
+						//
+						var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Types;
+						current_type = spec.MakeGenericType (this, targs);
+					} else {
+						current_type = spec;
+					}
+				}
+
+				return current_type;
+			}
+		}
+
+		public override TypeParameters CurrentTypeParameters {
+			get {
+				return PartialContainer.MemberName.TypeParameters;
+			}
+		}
+
+		int CurrentTypeParametersStartIndex {
+			get {
+				int total = all_tp_builders.Length;
+				if (CurrentTypeParameters != null) {
+					return total - CurrentTypeParameters.Count;
+				}
+				return total;
+			}
+		}
+
+		public virtual AssemblyDefinition DeclaringAssembly {
+			get {
+				return Module.DeclaringAssembly;
+			}
+		}
+
+		IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
+			get {
+				return Module.DeclaringAssembly;
+			}
+		}
+
+		public TypeSpec Definition {
+			get {
+				return spec;
+			}
+		}
+
+		public bool HasMembersDefined {
+			get {
+				return members_defined;
+			}
+		}
+		
+		public List<FullNamedExpression> TypeBaseExpressions {
+			get {
+				return type_bases;
+			}
+		}
+
+		public bool HasInstanceConstructor {
+			get {
+				return (caching_flags & Flags.HasInstanceConstructor) != 0;
+			}
+			set {
+				caching_flags |= Flags.HasInstanceConstructor;
+			}
+		}
+
+		// Indicated whether container has StructLayout attribute set Explicit
+		public bool HasExplicitLayout {
+			get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
+			set { caching_flags |= Flags.HasExplicitLayout; }
+		}
+
+		public bool HasOperators {
+			get {
+				return (caching_flags & Flags.HasUserOperators) != 0;
+			}
+			set {
+				caching_flags |= Flags.HasUserOperators;
+			}
+		}
+
+		public bool HasStructLayout {
+			get { return (caching_flags & Flags.HasStructLayout) != 0; }
+			set { caching_flags |= Flags.HasStructLayout; }
+		}
+
+		public TypeSpec[] Interfaces {
+			get {
+				return iface_exprs;
+			}
+		}
+
+		public bool IsGenericOrParentIsGeneric {
+			get {
+				return all_type_parameters != null;
+			}
+		}
+
+		public bool IsTopLevel {
+			get {
+				return !(Parent is TypeDefinition);
+			}
+		}
+
+		public bool IsPartial {
+			get {
+				return (ModFlags & Modifiers.PARTIAL) != 0;
+			}
+		}
+
+		bool ITypeDefinition.IsTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsCyclicTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		//
+		// Returns true for secondary partial containers
+		//
+		bool IsPartialPart {
+			get {
+				return PartialContainer != this;
+			}
+		}
+
+		public MemberCache MemberCache {
+			get {
+				return spec.MemberCache;
+			}
+		}
+
+		public List<MemberCore> Members {
+			get {
+				return members;
+			}
+		}
+
+		string ITypeDefinition.Namespace {
+			get {
+				var p = Parent;
+				while (p.Kind != MemberKind.Namespace)
+					p = p.Parent;
+
+				return p.MemberName == null ? null : p.GetSignatureForError ();
+			}
+		}
+
+		public ParametersCompiled PrimaryConstructorParameters { get; set; }
+
+		public Arguments PrimaryConstructorBaseArguments { get; set; }
+
+		public Location PrimaryConstructorBaseArgumentsStart { get; set; }
+
+		public TypeParameters TypeParametersAll {
+			get {
+				return all_type_parameters;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return PrimaryConstructorParameters != null ? attribute_targets_primary : attribute_targets;
+			}
+		}
+
+#if FULL_AST
+		public bool HasOptionalSemicolon {
+			get;
+			private set;
+		}
+		Location optionalSemicolon;
+		public Location OptionalSemicolon {
+			get {
+				return optionalSemicolon;
+			}
+			set {
+				optionalSemicolon = value;
+				HasOptionalSemicolon = true;
+			}
+		}
+#endif
+
+		#endregion
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public void AddMember (MemberCore symbol)
+		{
+			if (symbol.MemberName.ExplicitInterface != null) {
+				if (!(Kind == MemberKind.Class || Kind == MemberKind.Struct)) {
+					Report.Error (541, symbol.Location,
+						"`{0}': explicit interface declaration can only be declared in a class or struct",
+						symbol.GetSignatureForError ());
+				}
+			}
+
+			AddNameToContainer (symbol, symbol.MemberName.Name);
+			members.Add (symbol);
+		}
+
+		public override void AddTypeContainer (TypeContainer tc)
+		{
+			AddNameToContainer (tc, tc.Basename);
+
+			base.AddTypeContainer (tc);
+		}
+
+		protected override void AddTypeContainerMember (TypeContainer tc)
+		{
+			members.Add (tc);
+
+			if (containers == null)
+				containers = new List<TypeContainer> ();
+
+			base.AddTypeContainerMember (tc);
+		}
+
+		//
+		// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
+		//
+		public virtual void AddNameToContainer (MemberCore symbol, string name)
+		{
+			if (((ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0)
+				return;
+
+			MemberCore mc;
+			if (!PartialContainer.defined_names.TryGetValue (name, out mc)) {
+				PartialContainer.defined_names.Add (name, symbol);
+				return;
+			}
+
+			if (symbol.EnableOverloadChecks (mc))
+				return;
+
+			InterfaceMemberBase im = mc as InterfaceMemberBase;
+			if (im != null && im.IsExplicitImpl)
+				return;
+
+			Report.SymbolRelatedToPreviousError (mc);
+			if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
+				Error_MissingPartialModifier (symbol);
+				return;
+			}
+
+			if (symbol is TypeParameter) {
+				Report.Error (692, symbol.Location,
+					"Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
+			} else {
+				Report.Error (102, symbol.Location,
+					"The type `{0}' already contains a definition for `{1}'",
+					GetSignatureForError (), name);
+			}
+
+			return;
+		}
+
+		public void AddConstructor (Constructor c)
+		{
+			AddConstructor (c, false);
+		}
+
+		public void AddConstructor (Constructor c, bool isDefault)
+		{
+			bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
+			if (!isDefault)
+				AddNameToContainer (c, is_static ? Constructor.TypeConstructorName : Constructor.ConstructorName);
+
+			if (is_static && c.ParameterInfo.IsEmpty) {
+				PartialContainer.has_static_constructor = true;
+			} else {
+				PartialContainer.HasInstanceConstructor = true;
+			}
+
+			members.Add (c);
+		}
+
+		public bool AddField (FieldBase field)
+		{
+			AddMember (field);
+
+			if ((field.ModFlags & Modifiers.STATIC) != 0)
+				return true;
+
+			var first_field = PartialContainer.first_nonstatic_field;
+			if (first_field == null) {
+				PartialContainer.first_nonstatic_field = field;
+				return true;
+			}
+
+			if (Kind == MemberKind.Struct && first_field.Parent != field.Parent) {
+				Report.SymbolRelatedToPreviousError (first_field.Parent);
+				Report.Warning (282, 3, field.Location,
+					"struct instance field `{0}' found in different declaration from instance field `{1}'",
+					field.GetSignatureForError (), first_field.GetSignatureForError ());
+			}
+			return true;
+		}
+
+		/// <summary>
+		/// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
+		/// </summary>
+		public void AddIndexer (Indexer i)
+		{
+			members.Add (i);
+		}
+
+		public void AddOperator (Operator op)
+		{
+			PartialContainer.HasOperators = true;
+			AddMember (op);
+		}
+
+		public void AddPartialPart (TypeDefinition part)
+		{
+			if (Kind != MemberKind.Class)
+				return;
+
+			if (class_partial_parts == null)
+				class_partial_parts = new List<TypeDefinition> ();
+
+			class_partial_parts.Add (part);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Target == AttributeTargets.Method) {
+				foreach (var m in members) {
+					var c = m as Constructor;
+					if (c == null)
+						continue;
+
+					if (c.IsPrimaryConstructor) {
+						c.ApplyAttributeBuilder (a, ctor, cdata, pa);
+						return;
+					}
+				}
+
+				throw new InternalErrorException ();
+			}
+
+			if (has_normal_indexers && a.Type == pa.DefaultMember) {
+				Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
+				return;
+			}
+
+			if (a.Type == pa.Required) {
+				Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
+				return;
+			}
+
+			TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		} 
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		public TypeSpec BaseType {
+			get {
+				return spec.BaseType;
+			}
+		}
+
+		protected virtual TypeAttributes TypeAttr {
+			get {
+				return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel);
+			}
+		}
+
+		public int TypeParametersCount {
+			get {
+				return MemberName.Arity;
+			}
+		}
+
+		TypeParameterSpec[] ITypeDefinition.TypeParameters {
+			get {
+				return PartialContainer.CurrentTypeParameters.Types;
+			}
+		}
+
+		public string GetAttributeDefaultMember ()
+		{
+			return indexer_name ?? DefaultIndexerName;
+		}
+
+		public bool IsComImport {
+			get {
+				if (OptAttributes == null)
+					return false;
+
+				return OptAttributes.Contains (Module.PredefinedAttributes.ComImport);
+			}
+		}
+
+		public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
+		{
+			if (IsPartialPart)
+				PartialContainer.RegisterFieldForInitialization (field, expression);
+
+			if ((field.ModFlags & Modifiers.STATIC) != 0){
+				if (initialized_static_fields == null) {
+					HasStaticFieldInitializer = true;
+					initialized_static_fields = new List<FieldInitializer> (4);
+				}
+
+				initialized_static_fields.Add (expression);
+			} else {
+				if (initialized_fields == null)
+					initialized_fields = new List<FieldInitializer> (4);
+
+				initialized_fields.Add (expression);
+			}
+		}
+
+		public void ResolveFieldInitializers (BlockContext ec)
+		{
+			Debug.Assert (!IsPartialPart);
+
+			if (ec.IsStatic) {
+				if (initialized_static_fields == null)
+					return;
+
+				bool has_complex_initializer = !ec.Module.Compiler.Settings.Optimize;
+				int i;
+				ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
+				for (i = 0; i < initialized_static_fields.Count; ++i) {
+					FieldInitializer fi = initialized_static_fields [i];
+					ExpressionStatement s = fi.ResolveStatement (ec);
+					if (s == null) {
+						s = EmptyExpressionStatement.Instance;
+					} else if (!fi.IsSideEffectFree) {
+						has_complex_initializer = true;
+					}
+
+					init [i] = s;
+				}
+
+				for (i = 0; i < initialized_static_fields.Count; ++i) {
+					FieldInitializer fi = initialized_static_fields [i];
+					//
+					// Need special check to not optimize code like this
+					// static int a = b = 5;
+					// static int b = 0;
+					//
+					if (!has_complex_initializer && fi.IsDefaultInitializer)
+						continue;
+
+					ec.AssignmentInfoOffset += fi.AssignmentOffset;
+					ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
+				}
+
+				return;
+			}
+
+			if (initialized_fields == null)
+				return;
+
+			for (int i = 0; i < initialized_fields.Count; ++i) {
+				FieldInitializer fi = initialized_fields [i];
+
+				//
+				// Clone before resolving otherwise when field initializer is needed
+				// in more than 1 constructor any resolve after the initial one would
+				// only took the resolved expression which is problem for expressions
+				// that generate extra expressions or code during Resolve phase
+				//
+				var cloned = fi.Clone (new CloneContext ());
+
+				ExpressionStatement s = fi.ResolveStatement (ec);
+				if (s == null) {
+					initialized_fields [i] = new FieldInitializer (fi.Field, ErrorExpression.Instance, Location.Null);
+					continue;
+				}
+
+				//
+				// Field is re-initialized to its default value => removed
+				//
+				if (fi.IsDefaultInitializer && ec.Module.Compiler.Settings.Optimize)
+					continue;
+
+				ec.AssignmentInfoOffset += fi.AssignmentOffset;
+				ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
+				initialized_fields [i] = (FieldInitializer) cloned;
+			}
+		}
+
+		public override string DocComment {
+			get {
+				return comment;
+			}
+			set {
+				if (value == null)
+					return;
+
+				comment += value;
+			}
+		}
+
+		public PendingImplementation PendingImplementations {
+			get { return pending; }
+		}
+
+		internal override void GenerateDocComment (DocumentationBuilder builder)
+		{
+			if (IsPartialPart)
+				return;
+
+			base.GenerateDocComment (builder);
+
+			foreach (var member in members)
+				member.GenerateDocComment (builder);
+		}
+
+		public TypeSpec GetAttributeCoClass ()
+		{
+			if (OptAttributes == null)
+				return null;
+
+			Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CoClass);
+			if (a == null)
+				return null;
+
+			return a.GetCoClassAttributeValue ();
+		}
+
+		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+		{
+			Attribute a = null;
+			if (OptAttributes != null) {
+				a = OptAttributes.Search (pa);
+			}
+
+			if (a == null)
+				return null;
+
+			return a.GetAttributeUsageAttribute ();
+		}
+
+		public virtual CompilationSourceFile GetCompilationSourceFile ()
+		{
+			TypeContainer ns = Parent;
+			while (true) {
+				var sf = ns as CompilationSourceFile;
+				if (sf != null)
+					return sf;
+
+				ns = ns.Parent;
+			}
+		}
+
+		public virtual void SetBaseTypes (List<FullNamedExpression> baseTypes)
+		{
+			type_bases = baseTypes;
+		}
+
+		/// <summary>
+		///   This function computes the Base class and also the
+		///   list of interfaces that the class or struct @c implements.
+		///   
+		///   The return value is an array (might be null) of
+		///   interfaces implemented (as Types).
+		///   
+		///   The @base_class argument is set to the base object or null
+		///   if this is `System.Object'. 
+		/// </summary>
+		protected virtual TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			base_class = null;
+			if (type_bases == null)
+				return null;
+
+			int count = type_bases.Count;
+			TypeSpec[] ifaces = null;
+			var base_context = new BaseContext (this);
+			for (int i = 0, j = 0; i < count; i++){
+				FullNamedExpression fne = type_bases [i];
+
+				var fne_resolved = fne.ResolveAsType (base_context);
+				if (fne_resolved == null)
+					continue;
+
+				if (i == 0 && Kind == MemberKind.Class && !fne_resolved.IsInterface) {
+					if (fne_resolved.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+						Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
+							GetSignatureForError ());
+
+						continue;
+					}
+					
+					base_type = fne_resolved;
+					base_class = fne;
+					continue;
+				}
+
+				if (ifaces == null)
+					ifaces = new TypeSpec [count - i];
+
+				if (fne_resolved.IsInterface) {
+					for (int ii = 0; ii < j; ++ii) {
+						if (fne_resolved == ifaces [ii]) {
+							Report.Error (528, Location, "`{0}' is already listed in interface list",
+								fne_resolved.GetSignatureForError ());
+							break;
+						}
+					}
+
+					if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved)) {
+						Report.Error (61, fne.Location,
+							"Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
+							fne_resolved.GetSignatureForError (), GetSignatureForError ());
+					}
+				} else {
+					Report.SymbolRelatedToPreviousError (fne_resolved);
+					if (Kind != MemberKind.Class) {
+						Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
+					} else if (base_class != null)
+						Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
+							GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
+					else {
+						Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
+							GetSignatureForError (), fne_resolved.GetSignatureForError ());
+					}
+				}
+
+				ifaces [j++] = fne_resolved;
+			}
+
+			return ifaces;
+		}
+
+		//
+		// Checks that some operators come in pairs:
+		//  == and !=
+		// > and <
+		// >= and <=
+		// true and false
+		//
+		// They are matched based on the return type and the argument types
+		//
+		void CheckPairedOperators ()
+		{
+			bool has_equality_or_inequality = false;
+			List<Operator.OpType> found_matched = new List<Operator.OpType> ();
+
+			for (int i = 0; i < members.Count; ++i) {
+				var o_a = members[i] as Operator;
+				if (o_a == null)
+					continue;
+
+				var o_type = o_a.OperatorType;
+				if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
+					has_equality_or_inequality = true;
+
+				if (found_matched.Contains (o_type))
+					continue;
+
+				var matching_type = o_a.GetMatchingOperator ();
+				if (matching_type == Operator.OpType.TOP) {
+					continue;
+				}
+
+				bool pair_found = false;
+				for (int ii = 0; ii < members.Count; ++ii) {
+					var o_b = members[ii] as Operator;
+					if (o_b == null || o_b.OperatorType != matching_type)
+						continue;
+
+					if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
+						continue;
+
+					if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
+						continue;
+
+					found_matched.Add (matching_type);
+					pair_found = true;
+					break;
+				}
+
+				if (!pair_found) {
+					Report.Error (216, o_a.Location,
+						"The operator `{0}' requires a matching operator `{1}' to also be defined",
+						o_a.GetSignatureForError (), Operator.GetName (matching_type));
+				}
+			}
+
+			if (has_equality_or_inequality) {
+				if (!HasEquals)
+					Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
+						GetSignatureForError ());
+
+				if (!HasGetHashCode)
+					Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
+						GetSignatureForError ());
+			}
+		}
+
+		public override void CreateMetadataName (StringBuilder sb)
+		{
+			if (Parent.MemberName != null) {
+				Parent.CreateMetadataName (sb);
+
+				if (sb.Length != 0) {
+					sb.Append (".");
+				}
+			}
+
+			sb.Append (MemberName.Basename);
+		}
+	
+		bool CreateTypeBuilder ()
+		{
+			//
+			// Sets .size to 1 for structs with no instance fields
+			//
+			int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null && !(this is StateMachine) ? 1 : 0;
+
+			var parent_def = Parent as TypeDefinition;
+			if (parent_def == null) {
+				var sb = new StringBuilder ();
+				CreateMetadataName (sb);
+				TypeBuilder = Module.CreateBuilder (sb.ToString (), TypeAttr, type_size);
+			} else {
+				TypeBuilder = parent_def.TypeBuilder.DefineNestedType (Basename, TypeAttr, null, type_size);
+			}
+
+			if (DeclaringAssembly.Importer != null)
+				DeclaringAssembly.Importer.AddCompiledType (TypeBuilder, spec);
+
+			spec.SetMetaInfo (TypeBuilder);
+			spec.MemberCache = new MemberCache (this);
+
+			TypeParameters parentAllTypeParameters = null;
+			if (parent_def != null) {
+				spec.DeclaringType = Parent.CurrentType;
+				parent_def.MemberCache.AddMember (spec);
+				parentAllTypeParameters = parent_def.all_type_parameters;
+			}
+
+			if (MemberName.TypeParameters != null || parentAllTypeParameters != null) {
+				var tparam_names = CreateTypeParameters (parentAllTypeParameters);
+
+				all_tp_builders = TypeBuilder.DefineGenericParameters (tparam_names);
+
+				if (CurrentTypeParameters != null) {
+					CurrentTypeParameters.Create (spec, CurrentTypeParametersStartIndex, this);
+					CurrentTypeParameters.Define (all_tp_builders);
+				}
+			}
+
+			return true;
+		}
+
+		string[] CreateTypeParameters (TypeParameters parentAllTypeParameters)
+		{
+			string[] names;
+			int parent_offset = 0;
+			if (parentAllTypeParameters != null) {
+				if (CurrentTypeParameters == null) {
+					all_type_parameters = parentAllTypeParameters;
+					return parentAllTypeParameters.GetAllNames ();
+				}
+
+				names = new string[parentAllTypeParameters.Count + CurrentTypeParameters.Count];
+				all_type_parameters = new TypeParameters (names.Length);
+				all_type_parameters.Add (parentAllTypeParameters);
+
+				parent_offset = all_type_parameters.Count;
+				for (int i = 0; i < parent_offset; ++i)
+					names[i] = all_type_parameters[i].MemberName.Name;
+
+			} else {
+				names = new string[CurrentTypeParameters.Count];
+			}
+
+			for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+				if (all_type_parameters != null)
+					all_type_parameters.Add (MemberName.TypeParameters[i]);
+
+				var name = CurrentTypeParameters[i].MemberName.Name;
+				names[parent_offset + i] = name;
+				for (int ii = 0; ii < parent_offset + i; ++ii) {
+					if (names[ii] != name)
+						continue;
+
+					var tp = CurrentTypeParameters[i];
+					var conflict = all_type_parameters[ii];
+
+					tp.WarningParentNameConflict (conflict);
+				}
+			}
+
+			if (all_type_parameters == null)
+				all_type_parameters = CurrentTypeParameters;
+
+			return names;
+		}
+
+
+		public SourceMethodBuilder CreateMethodSymbolEntry ()
+		{
+			if (Module.DeclaringAssembly.SymbolWriter == null || (ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
+				return null;
+
+			var source_file = GetCompilationSourceFile ();
+			if (source_file == null)
+				return null;
+
+			return new SourceMethodBuilder (source_file.SymbolUnitEntry);
+		}
+
+		//
+		// Creates a proxy base method call inside this container for hoisted base member calls
+		//
+		public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
+		{
+			Method proxy_method;
+
+			//
+			// One proxy per base method is enough
+			//
+			if (hoisted_base_call_proxies == null) {
+				hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
+				proxy_method = null;
+			} else {
+				hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
+			}
+
+			if (proxy_method == null) {
+				string name = CompilerGeneratedContainer.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
+
+				MemberName member_name;
+				TypeArguments targs = null;
+				TypeSpec return_type = method.ReturnType;
+				var local_param_types = method.Parameters.Types;
+
+				if (method.IsGeneric) {
+					//
+					// Copy all base generic method type parameters info
+					//
+					var hoisted_tparams = method.GenericDefinition.TypeParameters;
+					var tparams = new TypeParameters ();
+
+					targs = new TypeArguments ();
+					targs.Arguments = new TypeSpec[hoisted_tparams.Length];
+					for (int i = 0; i < hoisted_tparams.Length; ++i) {
+						var tp = hoisted_tparams[i];
+						var local_tp = new TypeParameter (tp, null, new MemberName (tp.Name, Location), null);
+						tparams.Add (local_tp);
+
+						targs.Add (new SimpleName (tp.Name, Location));
+						targs.Arguments[i] = local_tp.Type;
+					}
+
+					member_name = new MemberName (name, tparams, Location);
+
+					//
+					// Mutate any method type parameters from original
+					// to newly created hoisted version
+					//
+					var mutator = new TypeParameterMutator (hoisted_tparams, tparams);
+					return_type = mutator.Mutate (return_type);
+					local_param_types = mutator.Mutate (local_param_types);
+				} else {
+					member_name = new MemberName (name);
+				}
+
+				var base_parameters = new Parameter[method.Parameters.Count];
+				for (int i = 0; i < base_parameters.Length; ++i) {
+					var base_param = method.Parameters.FixedParameters[i];
+					base_parameters[i] = new Parameter (new TypeExpression (local_param_types [i], Location),
+						base_param.Name, base_param.ModFlags, null, Location);
+					base_parameters[i].Resolve (this, i);
+				}
+
+				var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
+				if (method.Parameters.HasArglist) {
+					cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
+					cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
+				}
+
+				// Compiler generated proxy
+				proxy_method = new Method (this, new TypeExpression (return_type, Location),
+					Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
+					member_name, cloned_params, null);
+
+				var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location) {
+					IsCompilerGenerated = true
+				};
+
+				var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
+				mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
+				if (targs != null)
+					mg.SetTypeArguments (rc, targs);
+
+				// Get all the method parameters and pass them as arguments
+				var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
+				Statement statement;
+				if (method.ReturnType.Kind == MemberKind.Void)
+					statement = new StatementExpression (real_base_call);
+				else
+					statement = new Return (real_base_call, Location);
+
+				block.AddStatement (statement);
+				proxy_method.Block = block;
+
+				members.Add (proxy_method);
+				proxy_method.Define ();
+				proxy_method.PrepareEmit ();
+
+				hoisted_base_call_proxies.Add (method, proxy_method);
+			}
+
+			return proxy_method.Spec;
+		}
+
+		protected bool DefineBaseTypes ()
+		{
+			if (IsPartialPart && Kind == MemberKind.Class)
+				return true;
+
+			return DoDefineBaseType ();
+		}
+
+		bool DoDefineBaseType ()
+		{
+			iface_exprs = ResolveBaseTypes (out base_type_expr);
+			bool set_base_type;
+
+			if (IsPartialPart) {
+				set_base_type = false;
+
+				if (base_type_expr != null) {
+					if (PartialContainer.base_type_expr != null && PartialContainer.base_type != base_type) {
+						Report.SymbolRelatedToPreviousError (base_type_expr.Location, "");
+						Report.Error (263, Location,
+							"Partial declarations of `{0}' must not specify different base classes",
+							GetSignatureForError ());
+					} else {
+						PartialContainer.base_type_expr = base_type_expr;
+						PartialContainer.base_type = base_type;
+						set_base_type = true;
+					}
+				}
+
+				if (iface_exprs != null) {
+					if (PartialContainer.iface_exprs == null)
+						PartialContainer.iface_exprs = iface_exprs;
+					else {
+						var ifaces = new List<TypeSpec> (PartialContainer.iface_exprs);
+						foreach (var iface_partial in iface_exprs) {
+							if (ifaces.Contains (iface_partial))
+								continue;
+
+							ifaces.Add (iface_partial);
+						}
+
+						PartialContainer.iface_exprs = ifaces.ToArray ();
+					}
+				}
+
+				PartialContainer.members.AddRange (members);
+				if (containers != null) {
+					if (PartialContainer.containers == null)
+						PartialContainer.containers = new List<TypeContainer> ();
+
+					PartialContainer.containers.AddRange (containers);
+				}
+
+				if (PrimaryConstructorParameters != null) {
+					if (PartialContainer.PrimaryConstructorParameters != null) {
+						Report.Error (8036, Location, "Only one part of a partial type can declare primary constructor parameters");
+					} else {
+						PartialContainer.PrimaryConstructorParameters = PrimaryConstructorParameters;
+					}
+				}
+
+				members_defined = members_defined_ok = true;
+				caching_flags |= Flags.CloseTypeCreated;
+			} else {
+				set_base_type = true;
+			}
+
+			var cycle = CheckRecursiveDefinition (this);
+			if (cycle != null) {
+				Report.SymbolRelatedToPreviousError (cycle);
+				if (this is Interface) {
+					Report.Error (529, Location,
+						"Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
+					    GetSignatureForError (), cycle.GetSignatureForError ());
+
+					iface_exprs = null;
+					PartialContainer.iface_exprs = null;
+				} else {
+					Report.Error (146, Location,
+						"Circular base class dependency involving `{0}' and `{1}'",
+						GetSignatureForError (), cycle.GetSignatureForError ());
+
+					base_type = null;
+					PartialContainer.base_type = null;
+				}
+			}
+
+			if (iface_exprs != null) {
+				if (!PrimaryConstructorBaseArgumentsStart.IsNull) {
+					Report.Error (8049, PrimaryConstructorBaseArgumentsStart, "Implemented interfaces cannot have arguments");
+				}
+
+				foreach (var iface_type in iface_exprs) {
+					// Prevents a crash, the interface might not have been resolved: 442144
+					if (iface_type == null)
+						continue;
+					
+					if (!spec.AddInterfaceDefined (iface_type))
+						continue;
+
+					TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
+				}
+			}
+
+			if (Kind == MemberKind.Interface) {
+				spec.BaseType = Compiler.BuiltinTypes.Object;
+				return true;
+			}
+
+			if (set_base_type) {
+				SetBaseType ();
+			}
+
+			//
+			// Base type of partial container has to be resolved before we
+			// resolve any nested types of the container. We need to know
+			// partial parts because the base type can be specified in file
+			// defined after current container
+			//
+			if (class_partial_parts != null) {
+				foreach (var pp in class_partial_parts) {
+					if (pp.PrimaryConstructorBaseArguments != null)
+						PrimaryConstructorBaseArguments = pp.PrimaryConstructorBaseArguments;
+
+					pp.DoDefineBaseType ();
+				}
+
+			}
+
+			return true;
+		}
+
+		void SetBaseType ()
+		{
+			if (base_type == null) {
+				TypeBuilder.SetParent (null);
+				return;
+			}
+
+			if (spec.BaseType == base_type)
+				return;
+
+			spec.BaseType = base_type;
+
+			if (IsPartialPart)
+				spec.UpdateInflatedInstancesBaseType ();
+
+			// Set base type after type creation
+			TypeBuilder.SetParent (base_type.GetMetaInfo ());
+		}
+
+		public override void ExpandBaseInterfaces ()
+		{
+			if (!IsPartialPart)
+				DoExpandBaseInterfaces ();
+
+			base.ExpandBaseInterfaces ();
+		}
+
+		public void DoExpandBaseInterfaces ()
+		{
+			if ((caching_flags & Flags.InterfacesExpanded) != 0)
+				return;
+
+			caching_flags |= Flags.InterfacesExpanded;
+
+			//
+			// Expand base interfaces. It cannot be done earlier because all partial
+			// interface parts need to be defined before the type they are used from
+			//
+			if (iface_exprs != null) {
+				foreach (var iface in iface_exprs) {
+					if (iface == null)
+						continue;
+
+					var td = iface.MemberDefinition as TypeDefinition;
+					if (td != null)
+						td.DoExpandBaseInterfaces ();
+
+					if (iface.Interfaces == null)
+						continue;
+
+					foreach (var biface in iface.Interfaces) {
+						if (spec.AddInterfaceDefined (biface)) {
+							TypeBuilder.AddInterfaceImplementation (biface.GetMetaInfo ());
+						}
+					}
+				}
+			}
+
+			//
+			// Include all base type interfaces too, see ImportTypeBase for details
+			//
+			if (base_type != null) {
+				var td = base_type.MemberDefinition as TypeDefinition;
+				if (td != null)
+					td.DoExpandBaseInterfaces ();
+
+				//
+				// Simply use base interfaces only, they are all expanded which makes
+				// it easy to handle generic type argument propagation with single
+				// inflator only.
+				//
+				// interface IA<T> : IB<T>
+				// interface IB<U> : IC<U>
+				// interface IC<V>
+				//
+				if (base_type.Interfaces != null) {
+					foreach (var iface in base_type.Interfaces) {
+						spec.AddInterfaceDefined (iface);
+					}
+				}
+			}
+		}
+
+		public override void PrepareEmit ()
+		{
+			if ((caching_flags & Flags.CloseTypeCreated) != 0)
+				return;
+
+			foreach (var member in members) {
+				var pbm = member as PropertyBasedMember;
+				if (pbm != null)
+					pbm.PrepareEmit ();
+
+				var pm = member as IParametersMember;
+				if (pm != null) {
+					var mc = member as MethodOrOperator;
+					if (mc != null) {
+						mc.PrepareEmit ();
+					}
+
+					var p = pm.Parameters;
+					if (p.IsEmpty)
+						continue;
+
+					((ParametersCompiled) p).ResolveDefaultValues (member);
+					continue;
+				}
+
+				var c = member as Const;
+				if (c != null)
+					c.DefineValue ();
+			}
+
+			base.PrepareEmit ();
+		}
+
+		//
+		// Defines the type in the appropriate ModuleBuilder or TypeBuilder.
+		//
+		public override bool CreateContainer ()
+		{
+			if (TypeBuilder != null)
+				return !error;
+
+			if (error)
+				return false;
+
+			if (IsPartialPart) {
+				spec = PartialContainer.spec;
+				TypeBuilder = PartialContainer.TypeBuilder;
+				all_tp_builders = PartialContainer.all_tp_builders;
+				all_type_parameters = PartialContainer.all_type_parameters;
+			} else {
+				if (!CreateTypeBuilder ()) {
+					error = true;
+					return false;
+				}
+			}
+
+			return base.CreateContainer ();
+		}
+
+		protected override void DoDefineContainer ()
+		{
+			DefineBaseTypes ();
+
+			DoResolveTypeParameters ();
+		}
+
+		//
+		// Replaces normal spec with predefined one when compiling corlib
+		// and this type container defines predefined type
+		//
+		public void SetPredefinedSpec (BuiltinTypeSpec spec)
+		{
+			// When compiling build-in types we start with two
+			// version of same type. One is of BuiltinTypeSpec and
+			// second one is ordinary TypeSpec. The unification
+			// happens at later stage when we know which type
+			// really matches the builtin type signature. However
+			// that means TypeSpec create during CreateType of this
+			// type has to be replaced with builtin one
+			// 
+			spec.SetMetaInfo (TypeBuilder);
+			spec.MemberCache = this.spec.MemberCache;
+			spec.DeclaringType = this.spec.DeclaringType;
+
+			this.spec = spec;
+			current_type = null;
+		}
+
+		public override void RemoveContainer (TypeContainer cont)
+		{
+			base.RemoveContainer (cont);
+			Members.Remove (cont);
+			Cache.Remove (cont.Basename);
+		}
+
+		protected virtual bool DoResolveTypeParameters ()
+		{
+			var tparams = MemberName.TypeParameters;
+			if (tparams == null)
+				return true;
+
+			var base_context = new BaseContext (this);
+			for (int i = 0; i < tparams.Count; ++i) {
+				var tp = tparams[i];
+
+				if (!tp.ResolveConstraints (base_context)) {
+					error = true;
+					return false;
+				}
+
+				if (IsPartialPart) {
+					var pc_tp = PartialContainer.CurrentTypeParameters [i];
+
+					tp.Create (spec, this);
+					tp.Define (pc_tp);
+
+					if (tp.OptAttributes != null) {
+						if (pc_tp.OptAttributes == null)
+							pc_tp.OptAttributes = tp.OptAttributes;
+						else
+							pc_tp.OptAttributes.Attrs.AddRange (tp.OptAttributes.Attrs);
+					}
+				}
+			}
+
+			if (IsPartialPart) {
+				PartialContainer.CurrentTypeParameters.UpdateConstraints (this);
+			}
+
+			return true;
+		}
+
+		TypeSpec CheckRecursiveDefinition (TypeDefinition tc)
+		{
+			if (InTransit != null)
+				return spec;
+
+			InTransit = tc;
+
+			if (base_type != null) {
+				var ptc = base_type.MemberDefinition as TypeDefinition;
+				if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
+					return base_type;
+			}
+
+			if (iface_exprs != null) {
+				foreach (var iface in iface_exprs) {
+					// the interface might not have been resolved, prevents a crash, see #442144
+					if (iface == null)
+						continue;
+					var ptc = iface.MemberDefinition as Interface;
+					if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
+						return iface;
+				}
+			}
+
+			if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
+				return spec;
+
+			InTransit = null;
+			return null;
+		}
+
+		/// <summary>
+		///   Populates our TypeBuilder with fields and methods
+		/// </summary>
+		public sealed override bool Define ()
+		{
+			if (members_defined)
+				return members_defined_ok;
+
+			members_defined_ok = DoDefineMembers ();
+			members_defined = true;
+
+			base.Define ();
+
+			return members_defined_ok;
+		}
+
+		protected virtual bool DoDefineMembers ()
+		{
+			Debug.Assert (!IsPartialPart);
+
+			if (iface_exprs != null) {
+				foreach (var iface_type in iface_exprs) {
+					if (iface_type == null)
+						continue;
+
+					// Ensure the base is always setup
+					var compiled_iface = iface_type.MemberDefinition as Interface;
+					if (compiled_iface != null)
+						compiled_iface.Define ();
+
+					ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
+					if (oa != null && !IsObsolete)
+						AttributeTester.Report_ObsoleteMessage (oa, iface_type.GetSignatureForError (), Location, Report);
+
+					if (iface_type.Arity > 0) {
+						// TODO: passing `this' is wrong, should be base type iface instead
+						VarianceDecl.CheckTypeVariance (iface_type, Variance.Covariant, this);
+
+						if (((InflatedTypeSpec) iface_type).HasDynamicArgument () && !IsCompilerGenerated) {
+							Report.Error (1966, Location,
+								"`{0}': cannot implement a dynamic interface `{1}'",
+								GetSignatureForError (), iface_type.GetSignatureForError ());
+							return false;
+						}
+					}
+
+					if (iface_type.IsGenericOrParentIsGeneric) {
+						foreach (var prev_iface in iface_exprs) {
+							if (prev_iface == iface_type || prev_iface == null)
+								break;
+
+							if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface))
+								continue;
+
+							Report.Error (695, Location,
+								"`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
+								GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
+						}
+					}
+				}
+
+				if (Kind == MemberKind.Interface) {
+					foreach (var iface in spec.Interfaces) {
+						MemberCache.AddInterface (iface);
+					}
+				}
+			}
+
+			if (base_type != null) {
+				//
+				// Run checks skipped during DefineType (e.g FullNamedExpression::ResolveAsType)
+				//
+				if (base_type_expr != null) {
+					ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
+					if (obsolete_attr != null && !IsObsolete)
+						AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), base_type_expr.Location, Report);
+
+					if (IsGenericOrParentIsGeneric && base_type.IsAttribute) {
+						Report.Error (698, base_type_expr.Location,
+							"A generic type cannot derive from `{0}' because it is an attribute class",
+							base_type.GetSignatureForError ());
+					}
+				}
+
+				var baseContainer = base_type.MemberDefinition as ClassOrStruct;
+				if (baseContainer != null) {
+					baseContainer.Define ();
+
+					//
+					// It can trigger define of this type (for generic types only)
+					//
+					if (HasMembersDefined)
+						return true;
+				}
+			}
+
+			if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
+				pending = PendingImplementation.GetPendingImplementations (this);
+			}
+
+			var count = members.Count;		
+			for (int i = 0; i < count; ++i) {
+				var mc = members[i] as InterfaceMemberBase;
+				if (mc == null || !mc.IsExplicitImpl)
+					continue;
+
+				try {
+					mc.Define ();
+				} catch (Exception e) {
+					throw new InternalErrorException (mc, e);
+				}
+			}
+
+			for (int i = 0; i < count; ++i) {
+				var mc = members[i] as InterfaceMemberBase;
+				if (mc != null && mc.IsExplicitImpl)
+					continue;
+
+				if (members[i] is TypeContainer)
+					continue;
+
+				try {
+					members[i].Define ();
+				} catch (Exception e) {
+					throw new InternalErrorException (members[i], e);
+				}
+			}
+
+			if (HasOperators) {
+				CheckPairedOperators ();
+			}
+
+			if (requires_delayed_unmanagedtype_check) {
+				requires_delayed_unmanagedtype_check = false;
+				foreach (var member in members) {
+					var f = member as Field;
+					if (f != null && f.MemberType != null && f.MemberType.IsPointer)
+						TypeManager.VerifyUnmanaged (Module, f.MemberType, f.Location);
+				}
+			}
+
+			ComputeIndexerName();
+
+			if (HasEquals && !HasGetHashCode) {
+				Report.Warning (659, 3, Location,
+					"`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", GetSignatureForError ());
+			}
+
+			if (Kind == MemberKind.Interface && iface_exprs != null) {
+				MemberCache.RemoveHiddenMembers (spec);
+			}
+
+			return true;
+		}
+
+		void ComputeIndexerName ()
+		{
+			var indexers = MemberCache.FindMembers (spec, MemberCache.IndexerNameAlias, true);
+			if (indexers == null)
+				return;
+
+			string class_indexer_name = null;
+
+			//
+			// Check normal indexers for consistent name, explicit interface implementation
+			// indexers are ignored
+			//
+			foreach (var indexer in indexers) {
+				//
+				// FindMembers can return unfiltered full hierarchy names
+				//
+				if (indexer.DeclaringType != spec)
+					continue;
+
+				has_normal_indexers = true;
+
+				if (class_indexer_name == null) {
+					indexer_name = class_indexer_name = indexer.Name;
+					continue;
+				}
+
+				if (indexer.Name != class_indexer_name)
+					Report.Error (668, ((Indexer)indexer.MemberDefinition).Location,
+						"Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
+			}
+		}
+
+		void EmitIndexerName ()
+		{
+			if (!has_normal_indexers)
+				return;
+
+			var ctor = Module.PredefinedMembers.DefaultMemberAttributeCtor.Get ();
+			if (ctor == null)
+				return;
+
+			var encoder = new AttributeEncoder ();
+			encoder.Encode (GetAttributeDefaultMember ());
+			encoder.EncodeEmptyNamedArguments ();
+
+			TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+
+		public override void VerifyMembers ()
+		{
+			//
+			// Check for internal or private fields that were never assigned
+			//
+			if (!IsCompilerGenerated && Compiler.Settings.WarningLevel >= 3 && this == PartialContainer) {
+				bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
+				foreach (var member in members) {
+					if (member is Event) {
+						//
+						// An event can be assigned from same class only, report
+						// this warning for all accessibility modes
+						//
+						if (!member.IsUsed && !PartialContainer.HasStructLayout)
+							Report.Warning (67, 3, member.Location, "The event `{0}' is never used", member.GetSignatureForError ());
+
+						continue;
+					}
+
+					if ((member.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
+						if (is_type_exposed)
+							continue;
+
+						member.SetIsUsed ();
+					}
+
+					var f = member as Field;
+					if (f == null)
+						continue;
+
+					if (!member.IsUsed) {
+						if (!PartialContainer.HasStructLayout) {
+							if ((member.caching_flags & Flags.IsAssigned) == 0) {
+								Report.Warning (169, 3, member.Location, "The private field `{0}' is never used", member.GetSignatureForError ());
+							} else {
+								Report.Warning (414, 3, member.Location, "The private field `{0}' is assigned but its value is never used",
+									member.GetSignatureForError ());
+							}
+						}
+
+						continue;
+					}
+
+					if ((f.caching_flags & Flags.IsAssigned) != 0)
+						continue;
+
+					//
+					// Only report 649 on level 4
+					//
+					if (Compiler.Settings.WarningLevel < 4)
+						continue;
+
+					//
+					// Don't be pedantic when type requires specific layout
+					//
+					if (f.OptAttributes != null || PartialContainer.HasStructLayout)
+						continue;
+
+					Constant c = New.Constantify (f.MemberType, f.Location);
+					string value;
+					if (c != null) {
+						value = c.GetValueAsLiteral ();
+					} else if (TypeSpec.IsReferenceType (f.MemberType)) {
+						value = "null";
+					} else {
+						value = null;
+					}
+
+					if (value != null)
+						value = " `" + value + "'";
+
+					Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value{1}",
+						f.GetSignatureForError (), value);
+				}
+			}
+
+			base.VerifyMembers ();
+		}
+
+		public override void Emit ()
+		{
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			if (!IsCompilerGenerated) {
+				if (!IsTopLevel) {
+					MemberSpec candidate;
+					bool overrides = false;
+					var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides);
+					if (conflict_symbol == null && candidate == null) {
+						if ((ModFlags & Modifiers.NEW) != 0)
+							Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
+								GetSignatureForError ());
+					} else {
+						if ((ModFlags & Modifiers.NEW) == 0) {
+							if (candidate == null)
+								candidate = conflict_symbol;
+
+							Report.SymbolRelatedToPreviousError (candidate);
+							Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+								GetSignatureForError (), candidate.GetSignatureForError ());
+						}
+					}
+				}
+
+				// Run constraints check on all possible generic types
+				if (base_type != null && base_type_expr != null) {
+					ConstraintChecker.Check (this, base_type, base_type_expr.Location);
+				}
+
+				if (iface_exprs != null) {
+					foreach (var iface_type in iface_exprs) {
+						if (iface_type == null)
+							continue;
+
+						ConstraintChecker.Check (this, iface_type, Location);	// TODO: Location is wrong
+					}
+				}
+			}
+
+			if (all_tp_builders != null) {
+				int current_starts_index = CurrentTypeParametersStartIndex;
+				for (int i = 0; i < all_tp_builders.Length; i++) {
+					if (i < current_starts_index) {
+						all_type_parameters[i].EmitConstraints (all_tp_builders [i]);
+					} else {
+						var tp = CurrentTypeParameters [i - current_starts_index];
+						tp.CheckGenericConstraints (!IsObsolete);
+						tp.Emit ();
+					}
+				}
+			}
+
+			if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
+				Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
+
+#if STATIC
+			if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet)
+				TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType);
+#endif
+
+			base.Emit ();
+
+			for (int i = 0; i < members.Count; i++) {
+				var m = members[i];
+				if ((m.caching_flags & Flags.CloseTypeCreated) != 0)
+					continue;
+
+				m.Emit ();
+			}
+
+			EmitIndexerName ();
+			CheckAttributeClsCompliance ();
+
+			if (pending != null)
+				pending.VerifyPendingMethods ();
+		}
+
+
+		void CheckAttributeClsCompliance ()
+		{
+			if (!spec.IsAttribute || !IsExposedFromAssembly () || !Compiler.Settings.VerifyClsCompliance || !IsClsComplianceRequired ())
+				return;
+
+			foreach (var m in members) {
+				var c = m as Constructor;
+				if (c == null)
+					continue;
+
+				if (c.HasCompliantArgs)
+					return;
+			}
+
+			Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
+		}
+
+		public sealed override void EmitContainer ()
+		{
+			if ((caching_flags & Flags.CloseTypeCreated) != 0)
+				return;
+
+			Emit ();
+		}
+
+		public override void CloseContainer ()
+		{
+			if ((caching_flags & Flags.CloseTypeCreated) != 0)
+				return;
+
+			// Close base type container first to avoid TypeLoadException
+			if (spec.BaseType != null) {
+				var btype = spec.BaseType.MemberDefinition as TypeContainer;
+				if (btype != null) {
+					btype.CloseContainer ();
+
+					if ((caching_flags & Flags.CloseTypeCreated) != 0)
+						return;
+				}
+			}
+
+			try {
+				caching_flags |= Flags.CloseTypeCreated;
+				TypeBuilder.CreateType ();
+			} catch (TypeLoadException) {
+				//
+				// This is fine, the code still created the type
+				//
+			} catch (Exception e) {
+				throw new InternalErrorException (this, e);
+			}
+
+			base.CloseContainer ();
+			
+			containers = null;
+			initialized_fields = null;
+			initialized_static_fields = null;
+			type_bases = null;
+			OptAttributes = null;
+		}
+
+		//
+		// Performs the validation on a Method's modifiers (properties have
+		// the same properties).
+		//
+		// TODO: Why is it not done at parse stage, move to Modifiers::Check
+		//
+		public bool MethodModifiersValid (MemberCore mc)
+		{
+			const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
+			const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
+			bool ok = true;
+			var flags = mc.ModFlags;
+			
+			//
+			// At most one of static, virtual or override
+			//
+			if ((flags & Modifiers.STATIC) != 0){
+				if ((flags & vao) != 0){
+					Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
+						mc.GetSignatureForError ());
+					ok = false;
+				}
+			}
+
+			if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
+				Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
+					mc.GetSignatureForError ());
+				ok = false;
+			}
+
+			//
+			// If the declaration includes the abstract modifier, then the
+			// declaration does not include static, virtual or extern
+			//
+			if ((flags & Modifiers.ABSTRACT) != 0){
+				if ((flags & Modifiers.EXTERN) != 0){
+					Report.Error (
+						180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
+					ok = false;
+				}
+
+				if ((flags & Modifiers.SEALED) != 0) {
+					Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
+					ok = false;
+				}
+
+				if ((flags & Modifiers.VIRTUAL) != 0){
+					Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
+					ok = false;
+				}
+
+				if ((ModFlags & Modifiers.ABSTRACT) == 0){
+					Report.SymbolRelatedToPreviousError (this);
+					Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
+						mc.GetSignatureForError (), GetSignatureForError ());
+					ok = false;
+				}
+			}
+
+			if ((flags & Modifiers.PRIVATE) != 0){
+				if ((flags & vao) != 0){
+					Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
+					ok = false;
+				}
+			}
+
+			if ((flags & Modifiers.SEALED) != 0){
+				if ((flags & Modifiers.OVERRIDE) == 0){
+					Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
+					ok = false;
+				}
+			}
+
+			return ok;
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			// Check all container names for user classes
+			if (Kind != MemberKind.Delegate)
+				MemberCache.VerifyClsCompliance (Definition, Report);
+
+			if (BaseType != null && !BaseType.IsCLSCompliant ()) {
+				Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
+					GetSignatureForError (), BaseType.GetSignatureForError ());
+			}
+			return true;
+		}
+
+		/// <summary>
+		///   Performs checks for an explicit interface implementation.  First it
+		///   checks whether the `interface_type' is a base inteface implementation.
+		///   Then it checks whether `name' exists in the interface type.
+		/// </summary>
+		public bool VerifyImplements (InterfaceMemberBase mb)
+		{
+			var ifaces = PartialContainer.Interfaces;
+			if (ifaces != null) {
+				foreach (TypeSpec t in ifaces){
+					if (t == mb.InterfaceType)
+						return true;
+
+					var expanded_base = t.Interfaces;
+					if (expanded_base == null)
+						continue;
+
+					foreach (var bt in expanded_base) {
+						if (bt == mb.InterfaceType)
+							return true;
+					}
+				}
+			}
+			
+			Report.SymbolRelatedToPreviousError (mb.InterfaceType);
+			Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
+				mb.GetSignatureForError (), mb.InterfaceType.GetSignatureForError ());
+			return false;
+		}
+
+		//
+		// Used for visiblity checks to tests whether this definition shares
+		// base type baseType, it does member-definition search
+		//
+		public bool IsBaseTypeDefinition (TypeSpec baseType)
+		{
+			// RootContext check
+			if (TypeBuilder == null)
+				return false;
+
+			var type = spec;
+			do {
+				if (type.MemberDefinition == baseType.MemberDefinition)
+					return true;
+
+				type = type.BaseType;
+			} while (type != null);
+
+			return false;
+		}
+
+		public override bool IsClsComplianceRequired ()
+		{
+			if (IsPartialPart)
+				return PartialContainer.IsClsComplianceRequired ();
+
+			return base.IsClsComplianceRequired ();
+		}
+
+		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
+		{
+			return Module.DeclaringAssembly == assembly;
+		}
+
+		public virtual bool IsUnmanagedType ()
+		{
+			return false;
+		}
+
+		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+		{
+			throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
+		}
+
+		//
+		// Public function used to locate types.
+		//
+		// Returns: Type or null if they type can not be found.
+		//
+		public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			FullNamedExpression e;
+			if (arity == 0 && Cache.TryGetValue (name, out e) && mode != LookupMode.IgnoreAccessibility)
+				return e;
+
+			e = null;
+
+			if (arity == 0) {
+				var tp = CurrentTypeParameters;
+				if (tp != null) {
+					TypeParameter tparam = tp.Find (name);
+					if (tparam != null)
+						e = new TypeParameterExpr (tparam, Location.Null);
+				}
+			}
+
+			if (e == null) {
+				TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
+
+				if (t != null && (t.IsAccessible (this) || mode == LookupMode.IgnoreAccessibility))
+					e = new TypeExpression (t, Location.Null);
+				else {
+					var errors = Compiler.Report.Errors;
+					e = Parent.LookupNamespaceOrType (name, arity, mode, loc);
+
+					// TODO: LookupNamespaceOrType does more than just lookup. The result
+					// cannot be cached or the error reporting won't happen
+					if (errors != Compiler.Report.Errors)
+						return e;
+				}
+			}
+
+			// TODO MemberCache: How to cache arity stuff ?
+			if (arity == 0 && mode == LookupMode.Normal)
+				Cache[name] = e;
+
+			return e;
+		}
+
+		TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
+		{
+			// Has any nested type
+			// Does not work, because base type can have
+			//if (PartialContainer.Types == null)
+			//	return null;
+
+			var container = PartialContainer.CurrentType;
+			return MemberCache.FindNestedType (container, name, arity);
+		}
+
+		public void Mark_HasEquals ()
+		{
+			cached_method |= CachedMethods.Equals;
+		}
+
+		public void Mark_HasGetHashCode ()
+		{
+			cached_method |= CachedMethods.GetHashCode;
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (IsPartialPart)
+				return;
+
+			foreach (var m in members) {
+				m.WriteDebugSymbol (file);
+			}
+		}
+
+		/// <summary>
+		/// Method container contains Equals method
+		/// </summary>
+		public bool HasEquals {
+			get {
+				return (cached_method & CachedMethods.Equals) != 0;
+			}
+		}
+ 
+		/// <summary>
+		/// Method container contains GetHashCode method
+		/// </summary>
+		public bool HasGetHashCode {
+			get {
+				return (cached_method & CachedMethods.GetHashCode) != 0;
+			}
+		}
+
+		public bool HasStaticFieldInitializer {
+			get {
+				return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
+			}
+			set {
+				if (value)
+					cached_method |= CachedMethods.HasStaticFieldInitializer;
+				else
+					cached_method &= ~CachedMethods.HasStaticFieldInitializer;
+			}
+		}
+
+		public override string DocCommentHeader {
+			get { return "T:"; }
+		}
+	}
+
+	public abstract class ClassOrStruct : TypeDefinition
+	{
+		public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
+
+		SecurityType declarative_security;
+		protected Constructor generated_primary_constructor;
+
+		protected ClassOrStruct (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
+			: base (parent, name, attrs, kind)
+		{
+		}
+
+		public ToplevelBlock PrimaryConstructorBlock { get; set; }
+
+		protected override TypeAttributes TypeAttr {
+			get {
+				TypeAttributes ta = base.TypeAttr;
+				if (!has_static_constructor)
+					ta |= TypeAttributes.BeforeFieldInit;
+
+				if (Kind == MemberKind.Class) {
+					ta |= TypeAttributes.AutoLayout | TypeAttributes.Class;
+					if (IsStatic)
+						ta |= StaticClassAttribute;
+				} else {
+					ta |= TypeAttributes.SequentialLayout;
+				}
+
+				return ta;
+			}
+		}
+
+		public override void AddNameToContainer (MemberCore symbol, string name)
+		{
+			if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
+				if (symbol is TypeParameter) {
+					Report.Error (694, symbol.Location,
+						"Type parameter `{0}' has same name as containing type, or method",
+						symbol.GetSignatureForError ());
+					return;
+				}
+
+				InterfaceMemberBase imb = symbol as InterfaceMemberBase;
+				if (imb == null || !imb.IsExplicitImpl) {
+					Report.SymbolRelatedToPreviousError (this);
+					Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
+						symbol.GetSignatureForError ());
+					return;
+				}
+			}
+
+			base.AddNameToContainer (symbol, name);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.IsValidSecurityAttribute ()) {
+				a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
+				return;
+			}
+
+			if (a.Type == pa.StructLayout) {
+				PartialContainer.HasStructLayout = true;
+				if (a.IsExplicitLayoutKind ())
+					PartialContainer.HasExplicitLayout = true;
+			}
+
+			if (a.Type == pa.Dynamic) {
+				a.Error_MisusedDynamicAttribute ();
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		/// <summary>
+		/// Defines the default constructors 
+		/// </summary>
+		protected virtual Constructor DefineDefaultConstructor (bool is_static)
+		{
+			// The default instance constructor is public
+			// If the class is abstract, the default constructor is protected
+			// The default static constructor is private
+
+			Modifiers mods;
+			ParametersCompiled parameters = null;
+			if (is_static) {
+				mods = Modifiers.STATIC | Modifiers.PRIVATE;
+				parameters = ParametersCompiled.EmptyReadOnlyParameters;
+			} else {
+				mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
+				parameters = PrimaryConstructorParameters ?? ParametersCompiled.EmptyReadOnlyParameters;
+			}
+
+			var c = new Constructor (this, MemberName.Name, mods, null, parameters, Location);
+			if (Kind == MemberKind.Class)
+				c.Initializer = new GeneratedBaseInitializer (Location, PrimaryConstructorBaseArguments);
+
+			if (PrimaryConstructorParameters != null && !is_static)
+				c.IsPrimaryConstructor = true;
+			
+			AddConstructor (c, true);
+			if (PrimaryConstructorBlock == null) {
+				c.Block = new ToplevelBlock (Compiler, parameters, Location) {
+					IsCompilerGenerated = true
+				};
+			} else {
+				c.Block = PrimaryConstructorBlock;
+			}
+
+			return c;
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			CheckProtectedModifier ();
+
+			if (PrimaryConstructorParameters != null) {
+				foreach (Parameter p in PrimaryConstructorParameters.FixedParameters) {
+					if (p.Name == MemberName.Name) {
+						Report.Error (8039, p.Location, "Primary constructor of type `{0}' has parameter of same name as containing type",
+							GetSignatureForError ());
+					}
+
+					if (CurrentTypeParameters != null) {
+						for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+							var tp = CurrentTypeParameters [i];
+							if (p.Name == tp.Name) {
+								Report.Error (8038, p.Location, "Primary constructor of type `{0}' has parameter of same name as type parameter `{1}'",
+									GetSignatureForError (), p.GetSignatureForError ());
+							}
+						}
+					}
+				}
+			}
+
+			base.DoDefineMembers ();
+
+			return true;
+		}
+
+		public override void Emit ()
+		{
+			if (!has_static_constructor && HasStaticFieldInitializer) {
+				var c = DefineDefaultConstructor (true);
+				c.Define ();
+			}
+
+			base.Emit ();
+
+			if (declarative_security != null) {
+				foreach (var de in declarative_security) {
+#if STATIC
+					TypeBuilder.__AddDeclarativeSecurity (de);
+#else
+					TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
+				}
+			}
+		}
+	}
+
+
+	public sealed class Class : ClassOrStruct
+	{
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE |
+			Modifiers.ABSTRACT |
+			Modifiers.SEALED |
+			Modifiers.STATIC |
+			Modifiers.UNSAFE;
+			
+		public Class (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
+			: base (parent, name, attrs, MemberKind.Class)
+		{
+			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+			this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
+			spec = new TypeSpec (Kind, null, this, null, ModFlags);
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void SetBaseTypes (List<FullNamedExpression> baseTypes)
+		{
+			var pmn = MemberName;
+			if (pmn.Name == "Object" && !pmn.IsGeneric && Parent.MemberName.Name == "System" && Parent.MemberName.Left == null)
+				Report.Error (537, Location,
+					"The class System.Object cannot have a base class or implement an interface.");
+
+			base.SetBaseTypes (baseTypes);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.AttributeUsage) {
+				if (!BaseType.IsAttribute && spec.BuiltinType != BuiltinTypeSpec.Type.Attribute) {
+					Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
+				}
+			}
+
+			if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
+				Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
+				return;
+			}
+
+			if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
+				a.Error_MissingGuidAttribute ();
+				return;
+			}
+
+			if (a.Type == pa.Extension) {
+				a.Error_MisusedExtensionAttribute ();
+				return;
+			}
+
+			if (a.Type.IsConditionallyExcluded (this))
+				return;
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Class;
+			}
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
+				Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
+			}
+
+			if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
+				Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
+			}
+
+			if (IsStatic) {
+				if (PrimaryConstructorParameters != null) {
+					Report.Error (-800, Location, "`{0}': Static classes cannot have primary constructor", GetSignatureForError ());
+					PrimaryConstructorParameters = null;
+				}
+
+				foreach (var m in Members) {
+					if (m is Operator) {
+						Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
+						continue;
+					}
+
+					if (m is Destructor) {
+						Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
+						continue;
+					}
+
+					if (m is Indexer) {
+						Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
+						continue;
+					}
+
+					if ((m.ModFlags & Modifiers.STATIC) != 0 || m is TypeContainer)
+						continue;
+
+					if (m is Constructor) {
+						Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
+						continue;
+					}
+
+					Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
+				}
+			} else {
+				if (!PartialContainer.HasInstanceConstructor || PrimaryConstructorParameters != null)
+					generated_primary_constructor = DefineDefaultConstructor (false);
+			}
+
+			return base.DoDefineMembers ();
+		}
+
+		public override void Emit ()
+		{
+			base.Emit ();
+
+			if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
+				Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
+
+			if (base_type != null && base_type.HasDynamicElement) {
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
+			}
+		}
+
+		public override void GetCompletionStartingWith (string prefix, List<string> results)
+		{
+			base.GetCompletionStartingWith (prefix, results);
+
+			var bt = base_type;
+			while (bt != null) {
+				results.AddRange (MemberCache.GetCompletitionMembers (this, bt, prefix).Where (l => l.IsStatic).Select (l => l.Name));
+				bt = bt.BaseType;
+			}
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			var ifaces = base.ResolveBaseTypes (out base_class);
+
+			if (base_class == null) {
+				if (spec.BuiltinType != BuiltinTypeSpec.Type.Object)
+					base_type = Compiler.BuiltinTypes.Object;
+			} else {
+				if (base_type.IsGenericParameter){
+					Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
+						GetSignatureForError (), base_type.GetSignatureForError ());
+				} else if (base_type.IsStatic) {
+					Report.SymbolRelatedToPreviousError (base_type);
+					Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
+						GetSignatureForError (), base_type.GetSignatureForError ());
+				} else if (base_type.IsSealed) {
+					Report.SymbolRelatedToPreviousError (base_type);
+					Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
+						GetSignatureForError (), base_type.GetSignatureForError ());
+				} else if (PartialContainer.IsStatic && base_type.BuiltinType != BuiltinTypeSpec.Type.Object) {
+					Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
+						GetSignatureForError (), base_type.GetSignatureForError ());
+				}
+
+				switch (base_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Enum:
+				case BuiltinTypeSpec.Type.ValueType:
+				case BuiltinTypeSpec.Type.MulticastDelegate:
+				case BuiltinTypeSpec.Type.Delegate:
+				case BuiltinTypeSpec.Type.Array:
+					if (!(spec is BuiltinTypeSpec)) {
+						Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
+							GetSignatureForError (), base_type.GetSignatureForError ());
+
+						base_type = Compiler.BuiltinTypes.Object;
+					}
+					break;
+				}
+
+				if (!IsAccessibleAs (base_type)) {
+					Report.SymbolRelatedToPreviousError (base_type);
+					Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
+						base_type.GetSignatureForError (), GetSignatureForError ());
+				}
+			}
+
+			if (PartialContainer.IsStatic && ifaces != null) {
+				foreach (var t in ifaces)
+					Report.SymbolRelatedToPreviousError (t);
+				Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
+			}
+
+			return ifaces;
+		}
+
+		/// Search for at least one defined condition in ConditionalAttribute of attribute class
+		/// Valid only for attribute classes.
+		public override string[] ConditionalConditions ()
+		{
+			if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
+				return null;
+
+			caching_flags &= ~Flags.Excluded_Undetected;
+
+			if (OptAttributes == null)
+				return null;
+
+			Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
+			if (attrs == null)
+				return null;
+
+			string[] conditions = new string[attrs.Length];
+			for (int i = 0; i < conditions.Length; ++i)
+				conditions[i] = attrs[i].GetConditionalAttributeValue ();
+
+			caching_flags |= Flags.Excluded;
+			return conditions;
+		}
+	}
+
+	public sealed class Struct : ClassOrStruct
+	{
+		bool is_unmanaged, has_unmanaged_check_done;
+		bool InTransit;
+
+		// <summary>
+		//   Modifiers allowed in a struct declaration
+		// </summary>
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW       |
+			Modifiers.PUBLIC    |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL  |
+			Modifiers.UNSAFE    |
+			Modifiers.PRIVATE;
+
+		public Struct (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
+			: base (parent, name, attrs, MemberKind.Struct)
+		{
+			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;			
+			this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
+			spec = new TypeSpec (Kind, null, this, null, ModFlags);
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Struct;
+			}
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+
+			//
+			// When struct constains fixed fixed and struct layout has explicitly
+			// set CharSet, its value has to be propagated to compiler generated
+			// fixed types
+			//
+			if (a.Type == pa.StructLayout) {
+				var value = a.GetNamedValue ("CharSet");
+				if (value == null)
+					return;
+
+				for (int i = 0; i < Members.Count; ++i) {
+					FixedField ff = Members [i] as FixedField;
+					if (ff == null)
+						continue;
+
+					ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
+				}
+			}
+		}
+
+		bool CheckStructCycles ()
+		{
+			if (InTransit)
+				return false;
+
+			InTransit = true;
+			foreach (var member in Members) {
+				var field = member as Field;
+				if (field == null)
+					continue;
+
+				TypeSpec ftype = field.Spec.MemberType;
+				if (!ftype.IsStruct)
+					continue;
+
+				if (ftype is BuiltinTypeSpec)
+					continue;
+
+				foreach (var targ in ftype.TypeArguments) {
+					if (!CheckFieldTypeCycle (targ)) {
+						Report.Error (523, field.Location,
+							"Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
+							field.GetSignatureForError (), ftype.GetSignatureForError ());
+						break;
+					}
+				}
+
+				//
+				// Static fields of exactly same type are allowed
+				//
+				if (field.IsStatic && ftype == CurrentType)
+					continue;
+
+				if (!CheckFieldTypeCycle (ftype)) {
+					Report.Error (523, field.Location,
+						"Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
+						field.GetSignatureForError (), ftype.GetSignatureForError ());
+					break;
+				}
+			}
+
+			InTransit = false;
+			return true;
+		}
+
+		static bool CheckFieldTypeCycle (TypeSpec ts)
+		{
+			var fts = ts.MemberDefinition as Struct;
+			if (fts == null)
+				return true;
+
+			return fts.CheckStructCycles ();
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			if (PrimaryConstructorParameters != null)
+				generated_primary_constructor = DefineDefaultConstructor (false);
+
+			return base.DoDefineMembers ();
+		}
+
+		public override void Emit ()
+		{
+			CheckStructCycles ();
+
+			base.Emit ();
+		}
+
+		bool HasExplicitConstructor ()
+		{
+			foreach (var m in Members) {
+				var c = m as Constructor;
+				if (c == null)
+					continue;
+
+				if (!c.ParameterInfo.IsEmpty)
+					return true;
+			}
+
+			return false;
+		}
+
+		public override bool IsUnmanagedType ()
+		{
+			if (has_unmanaged_check_done)
+				return is_unmanaged;
+
+			if (requires_delayed_unmanagedtype_check)
+				return true;
+
+			var parent_def = Parent.PartialContainer;
+			if (parent_def != null && parent_def.IsGenericOrParentIsGeneric) {
+				has_unmanaged_check_done = true;
+				return false;
+			}
+
+			if (first_nonstatic_field != null) {
+				requires_delayed_unmanagedtype_check = true;
+
+				foreach (var member in Members) {
+					var f = member as Field;
+					if (f == null)
+						continue;
+
+					if (f.IsStatic)
+						continue;
+
+					// It can happen when recursive unmanaged types are defined
+					// struct S { S* s; }
+					TypeSpec mt = f.MemberType;
+					if (mt == null) {
+						return true;
+					}
+
+					if (mt.IsUnmanaged)
+						continue;
+
+					has_unmanaged_check_done = true;
+					return false;
+				}
+
+				has_unmanaged_check_done = true;
+			}
+
+			is_unmanaged = true;
+			return true;
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			var ifaces = base.ResolveBaseTypes (out base_class);
+			base_type = Compiler.BuiltinTypes.ValueType;
+			return ifaces;
+		}
+
+		public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
+		{
+			if ((field.ModFlags & Modifiers.STATIC) == 0 && !HasExplicitConstructor ()) {
+				Report.Error (8054, field.Location, "`{0}': Structs without explicit constructors cannot contain members with initializers",
+					field.GetSignatureForError ());
+
+				return;
+			}
+
+			base.RegisterFieldForInitialization (field, expression);
+		}
+	}
+
+	/// <summary>
+	///   Interfaces
+	/// </summary>
+	public sealed class Interface : TypeDefinition {
+
+		/// <summary>
+		///   Modifiers allowed in a class declaration
+		/// </summary>
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW       |
+			Modifiers.PUBLIC    |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL  |
+		 	Modifiers.UNSAFE    |
+			Modifiers.PRIVATE;
+
+		public Interface (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
+			: base (parent, name, attrs, MemberKind.Interface)
+		{
+			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+
+			this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
+			spec = new TypeSpec (Kind, null, this, null, ModFlags);
+		}
+
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Interface;
+			}
+		}
+
+		protected override TypeAttributes TypeAttr {
+			get {
+				const TypeAttributes DefaultTypeAttributes =
+					TypeAttributes.AutoLayout |
+					TypeAttributes.Abstract |
+					TypeAttributes.Interface;
+
+				return base.TypeAttr | DefaultTypeAttributes;
+			}
+		}
+
+		#endregion
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
+				a.Error_MissingGuidAttribute ();
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			if (iface_exprs != null) {
+				foreach (var iface in iface_exprs) {
+					if (iface.IsCLSCompliant ())
+						continue;
+
+					Report.SymbolRelatedToPreviousError (iface);
+					Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
+						GetSignatureForError (), iface.GetSignatureForError ());
+				}
+			}
+
+			return true;
+		}
+	}
+
+	public abstract class InterfaceMemberBase : MemberBase
+	{
+		//
+		// Common modifiers allowed in a class declaration
+		//
+		protected const Modifiers AllowedModifiersClass =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE |
+			Modifiers.STATIC |
+			Modifiers.VIRTUAL |
+			Modifiers.SEALED |
+			Modifiers.OVERRIDE |
+			Modifiers.ABSTRACT |
+			Modifiers.UNSAFE |
+			Modifiers.EXTERN;
+
+		//
+		// Common modifiers allowed in a struct declaration
+		//
+		protected const Modifiers AllowedModifiersStruct =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE |
+			Modifiers.STATIC |
+			Modifiers.OVERRIDE |
+			Modifiers.UNSAFE |
+			Modifiers.EXTERN;
+
+		//
+		// Common modifiers allowed in a interface declaration
+		//
+		protected const Modifiers AllowedModifiersInterface =
+			Modifiers.NEW |
+			Modifiers.UNSAFE;
+
+		//
+		// Whether this is an interface member.
+		//
+		public bool IsInterface;
+
+		//
+		// If true, this is an explicit interface implementation
+		//
+		public readonly bool IsExplicitImpl;
+
+		protected bool is_external_implementation;
+
+		//
+		// The interface type we are explicitly implementing
+		//
+		public TypeSpec InterfaceType;
+
+		//
+		// The method we're overriding if this is an override method.
+		//
+		protected MethodSpec base_method;
+
+		readonly Modifiers explicit_mod_flags;
+		public MethodAttributes flags;
+
+		protected InterfaceMemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
+			: base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs)
+		{
+			IsInterface = parent.Kind == MemberKind.Interface;
+			IsExplicitImpl = (MemberName.ExplicitInterface != null);
+			explicit_mod_flags = mod;
+		}
+
+		public abstract Variance ExpectedMemberTypeVariance { get; }
+		
+		protected override bool CheckBase ()
+		{
+			if (!base.CheckBase ())
+				return false;
+
+			if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+				CheckForDuplications ();
+			
+			if (IsExplicitImpl)
+				return true;
+
+			// For System.Object only
+			if (Parent.BaseType == null)
+				return true;
+
+			MemberSpec candidate;
+			bool overrides = false;
+			var base_member = FindBaseMember (out candidate, ref overrides);
+
+			if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+				if (base_member == null) {
+					if (candidate == null) {
+						if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
+							Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
+								"object.Finalize()");
+						} else {
+							Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
+								GetSignatureForError (), SimpleName.GetMemberType (this));
+						}
+					} else {
+						Report.SymbolRelatedToPreviousError (candidate);
+						if (this is Event)
+							Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
+								GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
+						else if (this is PropertyBase)
+							Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
+								GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
+						else
+							Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
+								GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
+					}
+
+					return false;
+				}
+
+				//
+				// Handles ambiguous overrides
+				//
+				if (candidate != null) {
+					Report.SymbolRelatedToPreviousError (candidate);
+					Report.SymbolRelatedToPreviousError (base_member);
+
+					// Get member definition for error reporting
+					var m1 = MemberCache.GetMember (base_member.DeclaringType.GetDefinition (), base_member);
+					var m2 = MemberCache.GetMember (candidate.DeclaringType.GetDefinition (), candidate);
+
+					Report.Error (462, Location,
+						"`{0}' cannot override inherited members `{1}' and `{2}' because they have the same signature when used in type `{3}'",
+						GetSignatureForError (), m1.GetSignatureForError (), m2.GetSignatureForError (), Parent.GetSignatureForError ());
+				}
+
+				if (!CheckOverrideAgainstBase (base_member))
+					return false;
+
+				ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
+				if (oa != null) {
+					if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
+						Report.SymbolRelatedToPreviousError (base_member);
+						Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
+							GetSignatureForError (), base_member.GetSignatureForError ());
+					}
+				} else {
+					if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
+						Report.SymbolRelatedToPreviousError (base_member);
+						Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
+							GetSignatureForError (), base_member.GetSignatureForError ());
+					}
+				}
+
+				base_method = base_member as MethodSpec;
+				return true;
+			}
+
+			if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
+				base_member = candidate;
+
+			if (base_member == null) {
+				if ((ModFlags & Modifiers.NEW) != 0) {
+					if (base_member == null) {
+						Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
+							GetSignatureForError ());
+					}
+				}
+			} else {
+				if ((ModFlags & Modifiers.NEW) == 0) {
+					ModFlags |= Modifiers.NEW;
+					if (!IsCompilerGenerated) {
+						Report.SymbolRelatedToPreviousError (base_member);
+						if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
+							Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
+								GetSignatureForError (), base_member.GetSignatureForError ());
+						} else {
+							Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+								GetSignatureForError (), base_member.GetSignatureForError ());
+						}
+					}
+				}
+
+				if (!IsInterface && base_member.IsAbstract && !overrides && !IsStatic) {
+					Report.SymbolRelatedToPreviousError (base_member);
+					Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
+						GetSignatureForError (), base_member.GetSignatureForError ());
+				}
+			}
+
+			return true;
+		}
+
+		protected virtual bool CheckForDuplications ()
+		{
+			return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
+		}
+
+		//
+		// Performs various checks on the MethodInfo `mb' regarding the modifier flags
+		// that have been defined.
+		//
+		protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
+		{
+			bool ok = true;
+
+			if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
+				Report.SymbolRelatedToPreviousError (base_member);
+				Report.Error (506, Location,
+					"`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
+					 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
+				ok = false;
+			}
+
+			// Now we check that the overriden method is not final	
+			if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
+				Report.SymbolRelatedToPreviousError (base_member);
+				Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
+							  GetSignatureForError (), TypeManager.CSharpSignature (base_member));
+				ok = false;
+			}
+
+			var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
+			if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
+				Report.SymbolRelatedToPreviousError (base_member);
+				if (this is PropertyBasedMember) {
+					Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
+						GetSignatureForError (), base_member_type.GetSignatureForError (), base_member.GetSignatureForError ());
+				} else {
+					Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
+						GetSignatureForError (), base_member_type.GetSignatureForError (), base_member.GetSignatureForError ());
+				}
+				ok = false;
+			}
+
+			return ok;
+		}
+
+		protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
+		{
+			var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
+			var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
+
+			if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
+				//
+				// It must be at least "protected"
+				//
+				if ((thisp & Modifiers.PROTECTED) == 0) {
+					return false;
+				}
+
+				//
+				// when overriding protected internal, the method can be declared
+				// protected internal only within the same assembly or assembly
+				// which has InternalsVisibleTo
+				//
+				if ((thisp & Modifiers.INTERNAL) != 0) {
+					return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
+				}
+
+				//
+				// protected overriding protected internal inside same assembly
+				// requires internal modifier as well
+				//
+				if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) {
+					return false;
+				}
+
+				return true;
+			}
+
+			return thisp == base_classp;
+		}
+
+		public override bool Define ()
+		{
+			if (IsInterface) {
+				ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
+					Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
+
+				flags = MethodAttributes.Public |
+					MethodAttributes.Abstract |
+					MethodAttributes.HideBySig |
+					MethodAttributes.NewSlot |
+					MethodAttributes.Virtual;
+			} else {
+				Parent.PartialContainer.MethodModifiersValid (this);
+
+				flags = ModifiersExtensions.MethodAttr (ModFlags);
+			}
+
+			if (IsExplicitImpl) {
+				InterfaceType = MemberName.ExplicitInterface.ResolveAsType (Parent);
+				if (InterfaceType == null)
+					return false;
+
+				if ((ModFlags & Modifiers.PARTIAL) != 0) {
+					Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
+						GetSignatureForError ());
+				}
+
+				if (!InterfaceType.IsInterface) {
+					Report.SymbolRelatedToPreviousError (InterfaceType);
+					Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
+						InterfaceType.GetSignatureForError ());
+				} else {
+					Parent.PartialContainer.VerifyImplements (this);
+				}
+
+				Modifiers allowed_explicit = Modifiers.AllowedExplicitImplFlags;
+				if (this is Method)
+					allowed_explicit |= Modifiers.ASYNC;
+
+				ModifiersExtensions.Check (allowed_explicit, explicit_mod_flags, 0, Location, Report);
+			}
+
+			return base.Define ();
+		}
+
+		protected bool DefineParameters (ParametersCompiled parameters)
+		{
+			if (!parameters.Resolve (this))
+				return false;
+
+			bool error = false;
+			for (int i = 0; i < parameters.Count; ++i) {
+				Parameter p = parameters [i];
+
+				if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
+					p.Warning_UselessOptionalParameter (Report);
+
+				if (p.CheckAccessibility (this))
+					continue;
+
+				TypeSpec t = parameters.Types [i];
+				Report.SymbolRelatedToPreviousError (t);
+				if (this is Indexer)
+					Report.Error (55, Location,
+						      "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
+						      t.GetSignatureForError (), GetSignatureForError ());
+				else if (this is Operator)
+					Report.Error (57, Location,
+						      "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
+						      t.GetSignatureForError (), GetSignatureForError ());
+				else
+					Report.Error (51, Location,
+						"Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
+						t.GetSignatureForError (), GetSignatureForError ());
+				error = true;
+			}
+			return !error;
+		}
+
+		protected override void DoMemberTypeDependentChecks ()
+		{
+			base.DoMemberTypeDependentChecks ();
+
+			VarianceDecl.CheckTypeVariance (MemberType, ExpectedMemberTypeVariance, this);
+		}
+
+		public override void Emit()
+		{
+			// for extern static method must be specified either DllImport attribute or MethodImplAttribute.
+			// We are more strict than csc and report this as an error because SRE does not allow emit that
+			if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation && (OptAttributes == null || !OptAttributes.HasResolveError ())) {
+				if (this is Constructor) {
+					Report.Warning (824, 1, Location,
+						"Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
+				} else {
+					Report.Warning (626, 1, Location,
+						"`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
+						GetSignatureForError ());
+				}
+			}
+
+			base.Emit ();
+		}
+
+		public override bool EnableOverloadChecks (MemberCore overload)
+		{
+			//
+			// Two members can differ in their explicit interface
+			// type parameter only
+			//
+			InterfaceMemberBase imb = overload as InterfaceMemberBase;
+			if (imb != null && imb.IsExplicitImpl) {
+				if (IsExplicitImpl) {
+					caching_flags |= Flags.MethodOverloadsExist;
+				}
+				return true;
+			}
+
+			return IsExplicitImpl;
+		}
+
+		protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
+		{
+			var base_modifiers = base_member.Modifiers;
+
+			// Remove internal modifier from types which are not internally accessible
+			if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) &&
+				!base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
+				base_modifiers = Modifiers.PROTECTED;
+
+			Report.SymbolRelatedToPreviousError (base_member);
+			Report.Error (507, member.Location,
+				"`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
+				member.GetSignatureForError (),
+				ModifiersExtensions.AccessibilityName (base_modifiers),
+				base_member.GetSignatureForError ());
+		}
+
+		protected void Error_StaticReturnType ()
+		{
+			Report.Error (722, Location,
+				"`{0}': static types cannot be used as return types",
+				MemberType.GetSignatureForError ());
+		}
+
+		/// <summary>
+		/// Gets base method and its return type
+		/// </summary>
+		protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
+		{
+			return MemberCache.FindBaseMember (this, out bestCandidate, ref overrides);
+		}
+
+		//
+		// The "short" name of this property / indexer / event.  This is the
+		// name without the explicit interface.
+		//
+		public string ShortName {
+			get { return MemberName.Name; }
+		}
+		
+		//
+		// Returns full metadata method name
+		//
+		public string GetFullName (MemberName name)
+		{
+			return GetFullName (name.Name);
+		}
+
+		public string GetFullName (string name)
+		{
+			if (!IsExplicitImpl)
+				return name;
+
+			//
+			// When dealing with explicit members a full interface type
+			// name is added to member name to avoid possible name conflicts
+			//
+			// We use CSharpName which gets us full name with benefit of
+			// replacing predefined names which saves some space and name
+			// is still unique
+			//
+			return InterfaceType.GetSignatureForError () + "." + name;
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			if (IsExplicitImpl)
+				return Parent.GetSignatureForDocumentation () + "." + InterfaceType.GetExplicitNameSignatureForDocumentation () + "#" + ShortName;
+
+			return Parent.GetSignatureForDocumentation () + "." + ShortName;
+		}
+
+		public override bool IsUsed 
+		{
+			get { return IsExplicitImpl || base.IsUsed; }
+		}
+
+		public override void SetConstraints (List<Constraints> constraints_list)
+		{
+			if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
+				Report.Error (460, Location,
+					"`{0}': Cannot specify constraints for overrides and explicit interface implementation methods",
+					GetSignatureForError ());
+			}
+
+			base.SetConstraints (constraints_list);
+		}
+	}
+
+	public abstract class MemberBase : MemberCore
+	{
+		protected FullNamedExpression type_expr;
+		protected TypeSpec member_type;
+		public new TypeDefinition Parent;
+
+		protected MemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod, MemberName name, Attributes attrs)
+			: base (parent, name, attrs)
+		{
+			this.Parent = parent;
+			this.type_expr = type;
+
+			if (name != MemberName.Null)
+				ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
+		}
+
+		#region Properties
+
+		public TypeSpec MemberType {
+			get {
+				return member_type;
+			}
+		}
+
+		public FullNamedExpression TypeExpression {
+			get {
+				return type_expr;
+			}
+		}
+
+		#endregion
+
+		//
+		// Main member define entry
+		//
+		public override bool Define ()
+		{
+			DoMemberTypeIndependentChecks ();
+
+			//
+			// Returns false only when type resolution failed
+			//
+			if (!ResolveMemberType ())
+				return false;
+
+			DoMemberTypeDependentChecks ();
+			return true;
+		}
+
+		//
+		// Any type_name independent checks
+		//
+		protected virtual void DoMemberTypeIndependentChecks ()
+		{
+			if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
+				(ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
+				Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
+					GetSignatureForError (), Parent.GetSignatureForError ());
+			}
+		}
+
+		//
+		// Any type_name dependent checks
+		//
+		protected virtual void DoMemberTypeDependentChecks ()
+		{
+			// verify accessibility
+			if (!IsAccessibleAs (MemberType)) {
+				Report.SymbolRelatedToPreviousError (MemberType);
+				if (this is Property)
+					Report.Error (53, Location,
+						"Inconsistent accessibility: property type `" +
+						MemberType.GetSignatureForError () + "' is less " +
+						"accessible than property `" + GetSignatureForError () + "'");
+				else if (this is Indexer)
+					Report.Error (54, Location,
+						"Inconsistent accessibility: indexer return type `" +
+						MemberType.GetSignatureForError () + "' is less " +
+						"accessible than indexer `" + GetSignatureForError () + "'");
+				else if (this is MethodCore) {
+					if (this is Operator)
+						Report.Error (56, Location,
+							"Inconsistent accessibility: return type `" +
+							MemberType.GetSignatureForError () + "' is less " +
+							"accessible than operator `" + GetSignatureForError () + "'");
+					else
+						Report.Error (50, Location,
+							"Inconsistent accessibility: return type `" +
+							MemberType.GetSignatureForError () + "' is less " +
+							"accessible than method `" + GetSignatureForError () + "'");
+				} else if (this is Event) {
+					Report.Error (7025, Location,
+						"Inconsistent accessibility: event type `{0}' is less accessible than event `{1}'",
+						MemberType.GetSignatureForError (), GetSignatureForError ());
+				} else {
+					Report.Error (52, Location,
+						      "Inconsistent accessibility: field type `" +
+						      MemberType.GetSignatureForError () + "' is less " +
+						      "accessible than field `" + GetSignatureForError () + "'");
+				}
+			}
+		}
+
+		protected void IsTypePermitted ()
+		{
+			if (MemberType.IsSpecialRuntimeType) {
+				if (Parent is StateMachine) {
+					Report.Error (4012, Location,
+						"Parameters or local variables of type `{0}' cannot be declared in async methods or iterators",
+						MemberType.GetSignatureForError ());
+				} else if (Parent is HoistedStoreyClass) {
+					Report.Error (4013, Location,
+						"Local variables of type `{0}' cannot be used inside anonymous methods, lambda expressions or query expressions",
+						MemberType.GetSignatureForError ());
+				} else {
+					Report.Error (610, Location, 
+						"Field or property cannot be of type `{0}'", MemberType.GetSignatureForError ());
+				}
+			}
+		}
+
+		protected virtual bool CheckBase ()
+		{
+			CheckProtectedModifier ();
+
+			return true;
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			return Parent.GetSignatureForDocumentation () + "." + MemberName.Basename;
+		}
+
+		protected virtual bool ResolveMemberType ()
+		{
+			if (member_type != null)
+				throw new InternalErrorException ("Multi-resolve");
+
+			member_type = type_expr.ResolveAsType (this);
+			return member_type != null;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/codegen.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/codegen.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/codegen.cs	(revision 11807)
@@ -0,0 +1,1365 @@
+//
+// codegen.cs: The code generator
+//
+// Authors:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2004 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	/// <summary>
+	///   An Emit Context is created for each body of code (from methods,
+	///   properties bodies, indexer bodies or constructor bodies)
+	/// </summary>
+	public class EmitContext : BuilderContext
+	{
+		// TODO: Has to be private
+		public readonly ILGenerator ig;
+
+		/// <summary>
+		///   The value that is allowed to be returned or NULL if there is no
+		///   return type.
+		/// </summary>
+		readonly TypeSpec return_type;
+
+		/// <summary>
+		///   Keeps track of the Type to LocalBuilder temporary storage created
+		///   to store structures (used to compute the address of the structure
+		///   value on structure method invocations)
+		/// </summary>
+		Dictionary<TypeSpec, object> temporary_storage;
+
+		/// <summary>
+		///   The location where we store the return value.
+		/// </summary>
+		public LocalBuilder return_value;
+
+
+		/// <summary>
+		///   Current loop begin and end labels.
+		/// </summary>
+		public Label LoopBegin, LoopEnd;
+
+		/// <summary>
+		///   Default target in a switch statement.   Only valid if
+		///   InSwitch is true
+		/// </summary>
+		public Label DefaultTarget;
+
+		/// <summary>
+		///   If this is non-null, points to the current switch statement
+		/// </summary>
+		public Switch Switch;
+
+		/// <summary>
+		///  Whether we are inside an anonymous method.
+		/// </summary>
+		public AnonymousExpression CurrentAnonymousMethod;
+		
+		readonly IMemberContext member_context;
+
+		readonly SourceMethodBuilder methodSymbols;
+
+		DynamicSiteClass dynamic_site_container;
+
+		Label? return_label;
+
+		List<IExpressionCleanup> epilogue_expressions;
+
+		public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type, SourceMethodBuilder methodSymbols)
+		{
+			this.member_context = rc;
+			this.ig = ig;
+			this.return_type = return_type;
+
+			if (rc.Module.Compiler.Settings.Checked)
+				flags |= Options.CheckedScope;
+
+			if (methodSymbols != null) {
+				this.methodSymbols = methodSymbols;
+				if (!rc.Module.Compiler.Settings.Optimize)
+					flags |= Options.AccurateDebugInfo;
+			} else {
+				flags |= Options.OmitDebugInfo;
+			}
+
+#if STATIC
+			ig.__CleverExceptionBlockAssistance ();
+#endif
+		}
+
+		#region Properties
+
+		internal AsyncTaskStorey AsyncTaskStorey {
+			get {
+				return CurrentAnonymousMethod.Storey as AsyncTaskStorey;
+			}
+		}
+
+		public BuiltinTypes BuiltinTypes {
+			get {
+				return MemberContext.Module.Compiler.BuiltinTypes;
+			}
+		}
+
+		public ConditionalAccessContext ConditionalAccess { get; set; }
+
+		public TypeSpec CurrentType {
+			get { return member_context.CurrentType; }
+		}
+
+		public TypeParameters CurrentTypeParameters {
+		    get { return member_context.CurrentTypeParameters; }
+		}
+
+		public MemberCore CurrentTypeDefinition {
+			get { return member_context.CurrentMemberDefinition; }
+		}
+
+		public bool EmitAccurateDebugInfo {
+			get {
+				return (flags & Options.AccurateDebugInfo) != 0;
+			}
+		}
+
+		public bool HasMethodSymbolBuilder {
+			get {
+				return methodSymbols != null;
+			}
+		}
+
+		public bool HasReturnLabel {
+			get {
+				return return_label.HasValue;
+			}
+		}
+
+		public bool IsStatic {
+			get { return member_context.IsStatic; }
+		}
+
+		public bool IsStaticConstructor {
+			get {
+				return member_context.IsStatic && (flags & Options.ConstructorScope) != 0;
+			}
+		}
+
+		public bool IsAnonymousStoreyMutateRequired {
+			get {
+				return CurrentAnonymousMethod != null &&
+					CurrentAnonymousMethod.Storey != null &&
+					CurrentAnonymousMethod.Storey.Mutator != null;
+			}
+		}
+
+		public IMemberContext MemberContext {
+			get {
+				return member_context;
+			}
+		}
+
+		public ModuleContainer Module {
+			get {
+				return member_context.Module;
+			}
+		}
+
+		public bool NotifyEvaluatorOnStore {
+			get {
+				return Module.Evaluator != null && Module.Evaluator.ModificationListener != null;
+			}
+		}
+
+		// Has to be used for specific emitter errors only any
+		// possible resolver errors have to be reported during Resolve
+		public Report Report {
+			get {
+				return member_context.Module.Compiler.Report;
+			}
+		}
+
+		public TypeSpec ReturnType {
+			get {
+				return return_type;
+			}
+		}
+
+		//
+		// The label where we have to jump before leaving the context
+		//
+		public Label ReturnLabel {
+			get {
+				return return_label.Value;
+			}
+		}
+
+		public List<IExpressionCleanup> StatementEpilogue {
+			get {
+				return epilogue_expressions;
+			}
+		}
+
+		public LocalVariable AsyncThrowVariable { get; set; }
+
+		public List<TryFinally> TryFinallyUnwind { get; set; }
+
+		#endregion
+
+		public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
+		{
+			if (epilogue_expressions == null) {
+				epilogue_expressions = new List<IExpressionCleanup> ();
+			} else if (epilogue_expressions.Contains (cleanupExpression)) {
+				return;
+			}
+
+			epilogue_expressions.Add (cleanupExpression);
+		}
+
+		public void AssertEmptyStack ()
+		{
+#if STATIC
+			if (ig.__StackHeight != 0)
+				throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
+					member_context.GetSignatureForError ());
+#endif
+		}
+
+		/// <summary>
+		///   This is called immediately before emitting an IL opcode to tell the symbol
+		///   writer to which source line this opcode belongs.
+		/// </summary>
+		public bool Mark (Location loc)
+		{
+			if ((flags & Options.OmitDebugInfo) != 0)
+				return false;
+
+			if (loc.IsNull || methodSymbols == null)
+				return false;
+
+			var sf = loc.SourceFile;
+			if (sf.IsHiddenLocation (loc))
+				return false;
+
+#if NET_4_0
+			methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
+#endif
+			return true;
+		}
+
+		public void MarkCallEntry (Location loc)
+		{
+			if (!EmitAccurateDebugInfo)
+				return;
+
+			//
+			// TODO: This should emit different kind of sequence point to make
+			// step-over work for statement over multiple lines
+			//
+			// Debugging experience for Foo (A () + B ()) where A and B are
+			// on separate lines is not great
+			//
+			Mark (loc);
+		}
+
+		public void DefineLocalVariable (string name, LocalBuilder builder)
+		{
+			if ((flags & Options.OmitDebugInfo) != 0)
+				return;
+
+			methodSymbols.AddLocal (builder.LocalIndex, name);
+		}
+
+		public void BeginCatchBlock (TypeSpec type)
+		{
+			if (IsAnonymousStoreyMutateRequired)
+				type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+			ig.BeginCatchBlock (type.GetMetaInfo ());
+		}
+
+		public void BeginFilterHandler ()
+		{
+			ig.BeginCatchBlock (null);
+		}
+
+		public void BeginExceptionBlock ()
+		{
+			ig.BeginExceptionBlock ();
+		}
+
+		public void BeginExceptionFilterBlock ()
+		{
+			ig.BeginExceptFilterBlock ();
+		}
+
+		public void BeginFinallyBlock ()
+		{
+			ig.BeginFinallyBlock ();
+		}
+
+		public void BeginScope ()
+		{
+			if ((flags & Options.OmitDebugInfo) != 0)
+				return;
+
+#if NET_4_0
+			methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
+#endif
+		}
+
+		public void BeginCompilerScope ()
+		{
+			if ((flags & Options.OmitDebugInfo) != 0)
+				return;
+
+#if NET_4_0
+			methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
+#endif
+		}
+
+		public void EndExceptionBlock ()
+		{
+			ig.EndExceptionBlock ();
+		}
+
+		public void EndScope ()
+		{
+			if ((flags & Options.OmitDebugInfo) != 0)
+				return;
+
+#if NET_4_0
+			methodSymbols.EndBlock (ig.ILOffset);
+#endif
+		}
+
+		public void CloseConditionalAccess (TypeSpec type)
+		{
+			if (type != null)
+				Emit (OpCodes.Newobj, Nullable.NullableInfo.GetConstructor (type));
+
+			MarkLabel (ConditionalAccess.EndLabel);
+			ConditionalAccess = null;
+		}
+
+		//
+		// Creates a nested container in this context for all dynamic compiler generated stuff
+		//
+		internal DynamicSiteClass CreateDynamicSite ()
+		{
+			if (dynamic_site_container == null) {
+				var mc = member_context.CurrentMemberDefinition as MemberBase;
+				dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
+
+				CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
+				dynamic_site_container.CreateContainer ();
+				dynamic_site_container.DefineContainer ();
+				dynamic_site_container.Define ();
+
+				var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
+				var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
+				CurrentType.MemberCache.AddMember (inflated);
+			}
+
+			return dynamic_site_container;
+		}
+
+		public Label CreateReturnLabel ()
+		{
+			if (!return_label.HasValue)
+				return_label = DefineLabel ();
+
+			return return_label.Value;
+		}
+
+		public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
+		{
+			if (IsAnonymousStoreyMutateRequired)
+				type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+			return ig.DeclareLocal (type.GetMetaInfo (), pinned);
+		}
+
+		public Label DefineLabel ()
+		{
+			return ig.DefineLabel ();
+		}
+
+		//
+		// Creates temporary field in current async storey
+		//
+		public StackFieldExpr GetTemporaryField (TypeSpec type, bool initializedFieldRequired = false)
+		{
+			var f = AsyncTaskStorey.AddCapturedLocalVariable (type, initializedFieldRequired);
+			var fexpr = new StackFieldExpr (f);
+			fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
+			return fexpr;
+		}
+
+		public void MarkLabel (Label label)
+		{
+			ig.MarkLabel (label);
+		}
+
+		public void Emit (OpCode opcode)
+		{
+			ig.Emit (opcode);
+		}
+
+		public void Emit (OpCode opcode, LocalBuilder local)
+		{
+			ig.Emit (opcode, local);
+		}
+
+		public void Emit (OpCode opcode, string arg)
+		{
+			ig.Emit (opcode, arg);
+		}
+
+		public void Emit (OpCode opcode, double arg)
+		{
+			ig.Emit (opcode, arg);
+		}
+
+		public void Emit (OpCode opcode, float arg)
+		{
+			ig.Emit (opcode, arg);
+		}
+
+		public void Emit (OpCode opcode, Label label)
+		{
+			ig.Emit (opcode, label);
+		}
+
+		public void Emit (OpCode opcode, Label[] labels)
+		{
+			ig.Emit (opcode, labels);
+		}
+
+		public void Emit (OpCode opcode, TypeSpec type)
+		{
+			if (IsAnonymousStoreyMutateRequired)
+				type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+			ig.Emit (opcode, type.GetMetaInfo ());
+		}
+
+		public void Emit (OpCode opcode, FieldSpec field)
+		{
+			if (IsAnonymousStoreyMutateRequired)
+				field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+			ig.Emit (opcode, field.GetMetaInfo ());
+		}
+
+		public void Emit (OpCode opcode, MethodSpec method)
+		{
+			if (IsAnonymousStoreyMutateRequired)
+				method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+			if (method.IsConstructor)
+				ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
+			else
+				ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
+		}
+
+		// TODO: REMOVE breaks mutator
+		public void Emit (OpCode opcode, MethodInfo method)
+		{
+			ig.Emit (opcode, method);
+		}
+
+		public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
+		{
+			// TODO MemberCache: This should mutate too
+			ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
+		}
+
+		public void EmitArrayNew (ArrayContainer ac)
+		{
+			if (ac.Rank == 1) {
+				var type = IsAnonymousStoreyMutateRequired ?
+					CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
+					ac.Element;
+
+				ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
+			} else {
+				if (IsAnonymousStoreyMutateRequired)
+					ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+				ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
+			}
+		}
+
+		public void EmitArrayAddress (ArrayContainer ac)
+		{
+			if (ac.Rank > 1) {
+				if (IsAnonymousStoreyMutateRequired)
+					ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+				ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
+			} else {
+				var type = IsAnonymousStoreyMutateRequired ?
+					CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
+					ac.Element;
+
+				ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
+			}
+		}
+
+		//
+		// Emits the right opcode to load from an array
+		//
+		public void EmitArrayLoad (ArrayContainer ac)
+		{
+			if (ac.Rank > 1) {
+				if (IsAnonymousStoreyMutateRequired)
+					ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+				ig.Emit (OpCodes.Call, ac.GetGetMethod ());
+				return;
+			}
+
+
+			var type = ac.Element;
+			if (type.Kind == MemberKind.Enum)
+				type = EnumSpec.GetUnderlyingType (type);
+
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Bool:
+				//
+				// Workaround MSIL limitation. Load bool element as single bit,
+				// bool array can actually store any byte value
+				//
+				ig.Emit (OpCodes.Ldelem_U1);
+				ig.Emit (OpCodes.Ldc_I4_0);
+				ig.Emit (OpCodes.Cgt_Un);
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				ig.Emit (OpCodes.Ldelem_U1);
+				break;
+			case BuiltinTypeSpec.Type.SByte:
+				ig.Emit (OpCodes.Ldelem_I1);
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				ig.Emit (OpCodes.Ldelem_I2);
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Char:
+				ig.Emit (OpCodes.Ldelem_U2);
+				break;
+			case BuiltinTypeSpec.Type.Int:
+				ig.Emit (OpCodes.Ldelem_I4);
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				ig.Emit (OpCodes.Ldelem_U4);
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.Long:
+				ig.Emit (OpCodes.Ldelem_I8);
+				break;
+			case BuiltinTypeSpec.Type.Float:
+				ig.Emit (OpCodes.Ldelem_R4);
+				break;
+			case BuiltinTypeSpec.Type.Double:
+				ig.Emit (OpCodes.Ldelem_R8);
+				break;
+			case BuiltinTypeSpec.Type.IntPtr:
+				ig.Emit (OpCodes.Ldelem_I);
+				break;
+			default:
+				switch (type.Kind) {
+				case MemberKind.Struct:
+					if (IsAnonymousStoreyMutateRequired)
+						type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+					ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
+					ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
+					break;
+				case MemberKind.TypeParameter:
+					if (IsAnonymousStoreyMutateRequired)
+						type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+					ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
+					break;
+				case MemberKind.PointerType:
+					ig.Emit (OpCodes.Ldelem_I);
+					break;
+				default:
+					ig.Emit (OpCodes.Ldelem_Ref);
+					break;
+				}
+				break;
+			}
+		}
+
+		//
+		// Emits the right opcode to store to an array
+		//
+		public void EmitArrayStore (ArrayContainer ac)
+		{
+			if (ac.Rank > 1) {
+				if (IsAnonymousStoreyMutateRequired)
+					ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+				ig.Emit (OpCodes.Call, ac.GetSetMethod ());
+				return;
+			}
+
+			var type = ac.Element;
+
+			if (type.Kind == MemberKind.Enum)
+				type = EnumSpec.GetUnderlyingType (type);
+
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Bool:
+				Emit (OpCodes.Stelem_I1);
+				return;
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Char:
+				Emit (OpCodes.Stelem_I2);
+				return;
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+				Emit (OpCodes.Stelem_I4);
+				return;
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.ULong:
+				Emit (OpCodes.Stelem_I8);
+				return;
+			case BuiltinTypeSpec.Type.Float:
+				Emit (OpCodes.Stelem_R4);
+				return;
+			case BuiltinTypeSpec.Type.Double:
+				Emit (OpCodes.Stelem_R8);
+				return;
+			}
+
+			switch (type.Kind) {
+			case MemberKind.Struct:
+				Emit (OpCodes.Stobj, type);
+				break;
+			case MemberKind.TypeParameter:
+				Emit (OpCodes.Stelem, type);
+				break;
+			case MemberKind.PointerType:
+				Emit (OpCodes.Stelem_I);
+				break;
+			default:
+				Emit (OpCodes.Stelem_Ref);
+				break;
+			}
+		}
+
+		public void EmitInt (int i)
+		{
+			EmitIntConstant (i);
+		}
+
+		void EmitIntConstant (int i)
+		{
+			switch (i) {
+			case -1:
+				ig.Emit (OpCodes.Ldc_I4_M1);
+				break;
+
+			case 0:
+				ig.Emit (OpCodes.Ldc_I4_0);
+				break;
+
+			case 1:
+				ig.Emit (OpCodes.Ldc_I4_1);
+				break;
+
+			case 2:
+				ig.Emit (OpCodes.Ldc_I4_2);
+				break;
+
+			case 3:
+				ig.Emit (OpCodes.Ldc_I4_3);
+				break;
+
+			case 4:
+				ig.Emit (OpCodes.Ldc_I4_4);
+				break;
+
+			case 5:
+				ig.Emit (OpCodes.Ldc_I4_5);
+				break;
+
+			case 6:
+				ig.Emit (OpCodes.Ldc_I4_6);
+				break;
+
+			case 7:
+				ig.Emit (OpCodes.Ldc_I4_7);
+				break;
+
+			case 8:
+				ig.Emit (OpCodes.Ldc_I4_8);
+				break;
+
+			default:
+				if (i >= -128 && i <= 127) {
+					ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
+				} else
+					ig.Emit (OpCodes.Ldc_I4, i);
+				break;
+			}
+		}
+
+		public void EmitLong (long l)
+		{
+			if (l >= int.MinValue && l <= int.MaxValue) {
+				EmitIntConstant (unchecked ((int) l));
+				ig.Emit (OpCodes.Conv_I8);
+			} else if (l >= 0 && l <= uint.MaxValue) {
+				EmitIntConstant (unchecked ((int) l));
+				ig.Emit (OpCodes.Conv_U8);
+			} else {
+				ig.Emit (OpCodes.Ldc_I8, l);
+			}
+		}
+
+		//
+		// Load the object from the pointer.  
+		//
+		public void EmitLoadFromPtr (TypeSpec type)
+		{
+			if (type.Kind == MemberKind.Enum)
+				type = EnumSpec.GetUnderlyingType (type);
+
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+				ig.Emit (OpCodes.Ldind_I4);
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				ig.Emit (OpCodes.Ldind_U4);
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				ig.Emit (OpCodes.Ldind_I2);
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Char:
+				ig.Emit (OpCodes.Ldind_U2);
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				ig.Emit (OpCodes.Ldind_U1);
+				break;
+			case BuiltinTypeSpec.Type.SByte:
+				ig.Emit (OpCodes.Ldind_I1);
+				break;
+			case BuiltinTypeSpec.Type.Bool:
+				ig.Emit (OpCodes.Ldind_I1);
+				ig.Emit (OpCodes.Ldc_I4_0);
+				ig.Emit (OpCodes.Cgt_Un);
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.Long:
+				ig.Emit (OpCodes.Ldind_I8);
+				break;
+			case BuiltinTypeSpec.Type.Float:
+				ig.Emit (OpCodes.Ldind_R4);
+				break;
+			case BuiltinTypeSpec.Type.Double:
+				ig.Emit (OpCodes.Ldind_R8);
+				break;
+			case BuiltinTypeSpec.Type.IntPtr:
+				ig.Emit (OpCodes.Ldind_I);
+				break;
+			default:
+				switch (type.Kind) {
+				case MemberKind.Struct:
+				case MemberKind.TypeParameter:
+					if (IsAnonymousStoreyMutateRequired)
+						type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+					ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
+					break;
+				case MemberKind.PointerType:
+					ig.Emit (OpCodes.Ldind_I);
+					break;
+				default:
+					ig.Emit (OpCodes.Ldind_Ref);
+					break;
+				}
+				break;
+			}
+		}
+
+		public void EmitNull ()
+		{
+			ig.Emit (OpCodes.Ldnull);
+		}
+
+		public void EmitArgumentAddress (int pos)
+		{
+			if (!IsStatic)
+				++pos;
+
+			if (pos > byte.MaxValue)
+				ig.Emit (OpCodes.Ldarga, pos);
+			else
+				ig.Emit (OpCodes.Ldarga_S, (byte) pos);
+		}
+
+		public void EmitArgumentLoad (int pos)
+		{
+			if (!IsStatic)
+				++pos;
+
+			switch (pos) {
+			case 0: ig.Emit (OpCodes.Ldarg_0); break;
+			case 1: ig.Emit (OpCodes.Ldarg_1); break;
+			case 2: ig.Emit (OpCodes.Ldarg_2); break;
+			case 3: ig.Emit (OpCodes.Ldarg_3); break;
+			default:
+				if (pos > byte.MaxValue)
+					ig.Emit (OpCodes.Ldarg, pos);
+				else
+					ig.Emit (OpCodes.Ldarg_S, (byte) pos);
+				break;
+			}
+		}
+
+		public void EmitArgumentStore (int pos)
+		{
+			if (!IsStatic)
+				++pos;
+
+			if (pos > byte.MaxValue)
+				ig.Emit (OpCodes.Starg, pos);
+			else
+				ig.Emit (OpCodes.Starg_S, (byte) pos);
+		}
+
+		//
+		// The stack contains the pointer and the value of type `type'
+		//
+		public void EmitStoreFromPtr (TypeSpec type)
+		{
+			if (type.IsEnum)
+				type = EnumSpec.GetUnderlyingType (type);
+
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+				ig.Emit (OpCodes.Stind_I4);
+				return;
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.ULong:
+				ig.Emit (OpCodes.Stind_I8);
+				return;
+			case BuiltinTypeSpec.Type.Char:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+				ig.Emit (OpCodes.Stind_I2);
+				return;
+			case BuiltinTypeSpec.Type.Float:
+				ig.Emit (OpCodes.Stind_R4);
+				return;
+			case BuiltinTypeSpec.Type.Double:
+				ig.Emit (OpCodes.Stind_R8);
+				return;
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Bool:
+				ig.Emit (OpCodes.Stind_I1);
+				return;
+			case BuiltinTypeSpec.Type.IntPtr:
+				ig.Emit (OpCodes.Stind_I);
+				return;
+			}
+
+			switch (type.Kind) {
+			case MemberKind.Struct:
+			case MemberKind.TypeParameter:
+				if (IsAnonymousStoreyMutateRequired)
+					type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+				ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
+				break;
+			default:
+				ig.Emit (OpCodes.Stind_Ref);
+				break;
+			}
+		}
+
+		public void EmitThis ()
+		{
+			ig.Emit (OpCodes.Ldarg_0);
+		}
+
+		public void EmitEpilogue ()
+		{
+			if (epilogue_expressions == null)
+				return;
+
+			foreach (var e in epilogue_expressions)
+				e.EmitCleanup (this);
+
+			epilogue_expressions = null;
+		}
+
+		/// <summary>
+		///   Returns a temporary storage for a variable of type t as 
+		///   a local variable in the current body.
+		/// </summary>
+		public LocalBuilder GetTemporaryLocal (TypeSpec t)
+		{
+			if (temporary_storage != null) {
+				object o;
+				if (temporary_storage.TryGetValue (t, out o)) {
+					if (o is Stack<LocalBuilder>) {
+						var s = (Stack<LocalBuilder>) o;
+						o = s.Count == 0 ? null : s.Pop ();
+					} else {
+						temporary_storage.Remove (t);
+					}
+				}
+				if (o != null)
+					return (LocalBuilder) o;
+			}
+			return DeclareLocal (t, false);
+		}
+
+		public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
+		{
+			if (temporary_storage == null) {
+				temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
+				temporary_storage.Add (t, b);
+				return;
+			}
+			object o;
+			
+			if (!temporary_storage.TryGetValue (t, out o)) {
+				temporary_storage.Add (t, b);
+				return;
+			}
+			var s = o as Stack<LocalBuilder>;
+			if (s == null) {
+				s = new Stack<LocalBuilder> ();
+				s.Push ((LocalBuilder)o);
+				temporary_storage [t] = s;
+			}
+			s.Push (b);
+		}
+
+		/// <summary>
+		///   ReturnValue creates on demand the LocalBuilder for the
+		///   return value from the function.  By default this is not
+		///   used.  This is only required when returns are found inside
+		///   Try or Catch statements.
+		///
+		///   This method is typically invoked from the Emit phase, so
+		///   we allow the creation of a return label if it was not
+		///   requested during the resolution phase.   Could be cleaned
+		///   up, but it would replicate a lot of logic in the Emit phase
+		///   of the code that uses it.
+		/// </summary>
+		public LocalBuilder TemporaryReturn ()
+		{
+			if (return_value == null){
+				return_value = DeclareLocal (return_type, false);
+			}
+
+			return return_value;
+		}
+	}
+
+	public class ConditionalAccessContext
+	{
+		public ConditionalAccessContext (TypeSpec type, Label endLabel)
+		{
+			Type = type;
+			EndLabel = endLabel;
+		}
+
+		public bool Statement { get; set; }
+		public Label EndLabel { get; private set; }
+		public TypeSpec Type { get; private set; }
+	}
+
+	struct CallEmitter
+	{
+		public Expression InstanceExpression;
+
+		//
+		// When call has to leave an extra copy of all arguments on the stack
+		//
+		public bool DuplicateArguments;
+
+		//
+		// Does not emit InstanceExpression load when InstanceExpressionOnStack
+		// is set. Used by compound assignments.
+		//
+		public bool InstanceExpressionOnStack;
+
+		//
+		// Any of arguments contains await expression
+		//
+		public bool HasAwaitArguments;
+
+		public bool ConditionalAccess;
+
+		//
+		// When dealing with await arguments the original arguments are converted
+		// into a new set with hoisted stack results
+		//
+		public Arguments EmittedArguments;
+
+		public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
+		{
+			EmitPredefined (ec, method, Arguments, false, loc);
+		}
+
+		public void EmitStatement (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
+		{
+			EmitPredefined (ec, method, Arguments, true, loc);
+		}
+
+		public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, bool statement = false, Location? loc = null)
+		{
+			Expression instance_copy = null;
+
+			if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
+				HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
+				if (HasAwaitArguments && InstanceExpressionOnStack) {
+					throw new NotSupportedException ();
+				}
+			}
+
+			OpCode call_op;
+			LocalTemporary lt = null;
+
+			if (method.IsStatic) {
+				call_op = OpCodes.Call;
+			} else {
+				call_op = IsVirtualCallRequired (InstanceExpression, method) ? OpCodes.Callvirt : OpCodes.Call;
+
+				if (HasAwaitArguments) {
+					instance_copy = InstanceExpression.EmitToField (ec);
+					var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
+
+					if (Arguments == null) {
+						ie.EmitLoad (ec);
+					}
+				} else if (!InstanceExpressionOnStack) {
+					var ie = new InstanceEmitter (InstanceExpression, IsAddressCall (InstanceExpression, call_op, method.DeclaringType));
+					ie.Emit (ec, ConditionalAccess);
+
+					if (DuplicateArguments) {
+						ec.Emit (OpCodes.Dup);
+						if (Arguments != null && Arguments.Count != 0) {
+							lt = new LocalTemporary (ie.GetStackType (ec));
+							lt.Store (ec);
+							instance_copy = lt;
+						}
+					}
+				}
+			}
+
+			if (Arguments != null && !InstanceExpressionOnStack) {
+				EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
+				if (EmittedArguments != null) {
+					if (instance_copy != null) {
+						var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
+						ie.Emit (ec, ConditionalAccess);
+
+						if (lt != null)
+							lt.Release (ec);
+					}
+
+					EmittedArguments.Emit (ec);
+				}
+			}
+
+			if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) {
+				ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
+			}
+
+			if (loc != null) {
+				//
+				// Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
+				// break at right place when LHS expression can be stepped-into
+				//
+				ec.MarkCallEntry (loc.Value);
+			}
+
+			//
+			// Set instance expression to actual result expression. When it contains await it can be
+			// picked up by caller
+			//
+			InstanceExpression = instance_copy;
+
+			if (method.Parameters.HasArglist) {
+				var varargs_types = GetVarargsTypes (method, Arguments);
+				ec.Emit (call_op, method, varargs_types);
+			} else {
+				//
+				// If you have:
+				// this.DoFoo ();
+				// and DoFoo is not virtual, you can omit the callvirt,
+				// because you don't need the null checking behavior.
+				//
+				ec.Emit (call_op, method);
+			}
+
+			// 
+			// Pop the return value if there is one and stack should be empty
+			//
+			if (statement && method.ReturnType.Kind != MemberKind.Void)
+				ec.Emit (OpCodes.Pop);
+		}
+
+		static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
+		{
+			AParametersCollection pd = method.Parameters;
+
+			Argument a = arguments[pd.Count - 1];
+			Arglist list = (Arglist) a.Expr;
+
+			return list.ArgumentTypes;
+		}
+
+		//
+		// Used to decide whether call or callvirt is needed
+		//
+		static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
+		{
+			//
+			// There are 2 scenarious where we emit callvirt
+			//
+			// Case 1: A method is virtual and it's not used to call base
+			// Case 2: A method instance expression can be null. In this casen callvirt ensures
+			// correct NRE exception when the method is called
+			//
+			var decl_type = method.DeclaringType;
+			if (decl_type.IsStruct || decl_type.IsEnum)
+				return false;
+
+			if (instance is BaseThis)
+				return false;
+
+			//
+			// It's non-virtual and will never be null and it can be determined
+			// whether it's known value or reference type by verifier
+			//
+			if (!method.IsVirtual && Expression.IsNeverNull (instance) && !instance.Type.IsGenericParameter)
+				return false;
+
+			return true;
+		}
+
+		static bool IsAddressCall (Expression instance, OpCode callOpcode, TypeSpec declaringType)
+		{
+			var instance_type = instance.Type;
+			return (instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
+				instance_type.IsGenericParameter || declaringType.IsNullableType;
+		}
+	}
+
+	public struct InstanceEmitter
+	{
+		readonly Expression instance;
+		readonly bool addressRequired;
+
+		public InstanceEmitter (Expression instance, bool addressLoad)
+		{
+			this.instance = instance;
+			this.addressRequired = addressLoad;
+		}
+
+		public void Emit (EmitContext ec, bool conditionalAccess)
+		{
+			Label NullOperatorLabel;
+			Nullable.Unwrap unwrap;
+
+			if (conditionalAccess && Expression.IsNeverNull (instance))
+				conditionalAccess = false;
+
+			if (conditionalAccess) {
+				NullOperatorLabel = ec.DefineLabel ();
+				unwrap = instance as Nullable.Unwrap;
+			} else {
+				NullOperatorLabel = new Label ();
+				unwrap = null;
+			}
+
+			IMemoryLocation instance_address = null;
+			bool conditional_access_dup = false;
+
+			if (unwrap != null) {
+				unwrap.Store (ec);
+				unwrap.EmitCheck (ec);
+				ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
+			} else {
+				if (conditionalAccess && addressRequired) {
+					//
+					// Don't allocate temp variable when instance load is cheap and load and load-address
+					// operate on same memory
+					//
+					instance_address = instance as VariableReference;
+					if (instance_address == null)
+						instance_address = instance as LocalTemporary;
+
+					if (instance_address == null) {
+						EmitLoad (ec);
+						ec.Emit (OpCodes.Dup);
+						ec.EmitLoadFromPtr (instance.Type);
+
+						conditional_access_dup = true;
+					} else {
+						instance.Emit (ec);
+					}
+
+					if (instance.Type.Kind == MemberKind.TypeParameter)
+						ec.Emit (OpCodes.Box, instance.Type);
+				} else {
+					EmitLoad (ec);
+
+					if (conditionalAccess) {
+						conditional_access_dup = !IsInexpensiveLoad ();
+						if (conditional_access_dup)
+							ec.Emit (OpCodes.Dup);
+					}
+				}
+
+				if (conditionalAccess) {
+					ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
+
+					if (conditional_access_dup)
+						ec.Emit (OpCodes.Pop);
+				}
+			}
+
+			if (conditionalAccess) {
+				if (!ec.ConditionalAccess.Statement) {
+					if (ec.ConditionalAccess.Type.IsNullableType)
+						Nullable.LiftedNull.Create (ec.ConditionalAccess.Type, Location.Null).Emit (ec);
+					else
+						ec.EmitNull ();
+				}
+
+				ec.Emit (OpCodes.Br, ec.ConditionalAccess.EndLabel);
+				ec.MarkLabel (NullOperatorLabel);
+
+				if (instance_address != null) {
+					instance_address.AddressOf (ec, AddressOp.Load);
+				} else if (unwrap != null) {
+					unwrap.Emit (ec);
+					var tmp = ec.GetTemporaryLocal (unwrap.Type);
+					ec.Emit (OpCodes.Stloc, tmp);
+					ec.Emit (OpCodes.Ldloca, tmp);
+					ec.FreeTemporaryLocal (tmp, unwrap.Type);
+				} else if (!conditional_access_dup) {
+					instance.Emit (ec);
+				}
+			}
+		}
+
+		public void EmitLoad (EmitContext ec)
+		{
+			var instance_type = instance.Type;
+
+			//
+			// Push the instance expression
+			//
+			if (addressRequired) {
+				//
+				// If the expression implements IMemoryLocation, then
+				// we can optimize and use AddressOf on the
+				// return.
+				//
+				// If not we have to use some temporary storage for
+				// it.
+				var iml = instance as IMemoryLocation;
+				if (iml != null) {
+					iml.AddressOf (ec, AddressOp.Load);
+				} else {
+					LocalTemporary temp = new LocalTemporary (instance_type);
+					instance.Emit (ec);
+					temp.Store (ec);
+					temp.AddressOf (ec, AddressOp.Load);
+				}
+
+				return;
+			}
+
+			instance.Emit (ec);
+
+			// Only to make verifier happy
+			if (RequiresBoxing ())
+				ec.Emit (OpCodes.Box, instance_type);
+		}
+
+		public TypeSpec GetStackType (EmitContext ec)
+		{
+			var instance_type = instance.Type;
+
+			if (addressRequired)
+				return ReferenceContainer.MakeType (ec.Module, instance_type);
+
+			if (instance_type.IsStructOrEnum)
+				return ec.Module.Compiler.BuiltinTypes.Object;
+
+			return instance_type;
+		}
+
+		bool RequiresBoxing ()
+		{
+			var instance_type = instance.Type;
+			if (instance_type.IsGenericParameter && !(instance is This) && TypeSpec.IsReferenceType (instance_type))
+				return true;
+
+			if (instance_type.IsStructOrEnum)
+				return true;
+
+			return false;
+		}
+
+		bool IsInexpensiveLoad ()
+		{
+			if (instance is Constant)
+				return instance.IsSideEffectFree;
+
+			if (RequiresBoxing ())
+				return false;
+
+			var vr = instance as VariableReference;
+			if (vr != null)
+				return !vr.IsRef;
+
+			if (instance is LocalTemporary)
+				return true;
+
+			var fe = instance as FieldExpr;
+			if (fe != null)
+				return fe.IsStatic || fe.InstanceExpression is This;
+
+			return false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/complete.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/complete.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/complete.cs	(revision 11807)
@@ -0,0 +1,226 @@
+//
+// complete.cs: Expression that are used for completion suggestions.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003-2009 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+// Completion* classes derive from ExpressionStatement as this allows
+// them to pass through the parser in many conditions that require
+// statements even when the expression is incomplete (for example
+// completing inside a lambda
+//
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Mono.CSharp {
+
+	//
+	// A common base class for Completing expressions, it
+	// is just a very simple ExpressionStatement
+	//
+	public abstract class CompletingExpression : ExpressionStatement
+	{
+		public static void AppendResults (List<string> results, string prefix, IEnumerable<string> names)
+		{
+			foreach (string name in names) {
+				if (name == null)
+					continue;
+
+				if (prefix != null && !name.StartsWith (prefix))
+					continue;
+
+				if (results.Contains (name))
+					continue;
+
+				if (prefix != null)
+					results.Add (name.Substring (prefix.Length));
+				else
+					results.Add (name);
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return null;
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			// Do nothing
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// Do nothing
+		}
+	}
+	
+	public class CompletionSimpleName : CompletingExpression {
+		public string Prefix;
+		
+		public CompletionSimpleName (string prefix, Location l)
+		{
+			this.loc = l;
+			this.Prefix = prefix;
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			var results = new List<string> ();
+
+			ec.CurrentMemberDefinition.GetCompletionStartingWith (Prefix, results);
+
+			throw new CompletionResult (Prefix, results.Distinct ().Select (l => l.Substring (Prefix.Length)).ToArray ());
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			// Nothing
+		}
+	}
+	
+	public class CompletionMemberAccess : CompletingExpression {
+		Expression expr;
+		string partial_name;
+		TypeArguments targs;
+		
+		public CompletionMemberAccess (Expression e, string partial_name, Location l)
+		{
+			this.expr = e;
+			this.loc = l;
+			this.partial_name = partial_name;
+		}
+
+		public CompletionMemberAccess (Expression e, string partial_name, TypeArguments targs, Location l)
+		{
+			this.expr = e;
+			this.loc = l;
+			this.partial_name = partial_name;
+			this.targs = targs;
+		}
+		
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			var sn = expr as SimpleName;
+			const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
+
+			if (sn != null) {
+				expr = sn.LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);
+
+				//
+				// Resolve expression which does have type set as we need expression type
+				// with disable flow analysis as we don't know whether left side expression
+				// is used as variable or type
+				//
+				if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
+					expr = expr.Resolve (rc);
+				} else if (expr is TypeParameterExpr) {
+					expr.Error_UnexpectedKind (rc, flags, sn.Location);
+					expr = null;
+				}
+			} else {
+				expr = expr.Resolve (rc, flags);
+			}
+
+			if (expr == null)
+				return null;
+
+			TypeSpec expr_type = expr.Type;
+			if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod) {
+				expr.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
+				return null;
+			}
+
+			if (targs != null) {
+				if (!targs.Resolve (rc))
+					return null;
+			}
+
+			var results = new List<string> ();
+			var nexpr = expr as NamespaceExpression;
+			if (nexpr != null) {
+				string namespaced_partial;
+
+				if (partial_name == null)
+					namespaced_partial = nexpr.Namespace.Name;
+				else
+					namespaced_partial = nexpr.Namespace.Name + "." + partial_name;
+
+				rc.CurrentMemberDefinition.GetCompletionStartingWith (namespaced_partial, results);
+				if (partial_name != null)
+					results = results.Select (l => l.Substring (partial_name.Length)).ToList ();
+			} else {
+				var r = MemberCache.GetCompletitionMembers (rc, expr_type, partial_name).Select (l => l.Name);
+				AppendResults (results, partial_name, r);
+			}
+
+			throw new CompletionResult (partial_name == null ? "" : partial_name, results.Distinct ().ToArray ());
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			CompletionMemberAccess target = (CompletionMemberAccess) t;
+
+			if (targs != null)
+				target.targs = targs.Clone ();
+
+			target.expr = expr.Clone (clonectx);
+		}
+	}
+
+	public class CompletionElementInitializer : CompletingExpression {
+		string partial_name;
+		
+		public CompletionElementInitializer (string partial_name, Location l)
+		{
+			this.partial_name = partial_name;
+			this.loc = l;
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			var members = MemberCache.GetCompletitionMembers (ec, ec.CurrentInitializerVariable.Type, partial_name);
+
+// TODO: Does this mean exact match only ?
+//			if (partial_name != null && results.Count > 0 && result [0] == "")
+//				throw new CompletionResult ("", new string [] { "=" });
+
+			var results = members.Where (l => (l.Kind & (MemberKind.Field | MemberKind.Property)) != 0).Select (l => l.Name).ToList ();
+			if (partial_name != null) {
+				var temp = new List<string> ();
+				AppendResults (temp, partial_name, results);
+				results = temp;
+			}
+
+			throw new CompletionResult (partial_name == null ? "" : partial_name, results.Distinct ().ToArray ());
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			// Nothing
+		}
+	}
+
+	public class EmptyCompletion : CompletingExpression
+	{
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			throw new CompletionResult ("", new string [0]);
+		}
+	}
+	
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/const.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/const.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/const.cs	(revision 11807)
@@ -0,0 +1,237 @@
+//
+// const.cs: Constant declarations.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@seznam.cz)
+//
+// Copyright 2001-2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+//
+
+#if STATIC
+using IKVM.Reflection;
+#else
+using System.Reflection;
+#endif
+
+namespace Mono.CSharp {
+
+	public class Const : FieldBase
+	{
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE;
+
+		public Const (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
+			: base (parent, type, mod_flags, AllowedModifiers, name, attrs)
+		{
+			ModFlags |= Modifiers.STATIC;
+		}
+
+		/// <summary>
+		///   Defines the constant in the @parent
+		/// </summary>
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			if (!member_type.IsConstantCompatible) {
+				Error_InvalidConstantType (member_type, Location, Report);
+			}
+
+			FieldAttributes field_attr = FieldAttributes.Static | ModifiersExtensions.FieldAttr (ModFlags);
+			// Decimals cannot be emitted into the constant blob.  So, convert to 'readonly'.
+			if (member_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+				field_attr |= FieldAttributes.InitOnly;
+			} else {
+				field_attr |= FieldAttributes.Literal;
+			}
+
+			FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), field_attr);
+			spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer);
+
+			Parent.MemberCache.AddMember (spec);
+
+			if ((field_attr & FieldAttributes.InitOnly) != 0)
+				Parent.PartialContainer.RegisterFieldForInitialization (this,
+					new FieldInitializer (this, initializer, Location));
+
+			if (declarators != null) {
+				var t = new TypeExpression (MemberType, TypeExpression.Location);
+				foreach (var d in declarators) {
+					var c = new Const (Parent, t, ModFlags & ~Modifiers.STATIC, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
+					c.initializer = d.Initializer;
+					((ConstInitializer) c.initializer).Name = d.Name.Value;
+					c.Define ();
+					Parent.PartialContainer.Members.Add (c);
+				}
+			}
+
+			return true;
+		}
+
+		public void DefineValue ()
+		{
+			var rc = new ResolveContext (this);
+			((ConstSpec) spec).GetConstant (rc);
+		}
+
+		/// <summary>
+		///  Emits the field value by evaluating the expression
+		/// </summary>
+		public override void Emit ()
+		{
+			var c = ((ConstSpec) spec).Value as Constant;
+			if (c.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+				Module.PredefinedAttributes.DecimalConstant.EmitAttribute (FieldBuilder, (decimal) c.GetValue (), c.Location);
+			} else {
+				FieldBuilder.SetConstant (c.GetValue ());
+			}
+
+			base.Emit ();
+		}
+
+		public static void Error_InvalidConstantType (TypeSpec t, Location loc, Report Report)
+		{
+			if (t.IsGenericParameter) {
+				Report.Error (1959, loc,
+					"Type parameter `{0}' cannot be declared const", t.GetSignatureForError ());
+			} else {
+				Report.Error (283, loc,
+					"The type `{0}' cannot be declared const", t.GetSignatureForError ());
+			}
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+	}
+
+	public class ConstSpec : FieldSpec
+	{
+		Expression value;
+
+		public ConstSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo fi, Modifiers mod, Expression value)
+			: base (declaringType, definition, memberType, fi, mod)
+		{
+			this.value = value;
+		}
+
+		//
+		// This expresion is guarantee to be a constant at emit phase only
+		//
+		public Expression Value {
+			get {
+				return value;
+			}
+		}
+
+		//
+		// For compiled constants we have to resolve the value as there could be constant dependecies. This
+		// is needed for imported constants too to get the right context type
+		//
+		public Constant GetConstant (ResolveContext rc)
+		{
+			if (value.eclass != ExprClass.Value)
+				value = value.Resolve (rc);
+
+			return (Constant) value;
+		}
+	}
+
+	public class ConstInitializer : ShimExpression
+	{
+		bool in_transit;
+		readonly FieldBase field;
+
+		public ConstInitializer (FieldBase field, Expression value, Location loc)
+			: base (value)
+		{
+			this.loc = loc;
+			this.field = field;
+		}
+
+		public string Name { get; set; }
+
+		protected override Expression DoResolve (ResolveContext unused)
+		{
+			if (type != null)
+				return expr;
+
+			var opt = ResolveContext.Options.ConstantScope;
+			if (field is EnumMember)
+				opt |= ResolveContext.Options.EnumScope;
+
+			//
+			// Use a context in which the constant was declared and
+			// not the one in which is referenced
+			//
+			var rc = new ResolveContext (field, opt);
+			expr = DoResolveInitializer (rc);
+			type = expr.Type;
+
+			return expr;
+		}
+
+		protected virtual Expression DoResolveInitializer (ResolveContext rc)
+		{
+			if (in_transit) {
+				field.Compiler.Report.Error (110, expr.Location,
+					"The evaluation of the constant value for `{0}' involves a circular definition",
+					GetSignatureForError ());
+
+				expr = null;
+			} else {
+				in_transit = true;
+				expr = expr.Resolve (rc);
+			}
+
+			in_transit = false;
+
+			if (expr != null) {
+				Constant c = expr as Constant;
+				if (c != null)
+					c = field.ConvertInitializer (rc, c);
+
+				if (c == null) {
+					if (TypeSpec.IsReferenceType (field.MemberType))
+						Error_ConstantCanBeInitializedWithNullOnly (rc, field.MemberType, expr.Location, GetSignatureForError ());
+					else if (!(expr is Constant))
+						Error_ExpressionMustBeConstant (rc, expr.Location, GetSignatureForError ());
+					else
+						expr.Error_ValueCannotBeConverted (rc, field.MemberType, false);
+				}
+
+				expr = c;
+			}
+
+			if (expr == null) {
+				expr = New.Constantify (field.MemberType, Location);
+				if (expr == null)
+					expr = Constant.CreateConstantFromValue (field.MemberType, null, Location);
+				expr = expr.Resolve (rc);
+			}
+
+			return expr;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			if (Name == null)
+				return field.GetSignatureForError ();
+
+			return field.Parent.GetSignatureForError () + "." + Name;
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/constant.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/constant.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/constant.cs	(revision 11807)
@@ -0,0 +1,2496 @@
+//
+// constant.cs: Constants.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001-2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011-2013 Xamarin Inc
+//
+
+using System;
+using System.Globalization;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	/// <summary>
+	///   Base class for constants and literals.
+	/// </summary>
+	public abstract class Constant : Expression
+	{
+		static readonly NumberFormatInfo nfi = CultureInfo.InvariantCulture.NumberFormat;
+
+		protected Constant (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		override public string ToString ()
+		{
+			return this.GetType ().Name + " (" + GetValueAsLiteral () + ")";
+		}
+
+		/// <summary>
+		///  This is used to obtain the actual value of the literal
+		///  cast into an object.
+		/// </summary>
+		public abstract object GetValue ();
+
+		public abstract long GetValueAsLong ();
+
+		public abstract string GetValueAsLiteral ();
+
+#if !STATIC
+		//
+		// Returns an object value which is typed to contant type
+		//
+		public virtual object GetTypedValue ()
+		{
+			return GetValue ();
+		}
+#endif
+
+		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
+		{
+			if (!expl && IsLiteral && 
+				BuiltinTypeSpec.IsPrimitiveTypeOrDecimal (target) &&
+				BuiltinTypeSpec.IsPrimitiveTypeOrDecimal (type)) {
+				ec.Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
+					GetValueAsLiteral (), target.GetSignatureForError ());
+			} else {
+				base.Error_ValueCannotBeConverted (ec, target, expl);
+			}
+		}
+
+		public Constant ImplicitConversionRequired (ResolveContext ec, TypeSpec type)
+		{
+			Constant c = ConvertImplicitly (type);
+			if (c == null)
+				Error_ValueCannotBeConverted (ec, type, false);
+
+			return c;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public virtual Constant ConvertImplicitly (TypeSpec type)
+		{
+			if (this.type == type)
+				return this;
+
+			if (!Convert.ImplicitNumericConversionExists (this.type, type))
+				return null;
+
+			bool fail;			
+			object constant_value = ChangeType (GetValue (), type, out fail);
+			if (fail){
+				//
+				// We should always catch the error before this is ever
+				// reached, by calling Convert.ImplicitStandardConversionExists
+				//
+				throw new InternalErrorException ("Missing constant conversion between `{0}' and `{1}'",
+				 Type.GetSignatureForError (), type.GetSignatureForError ());
+			}
+
+			return CreateConstantFromValue (type, constant_value, loc);
+		}
+
+		//
+		//  Returns a constant instance based on Type
+		//
+		public static Constant CreateConstantFromValue (TypeSpec t, object v, Location loc)
+		{
+			switch (t.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (t, (int) v, loc);
+			case BuiltinTypeSpec.Type.String:
+				return new StringConstant (t, (string) v, loc);
+			case BuiltinTypeSpec.Type.UInt:
+				return new UIntConstant (t, (uint) v, loc);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (t, (long) v, loc);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (t, (ulong) v, loc);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (t, (float) v, loc);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (t, (double) v, loc);
+			case BuiltinTypeSpec.Type.Short:
+				return new ShortConstant (t, (short) v, loc);
+			case BuiltinTypeSpec.Type.UShort:
+				return new UShortConstant (t, (ushort) v, loc);
+			case BuiltinTypeSpec.Type.SByte:
+				return new SByteConstant (t, (sbyte) v, loc);
+			case BuiltinTypeSpec.Type.Byte:
+				return new ByteConstant (t, (byte) v, loc);
+			case BuiltinTypeSpec.Type.Char:
+				return new CharConstant (t, (char) v, loc);
+			case BuiltinTypeSpec.Type.Bool:
+				return new BoolConstant (t, (bool) v, loc);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (t, (decimal) v, loc);
+			}
+
+			if (t.IsEnum) {
+				var real_type = EnumSpec.GetUnderlyingType (t);
+				return new EnumConstant (CreateConstantFromValue (real_type, v, loc), t);
+			}
+
+			if (v == null) {
+				if (t.IsNullableType)
+					return Nullable.LiftedNull.Create (t, loc);
+
+				if (TypeSpec.IsReferenceType (t))
+					return new NullConstant (t, loc);
+			}
+
+#if STATIC
+			throw new InternalErrorException ("Constant value `{0}' has unexpected underlying type `{1}'", v, t.GetSignatureForError ());
+#else
+			return null;
+#endif
+		}
+
+		//
+		// Returns a constant instance based on value and type. This is probing version of
+		// CreateConstantFromValue
+		//
+		public static Constant ExtractConstantFromValue (TypeSpec t, object v, Location loc)
+		{
+			switch (t.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+				if (v is int)
+					return new IntConstant (t, (int) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.String:
+				if (v is string)
+					return new StringConstant (t, (string) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				if (v is uint)
+					return new UIntConstant (t, (uint) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				if (v is long)
+					return new LongConstant (t, (long) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+				if (v is ulong)
+					return new ULongConstant (t, (ulong) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Float:
+				if (v is float)
+					return new FloatConstant (t, (float) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Double:
+				if (v is double)
+					return new DoubleConstant (t, (double) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				if (v is short)
+					return new ShortConstant (t, (short) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+				if (v is ushort)
+					return new UShortConstant (t, (ushort) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.SByte:
+				if (v is sbyte)
+					return new SByteConstant (t, (sbyte) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				if (v is byte)
+					return new ByteConstant (t, (byte) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Char:
+				if (v is char)
+					return new CharConstant (t, (char) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Bool:
+				if (v is bool)
+					return new BoolConstant (t, (bool) v, loc);
+				break;
+			case BuiltinTypeSpec.Type.Decimal:
+				if (v is decimal)
+					return new DecimalConstant (t, (decimal) v, loc);
+				break;
+			}
+
+			if (t.IsEnum) {
+				var real_type = EnumSpec.GetUnderlyingType (t);
+				return new EnumConstant (CreateConstantFromValue (real_type, v, loc), t);
+			}
+
+			if (v == null) {
+				if (t.IsNullableType)
+					return Nullable.LiftedNull.Create (t, loc);
+
+				if (TypeSpec.IsReferenceType (t))
+					return new NullConstant (t, loc);
+			}
+
+			return null;
+		}
+
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (this));
+			args.Add (new Argument (new TypeOf (type, loc)));
+
+			return CreateExpressionFactoryCall (ec, "Constant", args);
+		}
+
+		/// <summary>
+		/// Maybe ConvertTo name is better. It tries to convert `this' constant to target_type.
+		/// It throws OverflowException 
+		/// </summary>
+		// DON'T CALL THIS METHOD DIRECTLY AS IT DOES NOT HANDLE ENUMS
+		public abstract Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type);
+
+		// This is a custom version of Convert.ChangeType() which works
+		// with the TypeBuilder defined types when compiling corlib.
+		static object ChangeType (object value, TypeSpec targetType, out bool error)
+		{
+			IConvertible convert_value = value as IConvertible;
+
+			if (convert_value == null) {
+				error = true;
+				return null;
+			}
+
+			//
+			// We cannot rely on build-in type conversions as they are
+			// more limited than what C# supports.
+			// See char -> float/decimal/double conversion
+			//
+			error = false;
+			try {
+				switch (targetType.BuiltinType) {
+				case BuiltinTypeSpec.Type.Bool:
+					return convert_value.ToBoolean (nfi);
+				case BuiltinTypeSpec.Type.Byte:
+					return convert_value.ToByte (nfi);
+				case BuiltinTypeSpec.Type.Char:
+					return convert_value.ToChar (nfi);
+				case BuiltinTypeSpec.Type.Short:
+					return convert_value.ToInt16 (nfi);
+				case BuiltinTypeSpec.Type.Int:
+					return convert_value.ToInt32 (nfi);
+				case BuiltinTypeSpec.Type.Long:
+					return convert_value.ToInt64 (nfi);
+				case BuiltinTypeSpec.Type.SByte:
+					return convert_value.ToSByte (nfi);
+				case BuiltinTypeSpec.Type.Decimal:
+					if (convert_value.GetType () == typeof (char))
+						return (decimal) convert_value.ToInt32 (nfi);
+					return convert_value.ToDecimal (nfi);
+				case BuiltinTypeSpec.Type.Double:
+					if (convert_value.GetType () == typeof (char))
+						return (double) convert_value.ToInt32 (nfi);
+					return convert_value.ToDouble (nfi);
+				case BuiltinTypeSpec.Type.Float:
+					if (convert_value.GetType () == typeof (char))
+						return (float) convert_value.ToInt32 (nfi);
+					return convert_value.ToSingle (nfi);
+				case BuiltinTypeSpec.Type.String:
+					return convert_value.ToString (nfi);
+				case BuiltinTypeSpec.Type.UShort:
+					return convert_value.ToUInt16 (nfi);
+				case BuiltinTypeSpec.Type.UInt:
+					return convert_value.ToUInt32 (nfi);
+				case BuiltinTypeSpec.Type.ULong:
+					return convert_value.ToUInt64 (nfi);
+				case BuiltinTypeSpec.Type.Object:
+					return value;
+				}
+			} catch {
+			}
+
+			error = true;
+			return null;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			return this;
+		}
+
+		//
+		// Attempts to do a compile-time folding of a constant cast and handles
+		// error reporting for constant overlows only, on normal conversion
+		// errors returns null
+		// 
+		public Constant Reduce (ResolveContext ec, TypeSpec target_type)
+		{
+			try {
+				return TryReduceConstant (ec, target_type);
+			} catch (OverflowException) {
+				if (ec.ConstantCheckState && Type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
+					ec.Report.Error (221, loc,
+						"Constant value `{0}' cannot be converted to a `{1}' (use `unchecked' syntax to override)",
+						GetValueAsLiteral (), target_type.GetSignatureForError ());
+				} else {
+					Error_ValueCannotBeConverted (ec, target_type, false);
+				}
+
+				return New.Constantify (target_type, loc);
+			}
+		}
+
+		public Constant TryReduce (ResolveContext rc, TypeSpec targetType)
+		{
+			try {
+				return TryReduceConstant (rc, targetType);
+			} catch (OverflowException) {
+				return null;
+			}
+		}
+
+		Constant TryReduceConstant (ResolveContext ec, TypeSpec target_type)
+		{
+			if (Type == target_type) {
+				//
+				// Reducing literal value produces a new constant. Syntactically 10 is not same as (int)10 
+				//
+				if (IsLiteral)
+					return CreateConstantFromValue (target_type, GetValue (), loc);
+
+				return this;
+			}
+
+			Constant c;
+			if (target_type.IsEnum) {
+				c = TryReduceConstant (ec, EnumSpec.GetUnderlyingType (target_type));
+				if (c == null)
+					return null;
+
+				return new EnumConstant (c, target_type);
+			}
+
+			return ConvertExplicitly (ec.ConstantCheckState, target_type);
+		}
+
+		/// <summary>
+		/// Need to pass type as the constant can require a boxing
+		/// and in such case no optimization is possible
+		/// </summary>
+		public bool IsDefaultInitializer (TypeSpec type)
+		{
+			if (type == Type)
+				return IsDefaultValue;
+
+			return this is NullLiteral;
+		}
+
+		public abstract bool IsDefaultValue {
+			get;
+		}
+
+		public abstract bool IsNegative {
+			get;
+		}
+
+		//
+		// When constant is declared as literal
+		//
+		public virtual bool IsLiteral {
+			get { return false; }
+		}
+		
+		public virtual bool IsOneInteger {
+			get { return false; }
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		//
+		// Returns true iff 1) the stack type of this is one of Object, 
+		// int32, int64 and 2) this == 0 or this == null.
+		//
+		public virtual bool IsZeroInteger {
+			get { return false; }
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			// do nothing
+		}
+
+		public sealed override Expression Clone (CloneContext clonectx)
+		{
+			// No cloning is not needed for constants
+			return this;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			throw new NotSupportedException ("should not be reached");
+		}
+
+		public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return System.Linq.Expressions.Expression.Constant (GetTypedValue (), type.GetMetaInfo ());
+#endif
+		}
+
+		public new bool Resolve (ResolveContext rc)
+		{
+			// It exists only as hint not to call Resolve on constants
+			return true;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+	}
+
+	public abstract class IntegralConstant : Constant
+	{
+		protected IntegralConstant (TypeSpec type, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Value;
+		}
+
+		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
+		{
+			try {
+				ConvertExplicitly (true, target);
+				base.Error_ValueCannotBeConverted (ec, target, expl);
+			}
+			catch
+			{
+				ec.Report.Error (31, loc, "Constant value `{0}' cannot be converted to a `{1}'",
+					GetValue ().ToString (), target.GetSignatureForError ());
+			}
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return GetValue ().ToString ();
+		}
+		
+		public abstract Constant Increment ();
+	}
+	
+	public class BoolConstant : Constant {
+		public readonly bool Value;
+
+		public BoolConstant (BuiltinTypes types, bool val, Location loc)
+			: this (types.Bool, val, loc)
+		{
+		}
+		
+		public BoolConstant (TypeSpec type, bool val, Location loc)
+			: base (loc)
+		{
+			eclass = ExprClass.Value;
+			this.type = type;
+
+			Value = val;
+		}
+
+		public override object GetValue ()
+		{
+			return (object) Value;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return Value ? "true" : "false";
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value ? 1 : 0;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			if (Value)
+				ec.EmitInt (1);
+			else
+				ec.EmitInt (0);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return !Value;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+	
+		public override bool IsZeroInteger {
+			get { return Value == false; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			return null;
+		}
+
+	}
+
+	public class ByteConstant : IntegralConstant
+	{
+		public readonly byte Value;
+
+		public ByteConstant (BuiltinTypes types, byte v, Location loc)
+			: this (types.Byte, v, loc)
+		{
+		}
+
+		public ByteConstant (TypeSpec type, byte v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override Constant Increment ()
+		{
+			return new ByteConstant (type, checked ((byte)(Value + 1)), loc);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context){
+					if (Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class CharConstant : Constant {
+		public readonly char Value;
+
+		public CharConstant (BuiltinTypes types, char v, Location loc)
+			: this (types.Char, v, loc)
+		{
+		}
+
+		public CharConstant (TypeSpec type, char v, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Value;
+
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode ((ushort) Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (Value);
+		}
+
+		static string descape (char c)
+		{
+			switch (c){
+			case '\a':
+				return "\\a"; 
+			case '\b':
+				return "\\b"; 
+			case '\n':
+				return "\\n"; 
+			case '\t':
+				return "\\t"; 
+			case '\v':
+				return "\\v"; 
+			case '\r':
+				return "\\r"; 
+			case '\\':
+				return "\\\\";
+			case '\f':
+				return "\\f"; 
+			case '\0':
+				return "\\0"; 
+			case '"':
+				return "\\\""; 
+			case '\'':
+				return "\\\'"; 
+			}
+			return c.ToString ();
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return "\"" + descape (Value) + "\"";
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+
+		public override bool IsZeroInteger {
+			get { return Value == '\0'; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < Byte.MinValue || Value > Byte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value > Int16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class SByteConstant : IntegralConstant
+	{
+		public readonly sbyte Value;
+
+		public SByteConstant (BuiltinTypes types, sbyte v, Location loc)
+			: this (types.SByte, v, loc)
+		{
+		}
+
+		public SByteConstant (TypeSpec type, sbyte v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override Constant Increment ()
+		{
+		    return new SByteConstant (type, checked((sbyte)(Value + 1)), loc);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+		
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class ShortConstant : IntegralConstant {
+		public readonly short Value;
+
+		public ShortConstant (BuiltinTypes types, short v, Location loc)
+			: this (types.Short, v, loc)
+		{
+		}
+
+		public ShortConstant (TypeSpec type, short v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override Constant Increment ()
+		{
+			return new ShortConstant (type, checked((short)(Value + 1)), loc);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+		
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < Byte.MinValue || Value > Byte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value < SByte.MinValue || Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value < Char.MinValue)
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class UShortConstant : IntegralConstant
+	{
+		public readonly ushort Value;
+
+		public UShortConstant (BuiltinTypes types, ushort v, Location loc)
+			: this (types.UShort, v, loc)
+		{
+		}
+
+		public UShortConstant (TypeSpec type, ushort v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+	
+		public override Constant Increment ()
+		{
+			return new UShortConstant (type, checked((ushort)(Value + 1)), loc);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+	
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value > Byte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value > Int16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value > Char.MaxValue)
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+	}
+
+	public class IntConstant : IntegralConstant
+	{
+		public readonly int Value;
+
+		public IntConstant (BuiltinTypes types, int v, Location loc)
+			: this (types.Int, v, loc)
+		{
+		}
+
+		public IntConstant (TypeSpec type, int v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override Constant Increment ()
+		{
+			return new IntConstant (type, checked(Value + 1), loc);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+		
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < Byte.MinValue || Value > Byte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value < SByte.MinValue || Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value < Int16.MinValue || Value > Int16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context) {
+					if (Value < UInt16.MinValue || Value > UInt16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context) {
+					if (Value < UInt32.MinValue)
+						throw new OverflowException ();
+				}
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value < Char.MinValue || Value > Char.MaxValue)
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec type)
+		{
+			if (this.type == type)
+				return this;
+
+			Constant c = TryImplicitIntConversion (type);
+			if (c != null)
+				return c; //.Resolve (rc);
+
+			return base.ConvertImplicitly (type);
+		}
+
+		/// <summary>
+		///   Attempts to perform an implicit constant conversion of the IntConstant
+		///   into a different data type using casts (See Implicit Constant
+		///   Expression Conversions)
+		/// </summary>
+		Constant TryImplicitIntConversion (TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+				if (Value >= SByte.MinValue && Value <= SByte.MaxValue)
+					return new SByteConstant (target_type, (sbyte) Value, loc);
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				if (Value >= Byte.MinValue && Value <= Byte.MaxValue)
+					return new ByteConstant (target_type, (byte) Value, loc);
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				if (Value >= Int16.MinValue && Value <= Int16.MaxValue)
+					return new ShortConstant (target_type, (short) Value, loc);
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+				if (Value >= UInt16.MinValue && Value <= UInt16.MaxValue)
+					return new UShortConstant (target_type, (ushort) Value, loc);
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				if (Value >= 0)
+					return new UIntConstant (target_type, (uint) Value, loc);
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+				//
+				// we can optimize this case: a positive int32
+				// always fits on a uint64.  But we need an opcode
+				// to do it.
+				//
+				if (Value >= 0)
+					return new ULongConstant (target_type, (ulong) Value, loc);
+				break;
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, loc);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, loc);
+			}
+
+			return null;
+		}
+	}
+
+	public class UIntConstant : IntegralConstant {
+		public readonly uint Value;
+
+		public UIntConstant (BuiltinTypes types, uint v, Location loc)
+			: this (types.UInt, v, loc)
+		{
+		}
+
+		public UIntConstant (TypeSpec type, uint v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitInt (unchecked ((int) Value));
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override Constant Increment ()
+		{
+			return new UIntConstant (type, checked(Value + 1), loc);
+		}
+	
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < 0 || Value > byte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value > Int16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context) {
+					if (Value < UInt16.MinValue || Value > UInt16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				if (in_checked_context) {
+					if (Value > Int32.MaxValue)
+						throw new OverflowException ();
+				}
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value < Char.MinValue || Value > Char.MaxValue)
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class LongConstant : IntegralConstant {
+		public readonly long Value;
+
+		public LongConstant (BuiltinTypes types, long v, Location loc)
+			: this (types.Long, v, loc)
+		{
+		}
+
+		public LongConstant (TypeSpec type, long v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitLong (Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Value;
+		}
+
+		public override Constant Increment ()
+		{
+			return new LongConstant (type, checked(Value + 1), loc);
+		}
+		
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < Byte.MinValue || Value > Byte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value < SByte.MinValue || Value > SByte.MaxValue)
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value < Int16.MinValue || Value > Int16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context) {
+					if (Value < UInt16.MinValue || Value > UInt16.MaxValue)
+						throw new OverflowException ();
+				}
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				if (in_checked_context) {
+					if (Value < Int32.MinValue || Value > Int32.MaxValue)
+						throw new OverflowException ();
+				}
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context) {
+					if (Value < UInt32.MinValue || Value > UInt32.MaxValue)
+						throw new OverflowException ();
+				}
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				if (in_checked_context && Value < 0)
+					throw new OverflowException ();
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value < Char.MinValue || Value > Char.MaxValue)
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec type)
+		{
+			if (Value >= 0 && type.BuiltinType == BuiltinTypeSpec.Type.ULong) {
+				return new ULongConstant (type, (ulong) Value, loc);
+			}
+
+			return base.ConvertImplicitly (type);
+		}
+	}
+
+	public class ULongConstant : IntegralConstant {
+		public readonly ulong Value;
+
+		public ULongConstant (BuiltinTypes types, ulong v, Location loc)
+			: this (types.ULong, v, loc)
+		{
+		}
+
+		public ULongConstant (TypeSpec type, ulong v, Location loc)
+			: base (type, loc)
+		{
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitLong (unchecked ((long) Value));
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return (long) Value;
+		}
+
+		public override Constant Increment ()
+		{
+			return new ULongConstant (type, checked(Value + 1), loc);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+		
+		public override bool IsOneInteger {
+			get {
+				return Value == 1;
+			}
+		}		
+
+		public override bool IsZeroInteger {
+			get { return Value == 0; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context && Value > Byte.MaxValue)
+					throw new OverflowException ();
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context && Value > ((ulong) SByte.MaxValue))
+					throw new OverflowException ();
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context && Value > ((ulong) Int16.MaxValue))
+					throw new OverflowException ();
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context && Value > UInt16.MaxValue)
+					throw new OverflowException ();
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				if (in_checked_context && Value > UInt32.MaxValue)
+					throw new OverflowException ();
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context && Value > UInt32.MaxValue)
+					throw new OverflowException ();
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				if (in_checked_context && Value > Int64.MaxValue)
+					throw new OverflowException ();
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context && Value > Char.MaxValue)
+					throw new OverflowException ();
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class FloatConstant : Constant {
+		//
+		// Store constant value as double because float constant operations
+		// need to work on double value to match JIT
+		//
+		public readonly double DoubleValue;
+
+		public FloatConstant (BuiltinTypes types, double v, Location loc)
+			: this (types.Float, v, loc)
+		{
+		}
+
+		public FloatConstant (TypeSpec type, double v, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Value;
+
+			DoubleValue = v;
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec type)
+		{
+			if (type.BuiltinType == BuiltinTypeSpec.Type.Double)
+				return new DoubleConstant (type, DoubleValue, loc);
+
+			return base.ConvertImplicitly (type);
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Ldc_R4, Value);
+		}
+
+		public float Value {
+			get {
+				return (float) DoubleValue;
+			}
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return Value.ToString ();
+		}
+
+		public override long GetValueAsLong ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < byte.MinValue || Value > byte.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value < sbyte.MinValue || Value > sbyte.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value < short.MinValue || Value > short.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context) {
+					if (Value < ushort.MinValue || Value > ushort.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new UShortConstant (target_type, (ushort) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.Int:
+				if (in_checked_context) {
+					if (Value < int.MinValue || Value > int.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new IntConstant (target_type, (int) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context) {
+					if (Value < uint.MinValue || Value > uint.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new UIntConstant (target_type, (uint) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.Long:
+				if (in_checked_context) {
+					if (Value < long.MinValue || Value > long.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new LongConstant (target_type, (long) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				if (in_checked_context) {
+					if (Value < ulong.MinValue || Value > ulong.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new ULongConstant (target_type, (ulong) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, DoubleValue, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value < (float) char.MinValue || Value > (float) char.MaxValue || float.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) DoubleValue, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) DoubleValue, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class DoubleConstant : Constant
+	{
+		public readonly double Value;
+
+		public DoubleConstant (BuiltinTypes types, double v, Location loc)
+			: this (types.Double, v, loc)
+		{
+		}
+
+		public DoubleConstant (TypeSpec type, double v, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Value;
+
+			Value = v;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			enc.Encode (Value);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Ldc_R8, Value);
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return Value.ToString ();
+		}
+
+		public override long GetValueAsLong ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+				if (in_checked_context) {
+					if (Value < Byte.MinValue || Value > Byte.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new ByteConstant (target_type, (byte) Value, Location);
+			case BuiltinTypeSpec.Type.SByte:
+				if (in_checked_context) {
+					if (Value < SByte.MinValue || Value > SByte.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new SByteConstant (target_type, (sbyte) Value, Location);
+			case BuiltinTypeSpec.Type.Short:
+				if (in_checked_context) {
+					if (Value < short.MinValue || Value > short.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new ShortConstant (target_type, (short) Value, Location);
+			case BuiltinTypeSpec.Type.UShort:
+				if (in_checked_context) {
+					if (Value < ushort.MinValue || Value > ushort.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new UShortConstant (target_type, (ushort) Value, Location);
+			case BuiltinTypeSpec.Type.Int:
+				if (in_checked_context) {
+					if (Value < int.MinValue || Value > int.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new IntConstant (target_type, (int) Value, Location);
+			case BuiltinTypeSpec.Type.UInt:
+				if (in_checked_context) {
+					if (Value < uint.MinValue || Value > uint.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new UIntConstant (target_type, (uint) Value, Location);
+			case BuiltinTypeSpec.Type.Long:
+				if (in_checked_context) {
+					if (Value < long.MinValue || Value > long.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new LongConstant (target_type, (long) Value, Location);
+			case BuiltinTypeSpec.Type.ULong:
+				if (in_checked_context) {
+					if (Value < ulong.MinValue || Value > ulong.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new ULongConstant (target_type, (ulong) Value, Location);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, Location);
+			case BuiltinTypeSpec.Type.Char:
+				if (in_checked_context) {
+					if (Value < (double) char.MinValue || Value > (double) char.MaxValue || double.IsNaN (Value))
+						throw new OverflowException ();
+				}
+				return new CharConstant (target_type, (char) Value, Location);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (target_type, (decimal) Value, Location);
+			}
+
+			return null;
+		}
+
+	}
+
+	public class DecimalConstant : Constant {
+		public readonly decimal Value;
+
+		public DecimalConstant (BuiltinTypes types, decimal d, Location loc)
+			: this (types.Decimal, d, loc)
+		{
+		}
+
+		public DecimalConstant (TypeSpec type, decimal d, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Value;
+
+			Value = d;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			MethodSpec m;
+
+			int [] words = decimal.GetBits (Value);
+			int power = (words [3] >> 16) & 0xff;
+
+			if (power == 0) {
+				if (Value <= int.MaxValue && Value >= int.MinValue) {
+					m = ec.Module.PredefinedMembers.DecimalCtorInt.Resolve (loc);
+					if (m == null) {
+						return;
+					}
+
+					ec.EmitInt ((int) Value);
+					ec.Emit (OpCodes.Newobj, m);
+					return;
+				}
+
+				if (Value <= long.MaxValue && Value >= long.MinValue) {
+					m = ec.Module.PredefinedMembers.DecimalCtorLong.Resolve (loc);
+					if (m == null) {
+						return;
+					}
+
+					ec.EmitLong ((long) Value);
+					ec.Emit (OpCodes.Newobj, m);
+					return;
+				}
+			}
+
+			ec.EmitInt (words [0]);
+			ec.EmitInt (words [1]);
+			ec.EmitInt (words [2]);
+
+			// sign
+			ec.EmitInt (words [3] >> 31);
+
+			// power
+			ec.EmitInt (power);
+
+			m = ec.Module.PredefinedMembers.DecimalCtor.Resolve (loc);
+			if (m != null) {
+				ec.Emit (OpCodes.Newobj, m);
+			}
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == 0;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return Value < 0;
+			}
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+				return new SByteConstant (target_type, (sbyte) Value, loc);
+			case BuiltinTypeSpec.Type.Byte:
+				return new ByteConstant (target_type, (byte) Value, loc);
+			case BuiltinTypeSpec.Type.Short:
+				return new ShortConstant (target_type, (short) Value, loc);
+			case BuiltinTypeSpec.Type.UShort:
+				return new UShortConstant (target_type, (ushort) Value, loc);
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (target_type, (int) Value, loc);
+			case BuiltinTypeSpec.Type.UInt:
+				return new UIntConstant (target_type, (uint) Value, loc);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (target_type, (long) Value, loc);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (target_type, (ulong) Value, loc);
+			case BuiltinTypeSpec.Type.Char:
+				return new CharConstant (target_type, (char) Value, loc);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (target_type, (float) Value, loc);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (target_type, (double) Value, loc);
+			}
+
+			return null;
+		}
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return Value.ToString () + "M";
+		}
+
+		public override long GetValueAsLong ()
+		{
+			throw new NotSupportedException ();
+		}
+	}
+
+	public class StringConstant : Constant {
+		public StringConstant (BuiltinTypes types, string s, Location loc)
+			: this (types.String, s, loc)
+		{
+		}
+
+		public StringConstant (TypeSpec type, string s, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Value;
+
+			Value = s;
+		}
+
+		protected StringConstant (Location loc)
+			: base (loc)
+		{
+		}
+
+		public string Value { get; protected set; }
+
+		public override object GetValue ()
+		{
+			return Value;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			// FIXME: Escape the string.
+			return "\"" + Value + "\"";
+		}
+
+		public override long GetValueAsLong ()
+		{
+			throw new NotSupportedException ();
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			if (Value == null) {
+				ec.EmitNull ();
+				return;
+			}
+
+			//
+			// Use string.Empty for both literals and constants even if
+			// it's not allowed at language level
+			//
+			if (Value.Length == 0 && ec.Module.Compiler.Settings.Optimize) {
+				var string_type = ec.BuiltinTypes.String;
+				if (ec.CurrentType != string_type) {
+					var m = ec.Module.PredefinedMembers.StringEmpty.Get ();
+					if (m != null) {
+						ec.Emit (OpCodes.Ldsfld, m);
+						return;
+					}
+				}
+			}
+
+			ec.Emit (OpCodes.Ldstr, Value);
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			// cast to object
+			if (type != targetType)
+				enc.Encode (type);
+
+			enc.Encode (Value);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Value == null;
+			}
+		}
+
+		public override bool IsNegative {
+			get {
+				return false;
+			}
+		}
+
+		public override bool IsNull {
+			get {
+				return IsDefaultValue;
+			}
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			return null;
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec type)
+		{
+			if (IsDefaultValue && type.BuiltinType == BuiltinTypeSpec.Type.Object)
+				return new NullConstant (type, loc);
+
+			return base.ConvertImplicitly (type);
+		}
+	}
+
+	class NameOf : StringConstant
+	{
+		readonly SimpleName name;
+
+		public NameOf (SimpleName name)
+			: base (name.Location)
+		{
+			this.name = name;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			throw new NotSupportedException ();
+		}
+
+		bool ResolveArgumentExpression (ResolveContext rc, Expression expr)
+		{
+			var sn = expr as SimpleName;
+			if (sn != null) {
+				Value = sn.Name;
+
+				if (rc.Module.Compiler.Settings.Version < LanguageVersion.V_6)
+					rc.Report.FeatureIsNotAvailable (rc.Module.Compiler, Location, "nameof operator");
+
+				if (sn.HasTypeArguments) {
+					// TODO: csc compatible but unhelpful error message
+					rc.Report.Error (1001, loc, "Identifier expected");
+					return true;
+				}
+
+				sn.LookupNameExpression (rc, MemberLookupRestrictions.IgnoreArity | MemberLookupRestrictions.IgnoreAmbiguity);
+				return true;
+			}
+
+			var ma = expr as MemberAccess;
+			if (ma != null) {
+				FullNamedExpression fne = ma.LeftExpression as ATypeNameExpression;
+				if (fne == null) {
+					var qam = ma as QualifiedAliasMember;
+					if (qam == null)
+						return false;
+
+					fne = qam.CreateExpressionFromAlias (rc);
+					if (fne == null)
+						return true;
+				}
+
+				Value = ma.Name;
+
+				if (rc.Module.Compiler.Settings.Version < LanguageVersion.V_6)
+					rc.Report.FeatureIsNotAvailable (rc.Module.Compiler, Location, "nameof operator");
+
+				if (ma.HasTypeArguments) {
+					// TODO: csc compatible but unhelpful error message
+					rc.Report.Error (1001, loc, "Identifier expected");
+					return true;
+				}
+					
+				var left = fne.ResolveAsTypeOrNamespace (rc, true);
+				if (left == null)
+					return true;
+
+				var ns = left as NamespaceExpression;
+				if (ns != null) {
+					FullNamedExpression retval = ns.LookupTypeOrNamespace (rc, ma.Name, 0, LookupMode.NameOf, loc);
+					if (retval == null)
+						ns.Error_NamespaceDoesNotExist (rc, ma.Name, 0);
+
+					return true;
+				}
+
+				if (left.Type.IsGenericOrParentIsGeneric && left.Type.GetDefinition () != left.Type) {
+					rc.Report.Error (8071, loc, "Type arguments are not allowed in the nameof operator");
+				}
+
+				var mexpr = MemberLookup (rc, false, left.Type, ma.Name, 0, MemberLookupRestrictions.IgnoreArity | MemberLookupRestrictions.IgnoreAmbiguity, loc);
+				if (mexpr == null) {
+					ma.Error_IdentifierNotFound (rc, left.Type);
+					return true;
+				}
+
+				return true;
+			}
+
+			return false;
+		}
+
+		public Expression ResolveOverload (ResolveContext rc, Arguments args)
+		{
+			if (args == null || args.Count != 1) {
+				name.Error_NameDoesNotExist (rc);
+				return null;
+			}
+
+			var arg = args [0];
+			var res = ResolveArgumentExpression (rc, arg.Expr);
+			if (!res) {
+				name.Error_NameDoesNotExist (rc);
+				return null;
+			}
+
+			type = rc.BuiltinTypes.String;
+			eclass = ExprClass.Value;
+			return this;
+		}
+	}
+
+	//
+	// Null constant can have its own type, think of `default (Foo)'
+	//
+	public class NullConstant : Constant
+	{
+		public NullConstant (TypeSpec type, Location loc)
+			: base (loc)
+		{
+			eclass = ExprClass.Value;
+			this.type = type;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (type == InternalType.NullLiteral || type.BuiltinType == BuiltinTypeSpec.Type.Object) {
+				// Optimized version, also avoids referencing literal internal type
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (this));
+				return CreateExpressionFactoryCall (ec, "Constant", args);
+			}
+
+			return base.CreateExpressionTree (ec);
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			switch (targetType.BuiltinType) {
+			case BuiltinTypeSpec.Type.Object:
+				// Type it as string cast
+				enc.Encode (rc.Module.Compiler.BuiltinTypes.String);
+				goto case BuiltinTypeSpec.Type.String;
+			case BuiltinTypeSpec.Type.String:
+			case BuiltinTypeSpec.Type.Type:
+				enc.Encode (byte.MaxValue);
+				return;
+			default:
+				var ac = targetType as ArrayContainer;
+				if (ac != null && ac.Rank == 1 && !ac.Element.IsArray) {
+					enc.Encode (uint.MaxValue);
+					return;
+				}
+
+				break;
+			}
+
+			base.EncodeAttributeValue (rc, enc, targetType, parameterType);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.EmitNull ();
+
+			// Only to make verifier happy
+			if (type.IsGenericParameter)
+				ec.Emit (OpCodes.Unbox_Any, type);
+		}
+
+		public override string ExprClassName {
+			get {
+				return GetSignatureForError ();
+			}
+		}
+
+		public override Constant ConvertExplicitly (bool inCheckedContext, TypeSpec targetType)
+		{
+			if (targetType.IsPointer) {
+				if (IsLiteral || this is NullPointer)
+					return new NullPointer (targetType, loc);
+
+				return null;
+			}
+
+			// Exlude internal compiler types
+			if (targetType.Kind == MemberKind.InternalCompilerType && targetType.BuiltinType != BuiltinTypeSpec.Type.Dynamic)
+				return null;
+
+			if (!IsLiteral && !Convert.ImplicitStandardConversionExists (this, targetType))
+				return null;
+
+			if (TypeSpec.IsReferenceType (targetType))
+				return new NullConstant (targetType, loc);
+
+			if (targetType.IsNullableType)
+				return Nullable.LiftedNull.Create (targetType, loc);
+
+			return null;
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec targetType)
+		{
+			return ConvertExplicitly (false, targetType);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return "null";
+		}
+
+		public override object GetValue ()
+		{
+			return null;
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return GetSignatureForError ();
+		}
+
+		public override long GetValueAsLong ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override bool IsDefaultValue {
+			get { return true; }
+		}
+
+		public override bool IsNegative {
+			get { return false; }
+		}
+
+		public override bool IsNull {
+			get { return true; }
+		}
+
+		public override bool IsZeroInteger {
+			get { return true; }
+		}
+	}
+
+
+	//
+	// A null constant in a pointer context
+	//
+	class NullPointer : NullConstant
+	{
+		public NullPointer (TypeSpec type, Location loc)
+			: base (type, loc)
+		{
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Error_PointerInsideExpressionTree (ec);
+			return base.CreateExpressionTree (ec);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// Emits null pointer
+			//
+			ec.EmitInt (0);
+			ec.Emit (OpCodes.Conv_U);
+		}
+	}
+
+	/// <summary>
+	///   The value is constant, but when emitted has a side effect.  This is
+	///   used by BitwiseAnd to ensure that the second expression is invoked
+	///   regardless of the value of the left side.  
+	/// </summary>
+	public class SideEffectConstant : Constant
+	{
+		public readonly Constant value;
+		Expression side_effect;
+		
+		public SideEffectConstant (Constant value, Expression side_effect, Location loc)
+			: base (loc)
+		{
+			this.value = value;
+			type = value.Type;
+			eclass = ExprClass.Value;
+
+			while (side_effect is SideEffectConstant)
+				side_effect = ((SideEffectConstant) side_effect).side_effect;
+			this.side_effect = side_effect;
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return false;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return side_effect.ContainsEmitWithAwait ();
+		}
+
+		public override object GetValue ()
+		{
+			return value.GetValue ();
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return value.GetValueAsLiteral ();
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return value.GetValueAsLong ();
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			side_effect.EmitSideEffect (ec);
+			value.Emit (ec);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			side_effect.EmitSideEffect (ec);
+			value.EmitSideEffect (ec);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			side_effect.FlowAnalysis (fc);
+		}
+
+		public override bool IsDefaultValue {
+			get { return value.IsDefaultValue; }
+		}
+
+		public override bool IsNegative {
+			get { return value.IsNegative; }
+		}
+
+		public override bool IsZeroInteger {
+			get { return value.IsZeroInteger; }
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			Constant new_value = value.ConvertExplicitly (in_checked_context, target_type);
+			if (new_value == null)
+				return null;
+
+			var c = new SideEffectConstant (new_value, side_effect, new_value.Location);
+			c.type = target_type;
+			c.eclass = eclass;
+			return c;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/context.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/context.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/context.cs	(revision 11807)
@@ -0,0 +1,751 @@
+﻿//
+// context.cs: Various compiler contexts.
+//
+// Author:
+//   Marek Safar (marek.safar@gmail.com)
+//   Miguel de Icaza (miguel@ximian.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2004-2009 Novell, Inc.
+// Copyright 2011 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+using System.Diagnostics;
+
+namespace Mono.CSharp
+{
+	public enum LookupMode
+	{
+		Normal = 0,
+		Probing = 1,
+		IgnoreAccessibility = 2,
+		NameOf = 3
+	}
+
+	//
+	// Implemented by elements which can act as independent contexts
+	// during resolve phase. Used mostly for lookups.
+	//
+	public interface IMemberContext : IModuleContext
+	{
+		//
+		// A scope type context, it can be inflated for generic types
+		//
+		TypeSpec CurrentType { get; }
+
+		//
+		// A scope type parameters either VAR or MVAR
+		//
+		TypeParameters CurrentTypeParameters { get; }
+
+		//
+		// A member definition of the context. For partial types definition use
+		// CurrentTypeDefinition.PartialContainer otherwise the context is local
+		//
+		// TODO: Obsolete it in this context, dynamic context cannot guarantee sensible value
+		//
+		MemberCore CurrentMemberDefinition { get; }
+
+		bool IsObsolete { get; }
+		bool IsUnsafe { get; }
+		bool IsStatic { get; }
+
+		string GetSignatureForError ();
+
+		ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity);
+		FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc);
+		FullNamedExpression LookupNamespaceAlias (string name);
+	}
+
+	public interface IModuleContext
+	{
+		ModuleContainer Module { get; }
+	}
+
+	//
+	// Block or statement resolving context
+	//
+	public class BlockContext : ResolveContext
+	{
+		readonly TypeSpec return_type;
+
+		//
+		// Tracks the last offset used by VariableInfo
+		//
+		public int AssignmentInfoOffset;
+
+		public BlockContext (IMemberContext mc, ExplicitBlock block, TypeSpec returnType)
+			: base (mc)
+		{
+			if (returnType == null)
+				throw new ArgumentNullException ("returnType");
+
+			this.return_type = returnType;
+
+			// TODO: check for null value
+			CurrentBlock = block;
+		}
+
+		public BlockContext (ResolveContext rc, ExplicitBlock block, TypeSpec returnType)
+			: this (rc.MemberContext, block, returnType)
+		{
+			if (rc.IsUnsafe)
+				flags |= ResolveContext.Options.UnsafeScope;
+
+			if (rc.HasSet (ResolveContext.Options.CheckedScope))
+				flags |= ResolveContext.Options.CheckedScope;
+
+			if (!rc.ConstantCheckState)
+				flags &= ~Options.ConstantCheckState;
+
+			if (rc.IsInProbingMode)
+				flags |= ResolveContext.Options.ProbingMode;
+
+			if (rc.HasSet (ResolveContext.Options.FieldInitializerScope))
+				flags |= ResolveContext.Options.FieldInitializerScope;
+
+			if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
+				flags |= ResolveContext.Options.ExpressionTreeConversion;
+
+			if (rc.HasSet (ResolveContext.Options.BaseInitializer))
+				flags |= ResolveContext.Options.BaseInitializer;
+		}
+
+		public ExceptionStatement CurrentTryBlock { get; set; }
+
+		public LoopStatement EnclosingLoop { get; set; }
+
+		public LoopStatement EnclosingLoopOrSwitch { get; set; }
+
+		public Switch Switch { get; set; }
+
+		public TypeSpec ReturnType {
+			get { return return_type; }
+		}
+	}
+
+	//
+	// Expression resolving context
+	//
+	public class ResolveContext : IMemberContext
+	{
+		[Flags]
+		public enum Options
+		{
+			/// <summary>
+			///   This flag tracks the `checked' state of the compilation,
+			///   it controls whether we should generate code that does overflow
+			///   checking, or if we generate code that ignores overflows.
+			///
+			///   The default setting comes from the command line option to generate
+			///   checked or unchecked code plus any source code changes using the
+			///   checked/unchecked statements or expressions.   Contrast this with
+			///   the ConstantCheckState flag.
+			/// </summary>
+			CheckedScope = 1 << 0,
+
+			/// <summary>
+			///   The constant check state is always set to `true' and cant be changed
+			///   from the command line.  The source code can change this setting with
+			///   the `checked' and `unchecked' statements and expressions. 
+			/// </summary>
+			ConstantCheckState = 1 << 1,
+
+			AllCheckStateFlags = CheckedScope | ConstantCheckState,
+
+			//
+			// unsafe { ... } scope
+			//
+			UnsafeScope = 1 << 2,
+			CatchScope = 1 << 3,
+			FinallyScope = 1 << 4,
+			FieldInitializerScope = 1 << 5,
+			CompoundAssignmentScope = 1 << 6,
+			FixedInitializerScope = 1 << 7,
+			BaseInitializer = 1 << 8,
+
+			//
+			// Inside an enum definition, we do not resolve enumeration values
+			// to their enumerations, but rather to the underlying type/value
+			// This is so EnumVal + EnumValB can be evaluated.
+			//
+			// There is no "E operator + (E x, E y)", so during an enum evaluation
+			// we relax the rules
+			//
+			EnumScope = 1 << 9,
+
+			ConstantScope = 1 << 10,
+
+			ConstructorScope = 1 << 11,
+
+			UsingInitializerScope = 1 << 12,
+
+			LockScope = 1 << 13,
+
+			TryScope = 1 << 14,
+
+			TryWithCatchScope = 1 << 15,
+
+			ConditionalAccessReceiver = 1 << 16,
+
+			///
+			/// Indicates the current context is in probing mode, no errors are reported. 
+			///
+			ProbingMode = 1 << 22,
+
+			//
+			// Return and ContextualReturn statements will set the ReturnType
+			// value based on the expression types of each return statement
+			// instead of the method return type which is initially null.
+			//
+			InferReturnType = 1 << 23,
+
+			OmitDebuggingInfo = 1 << 24,
+
+			ExpressionTreeConversion = 1 << 25,
+
+			InvokeSpecialName = 1 << 26
+		}
+
+		// utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
+		// it's public so that we can use a struct at the callsite
+		public struct FlagsHandle : IDisposable
+		{
+			readonly ResolveContext ec;
+			readonly Options invmask, oldval;
+
+			public FlagsHandle (ResolveContext ec, Options flagsToSet)
+				: this (ec, flagsToSet, flagsToSet)
+			{
+			}
+
+			internal FlagsHandle (ResolveContext ec, Options mask, Options val)
+			{
+				this.ec = ec;
+				invmask = ~mask;
+				oldval = ec.flags & mask;
+				ec.flags = (ec.flags & invmask) | (val & mask);
+
+//				if ((mask & Options.ProbingMode) != 0)
+//					ec.Report.DisableReporting ();
+			}
+
+			public void Dispose ()
+			{
+//				if ((invmask & Options.ProbingMode) == 0)
+//					ec.Report.EnableReporting ();
+
+				ec.flags = (ec.flags & invmask) | oldval;
+			}
+		}
+
+		protected Options flags;
+
+		//
+		// Whether we are inside an anonymous method.
+		//
+		public AnonymousExpression CurrentAnonymousMethod;
+
+		//
+		// Holds a varible used during collection or object initialization.
+		//
+		public Expression CurrentInitializerVariable;
+
+		public Block CurrentBlock;
+
+		public readonly IMemberContext MemberContext;
+
+		public ResolveContext (IMemberContext mc)
+		{
+			if (mc == null)
+				throw new ArgumentNullException ();
+
+			MemberContext = mc;
+
+			//
+			// The default setting comes from the command line option
+			//
+			if (mc.Module.Compiler.Settings.Checked)
+				flags |= Options.CheckedScope;
+
+			//
+			// The constant check state is always set to true
+			//
+			flags |= Options.ConstantCheckState;
+		}
+
+		public ResolveContext (IMemberContext mc, Options options)
+			: this (mc)
+		{
+			flags |= options;
+		}
+
+		#region Properties
+
+		public BuiltinTypes BuiltinTypes {
+			get {
+				return MemberContext.Module.Compiler.BuiltinTypes;
+			}
+		}
+
+		public virtual ExplicitBlock ConstructorBlock {
+			get {
+				return CurrentBlock.Explicit;
+			}
+		}
+
+		//
+		// The current iterator
+		//
+		public Iterator CurrentIterator {
+			get { return CurrentAnonymousMethod as Iterator; }
+		}
+
+		public TypeSpec CurrentType {
+			get { return MemberContext.CurrentType; }
+		}
+
+		public TypeParameters CurrentTypeParameters {
+			get { return MemberContext.CurrentTypeParameters; }
+		}
+
+		public MemberCore CurrentMemberDefinition {
+			get { return MemberContext.CurrentMemberDefinition; }
+		}
+
+		public bool ConstantCheckState {
+			get { return (flags & Options.ConstantCheckState) != 0; }
+		}
+
+		public bool IsInProbingMode {
+			get {
+				return (flags & Options.ProbingMode) != 0;
+			}
+		}
+
+		public bool IsObsolete {
+			get {
+				// Disables obsolete checks when probing is on
+				return MemberContext.IsObsolete;
+			}
+		}
+
+		public bool IsStatic {
+			get {
+				return MemberContext.IsStatic;
+			}
+		}
+
+		public bool IsUnsafe {
+			get {
+				return HasSet (Options.UnsafeScope) || MemberContext.IsUnsafe;
+			}
+		}
+
+		public bool IsRuntimeBinder {
+			get {
+				return Module.Compiler.IsRuntimeBinder;
+			}
+		}
+
+		public bool IsVariableCapturingRequired {
+			get {
+				return !IsInProbingMode;
+			}
+		}
+
+		public ModuleContainer Module {
+			get {
+				return MemberContext.Module;
+			}
+		}
+
+		public Report Report {
+			get {
+				return Module.Compiler.Report;
+			}
+		}
+
+		#endregion
+
+		public bool MustCaptureVariable (INamedBlockVariable local)
+		{
+			if (CurrentAnonymousMethod == null)
+				return false;
+
+			//
+			// Capture only if this or any of child blocks contain yield
+			// or it's a parameter
+			//
+			if (CurrentAnonymousMethod.IsIterator)
+				return local.IsParameter || local.Block.Explicit.HasYield;
+
+			//
+			// Capture only if this or any of child blocks contain await
+			// or it's a parameter or we need to access variable from 
+			// different parameter block
+			//
+			if (CurrentAnonymousMethod is AsyncInitializer)
+				return local.IsParameter || local.Block.Explicit.HasAwait || CurrentBlock.Explicit.HasAwait ||
+					local.Block.ParametersBlock != CurrentBlock.ParametersBlock.Original;
+
+			return local.Block.ParametersBlock != CurrentBlock.ParametersBlock.Original;
+		}
+
+		public bool HasSet (Options options)
+		{
+			return (this.flags & options) == options;
+		}
+
+		public bool HasAny (Options options)
+		{
+			return (this.flags & options) != 0;
+		}
+
+
+		// Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
+		public FlagsHandle Set (Options options)
+		{
+			return new FlagsHandle (this, options);
+		}
+
+		public FlagsHandle With (Options options, bool enable)
+		{
+			return new FlagsHandle (this, options, enable ? options : 0);
+		}
+
+		#region IMemberContext Members
+
+		public string GetSignatureForError ()
+		{
+			return MemberContext.GetSignatureForError ();
+		}
+
+		public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
+		{
+			return MemberContext.LookupExtensionMethod (extensionType, name, arity);
+		}
+
+		public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			return MemberContext.LookupNamespaceOrType (name, arity, mode, loc);
+		}
+
+		public FullNamedExpression LookupNamespaceAlias (string name)
+		{
+			return MemberContext.LookupNamespaceAlias (name);
+		}
+
+		#endregion
+	}
+
+	public class FlowAnalysisContext
+	{
+		readonly CompilerContext ctx;
+		DefiniteAssignmentBitSet conditional_access;
+
+		public FlowAnalysisContext (CompilerContext ctx, ParametersBlock parametersBlock, int definiteAssignmentLength)
+		{
+			this.ctx = ctx;
+			this.ParametersBlock = parametersBlock;
+
+			DefiniteAssignment = definiteAssignmentLength == 0 ?
+				DefiniteAssignmentBitSet.Empty :
+				new DefiniteAssignmentBitSet (definiteAssignmentLength);
+		}
+
+		public DefiniteAssignmentBitSet DefiniteAssignment { get; set; }
+
+		public DefiniteAssignmentBitSet DefiniteAssignmentOnTrue { get; set; }
+
+		public DefiniteAssignmentBitSet DefiniteAssignmentOnFalse { get; set; }
+
+		public List<LabeledStatement> LabelStack { get; set; }
+
+		public ParametersBlock ParametersBlock { get; set; }
+
+		public Report Report {
+			get {
+				return ctx.Report;
+			}
+		}
+
+		public DefiniteAssignmentBitSet SwitchInitialDefinitiveAssignment { get; set; }
+
+		public TryFinally TryFinally { get; set; }
+
+		public bool UnreachableReported { get; set; }
+
+		public DefiniteAssignmentBitSet BranchDefiniteAssignment ()
+		{
+			var dat = DefiniteAssignment;
+			if (dat != DefiniteAssignmentBitSet.Empty)
+				DefiniteAssignment = new DefiniteAssignmentBitSet (dat);
+			return dat;
+		}
+
+		public void BranchConditionalAccessDefiniteAssignment ()
+		{
+			if (conditional_access == null)
+				conditional_access = BranchDefiniteAssignment ();
+		}
+
+		public void ConditionalAccessEnd ()
+		{
+			Debug.Assert (conditional_access != null);
+			DefiniteAssignment = conditional_access;
+			conditional_access = null;
+		}
+
+		public bool IsDefinitelyAssigned (VariableInfo variable)
+		{
+			return variable.IsAssigned (DefiniteAssignment);
+		}
+
+		public bool IsStructFieldDefinitelyAssigned (VariableInfo variable, string name)
+		{
+			return variable.IsStructFieldAssigned (DefiniteAssignment, name);
+		}
+
+		public void SetVariableAssigned (VariableInfo variable, bool generatedAssignment = false)
+		{
+			variable.SetAssigned (DefiniteAssignment, generatedAssignment);
+		}
+
+		public void SetStructFieldAssigned (VariableInfo variable, string name)
+		{
+			variable.SetStructFieldAssigned (DefiniteAssignment, name);
+		}
+	}
+
+
+	//
+	// This class is used during the Statement.Clone operation
+	// to remap objects that have been cloned.
+	//
+	// Since blocks are cloned by Block.Clone, we need a way for
+	// expressions that must reference the block to be cloned
+	// pointing to the new cloned block.
+	//
+	public class CloneContext
+	{
+		Dictionary<Block, Block> block_map = new Dictionary<Block, Block> ();
+
+		public void AddBlockMap (Block from, Block to)
+		{
+			block_map.Add (from, to);
+		}
+
+		public Block LookupBlock (Block from)
+		{
+			Block result;
+			if (!block_map.TryGetValue (from, out result)) {
+				result = (Block) from.Clone (this);
+			}
+
+			return result;
+		}
+
+		///
+		/// Remaps block to cloned copy if one exists.
+		///
+		public Block RemapBlockCopy (Block from)
+		{
+			Block mapped_to;
+			if (!block_map.TryGetValue (from, out mapped_to))
+				return from;
+
+			return mapped_to;
+		}
+	}
+
+	//
+	// Main compiler context
+	//
+	public class CompilerContext
+	{
+		static readonly TimeReporter DisabledTimeReporter = new TimeReporter (false);
+
+		readonly Report report;
+		readonly BuiltinTypes builtin_types;
+		readonly CompilerSettings settings;
+
+		Dictionary<string, SourceFile> all_source_files;
+
+		public CompilerContext (CompilerSettings settings, ReportPrinter reportPrinter)
+		{
+			this.settings = settings;
+			this.report = new Report (this, reportPrinter);
+			this.builtin_types = new BuiltinTypes ();
+			this.TimeReporter = DisabledTimeReporter;
+		}
+
+		#region Properties
+
+		public BuiltinTypes BuiltinTypes {
+			get {
+				return builtin_types;
+			}
+		}
+
+		// Used for special handling of runtime dynamic context mostly
+		// by error reporting but also by member accessibility checks
+		public bool IsRuntimeBinder {
+			get; set;
+		}
+
+		public Report Report {
+			get {
+				return report;
+			}
+		}
+
+		public CompilerSettings Settings {
+			get {
+				return settings;
+			}
+		}
+
+		public List<SourceFile> SourceFiles {
+			get {
+				return settings.SourceFiles;
+			}
+		}
+
+		internal TimeReporter TimeReporter {
+			get; set;
+		}
+
+		#endregion
+
+		//
+		// This is used when we encounter a #line preprocessing directive during parsing
+		// to register additional source file names
+		//
+		public SourceFile LookupFile (CompilationSourceFile comp_unit, string name)
+		{
+			if (all_source_files == null) {
+				all_source_files = new Dictionary<string, SourceFile> ();
+				foreach (var source in SourceFiles)
+					all_source_files[source.FullPathName] = source;
+			}
+
+			string path;
+			if (!Path.IsPathRooted (name)) {
+				var loc = comp_unit.SourceFile;
+				string root = Path.GetDirectoryName (loc.FullPathName);
+				path = Path.GetFullPath (Path.Combine (root, name));
+				var dir = Path.GetDirectoryName (loc.Name);
+				if (!string.IsNullOrEmpty (dir))
+					name = Path.Combine (dir, name);
+			} else
+				path = name;
+
+			SourceFile retval;
+			if (all_source_files.TryGetValue (path, out retval))
+				return retval;
+
+			retval = new SourceFile (name, path, all_source_files.Count + 1);
+			Location.AddFile (retval);
+			all_source_files.Add (path, retval);
+			return retval;
+		}
+	}
+
+	//
+	// Generic code emitter context
+	//
+	public class BuilderContext
+	{
+		[Flags]
+		public enum Options
+		{
+			/// <summary>
+			///   This flag tracks the `checked' state of the compilation,
+			///   it controls whether we should generate code that does overflow
+			///   checking, or if we generate code that ignores overflows.
+			///
+			///   The default setting comes from the command line option to generate
+			///   checked or unchecked code plus any source code changes using the
+			///   checked/unchecked statements or expressions.   Contrast this with
+			///   the ConstantCheckState flag.
+			/// </summary>
+			CheckedScope = 1 << 0,
+
+			AccurateDebugInfo = 1 << 1,
+
+			OmitDebugInfo = 1 << 2,
+
+			ConstructorScope = 1 << 3,
+
+			AsyncBody = 1 << 4,
+		}
+
+		// utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
+		// it's public so that we can use a struct at the callsite
+		public struct FlagsHandle : IDisposable
+		{
+			readonly BuilderContext ec;
+			readonly Options invmask, oldval;
+
+			public FlagsHandle (BuilderContext ec, Options flagsToSet)
+				: this (ec, flagsToSet, flagsToSet)
+			{
+			}
+
+			internal FlagsHandle (BuilderContext ec, Options mask, Options val)
+			{
+				this.ec = ec;
+				invmask = ~mask;
+				oldval = ec.flags & mask;
+				ec.flags = (ec.flags & invmask) | (val & mask);
+			}
+
+			public void Dispose ()
+			{
+				ec.flags = (ec.flags & invmask) | oldval;
+			}
+		}
+
+		protected Options flags;
+
+		public bool HasSet (Options options)
+		{
+			return (this.flags & options) == options;
+		}
+
+		// Temporarily set all the given flags to the given value.  Should be used in an 'using' statement
+		public FlagsHandle With (Options options, bool enable)
+		{
+			return new FlagsHandle (this, options, enable ? options : 0);
+		}
+	}
+
+	//
+	// Parser session objects. We could recreate all these objects for each parser
+	// instance but the best parser performance the session object can be reused
+	//
+	public class ParserSession
+	{
+		MD5 md5;
+
+		public readonly char[] StreamReaderBuffer = new char[SeekableStreamReader.DefaultReadAheadSize * 2];
+		public readonly Dictionary<char[], string>[] Identifiers = new Dictionary<char[], string>[Tokenizer.MaxIdentifierLength + 1];
+		public readonly List<Parameter> ParametersStack = new List<Parameter> (4);
+		public readonly char[] IDBuilder = new char[Tokenizer.MaxIdentifierLength];
+		public readonly char[] NumberBuilder = new char[Tokenizer.MaxNumberLength];
+
+		public LocationsBag LocationsBag { get; set; }
+		public bool UseJayGlobalArrays { get; set; }
+		public LocatedToken[] LocatedTokens { get; set; }
+
+		public MD5 GetChecksumAlgorithm ()
+		{
+			return md5 ?? (md5 = MD5.Create ());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/convert.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/convert.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/convert.cs	(revision 11807)
@@ -0,0 +1,2266 @@
+//
+// conversion.cs: various routines for implementing conversions.
+//
+// Authors:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Ravi Pratap (ravi@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc (http://www.xamarin.com)
+//
+
+using System;
+using System.Collections.Generic;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	//
+	// A container class for all the conversion operations
+	//
+	static class Convert
+	{
+		[Flags]
+		public enum UserConversionRestriction
+		{
+			None = 0,
+			ImplicitOnly = 1,
+			ProbingOnly = 1 << 1,
+			NullableSourceOnly = 1 << 2
+
+		}
+		//
+		// From a one-dimensional array-type S[] to System.Collections.IList<T> and base
+		// interfaces of this interface, provided there is an implicit reference conversion
+		// from S to T.
+		//
+		static bool ArrayToIList (ArrayContainer array, TypeSpec list, bool isExplicit)
+		{
+			if (array.Rank != 1 || !list.IsArrayGenericInterface)
+				return false;
+
+			var arg_type = list.TypeArguments[0];
+			if (array.Element == arg_type)
+				return true;
+
+			//
+			// Reject conversion from T[] to IList<U> even if T has U dependency
+			//
+			if (arg_type.IsGenericParameter)
+				return false;
+
+			if (isExplicit)
+				return ExplicitReferenceConversionExists (array.Element, arg_type);
+
+			return ImplicitReferenceConversionExists (array.Element, arg_type);
+		}
+		
+		static bool IList_To_Array(TypeSpec list, ArrayContainer array)
+		{
+			if (array.Rank != 1 || !list.IsArrayGenericInterface)
+				return false;
+
+			var arg_type = list.TypeArguments[0];
+			if (array.Element == arg_type)
+				return true;
+			
+			return ImplicitReferenceConversionExists (array.Element, arg_type) || ExplicitReferenceConversionExists (array.Element, arg_type);
+		}
+
+		public static Expression ImplicitTypeParameterConversion (Expression expr, TypeParameterSpec expr_type, TypeSpec target_type)
+		{
+			//
+			// From T to a type parameter U, provided T depends on U
+			//
+			if (target_type.IsGenericParameter) {
+				if (expr_type.TypeArguments != null && expr_type.HasDependencyOn (target_type)) {
+					if (expr == null)
+						return EmptyExpression.Null;
+
+					if (expr_type.IsReferenceType && !((TypeParameterSpec) target_type).IsReferenceType)
+						return new BoxedCast (expr, target_type);
+
+					return new ClassCast (expr, target_type);
+				}
+
+				return null;
+			}
+
+			//
+			// LAMESPEC: From T to dynamic type because it's like T to object
+			//
+			if (target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				if (expr == null)
+					return EmptyExpression.Null;
+
+				if (expr_type.IsReferenceType)
+					return new ClassCast (expr, target_type);
+
+				return new BoxedCast (expr, target_type);
+			}
+
+			//
+			// From T to its effective base class C
+			// From T to any base class of C (it cannot contain dynamic or be of dynamic type)
+			// From T to any interface implemented by C
+			//
+			var base_type = expr_type.GetEffectiveBase ();
+			if (base_type == target_type || TypeSpec.IsBaseClass (base_type, target_type, false) || base_type.ImplementsInterface (target_type, true)) {
+				if (expr == null)
+					return EmptyExpression.Null;
+
+				if (expr_type.IsReferenceType)
+					return new ClassCast (expr, target_type);
+
+				return new BoxedCast (expr, target_type);
+			}
+
+			if (target_type.IsInterface && expr_type.IsConvertibleToInterface (target_type)) {
+				if (expr == null)
+					return EmptyExpression.Null;
+
+				if (expr_type.IsReferenceType)
+					return new ClassCast (expr, target_type);
+
+				return new BoxedCast (expr, target_type);
+			}
+
+			return null;
+		}
+
+		static Expression ExplicitTypeParameterConversionFromT (Expression source, TypeSpec source_type, TypeSpec target_type)
+		{
+			var target_tp = target_type as TypeParameterSpec;
+			if (target_tp != null) {
+				//
+				// From a type parameter U to T, provided T depends on U
+				//
+				if (target_tp.TypeArguments != null && target_tp.HasDependencyOn (source_type)) {
+					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+				}
+			}
+
+			//
+			// From T to any interface-type I provided there is not already an implicit conversion from T to I
+			//
+			if (target_type.IsInterface)
+				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
+
+			return null;
+		}
+
+		static Expression ExplicitTypeParameterConversionToT (Expression source, TypeSpec source_type, TypeParameterSpec target_type)
+		{
+			//
+			// From the effective base class C of T to T and from any base class of C to T
+			//
+			var effective = target_type.GetEffectiveBase ();
+			if (TypeSpecComparer.IsEqual (effective, source_type) || TypeSpec.IsBaseClass (effective, source_type, false))
+				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+
+			return null;
+		}
+
+		public static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
+		{
+			TypeSpec expr_type = expr.Type;
+
+			if (expr_type.Kind == MemberKind.TypeParameter)
+				return ImplicitTypeParameterConversion (expr, (TypeParameterSpec) expr.Type, target_type);
+
+			//
+			// from the null type to any reference-type.
+			//
+			NullLiteral nl = expr as NullLiteral;
+			if (nl != null) {
+				return nl.ConvertImplicitly (target_type);
+			}
+
+			if (ImplicitReferenceConversionExists (expr_type, target_type)) {
+				// 
+				// Avoid wrapping implicitly convertible reference type
+				//
+				if (!explicit_cast)
+					return expr;
+
+				return EmptyCast.Create (expr, target_type);
+			}
+
+			return null;
+		}
+
+		//
+		// Implicit reference conversions
+		//
+		public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type)
+		{
+			return ImplicitReferenceConversionExists (expr_type, target_type, true);
+		}
+
+		public static bool ImplicitReferenceConversionExists (TypeSpec expr_type, TypeSpec target_type, bool refOnlyTypeParameter)
+		{
+			// It's here only to speed things up
+			if (target_type.IsStruct)
+				return false;
+
+			switch (expr_type.Kind) {
+			case MemberKind.TypeParameter:
+				return ImplicitTypeParameterConversion (null, (TypeParameterSpec) expr_type, target_type) != null &&
+					(!refOnlyTypeParameter || TypeSpec.IsReferenceType (expr_type));
+
+			case MemberKind.Class:
+				//
+				// From any class-type to dynamic (+object to speed up common path)
+				//
+				if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					return true;
+
+				if (target_type.IsClass) {
+					//
+					// Identity conversion, including dynamic erasure
+					//
+					if (TypeSpecComparer.IsEqual (expr_type, target_type))
+						return true;
+
+					//
+					// From any class-type S to any class-type T, provided S is derived from T
+					//
+					return TypeSpec.IsBaseClass (expr_type, target_type, true);
+				}
+
+				//
+				// From any class-type S to any interface-type T, provided S implements T
+				//
+				if (target_type.IsInterface)
+					return expr_type.ImplementsInterface (target_type, true);
+
+				return false;
+
+			case MemberKind.ArrayType:
+				//
+				// Identity array conversion
+				//
+				if (expr_type == target_type)
+					return true;
+
+				//
+				// From any array-type to System.Array
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Array:
+				case BuiltinTypeSpec.Type.Object:
+				case BuiltinTypeSpec.Type.Dynamic:
+					return true;
+				}
+
+				var expr_type_array = (ArrayContainer) expr_type;
+				var target_type_array = target_type as ArrayContainer;
+
+				//
+				// From an array-type S to an array-type of type T
+				//
+				if (target_type_array != null && expr_type_array.Rank == target_type_array.Rank) {
+
+					//
+					// Both SE and TE are reference-types. TE check is defered
+					// to ImplicitReferenceConversionExists
+					//
+					TypeSpec expr_element_type = expr_type_array.Element;
+					if (!TypeSpec.IsReferenceType (expr_element_type))
+						return false;
+
+					//
+					// An implicit reference conversion exists from SE to TE
+					//
+					return ImplicitReferenceConversionExists (expr_element_type, target_type_array.Element);
+				}
+
+				//
+				// From any array-type to the interfaces it implements
+				//
+				if (target_type.IsInterface) {
+					if (expr_type.ImplementsInterface (target_type, false))
+						return true;
+
+					// from an array-type of type T to IList<T>
+					if (ArrayToIList (expr_type_array, target_type, false))
+						return true;
+				}
+
+				return false;
+
+			case MemberKind.Delegate:
+				//
+				// From any delegate-type to System.Delegate (and its base types)
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Delegate:
+				case BuiltinTypeSpec.Type.MulticastDelegate:
+				case BuiltinTypeSpec.Type.Object:
+				case BuiltinTypeSpec.Type.Dynamic:
+					return true;
+				}
+
+				//
+				// Identity conversion, including dynamic erasure
+				//
+				if (TypeSpecComparer.IsEqual (expr_type, target_type))
+					return true;
+
+				//
+				// From any delegate-type to the interfaces it implements
+				// From any reference-type to an delegate type if is variance-convertible
+				//
+				return expr_type.ImplementsInterface (target_type, false) || TypeSpecComparer.Variant.IsEqual (expr_type, target_type);
+
+			case MemberKind.Interface:
+				//
+				// Identity conversion, including dynamic erasure
+				//
+				if (TypeSpecComparer.IsEqual (expr_type, target_type))
+					return true;
+
+				//
+				// From any interface type S to interface-type T
+				// From any reference-type to an interface if is variance-convertible
+				//
+				if (target_type.IsInterface)
+					return TypeSpecComparer.Variant.IsEqual (expr_type, target_type) || expr_type.ImplementsInterface (target_type, true);
+
+				return target_type.BuiltinType == BuiltinTypeSpec.Type.Object || target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+
+			case MemberKind.InternalCompilerType:
+				//
+				// from the null literal to any reference-type.
+				//
+				if (expr_type == InternalType.NullLiteral) {
+					// Exlude internal compiler types
+					if (target_type.Kind == MemberKind.InternalCompilerType)
+						return target_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+
+					return TypeSpec.IsReferenceType (target_type) || target_type.Kind == MemberKind.PointerType;
+				}
+
+				//
+				// Implicit dynamic conversion
+				//
+				if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					switch (target_type.Kind) {
+					case MemberKind.ArrayType:
+					case MemberKind.Class:
+					case MemberKind.Delegate:
+					case MemberKind.Interface:
+					case MemberKind.TypeParameter:
+						return true;
+					}
+
+					// dynamic to __arglist
+					if (target_type == InternalType.Arglist)
+						return true;
+
+					return false;
+				}
+
+				break;
+			}
+
+			return false;
+		}
+
+		public static Expression ImplicitBoxingConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
+		{
+			switch (target_type.BuiltinType) {
+			//
+			// From any non-nullable-value-type to the type object and dynamic
+			//
+			case BuiltinTypeSpec.Type.Object:
+			case BuiltinTypeSpec.Type.Dynamic:
+			//
+			// From any non-nullable-value-type to the type System.ValueType
+			//
+			case BuiltinTypeSpec.Type.ValueType:
+				//
+				// No ned to check for nullable type as underlying type is always convertible
+				//
+				if (!TypeSpec.IsValueType (expr_type))
+					return null;
+
+				return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
+
+			case BuiltinTypeSpec.Type.Enum:
+				//
+				// From any enum-type to the type System.Enum.
+				//
+				if (expr_type.IsEnum)
+					return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
+
+				break;
+			}
+
+			//
+			// From a nullable-type to a reference type, if a boxing conversion exists from
+			// the underlying type to the reference type
+			//
+			if (expr_type.IsNullableType) {
+				if (!TypeSpec.IsReferenceType (target_type))
+					return null;
+
+				var res = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
+
+				// "cast" underlying type to target type to emit correct InvalidCastException when
+				// underlying hierarchy changes without recompilation
+				if (res != null && expr != null)
+					res = new UnboxCast (res, target_type);
+
+				return res;
+			}
+
+			//
+			// A value type has a boxing conversion to an interface type I if it has a boxing conversion
+			// to an interface or delegate type I0 and I0 is variance-convertible to I
+			//
+			if (target_type.IsInterface && TypeSpec.IsValueType (expr_type) && expr_type.ImplementsInterface (target_type, true)) {
+				return expr == null ? EmptyExpression.Null : new BoxedCast (expr, target_type);
+			}
+
+			return null;
+		}
+
+		public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, TypeSpec target_type)
+		{
+			TypeSpec expr_type = expr.Type;
+
+			//
+			// From null to any nullable type
+			//
+			if (expr_type == InternalType.NullLiteral)
+				return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);
+
+			// S -> T?
+			TypeSpec t_el = Nullable.NullableInfo.GetUnderlyingType (target_type);
+
+			// S? -> T?
+			if (expr_type.IsNullableType)
+				expr_type = Nullable.NullableInfo.GetUnderlyingType (expr_type);
+
+			//
+			// Predefined implicit identity or implicit numeric conversion
+			// has to exist between underlying type S and underlying type T
+			//
+
+			// conversion exists only mode
+			if (ec == null) {
+				if (TypeSpecComparer.IsEqual (expr_type, t_el))
+					return EmptyExpression.Null;
+
+				if (expr is Constant)
+					return ((Constant) expr).ConvertImplicitly (t_el);
+
+				return ImplicitNumericConversion (null, expr_type, t_el);
+			}
+
+			Expression unwrap;
+			if (expr_type != expr.Type)
+				unwrap = Nullable.Unwrap.Create (expr);
+			else
+				unwrap = expr;
+
+			Expression conv = unwrap;
+			if (!TypeSpecComparer.IsEqual (expr_type, t_el)) {
+				if (conv is Constant)
+					conv = ((Constant)conv).ConvertImplicitly (t_el);
+				else
+					conv = ImplicitNumericConversion (conv, expr_type, t_el);
+
+				if (conv == null)
+					return null;
+			}
+			
+			if (expr_type != expr.Type)
+				return new Nullable.LiftedConversion (conv, unwrap, target_type).Resolve (ec);
+
+			return Nullable.Wrap.Create (conv, target_type);
+		}
+
+		/// <summary>
+		///   Implicit Numeric Conversions.
+		///
+		///   expr is the expression to convert, returns a new expression of type
+		///   target_type or null if an implicit conversion is not possible.
+		/// </summary>
+		public static Expression ImplicitNumericConversion (Expression expr, TypeSpec target_type)
+		{
+			return ImplicitNumericConversion (expr, expr.Type, target_type);
+		}
+
+		public static bool ImplicitNumericConversionExists (TypeSpec expr_type, TypeSpec target_type)
+		{
+			return ImplicitNumericConversion (null, expr_type, target_type) != null;
+		}
+
+		static Expression ImplicitNumericConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
+		{
+			switch (expr_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+				//
+				// From sbyte to short, int, long, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Int:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Short:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+
+				}
+
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				//
+				// From byte to short, ushort, int, uint, long, ulong, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Int:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.Short:
+				case BuiltinTypeSpec.Type.UShort:
+					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
+				case BuiltinTypeSpec.Type.ULong:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				//
+				// From short to int, long, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Int:
+					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+				//
+				// From ushort to int, uint, long, ulong, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Int:
+				case BuiltinTypeSpec.Type.UInt:
+					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
+				case BuiltinTypeSpec.Type.ULong:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Int:
+				//
+				// From int to long, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				//
+				// From uint to long, ulong, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
+				case BuiltinTypeSpec.Type.ULong:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				//
+				// From long to float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+				//
+				// From ulong to float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCastDuplex (expr, target_type, OpCodes.Conv_R_Un, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Char:
+				//
+				// From char to ushort, int, uint, long, ulong, float, double, decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.Int:
+				case BuiltinTypeSpec.Type.UInt:
+					return expr == null ? EmptyExpression.Null : EmptyCast.Create (expr, target_type);
+				case BuiltinTypeSpec.Type.ULong:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
+				case BuiltinTypeSpec.Type.Long:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
+				case BuiltinTypeSpec.Type.Float:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+				case BuiltinTypeSpec.Type.Double:
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				case BuiltinTypeSpec.Type.Decimal:
+					return expr == null ? EmptyExpression.Null : new OperatorCast (expr, target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Float:
+				//
+				// float to double
+				//
+				if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
+					return expr == null ? EmptyExpression.Null : new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				break;
+			}
+
+			return null;
+		}
+
+		//
+		// Full version of implicit conversion
+		//
+		public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, TypeSpec target_type)
+		{
+			if (ImplicitStandardConversionExists (ec, expr, target_type))
+				return true;
+
+			if (expr.Type == InternalType.AnonymousMethod) {
+				if (!target_type.IsDelegate && !target_type.IsExpressionTreeType)
+					return false;
+
+				AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
+				return ame.ImplicitStandardConversionExists (ec, target_type);
+			}
+			
+			// Conversion from __arglist to System.ArgIterator
+			if (expr.Type == InternalType.Arglist)
+				return target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec;
+
+			return UserDefinedConversion (ec, expr, target_type,
+				UserConversionRestriction.ImplicitOnly | UserConversionRestriction.ProbingOnly, Location.Null) != null;
+		}
+
+		public static bool ImplicitStandardConversionExists (ResolveContext rc, Expression expr, TypeSpec target_type)
+		{
+			if (expr.eclass == ExprClass.MethodGroup) {
+				if (target_type.IsDelegate && rc.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
+					MethodGroupExpr mg = expr as MethodGroupExpr;
+					if (mg != null)
+						return DelegateCreation.ImplicitStandardConversionExists (rc, mg, target_type);
+				}
+
+				return false;
+			}
+
+			return ImplicitStandardConversionExists (expr, target_type);
+		}
+
+		//
+		// Implicit standard conversion (only core conversions are used here)
+		//
+		public static bool ImplicitStandardConversionExists (Expression expr, TypeSpec target_type)
+		{
+			//
+			// Identity conversions
+			// Implicit numeric conversions
+			// Implicit nullable conversions
+			// Implicit reference conversions
+			// Boxing conversions
+			// Implicit constant expression conversions
+			// Implicit conversions involving type parameters
+			//
+
+			TypeSpec expr_type = expr.Type;
+
+			if (expr_type == target_type)
+				return true;
+
+			if (target_type.IsNullableType)
+				return ImplicitNulableConversion (null, expr, target_type) != null;
+
+			if (ImplicitNumericConversion (null, expr_type, target_type) != null)
+				return true;
+
+			if (ImplicitReferenceConversionExists (expr_type, target_type, false))
+				return true;
+
+			if (ImplicitBoxingConversion (null, expr_type, target_type) != null)
+				return true;
+			
+			//
+			// Implicit Constant Expression Conversions
+			//
+			if (expr is IntConstant){
+				int value = ((IntConstant) expr).Value;
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					if (value >= SByte.MinValue && value <= SByte.MaxValue)
+						return true;
+					break;
+				case BuiltinTypeSpec.Type.Byte:
+					if (value >= 0 && value <= Byte.MaxValue)
+						return true;
+					break;
+				case BuiltinTypeSpec.Type.Short:
+					if (value >= Int16.MinValue && value <= Int16.MaxValue)
+						return true;
+					break;
+				case BuiltinTypeSpec.Type.UShort:
+					if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
+						return true;
+					break;
+				case BuiltinTypeSpec.Type.UInt:
+					if (value >= 0)
+						return true;
+					break;
+				case BuiltinTypeSpec.Type.ULong:
+					 //
+					 // we can optimize this case: a positive int32
+					 // always fits on a uint64.  But we need an opcode
+					 // to do it.
+					 //
+					if (value >= 0)
+						return true;
+
+					break;
+				}
+			}
+
+			if (expr is LongConstant && target_type.BuiltinType == BuiltinTypeSpec.Type.ULong){
+				//
+				// Try the implicit constant expression conversion
+				// from long to ulong, instead of a nice routine,
+				// we just inline it
+				//
+				long v = ((LongConstant) expr).Value;
+				if (v >= 0)
+					return true;
+			}
+
+			if (expr is IntegralConstant && target_type.IsEnum) {
+				var i = (IntegralConstant) expr;
+				//
+				// LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
+				//
+				// An implicit enumeration conversion permits the decimal-integer-literal 0
+				// to be converted to any enum-type and to any nullable-type whose underlying
+				// type is an enum-type
+				//
+				return i.IsZeroInteger;
+			}
+
+			//
+			// Implicit dynamic conversion for remaining value types. It should probably
+			// go somewhere else
+			//
+			if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				switch (target_type.Kind) {
+				case MemberKind.Struct:
+				case MemberKind.Enum:
+					return true;
+				}
+
+				return false;
+			}
+
+			//
+			// In an unsafe context implicit conversions is extended to include
+			//
+			// From any pointer-type to the type void*
+			// From the null literal to any pointer-type.
+			//
+			// LAMESPEC: The specification claims this conversion is allowed in implicit conversion but
+			// in reality implicit standard conversion uses it
+			//
+			if (target_type.IsPointer && expr.Type.IsPointer && ((PointerContainer) target_type).Element.Kind == MemberKind.Void)
+				return true;
+
+			//
+			// Struct identity conversion, including dynamic erasure
+			//
+			if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
+				return true;
+
+			return false;
+		}
+
+		/// <summary>
+		///  Finds "most encompassed type" according to the spec (13.4.2)
+		///  amongst the methods in the MethodGroupExpr
+		/// </summary>
+		public static TypeSpec FindMostEncompassedType (IList<TypeSpec> types)
+		{
+			TypeSpec best = null;
+			EmptyExpression expr;
+
+			foreach (TypeSpec t in types) {
+				if (best == null) {
+					best = t;
+					continue;
+				}
+
+				expr = new EmptyExpression (t);
+				if (ImplicitStandardConversionExists (expr, best))
+					best = t;
+			}
+
+			expr = new EmptyExpression (best);
+			foreach (TypeSpec t in types) {
+				if (best == t)
+					continue;
+				if (!ImplicitStandardConversionExists (expr, t)) {
+					best = null;
+					break;
+				}
+			}
+
+			return best;
+		}
+
+		//
+		// Finds the most encompassing type (type into which all other
+		// types can convert to) amongst the types in the given set
+		//
+		static TypeSpec FindMostEncompassingType (IList<TypeSpec> types)
+		{
+			if (types.Count == 0)
+				return null;
+
+			if (types.Count == 1)
+				return types [0];
+
+			TypeSpec best = null;
+			for (int i = 0; i < types.Count; ++i) {
+				int ii = 0;
+				for (; ii < types.Count; ++ii) {
+					if (ii == i)
+						continue;
+
+					var expr = new EmptyExpression (types[ii]);
+					if (!ImplicitStandardConversionExists (expr, types [i])) {
+						ii = 0;
+						break;
+					}
+				}
+
+				if (ii == 0)
+					continue;
+
+				if (best == null) {
+					best = types[i];
+					continue;
+				}
+
+				// Indicates multiple best types
+				return InternalType.FakeInternalType;
+			}
+
+			return best;
+		}
+
+		//
+		// Finds the most specific source Sx according to the rules of the spec (13.4.4)
+		// by making use of FindMostEncomp* methods. Applies the correct rules separately
+		// for explicit and implicit conversion operators.
+		//
+		static TypeSpec FindMostSpecificSource (ResolveContext rc, List<MethodSpec> list, TypeSpec sourceType, Expression source, bool apply_explicit_conv_rules)
+		{
+			TypeSpec[] src_types_set = null;
+
+			//
+			// Try exact match first, if any operator converts from S then Sx = S
+			//
+			for (int i = 0; i < list.Count; ++i) {
+				TypeSpec param_type = list [i].Parameters.Types [0];
+
+				if (param_type == sourceType)
+					return param_type;
+
+				if (src_types_set == null)
+					src_types_set = new TypeSpec [list.Count];
+
+				src_types_set [i] = param_type;
+			}
+
+			//
+			// Explicit Conv rules
+			//
+			if (apply_explicit_conv_rules) {
+				var candidate_set = new List<TypeSpec> ();
+
+				foreach (TypeSpec param_type in src_types_set){
+					if (ImplicitStandardConversionExists (rc, source, param_type))
+						candidate_set.Add (param_type);
+				}
+
+				if (candidate_set.Count != 0) {
+					if (source.eclass == ExprClass.MethodGroup)
+						return InternalType.FakeInternalType;
+
+					return FindMostEncompassedType (candidate_set);
+				}
+			}
+
+			//
+			// Final case
+			//
+			if (apply_explicit_conv_rules)
+				return FindMostEncompassingType (src_types_set);
+			else
+				return FindMostEncompassedType (src_types_set);
+		}
+
+		/// <summary>
+		///  Finds the most specific target Tx according to section 13.4.4
+		/// </summary>
+		static public TypeSpec FindMostSpecificTarget (IList<MethodSpec> list,
+							   TypeSpec target, bool apply_explicit_conv_rules)
+		{
+			List<TypeSpec> tgt_types_set = null;
+
+			//
+			// If any operator converts to T then Tx = T
+			//
+			foreach (var mi in list){
+				TypeSpec ret_type = mi.ReturnType;
+				if (ret_type == target)
+					return ret_type;
+
+				if (tgt_types_set == null) {
+					tgt_types_set = new List<TypeSpec> (list.Count);
+				} else if (tgt_types_set.Contains (ret_type)) {
+					continue;
+				}
+
+				tgt_types_set.Add (ret_type);
+			}
+
+			//
+			// Explicit conv rules
+			//
+			if (apply_explicit_conv_rules) {
+				var candidate_set = new List<TypeSpec> ();
+
+				foreach (TypeSpec ret_type in tgt_types_set) {
+					var expr = new EmptyExpression (ret_type);
+
+					if (ImplicitStandardConversionExists (expr, target))
+						candidate_set.Add (ret_type);
+				}
+
+				if (candidate_set.Count != 0)
+					return FindMostEncompassingType (candidate_set);
+			}
+
+			//
+			// Okay, final case !
+			//
+			if (apply_explicit_conv_rules)
+				return FindMostEncompassedType (tgt_types_set);
+			else
+				return FindMostEncompassingType (tgt_types_set);
+		}
+
+		/// <summary>
+		///  User-defined Implicit conversions
+		/// </summary>
+		static public Expression ImplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
+		{
+			return UserDefinedConversion (ec, source, target, UserConversionRestriction.ImplicitOnly, loc);
+		}
+
+		/// <summary>
+		///  User-defined Explicit conversions
+		/// </summary>
+		static Expression ExplicitUserConversion (ResolveContext ec, Expression source, TypeSpec target, Location loc)
+		{
+			return UserDefinedConversion (ec, source, target, 0, loc);
+		}
+
+		static void FindApplicableUserDefinedConversionOperators (ResolveContext rc, IList<MemberSpec> operators, Expression source, TypeSpec target, UserConversionRestriction restr, ref List<MethodSpec> candidates)
+		{
+			if (source.Type.IsInterface) {
+				// Neither A nor B are interface-types
+				return;
+			}
+
+			// For a conversion operator to be applicable, it must be possible
+			// to perform a standard conversion from the source type to
+			// the operand type of the operator, and it must be possible
+			// to perform a standard conversion from the result type of
+			// the operator to the target type.
+
+			Expression texpr = null;
+
+			foreach (MethodSpec op in operators) {
+				
+				// Can be null because MemberCache.GetUserOperator does not resize the array
+				if (op == null)
+					continue;
+
+				var t = op.Parameters.Types[0];
+				if (source.Type != t && !ImplicitStandardConversionExists (rc, source, t)) {
+					if ((restr & UserConversionRestriction.ImplicitOnly) != 0)
+						continue;
+
+					if (!ImplicitStandardConversionExists (new EmptyExpression (t), source.Type))
+							continue;
+				}
+
+				if ((restr & UserConversionRestriction.NullableSourceOnly) != 0 && !t.IsNullableType)
+					continue;
+
+				t = op.ReturnType;
+
+				if (t.IsInterface)
+					continue;
+
+				if (target != t) {
+					if (t.IsNullableType)
+						t = Nullable.NullableInfo.GetUnderlyingType (t);
+
+					if (!ImplicitStandardConversionExists (new EmptyExpression (t), target)) {
+						if ((restr & UserConversionRestriction.ImplicitOnly) != 0)
+							continue;
+
+						if (texpr == null)
+							texpr = new EmptyExpression (target);
+
+						if (!ImplicitStandardConversionExists (texpr, t))
+							continue;
+					}
+				}
+
+				if (candidates == null)
+					candidates = new List<MethodSpec> ();
+
+				candidates.Add (op);
+			}
+		}
+
+		//
+		// User-defined conversions
+		//
+		public static Expression UserDefinedConversion (ResolveContext rc, Expression source, TypeSpec target, UserConversionRestriction restr, Location loc)
+		{
+			List<MethodSpec> candidates = null;
+
+			//
+			// If S or T are nullable types, source_type and target_type are their underlying types
+			// otherwise source_type and target_type are equal to S and T respectively.
+			//
+			TypeSpec source_type = source.Type;
+			TypeSpec target_type = target;
+			Expression source_type_expr;
+			bool nullable_source = false;
+			var implicitOnly = (restr & UserConversionRestriction.ImplicitOnly) != 0;
+
+			if (source_type.IsNullableType) {
+				// No unwrapping conversion S? -> T for non-reference types
+				if (implicitOnly && !TypeSpec.IsReferenceType (target_type) && !target_type.IsNullableType) {
+					source_type_expr = source;
+				} else {
+					source_type_expr = Nullable.Unwrap.CreateUnwrapped (source);
+					source_type = source_type_expr.Type;
+					nullable_source = true;
+				}
+			} else {
+				source_type_expr = source;
+			}
+
+			if (target_type.IsNullableType)
+				target_type = Nullable.NullableInfo.GetUnderlyingType (target_type);
+
+			// Only these containers can contain a user defined implicit or explicit operators
+			const MemberKind user_conversion_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.TypeParameter;
+
+			if ((source_type.Kind & user_conversion_kinds) != 0 && source_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
+				bool declared_only = source_type.IsStruct;
+
+				var operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Implicit, declared_only);
+				if (operators != null) {
+					FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
+				}
+
+				if (!implicitOnly) {
+					operators = MemberCache.GetUserOperator (source_type, Operator.OpType.Explicit, declared_only);
+					if (operators != null) {
+						FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
+					}
+				}
+			}
+
+			if ((target.Kind & user_conversion_kinds) != 0 && target_type.BuiltinType != BuiltinTypeSpec.Type.Decimal) {
+				bool declared_only = target.IsStruct || implicitOnly;
+
+				var operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Implicit, declared_only);
+				if (operators != null) {
+					FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
+				}
+
+				if (!implicitOnly) {
+					operators = MemberCache.GetUserOperator (target_type, Operator.OpType.Explicit, declared_only);
+					if (operators != null) {
+						FindApplicableUserDefinedConversionOperators (rc, operators, source_type_expr, target_type, restr, ref candidates);
+					}
+				}
+			}
+
+			if (candidates == null)
+				return null;
+
+			//
+			// Find the most specific conversion operator
+			//
+			MethodSpec most_specific_operator;
+			TypeSpec s_x, t_x;
+			if (candidates.Count == 1) {
+				most_specific_operator = candidates[0];
+				s_x = most_specific_operator.Parameters.Types[0];
+				t_x = most_specific_operator.ReturnType;
+			} else {
+				//
+				// Pass original source type to find the best match against input type and
+				// not the unwrapped expression
+				//
+				s_x = FindMostSpecificSource (rc, candidates, source.Type, source_type_expr, !implicitOnly);
+				if (s_x == null)
+					return null;
+
+				t_x = FindMostSpecificTarget (candidates, target, !implicitOnly);
+				if (t_x == null)
+					return null;
+
+				most_specific_operator = null;
+				for (int i = 0; i < candidates.Count; ++i) {
+					if (candidates[i].ReturnType == t_x && candidates[i].Parameters.Types[0] == s_x) {
+						most_specific_operator = candidates[i];
+						break;
+					}
+				}
+
+				if (most_specific_operator == null) {
+					//
+					// Unless running in probing more
+					//
+					if ((restr & UserConversionRestriction.ProbingOnly) == 0) {
+						MethodSpec ambig_arg = candidates [0];
+						most_specific_operator = candidates [1];
+						/*
+						foreach (var candidate in candidates) {
+							if (candidate.ReturnType == t_x)
+								most_specific_operator = candidate;
+							else if (candidate.Parameters.Types[0] == s_x)
+								ambig_arg = candidate;
+						}
+						*/
+						rc.Report.Error (457, loc,
+							"Ambiguous user defined operators `{0}' and `{1}' when converting from `{2}' to `{3}'",
+							ambig_arg.GetSignatureForError (), most_specific_operator.GetSignatureForError (),
+							source.Type.GetSignatureForError (), target.GetSignatureForError ());
+					}
+
+					return ErrorExpression.Instance;
+				}
+			}
+
+			//
+			// Convert input type when it's different to best operator argument
+			//
+			if (s_x != source_type) {
+				var c = source as Constant;
+				if (c != null) {
+					source = c.Reduce (rc, s_x);
+					if (source == null)
+						c = null;
+				}
+
+				if (c == null) {
+					source = implicitOnly ?
+						ImplicitConversionStandard (rc, source_type_expr, s_x, loc) :
+						ExplicitConversionStandard (rc, source_type_expr, s_x, loc);
+				}
+			} else {
+				source = source_type_expr;
+			}
+
+			source = new UserCast (most_specific_operator, source, loc).Resolve (rc);
+
+			//
+			// Convert result type when it's different to best operator return type
+			//
+			if (t_x != target_type) {
+				//
+				// User operator is of T?
+				//
+				if (t_x.IsNullableType && (target.IsNullableType || !implicitOnly)) {
+					//
+					// User operator return type does not match target type we need
+					// yet another conversion. This should happen for promoted numeric
+					// types only
+					//
+					if (t_x != target) {
+						var unwrap = Nullable.Unwrap.CreateUnwrapped (source);
+
+						source = implicitOnly ?
+							ImplicitConversionStandard (rc, unwrap, target_type, loc) :
+							ExplicitConversionStandard (rc, unwrap, target_type, loc);
+
+						if (source == null)
+							return null;
+
+						if (target.IsNullableType)
+							source = new Nullable.LiftedConversion (source, unwrap, target).Resolve (rc);
+					}
+				} else {
+					source = implicitOnly ?
+						ImplicitConversionStandard (rc, source, target_type, loc) :
+						ExplicitConversionStandard (rc, source, target_type, loc);
+
+					if (source == null)
+						return null;
+				}
+			}
+
+
+			//
+			// Source expression is of nullable type and underlying conversion returns
+			// only non-nullable type we need to lift it manually
+			//
+			if (nullable_source && !s_x.IsNullableType)
+				return new Nullable.LiftedConversion (source, source_type_expr, target).Resolve (rc);
+
+			//
+			// Target is of nullable type but source type is not, wrap the result expression
+			//
+			if (target.IsNullableType && !t_x.IsNullableType)
+				source = Nullable.Wrap.Create (source, target);
+
+			return source;
+		}
+
+		/// <summary>
+		///   Converts implicitly the resolved expression `expr' into the
+		///   `target_type'.  It returns a new expression that can be used
+		///   in a context that expects a `target_type'.
+		/// </summary>
+		static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
+							     TypeSpec target_type, Location loc)
+		{
+			Expression e;
+
+			if (target_type == null)
+				throw new Exception ("Target type is null");
+
+			e = ImplicitConversionStandard (ec, expr, target_type, loc);
+			if (e != null)
+				return e;
+
+			e = ImplicitUserConversion (ec, expr, target_type, loc);
+			if (e != null)
+				return e;
+
+			return null;
+		}
+
+
+		/// <summary>
+		///   Attempts to apply the `Standard Implicit
+		///   Conversion' rules to the expression `expr' into
+		///   the `target_type'.  It returns a new expression
+		///   that can be used in a context that expects a
+		///   `target_type'.
+		///
+		///   This is different from `ImplicitConversion' in that the
+		///   user defined implicit conversions are excluded.
+		/// </summary>
+		static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
+								     TypeSpec target_type, Location loc)
+		{
+			return ImplicitConversionStandard (ec, expr, target_type, loc, false);
+		}
+
+		static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, TypeSpec target_type, Location loc, bool explicit_cast)
+		{
+			if (expr.eclass == ExprClass.MethodGroup){
+				if (!target_type.IsDelegate){
+					return null;
+				}
+
+				//
+				// Only allow anonymous method conversions on post ISO_1
+				//
+				if (ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1){
+					MethodGroupExpr mg = expr as MethodGroupExpr;
+					if (mg != null)
+						return new ImplicitDelegateCreation (target_type, mg, loc).Resolve (ec);
+				}
+			}
+
+			TypeSpec expr_type = expr.Type;
+			Expression e;
+
+			if (expr_type == target_type) {
+				if (expr_type != InternalType.NullLiteral && expr_type != InternalType.AnonymousMethod)
+					return expr;
+				return null;
+			}
+
+			if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				switch (target_type.Kind) {
+				case MemberKind.ArrayType:
+				case MemberKind.Class:
+					if (target_type.BuiltinType == BuiltinTypeSpec.Type.Object)
+						return EmptyCast.Create (expr, target_type);
+
+					goto case MemberKind.Struct;
+				case MemberKind.Struct:
+				case MemberKind.Delegate:
+				case MemberKind.Enum:
+				case MemberKind.Interface:
+				case MemberKind.TypeParameter:
+					Arguments args = new Arguments (1);
+					args.Add (new Argument (expr));
+					return new DynamicConversion (target_type, explicit_cast ? CSharpBinderFlags.ConvertExplicit : 0, args, loc).Resolve (ec);
+				}
+
+				return null;
+			}
+
+			if (target_type.IsNullableType)
+				return ImplicitNulableConversion (ec, expr, target_type);
+
+			//
+			// Attempt to do the implicit constant expression conversions
+			//
+			Constant c = expr as Constant;
+			if (c != null) {
+				try {
+					c = c.ConvertImplicitly (target_type);
+				} catch {
+					throw new InternalErrorException ("Conversion error", loc);
+				}
+				if (c != null)
+					return c;
+			}
+
+			e = ImplicitNumericConversion (expr, expr_type, target_type);
+			if (e != null)
+				return e;
+
+			e = ImplicitReferenceConversion (expr, target_type, explicit_cast);
+			if (e != null)
+				return e;
+
+			e = ImplicitBoxingConversion (expr, expr_type, target_type);
+			if (e != null)
+				return e;
+
+			if (expr is IntegralConstant && target_type.IsEnum){
+				var i = (IntegralConstant) expr;
+				//
+				// LAMESPEC: csc allows any constant like 0 values to be converted, including const float f = 0.0
+				//
+				// An implicit enumeration conversion permits the decimal-integer-literal 0
+				// to be converted to any enum-type and to any nullable-type whose underlying
+				// type is an enum-type
+				//
+				if (i.IsZeroInteger) {
+					// Recreate 0 literal to remove any collected conversions
+					return new EnumConstant (new IntLiteral (ec.BuiltinTypes, 0, i.Location), target_type);
+				}
+			}
+
+			var target_pc = target_type as PointerContainer;
+			if (target_pc != null) {
+				if (expr_type.IsPointer) {
+					//
+					// Pointer types are same when they have same element types
+					//
+					if (expr_type == target_pc)
+						return expr;
+
+					if (target_pc.Element.Kind == MemberKind.Void)
+						return EmptyCast.Create (expr, target_type);
+
+						//return null;
+				}
+
+				if (expr_type == InternalType.NullLiteral)
+					return new NullPointer (target_type, loc);
+			}
+
+			if (expr_type == InternalType.AnonymousMethod){
+				AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
+				Expression am = ame.Compatible (ec, target_type);
+				if (am != null)
+					return am.Resolve (ec);
+
+				// Avoid CS1503 after CS1661
+				return ErrorExpression.Instance;
+			}
+
+			if (expr_type == InternalType.Arglist && target_type == ec.Module.PredefinedTypes.ArgIterator.TypeSpec)
+				return expr;
+
+			//
+			// dynamic erasure conversion on value types
+			//
+			if (expr_type.IsStruct && TypeSpecComparer.IsEqual (expr_type, target_type))
+				return expr_type == target_type ? expr : EmptyCast.Create (expr, target_type);
+
+			return null;
+		}
+
+		/// <summary>
+		///   Attempts to implicitly convert `source' into `target_type', using
+		///   ImplicitConversion.  If there is no implicit conversion, then
+		///   an error is signaled
+		/// </summary>
+		static public Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
+								     TypeSpec target_type, Location loc)
+		{
+			Expression e = ImplicitConversion (ec, source, target_type, loc);
+			if (e != null)
+				return e;
+
+			source.Error_ValueCannotBeConverted (ec, target_type, false);
+
+			return null;
+		}
+
+		/// <summary>
+		///   Performs the explicit numeric conversions
+		///
+		/// There are a few conversions that are not part of the C# standard,
+		/// they were interim hacks in the C# compiler that were supposed to
+		/// become explicit operators in the UIntPtr class and IntPtr class,
+		/// but for historical reasons it did not happen, so the C# compiler
+		/// ended up with these special hacks.
+		///
+		/// See bug 59800 for details.
+		///
+		/// The conversion are:
+		///   UIntPtr->SByte
+		///   UIntPtr->Int16
+		///   UIntPtr->Int32
+		///   IntPtr->UInt64
+		///   UInt64->IntPtr
+		///   SByte->UIntPtr
+		///   Int16->UIntPtr
+		///
+		/// </summary>
+		public static Expression ExplicitNumericConversion (ResolveContext rc, Expression expr, TypeSpec target_type)
+		{
+			// Not all predefined explicit numeric conversion are
+			// defined here, for some of them (mostly IntPtr/UIntPtr) we
+			// defer to user-operator handling which is now perfect but
+			// works for now
+			//
+			// LAMESPEC: Undocumented IntPtr/UIntPtr conversions
+			// IntPtr -> uint uses int
+			// UIntPtr -> long uses ulong
+			//
+
+			switch (expr.Type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+				//
+				// From sbyte to byte, ushort, uint, ulong, char, uintptr
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U1);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U2);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U4);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I1_U8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I1_CH);
+
+				// One of the built-in conversions that belonged in the class library
+				case BuiltinTypeSpec.Type.UIntPtr:
+					return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I1_U8), target_type, target_type, true);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Byte:
+				//
+				// From byte to sbyte and char
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U1_I1);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U1_CH);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				//
+				// From short to sbyte, byte, ushort, uint, ulong, char, uintptr
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I2_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U1);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U2);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U4);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I2_U8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I2_CH);
+
+				// One of the built-in conversions that belonged in the class library
+				case BuiltinTypeSpec.Type.UIntPtr:
+					return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
+				}
+				break;
+			case BuiltinTypeSpec.Type.UShort:
+				//
+				// From ushort to sbyte, byte, short, char
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U2_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U2_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U2_I2);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U2_CH);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Int:
+				//
+				// From int to sbyte, byte, short, ushort, uint, ulong, char, uintptr
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U2);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U4);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_U8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I4_CH);
+
+				// One of the built-in conversions that belonged in the class library
+				case BuiltinTypeSpec.Type.UIntPtr:
+					return new OperatorCast (new ConvCast (expr, rc.BuiltinTypes.ULong, ConvCast.Mode.I2_U8), target_type, target_type, true);
+				}
+				break;
+			case BuiltinTypeSpec.Type.UInt:
+				//
+				// From uint to sbyte, byte, short, ushort, int, char
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U4_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U4_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U4_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U4_U2);
+				case BuiltinTypeSpec.Type.Int:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U4_I4);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U4_CH);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				//
+				// From long to sbyte, byte, short, ushort, int, uint, ulong, char
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U2);
+				case BuiltinTypeSpec.Type.Int:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I4);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U4);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_U8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_CH);
+				}
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+				//
+				// From ulong to sbyte, byte, short, ushort, int, uint, long, char
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_U2);
+				case BuiltinTypeSpec.Type.Int:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I4);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_U4);
+				case BuiltinTypeSpec.Type.Long:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_CH);
+
+				// One of the built-in conversions that belonged in the class library
+				case BuiltinTypeSpec.Type.IntPtr:
+					return new OperatorCast (EmptyCast.Create (expr, rc.BuiltinTypes.Long), target_type, true);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Char:
+				//
+				// From char to sbyte, byte, short
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.CH_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.CH_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.CH_I2);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Float:
+				//
+				// From float to sbyte, byte, short,
+				// ushort, int, uint, long, ulong, char
+				// or decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U2);
+				case BuiltinTypeSpec.Type.Int:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I4);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U4);
+				case BuiltinTypeSpec.Type.Long:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_I8);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_U8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R4_CH);
+				case BuiltinTypeSpec.Type.Decimal:
+					return new OperatorCast (expr, target_type, true);
+				}
+				break;
+			case BuiltinTypeSpec.Type.Double:
+				//
+				// From double to sbyte, byte, short,
+				// ushort, int, uint, long, ulong,
+				// char, float or decimal
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U2);
+				case BuiltinTypeSpec.Type.Int:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I4);
+				case BuiltinTypeSpec.Type.UInt:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U4);
+				case BuiltinTypeSpec.Type.Long:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_I8);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_U8);
+				case BuiltinTypeSpec.Type.Char:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_CH);
+				case BuiltinTypeSpec.Type.Float:
+					return new ConvCast (expr, target_type, ConvCast.Mode.R8_R4);
+				case BuiltinTypeSpec.Type.Decimal:
+					return new OperatorCast (expr, target_type, true);
+				}
+				break;
+			case BuiltinTypeSpec.Type.UIntPtr:
+				//
+				// Various built-in conversions that belonged in the class library
+				//
+				// from uintptr to sbyte, short, int32
+				//
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I1);
+				case BuiltinTypeSpec.Type.Short:
+					return new ConvCast (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type, ConvCast.Mode.U4_I2);
+				case BuiltinTypeSpec.Type.Int:
+					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.UInt, true), target_type);
+				case BuiltinTypeSpec.Type.UInt:
+					return new OperatorCast (expr, expr.Type, target_type, true);
+				case BuiltinTypeSpec.Type.Long:
+					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.ULong, true), target_type);
+				}
+				break;
+			case BuiltinTypeSpec.Type.IntPtr:
+				if (target_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
+					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Int, true), target_type);
+				if (target_type.BuiltinType == BuiltinTypeSpec.Type.ULong)
+					return EmptyCast.Create (new OperatorCast (expr, expr.Type, rc.BuiltinTypes.Long, true), target_type);
+				
+				break;
+			case BuiltinTypeSpec.Type.Decimal:
+				// From decimal to sbyte, byte, short,
+				// ushort, int, uint, long, ulong, char,
+				// float, or double
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+				case BuiltinTypeSpec.Type.Byte:
+				case BuiltinTypeSpec.Type.Short:
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.Int:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.Long:
+				case BuiltinTypeSpec.Type.ULong:
+				case BuiltinTypeSpec.Type.Char:
+				case BuiltinTypeSpec.Type.Float:
+				case BuiltinTypeSpec.Type.Double:
+					return new OperatorCast (expr, expr.Type, target_type, true);
+				}
+
+				break;
+			}
+
+			return null;
+		}
+
+		/// <summary>
+		///  Returns whether an explicit reference conversion can be performed
+		///  from source_type to target_type
+		/// </summary>
+		public static bool ExplicitReferenceConversionExists (TypeSpec source_type, TypeSpec target_type)
+		{
+			Expression e = ExplicitReferenceConversion (null, source_type, target_type);
+			if (e == null)
+				return false;
+
+			if (e == EmptyExpression.Null)
+				return true;
+
+			throw new InternalErrorException ("Invalid probing conversion result");
+		}
+
+		/// <summary>
+		///   Implements Explicit Reference conversions
+		/// </summary>
+		static Expression ExplicitReferenceConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
+		{
+			//
+			// From object to a generic parameter
+			//
+			if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object && TypeManager.IsGenericParameter (target_type))
+				return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
+
+			//
+			// Explicit type parameter conversion from T
+			//
+			if (source_type.Kind == MemberKind.TypeParameter)
+				return ExplicitTypeParameterConversionFromT (source, source_type, target_type);
+
+			bool target_is_value_type = target_type.Kind == MemberKind.Struct || target_type.Kind == MemberKind.Enum;
+
+			//
+			// Unboxing conversion from System.ValueType to any non-nullable-value-type
+			//
+			if (source_type.BuiltinType == BuiltinTypeSpec.Type.ValueType && target_is_value_type)
+				return source == null ? EmptyExpression.Null : new UnboxCast (source, target_type);
+
+			//
+			// From object or dynamic to any reference type or value type (unboxing)
+			//
+			if (source_type.BuiltinType == BuiltinTypeSpec.Type.Object || source_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				if (target_type.IsPointer)
+					return null;
+
+				return
+					source == null ? EmptyExpression.Null :
+					target_is_value_type ? new UnboxCast (source, target_type) :
+					source is Constant ? (Expression) new EmptyConstantCast ((Constant) source, target_type) :
+					new ClassCast (source, target_type);
+			}
+
+			//
+			// From any class S to any class-type T, provided S is a base class of T
+			//
+			if (source_type.Kind == MemberKind.Class && TypeSpec.IsBaseClass (target_type, source_type, true))
+				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+
+			//
+			// From any interface-type S to to any class type T, provided T is not
+			// sealed, or provided T implements S.
+			//
+			// This also covers Explicit conversions involving type parameters
+			// section From any interface type to T
+			//
+			if (source_type.Kind == MemberKind.Interface) {
+				if (!target_type.IsSealed || target_type.ImplementsInterface (source_type, true)) {
+					if (source == null)
+						return EmptyExpression.Null;
+
+					//
+					// Unboxing conversion from any interface-type to any non-nullable-value-type that
+					// implements the interface-type
+					//
+					return target_is_value_type ? new UnboxCast (source, target_type) : (Expression) new ClassCast (source, target_type);
+				}
+
+				//
+				// From System.Collections.Generic.IList<T> and its base interfaces to a one-dimensional
+				// array type S[], provided there is an implicit or explicit reference conversion from S to T.
+				//
+				var target_array = target_type as ArrayContainer;
+				if (target_array != null && IList_To_Array (source_type, target_array))
+					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+
+				return null;
+			}
+
+			var source_array = source_type as ArrayContainer;
+			if (source_array != null) {
+				var target_array = target_type as ArrayContainer;
+				if (target_array != null) {
+					//
+					// From System.Array to any array-type
+					//
+					if (source_type.BuiltinType == BuiltinTypeSpec.Type.Array)
+						return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+
+					//
+					// From an array type S with an element type Se to an array type T with an
+					// element type Te provided all the following are true:
+					//     * S and T differe only in element type, in other words, S and T
+					//       have the same number of dimensions.
+					//     * Both Se and Te are reference types
+					//     * An explicit reference conversions exist from Se to Te
+					//
+					if (source_array.Rank == target_array.Rank) {
+
+						source_type = source_array.Element;
+						var target_element = target_array.Element;
+
+						//
+						// LAMESPEC: Type parameters are special cased somehow but
+						// only when both source and target elements are type parameters
+						//
+						if ((source_type.Kind & target_element.Kind & MemberKind.TypeParameter) == MemberKind.TypeParameter) {
+							//
+							// Conversion is allowed unless source element type has struct constrain
+							//
+							if (TypeSpec.IsValueType (source_type))
+								return null;
+						} else {
+							if (!TypeSpec.IsReferenceType (source_type))
+								return null;
+						}
+
+						if (!TypeSpec.IsReferenceType (target_element))
+							return null;
+
+						if (ExplicitReferenceConversionExists (source_type, target_element))
+							return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+							
+						return null;
+					}
+				}
+
+				//
+				// From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces, 
+				// provided that there is an explicit reference conversion from S to T
+				//
+				if (ArrayToIList (source_array, target_type, true))
+					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+
+				return null;
+			}
+
+			//
+			// From any class type S to any interface T, provides S is not sealed
+			// and provided S does not implement T.
+			//
+			if (target_type.IsInterface && !source_type.IsSealed && !source_type.ImplementsInterface (target_type, true)) {
+				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+			}
+
+			//
+			// From System delegate to any delegate-type
+			//
+			if (source_type.BuiltinType == BuiltinTypeSpec.Type.Delegate && target_type.IsDelegate)
+				return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+
+			//
+			// From variant generic delegate to same variant generic delegate type
+			//
+			if (source_type.IsDelegate && target_type.IsDelegate && source_type.MemberDefinition == target_type.MemberDefinition) {
+				var tparams = source_type.MemberDefinition.TypeParameters;
+				var targs_src = source_type.TypeArguments;
+				var targs_dst = target_type.TypeArguments;
+				int i;
+				for (i = 0; i < tparams.Length; ++i) {
+					//
+					// If TP is invariant, types have to be identical
+					//
+					if (TypeSpecComparer.IsEqual (targs_src[i], targs_dst[i]))
+						continue;
+
+					if (tparams[i].Variance == Variance.Covariant) {
+						//
+						//If TP is covariant, an implicit or explicit identity or reference conversion is required
+						//
+						if (ImplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
+							continue;
+
+						if (ExplicitReferenceConversionExists (targs_src[i], targs_dst[i]))
+							continue;
+
+					} else if (tparams[i].Variance == Variance.Contravariant) {
+						//
+						//If TP is contravariant, both are either identical or reference types
+						//
+						if (TypeSpec.IsReferenceType (targs_src[i]) && TypeSpec.IsReferenceType (targs_dst[i]))
+							continue;
+					}
+
+					break;
+				}
+
+				if (i == tparams.Length)
+					return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+			}
+
+			var tps = target_type as TypeParameterSpec;
+			if (tps != null)
+				return ExplicitTypeParameterConversionToT (source, source_type, tps);
+
+			return null;
+		}
+
+		/// <summary>
+		///   Performs an explicit conversion of the expression `expr' whose
+		///   type is expr.Type to `target_type'.
+		/// </summary>
+		static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
+								 TypeSpec target_type, Location loc)
+		{
+			TypeSpec expr_type = expr.Type;
+
+			// Explicit conversion includes implicit conversion and it used for enum underlying types too
+			Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
+			if (ne != null)
+				return ne;
+
+			if (expr_type.IsEnum) {
+				TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
+				Expression underlying = EmptyCast.Create (expr, EnumSpec.GetUnderlyingType (expr_type));
+				if (underlying.Type == real_target)
+					ne = underlying;
+
+				if (ne == null)
+					ne = ImplicitNumericConversion (underlying, real_target);
+
+				if (ne == null)
+					ne = ExplicitNumericConversion (ec, underlying, real_target);
+
+				//
+				// LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
+				//
+				if (ne == null && (real_target.BuiltinType == BuiltinTypeSpec.Type.IntPtr || real_target.BuiltinType == BuiltinTypeSpec.Type.UIntPtr))
+					ne = ExplicitUserConversion (ec, underlying, real_target, loc);
+
+				return ne != null ? EmptyCast.Create (ne, target_type) : null;
+			}
+
+			if (target_type.IsEnum) {
+				//
+				// System.Enum can be unboxed to any enum-type
+				//
+				if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Enum)
+					return new UnboxCast (expr, target_type);
+
+				TypeSpec real_target = target_type.IsEnum ? EnumSpec.GetUnderlyingType (target_type) : target_type;
+
+				if (expr_type == real_target)
+					return EmptyCast.Create (expr, target_type);
+
+				Constant c = expr as Constant;
+				if (c != null) {
+					c = c.TryReduce (ec, real_target);
+					if (c != null)
+						return c;
+				} else {
+					ne = ImplicitNumericConversion (expr, real_target);
+					if (ne != null)
+						return EmptyCast.Create (ne, target_type);
+
+					ne = ExplicitNumericConversion (ec, expr, real_target);
+					if (ne != null)
+						return EmptyCast.Create (ne, target_type);
+
+					//
+					// LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
+					//
+					if (expr_type.BuiltinType == BuiltinTypeSpec.Type.IntPtr || expr_type.BuiltinType == BuiltinTypeSpec.Type.UIntPtr) {
+						ne = ExplicitUserConversion (ec, expr, real_target, loc);
+						if (ne != null)
+							return ExplicitConversionCore (ec, ne, target_type, loc);
+					}
+				}
+			} else {
+				ne = ExplicitNumericConversion (ec, expr, target_type);
+				if (ne != null)
+					return ne;
+			}
+
+			//
+			// Skip the ExplicitReferenceConversion because we can not convert
+			// from Null to a ValueType, and ExplicitReference wont check against
+			// null literal explicitly
+			//
+			if (expr_type != InternalType.NullLiteral) {
+				ne = ExplicitReferenceConversion (expr, expr_type, target_type);
+				if (ne != null)
+					return ne;
+			}
+
+			if (ec.IsUnsafe){
+				ne = ExplicitUnsafe (expr, target_type);
+				if (ne != null)
+					return ne;
+			}
+			
+			return null;
+		}
+
+		public static Expression ExplicitUnsafe (Expression expr, TypeSpec target_type)
+		{
+			TypeSpec expr_type = expr.Type;
+
+			if (target_type.IsPointer){
+				if (expr_type.IsPointer)
+					return EmptyCast.Create (expr, target_type);
+
+				switch (expr_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+				case BuiltinTypeSpec.Type.Short:
+				case BuiltinTypeSpec.Type.Int:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_I);
+
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.Byte:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_U);
+
+				case BuiltinTypeSpec.Type.Long:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I8_I);
+
+				case BuiltinTypeSpec.Type.ULong:
+					return new ConvCast (expr, target_type, ConvCast.Mode.U8_I);
+				}
+			}
+
+			if (expr_type.IsPointer){
+				switch (target_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
+				case BuiltinTypeSpec.Type.Byte:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
+				case BuiltinTypeSpec.Type.Short:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
+				case BuiltinTypeSpec.Type.UShort:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
+				case BuiltinTypeSpec.Type.Int:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
+				case BuiltinTypeSpec.Type.UInt:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
+				case BuiltinTypeSpec.Type.Long:
+					return new ConvCast (expr, target_type, ConvCast.Mode.I_I8);
+				case BuiltinTypeSpec.Type.ULong:
+					return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
+				}
+			}
+			return null;
+		}
+
+		/// <summary>
+		///   Same as ExplicitConversion, only it doesn't include user defined conversions
+		/// </summary>
+		static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
+								     TypeSpec target_type, Location l)
+		{
+			int errors = ec.Report.Errors;
+			Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
+			if (ec.Report.Errors > errors)
+				return null;
+
+			if (ne != null)
+				return ne;
+
+			ne = ExplicitNumericConversion (ec, expr, target_type);
+			if (ne != null)
+				return ne;
+
+			ne = ExplicitReferenceConversion (expr, expr.Type, target_type);
+			if (ne != null)
+				return ne;
+
+			if (ec.IsUnsafe && expr.Type.IsPointer && target_type.IsPointer && ((PointerContainer)expr.Type).Element.Kind == MemberKind.Void)
+				return EmptyCast.Create (expr, target_type);
+
+			expr.Error_ValueCannotBeConverted (ec, target_type, true);
+			return null;
+		}
+
+		/// <summary>
+		///   Performs an explicit conversion of the expression `expr' whose
+		///   type is expr.Type to `target_type'.
+		/// </summary>
+		static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
+			TypeSpec target_type, Location loc)
+		{
+			Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
+			if (e != null) {
+				//
+				// Don't eliminate explicit precission casts
+				//
+				if (e == expr) {
+					if (target_type.BuiltinType == BuiltinTypeSpec.Type.Float)
+						return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
+					
+					if (target_type.BuiltinType == BuiltinTypeSpec.Type.Double)
+						return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
+				}
+					
+				return e;
+			}
+
+			TypeSpec expr_type = expr.Type;
+			if (target_type.IsNullableType) {
+				TypeSpec target;
+
+				if (expr_type.IsNullableType) {
+					target = Nullable.NullableInfo.GetUnderlyingType (target_type);
+					Expression unwrap = Nullable.Unwrap.Create (expr);
+					e = ExplicitConversion (ec, unwrap, target, expr.Location);
+					if (e == null)
+						return null;
+
+					return new Nullable.LiftedConversion (e, unwrap, target_type).Resolve (ec);
+				}
+				if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
+					return new UnboxCast (expr, target_type);
+				}
+
+				target = TypeManager.GetTypeArguments (target_type) [0];
+				e = ExplicitConversionCore (ec, expr, target, loc);
+				if (e != null)
+					return TypeSpec.IsReferenceType (expr.Type) ? new UnboxCast (expr, target_type) : Nullable.Wrap.Create (e, target_type);
+			} else if (expr_type.IsNullableType) {
+				e = ImplicitBoxingConversion (expr, Nullable.NullableInfo.GetUnderlyingType (expr_type), target_type);
+				if (e != null)
+					return e;
+
+				e = Nullable.Unwrap.Create (expr, false);			
+				e = ExplicitConversionCore (ec, e, target_type, loc);
+				if (e != null)
+					return EmptyCast.Create (e, target_type);
+			}
+			
+			e = ExplicitUserConversion (ec, expr, target_type, loc);
+
+			if (e != null)
+				return e;			
+
+			expr.Error_ValueCannotBeConverted (ec, target_type, true);
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-parser.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-parser.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-parser.cs	(revision 11807)
@@ -0,0 +1,16238 @@
+// created by jay 0.7 (c) 1998 Axel.Schreiner@informatik.uni-osnabrueck.de
+
+#line 2 "cs-parser.jay"
+//
+// cs-parser.jay: The Parser for the C# compiler
+//
+// Authors: Miguel de Icaza (miguel@gnome.org)
+//          Ravi Pratap     (ravi@ximian.com)
+//          Marek Safar	    (marek.safar@gmail.com)
+//
+// Dual Licensed under the terms of the GNU GPL and the MIT X11 license
+//
+// (C) 2001 Ximian, Inc (http://www.ximian.com)
+// (C) 2004-2011 Novell, Inc
+// Copyright 2011-2012 Xamarin Inc.
+//
+
+using System.Text;
+using System.IO;
+using System;
+using System.Collections.Generic;
+
+namespace Mono.CSharp
+{
+	/// <summary>
+	///    The C# Parser
+	/// </summary>
+	public class CSharpParser
+	{
+		[Flags]
+		enum ParameterModifierType
+		{
+			Ref		= 1 << 1,
+			Out		= 1 << 2,
+			This	= 1 << 3,
+			Params	= 1 << 4,
+			Arglist	= 1 << 5,
+			DefaultValue = 1 << 6,
+			
+			All = Ref | Out | This | Params | Arglist | DefaultValue,
+			PrimaryConstructor = Ref | Out | Params | DefaultValue
+		}
+		
+		static readonly object ModifierNone = 0;
+	
+		NamespaceContainer current_namespace;
+		TypeContainer current_container;
+		TypeDefinition current_type;
+		PropertyBase current_property;
+		EventProperty current_event;
+		EventField current_event_field;
+		FieldBase current_field;
+	
+		/// <summary>
+		///   Current block is used to add statements as we find
+		///   them.  
+		/// </summary>
+		Block      current_block;
+		
+		BlockVariable current_variable;
+
+		Delegate   current_delegate;
+		
+		AnonymousMethodExpression current_anonymous_method;
+
+		/// <summary>
+		///   This is used by the unary_expression code to resolve
+		///   a name against a parameter.  
+		/// </summary>
+		
+		// FIXME: This is very ugly and it's very hard to reset it correctly
+		// on all places, especially when some parameters are autogenerated.
+		ParametersCompiled current_local_parameters;
+
+		bool parsing_anonymous_method;
+		
+		bool async_block;
+
+		///
+		/// An out-of-band stack.
+		///
+		Stack<object> oob_stack;
+
+		///
+		/// Controls the verbosity of the errors produced by the parser
+		///
+		int yacc_verbose_flag;
+
+		/// 
+		/// Used by the interactive shell, flags whether EOF was reached
+		/// and an error was produced
+		///
+		public bool UnexpectedEOF;
+
+		///
+		/// The current file.
+		///
+		readonly CompilationSourceFile file;
+
+		///
+		/// Temporary Xml documentation cache.
+		/// For enum types, we need one more temporary store.
+		///
+		string tmpComment;
+		string enumTypeComment;
+	       		
+		/// Current attribute target
+		string current_attr_target;
+		
+		ParameterModifierType valid_param_mod;
+		
+		bool default_parameter_used;
+
+		/// When using the interactive parser, this holds the
+		/// resulting expression
+		public Class InteractiveResult;
+
+		//
+		// Keeps track of global data changes to undo on parser error
+		//
+		public Undo undo;
+
+		bool? interactive_async;
+		
+		Stack<Linq.QueryBlock> linq_clause_blocks;
+
+		ModuleContainer module;
+		
+		readonly CompilerContext compiler;
+		readonly LanguageVersion lang_version;
+		readonly bool doc_support;
+		readonly CompilerSettings settings;
+		readonly Report report;
+		
+		//
+		// Instead of allocating carrier array everytime we
+		// share the bucket for very common constructs which can never
+		// be recursive
+		//
+		List<Parameter> parameters_bucket;
+		
+		//
+		// Full AST support members
+		//
+		LocationsBag lbag;
+		List<Tuple<Modifiers, Location>> mod_locations;
+		Location parameterModifierLocation, savedLocation, savedEventAssignLocation;
+		Location savedAttrParenOpenLocation, savedAttrParenCloseLocation, savedOperatorLocation;
+		Stack<List<Location>> locationListStack = new Stack<List<Location>> (); // used for type parameters
+		Stack<Location> opt_intoStack = new Stack<Location> ();
+
+		bool HadAttributeParens;
+		List<Location> attributeArgumentCommas = new List<Location> ();
+		List<Location> parameterListCommas = new List<Location> ();
+		Stack<Location> location_stack;
+#line default
+
+  /** error output stream.
+      It should be changeable.
+    */
+  public System.IO.TextWriter ErrorOutput = System.Console.Out;
+
+  /** simplified error message.
+      @see <a href="#yyerror(java.lang.String, java.lang.String[])">yyerror</a>
+    */
+  public void yyerror (string message) {
+    yyerror(message, null);
+  }
+#pragma warning disable 649
+  /* An EOF token */
+  public int eof_token;
+#pragma warning restore 649
+  /** (syntax) error message.
+      Can be overwritten to control message format.
+      @param message text to be displayed.
+      @param expected vector of acceptable tokens, if available.
+    */
+  public void yyerror (string message, string[] expected) {
+    if ((yacc_verbose_flag > 0) && (expected != null) && (expected.Length  > 0)) {
+      ErrorOutput.Write (message+", expecting");
+      for (int n = 0; n < expected.Length; ++ n)
+        ErrorOutput.Write (" "+expected[n]);
+        ErrorOutput.WriteLine ();
+    } else
+      ErrorOutput.WriteLine (message);
+  }
+
+  /** debugging support, requires the package jay.yydebug.
+      Set to null to suppress debugging messages.
+    */
+//t  internal yydebug.yyDebug debug;
+
+  protected const int yyFinal = 7;
+//t // Put this array into a separate class so it is only initialized if debugging is actually used
+//t // Use MarshalByRefObject to disable inlining
+//t class YYRules : MarshalByRefObject {
+//t  public static readonly string [] yyRule = {
+//t    "$accept : compilation_unit",
+//t    "compilation_unit : outer_declaration opt_EOF",
+//t    "$$1 :",
+//t    "compilation_unit : interactive_parsing $$1 opt_EOF",
+//t    "compilation_unit : documentation_parsing",
+//t    "outer_declaration : opt_extern_alias_directives opt_using_directives",
+//t    "outer_declaration : opt_extern_alias_directives opt_using_directives namespace_or_type_declarations opt_attributes",
+//t    "outer_declaration : opt_extern_alias_directives opt_using_directives attribute_sections",
+//t    "outer_declaration : error",
+//t    "opt_EOF :",
+//t    "opt_EOF : EOF",
+//t    "extern_alias_directives : extern_alias_directive",
+//t    "extern_alias_directives : extern_alias_directives extern_alias_directive",
+//t    "extern_alias_directive : EXTERN_ALIAS IDENTIFIER IDENTIFIER SEMICOLON",
+//t    "extern_alias_directive : EXTERN_ALIAS error",
+//t    "using_directives : using_directive",
+//t    "using_directives : using_directives using_directive",
+//t    "using_directive : using_namespace",
+//t    "using_namespace : USING namespace_or_type_expr SEMICOLON",
+//t    "using_namespace : USING IDENTIFIER ASSIGN namespace_or_type_expr SEMICOLON",
+//t    "using_namespace : USING error",
+//t    "$$2 :",
+//t    "$$3 :",
+//t    "namespace_declaration : opt_attributes NAMESPACE namespace_name $$2 OPEN_BRACE $$3 opt_extern_alias_directives opt_using_directives opt_namespace_or_type_declarations CLOSE_BRACE opt_semicolon_error",
+//t    "namespace_declaration : opt_attributes NAMESPACE namespace_name",
+//t    "opt_semicolon_error :",
+//t    "opt_semicolon_error : SEMICOLON",
+//t    "opt_semicolon_error : error",
+//t    "namespace_name : IDENTIFIER",
+//t    "namespace_name : namespace_name DOT IDENTIFIER",
+//t    "namespace_name : error",
+//t    "opt_semicolon :",
+//t    "opt_semicolon : SEMICOLON",
+//t    "opt_comma :",
+//t    "opt_comma : COMMA",
+//t    "opt_using_directives :",
+//t    "opt_using_directives : using_directives",
+//t    "opt_extern_alias_directives :",
+//t    "opt_extern_alias_directives : extern_alias_directives",
+//t    "opt_namespace_or_type_declarations :",
+//t    "opt_namespace_or_type_declarations : namespace_or_type_declarations",
+//t    "namespace_or_type_declarations : namespace_or_type_declaration",
+//t    "namespace_or_type_declarations : namespace_or_type_declarations namespace_or_type_declaration",
+//t    "namespace_or_type_declaration : type_declaration",
+//t    "namespace_or_type_declaration : namespace_declaration",
+//t    "namespace_or_type_declaration : attribute_sections CLOSE_BRACE",
+//t    "type_declaration : class_declaration",
+//t    "type_declaration : struct_declaration",
+//t    "type_declaration : interface_declaration",
+//t    "type_declaration : enum_declaration",
+//t    "type_declaration : delegate_declaration",
+//t    "opt_attributes :",
+//t    "opt_attributes : attribute_sections",
+//t    "attribute_sections : attribute_section",
+//t    "attribute_sections : attribute_sections attribute_section",
+//t    "$$4 :",
+//t    "attribute_section : OPEN_BRACKET $$4 attribute_section_cont",
+//t    "$$5 :",
+//t    "attribute_section_cont : attribute_target COLON $$5 attribute_list opt_comma CLOSE_BRACKET",
+//t    "attribute_section_cont : attribute_list opt_comma CLOSE_BRACKET",
+//t    "attribute_section_cont : IDENTIFIER error",
+//t    "attribute_section_cont : error",
+//t    "attribute_target : IDENTIFIER",
+//t    "attribute_target : EVENT",
+//t    "attribute_target : RETURN",
+//t    "attribute_list : attribute",
+//t    "attribute_list : attribute_list COMMA attribute",
+//t    "$$6 :",
+//t    "attribute : attribute_name $$6 opt_attribute_arguments",
+//t    "attribute_name : namespace_or_type_expr",
+//t    "opt_attribute_arguments :",
+//t    "opt_attribute_arguments : OPEN_PARENS attribute_arguments CLOSE_PARENS",
+//t    "attribute_arguments :",
+//t    "attribute_arguments : positional_or_named_argument",
+//t    "attribute_arguments : named_attribute_argument",
+//t    "attribute_arguments : attribute_arguments COMMA positional_or_named_argument",
+//t    "attribute_arguments : attribute_arguments COMMA named_attribute_argument",
+//t    "positional_or_named_argument : expression",
+//t    "positional_or_named_argument : named_argument",
+//t    "positional_or_named_argument : error",
+//t    "$$7 :",
+//t    "named_attribute_argument : IDENTIFIER ASSIGN $$7 expression",
+//t    "named_argument : identifier_inside_body COLON opt_named_modifier expression_or_error",
+//t    "opt_named_modifier :",
+//t    "opt_named_modifier : REF",
+//t    "opt_named_modifier : OUT",
+//t    "opt_class_member_declarations :",
+//t    "opt_class_member_declarations : class_member_declarations",
+//t    "class_member_declarations : class_member_declaration",
+//t    "class_member_declarations : class_member_declarations class_member_declaration",
+//t    "class_member_declaration : constant_declaration",
+//t    "class_member_declaration : field_declaration",
+//t    "class_member_declaration : method_declaration",
+//t    "class_member_declaration : property_declaration",
+//t    "class_member_declaration : event_declaration",
+//t    "class_member_declaration : indexer_declaration",
+//t    "class_member_declaration : operator_declaration",
+//t    "class_member_declaration : constructor_declaration",
+//t    "class_member_declaration : primary_constructor_body",
+//t    "class_member_declaration : destructor_declaration",
+//t    "class_member_declaration : type_declaration",
+//t    "class_member_declaration : attributes_without_members",
+//t    "class_member_declaration : incomplete_member",
+//t    "class_member_declaration : error",
+//t    "$$8 :",
+//t    "primary_constructor_body : OPEN_BRACE $$8 opt_statement_list block_end",
+//t    "$$9 :",
+//t    "$$10 :",
+//t    "$$11 :",
+//t    "$$12 :",
+//t    "$$13 :",
+//t    "struct_declaration : opt_attributes opt_modifiers opt_partial STRUCT $$9 type_declaration_name $$10 opt_primary_parameters opt_class_base opt_type_parameter_constraints_clauses $$11 OPEN_BRACE $$12 opt_class_member_declarations CLOSE_BRACE $$13 opt_semicolon",
+//t    "struct_declaration : opt_attributes opt_modifiers opt_partial STRUCT error",
+//t    "$$14 :",
+//t    "constant_declaration : opt_attributes opt_modifiers CONST type IDENTIFIER $$14 constant_initializer opt_constant_declarators SEMICOLON",
+//t    "constant_declaration : opt_attributes opt_modifiers CONST type error",
+//t    "opt_constant_declarators :",
+//t    "opt_constant_declarators : constant_declarators",
+//t    "constant_declarators : constant_declarator",
+//t    "constant_declarators : constant_declarators constant_declarator",
+//t    "constant_declarator : COMMA IDENTIFIER constant_initializer",
+//t    "$$15 :",
+//t    "constant_initializer : ASSIGN $$15 constant_initializer_expr",
+//t    "constant_initializer : error",
+//t    "constant_initializer_expr : constant_expression",
+//t    "constant_initializer_expr : array_initializer",
+//t    "$$16 :",
+//t    "field_declaration : opt_attributes opt_modifiers member_type IDENTIFIER $$16 opt_field_initializer opt_field_declarators SEMICOLON",
+//t    "$$17 :",
+//t    "field_declaration : opt_attributes opt_modifiers FIXED simple_type IDENTIFIER $$17 fixed_field_size opt_fixed_field_declarators SEMICOLON",
+//t    "field_declaration : opt_attributes opt_modifiers FIXED simple_type error SEMICOLON",
+//t    "opt_field_initializer :",
+//t    "$$18 :",
+//t    "opt_field_initializer : ASSIGN $$18 variable_initializer",
+//t    "opt_field_declarators :",
+//t    "opt_field_declarators : field_declarators",
+//t    "field_declarators : field_declarator",
+//t    "field_declarators : field_declarators field_declarator",
+//t    "field_declarator : COMMA IDENTIFIER",
+//t    "$$19 :",
+//t    "field_declarator : COMMA IDENTIFIER ASSIGN $$19 variable_initializer",
+//t    "opt_fixed_field_declarators :",
+//t    "opt_fixed_field_declarators : fixed_field_declarators",
+//t    "fixed_field_declarators : fixed_field_declarator",
+//t    "fixed_field_declarators : fixed_field_declarators fixed_field_declarator",
+//t    "fixed_field_declarator : COMMA IDENTIFIER fixed_field_size",
+//t    "$$20 :",
+//t    "fixed_field_size : OPEN_BRACKET $$20 expression CLOSE_BRACKET",
+//t    "fixed_field_size : OPEN_BRACKET error",
+//t    "variable_initializer : expression",
+//t    "variable_initializer : array_initializer",
+//t    "variable_initializer : error",
+//t    "$$21 :",
+//t    "method_declaration : method_header $$21 method_body_expression_block",
+//t    "$$22 :",
+//t    "$$23 :",
+//t    "method_header : opt_attributes opt_modifiers member_type method_declaration_name OPEN_PARENS $$22 opt_formal_parameter_list CLOSE_PARENS $$23 opt_type_parameter_constraints_clauses",
+//t    "$$24 :",
+//t    "$$25 :",
+//t    "$$26 :",
+//t    "method_header : opt_attributes opt_modifiers PARTIAL VOID $$24 method_declaration_name OPEN_PARENS $$25 opt_formal_parameter_list CLOSE_PARENS $$26 opt_type_parameter_constraints_clauses",
+//t    "method_header : opt_attributes opt_modifiers member_type modifiers method_declaration_name OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS",
+//t    "method_header : opt_attributes opt_modifiers member_type method_declaration_name error",
+//t    "method_body_expression_block : method_body",
+//t    "method_body_expression_block : expression_block",
+//t    "method_body : block",
+//t    "method_body : SEMICOLON",
+//t    "$$27 :",
+//t    "expression_block : ARROW $$27 expression SEMICOLON",
+//t    "opt_formal_parameter_list :",
+//t    "opt_formal_parameter_list : formal_parameter_list",
+//t    "formal_parameter_list : fixed_parameters",
+//t    "formal_parameter_list : fixed_parameters COMMA parameter_array",
+//t    "formal_parameter_list : fixed_parameters COMMA arglist_modifier",
+//t    "formal_parameter_list : parameter_array COMMA error",
+//t    "formal_parameter_list : fixed_parameters COMMA parameter_array COMMA error",
+//t    "formal_parameter_list : arglist_modifier COMMA error",
+//t    "formal_parameter_list : fixed_parameters COMMA ARGLIST COMMA error",
+//t    "formal_parameter_list : parameter_array",
+//t    "formal_parameter_list : arglist_modifier",
+//t    "formal_parameter_list : error",
+//t    "fixed_parameters : fixed_parameter",
+//t    "fixed_parameters : fixed_parameters COMMA fixed_parameter",
+//t    "fixed_parameter : opt_attributes opt_parameter_modifier parameter_type identifier_inside_body",
+//t    "fixed_parameter : opt_attributes opt_parameter_modifier parameter_type identifier_inside_body OPEN_BRACKET CLOSE_BRACKET",
+//t    "fixed_parameter : attribute_sections error",
+//t    "fixed_parameter : opt_attributes opt_parameter_modifier parameter_type error",
+//t    "$$28 :",
+//t    "fixed_parameter : opt_attributes opt_parameter_modifier parameter_type identifier_inside_body ASSIGN $$28 constant_expression",
+//t    "opt_parameter_modifier :",
+//t    "opt_parameter_modifier : parameter_modifiers",
+//t    "parameter_modifiers : parameter_modifier",
+//t    "parameter_modifiers : parameter_modifiers parameter_modifier",
+//t    "parameter_modifier : REF",
+//t    "parameter_modifier : OUT",
+//t    "parameter_modifier : THIS",
+//t    "parameter_array : opt_attributes params_modifier type IDENTIFIER",
+//t    "parameter_array : opt_attributes params_modifier type IDENTIFIER ASSIGN constant_expression",
+//t    "parameter_array : opt_attributes params_modifier type error",
+//t    "params_modifier : PARAMS",
+//t    "params_modifier : PARAMS parameter_modifier",
+//t    "params_modifier : PARAMS params_modifier",
+//t    "arglist_modifier : ARGLIST",
+//t    "$$29 :",
+//t    "$$30 :",
+//t    "$$31 :",
+//t    "$$32 :",
+//t    "property_declaration : opt_attributes opt_modifiers member_type member_declaration_name $$29 OPEN_BRACE $$30 accessor_declarations $$31 CLOSE_BRACE $$32 opt_property_initializer",
+//t    "$$33 :",
+//t    "property_declaration : opt_attributes opt_modifiers member_type member_declaration_name $$33 expression_block",
+//t    "opt_property_initializer :",
+//t    "$$34 :",
+//t    "opt_property_initializer : ASSIGN $$34 property_initializer SEMICOLON",
+//t    "property_initializer : expression",
+//t    "property_initializer : array_initializer",
+//t    "$$35 :",
+//t    "$$36 :",
+//t    "indexer_declaration : opt_attributes opt_modifiers member_type indexer_declaration_name OPEN_BRACKET $$35 opt_formal_parameter_list CLOSE_BRACKET $$36 indexer_body",
+//t    "indexer_body : OPEN_BRACE accessor_declarations CLOSE_BRACE",
+//t    "indexer_body : expression_block",
+//t    "accessor_declarations : get_accessor_declaration",
+//t    "accessor_declarations : get_accessor_declaration accessor_declarations",
+//t    "accessor_declarations : set_accessor_declaration",
+//t    "accessor_declarations : set_accessor_declaration accessor_declarations",
+//t    "accessor_declarations : error",
+//t    "$$37 :",
+//t    "get_accessor_declaration : opt_attributes opt_modifiers GET $$37 accessor_body",
+//t    "$$38 :",
+//t    "set_accessor_declaration : opt_attributes opt_modifiers SET $$38 accessor_body",
+//t    "accessor_body : block",
+//t    "accessor_body : SEMICOLON",
+//t    "accessor_body : error",
+//t    "$$39 :",
+//t    "$$40 :",
+//t    "$$41 :",
+//t    "$$42 :",
+//t    "interface_declaration : opt_attributes opt_modifiers opt_partial INTERFACE $$39 type_declaration_name $$40 opt_class_base opt_type_parameter_constraints_clauses $$41 OPEN_BRACE opt_interface_member_declarations CLOSE_BRACE $$42 opt_semicolon",
+//t    "interface_declaration : opt_attributes opt_modifiers opt_partial INTERFACE error",
+//t    "opt_interface_member_declarations :",
+//t    "opt_interface_member_declarations : interface_member_declarations",
+//t    "interface_member_declarations : interface_member_declaration",
+//t    "interface_member_declarations : interface_member_declarations interface_member_declaration",
+//t    "interface_member_declaration : constant_declaration",
+//t    "interface_member_declaration : field_declaration",
+//t    "interface_member_declaration : method_declaration",
+//t    "interface_member_declaration : property_declaration",
+//t    "interface_member_declaration : event_declaration",
+//t    "interface_member_declaration : indexer_declaration",
+//t    "interface_member_declaration : operator_declaration",
+//t    "interface_member_declaration : constructor_declaration",
+//t    "interface_member_declaration : type_declaration",
+//t    "$$43 :",
+//t    "operator_declaration : opt_attributes opt_modifiers operator_declarator $$43 method_body_expression_block",
+//t    "operator_type : type_expression_or_array",
+//t    "operator_type : VOID",
+//t    "$$44 :",
+//t    "operator_declarator : operator_type OPERATOR overloadable_operator OPEN_PARENS $$44 opt_formal_parameter_list CLOSE_PARENS",
+//t    "operator_declarator : conversion_operator_declarator",
+//t    "overloadable_operator : BANG",
+//t    "overloadable_operator : TILDE",
+//t    "overloadable_operator : OP_INC",
+//t    "overloadable_operator : OP_DEC",
+//t    "overloadable_operator : TRUE",
+//t    "overloadable_operator : FALSE",
+//t    "overloadable_operator : PLUS",
+//t    "overloadable_operator : MINUS",
+//t    "overloadable_operator : STAR",
+//t    "overloadable_operator : DIV",
+//t    "overloadable_operator : PERCENT",
+//t    "overloadable_operator : BITWISE_AND",
+//t    "overloadable_operator : BITWISE_OR",
+//t    "overloadable_operator : CARRET",
+//t    "overloadable_operator : OP_SHIFT_LEFT",
+//t    "overloadable_operator : OP_SHIFT_RIGHT",
+//t    "overloadable_operator : OP_EQ",
+//t    "overloadable_operator : OP_NE",
+//t    "overloadable_operator : OP_GT",
+//t    "overloadable_operator : OP_LT",
+//t    "overloadable_operator : OP_GE",
+//t    "overloadable_operator : OP_LE",
+//t    "$$45 :",
+//t    "conversion_operator_declarator : IMPLICIT OPERATOR type OPEN_PARENS $$45 opt_formal_parameter_list CLOSE_PARENS",
+//t    "$$46 :",
+//t    "conversion_operator_declarator : EXPLICIT OPERATOR type OPEN_PARENS $$46 opt_formal_parameter_list CLOSE_PARENS",
+//t    "conversion_operator_declarator : IMPLICIT error",
+//t    "conversion_operator_declarator : EXPLICIT error",
+//t    "constructor_declaration : constructor_declarator constructor_body",
+//t    "$$47 :",
+//t    "$$48 :",
+//t    "constructor_declarator : opt_attributes opt_modifiers IDENTIFIER $$47 OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS $$48 opt_constructor_initializer",
+//t    "constructor_body : block_prepared",
+//t    "constructor_body : SEMICOLON",
+//t    "opt_constructor_initializer :",
+//t    "opt_constructor_initializer : constructor_initializer",
+//t    "$$49 :",
+//t    "constructor_initializer : COLON BASE OPEN_PARENS $$49 opt_argument_list CLOSE_PARENS",
+//t    "$$50 :",
+//t    "constructor_initializer : COLON THIS OPEN_PARENS $$50 opt_argument_list CLOSE_PARENS",
+//t    "constructor_initializer : COLON error",
+//t    "constructor_initializer : error",
+//t    "$$51 :",
+//t    "destructor_declaration : opt_attributes opt_modifiers TILDE $$51 IDENTIFIER OPEN_PARENS CLOSE_PARENS method_body",
+//t    "$$52 :",
+//t    "event_declaration : opt_attributes opt_modifiers EVENT type member_declaration_name $$52 opt_event_initializer opt_event_declarators SEMICOLON",
+//t    "$$53 :",
+//t    "$$54 :",
+//t    "event_declaration : opt_attributes opt_modifiers EVENT type member_declaration_name OPEN_BRACE $$53 event_accessor_declarations $$54 CLOSE_BRACE",
+//t    "event_declaration : opt_attributes opt_modifiers EVENT type error",
+//t    "opt_event_initializer :",
+//t    "$$55 :",
+//t    "opt_event_initializer : ASSIGN $$55 event_variable_initializer",
+//t    "opt_event_declarators :",
+//t    "opt_event_declarators : event_declarators",
+//t    "event_declarators : event_declarator",
+//t    "event_declarators : event_declarators event_declarator",
+//t    "event_declarator : COMMA IDENTIFIER",
+//t    "$$56 :",
+//t    "event_declarator : COMMA IDENTIFIER ASSIGN $$56 event_variable_initializer",
+//t    "$$57 :",
+//t    "event_variable_initializer : $$57 variable_initializer",
+//t    "event_accessor_declarations : add_accessor_declaration remove_accessor_declaration",
+//t    "event_accessor_declarations : remove_accessor_declaration add_accessor_declaration",
+//t    "event_accessor_declarations : add_accessor_declaration",
+//t    "event_accessor_declarations : remove_accessor_declaration",
+//t    "event_accessor_declarations : error",
+//t    "$$58 :",
+//t    "add_accessor_declaration : opt_attributes opt_modifiers ADD $$58 event_accessor_block",
+//t    "$$59 :",
+//t    "remove_accessor_declaration : opt_attributes opt_modifiers REMOVE $$59 event_accessor_block",
+//t    "event_accessor_block : opt_semicolon",
+//t    "event_accessor_block : block",
+//t    "attributes_without_members : attribute_sections CLOSE_BRACE",
+//t    "incomplete_member : opt_attributes opt_modifiers member_type CLOSE_BRACE",
+//t    "$$60 :",
+//t    "$$61 :",
+//t    "$$62 :",
+//t    "enum_declaration : opt_attributes opt_modifiers ENUM type_declaration_name opt_enum_base $$60 OPEN_BRACE $$61 opt_enum_member_declarations $$62 CLOSE_BRACE opt_semicolon",
+//t    "opt_enum_base :",
+//t    "opt_enum_base : COLON type",
+//t    "opt_enum_base : COLON error",
+//t    "opt_enum_member_declarations :",
+//t    "opt_enum_member_declarations : enum_member_declarations",
+//t    "opt_enum_member_declarations : enum_member_declarations COMMA",
+//t    "enum_member_declarations : enum_member_declaration",
+//t    "enum_member_declarations : enum_member_declarations COMMA enum_member_declaration",
+//t    "enum_member_declaration : opt_attributes IDENTIFIER",
+//t    "$$63 :",
+//t    "enum_member_declaration : opt_attributes IDENTIFIER $$63 ASSIGN constant_expression",
+//t    "enum_member_declaration : opt_attributes IDENTIFIER error",
+//t    "enum_member_declaration : attributes_without_members",
+//t    "$$64 :",
+//t    "$$65 :",
+//t    "$$66 :",
+//t    "delegate_declaration : opt_attributes opt_modifiers DELEGATE member_type type_declaration_name OPEN_PARENS $$64 opt_formal_parameter_list CLOSE_PARENS $$65 opt_type_parameter_constraints_clauses $$66 SEMICOLON",
+//t    "opt_nullable :",
+//t    "opt_nullable : INTERR_NULLABLE",
+//t    "namespace_or_type_expr : member_name",
+//t    "namespace_or_type_expr : qualified_alias_member IDENTIFIER opt_type_argument_list",
+//t    "namespace_or_type_expr : qualified_alias_member IDENTIFIER generic_dimension",
+//t    "member_name : simple_name_expr",
+//t    "member_name : namespace_or_type_expr DOT IDENTIFIER opt_type_argument_list",
+//t    "member_name : namespace_or_type_expr DOT IDENTIFIER generic_dimension",
+//t    "simple_name_expr : IDENTIFIER opt_type_argument_list",
+//t    "simple_name_expr : IDENTIFIER generic_dimension",
+//t    "opt_type_argument_list :",
+//t    "opt_type_argument_list : OP_GENERICS_LT type_arguments OP_GENERICS_GT",
+//t    "opt_type_argument_list : OP_GENERICS_LT error",
+//t    "type_arguments : type",
+//t    "type_arguments : type_arguments COMMA type",
+//t    "$$67 :",
+//t    "type_declaration_name : IDENTIFIER $$67 opt_type_parameter_list",
+//t    "member_declaration_name : method_declaration_name",
+//t    "method_declaration_name : type_declaration_name",
+//t    "method_declaration_name : explicit_interface IDENTIFIER opt_type_parameter_list",
+//t    "indexer_declaration_name : THIS",
+//t    "indexer_declaration_name : explicit_interface THIS",
+//t    "explicit_interface : IDENTIFIER opt_type_argument_list DOT",
+//t    "explicit_interface : qualified_alias_member IDENTIFIER opt_type_argument_list DOT",
+//t    "explicit_interface : explicit_interface IDENTIFIER opt_type_argument_list DOT",
+//t    "opt_type_parameter_list :",
+//t    "opt_type_parameter_list : OP_GENERICS_LT_DECL type_parameters OP_GENERICS_GT",
+//t    "type_parameters : type_parameter",
+//t    "type_parameters : type_parameters COMMA type_parameter",
+//t    "type_parameter : opt_attributes opt_type_parameter_variance IDENTIFIER",
+//t    "type_parameter : error",
+//t    "type_and_void : type_expression_or_array",
+//t    "type_and_void : VOID",
+//t    "member_type : type_and_void",
+//t    "type : type_expression_or_array",
+//t    "type : void_invalid",
+//t    "simple_type : type_expression",
+//t    "simple_type : void_invalid",
+//t    "parameter_type : type_expression_or_array",
+//t    "parameter_type : VOID",
+//t    "type_expression_or_array : type_expression",
+//t    "type_expression_or_array : type_expression rank_specifiers",
+//t    "type_expression : namespace_or_type_expr opt_nullable",
+//t    "type_expression : namespace_or_type_expr pointer_stars",
+//t    "type_expression : builtin_type_expression",
+//t    "void_invalid : VOID",
+//t    "builtin_type_expression : builtin_types opt_nullable",
+//t    "builtin_type_expression : builtin_types pointer_stars",
+//t    "builtin_type_expression : VOID pointer_stars",
+//t    "type_list : base_type_name",
+//t    "type_list : type_list COMMA base_type_name",
+//t    "base_type_name : type",
+//t    "builtin_types : OBJECT",
+//t    "builtin_types : STRING",
+//t    "builtin_types : BOOL",
+//t    "builtin_types : DECIMAL",
+//t    "builtin_types : FLOAT",
+//t    "builtin_types : DOUBLE",
+//t    "builtin_types : integral_type",
+//t    "integral_type : SBYTE",
+//t    "integral_type : BYTE",
+//t    "integral_type : SHORT",
+//t    "integral_type : USHORT",
+//t    "integral_type : INT",
+//t    "integral_type : UINT",
+//t    "integral_type : LONG",
+//t    "integral_type : ULONG",
+//t    "integral_type : CHAR",
+//t    "primary_expression : primary_expression_or_type",
+//t    "primary_expression : literal",
+//t    "primary_expression : array_creation_expression",
+//t    "primary_expression : parenthesized_expression",
+//t    "primary_expression : default_value_expression",
+//t    "primary_expression : invocation_expression",
+//t    "primary_expression : element_access",
+//t    "primary_expression : this_access",
+//t    "primary_expression : base_access",
+//t    "primary_expression : post_increment_expression",
+//t    "primary_expression : post_decrement_expression",
+//t    "primary_expression : object_or_delegate_creation_expression",
+//t    "primary_expression : anonymous_type_expression",
+//t    "primary_expression : typeof_expression",
+//t    "primary_expression : sizeof_expression",
+//t    "primary_expression : checked_expression",
+//t    "primary_expression : unchecked_expression",
+//t    "primary_expression : pointer_member_access",
+//t    "primary_expression : anonymous_method_expression",
+//t    "primary_expression : undocumented_expressions",
+//t    "primary_expression_or_type : simple_name_expr",
+//t    "primary_expression_or_type : IDENTIFIER GENERATE_COMPLETION",
+//t    "primary_expression_or_type : member_access",
+//t    "literal : boolean_literal",
+//t    "literal : LITERAL",
+//t    "literal : NULL",
+//t    "boolean_literal : TRUE",
+//t    "boolean_literal : FALSE",
+//t    "open_parens_any : OPEN_PARENS",
+//t    "open_parens_any : OPEN_PARENS_CAST",
+//t    "close_parens : CLOSE_PARENS",
+//t    "close_parens : COMPLETE_COMPLETION",
+//t    "parenthesized_expression : OPEN_PARENS expression CLOSE_PARENS",
+//t    "parenthesized_expression : OPEN_PARENS expression COMPLETE_COMPLETION",
+//t    "member_access : primary_expression DOT identifier_inside_body opt_type_argument_list",
+//t    "member_access : primary_expression DOT identifier_inside_body generic_dimension",
+//t    "member_access : primary_expression INTERR_OPERATOR DOT identifier_inside_body opt_type_argument_list",
+//t    "member_access : builtin_types DOT identifier_inside_body opt_type_argument_list",
+//t    "member_access : BASE DOT identifier_inside_body opt_type_argument_list",
+//t    "member_access : AWAIT DOT identifier_inside_body opt_type_argument_list",
+//t    "member_access : qualified_alias_member identifier_inside_body opt_type_argument_list",
+//t    "member_access : qualified_alias_member identifier_inside_body generic_dimension",
+//t    "member_access : primary_expression DOT GENERATE_COMPLETION",
+//t    "member_access : primary_expression DOT IDENTIFIER GENERATE_COMPLETION",
+//t    "member_access : builtin_types DOT GENERATE_COMPLETION",
+//t    "member_access : builtin_types DOT IDENTIFIER GENERATE_COMPLETION",
+//t    "invocation_expression : primary_expression open_parens_any opt_argument_list close_parens",
+//t    "invocation_expression : primary_expression open_parens_any argument_list error",
+//t    "invocation_expression : primary_expression open_parens_any error",
+//t    "opt_object_or_collection_initializer :",
+//t    "opt_object_or_collection_initializer : object_or_collection_initializer",
+//t    "object_or_collection_initializer : OPEN_BRACE opt_member_initializer_list close_brace_or_complete_completion",
+//t    "object_or_collection_initializer : OPEN_BRACE member_initializer_list COMMA CLOSE_BRACE",
+//t    "opt_member_initializer_list :",
+//t    "opt_member_initializer_list : member_initializer_list",
+//t    "member_initializer_list : member_initializer",
+//t    "member_initializer_list : member_initializer_list COMMA member_initializer",
+//t    "member_initializer_list : member_initializer_list error",
+//t    "member_initializer : IDENTIFIER ASSIGN initializer_value",
+//t    "member_initializer : AWAIT ASSIGN initializer_value",
+//t    "member_initializer : GENERATE_COMPLETION",
+//t    "member_initializer : non_assignment_expression opt_COMPLETE_COMPLETION",
+//t    "member_initializer : OPEN_BRACE expression_list CLOSE_BRACE",
+//t    "member_initializer : OPEN_BRACKET_EXPR expression_list CLOSE_BRACKET ASSIGN initializer_value",
+//t    "member_initializer : OPEN_BRACE CLOSE_BRACE",
+//t    "initializer_value : expression",
+//t    "initializer_value : object_or_collection_initializer",
+//t    "opt_argument_list :",
+//t    "opt_argument_list : argument_list",
+//t    "argument_list : argument_or_named_argument",
+//t    "argument_list : argument_list COMMA argument",
+//t    "argument_list : argument_list COMMA named_argument",
+//t    "argument_list : argument_list COMMA error",
+//t    "argument_list : COMMA error",
+//t    "argument : expression",
+//t    "argument : non_simple_argument",
+//t    "argument_or_named_argument : argument",
+//t    "argument_or_named_argument : named_argument",
+//t    "non_simple_argument : REF variable_reference",
+//t    "non_simple_argument : OUT variable_reference",
+//t    "non_simple_argument : ARGLIST OPEN_PARENS argument_list CLOSE_PARENS",
+//t    "non_simple_argument : ARGLIST OPEN_PARENS CLOSE_PARENS",
+//t    "variable_reference : expression",
+//t    "element_access : primary_expression OPEN_BRACKET_EXPR expression_list_arguments CLOSE_BRACKET",
+//t    "element_access : primary_expression INTERR_OPERATOR OPEN_BRACKET_EXPR expression_list_arguments CLOSE_BRACKET",
+//t    "element_access : primary_expression OPEN_BRACKET_EXPR expression_list_arguments error",
+//t    "element_access : primary_expression OPEN_BRACKET_EXPR error",
+//t    "expression_list : expression_or_error",
+//t    "expression_list : expression_list COMMA expression_or_error",
+//t    "expression_list_arguments : expression_list_argument",
+//t    "expression_list_arguments : expression_list_arguments COMMA expression_list_argument",
+//t    "expression_list_argument : expression",
+//t    "expression_list_argument : named_argument",
+//t    "this_access : THIS",
+//t    "base_access : BASE OPEN_BRACKET_EXPR expression_list_arguments CLOSE_BRACKET",
+//t    "base_access : BASE OPEN_BRACKET error",
+//t    "post_increment_expression : primary_expression OP_INC",
+//t    "post_decrement_expression : primary_expression OP_DEC",
+//t    "object_or_delegate_creation_expression : NEW new_expr_type open_parens_any opt_argument_list CLOSE_PARENS opt_object_or_collection_initializer",
+//t    "object_or_delegate_creation_expression : NEW new_expr_type object_or_collection_initializer",
+//t    "array_creation_expression : NEW new_expr_type OPEN_BRACKET_EXPR expression_list CLOSE_BRACKET opt_rank_specifier opt_array_initializer",
+//t    "array_creation_expression : NEW new_expr_type rank_specifiers opt_array_initializer",
+//t    "array_creation_expression : NEW rank_specifier array_initializer",
+//t    "array_creation_expression : NEW new_expr_type OPEN_BRACKET CLOSE_BRACKET OPEN_BRACKET_EXPR error CLOSE_BRACKET",
+//t    "array_creation_expression : NEW new_expr_type error",
+//t    "$$68 :",
+//t    "new_expr_type : $$68 simple_type",
+//t    "anonymous_type_expression : NEW OPEN_BRACE anonymous_type_parameters_opt_comma CLOSE_BRACE",
+//t    "anonymous_type_expression : NEW OPEN_BRACE GENERATE_COMPLETION",
+//t    "anonymous_type_parameters_opt_comma : anonymous_type_parameters_opt",
+//t    "anonymous_type_parameters_opt_comma : anonymous_type_parameters COMMA",
+//t    "anonymous_type_parameters_opt :",
+//t    "anonymous_type_parameters_opt : anonymous_type_parameters",
+//t    "anonymous_type_parameters : anonymous_type_parameter",
+//t    "anonymous_type_parameters : anonymous_type_parameters COMMA anonymous_type_parameter",
+//t    "anonymous_type_parameters : COMPLETE_COMPLETION",
+//t    "anonymous_type_parameters : anonymous_type_parameter COMPLETE_COMPLETION",
+//t    "anonymous_type_parameter : identifier_inside_body ASSIGN variable_initializer",
+//t    "anonymous_type_parameter : identifier_inside_body",
+//t    "anonymous_type_parameter : member_access",
+//t    "anonymous_type_parameter : error",
+//t    "opt_rank_specifier :",
+//t    "opt_rank_specifier : rank_specifiers",
+//t    "rank_specifiers : rank_specifier",
+//t    "rank_specifiers : rank_specifier rank_specifiers",
+//t    "rank_specifier : OPEN_BRACKET CLOSE_BRACKET",
+//t    "rank_specifier : OPEN_BRACKET dim_separators CLOSE_BRACKET",
+//t    "dim_separators : COMMA",
+//t    "dim_separators : dim_separators COMMA",
+//t    "opt_array_initializer :",
+//t    "opt_array_initializer : array_initializer",
+//t    "array_initializer : OPEN_BRACE CLOSE_BRACE",
+//t    "array_initializer : OPEN_BRACE variable_initializer_list opt_comma CLOSE_BRACE",
+//t    "variable_initializer_list : variable_initializer",
+//t    "variable_initializer_list : variable_initializer_list COMMA variable_initializer",
+//t    "typeof_expression : TYPEOF open_parens_any typeof_type_expression CLOSE_PARENS",
+//t    "typeof_type_expression : type_and_void",
+//t    "typeof_type_expression : error",
+//t    "generic_dimension : GENERIC_DIMENSION",
+//t    "qualified_alias_member : IDENTIFIER DOUBLE_COLON",
+//t    "sizeof_expression : SIZEOF open_parens_any type CLOSE_PARENS",
+//t    "sizeof_expression : SIZEOF open_parens_any type error",
+//t    "checked_expression : CHECKED open_parens_any expression CLOSE_PARENS",
+//t    "checked_expression : CHECKED error",
+//t    "unchecked_expression : UNCHECKED open_parens_any expression CLOSE_PARENS",
+//t    "unchecked_expression : UNCHECKED error",
+//t    "pointer_member_access : primary_expression OP_PTR IDENTIFIER opt_type_argument_list",
+//t    "$$69 :",
+//t    "anonymous_method_expression : DELEGATE opt_anonymous_method_signature $$69 block",
+//t    "$$70 :",
+//t    "anonymous_method_expression : ASYNC DELEGATE opt_anonymous_method_signature $$70 block",
+//t    "opt_anonymous_method_signature :",
+//t    "opt_anonymous_method_signature : anonymous_method_signature",
+//t    "$$71 :",
+//t    "anonymous_method_signature : OPEN_PARENS $$71 opt_formal_parameter_list CLOSE_PARENS",
+//t    "default_value_expression : DEFAULT open_parens_any type CLOSE_PARENS",
+//t    "unary_expression : primary_expression",
+//t    "unary_expression : BANG prefixed_unary_expression",
+//t    "unary_expression : TILDE prefixed_unary_expression",
+//t    "unary_expression : OPEN_PARENS_CAST type CLOSE_PARENS prefixed_unary_expression",
+//t    "unary_expression : AWAIT prefixed_unary_expression",
+//t    "unary_expression : BANG error",
+//t    "unary_expression : TILDE error",
+//t    "unary_expression : OPEN_PARENS_CAST type CLOSE_PARENS error",
+//t    "unary_expression : AWAIT error",
+//t    "prefixed_unary_expression : unary_expression",
+//t    "prefixed_unary_expression : PLUS prefixed_unary_expression",
+//t    "prefixed_unary_expression : MINUS prefixed_unary_expression",
+//t    "prefixed_unary_expression : OP_INC prefixed_unary_expression",
+//t    "prefixed_unary_expression : OP_DEC prefixed_unary_expression",
+//t    "prefixed_unary_expression : STAR prefixed_unary_expression",
+//t    "prefixed_unary_expression : BITWISE_AND prefixed_unary_expression",
+//t    "prefixed_unary_expression : PLUS error",
+//t    "prefixed_unary_expression : MINUS error",
+//t    "prefixed_unary_expression : OP_INC error",
+//t    "prefixed_unary_expression : OP_DEC error",
+//t    "prefixed_unary_expression : STAR error",
+//t    "prefixed_unary_expression : BITWISE_AND error",
+//t    "multiplicative_expression : prefixed_unary_expression",
+//t    "multiplicative_expression : multiplicative_expression STAR prefixed_unary_expression",
+//t    "multiplicative_expression : multiplicative_expression DIV prefixed_unary_expression",
+//t    "multiplicative_expression : multiplicative_expression PERCENT prefixed_unary_expression",
+//t    "multiplicative_expression : multiplicative_expression STAR error",
+//t    "multiplicative_expression : multiplicative_expression DIV error",
+//t    "multiplicative_expression : multiplicative_expression PERCENT error",
+//t    "additive_expression : multiplicative_expression",
+//t    "additive_expression : additive_expression PLUS multiplicative_expression",
+//t    "additive_expression : additive_expression MINUS multiplicative_expression",
+//t    "additive_expression : additive_expression PLUS error",
+//t    "additive_expression : additive_expression MINUS error",
+//t    "additive_expression : additive_expression AS type",
+//t    "additive_expression : additive_expression IS is_match_expr opt_identifier",
+//t    "additive_expression : additive_expression AS error",
+//t    "additive_expression : additive_expression IS error",
+//t    "additive_expression : AWAIT IS type",
+//t    "additive_expression : AWAIT AS type",
+//t    "is_match_expr : match_type",
+//t    "is_match_expr : match_type rank_specifiers",
+//t    "is_match_expr : literal",
+//t    "is_match_expr : PLUS prefixed_unary_expression",
+//t    "is_match_expr : MINUS prefixed_unary_expression",
+//t    "match_type : primary_expression_or_type opt_nullable",
+//t    "match_type : primary_expression_or_type pointer_stars",
+//t    "match_type : builtin_type_expression",
+//t    "match_type : void_invalid",
+//t    "shift_expression : additive_expression",
+//t    "shift_expression : shift_expression OP_SHIFT_LEFT additive_expression",
+//t    "shift_expression : shift_expression OP_SHIFT_RIGHT additive_expression",
+//t    "shift_expression : shift_expression OP_SHIFT_LEFT error",
+//t    "shift_expression : shift_expression OP_SHIFT_RIGHT error",
+//t    "relational_expression : shift_expression",
+//t    "relational_expression : relational_expression OP_LT shift_expression",
+//t    "relational_expression : relational_expression OP_GT shift_expression",
+//t    "relational_expression : relational_expression OP_LE shift_expression",
+//t    "relational_expression : relational_expression OP_GE shift_expression",
+//t    "relational_expression : relational_expression OP_LT error",
+//t    "relational_expression : relational_expression OP_GT error",
+//t    "relational_expression : relational_expression OP_LE error",
+//t    "relational_expression : relational_expression OP_GE error",
+//t    "equality_expression : relational_expression",
+//t    "equality_expression : equality_expression OP_EQ relational_expression",
+//t    "equality_expression : equality_expression OP_NE relational_expression",
+//t    "equality_expression : equality_expression OP_EQ error",
+//t    "equality_expression : equality_expression OP_NE error",
+//t    "and_expression : equality_expression",
+//t    "and_expression : and_expression BITWISE_AND equality_expression",
+//t    "and_expression : and_expression BITWISE_AND error",
+//t    "exclusive_or_expression : and_expression",
+//t    "exclusive_or_expression : exclusive_or_expression CARRET and_expression",
+//t    "exclusive_or_expression : exclusive_or_expression CARRET error",
+//t    "inclusive_or_expression : exclusive_or_expression",
+//t    "inclusive_or_expression : inclusive_or_expression BITWISE_OR exclusive_or_expression",
+//t    "inclusive_or_expression : inclusive_or_expression BITWISE_OR error",
+//t    "conditional_and_expression : inclusive_or_expression",
+//t    "conditional_and_expression : conditional_and_expression OP_AND inclusive_or_expression",
+//t    "conditional_and_expression : conditional_and_expression OP_AND error",
+//t    "conditional_or_expression : conditional_and_expression",
+//t    "conditional_or_expression : conditional_or_expression OP_OR conditional_and_expression",
+//t    "conditional_or_expression : conditional_or_expression OP_OR error",
+//t    "null_coalescing_expression : conditional_or_expression",
+//t    "null_coalescing_expression : conditional_or_expression OP_COALESCING null_coalescing_expression",
+//t    "conditional_expression : null_coalescing_expression",
+//t    "conditional_expression : null_coalescing_expression INTERR expression COLON expression",
+//t    "conditional_expression : null_coalescing_expression INTERR expression error",
+//t    "conditional_expression : null_coalescing_expression INTERR expression COLON error",
+//t    "conditional_expression : null_coalescing_expression INTERR expression COLON CLOSE_BRACE",
+//t    "assignment_expression : prefixed_unary_expression ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_MULT_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_DIV_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_MOD_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_ADD_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_SUB_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_SHIFT_LEFT_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_SHIFT_RIGHT_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_AND_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_OR_ASSIGN expression",
+//t    "assignment_expression : prefixed_unary_expression OP_XOR_ASSIGN expression",
+//t    "lambda_parameter_list : lambda_parameter",
+//t    "lambda_parameter_list : lambda_parameter_list COMMA lambda_parameter",
+//t    "lambda_parameter : parameter_modifier parameter_type identifier_inside_body",
+//t    "lambda_parameter : parameter_type identifier_inside_body",
+//t    "lambda_parameter : IDENTIFIER",
+//t    "lambda_parameter : AWAIT",
+//t    "opt_lambda_parameter_list :",
+//t    "opt_lambda_parameter_list : lambda_parameter_list",
+//t    "$$72 :",
+//t    "lambda_expression_body : $$72 expression",
+//t    "lambda_expression_body : block",
+//t    "lambda_expression_body : error",
+//t    "expression_or_error : expression",
+//t    "expression_or_error : error",
+//t    "$$73 :",
+//t    "lambda_expression : IDENTIFIER ARROW $$73 lambda_expression_body",
+//t    "$$74 :",
+//t    "lambda_expression : AWAIT ARROW $$74 lambda_expression_body",
+//t    "$$75 :",
+//t    "lambda_expression : ASYNC identifier_inside_body ARROW $$75 lambda_expression_body",
+//t    "$$76 :",
+//t    "$$77 :",
+//t    "lambda_expression : OPEN_PARENS_LAMBDA $$76 opt_lambda_parameter_list CLOSE_PARENS ARROW $$77 lambda_expression_body",
+//t    "$$78 :",
+//t    "$$79 :",
+//t    "lambda_expression : ASYNC OPEN_PARENS_LAMBDA $$78 opt_lambda_parameter_list CLOSE_PARENS ARROW $$79 lambda_expression_body",
+//t    "expression : assignment_expression",
+//t    "expression : non_assignment_expression",
+//t    "non_assignment_expression : conditional_expression",
+//t    "non_assignment_expression : lambda_expression",
+//t    "non_assignment_expression : query_expression",
+//t    "non_assignment_expression : ARGLIST",
+//t    "undocumented_expressions : REFVALUE OPEN_PARENS non_assignment_expression COMMA type CLOSE_PARENS",
+//t    "undocumented_expressions : REFTYPE open_parens_any expression CLOSE_PARENS",
+//t    "undocumented_expressions : MAKEREF open_parens_any expression CLOSE_PARENS",
+//t    "constant_expression : expression",
+//t    "boolean_expression : expression",
+//t    "opt_primary_parameters :",
+//t    "opt_primary_parameters : primary_parameters",
+//t    "primary_parameters : OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS",
+//t    "opt_primary_parameters_with_class_base :",
+//t    "opt_primary_parameters_with_class_base : class_base",
+//t    "opt_primary_parameters_with_class_base : primary_parameters",
+//t    "opt_primary_parameters_with_class_base : primary_parameters class_base",
+//t    "$$80 :",
+//t    "opt_primary_parameters_with_class_base : primary_parameters class_base OPEN_PARENS $$80 opt_argument_list CLOSE_PARENS",
+//t    "$$81 :",
+//t    "$$82 :",
+//t    "$$83 :",
+//t    "$$84 :",
+//t    "class_declaration : opt_attributes opt_modifiers opt_partial CLASS $$81 type_declaration_name $$82 opt_primary_parameters_with_class_base opt_type_parameter_constraints_clauses $$83 OPEN_BRACE opt_class_member_declarations CLOSE_BRACE $$84 opt_semicolon",
+//t    "opt_partial :",
+//t    "opt_partial : PARTIAL",
+//t    "opt_modifiers :",
+//t    "opt_modifiers : modifiers",
+//t    "modifiers : modifier",
+//t    "modifiers : modifiers modifier",
+//t    "modifier : NEW",
+//t    "modifier : PUBLIC",
+//t    "modifier : PROTECTED",
+//t    "modifier : INTERNAL",
+//t    "modifier : PRIVATE",
+//t    "modifier : ABSTRACT",
+//t    "modifier : SEALED",
+//t    "modifier : STATIC",
+//t    "modifier : READONLY",
+//t    "modifier : VIRTUAL",
+//t    "modifier : OVERRIDE",
+//t    "modifier : EXTERN",
+//t    "modifier : VOLATILE",
+//t    "modifier : UNSAFE",
+//t    "modifier : ASYNC",
+//t    "opt_class_base :",
+//t    "opt_class_base : class_base",
+//t    "class_base : COLON type_list",
+//t    "class_base : COLON type_list error",
+//t    "opt_type_parameter_constraints_clauses :",
+//t    "opt_type_parameter_constraints_clauses : type_parameter_constraints_clauses",
+//t    "type_parameter_constraints_clauses : type_parameter_constraints_clause",
+//t    "type_parameter_constraints_clauses : type_parameter_constraints_clauses type_parameter_constraints_clause",
+//t    "type_parameter_constraints_clause : WHERE IDENTIFIER COLON type_parameter_constraints",
+//t    "type_parameter_constraints_clause : WHERE IDENTIFIER error",
+//t    "type_parameter_constraints : type_parameter_constraint",
+//t    "type_parameter_constraints : type_parameter_constraints COMMA type_parameter_constraint",
+//t    "type_parameter_constraint : type",
+//t    "type_parameter_constraint : NEW OPEN_PARENS CLOSE_PARENS",
+//t    "type_parameter_constraint : CLASS",
+//t    "type_parameter_constraint : STRUCT",
+//t    "opt_type_parameter_variance :",
+//t    "opt_type_parameter_variance : type_parameter_variance",
+//t    "type_parameter_variance : OUT",
+//t    "type_parameter_variance : IN",
+//t    "$$85 :",
+//t    "block : OPEN_BRACE $$85 opt_statement_list block_end",
+//t    "block_end : CLOSE_BRACE",
+//t    "block_end : COMPLETE_COMPLETION",
+//t    "$$86 :",
+//t    "block_prepared : OPEN_BRACE $$86 opt_statement_list CLOSE_BRACE",
+//t    "block_prepared : CLOSE_BRACE",
+//t    "$$87 :",
+//t    "block_prepared_strict : OPEN_BRACE $$87 opt_statement_list CLOSE_BRACE",
+//t    "opt_statement_list :",
+//t    "opt_statement_list : statement_list",
+//t    "statement_list : statement",
+//t    "statement_list : statement_list statement",
+//t    "statement : block_variable_declaration",
+//t    "statement : valid_declaration_statement",
+//t    "statement : labeled_statement",
+//t    "statement : IDENTIFIER error",
+//t    "statement : error",
+//t    "interactive_statement_list : interactive_statement",
+//t    "interactive_statement_list : interactive_statement_list interactive_statement",
+//t    "interactive_statement : block_variable_declaration",
+//t    "interactive_statement : interactive_valid_declaration_statement",
+//t    "interactive_statement : labeled_statement",
+//t    "valid_declaration_statement : block",
+//t    "valid_declaration_statement : empty_statement",
+//t    "valid_declaration_statement : expression_statement",
+//t    "valid_declaration_statement : selection_statement",
+//t    "valid_declaration_statement : iteration_statement",
+//t    "valid_declaration_statement : jump_statement",
+//t    "valid_declaration_statement : try_statement",
+//t    "valid_declaration_statement : checked_statement",
+//t    "valid_declaration_statement : unchecked_statement",
+//t    "valid_declaration_statement : lock_statement",
+//t    "valid_declaration_statement : using_statement",
+//t    "valid_declaration_statement : unsafe_statement",
+//t    "valid_declaration_statement : fixed_statement",
+//t    "interactive_valid_declaration_statement : block",
+//t    "interactive_valid_declaration_statement : empty_statement",
+//t    "interactive_valid_declaration_statement : interactive_expression_statement",
+//t    "interactive_valid_declaration_statement : selection_statement",
+//t    "interactive_valid_declaration_statement : iteration_statement",
+//t    "interactive_valid_declaration_statement : jump_statement",
+//t    "interactive_valid_declaration_statement : try_statement",
+//t    "interactive_valid_declaration_statement : checked_statement",
+//t    "interactive_valid_declaration_statement : unchecked_statement",
+//t    "interactive_valid_declaration_statement : lock_statement",
+//t    "interactive_valid_declaration_statement : using_statement",
+//t    "interactive_valid_declaration_statement : unsafe_statement",
+//t    "interactive_valid_declaration_statement : fixed_statement",
+//t    "embedded_statement : valid_declaration_statement",
+//t    "embedded_statement : block_variable_declaration",
+//t    "embedded_statement : labeled_statement",
+//t    "embedded_statement : error",
+//t    "empty_statement : SEMICOLON",
+//t    "$$88 :",
+//t    "labeled_statement : identifier_inside_body COLON $$88 statement",
+//t    "variable_type : variable_type_simple",
+//t    "variable_type : variable_type_simple rank_specifiers",
+//t    "variable_type_simple : primary_expression_or_type opt_nullable",
+//t    "variable_type_simple : primary_expression_or_type pointer_stars",
+//t    "variable_type_simple : builtin_type_expression",
+//t    "variable_type_simple : void_invalid",
+//t    "pointer_stars : pointer_star",
+//t    "pointer_stars : pointer_star pointer_stars",
+//t    "pointer_star : STAR",
+//t    "identifier_inside_body : IDENTIFIER",
+//t    "identifier_inside_body : AWAIT",
+//t    "$$89 :",
+//t    "block_variable_declaration : variable_type identifier_inside_body $$89 opt_local_variable_initializer opt_variable_declarators semicolon_or_handle_error_close_brace",
+//t    "$$90 :",
+//t    "block_variable_declaration : CONST variable_type identifier_inside_body $$90 const_variable_initializer opt_const_declarators SEMICOLON",
+//t    "semicolon_or_handle_error_close_brace : SEMICOLON",
+//t    "semicolon_or_handle_error_close_brace : CLOSE_BRACE",
+//t    "opt_local_variable_initializer :",
+//t    "opt_local_variable_initializer : ASSIGN block_variable_initializer",
+//t    "opt_local_variable_initializer : error",
+//t    "opt_variable_declarators :",
+//t    "opt_variable_declarators : variable_declarators",
+//t    "opt_using_or_fixed_variable_declarators :",
+//t    "opt_using_or_fixed_variable_declarators : variable_declarators",
+//t    "variable_declarators : variable_declarator",
+//t    "variable_declarators : variable_declarators variable_declarator",
+//t    "variable_declarator : COMMA identifier_inside_body",
+//t    "variable_declarator : COMMA identifier_inside_body ASSIGN block_variable_initializer",
+//t    "const_variable_initializer :",
+//t    "const_variable_initializer : ASSIGN constant_initializer_expr",
+//t    "opt_const_declarators :",
+//t    "opt_const_declarators : const_declarators",
+//t    "const_declarators : const_declarator",
+//t    "const_declarators : const_declarators const_declarator",
+//t    "const_declarator : COMMA identifier_inside_body ASSIGN constant_initializer_expr",
+//t    "block_variable_initializer : variable_initializer",
+//t    "block_variable_initializer : STACKALLOC simple_type OPEN_BRACKET_EXPR expression CLOSE_BRACKET",
+//t    "block_variable_initializer : STACKALLOC simple_type",
+//t    "expression_statement : statement_expression SEMICOLON",
+//t    "expression_statement : statement_expression COMPLETE_COMPLETION",
+//t    "expression_statement : statement_expression CLOSE_BRACE",
+//t    "interactive_expression_statement : interactive_statement_expression SEMICOLON",
+//t    "interactive_expression_statement : interactive_statement_expression COMPLETE_COMPLETION",
+//t    "statement_expression : expression",
+//t    "interactive_statement_expression : expression",
+//t    "interactive_statement_expression : error",
+//t    "selection_statement : if_statement",
+//t    "selection_statement : switch_statement",
+//t    "if_statement : IF open_parens_any boolean_expression CLOSE_PARENS embedded_statement",
+//t    "if_statement : IF open_parens_any boolean_expression CLOSE_PARENS embedded_statement ELSE embedded_statement",
+//t    "if_statement : IF open_parens_any boolean_expression error",
+//t    "$$91 :",
+//t    "switch_statement : SWITCH open_parens_any expression CLOSE_PARENS OPEN_BRACE $$91 opt_switch_sections CLOSE_BRACE",
+//t    "switch_statement : SWITCH open_parens_any expression error",
+//t    "opt_switch_sections :",
+//t    "opt_switch_sections : switch_sections",
+//t    "switch_sections : switch_section",
+//t    "switch_sections : switch_sections switch_section",
+//t    "switch_sections : error",
+//t    "switch_section : switch_labels statement_list",
+//t    "switch_labels : switch_label",
+//t    "switch_labels : switch_labels switch_label",
+//t    "switch_label : CASE constant_expression COLON",
+//t    "switch_label : CASE constant_expression error",
+//t    "switch_label : DEFAULT_COLON",
+//t    "iteration_statement : while_statement",
+//t    "iteration_statement : do_statement",
+//t    "iteration_statement : for_statement",
+//t    "iteration_statement : foreach_statement",
+//t    "while_statement : WHILE open_parens_any boolean_expression CLOSE_PARENS embedded_statement",
+//t    "while_statement : WHILE open_parens_any boolean_expression error",
+//t    "do_statement : DO embedded_statement WHILE open_parens_any boolean_expression CLOSE_PARENS SEMICOLON",
+//t    "do_statement : DO embedded_statement error",
+//t    "do_statement : DO embedded_statement WHILE open_parens_any boolean_expression error",
+//t    "$$92 :",
+//t    "for_statement : FOR open_parens_any $$92 for_statement_cont",
+//t    "$$93 :",
+//t    "for_statement_cont : opt_for_initializer SEMICOLON $$93 for_statement_condition",
+//t    "for_statement_cont : opt_for_initializer CLOSE_PARENS",
+//t    "$$94 :",
+//t    "for_statement_condition : opt_for_condition SEMICOLON $$94 for_statement_end",
+//t    "for_statement_condition : boolean_expression CLOSE_PARENS",
+//t    "for_statement_end : opt_for_iterator CLOSE_PARENS embedded_statement",
+//t    "for_statement_end : error",
+//t    "opt_for_initializer :",
+//t    "opt_for_initializer : for_initializer",
+//t    "$$95 :",
+//t    "for_initializer : variable_type identifier_inside_body $$95 opt_local_variable_initializer opt_variable_declarators",
+//t    "for_initializer : statement_expression_list",
+//t    "opt_for_condition :",
+//t    "opt_for_condition : boolean_expression",
+//t    "opt_for_iterator :",
+//t    "opt_for_iterator : for_iterator",
+//t    "for_iterator : statement_expression_list",
+//t    "statement_expression_list : statement_expression",
+//t    "statement_expression_list : statement_expression_list COMMA statement_expression",
+//t    "foreach_statement : FOREACH open_parens_any type error",
+//t    "foreach_statement : FOREACH open_parens_any type identifier_inside_body error",
+//t    "$$96 :",
+//t    "foreach_statement : FOREACH open_parens_any type identifier_inside_body IN expression CLOSE_PARENS $$96 embedded_statement",
+//t    "foreach_statement : FOREACH open_parens_any type identifier_inside_body error",
+//t    "foreach_statement : FOREACH open_parens_any type error",
+//t    "jump_statement : break_statement",
+//t    "jump_statement : continue_statement",
+//t    "jump_statement : goto_statement",
+//t    "jump_statement : return_statement",
+//t    "jump_statement : throw_statement",
+//t    "jump_statement : yield_statement",
+//t    "break_statement : BREAK SEMICOLON",
+//t    "continue_statement : CONTINUE SEMICOLON",
+//t    "continue_statement : CONTINUE error",
+//t    "goto_statement : GOTO identifier_inside_body SEMICOLON",
+//t    "goto_statement : GOTO CASE constant_expression SEMICOLON",
+//t    "goto_statement : GOTO DEFAULT SEMICOLON",
+//t    "return_statement : RETURN opt_expression SEMICOLON",
+//t    "return_statement : RETURN expression error",
+//t    "return_statement : RETURN error",
+//t    "throw_statement : THROW opt_expression SEMICOLON",
+//t    "throw_statement : THROW expression error",
+//t    "throw_statement : THROW error",
+//t    "yield_statement : identifier_inside_body RETURN opt_expression SEMICOLON",
+//t    "yield_statement : identifier_inside_body RETURN expression error",
+//t    "yield_statement : identifier_inside_body BREAK SEMICOLON",
+//t    "opt_expression :",
+//t    "opt_expression : expression",
+//t    "try_statement : TRY block catch_clauses",
+//t    "try_statement : TRY block FINALLY block",
+//t    "try_statement : TRY block catch_clauses FINALLY block",
+//t    "try_statement : TRY block error",
+//t    "catch_clauses : catch_clause",
+//t    "catch_clauses : catch_clauses catch_clause",
+//t    "opt_identifier :",
+//t    "opt_identifier : identifier_inside_body",
+//t    "catch_clause : CATCH opt_catch_filter block",
+//t    "$$97 :",
+//t    "catch_clause : CATCH open_parens_any type opt_identifier CLOSE_PARENS $$97 opt_catch_filter block_prepared",
+//t    "catch_clause : CATCH open_parens_any error",
+//t    "catch_clause : CATCH open_parens_any type opt_identifier CLOSE_PARENS error",
+//t    "opt_catch_filter :",
+//t    "opt_catch_filter : IF open_parens_any expression CLOSE_PARENS",
+//t    "checked_statement : CHECKED block",
+//t    "unchecked_statement : UNCHECKED block",
+//t    "$$98 :",
+//t    "unsafe_statement : UNSAFE $$98 block",
+//t    "lock_statement : LOCK open_parens_any expression CLOSE_PARENS embedded_statement",
+//t    "lock_statement : LOCK open_parens_any expression error",
+//t    "$$99 :",
+//t    "$$100 :",
+//t    "fixed_statement : FIXED open_parens_any variable_type identifier_inside_body $$99 using_or_fixed_variable_initializer opt_using_or_fixed_variable_declarators CLOSE_PARENS $$100 embedded_statement",
+//t    "$$101 :",
+//t    "$$102 :",
+//t    "using_statement : USING open_parens_any variable_type identifier_inside_body $$101 using_initialization CLOSE_PARENS $$102 embedded_statement",
+//t    "using_statement : USING open_parens_any expression CLOSE_PARENS embedded_statement",
+//t    "using_statement : USING open_parens_any expression error",
+//t    "using_initialization : using_or_fixed_variable_initializer opt_using_or_fixed_variable_declarators",
+//t    "using_initialization : error",
+//t    "using_or_fixed_variable_initializer :",
+//t    "using_or_fixed_variable_initializer : ASSIGN variable_initializer",
+//t    "query_expression : first_from_clause query_body",
+//t    "query_expression : nested_from_clause query_body",
+//t    "query_expression : first_from_clause COMPLETE_COMPLETION",
+//t    "query_expression : nested_from_clause COMPLETE_COMPLETION",
+//t    "first_from_clause : FROM_FIRST identifier_inside_body IN expression",
+//t    "first_from_clause : FROM_FIRST type identifier_inside_body IN expression",
+//t    "nested_from_clause : FROM identifier_inside_body IN expression",
+//t    "nested_from_clause : FROM type identifier_inside_body IN expression",
+//t    "$$103 :",
+//t    "from_clause : FROM identifier_inside_body IN $$103 expression_or_error",
+//t    "$$104 :",
+//t    "from_clause : FROM type identifier_inside_body IN $$104 expression_or_error",
+//t    "query_body : query_body_clauses select_or_group_clause opt_query_continuation",
+//t    "query_body : select_or_group_clause opt_query_continuation",
+//t    "query_body : query_body_clauses COMPLETE_COMPLETION",
+//t    "query_body : query_body_clauses error",
+//t    "query_body : error",
+//t    "$$105 :",
+//t    "select_or_group_clause : SELECT $$105 expression_or_error",
+//t    "$$106 :",
+//t    "$$107 :",
+//t    "select_or_group_clause : GROUP $$106 expression_or_error $$107 by_expression",
+//t    "by_expression : BY expression_or_error",
+//t    "by_expression : error",
+//t    "query_body_clauses : query_body_clause",
+//t    "query_body_clauses : query_body_clauses query_body_clause",
+//t    "query_body_clause : from_clause",
+//t    "query_body_clause : let_clause",
+//t    "query_body_clause : where_clause",
+//t    "query_body_clause : join_clause",
+//t    "query_body_clause : orderby_clause",
+//t    "$$108 :",
+//t    "let_clause : LET identifier_inside_body ASSIGN $$108 expression_or_error",
+//t    "$$109 :",
+//t    "where_clause : WHERE $$109 expression_or_error",
+//t    "$$110 :",
+//t    "$$111 :",
+//t    "$$112 :",
+//t    "join_clause : JOIN identifier_inside_body IN $$110 expression_or_error ON $$111 expression_or_error EQUALS $$112 expression_or_error opt_join_into",
+//t    "$$113 :",
+//t    "$$114 :",
+//t    "$$115 :",
+//t    "join_clause : JOIN type identifier_inside_body IN $$113 expression_or_error ON $$114 expression_or_error EQUALS $$115 expression_or_error opt_join_into",
+//t    "opt_join_into :",
+//t    "opt_join_into : INTO identifier_inside_body",
+//t    "$$116 :",
+//t    "orderby_clause : ORDERBY $$116 orderings",
+//t    "orderings : order_by",
+//t    "$$117 :",
+//t    "orderings : order_by COMMA $$117 orderings_then_by",
+//t    "orderings_then_by : then_by",
+//t    "$$118 :",
+//t    "orderings_then_by : orderings_then_by COMMA $$118 then_by",
+//t    "order_by : expression",
+//t    "order_by : expression ASCENDING",
+//t    "order_by : expression DESCENDING",
+//t    "then_by : expression",
+//t    "then_by : expression ASCENDING",
+//t    "then_by : expression DESCENDING",
+//t    "opt_query_continuation :",
+//t    "$$119 :",
+//t    "opt_query_continuation : INTO identifier_inside_body $$119 query_body",
+//t    "interactive_parsing : EVAL_STATEMENT_PARSER EOF",
+//t    "interactive_parsing : EVAL_USING_DECLARATIONS_UNIT_PARSER using_directives opt_COMPLETE_COMPLETION",
+//t    "$$120 :",
+//t    "interactive_parsing : EVAL_STATEMENT_PARSER $$120 interactive_statement_list opt_COMPLETE_COMPLETION",
+//t    "interactive_parsing : EVAL_COMPILATION_UNIT_PARSER interactive_compilation_unit",
+//t    "interactive_compilation_unit : opt_extern_alias_directives opt_using_directives",
+//t    "interactive_compilation_unit : opt_extern_alias_directives opt_using_directives namespace_or_type_declarations",
+//t    "opt_COMPLETE_COMPLETION :",
+//t    "opt_COMPLETE_COMPLETION : COMPLETE_COMPLETION",
+//t    "close_brace_or_complete_completion : CLOSE_BRACE",
+//t    "close_brace_or_complete_completion : COMPLETE_COMPLETION",
+//t    "documentation_parsing : DOC_SEE doc_cref",
+//t    "doc_cref : doc_type_declaration_name opt_doc_method_sig",
+//t    "doc_cref : builtin_types opt_doc_method_sig",
+//t    "doc_cref : VOID opt_doc_method_sig",
+//t    "doc_cref : builtin_types DOT IDENTIFIER opt_doc_method_sig",
+//t    "doc_cref : doc_type_declaration_name DOT THIS",
+//t    "$$121 :",
+//t    "doc_cref : doc_type_declaration_name DOT THIS OPEN_BRACKET $$121 opt_doc_parameters CLOSE_BRACKET",
+//t    "doc_cref : EXPLICIT OPERATOR type opt_doc_method_sig",
+//t    "doc_cref : IMPLICIT OPERATOR type opt_doc_method_sig",
+//t    "doc_cref : OPERATOR overloadable_operator opt_doc_method_sig",
+//t    "doc_type_declaration_name : type_declaration_name",
+//t    "doc_type_declaration_name : doc_type_declaration_name DOT type_declaration_name",
+//t    "opt_doc_method_sig :",
+//t    "$$122 :",
+//t    "opt_doc_method_sig : OPEN_PARENS $$122 opt_doc_parameters CLOSE_PARENS",
+//t    "opt_doc_parameters :",
+//t    "opt_doc_parameters : doc_parameters",
+//t    "doc_parameters : doc_parameter",
+//t    "doc_parameters : doc_parameters COMMA doc_parameter",
+//t    "doc_parameter : opt_parameter_modifier parameter_type",
+//t  };
+//t public static string getRule (int index) {
+//t    return yyRule [index];
+//t }
+//t}
+  protected static readonly string [] yyNames = {    
+    "end-of-file",null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,null,null,null,null,null,null,null,
+    null,null,null,null,null,null,null,"EOF","NONE","ERROR",
+    "FIRST_KEYWORD","ABSTRACT","AS","ADD","BASE","BOOL","BREAK","BYTE",
+    "CASE","CATCH","CHAR","CHECKED","CLASS","CONST","CONTINUE","DECIMAL",
+    "DEFAULT","DELEGATE","DO","DOUBLE","ELSE","ENUM","EVENT","EXPLICIT",
+    "EXTERN","FALSE","FINALLY","FIXED","FLOAT","FOR","FOREACH","GOTO",
+    "IF","IMPLICIT","IN","INT","INTERFACE","INTERNAL","IS","LOCK","LONG",
+    "NAMESPACE","NEW","NULL","OBJECT","OPERATOR","OUT","OVERRIDE",
+    "PARAMS","PRIVATE","PROTECTED","PUBLIC","READONLY","REF","RETURN",
+    "REMOVE","SBYTE","SEALED","SHORT","SIZEOF","STACKALLOC","STATIC",
+    "STRING","STRUCT","SWITCH","THIS","THROW","TRUE","TRY","TYPEOF",
+    "UINT","ULONG","UNCHECKED","UNSAFE","USHORT","USING","VIRTUAL","VOID",
+    "VOLATILE","WHERE","WHILE","ARGLIST","PARTIAL","ARROW","FROM",
+    "FROM_FIRST","JOIN","ON","EQUALS","SELECT","GROUP","BY","LET",
+    "ORDERBY","ASCENDING","DESCENDING","INTO","INTERR_NULLABLE",
+    "EXTERN_ALIAS","REFVALUE","REFTYPE","MAKEREF","ASYNC","AWAIT",
+    "INTERR_OPERATOR","GET","SET","LAST_KEYWORD","OPEN_BRACE",
+    "CLOSE_BRACE","OPEN_BRACKET","CLOSE_BRACKET","OPEN_PARENS",
+    "CLOSE_PARENS","DOT","COMMA","COLON","SEMICOLON","TILDE","PLUS",
+    "MINUS","BANG","ASSIGN","OP_LT","OP_GT","BITWISE_AND","BITWISE_OR",
+    "STAR","PERCENT","DIV","CARRET","INTERR","DOUBLE_COLON","OP_INC",
+    "OP_DEC","OP_SHIFT_LEFT","OP_SHIFT_RIGHT","OP_LE","OP_GE","OP_EQ",
+    "OP_NE","OP_AND","OP_OR","OP_MULT_ASSIGN","OP_DIV_ASSIGN",
+    "OP_MOD_ASSIGN","OP_ADD_ASSIGN","OP_SUB_ASSIGN",
+    "OP_SHIFT_LEFT_ASSIGN","OP_SHIFT_RIGHT_ASSIGN","OP_AND_ASSIGN",
+    "OP_XOR_ASSIGN","OP_OR_ASSIGN","OP_PTR","OP_COALESCING",
+    "OP_GENERICS_LT","OP_GENERICS_LT_DECL","OP_GENERICS_GT","LITERAL",
+    "IDENTIFIER","OPEN_PARENS_LAMBDA","OPEN_PARENS_CAST",
+    "GENERIC_DIMENSION","DEFAULT_COLON","OPEN_BRACKET_EXPR",
+    "EVAL_STATEMENT_PARSER","EVAL_COMPILATION_UNIT_PARSER",
+    "EVAL_USING_DECLARATIONS_UNIT_PARSER","DOC_SEE","GENERATE_COMPLETION",
+    "COMPLETE_COMPLETION","UMINUS",
+  };
+
+  /** index-checked interface to yyNames[].
+      @param token single character or %token value.
+      @return token name or [illegal] or [unknown].
+    */
+//t  public static string yyname (int token) {
+//t    if ((token < 0) || (token > yyNames.Length)) return "[illegal]";
+//t    string name;
+//t    if ((name = yyNames[token]) != null) return name;
+//t    return "[unknown]";
+//t  }
+
+#pragma warning disable 414
+  int yyExpectingState;
+#pragma warning restore 414
+  /** computes list of expected tokens on error by tracing the tables.
+      @param state for which to compute the list.
+      @return list of token names.
+    */
+  protected int [] yyExpectingTokens (int state){
+    int token, n, len = 0;
+    bool[] ok = new bool[yyNames.Length];
+    if ((n = yySindex[state]) != 0)
+      for (token = n < 0 ? -n : 0;
+           (token < yyNames.Length) && (n+token < yyTable.Length); ++ token)
+        if (yyCheck[n+token] == token && !ok[token] && yyNames[token] != null) {
+          ++ len;
+          ok[token] = true;
+        }
+    if ((n = yyRindex[state]) != 0)
+      for (token = n < 0 ? -n : 0;
+           (token < yyNames.Length) && (n+token < yyTable.Length); ++ token)
+        if (yyCheck[n+token] == token && !ok[token] && yyNames[token] != null) {
+          ++ len;
+          ok[token] = true;
+        }
+    int [] result = new int [len];
+    for (n = token = 0; n < len;  ++ token)
+      if (ok[token]) result[n++] = token;
+    return result;
+  }
+  protected string[] yyExpecting (int state) {
+    int [] tokens = yyExpectingTokens (state);
+    string [] result = new string[tokens.Length];
+    for (int n = 0; n < tokens.Length;  n++)
+      result[n++] = yyNames[tokens [n]];
+    return result;
+  }
+
+  /** the generated parser, with debugging messages.
+      Maintains a state and a value stack, currently with fixed maximum size.
+      @param yyLex scanner.
+      @param yydebug debug message writer implementing yyDebug, or null.
+      @return result of the last reduction, if any.
+      @throws yyException on irrecoverable parse error.
+    */
+  internal Object yyparse (yyParser.yyInput yyLex, Object yyd)
+				 {
+//t    this.debug = (yydebug.yyDebug)yyd;
+    return yyparse(yyLex);
+  }
+
+  /** initial size and increment of the state/value stack [default 256].
+      This is not final so that it can be overwritten outside of invocations
+      of yyparse().
+    */
+  protected int yyMax;
+
+  /** executed at the beginning of a reduce action.
+      Used as $$ = yyDefault($1), prior to the user-specified action, if any.
+      Can be overwritten to provide deep copy, etc.
+      @param first value for $1, or null.
+      @return first.
+    */
+  protected Object yyDefault (Object first) {
+    return first;
+  }
+
+	static int[] global_yyStates;
+	static object[] global_yyVals;
+#pragma warning disable 649
+	protected bool use_global_stacks;
+#pragma warning restore 649
+	object[] yyVals;					// value stack
+	object yyVal;						// value stack ptr
+	int yyToken;						// current input
+	int yyTop;
+
+  /** the generated parser.
+      Maintains a state and a value stack, currently with fixed maximum size.
+      @param yyLex scanner.
+      @return result of the last reduction, if any.
+      @throws yyException on irrecoverable parse error.
+    */
+  internal Object yyparse (yyParser.yyInput yyLex)
+  {
+    if (yyMax <= 0) yyMax = 256;		// initial size
+    int yyState = 0;                   // state stack ptr
+    int [] yyStates;               	// state stack 
+    yyVal = null;
+    yyToken = -1;
+    int yyErrorFlag = 0;				// #tks to shift
+	if (use_global_stacks && global_yyStates != null) {
+		yyVals = global_yyVals;
+		yyStates = global_yyStates;
+   } else {
+		yyVals = new object [yyMax];
+		yyStates = new int [yyMax];
+		if (use_global_stacks) {
+			global_yyVals = yyVals;
+			global_yyStates = yyStates;
+		}
+	}
+
+    /*yyLoop:*/ for (yyTop = 0;; ++ yyTop) {
+      if (yyTop >= yyStates.Length) {			// dynamically increase
+        global::System.Array.Resize (ref yyStates, yyStates.Length+yyMax);
+        global::System.Array.Resize (ref yyVals, yyVals.Length+yyMax);
+      }
+      yyStates[yyTop] = yyState;
+      yyVals[yyTop] = yyVal;
+//t      if (debug != null) debug.push(yyState, yyVal);
+
+      /*yyDiscarded:*/ while (true) {	// discarding a token does not change stack
+        int yyN;
+        if ((yyN = yyDefRed[yyState]) == 0) {	// else [default] reduce (yyN)
+          if (yyToken < 0) {
+            yyToken = yyLex.advance() ? yyLex.token() : 0;
+//t            if (debug != null)
+//t              debug.lex(yyState, yyToken, yyname(yyToken), yyLex.value());
+          }
+          if ((yyN = yySindex[yyState]) != 0 && ((yyN += yyToken) >= 0)
+              && (yyN < yyTable.Length) && (yyCheck[yyN] == yyToken)) {
+//t            if (debug != null)
+//t              debug.shift(yyState, yyTable[yyN], yyErrorFlag-1);
+            yyState = yyTable[yyN];		// shift to yyN
+            yyVal = yyLex.value();
+            yyToken = -1;
+            if (yyErrorFlag > 0) -- yyErrorFlag;
+            goto continue_yyLoop;
+          }
+          if ((yyN = yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
+              && yyN < yyTable.Length && yyCheck[yyN] == yyToken)
+            yyN = yyTable[yyN];			// reduce (yyN)
+          else
+            switch (yyErrorFlag) {
+  
+            case 0:
+              yyExpectingState = yyState;
+              // yyerror(String.Format ("syntax error, got token `{0}'", yyname (yyToken)), yyExpecting(yyState));
+//t              if (debug != null) debug.error("syntax error");
+              if (yyToken == 0 /*eof*/ || yyToken == eof_token) throw new yyParser.yyUnexpectedEof ();
+              goto case 1;
+            case 1: case 2:
+              yyErrorFlag = 3;
+              do {
+                if ((yyN = yySindex[yyStates[yyTop]]) != 0
+                    && (yyN += Token.yyErrorCode) >= 0 && yyN < yyTable.Length
+                    && yyCheck[yyN] == Token.yyErrorCode) {
+//t                  if (debug != null)
+//t                    debug.shift(yyStates[yyTop], yyTable[yyN], 3);
+                  yyState = yyTable[yyN];
+                  yyVal = yyLex.value();
+                  goto continue_yyLoop;
+                }
+//t                if (debug != null) debug.pop(yyStates[yyTop]);
+              } while (-- yyTop >= 0);
+//t              if (debug != null) debug.reject();
+              throw new yyParser.yyException("irrecoverable syntax error");
+  
+            case 3:
+              if (yyToken == 0) {
+//t                if (debug != null) debug.reject();
+                throw new yyParser.yyException("irrecoverable syntax error at end-of-file");
+              }
+//t              if (debug != null)
+//t                debug.discard(yyState, yyToken, yyname(yyToken),
+//t  							yyLex.value());
+              yyToken = -1;
+              goto continue_yyDiscarded;		// leave stack alone
+            }
+        }
+        int yyV = yyTop + 1-yyLen[yyN];
+//t        if (debug != null)
+//t          debug.reduce(yyState, yyStates[yyV-1], yyN, YYRules.getRule (yyN), yyLen[yyN]);
+        yyVal = yyV > yyTop ? null : yyVals[yyV]; // yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
+        switch (yyN) {
+case 1:
+#line 389 "cs-parser.jay"
+  {
+		Lexer.check_incorrect_doc_comment ();
+	  }
+  break;
+case 2:
+#line 390 "cs-parser.jay"
+  { Lexer.CompleteOnEOF = false; }
+  break;
+case 6:
+  case_6();
+  break;
+case 7:
+#line 409 "cs-parser.jay"
+  {
+		module.AddAttributes ((Attributes) yyVals[0+yyTop], current_namespace);
+	  }
+  break;
+case 8:
+  case_8();
+  break;
+case 13:
+  case_13();
+  break;
+case 14:
+#line 454 "cs-parser.jay"
+  {
+		Error_SyntaxError (yyToken);
+	  }
+  break;
+case 17:
+  case_17();
+  break;
+case 18:
+  case_18();
+  break;
+case 19:
+  case_19();
+  break;
+case 20:
+  case_20();
+  break;
+case 21:
+  case_21();
+  break;
+case 22:
+  case_22();
+  break;
+case 23:
+  case_23();
+  break;
+case 24:
+  case_24();
+  break;
+case 27:
+  case_27();
+  break;
+case 28:
+  case_28();
+  break;
+case 29:
+  case_29();
+  break;
+case 30:
+  case_30();
+  break;
+case 43:
+  case_43();
+  break;
+case 44:
+#line 638 "cs-parser.jay"
+  {
+		current_namespace.DeclarationFound = true;
+	  }
+  break;
+case 45:
+  case_45();
+  break;
+case 53:
+  case_53();
+  break;
+case 54:
+  case_54();
+  break;
+case 55:
+  case_55();
+  break;
+case 56:
+  case_56();
+  break;
+case 57:
+  case_57();
+  break;
+case 58:
+  case_58();
+  break;
+case 59:
+  case_59();
+  break;
+case 60:
+  case_60();
+  break;
+case 61:
+  case_61();
+  break;
+case 62:
+  case_62();
+  break;
+case 63:
+#line 763 "cs-parser.jay"
+  { yyVal = "event"; PushLocation (GetLocation (yyVals[0+yyTop])); }
+  break;
+case 64:
+#line 764 "cs-parser.jay"
+  { yyVal = "return"; PushLocation (GetLocation (yyVals[0+yyTop])); }
+  break;
+case 65:
+#line 771 "cs-parser.jay"
+  {
+		yyVal = new List<Attribute> (4) { (Attribute) yyVals[0+yyTop] };
+	  }
+  break;
+case 66:
+  case_66();
+  break;
+case 67:
+#line 788 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 68:
+  case_68();
+  break;
+case 70:
+#line 816 "cs-parser.jay"
+  { yyVal = null; HadAttributeParens = false;  }
+  break;
+case 71:
+  case_71();
+  break;
+case 72:
+#line 828 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 73:
+  case_73();
+  break;
+case 74:
+  case_74();
+  break;
+case 75:
+  case_75();
+  break;
+case 76:
+  case_76();
+  break;
+case 77:
+#line 872 "cs-parser.jay"
+  {
+	  	yyVal = new Argument ((Expression) yyVals[0+yyTop]);
+	  }
+  break;
+case 79:
+  case_79();
+  break;
+case 80:
+#line 885 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 81:
+  case_81();
+  break;
+case 82:
+  case_82();
+  break;
+case 83:
+#line 911 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 84:
+#line 915 "cs-parser.jay"
+  { 
+		yyVal = Argument.AType.Ref;
+	  }
+  break;
+case 85:
+#line 919 "cs-parser.jay"
+  { 
+		yyVal = Argument.AType.Out;
+	  }
+  break;
+case 88:
+  case_88();
+  break;
+case 89:
+  case_89();
+  break;
+case 103:
+  case_103();
+  break;
+case 104:
+  case_104();
+  break;
+case 105:
+  case_105();
+  break;
+case 106:
+#line 996 "cs-parser.jay"
+  {
+	  }
+  break;
+case 107:
+  case_107();
+  break;
+case 108:
+  case_108();
+  break;
+case 109:
+  case_109();
+  break;
+case 110:
+  case_110();
+  break;
+case 111:
+  case_111();
+  break;
+case 112:
+#line 1046 "cs-parser.jay"
+  {
+		Error_SyntaxError (yyToken);
+	  }
+  break;
+case 113:
+  case_113();
+  break;
+case 114:
+  case_114();
+  break;
+case 115:
+  case_115();
+  break;
+case 118:
+#line 1095 "cs-parser.jay"
+  {
+		current_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 119:
+#line 1099 "cs-parser.jay"
+  {
+		current_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 120:
+  case_120();
+  break;
+case 121:
+#line 1115 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 122:
+  case_122();
+  break;
+case 123:
+  case_123();
+  break;
+case 126:
+  case_126();
+  break;
+case 127:
+  case_127();
+  break;
+case 128:
+  case_128();
+  break;
+case 129:
+  case_129();
+  break;
+case 130:
+#line 1194 "cs-parser.jay"
+  {
+		report.Error (1641, GetLocation (yyVals[-1+yyTop]), "A fixed size buffer field must have the array size specifier after the field name");
+	  }
+  break;
+case 132:
+  case_132();
+  break;
+case 133:
+  case_133();
+  break;
+case 136:
+#line 1224 "cs-parser.jay"
+  {
+		current_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 137:
+#line 1228 "cs-parser.jay"
+  {
+		current_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 138:
+  case_138();
+  break;
+case 139:
+#line 1241 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 140:
+  case_140();
+  break;
+case 143:
+#line 1260 "cs-parser.jay"
+  {
+		current_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 144:
+#line 1264 "cs-parser.jay"
+  {
+		current_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 145:
+  case_145();
+  break;
+case 146:
+#line 1280 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 147:
+  case_147();
+  break;
+case 148:
+  case_148();
+  break;
+case 151:
+  case_151();
+  break;
+case 152:
+  case_152();
+  break;
+case 153:
+  case_153();
+  break;
+case 154:
+#line 1348 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.All;
+	  }
+  break;
+case 155:
+  case_155();
+  break;
+case 156:
+  case_156();
+  break;
+case 157:
+#line 1387 "cs-parser.jay"
+  {
+		lexer.parsing_generic_declaration = true;
+	  }
+  break;
+case 158:
+  case_158();
+  break;
+case 159:
+#line 1397 "cs-parser.jay"
+  {
+		lexer.ConstraintsParsing = true;
+	  }
+  break;
+case 160:
+  case_160();
+  break;
+case 161:
+  case_161();
+  break;
+case 162:
+  case_162();
+  break;
+case 166:
+#line 1475 "cs-parser.jay"
+  { savedLocation = GetLocation (yyVals[0+yyTop]); yyVal = null; }
+  break;
+case 167:
+  case_167();
+  break;
+case 168:
+  case_168();
+  break;
+case 169:
+#line 1499 "cs-parser.jay"
+  { yyVal = ParametersCompiled.EmptyReadOnlyParameters; }
+  break;
+case 171:
+  case_171();
+  break;
+case 172:
+  case_172();
+  break;
+case 173:
+  case_173();
+  break;
+case 174:
+  case_174();
+  break;
+case 175:
+  case_175();
+  break;
+case 176:
+  case_176();
+  break;
+case 177:
+  case_177();
+  break;
+case 178:
+#line 1571 "cs-parser.jay"
+  {
+		yyVal = new ParametersCompiled (new Parameter[] { (Parameter) yyVals[0+yyTop] } );
+	  }
+  break;
+case 179:
+#line 1575 "cs-parser.jay"
+  {
+		yyVal = new ParametersCompiled (new Parameter [] { new ArglistParameter (GetLocation (yyVals[0+yyTop])) }, true);
+	  }
+  break;
+case 180:
+  case_180();
+  break;
+case 181:
+  case_181();
+  break;
+case 182:
+  case_182();
+  break;
+case 183:
+  case_183();
+  break;
+case 184:
+  case_184();
+  break;
+case 185:
+  case_185();
+  break;
+case 186:
+  case_186();
+  break;
+case 187:
+#line 1656 "cs-parser.jay"
+  {
+	  	++lexer.parsing_block;
+	  }
+  break;
+case 188:
+  case_188();
+  break;
+case 189:
+#line 1697 "cs-parser.jay"
+  { yyVal = Parameter.Modifier.NONE; }
+  break;
+case 191:
+#line 1705 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 192:
+  case_192();
+  break;
+case 193:
+  case_193();
+  break;
+case 194:
+  case_194();
+  break;
+case 195:
+  case_195();
+  break;
+case 196:
+  case_196();
+  break;
+case 197:
+  case_197();
+  break;
+case 198:
+  case_198();
+  break;
+case 199:
+  case_199();
+  break;
+case 200:
+  case_200();
+  break;
+case 201:
+#line 1799 "cs-parser.jay"
+  {
+		Error_DuplicateParameterModifier (GetLocation (yyVals[-1+yyTop]), Parameter.Modifier.PARAMS);
+	  }
+  break;
+case 202:
+  case_202();
+  break;
+case 203:
+  case_203();
+  break;
+case 204:
+  case_204();
+  break;
+case 205:
+  case_205();
+  break;
+case 206:
+  case_206();
+  break;
+case 207:
+#line 1849 "cs-parser.jay"
+  {
+		current_property = null;
+	  }
+  break;
+case 208:
+  case_208();
+  break;
+case 209:
+  case_209();
+  break;
+case 211:
+  case_211();
+  break;
+case 212:
+  case_212();
+  break;
+case 215:
+#line 1911 "cs-parser.jay"
+  {
+	  	valid_param_mod = ParameterModifierType.Params | ParameterModifierType.DefaultValue;
+	  }
+  break;
+case 216:
+  case_216();
+  break;
+case 217:
+  case_217();
+  break;
+case 218:
+#line 1957 "cs-parser.jay"
+  {
+		lbag.AppendToMember (current_property, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 219:
+  case_219();
+  break;
+case 224:
+  case_224();
+  break;
+case 225:
+  case_225();
+  break;
+case 226:
+  case_226();
+  break;
+case 227:
+  case_227();
+  break;
+case 228:
+  case_228();
+  break;
+case 230:
+  case_230();
+  break;
+case 231:
+  case_231();
+  break;
+case 232:
+#line 2098 "cs-parser.jay"
+  {
+	  }
+  break;
+case 233:
+  case_233();
+  break;
+case 234:
+  case_234();
+  break;
+case 235:
+  case_235();
+  break;
+case 236:
+  case_236();
+  break;
+case 237:
+#line 2138 "cs-parser.jay"
+  {
+		Error_SyntaxError (yyToken);	  
+	  }
+  break;
+case 240:
+  case_240();
+  break;
+case 241:
+  case_241();
+  break;
+case 242:
+#line 2163 "cs-parser.jay"
+  {
+		report.Error (525, GetLocation (yyVals[0+yyTop]), "Interfaces cannot contain fields or constants");
+	  }
+  break;
+case 243:
+#line 2167 "cs-parser.jay"
+  {
+		report.Error (525, GetLocation (yyVals[0+yyTop]), "Interfaces cannot contain fields or constants");
+	  }
+  break;
+case 248:
+#line 2175 "cs-parser.jay"
+  {
+	  	report.Error (567, GetLocation (yyVals[0+yyTop]), "Interfaces cannot contain operators");
+	  }
+  break;
+case 249:
+#line 2179 "cs-parser.jay"
+  {
+	  	report.Error (526, GetLocation (yyVals[0+yyTop]), "Interfaces cannot contain contructors");
+	  }
+  break;
+case 250:
+#line 2183 "cs-parser.jay"
+  {
+	  	report.Error (524, GetLocation (yyVals[0+yyTop]), "Interfaces cannot declare classes, structs, interfaces, delegates, or enumerations");
+	  }
+  break;
+case 251:
+#line 2189 "cs-parser.jay"
+  {
+	  }
+  break;
+case 252:
+  case_252();
+  break;
+case 254:
+  case_254();
+  break;
+case 255:
+#line 2233 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.DefaultValue;
+	  }
+  break;
+case 256:
+  case_256();
+  break;
+case 258:
+#line 2279 "cs-parser.jay"
+  { yyVal = Operator.OpType.LogicalNot; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 259:
+#line 2280 "cs-parser.jay"
+  { yyVal = Operator.OpType.OnesComplement; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 260:
+#line 2281 "cs-parser.jay"
+  { yyVal = Operator.OpType.Increment; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 261:
+#line 2282 "cs-parser.jay"
+  { yyVal = Operator.OpType.Decrement; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 262:
+#line 2283 "cs-parser.jay"
+  { yyVal = Operator.OpType.True; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 263:
+#line 2284 "cs-parser.jay"
+  { yyVal = Operator.OpType.False; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 264:
+#line 2286 "cs-parser.jay"
+  { yyVal = Operator.OpType.Addition; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 265:
+#line 2287 "cs-parser.jay"
+  { yyVal = Operator.OpType.Subtraction; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 266:
+#line 2289 "cs-parser.jay"
+  { yyVal = Operator.OpType.Multiply; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 267:
+#line 2290 "cs-parser.jay"
+  {  yyVal = Operator.OpType.Division; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 268:
+#line 2291 "cs-parser.jay"
+  { yyVal = Operator.OpType.Modulus; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 269:
+#line 2292 "cs-parser.jay"
+  { yyVal = Operator.OpType.BitwiseAnd; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 270:
+#line 2293 "cs-parser.jay"
+  { yyVal = Operator.OpType.BitwiseOr; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 271:
+#line 2294 "cs-parser.jay"
+  { yyVal = Operator.OpType.ExclusiveOr; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 272:
+#line 2295 "cs-parser.jay"
+  { yyVal = Operator.OpType.LeftShift; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 273:
+#line 2296 "cs-parser.jay"
+  { yyVal = Operator.OpType.RightShift; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 274:
+#line 2297 "cs-parser.jay"
+  { yyVal = Operator.OpType.Equality; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 275:
+#line 2298 "cs-parser.jay"
+  { yyVal = Operator.OpType.Inequality; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 276:
+#line 2299 "cs-parser.jay"
+  { yyVal = Operator.OpType.GreaterThan; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 277:
+#line 2300 "cs-parser.jay"
+  { yyVal = Operator.OpType.LessThan; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 278:
+#line 2301 "cs-parser.jay"
+  { yyVal = Operator.OpType.GreaterThanOrEqual; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 279:
+#line 2302 "cs-parser.jay"
+  { yyVal = Operator.OpType.LessThanOrEqual; savedOperatorLocation = GetLocation (yyVals[0+yyTop]); }
+  break;
+case 280:
+#line 2309 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.DefaultValue;
+	  }
+  break;
+case 281:
+  case_281();
+  break;
+case 282:
+#line 2332 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.DefaultValue;
+	  }
+  break;
+case 283:
+  case_283();
+  break;
+case 284:
+  case_284();
+  break;
+case 285:
+  case_285();
+  break;
+case 286:
+  case_286();
+  break;
+case 287:
+  case_287();
+  break;
+case 288:
+  case_288();
+  break;
+case 289:
+  case_289();
+  break;
+case 291:
+#line 2442 "cs-parser.jay"
+  { current_block = null; yyVal = null; }
+  break;
+case 294:
+#line 2454 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 295:
+  case_295();
+  break;
+case 296:
+#line 2464 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 297:
+  case_297();
+  break;
+case 298:
+  case_298();
+  break;
+case 299:
+  case_299();
+  break;
+case 300:
+  case_300();
+  break;
+case 301:
+  case_301();
+  break;
+case 302:
+  case_302();
+  break;
+case 303:
+  case_303();
+  break;
+case 304:
+  case_304();
+  break;
+case 305:
+  case_305();
+  break;
+case 306:
+  case_306();
+  break;
+case 307:
+  case_307();
+  break;
+case 309:
+#line 2591 "cs-parser.jay"
+  {
+	  	++lexer.parsing_block;
+	  }
+  break;
+case 310:
+  case_310();
+  break;
+case 313:
+#line 2609 "cs-parser.jay"
+  {
+		current_event_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 314:
+#line 2613 "cs-parser.jay"
+  {
+		current_event_field.AddDeclarator ((FieldDeclarator) yyVals[0+yyTop]);
+	  }
+  break;
+case 315:
+  case_315();
+  break;
+case 316:
+#line 2626 "cs-parser.jay"
+  {
+		++lexer.parsing_block;
+	  }
+  break;
+case 317:
+  case_317();
+  break;
+case 318:
+  case_318();
+  break;
+case 319:
+#line 2651 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 322:
+  case_322();
+  break;
+case 323:
+  case_323();
+  break;
+case 324:
+  case_324();
+  break;
+case 325:
+  case_325();
+  break;
+case 326:
+  case_326();
+  break;
+case 327:
+  case_327();
+  break;
+case 328:
+  case_328();
+  break;
+case 329:
+  case_329();
+  break;
+case 331:
+  case_331();
+  break;
+case 332:
+  case_332();
+  break;
+case 333:
+  case_333();
+  break;
+case 334:
+  case_334();
+  break;
+case 335:
+  case_335();
+  break;
+case 336:
+  case_336();
+  break;
+case 338:
+  case_338();
+  break;
+case 339:
+  case_339();
+  break;
+case 342:
+#line 2839 "cs-parser.jay"
+  {
+		lbag.AppendToMember (current_container, GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 344:
+  case_344();
+  break;
+case 345:
+  case_345();
+  break;
+case 346:
+  case_346();
+  break;
+case 347:
+  case_347();
+  break;
+case 348:
+  case_348();
+  break;
+case 350:
+#line 2913 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out | ParameterModifierType.Params | ParameterModifierType.DefaultValue;
+	  }
+  break;
+case 351:
+  case_351();
+  break;
+case 352:
+#line 2932 "cs-parser.jay"
+  {
+		lexer.ConstraintsParsing = false;
+	  }
+  break;
+case 353:
+  case_353();
+  break;
+case 355:
+  case_355();
+  break;
+case 357:
+  case_357();
+  break;
+case 358:
+  case_358();
+  break;
+case 360:
+  case_360();
+  break;
+case 361:
+  case_361();
+  break;
+case 362:
+  case_362();
+  break;
+case 363:
+  case_363();
+  break;
+case 365:
+  case_365();
+  break;
+case 366:
+  case_366();
+  break;
+case 367:
+  case_367();
+  break;
+case 368:
+  case_368();
+  break;
+case 369:
+#line 3062 "cs-parser.jay"
+  {
+		lexer.parsing_generic_declaration = true;
+	  }
+  break;
+case 370:
+  case_370();
+  break;
+case 371:
+  case_371();
+  break;
+case 373:
+  case_373();
+  break;
+case 374:
+  case_374();
+  break;
+case 375:
+  case_375();
+  break;
+case 376:
+  case_376();
+  break;
+case 377:
+  case_377();
+  break;
+case 378:
+  case_378();
+  break;
+case 380:
+  case_380();
+  break;
+case 381:
+  case_381();
+  break;
+case 382:
+  case_382();
+  break;
+case 383:
+  case_383();
+  break;
+case 384:
+  case_384();
+  break;
+case 386:
+#line 3187 "cs-parser.jay"
+  {
+		yyVal = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 387:
+#line 3194 "cs-parser.jay"
+  {
+		lexer.parsing_generic_declaration = true;
+	  }
+  break;
+case 393:
+  case_393();
+  break;
+case 395:
+#line 3224 "cs-parser.jay"
+  {
+		yyVal = new ComposedCast ((FullNamedExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+  break;
+case 396:
+  case_396();
+  break;
+case 397:
+#line 3243 "cs-parser.jay"
+  {
+		yyVal = new ComposedCast ((ATypeNameExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+  break;
+case 399:
+  case_399();
+  break;
+case 400:
+  case_400();
+  break;
+case 401:
+#line 3264 "cs-parser.jay"
+  {
+		yyVal = new ComposedCast ((FullNamedExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+  break;
+case 402:
+#line 3268 "cs-parser.jay"
+  {
+		yyVal = new ComposedCast (new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[-1+yyTop])), (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+  break;
+case 403:
+  case_403();
+  break;
+case 404:
+  case_404();
+  break;
+case 405:
+  case_405();
+  break;
+case 406:
+#line 3302 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Object, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 407:
+#line 3303 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.String, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 408:
+#line 3304 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Bool, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 409:
+#line 3305 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Decimal, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 410:
+#line 3306 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Float, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 411:
+#line 3307 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Double, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 413:
+#line 3312 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.SByte, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 414:
+#line 3313 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Byte, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 415:
+#line 3314 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Short, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 416:
+#line 3315 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.UShort, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 417:
+#line 3316 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Int, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 418:
+#line 3317 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.UInt, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 419:
+#line 3318 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Long, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 420:
+#line 3319 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.ULong, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 421:
+#line 3320 "cs-parser.jay"
+  { yyVal = new TypeExpression (compiler.BuiltinTypes.Char, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 443:
+  case_443();
+  break;
+case 447:
+#line 3363 "cs-parser.jay"
+  { yyVal = new NullLiteral (GetLocation (yyVals[0+yyTop])); }
+  break;
+case 448:
+#line 3367 "cs-parser.jay"
+  { yyVal = new BoolLiteral (compiler.BuiltinTypes, true, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 449:
+#line 3368 "cs-parser.jay"
+  { yyVal = new BoolLiteral (compiler.BuiltinTypes, false, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 454:
+  case_454();
+  break;
+case 455:
+#line 3401 "cs-parser.jay"
+  {
+		yyVal = new ParenthesizedExpression ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+  break;
+case 456:
+  case_456();
+  break;
+case 457:
+  case_457();
+  break;
+case 458:
+  case_458();
+  break;
+case 459:
+  case_459();
+  break;
+case 460:
+  case_460();
+  break;
+case 461:
+  case_461();
+  break;
+case 462:
+  case_462();
+  break;
+case 463:
+  case_463();
+  break;
+case 464:
+#line 3465 "cs-parser.jay"
+  {
+		yyVal = new CompletionMemberAccess ((Expression) yyVals[-2+yyTop], null,GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 465:
+  case_465();
+  break;
+case 466:
+#line 3473 "cs-parser.jay"
+  {
+		yyVal = new CompletionMemberAccess ((Expression) yyVals[-2+yyTop], null, lexer.Location);
+	  }
+  break;
+case 467:
+  case_467();
+  break;
+case 468:
+  case_468();
+  break;
+case 469:
+  case_469();
+  break;
+case 470:
+  case_470();
+  break;
+case 471:
+#line 3503 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 473:
+  case_473();
+  break;
+case 474:
+  case_474();
+  break;
+case 475:
+#line 3525 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 476:
+#line 3529 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	}
+  break;
+case 477:
+  case_477();
+  break;
+case 478:
+  case_478();
+  break;
+case 479:
+  case_479();
+  break;
+case 480:
+  case_480();
+  break;
+case 481:
+  case_481();
+  break;
+case 482:
+#line 3568 "cs-parser.jay"
+  {
+		yyVal = new CompletionElementInitializer (null, GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 483:
+  case_483();
+  break;
+case 484:
+  case_484();
+  break;
+case 485:
+  case_485();
+  break;
+case 486:
+  case_486();
+  break;
+case 489:
+#line 3608 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 491:
+  case_491();
+  break;
+case 492:
+  case_492();
+  break;
+case 493:
+  case_493();
+  break;
+case 494:
+  case_494();
+  break;
+case 495:
+  case_495();
+  break;
+case 496:
+#line 3662 "cs-parser.jay"
+  {
+		yyVal = new Argument ((Expression) yyVals[0+yyTop]);
+	  }
+  break;
+case 500:
+  case_500();
+  break;
+case 501:
+  case_501();
+  break;
+case 502:
+  case_502();
+  break;
+case 503:
+  case_503();
+  break;
+case 505:
+  case_505();
+  break;
+case 506:
+  case_506();
+  break;
+case 507:
+  case_507();
+  break;
+case 508:
+  case_508();
+  break;
+case 509:
+  case_509();
+  break;
+case 510:
+  case_510();
+  break;
+case 511:
+  case_511();
+  break;
+case 512:
+  case_512();
+  break;
+case 513:
+#line 3766 "cs-parser.jay"
+  {
+	  	yyVal = new Argument ((Expression) yyVals[0+yyTop]);
+	  }
+  break;
+case 515:
+#line 3774 "cs-parser.jay"
+  {
+		yyVal = new This (GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 516:
+  case_516();
+  break;
+case 517:
+  case_517();
+  break;
+case 518:
+#line 3794 "cs-parser.jay"
+  {
+		yyVal = new UnaryMutator (UnaryMutator.Mode.PostIncrement, (Expression) yyVals[-1+yyTop], GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 519:
+#line 3801 "cs-parser.jay"
+  {
+		yyVal = new UnaryMutator (UnaryMutator.Mode.PostDecrement, (Expression) yyVals[-1+yyTop], GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 520:
+  case_520();
+  break;
+case 521:
+  case_521();
+  break;
+case 522:
+  case_522();
+  break;
+case 523:
+  case_523();
+  break;
+case 524:
+  case_524();
+  break;
+case 525:
+  case_525();
+  break;
+case 526:
+  case_526();
+  break;
+case 527:
+#line 3868 "cs-parser.jay"
+  {
+		++lexer.parsing_type;
+	  }
+  break;
+case 528:
+  case_528();
+  break;
+case 529:
+  case_529();
+  break;
+case 530:
+#line 3890 "cs-parser.jay"
+  {
+		yyVal = new EmptyCompletion ();
+	  }
+  break;
+case 533:
+#line 3899 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 535:
+  case_535();
+  break;
+case 536:
+  case_536();
+  break;
+case 537:
+#line 3921 "cs-parser.jay"
+  {
+		yyVal = new EmptyCompletion ();
+	  }
+  break;
+case 538:
+#line 3925 "cs-parser.jay"
+  {
+	  	yyVal = yyVals[-1+yyTop];
+	  }
+  break;
+case 539:
+  case_539();
+  break;
+case 540:
+  case_540();
+  break;
+case 541:
+  case_541();
+  break;
+case 542:
+  case_542();
+  break;
+case 546:
+  case_546();
+  break;
+case 547:
+  case_547();
+  break;
+case 548:
+  case_548();
+  break;
+case 549:
+#line 3985 "cs-parser.jay"
+  {
+		yyVal = 2;
+	  }
+  break;
+case 550:
+#line 3989 "cs-parser.jay"
+  {
+		yyVal = ((int) yyVals[-1+yyTop]) + 1;
+	  }
+  break;
+case 551:
+#line 3996 "cs-parser.jay"
+  {
+		yyVal = null;
+	  }
+  break;
+case 552:
+#line 4000 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 553:
+  case_553();
+  break;
+case 554:
+  case_554();
+  break;
+case 555:
+  case_555();
+  break;
+case 556:
+  case_556();
+  break;
+case 557:
+  case_557();
+  break;
+case 559:
+  case_559();
+  break;
+case 560:
+  case_560();
+  break;
+case 561:
+  case_561();
+  break;
+case 562:
+  case_562();
+  break;
+case 563:
+  case_563();
+  break;
+case 564:
+  case_564();
+  break;
+case 565:
+  case_565();
+  break;
+case 566:
+  case_566();
+  break;
+case 567:
+  case_567();
+  break;
+case 568:
+  case_568();
+  break;
+case 569:
+#line 4133 "cs-parser.jay"
+  {
+		start_anonymous (false, (ParametersCompiled) yyVals[0+yyTop], false, GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 570:
+  case_570();
+  break;
+case 571:
+#line 4146 "cs-parser.jay"
+  {
+		start_anonymous (false, (ParametersCompiled) yyVals[0+yyTop], true, GetLocation (yyVals[-2+yyTop]));
+	  }
+  break;
+case 572:
+  case_572();
+  break;
+case 573:
+#line 4163 "cs-parser.jay"
+  {
+		yyVal = ParametersCompiled.Undefined;
+	  }
+  break;
+case 575:
+#line 4171 "cs-parser.jay"
+  {
+	  	valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+  break;
+case 576:
+  case_576();
+  break;
+case 577:
+  case_577();
+  break;
+case 579:
+#line 4197 "cs-parser.jay"
+  {
+		yyVal = new Unary (Unary.Operator.LogicalNot, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 580:
+#line 4201 "cs-parser.jay"
+  {
+		yyVal = new Unary (Unary.Operator.OnesComplement, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 581:
+  case_581();
+  break;
+case 582:
+  case_582();
+  break;
+case 583:
+  case_583();
+  break;
+case 584:
+  case_584();
+  break;
+case 585:
+  case_585();
+  break;
+case 586:
+  case_586();
+  break;
+case 588:
+#line 4265 "cs-parser.jay"
+  { 
+	  	yyVal = new Unary (Unary.Operator.UnaryPlus, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 589:
+#line 4269 "cs-parser.jay"
+  { 
+		yyVal = new Unary (Unary.Operator.UnaryNegation, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 590:
+#line 4273 "cs-parser.jay"
+  {
+		yyVal = new UnaryMutator (UnaryMutator.Mode.PreIncrement, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 591:
+#line 4277 "cs-parser.jay"
+  {
+		yyVal = new UnaryMutator (UnaryMutator.Mode.PreDecrement, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 592:
+#line 4281 "cs-parser.jay"
+  {
+		yyVal = new Indirection ((Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 593:
+#line 4285 "cs-parser.jay"
+  {
+		yyVal = new Unary (Unary.Operator.AddressOf, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 594:
+  case_594();
+  break;
+case 595:
+  case_595();
+  break;
+case 596:
+  case_596();
+  break;
+case 597:
+  case_597();
+  break;
+case 598:
+  case_598();
+  break;
+case 599:
+  case_599();
+  break;
+case 601:
+  case_601();
+  break;
+case 602:
+  case_602();
+  break;
+case 603:
+  case_603();
+  break;
+case 604:
+  case_604();
+  break;
+case 605:
+  case_605();
+  break;
+case 606:
+  case_606();
+  break;
+case 608:
+  case_608();
+  break;
+case 609:
+  case_609();
+  break;
+case 610:
+  case_610();
+  break;
+case 611:
+  case_611();
+  break;
+case 612:
+#line 4393 "cs-parser.jay"
+  {
+		yyVal = new As ((Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 613:
+  case_613();
+  break;
+case 614:
+  case_614();
+  break;
+case 615:
+  case_615();
+  break;
+case 616:
+  case_616();
+  break;
+case 617:
+  case_617();
+  break;
+case 619:
+  case_619();
+  break;
+case 621:
+#line 4445 "cs-parser.jay"
+  {
+		yyVal = new Unary (Unary.Operator.UnaryPlus, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 622:
+#line 4449 "cs-parser.jay"
+  {
+		yyVal = new Unary (Unary.Operator.UnaryNegation, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 623:
+  case_623();
+  break;
+case 624:
+  case_624();
+  break;
+case 628:
+  case_628();
+  break;
+case 629:
+  case_629();
+  break;
+case 630:
+  case_630();
+  break;
+case 631:
+  case_631();
+  break;
+case 633:
+  case_633();
+  break;
+case 634:
+  case_634();
+  break;
+case 635:
+  case_635();
+  break;
+case 636:
+  case_636();
+  break;
+case 637:
+  case_637();
+  break;
+case 638:
+  case_638();
+  break;
+case 639:
+  case_639();
+  break;
+case 640:
+  case_640();
+  break;
+case 642:
+  case_642();
+  break;
+case 643:
+  case_643();
+  break;
+case 644:
+  case_644();
+  break;
+case 645:
+  case_645();
+  break;
+case 647:
+  case_647();
+  break;
+case 648:
+  case_648();
+  break;
+case 650:
+  case_650();
+  break;
+case 651:
+  case_651();
+  break;
+case 653:
+  case_653();
+  break;
+case 654:
+  case_654();
+  break;
+case 656:
+  case_656();
+  break;
+case 657:
+  case_657();
+  break;
+case 659:
+  case_659();
+  break;
+case 660:
+  case_660();
+  break;
+case 662:
+  case_662();
+  break;
+case 664:
+  case_664();
+  break;
+case 665:
+  case_665();
+  break;
+case 666:
+  case_666();
+  break;
+case 667:
+  case_667();
+  break;
+case 668:
+  case_668();
+  break;
+case 669:
+  case_669();
+  break;
+case 670:
+  case_670();
+  break;
+case 671:
+  case_671();
+  break;
+case 672:
+  case_672();
+  break;
+case 673:
+  case_673();
+  break;
+case 674:
+  case_674();
+  break;
+case 675:
+  case_675();
+  break;
+case 676:
+  case_676();
+  break;
+case 677:
+  case_677();
+  break;
+case 678:
+  case_678();
+  break;
+case 679:
+  case_679();
+  break;
+case 680:
+  case_680();
+  break;
+case 681:
+  case_681();
+  break;
+case 682:
+  case_682();
+  break;
+case 683:
+  case_683();
+  break;
+case 684:
+  case_684();
+  break;
+case 685:
+#line 4821 "cs-parser.jay"
+  { yyVal = ParametersCompiled.EmptyReadOnlyParameters; }
+  break;
+case 686:
+  case_686();
+  break;
+case 687:
+#line 4832 "cs-parser.jay"
+  {
+		start_block (Location.Null);
+	  }
+  break;
+case 688:
+  case_688();
+  break;
+case 690:
+  case_690();
+  break;
+case 692:
+  case_692();
+  break;
+case 693:
+  case_693();
+  break;
+case 694:
+  case_694();
+  break;
+case 695:
+  case_695();
+  break;
+case 696:
+  case_696();
+  break;
+case 697:
+  case_697();
+  break;
+case 698:
+  case_698();
+  break;
+case 699:
+#line 4899 "cs-parser.jay"
+  {
+	  	valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+  break;
+case 700:
+  case_700();
+  break;
+case 701:
+  case_701();
+  break;
+case 702:
+#line 4913 "cs-parser.jay"
+  {
+	  	valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;	  
+	  }
+  break;
+case 703:
+  case_703();
+  break;
+case 704:
+  case_704();
+  break;
+case 710:
+#line 4938 "cs-parser.jay"
+  {
+		yyVal = new ArglistAccess (GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 711:
+  case_711();
+  break;
+case 712:
+  case_712();
+  break;
+case 713:
+  case_713();
+  break;
+case 715:
+#line 4967 "cs-parser.jay"
+  {
+		yyVal = new BooleanExpression ((Expression) yyVals[0+yyTop]);
+	  }
+  break;
+case 716:
+#line 4974 "cs-parser.jay"
+  {
+	  	yyVal = null;
+	  }
+  break;
+case 718:
+  case_718();
+  break;
+case 719:
+#line 4995 "cs-parser.jay"
+  {
+	  	yyVal = null;
+	  }
+  break;
+case 720:
+#line 4999 "cs-parser.jay"
+  {
+		yyVal = null;
+	  }
+  break;
+case 721:
+#line 5003 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 722:
+#line 5007 "cs-parser.jay"
+  {
+		yyVal = yyVals[-1+yyTop];
+	  }
+  break;
+case 723:
+  case_723();
+  break;
+case 724:
+  case_724();
+  break;
+case 725:
+#line 5032 "cs-parser.jay"
+  {
+	  }
+  break;
+case 726:
+  case_726();
+  break;
+case 727:
+  case_727();
+  break;
+case 728:
+  case_728();
+  break;
+case 729:
+  case_729();
+  break;
+case 730:
+#line 5084 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 731:
+#line 5086 "cs-parser.jay"
+  { yyVal = yyVals[0+yyTop]; StoreModifierLocation (Modifiers.PARTIAL, GetLocation (yyVals[0+yyTop])); }
+  break;
+case 732:
+  case_732();
+  break;
+case 733:
+#line 5099 "cs-parser.jay"
+  {
+		lexer.parsing_modifiers = false;		
+	  }
+  break;
+case 735:
+  case_735();
+  break;
+case 736:
+  case_736();
+  break;
+case 737:
+  case_737();
+  break;
+case 738:
+  case_738();
+  break;
+case 739:
+  case_739();
+  break;
+case 740:
+  case_740();
+  break;
+case 741:
+  case_741();
+  break;
+case 742:
+  case_742();
+  break;
+case 743:
+  case_743();
+  break;
+case 744:
+  case_744();
+  break;
+case 745:
+  case_745();
+  break;
+case 746:
+  case_746();
+  break;
+case 747:
+  case_747();
+  break;
+case 748:
+  case_748();
+  break;
+case 749:
+  case_749();
+  break;
+case 750:
+  case_750();
+  break;
+case 753:
+  case_753();
+  break;
+case 754:
+  case_754();
+  break;
+case 756:
+#line 5229 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 757:
+  case_757();
+  break;
+case 758:
+  case_758();
+  break;
+case 759:
+  case_759();
+  break;
+case 760:
+  case_760();
+  break;
+case 761:
+  case_761();
+  break;
+case 762:
+  case_762();
+  break;
+case 763:
+  case_763();
+  break;
+case 764:
+  case_764();
+  break;
+case 765:
+#line 5322 "cs-parser.jay"
+  {
+		yyVal = new SpecialContraintExpr (SpecialConstraint.Class, GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 766:
+#line 5326 "cs-parser.jay"
+  {
+		yyVal = new SpecialContraintExpr (SpecialConstraint.Struct, GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 767:
+#line 5333 "cs-parser.jay"
+  {
+		yyVal = null;
+	  }
+  break;
+case 768:
+  case_768();
+  break;
+case 769:
+  case_769();
+  break;
+case 770:
+  case_770();
+  break;
+case 771:
+  case_771();
+  break;
+case 772:
+#line 5378 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 773:
+  case_773();
+  break;
+case 774:
+  case_774();
+  break;
+case 775:
+  case_775();
+  break;
+case 776:
+  case_776();
+  break;
+case 777:
+  case_777();
+  break;
+case 778:
+  case_778();
+  break;
+case 779:
+  case_779();
+  break;
+case 784:
+#line 5440 "cs-parser.jay"
+  {
+		current_block.AddStatement ((Statement) yyVals[0+yyTop]);
+	  }
+  break;
+case 785:
+#line 5444 "cs-parser.jay"
+  {
+		current_block.AddStatement ((Statement) yyVals[0+yyTop]);
+	  }
+  break;
+case 787:
+  case_787();
+  break;
+case 788:
+  case_788();
+  break;
+case 791:
+#line 5478 "cs-parser.jay"
+  {
+		current_block.AddStatement ((Statement) yyVals[0+yyTop]);
+	  }
+  break;
+case 792:
+#line 5482 "cs-parser.jay"
+  {
+		current_block.AddStatement ((Statement) yyVals[0+yyTop]);
+	  }
+  break;
+case 821:
+  case_821();
+  break;
+case 822:
+  case_822();
+  break;
+case 823:
+  case_823();
+  break;
+case 824:
+  case_824();
+  break;
+case 825:
+  case_825();
+  break;
+case 828:
+  case_828();
+  break;
+case 829:
+  case_829();
+  break;
+case 830:
+  case_830();
+  break;
+case 834:
+  case_834();
+  break;
+case 835:
+#line 5633 "cs-parser.jay"
+  {
+		yyVal = ComposedTypeSpecifier.CreatePointer (GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 837:
+#line 5641 "cs-parser.jay"
+  {
+	  	yyVal = Error_AwaitAsIdentifier (yyVals[0+yyTop]);
+	  }
+  break;
+case 838:
+  case_838();
+  break;
+case 839:
+  case_839();
+  break;
+case 840:
+  case_840();
+  break;
+case 841:
+  case_841();
+  break;
+case 843:
+  case_843();
+  break;
+case 845:
+  case_845();
+  break;
+case 846:
+  case_846();
+  break;
+case 850:
+  case_850();
+  break;
+case 853:
+  case_853();
+  break;
+case 854:
+  case_854();
+  break;
+case 855:
+#line 5755 "cs-parser.jay"
+  {
+		report.Error (145, lexer.Location, "A const field requires a value to be provided");
+	  }
+  break;
+case 856:
+  case_856();
+  break;
+case 861:
+  case_861();
+  break;
+case 863:
+  case_863();
+  break;
+case 864:
+  case_864();
+  break;
+case 865:
+  case_865();
+  break;
+case 866:
+#line 5805 "cs-parser.jay"
+  { yyVal = yyVals[-1+yyTop]; }
+  break;
+case 867:
+  case_867();
+  break;
+case 868:
+#line 5815 "cs-parser.jay"
+  { yyVal = yyVals[-1+yyTop]; }
+  break;
+case 869:
+#line 5816 "cs-parser.jay"
+  { yyVal = yyVals[-1+yyTop]; }
+  break;
+case 870:
+  case_870();
+  break;
+case 871:
+  case_871();
+  break;
+case 872:
+  case_872();
+  break;
+case 875:
+  case_875();
+  break;
+case 876:
+  case_876();
+  break;
+case 877:
+  case_877();
+  break;
+case 878:
+#line 5888 "cs-parser.jay"
+  {
+		start_block (GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 879:
+  case_879();
+  break;
+case 880:
+  case_880();
+  break;
+case 881:
+#line 5908 "cs-parser.jay"
+  {
+		report.Warning (1522, 1, current_block.StartLocation, "Empty switch block"); 
+	  }
+  break;
+case 885:
+#line 5918 "cs-parser.jay"
+  {
+		Error_SyntaxError (yyToken);
+	  }
+  break;
+case 887:
+  case_887();
+  break;
+case 888:
+#line 5935 "cs-parser.jay"
+  {
+		current_block.AddStatement ((Statement) yyVals[0+yyTop]);
+	  }
+  break;
+case 889:
+  case_889();
+  break;
+case 890:
+  case_890();
+  break;
+case 891:
+#line 5952 "cs-parser.jay"
+  {
+		yyVal = new SwitchLabel (null, GetLocation (yyVals[0+yyTop]));
+	  }
+  break;
+case 896:
+  case_896();
+  break;
+case 897:
+  case_897();
+  break;
+case 898:
+  case_898();
+  break;
+case 899:
+  case_899();
+  break;
+case 900:
+  case_900();
+  break;
+case 901:
+  case_901();
+  break;
+case 902:
+#line 6013 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 903:
+  case_903();
+  break;
+case 904:
+#line 6028 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 905:
+  case_905();
+  break;
+case 906:
+  case_906();
+  break;
+case 907:
+#line 6049 "cs-parser.jay"
+  {
+		yyVal = yyVals[0+yyTop];
+	  }
+  break;
+case 908:
+  case_908();
+  break;
+case 909:
+  case_909();
+  break;
+case 910:
+  case_910();
+  break;
+case 911:
+#line 6083 "cs-parser.jay"
+  { yyVal = new EmptyStatement (lexer.Location); }
+  break;
+case 913:
+  case_913();
+  break;
+case 914:
+  case_914();
+  break;
+case 916:
+#line 6107 "cs-parser.jay"
+  { yyVal = null; }
+  break;
+case 918:
+#line 6112 "cs-parser.jay"
+  { yyVal = new EmptyStatement (lexer.Location); }
+  break;
+case 922:
+  case_922();
+  break;
+case 923:
+  case_923();
+  break;
+case 924:
+  case_924();
+  break;
+case 925:
+  case_925();
+  break;
+case 926:
+  case_926();
+  break;
+case 927:
+  case_927();
+  break;
+case 928:
+  case_928();
+  break;
+case 935:
+  case_935();
+  break;
+case 936:
+  case_936();
+  break;
+case 937:
+  case_937();
+  break;
+case 938:
+  case_938();
+  break;
+case 939:
+  case_939();
+  break;
+case 940:
+  case_940();
+  break;
+case 941:
+  case_941();
+  break;
+case 942:
+  case_942();
+  break;
+case 943:
+  case_943();
+  break;
+case 944:
+  case_944();
+  break;
+case 945:
+  case_945();
+  break;
+case 946:
+  case_946();
+  break;
+case 947:
+  case_947();
+  break;
+case 948:
+  case_948();
+  break;
+case 949:
+  case_949();
+  break;
+case 952:
+#line 6358 "cs-parser.jay"
+  {
+		yyVal = new TryCatch ((Block) yyVals[-1+yyTop], (List<Catch>) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]), false);
+	  }
+  break;
+case 953:
+  case_953();
+  break;
+case 954:
+  case_954();
+  break;
+case 955:
+  case_955();
+  break;
+case 956:
+  case_956();
+  break;
+case 957:
+  case_957();
+  break;
+case 960:
+  case_960();
+  break;
+case 961:
+  case_961();
+  break;
+case 962:
+  case_962();
+  break;
+case 963:
+  case_963();
+  break;
+case 964:
+  case_964();
+  break;
+case 966:
+  case_966();
+  break;
+case 967:
+#line 6483 "cs-parser.jay"
+  {
+		yyVal = new Checked ((Block) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 968:
+#line 6490 "cs-parser.jay"
+  {
+		yyVal = new Unchecked ((Block) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+  break;
+case 969:
+  case_969();
+  break;
+case 970:
+#line 6500 "cs-parser.jay"
+  {
+		yyVal = new Unsafe ((Block) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+  break;
+case 971:
+  case_971();
+  break;
+case 972:
+  case_972();
+  break;
+case 973:
+  case_973();
+  break;
+case 974:
+  case_974();
+  break;
+case 975:
+  case_975();
+  break;
+case 976:
+  case_976();
+  break;
+case 977:
+  case_977();
+  break;
+case 978:
+  case_978();
+  break;
+case 979:
+  case_979();
+  break;
+case 980:
+  case_980();
+  break;
+case 982:
+  case_982();
+  break;
+case 983:
+#line 6605 "cs-parser.jay"
+  {
+		Error_MissingInitializer (lexer.Location);
+	  }
+  break;
+case 984:
+  case_984();
+  break;
+case 985:
+  case_985();
+  break;
+case 986:
+  case_986();
+  break;
+case 987:
+  case_987();
+  break;
+case 988:
+  case_988();
+  break;
+case 989:
+  case_989();
+  break;
+case 990:
+  case_990();
+  break;
+case 991:
+  case_991();
+  break;
+case 992:
+  case_992();
+  break;
+case 993:
+#line 6710 "cs-parser.jay"
+  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+  break;
+case 994:
+  case_994();
+  break;
+case 995:
+#line 6725 "cs-parser.jay"
+  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+  break;
+case 996:
+  case_996();
+  break;
+case 997:
+  case_997();
+  break;
+case 998:
+  case_998();
+  break;
+case 1000:
+  case_1000();
+  break;
+case 1001:
+  case_1001();
+  break;
+case 1002:
+#line 6789 "cs-parser.jay"
+  {
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+  break;
+case 1003:
+  case_1003();
+  break;
+case 1004:
+  case_1004();
+  break;
+case 1005:
+  case_1005();
+  break;
+case 1006:
+  case_1006();
+  break;
+case 1007:
+#line 6828 "cs-parser.jay"
+  {
+	  	yyVal = new object[] { yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]) };
+	  }
+  break;
+case 1008:
+  case_1008();
+  break;
+case 1010:
+  case_1010();
+  break;
+case 1016:
+#line 6857 "cs-parser.jay"
+  {
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+  break;
+case 1017:
+  case_1017();
+  break;
+case 1018:
+#line 6876 "cs-parser.jay"
+  {
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+  break;
+case 1019:
+  case_1019();
+  break;
+case 1020:
+  case_1020();
+  break;
+case 1021:
+  case_1021();
+  break;
+case 1022:
+  case_1022();
+  break;
+case 1023:
+  case_1023();
+  break;
+case 1024:
+  case_1024();
+  break;
+case 1025:
+  case_1025();
+  break;
+case 1026:
+  case_1026();
+  break;
+case 1027:
+  case_1027();
+  break;
+case 1029:
+  case_1029();
+  break;
+case 1030:
+  case_1030();
+  break;
+case 1031:
+  case_1031();
+  break;
+case 1033:
+  case_1033();
+  break;
+case 1034:
+  case_1034();
+  break;
+case 1036:
+  case_1036();
+  break;
+case 1037:
+  case_1037();
+  break;
+case 1038:
+#line 7077 "cs-parser.jay"
+  {
+		yyVal = new Linq.OrderByAscending ((Linq.QueryBlock) current_block, (Expression)yyVals[0+yyTop]);	
+	  }
+  break;
+case 1039:
+  case_1039();
+  break;
+case 1040:
+  case_1040();
+  break;
+case 1041:
+#line 7094 "cs-parser.jay"
+  {
+		yyVal = new Linq.ThenByAscending ((Linq.QueryBlock) current_block, (Expression)yyVals[0+yyTop]);	
+	  }
+  break;
+case 1042:
+  case_1042();
+  break;
+case 1043:
+  case_1043();
+  break;
+case 1045:
+  case_1045();
+  break;
+case 1046:
+  case_1046();
+  break;
+case 1049:
+  case_1049();
+  break;
+case 1050:
+  case_1050();
+  break;
+case 1058:
+#line 7219 "cs-parser.jay"
+  {
+		module.DocumentationBuilder.ParsedName = (MemberName) yyVals[0+yyTop];
+	  }
+  break;
+case 1059:
+#line 7226 "cs-parser.jay"
+  {
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)yyVals[0+yyTop];
+	  }
+  break;
+case 1060:
+  case_1060();
+  break;
+case 1061:
+  case_1061();
+  break;
+case 1062:
+  case_1062();
+  break;
+case 1063:
+#line 7249 "cs-parser.jay"
+  {
+		yyVal = new MemberName ((MemberName) yyVals[-2+yyTop], MemberCache.IndexerNameAlias, Location.Null);
+	  }
+  break;
+case 1064:
+#line 7253 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+  break;
+case 1065:
+  case_1065();
+  break;
+case 1066:
+  case_1066();
+  break;
+case 1067:
+  case_1067();
+  break;
+case 1068:
+  case_1068();
+  break;
+case 1070:
+#line 7289 "cs-parser.jay"
+  {
+		yyVal = new MemberName (((MemberName) yyVals[-2+yyTop]), (MemberName) yyVals[0+yyTop]);
+	  }
+  break;
+case 1072:
+#line 7297 "cs-parser.jay"
+  {
+		valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+  break;
+case 1073:
+#line 7301 "cs-parser.jay"
+  {
+		yyVal = yyVals[-1+yyTop];
+	  }
+  break;
+case 1074:
+#line 7308 "cs-parser.jay"
+  {
+		yyVal = new List<DocumentationParameter> (0);
+	  }
+  break;
+case 1076:
+  case_1076();
+  break;
+case 1077:
+  case_1077();
+  break;
+case 1078:
+  case_1078();
+  break;
+#line default
+        }
+        yyTop -= yyLen[yyN];
+        yyState = yyStates[yyTop];
+        int yyM = yyLhs[yyN];
+        if (yyState == 0 && yyM == 0) {
+//t          if (debug != null) debug.shift(0, yyFinal);
+          yyState = yyFinal;
+          if (yyToken < 0) {
+            yyToken = yyLex.advance() ? yyLex.token() : 0;
+//t            if (debug != null)
+//t               debug.lex(yyState, yyToken,yyname(yyToken), yyLex.value());
+          }
+          if (yyToken == 0) {
+//t            if (debug != null) debug.accept(yyVal);
+            return yyVal;
+          }
+          goto continue_yyLoop;
+        }
+        if (((yyN = yyGindex[yyM]) != 0) && ((yyN += yyState) >= 0)
+            && (yyN < yyTable.Length) && (yyCheck[yyN] == yyState))
+          yyState = yyTable[yyN];
+        else
+          yyState = yyDgoto[yyM];
+//t        if (debug != null) debug.shift(yyStates[yyTop], yyState);
+	 goto continue_yyLoop;
+      continue_yyDiscarded: ;	// implements the named-loop continue: 'continue yyDiscarded'
+      }
+    continue_yyLoop: ;		// implements the named-loop continue: 'continue yyLoop'
+    }
+  }
+
+/*
+ All more than 3 lines long rules are wrapped into a method
+*/
+void case_6()
+#line 397 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null) {
+			Attributes attrs = (Attributes) yyVals[0+yyTop];
+			report.Error (1730, attrs.Attrs [0].Location,
+				"Assembly and module attributes must precede all other elements except using clauses and extern alias declarations");
+
+			current_namespace.UnattachedAttributes = attrs;
+		}
+	  }
+
+void case_8()
+#line 411 "cs-parser.jay"
+{
+		if (yyToken == Token.EXTERN_ALIAS)
+			report.Error (439, lexer.Location, "An extern alias declaration must precede all other elements");
+		else
+			Error_SyntaxError (yyToken);
+	  }
+
+void case_13()
+#line 431 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		string s = lt.Value;
+		if (s != "alias") {
+			syntax_error (lt.Location, "`alias' expected");
+		} else {
+			if (lang_version == LanguageVersion.ISO_1)
+				FeatureIsNotAvailable (lt.Location, "external alias");
+
+			lt = (LocatedToken) yyVals[-1+yyTop];
+			if (lt.Value == QualifiedAliasMember.GlobalAlias) {
+				RootNamespace.Error_GlobalNamespaceRedefined (report, lt.Location);
+			}
+			
+			var na = new UsingExternAlias (new SimpleMemberName (lt.Value, lt.Location), GetLocation (yyVals[-3+yyTop]));
+			current_namespace.AddUsing (na);
+			
+			lbag.AddLocation (na, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+	  }
+
+void case_17()
+#line 464 "cs-parser.jay"
+{
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_18()
+#line 472 "cs-parser.jay"
+{
+		var un = new UsingNamespace ((ATypeNameExpression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		current_namespace.AddUsing (un);
+		
+		lbag.AddLocation (un, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_19()
+#line 479 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		if (lang_version != LanguageVersion.ISO_1 && lt.Value == "global") {
+			report.Warning (440, 2, lt.Location,
+			 "An alias named `global' will not be used when resolving `global::'. The global namespace will be used instead");
+		}
+
+		var un = new UsingAliasNamespace (new SimpleMemberName (lt.Value, lt.Location), (ATypeNameExpression) yyVals[-1+yyTop], GetLocation (yyVals[-4+yyTop]));
+		current_namespace.AddUsing (un);
+		lbag.AddLocation (un, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_20()
+#line 491 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	 }
+
+void case_21()
+#line 504 "cs-parser.jay"
+{
+		Attributes attrs = (Attributes) yyVals[-2+yyTop];
+		var name = (MemberName) yyVals[0+yyTop];
+		if (attrs != null) {
+			bool valid_global_attrs = true;
+			if ((current_namespace.DeclarationFound || current_namespace != file)) {
+				valid_global_attrs = false;
+			} else {
+				foreach (var a in attrs.Attrs) {
+					if (a.ExplicitTarget == "assembly" || a.ExplicitTarget == "module")
+						continue;
+						
+					valid_global_attrs = false;
+					break;
+				}
+			}
+			
+			if (!valid_global_attrs)
+				report.Error (1671, name.Location, "A namespace declaration cannot have modifiers or attributes");
+		}
+	
+		module.AddAttributes (attrs, current_namespace);
+		
+		var ns = new NamespaceContainer (name, current_namespace);
+		current_namespace.AddTypeContainer (ns);
+		current_container = current_namespace = ns;
+	  }
+
+void case_22()
+#line 532 "cs-parser.jay"
+{
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_23()
+#line 537 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null)
+			lbag.AddLocation (current_container, GetLocation (yyVals[-9+yyTop]), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+		else
+			lbag.AddLocation (current_container, GetLocation (yyVals[-9+yyTop]), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  
+		current_container = current_namespace = current_namespace.Parent;
+	  }
+
+void case_24()
+#line 546 "cs-parser.jay"
+{
+		report.Error (1514, lexer.Location, "Unexpected symbol `{0}', expecting `.' or `{{'", GetSymbolName (yyToken));
+
+		var name = (MemberName) yyVals[0+yyTop];		
+		var ns = new NamespaceContainer (name, current_namespace);
+		lbag.AddLocation (ns, GetLocation (yyVals[-1+yyTop]));
+		current_namespace.AddTypeContainer (ns);
+	  }
+
+void case_27()
+#line 560 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  	yyVal = null;
+	  }
+
+void case_28()
+#line 568 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		yyVal = new MemberName (lt.Value, lt.Location);
+	  }
+
+void case_29()
+#line 573 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		yyVal = new MemberName ((MemberName) yyVals[-2+yyTop], lt.Value, lt.Location);		
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_30()
+#line 579 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new MemberName ("<invalid>", lexer.Location);
+	  }
+
+void case_43()
+#line 617 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null) {
+			TypeContainer ds = (TypeContainer)yyVals[0+yyTop];
+
+			if ((ds.ModFlags & (Modifiers.PRIVATE | Modifiers.PROTECTED)) != 0){
+				report.Error (1527, ds.Location, 
+				"Namespace elements cannot be explicitly declared as private, protected or protected internal");
+			}
+
+			/* Here is a trick, for explicit attributes we don't know where they belong to until*/
+			/* we parse succeeding declaration hence we parse them as normal and re-attach them*/
+			/* when we know whether they are global (assembly:, module:) or local (type:).*/
+			if (ds.OptAttributes != null) {
+				ds.OptAttributes.ConvertGlobalAttributes (ds, current_namespace, !current_namespace.DeclarationFound && current_namespace == file);
+			}
+		}
+		current_namespace.DeclarationFound = true;
+	  }
+
+void case_45()
+#line 639 "cs-parser.jay"
+{
+		current_namespace.UnattachedAttributes = (Attributes) yyVals[-1+yyTop];
+		report.Error (1518, lexer.Location, "Attributes must be attached to class, delegate, enum, interface or struct");
+		lexer.putback ('}');
+	  }
+
+void case_53()
+#line 672 "cs-parser.jay"
+{
+		var sect = (List<Attribute>) yyVals[0+yyTop];
+		yyVal = new Attributes (sect);
+	  }
+
+void case_54()
+#line 677 "cs-parser.jay"
+{
+		Attributes attrs = yyVals[-1+yyTop] as Attributes;
+		var sect = (List<Attribute>) yyVals[0+yyTop];
+		if (attrs == null)
+			attrs = new Attributes (sect);
+		else if (sect != null)
+			attrs.AddAttributes (sect);
+		yyVal = attrs;
+	  }
+
+void case_55()
+#line 690 "cs-parser.jay"
+{
+	  	PushLocation (GetLocation (yyVals[0+yyTop]));
+		lexer.parsing_attribute_section = true;
+	  }
+
+void case_56()
+#line 695 "cs-parser.jay"
+{
+		lexer.parsing_attribute_section = false;
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_57()
+#line 703 "cs-parser.jay"
+{
+		current_attr_target = (string) yyVals[-1+yyTop];
+		if (current_attr_target == "assembly" || current_attr_target == "module") {
+			Lexer.check_incorrect_doc_comment ();
+		}
+	  }
+
+void case_58()
+#line 710 "cs-parser.jay"
+{
+		/* when attribute target is invalid*/
+		if (current_attr_target == string.Empty)
+			yyVal = new List<Attribute> (0);
+		else
+			yyVal = yyVals[-2+yyTop];
+		lbag.InsertLocation (yyVal, 0, GetLocation (yyVals[-4+yyTop]));
+		lbag.InsertLocation (yyVal, 0, PopLocation ());
+		lbag.InsertLocation (yyVal, 0, PopLocation ());
+		if (yyVals[-1+yyTop] != null) {
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+		} else {
+			lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+		}
+
+		current_attr_target = null;
+		lexer.parsing_attribute_section = false;
+ 	  }
+
+void case_59()
+#line 729 "cs-parser.jay"
+{
+		yyVal = yyVals[-2+yyTop];
+		lbag.InsertLocation (yyVal, 0, PopLocation ());
+		if (yyVals[-1+yyTop] != null) {
+			lbag.AddLocation (yyVal, GetLocation(yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+		} else {
+			lbag.AddLocation (yyVal, GetLocation(yyVals[0+yyTop]));
+		}
+	  }
+
+void case_60()
+#line 739 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		var tne = new SimpleName (lt.Value, null, lt.Location);
+
+		yyVal = new List<Attribute> () {
+			new Attribute (null, tne, null, GetLocation (yyVals[-1+yyTop]), false)
+		};
+	  }
+
+void case_61()
+#line 750 "cs-parser.jay"
+{
+ 		CheckAttributeTarget (yyToken, GetTokenName (yyToken), GetLocation (yyVals[0+yyTop])); 
+ 		yyVal = null;
+	  }
+
+void case_62()
+#line 758 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		yyVal = CheckAttributeTarget (yyToken, lt.Value, lt.Location);
+		PushLocation (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_66()
+#line 773 "cs-parser.jay"
+{
+		var attrs = (List<Attribute>) yyVals[-2+yyTop];
+		if (attrs != null) {
+			attrs.Add ((Attribute) yyVals[0+yyTop]);
+	  		lbag.AddLocation (attrs, GetLocation (yyVals[-1+yyTop]));
+	  	}
+
+		yyVal = attrs;
+	  }
+
+void case_68()
+#line 790 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		
+		var tne = (ATypeNameExpression) yyVals[-2+yyTop];
+		if (tne.HasTypeArguments) {
+			report.Error (404, tne.Location, "Attributes cannot be generic");
+		}
+		Arguments [] arguments = (Arguments []) yyVals[0+yyTop];
+
+		yyVal = new Attribute (current_attr_target, tne, (Arguments[]) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]), lexer.IsEscapedIdentifier (tne));
+		if (arguments != null) {
+			attributeArgumentCommas.Insert (0, savedAttrParenOpenLocation);
+			attributeArgumentCommas.Add (savedAttrParenCloseLocation);
+			lbag.AddLocation (yyVal, attributeArgumentCommas);
+			attributeArgumentCommas.Clear ();
+		} else if (HadAttributeParens) {
+			lbag.AddLocation (yyVal, savedAttrParenOpenLocation, savedAttrParenCloseLocation);
+		}
+	  }
+
+void case_71()
+#line 818 "cs-parser.jay"
+{
+		savedAttrParenOpenLocation = GetLocation (yyVals[-2+yyTop]);
+		savedAttrParenCloseLocation = GetLocation (yyVals[0+yyTop]);
+		yyVal = yyVals[-1+yyTop];
+		HadAttributeParens = true;
+	  }
+
+void case_73()
+#line 830 "cs-parser.jay"
+{
+	  	Arguments a = new Arguments (4);
+		a.Add ((Argument) yyVals[0+yyTop]);
+		yyVal = new Arguments [] { a, null };
+	  }
+
+void case_74()
+#line 836 "cs-parser.jay"
+{
+	  	Arguments a = new Arguments (4);
+		a.Add ((Argument) yyVals[0+yyTop]);  
+		yyVal = new Arguments [] { null, a };
+	  }
+
+void case_75()
+#line 842 "cs-parser.jay"
+{
+		Arguments[] o = (Arguments[]) yyVals[-2+yyTop];
+		if (o [1] != null) {
+			report.Error (1016, ((Argument) yyVals[0+yyTop]).Expr.Location, "Named attribute arguments must appear after the positional arguments");
+			o [0] = new Arguments (4);
+		}
+		
+		Arguments args = ((Arguments) o [0]);
+		if (args.Count > 0 && !(yyVals[0+yyTop] is NamedArgument) && args [args.Count - 1] is NamedArgument)
+			Error_NamedArgumentExpected ((NamedArgument) args [args.Count - 1]);
+		
+		args.Add ((Argument) yyVals[0+yyTop]);
+		attributeArgumentCommas.Add (GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_76()
+#line 857 "cs-parser.jay"
+{
+		Arguments[] o = (Arguments[]) yyVals[-2+yyTop];
+		if (o [1] == null) {
+			o [1] = new Arguments (4);
+		}
+
+		((Arguments) o [1]).Add ((Argument) yyVals[0+yyTop]);
+		attributeArgumentCommas.Add (GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_79()
+#line 875 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	  }
+
+void case_81()
+#line 887 "cs-parser.jay"
+{
+	  	--lexer.parsing_block;
+	  	var lt = (LocatedToken) yyVals[-3+yyTop];
+		yyVal = new NamedArgument (lt.Value, lt.Location, (Expression) yyVals[0+yyTop]);	  
+		lbag.AddLocation (yyVal, GetLocation(yyVals[-2+yyTop]));
+	  }
+
+void case_82()
+#line 897 "cs-parser.jay"
+{
+		if (lang_version <= LanguageVersion.V_3)
+			FeatureIsNotAvailable (GetLocation (yyVals[-3+yyTop]), "named argument");
+			
+		/* Avoid boxing in common case (no modifier)*/
+		var arg_mod = yyVals[-1+yyTop] == null ? Argument.AType.None : (Argument.AType) yyVals[-1+yyTop];
+			
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		yyVal = new NamedArgument (lt.Value, lt.Location, (Expression) yyVals[0+yyTop], arg_mod);
+		lbag.AddLocation (yyVal, GetLocation(yyVals[-2+yyTop]));
+	  }
+
+void case_88()
+#line 929 "cs-parser.jay"
+{
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+
+void case_89()
+#line 934 "cs-parser.jay"
+{
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+
+void case_103()
+#line 955 "cs-parser.jay"
+{
+		report.Error (1519, lexer.Location, "Unexpected symbol `{0}' in class, struct, or interface member declaration",
+			GetSymbolName (yyToken));
+		yyVal = null;
+		lexer.parsing_generic_declaration = false;
+	  }
+
+void case_104()
+#line 965 "cs-parser.jay"
+{
+		current_local_parameters = current_type.PrimaryConstructorParameters;
+		if (current_local_parameters == null) {
+			report.Error (9010, GetLocation (yyVals[0+yyTop]), "Primary constructor body is not allowed");
+			current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		}
+
+		++lexer.parsing_block;
+		start_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_105()
+#line 976 "cs-parser.jay"
+{
+		current_local_parameters = null;
+		var t = current_type as ClassOrStruct;
+		if (t != null) {
+			var b = (ToplevelBlock) yyVals[0+yyTop];
+			if (t.PrimaryConstructorBlock != null) {
+				report.Error (8041, b.StartLocation, "Primary constructor already has a body");
+			} else {
+				t.PrimaryConstructorBlock = b;
+			}
+		}
+	  }
+
+void case_107()
+#line 998 "cs-parser.jay"
+{ 
+		lexer.ConstraintsParsing = true;
+		valid_param_mod = ParameterModifierType.PrimaryConstructor;
+		push_current_container (new Struct (current_container, (MemberName) yyVals[0+yyTop], (Modifiers) yyVals[-4+yyTop], (Attributes) yyVals[-5+yyTop]), yyVals[-3+yyTop]);
+		lbag.AddMember (current_container, GetModifierLocations (), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_108()
+#line 1007 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+		lexer.ConstraintsParsing = false;
+
+		if (yyVals[-2+yyTop] != null)
+			current_type.PrimaryConstructorParameters = (ParametersCompiled) yyVals[-2+yyTop];
+
+		if (yyVals[0+yyTop] != null)
+			current_container.SetConstraints ((List<Constraints>) yyVals[0+yyTop]);
+
+		if (doc_support)
+			current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
+
+		
+		lexer.parsing_modifiers = true;
+	  }
+
+void case_109()
+#line 1024 "cs-parser.jay"
+{
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_110()
+#line 1029 "cs-parser.jay"
+{
+		--lexer.parsing_declaration;
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_111()
+#line 1035 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] == null) {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		} else {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+		yyVal = pop_current_class ();
+	  }
+
+void case_113()
+#line 1053 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		var mod = (Modifiers) yyVals[-3+yyTop];
+		current_field = new Const (current_type, (FullNamedExpression) yyVals[-1+yyTop], mod, new MemberName (lt.Value, lt.Location), (Attributes) yyVals[-4+yyTop]);
+		current_type.AddMember (current_field);
+		
+		if ((mod & Modifiers.STATIC) != 0) {
+			report.Error (504, current_field.Location, "The constant `{0}' cannot be marked static", current_field.GetSignatureForError ());
+		}
+		
+		yyVal = current_field;
+	  }
+
+void case_114()
+#line 1066 "cs-parser.jay"
+{
+		if (doc_support) {
+			current_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		current_field.Initializer = (ConstInitializer) yyVals[-2+yyTop];
+		lbag.AddMember (current_field, GetModifierLocations (), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[0+yyTop]));
+		current_field = null;
+	  }
+
+void case_115()
+#line 1079 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		current_type.AddMember (new Const (current_type, (FullNamedExpression) yyVals[-1+yyTop], (Modifiers) yyVals[-3+yyTop], MemberName.Null, (Attributes) yyVals[-4+yyTop]));
+	  }
+
+void case_120()
+#line 1104 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+	  	yyVal = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (ConstInitializer) yyVals[0+yyTop]);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_122()
+#line 1117 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		yyVal = new ConstInitializer (current_field, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_123()
+#line 1123 "cs-parser.jay"
+{
+		report.Error (145, lexer.Location, "A const field requires a value to be provided");
+		yyVal = null;
+	  }
+
+void case_126()
+#line 1138 "cs-parser.jay"
+{
+	  	lexer.parsing_generic_declaration = false;
+
+		FullNamedExpression type = (FullNamedExpression) yyVals[-1+yyTop];
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (670, GetLocation (yyVals[-1+yyTop]), "Fields cannot have void type");
+			
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		current_field = new Field (current_type, type, (Modifiers) yyVals[-2+yyTop], new MemberName (lt.Value, lt.Location), (Attributes) yyVals[-3+yyTop]);
+		current_type.AddField (current_field);
+		yyVal = current_field;
+	  }
+
+void case_127()
+#line 1153 "cs-parser.jay"
+{ 
+		if (doc_support) {
+			current_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+			
+		lbag.AddMember (current_field, GetModifierLocations (), GetLocation (yyVals[0+yyTop]));
+		yyVal = current_field;
+		current_field = null;
+	  }
+
+void case_128()
+#line 1166 "cs-parser.jay"
+{ 
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "fixed size buffers");
+
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		current_field = new FixedField (current_type, (FullNamedExpression) yyVals[-1+yyTop], (Modifiers) yyVals[-3+yyTop],
+			new MemberName (lt.Value, lt.Location), (Attributes) yyVals[-4+yyTop]);
+			
+		current_type.AddField (current_field);
+	  }
+
+void case_129()
+#line 1177 "cs-parser.jay"
+{
+		if (doc_support) {
+			current_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+	    }
+
+		current_field.Initializer = (ConstInitializer) yyVals[-2+yyTop];	    
+		lbag.AddMember (current_field, GetModifierLocations (), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[0+yyTop]));
+		yyVal = current_field;
+	    current_field = null;
+	  }
+
+void case_132()
+#line 1200 "cs-parser.jay"
+{
+	  	++lexer.parsing_block;
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  	start_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_133()
+#line 1206 "cs-parser.jay"
+{
+	  	--lexer.parsing_block;
+		current_field.Initializer = (Expression) yyVals[0+yyTop];
+		lbag.AppendToMember (current_field, GetLocation (yyVals[-2+yyTop]));
+		end_block (lexer.Location);
+		current_local_parameters = null;
+	  }
+
+void case_138()
+#line 1233 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+	  	yyVal = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), null);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_140()
+#line 1243 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		var lt = (LocatedToken) yyVals[-3+yyTop];	  
+	  	yyVal = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (Expression) yyVals[0+yyTop]);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_145()
+#line 1269 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];	  
+		yyVal = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (ConstInitializer) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_147()
+#line 1282 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		yyVal = new ConstInitializer (current_field, (Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_148()
+#line 1288 "cs-parser.jay"
+{
+		report.Error (443, lexer.Location, "Value or constant expected");
+		yyVal = null;
+	  }
+
+void case_151()
+#line 1298 "cs-parser.jay"
+{
+		/* It has to be here for the parent to safely restore artificial block*/
+	  	Error_SyntaxError (yyToken);
+	  	yyVal = null;
+	  }
+
+void case_152()
+#line 1307 "cs-parser.jay"
+{
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+
+		/* Was added earlier in the case of body being eof for full ast*/
+	  }
+
+void case_153()
+#line 1314 "cs-parser.jay"
+{
+		Method method = (Method) yyVals[-2+yyTop];
+		method.Block = (ToplevelBlock) yyVals[0+yyTop];
+		async_block = false;
+		
+		if (method.Block == null) {
+			lbag.AppendToMember (method, savedLocation); /* semicolon*/
+			method.ParameterInfo.CheckParameters (method);
+
+			if ((method.ModFlags & Modifiers.ASYNC) != 0) {
+				report.Error (1994, method.Location, "`{0}': The async modifier can only be used with methods that have a body",
+					method.GetSignatureForError ());
+			}
+		} else {
+			if (current_container.Kind == MemberKind.Interface) {
+				report.Error (531, method.Location, "`{0}': interface members cannot have a definition",
+					method.GetSignatureForError ());
+			}
+		}
+
+		current_local_parameters = null;
+
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_155()
+#line 1350 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+		MemberName name = (MemberName) yyVals[-4+yyTop];
+		current_local_parameters = (ParametersCompiled) yyVals[-1+yyTop];
+
+		var method = Method.Create (current_type, (FullNamedExpression) yyVals[-5+yyTop], (Modifiers) yyVals[-6+yyTop],
+				     name, current_local_parameters, (Attributes) yyVals[-7+yyTop]);
+
+		current_type.AddMember (method);
+
+		async_block = (method.ModFlags & Modifiers.ASYNC) != 0;
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		lbag.AddMember (method, GetModifierLocations (), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+		yyVal = method;
+
+		lexer.ConstraintsParsing = true;
+	  }
+
+void case_156()
+#line 1371 "cs-parser.jay"
+{
+		lexer.ConstraintsParsing = false;
+
+		if (yyVals[0+yyTop] != null) {
+			var method = (Method) yyVals[-1+yyTop];
+			method.SetConstraints ((List<Constraints>) yyVals[0+yyTop]);
+		}
+
+		yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_158()
+#line 1390 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;
+	  	valid_param_mod = ParameterModifierType.All;
+	  }
+
+void case_160()
+#line 1399 "cs-parser.jay"
+{
+		lexer.ConstraintsParsing = false;
+		valid_param_mod = 0;
+
+		MemberName name = (MemberName) yyVals[-6+yyTop];
+		current_local_parameters = (ParametersCompiled) yyVals[-3+yyTop];
+
+		var modifiers = (Modifiers) yyVals[-10+yyTop];
+		modifiers |= Modifiers.PARTIAL;
+
+		var method = Method.Create (current_type, new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[-8+yyTop])),
+				     modifiers, name, current_local_parameters, (Attributes) yyVals[-11+yyTop]);
+
+		current_type.AddMember (method);
+
+		async_block = (method.ModFlags & Modifiers.ASYNC) != 0;
+
+		if (yyVals[0+yyTop] != null)
+			method.SetConstraints ((List<Constraints>) yyVals[0+yyTop]);
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		StoreModifierLocation (Modifiers.PARTIAL, GetLocation (yyVals[-9+yyTop]));
+		lbag.AddMember (method, GetModifierLocations (), GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		yyVal = method;
+	  }
+
+void case_161()
+#line 1430 "cs-parser.jay"
+{
+		MemberName name = (MemberName) yyVals[-3+yyTop];
+		report.Error (1585, name.Location, 
+			"Member modifier `{0}' must precede the member type and name", ModifiersExtensions.Name ((Modifiers) yyVals[-4+yyTop]));
+
+		var method = Method.Create (current_type, (FullNamedExpression) yyVals[-5+yyTop],
+					    0, name, (ParametersCompiled) yyVals[-1+yyTop], (Attributes) yyVals[-7+yyTop]);
+
+		current_type.AddMember (method);
+
+		current_local_parameters = (ParametersCompiled) yyVals[-1+yyTop];
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		yyVal = method;
+	  }
+
+void case_162()
+#line 1451 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		current_local_parameters = ParametersCompiled.Undefined;
+
+		MemberName name = (MemberName) yyVals[-1+yyTop];
+		var method = Method.Create (current_type, (FullNamedExpression) yyVals[-2+yyTop], (Modifiers) yyVals[-3+yyTop],
+									name, current_local_parameters, (Attributes) yyVals[-4+yyTop]);
+
+		current_type.AddMember (method);
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		yyVal = method;
+	  }
+
+void case_167()
+#line 1480 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.V_6) {
+			FeatureIsNotAvailable (GetLocation (yyVals[0+yyTop]), "expression bodied members");
+		}
+
+		++lexer.parsing_block;
+		start_block (GetLocation (yyVals[0+yyTop]));
+	 }
+
+void case_168()
+#line 1489 "cs-parser.jay"
+{
+		lexer.parsing_block = 0;
+		current_block.AddStatement (new ContextualReturn ((Expression) yyVals[-1+yyTop]));
+		var b = end_block (GetLocation (yyVals[0+yyTop]));
+		b.IsCompilerGenerated = true;
+		yyVal = b;
+	 }
+
+void case_171()
+#line 1505 "cs-parser.jay"
+{
+		var pars_list = (List<Parameter>) yyVals[0+yyTop];
+	  	yyVal = new ParametersCompiled (pars_list.ToArray ());
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_172()
+#line 1511 "cs-parser.jay"
+{
+		var pars_list = (List<Parameter>) yyVals[-2+yyTop];
+		pars_list.Add ((Parameter) yyVals[0+yyTop]);
+		parameterListCommas.Add (GetLocation (yyVals[-1+yyTop]));
+		
+		yyVal = new ParametersCompiled (pars_list.ToArray ()); 
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_173()
+#line 1520 "cs-parser.jay"
+{
+		var pars_list = (List<Parameter>) yyVals[-2+yyTop];
+		pars_list.Add (new ArglistParameter (GetLocation (yyVals[0+yyTop])));
+		parameterListCommas.Add (GetLocation (yyVals[-1+yyTop]));
+		
+		yyVal = new ParametersCompiled (pars_list.ToArray (), true);
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_174()
+#line 1529 "cs-parser.jay"
+{
+		if (yyVals[-2+yyTop] != null)
+			report.Error (231, ((Parameter) yyVals[-2+yyTop]).Location, "A params parameter must be the last parameter in a formal parameter list");
+
+		yyVal = new ParametersCompiled (new Parameter[] { (Parameter) yyVals[-2+yyTop] } );			
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_175()
+#line 1537 "cs-parser.jay"
+{
+		if (yyVals[-2+yyTop] != null)
+			report.Error (231, ((Parameter) yyVals[-2+yyTop]).Location, "A params parameter must be the last parameter in a formal parameter list");
+
+		var pars_list = (List<Parameter>) yyVals[-4+yyTop];
+		pars_list.Add (new ArglistParameter (GetLocation (yyVals[-2+yyTop])));
+		parameterListCommas.Add (GetLocation (yyVals[-3+yyTop]));
+		parameterListCommas.Add (GetLocation (yyVals[-1+yyTop]));
+		
+		yyVal = new ParametersCompiled (pars_list.ToArray (), true);
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_176()
+#line 1550 "cs-parser.jay"
+{
+		report.Error (257, GetLocation (yyVals[-2+yyTop]), "An __arglist parameter must be the last parameter in a formal parameter list");
+
+		yyVal = new ParametersCompiled (new Parameter [] { new ArglistParameter (GetLocation (yyVals[-2+yyTop])) }, true);
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_177()
+#line 1557 "cs-parser.jay"
+{
+		report.Error (257, GetLocation (yyVals[-2+yyTop]), "An __arglist parameter must be the last parameter in a formal parameter list");
+
+		var pars_list = (List<Parameter>) yyVals[-4+yyTop];
+		pars_list.Add (new ArglistParameter (GetLocation (yyVals[-2+yyTop])));
+		parameterListCommas.Add (GetLocation (yyVals[-3+yyTop]));
+		parameterListCommas.Add (GetLocation (yyVals[-1+yyTop]));
+
+		yyVal = new ParametersCompiled (pars_list.ToArray (), true);
+	  	lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_180()
+#line 1577 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = ParametersCompiled.EmptyReadOnlyParameters;
+	  }
+
+void case_181()
+#line 1585 "cs-parser.jay"
+{
+		parameters_bucket.Clear ();
+		Parameter p = (Parameter) yyVals[0+yyTop];
+		parameters_bucket.Add (p);
+		parameterListCommas.Clear ();
+		default_parameter_used = p.HasDefaultValue;
+		yyVal = parameters_bucket;
+	  }
+
+void case_182()
+#line 1594 "cs-parser.jay"
+{
+		var pars = (List<Parameter>) yyVals[-2+yyTop];
+		Parameter p = (Parameter) yyVals[0+yyTop];
+		if (p != null) {
+			if (p.HasExtensionMethodModifier)
+				report.Error (1100, p.Location, "The parameter modifier `this' can only be used on the first parameter");
+			else if (!p.HasDefaultValue && default_parameter_used)
+				report.Error (1737, p.Location, "Optional parameter cannot precede required parameters");
+
+			default_parameter_used |= p.HasDefaultValue;
+			pars.Add (p);
+			
+			parameterListCommas.Add (GetLocation (yyVals[-1+yyTop]));
+		}
+		
+		yyVal = yyVals[-2+yyTop];
+	  }
+
+void case_183()
+#line 1618 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		yyVal = new Parameter ((FullNamedExpression) yyVals[-1+yyTop], lt.Value, (Parameter.Modifier) yyVals[-2+yyTop], (Attributes) yyVals[-3+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, parameterModifierLocation);
+	  }
+
+void case_184()
+#line 1627 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		report.Error (1552, lt.Location, "Array type specifier, [], must appear before parameter name");
+		yyVal = new Parameter ((FullNamedExpression) yyVals[-3+yyTop], lt.Value, (Parameter.Modifier) yyVals[-4+yyTop], (Attributes) yyVals[-5+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, parameterModifierLocation);
+	  }
+
+void case_185()
+#line 1634 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  	Location l = GetLocation (yyVals[0+yyTop]);
+		yyVal = new Parameter (null, null, Parameter.Modifier.NONE, (Attributes) yyVals[-1+yyTop], l);
+	  }
+
+void case_186()
+#line 1643 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  	Location l = GetLocation (yyVals[0+yyTop]);
+		yyVal = new Parameter ((FullNamedExpression) yyVals[-1+yyTop], null, (Parameter.Modifier) yyVals[-2+yyTop], (Attributes) yyVals[-3+yyTop], l);
+		lbag.AddLocation (yyVal, parameterModifierLocation);
+	  }
+
+void case_188()
+#line 1658 "cs-parser.jay"
+{
+	  	--lexer.parsing_block;
+		if (lang_version <= LanguageVersion.V_3) {
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "optional parameter");
+		}
+		
+		Parameter.Modifier mod = (Parameter.Modifier) yyVals[-5+yyTop];
+		if (mod != Parameter.Modifier.NONE) {
+			switch (mod) {
+			case Parameter.Modifier.REF:
+			case Parameter.Modifier.OUT:
+				report.Error (1741, GetLocation (yyVals[-5+yyTop]), "Cannot specify a default value for the `{0}' parameter",
+					Parameter.GetModifierSignature (mod));
+				break;
+				
+			case Parameter.Modifier.This:
+				report.Error (1743, GetLocation (yyVals[-5+yyTop]), "Cannot specify a default value for the `{0}' parameter",
+					Parameter.GetModifierSignature (mod));
+				break;
+			default:
+				throw new NotImplementedException (mod.ToString ());
+			}
+				
+			mod = Parameter.Modifier.NONE;
+		}
+		
+		if ((valid_param_mod & ParameterModifierType.DefaultValue) == 0)
+			report.Error (1065, GetLocation (yyVals[-2+yyTop]), "Optional parameter is not valid in this context");
+		
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		yyVal = new Parameter ((FullNamedExpression) yyVals[-4+yyTop], lt.Value, mod, (Attributes) yyVals[-6+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, parameterModifierLocation, GetLocation (yyVals[-2+yyTop])); /* parameterModifierLocation should be ignored when mod == NONE*/
+		
+		if (yyVals[0+yyTop] != null)
+			((Parameter) yyVal).DefaultValue = new DefaultParameterValueExpression ((Expression) yyVals[0+yyTop]);
+	  }
+
+void case_192()
+#line 1707 "cs-parser.jay"
+{
+		Parameter.Modifier p2 = (Parameter.Modifier)yyVals[0+yyTop];
+  		Parameter.Modifier mod = (Parameter.Modifier)yyVals[-1+yyTop] | p2;
+  		if (((Parameter.Modifier)yyVals[-1+yyTop] & p2) == p2) {
+  			Error_DuplicateParameterModifier (lexer.Location, p2);
+  		} else {
+	  		switch (mod & ~Parameter.Modifier.This) {
+  				case Parameter.Modifier.REF:
+					report.Error (1101, lexer.Location, "The parameter modifiers `this' and `ref' cannot be used altogether");
+  					break;
+   				case Parameter.Modifier.OUT:
+					report.Error (1102, lexer.Location, "The parameter modifiers `this' and `out' cannot be used altogether");
+  					break;
+  				default:
+ 					report.Error (1108, lexer.Location, "A parameter cannot have specified more than one modifier");
+ 					break;
+ 			}
+  		}
+  		yyVal = mod;
+	  }
+
+void case_193()
+#line 1731 "cs-parser.jay"
+{
+	  	if ((valid_param_mod & ParameterModifierType.Ref) == 0)
+	  		Error_ParameterModifierNotValid ("ref", GetLocation (yyVals[0+yyTop]));
+		parameterModifierLocation = GetLocation (yyVals[0+yyTop]);
+	  	yyVal = Parameter.Modifier.REF;
+	  }
+
+void case_194()
+#line 1738 "cs-parser.jay"
+{
+	  	if ((valid_param_mod & ParameterModifierType.Out) == 0)
+	  		Error_ParameterModifierNotValid ("out", GetLocation (yyVals[0+yyTop]));
+		parameterModifierLocation = GetLocation (yyVals[0+yyTop]);
+	  	yyVal = Parameter.Modifier.OUT;
+	  }
+
+void case_195()
+#line 1745 "cs-parser.jay"
+{
+		if ((valid_param_mod & ParameterModifierType.This) == 0)
+	  		Error_ParameterModifierNotValid ("this", GetLocation (yyVals[0+yyTop]));
+
+	  	if (lang_version <= LanguageVersion.ISO_2)
+	  		FeatureIsNotAvailable (GetLocation (yyVals[0+yyTop]), "extension methods");
+		parameterModifierLocation = GetLocation (yyVals[0+yyTop]);
+		yyVal = Parameter.Modifier.This;
+	  }
+
+void case_196()
+#line 1758 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		yyVal = new ParamsParameter ((FullNamedExpression) yyVals[-1+yyTop], lt.Value, (Attributes) yyVals[-3+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, savedLocation);
+	  }
+
+void case_197()
+#line 1764 "cs-parser.jay"
+{
+		report.Error (1751, GetLocation (yyVals[-4+yyTop]), "Cannot specify a default value for a parameter array");
+		
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new ParamsParameter ((FullNamedExpression) yyVals[-3+yyTop], lt.Value, (Attributes) yyVals[-5+yyTop], lt.Location);		
+		lbag.AddLocation (yyVal, savedLocation);
+	  }
+
+void case_198()
+#line 1772 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new ParamsParameter ((FullNamedExpression) yyVals[-1+yyTop], null, (Attributes) yyVals[-3+yyTop], Location.Null);
+	  }
+
+void case_199()
+#line 1781 "cs-parser.jay"
+{
+		if ((valid_param_mod & ParameterModifierType.Params) == 0)
+			report.Error (1670, (GetLocation (yyVals[0+yyTop])), "The `params' modifier is not allowed in current context");
+		savedLocation = GetLocation (yyVals[0+yyTop]);
+	  }
+
+void case_200()
+#line 1787 "cs-parser.jay"
+{
+		Parameter.Modifier mod = (Parameter.Modifier)yyVals[0+yyTop];
+		if ((mod & Parameter.Modifier.This) != 0) {
+			report.Error (1104, GetLocation (yyVals[-1+yyTop]), "The parameter modifiers `this' and `params' cannot be used altogether");
+		} else {
+			report.Error (1611, GetLocation (yyVals[-1+yyTop]), "The params parameter cannot be declared as ref or out");
+		}	  
+		savedLocation = GetLocation (yyVals[-1+yyTop]);
+	  }
+
+void case_202()
+#line 1804 "cs-parser.jay"
+{
+	  	if ((valid_param_mod & ParameterModifierType.Arglist) == 0)
+	  		report.Error (1669, GetLocation (yyVals[0+yyTop]), "__arglist is not valid in this context");
+	  }
+
+void case_203()
+#line 1815 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;
+		if (doc_support)
+			tmpComment = Lexer.consume_doc_comment ();
+	  }
+
+void case_204()
+#line 1821 "cs-parser.jay"
+{
+		var type = (FullNamedExpression) yyVals[-3+yyTop];
+		current_property = new Property (current_type, type, (Modifiers) yyVals[-4+yyTop],
+			(MemberName) yyVals[-2+yyTop], (Attributes) yyVals[-5+yyTop]);
+			
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (547, GetLocation (yyVals[-3+yyTop]), "`{0}': property or indexer cannot have void type", current_property.GetSignatureForError ());					
+			
+		current_type.AddMember (current_property);
+		lbag.AddMember (current_property, GetModifierLocations (), GetLocation (yyVals[0+yyTop]));
+		
+		lexer.PropertyParsing = true;
+	  }
+
+void case_205()
+#line 1835 "cs-parser.jay"
+{
+		lexer.PropertyParsing = false;
+		
+		if (doc_support)
+			current_property.DocComment = ConsumeStoredComment ();				
+	  }
+
+void case_206()
+#line 1842 "cs-parser.jay"
+{
+		lbag.AppendToMember (current_property, GetLocation (yyVals[0+yyTop]));
+		lexer.parsing_modifiers = true;
+	  }
+
+void case_208()
+#line 1854 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;
+		if (doc_support)
+			tmpComment = Lexer.consume_doc_comment ();
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  }
+
+void case_209()
+#line 1861 "cs-parser.jay"
+{
+		var type = (FullNamedExpression) yyVals[-3+yyTop];
+		var property = new Property (current_type, type, (Modifiers) yyVals[-4+yyTop],
+			(MemberName) yyVals[-2+yyTop], (Attributes) yyVals[-5+yyTop]);
+
+		property.Get = new Property.GetMethod (property, Modifiers.COMPILER_GENERATED, null, property.Location);
+		property.Get.Block = (ToplevelBlock) yyVals[0+yyTop];
+
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (531, property.Get.Block.StartLocation,
+				"`{0}': interface members cannot have a definition", property.GetSignatureForError ());
+		}
+
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (547, GetLocation (yyVals[-3+yyTop]), "`{0}': property or indexer cannot have void type", property.GetSignatureForError ());
+
+		current_type.AddMember (property);
+
+		current_local_parameters = null;
+	  }
+
+void case_211()
+#line 1886 "cs-parser.jay"
+{
+		++lexer.parsing_block;
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		start_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_212()
+#line 1892 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		((Property)current_property).Initializer = (Expression) yyVals[-1+yyTop];
+		lbag.AppendToMember (current_property, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+		end_block (GetLocation (yyVals[0+yyTop]));
+		current_local_parameters = null;
+	  }
+
+void case_216()
+#line 1913 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+		var type = (FullNamedExpression) yyVals[-5+yyTop];
+		Indexer indexer = new Indexer (current_type, type, (MemberName) yyVals[-4+yyTop], (Modifiers) yyVals[-6+yyTop], (ParametersCompiled) yyVals[-1+yyTop], (Attributes) yyVals[-7+yyTop]);
+			
+		current_property = indexer;
+
+  		current_type.AddIndexer (indexer);
+		lbag.AddMember (current_property, GetModifierLocations (), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+  		
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (620, GetLocation (yyVals[-5+yyTop]), "`{0}': indexer return type cannot be `void'", indexer.GetSignatureForError ());  		
+
+		if (indexer.ParameterInfo.IsEmpty) {
+			report.Error (1551, GetLocation (yyVals[-3+yyTop]), "Indexers must have at least one parameter");
+		}
+
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+
+		lexer.PropertyParsing = true;
+		current_local_parameters = (ParametersCompiled) yyVals[-1+yyTop];
+	  }
+
+void case_217()
+#line 1939 "cs-parser.jay"
+{
+ 		lexer.PropertyParsing = false;
+		current_local_parameters = null;
+
+		if (current_property.AccessorFirst != null && current_property.AccessorFirst.Block == null)
+			((Indexer) current_property).ParameterInfo.CheckParameters (current_property);
+	  
+		if (doc_support)
+			current_property.DocComment = ConsumeStoredComment ();
+			
+		current_property = null;		
+	  }
+
+void case_219()
+#line 1959 "cs-parser.jay"
+{
+		current_property.Get = new Indexer.GetIndexerMethod (current_property, Modifiers.COMPILER_GENERATED, current_local_parameters, null, current_property.Location);
+		current_property.Get.Block = (ToplevelBlock) yyVals[0+yyTop];
+	  }
+
+void case_224()
+#line 1971 "cs-parser.jay"
+{
+	  	if (yyToken == Token.CLOSE_BRACE) {
+	  		report.Error (548, lexer.Location, "`{0}': property or indexer must have at least one accessor", current_property.GetSignatureForError ());
+		} else {
+			if (yyToken == Token.SEMICOLON)
+				report.Error (1597, lexer.Location, "Semicolon after method or accessor block is not valid");
+			else
+				report.Error (1014, GetLocation (yyVals[0+yyTop]), "A get or set accessor expected");
+		}
+	  }
+
+void case_225()
+#line 1985 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] != ModifierNone && lang_version == LanguageVersion.ISO_1) {
+			FeatureIsNotAvailable (GetLocation (yyVals[-1+yyTop]), "access modifiers on properties");
+		}
+	  
+		if (current_property.Get != null) {
+			report.Error (1007, GetLocation (yyVals[0+yyTop]), "Property accessor already defined");
+		}
+		
+		if (current_property is Indexer) {
+			current_property.Get = new Indexer.GetIndexerMethod (current_property, (Modifiers) yyVals[-1+yyTop], ((Indexer)current_property).ParameterInfo.Clone (),
+				(Attributes) yyVals[-2+yyTop], GetLocation (yyVals[0+yyTop]));
+		} else {
+			current_property.Get = new Property.GetMethod (current_property,
+				(Modifiers) yyVals[-1+yyTop], (Attributes) yyVals[-2+yyTop], GetLocation (yyVals[0+yyTop]));
+		}	
+	  
+		current_local_parameters = current_property.Get.ParameterInfo;	  
+		lexer.PropertyParsing = false;
+	  }
+
+void case_226()
+#line 2006 "cs-parser.jay"
+{
+	  	if (yyVals[0+yyTop] != null) {
+	  		current_property.Get.Block = (ToplevelBlock) yyVals[0+yyTop];			
+	  	
+			if (current_container.Kind == MemberKind.Interface) {
+				report.Error (531, current_property.Get.Block.StartLocation,
+					"`{0}': interface members cannot have a definition", current_property.Get.GetSignatureForError ());
+			}
+			lbag.AddMember (current_property.Get, GetModifierLocations ());
+		} else {
+			lbag.AddMember (current_property.Get, GetModifierLocations (), savedLocation);
+		}
+	  
+		current_local_parameters = null;
+		lexer.PropertyParsing = true;
+
+		if (doc_support)
+			if (Lexer.doc_state == XmlCommentState.Error)
+				Lexer.doc_state = XmlCommentState.NotAllowed;
+	  }
+
+void case_227()
+#line 2030 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] != ModifierNone && lang_version == LanguageVersion.ISO_1) {
+			FeatureIsNotAvailable (GetLocation (yyVals[-1+yyTop]), "access modifiers on properties");
+		}
+		
+		if (current_property.Set != null) {
+			report.Error (1007, GetLocation (yyVals[0+yyTop]), "Property accessor already defined");
+		}
+	  
+		if (current_property is Indexer) {
+			current_property.Set = new Indexer.SetIndexerMethod (current_property, (Modifiers) yyVals[-1+yyTop],
+				ParametersCompiled.MergeGenerated (compiler,
+				((Indexer)current_property).ParameterInfo, true, new Parameter (
+					current_property.TypeExpression, "value", Parameter.Modifier.NONE, null, GetLocation (yyVals[0+yyTop])),
+					null),
+				(Attributes) yyVals[-2+yyTop], GetLocation (yyVals[0+yyTop]));
+		} else {
+			current_property.Set = new Property.SetMethod (current_property, (Modifiers) yyVals[-1+yyTop], 
+				ParametersCompiled.CreateImplicitParameter (current_property.TypeExpression, GetLocation (yyVals[0+yyTop])),
+				(Attributes) yyVals[-2+yyTop], GetLocation (yyVals[0+yyTop]));
+		}
+		
+		current_local_parameters = current_property.Set.ParameterInfo;	
+		lexer.PropertyParsing = false;
+	  }
+
+void case_228()
+#line 2056 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null) {		
+			current_property.Set.Block = (ToplevelBlock) yyVals[0+yyTop];
+		
+			if (current_container.Kind == MemberKind.Interface) {
+				report.Error (531, current_property.Set.Block.StartLocation,
+					"`{0}': interface members cannot have a definition", current_property.Set.GetSignatureForError ());
+			}
+			lbag.AddMember (current_property.Set, GetModifierLocations ());
+		} else {
+			lbag.AddMember (current_property.Set, GetModifierLocations (), savedLocation);
+		}
+		
+		current_local_parameters = null;
+		lexer.PropertyParsing = true;
+
+		if (doc_support
+			&& Lexer.doc_state == XmlCommentState.Error)
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+	  }
+
+void case_230()
+#line 2081 "cs-parser.jay"
+{
+		savedLocation = GetLocation (yyVals[0+yyTop]);
+	  	yyVal = null;
+	  }
+
+void case_231()
+#line 2086 "cs-parser.jay"
+{
+	  	Error_SyntaxError (1043, yyToken, "Invalid accessor body");
+	  	yyVal = null;
+	  }
+
+void case_233()
+#line 2100 "cs-parser.jay"
+{
+		lexer.ConstraintsParsing = true;
+		push_current_container (new Interface (current_container, (MemberName) yyVals[0+yyTop], (Modifiers) yyVals[-4+yyTop], (Attributes) yyVals[-5+yyTop]), yyVals[-3+yyTop]);
+		lbag.AddMember (current_container, GetModifierLocations (), GetLocation (yyVals[-2+yyTop]));		
+	  }
+
+void case_234()
+#line 2107 "cs-parser.jay"
+{
+		lexer.ConstraintsParsing = false;
+
+		if (yyVals[0+yyTop] != null)
+			current_container.SetConstraints ((List<Constraints>) yyVals[0+yyTop]);
+
+		if (doc_support) {
+			current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		lexer.parsing_modifiers = true;
+	  }
+
+void case_235()
+#line 2121 "cs-parser.jay"
+{
+		--lexer.parsing_declaration;	  
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_236()
+#line 2127 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] == null) {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		} else {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+		yyVal = pop_current_class ();
+	  }
+
+void case_240()
+#line 2148 "cs-parser.jay"
+{
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+
+void case_241()
+#line 2153 "cs-parser.jay"
+{
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+
+void case_252()
+#line 2191 "cs-parser.jay"
+{
+		OperatorDeclaration decl = (OperatorDeclaration) yyVals[-2+yyTop];
+		if (decl != null) {
+			Operator op = new Operator (
+				current_type, decl.optype, decl.ret_type, (Modifiers) yyVals[-3+yyTop], 
+				current_local_parameters,
+				(ToplevelBlock) yyVals[0+yyTop], (Attributes) yyVals[-4+yyTop], decl.location);
+				
+			if (op.Block == null)
+				op.ParameterInfo.CheckParameters (op);
+
+			if (doc_support) {
+				op.DocComment = tmpComment;
+				Lexer.doc_state = XmlCommentState.Allowed;
+			}
+
+			/* Note again, checking is done in semantic analysis*/
+			current_type.AddOperator (op);
+
+			lbag.AddMember (op, GetModifierLocations (), lbag.GetLocations (decl));
+			if (yyVals[0+yyTop] == null) { /* Semicolon*/
+				lbag.AddLocation (op, savedLocation); 
+			}
+		}
+		
+		current_local_parameters = null;
+	  }
+
+void case_254()
+#line 2223 "cs-parser.jay"
+{
+		report.Error (590, GetLocation (yyVals[0+yyTop]), "User-defined operators cannot return void");
+		yyVal = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_256()
+#line 2235 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+
+		Location loc = GetLocation (yyVals[-5+yyTop]);
+		Operator.OpType op = (Operator.OpType) yyVals[-4+yyTop];
+		current_local_parameters = (ParametersCompiled)yyVals[-1+yyTop];
+		
+		int p_count = current_local_parameters.Count;
+		if (p_count == 1) {
+			if (op == Operator.OpType.Addition)
+				op = Operator.OpType.UnaryPlus;
+			else if (op == Operator.OpType.Subtraction)
+				op = Operator.OpType.UnaryNegation;
+		}
+		
+		if (IsUnaryOperator (op)) {
+			if (p_count == 2) {
+				report.Error (1020, loc, "Overloadable binary operator expected");
+			} else if (p_count != 1) {
+				report.Error (1535, loc, "Overloaded unary operator `{0}' takes one parameter",
+					Operator.GetName (op));
+			}
+		} else {
+			if (p_count == 1) {
+				report.Error (1019, loc, "Overloadable unary operator expected");
+			} else if (p_count != 2) {
+				report.Error (1534, loc, "Overloaded binary operator `{0}' takes two parameters",
+					Operator.GetName (op));
+			}
+		}
+		
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+
+		yyVal = new OperatorDeclaration (op, (FullNamedExpression) yyVals[-6+yyTop], loc);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-5+yyTop]), savedOperatorLocation, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_281()
+#line 2311 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+
+		Location loc = GetLocation (yyVals[-5+yyTop]);
+		current_local_parameters = (ParametersCompiled)yyVals[-1+yyTop];  
+
+		if (current_local_parameters.Count != 1) {
+			report.Error (1535, loc, "Overloaded unary operator `implicit' takes one parameter");
+		}
+
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+
+		yyVal = new OperatorDeclaration (Operator.OpType.Implicit, (FullNamedExpression) yyVals[-4+yyTop], loc);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_283()
+#line 2334 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+		
+		Location loc = GetLocation (yyVals[-5+yyTop]);
+		current_local_parameters = (ParametersCompiled)yyVals[-1+yyTop];  
+
+		if (current_local_parameters.Count != 1) {
+			report.Error (1535, loc, "Overloaded unary operator `explicit' takes one parameter");
+		}
+
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+
+		yyVal = new OperatorDeclaration (Operator.OpType.Explicit, (FullNamedExpression) yyVals[-4+yyTop], loc);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_284()
+#line 2353 "cs-parser.jay"
+{
+	  	Error_SyntaxError (yyToken);
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		yyVal = new OperatorDeclaration (Operator.OpType.Implicit, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_285()
+#line 2359 "cs-parser.jay"
+{
+	  	Error_SyntaxError (yyToken);
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  	yyVal = new OperatorDeclaration (Operator.OpType.Explicit, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_286()
+#line 2369 "cs-parser.jay"
+{ 
+		Constructor c = (Constructor) yyVals[-1+yyTop];
+		c.Block = (ToplevelBlock) yyVals[0+yyTop];
+		
+		if (doc_support)
+			c.DocComment = ConsumeStoredComment ();
+
+		current_local_parameters = null;
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_287()
+#line 2386 "cs-parser.jay"
+{
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		valid_param_mod = ParameterModifierType.All;
+	  }
+
+void case_288()
+#line 2395 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+		current_local_parameters = (ParametersCompiled) yyVals[-1+yyTop];
+		
+		var lt = (LocatedToken) yyVals[-4+yyTop];
+		var mods = (Modifiers) yyVals[-5+yyTop];
+		var c = new Constructor (current_type, lt.Value, mods, (Attributes) yyVals[-6+yyTop], current_local_parameters, lt.Location);
+
+		if (lt.Value != current_container.MemberName.Name) {
+			report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
+		} else if ((mods & Modifiers.STATIC) != 0) {
+			if ((mods & Modifiers.AccessibilityMask) != 0){
+				report.Error (515, c.Location,
+					"`{0}': static constructor cannot have an access modifier",
+					c.GetSignatureForError ());
+			}
+		}
+
+		current_type.AddConstructor (c);
+		lbag.AddMember (c, GetModifierLocations (), GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+		yyVal = c;
+
+		/**/
+		/* start block here, so possible anonymous methods inside*/
+		/* constructor initializer can get correct parent block*/
+		/**/
+	  	start_block (lexer.Location);
+	  }
+
+void case_289()
+#line 2424 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null) {
+			var c = (Constructor) yyVals[-1+yyTop];
+			c.Initializer = (ConstructorInitializer) yyVals[0+yyTop];
+			
+			if (c.IsStatic) {
+				report.Error (514, c.Location,
+					"`{0}': static constructor cannot have an explicit `this' or `base' constructor call",
+					c.GetSignatureForError ());
+			}
+		}
+
+		yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_295()
+#line 2456 "cs-parser.jay"
+{
+	  	--lexer.parsing_block;
+		yyVal = new ConstructorBaseInitializer ((Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_297()
+#line 2466 "cs-parser.jay"
+{
+	  	--lexer.parsing_block;
+		yyVal = new ConstructorThisInitializer ((Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_298()
+#line 2472 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);	  
+		yyVal = new ConstructorThisInitializer (null, GetLocation (yyVals[0+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_299()
+#line 2478 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	  }
+
+void case_300()
+#line 2486 "cs-parser.jay"
+{
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+		
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  }
+
+void case_301()
+#line 2495 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		if (lt.Value != current_container.MemberName.Name){
+			report.Error (574, lt.Location, "Name of destructor must match name of class");
+		} else if (current_container.Kind != MemberKind.Class){
+			report.Error (575, lt.Location, "Only class types can contain destructor");
+		}
+		
+		Destructor d = new Destructor (current_type, (Modifiers) yyVals[-6+yyTop],
+			ParametersCompiled.EmptyReadOnlyParameters, (Attributes) yyVals[-7+yyTop], lt.Location);
+		d.Identifier = lt.Value;
+		if (doc_support)
+			d.DocComment = ConsumeStoredComment ();
+		  
+		d.Block = (ToplevelBlock) yyVals[0+yyTop];
+		current_type.AddMember (d);
+		lbag.AddMember (d, GetModifierLocations (), GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[-1+yyTop]));
+
+		current_local_parameters = null;
+	  }
+
+void case_302()
+#line 2521 "cs-parser.jay"
+{
+		current_event_field = new EventField (current_type, (FullNamedExpression) yyVals[-1+yyTop], (Modifiers) yyVals[-3+yyTop], (MemberName) yyVals[0+yyTop], (Attributes) yyVals[-4+yyTop]);
+		current_type.AddMember (current_event_field);
+		
+		if (current_event_field.MemberName.ExplicitInterface != null) {
+			report.Error (71, current_event_field.Location, "`{0}': An explicit interface implementation of an event must use property syntax",
+			current_event_field.GetSignatureForError ());
+		}
+		
+		yyVal = current_event_field;
+	  }
+
+void case_303()
+#line 2535 "cs-parser.jay"
+{
+		if (doc_support) {
+			current_event_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		if (current_event_field.Initializer != null) {
+			lbag.AddMember (current_event_field, GetModifierLocations (), GetLocation (yyVals[-6+yyTop]), savedEventAssignLocation, GetLocation (yyVals[0+yyTop]));
+		} else {
+			lbag.AddMember (current_event_field, GetModifierLocations (), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+		current_event_field = null;
+	  }
+
+void case_304()
+#line 2551 "cs-parser.jay"
+{
+		current_event = new EventProperty (current_type, (FullNamedExpression) yyVals[-2+yyTop], (Modifiers) yyVals[-4+yyTop], (MemberName) yyVals[-1+yyTop], (Attributes) yyVals[-5+yyTop]);
+		current_type.AddMember (current_event);
+		lbag.AddMember (current_event, GetModifierLocations (), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+		
+		lexer.EventParsing = true;
+	  }
+
+void case_305()
+#line 2559 "cs-parser.jay"
+{
+		if (current_container.Kind == MemberKind.Interface)
+			report.Error (69, GetLocation (yyVals[-2+yyTop]), "Event in interface cannot have add or remove accessors");
+	  
+		lexer.EventParsing = false;
+	  }
+
+void case_306()
+#line 2566 "cs-parser.jay"
+{
+		if (doc_support) {
+			current_event.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		lbag.AppendToMember (current_event, GetLocation (yyVals[-1+yyTop]));
+	  	current_event = null;	
+		current_local_parameters = null;
+	  }
+
+void case_307()
+#line 2579 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		current_type.AddMember (new EventField (current_type, (FullNamedExpression) yyVals[-1+yyTop], (Modifiers) yyVals[-3+yyTop], MemberName.Null, (Attributes) yyVals[-4+yyTop]));
+	  }
+
+void case_310()
+#line 2593 "cs-parser.jay"
+{
+	  	--lexer.parsing_block;
+	  	savedEventAssignLocation = GetLocation (yyVals[-2+yyTop]);
+		current_event_field.Initializer = (Expression) yyVals[0+yyTop];
+	  }
+
+void case_315()
+#line 2618 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+	  	yyVal = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), null);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_317()
+#line 2628 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		var lt = (LocatedToken) yyVals[-3+yyTop];	  
+	  	yyVal = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (Expression) yyVals[0+yyTop]);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_318()
+#line 2637 "cs-parser.jay"
+{
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (68, lexer.Location, "`{0}': event in interface cannot have an initializer",
+				current_event_field.GetSignatureForError ());
+		}
+		
+	  	if ((current_event_field.ModFlags & Modifiers.ABSTRACT) != 0) {
+			report.Error (74, lexer.Location, "`{0}': abstract event cannot have an initializer",
+				current_event_field.GetSignatureForError ());
+	  	}		
+	  }
+
+void case_322()
+#line 2658 "cs-parser.jay"
+{
+		report.Error (65, lexer.Location, "`{0}': event property must have both add and remove accessors",
+			current_event.GetSignatureForError ());
+	  }
+
+void case_323()
+#line 2663 "cs-parser.jay"
+{
+		report.Error (65, lexer.Location, "`{0}': event property must have both add and remove accessors",
+			current_event.GetSignatureForError ());
+	  }
+
+void case_324()
+#line 2668 "cs-parser.jay"
+{ 
+		report.Error (1055, GetLocation (yyVals[0+yyTop]), "An add or remove accessor expected");
+		yyVal = null;
+	  }
+
+void case_325()
+#line 2676 "cs-parser.jay"
+{
+	  	if (yyVals[-1+yyTop] != ModifierNone) {
+			report.Error (1609, GetLocation (yyVals[-1+yyTop]), "Modifiers cannot be placed on event accessor declarations");
+	  	}
+	  	
+	  	current_event.Add = new EventProperty.AddDelegateMethod (current_event, (Attributes) yyVals[-2+yyTop], GetLocation (yyVals[0+yyTop]));
+		current_local_parameters = current_event.Add.ParameterInfo;
+		
+		lbag.AddMember (current_event.Add, GetModifierLocations ());
+		lexer.EventParsing = false;		
+	  }
+
+void case_326()
+#line 2688 "cs-parser.jay"
+{
+		lexer.EventParsing = true;
+	  
+	  	current_event.Add.Block = (ToplevelBlock) yyVals[0+yyTop];
+		
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (531, current_event.Add.Block.StartLocation,
+				"`{0}': interface members cannot have a definition", current_event.Add.GetSignatureForError ());
+		}
+		
+		current_local_parameters = null;
+	  }
+
+void case_327()
+#line 2704 "cs-parser.jay"
+{
+	  	if (yyVals[-1+yyTop] != ModifierNone) {
+			report.Error (1609, GetLocation (yyVals[-1+yyTop]), "Modifiers cannot be placed on event accessor declarations");
+	  	}
+	  	
+	  	current_event.Remove = new EventProperty.RemoveDelegateMethod (current_event, (Attributes) yyVals[-2+yyTop], GetLocation (yyVals[0+yyTop]));
+		current_local_parameters = current_event.Remove.ParameterInfo;
+
+		lbag.AddMember (current_event.Remove, GetModifierLocations ());
+		lexer.EventParsing = false;		
+	  }
+
+void case_328()
+#line 2716 "cs-parser.jay"
+{
+		lexer.EventParsing = true;
+	  
+	  	current_event.Remove.Block = (ToplevelBlock) yyVals[0+yyTop];
+		
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (531, current_event.Remove.Block.StartLocation,
+				"`{0}': interface members cannot have a definition", current_event.Remove.GetSignatureForError ());
+		}
+		
+		current_local_parameters = null;
+	  }
+
+void case_329()
+#line 2732 "cs-parser.jay"
+{
+		report.Error (73, lexer.Location, "An add or remove accessor must have a body");
+		yyVal = null;
+	  }
+
+void case_331()
+#line 2741 "cs-parser.jay"
+{
+		current_type.UnattachedAttributes = (Attributes) yyVals[-1+yyTop];
+		report.Error (1519, GetLocation (yyVals[-1+yyTop]), "An attribute is missing member declaration");
+		lexer.putback ('}');
+	  }
+
+void case_332()
+#line 2752 "cs-parser.jay"
+{
+		report.Error (1519, lexer.Location, "Unexpected symbol `}' in class, struct, or interface member declaration");
+ 
+		lexer.putback ('}');
+
+	  	lexer.parsing_generic_declaration = false;
+		FullNamedExpression type = (FullNamedExpression) yyVals[-1+yyTop];
+		current_field = new Field (current_type, type, (Modifiers) yyVals[-2+yyTop], MemberName.Null, (Attributes) yyVals[-3+yyTop]);
+		current_type.AddField (current_field);
+		lbag.AddMember (current_field, GetModifierLocations ());
+		yyVal = current_field;
+	  }
+
+void case_333()
+#line 2772 "cs-parser.jay"
+{
+		if (doc_support)
+			enumTypeComment = Lexer.consume_doc_comment ();
+	  }
+
+void case_334()
+#line 2777 "cs-parser.jay"
+{
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+
+		MemberName name = (MemberName) yyVals[-3+yyTop];
+		if (name.IsGeneric) {
+			report.Error (1675, name.Location, "Enums cannot have type parameters");
+		}
+		
+		push_current_container (new Enum (current_container, (FullNamedExpression) yyVals[-2+yyTop], (Modifiers) yyVals[-5+yyTop], name, (Attributes) yyVals[-6+yyTop]), null);
+		if (yyVals[-2+yyTop] != null) {
+			lbag.AddMember (current_container, GetModifierLocations (), GetLocation (yyVals[-4+yyTop]), savedLocation, GetLocation (yyVals[0+yyTop]));
+		} else {
+			lbag.AddMember (current_container, GetModifierLocations (), GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+	  }
+
+void case_335()
+#line 2794 "cs-parser.jay"
+{
+		lexer.parsing_modifiers = true;
+	  
+	  	/* here will be evaluated after CLOSE_BLACE is consumed.*/
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_336()
+#line 2802 "cs-parser.jay"
+{
+		lbag.AppendToMember (current_container, GetLocation (yyVals[-1+yyTop]));
+		if (yyVals[0+yyTop] != null) {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[0+yyTop]));
+		}
+		if (doc_support)
+			current_container.DocComment = enumTypeComment;
+			
+		--lexer.parsing_declaration;
+
+/*			if (doc_support)*/
+/*				em.DocComment = ev.DocComment;*/
+
+		yyVal = pop_current_class ();
+	  }
+
+void case_338()
+#line 2822 "cs-parser.jay"
+{
+		savedLocation = GetLocation (yyVals[-1+yyTop]);
+		yyVal = yyVals[0+yyTop];
+	 }
+
+void case_339()
+#line 2827 "cs-parser.jay"
+{
+	 	Error_TypeExpected (GetLocation (yyVals[-1+yyTop]));
+		yyVal = null;
+	 }
+
+void case_344()
+#line 2845 "cs-parser.jay"
+{
+		lbag.AppendToMember (current_container, GetLocation (yyVals[-1+yyTop]));
+	  	yyVal = yyVals[0+yyTop];
+	  }
+
+void case_345()
+#line 2853 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+	  	var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) yyVals[-1+yyTop]);
+	  	((Enum) current_type).AddEnumMember (em);
+
+		if (doc_support) {
+			em.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+
+		yyVal = em;
+	  }
+
+void case_346()
+#line 2866 "cs-parser.jay"
+{
+	  	++lexer.parsing_block;
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+	  }
+
+void case_347()
+#line 2874 "cs-parser.jay"
+{ 
+		--lexer.parsing_block;
+		
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+	  	var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) yyVals[-4+yyTop]);
+	  	em.Initializer = new ConstInitializer (em, (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  	((Enum) current_type).AddEnumMember (em);
+		
+		if (doc_support)
+			em.DocComment = ConsumeStoredComment ();
+
+		yyVal = em;
+	  }
+
+void case_348()
+#line 2888 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+	  	var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) yyVals[-2+yyTop]);
+	  	((Enum) current_type).AddEnumMember (em);
+
+		if (doc_support) {
+			em.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+
+		yyVal = em;
+	  }
+
+void case_351()
+#line 2915 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+
+		ParametersCompiled p = (ParametersCompiled) yyVals[-1+yyTop];
+
+		Delegate del = new Delegate (current_container, (FullNamedExpression) yyVals[-5+yyTop], (Modifiers) yyVals[-7+yyTop], (MemberName) yyVals[-4+yyTop], p, (Attributes) yyVals[-8+yyTop]);
+
+		p.CheckParameters (del);
+
+		current_container.AddTypeContainer (del);
+
+		current_delegate = del;
+		lexer.ConstraintsParsing = true;
+	  }
+
+void case_353()
+#line 2934 "cs-parser.jay"
+{
+		if (doc_support) {
+			current_delegate.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+	  
+		if (yyVals[-2+yyTop] != null)
+			current_delegate.SetConstraints ((List<Constraints>) yyVals[-2+yyTop]);
+		lbag.AddMember (current_delegate, GetModifierLocations (), GetLocation (yyVals[-10+yyTop]), GetLocation (yyVals[-7+yyTop]), GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[0+yyTop]));
+
+		yyVal = current_delegate;
+
+		current_delegate = null;
+	  }
+
+void case_355()
+#line 2953 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[0+yyTop]), "nullable types");
+	  
+	  	yyVal = ComposedTypeSpecifier.CreateNullable (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_357()
+#line 2964 "cs-parser.jay"
+{
+		var lt1 = (LocatedToken) yyVals[-2+yyTop];
+		var lt2 = (LocatedToken) yyVals[-1+yyTop];
+		
+		yyVal = new QualifiedAliasMember (lt1.Value, lt2.Value, (TypeArguments) yyVals[0+yyTop], lt1.Location);
+		lbag.AddLocation (yyVal, savedLocation, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_358()
+#line 2972 "cs-parser.jay"
+{
+		var lt1 = (LocatedToken) yyVals[-2+yyTop];
+		var lt2 = (LocatedToken) yyVals[-1+yyTop];
+		var qam = new QualifiedAliasMember (lt1.Value, lt2.Value, (int) yyVals[0+yyTop], lt1.Location);
+		lbag.AddLocation (qam.TypeArguments, Lexer.GenericDimensionLocations);
+		yyVal = qam;
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_360()
+#line 2985 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_361()
+#line 2991 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		var ma = new MemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, (int) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (ma.TypeArguments, Lexer.GenericDimensionLocations);
+		yyVal = ma;
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_362()
+#line 3002 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new SimpleName (lt.Value, (TypeArguments)yyVals[0+yyTop], lt.Location);
+	  }
+
+void case_363()
+#line 3007 "cs-parser.jay"
+{  
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		var sn = new SimpleName (lt.Value, (int) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (sn.TypeArguments, Lexer.GenericDimensionLocations);
+		yyVal = sn;
+	  }
+
+void case_365()
+#line 3021 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "generics");
+		var list = locationListStack.Pop ();
+		list.Add (GetLocation (yyVals[-2+yyTop]));
+		list.Add (GetLocation (yyVals[-1+yyTop]));
+		lbag.AddLocation (yyVals[-1+yyTop], list);
+	
+		yyVal = yyVals[-1+yyTop];;
+	  }
+
+void case_366()
+#line 3032 "cs-parser.jay"
+{
+		Error_TypeExpected (lexer.Location);
+		yyVal = new TypeArguments ();
+	  }
+
+void case_367()
+#line 3040 "cs-parser.jay"
+{
+		TypeArguments type_args = new TypeArguments ();
+		type_args.Add ((FullNamedExpression) yyVals[0+yyTop]);
+		yyVal = type_args;
+		locationListStack.Push (new List<Location> ());
+	  }
+
+void case_368()
+#line 3047 "cs-parser.jay"
+{
+		TypeArguments type_args = (TypeArguments) yyVals[-2+yyTop];
+		type_args.Add ((FullNamedExpression) yyVals[0+yyTop]);
+		yyVal = type_args;
+		locationListStack.Peek ().Add (GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_370()
+#line 3064 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new MemberName (lt.Value, (TypeParameters)yyVals[0+yyTop], lt.Location);
+	  }
+
+void case_371()
+#line 3073 "cs-parser.jay"
+{
+	  	MemberName mn = (MemberName)yyVals[0+yyTop];
+	  	if (mn.TypeParameters != null)
+	  		syntax_error (mn.Location, string.Format ("Member `{0}' cannot declare type arguments",
+	  			mn.GetSignatureForError ()));
+	  }
+
+void case_373()
+#line 3084 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;	  
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberName (lt.Value, (TypeParameters) yyVals[0+yyTop], (ATypeNameExpression) yyVals[-2+yyTop], lt.Location);
+	  }
+
+void case_374()
+#line 3093 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;	  
+		yyVal = new MemberName (TypeDefinition.DefaultIndexerName, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_375()
+#line 3098 "cs-parser.jay"
+{
+		lexer.parsing_generic_declaration = false;
+		yyVal = new MemberName (TypeDefinition.DefaultIndexerName, null, (ATypeNameExpression) yyVals[-1+yyTop], GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_376()
+#line 3106 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new SimpleName (lt.Value, (TypeArguments) yyVals[-1+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_377()
+#line 3112 "cs-parser.jay"
+{
+		var lt1 = (LocatedToken) yyVals[-3+yyTop];
+		var lt2 = (LocatedToken) yyVals[-2+yyTop];
+
+		yyVal = new QualifiedAliasMember (lt1.Value, lt2.Value, (TypeArguments) yyVals[-1+yyTop], lt1.Location);
+		lbag.AddLocation (yyVal, savedLocation, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_378()
+#line 3120 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new MemberAccess ((ATypeNameExpression) yyVals[-3+yyTop], lt.Value, (TypeArguments) yyVals[-1+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_380()
+#line 3130 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "generics");
+	  
+		yyVal = yyVals[-1+yyTop];
+		var list = locationListStack.Pop ();
+		list.Add (GetLocation (yyVals[-2+yyTop]));
+		list.Add (GetLocation (yyVals[-1+yyTop]));
+		lbag.AddLocation (yyVals[-1+yyTop], list);
+	  }
+
+void case_381()
+#line 3144 "cs-parser.jay"
+{
+		var tparams = new TypeParameters ();
+		tparams.Add ((TypeParameter)yyVals[0+yyTop]);
+		yyVal = tparams;
+		locationListStack.Push (new List<Location> ());
+	  }
+
+void case_382()
+#line 3151 "cs-parser.jay"
+{
+		var tparams = (TypeParameters) yyVals[-2+yyTop];
+		tparams.Add ((TypeParameter)yyVals[0+yyTop]);
+		yyVal = tparams;
+		locationListStack.Peek ().Add (GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_383()
+#line 3161 "cs-parser.jay"
+{
+		var lt = (LocatedToken)yyVals[0+yyTop];
+		var variance = (VarianceDecl) yyVals[-1+yyTop];
+		yyVal = new TypeParameter (new MemberName (lt.Value, lt.Location), (Attributes)yyVals[-2+yyTop], variance);
+		if (variance != null)
+			lbag.AddLocation (yyVal, savedLocation);
+  	  }
+
+void case_384()
+#line 3169 "cs-parser.jay"
+{
+  	  	if (GetTokenName (yyToken) == "type")
+			report.Error (81, GetLocation (yyVals[0+yyTop]), "Type parameter declaration must be an identifier not a type");
+		else
+			Error_SyntaxError (yyToken);
+			
+  	  	yyVal = new TypeParameter (MemberName.Null, null, null);
+  	  }
+
+void case_393()
+#line 3213 "cs-parser.jay"
+{
+		report.Error (1536, GetLocation (yyVals[0+yyTop]), "Invalid parameter type `void'");
+		yyVal = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_396()
+#line 3229 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null) {
+			yyVal = new ComposedCast ((ATypeNameExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+		} else {
+			var sn = yyVals[-1+yyTop] as SimpleName;
+			if (sn != null && sn.Name == "var")
+				yyVal = new VarExpr (sn.Location);
+			else
+				yyVal = yyVals[-1+yyTop];
+		}
+	  }
+
+void case_399()
+#line 3249 "cs-parser.jay"
+{
+		Expression.Error_VoidInvalidInTheContext (GetLocation (yyVals[0+yyTop]), report);
+		yyVal = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_400()
+#line 3257 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null)
+			yyVal = new ComposedCast ((FullNamedExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+
+void case_403()
+#line 3273 "cs-parser.jay"
+{
+		var types = new List<FullNamedExpression> (2);
+		types.Add ((FullNamedExpression) yyVals[0+yyTop]);
+		yyVal = types;
+	  }
+
+void case_404()
+#line 3279 "cs-parser.jay"
+{
+		var types = (List<FullNamedExpression>) yyVals[-2+yyTop];
+		types.Add ((FullNamedExpression) yyVals[0+yyTop]);
+		lbag.AddLocation (types, GetLocation (yyVals[-1+yyTop]));
+		yyVal = types;
+	  }
+
+void case_405()
+#line 3289 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is ComposedCast) {
+			report.Error (1521, GetLocation (yyVals[0+yyTop]), "Invalid base type `{0}'", ((ComposedCast)yyVals[0+yyTop]).GetSignatureForError ());
+		}
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_443()
+#line 3353 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+	       yyVal = new CompletionSimpleName (MemberName.MakeName (lt.Value, null), lt.Location);
+	  }
+
+void case_454()
+#line 3394 "cs-parser.jay"
+{
+		yyVal = new ParenthesizedExpression ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_456()
+#line 3406 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_457()
+#line 3412 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		var ma = new MemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, (int) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (ma.TypeArguments, Lexer.GenericDimensionLocations);
+		yyVal = ma;
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_458()
+#line 3420 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation (yyVals[-3+yyTop]), "null propagating operator");
+
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new ConditionalMemberAccess ((Expression) yyVals[-4+yyTop], lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_459()
+#line 3429 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_460()
+#line 3435 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberAccess (new BaseThis (GetLocation (yyVals[-3+yyTop])), lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_461()
+#line 3441 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberAccess (new SimpleName ("await", ((LocatedToken) yyVals[-3+yyTop]).Location), lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_462()
+#line 3447 "cs-parser.jay"
+{
+		var lt1 = (LocatedToken) yyVals[-2+yyTop];
+		var lt2 = (LocatedToken) yyVals[-1+yyTop];
+
+		yyVal = new QualifiedAliasMember (lt1.Value, lt2.Value, (TypeArguments) yyVals[0+yyTop], lt1.Location);
+		lbag.AddLocation (yyVal, savedLocation, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_463()
+#line 3455 "cs-parser.jay"
+{
+		var lt1 = (LocatedToken) yyVals[-2+yyTop];
+		var lt2 = (LocatedToken) yyVals[-1+yyTop];
+		var qam = new QualifiedAliasMember (lt1.Value, lt2.Value, (int) yyVals[0+yyTop], lt1.Location);
+		lbag.AddLocation (qam.TypeArguments, Lexer.GenericDimensionLocations);
+		yyVal = qam;
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_465()
+#line 3466 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new CompletionMemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, lt.Location);
+	  }
+
+void case_467()
+#line 3474 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new CompletionMemberAccess ((Expression) yyVals[-3+yyTop], lt.Value, lt.Location);
+ 	  }
+
+void case_468()
+#line 3482 "cs-parser.jay"
+{
+		yyVal = new Invocation ((Expression) yyVals[-3+yyTop], (Arguments) yyVals[-1+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_469()
+#line 3487 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Invocation ((Expression) yyVals[-3+yyTop], (Arguments) yyVals[-1+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_470()
+#line 3494 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Invocation ((Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_473()
+#line 3509 "cs-parser.jay"
+{
+	  	if (yyVals[-1+yyTop] == null) {
+	  		yyVal = new CollectionOrObjectInitializers (GetLocation (yyVals[-2+yyTop]));
+	  	} else {
+	  		yyVal = new CollectionOrObjectInitializers ((List<Expression>) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  	}
+ 		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_474()
+#line 3518 "cs-parser.jay"
+{
+	  	yyVal = new CollectionOrObjectInitializers ((List<Expression>) yyVals[-2+yyTop], GetLocation (yyVals[-3+yyTop]));
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_477()
+#line 3534 "cs-parser.jay"
+{
+	  	var a = new List<Expression> ();
+	  	a.Add ((Expression) yyVals[0+yyTop]);
+	  	yyVal = a;
+	  }
+
+void case_478()
+#line 3540 "cs-parser.jay"
+{
+	  	var a = (List<Expression>)yyVals[-2+yyTop];
+	  	a.Add ((Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (a, GetLocation (yyVals[-1+yyTop]));
+	  	yyVal = a;
+	  }
+
+void case_479()
+#line 3546 "cs-parser.jay"
+{
+	  	Error_SyntaxError (yyToken);
+		yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_480()
+#line 3554 "cs-parser.jay"
+{
+	  	var lt = (LocatedToken) yyVals[-2+yyTop];
+	  	yyVal = new ElementInitializer (lt.Value, (Expression)yyVals[0+yyTop], lt.Location);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_481()
+#line 3560 "cs-parser.jay"
+{
+	  	var lt = (LocatedToken) Error_AwaitAsIdentifier (yyVals[-2+yyTop]);
+	  	yyVal = new ElementInitializer (lt.Value, (Expression)yyVals[0+yyTop], lt.Location);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_483()
+#line 3569 "cs-parser.jay"
+{
+		CompletionSimpleName csn = yyVals[-1+yyTop] as CompletionSimpleName;
+		if (csn == null)
+			yyVal = new CollectionElementInitializer ((Expression)yyVals[-1+yyTop]);
+		else
+			yyVal = new CompletionElementInitializer (csn.Prefix, csn.Location);
+	  }
+
+void case_484()
+#line 3577 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] == null)
+			yyVal = new CollectionElementInitializer (GetLocation (yyVals[-2+yyTop]));
+		else {
+	  		yyVal = new CollectionElementInitializer ((List<Expression>)yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+		}
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_485()
+#line 3587 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation (yyVals[-4+yyTop]), "dictionary initializer");
+
+		yyVal = new DictionaryElementInitializer ((List<Expression>)yyVals[-3+yyTop], (Expression) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_486()
+#line 3595 "cs-parser.jay"
+{
+	  	report.Error (1920, GetLocation (yyVals[-1+yyTop]), "An element initializer cannot be empty");
+		yyVal = new CollectionElementInitializer (GetLocation (yyVals[-1+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_491()
+#line 3614 "cs-parser.jay"
+{ 
+		Arguments list = new Arguments (4);
+		list.Add ((Argument) yyVals[0+yyTop]);
+		yyVal = list;
+	  }
+
+void case_492()
+#line 3620 "cs-parser.jay"
+{
+		Arguments list = (Arguments) yyVals[-2+yyTop];
+		if (list [list.Count - 1] is NamedArgument)
+			Error_NamedArgumentExpected ((NamedArgument) list [list.Count - 1]);
+		
+		list.Add ((Argument) yyVals[0+yyTop]);
+		lbag.AddLocation (list, GetLocation (yyVals[-1+yyTop]));
+		yyVal = list;
+	  }
+
+void case_493()
+#line 3630 "cs-parser.jay"
+{
+		Arguments list = (Arguments) yyVals[-2+yyTop];
+		NamedArgument a = (NamedArgument) yyVals[0+yyTop];
+		for (int i = 0; i < list.Count; ++i) {
+			NamedArgument na = list [i] as NamedArgument;
+			if (na != null && na.Name == a.Name)
+				report.Error (1740, na.Location, "Named argument `{0}' specified multiple times",
+					na.Name);
+		}
+		
+		list.Add (a);
+		lbag.AddLocation (list, GetLocation (yyVals[-1+yyTop]));
+		yyVal = list;
+	  }
+
+void case_494()
+#line 3645 "cs-parser.jay"
+{
+	  	if (lexer.putback_char == -1)
+	  		lexer.putback (')'); /* TODO: Wrong but what can I do*/
+		Error_SyntaxError (yyToken);
+		yyVal = yyVals[-2+yyTop];
+	  }
+
+void case_495()
+#line 3652 "cs-parser.jay"
+{
+	  	report.Error (839, GetLocation (yyVals[-1+yyTop]), "An argument is missing");
+	  	yyVal = null;
+	  }
+
+void case_500()
+#line 3673 "cs-parser.jay"
+{ 
+		yyVal = new Argument ((Expression) yyVals[0+yyTop], Argument.AType.Ref);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_501()
+#line 3678 "cs-parser.jay"
+{ 
+		yyVal = new Argument ((Expression) yyVals[0+yyTop], Argument.AType.Out);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_502()
+#line 3683 "cs-parser.jay"
+{
+		yyVal = new Argument (new Arglist ((Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop])));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_503()
+#line 3688 "cs-parser.jay"
+{
+		yyVal = new Argument (new Arglist (GetLocation (yyVals[-2+yyTop])));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_505()
+#line 3700 "cs-parser.jay"
+{
+		yyVal = new ElementAccess ((Expression) yyVals[-3+yyTop], (Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_506()
+#line 3705 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation (yyVals[-3+yyTop]), "null propagating operator");
+
+		yyVal = new ElementAccess ((Expression) yyVals[-4+yyTop], (Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop])) {
+			ConditionalAccess = true
+		};
+
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_507()
+#line 3716 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new ElementAccess ((Expression) yyVals[-3+yyTop], (Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_508()
+#line 3721 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new ElementAccess ((Expression) yyVals[-2+yyTop], null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_509()
+#line 3729 "cs-parser.jay"
+{
+		var list = new List<Expression> (4);
+		list.Add ((Expression) yyVals[0+yyTop]);
+		yyVal = list;
+	  }
+
+void case_510()
+#line 3735 "cs-parser.jay"
+{
+		var list = (List<Expression>) yyVals[-2+yyTop];
+		list.Add ((Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (list, GetLocation (yyVals[-1+yyTop]));
+		yyVal = list;
+	  }
+
+void case_511()
+#line 3745 "cs-parser.jay"
+{
+		Arguments args = new Arguments (4);
+		args.Add ((Argument) yyVals[0+yyTop]);
+		yyVal = args;
+	  }
+
+void case_512()
+#line 3751 "cs-parser.jay"
+{
+		Arguments args = (Arguments) yyVals[-2+yyTop];
+		if (args [args.Count - 1] is NamedArgument && !(yyVals[0+yyTop] is NamedArgument))
+			Error_NamedArgumentExpected ((NamedArgument) args [args.Count - 1]);
+	  
+		args.Add ((Argument) yyVals[0+yyTop]);
+		lbag.AddLocation (args, GetLocation (yyVals[-1+yyTop]));
+		yyVal = args;	  
+	  }
+
+void case_516()
+#line 3779 "cs-parser.jay"
+{
+	  	yyVal = new ElementAccess (new BaseThis (GetLocation (yyVals[-3+yyTop])), (Arguments) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_517()
+#line 3784 "cs-parser.jay"
+{
+	  	Error_SyntaxError (yyToken);
+		yyVal = new ElementAccess (null, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_520()
+#line 3806 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] != null) {
+			if (lang_version <= LanguageVersion.ISO_2)
+				FeatureIsNotAvailable (GetLocation (yyVals[-5+yyTop]), "object initializers");
+				
+			yyVal = new NewInitialize ((FullNamedExpression) yyVals[-4+yyTop], (Arguments) yyVals[-2+yyTop], (CollectionOrObjectInitializers) yyVals[0+yyTop], GetLocation (yyVals[-5+yyTop]));
+		} else {
+			yyVal = new New ((FullNamedExpression) yyVals[-4+yyTop], (Arguments) yyVals[-2+yyTop], GetLocation (yyVals[-5+yyTop]));
+		}
+		
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_521()
+#line 3819 "cs-parser.jay"
+{
+		if (lang_version <= LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "collection initializers");
+	  
+		yyVal = new NewInitialize ((FullNamedExpression) yyVals[-1+yyTop], null, (CollectionOrObjectInitializers) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_522()
+#line 3831 "cs-parser.jay"
+{
+		yyVal = new ArrayCreation ((FullNamedExpression) yyVals[-5+yyTop], (List<Expression>) yyVals[-3+yyTop],
+				new ComposedTypeSpecifier (((List<Expression>) yyVals[-3+yyTop]).Count, GetLocation (yyVals[-4+yyTop])) {
+	  				Next = (ComposedTypeSpecifier) yyVals[-1+yyTop]
+			  	}, (ArrayInitializer) yyVals[0+yyTop], GetLocation (yyVals[-6+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_523()
+#line 3839 "cs-parser.jay"
+{
+	  	if (yyVals[0+yyTop] == null)
+	  		report.Error (1586, GetLocation (yyVals[-3+yyTop]), "Array creation must have array size or array initializer");
+
+		yyVal = new ArrayCreation ((FullNamedExpression) yyVals[-2+yyTop], (ComposedTypeSpecifier) yyVals[-1+yyTop], (ArrayInitializer) yyVals[0+yyTop], GetLocation (yyVals[-3+yyTop]));
+	  }
+
+void case_524()
+#line 3846 "cs-parser.jay"
+{
+		if (lang_version <= LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "implicitly typed arrays");
+	  
+		yyVal = new ImplicitlyTypedArrayCreation ((ComposedTypeSpecifier) yyVals[-1+yyTop], (ArrayInitializer) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_525()
+#line 3853 "cs-parser.jay"
+{
+		report.Error (178, GetLocation (yyVals[-1+yyTop]), "Invalid rank specifier, expecting `,' or `]'");
+		yyVal = new ArrayCreation ((FullNamedExpression) yyVals[-5+yyTop], null, GetLocation (yyVals[-6+yyTop]));
+	  }
+
+void case_526()
+#line 3858 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		/* It can be any of new expression, create the most common one*/
+		yyVal = new New ((FullNamedExpression) yyVals[-1+yyTop], null, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_528()
+#line 3870 "cs-parser.jay"
+{
+		--lexer.parsing_type;
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_529()
+#line 3878 "cs-parser.jay"
+{
+		if (lang_version <= LanguageVersion.ISO_2)
+	  		FeatureIsNotAvailable (GetLocation (yyVals[-3+yyTop]), "anonymous types");
+
+		yyVal = new NewAnonymousType ((List<AnonymousTypeParameter>) yyVals[-1+yyTop], current_container, GetLocation (yyVals[-3+yyTop]));
+		
+		/* TODO: lbag comma location*/
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_535()
+#line 3905 "cs-parser.jay"
+{
+	  	var a = new List<AnonymousTypeParameter> (4);
+	  	a.Add ((AnonymousTypeParameter) yyVals[0+yyTop]);
+	  	yyVal = a;
+	  }
+
+void case_536()
+#line 3911 "cs-parser.jay"
+{
+	  	var a = (List<AnonymousTypeParameter>) yyVals[-2+yyTop];
+	  	a.Add ((AnonymousTypeParameter) yyVals[0+yyTop]);
+	  	lbag.AddLocation (a, GetLocation (yyVals[-1+yyTop]));
+
+	  	yyVal = a;
+	  }
+
+void case_539()
+#line 3930 "cs-parser.jay"
+{
+		var lt = (LocatedToken)yyVals[-2+yyTop];
+	  	yyVal = new AnonymousTypeParameter ((Expression)yyVals[0+yyTop], lt.Value, lt.Location);
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_540()
+#line 3936 "cs-parser.jay"
+{
+		var lt = (LocatedToken)yyVals[0+yyTop];
+	  	yyVal = new AnonymousTypeParameter (new SimpleName (lt.Value, lt.Location),
+	  		lt.Value, lt.Location);
+	  }
+
+void case_541()
+#line 3942 "cs-parser.jay"
+{
+	  	MemberAccess ma = (MemberAccess) yyVals[0+yyTop];
+	  	yyVal = new AnonymousTypeParameter (ma, ma.Name, ma.Location);
+	  }
+
+void case_542()
+#line 3947 "cs-parser.jay"
+{
+		report.Error (746, lexer.Location,
+			"Invalid anonymous type member declarator. Anonymous type members must be a member assignment, simple name or member access expression");
+		yyVal = null;
+	  }
+
+void case_546()
+#line 3962 "cs-parser.jay"
+{
+	  	((ComposedTypeSpecifier) yyVals[-1+yyTop]).Next = (ComposedTypeSpecifier) yyVals[0+yyTop];
+	  	yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_547()
+#line 3970 "cs-parser.jay"
+{
+		yyVal = ComposedTypeSpecifier.CreateArrayDimension (1, GetLocation (yyVals[-1+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_548()
+#line 3975 "cs-parser.jay"
+{
+		yyVal = ComposedTypeSpecifier.CreateArrayDimension ((int)yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_553()
+#line 4005 "cs-parser.jay"
+{
+		var ai = new ArrayInitializer (0, GetLocation (yyVals[-1+yyTop]));
+		ai.VariableDeclaration = current_variable;
+		lbag.AddLocation (ai, GetLocation (yyVals[0+yyTop]));
+		yyVal = ai;
+	  }
+
+void case_554()
+#line 4012 "cs-parser.jay"
+{
+		var ai = new ArrayInitializer ((List<Expression>) yyVals[-2+yyTop], GetLocation (yyVals[-3+yyTop]));
+		ai.VariableDeclaration = current_variable;
+		if (yyVals[-1+yyTop] != null) {
+			lbag.AddLocation (ai, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+		} else {
+			lbag.AddLocation (ai, GetLocation (yyVals[0+yyTop]));
+		}
+		yyVal = ai;
+	  }
+
+void case_555()
+#line 4026 "cs-parser.jay"
+{
+		var list = new List<Expression> (4);
+		list.Add ((Expression) yyVals[0+yyTop]);
+		yyVal = list;
+	  }
+
+void case_556()
+#line 4032 "cs-parser.jay"
+{
+		var list = (List<Expression>) yyVals[-2+yyTop];
+		list.Add ((Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (list, GetLocation (yyVals[-1+yyTop]));
+		yyVal = list;
+	  }
+
+void case_557()
+#line 4042 "cs-parser.jay"
+{
+		yyVal = new TypeOf ((FullNamedExpression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_559()
+#line 4051 "cs-parser.jay"
+{
+	 	Error_TypeExpected (lexer.Location);
+	 	yyVal = null;
+	 }
+
+void case_560()
+#line 4059 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[0+yyTop]), "generics");
+
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_561()
+#line 4069 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		if (lang_version == LanguageVersion.ISO_1)
+			FeatureIsNotAvailable (lt.Location, "namespace alias qualifier");
+		savedLocation = GetLocation (yyVals[0+yyTop]);
+		yyVal = lt;		
+	  }
+
+void case_562()
+#line 4080 "cs-parser.jay"
+{ 
+		yyVal = new SizeOf ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_563()
+#line 4085 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new SizeOf ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_564()
+#line 4095 "cs-parser.jay"
+{
+		yyVal = new CheckedExpr ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_565()
+#line 4100 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new CheckedExpr (null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_566()
+#line 4109 "cs-parser.jay"
+{
+		yyVal = new UnCheckedExpr ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_567()
+#line 4114 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new UnCheckedExpr (null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_568()
+#line 4123 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberAccess (new Indirection ((Expression) yyVals[-3+yyTop], GetLocation (yyVals[-2+yyTop])), lt.Value, (TypeArguments) yyVals[0+yyTop], lt.Location);
+	  }
+
+void case_570()
+#line 4135 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		if ((ParametersCompiled) yyVals[-2+yyTop] != ParametersCompiled.Undefined) {
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-3+yyTop]), PopLocation (), PopLocation ());
+		} else {
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-3+yyTop]));
+		}
+	  }
+
+void case_572()
+#line 4148 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		
+		if ((ParametersCompiled) yyVals[-2+yyTop] != ParametersCompiled.Undefined) {
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-3+yyTop]), PopLocation (), PopLocation ());
+		} else {
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-3+yyTop]));
+		}
+	  }
+
+void case_576()
+#line 4173 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+	  	yyVal = yyVals[-1+yyTop];
+	  	PushLocation (GetLocation (yyVals[-1+yyTop]));
+	  	PushLocation (GetLocation (yyVals[-3+yyTop]));
+	  }
+
+void case_577()
+#line 4183 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-3+yyTop]), "default value expression");
+
+		yyVal = new DefaultValueExpression ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_581()
+#line 4203 "cs-parser.jay"
+{
+		yyVal = new Cast ((FullNamedExpression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_582()
+#line 4208 "cs-parser.jay"
+{
+		if (!async_block) {
+			 if (current_anonymous_method is LambdaExpression) {
+				report.Error (4034, GetLocation (yyVals[-1+yyTop]),
+					"The `await' operator can only be used when its containing lambda expression is marked with the `async' modifier");
+			} else if (current_anonymous_method != null) {
+				report.Error (4035, GetLocation (yyVals[-1+yyTop]),
+					"The `await' operator can only be used when its containing anonymous method is marked with the `async' modifier");
+			} else if (interactive_async != null) {
+				current_block.Explicit.RegisterAsyncAwait ();
+				interactive_async = true;
+			} else {
+				report.Error (4033, GetLocation (yyVals[-1+yyTop]),
+					"The `await' operator can only be used when its containing method is marked with the `async' modifier");
+			}
+		} else {
+			current_block.Explicit.RegisterAsyncAwait ();
+		}
+		
+		yyVal = new Await ((Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_583()
+#line 4230 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Unary (Unary.Operator.LogicalNot, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_584()
+#line 4236 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Unary (Unary.Operator.OnesComplement, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_585()
+#line 4242 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Cast ((FullNamedExpression) yyVals[-2+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_586()
+#line 4249 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Await (null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_594()
+#line 4287 "cs-parser.jay"
+{ 
+		Error_SyntaxError (yyToken);
+
+	  	yyVal = new Unary (Unary.Operator.UnaryPlus, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_595()
+#line 4293 "cs-parser.jay"
+{ 
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Unary (Unary.Operator.UnaryNegation, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_596()
+#line 4299 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new UnaryMutator (UnaryMutator.Mode.PreIncrement, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_597()
+#line 4305 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new UnaryMutator (UnaryMutator.Mode.PreDecrement, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_598()
+#line 4311 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Indirection (null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_599()
+#line 4317 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Unary (Unary.Operator.AddressOf, null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_601()
+#line 4327 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Multiply, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_602()
+#line 4332 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Division, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_603()
+#line 4337 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Modulus, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_604()
+#line 4342 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Multiply, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_605()
+#line 4349 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Division, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_606()
+#line 4356 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Modulus, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_608()
+#line 4367 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Addition, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_609()
+#line 4372 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Subtraction, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_610()
+#line 4377 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Addition, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_611()
+#line 4384 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Subtraction, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_613()
+#line 4395 "cs-parser.jay"
+{
+		var is_expr = new Is ((Expression) yyVals[-3+yyTop], (Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		if (yyVals[0+yyTop] != null) {
+			if (lang_version != LanguageVersion.Experimental)
+				FeatureIsNotAvailable (GetLocation (yyVals[0+yyTop]), "type pattern matching");
+
+			var lt = (LocatedToken) yyVals[0+yyTop];
+			is_expr.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+			current_block.AddLocalName (is_expr.Variable);
+		}
+
+		yyVal = is_expr;
+	  }
+
+void case_614()
+#line 4409 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new As ((Expression) yyVals[-2+yyTop], null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_615()
+#line 4415 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Is ((Expression) yyVals[-2+yyTop], null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_616()
+#line 4421 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new Is (new SimpleName (lt.Value, lt.Location), (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_617()
+#line 4426 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new As (new SimpleName (lt.Value, lt.Location), (Expression) yyVals[0+yyTop], GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_619()
+#line 4435 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] is VarExpr)
+			yyVals[-1+yyTop] = new SimpleName ("var", ((VarExpr) yyVals[-1+yyTop]).Location);
+
+		yyVal = new ComposedCast ((FullNamedExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+
+void case_623()
+#line 4454 "cs-parser.jay"
+{
+		Expression expr = (Expression) yyVals[-1+yyTop];
+		if (yyVals[0+yyTop] == null) {
+			SimpleName sn = expr as SimpleName;
+			if (sn != null && sn.Name == "var")
+				yyVal = new VarExpr (sn.Location);
+			else
+				yyVal = yyVals[-1+yyTop];
+		} else if (expr is ATypeNameExpression) {
+			yyVal = new ComposedCast ((ATypeNameExpression)expr, (ComposedTypeSpecifier) yyVals[0+yyTop]);
+		} else {
+			Error_ExpectingTypeName (expr);
+			yyVal = null;
+		}
+	  }
+
+void case_624()
+#line 4470 "cs-parser.jay"
+{
+		ATypeNameExpression expr = yyVals[-1+yyTop] as ATypeNameExpression;
+
+		if (expr != null) {
+			yyVal = new ComposedCast (expr, (ComposedTypeSpecifier) yyVals[0+yyTop]);
+		} else {
+			Error_ExpectingTypeName ((Expression)yyVals[-1+yyTop]);
+			yyVal = expr;
+		}
+	  }
+
+void case_628()
+#line 4487 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.LeftShift, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_629()
+#line 4492 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.RightShift, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_630()
+#line 4497 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.LeftShift, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_631()
+#line 4504 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.RightShift, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_633()
+#line 4515 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.LessThan, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_634()
+#line 4520 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.GreaterThan, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_635()
+#line 4525 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.LessThanOrEqual, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_636()
+#line 4530 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.GreaterThanOrEqual, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_637()
+#line 4535 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.LessThan, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_638()
+#line 4542 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.GreaterThan, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_639()
+#line 4549 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.LessThanOrEqual, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_640()
+#line 4556 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.GreaterThanOrEqual, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_642()
+#line 4567 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Equality, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_643()
+#line 4572 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.Inequality, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_644()
+#line 4577 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Equality, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_645()
+#line 4584 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.Inequality, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_647()
+#line 4595 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.BitwiseAnd, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_648()
+#line 4600 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.BitwiseAnd, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_650()
+#line 4611 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.ExclusiveOr, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_651()
+#line 4616 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.ExclusiveOr, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_653()
+#line 4627 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.BitwiseOr, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_654()
+#line 4632 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.BitwiseOr, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_656()
+#line 4643 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.LogicalAnd, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_657()
+#line 4648 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.LogicalAnd, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_659()
+#line 4659 "cs-parser.jay"
+{
+		yyVal = new Binary (Binary.Operator.LogicalOr, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_660()
+#line 4664 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Binary (Binary.Operator.LogicalOr, (Expression) yyVals[-2+yyTop], null);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_662()
+#line 4675 "cs-parser.jay"
+{
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation (yyVals[-1+yyTop]), "null coalescing operator");
+			
+		yyVal = new Nullable.NullCoalescingOperator ((Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_664()
+#line 4687 "cs-parser.jay"
+{
+		yyVal = new Conditional (new BooleanExpression ((Expression) yyVals[-4+yyTop]), (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_665()
+#line 4692 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Conditional (new BooleanExpression ((Expression) yyVals[-3+yyTop]), (Expression) yyVals[-1+yyTop], null, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_666()
+#line 4698 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Conditional (new BooleanExpression ((Expression) yyVals[-4+yyTop]), (Expression) yyVals[-2+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_667()
+#line 4705 "cs-parser.jay"
+{
+		Error_SyntaxError (Token.CLOSE_BRACE);
+
+		yyVal = new Conditional (new BooleanExpression ((Expression) yyVals[-4+yyTop]), (Expression) yyVals[-2+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+		lexer.putback ('}');
+	  }
+
+void case_668()
+#line 4716 "cs-parser.jay"
+{
+		yyVal = new SimpleAssign ((Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_669()
+#line 4721 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.Multiply, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_670()
+#line 4726 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.Division, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_671()
+#line 4731 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.Modulus, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_672()
+#line 4736 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.Addition, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_673()
+#line 4741 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.Subtraction, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_674()
+#line 4746 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.LeftShift, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_675()
+#line 4751 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.RightShift, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_676()
+#line 4756 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.BitwiseAnd, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_677()
+#line 4761 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.BitwiseOr, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_678()
+#line 4766 "cs-parser.jay"
+{
+		yyVal = new CompoundAssign (Binary.Operator.ExclusiveOr, (Expression) yyVals[-2+yyTop], (Expression) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_679()
+#line 4774 "cs-parser.jay"
+{
+		var pars = new List<Parameter> (4);
+		pars.Add ((Parameter) yyVals[0+yyTop]);
+		parameterListCommas.Clear ();
+		yyVal = pars;
+	  }
+
+void case_680()
+#line 4781 "cs-parser.jay"
+{
+		var pars = (List<Parameter>) yyVals[-2+yyTop];
+		Parameter p = (Parameter)yyVals[0+yyTop];
+		if (pars[0].GetType () != p.GetType ()) {
+			report.Error (748, p.Location, "All lambda parameters must be typed either explicitly or implicitly");
+		}
+		
+		pars.Add (p);
+		parameterListCommas.Add (GetLocation (yyVals[-1+yyTop]));
+
+		yyVal = pars;
+	  }
+
+void case_681()
+#line 4797 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+
+		yyVal = new Parameter ((FullNamedExpression) yyVals[-1+yyTop], lt.Value, (Parameter.Modifier) yyVals[-2+yyTop], null, lt.Location);
+	  }
+
+void case_682()
+#line 4803 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+
+		yyVal = new Parameter ((FullNamedExpression) yyVals[-1+yyTop], lt.Value, Parameter.Modifier.NONE, null, lt.Location);
+	  }
+
+void case_683()
+#line 4809 "cs-parser.jay"
+{
+	  	var lt = (LocatedToken) yyVals[0+yyTop];
+		yyVal = new ImplicitLambdaParameter (lt.Value, lt.Location);
+	  }
+
+void case_684()
+#line 4814 "cs-parser.jay"
+{
+	  	var lt = (LocatedToken) Error_AwaitAsIdentifier (yyVals[0+yyTop]);
+		yyVal = new ImplicitLambdaParameter (lt.Value, lt.Location);
+	  }
+
+void case_686()
+#line 4822 "cs-parser.jay"
+{ 
+		var pars_list = (List<Parameter>) yyVals[0+yyTop];
+		yyVal = new ParametersCompiled (pars_list.ToArray ());
+		lbag.AddLocation (yyVal, parameterListCommas);
+	  }
+
+void case_688()
+#line 4834 "cs-parser.jay"
+{
+		Block b = end_block (Location.Null);
+		b.IsCompilerGenerated = true;
+		b.AddStatement (new ContextualReturn ((Expression) yyVals[0+yyTop]));
+		yyVal = b;
+	  }
+
+void case_690()
+#line 4842 "cs-parser.jay"
+{
+	  	/* Handles only cases like foo = x.FirstOrDefault (l => );*/
+	  	/* where we must restore current_variable*/
+		Block b = end_block (Location.Null);
+		b.IsCompilerGenerated = true;
+
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	  }
+
+void case_692()
+#line 4856 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	  }
+
+void case_693()
+#line 4864 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];	
+		Parameter p = new ImplicitLambdaParameter (lt.Value, lt.Location);
+		start_anonymous (true, new ParametersCompiled (p), false, lt.Location);
+	  }
+
+void case_694()
+#line 4870 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_695()
+#line 4875 "cs-parser.jay"
+{
+		var lt = (LocatedToken) Error_AwaitAsIdentifier (yyVals[-1+yyTop]);
+		Parameter p = new ImplicitLambdaParameter (lt.Value, lt.Location);
+		start_anonymous (true, new ParametersCompiled (p), false, lt.Location);
+	  }
+
+void case_696()
+#line 4881 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_697()
+#line 4886 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		Parameter p = new ImplicitLambdaParameter (lt.Value, lt.Location);
+		start_anonymous (true, new ParametersCompiled (p), true, lt.Location);
+	  }
+
+void case_698()
+#line 4892 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_700()
+#line 4901 "cs-parser.jay"
+{
+	  	valid_param_mod = 0;
+		start_anonymous (true, (ParametersCompiled) yyVals[-2+yyTop], false, GetLocation (yyVals[-4+yyTop]));
+	  }
+
+void case_701()
+#line 4906 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_703()
+#line 4915 "cs-parser.jay"
+{
+	  	valid_param_mod = 0;
+		start_anonymous (true, (ParametersCompiled) yyVals[-2+yyTop], true, GetLocation (yyVals[-5+yyTop]));
+	  }
+
+void case_704()
+#line 4920 "cs-parser.jay"
+{
+		yyVal = end_anonymous ((ParametersBlock) yyVals[0+yyTop]);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-7+yyTop]), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_711()
+#line 4943 "cs-parser.jay"
+{
+		yyVal = new RefValueExpr ((Expression) yyVals[-3+yyTop], (FullNamedExpression) yyVals[-1+yyTop], GetLocation (yyVals[-5+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_712()
+#line 4948 "cs-parser.jay"
+{
+		yyVal = new RefTypeExpr ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_713()
+#line 4953 "cs-parser.jay"
+{
+		yyVal = new MakeRefExpr ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));	  
+	  }
+
+void case_718()
+#line 4980 "cs-parser.jay"
+{
+		yyVal = yyVals[-1+yyTop];
+
+		/* Cannot use opt_formal_parameter_list because it can be shared instance for empty parameters*/
+	  	lbag.AppendToMember (current_container, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation (yyVals[-2+yyTop]), "primary constructor");
+	  }
+
+void case_723()
+#line 5009 "cs-parser.jay"
+{
+		++lexer.parsing_block;
+		current_type.PrimaryConstructorBaseArgumentsStart = GetLocation (yyVals[0+yyTop]);
+	  }
+
+void case_724()
+#line 5014 "cs-parser.jay"
+{
+		lbag.AppendToMember (current_container, GetLocation (yyVals[0+yyTop]));
+		current_type.PrimaryConstructorBaseArguments = (Arguments) yyVals[-1+yyTop];
+		--lexer.parsing_block;
+
+		yyVal = yyVals[-5+yyTop];
+	  }
+
+void case_726()
+#line 5034 "cs-parser.jay"
+{
+		lexer.ConstraintsParsing = true;
+
+		Class c = new Class (current_container, (MemberName) yyVals[0+yyTop], (Modifiers) yyVals[-4+yyTop], (Attributes) yyVals[-5+yyTop]);
+		if (((c.ModFlags & Modifiers.STATIC) != 0) && lang_version == LanguageVersion.ISO_1) {
+			FeatureIsNotAvailable (c.Location, "static classes");
+		}
+			
+		push_current_container (c, yyVals[-3+yyTop]);
+		lbag.AddMember (current_container, GetModifierLocations (), GetLocation (yyVals[-2+yyTop]));
+		valid_param_mod = ParameterModifierType.PrimaryConstructor;
+	  }
+
+void case_727()
+#line 5048 "cs-parser.jay"
+{
+		valid_param_mod = 0;
+		lexer.ConstraintsParsing = false;
+
+		if (yyVals[-1+yyTop] != null)
+			current_type.PrimaryConstructorParameters = (ParametersCompiled) yyVals[-1+yyTop];
+
+		if (yyVals[0+yyTop] != null)
+			current_container.SetConstraints ((List<Constraints>) yyVals[0+yyTop]);
+
+		if (doc_support) {
+			current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		lexer.parsing_modifiers = true;
+	  }
+
+void case_728()
+#line 5066 "cs-parser.jay"
+{
+		--lexer.parsing_declaration;
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+
+void case_729()
+#line 5072 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] == null) {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		} else {
+			lbag.AppendToMember (current_container, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+		yyVal = pop_current_class ();
+	  }
+
+void case_732()
+#line 5091 "cs-parser.jay"
+{
+	    mod_locations = null;
+		yyVal = ModifierNone;
+		lexer.parsing_modifiers = false;
+	  }
+
+void case_735()
+#line 5105 "cs-parser.jay"
+{ 
+		var m1 = (Modifiers) yyVals[-1+yyTop];
+		var m2 = (Modifiers) yyVals[0+yyTop];
+
+		if ((m1 & m2) != 0) {
+			report.Error (1004, lexer.Location - ModifiersExtensions.Name (m2).Length,
+				"Duplicate `{0}' modifier", ModifiersExtensions.Name (m2));
+		} else if ((m2 & Modifiers.AccessibilityMask) != 0 && (m1 & Modifiers.AccessibilityMask) != 0 &&
+			((m2 | m1 & Modifiers.AccessibilityMask) != (Modifiers.PROTECTED | Modifiers.INTERNAL))) {
+			report.Error (107, lexer.Location - ModifiersExtensions.Name (m2).Length,
+				"More than one protection modifier specified");
+		}
+		
+		yyVal = m1 | m2;
+	  }
+
+void case_736()
+#line 5124 "cs-parser.jay"
+{
+		yyVal = Modifiers.NEW;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+		
+		if (current_container.Kind == MemberKind.Namespace)
+			report.Error (1530, GetLocation (yyVals[0+yyTop]), "Keyword `new' is not allowed on namespace elements");
+	  }
+
+void case_737()
+#line 5132 "cs-parser.jay"
+{
+		yyVal = Modifiers.PUBLIC;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_738()
+#line 5137 "cs-parser.jay"
+{
+		yyVal = Modifiers.PROTECTED;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_739()
+#line 5142 "cs-parser.jay"
+{
+		yyVal = Modifiers.INTERNAL;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_740()
+#line 5147 "cs-parser.jay"
+{
+		yyVal = Modifiers.PRIVATE;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_741()
+#line 5152 "cs-parser.jay"
+{
+		yyVal = Modifiers.ABSTRACT;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_742()
+#line 5157 "cs-parser.jay"
+{
+		yyVal = Modifiers.SEALED;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_743()
+#line 5162 "cs-parser.jay"
+{
+		yyVal = Modifiers.STATIC;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_744()
+#line 5167 "cs-parser.jay"
+{
+		yyVal = Modifiers.READONLY;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_745()
+#line 5172 "cs-parser.jay"
+{
+		yyVal = Modifiers.VIRTUAL;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_746()
+#line 5177 "cs-parser.jay"
+{
+		yyVal = Modifiers.OVERRIDE;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_747()
+#line 5182 "cs-parser.jay"
+{
+		yyVal = Modifiers.EXTERN;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_748()
+#line 5187 "cs-parser.jay"
+{
+		yyVal = Modifiers.VOLATILE;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_749()
+#line 5192 "cs-parser.jay"
+{
+		yyVal = Modifiers.UNSAFE;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+		if (!settings.Unsafe)
+			Error_UnsafeCodeNotAllowed (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_750()
+#line 5199 "cs-parser.jay"
+{
+		yyVal = Modifiers.ASYNC;
+		StoreModifierLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_753()
+#line 5212 "cs-parser.jay"
+{
+		current_type.SetBaseTypes ((List<FullNamedExpression>) yyVals[0+yyTop]);
+		lbag.AppendToMember (current_type, GetLocation (yyVals[-1+yyTop]));
+	 }
+
+void case_754()
+#line 5217 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		current_type.SetBaseTypes ((List<FullNamedExpression>) yyVals[-1+yyTop]);
+	  }
+
+void case_757()
+#line 5234 "cs-parser.jay"
+{
+		var constraints = new List<Constraints> (1);
+		constraints.Add ((Constraints) yyVals[0+yyTop]);
+		yyVal = constraints;
+	  }
+
+void case_758()
+#line 5240 "cs-parser.jay"
+{
+		var constraints = (List<Constraints>) yyVals[-1+yyTop];
+		Constraints new_constraint = (Constraints)yyVals[0+yyTop];
+
+		foreach (Constraints c in constraints) {
+			if (new_constraint.TypeParameter.Value == c.TypeParameter.Value) {
+				report.Error (409, new_constraint.Location,
+					"A constraint clause has already been specified for type parameter `{0}'",
+					new_constraint.TypeParameter.Value);
+			}
+		}
+
+		constraints.Add (new_constraint);
+		yyVal = constraints;
+	  }
+
+void case_759()
+#line 5259 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		yyVal = new Constraints (new SimpleMemberName (lt.Value, lt.Location), (List<FullNamedExpression>) yyVals[0+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_760()
+#line 5265 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new Constraints (new SimpleMemberName (lt.Value, lt.Location), null, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_761()
+#line 5275 "cs-parser.jay"
+{
+		var constraints = new List<FullNamedExpression> (1);
+		constraints.Add ((FullNamedExpression) yyVals[0+yyTop]);
+		yyVal = constraints;
+	  }
+
+void case_762()
+#line 5281 "cs-parser.jay"
+{
+		var constraints = (List<FullNamedExpression>) yyVals[-2+yyTop];
+		var prev = constraints [constraints.Count - 1] as SpecialContraintExpr;
+		if (prev != null && (prev.Constraint & SpecialConstraint.Constructor) != 0) {			
+			report.Error (401, GetLocation (yyVals[-1+yyTop]), "The `new()' constraint must be the last constraint specified");
+		}
+		
+		prev = yyVals[0+yyTop] as SpecialContraintExpr;
+		if (prev != null) {
+			if ((prev.Constraint & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0) {
+				report.Error (449, prev.Location, "The `class' or `struct' constraint must be the first constraint specified");			
+			} else {
+			 	prev = constraints [0] as SpecialContraintExpr;
+			 	if (prev != null && (prev.Constraint & SpecialConstraint.Struct) != 0) {			
+					report.Error (451, GetLocation (yyVals[0+yyTop]), "The `new()' constraint cannot be used with the `struct' constraint");
+				}
+			}
+		}
+
+		constraints.Add ((FullNamedExpression) yyVals[0+yyTop]);
+		lbag.AddLocation (constraints, GetLocation (yyVals[-1+yyTop]));
+		yyVal = constraints;
+	  }
+
+void case_763()
+#line 5308 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is ComposedCast)
+			report.Error (706, GetLocation (yyVals[0+yyTop]), "Invalid constraint type `{0}'", ((ComposedCast)yyVals[0+yyTop]).GetSignatureForError ());
+	  
+	  	yyVal = yyVals[0+yyTop];
+	  }
+
+void case_764()
+#line 5315 "cs-parser.jay"
+{
+		yyVal = new SpecialContraintExpr (SpecialConstraint.Constructor, GetLocation (yyVals[-2+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_768()
+#line 5335 "cs-parser.jay"
+{
+		if (lang_version <= LanguageVersion.V_3)
+			FeatureIsNotAvailable (lexer.Location, "generic type variance");
+		
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_769()
+#line 5345 "cs-parser.jay"
+{
+		yyVal = new VarianceDecl (Variance.Covariant, GetLocation (yyVals[0+yyTop]));
+		savedLocation = GetLocation (yyVals[0+yyTop]);
+	  }
+
+void case_770()
+#line 5350 "cs-parser.jay"
+{
+		yyVal = new VarianceDecl (Variance.Contravariant, GetLocation (yyVals[0+yyTop]));
+		savedLocation = GetLocation (yyVals[0+yyTop]);
+	  }
+
+void case_771()
+#line 5371 "cs-parser.jay"
+{
+		++lexer.parsing_block;
+		start_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_773()
+#line 5383 "cs-parser.jay"
+{
+	 	--lexer.parsing_block;
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_774()
+#line 5388 "cs-parser.jay"
+{
+	 	--lexer.parsing_block;
+		yyVal = end_block (lexer.Location);
+	  }
+
+void case_775()
+#line 5397 "cs-parser.jay"
+{
+		++lexer.parsing_block;
+		current_block.StartLocation = GetLocation (yyVals[0+yyTop]);
+	  }
+
+void case_776()
+#line 5402 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_777()
+#line 5406 "cs-parser.jay"
+{
+		report.Error (1525, GetLocation (yyVals[0+yyTop]), "Unexpected symbol '}', expected '{'");
+		lexer.putback ('}');
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_778()
+#line 5415 "cs-parser.jay"
+{
+		++lexer.parsing_block;
+		current_block.StartLocation = GetLocation (yyVals[0+yyTop]);
+	  }
+
+void case_779()
+#line 5420 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_787()
+#line 5448 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		var lt =(LocatedToken) yyVals[-1+yyTop];
+		var sn = new SimpleName (lt.Value, lt.Location);
+		current_block.AddStatement(new StatementErrorExpression (sn));
+		yyVal = null;
+	}
+
+void case_788()
+#line 5457 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	  }
+
+void case_821()
+#line 5521 "cs-parser.jay"
+{
+		  report.Error (1023, GetLocation (yyVals[0+yyTop]), "An embedded statement may not be a declaration or labeled statement");
+		  yyVal = null;
+	  }
+
+void case_822()
+#line 5526 "cs-parser.jay"
+{
+		  report.Error (1023, GetLocation (yyVals[0+yyTop]), "An embedded statement may not be a declaration or labeled statement");
+		  yyVal = null;
+	  }
+
+void case_823()
+#line 5531 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_824()
+#line 5539 "cs-parser.jay"
+{
+		/* Uses lexer.Location because semicolon location is not kept in quick mode*/
+		yyVal = new EmptyStatement (lexer.Location);
+	  }
+
+void case_825()
+#line 5547 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		LabeledStatement labeled = new LabeledStatement (lt.Value, current_block, lt.Location);
+		lbag.AddLocation (labeled, GetLocation (yyVals[0+yyTop]));
+		current_block.AddLabel (labeled);
+		current_block.AddStatement (labeled);
+	  }
+
+void case_828()
+#line 5560 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] is VarExpr)
+			yyVals[-1+yyTop] = new SimpleName ("var", ((VarExpr) yyVals[-1+yyTop]).Location);
+	  
+		yyVal = new ComposedCast ((FullNamedExpression) yyVals[-1+yyTop], (ComposedTypeSpecifier) yyVals[0+yyTop]);
+	  }
+
+void case_829()
+#line 5576 "cs-parser.jay"
+{ 
+		/* Ok, the above "primary_expression" is there to get rid of*/
+		/* both reduce/reduce and shift/reduces in the grammar, it should*/
+		/* really just be "type_name".  If you use type_name, a reduce/reduce*/
+		/* creeps up.  If you use namespace_or_type_name (which is all we need*/
+		/* really) two shift/reduces appear.*/
+		/* */
+
+		/* So the super-trick is that primary_expression*/
+		/* can only be either a SimpleName or a MemberAccess. */
+		/* The MemberAccess case arises when you have a fully qualified type-name like :*/
+		/* Foo.Bar.Blah i;*/
+		/* SimpleName is when you have*/
+		/* Blah i;*/
+		
+		Expression expr = (Expression) yyVals[-1+yyTop];
+		if (yyVals[0+yyTop] == null) {
+			SimpleName sn = expr as SimpleName;
+			if (sn != null && sn.Name == "var")
+				yyVal = new VarExpr (sn.Location);
+			else
+				yyVal = yyVals[-1+yyTop];
+		} else if (expr is ATypeNameExpression) {
+			yyVal = new ComposedCast ((ATypeNameExpression)expr, (ComposedTypeSpecifier) yyVals[0+yyTop]);
+		} else {
+			Error_ExpectingTypeName (expr);
+			yyVal = null;
+		}
+	  }
+
+void case_830()
+#line 5606 "cs-parser.jay"
+{
+		ATypeNameExpression expr = yyVals[-1+yyTop] as ATypeNameExpression;
+
+		if (expr != null) {
+			yyVal = new ComposedCast (expr, (ComposedTypeSpecifier) yyVals[0+yyTop]);
+		} else {
+			Error_ExpectingTypeName ((Expression)yyVals[-1+yyTop]);
+			yyVal = expr;
+		}
+	  }
+
+void case_834()
+#line 5623 "cs-parser.jay"
+{
+	  	((ComposedTypeSpecifier) yyVals[-1+yyTop]).Next = (ComposedTypeSpecifier) yyVals[0+yyTop];
+	  	yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_838()
+#line 5646 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new BlockVariable ((FullNamedExpression) yyVals[-1+yyTop], li);
+	  }
+
+void case_839()
+#line 5653 "cs-parser.jay"
+{
+		yyVal = current_variable;
+		current_variable = null;
+		if (yyVals[-2+yyTop] != null)
+			lbag.AddLocation (yyVal, PopLocation (), GetLocation (yyVals[0+yyTop]));
+		else
+			lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_840()
+#line 5662 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.Constant, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new BlockConstant ((FullNamedExpression) yyVals[-1+yyTop], li);
+	  }
+
+void case_841()
+#line 5669 "cs-parser.jay"
+{
+		if (current_variable.Initializer != null) {
+			lbag.AddLocation (current_variable, GetLocation (yyVals[-6+yyTop]), savedLocation, GetLocation (yyVals[0+yyTop]));
+		} else {
+			lbag.AddLocation (current_variable, GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[0+yyTop]));
+		}
+		yyVal = current_variable;;
+		current_variable = null;
+	  }
+
+void case_843()
+#line 5682 "cs-parser.jay"
+{
+		/* Redundant, but wont regress*/
+		report.Error (1525, lexer.Location, "Unexpected symbol }");
+		lexer.putback ('}');
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_845()
+#line 5693 "cs-parser.jay"
+{
+		current_variable.Initializer = (Expression) yyVals[0+yyTop];
+		PushLocation (GetLocation (yyVals[-1+yyTop]));
+		yyVal = current_variable;
+	  }
+
+void case_846()
+#line 5699 "cs-parser.jay"
+{
+	  	if (yyToken == Token.OPEN_BRACKET_EXPR) {
+			report.Error (650, lexer.Location,
+				"Syntax error, bad array declarator. To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type");
+		} else {
+			Error_SyntaxError (yyToken);
+		}
+	  }
+
+void case_850()
+#line 5717 "cs-parser.jay"
+{
+		foreach (var d in current_variable.Declarators) {
+			if (d.Initializer == null)
+				Error_MissingInitializer (d.Variable.Location);
+		}
+	  }
+
+void case_853()
+#line 5732 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];	  
+		var li = new LocalVariable (current_variable.Variable, lt.Value, lt.Location);
+		var d = new BlockVariableDeclarator (li, null);
+		current_variable.AddDeclarator (d);
+		current_block.AddLocalName (li);
+	  	lbag.AddLocation (d, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_854()
+#line 5741 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];	  
+		var li = new LocalVariable (current_variable.Variable, lt.Value, lt.Location);
+		var d = new BlockVariableDeclarator (li, (Expression) yyVals[0+yyTop]);
+		current_variable.AddDeclarator (d);
+		current_block.AddLocalName (li);
+	  	lbag.AddLocation (d, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_856()
+#line 5757 "cs-parser.jay"
+{
+		savedLocation = GetLocation (yyVals[-1+yyTop]);
+		current_variable.Initializer = (Expression) yyVals[0+yyTop];
+	  }
+
+void case_861()
+#line 5775 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];	  
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.Constant, lt.Location);
+		var d = new BlockVariableDeclarator (li, (Expression) yyVals[0+yyTop]);
+		current_variable.AddDeclarator (d);
+		current_block.AddLocalName (li);
+	  	lbag.AddLocation (d, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_863()
+#line 5788 "cs-parser.jay"
+{
+		yyVal = new StackAlloc ((Expression) yyVals[-3+yyTop], (Expression) yyVals[-1+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_864()
+#line 5793 "cs-parser.jay"
+{
+		report.Error (1575, GetLocation (yyVals[-1+yyTop]), "A stackalloc expression requires [] after type");
+		yyVal = new StackAlloc ((Expression) yyVals[0+yyTop], null, GetLocation (yyVals[-1+yyTop]));		
+	  }
+
+void case_865()
+#line 5801 "cs-parser.jay"
+{
+		yyVal = yyVals[-1+yyTop];
+		lbag.AddStatement (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_867()
+#line 5807 "cs-parser.jay"
+{
+		yyVal = yyVals[-1+yyTop];
+		report.Error (1002, GetLocation (yyVals[0+yyTop]), "; expected");
+		lexer.putback ('}');
+	  }
+
+void case_870()
+#line 5825 "cs-parser.jay"
+{
+		ExpressionStatement s = yyVals[0+yyTop] as ExpressionStatement;
+		if (s == null) {
+			var expr = yyVals[0+yyTop] as Expression;
+			yyVal = new StatementErrorExpression (expr);
+		} else {
+			yyVal = new StatementExpression (s);
+		}
+	  }
+
+void case_871()
+#line 5838 "cs-parser.jay"
+{
+		Expression expr = (Expression) yyVals[0+yyTop];
+		yyVal = new StatementExpression (new OptionalAssign (expr, lexer.Location));
+	  }
+
+void case_872()
+#line 5843 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_875()
+#line 5857 "cs-parser.jay"
+{ 
+		if (yyVals[0+yyTop] is EmptyStatement)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+		
+		yyVal = new If ((BooleanExpression) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_876()
+#line 5866 "cs-parser.jay"
+{
+		yyVal = new If ((BooleanExpression) yyVals[-4+yyTop], (Statement) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-6+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+		
+		if (yyVals[-2+yyTop] is EmptyStatement)
+			Warning_EmptyStatement (GetLocation (yyVals[-2+yyTop]));
+		if (yyVals[0+yyTop] is EmptyStatement)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_877()
+#line 5876 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		
+		yyVal = new If ((BooleanExpression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_879()
+#line 5890 "cs-parser.jay"
+{
+		yyVal = new Switch ((Expression) yyVals[-5+yyTop], (ExplicitBlock) current_block.Explicit, GetLocation (yyVals[-7+yyTop]));	
+		end_block (GetLocation (yyVals[0+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_880()
+#line 5896 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  
+		yyVal = new Switch ((Expression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop]));	
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_887()
+#line 5927 "cs-parser.jay"
+{
+	  	var label = (SwitchLabel) yyVals[0+yyTop];
+	  	label.SectionStart = true;
+		current_block.AddStatement (label);
+	  }
+
+void case_889()
+#line 5940 "cs-parser.jay"
+{
+	 	yyVal = new SwitchLabel ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	 	lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	 }
+
+void case_890()
+#line 5945 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new SwitchLabel ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_896()
+#line 5964 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  
+		yyVal = new While ((BooleanExpression) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_897()
+#line 5972 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		
+		yyVal = new While ((BooleanExpression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_898()
+#line 5982 "cs-parser.jay"
+{
+		yyVal = new Do ((Statement) yyVals[-5+yyTop], (BooleanExpression) yyVals[-2+yyTop], GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-4+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_899()
+#line 5987 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new Do ((Statement) yyVals[-1+yyTop], null, GetLocation (yyVals[-2+yyTop]), Location.Null);
+	  }
+
+void case_900()
+#line 5992 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	  
+		yyVal = new Do ((Statement) yyVals[-4+yyTop], (BooleanExpression) yyVals[-1+yyTop], GetLocation (yyVals[-5+yyTop]), GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_901()
+#line 6002 "cs-parser.jay"
+{
+		start_block (GetLocation (yyVals[0+yyTop]));
+		current_block.IsCompilerGenerated = true;
+		For f = new For (GetLocation (yyVals[-1+yyTop]));
+		current_block.AddStatement (f);
+		lbag.AddStatement (f, current_block.StartLocation);
+		yyVal = f;
+	  }
+
+void case_903()
+#line 6019 "cs-parser.jay"
+{
+		For f =  (For) yyVals[-2+yyTop];
+		f.Initializer = (Statement) yyVals[-1+yyTop];
+		lbag.AddLocation (f, GetLocation (yyVals[0+yyTop]));
+		yyVal = f;
+	  }
+
+void case_905()
+#line 6029 "cs-parser.jay"
+{
+		report.Error (1525, GetLocation (yyVals[0+yyTop]), "Unexpected symbol ')', expected ';'");
+		For f =  (For) yyVals[-2+yyTop];
+		f.Initializer = (Statement) yyVals[-1+yyTop];
+		lbag.AddLocation (f, GetLocation (yyVals[0+yyTop]));
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	}
+
+void case_906()
+#line 6040 "cs-parser.jay"
+{
+		For f =  (For) yyVals[-2+yyTop];
+		f.Condition = (BooleanExpression) yyVals[-1+yyTop];
+		lbag.AddLocation (f, GetLocation (yyVals[0+yyTop]));
+		yyVal = f;
+	  }
+
+void case_908()
+#line 6051 "cs-parser.jay"
+{
+		report.Error (1525, GetLocation (yyVals[0+yyTop]), "Unexpected symbol ')', expected ';'");
+		For f =  (For) yyVals[-2+yyTop];
+		f.Condition = (BooleanExpression) yyVals[-1+yyTop];
+		lbag.AddLocation (f, GetLocation (yyVals[0+yyTop]));
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	}
+
+void case_909()
+#line 6063 "cs-parser.jay"
+{
+		For f =  (For) yyVals[-3+yyTop];
+		f.Iterator = (Statement) yyVals[-2+yyTop];
+		
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  
+		f.Statement = (Statement) yyVals[0+yyTop];
+		lbag.AddLocation (f, GetLocation (yyVals[-1+yyTop]));
+
+		yyVal = end_block (GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_910()
+#line 6076 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = end_block (current_block.StartLocation);
+	  }
+
+void case_913()
+#line 6089 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new BlockVariable ((FullNamedExpression) yyVals[-1+yyTop], li);
+	  }
+
+void case_914()
+#line 6096 "cs-parser.jay"
+{
+		yyVal = current_variable;
+		if (yyVals[-1+yyTop] != null)
+			lbag.AddLocation (current_variable, PopLocation ());
+
+		current_variable = null;
+	  }
+
+void case_922()
+#line 6123 "cs-parser.jay"
+{
+	  	var sl = yyVals[-2+yyTop] as StatementList;
+	  	if (sl == null) {
+	  		sl = new StatementList ((Statement) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop]);
+			lbag.AddStatement (sl, GetLocation (yyVals[-1+yyTop]));
+	  	} else {
+	  		sl.Add ((Statement) yyVals[0+yyTop]);
+	  		lbag.AddLocation (sl, GetLocation (yyVals[-1+yyTop]));
+	  		
+	  	}
+	  		
+		yyVal = sl;
+	  }
+
+void case_923()
+#line 6140 "cs-parser.jay"
+{
+		report.Error (230, GetLocation (yyVals[-3+yyTop]), "Type and identifier are both required in a foreach statement");
+
+		start_block (GetLocation (yyVals[-2+yyTop]));
+		current_block.IsCompilerGenerated = true;
+		
+		Foreach f = new Foreach ((Expression) yyVals[-1+yyTop], null, null, null, null, GetLocation (yyVals[-3+yyTop]));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation (yyVals[-2+yyTop]));
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_924()
+#line 6153 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+	
+		start_block (GetLocation (yyVals[-3+yyTop]));
+		current_block.IsCompilerGenerated = true;
+		
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.ForeachVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		
+		Foreach f = new Foreach ((Expression) yyVals[-2+yyTop], li, null, null, null, GetLocation (yyVals[-4+yyTop]));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation (yyVals[-3+yyTop]));
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_925()
+#line 6170 "cs-parser.jay"
+{
+		start_block (GetLocation (yyVals[-5+yyTop]));
+		current_block.IsCompilerGenerated = true;
+		
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.ForeachVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		yyVal = li;
+	  }
+
+void case_926()
+#line 6180 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+		
+		Foreach f = new Foreach ((Expression) yyVals[-6+yyTop], (LocalVariable) yyVals[-1+yyTop], (Expression) yyVals[-3+yyTop], (Statement) yyVals[0+yyTop], current_block, GetLocation (yyVals[-8+yyTop]));
+		lbag.AddStatement (f, GetLocation (yyVals[-7+yyTop]), GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		end_block (GetLocation (yyVals[-2+yyTop]));
+		
+		yyVal = f;
+	  }
+
+void case_927()
+#line 6191 "cs-parser.jay"
+{
+		start_block (GetLocation (yyVals[-3+yyTop]));
+		current_block.IsCompilerGenerated = true;
+		var lt = yyVals[-1+yyTop] as LocatedToken;
+		var li = lt != null ? new LocalVariable (current_block, lt.Value, LocalVariable.Flags.ForeachVariable | LocalVariable.Flags.Used, lt.Location) : null;
+		
+		Foreach f = new Foreach ((Expression) yyVals[-2+yyTop], li, null, null, null, GetLocation (yyVals[-4+yyTop]));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation (yyVals[-3+yyTop]));
+		yyVal = end_block (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_928()
+#line 6204 "cs-parser.jay"
+{
+		Foreach f = new Foreach ((Expression) yyVals[-1+yyTop], null, null, null, null, GetLocation (yyVals[-3+yyTop]));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation (yyVals[-2+yyTop]));
+		yyVal = f;
+	  }
+
+void case_935()
+#line 6224 "cs-parser.jay"
+{
+		yyVal = new Break (GetLocation (yyVals[-1+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_936()
+#line 6232 "cs-parser.jay"
+{
+		yyVal = new Continue (GetLocation (yyVals[-1+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_937()
+#line 6237 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new Continue (GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_938()
+#line 6245 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new Goto (lt.Value, GetLocation (yyVals[-2+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_939()
+#line 6251 "cs-parser.jay"
+{
+		yyVal = new GotoCase ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_940()
+#line 6256 "cs-parser.jay"
+{
+		yyVal = new GotoDefault (GetLocation (yyVals[-2+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_941()
+#line 6264 "cs-parser.jay"
+{
+		yyVal = new Return ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_942()
+#line 6269 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new Return ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_943()
+#line 6274 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new Return (null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_944()
+#line 6282 "cs-parser.jay"
+{
+		yyVal = new Throw ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_945()
+#line 6287 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new Throw ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_946()
+#line 6292 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new Throw (null, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_947()
+#line 6300 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		string s = lt.Value;
+		if (s != "yield"){
+			report.Error (1003, lt.Location, "; expected");
+		} else if (yyVals[-1+yyTop] == null) {
+			report.Error (1627, GetLocation (yyVals[0+yyTop]), "Expression expected after yield return");
+		} else if (lang_version == LanguageVersion.ISO_1){
+			FeatureIsNotAvailable (lt.Location, "iterators");
+		}
+		
+		current_block.Explicit.RegisterIteratorYield ();
+		yyVal = new Yield ((Expression) yyVals[-1+yyTop], lt.Location);
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_948()
+#line 6316 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		string s = lt.Value;
+		if (s != "yield"){
+			report.Error (1003, lt.Location, "; expected");
+		} else if (yyVals[-1+yyTop] == null) {
+			report.Error (1627, GetLocation (yyVals[0+yyTop]), "Expression expected after yield return");
+		} else if (lang_version == LanguageVersion.ISO_1){
+			FeatureIsNotAvailable (lt.Location, "iterators");
+		}
+		
+		current_block.Explicit.RegisterIteratorYield ();
+		yyVal = new Yield ((Expression) yyVals[-1+yyTop], lt.Location);
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_949()
+#line 6334 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		string s = lt.Value;
+		if (s != "yield"){
+			report.Error (1003, lt.Location, "; expected");
+		} else if (lang_version == LanguageVersion.ISO_1){
+			FeatureIsNotAvailable (lt.Location, "iterators");
+		}
+		
+		current_block.ParametersBlock.TopBlock.IsIterator = true;
+		yyVal = new YieldBreak (lt.Location);
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-1+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_953()
+#line 6360 "cs-parser.jay"
+{
+		yyVal = new TryFinally ((Statement) yyVals[-2+yyTop], (ExplicitBlock) yyVals[0+yyTop], GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_954()
+#line 6365 "cs-parser.jay"
+{
+		yyVal = new TryFinally (new TryCatch ((Block) yyVals[-3+yyTop], (List<Catch>) yyVals[-2+yyTop], GetLocation (yyVals[-4+yyTop]), true), (ExplicitBlock) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_955()
+#line 6370 "cs-parser.jay"
+{
+		Error_SyntaxError (1524, yyToken);
+		yyVal = new TryCatch ((Block) yyVals[-1+yyTop], null, GetLocation (yyVals[-2+yyTop]), false);
+	  }
+
+void case_956()
+#line 6378 "cs-parser.jay"
+{
+		var l = new List<Catch> (2);
+
+		l.Add ((Catch) yyVals[0+yyTop]);
+		yyVal = l;
+	  }
+
+void case_957()
+#line 6385 "cs-parser.jay"
+{
+		var l = (List<Catch>) yyVals[-1+yyTop];
+		
+		Catch c = (Catch) yyVals[0+yyTop];
+		var prev_catch = l [l.Count - 1];
+		if (prev_catch.IsGeneral && prev_catch.Filter == null) {
+			report.Error (1017, c.loc, "Try statement already has an empty catch block");
+		}
+		
+		l.Add (c);
+		yyVal = l;
+	  }
+
+void case_960()
+#line 6406 "cs-parser.jay"
+{
+	  	var c = new Catch ((ExplicitBlock) yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+	  	c.Filter = (CatchFilterExpression) yyVals[-1+yyTop];
+	  	yyVal = c;
+	  }
+
+void case_961()
+#line 6412 "cs-parser.jay"
+{
+		start_block (GetLocation (yyVals[-3+yyTop]));
+		var c = new Catch ((ExplicitBlock) current_block, GetLocation (yyVals[-4+yyTop]));
+		c.TypeExpression = (FullNamedExpression) yyVals[-2+yyTop];
+
+		if (yyVals[-1+yyTop] != null) {
+			var lt = (LocatedToken) yyVals[-1+yyTop];
+			c.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+			current_block.AddLocalName (c.Variable);
+		}
+
+		lbag.AddLocation (c, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[0+yyTop]));
+		yyVal = c;
+	  }
+
+void case_962()
+#line 6427 "cs-parser.jay"
+{
+	  	((Catch) yyVals[-2+yyTop]).Filter = (CatchFilterExpression) yyVals[-1+yyTop];
+		yyVal = yyVals[-2+yyTop];
+	  }
+
+void case_963()
+#line 6432 "cs-parser.jay"
+{
+	  	if (yyToken == Token.CLOSE_PARENS) {
+			report.Error (1015, lexer.Location,
+				"A type that derives from `System.Exception', `object', or `string' expected");
+		} else {
+			Error_SyntaxError (yyToken);
+		}
+		
+		yyVal = new Catch (null, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_964()
+#line 6443 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		/* Required otherwise missing block could not be detected because*/
+		/* start_block is run early*/
+		var c = new Catch (null, GetLocation (yyVals[-5+yyTop]));
+		c.TypeExpression = (FullNamedExpression) yyVals[-3+yyTop];
+		
+		if (yyVals[-2+yyTop] != null) {
+			var lt = (LocatedToken) yyVals[-2+yyTop];
+			c.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+		}
+
+		if (yyVals[-2+yyTop] != null) {
+			var lt = (LocatedToken) yyVals[-2+yyTop];
+			c.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+		}
+
+		lbag.AddLocation (c, GetLocation (yyVals[-4+yyTop]), GetLocation (yyVals[-1+yyTop]));
+
+		yyVal = c;
+	  }
+
+void case_966()
+#line 6470 "cs-parser.jay"
+{
+		if (lang_version <= LanguageVersion.V_5)
+			FeatureIsNotAvailable (GetLocation (yyVals[-3+yyTop]), "exception filter");
+
+	  	yyVal = new CatchFilterExpression ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-3+yyTop]));
+	  	lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]), GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_969()
+#line 6495 "cs-parser.jay"
+{
+		if (!settings.Unsafe)
+			Error_UnsafeCodeNotAllowed (GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_971()
+#line 6505 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  
+		yyVal = new Lock ((Expression) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_972()
+#line 6513 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+
+		yyVal = new Lock ((Expression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_973()
+#line 6523 "cs-parser.jay"
+{
+	    start_block (GetLocation (yyVals[-2+yyTop]));
+	    
+		current_block.IsCompilerGenerated = true;
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.FixedVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new Fixed.VariableDeclaration ((FullNamedExpression) yyVals[-1+yyTop], li);
+	  }
+
+void case_974()
+#line 6533 "cs-parser.jay"
+{
+		yyVal = current_variable;
+		current_variable = null;
+	  }
+
+void case_975()
+#line 6538 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  
+		Fixed f = new Fixed ((Fixed.VariableDeclaration) yyVals[-1+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-9+yyTop]));
+		current_block.AddStatement (f);
+		lbag.AddStatement (f, GetLocation (yyVals[-8+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		yyVal = end_block (GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_976()
+#line 6551 "cs-parser.jay"
+{
+	    start_block (GetLocation (yyVals[-2+yyTop]));
+	    
+		current_block.IsCompilerGenerated = true;
+		var lt = (LocatedToken) yyVals[0+yyTop];
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.UsingVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new Using.VariableDeclaration ((FullNamedExpression) yyVals[-1+yyTop], li);
+	  }
+
+void case_977()
+#line 6561 "cs-parser.jay"
+{
+		yyVal = current_variable;	  
+		current_variable = null;
+	  }
+
+void case_978()
+#line 6566 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  
+		Using u = new Using ((Using.VariableDeclaration) yyVals[-1+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-8+yyTop]));
+		lbag.AddStatement (u, GetLocation (yyVals[-7+yyTop]), GetLocation (yyVals[-2+yyTop]));
+		current_block.AddStatement (u);
+		yyVal = end_block (GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_979()
+#line 6576 "cs-parser.jay"
+{
+		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
+	  
+		yyVal = new Using ((Expression) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
+	  }
+
+void case_980()
+#line 6584 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		
+		yyVal = new Using ((Expression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_982()
+#line 6595 "cs-parser.jay"
+{
+		/* It has to be here for the parent to safely restore artificial block*/
+	  	Error_SyntaxError (yyToken);
+	  }
+
+void case_984()
+#line 6607 "cs-parser.jay"
+{
+		current_variable.Initializer = (Expression) yyVals[0+yyTop];
+		lbag.AddLocation (current_variable, GetLocation (yyVals[-1+yyTop]));
+		yyVal = current_variable;
+	  }
+
+void case_985()
+#line 6619 "cs-parser.jay"
+{
+		lexer.query_parsing = false;
+			
+		Linq.AQueryClause from = yyVals[-1+yyTop] as Linq.AQueryClause;
+			
+		from.Tail.Next = (Linq.AQueryClause)yyVals[0+yyTop];
+		yyVal = from;
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_986()
+#line 6631 "cs-parser.jay"
+{
+		Linq.AQueryClause from = yyVals[-1+yyTop] as Linq.AQueryClause;
+			
+		from.Tail.Next = (Linq.AQueryClause)yyVals[0+yyTop];
+		yyVal = from;
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_987()
+#line 6642 "cs-parser.jay"
+{
+	        lexer.query_parsing = false;
+		yyVal = yyVals[-1+yyTop];
+
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_988()
+#line 6649 "cs-parser.jay"
+{
+	        yyVal = yyVals[-1+yyTop];
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_989()
+#line 6658 "cs-parser.jay"
+{
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)yyVals[0+yyTop], rv, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (clause, GetLocation (yyVals[-1+yyTop]));
+		yyVal = new Linq.QueryExpression (clause);
+	  }
+
+void case_990()
+#line 6668 "cs-parser.jay"
+{
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)yyVals[0+yyTop], rv, GetLocation (yyVals[-4+yyTop])) {
+				IdentifierType = (FullNamedExpression)yyVals[-3+yyTop]
+		};
+		lbag.AddLocation (clause, GetLocation (yyVals[-1+yyTop]));
+		yyVal = new Linq.QueryExpression (clause);
+	  }
+
+void case_991()
+#line 6683 "cs-parser.jay"
+{
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)yyVals[0+yyTop], rv, GetLocation (yyVals[-3+yyTop]));
+		lbag.AddLocation (clause, GetLocation (yyVals[-1+yyTop]));
+		yyVal = new Linq.QueryExpression (clause);
+	  }
+
+void case_992()
+#line 6693 "cs-parser.jay"
+{
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)yyVals[0+yyTop], rv, GetLocation (yyVals[-4+yyTop])) {
+				IdentifierType = (FullNamedExpression)yyVals[-3+yyTop]
+		};
+		lbag.AddLocation (clause, GetLocation (yyVals[-1+yyTop]));
+		yyVal = new Linq.QueryExpression (clause);
+	  }
+
+void case_994()
+#line 6712 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+		yyVal = new Linq.SelectMany ((Linq.QueryBlock)current_block, sn, (Expression)yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+		((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_996()
+#line 6727 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+
+		yyVal = new Linq.SelectMany ((Linq.QueryBlock)current_block, sn, (Expression)yyVals[0+yyTop], GetLocation (yyVals[-5+yyTop])) {
+			IdentifierType = (FullNamedExpression)yyVals[-4+yyTop]
+		};
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+		
+		((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  }
+
+void case_997()
+#line 6746 "cs-parser.jay"
+{
+	  	Linq.AQueryClause head = (Linq.AQueryClause)yyVals[-1+yyTop];
+		
+		if (yyVals[0+yyTop] != null)
+			head.Next = (Linq.AQueryClause)yyVals[0+yyTop];
+				
+		if (yyVals[-2+yyTop] != null) {
+			Linq.AQueryClause clause = (Linq.AQueryClause)yyVals[-2+yyTop];
+			clause.Tail.Next = head;
+			head = clause;
+		}
+		
+		yyVal = head;
+	  }
+
+void case_998()
+#line 6761 "cs-parser.jay"
+{
+	  	Linq.AQueryClause head = (Linq.AQueryClause)yyVals[0+yyTop];
+
+		if (yyVals[-1+yyTop] != null) {
+			Linq.AQueryClause clause = (Linq.AQueryClause)yyVals[-1+yyTop];
+			clause.Tail.Next = head;
+			head = clause;
+		}
+		
+		yyVal = head;
+	  }
+
+void case_1000()
+#line 6774 "cs-parser.jay"
+{
+		report.Error (742, GetLocation (yyVals[0+yyTop]), "Unexpected symbol `{0}'. A query body must end with select or group clause", GetSymbolName (yyToken));
+		yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_1001()
+#line 6779 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = null;
+	  }
+
+void case_1003()
+#line 6791 "cs-parser.jay"
+{
+		yyVal = new Linq.Select ((Linq.QueryBlock)current_block, (Expression)yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_1004()
+#line 6798 "cs-parser.jay"
+{
+	  	if (linq_clause_blocks == null)
+	  		linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  	linq_clause_blocks.Push ((Linq.QueryBlock)current_block);
+	  }
+
+void case_1005()
+#line 6806 "cs-parser.jay"
+{
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+
+void case_1006()
+#line 6813 "cs-parser.jay"
+{
+		var obj = (object[]) yyVals[0+yyTop];
+
+		yyVal = new Linq.GroupBy ((Linq.QueryBlock)current_block, (Expression)yyVals[-2+yyTop], linq_clause_blocks.Pop (), (Expression)obj[0], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddLocation (yyVal, (Location) obj[1]);
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_1008()
+#line 6830 "cs-parser.jay"
+{
+		Error_SyntaxError (yyToken);
+		yyVal = new object[2] { null, Location.Null };
+	  }
+
+void case_1010()
+#line 6839 "cs-parser.jay"
+{
+		((Linq.AQueryClause)yyVals[-1+yyTop]).Tail.Next = (Linq.AQueryClause)yyVals[0+yyTop];
+		yyVal = yyVals[-1+yyTop];
+	  }
+
+void case_1017()
+#line 6859 "cs-parser.jay"
+{
+		var lt = (LocatedToken) yyVals[-3+yyTop];
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+	  	yyVal = new Linq.Let ((Linq.QueryBlock) current_block, sn, (Expression)yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
+		lbag.AddLocation (yyVal, GetLocation (yyVals[-2+yyTop]));
+	  	
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+		
+		((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+	  }
+
+void case_1019()
+#line 6878 "cs-parser.jay"
+{
+		yyVal = new Linq.Where ((Linq.QueryBlock)current_block, (Expression)yyVals[0+yyTop], GetLocation (yyVals[-2+yyTop]));
+
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+
+void case_1020()
+#line 6888 "cs-parser.jay"
+{
+		if (linq_clause_blocks == null)
+			linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+
+void case_1021()
+#line 6896 "cs-parser.jay"
+{
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+
+void case_1022()
+#line 6904 "cs-parser.jay"
+{
+		current_block.AddStatement (new ContextualReturn ((Expression) yyVals[-1+yyTop]));
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+
+void case_1023()
+#line 6912 "cs-parser.jay"
+{
+		current_block.AddStatement (new ContextualReturn ((Expression) yyVals[-1+yyTop]));
+		current_block.SetEndLocation (lexer.Location);
+	  
+		var outer_selector = linq_clause_blocks.Pop ();
+		var block = linq_clause_blocks.Pop ();
+
+		var lt = (LocatedToken) yyVals[-10+yyTop];	
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+		Linq.RangeVariable into;
+		
+		if (yyVals[0+yyTop] == null) {
+			into = sn;
+	  		yyVal = new Linq.Join (block, sn, (Expression)yyVals[-7+yyTop], outer_selector, (Linq.QueryBlock) current_block, GetLocation (yyVals[-11+yyTop]));
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-9+yyTop]), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-3+yyTop]));
+		} else {
+			/**/
+			/* Set equals right side parent to beginning of linq query, it is not accessible therefore cannot cause name collisions*/
+			/**/
+			var parent = block.Parent;
+			while (parent is Linq.QueryBlock) {
+				parent = parent.Parent;
+			}
+			current_block.Parent = parent;
+			
+			((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		
+			lt = (LocatedToken) yyVals[0+yyTop];
+			into = new Linq.RangeVariable (lt.Value, lt.Location);
+
+			yyVal = new Linq.GroupJoin (block, sn, (Expression)yyVals[-7+yyTop], outer_selector, (Linq.QueryBlock) current_block, into, GetLocation (yyVals[-11+yyTop]));	
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-9+yyTop]), GetLocation (yyVals[-6+yyTop]), GetLocation (yyVals[-3+yyTop]), opt_intoStack.Pop ());
+		}
+
+		current_block = block.Parent;
+		((Linq.QueryBlock)current_block).AddRangeVariable (into);
+	  }
+
+void case_1024()
+#line 6950 "cs-parser.jay"
+{
+		if (linq_clause_blocks == null)
+			linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+
+void case_1025()
+#line 6958 "cs-parser.jay"
+{
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+
+void case_1026()
+#line 6966 "cs-parser.jay"
+{
+		current_block.AddStatement (new ContextualReturn ((Expression) yyVals[-1+yyTop]));
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+
+void case_1027()
+#line 6974 "cs-parser.jay"
+{
+		current_block.AddStatement (new ContextualReturn ((Expression) yyVals[-1+yyTop]));
+		current_block.SetEndLocation (lexer.Location);
+	  
+		var outer_selector = linq_clause_blocks.Pop ();
+		var block = linq_clause_blocks.Pop ();
+		
+		var lt = (LocatedToken) yyVals[-10+yyTop];
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+		Linq.RangeVariable into;
+		
+		if (yyVals[0+yyTop] == null) {
+			into = sn;		
+	  		yyVal = new Linq.Join (block, sn, (Expression)yyVals[-7+yyTop], outer_selector, (Linq.QueryBlock) current_block, GetLocation (yyVals[-12+yyTop])) {
+	  			IdentifierType = (FullNamedExpression)yyVals[-11+yyTop]
+	  		};
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-10+yyTop]), GetLocation (yyVals[-7+yyTop]), GetLocation (yyVals[-4+yyTop]));
+		} else {
+			/**/
+			/* Set equals right side parent to beginning of linq query, it is not accessible therefore cannot cause name collisions*/
+			/**/
+			var parent = block.Parent;
+			while (parent is Linq.QueryBlock) {
+				parent = parent.Parent;
+			}
+			current_block.Parent = parent;
+		
+			((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		
+			lt = (LocatedToken) yyVals[0+yyTop];
+			into = new Linq.RangeVariable (lt.Value, lt.Location); /* TODO:*/
+			
+			yyVal = new Linq.GroupJoin (block, sn, (Expression)yyVals[-7+yyTop], outer_selector, (Linq.QueryBlock) current_block, into, GetLocation (yyVals[-12+yyTop])) {
+	  			IdentifierType = (FullNamedExpression)yyVals[-11+yyTop]
+	  		};			
+			lbag.AddLocation (yyVal, GetLocation (yyVals[-10+yyTop]), GetLocation (yyVals[-7+yyTop]), GetLocation (yyVals[-4+yyTop]), opt_intoStack.Pop ());
+		}
+		
+		current_block = block.Parent;
+		((Linq.QueryBlock)current_block).AddRangeVariable (into);		
+	  }
+
+void case_1029()
+#line 7020 "cs-parser.jay"
+{
+		opt_intoStack.Push (GetLocation (yyVals[-1+yyTop]));
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_1030()
+#line 7028 "cs-parser.jay"
+{
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		lbag.AddLocation (current_block, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_1031()
+#line 7033 "cs-parser.jay"
+{
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		yyVal = yyVals[0+yyTop];
+	  }
+
+void case_1033()
+#line 7044 "cs-parser.jay"
+{
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+
+void case_1034()
+#line 7051 "cs-parser.jay"
+{
+		((Linq.AQueryClause)yyVals[-3+yyTop]).Next = (Linq.AQueryClause)yyVals[0+yyTop];
+		yyVal = yyVals[-3+yyTop];
+	  }
+
+void case_1036()
+#line 7060 "cs-parser.jay"
+{
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		current_block = new Linq.QueryBlock ((Linq.QueryBlock) current_block, lexer.Location);	 
+	 }
+
+void case_1037()
+#line 7067 "cs-parser.jay"
+{
+		((Linq.AQueryClause)yyVals[-3+yyTop]).Tail.Next = (Linq.AQueryClause)yyVals[0+yyTop];
+		yyVal = yyVals[-3+yyTop];
+	 }
+
+void case_1039()
+#line 7079 "cs-parser.jay"
+{
+		yyVal = new Linq.OrderByAscending ((Linq.QueryBlock) current_block, (Expression)yyVals[-1+yyTop]);	
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_1040()
+#line 7084 "cs-parser.jay"
+{
+		yyVal = new Linq.OrderByDescending ((Linq.QueryBlock) current_block, (Expression)yyVals[-1+yyTop]);	
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_1042()
+#line 7096 "cs-parser.jay"
+{
+		yyVal = new Linq.ThenByAscending ((Linq.QueryBlock) current_block, (Expression)yyVals[-1+yyTop]);	
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_1043()
+#line 7101 "cs-parser.jay"
+{
+		yyVal = new Linq.ThenByDescending ((Linq.QueryBlock) current_block, (Expression)yyVals[-1+yyTop]);	
+		lbag.AddLocation (yyVal, GetLocation (yyVals[0+yyTop]));
+	  }
+
+void case_1045()
+#line 7111 "cs-parser.jay"
+{
+		/* query continuation block is not linked with query block but with block*/
+		/* before. This means each query can use same range variable names for*/
+		/* different identifiers.*/
+
+		current_block.SetEndLocation (GetLocation (yyVals[-1+yyTop]));
+		current_block = current_block.Parent;
+	
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		
+		if (linq_clause_blocks == null)
+			linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);		
+	  }
+
+void case_1046()
+#line 7127 "cs-parser.jay"
+{
+		var current_block = linq_clause_blocks.Pop ();	  
+		var lt = (LocatedToken) yyVals[-2+yyTop];
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+  		yyVal = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, null, rv, GetLocation (yyVals[-3+yyTop])) {
+  			next = (Linq.AQueryClause)yyVals[0+yyTop]
+  		};
+	  }
+
+void case_1049()
+#line 7154 "cs-parser.jay"
+{ 
+		current_container = current_type = new Class (current_container, new MemberName ("<InteractiveExpressionClass>"), Modifiers.PUBLIC, null);
+
+		/* (ref object retval)*/
+		Parameter [] mpar = new Parameter [1];
+		mpar [0] = new Parameter (new TypeExpression (compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null);
+
+		ParametersCompiled pars = new ParametersCompiled (mpar);
+		var mods = Modifiers.PUBLIC | Modifiers.STATIC;
+		if (settings.Unsafe)
+			mods |= Modifiers.UNSAFE;
+
+		current_local_parameters = pars;
+		var method = new InteractiveMethod (
+			current_type,
+			new TypeExpression (compiler.BuiltinTypes.Void, Location.Null),
+			mods,
+			pars);
+			
+		current_type.AddMember (method);			
+		oob_stack.Push (method);
+
+		interactive_async = false;
+
+		++lexer.parsing_block;
+		start_block (lexer.Location);
+	  }
+
+void case_1050()
+#line 7182 "cs-parser.jay"
+{
+		--lexer.parsing_block;
+		var method = (InteractiveMethod) oob_stack.Pop ();
+		method.Block = (ToplevelBlock) end_block(lexer.Location);
+
+		if (interactive_async == true) {
+			method.ChangeToAsync ();
+		}
+
+		InteractiveResult = (Class) pop_current_class ();
+		current_local_parameters = null;
+	  }
+
+void case_1060()
+#line 7228 "cs-parser.jay"
+{
+		module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)yyVals[-1+yyTop];
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)yyVals[0+yyTop];
+		yyVal = null;
+	  }
+
+void case_1061()
+#line 7234 "cs-parser.jay"
+{
+		module.DocumentationBuilder.ParsedBuiltinType = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation (yyVals[-1+yyTop]));
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)yyVals[0+yyTop];
+		yyVal = null;
+	  }
+
+void case_1062()
+#line 7240 "cs-parser.jay"
+{
+		module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)yyVals[-3+yyTop];
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)yyVals[0+yyTop];
+		var lt = (LocatedToken) yyVals[-1+yyTop];
+		yyVal = new MemberName (lt.Value);
+	  }
+
+void case_1065()
+#line 7255 "cs-parser.jay"
+{
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)yyVals[-1+yyTop];
+		yyVal = new MemberName ((MemberName) yyVals[-6+yyTop], MemberCache.IndexerNameAlias, Location.Null);
+	  }
+
+void case_1066()
+#line 7260 "cs-parser.jay"
+{
+		var p = (List<DocumentationParameter>)yyVals[0+yyTop] ?? new List<DocumentationParameter> (1);
+		p.Add (new DocumentationParameter ((FullNamedExpression) yyVals[-1+yyTop]));
+		module.DocumentationBuilder.ParsedParameters = p;
+		module.DocumentationBuilder.ParsedOperator = Operator.OpType.Explicit;
+		yyVal = null;
+	  }
+
+void case_1067()
+#line 7268 "cs-parser.jay"
+{
+		var p = (List<DocumentationParameter>)yyVals[0+yyTop] ?? new List<DocumentationParameter> (1);
+		p.Add (new DocumentationParameter ((FullNamedExpression) yyVals[-1+yyTop]));
+		module.DocumentationBuilder.ParsedParameters = p;
+		module.DocumentationBuilder.ParsedOperator = Operator.OpType.Implicit;
+		yyVal = null;
+	  }
+
+void case_1068()
+#line 7276 "cs-parser.jay"
+{
+		var p = (List<DocumentationParameter>)yyVals[0+yyTop];
+		module.DocumentationBuilder.ParsedParameters = p;
+		module.DocumentationBuilder.ParsedOperator = (Operator.OpType) yyVals[-1+yyTop];
+		yyVal = null;
+	  }
+
+void case_1076()
+#line 7314 "cs-parser.jay"
+{
+		var parameters = new List<DocumentationParameter> ();
+		parameters.Add ((DocumentationParameter) yyVals[0+yyTop]);
+		yyVal = parameters;
+	  }
+
+void case_1077()
+#line 7320 "cs-parser.jay"
+{
+		var parameters = yyVals[-2+yyTop] as List<DocumentationParameter>;
+		parameters.Add ((DocumentationParameter) yyVals[0+yyTop]);
+		yyVal = parameters;
+	  }
+
+void case_1078()
+#line 7329 "cs-parser.jay"
+{
+		if (yyVals[-1+yyTop] != null)
+			yyVal = new DocumentationParameter ((Parameter.Modifier) yyVals[-1+yyTop], (FullNamedExpression) yyVals[0+yyTop]);
+		else
+			yyVal = new DocumentationParameter ((FullNamedExpression) yyVals[0+yyTop]);
+	  }
+
+#line default
+   static readonly short [] yyLhs  = {              -1,
+    0,    4,    0,    0,    1,    1,    1,    1,    2,    2,
+   11,   11,   12,   12,   13,   13,   14,   15,   15,   15,
+   19,   20,   17,   17,   22,   22,   22,   18,   18,   18,
+   23,   23,   24,   24,    7,    7,    6,    6,   21,   21,
+    8,    8,   25,   25,   25,   26,   26,   26,   26,   26,
+    9,    9,   10,   10,   34,   32,   37,   33,   33,   33,
+   33,   35,   35,   35,   36,   36,   41,   38,   39,   40,
+   40,   42,   42,   42,   42,   42,   43,   43,   43,   47,
+   44,   46,   49,   49,   49,   51,   51,   52,   52,   53,
+   53,   53,   53,   53,   53,   53,   53,   53,   53,   53,
+   53,   53,   53,   67,   62,   72,   74,   77,   78,   79,
+   28,   28,   82,   54,   54,   83,   83,   84,   84,   85,
+   87,   81,   81,   86,   86,   92,   55,   96,   55,   55,
+   91,   99,   91,   93,   93,  100,  100,  101,  102,  101,
+   97,   97,  103,  103,  104,  105,   95,   95,   98,   98,
+   98,  108,   56,  111,  112,  106,  113,  114,  115,  106,
+  106,  106,  107,  107,  117,  117,  120,  118,  110,  110,
+  121,  121,  121,  121,  121,  121,  121,  121,  121,  121,
+  122,  122,  125,  125,  125,  125,  128,  125,  126,  126,
+  129,  129,  130,  130,  130,  123,  123,  123,  131,  131,
+  131,  124,  133,  135,  136,  138,   57,  139,   57,  137,
+  141,  137,  140,  140,  143,  145,   59,  144,  144,  134,
+  134,  134,  134,  134,  149,  146,  150,  147,  148,  148,
+  148,  151,  152,  153,  155,   29,   29,  154,  154,  156,
+  156,  157,  157,  157,  157,  157,  157,  157,  157,  157,
+  159,   60,  160,  160,  163,  158,  158,  162,  162,  162,
+  162,  162,  162,  162,  162,  162,  162,  162,  162,  162,
+  162,  162,  162,  162,  162,  162,  162,  162,  162,  165,
+  164,  166,  164,  164,  164,   61,  169,  171,  167,  168,
+  168,  170,  170,  175,  173,  176,  173,  173,  173,  177,
+   63,  179,   58,  182,  183,   58,   58,  178,  185,  178,
+  180,  180,  186,  186,  187,  188,  187,  189,  184,  181,
+  181,  181,  181,  181,  193,  190,  194,  191,  192,  192,
+   64,   65,  196,  198,  199,   30,  195,  195,  195,  197,
+  197,  197,  200,  200,  201,  202,  201,  201,  201,  203,
+  204,  205,   31,  206,  206,   16,   16,   16,  207,  207,
+  207,  211,  211,  209,  209,  209,  212,  212,  214,   71,
+  132,  109,  109,  142,  142,  215,  215,  215,  213,  213,
+  216,  216,  217,  217,  219,  219,   90,   80,   80,   94,
+   94,  127,  127,  161,  161,  221,  221,  221,  220,  224,
+  224,  224,  226,  226,  227,  225,  225,  225,  225,  225,
+  225,  225,  228,  228,  228,  228,  228,  228,  228,  228,
+  228,  229,  229,  229,  229,  229,  229,  229,  229,  229,
+  229,  229,  229,  229,  229,  229,  229,  229,  229,  229,
+  229,  230,  230,  230,  231,  231,  231,  251,  251,  252,
+  252,  253,  253,  233,  233,  250,  250,  250,  250,  250,
+  250,  250,  250,  250,  250,  250,  250,  235,  235,  235,
+  255,  255,  256,  256,  257,  257,  259,  259,  259,  260,
+  260,  260,  260,  260,  260,  260,  261,  261,  174,  174,
+  254,  254,  254,  254,  254,  266,  266,  265,  265,  267,
+  267,  267,  267,  268,  236,  236,  236,  236,  264,  264,
+  269,  269,  270,  270,  237,  238,  238,  239,  240,  241,
+  241,  232,  232,  232,  232,  232,  275,  271,  242,  242,
+  276,  276,  277,  277,  278,  278,  278,  278,  279,  279,
+  279,  279,  272,  272,  222,  222,  274,  274,  280,  280,
+  273,  273,   89,   89,  281,  281,  243,  282,  282,  210,
+  208,  244,  244,  245,  245,  246,  246,  247,  284,  248,
+  285,  248,  283,  283,  287,  286,  234,  288,  288,  288,
+  288,  288,  288,  288,  288,  288,  289,  289,  289,  289,
+  289,  289,  289,  289,  289,  289,  289,  289,  289,  290,
+  290,  290,  290,  290,  290,  290,  291,  291,  291,  291,
+  291,  291,  291,  291,  291,  291,  291,  292,  292,  292,
+  292,  292,  294,  294,  294,  294,  295,  295,  295,  295,
+  295,  296,  296,  296,  296,  296,  296,  296,  296,  296,
+  297,  297,  297,  297,  297,  298,  298,  298,  299,  299,
+  299,  300,  300,  300,  301,  301,  301,  302,  302,  302,
+  303,  303,  304,  304,  304,  304,  304,  305,  305,  305,
+  305,  305,  305,  305,  305,  305,  305,  305,  306,  306,
+  307,  307,  307,  307,  308,  308,  310,  309,  309,  309,
+   50,   50,  312,  311,  313,  311,  314,  311,  315,  316,
+  311,  317,  318,  311,   45,   45,  262,  262,  262,  262,
+  249,  249,  249,   88,  320,   73,   73,  321,  322,  322,
+  322,  322,  324,  322,  325,  326,  327,  328,   27,   70,
+   70,   69,   69,  116,  116,  329,  329,  329,  329,  329,
+  329,  329,  329,  329,  329,  329,  329,  329,  329,  329,
+   75,   75,  323,  323,   76,   76,  330,  330,  331,  331,
+  332,  332,  333,  333,  333,  333,  218,  218,  334,  334,
+  335,  119,   68,   68,  336,  172,  172,  338,  337,   66,
+   66,  339,  339,  340,  340,  340,  340,  340,  344,  344,
+  345,  345,  345,  342,  342,  342,  342,  342,  342,  342,
+  342,  342,  342,  342,  342,  342,  346,  346,  346,  346,
+  346,  346,  346,  346,  346,  346,  346,  346,  346,  360,
+  360,  360,  360,  347,  361,  343,  362,  362,  363,  363,
+  363,  363,  223,  223,  364,   48,   48,  366,  341,  370,
+  341,  368,  368,  365,  365,  365,  367,  367,  374,  374,
+  373,  373,  375,  375,  369,  369,  371,  371,  376,  376,
+  377,  372,  372,  372,  348,  348,  348,  359,  359,  378,
+  379,  379,  349,  349,  380,  380,  380,  383,  381,  381,
+  382,  382,  384,  384,  384,  385,  386,  386,  387,  387,
+  387,  350,  350,  350,  350,  388,  388,  389,  389,  389,
+  393,  390,  396,  392,  392,  399,  395,  395,  398,  398,
+  394,  394,  402,  401,  401,  397,  397,  400,  400,  404,
+  403,  403,  391,  391,  405,  391,  391,  391,  351,  351,
+  351,  351,  351,  351,  406,  407,  407,  408,  408,  408,
+  409,  409,  409,  410,  410,  410,  411,  411,  411,  412,
+  412,  352,  352,  352,  352,  413,  413,  293,  293,  414,
+  416,  414,  414,  414,  415,  415,  353,  354,  417,  357,
+  355,  355,  419,  420,  358,  422,  423,  356,  356,  356,
+  421,  421,  418,  418,  319,  319,  319,  319,  424,  424,
+  426,  426,  428,  427,  429,  427,  425,  425,  425,  425,
+  425,  433,  431,  434,  436,  431,  435,  435,  430,  430,
+  437,  437,  437,  437,  437,  442,  438,  443,  439,  444,
+  445,  446,  440,  448,  449,  450,  440,  447,  447,  452,
+  441,  451,  455,  451,  454,  457,  454,  453,  453,  453,
+  456,  456,  456,  432,  458,  432,    3,    3,  459,    3,
+    3,  460,  460,  263,  263,  258,  258,    5,  461,  461,
+  461,  461,  461,  465,  461,  461,  461,  461,  462,  462,
+  463,  466,  463,  464,  464,  467,  467,  468,
+  };
+   static readonly short [] yyLen = {           2,
+    2,    0,    3,    1,    2,    4,    3,    1,    0,    1,
+    1,    2,    4,    2,    1,    2,    1,    3,    5,    2,
+    0,    0,   11,    3,    0,    1,    1,    1,    3,    1,
+    0,    1,    0,    1,    0,    1,    0,    1,    0,    1,
+    1,    2,    1,    1,    2,    1,    1,    1,    1,    1,
+    0,    1,    1,    2,    0,    3,    0,    6,    3,    2,
+    1,    1,    1,    1,    1,    3,    0,    3,    1,    0,
+    3,    0,    1,    1,    3,    3,    1,    1,    1,    0,
+    4,    4,    0,    1,    1,    0,    1,    1,    2,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    0,    4,    0,    0,    0,    0,    0,
+   17,    5,    0,    9,    5,    0,    1,    1,    2,    3,
+    0,    3,    1,    1,    1,    0,    8,    0,    9,    6,
+    0,    0,    3,    0,    1,    1,    2,    2,    0,    5,
+    0,    1,    1,    2,    3,    0,    4,    2,    1,    1,
+    1,    0,    3,    0,    0,   10,    0,    0,    0,   12,
+    8,    5,    1,    1,    1,    1,    0,    4,    0,    1,
+    1,    3,    3,    3,    5,    3,    5,    1,    1,    1,
+    1,    3,    4,    6,    2,    4,    0,    7,    0,    1,
+    1,    2,    1,    1,    1,    4,    6,    4,    1,    2,
+    2,    1,    0,    0,    0,    0,   12,    0,    6,    0,
+    0,    4,    1,    1,    0,    0,   10,    3,    1,    1,
+    2,    1,    2,    1,    0,    5,    0,    5,    1,    1,
+    1,    0,    0,    0,    0,   15,    5,    0,    1,    1,
+    2,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    0,    5,    1,    1,    0,    7,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    0,
+    7,    0,    7,    2,    2,    2,    0,    0,    9,    1,
+    1,    0,    1,    0,    6,    0,    6,    2,    1,    0,
+    8,    0,    9,    0,    0,   10,    5,    0,    0,    3,
+    0,    1,    1,    2,    2,    0,    5,    0,    2,    2,
+    2,    1,    1,    1,    0,    5,    0,    5,    1,    1,
+    2,    4,    0,    0,    0,   12,    0,    2,    2,    0,
+    1,    2,    1,    3,    2,    0,    5,    3,    1,    0,
+    0,    0,   13,    0,    1,    1,    3,    3,    1,    4,
+    4,    2,    2,    0,    3,    2,    1,    3,    0,    3,
+    1,    1,    3,    1,    2,    3,    4,    4,    0,    3,
+    1,    3,    3,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    2,    2,    2,    1,    1,    2,
+    2,    2,    1,    3,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    2,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    3,    3,    4,    4,    5,    4,    4,
+    4,    3,    3,    3,    4,    3,    4,    4,    4,    3,
+    0,    1,    3,    4,    0,    1,    1,    3,    2,    3,
+    3,    1,    2,    3,    5,    2,    1,    1,    0,    1,
+    1,    3,    3,    3,    2,    1,    1,    1,    1,    2,
+    2,    4,    3,    1,    4,    5,    4,    3,    1,    3,
+    1,    3,    1,    1,    1,    4,    3,    2,    2,    6,
+    3,    7,    4,    3,    7,    3,    0,    2,    4,    3,
+    1,    2,    0,    1,    1,    3,    1,    2,    3,    1,
+    1,    1,    0,    1,    1,    2,    2,    3,    1,    2,
+    0,    1,    2,    4,    1,    3,    4,    1,    1,    1,
+    2,    4,    4,    4,    2,    4,    2,    4,    0,    4,
+    0,    5,    0,    1,    0,    4,    4,    1,    2,    2,
+    4,    2,    2,    2,    4,    2,    1,    2,    2,    2,
+    2,    2,    2,    2,    2,    2,    2,    2,    2,    1,
+    3,    3,    3,    3,    3,    3,    1,    3,    3,    3,
+    3,    3,    4,    3,    3,    3,    3,    1,    2,    1,
+    2,    2,    2,    2,    1,    1,    1,    3,    3,    3,
+    3,    1,    3,    3,    3,    3,    3,    3,    3,    3,
+    1,    3,    3,    3,    3,    1,    3,    3,    1,    3,
+    3,    1,    3,    3,    1,    3,    3,    1,    3,    3,
+    1,    3,    1,    5,    4,    5,    5,    3,    3,    3,
+    3,    3,    3,    3,    3,    3,    3,    3,    1,    3,
+    3,    2,    1,    1,    0,    1,    0,    2,    1,    1,
+    1,    1,    0,    4,    0,    4,    0,    5,    0,    0,
+    7,    0,    0,    8,    1,    1,    1,    1,    1,    1,
+    6,    4,    4,    1,    1,    0,    1,    3,    0,    1,
+    1,    2,    0,    6,    0,    0,    0,    0,   15,    0,
+    1,    0,    1,    1,    2,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    0,    1,    2,    3,    0,    1,    1,    2,    4,    3,
+    1,    3,    1,    3,    1,    1,    0,    1,    1,    1,
+    0,    4,    1,    1,    0,    4,    1,    0,    4,    0,
+    1,    1,    2,    1,    1,    1,    2,    1,    1,    2,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+    1,    1,    1,    1,    0,    4,    1,    2,    2,    2,
+    1,    1,    1,    2,    1,    1,    1,    0,    6,    0,
+    7,    1,    1,    0,    2,    1,    0,    1,    0,    1,
+    1,    2,    2,    4,    0,    2,    0,    1,    1,    2,
+    4,    1,    5,    2,    2,    2,    2,    2,    2,    1,
+    1,    1,    1,    1,    5,    7,    4,    0,    8,    4,
+    0,    1,    1,    2,    1,    2,    1,    2,    3,    3,
+    1,    1,    1,    1,    1,    5,    4,    7,    3,    6,
+    0,    4,    0,    4,    2,    0,    4,    2,    3,    1,
+    0,    1,    0,    5,    1,    0,    1,    0,    1,    1,
+    1,    3,    4,    5,    0,    9,    5,    4,    1,    1,
+    1,    1,    1,    1,    2,    2,    2,    3,    4,    3,
+    3,    3,    2,    3,    3,    2,    4,    4,    3,    0,
+    1,    3,    4,    5,    3,    1,    2,    0,    1,    3,
+    0,    8,    3,    6,    0,    4,    2,    2,    0,    3,
+    5,    4,    0,    0,   10,    0,    0,    9,    5,    4,
+    2,    1,    0,    2,    2,    2,    2,    2,    4,    5,
+    4,    5,    0,    5,    0,    6,    3,    2,    2,    2,
+    1,    0,    3,    0,    0,    5,    2,    1,    1,    2,
+    1,    1,    1,    1,    1,    0,    5,    0,    3,    0,
+    0,    0,   12,    0,    0,    0,   13,    0,    2,    0,
+    3,    1,    0,    4,    1,    0,    4,    1,    2,    2,
+    1,    2,    2,    0,    0,    4,    2,    3,    0,    4,
+    2,    2,    3,    0,    1,    1,    1,    2,    2,    2,
+    2,    4,    3,    0,    7,    4,    4,    3,    1,    3,
+    0,    0,    4,    0,    1,    1,    3,    2,
+  };
+   static readonly short [] yyDefRed = {            0,
+    8,    0,    0,    0,    0,    0,    0,    0,    2,    4,
+    0,    0,   11,   14,    0, 1047,    0,    0, 1051,    0,
+    0,   15,   17,  408,  414,  421,  409,  411,    0,  410,
+    0,  417,  419,  406,    0,  413,  415,  407,  418,  420,
+  416,    0,  369, 1069,    0,  412, 1058,    0,   10,    1,
+    0,    0,    0,   12,    0,  872,    0,    0,    0,    0,
+    0,    0,    0,    0,  449,    0,    0,    0,    0,    0,
+    0,    0,  447,    0,    0,    0,  515,    0,  448,    0,
+    0,    0,  969,    0,    0,    0,  710,    0,    0,    0,
+    0,    0,    0,    0,  771,    0,  824,    0,    0,    0,
+    0,    0,    0,    0,    0,  446,    0,  699,    0,  871,
+    0,  807,    0,  442,  832,  831,    0,    0,    0,  423,
+  424,  425,  426,  427,  428,  429,  430,  431,  432,  433,
+  434,  435,  436,  437,  438,  439,  440,  441,  444,  445,
+  706,  587,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  707,  705,  708,  709,  791,  793,
+    0,  789,  792,  808,  810,  811,  812,  813,  814,  815,
+  816,  817,  818,  819,  809,    0,    0,    0,  873,  874,
+  892,  893,  894,  895,  929,  930,  931,  932,  933,  934,
+    0,    0,    0,   20,    0,    0,  356,    0,  359, 1055,
+   16, 1048,    0,    0,  263,  262,  259,  264,  265,  258,
+  277,  276,  269,  270,  266,  268,  267,  271,  260,  261,
+  272,  273,  279,  278,  274,  275,    0, 1072, 1061,    0,
+    0, 1060,    0, 1059,    3,   55,    0,    0,    0,   44,
+   41,   43,   46,   47,   48,   49,   50,   53,   13,    0,
+    0,    0,  935,  565,  450,  451,  967,    0,    0,    0,
+    0,    0,    0,    0,    0,  937,  936,    0,  575,  569,
+  574,  823,  870,  794,  821,  820,  822,  795,  796,  797,
+  798,  799,  800,  801,  802,  803,  804,  805,  806,    0,
+    0,    0,  901,    0,    0,    0,  837,  836,    0,    0,
+    0,    0,    0,    0,    0,    0,  943,    0,    0,    0,
+    0,  422,    0,    0,    0,  946,    0,    0,    0,    0,
+  567,  968,    0,    0,    0,  835,  402,    0,    0,    0,
+    0,    0,    0,  388,  389,    0,  398,    0,    0,    0,
+    0,    0,    0,    0,  702,    0,  586,    0,    0,  695,
+    0,    0,  582,    0,    0,  584,  580,  594,  588,  595,
+  589,  583,  579,  599,  593,  598,  592,  596,  590,  597,
+  591,  693,  561,    0,  560,  443,  362,  363,    0,    0,
+    0,    0,    0,  825,    0,  355,    0,  400,  401,    0,
+    0,  518,  519,    0,    0,    0,  829,  830,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0, 1050,  790,  838,  828,    0,  868,  869, 1001, 1018,
+    0,    0, 1002, 1004,    0, 1030,  987,  985, 1011,    0,
+    0, 1009, 1012, 1013, 1014, 1015,  988,  986,    0,    0,
+    0,    0,   18,    0,    0,    0, 1068,    0,    0,  370,
+    0,    0, 1070,    0,    0,   42,  741,  747,  739,    0,
+  736,  746,  740,  738,  737,  744,  742,  743,  749,  745,
+  748,  750,    0,    0,  734,   45,   54,  517,    0,  513,
+  514,    0,    0,  511,    0,  840,    0,    0,    0,  899,
+    0,  867,  865,  866,    0,    0,    0,  714,    0,  940,
+  938,  715,    0,    0,  542,    0,    0,  530,  537,    0,
+    0,    0,  531,    0,    0,  547,  549,    0,  526,    0,
+    0,    0,    0,    0,  521,    0,  524,  528,  391,  390,
+  942,  941,    0,    0,  945,  944,  955,    0,    0,    0,
+  956,  559,    0,  385,  558,    0,    0,  970,    0,    0,
+  834,    0,  396,  397,    0,    0,  395,    0,    0,    0,
+  600,    0,    0,  571,    0,  697,  617,  616,    0,    0,
+  788,    0,    0,    0,  782,  784,  785,  786,  454,  455,
+    0,  366,  367,    0,  194,  193,  195,    0,  684,    0,
+    0,    0,  392,    0,  679,    0,    0,  949,    0,    0,
+    0,  462,  463,    0,  466,    0,    0,    0,    0,  464,
+    0,    0,  508,    0,  470,    0,    0,    0,    0,  496,
+  499,    0,    0,  491,  498,  497,  668,  669,  670,  671,
+  672,  673,  674,  675,  676,  678,  677,  604,  601,  606,
+  603,  605,  602,  614,  612,  615,    0,    0,  626,  625,
+    0,    0,    0,    0,  610,    0,  611,    0,  630,    0,
+    0,  631,    0,  637,    0,  638,    0,  639,    0,  640,
+    0,  644,    0,  645,    0,  648,    0,  651,    0,  654,
+    0,  657,    0,  660,    0,  662,    0,    0,  546,    0,
+    0,    0,    0,    0,    0,    0,    0,    0, 1000,  999,
+    0, 1010,    0,  998,    0,    0,  357,  358, 1066, 1067,
+    0,    0,  191,    0,    0, 1076,  384,    0,    0,    0,
+  381, 1062, 1064,   61,   63,   64,    0,    0,   56,    0,
+    0,   65,   67,   30,   28,    0,    0,    0,  731,    0,
+  735,  460,    0,  516,    0,  564,    0,  577,  180,  202,
+    0,    0,    0,  170,    0,    0,    0,  181,  570,    0,
+  973,    0,  921,  902,    0,  912,    0,  923,    0,  939,
+  877,    0,  972,    0,    0,  529,    0,  538,  548,  550,
+    0,    0,    0,    0,  482,    0,    0,  477,    0,    0,
+  692,  691,  509,    0,  552,  523,    0,    0,  151,  553,
+  149,  150,  555,    0,  563,  562,  880,    0,    0,    0,
+    0,  953,    0,  957,  557,  566,  980,    0,  976,  897,
+    0,  991,    0,  989,    0,    0,  712,  713,    0,    0,
+    0,  690,  689,  696,    0,  461,  787,  773,  774,  772,
+  783,  694,    0,  365,  682,    0,    0,    0,  585,  581,
+  948,  947,  826,  467,  459,    0,    0,  465,  456,  457,
+  568,  507,  505,  504,  501,  500,    0,  495,  452,  453,
+  468,  469,    0,  621,  622,  623,  624,  959,  613,  619,
+  665,    0,  846,    0,    0, 1019,  993,    0, 1020,    0,
+ 1003, 1005, 1016,    0, 1031,    0,  997, 1045,   19,  360,
+  361, 1078,  192, 1073,    0,  770,  769,    0,  768,    0,
+  380,    0,   60,   57,    0,    0,    0,    0,    0,    0,
+  387,    0,  725,    0,    0,   85,   84,    0,  512,    0,
+    0,    0,    0,    0,  185,  576,    0,    0,    0,    0,
+    0,  913,  905,  903,    0,  924,    0,    0,  971,  539,
+  536,    0,  486,    0,    0,    0, 1056, 1057,  473,  479,
+    0,  483,    0,    0,    0,    0,    0,    0,  878,    0,
+  963,    0,  960,  954,  979,    0,  896,  992,  990,    0,
+  572,    0,  698,  688,  368,  681,  680,  700,  458,  506,
+  503,    0,  494,  493,  492,  666,  667,  664,    0,  862,
+  845,    0,    0,    0,  851,    0,  995,    0, 1024,    0,
+    0, 1039, 1040, 1033,    0, 1077,  383,  382,    0,    0,
+   66,   59,    0,   68,   29,   22,    0,    0,  333,    0,
+  237,    0,  112,    0,   82,  856,  124,  125,    0,    0,
+    0,  859,  200,  201,    0,    0,    0,    0,  173,  182,
+  174,  176,  900,    0,    0,    0,    0,    0,  922,    0,
+    0,  487,  488,  481,  484,  480,    0,  474,  478,    0,
+  544,    0,  510,  520,  472,  556,  554,    0,    0,    0,
+  982,    0,    0,  711,  703,    0,  502,    0,    0,  843,
+  842,  839,  852,  994,    0,    0,    0, 1008,    0, 1006,
+ 1017,    0, 1046, 1065,    0,   79,    0,    0,   73,   74,
+   77,   78,    0,  350,  339,  338,    0,  726,  233,  107,
+    0,  841,  860,  186,    0,  198,    0,    0,    0,  898,
+  984,    0,    0,    0,    0,  904,    0,  925,  876,    0,
+  525,  522,  885,    0,  891,    0,    0,  883,    0,  887,
+  966,    0,  981,  977,    0,  701,    0,    0,  996, 1021,
+    0, 1007,    0,    0, 1035,    0,   80,   71,    0,    0,
+    0,  334,    0,    0,    0,    0,    0,  187,    0,  177,
+  175,  974,  914,  908,  906,    0,  485,    0,  879,  884,
+    0,  888,  964,    0,    0,  704,    0,  854,    0, 1025,
+ 1042, 1043, 1036,   58,    0,   75,   76,    0,    0,    0,
+    0,    0,    0,    0,  720,    0,  752,    0,  717,  861,
+  184,    0,  197,    0,    0,  926,  890,  889,    0,  978,
+  863,    0,    0,    0,   81,    0,    0,  351,    0,    0,
+  349,  335,    0,  343,    0,  405,    0,  403,    0,    0,
+  727,    0,  757,  234,    0,  188,  975,  910,  907,    0,
+    0,  919,  775,  777,  962, 1022,    0, 1037,    0,    0,
+    0,  331,    0,    0,  718,  754,    0,  723,    0,    0,
+  758,    0,  108,    0,    0,    0, 1026,   27,   26,   23,
+  352,  348,    0,    0,  344,  404,    0,  760,    0,    0,
+    0,    0,  909,    0,    0,    0,    0,    0,   32,  336,
+    0,  765,    0,  766,  763,    0,  761,  103,  104,    0,
+  100,    0,    0,   88,   90,   91,   92,   93,   94,   95,
+   96,   97,   98,   99,  101,  102,  152,    0,    0,  250,
+  242,  243,  244,  245,  246,  247,  248,  249,    0,    0,
+  240,  109,  776,    0, 1023,    0,  353,  347,  724,    0,
+    0,    0,    0,  728,   89,    0,  291,  286,  290,    0,
+  235,  241,    0, 1029, 1027,  764,  762,    0,    0,    0,
+    0,    0,    0,    0,    0,  300,    0,    0,  251,    0,
+    0,  257,    0,  167,  166,  153,  163,  164,  165,    0,
+    0,    0,  105,    0,    0,  285,    0,    0,  284,    0,
+  157,    0,    0,  374,  332,    0,  372,    0,    0,    0,
+    0,    0,    0,    0,    0,  729,    0,  236,  110,  115,
+  113,  307,    0,  371,    0,    0,    0,    0,  128,    0,
+    0,    0,    0,    0,    0,  162,  154,    0,    0,    0,
+  215,    0,  375,    0,  252,    0,    0,    0,    0,  304,
+    0,  282,  130,    0,  280,    0,    0,    0,  132,    0,
+  376,    0,    0,  204,  209,    0,    0,    0,  373,  255,
+  168,  111,  123,  121,    0,    0,  309,    0,    0,    0,
+    0,    0,  158,    0,  288,    0,    0,    0,    0,  136,
+    0,    0,    0,    0,  377,  378,    0,    0,    0,    0,
+    0,  118,  324,    0,  305,    0,    0,  318,    0,    0,
+    0,  313,    0,  148,    0,    0,    0,    0,  143,    0,
+    0,  301,    0,  133,    0,  127,  137,  155,  161,  224,
+    0,  205,    0,    0,  216,    0,  122,    0,  114,  119,
+    0,    0,    0,  320,    0,  321,  310,    0,    0,  303,
+  314,  283,    0,    0,  129,  144,  281,    0,  299,    0,
+  289,  293,  139,    0,    0,    0,  221,  223,    0,  256,
+  120,  325,  327,  306,    0,    0,  319,  316,  147,  145,
+  159,  298,    0,    0,    0,  156,  225,  227,  206,    0,
+  219,  217,    0,    0,  318,    0,  294,  296,  140,    0,
+    0,    0,    0,  329,  330,  326,  328,  317,  160,    0,
+    0,  231,  230,  229,  226,  228,  211,  207,  218,    0,
+    0,    0,  295,  297,  213,  214,    0,  212,
+  };
+  protected static readonly short [] yyDgoto  = {             7,
+    8,   50,    9,   51,   10,   11,   52,  237,  771,  772,
+   12,   13,   53,   22,   23,  331,  240,  756,  939, 1133,
+ 1257, 1310, 1634,  936,  241,  242,  243,  244,  245,  246,
+  247,  248,  749,  474,  750,  751, 1040,  752,  753, 1044,
+  937, 1128, 1129, 1130,  273,  641, 1225,  111,  948,  813,
+ 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351,
+ 1352, 1353, 1354, 1355, 1356,  593, 1382,  860,  493,  760,
+ 1437, 1054, 1238, 1195, 1236, 1271, 1322, 1393, 1478, 1266,
+ 1505, 1479, 1530, 1531, 1532, 1056, 1528, 1057,  822,  940,
+ 1490, 1464, 1518,  548, 1511, 1484, 1547, 1020, 1516, 1519,
+ 1520, 1615, 1548, 1549, 1545, 1357, 1416, 1386, 1438,  773,
+ 1492, 1594, 1461, 1551, 1626,  494, 1417, 1418,  274, 1447,
+  774,  775,  776,  777,  778,  731,  611, 1242,  732,  733,
+  954, 1440, 1469, 1562, 1523, 1596, 1648, 1632, 1470, 1657,
+ 1652, 1441, 1496, 1622, 1599, 1563, 1564, 1645, 1630, 1631,
+ 1052, 1194, 1302, 1369, 1421, 1370, 1371, 1409, 1444, 1410,
+  334,  227, 1527, 1412, 1512, 1509, 1358, 1388, 1433, 1591,
+ 1553, 1285, 1592,  642, 1640, 1641, 1432, 1508, 1481, 1540,
+ 1535, 1506, 1572, 1577, 1538, 1541, 1542, 1625, 1578, 1536,
+ 1537, 1636, 1623, 1624, 1049, 1137, 1262, 1230, 1293, 1263,
+ 1264, 1313, 1191, 1290, 1327,  388,  197,  113,  377,  378,
+  114,  604,  470,  230, 1456,  740,  741,  928,  941,  335,
+  336,  435,  327,  337,  311, 1267, 1268,   46,  118,  312,
+  120,  121,  122,  123,  124,  125,  126,  127,  128,  129,
+  130,  131,  132,  133,  134,  135,  136,  137,  138,  139,
+  140,  258,  891,  818, 1094, 1083,  806,  979,  807,  808,
+ 1084,  141,  202,  814,  644,  645,  646,  885,  503,  504,
+  304, 1092,  816,  436,  306,  532,  533,  534,  535,  538,
+  824,  566,  270,  509,  849,  271,  508,  142,  143,  144,
+  145,  673,  899,  674,  146,  147,  148,  149,  150,  151,
+  152,  153,  154,  155,  156,  614,  615,  616,  854,  855,
+  157,  601,  589,  851,  379, 1106,  585, 1175,  158,  523,
+ 1233, 1234, 1237, 1317, 1050, 1193, 1300, 1413,  495, 1272,
+ 1273, 1336, 1337,  929,  354, 1305,    0,    0,  594,  595,
+  275,  276,  277,  161,  162,  163,  278,  279,  280,  281,
+  282,  283,  284,  285,  286,  287,  288,  289,  175,  290,
+  621,  176,  177,  328,  905,  708, 1023, 1112,  951,  767,
+ 1060, 1021, 1024, 1153, 1025, 1061, 1062,  291,  178,  179,
+  180, 1166, 1098, 1167, 1168, 1169, 1170,  181,  182,  183,
+  184,  784,  516,  785, 1156, 1078, 1157, 1279, 1245, 1280,
+  786, 1077,  787, 1282, 1206,  185,  186,  187,  188,  189,
+  190,  313,  560,  561,  831, 1214,  324, 1076,  961, 1244,
+ 1103,  996, 1215,  191,  448,  192,  449, 1026, 1115,  450,
+  451,  724,  715,  716, 1120, 1030,  452,  453,  454,  455,
+  456, 1031,  710, 1028, 1219, 1306, 1375, 1117, 1253, 1326,
+  915,  718,  916, 1184, 1122, 1185, 1254, 1035,   17,   19,
+   47,   48,  229,  734,  932,  468,  735,  736,
+  };
+  protected static readonly short [] yySindex = {          -68,
+    0, -187,  189,  161,  258,18441,    0,  251,    0,    0,
+  258,  161,    0,    0,  303,    0, 8261,  258,    0, -151,
+ -258,    0,    0,    0,    0,    0,    0,    0,  249,    0,
+  448,    0,    0,    0, 5471,    0,    0,    0,    0,    0,
+    0,  297,    0,    0,  426,    0,    0,  720,    0,    0,
+  251,  495,  258,    0,  534,    0,  322,  590, -183,17987,
+  -27,  138,  512, 8419,    0,  138,  138,  138,  -90,  138,
+  138,  610,    0,10410,  138,  138,    0,10568,    0,  642,
+  138, -181,    0,  138,  645,  138,    0,18473,18473,  666,
+  138,  138,   97,10728,    0,17096,    0,11916,12048,12180,
+12312,12444,12576,12708,12840,    0,  232,    0, 9503,    0,
+  184,    0,   50,    0,    0,    0,  579,  500, -234,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  853,  917,  209,  755,  636,  338,  671,  697,
+  686,  694,  533,  713,    0,    0,    0,    0,    0,    0,
+ 3940,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   50,  745,  197,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+  377,  418,  495,    0,  517, -240,    0,  704,    0,    0,
+    0,    0, 9503, 9503,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  297,    0,    0,  712,
+  751,    0, -200,    0,    0,    0,  495,19024,  841,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,  877,
+   50,17233,    0,    0,    0,    0,    0,17096, -205, -141,
+  901,  811,  488,  500,   50,    0,    0, 9503,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,  156,
+  275,17987,    0, 9503,17096,  816,    0,    0,  826,17096,
+17096, 6467,  537,  -93,  874, 9503,    0,10728,  232, 1010,
+  897,    0,  913, 9503,17096,    0, 1022,  918,  690,  951,
+    0,    0,17096,  642,16685,    0,    0,  645,17096,  577,
+  634,  989,   50,    0,    0,  745,    0, -234, 1013,   50,
+17096,17096,17096,  512,    0,  980,    0, 9503, 9503,    0,
+11784,   50,    0, 8577,  250,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0, 1069,    0,    0,    0,    0,18291,  577,
+  959,  958,17096,    0,  562,    0,  126,    0,    0,  316,
+  259,    0,    0,  923,10860, 8893,    0,    0,17096,17096,
+17096,17096,17096,17096,17096,17096,17096,17096,17096,12972,
+13104,13236, 2103,15577,13368,13500,13632,13764,13896,14028,
+14160,14292,14424,14556,14688,14820,14952,15084,15216,17644,
+17096,    0,    0,    0,    0,  745,    0,    0,    0,    0,
+18473,18473,    0,    0,   50,    0,    0,    0,    0,  552,
+  981,    0,    0,    0,    0,    0,    0,    0,  495,  841,
+  927,  943,    0,  562,  297,  297,    0,  486,  107,    0,
+  297,  998,    0, -193,19024,    0,    0,    0,    0, -145,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  255,19054,    0,    0,    0,    0,  962,    0,
+    0, 1003,  788,    0, 1001,    0, 1011,  164,  642,    0,
+  138,    0,    0,    0,   50,16685, -115,    0, 1021,    0,
+    0,    0,  112,  168,    0,  811,  488,    0,    0, 1008,
+    0, 1041,    0, 1037,  983,    0,    0,  805,    0, 9167,
+  806,11018,  874,16548,    0, 9328,    0,    0,    0,    0,
+    0,    0,  174,  192,    0,    0,    0, -224,  642, -147,
+    0,    0,  645,    0,    0, 1042, 1044,    0,  195,   50,
+    0,  205,    0,    0,17096, 1126,    0,17096, 1129, 1050,
+    0, 1053, 1055,    0,18291,    0,    0,    0,  188,  962,
+    0,  -92, -272, 8577,    0,    0,    0,    0,    0,    0,
+  188,    0,    0, -235,    0,    0,    0,  645,    0,  577,
+   50, 9661,    0, 1056,    0, 1060,15348,    0, 1181, 1061,
+ 8577,    0,    0, 1014,    0,  962,   50,17233, 1015,    0,
+  562,  962,    0,  116,    0,17096,17096, 1067, 1186,    0,
+    0,  270,  146,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,17769,17769,    0,    0,
+ -234,    0,   50,  745,    0,  917,    0,  917,    0,11652,
+  209,    0,  209,    0,  755,    0,  755,    0,  755,    0,
+  755,    0,  636,    0,  636,    0,  338,    0,  671,    0,
+  697,    0,  686,    0,  694,    0,  -57, -180,    0,11018,
+ 1151,   50, 1152,   50,11018,11018, 1066,17096,    0,    0,
+  981,    0,   50,    0,  244,  562,    0,    0,    0,    0,
+ 9661,  486,    0, 1076, 1075,    0,    0,  707,  495,   -8,
+    0,    0,    0,    0,    0,    0, -185, 1077,    0, 1079,
+ 1081,    0,    0,    0,    0, 1083,10269, 1039,    0,  435,
+    0,    0,  687,    0,17233,    0, 1082,    0,    0,    0,
+  729,  141, 1086,    0, 1088, 1091, 1092,    0,    0,17096,
+    0,   50,    0,    0,  818,    0, 1094,    0,  256,    0,
+    0, 8419,    0, 8419, 9802,    0,15688,    0,    0,    0,
+ 9962,10094,  422,11018,    0,    7,  149,    0, 1031, 1046,
+    0,    0,    0,  834,    0,    0, 1099, 1098,    0,    0,
+    0,    0,    0, 1100,    0,    0,    0, 1106,  138, 4352,
+  642,    0,  642,    0,    0,    0,    0, 8419,    0,    0,
+ 8419,    0,17096,    0,17096, 9503,    0,    0,  642, 1103,
+  188,    0,    0,    0,17096,    0,    0,    0,    0,    0,
+    0,    0, 9503,    0,    0,   50,18291, 1135,    0,    0,
+    0,    0,    0,    0,    0,  962,  842,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,16411,    0,    0,    0,
+    0,    0, 9486,    0,    0,    0,    0,    0,    0,    0,
+    0,10252,    0, 9644, 1108,    0,    0, 1190,    0, 1191,
+    0,    0,    0,  932,    0, 1111,    0,    0,    0,    0,
+    0,    0,    0,    0,  486,    0,    0, 1068,    0,  107,
+    0,  486,    0,    0,  927, 1119, 1122, 1072, 1130, 1039,
+    0, 1121,    0, 1245, 1246,    0,    0,11018,    0,16822,
+ 1128,  729, 9661, 9503,    0,    0,  371, 1249, 1250,  219,
+ 1127,    0,    0,    0,17096,    0,17096, 1230,    0,    0,
+    0,16959,    0,  342,16959,  848,    0,    0,    0,    0,
+ 9030,    0, 1256,  745,11018, 1145, 9802, 1146,    0,17096,
+    0,   50,    0,    0,    0,  -87,    0,    0,    0, 1141,
+    0, 1174,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  706,    0,    0,    0,    0,    0,    0, 9503,    0,
+    0,   50, -242, 1108,    0,11018,    0,11018,    0,  191,
+11018,    0,    0,    0,  503,    0,    0,    0, 1150,  927,
+    0,    0,11176,    0,    0,    0, 1155, 4512,    0, 1039,
+    0, 1039,    0, 1039,    0,    0,    0,    0,   50, 1156,
+ 1128,    0,    0,    0, -109, -125, 1154, 1157,    0,    0,
+    0,    0,    0, 1159, 9802, 1108, -180,17096,    0, 1166,
+ 8419,    0,    0,    0,    0,    0, 1158,    0,    0, 1170,
+    0,  874,    0,    0,    0,    0,    0, -201, 1169, 1171,
+    0, 1108, 1175,    0,    0,  188,    0, 1123, 1167,    0,
+    0,    0,    0,    0,11018, 1204,11018,    0,11018,    0,
+    0,17096,    0,    0, 1081,    0,  515,  739,    0,    0,
+    0,    0,  161,    0,    0,    0, 1185,    0,    0,    0,
+ 1172,    0,    0,    0,  682,    0, 1176, 1300, 1303,    0,
+    0, 1108, 1193, 1108, 1195,    0, 1187,    0,    0,16959,
+    0,    0,    0,17096,    0, 1194, -209,    0, 8101,    0,
+    0, 1313,    0,    0,  188,    0,17096, 9644,    0,    0,
+ 1223,    0,  964, 1197,    0, 1202,    0,    0,11176,  258,
+  164,    0,  852, 1199, 1205,16822, 1207,    0,17096,    0,
+    0,    0,    0,    0,    0, 8419,    0,   77,    0,    0,
+ 8577,    0,    0, 1290, 8419,    0, 1213,    0,11018,    0,
+    0,    0,    0,    0,17096,    0,    0,  495, 1214,  495,
+  164, 9503, 1199, 1253,    0, 1253,    0, 1199,    0,    0,
+    0,17096,    0, 8419,11334,    0,    0,    0,  906,    0,
+    0, 1240,11018,17096,    0,  495, 1220,    0, 1180,  991,
+    0,    0, 1225,    0, 1222,    0,  165,    0, 1229, 1183,
+    0, 1253,    0,    0, 1253,    0,    0,    0,    0, 1231,
+ 1094,    0,    0,    0,    0,    0, 1255,    0,   68, 1253,
+ 1349,    0, 1238,  495,    0,    0, 9503,    0,  106, 1241,
+    0, 1242,    0, 8419, 8577,11018,    0,    0,    0,    0,
+    0,    0, 1226, 1235,    0,    0,16548,    0, 2289,   66,
+  495, 1247,    0, 1248, 1260,11018, 1251,17096,    0,    0,
+ 1254,    0, 1257,    0,    0, 1243,    0,    0,    0,19054,
+    0, 1261,   66,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  714,19054,    0,
+    0,    0,    0,    0,    0,    0,    0,    0, 1262,  495,
+    0,    0,    0,   50,    0, 1260,    0,    0,    0, 1259,
+ 2289, 8577,18159,    0,    0,  595,    0,    0,    0, 5312,
+    0,    0,   66,    0,    0,    0,    0, -272, 9503, 9503,
+  176, 9503,  477,  645, 1282,    0,  577, 1663,    0, 1317,
+    0,    0, 1235,    0,    0,    0,    0,    0,    0, 4029,
+ 1235, 1264,    0, -123, -120,    0, 9503, -118,    0, 9503,
+    0, 1215, 1265,    0,    0,   12,    0,  143, 4675,    0,
+ 1266, 1219,  153,  595, 5471,    0,17096,    0,    0,    0,
+    0,    0,   12,    0, 1271, 1221, 1269, 1267,    0, 1270,
+ 1224, 1275,  164, 1272, 1274,    0,    0, 1280, 1281, 1310,
+    0,  962,    0,  965,    0, 1296, 1292, 1235,  -62,    0,
+ 1288,    0,    0, 1301,    0, 1304, 1299, 1302,    0, 1306,
+    0,  164,  164,    0,    0,  164, 1305, 1309,    0,    0,
+    0,    0,    0,    0, 1314,  150,    0, 1316,  164, 1421,
+ 1318,  164,    0,  501,    0, 9802, 1273, 1308, 1306,    0,
+ 1321, 1322,  152, 1325,    0,    0,  164,16822, 1278, 1323,
+ 1314,    0,    0,19054,    0,  495,  495,    0, 1279, 1324,
+ 1316,    0, 1326,    0,17096, 1284, 1327, 1318,    0, 1332,
+  164,    0,  114,    0, 1328,    0,    0,    0,    0,    0,
+19054,    0,  152,  152,    0, 1333,    0,  -62,    0,    0,
+  409, 1338,19054,    0,19054,    0,    0, 9802, 1329,    0,
+    0,    0, 1337, 1301,    0,    0,    0, 1336,    0,  208,
+    0,    0,    0, 1253, 1017, 1343,    0,    0,  538,    0,
+    0,    0,    0,    0, 1398, 1451,    0,    0,    0,    0,
+    0,    0, 1344, 1345, 9802,    0,    0,    0,    0,  152,
+    0,    0,  580,  580,    0, 1253,    0,    0,    0, -143,
+ -143, 1340, 1354,    0,    0,    0,    0,    0,    0,16548,
+16548,    0,    0,    0,    0,    0,    0,    0,    0, 1360,
+ 1361,16822,    0,    0,    0,    0, 1358,    0,
+  };
+  protected static readonly short [] yyRindex = {         1936,
+    0,    0, 8735, 1936,    0,    0,    0, 1736,    0,    0,
+ 3522, 1489,    0,    0,    0,    0,    0, 3522,    0,    0,
+   56,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0, 1737,    0,    0, 1737,    0,    0, 1737,    0,    0,
+ 1736, 3602, 2027,    0,    0,    0,    0,    0,    0,    0,
+    0,    0, 1371,    0,    0,    0,    0,    0,    0,    0,
+    0,10427,    0, 1363,    0,    0,    0, 1363,    0,    0,
+    0,    0,    0,    0, 3192,    0,    0,    0,    0,    0,
+    0,    0,    0,  190,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0, 5375,    0,    0,    0,
+    0,    0,    0,    0,    0,    0, 5788, 5311, 5699,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0, 5893, 6070, 4119, 6623, 7048, 7255, 7393, 7531,
+ 7669, 7807, 1311, 5470,    0,    0,    0,    0,    0,    0,
+   56,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  238,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0, 3649,    0,  688,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0, 1737,    0,    0,  307,
+    0,    0,    0,    0,    0,    0, 3712,  432, 3755,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0, 4351,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0, 1373,    0,    0,    0,    0,    0,    0, 4351, 1366,
+    0,    0,    0,    0,    0,    0, 1366,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0, 2148,    0,  403,
+ 2851,    0,    0,    0,    0, 2982,    0, 2851,    0,    0,
+    0,    0,    0, 1371,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  198,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0, 1372, 3087,
+    0,    0, 1363,    0, 4351,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  278,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0, 2384,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+ 1852,    0,    0,    0,    0,    0,    0,    0, 3798, 3861,
+    0,    0,    0, 1531, 1737, 1737,    0, 8910, -206,    0,
+ 1737, 1744,    0,    0,   84,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  479,17919,    0,    0,    0,    0, 4351,    0,
+    0,    0,    0,    0,    0,    0,    0,18191,    0,    0,
+    0,    0,    0,    0,    0,  868,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  233, 1047,    0,    0,  230,
+ 1928,    0,    0, 1378,  513,    0,    0,    0,    0,  215,
+    0,    0, 4831, 1376,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0, 1384,    0, 2553,
+    0,    0,  222,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0, 1372,    0,    0,    0,17370, 4351,
+    0, 7940,    0,  225,    0,    0,    0,    0,    0,    0,
+17370,    0,    0,    0,    0,    0,    0,   60,    0,  703,
+    0,    0,    0, 1381,    0,    0,    0,    0, 1366,    0,
+    0,    0,    0, 4191,    0, 4351,    0,    0, 4030,    0,
+ 4351, 4991,    0,    0,    0,    0,    0, -202,    0,    0,
+    0,    0,  313,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+ 5535, 5640, 6142, 5965,    0, 6247,    0, 6319,    0,    0,
+ 6469,    0, 6554,    0, 6692,    0, 6761,    0, 6830,    0,
+ 6899,    0, 7117,    0, 7186,    0, 7324,    0, 7462,    0,
+ 7600,    0, 7738,    0, 7876,    0,    0,  749,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+ 1852,    0,    0,    0,    0, 1531,    0,    0,    0,    0,
+    0,11035,    0,    0,  817,    0,    0, 1339,15851,    0,
+    0,    0,    0,    0,    0,    0,  781,  774,    0,    0,
+ 1385,    0,    0,    0,    0, 1820,    0,    0,    0,    0,
+    0,    0,11492,    0,    0,    0,  845,    0,    0,    0,
+11193,18364,    0,    0,  881,  920,  937,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  870,    0,    0,    0,
+    0,    0,    0,    0,    0,    0, 1386,    0,    0,    0,
+    0,    0, 6961,    0,    0,    0,  261,    0,  117, 4511,
+    0,    0,    0,    0,    0,    0,    0, 1387,    0,    0,
+    0,    0,    0, 1388,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+17370,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0, 4351,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  674,    0,    0,    0,    0,    0,
+    0,    0,    0, -169,    0,  576,    0,    0,    0,    0,
+    0,    0,    0,    0,11193,    0,    0,    0,    0, -206,
+    0, 9345,    0,    0, 1391,    0,  873,    0,    0,    0,
+    0, 1395,    0, 1346, 1348,    0,    0,    0,    0,    0,
+ 1382,11351,    0,    0,    0,    0,18396,    0,    0,    0,
+  939,    0,    0,    0,    0,    0,    0, 2721,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0, 4671,    0, 5151, 1399,    0,    0,    0,
+    0, 1396,    0,    0,    0,  939,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  771,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  940,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+ 1394,    0,    0,    0,    0,    0,  957,  960,    0,    0,
+    0,    0,    0,    0,    0, 1401,  761, 1400,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0, 4831,    0,    0,    0,    0,    0, 1403,    0,    0,
+    0, 1401,    0,    0,    0,17370,    0,  752,  762,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0, 1385,    0,15689,    0,    0,    0,
+    0,    0,18521,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  793,    0,  798,    0,    0,    0,
+    0, 1402,    0,  895, 1404,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0, 1407,    0,    0,    0,
+    0,  202,    0,    0,17370,    0,    0,    0,    0,    0,
+    0,    0,  113,  678,    0,    0,    0,    0,    0,18592,
+18191,    0,  386,  511,  449,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+ -208,    0,    0, 1020,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,18748,    0, -253,
+18191,    0,  522, 1410,    0, 1410,    0,  511,    0,    0,
+    0,    0,    0,    0, 1406,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,18791,    0,    0,    0,16125,
+    0,    0, 1411,    0,    0,    0,  364,    0,  532,    0,
+    0,  606,    0,    0, 1410,    0,    0,    0,    0,    0,
+ 1409,    0,    0,    0,    0,    0,    0,    0, 3479, 1412,
+  493,    0,    0,  333,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0, 1414,    0,    0,    0,    0,    0,
+    0,    0,    0, 3363,    0,    0, 1376,    0,    0,15957,
+16209,    0,    0,    0,  767,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  617,    0,    0,    0,18091,
+    0,    0,16041,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0, 5152,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,16293,
+    0,    0,    0,    0,    0,  767,    0,    0,    0,    0,
+    0,  198,  479,    0,    0,    0,    0,    0,    0,  479,
+    0,    0,15957,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0, 4830,  507,    0,16335,    0,    0,    0,
+ 4990,    0, 3363,    0,    0,    0,    0,    0,    0,    0,
+ 3363,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  257,    0,  584,    0,  647,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  824,    0,  692,    0,    0,    0,    0,    0,
+    0,    0,18191,  947,    0,    0,    0,    0,    0,    0,
+    0, 1390,    0,  438,    0,    0,    0, 3363,    0,    0,
+  963,    0,    0,    0,    0,    0,    0,    0,    0, 1417,
+    0,18191,18191,    0,    0,18259,    0,    0,    0,    0,
+    0,    0,    0,    0, 1418,15719,    0, 1420,18191,17507,
+ 1425,18191,    0,    0,    0,    0,    0,    0, 1426,    0,
+    0,    0,18984,    0,    0,    0,18191,    0,    0,    0,
+ 1427,    0,    0,  424,    0,18914,18954,    0,    0,    0,
+ 1428,    0,    0,    0,    0,    0,    0, 1430,    0,    0,
+18191,    0,  716,    0,  968,    0,    0,    0,    0,    0,
+ 1029,    0,18834,18874,    0,    0,    0,    0,    0,    0,
+    0,    0, 1469,    0, 1525,    0,    0,    0,  978,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  611,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,18984,
+    0,    0,18634,18672,    0,  611,    0,    0,    0,    0,
+    0,15498,    0,    0,    0,    0,    0,    0,    0, 1376,
+ 1376,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,
+  };
+  protected static readonly short [] yyGindex = {            0,
+    0, 1757,    0,    0,    0,   -1,  -16, -178,  -44,  -41,
+    0, 1797, 1806,  103,    0,    6,    0,    0,    0,    0,
+    0,    0,-1157, -774, -216, -708,    0,    0,    0,    0,
+    0, -221,    0,    0,    0,  776,    0,  883,    0,    0,
+    0,    0,  630,  632,  -17, -227,    0,  -47,    0, -112,
+  430,    0,  487, -587, -577, -576, -541, -537, -525, -516,
+ -503,    0,    0,-1152,    0,-1187,    0,  434,-1258,    0,
+    3,    0,    0,    0,  596,-1183,    0,    0,    0,   -3,
+  267,    0,    0,    0,  306,-1151,    0, -281, -301, -354,
+    0,    0,    0, -985,  262,    0,    0, -529,    0,    0,
+  320,    0,    0,  299,    0,    0,  401,    0, -630, -856,
+    0,    0,    0,    0,    0, -404,  335,-1396,  -10,    0,
+    0,    0,  893,  898,  900, 1089, -572,    0,    0, -336,
+  902,  436,    0, -905,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  234,    0,    0,
+    0,    0,    0,    0,    0,    0,  496,    0,    0,    0,
+ -315,  423,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  505,    0, -531,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  246,    0,    0,  331,    0,    0,  336,
+  340,  266,    0,    0,    0,    0,    0,    0,    0,    0,
+  598,    0,    0,    0,    0,  -86,    0,  135, -373, -304,
+ 1277,    0,  421,    0, -349,    0,  966,    0, 1577,  148,
+ -305, -274,  -81,  203, 1232,    0,  601,    0,  -21,  509,
+ 1495,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0, -267,
+    0,   28,    0, -352,    0, -280,    0,    0,    0,  931,
+ -927, -313, -132,  554,    0, 1026,    0, 1276, -343, 1160,
+    0,    0,  828, 1851,    0,    0,    0,    0, 1137,    0,
+    0,    0, 1593,    0,    0,    0,    0,    0, 1627,  986,
+  987,    0,  946,    0,  812,  984, 1514, 1515, 1513, 1516,
+ 1517,    0, 1512,    0,    0,    0, 1084, 1364, -569,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0, -306,
+  748,    0, -444,    0,    0,    0,    0,    0, -475,    0,
+  681,    0,  573,    0,    0,    0,    0,    0,  787, -563,
+  -11, -334,   -7,    0, 1796,    0,   48,    0,   85,   91,
+  111,  128,  157,  173,  175,  181,  193,  194,    0, -662,
+    0,  -23,    0,    0,  882,    0,  804,    0,    0,    0,
+    0,  784, -959,  862, -931,    0,  905, -489,    0,    0,
+    0,    0,    0,    0,  800,    0,  802,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  724,    0,    0,    0,    0,    0,    0,    0,
+    0,  -31,    0, 1416,  763,    0,    0,  985,    0,    0,
+    0,    0,    0,    0, -176,    0,    0,    0,    0,    0,
+ 1529, 1283,    0,    0,    0,    0, 1532,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  607,    0,    0,    0,
+    0,    0,    0,    0,    0,  731,    0,    0,    0,    0,
+    0,    0,   35, 1054,    0,    0,    0, 1062,
+  };
+  protected static readonly short [] yyTable = {           110,
+  550,  193,   18,  547,  564,  159,  112,  238,   44,  160,
+  239,  622,  817,  519,  459,  458,  823,  497,  761,  597,
+  476,  299,  572,  545,  501,  196,  783,  580,  432,  543,
+  861,  862,  397, 1108,  531,  389,  265,  398,  264,  866,
+  332,  339,  612,  643, 1240,  346,  318, 1086,  257,  988,
+  254,  634, 1274,  710, 1163, 1054,  310,  873, 1164,  886,
+  317,  577,  744,  613,  164,  385, 1164,  829,   14,  319,
+  933,  322,  254, 1495,  321,  903,   20, 1261,  355,  232,
+  623, 1383,  234,    6,  333,  340, 1038,   51,  745,  268,
+  727, 1303, 1113,  292,  293,  294,  858,  300,  301,   51,
+ 1390,  165,  314,  315,  194,  381, 1311,  166,  320,  323,
+  754,  325, 1642,  329,  321,  340, 1152, 1324,  342,  343,
+  746,  558,  386,  201,  472,  762, 1110,  167,  434,  968,
+ 1146,  969, 1450,  462, 1111, 1452,  463, 1458,  833,  863,
+  788, 1261, 1152,  110,  168,  396, 1144,  255,  238,  159,
+  112,  460,  326,  160,  198,  201, 1330,  859,  922,  728,
+  886,  709,  539,  857,  115,   51,  255,  501, 1101, 1038,
+  710,  200,  710,  169, 1038,  995, 1038,  295,  997, 1038,
+ 1038,  864, 1038, 1038,   95,  296,   95,    1,  255,  170,
+  255,  171,  475, 1503, 1398,  460,  256,  172,  901,  465,
+  466,  904, 1621,  499,  502, 1038,  373,  115,  164,  173,
+  174,  115,   51, 1165,  886,  256,  856,  506,   43,  116,
+ 1113, 1165,  198,  198,   95,  747,  809,  710,  266,  374,
+  255,   15, 1207, 1643,  500,  473,  375,  256,  497,  256,
+  505,  815,  476,  198,  573,  165,  571,  297,  612,  574,
+  372,  166,  875,  297,  530, 1446,  389,  879,  881,  597,
+ 1038,  467,  116, 1448,  507,  970,  116,  195,  515,  613,
+  264,  167,  297,  755,  540, 1571,  541,  518,  255,  256,
+  264, 1003,  522,  524,  877,  576,  597,  323,  168,    2,
+  517,  396,  579, 1147, 1075, 1451,  613,  554, 1453,  373,
+ 1459,  570, 1595,  298,  590,  567,  379,  569,  115,  298,
+  553,  522, 1054,  568, 1605,  393, 1606,  169,  902, 1504,
+ 1502, 1338,  374, 1308,  582,  583,  880,  256,  298,  375,
+  542,  544, 1247,  170, 1229,  171,  376,  198,  198,  626,
+    6,  172,  596,  631,  587,  588,  598,  502,  502,  267,
+ 1186,  620,  920,  173,  174,  732,    3,    4,    5,    6,
+  732, 1318,  737,  116,  732,  619,  930,  791, 1041, 1589,
+  603,  882, 1054,  344, 1265,  977, 1567,  500,  640,  732,
+ 1065,  647,  648,  649,  650,  651,  652,  653,  654,  655,
+  656,  657,  264,  711,  713,  923,  955,  717, 1466,  900,
+  501,  892,  198,  373,  980, 1533,  732, 1560,  931,  665,
+ 1616,  510,  297,  707,  238,  613, 1428,  460, 1159,  769,
+ 1296,  921,  393,  793,  738,  732,  374,  739,  198,  825,
+  393, 1426,  393, 1339,  393,  236,  978,  712,  714,  115,
+  198,  564, 1639,  852, 1309,   16, 1118,  827,  198,  382,
+  837, 1041, 1248,  549,  198,  837, 1041, 1096, 1041,  297,
+  840, 1041, 1041, 1612, 1041, 1041,  725,  781,  298,  789,
+  413, 1613,  115,  960, 1073, 1079,  236, 1473,  393,  748,
+ 1427, 1319,  198,  198,  792, 1054,  883, 1041,  297, 1590,
+  765, 1054,  782,  961,  116,  511,  502,  383,  779,  729,
+  730,  115, 1009,  837,  770,  742,  414,   49,  198,  255,
+  236,  966,  369,  198, 1467,  298,  345,  497,    2,  236,
+  893,  236,  839,  981,  812,  119,  640,  116,  821,  531,
+  612,  757, 1614,  236, 1012,  758, 1176,  501,  780, 1297,
+  794, 1119, 1041, 1246,  624, 1151,  826,  198,  832,  967,
+  497,  613, 1250,  203,  625,   95,  116,  842,  256,  384,
+  844,  669,  379,  865,  828,  837,  780,  838,  119,  961,
+  961, 1474,  119,  437,  372,  198,  198,  841,  853,  876,
+  502, 1277,  596,  475,  896,  830,  598,  415,  416,  897,
+  853, 1074,   20,  781,  386,  198,  759,  906,  540,  369,
+  827,  837,  911,  912,  540, 1216, 1488,  837,  198,  596,
+  500, 1341, 1360,  598,  837, 1063,  670,  462,  884,  884,
+  919,  297,  599,  373,  369,  898,  438,  780,  369,  476,
+  364,  126,  439,  126, 1341, 1521, 1522,  613,  126, 1524,
+  386, 1323,  889,  512,  475,  379,  374,  861, 1058,  379,
+  489,  513, 1543,  375,  781, 1550,  827, 1597, 1598,  540,
+  376, 1360,  837,  115,  908, 1014,  910,  809,  228,  119,
+ 1566, 1602,  369,  439,  379,  918,  982,  629,  379,  600,
+  379,  379,  379,  379, 1341,  490,  732,  630,  379,  627,
+  476,  250,  812,  379, 1588,  251,  836,  812,  812,  890,
+  914,  342,  753,  732,  514, 1095,  943,  489,  732, 1091,
+ 1085, 1067,  732,  550, 1633,  440,  985,  502,  116,  198,
+  441,   55,  442, 1603,  719,  443,  444,  732,  445,  446,
+  944,  753, 1429, 1361,  962,  753,  423,  424,  732,  628,
+  236,  115,  490, 1362, 1363,  252,  198,  500, 1235,  530,
+  730,   51,  204,  719,  732,  783,  440,  945,  439,  364,
+  942,  441,  522,  442,  372,  364,  443,  444,  115,  445,
+  446, 1155,  364,  732,  730,  264,  364,  821,  731, 1364,
+  379, 1430, 1361, 1365,  812, 1331,  812,  716, 1269,  364,
+  815,  605, 1362, 1363, 1454, 1366,  116,  228,  606,  231,
+  119,  730,  731,  975, 1367,  379,  447,  719, 1468,  379,
+  607,  364,  379,  373,  379, 1132,  716, 1368, 1006,  379,
+  993,  364,  994,  116,  716,  998,  992,  999, 1364,  731,
+ 1486, 1032, 1365,  119,  597, 1055,  374, 1004, 1001,  502,
+  853,  440, 1000,  375, 1366,  502,  441,  457,  442,  751,
+  376,  443,  444, 1367,  445,  446,  990,  372, 1123, 1005,
+  721,  345,  119,  390,  236,  198, 1368,  345,   95,  640,
+  722,  255, 1093,  391,  346,  640,  597, 1415,  751,  373,
+ 1414,  535, 1208,  269, 1018,  738,  821,  535,  739,  721,
+  440,  198,  392,  393, 1058,  441, 1187,  442,  461,  722,
+  443,  444,  374,  445,  446, 1620,  373,  536,  373,  375,
+  249,  537,  394, 1114, 1032, 1116,  376, 1243, 1121, 1032,
+  256, 1032,  671,  395, 1032, 1032,  371, 1032, 1032,  374,
+  812,  374,  518, 1034,  429,  386,  375, 1414,  375,  115,
+  748,  115, 1047,  376,  898,  557,  430,   95,  756, 1080,
+ 1066,  371,  387,  755, 1082,  759, 1329, 1082,  558,  759,
+ 1276, 1132,   95,  761,  198,  326,  253,  812,  373,  821,
+  597, 1415, 1099,  756, 1109,  559,  374,  302,  755,  303,
+  198,  720,  756,  375,  759,  115, 1554,  755,  115,  208,
+  386,  374,  946,  759,  116,  502,  116,  198,  375,  947,
+  926,  198, 1179, 1439, 1181, 1032, 1182,  462,  812,   95,
+  812, 1141,  927,  812,  203, 1439, 1034, 1145,  419,  420,
+  326, 1034, 1028, 1034,  119, 1131, 1034, 1034, 1408, 1034,
+ 1034,  326,  421,  422,  605, 1420,  952,  341,  497,  476,
+  116,  606,  847,  116, 1136,  748, 1378,  597, 1607, 1256,
+  847, 1197, 1138,  607, 1139,  425, 1140,  821, 1443,  364,
+  522,  364, 1465, 1198,  364,  364,  302, 1411,  302,  198,
+ 1443,  427,  364,  302, 1411,  683,  364,  683, 1107, 1465,
+  893, 1283, 1284,  292,  292, 1629,  426,  198,  198,  364,
+ 1387,  228,  292,  233,  428,  853,  550,  812, 1497,  812,
+ 1498,  812,  119,  431, 1183, 1028, 1252, 1034, 1650, 1651,
+ 1028, 1188, 1028, 1189,  303, 1028, 1028,  844, 1028, 1028,
+  864,  364,  464,  844,  864,  844,  864,  469,  864,  119,
+  853, 1190,  498,  844,  853,  844,  853,  844,  853,  848,
+ 1287,  502, 1082,  848,   69,   69,  518,  848,   69,  417,
+  418,  364,  364,  198,  364,  364,   62,  596,  764, 1217,
+  821,  598,  765,  183,  853,  183,  549,  183,  196,  471,
+  196, 1131,  196, 1228,  198,  799,  810,  344,  518,  800,
+  537,  518,  198,  238,  352, 1259,  460, 1075, 1260, 1075,
+  963,  369,  520, 1325,  964,  369, 1028,  364,  369,  596,
+  369,  812,  521,  598,  984,  369,  562, 1255,  985,  496,
+  236,  238, 1010, 1376,  460,   24,  765,   25, 1087,  855,
+   26,  855,  985, 1231,  518,   27, 1058, 1232,  115,   28,
+  685,  687,  689,  691,  399,  812, 1183,   45,   30,  369,
+  911,  546,  915,   70,  911,   32,  915,   70,  117, 1259,
+   33,  171, 1260,  171,   34,  400,  401,  402,  403,  404,
+  405,  406,  407,  408,  409,  551,   36,  847,   37,  502,
+  387,  847,   38, 1283, 1284, 1340, 1359,  555, 1260,  739,
+   39,   40,  575,  116,   41, 1032, 1033,  563,  812,  552,
+  178,  117,  178,  596,  556,  117,  199,  598, 1340,  640,
+  119, 1260,  119,  410,  411,  412,  578,  179,  812,  179,
+  518,  983,   72,  983,   72, 1335,  115, 1221, 1222,  338,
+  338,  131,  586,  131,  602, 1359, 1394,  202,  739,  202,
+  172,  617,  172,   24,  618,   25,  723,  308,   26,  308,
+  338,  632,  138,   27,  138,  380,  119,   28, 1340,  119,
+ 1656, 1260,  315,  115,  315,  974,   30,  976,  115, 1292,
+  236,  726,  115,   32,  199,  199,  198,  743,   33,  380,
+  596,  116,   34,  766,  598, 1419,  374, 1335,  763,  374,
+  469, 1617, 1618,  768,   36,  199,   37,  965,  965,  795,
+   38,  115,  117,  732,  732, 1424, 1425,  790,   39,   40,
+  676,  678,   41,  681,  683,   85,  693,  695,  116,  796,
+  364,  797,  798,  116,  835,  836,  836,  116,  364,  843,
+  364,  836,  845, 1457,  846,  847, 1460,  848,  836, 1477,
+  867,  198,  868, 1419,  338,  338,  871,  872,  887,  364,
+  364,  888,  874,  878,  907,  909,  116,  913,  924,  925,
+  462,  115,  115,  198,  934,  935,  938,   43,  956,  364,
+  200, 1534,  957,  950,  739,  958,  959,  364,  965,  983,
+  364,  986,  893,  989,  987, 1002,  836, 1008, 1561,  199,
+  199,  739, 1022, 1027, 1029, 1034, 1037,  380,   38, 1042,
+ 1045, 1573, 1575, 1043,  739,  739, 1048, 1046,  821,  338,
+ 1051, 1053, 1059, 1419, 1071, 1072,  116,  116, 1075, 1081,
+  518, 1090,  540, 1104, 1097,  198, 1105,  198, 1561, 1561,
+ 1124,  739,  739,  117,  198,  338, 1134, 1583, 1148,  115,
+  364, 1149, 1142,  198,  198, 1150,  198,  338, 1158, 1160,
+ 1161, 1171, 1442, 1172,  199,  338, 1177, 1174, 1178,  549,
+ 1180,  338, 1192, 1196, 1442, 1200,  117, 1199, 1201, 1442,
+  821,  198, 1209, 1205,  198, 1202,  661, 1204, 1213, 1220,
+  199, 1223, 1224, 1442, 1232, 1561, 1231, 1241,  739,  338,
+  338,  829,  199, 1251,  116,  117, 1258, 1286, 1289,  119,
+  199, 1270,  502,  502, 1295, 1442,  199,  821, 1291, 1294,
+ 1298, 1299, 1307, 1304, 1312,  338, 1314, 1328, 1320, 1321,
+  338, 1329, 1635, 1635, 1372, 1374, 1373, 1381, 1431, 1644,
+ 1644, 1445,  640,  640,  199,  199, 1379, 1377, 1380, 1384,
+ 1391, 1396, 1449, 1462, 1655, 1471, 1463, 1472, 1480, 1474,
+ 1482, 1485, 1453, 1483,  338,  117, 1487, 1491, 1494,  661,
+  199, 1493, 1414, 1489,  661,  199,  661,  661,  661,  661,
+  661,  661,  661,  661,  661,  661,  661, 1500, 1501, 1507,
+ 1510, 1514,  338,  338, 1515, 1513, 1544,  119, 1525,  661,
+ 1517,  661, 1526,  661, 1556,  661,  661,  661, 1529,  199,
+ 1539, 1555, 1546, 1558, 1559, 1565, 1568, 1579, 1582, 1569,
+ 1580,  661, 1584, 1585, 1587, 1600, 1604, 1609, 1611, 1593,
+ 1608, 1619, 1603, 1602,  119, 1627, 1628,  199,  199,  119,
+  353, 1647, 1649,  119,  357,  359,  361,  363,  365,  367,
+  369,  371, 1653, 1654, 1658,    9, 1071,  199,  573,  950,
+  661,  533,  951, 1063,  685,   38,  534,  117,  489,   38,
+  199,  965,  119,  686,  532,   33,   33,  767,  857,  490,
+   38,   34,  337,  364,  232,   38,  106,   34,  958,   38,
+  858,  881,   38,  849,  850,  882,  916,  755,  918,  341,
+  917,  920,  780,  732,   38,   38,  364,  732,  755,   38,
+   38,  364,  364,  134,  116,   38,  311,   38,   38,   38,
+   38,  141,  135,  117,  312,   38,  142,  235,   54,   38,
+   21,   38,  119,  119,  364, 1125,  338, 1041, 1226,   24,
+ 1227,   38, 1422,   38,   38,  117,   38,  364,  364, 1385,
+   38, 1423,  364, 1275, 1601,  364, 1570,  364, 1557,  364,
+  364,  364,  364,  338, 1475, 1610, 1586,  364, 1552, 1068,
+   38,  364,  117, 1064, 1069,  364, 1070,   38,   38,  953,
+ 1455,  199, 1389,  364, 1646, 1392,  364, 1476,  364,  364,
+ 1638, 1581, 1576,  364,  364, 1574,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  199, 1637,
+  119, 1315,  364,  364, 1499, 1038,  565, 1316,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  672,  364,
+  364, 1089,  886,  364,  364,  364,  364,  364, 1015, 1162,
+  364,  364,  305,  477,  949,  364,  364,  364,  364,  364,
+  364,  364,  364,  971,  353,   37,  584, 1100,  697,  701,
+  699,  706, 1239,  703,  364,  705,  478,  364,  850,  364,
+ 1007,  364, 1301, 1397,  364, 1211,  433, 1203, 1154,  479,
+  364, 1218,  338, 1173,  481, 1143, 1210,  581, 1281,  482,
+ 1212,  483,  484,  485,  486,  834, 1249,  353,  721,  487,
+ 1102,  722, 1395,  488, 1288, 1039, 1036, 1434,  338,    0,
+    0,    0,    0,    0,    0,  489,    0,    0,  490,    0,
+  491,    0,    0,  917,    0,    0,    0,  199,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  117,  492,  117,   36,    0,    0,    0,
+    0, 1435,    0,  199,    0,    0,  659,  661,  663,    0,
+    0,  581,  581,  581,  581,  581,  581,  581,  581,  581,
+  581,  581,  581,  581,  581,  581,  581,    0,    0,    0,
+    0,  338,    0,    0,    0,    0,    0,    0,    0,  117,
+    0,    0,  117,    0,    0,    0,   24,  338,    0,    0,
+   24, 1436,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   24,    0,    0,  338,    0,   24,    0,  338,    0,
+   24,    0,    0,   24,    0,    0,  199, 1044,    0,    0,
+    0,    0,    0,    0,    0,   24,   24,    0,    0,    0,
+   24,   24,  199,    0,    0,    0,   24,    0,   24,   24,
+   24,   24,    0,    0,    0,    0,   24,    0,    0,  199,
+   24,    0,   24,  199,    0,    0,    0,  833,    0,    0,
+    0,    0,   24,    0,    0,   24,    0,   24,    0,    0,
+    0,   24,    0,    0,    0,    0,  581,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   24,    0,    0,  338,  338,    0,   21,   24,   24,
+ 1044,    0,   37,    0,    0, 1044,   37, 1044, 1044, 1044,
+ 1044, 1044, 1044, 1044, 1044, 1044, 1044,   37,    0,    0,
+    0,  199,   37,    0,    0,    0,   37,    0,    0,   37,
+ 1044,    0, 1044,    0, 1044,    0, 1044, 1044, 1044,  199,
+  199,   37,   37,    0,    0,    0,   37,   37,    0,    0,
+    0,    0,   37,  870,   37,   37,   37,   37,    0,    0,
+  338,    0,   37,    0,    0,    0,   37,    0,   37,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   37,    0,
+   37,   37,    0,   37,    0,    0,    0,   37,    0,  338,
+    0, 1044,    0,   36,    0,    0,    0,   36,    0,    0,
+    0,  444,    0,  894,  895,  199,  541,   37,   36,  444,
+    0,  444,  541,   36,    0,   37,  353,   36,    0,    0,
+   36,    0,  117,    0,    0,    0,  199,    0,    0,    0,
+  444,  444,   36,   36,  199,    0,    0,   36,   36,    0,
+    0,    0,    0,   36,    0,   36,   36,   36,   36,    0,
+  444,    0,    0,   36,    0,    0,    0,   36,  444,   36,
+    0,  444,    0,    0,    0,    0,    0,  541,  664,   36,
+    0,    0,   36,    0,   36,    0,    0,   24,   36,   25,
+    0,    0,   26,    0,    0,    0,    0,   27,    0,    0,
+    0,   28,    0,  545,    0,    0,    0,    0,   36,    0,
+   30,    0,    0,    0,    0,   36,   36,   32,    0,    0,
+  117,    0,   33,  833,    0,    0,   34,    0,  833,  833,
+    0,    0,    0,    0,    0,    0,    0,    0,   36,    0,
+   37,    0,    0,    0,   38,    0,    0,  353,    0,    0,
+    0,  833,   39,   40,    0,    0,   41,  117,    0,   85,
+    0,    0,  117,    0,  833,  833,  117,    0,    0,  833,
+    0,    0,  833,    0,  833,    0,  833,  833,  833,  833,
+    0,    0,    0,  338,  833,    0,    0,    0,  833,    0,
+    0,    0,  833,    0,    0,  117,    0,    0,    0,    0,
+  833,    0,    0,  833,    0,  833,  833,    0,    0,    0,
+  833,  833,    0,  833,  833,  833,  833,  833,  833,  833,
+  833,  833,  833,  833,    0,    0,    0,    0,  199,  833,
+  833,    0,    0,    0,    0,  833,  833,  833,  833,  833,
+  833,  380,  833,  833,  833,    0,  833,  833,  338,    0,
+  833,  833,  833,  833,    0,  117,  117,  833,  833,    0,
+    0,    0,  833,  833,  833,  833,  833,  833,  833,  833,
+  338,    0,  952,   24,    0,   25,    0,    0,   26,    0,
+ 1332,  833,    0,   27,  833,    0,  833,   28,  833,    0,
+    0,  833,    0,  199,    0,    0,   30,  833,    0,    0,
+    0,    0,    0,   32,    0,    0,    0,    0,   33,    0,
+ 1333,    0,   34,    0,    0,  199,    0,    0,    0,    0,
+    0,    0,    0,    0,   36,    0,   37,  581,    0,    0,
+   38, 1334,  338,  117,  338,    0,    0,    0,   39,   40,
+    0,  338,   41,    0,    0,   85,    0,    0,    0,    0,
+  338,  338,    0,  338,    0,    0,    0,    0,    0,  545,
+    0,    0,    0,    0,  545,  545,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  199,  338,  199,
+    0,  338,    0,    0,    0,    0,  199,  545,    0,    0,
+    0,    0,    0,    0,    0,  199,  199,    0,  199,    0,
+  545,  545,    0,    0,    0,  545,    0,    0,  545,    0,
+  545,    0,  545,  545,  545,  545,    0,    0,    0,    0,
+  545,    0,    0,  199,  545,    0,  199,  380,  545,    0,
+    0,    0,    0,    0,    0,    0,  545,    0,    0,  545,
+  875,  545,  545,    0,    0,    0,  545,  545,    0,  545,
+  545,  545,  545,  545,  545,  545,  545,  545,  545,  545,
+    0,    0,    0,    0,    0,  545,  545,  545,    0,    0,
+    0,  545,  545,    0,  545,  545,  545,  545,  545,  545,
+  545,    0,  545,  545,    0,  545,  545,  545,  545,  545,
+  545,  545,  545,  545,  545,    0,  545,  545,  545,  545,
+  545,  545,  545,  545,  545,  545,  545,  545,  545,  545,
+  545,  545,  545,  545,  545,  545,  545,  545,    0,    0,
+  545,    0,  545,    0,  545,    0,    0,  545,  952,  952,
+    0,    0,    0,  545,    0,    0,  952,  952,  952,  952,
+  952,    0,  952,  952,    0,  952,  952,  952,  952,  952,
+  952,  952,  952,    0,    0,    0,    0,  952,    0,  952,
+  952,  952,  952,  952,  952,    0,    0,  952,    0,    0,
+  354,  952,  952,    0,  952,  952,  952,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  952,    0,  952,    0,
+  952,  952,    0,    0,  952,    0,  952,  952,  952,  952,
+  952,  952,  952,  952,  952,  952,  952,  952,    0,  952,
+    0,    0,  952,  952,    0,    0,  952,  952,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  952,  952,  952,  952,  952,    0,    0,    0,    0,
+  952,  952,    0,    0,  952,    0,    0,    0,    0,  952,
+  952,  952,  952,  952,    0,    0,    0,  952,    0,  952,
+    0,    0,    0,    0,    0,  952,  952,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+  952,  952,  952,  952,    0,  952,  875,  875,    0,    0,
+    0,  394,  952,    0,  875,  875,  875,  875,  875,    0,
+  875,  875,    0,  875,  875,  875,  875,  875,  875,  875,
+    0,    0,    0,    0,    0,  875,    0,  875,  875,  875,
+  875,  875,  875,    0,    0,  875,    0,    0,    0,  875,
+  875,    0,  875,  875,  875,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  875,    0,  875,    0,  875,  875,
+    0,    0,  875,    0,  875,  875,  875,  875,  875,  875,
+  875,  875,  875,  875,  875,  875,    0,  875,    0,    0,
+  875,  875,    0,    0,  875,  875,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,  875,
+  875,  875,  875,  875,    0,    0,  364,    0,  875,  875,
+    0,    0,  875,    0,    0,    0,    0,  875,  875,  875,
+  875,  875,    0,    0,    0,  875,  354,  875,    0,    0,
+    0,  354,  354,  875,  875,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  354,    0,    0,    0,  875,  875,
+  875,  875,    0,  875,    0,    0,    0,  354,  354,    0,
+  875,    0,  354,    0,    0,  354,    0,  354,    0,  354,
+  354,  354,  354,    0,    0,    0,    0,  354,    0,    0,
+    0,  354,    0,    0,    0,  354,    0,    0,    0,    0,
+    0,    0,    0,  354,    0,    0,  354,    0,  354,  354,
+    0,  399,    0,  354,  354,    0,  354,  354,  354,  354,
+  354,  354,  354,  354,  354,  354,  354,    0,    0,    0,
+    0,    0,  354,  354,    0,    0,    0,    0,  354,  354,
+  354,  354,  354,  354,    0,  354,  354,  354,    0,  354,
+  354,    0,    0,  354,  354,  354,  354,  394,    0,    0,
+  354,  354,  394,  394,    0,  354,  354,  354,  354,  354,
+  354,  354,  354,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  354,  394,    0,  354,    0,  354,
+    0,  354,    0,    0,  354,    0,    0,    0,  394,  394,
+  354,    0,    0,  394,    0,    0,  394,    0,  394,    0,
+  394,  394,  394,  394,    0,    0,    0,    0,  394,    0,
+    0,    0,  394,    0,    0,    0,  394,    0,    0,    0,
+    0,    0,    0,    0,  394,    0,    0,  394,    0,  394,
+  394,    0,    0,    0,  394,  394,    0,  394,  394,  394,
+  394,  394,  394,  394,  394,  394,  394,  394,    0,    0,
+    0,    0,  364,  394,  394,    0,    0,    0,  364,  394,
+  394,    0,  394,  394,  394,    0,  394,  394,  394,    0,
+  394,  394,   31,    0,  394,  394,  394,  394,    0,    0,
+    0,  394,  394,    0,    0,    0,  394,  394,  394,  394,
+  394,  394,  394,  394,  364,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  394,    0,    0,  394,    0,
+  394,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  394,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  364,    0,    0,    0,  364,
+  364,    0,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,    0,    0,    0,  399,    0,  364,
+    0,    0,    0,  399,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,    0,  364,  364,    0,    0,  364,
+  364,  364,  364,  364,    0,    0,  364,  364,   25,    0,
+    0,  364,  364,  364,  364,  364,  364,  364,  364,  399,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+  364,    0,    0,  364,    0,  364,    0,  364,    0,    0,
+  364,    0,    0,    0,    0,    0,  364,    0,    0,    0,
+    0,   35,    0,    0,    0,    0,    0,    0,    0,    0,
+  399,    0,    0,    0,  399,  399,    0,  399,  399,  399,
+  399,  399,  399,  399,  399,  399,  399,  399,    0,    0,
+    0,    0,    0,    0,  399,    0,    0,    0,    0,  399,
+  399,  399,  399,  399,  399,    0,  399,  399,  399,    0,
+  399,  399,    0,    0,  399,  399,  399,  399,    0,    0,
+    0,  399,  399,    0,    0,    0,  399,  399,  399,  399,
+  399,  399,  399,  399,    0,    0,    0,    0,    0,    0,
+    0,    5,    0,    0,    0,  399,    0,    0,  399,    0,
+  399,    0,  399,    0,    0,  399,    0,    0,   31,   31,
+    0,  399,    0,   31,    0,    0,    0,   31,    0,   31,
+    0,    0,   31,    0,   31,   31,    0,   31,    0,   31,
+    0,   31,    0,   31,   31,   31,   31,    0, 1052,   31,
+   31,    0,    0,    0,    0,   31,    0,   31,   31,   31,
+    0,    0,   31,   31,   31,    0,   31,    0,    0,   31,
+    0,   31,   31,   31,   31,    0,    0,    0,   31,   31,
+   31,    0,    0,   31,   31,   31,    0,    0,    0,    0,
+    0,    0,   31,   31,    0,   31,   31,    0,   31,   31,
+   31,    0,    0,    0,   31,    0,    0,    0,    0,    0,
+    0,   51,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   31,    0,    0,    0,    0,    0,
+   31,   31,   31,    0,    0,   25,    0,    0,    0,   25,
+   31,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   25,    0,    0,    0,    7,   25,    0,    0,    0,   25,
+    0,    0,   25,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   25,   25,    0,    0,   35,   25,
+   25,   31,   35,    0,    0,   25,    0,   25,   25,   25,
+   25,    0,    0,   35,    0,   25,    0, 1053,   35,   25,
+    0,   25,   35,    0,    0,   35,    0,    0,    0,    0,
+    0,   25,    0,    0,   25,    0,   25,   35,   35,    0,
+   25,    0,   35,   35,    0,    0,    0,    0,   35,    0,
+   35,   35,   35,   35,    0,    0,    0,    0,   35,    0,
+   25,    0,   35,    0,   35,    0,    0,   25,   25,    0,
+    0,    0,    0,    0,   35,    0,    0,   35,    5,   35,
+   52,    0,   51,   35,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   51,    0,    0,    0,    0,   51,    0,
+    0,    0,   51,   35,    0,   51,    0,    0,    0,    0,
+    0,   35,    0,    0,    0,    0,    0,   51,   51,    0,
+    0,    0,   51,   51,    0, 1052,    0,    0,   51,   51,
+   51,   51,   51,   51,    0,    0,    0,    0,   51,    0,
+   51,    0,   51,    0,   51,   51,    0,    0,    0,   51,
+    0,    0,   51,    0,   51,    0,    0,   51,    0,   51,
+    0,    0,    0,   51,   51,   51,    0,    0,    0,   51,
+   51,    0,    0,    0,    0,   51,    0,   51,   51,   51,
+   51,    0,    0,   51,    0,   51,    0,    0,   51,   51,
+    0,   51,   51,    0,    0,    0,    0,    0,    0,    0,
+    0,   51,    0,   51,   51,    0,   51,    0,   51,    0,
+   51,    0,   51,    0,    0,   51,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   51,   51,    0,
+   51,    7,   51,   51,    0,   52,    0,    0,   51,    0,
+   51,   51,   51,   51,    0,    0,   52,    0,   51,    0,
+    0,   52,   51,    0,   51,   52,    0,    0,   52,    0,
+    0,    0,    0,    0,   51,    0,    0,   51,    0,   51,
+   52,   52,    0,   51, 1053,   52,   52,    0,   51,    0,
+    0,   52,    0,   52,   52,   52,   52,    0,    0,   51,
+    0,   52,    0,   51,   51,   52,    0,   52,   51,    0,
+    0,   51,    0,    0,    0,    0,    0,   52,    0,    0,
+   52,    0,   52,   51,   51,    0,   52,    0,   51,   51,
+    0,    0,    0,    0,   51,    0,   51,   51,   51,   51,
+    0,    0,    0,    0,   51,    0,   52,   52,   51,    0,
+   51,   52,    0,    0,    0,    0,    0,    0,    0,    0,
+   51,    0,   52,   51,    0,   51,    0,   52,    0,   51,
+    0,   52,    0,    0,   52,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   52,   52,    0,   51,
+    0,   52,   52,    0,    0,    0,    0,   52,    0,   52,
+   52,   52,   52,    0,    0,    0,    0,   52,    0,    0,
+    0,   52,    0,   52,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   52,    0,   56,   52,    0,   52,    0,
+    0,    0,   52,   57,   24,   58,   25,    0,    0,   26,
+   59,    0,   60,   61,   27,   62,   63,   64,   28,    0,
+    0,    0,   52,    0,   65,    0,   66,   30,   67,   68,
+   69,   70,    0,    0,   32,    0,    0,    0,   71,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   74,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,   76,   77,   78,   79,   80,   81,   39,
+   40,   82,   83,   41,   84,    0,   85,    0,    0,   86,
+   87,    0,    0,   88,   89,  836,    0,    0,    0,  477,
+    0,  836,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,   93,   94,    0,    0,    0,    0,   95,    0,    0,
+    0,   96,  478,    0,    0,    0,   97,   98,   99,  100,
+  101,    0,    0,    0,  102,  479,  103,  836,    0,    0,
+  481,    0,  104,  105,    0,  482,    0,  483,  484,  485,
+  486,    0,    0,    0,    0,  487,    0,    0,    0,  488,
+    0,    0,    0, 1434,    0,    0,    0,  106,  107,  108,
+  109,  489,    0,    0,  490,    0,  491,    0,  836,  200,
+    0,    0,    0,  836,  627,  836,  836,  836,  836,  836,
+  836,  836,  836,  836,  836,  836,  836,    0,    0,    0,
+  492,    0,  836,  836,    0,    0,    0,    0,  836,  836,
+  836,  836,  836,  836,  836,  836,  836,    0,  836,  836,
+    0,  836,  836,  836,  836,  836,  836,  836,  836,  836,
+  836,    0,  836,  836,  836,  836,  836,  836,  836,  836,
+  836,  836,  836,  836,  836,  836,  836,  836,  836,  836,
+  836,  836,  836,  836,  836,    0,  836, 1436,  836,    0,
+  836,  836,  836,  836,    0,    0,    0,  627,    0,  836,
+    0,    0,  627,    0,  627,  627,  627,  627,  627,  627,
+  627,  627,  627,  627,  627,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  627,  836,  627,
+    0,  627,    0,  627,  627,  627,    0,    0,    0,    0,
+    0,  627,  627,  627,  627,    0,    0,    0,  627,  627,
+    0,    0,    0,  627,  627,  627,  627,  627,  627,  627,
+  627,    0,    0,    0,    0,    0,    0,    0,    0,  836,
+    0,    0,  627,    0,  836,    0,  836,  836,  836,  836,
+  836,  836,  836,  836,  836,  836,  836,  836,  627,    0,
+    0,    0,    0,  836,  836,    0,    0,    0,    0,  836,
+  836,  836,  836,  836,  836,  836,  836,  836,    0,  836,
+  836,    0,  836,  836,  836,  836,  836,  836,  836,  836,
+  836,  836,    0,  836,  836,  836,  836,  836,  836,  836,
+  836,  836,  836,  836,  836,  836,  836,  836,  836,  836,
+  836,  836,  836,  836,  836,  836,  364,  991,    0,  836,
+    0,  836,  364,    0,  836,    0,   24,    0,   25,    0,
+  836,   26,    0,    0,    0,    0,   27,    0,    0,    0,
+   28,    0,    0,    0,    0,    0,    0,    0,    0,   30,
+    0,    0,    0,    0,    0,    0,   32,    0,  364,    0,
+    0,   33,    0,    0,    0,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+    0,    0,    0,   38,    0,    0,    0,    0,    0,    0,
+    0,   39,   40,    0,    0,   41,    0,    0,   85,  364,
+    0,    0,    0,    0,  364,    0,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,    0,    0,
+    0,    0,    0,  364,  364,    0,    0,    0,    0,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,    0,  364,
+  364,    0,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,    0,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,    0,  547, 1135,    0,  364,
+  380,  364,  547,    0,  364,    0,   24,    0,   25,    0,
+  364,   26,    0,    0,    0,    0,   27,    0,    0,    0,
+   28,    0,    0,    0,    0,    0,    0,    0,    0,   30,
+    0,    0,    0,    0,    0,    0,   32,    0,  547,    0,
+    0,   33,    0,    0,    0,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+    0,    0,    0,   38,    0,    0,    0,    0,    0,    0,
+    0,   39,   40,    0,    0,   41,    0,    0,   85,  547,
+    0,    0,    0,    0,  547,    0,  547,  547,  547,  547,
+  547,  547,  547,  547,  547,  547,  547,    0,    0,    0,
+    0,    0,    0,  547,  547,    0,    0,    0,  547,  547,
+  547,  547,  547,  547,  547,  547,  547,  547,    0,  547,
+  547,    0,  547,  547,  547,  547,  547,  547,  547,  547,
+  547,  547,    0,  547,  547,  547,  547,  547,  547,  547,
+  547,  547,  547,  547,  547,  547,  547,  547,  547,  547,
+  547,  547,  547,  547,  547,    0,  543,    0,    0,  547,
+  380,  547,  543,    0,    0,  477,    0,    0,    0,    0,
+  547,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  478,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  543,    0,
+    0,  479,    0,    0,    0,    0,  481,    0,    0,    0,
+    0,  482,    0,  483,  484,  485,  486,    0,    0,    0,
+    0,  487,    0,    0,    0,  488,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  489,    0,  543,
+  490,    0,  491,    0,  543,    0,  543,  543,  543,  543,
+  543,  543,  543,  543,  543,  543,  543,    0,    0,    0,
+    0,    0,    0,  543,  543,    0,  492,    0,  543,  543,
+    0,  543,  543,  543,  543,  543,  543,  543,    0,  543,
+  543,    0,  543,  543,  543,  543,  543,  543,  543,  543,
+  543,  543,    0,  543,  543,  543,  543,  543,  543,  543,
+  543,  543,  543,  543,  543,  543,  543,  543,  543,  543,
+  543,  543,  543,  543,  543,    0,  551,    0,    0,  543,
+  386,  543,  551, 1453,  543,    0,    0,    0,    0,    0,
+  543,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  386,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  386,    0,  551,    0,
+    0,  386,    0,    0,  254,    0,  386,    0,  386,  386,
+  386,  386,    0,    0,    0,    0,  386,    0,    0,    0,
+  386,    0,    0,    0,  386,    0,    0,    0,    0,    0,
+    0,    0,  386,    0,    0,  386,    0,  386,    0,  551,
+    0,    0,    0,    0,  551,    0,  551,  551,  551,  551,
+  551,  551,  551,  551,  551,  551,  551,    0,    0,    0,
+    0,  386,    0,  551,  551,    0,    0,    0,  386,  551,
+    0,  551,  551,  551,  551,  551,  551,  551,    0,  551,
+  551,    0,  551,  551,  551,  551,  551,  551,  551,  551,
+  551,  551,    0,  551,  551,  551,  551,  551,  551,  551,
+  551,  551,  551,  551,  551,  551,  551,  551,  551,  551,
+  551,  551,  551,  551,  551,    0,  364,    0,  386,  551,
+  385,  551,  364,    0,  551,    0,    0,    0,    0,    0,
+  551,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  385,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  385,    0,  364,    0,
+    0,  385,    0,    0,  253,    0,  385,    0,  385,  385,
+  385,  385,    0,    0,    0,    0,  385,    0,    0,    0,
+  385,    0,    0,    0,  385,    0,    0,    0,    0,    0,
+    0,    0,  385,    0,    0,  385,    0,  385,    0,  364,
+    0,    0,    0,    0,  364,    0,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,    0,    0,    0,
+    0,  385,    0,  364,  364,    0,    0,    0,  385,  364,
+    0,  364,  364,  364,  364,  364,  364,  364,    0,  364,
+  364,    0,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,    0,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,    0,  471,    0,  385,  364,
+    0,  364,  471,    0,  364,    0,  732,    0,  732,    0,
+  364,  732,    0,  732,  732,    0,  732,    0,  732,    0,
+  732,    0,  732,  732,  732,    0,    0,    0,  732,  732,
+    0,    0,    0,    0,  732,    0,  732,  732,  471,    0,
+    0,  732,    0,    0,    0,  732,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  732,    0,  732,
+    0,    0,    0,  732,  732,    0,    0,    0,    0,    0,
+    0,  732,  732,    0,    0,  732,    0,    0,  732,  471,
+    0,    0,    0,  732,  471,    0,  471,  471,  471,  471,
+  471,  471,  471,  471,  471,  471,  471,    0,    0,    0,
+    0,    0,    0,  471,  471,    0,    0,    0,    0,  471,
+    0,  471,  471,  471,  471,  471,  471,  471,    0,  471,
+  471,    0,  471,  471,  471,  471,  471,  471,  471,  471,
+  471,  471,    0,  471,  471,  471,  471,  471,  471,  471,
+  471,  471,  471,  471,  471,  471,  471,  471,  471,  471,
+  471,  471,  471,  471,  471,    0,  578,    0,    0,  471,
+  732,  471,  578,    0,  471,    0,   24,    0,   25,    0,
+  471,   26,    0,    0, 1399,    0,   27,    0,  757,    0,
+   28,    0,  758, 1400, 1401,    0,    0,    0, 1402,   30,
+    0,    0,    0,    0, 1403,    0,   32,    0,  578,    0,
+    0,   33,    0,    0,    0,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+  364,    0,    0,   38,    0,    0,  364,    0,    0,    0,
+  836,   39,   40,    0,    0,   41,    0,    0, 1404,  578,
+    0,    0,    0, 1405,  578,    0,  578,  578,  578,  578,
+  578,  578,  578,  578,  578,  578,  578,    0,    0,    0,
+    0,    0,  364,  578,    0,    0,    0,    0,    0,  578,
+    0,  578,    0,  578,    0,  578,  578,  578,  836,  578,
+  578,    0,  578,  578,  578,  578,  578,  578,  578,  578,
+  578,  578,    0,    0,    0,  578,  578,  578,  578,  578,
+  578,  578,  578,  578,  578,  578,  578,  578,  578,  578,
+  578,  578,  578,    0,  578,  663,    0,    0,    0,  578,
+ 1407,  364,    0,    0,    0,    0,    0,  364,  364,    0,
+  578,    0,    0,  364,  364,  364,  364,  364,  364,  364,
+  836,  364,    0,  364,  364,  205,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,    0,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  364,    0,
+  354,    0,    0,  364,    0,  364,  354,  206,  364,    0,
+    0,    0,    0,    0,  364,    0,    0,    0,  663,    0,
+    0,    0,    0,  663,    0,  663,  663,  663,  663,  663,
+  663,  663,  663,  663,  663,  663,    0,    0,    0,    0,
+    0,    0,  354,    0,    0,    0,    0,    0,  663,    0,
+  663,    0,  663,    0,  663,  663,  663,    0,  207,  208,
+  209,  210,    0,  211,  212,  213,  214,  215,  216,  217,
+  218,    0,    0,  219,  220,  221,  222,  223,  224,  225,
+  226,    0,    0,  354,    0,    0,    0,    0,  354,    0,
+  354,  354,  354,  354,  354,  354,  354,  354,  354,  354,
+  354,    0,    0,    0,    0,  620,    0,  354,  422,  663,
+    0,  620,    0,  354,  354,  354,  422,  354,  422,  354,
+  354,  354,    0,  354,  354,    0,    0,  354,  354,  354,
+  354,    0,    0,    0,  354,  354,    0,  422,  422,  354,
+  354,  354,  354,  354,  354,  354,  354,  620,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  422,  354,    0,
+    0,    0,    0,  354,  422,  422,    0,    0,  422,    0,
+  422,    0,    0,    0,  354,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  620,    0,
+    0,    0,    0,  620,    0,  620,  620,  620,  620,  620,
+  620,  620,  620,  620,  620,  620,  422,    0,    0,    0,
+    0,    0,  620,  423,    0,    0,    0,    0,  620,    0,
+  620,  423,  620,  423,  620,  620,  620,    0,  620,  620,
+    0,    0,  620,  620,  620,  620,    0,    0,    0,  620,
+  620,    0,  423,  423,  620,  620,  620,  620,  620,  620,
+  620,  620,    0,  354,    0,    0,    0,    0,    0,  354,
+    0,    0,  423,  620,    0,    0,    0,    0,  620,    0,
+  423,  354,  422,  423,    0,    0,    0,  422,  354,  620,
+  422,  422,  422,  422,    0,  422,    0,  422,  422,    0,
+  422,  422,  422,  422,  422,  354,  422,  422,  422,  422,
+    0,  422,  422,  422,  422,  422,  422,  422,  422,  422,
+  422,  422,  422,  422,  422,  422,  422,  422,  422,  422,
+  422,  422,  422,    0,    0,    0,    0,  354,    0,  422,
+    0,    0,  422,    0,    0,    0,  354,    0,  422,    0,
+    0,  354,    0,  354,  354,  354,  354,  354,  354,  354,
+  354,  354,  354,  354,    0,    0,    0,    0,  600,    0,
+  354,    0,    0,    0,  600,    0,  354,  354,  354,    0,
+  354,    0,  354,  354,  354,    0,  354,  354,    0,    0,
+  354,  354,  354,  354,    0,    0,    0,  354,  354,    0,
+    0,    0,  354,  354,  354,  354,  354,  354,  354,  354,
+  600,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  354,    0,    0,    0,    0,  354,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  354,    0,    0,
+  618,    0,    0,    0,    0,    0,  618,    0,    0,    0,
+    0,  600,    0,    0,    0,    0,  600,    0,  600,  600,
+  600,  600,  600,  600,  600,  600,  600,  600,  600,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  600,  618,  600,    0,  600,    0,  600,  600,  600,
+    0,  600,  600,    0,    0,  600,  600,  600,  600,  600,
+  600,  600,  600,  600,    0,    0,    0,  600,  600,  600,
+  600,  600,  600,  600,  600,    0,    0,    0,    0,    0,
+    0,    0,    0,  618,    0,    0,  600,    0,  618,    0,
+  618,  618,  618,  618,  618,  618,  618,  618,  618,  618,
+  618,    0,  600,    0,    0,  607,    0,  618,    0,    0,
+    0,  607,    0,  618,    0,  618,    0,  618,    0,  618,
+  618,  618,    0,  618,  618,    0,    0,  618,  618,  618,
+  618,    0,    0,    0,  618,  618,    0,    0,    0,  618,
+  618,  618,  618,  618,  618,  618,  618,  607,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  618,    0,
+    0,    0,    0,  618,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  618,    0,    0,  958,    0,    0,
+    0,    0,    0,  958,    0,    0,    0,    0,  607,    0,
+    0,    0,    0,  607,    0,  607,  607,  607,  607,  607,
+  607,  607,  607,  607,  607,  607,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  607,  958,
+  607,    0,  607,    0,  607,  607,  607,    0,  607,  607,
+    0,    0,  607,  607,  607,  607,    0,    0,    0,  607,
+  607,    0,    0,    0,  607,  607,  607,  607,  607,  607,
+  607,  607,    0,    0,    0,    0,    0,    0,    0,    0,
+  958,    0,    0,  607,    0,  958,    0,  958,  958,  958,
+  958,  958,  958,  958,  958,  958,  958,  958,    0,  607,
+    0,    0,  608,    0,    0,    0,    0,    0,  608,    0,
+  958,    0,  958,    0,  958,    0,  958,  958,  958,    0,
+  958,  958,    0,    0,  958,  958,  958,  958,    0,    0,
+    0,  958,  958,    0,    0,    0,  958,  958,  958,  958,
+  958,  958,  958,  958,  608,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  958,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  958,    0,    0,  609,    0,    0,    0,    0,    0,
+  609,    0,    0,    0,    0,  608,    0,    0,    0,    0,
+  608,    0,  608,  608,  608,  608,  608,  608,  608,  608,
+  608,  608,  608,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  608,  609,  608,    0,  608,
+    0,  608,  608,  608,    0,  608,  608,    0,    0,  608,
+  608,  608,  608,    0,    0,    0,  608,  608,    0,    0,
+    0,  608,  608,  608,  608,  608,  608,  608,  608,    0,
+    0,    0,    0,    0,    0,    0,    0,  609,    0,    0,
+  608,    0,  609,    0,  609,  609,  609,  609,  609,  609,
+  609,  609,  609,  609,  609,    0,  608,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  609,    0,  609,
+    0,  609,    0,  609,  609,  609,    0,  609,  609,    0,
+    0,  609,  609,  609,  609,    0,    0,    0,  609,  609,
+    0,    0,    0,  609,  609,  609,  609,  609,  609,  609,
+  609,    0,  525,    0,  628,    0,    0,    0,    0,    0,
+   57,   24,  609,   25,    0,    0,   26,  259,    0,    0,
+    0,   27,   62,   63,    0,   28,    0,    0,  609,    0,
+    0,   65,    0,    0,   30,    0,    0,    0,    0,    0,
+    0,   32,    0,    0,    0,    0,   33,    0,   72,   73,
+   34,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   36,    0,   37,   75,    0,    0,   38,    0,
+    0,   77,    0,   79,    0,   81,   39,   40,  260,    0,
+   41,    0,    0,    0,    0,    0,    0,  628,    0,  629,
+    0,    0,  628,    0,  628,  628,  628,  628,  628,  628,
+  628,  628,  628,  628,  628,   90,   91,   92,  261,  526,
+    0,    0,    0,    0,    0,    0,    0,  628,   96,  628,
+    0,  628,    0,  628,  628,  628,    0,    0,    0,    0,
+    0,  628,  628,  628,  628,    0,    0,    0,  628,  628,
+    0,    0,    0,  628,  628,  628,  628,  628,  628,  628,
+  628,    0,    0,    0,    0,    0,    0,    0,  632,    0,
+    0,    0,  628,    0,  106,  527,    0,    0,    0,    0,
+    0,    0,  629,    0,    0,  528,  529,  629,  628,  629,
+  629,  629,  629,  629,  629,  629,  629,  629,  629,  629,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  629,    0,  629,    0,  629,    0,  629,  629,
+  629,    0,    0,    0,    0,    0,  629,  629,  629,  629,
+    0,    0,    0,  629,  629,    0,    0,  633,  629,  629,
+  629,  629,  629,  629,  629,  629,    0,    0,    0,    0,
+    0,  632,    0,    0,    0,    0,  632,  629,  632,  632,
+  632,  632,  632,  632,  632,  632,  632,  632,  632,    0,
+    0,    0,    0,  629,    0,    0,    0,    0,    0,    0,
+    0,  632,    0,  632,    0,  632,    0,  632,  632,  632,
+    0,    0,    0,    0,    0,  632,  632,  632,  632,    0,
+    0,    0,  632,  632,    0,    0,  634,    0,    0,  632,
+  632,  632,  632,  632,  632,    0,    0,    0,    0,    0,
+  633,    0,    0,    0,    0,  633,  632,  633,  633,  633,
+  633,  633,  633,  633,  633,  633,  633,  633,    0,    0,
+    0,    0,  632,    0,    0,    0,    0,    0,    0,    0,
+  633,    0,  633,    0,  633,    0,  633,  633,  633,    0,
+    0,    0,    0,    0,  633,  633,  633,  633,    0,    0,
+    0,  633,  633,    0,    0,  635,    0,    0,  633,  633,
+  633,  633,  633,  633,    0,    0,    0,    0,    0,  634,
+    0,    0,    0,    0,  634,  633,  634,  634,  634,  634,
+  634,  634,  634,  634,  634,  634,  634,    0,    0,    0,
+    0,  633,    0,    0,    0,    0,    0,    0,    0,  634,
+    0,  634,    0,  634,    0,  634,  634,  634,    0,    0,
+    0,    0,    0,  634,  634,  634,  634,    0,    0,    0,
+  634,  634,    0,    0,  636,    0,    0,  634,  634,  634,
+  634,  634,  634,    0,    0,    0,    0,    0,  635,    0,
+    0,    0,    0,  635,  634,  635,  635,  635,  635,  635,
+  635,  635,  635,  635,  635,  635,    0,    0,    0,    0,
+  634,    0,    0,    0,    0,    0,    0,    0,  635,    0,
+  635,    0,  635,    0,  635,  635,  635,    0,    0,    0,
+    0,    0,  635,  635,  635,  635,  364,    0,    0,  635,
+  635,    0,  364,    0,    0,    0,  635,  635,  635,  635,
+  635,  635,    0,    0,    0,    0,    0,  636,    0,    0,
+    0,    0,  636,  635,  636,  636,  636,  636,  636,  636,
+  636,  636,  636,  636,  636,    0,    0,    0,  364,  635,
+    0,    0,    0,    0,    0,    0,    0,  636,    0,  636,
+    0,  636,    0,  636,  636,  636,    0,    0,    0,    0,
+    0,  636,  636,  636,  636,    0,    0,    0,  636,  636,
+    0,    0,    0,    0,    0,  636,  636,  636,  636,  636,
+  636,    0,    0,  641,    0,    0,    0,    0,    0,    0,
+    0,    0,  636,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  364,    0,    0,    0,  636,  364,
+    0,    0,  364,    0,  364,  364,    0,    0,    0,  364,
+  364,    0,    0,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,    0,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  642,  364,  364,    0,    0,    0,    0,    0,
+    0,  364,    0,    0,  364,    0,  641,    0,    0,    0,
+  364,  641,    0,  641,  641,  641,  641,  641,  641,  641,
+  641,  641,  641,  641,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  641,    0,  641,    0,
+  641,    0,  641,  641,  641,    0,    0,    0,    0,    0,
+    0,    0,  641,  641,    0,    0,    0,  641,  641,    0,
+    0,  643,    0,    0,    0,    0,  641,  641,  641,  641,
+    0,    0,    0,    0,    0,  642,    0,    0,    0,    0,
+  642,  641,  642,  642,  642,  642,  642,  642,  642,  642,
+  642,  642,  642,    0,    0,    0,    0,  641,    0,    0,
+    0,    0,    0,    0,    0,  642,    0,  642,    0,  642,
+    0,  642,  642,  642,    0,    0,    0,    0,    0,    0,
+    0,  642,  642,    0,    0,    0,  642,  642,    0,    0,
+  646,    0,    0,    0,    0,  642,  642,  642,  642,    0,
+    0,    0,    0,    0,  643,    0,    0,    0,    0,  643,
+  642,  643,  643,  643,  643,  643,  643,  643,  643,  643,
+  643,  643,    0,    0,    0,    0,  642,    0,    0,    0,
+    0,    0,    0,    0,  643,    0,  643,    0,  643,    0,
+  643,  643,  643,    0,    0,    0,    0,    0,    0,    0,
+  643,  643,    0,    0,    0,  643,  643,    0,    0,  647,
+    0,    0,    0,    0,  643,  643,  643,  643,    0,    0,
+    0,    0,    0,  646,    0,    0,    0,    0,  646,  643,
+  646,  646,  646,  646,  646,  646,  646,  646,  646,  646,
+  646,    0,    0,    0,    0,  643,    0,    0,    0,    0,
+    0,    0,    0,  646,    0,  646,    0,  646,    0,  646,
+  646,  646,    0,    0,    0,    0,    0,    0,    0,  646,
+  646,    0,    0,    0,  646,  646,    0,    0,  649,    0,
+    0,    0,    0,    0,    0,  646,  646,    0,    0,    0,
+    0,    0,  647,    0,    0,    0,    0,  647,  646,  647,
+  647,  647,  647,  647,  647,  647,  647,  647,  647,  647,
+    0,    0,    0,    0,  646,    0,    0,    0,    0,    0,
+    0,    0,  647,    0,  647,    0,  647,    0,  647,  647,
+  647,    0,    0,    0,    0,    0,    0,    0,  647,  647,
+    0,    0,    0,  647,  647,    0,    0,  650,    0,    0,
+    0,    0,    0,    0,  647,  647,    0,    0,    0,    0,
+    0,  649,    0,    0,    0,    0,  649,  647,  649,  649,
+  649,  649,  649,  649,  649,  649,  649,  649,  649,    0,
+    0,    0,    0,  647,    0,    0,    0,    0,    0,    0,
+    0,  649,    0,  649,    0,  649,    0,  649,  649,  649,
+    0,    0,    0,    0,    0,    0,    0,    0,  649,    0,
+    0,    0,  649,  649,    0,    0,  652,    0,    0,    0,
+    0,    0,    0,  649,  649,    0,    0,    0,    0,    0,
+  650,    0,    0,    0,    0,  650,  649,  650,  650,  650,
+  650,  650,  650,  650,  650,  650,  650,  650,    0,    0,
+    0,    0,  649,    0,    0,    0,    0,    0,    0,    0,
+  650,    0,  650,    0,  650,    0,  650,  650,  650,    0,
+    0,    0,    0,    0,    0,    0,    0,  650,    0,    0,
+    0,  650,  650,    0,    0,  653,    0,    0,    0,    0,
+    0,    0,  650,  650,    0,    0,    0,    0,    0,  652,
+    0,    0,    0,    0,  652,  650,  652,  652,  652,  652,
+  652,  652,  652,  652,  652,  652,  652,    0,    0,    0,
+    0,  650,    0,    0,    0,    0,    0,    0,    0,  652,
+    0,  652,    0,  652,    0,  652,  652,  652,    0,    0,
+    0,    0,    0,    0,    0,    0,  652,    0,    0,    0,
+    0,  652,    0,    0,  655,    0,    0,    0,    0,    0,
+    0,  652,  652,    0,    0,    0,    0,    0,  653,    0,
+    0,    0,    0,  653,  652,  653,  653,  653,  653,  653,
+  653,  653,  653,  653,  653,  653,    0,    0,    0,    0,
+  652,    0,    0,    0,    0,    0,    0,    0,  653,    0,
+  653,    0,  653,    0,  653,  653,  653,    0,    0,    0,
+    0,    0,    0,    0,    0,  653,    0,    0,    0,    0,
+  653,    0,    0,  656,    0,    0,    0,    0,    0,    0,
+  653,  653,    0,    0,    0,    0,    0,  655,    0,    0,
+    0,    0,  655,  653,  655,  655,  655,  655,  655,  655,
+  655,  655,  655,  655,  655,    0,    0,    0,    0,  653,
+    0,    0,    0,    0,    0,    0,    0,  655,    0,  655,
+    0,  655,    0,  655,  655,  655,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,  655,
+    0,    0,  658,    0,    0,    0,    0,    0,    0,  655,
+  655,    0,    0,    0,    0,    0,  656,    0,    0,    0,
+    0,  656,  655,  656,  656,  656,  656,  656,  656,  656,
+  656,  656,  656,  656,    0,    0,    0,    0,  655,    0,
+    0,    0,    0,    0,    0,    0,  656,    0,  656,    0,
+  656,    0,  656,  656,  656,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  656,    0,
+    0,  659,    0,    0,    0,    0,    0,    0,  656,  656,
+    0,    0,    0,    0,    0,  658,    0,    0,    0,    0,
+  658,  656,  658,  658,  658,  658,  658,  658,  658,  658,
+  658,  658,  658,    0,    0,    0,    0,  656,    0,    0,
+    0,    0,    0,    0,    0,  658,    0,  658,    0,  658,
+    0,  658,  658,  658,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  658,    0,    0,
+    0,  364,    0,    0,    0,  836,    0,    0,  658,    0,
+    0,    0,    0,    0,  659,    0,    0,    0,    0,  659,
+  658,  659,  659,  659,  659,  659,  659,  659,  659,  659,
+  659,  659,    0,    0,    0,    0,  658,  364,    0,    0,
+    0,    0,    0,    0,  659,    0,  659,    0,  659,    0,
+  659,  659,  659,  836,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,  659,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  659,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,  659,
+    0,    0,    0,    0,    0,    0,  364,    0,    0,    0,
+    0,    0,  364,  364,    0,  659,    0,    0,  364,  364,
+    0,  364,    0,  364,    0,  836,  364,    0,  364,  364,
+    0,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,    0,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,    0,    0,  591,    0,  364,    0,
+  364,    0,    0,  364,   57,   24,   58,   25, 1164,  364,
+   26,   59,    0,   60,   61,   27,   62,   63,   64,   28,
+    0,    0,    0,    0,    0,   65,    0,   66,   30,   67,
+   68,   69,   70,    0,    0,   32,    0,    0,    0,   71,
+   33,    0,   72,   73,   34,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   74,    0,   36,    0,   37,   75,
+    0,    0,   38,    0,   76,   77,   78,   79,   80,   81,
+   39,   40,   82,   83,   41,   84,    0,   85,    0,    0,
+   86,   87,    0,    0,   88,   89,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   90,
+   91,   92,   93,   94,    0,    0,    0,    0,   95,    0,
+    0,    0,   96,    0,    0,    0,    0,   97,   98,   99,
+  100,  101,    0,    0,    0,  102,    0,  103,    0,    0,
+    0,    0,    0,  104,  105,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   56,    0,  106,  592,
+  108,  109,    0, 1165,   57,   24,   58,   25,    0,    0,
+   26,   59,    0,   60,   61,   27,   62,   63,   64,   28,
+    0,    0,    0,    0,    0,   65,    0,   66,   30,   67,
+   68,   69,   70,    0,    0,   32,    0,    0,    0,   71,
+   33,    0,   72,   73,   34,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   74,    0,   36,    0,   37,   75,
+    0,    0,   38,    0,   76,   77,   78,   79,   80,   81,
+   39,   40,   82,   83,   41,   84,    0,   85,    0,    0,
+   86,   87,    0,    0,   88,   89,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   90,
+   91,   92,   93,   94,    0,    0,    0,    0,   95,    0,
+    0,    0,   96,    0,    0,    0,    0,   97,   98,   99,
+  100,  101,    0,    0,    0,  102,    0,  103,    0,    0,
+    0,    0,    0,  104,  105,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  272,    0,    0,    0,  106,  107,
+  108,  109,   57,   24,   58,   25,    0,    0,   26,   59,
+    0,   60,   61,   27,   62,   63,   64,   28,    0,    0,
+    0,    0,    0,   65,    0,   66,   30,   67,   68,   69,
+   70,    0,    0,   32,    0,    0,    0,   71,   33,    0,
+   72,   73,   34,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   74,    0,   36,    0,   37,   75,    0,    0,
+   38,    0,   76,   77,   78,   79,   80,   81,   39,   40,
+   82,   83,   41,   84,    0,   85,    0,    0,   86,   87,
+    0,    0,   88,   89,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   90,   91,   92,
+   93,   94,    0,    0,    0,    0,   95,    0,    0,    0,
+   96,    0,    0,    0,    0,   97,   98,   99,  100,  101,
+    0,    0,    0,  102,    0,  103,    0,    0,    0,    0,
+    0,  104,  105,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  591,    0,    0,    0,  106,  107,  108,  109,
+   57,   24,   58,   25,    0,    0,   26,   59,    0,   60,
+   61,   27,   62,   63,   64,   28,    0,    0,    0,    0,
+    0,   65,    0,   66,   30,   67,   68,   69,   70,    0,
+    0,   32,    0,    0,    0,   71,   33,    0,   72,   73,
+   34,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   74,    0,   36,    0,   37,   75,    0,    0,   38,    0,
+   76,   77,   78,   79,   80,   81,   39,   40,   82,   83,
+   41,   84,    0,   85,    0,    0,   86,   87,    0,    0,
+   88,   89,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   90,   91,   92,   93,   94,
+    0,    0,    0,    0,   95,    0,    0,    0,   96,    0,
+    0,    0,    0,   97,   98,   99,  100,  101,    0,    0,
+    0,  102,    0,  103,    0,    0,    0,    0,    0,  104,
+  105,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+ 1049,    0,    0,    0,  106,  592,  108,  109, 1049, 1049,
+ 1049, 1049,    0,    0, 1049, 1049,    0, 1049, 1049, 1049,
+ 1049, 1049, 1049, 1049,    0,    0,    0,    0,    0, 1049,
+    0, 1049, 1049, 1049, 1049, 1049, 1049,    0,    0, 1049,
+    0,    0,    0, 1049, 1049,    0, 1049, 1049, 1049,    0,
+    0,    0,    0,    0,    0,    0,    0,    0, 1049,    0,
+ 1049,    0, 1049, 1049,    0,    0, 1049,    0, 1049, 1049,
+ 1049, 1049, 1049, 1049, 1049, 1049, 1049, 1049, 1049, 1049,
+    0, 1049,    0,    0, 1049, 1049,    0,    0, 1049, 1049,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0, 1049, 1049, 1049, 1049, 1049,    0,    0,
+    0,    0, 1049,    0,    0,    0, 1049,    0,    0,    0,
+    0, 1049, 1049, 1049, 1049, 1049,    0,    0,    0, 1049,
+    0, 1049,    0,    0,    0,    0,    0, 1049, 1049,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  635,    0,
+    0,    0, 1049, 1049, 1049, 1049,   57,   24,    0,   25,
+    0,    0,   26,  259,    0,    0,    0,   27,   62,   63,
+    0,   28,    0,    0,  189,    0,  189,   65,    0,  189,
+   30,    0,    0,    0,  189,    0,    0,   32,  189,    0,
+    0,    0,   33,    0,   72,   73,   34,  189,  636,    0,
+    0,    0,    0,    0,  189,  637,    0,    0,   36,  189,
+   37,   75,    0,  189,   38,    0,    0,   77,    0,   79,
+    0,   81,   39,   40,  260,  189,   41,  189,    0,    0,
+    0,  189,    0,  638,    0,    0,   88,   89,    0,  189,
+  189,    0,    0,  189,    0,    0,  189,    0,    0,    0,
+    0,   90,   91,   92,   93,   94,    0,    0,    0,    0,
+    0,    0,    0,    0,   96,    0,    0,  639,    0,    0,
+   98,   99,  100,  101,    0,    0,    0,  102,    0,  103,
+    0,    0, 1074,    0,    0,  104,  105,    0,    0,    0,
+    0,    0,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+  106,  107,  108,  109,   65,    0,    0,   30,    0,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,  189,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+   87,    0,    0,   88,   89,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,   93,  801,    0,    0,    0,    0,  802, 1088,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,    0,    0,    0,
+    0,    0,  104,  105,    0,    0,    0,    0,    0,    0,
+   57,   24,    0,   25,    0,    0,   26,  259,    0,    0,
+    0,   27,   62,   63,    0,   28,    0,  106,  803,  108,
+  109,   65,    0,  804,   30,    0,    0,    0,  805,    0,
+    0,   32,    0,    0,    0,    0,   33,    0,   72,   73,
+   34,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   36,    0,   37,   75,    0,    0,   38,    0,
+    0,   77,    0,   79,    0,   81,   39,   40,  260,    0,
+   41,    0,    0,    0,    0,    0,    0,   87,    0,    0,
+   88,   89,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   90,   91,   92,   93,  801,
+    0,    0,    0,    0,  802,    0,    0,    0,   96,    0,
+    0,    0,    0,    0,   98,   99,  100,  101,    0,    0,
+    0,  102,    0,  103,    0,    0,    0,    0,    0,  104,
+  105,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  819,  106,  803,  108,  109,    0,    0,
+  804,   57,   24,    0,   25,  805,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,  189,
+    0,  189,   65,    0,  189,   30,    0,    0,    0,  189,
+    0,    0,   32,  189,    0,    0,    0,   33,    0,   72,
+   73,   34,  189,    0,    0,    0,    0,    0,    0,  189,
+    0,    0,    0,   36,  189,   37,   75,    0,  189,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+  189,   41,  189,    0,    0,    0,  189,    0,   87,    0,
+    0,   88,   89,    0,  189,  189,    0,    0,  189,    0,
+    0,  189,    0,    0,    0,    0,   90,   91,   92,   93,
+  308,    0,    0,    0,    0,  546,  820,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103, 1074,    0,    0,    0,    0,
+  104,  105,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0, 1013,    0,    0,    0,  106,  309,  108,  109,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,  189,   28,    0,    0,   24,    0,   25,
+   65,    0,   26,   30,    0,    0,    0,   27,    0,    0,
+   32,   28,    0,    0,    0,   33,    0,   72,   73,   34,
+   30,  636,    0,    0,    0,    0,    0,   32,  637,    0,
+    0,   36,   33,   37,   75,    0,   34,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,   36,   41,
+   37,    0,    0,    0,   38,    0,  638,    0,    0,   88,
+   89,    0,   39,   40,    0,    0,   41,    0,    0,   85,
+    0,    0,    0,    0,   90,   91,   92,   93,   94,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,    0,    0,    0,    0,    0,  104,  105,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,  819,
+    0,    0,    0,  106,  107,  108,  109,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,  380,   28,    0,    0,   24,    0,   25,   65,    0,
+   26,   30,    0,    0,    0,   27,    0,    0,   32,   28,
+    0,    0,    0,   33,    0,   72,   73,   34,   30,    0,
+    0,    0,    0,    0,    0,   32,    0,    0,    0,   36,
+   33,   37,   75, 1019,   34,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,   36,   41,   37,    0,
+    0,    0,   38,    0,   87,    0,    0,   88,   89,    0,
+   39,   40,    0,    0,   41,    0,    0,  608,    0,    0,
+    0,    0,   90,   91,   92,   93,  308,    0,    0,    0,
+    0,  546,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,    0,    0,    0,    0,    0,  104,  105,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  819,    0,    0,
+    0,  106,  309,  108,  109,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,  380,
+   28,    0,    0,    0,    0,    0,   65,    0,    0,   30,
+    0,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,   87,    0,    0,   88,   89,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,   93,  308,    0,    0,    0,    0,  546,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,    0,
+    0,    0,    0,    0,  104,  105,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  347,    0,  106,
+  309,  108,  109,  348,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,    0,    0,   30,
+    0,    0,    0,    0,    0,    0,   32,    0,    0,  349,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,  350,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  351,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,  352,    0,    0,    0,   98,
+   99,  100,  101,  972,    0,    0,  102,    0,  103,  811,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,   87,    0,    0,   88,   89,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,   93,  308,    0,    0,    0,
+    0,    0,  973,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,    0,    0,    0,    0,    0,  104,  105,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0, 1016,    0,    0,
+    0,  106,  309,  108,  109,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,   24,    0,   25,   65,    0,   26,   30,
+    0,    0,    0,   27,    0,    0,   32,   28,    0,    0,
+    0,   33,    0,   72,   73,   34,   30,    0,    0,    0,
+    0,    0,    0,   32,    0,    0,    0,   36,   33,   37,
+   75,    0,   34,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,   36,   41,   37,    0,    0,    0,
+   38,    0,   87,    0,    0,   88,   89,    0,   39,   40,
+    0,    0,   41,    0,    0,  563,    0,    0,    0,    0,
+   90,   91,   92,   93,  308,    0,    0,    0,    0,    0,
+ 1017,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,    0,
+    0,    0,    0,    0,  104,  105,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  307,    0,    0,    0,  106,
+  309,  108,  109,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,  380,   28,    0,
+    0,  527,    0,  527,   65,    0,  527,   30,    0,    0,
+    0,  527,    0,    0,   32,  527,    0,    0,    0,   33,
+    0,   72,   73,   34,  527,    0,    0,    0,    0,    0,
+    0,  527,    0,    0,    0,   36,  527,   37,   75,    0,
+  527,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,  527,   41,  527,    0,    0,    0,  527,    0,
+   87,    0,    0,   88,   89,    0,  527,  527,    0,    0,
+  527,    0,    0,  527,    0,    0,    0,    0,   90,   91,
+   92,   93,  308,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,    0,    0,    0,
+    0,    0,  104,  105,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  316,    0,    0,    0,  106,  309,  108,
+  109,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,  527,   28,    0,    0,    0,
+    0,    0,   65,    0,    0,   30,    0,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,   87,    0,
+    0,   88,   89,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,   93,
+  308,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,    0,    0,    0,    0,    0,
+  104,  105,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  347,    0,  106,  309,  108,  109,  348,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,    0,    0,   30,    0,    0,    0,    0,
+    0,    0,   32,    0,    0,  349,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+  350,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  351,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,  352,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,  633,    0,    0,    0,    0,
+  104,  105,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+    0,    0,    0,    0,   65,  106,  263,   30,  109,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,    0,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+   87,    0,    0,   88,   89,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,   93,   94,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,    0,    0,    0,
+    0,    0,  104,  105,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  811,    0,    0,    0,  106,  107,  108,
+  109,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,  190,
+    0,  190,   65,    0,  190,   30,    0,    0,    0,  190,
+    0,    0,   32,  190,    0,    0,    0,   33,    0,   72,
+   73,   34,  190,    0,    0,    0,    0,    0,    0,  190,
+    0,    0,    0,   36,  190,   37,   75,    0,  190,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+  190,   41,  190,    0,    0,    0,  190,    0,   87,    0,
+    0,   88,   89,    0,  190,  190,    0,    0,  190,    0,
+    0,  190,    0,    0,    0,    0,   90,   91,   92,   93,
+  308,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,    0,    0,    0,    0,    0,
+  104,  105,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0, 1126,    0,    0,    0,  106,  309,  108,  109,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,  190,   28,    0,    0,  189,    0,  189,
+   65,    0,  189,   30,    0,    0,    0,  189,    0,    0,
+   32,  189,    0,    0,    0,   33,    0,   72,   73,   34,
+  189,    0,    0,    0,    0,    0,    0,  189,    0,    0,
+    0,   36,  189,   37,   75,    0,  189,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,  189,   41,
+  189,    0,    0,    0,  189,    0,   87,    0,    0,   88,
+   89,    0,  189,  189,    0,    0,  189,    0,    0,  189,
+    0,    0,    0,    0,   90,   91,   92,   93,   94,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,    0,    0,    0,    0,    0,  104,  105,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0, 1278,
+    0,    0,    0,  106, 1127,  108,  109,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,  189,   28,    0,    0,  199,    0,  199,   65,    0,
+  199,   30,    0,    0,    0,  199,    0,    0,   32,  199,
+    0,    0,    0,   33,    0,   72,   73,   34,  199,    0,
+    0,    0,    0,    0,    0,  199,    0,    0,    0,   36,
+  199,   37,   75,    0,  199,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,  199,   41,  199,    0,
+    0,    0,  199,    0,   87,    0,    0,   88,   89,    0,
+  199,  199,    0,    0,  199,    0,    0,  199,    0,    0,
+    0,    0,   90,   91,   92,   93,  308,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,    0,    0,    0,    0,    0,  104,  105,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   83,    0,    0,
+    0,  106,  309,  108,  109,   83,   83,    0,   83,    0,
+    0,   83,   83,    0,    0,    0,   83,   83,   83,  199,
+   83,    0,    0,    0,    0,    0,   83,    0,    0,   83,
+    0,    0,    0,    0,    0,    0,   83,    0,    0,    0,
+    0,   83,    0,   83,   83,   83,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   83,    0,   83,
+   83,    0,    0,   83,    0,    0,   83,    0,   83,    0,
+   83,   83,   83,   83,    0,   83,    0,    0,    0,    0,
+    0,    0,   83,    0,    0,   83,   83,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   83,   83,   83,   83,   83,    0,    0,    0,    0,    0,
+    0,    0,    0,   83,    0,    0,    0,    0,    0,   83,
+   83,   83,   83,    0,    0,    0,   83,    0,   83,    0,
+    0,    0,    0,    0,   83,   83,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  347,    0,   83,
+   83,   83,   83,  348,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,    0,    0,   30,
+    0,    0,    0,    0,    0,    0,   32,    0,    0,  349,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  351,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,  352,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,  347,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  351,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,  352,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,  356,    0,    0,    0,    0,  104,  105,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,    0,    0,    0,    0,
+   65,  106,  263,   30,  109,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,  261,  351,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,  358,    0,    0,    0,    0,  104,  105,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,  106,  263,   30,  109,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  351,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,  360,    0,    0,    0,    0,
+  104,  105,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+    0,    0,    0,    0,   65,  106,  263,   30,  109,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,    0,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,  261,  351,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,  362,    0,    0,
+    0,    0,  104,  105,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,  106,  263,   30,
+  109,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  351,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,  364,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  351,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,  366,    0,    0,    0,    0,  104,  105,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,    0,    0,    0,    0,
+   65,  106,  263,   30,  109,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,  261,  351,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,  368,    0,    0,    0,    0,  104,  105,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,  106,  263,   30,  109,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  351,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,  370,    0,    0,    0,    0,
+  104,  105,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+    0,    0,    0,    0,   65,  106,  263,   30,  109,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,    0,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,  261,  351,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,  658,    0,    0,
+    0,    0,  104,  105,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,  106,  263,   30,
+  109,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  351,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,  660,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  351,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,  662,    0,    0,    0,    0,  104,  105,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,    0,    0,    0,    0,
+   65,  106,  263,   30,  109,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,  261,  351,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,  675,    0,    0,    0,    0,  104,  105,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,  106,  263,   30,  109,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  351,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,  677,    0,    0,    0,    0,
+  104,  105,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+    0,    0,    0,    0,   65,  106,  263,   30,  109,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,    0,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,  261,  351,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,  679,    0,    0,
+    0,    0,  104,  105,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,  106,  263,   30,
+  109,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  680,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,  682,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  680,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,  684,    0,    0,    0,    0,  104,  105,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,    0,    0,    0,    0,
+   65,  106,  263,   30,  109,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,  261,  680,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,  686,    0,    0,    0,    0,  104,  105,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,  106,  263,   30,  109,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  680,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,  688,    0,    0,    0,    0,
+  104,  105,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+    0,    0,    0,    0,   65,  106,  263,   30,  109,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,    0,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,  261,  680,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,  690,    0,    0,
+    0,    0,  104,  105,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,  106,  263,   30,
+  109,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  680,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,  692,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  680,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,  694,    0,    0,    0,    0,  104,  105,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,    0,    0,    0,    0,
+   65,  106,  263,   30,  109,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,  261,  680,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,  696,    0,    0,    0,    0,  104,  105,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,  106,  263,   30,  109,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  680,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,  698,    0,    0,    0,    0,
+  104,  105,    0,   57,   24,    0,   25,    0,    0,   26,
+  259,    0,    0,    0,   27,   62,   63,    0,   28,    0,
+    0,    0,    0,    0,   65,  106,  263,   30,  109,    0,
+    0,    0,    0,    0,   32,    0,    0,    0,    0,   33,
+    0,   72,   73,   34,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   36,    0,   37,   75,    0,
+    0,   38,    0,    0,   77,    0,   79,    0,   81,   39,
+   40,  260,    0,   41,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   90,   91,
+   92,  261,  680,    0,    0,    0,    0,    0,    0,    0,
+    0,   96,    0,    0,    0,    0,    0,   98,   99,  100,
+  101,    0,    0,    0,  102,    0,  103,  700,    0,    0,
+    0,    0,  104,  105,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,    0,    0,    0,    0,   65,  106,  263,   30,
+  109,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,  261,  680,    0,    0,    0,    0,    0,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,  702,
+    0,    0,    0,    0,  104,  105,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,    0,    0,    0,    0,   65,  106,
+  263,   30,  109,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  680,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,  704,    0,    0,    0,    0,  104,  105,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,    0,    0,    0,    0,
+   65,  106,  263,   30,  109,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,  261,  680,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,  869,    0,    0,    0,    0,  104,  105,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,  106,  263,   30,  109,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  351,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,    0,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,    0,    0,    0,    0,    0,
+  104,  105,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  210,    0,    0,    0,    0,  210,    0,
+    0,    0,  210,    0,  210,  106,  263,  210,  109,  210,
+  210,    0,  210,    0,  210,    0,  210,    0,  210,  210,
+  210,  210,    0,    0,  210,  210,    0,    0,    0,    0,
+  210,    0,  210,  210,  210,    0,    0,  210,    0,  210,
+    0,  210,    0,    0,  210,    0,  210,  210,  210,  210,
+    0,    0,    0,  210,  210,  210,    0,    0,  210,  210,
+  210,    0,    0,    0,    0,    0,    0,  210,  210,    0,
+  210,  210,  666,  210,  210,  210,    0,    0,    0,  210,
+   57,   24,    0,   25,    0,    0,   26,  259,    0,    0,
+    0,   27,   62,   63,    0,   28,    0,    0,    0,  210,
+    0,   65,    0,    0,   30,  210,  210,  210,    0,    0,
+    0,   32,    0,    0,    0,  210,   33,    0,   72,   73,
+   34,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   36,    0,   37,   75,    0,    0,   38,    0,
+    0,   77,    0,   79,    0,   81,   39,   40,  260,    0,
+   41,    0,    0,   85,    0,    0,  210,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,   90,   91,   92,  261,  262,
+    0,    0,    0,  525,    0,    0,    0,    0,   96,    0,
+  364,   57,   24,    0,   25,  667,  668,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,    0,    0,
+    0,    0,   65,    0,    0,   30,    0,    0,    0,   51,
+    0,   51,   32,    0,    0,    0,  364,   33,    0,   72,
+   73,   34,    0,    0,  106,  263,    0,    0,    0,    0,
+    0,    0,   51,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,   51,   81,   39,   40,  260,
+   51,   41,    0,    0,    0,   51,    0,   51,   51,   51,
+   51,    0,    0,   51,    0,   51,    0,    0,    0,   51,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,  261,
+  526,   51,  364,    0,   51,    0,   51,    0,    0,   96,
+  364,  364,  364,  364,  836,    0,    0,  364,  364,    0,
+    0,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+   51,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,  364,  364,  364,  364,  364,  364,  364,
+  364,  364,  364,    0,    0,  106,  527,    0,    0,  364,
+    0,   52,  364,   52,    0,   52,    0,   52,    0,    0,
+   52,    0,   52,   52,    0,   52,    0,   52,    0,   52,
+    0,   52,   52,   52,   52,    0,    0,   52,   52,    0,
+    0,    0,    0,   52,   52,   52,   52,   52,    0,    0,
+   52,    0,   52,    0,   52,    0,   52,   52,    0,   52,
+   52,   52,   52,    0,    0,   52,   52,   52,   52,    0,
+    0,   52,   52,   52,    0,    0,    0,    0,    0,    0,
+   52,   52,    0,   52,   52,    0,   52,   52,   52,    0,
+    0,    0,   52,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   52,    0,    0,   52,   52,   51,    0,    0,
+    0,   51,    0,   51,    0,    0,   51,    0,   51,   51,
+    0,   51,    0,   51,    0,   51,    0,   51,   51,   51,
+   51,    0,    0,   51,   51,    0,    0,    0,    0,   51,
+    0,   51,   51,   51,    0,    0,   51,    0,   51,    0,
+   51,    0,    0,   51,    0,   51,   51,   51,   51,   52,
+    0,    0,   51,   51,   51,    0,    0,   51,   51,   51,
+    0,    0,    0,    0,    0,    0,   51,   51,    0,   51,
+   51,    0,   51,   51,   51,    0,    0,    0,   51,    0,
+    0,   51,    0,    0,    0,   51,    0,   51,    0,    0,
+   51,    0,   51,   51,    0,   51,    0,   51,   51,   51,
+    0,   51,   51,   51,   51,   86,    0,   51,   51,    0,
+    0,    0,    0,   51,   51,   51,   51,   51,    0,    0,
+   51,    0,   51,    0,   51,    0,    0,   51,    0,   51,
+   51,   51,   51,    0,    0,    0,   51,   51,   51,    0,
+    0,   51,   51,   51,    0,    0,    0,    0,    0,    0,
+   51,   51,    0,   51,   51,   51,   51,   51,   51,    0,
+    0,    0,   51,    0,    0,   52,    0,    0,    0,   52,
+    0,   52,    0,    0,   52,    0,   52,   52,    0,   52,
+    0,   52,   51,   52,    0,   52,   52,   52,   52,   87,
+    0,   52,   52,    0,    0,    0,    0,   52,   51,   52,
+   52,   52,    0,    0,   52,    0,   52,    0,   52,    0,
+    0,   52,    0,   52,   52,   52,   52,    0,    0,    0,
+   52,   52,   52,    0,    0,   52,   52,   52,    0,    0,
+    0,    0,    0,    0,   52,   52,    0,   52,   52,   51,
+   52,   52,   52,    0,    0,    0,   52,    0,    0,   51,
+    0,    0,    0,   51,    0,   51,    0,    0,   51,    0,
+   51,   51,    0,   51,    0,   51,   52,   51,    0,   51,
+   51,   51,   51,    0,    0,   51,   51,    0,    0,    0,
+    0,   51,   52,   51,   51,   51,    0,    0,   51,    0,
+   51,    0,   51,    0,    0,   51,    0,   51,   51,   51,
+   51,    0,    0,    0,   51,   51,   51,    0,    0,   51,
+   51,   51,    0,    0,    0,    0,    0,    0,   51,   51,
+    0,   51,   51,   52,   51,   51,   51,    0,    0,    0,
+   51,    0,    0,   51,    0,    0,    0,   51,    0,   51,
+    0,    0,   51,    0,   51,   51,    0,   51,    0,   51,
+   51,   51,    0,   51,   51,   51,   51,  238,    0,   51,
+   51,    0,    0,    0,    0,   51,    0,   51,   51,   51,
+    0,    0,   51,    0,   51,  364,   51,    0,    0,   51,
+    0,   51,   51,   51,   51,    0,    0,    0,   51,   51,
+   51,    0,    0,   51,   51,   51,    0,    0,  364,    0,
+    0,    0,   51,   51,    0,   51,   51,   51,   51,   51,
+   51,  364,    0,    0,   51,    0,  364,    0,    0,  364,
+    0,  364,    0,  364,  364,  364,  364,    0,    0,    0,
+    0,  364,    0,    0,   51,  364,    0,    0,    0,  364,
+    0,  239,    0,    0,    0,    0,    0,  364,    0,    0,
+  364,    0,  364,    0,   57,   24,    0,   25,    0,    0,
+   26,  259,    0,    0,    0,   27,   62,   63,    0,   28,
+    0,  364,    0,    0,    0,   65,  364,    0,   30,    0,
+    0,    0,    0,  364,  364,   32,  287,    0,  364,    0,
+   33,   51,   72,   73,   34,    0,  636,    0,    0,    0,
+    0,  364,    0,  637,    0,    0,   36,    0,   37,   75,
+    0,    0,   38,    0,    0,   77,    0,   79,    0,   81,
+   39,   40,  260,    0,   41,    0,    0,    0,    0,    0,
+    0,  638,    0,  364,   88,   89,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   90,
+   91,   92,   93,   94,    0,    0,    0,    0,    0,    0,
+    0,    0,   96, 1011,    0,  639,    0,    0,   98,   99,
+  100,  101,    0,    0,    0,  102,    0,  103,    0,    0,
+    0,    0,    0,  104,  105,    0,    0,    0,    0,    0,
+    0,   57,   24,    0,   25,    0,    0,   26,  259,    0,
+    0,    0,   27,   62,   63,    0,   28,    0,  106,  107,
+  108,  109,   65,    0,    0,   30,    0,    0,    0,    0,
+    0,    0,   32,    0,    0,    0,    0,   33,    0,   72,
+   73,   34,    0,  636,    0,    0,    0,    0,    0,    0,
+  637,    0,    0,   36,    0,   37,   75,    0,    0,   38,
+    0,    0,   77,    0,   79,    0,   81,   39,   40,  260,
+    0,   41,    0,    0,    0,    0,    0,    0,  638,    0,
+    0,   88,   89,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,   90,   91,   92,   93,
+   94,    0,    0,    0,    0,    0,    0,    0,    0,   96,
+    0,    0,  639,    0,    0,   98,   99,  100,  101,    0,
+    0,    0,  102,    0,  103,    0,    0,    0,    0,    0,
+  104,  105,    0,    0,    0,    0,    0,    0,   57,   24,
+    0,   25,    0,    0,   26,  259,    0,    0,    0,   27,
+   62,   63,    0,   28,    0,  106,  107,  108,  109,   65,
+    0,    0,   30,    0,    0,    0,    0,    0,    0,   32,
+    0,    0,    0,    0,   33,    0,   72,   73,   34,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   36,    0,   37,   75,    0,    0,   38,    0,    0,   77,
+    0,   79,    0,   81,   39,   40,  260,    0,   41,    0,
+    0,   85,    0,    0,    0,   87,    0,    0,   88,   89,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,   90,   91,   92,   93,  308,    0,    0,
+    0,    0,    0,    0,    0,    0,   96,    0,    0,    0,
+    0,    0,   98,   99,  100,  101,    0,    0,    0,  102,
+    0,  103,    0,    0,    0,    0,    0,  104,  105,    0,
+    0,    0,    0,    0,    0,   57,   24,    0,   25,    0,
+    0,   26,  259,    0,    0,    0,   27,   62,   63,    0,
+   28,    0,  106,  309,  108,  109,   65,    0,    0,   30,
+    0,    0,    0,    0,    0,    0,   32,    0,    0,    0,
+    0,   33,    0,   72,   73,   34,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   36,    0,   37,
+   75,    0,    0,   38,    0,    0,   77,    0,   79,    0,
+   81,   39,   40,  260,    0,   41,    0,    0,    0,    0,
+    0,    0,   87,    0,    0,   88,   89,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+   90,   91,   92,   93,  308,    0,    0,    0,    0,  546,
+    0,    0,    0,   96,    0,    0,    0,    0,    0,   98,
+   99,  100,  101,    0,    0,    0,  102,    0,  103,    0,
+    0,    0,    0,    0,  104,  105,    0,    0,    0,    0,
+    0,    0,   57,   24,    0,   25,    0,    0,   26,  259,
+    0,    0,    0,   27,   62,   63,    0,   28,    0,  106,
+  309,  108,  109,   65,    0,    0,   30,    0,    0,    0,
+    0,    0,    0,   32,    0,    0,    0,    0,   33,    0,
+   72,   73,   34,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   36,    0,   37,   75,    0,    0,
+   38,    0,    0,   77,    0,   79,    0,   81,   39,   40,
+  260,    0,   41,    0,    0,    0,    0,    0,    0,   87,
+    0,    0,   88,   89,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   90,   91,   92,
+   93,  308,    0,    0,    0,    0,  540,    0,    0,    0,
+   96,    0,    0,    0,    0,    0,   98,   99,  100,  101,
+    0,    0,    0,  102,    0,  103,    0,    0,    0,    0,
+    0,  104,  105,    0,    0,    0,    0,    0,    0,   57,
+   24,    0,   25,    0,    0,   26,  259,    0,    0,    0,
+   27,   62,   63,    0,   28,    0,  106,  309,  108,  109,
+   65,    0,    0,   30,    0,    0,    0,    0,    0,    0,
+   32,    0,    0,    0,    0,   33,    0,   72,   73,   34,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   36,    0,   37,   75,    0,    0,   38,    0,    0,
+   77,    0,   79,    0,   81,   39,   40,  260,    0,   41,
+    0,    0,    0,    0,    0,    0,   87,    0,    0,   88,
+   89,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   90,   91,   92,   93,  308,    0,
+    0,    0,    0,    0,    0,    0,    0,   96,    0,    0,
+    0,    0,    0,   98,   99,  100,  101,    0,    0,    0,
+  102,    0,  103,    0,    0,    0,    0,    0,  104,  105,
+    0,    0,    0,    0,    0,    0,   57,   24,    0,   25,
+    0,    0,   26,  259,    0,    0,    0,   27,   62,   63,
+    0,   28,    0,  106,  309,  108,  109,   65,    0,    0,
+   30,    0,    0,    0,    0,    0,    0,   32,    0,    0,
+    0,    0,   33,    0,   72,   73,   34,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,   36,    0,
+   37,   75,    0,    0,   38,    0,    0,   77,    0,   79,
+    0,   81,   39,   40,  260,    0,   41,    0,    0,    0,
+    0,    0,    0,   87,    0,    0,   88,   89,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,   90,   91,   92,   93,   94,    0,    0,    0,    0,
+    0,    0,    0,    0,   96,    0,    0,    0,    0,    0,
+   98,   99,  100,  101,    0,    0,    0,  102,    0,  103,
+    0,    0,    0,    0,    0,  104,  105,    0,    0,    0,
+    0,    0,    0,  687,  687,    0,  687,    0,    0,  687,
+  687,    0,    0,    0,  687,  687,  687,    0,  687,    0,
+  106,  107,  108,  109,  687,    0,    0,  687,    0,    0,
+    0,    0,    0,    0,  687,    0,    0,    0,    0,  687,
+    0,  687,  687,  687,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  687,    0,  687,  687,    0,
+    0,  687,    0,    0,  687,    0,  687,    0,  687,  687,
+  687,  687,    0,  687,    0,    0,    0,    0,    0,    0,
+  687,    0,    0,  687,  687,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,  687,  687,
+  687,  687,  687,    0,    0,    0,    0,    0,    0,    0,
+    0,  687,    0,    0,    0,    0,    0,  687,  687,  687,
+  687,    0,    0,    0,  687,    0,  687,    0,    0,    0,
+    0,    0,  687,  687,    0,    0,    0,    0,    0,    0,
+  146,  146,    0,  146,    0,    0,  146,  146,    0,    0,
+    0,  146,  146,  146,    0,  146,    0,  687,  687,  687,
+  687,  146,    0,    0,  146,    0,    0,    0,    0,    0,
+    0,  146,    0,    0,    0,    0,  146,    0,  146,  146,
+  146,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,  146,    0,  146,  146,    0,    0,  146,    0,
+    0,  146,    0,  146,    0,  146,  146,  146,  146,    0,
+  146,    0,    0,    0,    0,    0,    0,  146,    0,    0,
+  146,  146,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  146,  146,  146,  146,  146,
+    0,    0,    0,    0,    0,    0,    0,    0,  146,    0,
+    0,    0,    0,    0,  146,  146,  146,  146,    0,    0,
+    0,  146,    0,  146,    0,    0,    0,    0,    0,  146,
+  146,    0,    0,    0,    0,    0,    0,   57,   24,    0,
+   25,    0,    0,   26,  259,    0,    0,    0,   27,   62,
+   63,    0,   28,    0,  146,  146,  146,  146,   65,    0,
+    0,   30,    0,    0,    0,    0,    0,    0,   32,    0,
+    0,    0,    0,   33,    0,   72,   73,   34,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   36,
+    0,   37,   75,    0,    0,   38,    0,    0,   77,    0,
+   79,    0,   81,   39,   40,  260,    0,   41,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,   90,   91,   92,  261,  680,    0,    0,    0,
+    0,    0,    0,    0,    0,   96,    0,    0,    0,    0,
+    0,   98,   99,  100,  101,    0,    0,    0,  102,    0,
+  103,    0,   57,   24,    0,   25,  104,  105,   26,  259,
+    0,    0,    0,   27,   62,   63,    0,   28,    0,    0,
+    0,    0,    0,   65,    0,    0,   30,    0,    0,    0,
+    0,  106,  263,   32,  109,    0,    0,    0,   33,    0,
+   72,   73,   34,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,   36,    0,   37,   75,    0,    0,
+   38,    0,    0,   77,    0,   79,    0,   81,   39,   40,
+  260,    0,   41,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,   90,   91,   92,
+  261,  351,    0,    0,    0,    0,    0,    0,    0,    0,
+   96,    0,    0,    0,    0,    0,   98,   99,  100,  101,
+    0,    0,    0,  102,    0,  103,    0,    0,    0,    0,
+    0,  104,  105,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,  733,    0,  733,    0,  733,  106,  263,  733,  109,
+  733,  733,    0,  733,    0,  733,    0,  733,    0,  733,
+  733,  733,    0,    0,    0,  733,  733,    0,    0,    0,
+    0,  733,    0,  733,  733,    0,    0,    0,  733,    0,
+    0,    0,  733,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,  733,  733,    0,  733,    0,    0,    0,
+  733,  733,    0,    0,    0,    0,    0,    0,  733,  733,
+   57,   24,  733,   25,    0,  733,   26,  259,    0,    0,
+  733,   27,   62,   63,    0,   28,    0,    0,    0,    0,
+    0,   65,    0,    0,   30,    0,    0,    0,    0,    0,
+    0,   32,    0,  733,  733,    0,   33,    0,   72,   73,
+   34,    0,    0,    0,    0,    0,  733,    0,    0,    0,
+    0,    0,   36,    0,   37,   75,    0,    0,   38,    0,
+    0,   77,    0,   79,    0,   81,   39,   40,  260,    0,
+   41,    0,    0,   85,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,  733,    0,    0,
+    0,    0,    0,    0,    0,   90,   91,   92,  261,  262,
+    0,    0,    0,    0,    0,  732,    0,  732,   96,    0,
+  732,    0,  732,  732,    0,  732,    0,  732,    0,  732,
+    0,  732,  732,  732,    0,    0,    0,  732,  732,    0,
+    0,    0,    0,  732,    0,  732,  732,    0,    0,    0,
+  732,    0,    0,    0,  732,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,  106,  263,  732,    0,  732,    0,
+    0,    0,  732,  732,    0,    0,    0,    0,    0,    0,
+  732,  732,    0,   24,  732,   25,    0,  732,   26,    0,
+    0, 1399,  732,   27,    0,  757,    0,   28,    0,  758,
+ 1400, 1401,    0,    0,    0, 1402,   30,    0,    0,    0,
+    0, 1403,    0,   32,    0,   51,    0,   51,   33,    0,
+   51,    0,   34,    0,    0,   51,    0,    0,  732,   51,
+    0,    0,    0,    0,   36,    0,   37,    0,   51,    0,
+   38,    0,    0,    0,    0,   51,    0,    0,   39,   40,
+   51,    0,   41,    0,   51, 1404,   51,    0,   51,    0,
+ 1405,    0,    0,   51,    0,    0,   51,    0,   51,  732,
+    0,    0,   51,    0,    0,   51,    0,    0,    0,    0,
+   51,   51,    0,   51,   51,   51,    0,   51,   51,    0,
+    0,    0,    0,   51,    0,    0, 1406,   51,    0,    0,
+    0,    0,    0,    0,    0,    0,   51,    0,    0,    0,
+    0,    0,    0,   51,    0,   24,    0,   25,   51,    0,
+   26,    0,   51,  169,   51,   27,   51,    0,    0,   28,
+    0,   51,    0,    0,   51,    0,   51, 1407,   30,    0,
+   51,    0,    0,   51,    0,   32,    0,    0,   51,   51,
+   33,    0,   51,    0,   34,   51,  605,    0,    0,    0,
+    0,    0,    0,  606,    0,    0,   36,    0,   37,   51,
+    0,    0,   38,    0,    0,  607,    0,    0,    0,    0,
+   39,   40,    0,    0,   41,    0,    0,  608,   52,  169,
+   52,    0,    0,   52,    0,    0,    0,    0,   52,    0,
+    0,    0,   52,    0,    0,    0,    0,    0,    0,    0,
+    0,   52,    0,  609,    0,    0,    0,    0,   52,    0,
+   51,    0,   51,   52,    0,   51,    0,   52,    0,   52,
+   51,   52,    0,    0,   51,    0,   52,   51,    0,   52,
+    0,   52,    0,   51,    0,   52,    0,    0,   52,    0,
+   51,    0,    0,   52,   52,   51,    0,   52,    0,   51,
+   52,   51,    0,   51,    0,   24,    0,   25,   51,  610,
+   26,   51,    0,   51,    0,   27,    0,   51,    0,   28,
+   51,    0,    0,   29,    0,   51,   51,    0,   30,   51,
+    0,    0,   51,   31,    0,   32,    0,   24,    0,   25,
+   33,    0,   26,    0,   34,   35,    0,   27,    0,    0,
+    0,   28,    0,    0,    0,    0,   36,    0,   37,    0,
+   30,    0,   38,    0,    0,    0,    0,   32,    0,    0,
+   39,   40,   33,    0,   41,    0,   34,   42,    0,    0,
+    0,   37,   52,    0,    0,    0,    0,    0,   36,    0,
+   37,    0,   37,    0,   38,    0,    0,   37,    0,    0,
+    0,   37,   39,   40,   37,    0,   41,    0,    0,   85,
+    0,    0,    0,    0,   51,    0,   37,   37,    0,    0,
+    0,   37,   37,    0,    0,    0,    0,   37,    0,   37,
+   37,   37,   37,    0,    0,  297,    0,   37,    0,    0,
+    0,   37,    0,   37,    0,    0,    0,    0,    0,    0,
+    0,    0,   35,   37,    0,   37,   37,    0,   37,   43,
+    0,    0,   37,   35,    0,    0,    0,    0,   35,    0,
+    0,    0,   35,    0,    0,   35,    0,    0,    0,    0,
+    0,    0,   37,    0,    0,    0,    0,   35,   35,   37,
+   37,  330,   35,   35,   31,    0,    0,    0,   35,    0,
+   35,   35,   35,   35,    0,    0,    0,    0,   35,    0,
+    0,    0,   35,    0,   35,    0,    0,   31,    0,    0,
+    0,    0,    0,    0,   35,    0,    0,   35,    0,   35,
+   31,    0,   31,   35,   31,   31,    0,    0,    0,    0,
+   31,    0,   31,   31,   31,   31,    0,    0,   31,    0,
+   31,    0,    0,   35,   31,   31,    0,    0,    0,    0,
+   35,   35,    0,    0,    0,    0,   31,    0,   31,   31,
+    0,   31,    0,   31,    0,    0,    0,    0,   31,    0,
+   31,   31,   31,   31,    0,    0,    0,    0,   31,    0,
+    0,    0,   31,    0,    0,   31,    0,    0,    0,    0,
+    0,    0,   31,   31,   31,    0,    0,   31,   51,   31,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,   51,
+    0,    0,    0,    0,   51,    0,    0,    0,   51,    0,
+    0,   51,    0,   31,    0,    0,    0,    0,    0,    0,
+   31,   31,    0,   51,   51,    0,    0,    0,   51,   51,
+    0,   51,    0,    0,   51,    0,   51,   51,   51,   51,
+    0,    0,   51,    0,   51,    0,    0,   51,   51,    0,
+   51,   51,    0,    0,   51,    0,    0,    0,    0,    0,
+   51,    0,    0,   51,    0,   51,   51,   51,    0,   51,
+    0,   51,   51,    0,   51,    0,    0,   51,    0,   51,
+   51,   51,   51,    0,    0,    0,    0,   51,    0,   51,
+    0,   51,    0,   51,    0,    0,   39,   51,    0,    0,
+    0,    0,    0,   51,    0,    0,   51,    0,   51,    0,
+   51,    0,   51,    0,   51,   51,    0,    0,    0,    0,
+   51,    0,   51,   51,   51,   51,    0,    0,    0,    0,
+   51,    0,   51,    0,   51,    0,    0,   51,    0,   40,
+    0,    0,    0,    0,    0,    0,   51,    0,    0,   51,
+   51,   51,    0,    0,   51,   51,    0,    0,    0,    0,
+   51,    0,   51,   51,   51,   51,    0,    0,    0,    0,
+   51,    0,    0,    0,   51,   51,    0,   51,   51,   51,
+    0,    0,  220,    0,    0,    0,   51,    0,    0,   51,
+   51,   51,    0,    0,   51,   51,   51,    0,    0,    0,
+   51,    0,   51,   51,   51,   51,    0,    0,   51,    0,
+   51,    0,    0,    0,   51,   51,    0,   51,   51,   51,
+    0,    0,  222,    0,   51,    0,   51,    0,    0,   51,
+   51,   51,    0,    0,    0,   51,    0,    0,    0,    0,
+   51,    0,   51,   51,   51,   51,    0,   51,    0,    0,
+   51,    0,    0,    0,   51,   51,    0,    0,    0,    0,
+   51,    0,  322,    0,  477,   51,   51,    0,    0,   51,
+   51,   51,   51,   51,   51,   51,    0,    0,    0,    0,
+   51,    0,    0,    0,   51,    0,    0,  478,    0,    0,
+    0,    0,    0,    0,  477,   51,   51,    0,    0,   51,
+  479,   51,  323,    0,  480,  481,    0,    0,    0,    0,
+  482,    0,  483,  484,  485,  486,    0,  478,    0,    0,
+  487,    0,    0,    0,  488,   51,    0,    0,   51,   51,
+  479,    0,    0,    0,    0,  481,  489,    0,    0,  490,
+  482,  491,  483,  484,  485,  486,    0,    0,    0,    0,
+  487,    0,    0,    0,  488,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  492,  489,    0,    0,  490,
+    0,  491,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+    0,    0,    0,    0,    0,  492,
+  };
+  protected static readonly short [] yyCheck = {            17,
+  306,   18,    4,  305,  320,   17,   17,   52,    6,   17,
+   52,  385,  544,  295,  193,  192,  546,  239,  494,  354,
+  237,   69,  329,  304,  252,   20,  516,  341,  161,  304,
+  594,  601,  119, 1019,  302,  117,   60,  119,   60,  612,
+   88,   89,  379,  396, 1196,   93,   78,  975,   59,  824,
+  256,  395, 1236,  256,  256,    0,   74,  621,  268,  268,
+   78,  336,  256,  379,   17,  113,  268,  292,  256,   80,
+  256,   82,  256, 1470,  256,  256,  335, 1230,   96,   45,
+  385, 1340,   48,    0,   88,   89,  256,  294,  282,   62,
+  464, 1275, 1024,   66,   67,   68,  369,   70,   71,  306,
+ 1359,   17,   75,   76,  256,  109, 1290,   17,   81,   82,
+  256,   84,  256,   86,  256,  369, 1076, 1305,   91,   92,
+  314,  269,  357,   21,  325,  499,  369,   17,  176,  792,
+  256,  794,  256,  374,  377,  256,  377,  256,  286,  375,
+  256, 1294, 1102,  161,   17,  118,  256,  372,  193,  161,
+  161,  193,  387,  161,   20,   53, 1314,  430,  731,  464,
+  369,  436,  256,  256,   17,  419,  372,  395,  256,  339,
+  373,  430,  375,   17,  344,  838,  346,  268,  841,  349,
+  350,  417,  352,  353,  368,  276,  368,  256,  372,   17,
+  372,   17,  237,  256, 1382,  237,  421,   17,  256,  203,
+  204,  382, 1599,  251,  252,  375,  392,   60,  161,   17,
+   17,   64,  419,  423,  423,  421,  590,  265,  419,   17,
+ 1152,  423,   88,   89,  368,  419,  540,  430,  256,  415,
+  372,  419, 1160,  377,  252,  233,  422,  421,  460,  421,
+  258,  543,  459,  109,  331,  161,  328,  363,  585,  331,
+  343,  161,  626,  363,  302, 1413,  338,  631,  632,  594,
+  430,  227,   60, 1421,  268,  795,   64,  419,  292,  585,
+  292,  161,  363,  419,  368, 1534,  370,  295,  372,  421,
+  302,  851,  300,  301,  628,  333,  621,  260,  161,  358,
+  294,  264,  340,  419,  382,  419,  612,  315,  419,  392,
+  419,  325, 1561,  419,  352,  323,    0,  325,  161,  419,
+  314,  329,  257,  324, 1573,  256, 1575,  161,  376,  382,
+ 1478,  256,  415,  256,  342,  343,  631,  421,  419,  422,
+  424,  304,  256,  161, 1191,  161,  429,  203,  204,  387,
+  257,  161,  354,  391,  348,  349,  354,  395,  396,  377,
+ 1125,  383,  726,  161,  161,  272,  425,  426,  427,  428,
+  277,  256,  256,  161,  281,  383,  375,  256,  256,  256,
+  374,  256,  256,  277, 1231,  369, 1528,  395,  396,  296,
+  953,  399,  400,  401,  402,  403,  404,  405,  406,  407,
+  408,  409,  414,  441,  442,  732,  256,  445,  256,  674,
+  628,  256,  268,  392,  256,  256,  323,  256,  417,  413,
+ 1594,  256,  363,  431,  459,  731, 1402,  459, 1081,  256,
+  256,  726,  363,  256,  469,  342,  415,  469,  294,  256,
+  371,  256,  373,  368,  375,  370,  430,  441,  442,  292,
+  306,  757, 1626,  256,  377,  257,  256,  256,  314,  266,
+  256,  339,  376,  306,  320,  266,  344,  987,  346,  363,
+  256,  349,  350,  256,  352,  353,  461,  515,  419,  517,
+  262,  264,  325,  780,  256,  965,  370,  325,  419,  474,
+  305,  376,  348,  349,  373,  369,  371,  375,  363,  376,
+  375,  375,  516,  292,  292,  340,  544,  314,  509,  465,
+  466,  354,  876,  314,  341,  471,  298,  257,  374,  372,
+  370,  256,  256,  379,  372,  419,  420,  739,  358,  370,
+  375,  370,  570,  375,  542,   17,  544,  325,  546,  797,
+  867,  277,  325,  370,  887,  281, 1106,  765,  511,  375,
+  373,  351,  430, 1206,  419, 1075,  373,  413,  559,  294,
+  772,  867, 1215,  305,  429,  368,  354,  575,  421,  376,
+  578,  414,  256,  611,  373,  376,  369,  373,   60,  368,
+  369,  419,   64,  377,  343,  441,  442,  373,  589,  627,
+  628, 1244,  594,  369,  671,  558,  594,  379,  380,  671,
+  601,  373,  335,  369,  373,  461,  342,  710,  369,  343,
+  363,  369,  715,  716,  375, 1175, 1463,  375,  474,  621,
+  628, 1320, 1321,  621,  382,  952,  414,  374,  636,  637,
+  377,  363,  373,  392,  368,  673,  430,  430,  372,  369,
+  374,  375,  256,  377, 1343, 1492, 1493,  953,  382, 1496,
+  419, 1304,  373,  369,  430,  339,  415, 1211,  950,  343,
+  373,  377, 1509,  422,  430, 1512,  419, 1563, 1564,  430,
+  429, 1370,  430,  516,  712,  893,  714,  981,  372,  161,
+ 1527,  263,  416,  256,  368,  723,  809,  419,  372,  430,
+  374,  375,  376,  377, 1393,  373,  263,  429,  382,  374,
+  430,  370,  710,  256, 1551,  374,  294,  715,  716,  430,
+  718,  369,  339,  272,  430,  986,  272,  430,  277,  984,
+  369,  341,  281, 1019, 1620,  339,  375,  765,  516,  585,
+  344,  419,  346,  315,  339,  349,  350,  296,  352,  353,
+  296,  368,  256, 1321,  782,  372,  399,  400,  315,  424,
+  370,  594,  430, 1321, 1321,  424,  612,  765, 1193,  797,
+  272,  419,  305,  368,  323, 1245,  339,  323,  256,  357,
+  758,  344,  780,  346,  343,  363,  349,  350,  621,  352,
+  353, 1078,  370,  342,  296,  797,  374,  795,  272, 1321,
+  343,  305, 1370, 1321,  802, 1317,  804,  339, 1233,  387,
+ 1092,  306, 1370, 1370, 1425, 1321,  594,  372,  313,  374,
+  292,  323,  296,  382, 1321,  368,  430,  256, 1439,  372,
+  325,  374,  375,  392,  377, 1043,  368, 1321,  866,  382,
+  831,  419,  833,  621,  376,  843,  830,  845, 1370,  323,
+ 1461,  256, 1370,  325, 1169,  948,  415,  855,  849,  887,
+  851,  339,  846,  422, 1370,  893,  344,  430,  346,  339,
+  429,  349,  350, 1370,  352,  353,  829,  343, 1035,  863,
+  339,  369,  354,  364,  370,  731, 1370,  375,  368,  887,
+  339,  372,  985,  374,  382,  893, 1211,  377,  368,  392,
+  343,  369, 1164,  372,  902,  930,  904,  375,  930,  368,
+  339,  757,  393,  394, 1196,  344,  382,  346,  382,  368,
+  349,  350,  415,  352,  353,  368,  392,  371,  392,  422,
+  377,  375,  413, 1026,  339, 1028,  429, 1199, 1031,  344,
+  421,  346,  414,  424,  349,  350,  343,  352,  353,  415,
+  948,  415,  950,  256,  402,  357,  422,  343,  422,  792,
+  935,  794,  940,  429,  992,  256,  414,  368,  343,  967,
+  954,  368,  374,  343,  972,  339,  377,  975,  269,  343,
+ 1242, 1189,  368, 1439,  830,  387,  377,  985,  392,  987,
+ 1305,  377,  990,  368, 1022,  286,  415,  368,  368,  370,
+  846,  430,  377,  422,  368,  838, 1516,  377,  841,  343,
+  357,  415,  306,  377,  792, 1043,  794,  863,  422,  313,
+  294,  867, 1115, 1408, 1117,  430, 1119,  374, 1026,  368,
+ 1028, 1059,  306, 1031,  368, 1420,  339, 1065,  383,  384,
+  387,  344,  256,  346,  516, 1043,  349,  350, 1383,  352,
+  353,  387,  397,  398,  306, 1390,  308,  372, 1260, 1256,
+  838,  313,  369,  841, 1048, 1040, 1328, 1382, 1578, 1228,
+  377,  370, 1050,  325, 1052,  385, 1054, 1075, 1408,  357,
+ 1078,  374, 1436,  382,  377,  363,  375, 1383,  377,  935,
+ 1420,  386,  370,  382, 1390,  373,  374,  375,  373, 1453,
+  375,  368,  369,  368,  369, 1615,  390,  953,  954,  387,
+  377,  372,  377,  374,  401, 1106, 1402, 1115, 1472, 1117,
+ 1474, 1119,  594,  391, 1122,  339, 1219,  430, 1640, 1641,
+  344,  373,  346,  375,  370,  349,  350,  369,  352,  353,
+  369,  419,  419,  375,  373,  377,  375,  416,  377,  621,
+  369, 1133,  256,  373,  373,  375,  375,  377,  377,  369,
+ 1253, 1189, 1160,  373,  371,  372, 1164,  377,  375,  395,
+  396,  371,  372, 1019,  374,  375,  376, 1169,  371, 1177,
+ 1178, 1169,  375,  371, 1175,  373, 1019,  375,  371,  419,
+  373, 1189,  375, 1190, 1040,  371,  371,  277, 1196,  375,
+  375, 1199, 1048, 1228,  374, 1230, 1228,  371, 1230,  373,
+  373,  368,  377, 1306,  377,  372,  430,  374,  375, 1211,
+  377, 1219,  377, 1211,  371,  382,  256, 1225,  375,  369,
+  370, 1256,  371, 1326, 1256,  265,  375,  267,  371,  375,
+  270,  377,  375,  372, 1242,  275, 1528,  376, 1081,  279,
+  419,  420,  421,  422,  382, 1253, 1254,    6,  288,  416,
+  373,  368,  373,  371,  377,  295,  377,  375,   17, 1294,
+  300,  371, 1294,  373,  304,  403,  404,  405,  406,  407,
+  408,  409,  410,  411,  412,  256,  316,  373,  318, 1317,
+  374,  377,  322,  368,  369, 1320, 1321,  256, 1320, 1321,
+  330,  331,  294, 1081,  334,  354,  355,  337, 1306,  377,
+  371,   60,  373, 1305,  377,   64,   20, 1305, 1343, 1317,
+  792, 1343,  794,  387,  388,  389,  294,  371, 1326,  373,
+ 1328,  373,  373,  375,  375, 1319, 1169,  354,  355,   88,
+   89,  375,  343,  377,  256, 1370, 1374,  371, 1370,  373,
+  371,  373,  373,  265,  377,  267,  356,  375,  270,  377,
+  109,  419,  375,  275,  377,  419,  838,  279, 1393,  841,
+ 1652, 1393,  375, 1206,  377,  802,  288,  804, 1211,  369,
+  370,  419, 1215,  295,   88,   89, 1232,  370,  300,  419,
+ 1382, 1169,  304,  373, 1382, 1386,  415, 1381,  376,  415,
+  416,  365,  366,  373,  316,  109,  318,  368,  369,  382,
+  322, 1244,  161,  365,  366, 1399, 1400,  377,  330,  331,
+  415,  416,  334,  417,  418,  337,  423,  424, 1206,  369,
+  364,  375,  430, 1211,  373,  369,  373, 1215,  372,  294,
+  374,  375,  294, 1427,  375,  373, 1430,  373,  382, 1447,
+  375, 1297,  373, 1444,  203,  204,  256,  377,  372,  393,
+  394,  256,  429,  429,  294,  294, 1244,  382,  373,  375,
+  374, 1304, 1305, 1319,  376,  375,  374,  419,  373,  413,
+  430, 1506,  375,  382, 1506,  375,  375,  421,  375,  424,
+  424,  373,  375,  368,  375,  373,  430,  343, 1523,  203,
+  204, 1523,  375,  294,  294,  375,  419,  419,    0,  371,
+  419, 1536, 1537,  372, 1536, 1537,  376,  368, 1516,  268,
+  256,  256,  375, 1514,  256,  256, 1304, 1305,  382,  280,
+ 1528,  256,  368,  373,  369, 1381,  343, 1383, 1563, 1564,
+  371, 1563, 1564,  292, 1390,  294,  372, 1545,  375, 1382,
+    0,  375,  377, 1399, 1400,  377, 1402,  306,  373,  382,
+  371,  373, 1408,  373,  268,  314,  424,  373,  382, 1402,
+  347,  320,  368,  382, 1420,  256,  325,  382,  256, 1425,
+ 1578, 1427,  369,  377, 1430,  373,  256,  373,  256,  347,
+  294,  375,  371, 1439,  376, 1620,  372,  371, 1620,  348,
+  349,  292,  306,  371, 1382,  354,  373,  348,  369, 1081,
+  314,  339, 1640, 1641,  373, 1461,  320, 1615,  419,  375,
+  372,  419,  348,  373,  256,  374,  369,  382,  368,  368,
+  379,  377, 1623, 1624,  368,  356,  369,  375,  337, 1630,
+ 1631,  305, 1640, 1641,  348,  349,  373,  377,  372,  369,
+  369,  373,  369,  419, 1652,  370,  372,  419,  368,  419,
+  372,  372,  419,  377,  413,  414,  372,  374,  368,  339,
+  374,  372,  343,  382,  344,  379,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,  372,  377,  382,
+  370,  373,  441,  442,  373,  372,  256, 1169,  374,  369,
+  375,  371,  374,  373,  377,  375,  376,  377,  375,  413,
+  375,  419,  375,  373,  373,  371,  419,  419,  373,  377,
+  377,  391,  419,  377,  373,  373,  369,  371,  373,  382,
+  382,  369,  315,  263, 1206,  372,  372,  441,  442, 1211,
+   94,  382,  369, 1215,   98,   99,  100,  101,  102,  103,
+  104,  105,  373,  373,  377,    0,    0,  461,  368,  377,
+  430,  369,  377,    0,  373,  257,  369,  516,  373,  261,
+  474,  368, 1244,  373,  369,  371,  369,  419,  377,  373,
+  272,  371,  368,  374,  419,  277,  419,  369,  373,  281,
+  377,  369,  284,  373,  373,  369,  377,  368,  373,  369,
+  377,  373,  369,  315,  296,  297,  256,  263,  377,  301,
+  302,  261,  262,  377,  377,  307,  377,  309,  310,  311,
+  312,  377,  377,  377,  377,  317,  377,   51,   12,  321,
+    5,  323, 1304, 1305,  284, 1040,  585,  935, 1189,    0,
+ 1189,  333, 1393,  335,  336,  594,  338,  297,  298, 1343,
+  342, 1398,  302, 1238, 1568,  305, 1531,  307, 1519,  309,
+  310,  311,  312,  612, 1444, 1584, 1548,  317, 1514,  957,
+  362,  321,  621,  952,  957,  325,  957,  369,  370,  771,
+ 1425,  585, 1358,  333, 1631, 1370,  336, 1445,  338,  339,
+ 1625, 1541, 1537,  343,  344, 1536,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,  357,  612, 1624,
+ 1382, 1294,  362,  363, 1474,  930,  320, 1297,  368,  369,
+  370,  371,  372,  373,  374,  375,  376,  377,  414,  379,
+  380,  981,  637,  383,  384,  385,  386,  387,  893, 1092,
+  390,  391,   72,  261,  765,  395,  396,  397,  398,  399,
+  400,  401,  402,  797,  308,    0,  344,  992,  425,  427,
+  426,  430, 1195,  428,  414,  429,  284,  417,  585,  419,
+  867,  421, 1272, 1381,  424, 1169,  161, 1154, 1077,  297,
+  430, 1178,  731, 1102,  302, 1061, 1167,  341, 1245,  307,
+ 1169,  309,  310,  311,  312,  560, 1214,  351,  450,  317,
+  996,  450, 1376,  321, 1254,  932,  925,  325,  757,   -1,
+   -1,   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,   -1,
+  338,   -1,   -1,  721,   -1,   -1,   -1,  731,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  792,  362,  794,    0,   -1,   -1,   -1,
+   -1,  369,   -1,  757,   -1,   -1,  410,  411,  412,   -1,
+   -1,  415,  416,  417,  418,  419,  420,  421,  422,  423,
+  424,  425,  426,  427,  428,  429,  430,   -1,   -1,   -1,
+   -1,  830,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  838,
+   -1,   -1,  841,   -1,   -1,   -1,  257,  846,   -1,   -1,
+  261,  419,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  272,   -1,   -1,  863,   -1,  277,   -1,  867,   -1,
+  281,   -1,   -1,  284,   -1,   -1,  830,  256,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  296,  297,   -1,   -1,   -1,
+  301,  302,  846,   -1,   -1,   -1,  307,   -1,  309,  310,
+  311,  312,   -1,   -1,   -1,   -1,  317,   -1,   -1,  863,
+  321,   -1,  323,  867,   -1,   -1,   -1,    0,   -1,   -1,
+   -1,   -1,  333,   -1,   -1,  336,   -1,  338,   -1,   -1,
+   -1,  342,   -1,   -1,   -1,   -1,  540,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  362,   -1,   -1,  953,  954,   -1,  368,  369,  370,
+  339,   -1,  257,   -1,   -1,  344,  261,  346,  347,  348,
+  349,  350,  351,  352,  353,  354,  355,  272,   -1,   -1,
+   -1,  935,  277,   -1,   -1,   -1,  281,   -1,   -1,  284,
+  369,   -1,  371,   -1,  373,   -1,  375,  376,  377,  953,
+  954,  296,  297,   -1,   -1,   -1,  301,  302,   -1,   -1,
+   -1,   -1,  307,  617,  309,  310,  311,  312,   -1,   -1,
+ 1019,   -1,  317,   -1,   -1,   -1,  321,   -1,  323,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  333,   -1,
+  335,  336,   -1,  338,   -1,   -1,   -1,  342,   -1, 1048,
+   -1,  430,   -1,  257,   -1,   -1,   -1,  261,   -1,   -1,
+   -1,  364,   -1,  667,  668, 1019,  369,  362,  272,  372,
+   -1,  374,  375,  277,   -1,  370,  680,  281,   -1,   -1,
+  284,   -1, 1081,   -1,   -1,   -1, 1040,   -1,   -1,   -1,
+  393,  394,  296,  297, 1048,   -1,   -1,  301,  302,   -1,
+   -1,   -1,   -1,  307,   -1,  309,  310,  311,  312,   -1,
+  413,   -1,   -1,  317,   -1,   -1,   -1,  321,  421,  323,
+   -1,  424,   -1,   -1,   -1,   -1,   -1,  430,  256,  333,
+   -1,   -1,  336,   -1,  338,   -1,   -1,  265,  342,  267,
+   -1,   -1,  270,   -1,   -1,   -1,   -1,  275,   -1,   -1,
+   -1,  279,   -1,    0,   -1,   -1,   -1,   -1,  362,   -1,
+  288,   -1,   -1,   -1,   -1,  369,  370,  295,   -1,   -1,
+ 1169,   -1,  300,  256,   -1,   -1,  304,   -1,  261,  262,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,
+  318,   -1,   -1,   -1,  322,   -1,   -1,  801,   -1,   -1,
+   -1,  284,  330,  331,   -1,   -1,  334, 1206,   -1,  337,
+   -1,   -1, 1211,   -1,  297,  298, 1215,   -1,   -1,  302,
+   -1,   -1,  305,   -1,  307,   -1,  309,  310,  311,  312,
+   -1,   -1,   -1, 1232,  317,   -1,   -1,   -1,  321,   -1,
+   -1,   -1,  325,   -1,   -1, 1244,   -1,   -1,   -1,   -1,
+  333,   -1,   -1,  336,   -1,  338,  339,   -1,   -1,   -1,
+  343,  344,   -1,  346,  347,  348,  349,  350,  351,  352,
+  353,  354,  355,  356,   -1,   -1,   -1,   -1, 1232,  362,
+  363,   -1,   -1,   -1,   -1,  368,  369,  370,  371,  372,
+  373,  419,  375,  376,  377,   -1,  379,  380, 1297,   -1,
+  383,  384,  385,  386,   -1, 1304, 1305,  390,  391,   -1,
+   -1,   -1,  395,  396,  397,  398,  399,  400,  401,  402,
+ 1319,   -1,    0,  265,   -1,  267,   -1,   -1,  270,   -1,
+  272,  414,   -1,  275,  417,   -1,  419,  279,  421,   -1,
+   -1,  424,   -1, 1297,   -1,   -1,  288,  430,   -1,   -1,
+   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,
+  302,   -1,  304,   -1,   -1, 1319,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  316,   -1,  318,  981,   -1,   -1,
+  322,  323, 1381, 1382, 1383,   -1,   -1,   -1,  330,  331,
+   -1, 1390,  334,   -1,   -1,  337,   -1,   -1,   -1,   -1,
+ 1399, 1400,   -1, 1402,   -1,   -1,   -1,   -1,   -1,  256,
+   -1,   -1,   -1,   -1,  261,  262,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1, 1381, 1427, 1383,
+   -1, 1430,   -1,   -1,   -1,   -1, 1390,  284,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1, 1399, 1400,   -1, 1402,   -1,
+  297,  298,   -1,   -1,   -1,  302,   -1,   -1,  305,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,   -1,   -1,   -1,
+  317,   -1,   -1, 1427,  321,   -1, 1430,  419,  325,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,
+    0,  338,  339,   -1,   -1,   -1,  343,  344,   -1,  346,
+  347,  348,  349,  350,  351,  352,  353,  354,  355,  356,
+   -1,   -1,   -1,   -1,   -1,  362,  363,  364,   -1,   -1,
+   -1,  368,  369,   -1,  371,  372,  373,  374,  375,  376,
+  377,   -1,  379,  380,   -1,  382,  383,  384,  385,  386,
+  387,  388,  389,  390,  391,   -1,  393,  394,  395,  396,
+  397,  398,  399,  400,  401,  402,  403,  404,  405,  406,
+  407,  408,  409,  410,  411,  412,  413,  414,   -1,   -1,
+  417,   -1,  419,   -1,  421,   -1,   -1,  424,  256,  257,
+   -1,   -1,   -1,  430,   -1,   -1,  264,  265,  266,  267,
+  268,   -1,  270,  271,   -1,  273,  274,  275,  276,  277,
+  278,  279,  280,   -1,   -1,   -1,   -1,  285,   -1,  287,
+  288,  289,  290,  291,  292,   -1,   -1,  295,   -1,   -1,
+    0,  299,  300,   -1,  302,  303,  304,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  314,   -1,  316,   -1,
+  318,  319,   -1,   -1,  322,   -1,  324,  325,  326,  327,
+  328,  329,  330,  331,  332,  333,  334,  335,   -1,  337,
+   -1,   -1,  340,  341,   -1,   -1,  344,  345,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,
+  368,  369,   -1,   -1,  372,   -1,   -1,   -1,   -1,  377,
+  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,
+   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  418,  419,  420,  421,   -1,  423,  256,  257,   -1,   -1,
+   -1,    0,  430,   -1,  264,  265,  266,  267,  268,   -1,
+  270,  271,   -1,  273,  274,  275,  276,  277,  278,  279,
+   -1,   -1,   -1,   -1,   -1,  285,   -1,  287,  288,  289,
+  290,  291,  292,   -1,   -1,  295,   -1,   -1,   -1,  299,
+  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  314,   -1,  316,   -1,  318,  319,
+   -1,   -1,  322,   -1,  324,  325,  326,  327,  328,  329,
+  330,  331,  332,  333,  334,  335,   -1,  337,   -1,   -1,
+  340,  341,   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,
+  360,  361,  362,  363,   -1,   -1,    0,   -1,  368,  369,
+   -1,   -1,  372,   -1,   -1,   -1,   -1,  377,  378,  379,
+  380,  381,   -1,   -1,   -1,  385,  256,  387,   -1,   -1,
+   -1,  261,  262,  393,  394,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  284,   -1,   -1,   -1,  418,  419,
+  420,  421,   -1,  423,   -1,   -1,   -1,  297,  298,   -1,
+  430,   -1,  302,   -1,   -1,  305,   -1,  307,   -1,  309,
+  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,   -1,
+   -1,  321,   -1,   -1,   -1,  325,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  333,   -1,   -1,  336,   -1,  338,  339,
+   -1,    0,   -1,  343,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,   -1,  362,  363,   -1,   -1,   -1,   -1,  368,  369,
+  370,  371,  372,  373,   -1,  375,  376,  377,   -1,  379,
+  380,   -1,   -1,  383,  384,  385,  386,  256,   -1,   -1,
+  390,  391,  261,  262,   -1,  395,  396,  397,  398,  399,
+  400,  401,  402,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  414,  284,   -1,  417,   -1,  419,
+   -1,  421,   -1,   -1,  424,   -1,   -1,   -1,  297,  298,
+  430,   -1,   -1,  302,   -1,   -1,  305,   -1,  307,   -1,
+  309,  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,
+   -1,   -1,  321,   -1,   -1,   -1,  325,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,   -1,  338,
+  339,   -1,   -1,   -1,  343,  344,   -1,  346,  347,  348,
+  349,  350,  351,  352,  353,  354,  355,  356,   -1,   -1,
+   -1,   -1,  256,  362,  363,   -1,   -1,   -1,  262,  368,
+  369,   -1,  371,  372,  373,   -1,  375,  376,  377,   -1,
+  379,  380,    0,   -1,  383,  384,  385,  386,   -1,   -1,
+   -1,  390,  391,   -1,   -1,   -1,  395,  396,  397,  398,
+  399,  400,  401,  402,  298,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  414,   -1,   -1,  417,   -1,
+  419,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,  343,
+  344,   -1,  346,  347,  348,  349,  350,  351,  352,  353,
+  354,  355,  356,  357,   -1,   -1,   -1,  256,   -1,  363,
+   -1,   -1,   -1,  262,  368,  369,  370,  371,  372,  373,
+  374,  375,  376,  377,   -1,  379,  380,   -1,   -1,  383,
+  384,  385,  386,  387,   -1,   -1,  390,  391,    0,   -1,
+   -1,  395,  396,  397,  398,  399,  400,  401,  402,  298,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  414,   -1,   -1,  417,   -1,  419,   -1,  421,   -1,   -1,
+  424,   -1,   -1,   -1,   -1,   -1,  430,   -1,   -1,   -1,
+   -1,    0,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  339,   -1,   -1,   -1,  343,  344,   -1,  346,  347,  348,
+  349,  350,  351,  352,  353,  354,  355,  356,   -1,   -1,
+   -1,   -1,   -1,   -1,  363,   -1,   -1,   -1,   -1,  368,
+  369,  370,  371,  372,  373,   -1,  375,  376,  377,   -1,
+  379,  380,   -1,   -1,  383,  384,  385,  386,   -1,   -1,
+   -1,  390,  391,   -1,   -1,   -1,  395,  396,  397,  398,
+  399,  400,  401,  402,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,    0,   -1,   -1,   -1,  414,   -1,   -1,  417,   -1,
+  419,   -1,  421,   -1,   -1,  424,   -1,   -1,  256,  257,
+   -1,  430,   -1,  261,   -1,   -1,   -1,  265,   -1,  267,
+   -1,   -1,  270,   -1,  272,  273,   -1,  275,   -1,  277,
+   -1,  279,   -1,  281,  282,  283,  284,   -1,    0,  287,
+  288,   -1,   -1,   -1,   -1,  293,   -1,  295,  296,  297,
+   -1,   -1,  300,  301,  302,   -1,  304,   -1,   -1,  307,
+   -1,  309,  310,  311,  312,   -1,   -1,   -1,  316,  317,
+  318,   -1,   -1,  321,  322,  323,   -1,   -1,   -1,   -1,
+   -1,   -1,  330,  331,   -1,  333,  334,   -1,  336,  337,
+  338,   -1,   -1,   -1,  342,   -1,   -1,   -1,   -1,   -1,
+   -1,    0,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  362,   -1,   -1,   -1,   -1,   -1,
+  368,  369,  370,   -1,   -1,  257,   -1,   -1,   -1,  261,
+  378,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  272,   -1,   -1,   -1,    0,  277,   -1,   -1,   -1,  281,
+   -1,   -1,  284,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  296,  297,   -1,   -1,  257,  301,
+  302,  419,  261,   -1,   -1,  307,   -1,  309,  310,  311,
+  312,   -1,   -1,  272,   -1,  317,   -1,    0,  277,  321,
+   -1,  323,  281,   -1,   -1,  284,   -1,   -1,   -1,   -1,
+   -1,  333,   -1,   -1,  336,   -1,  338,  296,  297,   -1,
+  342,   -1,  301,  302,   -1,   -1,   -1,   -1,  307,   -1,
+  309,  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,
+  362,   -1,  321,   -1,  323,   -1,   -1,  369,  370,   -1,
+   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,  257,  338,
+    0,   -1,  261,  342,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  272,   -1,   -1,   -1,   -1,  277,   -1,
+   -1,   -1,  281,  362,   -1,  284,   -1,   -1,   -1,   -1,
+   -1,  370,   -1,   -1,   -1,   -1,   -1,  296,  297,   -1,
+   -1,   -1,  301,  302,   -1,  257,   -1,   -1,  307,  261,
+  309,  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,
+  272,   -1,  321,   -1,  323,  277,   -1,   -1,   -1,  281,
+   -1,   -1,  284,   -1,  333,   -1,   -1,  336,   -1,  338,
+   -1,   -1,   -1,  342,  296,  297,   -1,   -1,   -1,  301,
+  302,   -1,   -1,   -1,   -1,  307,   -1,  309,  310,  311,
+  312,   -1,   -1,  362,   -1,  317,   -1,   -1,  257,  321,
+   -1,  323,  261,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  333,   -1,  272,  336,   -1,  338,   -1,  277,   -1,
+  342,   -1,  281,   -1,   -1,  284,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  296,  297,   -1,
+  362,  257,  301,  302,   -1,  261,   -1,   -1,  307,   -1,
+  309,  310,  311,  312,   -1,   -1,  272,   -1,  317,   -1,
+   -1,  277,  321,   -1,  323,  281,   -1,   -1,  284,   -1,
+   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,   -1,  338,
+  296,  297,   -1,  342,  257,  301,  302,   -1,  261,   -1,
+   -1,  307,   -1,  309,  310,  311,  312,   -1,   -1,  272,
+   -1,  317,   -1,  362,  277,  321,   -1,  323,  281,   -1,
+   -1,  284,   -1,   -1,   -1,   -1,   -1,  333,   -1,   -1,
+  336,   -1,  338,  296,  297,   -1,  342,   -1,  301,  302,
+   -1,   -1,   -1,   -1,  307,   -1,  309,  310,  311,  312,
+   -1,   -1,   -1,   -1,  317,   -1,  362,  257,  321,   -1,
+  323,  261,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  333,   -1,  272,  336,   -1,  338,   -1,  277,   -1,  342,
+   -1,  281,   -1,   -1,  284,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  296,  297,   -1,  362,
+   -1,  301,  302,   -1,   -1,   -1,   -1,  307,   -1,  309,
+  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,   -1,
+   -1,  321,   -1,  323,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  333,   -1,  256,  336,   -1,  338,   -1,
+   -1,   -1,  342,  264,  265,  266,  267,   -1,   -1,  270,
+  271,   -1,  273,  274,  275,  276,  277,  278,  279,   -1,
+   -1,   -1,  362,   -1,  285,   -1,  287,  288,  289,  290,
+  291,  292,   -1,   -1,  295,   -1,   -1,   -1,  299,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  314,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,  324,  325,  326,  327,  328,  329,  330,
+  331,  332,  333,  334,  335,   -1,  337,   -1,   -1,  340,
+  341,   -1,   -1,  344,  345,  256,   -1,   -1,   -1,  261,
+   -1,  262,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,  368,   -1,   -1,
+   -1,  372,  284,   -1,   -1,   -1,  377,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,  297,  387,  298,   -1,   -1,
+  302,   -1,  393,  394,   -1,  307,   -1,  309,  310,  311,
+  312,   -1,   -1,   -1,   -1,  317,   -1,   -1,   -1,  321,
+   -1,   -1,   -1,  325,   -1,   -1,   -1,  418,  419,  420,
+  421,  333,   -1,   -1,  336,   -1,  338,   -1,  339,  430,
+   -1,   -1,   -1,  344,  256,  346,  347,  348,  349,  350,
+  351,  352,  353,  354,  355,  356,  357,   -1,   -1,   -1,
+  362,   -1,  363,  364,   -1,   -1,   -1,   -1,  369,  370,
+  371,  372,  373,  374,  375,  376,  377,   -1,  379,  380,
+   -1,  382,  383,  384,  385,  386,  387,  388,  389,  390,
+  391,   -1,  393,  394,  395,  396,  397,  398,  399,  400,
+  401,  402,  403,  404,  405,  406,  407,  408,  409,  410,
+  411,  412,  413,  414,  415,   -1,  256,  419,  419,   -1,
+  421,  422,  262,  424,   -1,   -1,   -1,  339,   -1,  430,
+   -1,   -1,  344,   -1,  346,  347,  348,  349,  350,  351,
+  352,  353,  354,  355,  356,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,  298,  371,
+   -1,  373,   -1,  375,  376,  377,   -1,   -1,   -1,   -1,
+   -1,  383,  384,  385,  386,   -1,   -1,   -1,  390,  391,
+   -1,   -1,   -1,  395,  396,  397,  398,  399,  400,  401,
+  402,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  339,
+   -1,   -1,  414,   -1,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,  357,  430,   -1,
+   -1,   -1,   -1,  363,  364,   -1,   -1,   -1,   -1,  369,
+  370,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,  415,  256,  256,   -1,  419,
+   -1,  421,  262,   -1,  424,   -1,  265,   -1,  267,   -1,
+  430,  270,   -1,   -1,   -1,   -1,  275,   -1,   -1,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,  298,   -1,
+   -1,  300,   -1,   -1,   -1,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+   -1,   -1,   -1,  322,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  330,  331,   -1,   -1,  334,   -1,   -1,  337,  339,
+   -1,   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,  357,   -1,   -1,
+   -1,   -1,   -1,  363,  364,   -1,   -1,   -1,   -1,  369,
+  370,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,   -1,  256,  256,   -1,  419,
+  419,  421,  262,   -1,  424,   -1,  265,   -1,  267,   -1,
+  430,  270,   -1,   -1,   -1,   -1,  275,   -1,   -1,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,  298,   -1,
+   -1,  300,   -1,   -1,   -1,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+   -1,   -1,   -1,  322,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  330,  331,   -1,   -1,  334,   -1,   -1,  337,  339,
+   -1,   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,   -1,   -1,  363,  364,   -1,   -1,   -1,  368,  369,
+  370,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,   -1,  256,   -1,   -1,  419,
+  419,  421,  262,   -1,   -1,  261,   -1,   -1,   -1,   -1,
+  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  284,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  298,   -1,
+   -1,  297,   -1,   -1,   -1,   -1,  302,   -1,   -1,   -1,
+   -1,  307,   -1,  309,  310,  311,  312,   -1,   -1,   -1,
+   -1,  317,   -1,   -1,   -1,  321,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  333,   -1,  339,
+  336,   -1,  338,   -1,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,   -1,   -1,  363,  364,   -1,  362,   -1,  368,  369,
+   -1,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,   -1,  256,   -1,   -1,  419,
+  261,  421,  262,  419,  424,   -1,   -1,   -1,   -1,   -1,
+  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  284,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  297,   -1,  298,   -1,
+   -1,  302,   -1,   -1,  305,   -1,  307,   -1,  309,  310,
+  311,  312,   -1,   -1,   -1,   -1,  317,   -1,   -1,   -1,
+  321,   -1,   -1,   -1,  325,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  333,   -1,   -1,  336,   -1,  338,   -1,  339,
+   -1,   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,  362,   -1,  363,  364,   -1,   -1,   -1,  369,  369,
+   -1,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,   -1,  256,   -1,  419,  419,
+  261,  421,  262,   -1,  424,   -1,   -1,   -1,   -1,   -1,
+  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  284,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  297,   -1,  298,   -1,
+   -1,  302,   -1,   -1,  305,   -1,  307,   -1,  309,  310,
+  311,  312,   -1,   -1,   -1,   -1,  317,   -1,   -1,   -1,
+  321,   -1,   -1,   -1,  325,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  333,   -1,   -1,  336,   -1,  338,   -1,  339,
+   -1,   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,  362,   -1,  363,  364,   -1,   -1,   -1,  369,  369,
+   -1,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,   -1,  256,   -1,  419,  419,
+   -1,  421,  262,   -1,  424,   -1,  265,   -1,  267,   -1,
+  430,  270,   -1,  272,  273,   -1,  275,   -1,  277,   -1,
+  279,   -1,  281,  282,  283,   -1,   -1,   -1,  287,  288,
+   -1,   -1,   -1,   -1,  293,   -1,  295,  296,  298,   -1,
+   -1,  300,   -1,   -1,   -1,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+   -1,   -1,   -1,  322,  323,   -1,   -1,   -1,   -1,   -1,
+   -1,  330,  331,   -1,   -1,  334,   -1,   -1,  337,  339,
+   -1,   -1,   -1,  342,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,   -1,   -1,  363,  364,   -1,   -1,   -1,   -1,  369,
+   -1,  371,  372,  373,  374,  375,  376,  377,   -1,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,  413,  414,   -1,  256,   -1,   -1,  419,
+  419,  421,  262,   -1,  424,   -1,  265,   -1,  267,   -1,
+  430,  270,   -1,   -1,  273,   -1,  275,   -1,  277,   -1,
+  279,   -1,  281,  282,  283,   -1,   -1,   -1,  287,  288,
+   -1,   -1,   -1,   -1,  293,   -1,  295,   -1,  298,   -1,
+   -1,  300,   -1,   -1,   -1,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  256,   -1,   -1,  322,   -1,   -1,  262,   -1,   -1,   -1,
+  266,  330,  331,   -1,   -1,  334,   -1,   -1,  337,  339,
+   -1,   -1,   -1,  342,  344,   -1,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,   -1,  298,  363,   -1,   -1,   -1,   -1,   -1,  369,
+   -1,  371,   -1,  373,   -1,  375,  376,  377,  314,  379,
+  380,   -1,  382,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,   -1,   -1,  395,  396,  397,  398,  399,
+  400,  401,  402,  403,  404,  405,  406,  407,  408,  409,
+  410,  411,  412,   -1,  414,  256,   -1,   -1,   -1,  419,
+  419,  357,   -1,   -1,   -1,   -1,   -1,  363,  364,   -1,
+  430,   -1,   -1,  369,  370,  371,  372,  373,  374,  375,
+  376,  377,   -1,  379,  380,  285,  382,  383,  384,  385,
+  386,  387,  388,  389,  390,  391,   -1,  393,  394,  395,
+  396,  397,  398,  399,  400,  401,  402,  403,  404,  405,
+  406,  407,  408,  409,  410,  411,  412,  413,  414,   -1,
+  256,   -1,   -1,  419,   -1,  421,  262,  327,  424,   -1,
+   -1,   -1,   -1,   -1,  430,   -1,   -1,   -1,  339,   -1,
+   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,  350,
+  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,   -1,
+   -1,   -1,  298,   -1,   -1,   -1,   -1,   -1,  369,   -1,
+  371,   -1,  373,   -1,  375,  376,  377,   -1,  378,  379,
+  380,  381,   -1,  383,  384,  385,  386,  387,  388,  389,
+  390,   -1,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,   -1,   -1,  339,   -1,   -1,   -1,   -1,  344,   -1,
+  346,  347,  348,  349,  350,  351,  352,  353,  354,  355,
+  356,   -1,   -1,   -1,   -1,  256,   -1,  363,  364,  430,
+   -1,  262,   -1,  369,  370,  371,  372,  373,  374,  375,
+  376,  377,   -1,  379,  380,   -1,   -1,  383,  384,  385,
+  386,   -1,   -1,   -1,  390,  391,   -1,  393,  394,  395,
+  396,  397,  398,  399,  400,  401,  402,  298,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  413,  414,   -1,
+   -1,   -1,   -1,  419,  256,  421,   -1,   -1,  424,   -1,
+  262,   -1,   -1,   -1,  430,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  339,   -1,
+   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,  350,
+  351,  352,  353,  354,  355,  356,  298,   -1,   -1,   -1,
+   -1,   -1,  363,  364,   -1,   -1,   -1,   -1,  369,   -1,
+  371,  372,  373,  374,  375,  376,  377,   -1,  379,  380,
+   -1,   -1,  383,  384,  385,  386,   -1,   -1,   -1,  390,
+  391,   -1,  393,  394,  395,  396,  397,  398,  399,  400,
+  401,  402,   -1,  256,   -1,   -1,   -1,   -1,   -1,  262,
+   -1,   -1,  413,  414,   -1,   -1,   -1,   -1,  419,   -1,
+  421,  363,  364,  424,   -1,   -1,   -1,  369,  370,  430,
+  372,  373,  374,  375,   -1,  377,   -1,  379,  380,   -1,
+  382,  383,  384,  385,  386,  298,  388,  389,  390,  391,
+   -1,  393,  394,  395,  396,  397,  398,  399,  400,  401,
+  402,  403,  404,  405,  406,  407,  408,  409,  410,  411,
+  412,  413,  414,   -1,   -1,   -1,   -1,  419,   -1,  421,
+   -1,   -1,  424,   -1,   -1,   -1,  339,   -1,  430,   -1,
+   -1,  344,   -1,  346,  347,  348,  349,  350,  351,  352,
+  353,  354,  355,  356,   -1,   -1,   -1,   -1,  256,   -1,
+  363,   -1,   -1,   -1,  262,   -1,  369,  370,  371,   -1,
+  373,   -1,  375,  376,  377,   -1,  379,  380,   -1,   -1,
+  383,  384,  385,  386,   -1,   -1,   -1,  390,  391,   -1,
+   -1,   -1,  395,  396,  397,  398,  399,  400,  401,  402,
+  298,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  414,   -1,   -1,   -1,   -1,  419,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  430,   -1,   -1,
+  256,   -1,   -1,   -1,   -1,   -1,  262,   -1,   -1,   -1,
+   -1,  339,   -1,   -1,   -1,   -1,  344,   -1,  346,  347,
+  348,  349,  350,  351,  352,  353,  354,  355,  356,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  369,  298,  371,   -1,  373,   -1,  375,  376,  377,
+   -1,  379,  380,   -1,   -1,  383,  384,  385,  386,  387,
+  388,  389,  390,  391,   -1,   -1,   -1,  395,  396,  397,
+  398,  399,  400,  401,  402,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  339,   -1,   -1,  414,   -1,  344,   -1,
+  346,  347,  348,  349,  350,  351,  352,  353,  354,  355,
+  356,   -1,  430,   -1,   -1,  256,   -1,  363,   -1,   -1,
+   -1,  262,   -1,  369,   -1,  371,   -1,  373,   -1,  375,
+  376,  377,   -1,  379,  380,   -1,   -1,  383,  384,  385,
+  386,   -1,   -1,   -1,  390,  391,   -1,   -1,   -1,  395,
+  396,  397,  398,  399,  400,  401,  402,  298,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  414,   -1,
+   -1,   -1,   -1,  419,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  430,   -1,   -1,  256,   -1,   -1,
+   -1,   -1,   -1,  262,   -1,   -1,   -1,   -1,  339,   -1,
+   -1,   -1,   -1,  344,   -1,  346,  347,  348,  349,  350,
+  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,  298,
+  371,   -1,  373,   -1,  375,  376,  377,   -1,  379,  380,
+   -1,   -1,  383,  384,  385,  386,   -1,   -1,   -1,  390,
+  391,   -1,   -1,   -1,  395,  396,  397,  398,  399,  400,
+  401,  402,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  339,   -1,   -1,  414,   -1,  344,   -1,  346,  347,  348,
+  349,  350,  351,  352,  353,  354,  355,  356,   -1,  430,
+   -1,   -1,  256,   -1,   -1,   -1,   -1,   -1,  262,   -1,
+  369,   -1,  371,   -1,  373,   -1,  375,  376,  377,   -1,
+  379,  380,   -1,   -1,  383,  384,  385,  386,   -1,   -1,
+   -1,  390,  391,   -1,   -1,   -1,  395,  396,  397,  398,
+  399,  400,  401,  402,  298,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  414,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  430,   -1,   -1,  256,   -1,   -1,   -1,   -1,   -1,
+  262,   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,   -1,
+  344,   -1,  346,  347,  348,  349,  350,  351,  352,  353,
+  354,  355,  356,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  369,  298,  371,   -1,  373,
+   -1,  375,  376,  377,   -1,  379,  380,   -1,   -1,  383,
+  384,  385,  386,   -1,   -1,   -1,  390,  391,   -1,   -1,
+   -1,  395,  396,  397,  398,  399,  400,  401,  402,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,
+  414,   -1,  344,   -1,  346,  347,  348,  349,  350,  351,
+  352,  353,  354,  355,  356,   -1,  430,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,
+   -1,  373,   -1,  375,  376,  377,   -1,  379,  380,   -1,
+   -1,  383,  384,  385,  386,   -1,   -1,   -1,  390,  391,
+   -1,   -1,   -1,  395,  396,  397,  398,  399,  400,  401,
+  402,   -1,  256,   -1,  256,   -1,   -1,   -1,   -1,   -1,
+  264,  265,  414,  267,   -1,   -1,  270,  271,   -1,   -1,
+   -1,  275,  276,  277,   -1,  279,   -1,   -1,  430,   -1,
+   -1,  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,   -1,
+   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,
+  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,
+   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,
+  334,   -1,   -1,   -1,   -1,   -1,   -1,  339,   -1,  256,
+   -1,   -1,  344,   -1,  346,  347,  348,  349,  350,  351,
+  352,  353,  354,  355,  356,  359,  360,  361,  362,  363,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,  372,  371,
+   -1,  373,   -1,  375,  376,  377,   -1,   -1,   -1,   -1,
+   -1,  383,  384,  385,  386,   -1,   -1,   -1,  390,  391,
+   -1,   -1,   -1,  395,  396,  397,  398,  399,  400,  401,
+  402,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,
+   -1,   -1,  414,   -1,  418,  419,   -1,   -1,   -1,   -1,
+   -1,   -1,  339,   -1,   -1,  429,  430,  344,  430,  346,
+  347,  348,  349,  350,  351,  352,  353,  354,  355,  356,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  369,   -1,  371,   -1,  373,   -1,  375,  376,
+  377,   -1,   -1,   -1,   -1,   -1,  383,  384,  385,  386,
+   -1,   -1,   -1,  390,  391,   -1,   -1,  256,  395,  396,
+  397,  398,  399,  400,  401,  402,   -1,   -1,   -1,   -1,
+   -1,  339,   -1,   -1,   -1,   -1,  344,  414,  346,  347,
+  348,  349,  350,  351,  352,  353,  354,  355,  356,   -1,
+   -1,   -1,   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  369,   -1,  371,   -1,  373,   -1,  375,  376,  377,
+   -1,   -1,   -1,   -1,   -1,  383,  384,  385,  386,   -1,
+   -1,   -1,  390,  391,   -1,   -1,  256,   -1,   -1,  397,
+  398,  399,  400,  401,  402,   -1,   -1,   -1,   -1,   -1,
+  339,   -1,   -1,   -1,   -1,  344,  414,  346,  347,  348,
+  349,  350,  351,  352,  353,  354,  355,  356,   -1,   -1,
+   -1,   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  369,   -1,  371,   -1,  373,   -1,  375,  376,  377,   -1,
+   -1,   -1,   -1,   -1,  383,  384,  385,  386,   -1,   -1,
+   -1,  390,  391,   -1,   -1,  256,   -1,   -1,  397,  398,
+  399,  400,  401,  402,   -1,   -1,   -1,   -1,   -1,  339,
+   -1,   -1,   -1,   -1,  344,  414,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,
+   -1,  371,   -1,  373,   -1,  375,  376,  377,   -1,   -1,
+   -1,   -1,   -1,  383,  384,  385,  386,   -1,   -1,   -1,
+  390,  391,   -1,   -1,  256,   -1,   -1,  397,  398,  399,
+  400,  401,  402,   -1,   -1,   -1,   -1,   -1,  339,   -1,
+   -1,   -1,   -1,  344,  414,  346,  347,  348,  349,  350,
+  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,   -1,
+  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,
+  371,   -1,  373,   -1,  375,  376,  377,   -1,   -1,   -1,
+   -1,   -1,  383,  384,  385,  386,  256,   -1,   -1,  390,
+  391,   -1,  262,   -1,   -1,   -1,  397,  398,  399,  400,
+  401,  402,   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,
+   -1,   -1,  344,  414,  346,  347,  348,  349,  350,  351,
+  352,  353,  354,  355,  356,   -1,   -1,   -1,  298,  430,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,
+   -1,  373,   -1,  375,  376,  377,   -1,   -1,   -1,   -1,
+   -1,  383,  384,  385,  386,   -1,   -1,   -1,  390,  391,
+   -1,   -1,   -1,   -1,   -1,  397,  398,  399,  400,  401,
+  402,   -1,   -1,  256,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  414,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  364,   -1,   -1,   -1,  430,  369,
+   -1,   -1,  372,   -1,  374,  375,   -1,   -1,   -1,  379,
+  380,   -1,   -1,  383,  384,  385,  386,  387,  388,  389,
+  390,  391,   -1,  393,  394,  395,  396,  397,  398,  399,
+  400,  401,  402,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  256,  413,  414,   -1,   -1,   -1,   -1,   -1,
+   -1,  421,   -1,   -1,  424,   -1,  339,   -1,   -1,   -1,
+  430,  344,   -1,  346,  347,  348,  349,  350,  351,  352,
+  353,  354,  355,  356,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,   -1,
+  373,   -1,  375,  376,  377,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  385,  386,   -1,   -1,   -1,  390,  391,   -1,
+   -1,  256,   -1,   -1,   -1,   -1,  399,  400,  401,  402,
+   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,   -1,
+  344,  414,  346,  347,  348,  349,  350,  351,  352,  353,
+  354,  355,  356,   -1,   -1,   -1,   -1,  430,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,   -1,  373,
+   -1,  375,  376,  377,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  385,  386,   -1,   -1,   -1,  390,  391,   -1,   -1,
+  256,   -1,   -1,   -1,   -1,  399,  400,  401,  402,   -1,
+   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,   -1,  344,
+  414,  346,  347,  348,  349,  350,  351,  352,  353,  354,
+  355,  356,   -1,   -1,   -1,   -1,  430,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  369,   -1,  371,   -1,  373,   -1,
+  375,  376,  377,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  385,  386,   -1,   -1,   -1,  390,  391,   -1,   -1,  256,
+   -1,   -1,   -1,   -1,  399,  400,  401,  402,   -1,   -1,
+   -1,   -1,   -1,  339,   -1,   -1,   -1,   -1,  344,  414,
+  346,  347,  348,  349,  350,  351,  352,  353,  354,  355,
+  356,   -1,   -1,   -1,   -1,  430,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  369,   -1,  371,   -1,  373,   -1,  375,
+  376,  377,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  385,
+  386,   -1,   -1,   -1,  390,  391,   -1,   -1,  256,   -1,
+   -1,   -1,   -1,   -1,   -1,  401,  402,   -1,   -1,   -1,
+   -1,   -1,  339,   -1,   -1,   -1,   -1,  344,  414,  346,
+  347,  348,  349,  350,  351,  352,  353,  354,  355,  356,
+   -1,   -1,   -1,   -1,  430,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  369,   -1,  371,   -1,  373,   -1,  375,  376,
+  377,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  385,  386,
+   -1,   -1,   -1,  390,  391,   -1,   -1,  256,   -1,   -1,
+   -1,   -1,   -1,   -1,  401,  402,   -1,   -1,   -1,   -1,
+   -1,  339,   -1,   -1,   -1,   -1,  344,  414,  346,  347,
+  348,  349,  350,  351,  352,  353,  354,  355,  356,   -1,
+   -1,   -1,   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  369,   -1,  371,   -1,  373,   -1,  375,  376,  377,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  386,   -1,
+   -1,   -1,  390,  391,   -1,   -1,  256,   -1,   -1,   -1,
+   -1,   -1,   -1,  401,  402,   -1,   -1,   -1,   -1,   -1,
+  339,   -1,   -1,   -1,   -1,  344,  414,  346,  347,  348,
+  349,  350,  351,  352,  353,  354,  355,  356,   -1,   -1,
+   -1,   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  369,   -1,  371,   -1,  373,   -1,  375,  376,  377,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  386,   -1,   -1,
+   -1,  390,  391,   -1,   -1,  256,   -1,   -1,   -1,   -1,
+   -1,   -1,  401,  402,   -1,   -1,   -1,   -1,   -1,  339,
+   -1,   -1,   -1,   -1,  344,  414,  346,  347,  348,  349,
+  350,  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,
+   -1,  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,
+   -1,  371,   -1,  373,   -1,  375,  376,  377,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  386,   -1,   -1,   -1,
+   -1,  391,   -1,   -1,  256,   -1,   -1,   -1,   -1,   -1,
+   -1,  401,  402,   -1,   -1,   -1,   -1,   -1,  339,   -1,
+   -1,   -1,   -1,  344,  414,  346,  347,  348,  349,  350,
+  351,  352,  353,  354,  355,  356,   -1,   -1,   -1,   -1,
+  430,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,
+  371,   -1,  373,   -1,  375,  376,  377,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  386,   -1,   -1,   -1,   -1,
+  391,   -1,   -1,  256,   -1,   -1,   -1,   -1,   -1,   -1,
+  401,  402,   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,
+   -1,   -1,  344,  414,  346,  347,  348,  349,  350,  351,
+  352,  353,  354,  355,  356,   -1,   -1,   -1,   -1,  430,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,
+   -1,  373,   -1,  375,  376,  377,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  391,
+   -1,   -1,  256,   -1,   -1,   -1,   -1,   -1,   -1,  401,
+  402,   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,
+   -1,  344,  414,  346,  347,  348,  349,  350,  351,  352,
+  353,  354,  355,  356,   -1,   -1,   -1,   -1,  430,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,   -1,
+  373,   -1,  375,  376,  377,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  391,   -1,
+   -1,  256,   -1,   -1,   -1,   -1,   -1,   -1,  401,  402,
+   -1,   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,   -1,
+  344,  414,  346,  347,  348,  349,  350,  351,  352,  353,
+  354,  355,  356,   -1,   -1,   -1,   -1,  430,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  369,   -1,  371,   -1,  373,
+   -1,  375,  376,  377,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  391,   -1,   -1,
+   -1,  262,   -1,   -1,   -1,  266,   -1,   -1,  402,   -1,
+   -1,   -1,   -1,   -1,  339,   -1,   -1,   -1,   -1,  344,
+  414,  346,  347,  348,  349,  350,  351,  352,  353,  354,
+  355,  356,   -1,   -1,   -1,   -1,  430,  298,   -1,   -1,
+   -1,   -1,   -1,   -1,  369,   -1,  371,   -1,  373,   -1,
+  375,  376,  377,  314,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  391,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  402,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  414,
+   -1,   -1,   -1,   -1,   -1,   -1,  357,   -1,   -1,   -1,
+   -1,   -1,  363,  364,   -1,  430,   -1,   -1,  369,  370,
+   -1,  372,   -1,  374,   -1,  376,  377,   -1,  379,  380,
+   -1,  382,  383,  384,  385,  386,  387,  388,  389,  390,
+  391,   -1,  393,  394,  395,  396,  397,  398,  399,  400,
+  401,  402,  403,  404,  405,  406,  407,  408,  409,  410,
+  411,  412,  413,  414,   -1,   -1,  256,   -1,  419,   -1,
+  421,   -1,   -1,  424,  264,  265,  266,  267,  268,  430,
+  270,  271,   -1,  273,  274,  275,  276,  277,  278,  279,
+   -1,   -1,   -1,   -1,   -1,  285,   -1,  287,  288,  289,
+  290,  291,  292,   -1,   -1,  295,   -1,   -1,   -1,  299,
+  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  314,   -1,  316,   -1,  318,  319,
+   -1,   -1,  322,   -1,  324,  325,  326,  327,  328,  329,
+  330,  331,  332,  333,  334,  335,   -1,  337,   -1,   -1,
+  340,  341,   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,
+  360,  361,  362,  363,   -1,   -1,   -1,   -1,  368,   -1,
+   -1,   -1,  372,   -1,   -1,   -1,   -1,  377,  378,  379,
+  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,
+   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,  418,  419,
+  420,  421,   -1,  423,  264,  265,  266,  267,   -1,   -1,
+  270,  271,   -1,  273,  274,  275,  276,  277,  278,  279,
+   -1,   -1,   -1,   -1,   -1,  285,   -1,  287,  288,  289,
+  290,  291,  292,   -1,   -1,  295,   -1,   -1,   -1,  299,
+  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  314,   -1,  316,   -1,  318,  319,
+   -1,   -1,  322,   -1,  324,  325,  326,  327,  328,  329,
+  330,  331,  332,  333,  334,  335,   -1,  337,   -1,   -1,
+  340,  341,   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,
+  360,  361,  362,  363,   -1,   -1,   -1,   -1,  368,   -1,
+   -1,   -1,  372,   -1,   -1,   -1,   -1,  377,  378,  379,
+  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,
+   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  256,   -1,   -1,   -1,  418,  419,
+  420,  421,  264,  265,  266,  267,   -1,   -1,  270,  271,
+   -1,  273,  274,  275,  276,  277,  278,  279,   -1,   -1,
+   -1,   -1,   -1,  285,   -1,  287,  288,  289,  290,  291,
+  292,   -1,   -1,  295,   -1,   -1,   -1,  299,  300,   -1,
+  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  314,   -1,  316,   -1,  318,  319,   -1,   -1,
+  322,   -1,  324,  325,  326,  327,  328,  329,  330,  331,
+  332,  333,  334,  335,   -1,  337,   -1,   -1,  340,  341,
+   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,
+  362,  363,   -1,   -1,   -1,   -1,  368,   -1,   -1,   -1,
+  372,   -1,   -1,   -1,   -1,  377,  378,  379,  380,  381,
+   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,
+   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  256,   -1,   -1,   -1,  418,  419,  420,  421,
+  264,  265,  266,  267,   -1,   -1,  270,  271,   -1,  273,
+  274,  275,  276,  277,  278,  279,   -1,   -1,   -1,   -1,
+   -1,  285,   -1,  287,  288,  289,  290,  291,  292,   -1,
+   -1,  295,   -1,   -1,   -1,  299,  300,   -1,  302,  303,
+  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  314,   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,
+  324,  325,  326,  327,  328,  329,  330,  331,  332,  333,
+  334,  335,   -1,  337,   -1,   -1,  340,  341,   -1,   -1,
+  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,
+   -1,   -1,   -1,   -1,  368,   -1,   -1,   -1,  372,   -1,
+   -1,   -1,   -1,  377,  378,  379,  380,  381,   -1,   -1,
+   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,
+  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  256,   -1,   -1,   -1,  418,  419,  420,  421,  264,  265,
+  266,  267,   -1,   -1,  270,  271,   -1,  273,  274,  275,
+  276,  277,  278,  279,   -1,   -1,   -1,   -1,   -1,  285,
+   -1,  287,  288,  289,  290,  291,  292,   -1,   -1,  295,
+   -1,   -1,   -1,  299,  300,   -1,  302,  303,  304,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  314,   -1,
+  316,   -1,  318,  319,   -1,   -1,  322,   -1,  324,  325,
+  326,  327,  328,  329,  330,  331,  332,  333,  334,  335,
+   -1,  337,   -1,   -1,  340,  341,   -1,   -1,  344,  345,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,
+   -1,   -1,  368,   -1,   -1,   -1,  372,   -1,   -1,   -1,
+   -1,  377,  378,  379,  380,  381,   -1,   -1,   -1,  385,
+   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,
+   -1,   -1,  418,  419,  420,  421,  264,  265,   -1,  267,
+   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,
+   -1,  279,   -1,   -1,  265,   -1,  267,  285,   -1,  270,
+  288,   -1,   -1,   -1,  275,   -1,   -1,  295,  279,   -1,
+   -1,   -1,  300,   -1,  302,  303,  304,  288,  306,   -1,
+   -1,   -1,   -1,   -1,  295,  313,   -1,   -1,  316,  300,
+  318,  319,   -1,  304,  322,   -1,   -1,  325,   -1,  327,
+   -1,  329,  330,  331,  332,  316,  334,  318,   -1,   -1,
+   -1,  322,   -1,  341,   -1,   -1,  344,  345,   -1,  330,
+  331,   -1,   -1,  334,   -1,   -1,  337,   -1,   -1,   -1,
+   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  372,   -1,   -1,  375,   -1,   -1,
+  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,
+   -1,   -1,  373,   -1,   -1,  393,  394,   -1,   -1,   -1,
+   -1,   -1,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+  418,  419,  420,  421,  285,   -1,   -1,  288,   -1,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,  419,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+  341,   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,  368,  369,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,
+   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,
+  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,
+   -1,  275,  276,  277,   -1,  279,   -1,  418,  419,  420,
+  421,  285,   -1,  424,  288,   -1,   -1,   -1,  429,   -1,
+   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,
+  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,
+   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,
+  334,   -1,   -1,   -1,   -1,   -1,   -1,  341,   -1,   -1,
+  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,
+   -1,   -1,   -1,   -1,  368,   -1,   -1,   -1,  372,   -1,
+   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,
+   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,
+  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  256,  418,  419,  420,  421,   -1,   -1,
+  424,  264,  265,   -1,  267,  429,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,  265,
+   -1,  267,  285,   -1,  270,  288,   -1,   -1,   -1,  275,
+   -1,   -1,  295,  279,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,  288,   -1,   -1,   -1,   -1,   -1,   -1,  295,
+   -1,   -1,   -1,  316,  300,  318,  319,   -1,  304,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+  316,  334,  318,   -1,   -1,   -1,  322,   -1,  341,   -1,
+   -1,  344,  345,   -1,  330,  331,   -1,   -1,  334,   -1,
+   -1,  337,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,  368,  369,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  371,   -1,   -1,   -1,   -1,
+  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  256,   -1,   -1,   -1,  418,  419,  420,  421,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,  419,  279,   -1,   -1,  265,   -1,  267,
+  285,   -1,  270,  288,   -1,   -1,   -1,  275,   -1,   -1,
+  295,  279,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+  288,  306,   -1,   -1,   -1,   -1,   -1,  295,  313,   -1,
+   -1,  316,  300,  318,  319,   -1,  304,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,  316,  334,
+  318,   -1,   -1,   -1,  322,   -1,  341,   -1,   -1,  344,
+  345,   -1,  330,  331,   -1,   -1,  334,   -1,   -1,  337,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,  394,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,
+   -1,   -1,   -1,  418,  419,  420,  421,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,  419,  279,   -1,   -1,  265,   -1,  267,  285,   -1,
+  270,  288,   -1,   -1,   -1,  275,   -1,   -1,  295,  279,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,  288,   -1,
+   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,  316,
+  300,  318,  319,  320,  304,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,  316,  334,  318,   -1,
+   -1,   -1,  322,   -1,  341,   -1,   -1,  344,  345,   -1,
+  330,  331,   -1,   -1,  334,   -1,   -1,  337,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,  368,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,   -1,
+   -1,  418,  419,  420,  421,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,  419,
+  279,   -1,   -1,   -1,   -1,   -1,  285,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,  341,   -1,   -1,  344,  345,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,  368,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,
+   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,  418,
+  419,  420,  421,  262,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,  298,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  343,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,  374,   -1,   -1,   -1,  378,
+  379,  380,  381,  382,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,  341,   -1,   -1,  344,  345,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,  369,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,   -1,
+   -1,  418,  419,  420,  421,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,  265,   -1,  267,  285,   -1,  270,  288,
+   -1,   -1,   -1,  275,   -1,   -1,  295,  279,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,  288,   -1,   -1,   -1,
+   -1,   -1,   -1,  295,   -1,   -1,   -1,  316,  300,  318,
+  319,   -1,  304,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,  316,  334,  318,   -1,   -1,   -1,
+  322,   -1,  341,   -1,   -1,  344,  345,   -1,  330,  331,
+   -1,   -1,  334,   -1,   -1,  337,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+  369,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,
+   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  256,   -1,   -1,   -1,  418,
+  419,  420,  421,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,  419,  279,   -1,
+   -1,  265,   -1,  267,  285,   -1,  270,  288,   -1,   -1,
+   -1,  275,   -1,   -1,  295,  279,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,  288,   -1,   -1,   -1,   -1,   -1,
+   -1,  295,   -1,   -1,   -1,  316,  300,  318,  319,   -1,
+  304,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,  316,  334,  318,   -1,   -1,   -1,  322,   -1,
+  341,   -1,   -1,  344,  345,   -1,  330,  331,   -1,   -1,
+  334,   -1,   -1,  337,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,
+   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  256,   -1,   -1,   -1,  418,  419,  420,
+  421,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,  419,  279,   -1,   -1,   -1,
+   -1,   -1,  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,  341,   -1,
+   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,
+  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  256,   -1,  418,  419,  420,  421,  262,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,  298,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  343,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,  374,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  256,   -1,   -1,   -1,   -1,
+  393,  394,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+   -1,   -1,   -1,   -1,  285,  418,  419,  288,  421,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+  341,   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,
+   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  256,   -1,   -1,   -1,  418,  419,  420,
+  421,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,  265,
+   -1,  267,  285,   -1,  270,  288,   -1,   -1,   -1,  275,
+   -1,   -1,  295,  279,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,  288,   -1,   -1,   -1,   -1,   -1,   -1,  295,
+   -1,   -1,   -1,  316,  300,  318,  319,   -1,  304,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+  316,  334,  318,   -1,   -1,   -1,  322,   -1,  341,   -1,
+   -1,  344,  345,   -1,  330,  331,   -1,   -1,  334,   -1,
+   -1,  337,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,
+  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  256,   -1,   -1,   -1,  418,  419,  420,  421,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,  419,  279,   -1,   -1,  265,   -1,  267,
+  285,   -1,  270,  288,   -1,   -1,   -1,  275,   -1,   -1,
+  295,  279,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+  288,   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,
+   -1,  316,  300,  318,  319,   -1,  304,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,  316,  334,
+  318,   -1,   -1,   -1,  322,   -1,  341,   -1,   -1,  344,
+  345,   -1,  330,  331,   -1,   -1,  334,   -1,   -1,  337,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,  394,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,
+   -1,   -1,   -1,  418,  419,  420,  421,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,  419,  279,   -1,   -1,  265,   -1,  267,  285,   -1,
+  270,  288,   -1,   -1,   -1,  275,   -1,   -1,  295,  279,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,  288,   -1,
+   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,  316,
+  300,  318,  319,   -1,  304,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,  316,  334,  318,   -1,
+   -1,   -1,  322,   -1,  341,   -1,   -1,  344,  345,   -1,
+  330,  331,   -1,   -1,  334,   -1,   -1,  337,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,   -1,
+   -1,  418,  419,  420,  421,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,  419,
+  279,   -1,   -1,   -1,   -1,   -1,  285,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,  341,   -1,   -1,  344,  345,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,
+   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  256,   -1,  418,
+  419,  420,  421,  262,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,  298,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,  374,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,  374,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,  256,   -1,   -1,   -1,   -1,  393,  394,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,
+  285,  418,  419,  288,  421,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,  256,   -1,   -1,   -1,   -1,  393,  394,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,  418,  419,  288,  421,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  256,   -1,   -1,   -1,   -1,
+  393,  394,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+   -1,   -1,   -1,   -1,  285,  418,  419,  288,  421,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,  256,   -1,   -1,
+   -1,   -1,  393,  394,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,  418,  419,  288,
+  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,  256,   -1,   -1,   -1,   -1,  393,  394,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,
+  285,  418,  419,  288,  421,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,  256,   -1,   -1,   -1,   -1,  393,  394,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,  418,  419,  288,  421,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  256,   -1,   -1,   -1,   -1,
+  393,  394,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+   -1,   -1,   -1,   -1,  285,  418,  419,  288,  421,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,  256,   -1,   -1,
+   -1,   -1,  393,  394,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,  418,  419,  288,
+  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,  256,   -1,   -1,   -1,   -1,  393,  394,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,
+  285,  418,  419,  288,  421,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,  256,   -1,   -1,   -1,   -1,  393,  394,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,  418,  419,  288,  421,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  256,   -1,   -1,   -1,   -1,
+  393,  394,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+   -1,   -1,   -1,   -1,  285,  418,  419,  288,  421,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,  256,   -1,   -1,
+   -1,   -1,  393,  394,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,  418,  419,  288,
+  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,  256,   -1,   -1,   -1,   -1,  393,  394,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,
+  285,  418,  419,  288,  421,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,  256,   -1,   -1,   -1,   -1,  393,  394,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,  418,  419,  288,  421,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  256,   -1,   -1,   -1,   -1,
+  393,  394,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+   -1,   -1,   -1,   -1,  285,  418,  419,  288,  421,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,  256,   -1,   -1,
+   -1,   -1,  393,  394,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,  418,  419,  288,
+  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,  256,   -1,   -1,   -1,   -1,  393,  394,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,
+  285,  418,  419,  288,  421,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,  256,   -1,   -1,   -1,   -1,  393,  394,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,  418,  419,  288,  421,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,  256,   -1,   -1,   -1,   -1,
+  393,  394,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+   -1,   -1,   -1,   -1,  285,  418,  419,  288,  421,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,  256,   -1,   -1,
+   -1,   -1,  393,  394,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,   -1,   -1,   -1,   -1,  285,  418,  419,  288,
+  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,  256,
+   -1,   -1,   -1,   -1,  393,  394,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,  285,  418,
+  419,  288,  421,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,  256,   -1,   -1,   -1,   -1,  393,  394,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,   -1,
+  285,  418,  419,  288,  421,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,  256,   -1,   -1,   -1,   -1,  393,  394,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,  418,  419,  288,  421,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,
+  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  256,   -1,   -1,   -1,   -1,  261,   -1,
+   -1,   -1,  265,   -1,  267,  418,  419,  270,  421,  272,
+  273,   -1,  275,   -1,  277,   -1,  279,   -1,  281,  282,
+  283,  284,   -1,   -1,  287,  288,   -1,   -1,   -1,   -1,
+  293,   -1,  295,  296,  297,   -1,   -1,  300,   -1,  302,
+   -1,  304,   -1,   -1,  307,   -1,  309,  310,  311,  312,
+   -1,   -1,   -1,  316,  317,  318,   -1,   -1,  321,  322,
+  323,   -1,   -1,   -1,   -1,   -1,   -1,  330,  331,   -1,
+  333,  334,  256,  336,  337,  338,   -1,   -1,   -1,  342,
+  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,
+   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,  362,
+   -1,  285,   -1,   -1,  288,  368,  369,  370,   -1,   -1,
+   -1,  295,   -1,   -1,   -1,  378,  300,   -1,  302,  303,
+  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,
+   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,
+  334,   -1,   -1,  337,   -1,   -1,  419,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,
+   -1,   -1,   -1,  256,   -1,   -1,   -1,   -1,  372,   -1,
+  262,  264,  265,   -1,  267,  379,  380,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,   -1,
+   -1,   -1,  285,   -1,   -1,  288,   -1,   -1,   -1,  261,
+   -1,  263,  295,   -1,   -1,   -1,  298,  300,   -1,  302,
+  303,  304,   -1,   -1,  418,  419,   -1,   -1,   -1,   -1,
+   -1,   -1,  284,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,  297,  329,  330,  331,  332,
+  302,  334,   -1,   -1,   -1,  307,   -1,  309,  310,  311,
+  312,   -1,   -1,  315,   -1,  317,   -1,   -1,   -1,  321,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,  333,  364,   -1,  336,   -1,  338,   -1,   -1,  372,
+  372,  373,  374,  375,  376,   -1,   -1,  379,  380,   -1,
+   -1,  383,  384,  385,  386,  387,  388,  389,  390,  391,
+  362,  393,  394,  395,  396,  397,  398,  399,  400,  401,
+  402,  403,  404,  405,  406,  407,  408,  409,  410,  411,
+  412,  413,  414,   -1,   -1,  418,  419,   -1,   -1,  421,
+   -1,  261,  424,  263,   -1,  265,   -1,  267,   -1,   -1,
+  270,   -1,  272,  273,   -1,  275,   -1,  277,   -1,  279,
+   -1,  281,  282,  283,  284,   -1,   -1,  287,  288,   -1,
+   -1,   -1,   -1,  293,  294,  295,  296,  297,   -1,   -1,
+  300,   -1,  302,   -1,  304,   -1,  306,  307,   -1,  309,
+  310,  311,  312,   -1,   -1,  315,  316,  317,  318,   -1,
+   -1,  321,  322,  323,   -1,   -1,   -1,   -1,   -1,   -1,
+  330,  331,   -1,  333,  334,   -1,  336,  337,  338,   -1,
+   -1,   -1,  342,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  362,   -1,   -1,  365,  366,  261,   -1,   -1,
+   -1,  265,   -1,  267,   -1,   -1,  270,   -1,  272,  273,
+   -1,  275,   -1,  277,   -1,  279,   -1,  281,  282,  283,
+  284,   -1,   -1,  287,  288,   -1,   -1,   -1,   -1,  293,
+   -1,  295,  296,  297,   -1,   -1,  300,   -1,  302,   -1,
+  304,   -1,   -1,  307,   -1,  309,  310,  311,  312,  419,
+   -1,   -1,  316,  317,  318,   -1,   -1,  321,  322,  323,
+   -1,   -1,   -1,   -1,   -1,   -1,  330,  331,   -1,  333,
+  334,   -1,  336,  337,  338,   -1,   -1,   -1,  342,   -1,
+   -1,  261,   -1,   -1,   -1,  265,   -1,  267,   -1,   -1,
+  270,   -1,  272,  273,   -1,  275,   -1,  277,  362,  279,
+   -1,  281,  282,  283,  284,  369,   -1,  287,  288,   -1,
+   -1,   -1,   -1,  293,  378,  295,  296,  297,   -1,   -1,
+  300,   -1,  302,   -1,  304,   -1,   -1,  307,   -1,  309,
+  310,  311,  312,   -1,   -1,   -1,  316,  317,  318,   -1,
+   -1,  321,  322,  323,   -1,   -1,   -1,   -1,   -1,   -1,
+  330,  331,   -1,  333,  334,  419,  336,  337,  338,   -1,
+   -1,   -1,  342,   -1,   -1,  261,   -1,   -1,   -1,  265,
+   -1,  267,   -1,   -1,  270,   -1,  272,  273,   -1,  275,
+   -1,  277,  362,  279,   -1,  281,  282,  283,  284,  369,
+   -1,  287,  288,   -1,   -1,   -1,   -1,  293,  378,  295,
+  296,  297,   -1,   -1,  300,   -1,  302,   -1,  304,   -1,
+   -1,  307,   -1,  309,  310,  311,  312,   -1,   -1,   -1,
+  316,  317,  318,   -1,   -1,  321,  322,  323,   -1,   -1,
+   -1,   -1,   -1,   -1,  330,  331,   -1,  333,  334,  419,
+  336,  337,  338,   -1,   -1,   -1,  342,   -1,   -1,  261,
+   -1,   -1,   -1,  265,   -1,  267,   -1,   -1,  270,   -1,
+  272,  273,   -1,  275,   -1,  277,  362,  279,   -1,  281,
+  282,  283,  284,   -1,   -1,  287,  288,   -1,   -1,   -1,
+   -1,  293,  378,  295,  296,  297,   -1,   -1,  300,   -1,
+  302,   -1,  304,   -1,   -1,  307,   -1,  309,  310,  311,
+  312,   -1,   -1,   -1,  316,  317,  318,   -1,   -1,  321,
+  322,  323,   -1,   -1,   -1,   -1,   -1,   -1,  330,  331,
+   -1,  333,  334,  419,  336,  337,  338,   -1,   -1,   -1,
+  342,   -1,   -1,  261,   -1,   -1,   -1,  265,   -1,  267,
+   -1,   -1,  270,   -1,  272,  273,   -1,  275,   -1,  277,
+  362,  279,   -1,  281,  282,  283,  284,  369,   -1,  287,
+  288,   -1,   -1,   -1,   -1,  293,   -1,  295,  296,  297,
+   -1,   -1,  300,   -1,  302,  261,  304,   -1,   -1,  307,
+   -1,  309,  310,  311,  312,   -1,   -1,   -1,  316,  317,
+  318,   -1,   -1,  321,  322,  323,   -1,   -1,  284,   -1,
+   -1,   -1,  330,  331,   -1,  333,  334,  419,  336,  337,
+  338,  297,   -1,   -1,  342,   -1,  302,   -1,   -1,  305,
+   -1,  307,   -1,  309,  310,  311,  312,   -1,   -1,   -1,
+   -1,  317,   -1,   -1,  362,  321,   -1,   -1,   -1,  325,
+   -1,  369,   -1,   -1,   -1,   -1,   -1,  333,   -1,   -1,
+  336,   -1,  338,   -1,  264,  265,   -1,  267,   -1,   -1,
+  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,
+   -1,  357,   -1,   -1,   -1,  285,  362,   -1,  288,   -1,
+   -1,   -1,   -1,  369,  370,  295,  372,   -1,  374,   -1,
+  300,  419,  302,  303,  304,   -1,  306,   -1,   -1,   -1,
+   -1,  387,   -1,  313,   -1,   -1,  316,   -1,  318,  319,
+   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,
+  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,
+   -1,  341,   -1,  419,  344,  345,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,
+  360,  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  372,  373,   -1,  375,   -1,   -1,  378,  379,
+  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,
+   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,
+   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,
+   -1,   -1,  275,  276,  277,   -1,  279,   -1,  418,  419,
+  420,  421,  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,
+   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,
+  303,  304,   -1,  306,   -1,   -1,   -1,   -1,   -1,   -1,
+  313,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,
+   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,
+   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,  341,   -1,
+   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,
+  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,
+   -1,   -1,  375,   -1,   -1,  378,  379,  380,  381,   -1,
+   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,
+  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,  264,  265,
+   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,
+  276,  277,   -1,  279,   -1,  418,  419,  420,  421,  285,
+   -1,   -1,  288,   -1,   -1,   -1,   -1,   -1,   -1,  295,
+   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,
+   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,
+   -1,  337,   -1,   -1,   -1,  341,   -1,   -1,  344,  345,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,
+   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,
+   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,
+   -1,   -1,   -1,   -1,   -1,  264,  265,   -1,  267,   -1,
+   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,   -1,
+  279,   -1,  418,  419,  420,  421,  285,   -1,   -1,  288,
+   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,
+   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,
+  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,   -1,
+  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,   -1,
+   -1,   -1,  341,   -1,   -1,  344,  345,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,  368,
+   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,
+  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,   -1,
+   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,
+   -1,   -1,  264,  265,   -1,  267,   -1,   -1,  270,  271,
+   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,  418,
+  419,  420,  421,  285,   -1,   -1,  288,   -1,   -1,   -1,
+   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,
+  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,
+  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,
+  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,  341,
+   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,
+  362,  363,   -1,   -1,   -1,   -1,  368,   -1,   -1,   -1,
+  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,
+   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,
+   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,  264,
+  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,   -1,
+  275,  276,  277,   -1,  279,   -1,  418,  419,  420,  421,
+  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,   -1,   -1,
+  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,  304,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,   -1,
+  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,  334,
+   -1,   -1,   -1,   -1,   -1,   -1,  341,   -1,   -1,  344,
+  345,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,
+   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,   -1,
+  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,  394,
+   -1,   -1,   -1,   -1,   -1,   -1,  264,  265,   -1,  267,
+   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,  277,
+   -1,  279,   -1,  418,  419,  420,  421,  285,   -1,   -1,
+  288,   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,   -1,
+   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,   -1,
+  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,  327,
+   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,   -1,
+   -1,   -1,   -1,  341,   -1,   -1,  344,  345,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,   -1,
+  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,  387,
+   -1,   -1,   -1,   -1,   -1,  393,  394,   -1,   -1,   -1,
+   -1,   -1,   -1,  264,  265,   -1,  267,   -1,   -1,  270,
+  271,   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,
+  418,  419,  420,  421,  285,   -1,   -1,  288,   -1,   -1,
+   -1,   -1,   -1,   -1,  295,   -1,   -1,   -1,   -1,  300,
+   -1,  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,
+   -1,  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,
+  331,  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,
+  341,   -1,   -1,  344,  345,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,
+  361,  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,
+  381,   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,
+   -1,   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,
+  264,  265,   -1,  267,   -1,   -1,  270,  271,   -1,   -1,
+   -1,  275,  276,  277,   -1,  279,   -1,  418,  419,  420,
+  421,  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,   -1,
+   -1,  295,   -1,   -1,   -1,   -1,  300,   -1,  302,  303,
+  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,
+   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,
+  334,   -1,   -1,   -1,   -1,   -1,   -1,  341,   -1,   -1,
+  344,  345,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  372,   -1,
+   -1,   -1,   -1,   -1,  378,  379,  380,  381,   -1,   -1,
+   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,   -1,  393,
+  394,   -1,   -1,   -1,   -1,   -1,   -1,  264,  265,   -1,
+  267,   -1,   -1,  270,  271,   -1,   -1,   -1,  275,  276,
+  277,   -1,  279,   -1,  418,  419,  420,  421,  285,   -1,
+   -1,  288,   -1,   -1,   -1,   -1,   -1,   -1,  295,   -1,
+   -1,   -1,   -1,  300,   -1,  302,  303,  304,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  316,
+   -1,  318,  319,   -1,   -1,  322,   -1,   -1,  325,   -1,
+  327,   -1,  329,  330,  331,  332,   -1,  334,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  359,  360,  361,  362,  363,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  372,   -1,   -1,   -1,   -1,
+   -1,  378,  379,  380,  381,   -1,   -1,   -1,  385,   -1,
+  387,   -1,  264,  265,   -1,  267,  393,  394,  270,  271,
+   -1,   -1,   -1,  275,  276,  277,   -1,  279,   -1,   -1,
+   -1,   -1,   -1,  285,   -1,   -1,  288,   -1,   -1,   -1,
+   -1,  418,  419,  295,  421,   -1,   -1,   -1,  300,   -1,
+  302,  303,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  316,   -1,  318,  319,   -1,   -1,
+  322,   -1,   -1,  325,   -1,  327,   -1,  329,  330,  331,
+  332,   -1,  334,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  359,  360,  361,
+  362,  363,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+  372,   -1,   -1,   -1,   -1,   -1,  378,  379,  380,  381,
+   -1,   -1,   -1,  385,   -1,  387,   -1,   -1,   -1,   -1,
+   -1,  393,  394,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  263,   -1,  265,   -1,  267,  418,  419,  270,  421,
+  272,  273,   -1,  275,   -1,  277,   -1,  279,   -1,  281,
+  282,  283,   -1,   -1,   -1,  287,  288,   -1,   -1,   -1,
+   -1,  293,   -1,  295,  296,   -1,   -1,   -1,  300,   -1,
+   -1,   -1,  304,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,  315,  316,   -1,  318,   -1,   -1,   -1,
+  322,  323,   -1,   -1,   -1,   -1,   -1,   -1,  330,  331,
+  264,  265,  334,  267,   -1,  337,  270,  271,   -1,   -1,
+  342,  275,  276,  277,   -1,  279,   -1,   -1,   -1,   -1,
+   -1,  285,   -1,   -1,  288,   -1,   -1,   -1,   -1,   -1,
+   -1,  295,   -1,  365,  366,   -1,  300,   -1,  302,  303,
+  304,   -1,   -1,   -1,   -1,   -1,  378,   -1,   -1,   -1,
+   -1,   -1,  316,   -1,  318,  319,   -1,   -1,  322,   -1,
+   -1,  325,   -1,  327,   -1,  329,  330,  331,  332,   -1,
+  334,   -1,   -1,  337,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,  419,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  359,  360,  361,  362,  363,
+   -1,   -1,   -1,   -1,   -1,  265,   -1,  267,  372,   -1,
+  270,   -1,  272,  273,   -1,  275,   -1,  277,   -1,  279,
+   -1,  281,  282,  283,   -1,   -1,   -1,  287,  288,   -1,
+   -1,   -1,   -1,  293,   -1,  295,  296,   -1,   -1,   -1,
+  300,   -1,   -1,   -1,  304,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,  418,  419,  316,   -1,  318,   -1,
+   -1,   -1,  322,  323,   -1,   -1,   -1,   -1,   -1,   -1,
+  330,  331,   -1,  265,  334,  267,   -1,  337,  270,   -1,
+   -1,  273,  342,  275,   -1,  277,   -1,  279,   -1,  281,
+  282,  283,   -1,   -1,   -1,  287,  288,   -1,   -1,   -1,
+   -1,  293,   -1,  295,   -1,  265,   -1,  267,  300,   -1,
+  270,   -1,  304,   -1,   -1,  275,   -1,   -1,  378,  279,
+   -1,   -1,   -1,   -1,  316,   -1,  318,   -1,  288,   -1,
+  322,   -1,   -1,   -1,   -1,  295,   -1,   -1,  330,  331,
+  300,   -1,  334,   -1,  304,  337,  306,   -1,  308,   -1,
+  342,   -1,   -1,  313,   -1,   -1,  316,   -1,  318,  419,
+   -1,   -1,  322,   -1,   -1,  325,   -1,   -1,   -1,   -1,
+  330,  331,   -1,  265,  334,  267,   -1,  337,  270,   -1,
+   -1,   -1,   -1,  275,   -1,   -1,  378,  279,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,  288,   -1,   -1,   -1,
+   -1,   -1,   -1,  295,   -1,  265,   -1,  267,  300,   -1,
+  270,   -1,  304,  373,  306,  275,  308,   -1,   -1,  279,
+   -1,  313,   -1,   -1,  316,   -1,  318,  419,  288,   -1,
+  322,   -1,   -1,  325,   -1,  295,   -1,   -1,  330,  331,
+  300,   -1,  334,   -1,  304,  337,  306,   -1,   -1,   -1,
+   -1,   -1,   -1,  313,   -1,   -1,  316,   -1,  318,  419,
+   -1,   -1,  322,   -1,   -1,  325,   -1,   -1,   -1,   -1,
+  330,  331,   -1,   -1,  334,   -1,   -1,  337,  265,  371,
+  267,   -1,   -1,  270,   -1,   -1,   -1,   -1,  275,   -1,
+   -1,   -1,  279,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,  288,   -1,  363,   -1,   -1,   -1,   -1,  295,   -1,
+  265,   -1,  267,  300,   -1,  270,   -1,  304,   -1,  306,
+  275,  308,   -1,   -1,  279,   -1,  313,  419,   -1,  316,
+   -1,  318,   -1,  288,   -1,  322,   -1,   -1,  325,   -1,
+  295,   -1,   -1,  330,  331,  300,   -1,  334,   -1,  304,
+  337,  306,   -1,  308,   -1,  265,   -1,  267,  313,  419,
+  270,  316,   -1,  318,   -1,  275,   -1,  322,   -1,  279,
+  325,   -1,   -1,  283,   -1,  330,  331,   -1,  288,  334,
+   -1,   -1,  337,  293,   -1,  295,   -1,  265,   -1,  267,
+  300,   -1,  270,   -1,  304,  305,   -1,  275,   -1,   -1,
+   -1,  279,   -1,   -1,   -1,   -1,  316,   -1,  318,   -1,
+  288,   -1,  322,   -1,   -1,   -1,   -1,  295,   -1,   -1,
+  330,  331,  300,   -1,  334,   -1,  304,  337,   -1,   -1,
+   -1,  261,  419,   -1,   -1,   -1,   -1,   -1,  316,   -1,
+  318,   -1,  272,   -1,  322,   -1,   -1,  277,   -1,   -1,
+   -1,  281,  330,  331,  284,   -1,  334,   -1,   -1,  337,
+   -1,   -1,   -1,   -1,  419,   -1,  296,  297,   -1,   -1,
+   -1,  301,  302,   -1,   -1,   -1,   -1,  307,   -1,  309,
+  310,  311,  312,   -1,   -1,  363,   -1,  317,   -1,   -1,
+   -1,  321,   -1,  323,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,  261,  333,   -1,  335,  336,   -1,  338,  419,
+   -1,   -1,  342,  272,   -1,   -1,   -1,   -1,  277,   -1,
+   -1,   -1,  281,   -1,   -1,  284,   -1,   -1,   -1,   -1,
+   -1,   -1,  362,   -1,   -1,   -1,   -1,  296,  297,  369,
+  370,  419,  301,  302,  261,   -1,   -1,   -1,  307,   -1,
+  309,  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,
+   -1,   -1,  321,   -1,  323,   -1,   -1,  284,   -1,   -1,
+   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,   -1,  338,
+  297,   -1,  261,  342,  263,  302,   -1,   -1,   -1,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,   -1,  315,   -1,
+  317,   -1,   -1,  362,  321,  284,   -1,   -1,   -1,   -1,
+  369,  370,   -1,   -1,   -1,   -1,  333,   -1,  297,  336,
+   -1,  338,   -1,  302,   -1,   -1,   -1,   -1,  307,   -1,
+  309,  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,
+   -1,   -1,  321,   -1,   -1,  362,   -1,   -1,   -1,   -1,
+   -1,   -1,  369,  370,  333,   -1,   -1,  336,  261,  338,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,  272,
+   -1,   -1,   -1,   -1,  277,   -1,   -1,   -1,  281,   -1,
+   -1,  284,   -1,  362,   -1,   -1,   -1,   -1,   -1,   -1,
+  369,  370,   -1,  296,  297,   -1,   -1,   -1,  301,  302,
+   -1,  261,   -1,   -1,  307,   -1,  309,  310,  311,  312,
+   -1,   -1,  272,   -1,  317,   -1,   -1,  277,  321,   -1,
+  323,  281,   -1,   -1,  284,   -1,   -1,   -1,   -1,   -1,
+  333,   -1,   -1,  336,   -1,  338,  296,  297,   -1,  342,
+   -1,  301,  302,   -1,  261,   -1,   -1,  307,   -1,  309,
+  310,  311,  312,   -1,   -1,   -1,   -1,  317,   -1,  362,
+   -1,  321,   -1,  323,   -1,   -1,  369,  284,   -1,   -1,
+   -1,   -1,   -1,  333,   -1,   -1,  336,   -1,  338,   -1,
+  297,   -1,  342,   -1,  261,  302,   -1,   -1,   -1,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,   -1,   -1,   -1,
+  317,   -1,  362,   -1,  321,   -1,   -1,  284,   -1,  369,
+   -1,   -1,   -1,   -1,   -1,   -1,  333,   -1,   -1,  336,
+  297,  338,   -1,   -1,  261,  302,   -1,   -1,   -1,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,   -1,   -1,   -1,
+  317,   -1,   -1,   -1,  321,  362,   -1,  284,  365,  366,
+   -1,   -1,  369,   -1,   -1,   -1,  333,   -1,   -1,  336,
+  297,  338,   -1,   -1,  261,  302,  263,   -1,   -1,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,   -1,  315,   -1,
+  317,   -1,   -1,   -1,  321,  362,   -1,  284,  365,  366,
+   -1,   -1,  369,   -1,  261,   -1,  333,   -1,   -1,  336,
+  297,  338,   -1,   -1,   -1,  302,   -1,   -1,   -1,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,  284,   -1,   -1,
+  317,   -1,   -1,   -1,  321,  362,   -1,   -1,   -1,   -1,
+  297,   -1,  369,   -1,  261,  302,  333,   -1,   -1,  336,
+  307,  338,  309,  310,  311,  312,   -1,   -1,   -1,   -1,
+  317,   -1,   -1,   -1,  321,   -1,   -1,  284,   -1,   -1,
+   -1,   -1,   -1,   -1,  261,  362,  333,   -1,   -1,  336,
+  297,  338,  369,   -1,  301,  302,   -1,   -1,   -1,   -1,
+  307,   -1,  309,  310,  311,  312,   -1,  284,   -1,   -1,
+  317,   -1,   -1,   -1,  321,  362,   -1,   -1,  365,  366,
+  297,   -1,   -1,   -1,   -1,  302,  333,   -1,   -1,  336,
+  307,  338,  309,  310,  311,  312,   -1,   -1,   -1,   -1,
+  317,   -1,   -1,   -1,  321,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  362,  333,   -1,   -1,  336,
+   -1,  338,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,   -1,
+   -1,   -1,   -1,   -1,   -1,  362,
+  };
+
+#line 7338 "cs-parser.jay"
+
+// <summary>
+//  A class used to hold info about an operator declarator
+// </summary>
+class OperatorDeclaration {
+	public readonly Operator.OpType optype;
+	public readonly FullNamedExpression ret_type;
+	public readonly Location location;
+
+	public OperatorDeclaration (Operator.OpType op, FullNamedExpression ret_type, Location location)
+	{
+		optype = op;
+		this.ret_type = ret_type;
+		this.location = location;
+	}
+}
+
+void Error_ExpectingTypeName (Expression expr)
+{
+	if (expr is Invocation){
+		report.Error (1002, expr.Location, "Expecting `;'");
+	} else {
+		expr.Error_InvalidExpressionStatement (report);
+	}
+}
+
+void Error_ParameterModifierNotValid (string modifier, Location loc)
+{
+	report.Error (631, loc, "The parameter modifier `{0}' is not valid in this context",
+			              modifier);
+}
+
+void Error_DuplicateParameterModifier (Location loc, Parameter.Modifier mod)
+{
+	report.Error (1107, loc, "Duplicate parameter modifier `{0}'",
+  		Parameter.GetModifierSignature (mod));
+}
+
+void Error_TypeExpected (Location loc)
+{
+	report.Error (1031, loc, "Type expected");
+}
+
+void Error_UnsafeCodeNotAllowed (Location loc)
+{
+	report.Error (227, loc, "Unsafe code requires the `unsafe' command line option to be specified");
+}
+
+void Warning_EmptyStatement (Location loc)
+{
+	report.Warning (642, 3, loc, "Possible mistaken empty statement");
+}
+
+void Error_NamedArgumentExpected (NamedArgument a)
+{
+	report.Error (1738, a.Location, "Named arguments must appear after the positional arguments");
+}
+
+void Error_MissingInitializer (Location loc)
+{
+	report.Error (210, loc, "You must provide an initializer in a fixed or using statement declaration");
+}
+
+object Error_AwaitAsIdentifier (object token)
+{
+	if (async_block) {
+		report.Error (4003, GetLocation (token), "`await' cannot be used as an identifier within an async method or lambda expression");
+		return new LocatedToken ("await", GetLocation (token));
+	}
+
+	return token;
+}
+
+void push_current_container (TypeDefinition tc, object partial_token)
+{
+	if (module.Evaluator != null){
+		tc.Definition.Modifiers = tc.ModFlags = (tc.ModFlags & ~Modifiers.AccessibilityMask) | Modifiers.PUBLIC;
+		if (undo == null)
+			undo = new Undo ();
+
+		undo.AddTypeContainer (current_container, tc);
+	}
+	
+	if (partial_token != null)
+		current_container.AddPartial (tc);
+	else
+		current_container.AddTypeContainer (tc);
+		
+	++lexer.parsing_declaration;
+	current_container = tc;
+	current_type = tc;
+}
+
+TypeContainer pop_current_class ()
+{
+	var retval = current_container;
+
+	current_container = current_container.Parent;
+	current_type = current_type.Parent as TypeDefinition;
+
+	return retval;
+}
+
+[System.Diagnostics.Conditional ("FULL_AST")]
+void StoreModifierLocation (object token, Location loc)
+{
+	if (lbag == null)
+		return;
+
+	if (mod_locations == null)
+  		mod_locations = new List<Tuple<Modifiers, Location>> ();
+
+	mod_locations.Add (Tuple.Create ((Modifiers) token, loc));
+}
+
+List<Tuple<Modifiers, Location>> GetModifierLocations ()
+{
+	var result = mod_locations;
+	mod_locations = null;
+	return result;
+}
+
+[System.Diagnostics.Conditional ("FULL_AST")]
+void PushLocation (Location loc)
+{
+	if (location_stack == null)
+		location_stack = new Stack<Location> ();
+
+	location_stack.Push (loc);
+}
+
+Location PopLocation ()
+{
+	if (location_stack == null)
+		return Location.Null;
+
+	return location_stack.Pop ();
+}
+
+string CheckAttributeTarget (int token, string a, Location l)
+{
+	switch (a) {
+	case "assembly" : case "module" : case "field" : case "method" : case "param" : case "property" : case "type" :
+			return a;
+	}
+
+	if (!Tokenizer.IsValidIdentifier (a)) {
+		Error_SyntaxError (token);
+	} else {
+		report.Warning (658, 1, l,
+			 "`{0}' is invalid attribute target. All attributes in this attribute section will be ignored", a);
+	}
+
+	return string.Empty;
+}
+
+static bool IsUnaryOperator (Operator.OpType op)
+{
+	switch (op) {
+		
+	case Operator.OpType.LogicalNot: 
+	case Operator.OpType.OnesComplement: 
+	case Operator.OpType.Increment:
+	case Operator.OpType.Decrement:
+	case Operator.OpType.True: 
+	case Operator.OpType.False: 
+	case Operator.OpType.UnaryPlus: 
+	case Operator.OpType.UnaryNegation:
+		return true;
+	}
+	return false;
+}
+
+void syntax_error (Location l, string msg)
+{
+	report.Error (1003, l, "Syntax error, " + msg);
+}
+
+Tokenizer lexer;
+
+public Tokenizer Lexer {
+	get {
+		return lexer;
+	}
+}		   
+
+public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, ParserSession session)
+	: this (reader, file, file.Compiler.Report, session)
+{
+}
+
+public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report, ParserSession session)
+{
+	this.file = file;
+	current_container = current_namespace = file;
+	
+	this.module = file.Module;
+	this.compiler = file.Compiler;
+	this.settings = compiler.Settings;
+	this.report = report;
+	
+	lang_version = settings.Version;
+	yacc_verbose_flag = settings.VerboseParserFlag;
+	doc_support = settings.DocumentationFile != null;
+	lexer = new Tokenizer (reader, file, session, report);
+	oob_stack = new Stack<object> ();
+	lbag = session.LocationsBag;
+	use_global_stacks = session.UseJayGlobalArrays;
+	parameters_bucket = session.ParametersStack;
+}
+
+public void parse ()
+{
+	eof_token = Token.EOF;
+	
+	try {
+		if (yacc_verbose_flag > 1)
+			yyparse (lexer, new yydebug.yyDebugSimple ());
+		else
+			yyparse (lexer);
+			
+		Tokenizer tokenizer = lexer as Tokenizer;
+		tokenizer.cleanup ();		
+	} catch (Exception e){
+	  	if (e is yyParser.yyUnexpectedEof) {
+			Error_SyntaxError (yyToken);
+			UnexpectedEOF = true;
+			return;
+		}
+			
+		if (e is yyParser.yyException) {
+			if (report.Errors == 0)
+				report.Error (-25, lexer.Location, "Parsing error");
+		} else {
+			// Used by compiler-tester to test internal errors
+			if (yacc_verbose_flag > 0 || e is FatalException)
+				throw;
+		
+			report.Error (589, lexer.Location, "Internal compiler error during parsing" + e);
+		}
+	}
+}
+
+void CheckToken (int error, int yyToken, string msg, Location loc)
+{
+	if (yyToken >= Token.FIRST_KEYWORD && yyToken <= Token.LAST_KEYWORD)
+		report.Error (error, loc, "{0}: `{1}' is a keyword", msg, GetTokenName (yyToken));
+	else
+		report.Error (error, loc, msg);
+}
+
+string ConsumeStoredComment ()
+{
+	string s = tmpComment;
+	tmpComment = null;
+	Lexer.doc_state = XmlCommentState.Allowed;
+	return s;
+}
+
+void FeatureIsNotAvailable (Location loc, string feature)
+{
+	report.FeatureIsNotAvailable (compiler, loc, feature);
+}
+
+Location GetLocation (object obj)
+{
+	var lt = obj as LocatedToken;
+	if (lt != null)
+		return lt.Location;
+		
+	var mn = obj as MemberName;
+	if (mn != null)
+		return mn.Location;
+		
+	var expr = obj as Expression;
+	if (expr != null)
+		return expr.Location;
+
+	return lexer.Location;
+}
+
+void start_block (Location loc)
+{
+	if (current_block == null) {
+		current_block = new ToplevelBlock (compiler, current_local_parameters, loc);
+		parsing_anonymous_method = false;
+	} else if (parsing_anonymous_method) {
+		current_block = new ParametersBlock (current_block, current_local_parameters, loc);
+		parsing_anonymous_method = false;
+	} else {
+		current_block = new ExplicitBlock (current_block, loc, Location.Null);
+	}
+}
+
+Block
+end_block (Location loc)
+{
+	Block retval = current_block.Explicit;
+	retval.SetEndLocation (loc);
+	current_block = retval.Parent;
+	return retval;
+}
+
+void start_anonymous (bool isLambda, ParametersCompiled parameters, bool isAsync, Location loc)
+{
+	oob_stack.Push (current_anonymous_method);
+	oob_stack.Push (current_local_parameters);
+	oob_stack.Push (current_variable);
+	oob_stack.Push (async_block);
+
+	current_local_parameters = parameters;
+	if (isLambda) {
+		if (lang_version <= LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (loc, "lambda expressions");
+
+		current_anonymous_method = new LambdaExpression (loc);
+	} else {
+		if (lang_version == LanguageVersion.ISO_1)
+			FeatureIsNotAvailable (loc, "anonymous methods");
+			
+		current_anonymous_method = new AnonymousMethodExpression (loc);
+	}
+	current_anonymous_method.IsAsync = isAsync;
+	
+	async_block = isAsync;
+	// Force the next block to be created as a ToplevelBlock
+	parsing_anonymous_method = true;
+}
+
+/*
+ * Completes the anonymous method processing, if lambda_expr is null, this
+ * means that we have a Statement instead of an Expression embedded 
+ */
+AnonymousMethodExpression end_anonymous (ParametersBlock anon_block)
+{
+	AnonymousMethodExpression retval;
+
+	if (async_block)
+		anon_block.IsAsync = true;
+
+	current_anonymous_method.Block = anon_block;
+	retval = current_anonymous_method;
+
+	async_block = (bool) oob_stack.Pop ();
+	current_variable = (BlockVariable) oob_stack.Pop ();
+	current_local_parameters = (ParametersCompiled) oob_stack.Pop ();
+	current_anonymous_method = (AnonymousMethodExpression) oob_stack.Pop ();
+
+	return retval;
+}
+
+void Error_SyntaxError (int token)
+{
+	Error_SyntaxError (0, token);
+}
+
+void Error_SyntaxError (int error_code, int token)
+{
+	Error_SyntaxError (error_code, token, "Unexpected symbol");
+}
+
+void Error_SyntaxError (int error_code, int token, string msg)
+{
+	Lexer.CompleteOnEOF = false;
+
+	// An error message has been reported by tokenizer
+	if (token == Token.ERROR)
+		return;
+	
+	// Avoid duplicit error message after unterminated string literals
+	if (token == Token.LITERAL && lexer.Location.Column == 0)
+		return;
+
+	string symbol = GetSymbolName (token);
+	string expecting = GetExpecting ();
+	var loc = lexer.Location - symbol.Length;
+	
+	if (error_code == 0) {
+		if (expecting == "`identifier'") {
+			if (token > Token.FIRST_KEYWORD && token < Token.LAST_KEYWORD) {
+				report.Error (1041, loc, "Identifier expected, `{0}' is a keyword", symbol);
+				return;
+			}
+			
+			error_code = 1001;
+			expecting = "identifier";
+		} else if (expecting == "`)'") {
+			error_code = 1026;
+		} else {
+			error_code = 1525;
+		}
+	}
+	
+	if (string.IsNullOrEmpty (expecting))
+		report.Error (error_code, loc, "{1} `{0}'", symbol, msg);
+	else
+		report.Error (error_code, loc, "{2} `{0}', expecting {1}", symbol, expecting, msg);	  
+}
+
+string GetExpecting ()
+{
+	int [] tokens = yyExpectingTokens (yyExpectingState);
+	var names = new List<string> (tokens.Length);
+	bool has_type = false;
+	bool has_identifier = false;
+	for (int i = 0; i < tokens.Length; i++){
+		int token = tokens [i];
+		has_identifier |= token == Token.IDENTIFIER;
+		
+		string name = GetTokenName (token);
+		if (name == "<internal>")
+			continue;
+			
+		has_type |= name == "type";
+		if (names.Contains (name))
+			continue;
+		
+		names.Add (name);
+	}
+
+	//
+	// Too many tokens to enumerate
+	//
+	if (names.Count > 8)
+		return null;
+
+	if (has_type && has_identifier)
+		names.Remove ("identifier");
+
+	if (names.Count == 1)
+		return "`" + GetTokenName (tokens [0]) + "'";
+	
+	StringBuilder sb = new StringBuilder ();
+	names.Sort ();
+	int count = names.Count;
+	for (int i = 0; i < count; i++){
+		bool last = i + 1 == count;
+		if (last)
+			sb.Append ("or ");
+		sb.Append ('`');
+		sb.Append (names [i]);
+		sb.Append (last ? "'" : count < 3 ? "' " : "', ");
+	}
+	return sb.ToString ();
+}
+
+
+string GetSymbolName (int token)
+{
+	switch (token){
+	case Token.LITERAL:
+		return ((Constant)lexer.Value).GetValue ().ToString ();
+	case Token.IDENTIFIER:
+		return ((LocatedToken)lexer.Value).Value;
+
+	case Token.BOOL:
+		return "bool";
+	case Token.BYTE:
+		return "byte";
+	case Token.CHAR:
+		return "char";
+	case Token.VOID:
+		return "void";
+	case Token.DECIMAL:
+		return "decimal";
+	case Token.DOUBLE:
+		return "double";
+	case Token.FLOAT:
+		return "float";
+	case Token.INT:
+		return "int";
+	case Token.LONG:
+		return "long";
+	case Token.SBYTE:
+		return "sbyte";
+	case Token.SHORT:
+		return "short";
+	case Token.STRING:
+		return "string";
+	case Token.UINT:
+		return "uint";
+	case Token.ULONG:
+		return "ulong";
+	case Token.USHORT:
+		return "ushort";
+	case Token.OBJECT:
+		return "object";
+		
+	case Token.PLUS:
+		return "+";
+	case Token.UMINUS:
+	case Token.MINUS:
+		return "-";
+	case Token.BANG:
+		return "!";
+	case Token.BITWISE_AND:
+		return "&";
+	case Token.BITWISE_OR:
+		return "|";
+	case Token.STAR:
+		return "*";
+	case Token.PERCENT:
+		return "%";
+	case Token.DIV:
+		return "/";
+	case Token.CARRET:
+		return "^";
+	case Token.OP_INC:
+		return "++";
+	case Token.OP_DEC:
+		return "--";
+	case Token.OP_SHIFT_LEFT:
+		return "<<";
+	case Token.OP_SHIFT_RIGHT:
+		return ">>";
+	case Token.OP_LT:
+		return "<";
+	case Token.OP_GT:
+		return ">";
+	case Token.OP_LE:
+		return "<=";
+	case Token.OP_GE:
+		return ">=";
+	case Token.OP_EQ:
+		return "==";
+	case Token.OP_NE:
+		return "!=";
+	case Token.OP_AND:
+		return "&&";
+	case Token.OP_OR:
+		return "||";
+	case Token.OP_PTR:
+		return "->";
+	case Token.OP_COALESCING:	
+		return "??";
+	case Token.OP_MULT_ASSIGN:
+		return "*=";
+	case Token.OP_DIV_ASSIGN:
+		return "/=";
+	case Token.OP_MOD_ASSIGN:
+		return "%=";
+	case Token.OP_ADD_ASSIGN:
+		return "+=";
+	case Token.OP_SUB_ASSIGN:
+		return "-=";
+	case Token.OP_SHIFT_LEFT_ASSIGN:
+		return "<<=";
+	case Token.OP_SHIFT_RIGHT_ASSIGN:
+		return ">>=";
+	case Token.OP_AND_ASSIGN:
+		return "&=";
+	case Token.OP_XOR_ASSIGN:
+		return "^=";
+	case Token.OP_OR_ASSIGN:
+		return "|=";
+	}
+
+	return GetTokenName (token);
+}
+
+static string GetTokenName (int token)
+{
+	switch (token){
+	case Token.ABSTRACT:
+		return "abstract";
+	case Token.AS:
+		return "as";
+	case Token.ADD:
+		return "add";
+	case Token.ASYNC:
+		return "async";
+	case Token.BASE:
+		return "base";
+	case Token.BREAK:
+		return "break";
+	case Token.CASE:
+		return "case";
+	case Token.CATCH:
+		return "catch";
+	case Token.CHECKED:
+		return "checked";
+	case Token.CLASS:
+		return "class";
+	case Token.CONST:
+		return "const";
+	case Token.CONTINUE:
+		return "continue";
+	case Token.DEFAULT:
+		return "default";
+	case Token.DELEGATE:
+		return "delegate";
+	case Token.DO:
+		return "do";
+	case Token.ELSE:
+		return "else";
+	case Token.ENUM:
+		return "enum";
+	case Token.EVENT:
+		return "event";
+	case Token.EXPLICIT:
+		return "explicit";
+	case Token.EXTERN:
+	case Token.EXTERN_ALIAS:
+		return "extern";
+	case Token.FALSE:
+		return "false";
+	case Token.FINALLY:
+		return "finally";
+	case Token.FIXED:
+		return "fixed";
+	case Token.FOR:
+		return "for";
+	case Token.FOREACH:
+		return "foreach";
+	case Token.GOTO:
+		return "goto";
+	case Token.IF:
+		return "if";
+	case Token.IMPLICIT:
+		return "implicit";
+	case Token.IN:
+		return "in";
+	case Token.INTERFACE:
+		return "interface";
+	case Token.INTERNAL:
+		return "internal";
+	case Token.IS:
+		return "is";
+	case Token.LOCK:
+		return "lock";
+	case Token.NAMESPACE:
+		return "namespace";
+	case Token.NEW:
+		return "new";
+	case Token.NULL:
+		return "null";
+	case Token.OPERATOR:
+		return "operator";
+	case Token.OUT:
+		return "out";
+	case Token.OVERRIDE:
+		return "override";
+	case Token.PARAMS:
+		return "params";
+	case Token.PRIVATE:
+		return "private";
+	case Token.PROTECTED:
+		return "protected";
+	case Token.PUBLIC:
+		return "public";
+	case Token.READONLY:
+		return "readonly";
+	case Token.REF:
+		return "ref";
+	case Token.RETURN:
+		return "return";
+	case Token.REMOVE:
+		return "remove";
+	case Token.SEALED:
+		return "sealed";
+	case Token.SIZEOF:
+		return "sizeof";
+	case Token.STACKALLOC:
+		return "stackalloc";
+	case Token.STATIC:
+		return "static";
+	case Token.STRUCT:
+		return "struct";
+	case Token.SWITCH:
+		return "switch";
+	case Token.THIS:
+		return "this";
+	case Token.THROW:
+		return "throw";
+	case Token.TRUE:
+		return "true";
+	case Token.TRY:
+		return "try";
+	case Token.TYPEOF:
+		return "typeof";
+	case Token.UNCHECKED:
+		return "unchecked";
+	case Token.UNSAFE:
+		return "unsafe";
+	case Token.USING:
+		return "using";
+	case Token.VIRTUAL:
+		return "virtual";
+	case Token.VOLATILE:
+		return "volatile";
+	case Token.WHERE:
+		return "where";
+	case Token.WHILE:
+		return "while";
+	case Token.ARGLIST:
+		return "__arglist";
+	case Token.REFVALUE:
+		return "__refvalue";
+	case Token.REFTYPE:
+		return "__reftype";
+	case Token.MAKEREF:
+		return "__makeref";
+	case Token.PARTIAL:
+		return "partial";
+	case Token.ARROW:
+		return "=>";
+	case Token.FROM:
+	case Token.FROM_FIRST:
+		return "from";
+	case Token.JOIN:
+		return "join";
+	case Token.ON:
+		return "on";
+	case Token.EQUALS:
+		return "equals";
+	case Token.SELECT:
+		return "select";
+	case Token.GROUP:
+		return "group";
+	case Token.BY:
+		return "by";
+	case Token.LET:
+		return "let";
+	case Token.ORDERBY:
+		return "orderby";
+	case Token.ASCENDING:
+		return "ascending";
+	case Token.DESCENDING:
+		return "descending";
+	case Token.INTO:
+		return "into";
+	case Token.GET:
+		return "get";
+	case Token.SET:
+		return "set";
+	case Token.OPEN_BRACE:
+		return "{";
+	case Token.CLOSE_BRACE:
+		return "}";
+	case Token.OPEN_BRACKET:
+	case Token.OPEN_BRACKET_EXPR:
+		return "[";
+	case Token.CLOSE_BRACKET:
+		return "]";
+	case Token.OPEN_PARENS_CAST:
+	case Token.OPEN_PARENS_LAMBDA:
+	case Token.OPEN_PARENS:
+		return "(";
+	case Token.CLOSE_PARENS:
+		return ")";
+	case Token.DOT:
+		return ".";
+	case Token.COMMA:
+		return ",";
+	case Token.DEFAULT_COLON:
+		return "default:";
+	case Token.COLON:
+		return ":";
+	case Token.SEMICOLON:
+		return ";";
+	case Token.TILDE:
+		return "~";
+		
+	case Token.PLUS:
+	case Token.UMINUS:
+	case Token.MINUS:
+	case Token.BANG:
+	case Token.OP_LT:
+	case Token.OP_GT:
+	case Token.BITWISE_AND:
+	case Token.BITWISE_OR:
+	case Token.STAR:
+	case Token.PERCENT:
+	case Token.DIV:
+	case Token.CARRET:
+	case Token.OP_INC:
+	case Token.OP_DEC:
+	case Token.OP_SHIFT_LEFT:
+	case Token.OP_SHIFT_RIGHT:
+	case Token.OP_LE:
+	case Token.OP_GE:
+	case Token.OP_EQ:
+	case Token.OP_NE:
+	case Token.OP_AND:
+	case Token.OP_OR:
+	case Token.OP_PTR:
+	case Token.OP_COALESCING:	
+	case Token.OP_MULT_ASSIGN:
+	case Token.OP_DIV_ASSIGN:
+	case Token.OP_MOD_ASSIGN:
+	case Token.OP_ADD_ASSIGN:
+	case Token.OP_SUB_ASSIGN:
+	case Token.OP_SHIFT_LEFT_ASSIGN:
+	case Token.OP_SHIFT_RIGHT_ASSIGN:
+	case Token.OP_AND_ASSIGN:
+	case Token.OP_XOR_ASSIGN:
+	case Token.OP_OR_ASSIGN:
+		return "<operator>";
+
+	case Token.BOOL:
+	case Token.BYTE:
+	case Token.CHAR:
+	case Token.VOID:
+	case Token.DECIMAL:
+	case Token.DOUBLE:
+	case Token.FLOAT:
+	case Token.INT:
+	case Token.LONG:
+	case Token.SBYTE:
+	case Token.SHORT:
+	case Token.STRING:
+	case Token.UINT:
+	case Token.ULONG:
+	case Token.USHORT:
+	case Token.OBJECT:
+		return "type";
+	
+	case Token.ASSIGN:
+		return "=";
+	case Token.OP_GENERICS_LT:
+	case Token.GENERIC_DIMENSION:
+		return "<";
+	case Token.OP_GENERICS_GT:
+		return ">";
+	case Token.INTERR:
+	case Token.INTERR_NULLABLE:
+		return "?";
+	case Token.DOUBLE_COLON:
+		return "::";
+	case Token.LITERAL:
+		return "value";
+	case Token.IDENTIFIER:
+	case Token.AWAIT:
+		return "identifier";
+
+	case Token.EOF:
+		return "end-of-file";
+
+		// All of these are internal.
+	case Token.NONE:
+	case Token.ERROR:
+	case Token.FIRST_KEYWORD:
+	case Token.EVAL_COMPILATION_UNIT_PARSER:
+	case Token.EVAL_USING_DECLARATIONS_UNIT_PARSER:
+	case Token.EVAL_STATEMENT_PARSER:
+	case Token.LAST_KEYWORD:
+	case Token.GENERATE_COMPLETION:
+	case Token.COMPLETE_COMPLETION:
+		return "<internal>";
+
+		// A bit more robust.
+	default:
+		return yyNames [token];
+        }
+}
+
+/* end end end */
+}
+#line default
+namespace yydebug {
+        using System;
+	 internal interface yyDebug {
+		 void push (int state, Object value);
+		 void lex (int state, int token, string name, Object value);
+		 void shift (int from, int to, int errorFlag);
+		 void pop (int state);
+		 void discard (int state, int token, string name, Object value);
+		 void reduce (int from, int to, int rule, string text, int len);
+		 void shift (int from, int to);
+		 void accept (Object value);
+		 void error (string message);
+		 void reject ();
+	 }
+	 
+	 class yyDebugSimple : yyDebug {
+		 void println (string s){
+			 Console.Error.WriteLine (s);
+		 }
+		 
+		 public void push (int state, Object value) {
+			 println ("push\tstate "+state+"\tvalue "+value);
+		 }
+		 
+		 public void lex (int state, int token, string name, Object value) {
+			 println("lex\tstate "+state+"\treading "+name+"\tvalue "+value);
+		 }
+		 
+		 public void shift (int from, int to, int errorFlag) {
+			 switch (errorFlag) {
+			 default:				// normally
+				 println("shift\tfrom state "+from+" to "+to);
+				 break;
+			 case 0: case 1: case 2:		// in error recovery
+				 println("shift\tfrom state "+from+" to "+to
+					     +"\t"+errorFlag+" left to recover");
+				 break;
+			 case 3:				// normally
+				 println("shift\tfrom state "+from+" to "+to+"\ton error");
+				 break;
+			 }
+		 }
+		 
+		 public void pop (int state) {
+			 println("pop\tstate "+state+"\ton error");
+		 }
+		 
+		 public void discard (int state, int token, string name, Object value) {
+			 println("discard\tstate "+state+"\ttoken "+name+"\tvalue "+value);
+		 }
+		 
+		 public void reduce (int from, int to, int rule, string text, int len) {
+			 println("reduce\tstate "+from+"\tuncover "+to
+				     +"\trule ("+rule+") "+text);
+		 }
+		 
+		 public void shift (int from, int to) {
+			 println("goto\tfrom state "+from+" to "+to);
+		 }
+		 
+		 public void accept (Object value) {
+			 println("accept\tvalue "+value);
+		 }
+		 
+		 public void error (string message) {
+			 println("error\t"+message);
+		 }
+		 
+		 public void reject () {
+			 println("reject");
+		 }
+		 
+	 }
+}
+// %token constants
+ class Token {
+  public const int EOF = 257;
+  public const int NONE = 258;
+  public const int ERROR = 259;
+  public const int FIRST_KEYWORD = 260;
+  public const int ABSTRACT = 261;
+  public const int AS = 262;
+  public const int ADD = 263;
+  public const int BASE = 264;
+  public const int BOOL = 265;
+  public const int BREAK = 266;
+  public const int BYTE = 267;
+  public const int CASE = 268;
+  public const int CATCH = 269;
+  public const int CHAR = 270;
+  public const int CHECKED = 271;
+  public const int CLASS = 272;
+  public const int CONST = 273;
+  public const int CONTINUE = 274;
+  public const int DECIMAL = 275;
+  public const int DEFAULT = 276;
+  public const int DELEGATE = 277;
+  public const int DO = 278;
+  public const int DOUBLE = 279;
+  public const int ELSE = 280;
+  public const int ENUM = 281;
+  public const int EVENT = 282;
+  public const int EXPLICIT = 283;
+  public const int EXTERN = 284;
+  public const int FALSE = 285;
+  public const int FINALLY = 286;
+  public const int FIXED = 287;
+  public const int FLOAT = 288;
+  public const int FOR = 289;
+  public const int FOREACH = 290;
+  public const int GOTO = 291;
+  public const int IF = 292;
+  public const int IMPLICIT = 293;
+  public const int IN = 294;
+  public const int INT = 295;
+  public const int INTERFACE = 296;
+  public const int INTERNAL = 297;
+  public const int IS = 298;
+  public const int LOCK = 299;
+  public const int LONG = 300;
+  public const int NAMESPACE = 301;
+  public const int NEW = 302;
+  public const int NULL = 303;
+  public const int OBJECT = 304;
+  public const int OPERATOR = 305;
+  public const int OUT = 306;
+  public const int OVERRIDE = 307;
+  public const int PARAMS = 308;
+  public const int PRIVATE = 309;
+  public const int PROTECTED = 310;
+  public const int PUBLIC = 311;
+  public const int READONLY = 312;
+  public const int REF = 313;
+  public const int RETURN = 314;
+  public const int REMOVE = 315;
+  public const int SBYTE = 316;
+  public const int SEALED = 317;
+  public const int SHORT = 318;
+  public const int SIZEOF = 319;
+  public const int STACKALLOC = 320;
+  public const int STATIC = 321;
+  public const int STRING = 322;
+  public const int STRUCT = 323;
+  public const int SWITCH = 324;
+  public const int THIS = 325;
+  public const int THROW = 326;
+  public const int TRUE = 327;
+  public const int TRY = 328;
+  public const int TYPEOF = 329;
+  public const int UINT = 330;
+  public const int ULONG = 331;
+  public const int UNCHECKED = 332;
+  public const int UNSAFE = 333;
+  public const int USHORT = 334;
+  public const int USING = 335;
+  public const int VIRTUAL = 336;
+  public const int VOID = 337;
+  public const int VOLATILE = 338;
+  public const int WHERE = 339;
+  public const int WHILE = 340;
+  public const int ARGLIST = 341;
+  public const int PARTIAL = 342;
+  public const int ARROW = 343;
+  public const int FROM = 344;
+  public const int FROM_FIRST = 345;
+  public const int JOIN = 346;
+  public const int ON = 347;
+  public const int EQUALS = 348;
+  public const int SELECT = 349;
+  public const int GROUP = 350;
+  public const int BY = 351;
+  public const int LET = 352;
+  public const int ORDERBY = 353;
+  public const int ASCENDING = 354;
+  public const int DESCENDING = 355;
+  public const int INTO = 356;
+  public const int INTERR_NULLABLE = 357;
+  public const int EXTERN_ALIAS = 358;
+  public const int REFVALUE = 359;
+  public const int REFTYPE = 360;
+  public const int MAKEREF = 361;
+  public const int ASYNC = 362;
+  public const int AWAIT = 363;
+  public const int INTERR_OPERATOR = 364;
+  public const int GET = 365;
+  public const int SET = 366;
+  public const int LAST_KEYWORD = 367;
+  public const int OPEN_BRACE = 368;
+  public const int CLOSE_BRACE = 369;
+  public const int OPEN_BRACKET = 370;
+  public const int CLOSE_BRACKET = 371;
+  public const int OPEN_PARENS = 372;
+  public const int CLOSE_PARENS = 373;
+  public const int DOT = 374;
+  public const int COMMA = 375;
+  public const int COLON = 376;
+  public const int SEMICOLON = 377;
+  public const int TILDE = 378;
+  public const int PLUS = 379;
+  public const int MINUS = 380;
+  public const int BANG = 381;
+  public const int ASSIGN = 382;
+  public const int OP_LT = 383;
+  public const int OP_GT = 384;
+  public const int BITWISE_AND = 385;
+  public const int BITWISE_OR = 386;
+  public const int STAR = 387;
+  public const int PERCENT = 388;
+  public const int DIV = 389;
+  public const int CARRET = 390;
+  public const int INTERR = 391;
+  public const int DOUBLE_COLON = 392;
+  public const int OP_INC = 393;
+  public const int OP_DEC = 394;
+  public const int OP_SHIFT_LEFT = 395;
+  public const int OP_SHIFT_RIGHT = 396;
+  public const int OP_LE = 397;
+  public const int OP_GE = 398;
+  public const int OP_EQ = 399;
+  public const int OP_NE = 400;
+  public const int OP_AND = 401;
+  public const int OP_OR = 402;
+  public const int OP_MULT_ASSIGN = 403;
+  public const int OP_DIV_ASSIGN = 404;
+  public const int OP_MOD_ASSIGN = 405;
+  public const int OP_ADD_ASSIGN = 406;
+  public const int OP_SUB_ASSIGN = 407;
+  public const int OP_SHIFT_LEFT_ASSIGN = 408;
+  public const int OP_SHIFT_RIGHT_ASSIGN = 409;
+  public const int OP_AND_ASSIGN = 410;
+  public const int OP_XOR_ASSIGN = 411;
+  public const int OP_OR_ASSIGN = 412;
+  public const int OP_PTR = 413;
+  public const int OP_COALESCING = 414;
+  public const int OP_GENERICS_LT = 415;
+  public const int OP_GENERICS_LT_DECL = 416;
+  public const int OP_GENERICS_GT = 417;
+  public const int LITERAL = 418;
+  public const int IDENTIFIER = 419;
+  public const int OPEN_PARENS_LAMBDA = 420;
+  public const int OPEN_PARENS_CAST = 421;
+  public const int GENERIC_DIMENSION = 422;
+  public const int DEFAULT_COLON = 423;
+  public const int OPEN_BRACKET_EXPR = 424;
+  public const int EVAL_STATEMENT_PARSER = 425;
+  public const int EVAL_COMPILATION_UNIT_PARSER = 426;
+  public const int EVAL_USING_DECLARATIONS_UNIT_PARSER = 427;
+  public const int DOC_SEE = 428;
+  public const int GENERATE_COMPLETION = 429;
+  public const int COMPLETE_COMPLETION = 430;
+  public const int UMINUS = 431;
+  public const int yyErrorCode = 256;
+ }
+ namespace yyParser {
+  using System;
+  /** thrown for irrecoverable syntax errors and stack overflow.
+    */
+  internal class yyException : System.Exception {
+    public yyException (string message) : base (message) {
+    }
+  }
+  internal class yyUnexpectedEof : yyException {
+    public yyUnexpectedEof (string message) : base (message) {
+    }
+    public yyUnexpectedEof () : base ("") {
+    }
+  }
+
+  /** must be implemented by a scanner object to supply input to the parser.
+    */
+  internal interface yyInput {
+    /** move on to next token.
+        @return false if positioned beyond tokens.
+        @throws IOException on input error.
+      */
+    bool advance (); // throws java.io.IOException;
+    /** classifies current token.
+        Should not be called if advance() returned false.
+        @return current %token or single character.
+      */
+    int token ();
+    /** associated with current token.
+        Should not be called if advance() returned false.
+        @return value for token().
+      */
+    Object value ();
+  }
+ }
+} // close outermost namespace, that MUST HAVE BEEN opened in the prolog
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-parser.jay
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-parser.jay	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-parser.jay	(revision 11807)
@@ -0,0 +1,8195 @@
+%{
+//
+// cs-parser.jay: The Parser for the C# compiler
+//
+// Authors: Miguel de Icaza (miguel@gnome.org)
+//          Ravi Pratap     (ravi@ximian.com)
+//          Marek Safar	    (marek.safar@gmail.com)
+//
+// Dual Licensed under the terms of the GNU GPL and the MIT X11 license
+//
+// (C) 2001 Ximian, Inc (http://www.ximian.com)
+// (C) 2004-2011 Novell, Inc
+// Copyright 2011-2012 Xamarin Inc.
+//
+
+using System.Text;
+using System.IO;
+using System;
+using System.Collections.Generic;
+
+namespace Mono.CSharp
+{
+	/// <summary>
+	///    The C# Parser
+	/// </summary>
+	public class CSharpParser
+	{
+		[Flags]
+		enum ParameterModifierType
+		{
+			Ref		= 1 << 1,
+			Out		= 1 << 2,
+			This	= 1 << 3,
+			Params	= 1 << 4,
+			Arglist	= 1 << 5,
+			DefaultValue = 1 << 6,
+			
+			All = Ref | Out | This | Params | Arglist | DefaultValue,
+			PrimaryConstructor = Ref | Out | Params | DefaultValue
+		}
+		
+		static readonly object ModifierNone = 0;
+	
+		NamespaceContainer current_namespace;
+		TypeContainer current_container;
+		TypeDefinition current_type;
+		PropertyBase current_property;
+		EventProperty current_event;
+		EventField current_event_field;
+		FieldBase current_field;
+	
+		/// <summary>
+		///   Current block is used to add statements as we find
+		///   them.  
+		/// </summary>
+		Block      current_block;
+		
+		BlockVariable current_variable;
+
+		Delegate   current_delegate;
+		
+		AnonymousMethodExpression current_anonymous_method;
+
+		/// <summary>
+		///   This is used by the unary_expression code to resolve
+		///   a name against a parameter.  
+		/// </summary>
+		
+		// FIXME: This is very ugly and it's very hard to reset it correctly
+		// on all places, especially when some parameters are autogenerated.
+		ParametersCompiled current_local_parameters;
+
+		bool parsing_anonymous_method;
+		
+		bool async_block;
+
+		///
+		/// An out-of-band stack.
+		///
+		Stack<object> oob_stack;
+
+		///
+		/// Controls the verbosity of the errors produced by the parser
+		///
+		int yacc_verbose_flag;
+
+		/// 
+		/// Used by the interactive shell, flags whether EOF was reached
+		/// and an error was produced
+		///
+		public bool UnexpectedEOF;
+
+		///
+		/// The current file.
+		///
+		readonly CompilationSourceFile file;
+
+		///
+		/// Temporary Xml documentation cache.
+		/// For enum types, we need one more temporary store.
+		///
+		string tmpComment;
+		string enumTypeComment;
+	       		
+		/// Current attribute target
+		string current_attr_target;
+		
+		ParameterModifierType valid_param_mod;
+		
+		bool default_parameter_used;
+
+		/// When using the interactive parser, this holds the
+		/// resulting expression
+		public Class InteractiveResult;
+
+		//
+		// Keeps track of global data changes to undo on parser error
+		//
+		public Undo undo;
+
+		bool? interactive_async;
+		
+		Stack<Linq.QueryBlock> linq_clause_blocks;
+
+		ModuleContainer module;
+		
+		readonly CompilerContext compiler;
+		readonly LanguageVersion lang_version;
+		readonly bool doc_support;
+		readonly CompilerSettings settings;
+		readonly Report report;
+		
+		//
+		// Instead of allocating carrier array everytime we
+		// share the bucket for very common constructs which can never
+		// be recursive
+		//
+		List<Parameter> parameters_bucket;
+		
+		//
+		// Full AST support members
+		//
+		LocationsBag lbag;
+		List<Tuple<Modifiers, Location>> mod_locations;
+		Location parameterModifierLocation, savedLocation, savedEventAssignLocation;
+		Location savedAttrParenOpenLocation, savedAttrParenCloseLocation, savedOperatorLocation;
+		Stack<List<Location>> locationListStack = new Stack<List<Location>> (); // used for type parameters
+		Stack<Location> opt_intoStack = new Stack<Location> ();
+
+		bool HadAttributeParens;
+		List<Location> attributeArgumentCommas = new List<Location> ();
+		List<Location> parameterListCommas = new List<Location> ();
+		Stack<Location> location_stack;
+%}
+
+%token EOF
+%token NONE   /* This token is never returned by our lexer */
+%token ERROR		// This is used not by the parser, but by the tokenizer.
+			// do not remove.
+
+/*
+ *These are the C# keywords
+ */
+%token FIRST_KEYWORD
+%token ABSTRACT	
+%token AS
+%token ADD
+%token BASE	
+%token BOOL	
+%token BREAK	
+%token BYTE	
+%token CASE	
+%token CATCH	
+%token CHAR	
+%token CHECKED	
+%token CLASS	
+%token CONST	
+%token CONTINUE	
+%token DECIMAL	
+%token DEFAULT	
+%token DELEGATE	
+%token DO	
+%token DOUBLE	
+%token ELSE	
+%token ENUM	
+%token EVENT	
+%token EXPLICIT	
+%token EXTERN	
+%token FALSE	
+%token FINALLY	
+%token FIXED	
+%token FLOAT	
+%token FOR	
+%token FOREACH	
+%token GOTO	
+%token IF	
+%token IMPLICIT	
+%token IN	
+%token INT	
+%token INTERFACE
+%token INTERNAL	
+%token IS	
+%token LOCK	
+%token LONG	
+%token NAMESPACE
+%token NEW	
+%token NULL	
+%token OBJECT	
+%token OPERATOR	
+%token OUT	
+%token OVERRIDE	
+%token PARAMS	
+%token PRIVATE	
+%token PROTECTED
+%token PUBLIC	
+%token READONLY	
+%token REF	
+%token RETURN	
+%token REMOVE
+%token SBYTE	
+%token SEALED	
+%token SHORT	
+%token SIZEOF	
+%token STACKALLOC
+%token STATIC	
+%token STRING	
+%token STRUCT	
+%token SWITCH	
+%token THIS	
+%token THROW	
+%token TRUE	
+%token TRY	
+%token TYPEOF	
+%token UINT	
+%token ULONG	
+%token UNCHECKED
+%token UNSAFE	
+%token USHORT	
+%token USING	
+%token VIRTUAL	
+%token VOID	
+%token VOLATILE
+%token WHERE
+%token WHILE	
+%token ARGLIST
+%token PARTIAL
+%token ARROW
+%token FROM
+%token FROM_FIRST
+%token JOIN
+%token ON
+%token EQUALS
+%token SELECT
+%token GROUP
+%token BY
+%token LET
+%token ORDERBY
+%token ASCENDING
+%token DESCENDING
+%token INTO
+%token INTERR_NULLABLE
+%token EXTERN_ALIAS
+%token REFVALUE
+%token REFTYPE
+%token MAKEREF
+%token ASYNC
+%token AWAIT
+%token INTERR_OPERATOR
+
+/* C# keywords which are not really keywords */
+%token GET
+%token SET
+
+%left LAST_KEYWORD
+
+/* C# single character operators/punctuation. */
+%token OPEN_BRACE
+%token CLOSE_BRACE
+%token OPEN_BRACKET
+%token CLOSE_BRACKET
+%token OPEN_PARENS
+%token CLOSE_PARENS
+
+%token DOT
+%token COMMA
+%token COLON
+%token SEMICOLON
+%token TILDE
+
+%token PLUS
+%token MINUS
+%token BANG
+%token ASSIGN
+%token OP_LT
+%token OP_GT
+%token BITWISE_AND
+%token BITWISE_OR
+%token STAR
+%token PERCENT
+%token DIV
+%token CARRET
+%token INTERR
+
+/* C# multi-character operators. */
+%token DOUBLE_COLON
+%token OP_INC
+%token OP_DEC
+%token OP_SHIFT_LEFT
+%token OP_SHIFT_RIGHT
+%token OP_LE
+%token OP_GE
+%token OP_EQ
+%token OP_NE
+%token OP_AND
+%token OP_OR
+%token OP_MULT_ASSIGN
+%token OP_DIV_ASSIGN
+%token OP_MOD_ASSIGN
+%token OP_ADD_ASSIGN
+%token OP_SUB_ASSIGN
+%token OP_SHIFT_LEFT_ASSIGN
+%token OP_SHIFT_RIGHT_ASSIGN
+%token OP_AND_ASSIGN
+%token OP_XOR_ASSIGN
+%token OP_OR_ASSIGN
+%token OP_PTR
+%token OP_COALESCING
+
+/* Generics <,> tokens */
+%token OP_GENERICS_LT
+%token OP_GENERICS_LT_DECL
+%token OP_GENERICS_GT
+
+%token LITERAL
+
+%token IDENTIFIER
+%token OPEN_PARENS_LAMBDA
+%token OPEN_PARENS_CAST
+%token GENERIC_DIMENSION
+%token DEFAULT_COLON
+%token OPEN_BRACKET_EXPR
+
+// Make the parser go into eval mode parsing (statements and compilation units).
+%token EVAL_STATEMENT_PARSER
+%token EVAL_COMPILATION_UNIT_PARSER
+%token EVAL_USING_DECLARATIONS_UNIT_PARSER
+
+%token DOC_SEE
+
+// 
+// This token is generated to trigger the completion engine at this point
+//
+%token GENERATE_COMPLETION
+
+//
+// This token is return repeatedly after the first GENERATE_COMPLETION
+// token is produced and before the final EOF
+//
+%token COMPLETE_COMPLETION
+
+/* Add precedence rules to solve dangling else s/r conflict */
+%nonassoc IF
+%nonassoc ELSE
+
+/* Define the operator tokens and their precedences */
+%right ASSIGN
+%right OP_COALESCING
+%right INTERR
+%left OP_OR
+%left OP_AND
+%left BITWISE_OR
+%left BITWISE_AND
+%left OP_SHIFT_LEFT OP_SHIFT_RIGHT
+%left PLUS MINUS
+%left STAR DIV PERCENT
+%right BANG CARRET UMINUS
+%nonassoc OP_INC OP_DEC
+%left OPEN_PARENS
+%left OPEN_BRACKET OPEN_BRACE
+%left DOT
+
+%start compilation_unit
+%%
+
+compilation_unit
+	: outer_declaration opt_EOF
+	  {
+		Lexer.check_incorrect_doc_comment ();
+	  }
+	| interactive_parsing  { Lexer.CompleteOnEOF = false; } opt_EOF
+	| documentation_parsing
+	;
+	
+outer_declaration
+	: opt_extern_alias_directives opt_using_directives
+	| opt_extern_alias_directives opt_using_directives namespace_or_type_declarations opt_attributes
+	  {
+		if ($4 != null) {
+			Attributes attrs = (Attributes) $4;
+			report.Error (1730, attrs.Attrs [0].Location,
+				"Assembly and module attributes must precede all other elements except using clauses and extern alias declarations");
+
+			current_namespace.UnattachedAttributes = attrs;
+		}
+	  }
+	| opt_extern_alias_directives opt_using_directives attribute_sections
+	  {
+		module.AddAttributes ((Attributes) $3, current_namespace);
+	  }
+	| error
+	  {
+		if (yyToken == Token.EXTERN_ALIAS)
+			report.Error (439, lexer.Location, "An extern alias declaration must precede all other elements");
+		else
+			Error_SyntaxError (yyToken);
+	  }
+	;
+	
+opt_EOF
+	: /* empty */
+	| EOF
+	;
+
+extern_alias_directives
+	: extern_alias_directive
+	| extern_alias_directives extern_alias_directive
+	;
+
+extern_alias_directive
+	: EXTERN_ALIAS IDENTIFIER IDENTIFIER SEMICOLON
+	  {
+		var lt = (LocatedToken) $2;
+		string s = lt.Value;
+		if (s != "alias") {
+			syntax_error (lt.Location, "`alias' expected");
+		} else {
+			if (lang_version == LanguageVersion.ISO_1)
+				FeatureIsNotAvailable (lt.Location, "external alias");
+
+			lt = (LocatedToken) $3;
+			if (lt.Value == QualifiedAliasMember.GlobalAlias) {
+				RootNamespace.Error_GlobalNamespaceRedefined (report, lt.Location);
+			}
+			
+			var na = new UsingExternAlias (new SimpleMemberName (lt.Value, lt.Location), GetLocation ($1));
+			current_namespace.AddUsing (na);
+			
+			lbag.AddLocation (na, GetLocation ($2), GetLocation ($4));
+		}
+	  }
+	| EXTERN_ALIAS error
+	  {
+		Error_SyntaxError (yyToken);
+	  }
+	;
+ 
+using_directives
+	: using_directive 
+	| using_directives using_directive
+	;
+
+using_directive
+	: using_namespace
+	  {
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	;
+
+using_namespace
+	: USING namespace_or_type_expr SEMICOLON 
+	  {
+		var un = new UsingNamespace ((ATypeNameExpression) $2, GetLocation ($1));
+		current_namespace.AddUsing (un);
+		
+		lbag.AddLocation (un, GetLocation ($3));
+	  }
+	| USING IDENTIFIER ASSIGN namespace_or_type_expr SEMICOLON
+	  {
+		var lt = (LocatedToken) $2;
+		if (lang_version != LanguageVersion.ISO_1 && lt.Value == "global") {
+			report.Warning (440, 2, lt.Location,
+			 "An alias named `global' will not be used when resolving `global::'. The global namespace will be used instead");
+		}
+
+		var un = new UsingAliasNamespace (new SimpleMemberName (lt.Value, lt.Location), (ATypeNameExpression) $4, GetLocation ($1));
+		current_namespace.AddUsing (un);
+		lbag.AddLocation (un, GetLocation ($3), GetLocation ($5));
+	  }
+	| USING error
+	 {
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	 }
+	;
+
+//
+// Strictly speaking, namespaces don't have attributes but
+// we parse global attributes along with namespace declarations and then
+// detach them
+// 
+namespace_declaration
+	: opt_attributes NAMESPACE namespace_name
+	  {
+		Attributes attrs = (Attributes) $1;
+		var name = (MemberName) $3;
+		if (attrs != null) {
+			bool valid_global_attrs = true;
+			if ((current_namespace.DeclarationFound || current_namespace != file)) {
+				valid_global_attrs = false;
+			} else {
+				foreach (var a in attrs.Attrs) {
+					if (a.ExplicitTarget == "assembly" || a.ExplicitTarget == "module")
+						continue;
+						
+					valid_global_attrs = false;
+					break;
+				}
+			}
+			
+			if (!valid_global_attrs)
+				report.Error (1671, name.Location, "A namespace declaration cannot have modifiers or attributes");
+		}
+	
+		module.AddAttributes (attrs, current_namespace);
+		
+		var ns = new NamespaceContainer (name, current_namespace);
+		current_namespace.AddTypeContainer (ns);
+		current_container = current_namespace = ns;
+	  }
+	  OPEN_BRACE
+	  {
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	  opt_extern_alias_directives opt_using_directives opt_namespace_or_type_declarations CLOSE_BRACE opt_semicolon_error
+	  {
+		if ($11 != null)
+			lbag.AddLocation (current_container, GetLocation ($2), GetLocation ($5), GetLocation ($10), GetLocation ($11));
+		else
+			lbag.AddLocation (current_container, GetLocation ($2), GetLocation ($5), GetLocation ($10));
+	  
+		current_container = current_namespace = current_namespace.Parent;
+	  }
+	| opt_attributes NAMESPACE namespace_name
+	  {
+		report.Error (1514, lexer.Location, "Unexpected symbol `{0}', expecting `.' or `{{'", GetSymbolName (yyToken));
+
+		var name = (MemberName) $3;		
+		var ns = new NamespaceContainer (name, current_namespace);
+		lbag.AddLocation (ns, GetLocation ($2));
+		current_namespace.AddTypeContainer (ns);
+	  }
+	;
+
+opt_semicolon_error
+	: /* empty */
+	| SEMICOLON
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+	  	$$ = null;
+	  }
+	;
+
+namespace_name
+	: IDENTIFIER
+	  {
+		var lt = (LocatedToken) $1;
+		$$ = new MemberName (lt.Value, lt.Location);
+	  }
+	| namespace_name DOT IDENTIFIER
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberName ((MemberName) $1, lt.Value, lt.Location);		
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new MemberName ("<invalid>", lexer.Location);
+	  }
+	;
+
+opt_semicolon
+	: /* empty */
+	| SEMICOLON
+	;
+
+opt_comma
+	: /* empty */
+	| COMMA
+	;
+
+opt_using_directives
+	: /* empty */
+	| using_directives
+	;
+
+opt_extern_alias_directives
+	: /* empty */
+	| extern_alias_directives
+	;
+
+opt_namespace_or_type_declarations
+	: /* empty */
+	| namespace_or_type_declarations
+	;
+
+namespace_or_type_declarations
+	: namespace_or_type_declaration
+	| namespace_or_type_declarations namespace_or_type_declaration
+	;
+
+namespace_or_type_declaration
+	: type_declaration
+	  {
+		if ($1 != null) {
+			TypeContainer ds = (TypeContainer)$1;
+
+			if ((ds.ModFlags & (Modifiers.PRIVATE | Modifiers.PROTECTED)) != 0){
+				report.Error (1527, ds.Location, 
+				"Namespace elements cannot be explicitly declared as private, protected or protected internal");
+			}
+
+			// Here is a trick, for explicit attributes we don't know where they belong to until
+			// we parse succeeding declaration hence we parse them as normal and re-attach them
+			// when we know whether they are global (assembly:, module:) or local (type:).
+			if (ds.OptAttributes != null) {
+				ds.OptAttributes.ConvertGlobalAttributes (ds, current_namespace, !current_namespace.DeclarationFound && current_namespace == file);
+			}
+		}
+		current_namespace.DeclarationFound = true;
+	  }
+	| namespace_declaration
+	  {
+		current_namespace.DeclarationFound = true;
+	  }
+	| attribute_sections CLOSE_BRACE {
+		current_namespace.UnattachedAttributes = (Attributes) $1;
+		report.Error (1518, lexer.Location, "Attributes must be attached to class, delegate, enum, interface or struct");
+		lexer.putback ('}');
+	  }
+	;
+
+type_declaration
+	: class_declaration		
+	| struct_declaration
+	| interface_declaration
+	| enum_declaration		
+	| delegate_declaration
+//
+// Enable this when we have handled all errors, because this acts as a generic fallback
+//
+//	| error {
+//		Console.WriteLine ("Token=" + yyToken);
+//		report.Error (1518, GetLocation ($1), "Expected class, struct, interface, enum or delegate");
+//	  }
+	;
+
+//
+// Attributes
+//
+
+opt_attributes
+	: /* empty */ 
+	| attribute_sections
+    ;
+ 
+attribute_sections
+	: attribute_section
+	  {
+		var sect = (List<Attribute>) $1;
+		$$ = new Attributes (sect);
+	  }
+	| attribute_sections attribute_section
+	  {
+		Attributes attrs = $1 as Attributes;
+		var sect = (List<Attribute>) $2;
+		if (attrs == null)
+			attrs = new Attributes (sect);
+		else if (sect != null)
+			attrs.AddAttributes (sect);
+		$$ = attrs;
+	  }
+	;
+	
+attribute_section
+	: OPEN_BRACKET
+	  {
+	  	PushLocation (GetLocation ($1));
+		lexer.parsing_attribute_section = true;
+	  }
+	  attribute_section_cont
+	  {
+		lexer.parsing_attribute_section = false;
+		$$ = $3;
+	  }
+	;	
+	
+attribute_section_cont
+	: attribute_target COLON
+	  {
+		current_attr_target = (string) $1;
+		if (current_attr_target == "assembly" || current_attr_target == "module") {
+			Lexer.check_incorrect_doc_comment ();
+		}
+	  }
+	  attribute_list opt_comma CLOSE_BRACKET
+	  {
+		// when attribute target is invalid
+		if (current_attr_target == string.Empty)
+			$$ = new List<Attribute> (0);
+		else
+			$$ = $4;
+		lbag.InsertLocation ($$, 0, GetLocation ($2));
+		lbag.InsertLocation ($$, 0, PopLocation ());
+		lbag.InsertLocation ($$, 0, PopLocation ());
+		if ($5 != null) {
+			lbag.AddLocation ($$, GetLocation ($5), GetLocation ($6));
+		} else {
+			lbag.AddLocation ($$, GetLocation ($6));
+		}
+
+		current_attr_target = null;
+		lexer.parsing_attribute_section = false;
+ 	  }
+	| attribute_list opt_comma CLOSE_BRACKET
+	  {
+		$$ = $1;
+		lbag.InsertLocation ($$, 0, PopLocation ());
+		if ($2 != null) {
+			lbag.AddLocation ($$, GetLocation($2), GetLocation ($3));
+		} else {
+			lbag.AddLocation ($$, GetLocation($3));
+		}
+	  }
+	| IDENTIFIER error
+	  {
+		Error_SyntaxError (yyToken);
+
+		var lt = (LocatedToken) $1;
+		var tne = new SimpleName (lt.Value, null, lt.Location);
+
+		$$ = new List<Attribute> () {
+			new Attribute (null, tne, null, GetLocation ($1), false)
+		};
+	  }
+	| error
+	  {
+ 		CheckAttributeTarget (yyToken, GetTokenName (yyToken), GetLocation ($1)); 
+ 		$$ = null;
+	  }
+	;	
+
+attribute_target
+	: IDENTIFIER
+	  {
+		var lt = (LocatedToken) $1;
+		$$ = CheckAttributeTarget (yyToken, lt.Value, lt.Location);
+		PushLocation (GetLocation ($1));
+	  }
+	| EVENT  { $$ = "event"; PushLocation (GetLocation ($1)); }
+	| RETURN { $$ = "return"; PushLocation (GetLocation ($1)); }
+	;
+
+attribute_list
+	: attribute
+	  {
+		$$ = new List<Attribute> (4) { (Attribute) $1 };
+	  }
+	| attribute_list COMMA attribute
+	  {
+		var attrs = (List<Attribute>) $1;
+		if (attrs != null) {
+			attrs.Add ((Attribute) $3);
+	  		lbag.AddLocation (attrs, GetLocation ($2));
+	  	}
+
+		$$ = attrs;
+	  }
+	;
+
+attribute
+	: attribute_name
+	  {
+		++lexer.parsing_block;
+	  }
+	  opt_attribute_arguments
+	  {
+		--lexer.parsing_block;
+		
+		var tne = (ATypeNameExpression) $1;
+		if (tne.HasTypeArguments) {
+			report.Error (404, tne.Location, "Attributes cannot be generic");
+		}
+		Arguments [] arguments = (Arguments []) $3;
+
+		$$ = new Attribute (current_attr_target, tne, (Arguments[]) $3, GetLocation ($1), lexer.IsEscapedIdentifier (tne));
+		if (arguments != null) {
+			attributeArgumentCommas.Insert (0, savedAttrParenOpenLocation);
+			attributeArgumentCommas.Add (savedAttrParenCloseLocation);
+			lbag.AddLocation ($$, attributeArgumentCommas);
+			attributeArgumentCommas.Clear ();
+		} else if (HadAttributeParens) {
+			lbag.AddLocation ($$, savedAttrParenOpenLocation, savedAttrParenCloseLocation);
+		}
+	  }
+	;
+
+attribute_name
+	: namespace_or_type_expr
+	;
+
+opt_attribute_arguments
+	: /* empty */   { $$ = null; HadAttributeParens = false;  }
+	| OPEN_PARENS attribute_arguments CLOSE_PARENS
+	  {
+		savedAttrParenOpenLocation = GetLocation ($1);
+		savedAttrParenCloseLocation = GetLocation ($3);
+		$$ = $2;
+		HadAttributeParens = true;
+	  }
+	;
+
+
+attribute_arguments
+	: /* empty */ 		{ $$ = null; } 
+	| positional_or_named_argument
+	  {
+	  	Arguments a = new Arguments (4);
+		a.Add ((Argument) $1);
+		$$ = new Arguments [] { a, null };
+	  }
+	| named_attribute_argument
+	  {
+	  	Arguments a = new Arguments (4);
+		a.Add ((Argument) $1);  
+		$$ = new Arguments [] { null, a };
+	  }
+    | attribute_arguments COMMA positional_or_named_argument
+	  {
+		Arguments[] o = (Arguments[]) $1;
+		if (o [1] != null) {
+			report.Error (1016, ((Argument) $3).Expr.Location, "Named attribute arguments must appear after the positional arguments");
+			o [0] = new Arguments (4);
+		}
+		
+		Arguments args = ((Arguments) o [0]);
+		if (args.Count > 0 && !($3 is NamedArgument) && args [args.Count - 1] is NamedArgument)
+			Error_NamedArgumentExpected ((NamedArgument) args [args.Count - 1]);
+		
+		args.Add ((Argument) $3);
+		attributeArgumentCommas.Add (GetLocation ($2));
+	  }
+    | attribute_arguments COMMA named_attribute_argument
+	  {
+		Arguments[] o = (Arguments[]) $1;
+		if (o [1] == null) {
+			o [1] = new Arguments (4);
+		}
+
+		((Arguments) o [1]).Add ((Argument) $3);
+		attributeArgumentCommas.Add (GetLocation ($2));
+	  }
+    ;
+
+positional_or_named_argument
+	: expression
+	  {
+	  	$$ = new Argument ((Expression) $1);
+	  }
+	| named_argument
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	  }
+	;
+
+named_attribute_argument
+	: IDENTIFIER ASSIGN
+	  {
+		++lexer.parsing_block;
+	  }
+	  expression
+	  {
+	  	--lexer.parsing_block;
+	  	var lt = (LocatedToken) $1;
+		$$ = new NamedArgument (lt.Value, lt.Location, (Expression) $4);	  
+		lbag.AddLocation ($$, GetLocation($2));
+	  }
+	;
+	
+named_argument
+	: identifier_inside_body COLON opt_named_modifier expression_or_error
+	  {
+		if (lang_version <= LanguageVersion.V_3)
+			FeatureIsNotAvailable (GetLocation ($1), "named argument");
+			
+		// Avoid boxing in common case (no modifier)
+		var arg_mod = $3 == null ? Argument.AType.None : (Argument.AType) $3;
+			
+		var lt = (LocatedToken) $1;
+		$$ = new NamedArgument (lt.Value, lt.Location, (Expression) $4, arg_mod);
+		lbag.AddLocation ($$, GetLocation($2));
+	  }
+	;
+	
+opt_named_modifier
+	: /* empty */   { $$ = null; }
+	| REF
+	  { 
+		$$ = Argument.AType.Ref;
+	  }
+	| OUT
+	  { 
+		$$ = Argument.AType.Out;
+	  }
+	;
+		  
+opt_class_member_declarations
+	: /* empty */
+	| class_member_declarations
+	;
+
+class_member_declarations
+	: class_member_declaration
+	  {
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+	| class_member_declarations class_member_declaration
+	  {
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+	;
+	
+class_member_declaration
+	: constant_declaration
+	| field_declaration
+	| method_declaration
+	| property_declaration
+	| event_declaration
+	| indexer_declaration
+	| operator_declaration
+	| constructor_declaration
+	| primary_constructor_body
+	| destructor_declaration
+	| type_declaration
+	| attributes_without_members
+	| incomplete_member
+	| error
+	  {
+		report.Error (1519, lexer.Location, "Unexpected symbol `{0}' in class, struct, or interface member declaration",
+			GetSymbolName (yyToken));
+		$$ = null;
+		lexer.parsing_generic_declaration = false;
+	  }	
+	;
+
+primary_constructor_body
+	: OPEN_BRACE
+	  {
+		current_local_parameters = current_type.PrimaryConstructorParameters;
+		if (current_local_parameters == null) {
+			report.Error (9010, GetLocation ($1), "Primary constructor body is not allowed");
+			current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		}
+
+		++lexer.parsing_block;
+		start_block (GetLocation ($1));
+	  }
+	  opt_statement_list block_end
+	  {
+		current_local_parameters = null;
+		var t = current_type as ClassOrStruct;
+		if (t != null) {
+			var b = (ToplevelBlock) $4;
+			if (t.PrimaryConstructorBlock != null) {
+				report.Error (8041, b.StartLocation, "Primary constructor already has a body");
+			} else {
+				t.PrimaryConstructorBlock = b;
+			}
+		}
+	  }
+	;
+
+struct_declaration
+	: opt_attributes
+	  opt_modifiers
+	  opt_partial
+	  STRUCT
+	  {
+	  }
+	  type_declaration_name
+	  { 
+		lexer.ConstraintsParsing = true;
+		valid_param_mod = ParameterModifierType.PrimaryConstructor;
+		push_current_container (new Struct (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1), $3);
+		lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
+	  }
+	  opt_primary_parameters
+	  opt_class_base
+	  opt_type_parameter_constraints_clauses
+	  {
+		valid_param_mod = 0;
+		lexer.ConstraintsParsing = false;
+
+		if ($8 != null)
+			current_type.PrimaryConstructorParameters = (ParametersCompiled) $8;
+
+		if ($10 != null)
+			current_container.SetConstraints ((List<Constraints>) $10);
+
+		if (doc_support)
+			current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
+
+		
+		lexer.parsing_modifiers = true;
+	  }
+	  OPEN_BRACE
+	  {
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	  opt_class_member_declarations CLOSE_BRACE	
+	  {
+		--lexer.parsing_declaration;
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	  opt_semicolon
+	  {
+		if ($16 == null) {
+			lbag.AppendToMember (current_container, GetLocation ($12), GetLocation ($15));
+		} else {
+			lbag.AppendToMember (current_container, GetLocation ($12), GetLocation ($15), GetLocation ($17));
+		}
+		$$ = pop_current_class ();
+	  }
+	| opt_attributes opt_modifiers opt_partial STRUCT error
+	  {
+		Error_SyntaxError (yyToken);
+	  }
+	;
+	
+constant_declaration
+	: opt_attributes 
+	  opt_modifiers
+	  CONST type IDENTIFIER
+	  {
+		var lt = (LocatedToken) $5;
+		var mod = (Modifiers) $2;
+		current_field = new Const (current_type, (FullNamedExpression) $4, mod, new MemberName (lt.Value, lt.Location), (Attributes) $1);
+		current_type.AddMember (current_field);
+		
+		if ((mod & Modifiers.STATIC) != 0) {
+			report.Error (504, current_field.Location, "The constant `{0}' cannot be marked static", current_field.GetSignatureForError ());
+		}
+		
+		$$ = current_field;
+	  }
+	  constant_initializer opt_constant_declarators SEMICOLON
+	  {
+		if (doc_support) {
+			current_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		current_field.Initializer = (ConstInitializer) $7;
+		lbag.AddMember (current_field, GetModifierLocations (), GetLocation ($3), GetLocation ($9));
+		current_field = null;
+	  }
+	| opt_attributes 
+	  opt_modifiers
+	  CONST type error
+	  {
+		Error_SyntaxError (yyToken);
+
+		current_type.AddMember (new Const (current_type, (FullNamedExpression) $4, (Modifiers) $2, MemberName.Null, (Attributes) $1));
+	  }	
+	;
+	
+opt_constant_declarators
+	: /* empty */
+	| constant_declarators
+	;
+	
+constant_declarators
+	: constant_declarator
+	  {
+		current_field.AddDeclarator ((FieldDeclarator) $1);
+	  }
+	| constant_declarators constant_declarator
+	  {
+		current_field.AddDeclarator ((FieldDeclarator) $2);
+	  }
+	;
+	
+constant_declarator
+	: COMMA IDENTIFIER constant_initializer
+	  {
+		var lt = (LocatedToken) $2;
+	  	$$ = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (ConstInitializer) $3);
+	  	lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	;		
+
+constant_initializer
+	: ASSIGN
+	  {
+		++lexer.parsing_block;
+	  }
+	  constant_initializer_expr
+	  {
+		--lexer.parsing_block;
+		$$ = new ConstInitializer (current_field, (Expression) $3, GetLocation ($1));
+	  	lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	| error
+	  {
+		report.Error (145, lexer.Location, "A const field requires a value to be provided");
+		$$ = null;
+	  }	  
+	;
+	
+constant_initializer_expr
+	: constant_expression
+	| array_initializer
+	;
+
+field_declaration
+	: opt_attributes
+	  opt_modifiers
+	  member_type IDENTIFIER
+	  {
+	  	lexer.parsing_generic_declaration = false;
+
+		FullNamedExpression type = (FullNamedExpression) $3;
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (670, GetLocation ($3), "Fields cannot have void type");
+			
+		var lt = (LocatedToken) $4;
+		current_field = new Field (current_type, type, (Modifiers) $2, new MemberName (lt.Value, lt.Location), (Attributes) $1);
+		current_type.AddField (current_field);
+		$$ = current_field;
+	  }
+	  opt_field_initializer
+	  opt_field_declarators
+	  SEMICOLON
+	  { 
+		if (doc_support) {
+			current_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+			
+		lbag.AddMember (current_field, GetModifierLocations (), GetLocation ($8));
+		$$ = current_field;
+		current_field = null;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  FIXED simple_type IDENTIFIER
+	  { 
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($3), "fixed size buffers");
+
+		var lt = (LocatedToken) $5;
+		current_field = new FixedField (current_type, (FullNamedExpression) $4, (Modifiers) $2,
+			new MemberName (lt.Value, lt.Location), (Attributes) $1);
+			
+		current_type.AddField (current_field);
+	  }
+	  fixed_field_size opt_fixed_field_declarators SEMICOLON
+	  {
+		if (doc_support) {
+			current_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+	    }
+
+		current_field.Initializer = (ConstInitializer) $7;	    
+		lbag.AddMember (current_field, GetModifierLocations (), GetLocation ($3), GetLocation ($9));
+		$$ = current_field;
+	    current_field = null;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  FIXED simple_type error
+	  SEMICOLON
+	  {
+		report.Error (1641, GetLocation ($5), "A fixed size buffer field must have the array size specifier after the field name");
+	  }
+	;
+	
+opt_field_initializer
+	: /* empty */
+	| ASSIGN
+	  {
+	  	++lexer.parsing_block;
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  	start_block (GetLocation ($1));
+	  }
+	  variable_initializer
+	  {
+	  	--lexer.parsing_block;
+		current_field.Initializer = (Expression) $3;
+		lbag.AppendToMember (current_field, GetLocation ($1));
+		end_block (lexer.Location);
+		current_local_parameters = null;
+	  }
+	;
+	
+opt_field_declarators
+	: /* empty */
+	| field_declarators
+	;
+	
+field_declarators
+	: field_declarator
+	  {
+		current_field.AddDeclarator ((FieldDeclarator) $1);
+	  }
+	| field_declarators field_declarator
+	  {
+		current_field.AddDeclarator ((FieldDeclarator) $2);
+	  }
+	;
+	
+field_declarator
+	: COMMA IDENTIFIER
+	  {
+		var lt = (LocatedToken) $2;
+	  	$$ = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), null);
+	  	lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	| COMMA IDENTIFIER ASSIGN
+	  {
+		++lexer.parsing_block;
+	  }
+	  variable_initializer
+	  {
+		--lexer.parsing_block;
+		var lt = (LocatedToken) $2;	  
+	  	$$ = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (Expression) $5);
+	  	lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3));
+	  }
+	;	
+
+opt_fixed_field_declarators
+	: /* empty */
+	| fixed_field_declarators
+	;
+	
+fixed_field_declarators
+	: fixed_field_declarator
+	  {
+		current_field.AddDeclarator ((FieldDeclarator) $1);
+	  }
+	| fixed_field_declarators fixed_field_declarator
+	  {
+		current_field.AddDeclarator ((FieldDeclarator) $2);
+	  }
+	;
+	
+fixed_field_declarator
+	: COMMA IDENTIFIER fixed_field_size
+	  {
+		var lt = (LocatedToken) $2;	  
+		$$ = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (ConstInitializer) $3);
+		lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	;
+
+fixed_field_size
+	: OPEN_BRACKET
+	  {
+		++lexer.parsing_block;
+	  }
+	  expression CLOSE_BRACKET
+	  {
+		--lexer.parsing_block;
+		$$ = new ConstInitializer (current_field, (Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	| OPEN_BRACKET error
+	  {
+		report.Error (443, lexer.Location, "Value or constant expected");
+		$$ = null;
+	  }	  
+	;
+
+variable_initializer
+	: expression
+	| array_initializer
+	| error
+	  {
+		// It has to be here for the parent to safely restore artificial block
+	  	Error_SyntaxError (yyToken);
+	  	$$ = null;
+	  }
+	;
+
+method_declaration
+	: method_header
+	  {
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+
+		// Was added earlier in the case of body being eof for full ast
+	  }
+	  method_body_expression_block
+	  {
+		Method method = (Method) $1;
+		method.Block = (ToplevelBlock) $3;
+		async_block = false;
+		
+		if (method.Block == null) {
+			lbag.AppendToMember (method, savedLocation); // semicolon
+			method.ParameterInfo.CheckParameters (method);
+
+			if ((method.ModFlags & Modifiers.ASYNC) != 0) {
+				report.Error (1994, method.Location, "`{0}': The async modifier can only be used with methods that have a body",
+					method.GetSignatureForError ());
+			}
+		} else {
+			if (current_container.Kind == MemberKind.Interface) {
+				report.Error (531, method.Location, "`{0}': interface members cannot have a definition",
+					method.GetSignatureForError ());
+			}
+		}
+
+		current_local_parameters = null;
+
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	;
+
+method_header
+	: opt_attributes
+	  opt_modifiers
+	  member_type
+	  method_declaration_name OPEN_PARENS
+	  {
+		valid_param_mod = ParameterModifierType.All;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+		MemberName name = (MemberName) $4;
+		current_local_parameters = (ParametersCompiled) $7;
+
+		var method = Method.Create (current_type, (FullNamedExpression) $3, (Modifiers) $2,
+				     name, current_local_parameters, (Attributes) $1);
+
+		current_type.AddMember (method);
+
+		async_block = (method.ModFlags & Modifiers.ASYNC) != 0;
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		lbag.AddMember (method, GetModifierLocations (), GetLocation ($5), GetLocation ($8));
+		$$ = method;
+
+		lexer.ConstraintsParsing = true;
+	  }
+	  opt_type_parameter_constraints_clauses
+	  {
+		lexer.ConstraintsParsing = false;
+
+		if ($10 != null) {
+			var method = (Method) $9;
+			method.SetConstraints ((List<Constraints>) $10);
+		}
+
+		$$ = $9;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  PARTIAL
+	  VOID
+	  {
+		lexer.parsing_generic_declaration = true;
+	  }
+	  method_declaration_name
+	  OPEN_PARENS
+	  {
+		lexer.parsing_generic_declaration = false;
+	  	valid_param_mod = ParameterModifierType.All;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS 
+	  {
+		lexer.ConstraintsParsing = true;
+	  }
+	  opt_type_parameter_constraints_clauses
+	  {
+		lexer.ConstraintsParsing = false;
+		valid_param_mod = 0;
+
+		MemberName name = (MemberName) $6;
+		current_local_parameters = (ParametersCompiled) $9;
+
+		var modifiers = (Modifiers) $2;
+		modifiers |= Modifiers.PARTIAL;
+
+		var method = Method.Create (current_type, new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($4)),
+				     modifiers, name, current_local_parameters, (Attributes) $1);
+
+		current_type.AddMember (method);
+
+		async_block = (method.ModFlags & Modifiers.ASYNC) != 0;
+
+		if ($12 != null)
+			method.SetConstraints ((List<Constraints>) $12);
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		StoreModifierLocation (Modifiers.PARTIAL, GetLocation ($3));
+		lbag.AddMember (method, GetModifierLocations (), GetLocation ($7), GetLocation ($10));
+		$$ = method;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  member_type
+	  modifiers method_declaration_name OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS
+	  {
+		MemberName name = (MemberName) $5;
+		report.Error (1585, name.Location, 
+			"Member modifier `{0}' must precede the member type and name", ModifiersExtensions.Name ((Modifiers) $4));
+
+		var method = Method.Create (current_type, (FullNamedExpression) $3,
+					    0, name, (ParametersCompiled) $7, (Attributes) $1);
+
+		current_type.AddMember (method);
+
+		current_local_parameters = (ParametersCompiled) $7;
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		$$ = method;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  member_type
+	  method_declaration_name error
+	  {
+		Error_SyntaxError (yyToken);
+		current_local_parameters = ParametersCompiled.Undefined;
+
+		MemberName name = (MemberName) $4;
+		var method = Method.Create (current_type, (FullNamedExpression) $3, (Modifiers) $2,
+									name, current_local_parameters, (Attributes) $1);
+
+		current_type.AddMember (method);
+
+		if (doc_support)
+			method.DocComment = Lexer.consume_doc_comment ();
+
+		$$ = method;
+	  }
+	;
+
+method_body_expression_block
+	: method_body
+	| expression_block
+	;
+
+method_body
+	: block
+	| SEMICOLON		{ savedLocation = GetLocation ($1); $$ = null; }
+	;
+
+expression_block
+	: ARROW
+	 {
+		if (lang_version < LanguageVersion.V_6) {
+			FeatureIsNotAvailable (GetLocation ($1), "expression bodied members");
+		}
+
+		++lexer.parsing_block;
+		start_block (GetLocation ($1));
+	 }
+	 expression SEMICOLON
+	 {
+		lexer.parsing_block = 0;
+		current_block.AddStatement (new ContextualReturn ((Expression) $3));
+		var b = end_block (GetLocation ($4));
+		b.IsCompilerGenerated = true;
+		$$ = b;
+	 }
+	;
+
+opt_formal_parameter_list
+	: /* empty */			{ $$ = ParametersCompiled.EmptyReadOnlyParameters; }
+	| formal_parameter_list
+	;
+	
+formal_parameter_list
+	: fixed_parameters
+	  {
+		var pars_list = (List<Parameter>) $1;
+	  	$$ = new ParametersCompiled (pars_list.ToArray ());
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  } 
+	| fixed_parameters COMMA parameter_array
+	  {
+		var pars_list = (List<Parameter>) $1;
+		pars_list.Add ((Parameter) $3);
+		parameterListCommas.Add (GetLocation ($2));
+		
+		$$ = new ParametersCompiled (pars_list.ToArray ()); 
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  }
+	| fixed_parameters COMMA arglist_modifier
+	  {
+		var pars_list = (List<Parameter>) $1;
+		pars_list.Add (new ArglistParameter (GetLocation ($3)));
+		parameterListCommas.Add (GetLocation ($2));
+		
+		$$ = new ParametersCompiled (pars_list.ToArray (), true);
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  }
+	| parameter_array COMMA error
+	  {
+		if ($1 != null)
+			report.Error (231, ((Parameter) $1).Location, "A params parameter must be the last parameter in a formal parameter list");
+
+		$$ = new ParametersCompiled (new Parameter[] { (Parameter) $1 } );			
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  }
+	| fixed_parameters COMMA parameter_array COMMA error
+	  {
+		if ($3 != null)
+			report.Error (231, ((Parameter) $3).Location, "A params parameter must be the last parameter in a formal parameter list");
+
+		var pars_list = (List<Parameter>) $1;
+		pars_list.Add (new ArglistParameter (GetLocation ($3)));
+		parameterListCommas.Add (GetLocation ($2));
+		parameterListCommas.Add (GetLocation ($4));
+		
+		$$ = new ParametersCompiled (pars_list.ToArray (), true);
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  }
+	| arglist_modifier COMMA error
+	  {
+		report.Error (257, GetLocation ($1), "An __arglist parameter must be the last parameter in a formal parameter list");
+
+		$$ = new ParametersCompiled (new Parameter [] { new ArglistParameter (GetLocation ($1)) }, true);
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  }
+	| fixed_parameters COMMA ARGLIST COMMA error 
+	  {
+		report.Error (257, GetLocation ($3), "An __arglist parameter must be the last parameter in a formal parameter list");
+
+		var pars_list = (List<Parameter>) $1;
+		pars_list.Add (new ArglistParameter (GetLocation ($3)));
+		parameterListCommas.Add (GetLocation ($2));
+		parameterListCommas.Add (GetLocation ($4));
+
+		$$ = new ParametersCompiled (pars_list.ToArray (), true);
+	  	lbag.AddLocation ($$, parameterListCommas);
+	  }
+	| parameter_array 
+	  {
+		$$ = new ParametersCompiled (new Parameter[] { (Parameter) $1 } );
+	  }
+	| arglist_modifier
+	  {
+		$$ = new ParametersCompiled (new Parameter [] { new ArglistParameter (GetLocation ($1)) }, true);
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = ParametersCompiled.EmptyReadOnlyParameters;
+	  }
+	;
+
+fixed_parameters
+	: fixed_parameter	
+	  {
+		parameters_bucket.Clear ();
+		Parameter p = (Parameter) $1;
+		parameters_bucket.Add (p);
+		parameterListCommas.Clear ();
+		default_parameter_used = p.HasDefaultValue;
+		$$ = parameters_bucket;
+	  }
+	| fixed_parameters COMMA fixed_parameter
+	  {
+		var pars = (List<Parameter>) $1;
+		Parameter p = (Parameter) $3;
+		if (p != null) {
+			if (p.HasExtensionMethodModifier)
+				report.Error (1100, p.Location, "The parameter modifier `this' can only be used on the first parameter");
+			else if (!p.HasDefaultValue && default_parameter_used)
+				report.Error (1737, p.Location, "Optional parameter cannot precede required parameters");
+
+			default_parameter_used |= p.HasDefaultValue;
+			pars.Add (p);
+			
+			parameterListCommas.Add (GetLocation ($2));
+		}
+		
+		$$ = $1;
+	  }
+	;
+
+fixed_parameter
+	: opt_attributes
+	  opt_parameter_modifier
+	  parameter_type
+	  identifier_inside_body
+	  {
+		var lt = (LocatedToken) $4;
+		$$ = new Parameter ((FullNamedExpression) $3, lt.Value, (Parameter.Modifier) $2, (Attributes) $1, lt.Location);
+		lbag.AddLocation ($$, parameterModifierLocation);
+	  }
+	| opt_attributes
+	  opt_parameter_modifier
+	  parameter_type
+	  identifier_inside_body OPEN_BRACKET CLOSE_BRACKET
+	  {
+		var lt = (LocatedToken) $4;
+		report.Error (1552, lt.Location, "Array type specifier, [], must appear before parameter name");
+		$$ = new Parameter ((FullNamedExpression) $3, lt.Value, (Parameter.Modifier) $2, (Attributes) $1, lt.Location);
+		lbag.AddLocation ($$, parameterModifierLocation);
+	  }
+	| attribute_sections error
+	  {
+		Error_SyntaxError (yyToken);
+	  	Location l = GetLocation ($2);
+		$$ = new Parameter (null, null, Parameter.Modifier.NONE, (Attributes) $1, l);
+	  }
+	| opt_attributes
+	  opt_parameter_modifier
+	  parameter_type
+	  error
+	  {
+		Error_SyntaxError (yyToken);
+	  	Location l = GetLocation ($4);
+		$$ = new Parameter ((FullNamedExpression) $3, null, (Parameter.Modifier) $2, (Attributes) $1, l);
+		lbag.AddLocation ($$, parameterModifierLocation);
+	  }
+	| opt_attributes
+	  opt_parameter_modifier
+	  parameter_type
+	  identifier_inside_body
+	  ASSIGN
+	  {
+	  	++lexer.parsing_block;
+	  }
+	  constant_expression
+	  {
+	  	--lexer.parsing_block;
+		if (lang_version <= LanguageVersion.V_3) {
+			FeatureIsNotAvailable (GetLocation ($5), "optional parameter");
+		}
+		
+		Parameter.Modifier mod = (Parameter.Modifier) $2;
+		if (mod != Parameter.Modifier.NONE) {
+			switch (mod) {
+			case Parameter.Modifier.REF:
+			case Parameter.Modifier.OUT:
+				report.Error (1741, GetLocation ($2), "Cannot specify a default value for the `{0}' parameter",
+					Parameter.GetModifierSignature (mod));
+				break;
+				
+			case Parameter.Modifier.This:
+				report.Error (1743, GetLocation ($2), "Cannot specify a default value for the `{0}' parameter",
+					Parameter.GetModifierSignature (mod));
+				break;
+			default:
+				throw new NotImplementedException (mod.ToString ());
+			}
+				
+			mod = Parameter.Modifier.NONE;
+		}
+		
+		if ((valid_param_mod & ParameterModifierType.DefaultValue) == 0)
+			report.Error (1065, GetLocation ($5), "Optional parameter is not valid in this context");
+		
+		var lt = (LocatedToken) $4;
+		$$ = new Parameter ((FullNamedExpression) $3, lt.Value, mod, (Attributes) $1, lt.Location);
+		lbag.AddLocation ($$, parameterModifierLocation, GetLocation ($5)); // parameterModifierLocation should be ignored when mod == NONE
+		
+		if ($7 != null)
+			((Parameter) $$).DefaultValue = new DefaultParameterValueExpression ((Expression) $7);
+	  }
+	;
+
+opt_parameter_modifier
+	: /* empty */		{ $$ = Parameter.Modifier.NONE; }
+	| parameter_modifiers
+	;
+
+parameter_modifiers
+	: parameter_modifier
+	  {
+		$$ = $1;
+	  }
+	| parameter_modifiers parameter_modifier
+	  {
+		Parameter.Modifier p2 = (Parameter.Modifier)$2;
+  		Parameter.Modifier mod = (Parameter.Modifier)$1 | p2;
+  		if (((Parameter.Modifier)$1 & p2) == p2) {
+  			Error_DuplicateParameterModifier (lexer.Location, p2);
+  		} else {
+	  		switch (mod & ~Parameter.Modifier.This) {
+  				case Parameter.Modifier.REF:
+					report.Error (1101, lexer.Location, "The parameter modifiers `this' and `ref' cannot be used altogether");
+  					break;
+   				case Parameter.Modifier.OUT:
+					report.Error (1102, lexer.Location, "The parameter modifiers `this' and `out' cannot be used altogether");
+  					break;
+  				default:
+ 					report.Error (1108, lexer.Location, "A parameter cannot have specified more than one modifier");
+ 					break;
+ 			}
+  		}
+  		$$ = mod;
+	  }
+	;
+
+parameter_modifier
+	: REF
+	  {
+	  	if ((valid_param_mod & ParameterModifierType.Ref) == 0)
+	  		Error_ParameterModifierNotValid ("ref", GetLocation ($1));
+		parameterModifierLocation = GetLocation ($1);
+	  	$$ = Parameter.Modifier.REF;
+	  }
+	| OUT
+	  {
+	  	if ((valid_param_mod & ParameterModifierType.Out) == 0)
+	  		Error_ParameterModifierNotValid ("out", GetLocation ($1));
+		parameterModifierLocation = GetLocation ($1);
+	  	$$ = Parameter.Modifier.OUT;
+	  }
+	| THIS
+	  {
+		if ((valid_param_mod & ParameterModifierType.This) == 0)
+	  		Error_ParameterModifierNotValid ("this", GetLocation ($1));
+
+	  	if (lang_version <= LanguageVersion.ISO_2)
+	  		FeatureIsNotAvailable (GetLocation ($1), "extension methods");
+		parameterModifierLocation = GetLocation ($1);
+		$$ = Parameter.Modifier.This;
+	  }
+	;
+
+parameter_array
+	: opt_attributes params_modifier type IDENTIFIER
+	  {
+		var lt = (LocatedToken) $4;
+		$$ = new ParamsParameter ((FullNamedExpression) $3, lt.Value, (Attributes) $1, lt.Location);
+		lbag.AddLocation ($$, savedLocation);
+	  }
+	| opt_attributes params_modifier type IDENTIFIER ASSIGN constant_expression
+	  {
+		report.Error (1751, GetLocation ($2), "Cannot specify a default value for a parameter array");
+		
+		var lt = (LocatedToken) $4;
+		$$ = new ParamsParameter ((FullNamedExpression) $3, lt.Value, (Attributes) $1, lt.Location);		
+		lbag.AddLocation ($$, savedLocation);
+	  }
+	| opt_attributes params_modifier type error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new ParamsParameter ((FullNamedExpression) $3, null, (Attributes) $1, Location.Null);
+	  }
+	;
+	
+params_modifier
+	: PARAMS
+	  {
+		if ((valid_param_mod & ParameterModifierType.Params) == 0)
+			report.Error (1670, (GetLocation ($1)), "The `params' modifier is not allowed in current context");
+		savedLocation = GetLocation ($1);
+	  }
+	| PARAMS parameter_modifier
+	  {
+		Parameter.Modifier mod = (Parameter.Modifier)$2;
+		if ((mod & Parameter.Modifier.This) != 0) {
+			report.Error (1104, GetLocation ($1), "The parameter modifiers `this' and `params' cannot be used altogether");
+		} else {
+			report.Error (1611, GetLocation ($1), "The params parameter cannot be declared as ref or out");
+		}	  
+		savedLocation = GetLocation ($1);
+	  }
+	| PARAMS params_modifier
+	  {
+		Error_DuplicateParameterModifier (GetLocation ($1), Parameter.Modifier.PARAMS);
+	  }
+	;
+	
+arglist_modifier
+	: ARGLIST
+	  {
+	  	if ((valid_param_mod & ParameterModifierType.Arglist) == 0)
+	  		report.Error (1669, GetLocation ($1), "__arglist is not valid in this context");
+	  }
+	;
+
+property_declaration
+	: opt_attributes
+	  opt_modifiers
+	  member_type
+	  member_declaration_name
+	  {
+		lexer.parsing_generic_declaration = false;
+		if (doc_support)
+			tmpComment = Lexer.consume_doc_comment ();
+	  }
+	  OPEN_BRACE
+	  {
+		var type = (FullNamedExpression) $3;
+		current_property = new Property (current_type, type, (Modifiers) $2,
+			(MemberName) $4, (Attributes) $1);
+			
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (547, GetLocation ($3), "`{0}': property or indexer cannot have void type", current_property.GetSignatureForError ());					
+			
+		current_type.AddMember (current_property);
+		lbag.AddMember (current_property, GetModifierLocations (), GetLocation ($6));
+		
+		lexer.PropertyParsing = true;
+	  }
+	  accessor_declarations 
+	  {
+		lexer.PropertyParsing = false;
+		
+		if (doc_support)
+			current_property.DocComment = ConsumeStoredComment ();				
+	  }
+	  CLOSE_BRACE
+	  {
+		lbag.AppendToMember (current_property, GetLocation ($10));
+		lexer.parsing_modifiers = true;
+	  }
+	  opt_property_initializer
+	  {
+		current_property = null;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  member_type
+	  member_declaration_name
+	  {
+		lexer.parsing_generic_declaration = false;
+		if (doc_support)
+			tmpComment = Lexer.consume_doc_comment ();
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  }
+	  expression_block
+	  {
+		var type = (FullNamedExpression) $3;
+		var property = new Property (current_type, type, (Modifiers) $2,
+			(MemberName) $4, (Attributes) $1);
+
+		property.Get = new Property.GetMethod (property, Modifiers.COMPILER_GENERATED, null, property.Location);
+		property.Get.Block = (ToplevelBlock) $6;
+
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (531, property.Get.Block.StartLocation,
+				"`{0}': interface members cannot have a definition", property.GetSignatureForError ());
+		}
+
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (547, GetLocation ($3), "`{0}': property or indexer cannot have void type", property.GetSignatureForError ());
+
+		current_type.AddMember (property);
+
+		current_local_parameters = null;
+	  }
+	;
+
+opt_property_initializer
+	: /* empty */
+	| ASSIGN
+	  {
+		++lexer.parsing_block;
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		start_block (GetLocation ($1));
+	  }
+	  property_initializer SEMICOLON
+	  {
+		--lexer.parsing_block;
+		((Property)current_property).Initializer = (Expression) $3;
+		lbag.AppendToMember (current_property, GetLocation ($1), GetLocation ($4));
+		end_block (GetLocation ($4));
+		current_local_parameters = null;
+	  }
+	;
+
+property_initializer
+	: expression
+	| array_initializer
+	;
+
+indexer_declaration
+	: opt_attributes opt_modifiers
+	  member_type indexer_declaration_name OPEN_BRACKET
+	  {
+	  	valid_param_mod = ParameterModifierType.Params | ParameterModifierType.DefaultValue;
+	  }
+	  opt_formal_parameter_list CLOSE_BRACKET 
+	  {
+		valid_param_mod = 0;
+		var type = (FullNamedExpression) $3;
+		Indexer indexer = new Indexer (current_type, type, (MemberName) $4, (Modifiers) $2, (ParametersCompiled) $7, (Attributes) $1);
+			
+		current_property = indexer;
+
+  		current_type.AddIndexer (indexer);
+		lbag.AddMember (current_property, GetModifierLocations (), GetLocation ($5), GetLocation ($8));
+  		
+		if (type.Type != null && type.Type.Kind == MemberKind.Void)
+			report.Error (620, GetLocation ($3), "`{0}': indexer return type cannot be `void'", indexer.GetSignatureForError ());  		
+
+		if (indexer.ParameterInfo.IsEmpty) {
+			report.Error (1551, GetLocation ($5), "Indexers must have at least one parameter");
+		}
+
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+
+		lexer.PropertyParsing = true;
+		current_local_parameters = (ParametersCompiled) $7;
+	  }
+	  indexer_body
+	  {
+ 		lexer.PropertyParsing = false;
+		current_local_parameters = null;
+
+		if (current_property.AccessorFirst != null && current_property.AccessorFirst.Block == null)
+			((Indexer) current_property).ParameterInfo.CheckParameters (current_property);
+	  
+		if (doc_support)
+			current_property.DocComment = ConsumeStoredComment ();
+			
+		current_property = null;		
+	  }
+	;
+
+indexer_body
+	: OPEN_BRACE accessor_declarations CLOSE_BRACE
+	  {
+		lbag.AppendToMember (current_property, GetLocation ($1), GetLocation ($3));
+	  }
+	| expression_block
+	  {
+		current_property.Get = new Indexer.GetIndexerMethod (current_property, Modifiers.COMPILER_GENERATED, current_local_parameters, null, current_property.Location);
+		current_property.Get.Block = (ToplevelBlock) $1;
+	  }
+	;
+
+accessor_declarations
+	: get_accessor_declaration
+	| get_accessor_declaration accessor_declarations
+	| set_accessor_declaration
+	| set_accessor_declaration accessor_declarations
+	| error
+	  {
+	  	if (yyToken == Token.CLOSE_BRACE) {
+	  		report.Error (548, lexer.Location, "`{0}': property or indexer must have at least one accessor", current_property.GetSignatureForError ());
+		} else {
+			if (yyToken == Token.SEMICOLON)
+				report.Error (1597, lexer.Location, "Semicolon after method or accessor block is not valid");
+			else
+				report.Error (1014, GetLocation ($1), "A get or set accessor expected");
+		}
+	  }
+	;
+
+get_accessor_declaration
+	: opt_attributes opt_modifiers GET
+	  {
+		if ($2 != ModifierNone && lang_version == LanguageVersion.ISO_1) {
+			FeatureIsNotAvailable (GetLocation ($2), "access modifiers on properties");
+		}
+	  
+		if (current_property.Get != null) {
+			report.Error (1007, GetLocation ($3), "Property accessor already defined");
+		}
+		
+		if (current_property is Indexer) {
+			current_property.Get = new Indexer.GetIndexerMethod (current_property, (Modifiers) $2, ((Indexer)current_property).ParameterInfo.Clone (),
+				(Attributes) $1, GetLocation ($3));
+		} else {
+			current_property.Get = new Property.GetMethod (current_property,
+				(Modifiers) $2, (Attributes) $1, GetLocation ($3));
+		}	
+	  
+		current_local_parameters = current_property.Get.ParameterInfo;	  
+		lexer.PropertyParsing = false;
+	  }
+	  accessor_body
+	  {
+	  	if ($5 != null) {
+	  		current_property.Get.Block = (ToplevelBlock) $5;			
+	  	
+			if (current_container.Kind == MemberKind.Interface) {
+				report.Error (531, current_property.Get.Block.StartLocation,
+					"`{0}': interface members cannot have a definition", current_property.Get.GetSignatureForError ());
+			}
+			lbag.AddMember (current_property.Get, GetModifierLocations ());
+		} else {
+			lbag.AddMember (current_property.Get, GetModifierLocations (), savedLocation);
+		}
+	  
+		current_local_parameters = null;
+		lexer.PropertyParsing = true;
+
+		if (doc_support)
+			if (Lexer.doc_state == XmlCommentState.Error)
+				Lexer.doc_state = XmlCommentState.NotAllowed;
+	  }
+	;
+
+set_accessor_declaration
+	: opt_attributes opt_modifiers SET 
+	  {
+		if ($2 != ModifierNone && lang_version == LanguageVersion.ISO_1) {
+			FeatureIsNotAvailable (GetLocation ($2), "access modifiers on properties");
+		}
+		
+		if (current_property.Set != null) {
+			report.Error (1007, GetLocation ($3), "Property accessor already defined");
+		}
+	  
+		if (current_property is Indexer) {
+			current_property.Set = new Indexer.SetIndexerMethod (current_property, (Modifiers) $2,
+				ParametersCompiled.MergeGenerated (compiler,
+				((Indexer)current_property).ParameterInfo, true, new Parameter (
+					current_property.TypeExpression, "value", Parameter.Modifier.NONE, null, GetLocation ($3)),
+					null),
+				(Attributes) $1, GetLocation ($3));
+		} else {
+			current_property.Set = new Property.SetMethod (current_property, (Modifiers) $2, 
+				ParametersCompiled.CreateImplicitParameter (current_property.TypeExpression, GetLocation ($3)),
+				(Attributes) $1, GetLocation ($3));
+		}
+		
+		current_local_parameters = current_property.Set.ParameterInfo;	
+		lexer.PropertyParsing = false;
+	  }
+	  accessor_body
+	  {
+		if ($5 != null) {		
+			current_property.Set.Block = (ToplevelBlock) $5;
+		
+			if (current_container.Kind == MemberKind.Interface) {
+				report.Error (531, current_property.Set.Block.StartLocation,
+					"`{0}': interface members cannot have a definition", current_property.Set.GetSignatureForError ());
+			}
+			lbag.AddMember (current_property.Set, GetModifierLocations ());
+		} else {
+			lbag.AddMember (current_property.Set, GetModifierLocations (), savedLocation);
+		}
+		
+		current_local_parameters = null;
+		lexer.PropertyParsing = true;
+
+		if (doc_support
+			&& Lexer.doc_state == XmlCommentState.Error)
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+	  }
+	;
+
+accessor_body
+	: block 
+	| SEMICOLON
+	  {
+		savedLocation = GetLocation ($1);
+	  	$$ = null;
+	  }
+	| error
+	  {
+	  	Error_SyntaxError (1043, yyToken, "Invalid accessor body");
+	  	$$ = null;
+	  }
+	;
+
+interface_declaration
+	: opt_attributes
+	  opt_modifiers
+	  opt_partial
+	  INTERFACE
+	  {
+	  }
+	  type_declaration_name
+	  {
+		lexer.ConstraintsParsing = true;
+		push_current_container (new Interface (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1), $3);
+		lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));		
+	  }
+	  opt_class_base
+	  opt_type_parameter_constraints_clauses
+	  {
+		lexer.ConstraintsParsing = false;
+
+		if ($9 != null)
+			current_container.SetConstraints ((List<Constraints>) $9);
+
+		if (doc_support) {
+			current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		lexer.parsing_modifiers = true;
+	  }
+	  OPEN_BRACE opt_interface_member_declarations CLOSE_BRACE
+	  {
+		--lexer.parsing_declaration;	  
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	  opt_semicolon 
+	  {
+		if ($15 == null) {
+			lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13));
+		} else {
+			lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13), GetLocation ($15));
+		}
+		$$ = pop_current_class ();
+	  }
+	| opt_attributes opt_modifiers opt_partial INTERFACE error
+	  {
+		Error_SyntaxError (yyToken);	  
+	  }
+	;
+
+opt_interface_member_declarations
+	: /* empty */
+	| interface_member_declarations
+	;
+
+interface_member_declarations
+	: interface_member_declaration
+	  {
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+	| interface_member_declarations interface_member_declaration
+	  {
+		lexer.parsing_modifiers = true;
+		lexer.parsing_block = 0;
+	  }
+	;
+
+interface_member_declaration
+	: constant_declaration
+	  {
+		report.Error (525, GetLocation ($1), "Interfaces cannot contain fields or constants");
+	  }
+	| field_declaration
+	  {
+		report.Error (525, GetLocation ($1), "Interfaces cannot contain fields or constants");
+	  }
+	| method_declaration
+	| property_declaration
+	| event_declaration
+	| indexer_declaration
+	| operator_declaration
+	  {
+	  	report.Error (567, GetLocation ($1), "Interfaces cannot contain operators");
+	  }
+	| constructor_declaration
+	  {
+	  	report.Error (526, GetLocation ($1), "Interfaces cannot contain contructors");
+	  }
+	| type_declaration
+	  {
+	  	report.Error (524, GetLocation ($1), "Interfaces cannot declare classes, structs, interfaces, delegates, or enumerations");
+	  }
+	;
+
+operator_declaration
+	: opt_attributes opt_modifiers operator_declarator 
+	  {
+	  }
+	  method_body_expression_block
+	  {
+		OperatorDeclaration decl = (OperatorDeclaration) $3;
+		if (decl != null) {
+			Operator op = new Operator (
+				current_type, decl.optype, decl.ret_type, (Modifiers) $2, 
+				current_local_parameters,
+				(ToplevelBlock) $5, (Attributes) $1, decl.location);
+				
+			if (op.Block == null)
+				op.ParameterInfo.CheckParameters (op);
+
+			if (doc_support) {
+				op.DocComment = tmpComment;
+				Lexer.doc_state = XmlCommentState.Allowed;
+			}
+
+			// Note again, checking is done in semantic analysis
+			current_type.AddOperator (op);
+
+			lbag.AddMember (op, GetModifierLocations (), lbag.GetLocations (decl));
+			if ($5 == null) { // Semicolon
+				lbag.AddLocation (op, savedLocation); 
+			}
+		}
+		
+		current_local_parameters = null;
+	  }
+	;
+
+operator_type
+	: type_expression_or_array
+	| VOID
+	  {
+		report.Error (590, GetLocation ($1), "User-defined operators cannot return void");
+		$$ = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1));
+	  }
+	;
+
+operator_declarator
+	: operator_type OPERATOR overloadable_operator OPEN_PARENS
+	  {
+		valid_param_mod = ParameterModifierType.DefaultValue;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+
+		Location loc = GetLocation ($2);
+		Operator.OpType op = (Operator.OpType) $3;
+		current_local_parameters = (ParametersCompiled)$6;
+		
+		int p_count = current_local_parameters.Count;
+		if (p_count == 1) {
+			if (op == Operator.OpType.Addition)
+				op = Operator.OpType.UnaryPlus;
+			else if (op == Operator.OpType.Subtraction)
+				op = Operator.OpType.UnaryNegation;
+		}
+		
+		if (IsUnaryOperator (op)) {
+			if (p_count == 2) {
+				report.Error (1020, loc, "Overloadable binary operator expected");
+			} else if (p_count != 1) {
+				report.Error (1535, loc, "Overloaded unary operator `{0}' takes one parameter",
+					Operator.GetName (op));
+			}
+		} else {
+			if (p_count == 1) {
+				report.Error (1019, loc, "Overloadable unary operator expected");
+			} else if (p_count != 2) {
+				report.Error (1534, loc, "Overloaded binary operator `{0}' takes two parameters",
+					Operator.GetName (op));
+			}
+		}
+		
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+
+		$$ = new OperatorDeclaration (op, (FullNamedExpression) $1, loc);
+		lbag.AddLocation ($$, GetLocation ($2), savedOperatorLocation, GetLocation ($4), GetLocation ($7));
+	  }
+	| conversion_operator_declarator
+	;
+
+overloadable_operator
+// Unary operators:
+	: BANG   { $$ = Operator.OpType.LogicalNot; savedOperatorLocation = GetLocation ($1); }
+        | TILDE  { $$ = Operator.OpType.OnesComplement; savedOperatorLocation = GetLocation ($1); }  
+        | OP_INC { $$ = Operator.OpType.Increment; savedOperatorLocation = GetLocation ($1); }
+        | OP_DEC { $$ = Operator.OpType.Decrement; savedOperatorLocation = GetLocation ($1); }
+        | TRUE   { $$ = Operator.OpType.True; savedOperatorLocation = GetLocation ($1); }
+        | FALSE  { $$ = Operator.OpType.False; savedOperatorLocation = GetLocation ($1); }
+// Unary and binary:
+        | PLUS { $$ = Operator.OpType.Addition; savedOperatorLocation = GetLocation ($1); }
+        | MINUS { $$ = Operator.OpType.Subtraction; savedOperatorLocation = GetLocation ($1); }
+// Binary:
+        | STAR { $$ = Operator.OpType.Multiply; savedOperatorLocation = GetLocation ($1); }
+        | DIV {  $$ = Operator.OpType.Division; savedOperatorLocation = GetLocation ($1); }
+        | PERCENT { $$ = Operator.OpType.Modulus; savedOperatorLocation = GetLocation ($1); }
+        | BITWISE_AND { $$ = Operator.OpType.BitwiseAnd; savedOperatorLocation = GetLocation ($1); }
+        | BITWISE_OR { $$ = Operator.OpType.BitwiseOr; savedOperatorLocation = GetLocation ($1); }
+        | CARRET { $$ = Operator.OpType.ExclusiveOr; savedOperatorLocation = GetLocation ($1); }
+        | OP_SHIFT_LEFT { $$ = Operator.OpType.LeftShift; savedOperatorLocation = GetLocation ($1); }
+        | OP_SHIFT_RIGHT { $$ = Operator.OpType.RightShift; savedOperatorLocation = GetLocation ($1); }
+        | OP_EQ { $$ = Operator.OpType.Equality; savedOperatorLocation = GetLocation ($1); }
+        | OP_NE { $$ = Operator.OpType.Inequality; savedOperatorLocation = GetLocation ($1); }
+        | OP_GT { $$ = Operator.OpType.GreaterThan; savedOperatorLocation = GetLocation ($1); }
+        | OP_LT { $$ = Operator.OpType.LessThan; savedOperatorLocation = GetLocation ($1); }
+        | OP_GE { $$ = Operator.OpType.GreaterThanOrEqual; savedOperatorLocation = GetLocation ($1); }
+        | OP_LE { $$ = Operator.OpType.LessThanOrEqual; savedOperatorLocation = GetLocation ($1); }
+	;
+
+conversion_operator_declarator
+	: IMPLICIT OPERATOR type OPEN_PARENS
+	  {
+		valid_param_mod = ParameterModifierType.DefaultValue;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+
+		Location loc = GetLocation ($2);
+		current_local_parameters = (ParametersCompiled)$6;  
+
+		if (current_local_parameters.Count != 1) {
+			report.Error (1535, loc, "Overloaded unary operator `implicit' takes one parameter");
+		}
+
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+
+		$$ = new OperatorDeclaration (Operator.OpType.Implicit, (FullNamedExpression) $3, loc);
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($2), GetLocation ($4), GetLocation ($7));
+	  }
+	| EXPLICIT OPERATOR type OPEN_PARENS
+	  {
+		valid_param_mod = ParameterModifierType.DefaultValue;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+		
+		Location loc = GetLocation ($2);
+		current_local_parameters = (ParametersCompiled)$6;  
+
+		if (current_local_parameters.Count != 1) {
+			report.Error (1535, loc, "Overloaded unary operator `explicit' takes one parameter");
+		}
+
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+
+		$$ = new OperatorDeclaration (Operator.OpType.Explicit, (FullNamedExpression) $3, loc);
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($2), GetLocation ($4), GetLocation ($7));
+	  }
+	| IMPLICIT error 
+	  {
+	  	Error_SyntaxError (yyToken);
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		$$ = new OperatorDeclaration (Operator.OpType.Implicit, null, GetLocation ($1));
+	  }
+	| EXPLICIT error 
+	  {
+	  	Error_SyntaxError (yyToken);
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  	$$ = new OperatorDeclaration (Operator.OpType.Explicit, null, GetLocation ($1));
+	  }
+	;
+
+constructor_declaration
+	: constructor_declarator
+	  constructor_body
+	  { 
+		Constructor c = (Constructor) $1;
+		c.Block = (ToplevelBlock) $2;
+		
+		if (doc_support)
+			c.DocComment = ConsumeStoredComment ();
+
+		current_local_parameters = null;
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	;
+
+constructor_declarator
+	: opt_attributes
+	  opt_modifiers
+	  IDENTIFIER
+	  {
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		valid_param_mod = ParameterModifierType.All;
+	  }
+	  OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+		current_local_parameters = (ParametersCompiled) $6;
+		
+		var lt = (LocatedToken) $3;
+		var mods = (Modifiers) $2;
+		var c = new Constructor (current_type, lt.Value, mods, (Attributes) $1, current_local_parameters, lt.Location);
+
+		if (lt.Value != current_container.MemberName.Name) {
+			report.Error (1520, c.Location, "Class, struct, or interface method must have a return type");
+		} else if ((mods & Modifiers.STATIC) != 0) {
+			if ((mods & Modifiers.AccessibilityMask) != 0){
+				report.Error (515, c.Location,
+					"`{0}': static constructor cannot have an access modifier",
+					c.GetSignatureForError ());
+			}
+		}
+
+		current_type.AddConstructor (c);
+		lbag.AddMember (c, GetModifierLocations (), GetLocation ($5), GetLocation ($7));
+		$$ = c;
+
+		//
+		// start block here, so possible anonymous methods inside
+		// constructor initializer can get correct parent block
+		//
+	  	start_block (lexer.Location);
+	  }
+	  opt_constructor_initializer
+	  {
+		if ($9 != null) {
+			var c = (Constructor) $8;
+			c.Initializer = (ConstructorInitializer) $9;
+			
+			if (c.IsStatic) {
+				report.Error (514, c.Location,
+					"`{0}': static constructor cannot have an explicit `this' or `base' constructor call",
+					c.GetSignatureForError ());
+			}
+		}
+
+		$$ = $8;
+	  }
+	;
+
+constructor_body
+	: block_prepared
+	| SEMICOLON 		{ current_block = null; $$ = null; }
+	;
+
+opt_constructor_initializer
+	: /* Empty */
+	| constructor_initializer
+	;
+
+constructor_initializer
+	: COLON BASE OPEN_PARENS
+	  {
+		++lexer.parsing_block;
+	  }
+	  opt_argument_list CLOSE_PARENS
+	  {
+	  	--lexer.parsing_block;
+		$$ = new ConstructorBaseInitializer ((Arguments) $5, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3), GetLocation ($6));
+	  }
+	| COLON THIS OPEN_PARENS
+	  {
+		++lexer.parsing_block;
+	  }
+	  opt_argument_list CLOSE_PARENS
+	  {
+	  	--lexer.parsing_block;
+		$$ = new ConstructorThisInitializer ((Arguments) $5, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3), GetLocation ($6));
+	  }
+	| COLON error
+	  {
+		Error_SyntaxError (yyToken);	  
+		$$ = new ConstructorThisInitializer (null, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	  }
+	;
+
+destructor_declaration
+	: opt_attributes opt_modifiers TILDE 
+	  {
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+		
+		current_local_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+	  }
+	  IDENTIFIER OPEN_PARENS CLOSE_PARENS method_body
+	  {
+		var lt = (LocatedToken) $5;
+		if (lt.Value != current_container.MemberName.Name){
+			report.Error (574, lt.Location, "Name of destructor must match name of class");
+		} else if (current_container.Kind != MemberKind.Class){
+			report.Error (575, lt.Location, "Only class types can contain destructor");
+		}
+		
+		Destructor d = new Destructor (current_type, (Modifiers) $2,
+			ParametersCompiled.EmptyReadOnlyParameters, (Attributes) $1, lt.Location);
+		d.Identifier = lt.Value;
+		if (doc_support)
+			d.DocComment = ConsumeStoredComment ();
+		  
+		d.Block = (ToplevelBlock) $8;
+		current_type.AddMember (d);
+		lbag.AddMember (d, GetModifierLocations (), GetLocation ($3), GetLocation ($6), GetLocation ($7));
+
+		current_local_parameters = null;
+	  }
+	;
+
+event_declaration
+	: opt_attributes
+	  opt_modifiers
+	  EVENT type member_declaration_name
+	  {
+		current_event_field = new EventField (current_type, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, (Attributes) $1);
+		current_type.AddMember (current_event_field);
+		
+		if (current_event_field.MemberName.ExplicitInterface != null) {
+			report.Error (71, current_event_field.Location, "`{0}': An explicit interface implementation of an event must use property syntax",
+			current_event_field.GetSignatureForError ());
+		}
+		
+		$$ = current_event_field;
+	  }
+	  opt_event_initializer
+	  opt_event_declarators
+	  SEMICOLON
+	  {
+		if (doc_support) {
+			current_event_field.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		if (current_event_field.Initializer != null) {
+			lbag.AddMember (current_event_field, GetModifierLocations (), GetLocation ($3), savedEventAssignLocation, GetLocation ($9));
+		} else {
+			lbag.AddMember (current_event_field, GetModifierLocations (), GetLocation ($3), GetLocation ($9));
+		}
+		current_event_field = null;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  EVENT type member_declaration_name
+	  OPEN_BRACE
+	  {
+		current_event = new EventProperty (current_type, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, (Attributes) $1);
+		current_type.AddMember (current_event);
+		lbag.AddMember (current_event, GetModifierLocations (), GetLocation ($3), GetLocation ($6));
+		
+		lexer.EventParsing = true;
+	  }
+	  event_accessor_declarations
+	  {
+		if (current_container.Kind == MemberKind.Interface)
+			report.Error (69, GetLocation ($6), "Event in interface cannot have add or remove accessors");
+	  
+		lexer.EventParsing = false;
+	  }
+	  CLOSE_BRACE
+	  {
+		if (doc_support) {
+			current_event.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		lbag.AppendToMember (current_event, GetLocation ($9));
+	  	current_event = null;	
+		current_local_parameters = null;
+	  }
+	| opt_attributes
+	  opt_modifiers
+	  EVENT type error
+	  {
+		Error_SyntaxError (yyToken);
+
+		current_type.AddMember (new EventField (current_type, (FullNamedExpression) $4, (Modifiers) $2, MemberName.Null, (Attributes) $1));
+	  }
+	;
+	
+opt_event_initializer
+	: /* empty */
+	| ASSIGN
+	  {
+	  	++lexer.parsing_block;
+	  }
+	  event_variable_initializer
+	  {
+	  	--lexer.parsing_block;
+	  	savedEventAssignLocation = GetLocation ($1);
+		current_event_field.Initializer = (Expression) $3;
+	  }
+	;
+	
+opt_event_declarators
+	: /* empty */
+	| event_declarators
+	;
+	
+event_declarators
+	: event_declarator
+	  {
+		current_event_field.AddDeclarator ((FieldDeclarator) $1);
+	  }
+	| event_declarators event_declarator
+	  {
+		current_event_field.AddDeclarator ((FieldDeclarator) $2);
+	  }
+	;
+	
+event_declarator
+	: COMMA IDENTIFIER
+	  {
+		var lt = (LocatedToken) $2;
+	  	$$ = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), null);
+	  	lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	| COMMA IDENTIFIER ASSIGN
+	  {
+		++lexer.parsing_block;
+	  }
+	  event_variable_initializer
+	  {
+		--lexer.parsing_block;
+		var lt = (LocatedToken) $2;	  
+	  	$$ = new FieldDeclarator (new SimpleMemberName (lt.Value, lt.Location), (Expression) $5);
+	  	lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3));
+	  }
+	;
+	
+event_variable_initializer
+	: {
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (68, lexer.Location, "`{0}': event in interface cannot have an initializer",
+				current_event_field.GetSignatureForError ());
+		}
+		
+	  	if ((current_event_field.ModFlags & Modifiers.ABSTRACT) != 0) {
+			report.Error (74, lexer.Location, "`{0}': abstract event cannot have an initializer",
+				current_event_field.GetSignatureForError ());
+	  	}		
+	  }
+	  variable_initializer
+	  {
+		$$ = $2;
+	  }
+	;
+	
+event_accessor_declarations
+	: add_accessor_declaration remove_accessor_declaration
+	| remove_accessor_declaration add_accessor_declaration
+	| add_accessor_declaration
+	  {
+		report.Error (65, lexer.Location, "`{0}': event property must have both add and remove accessors",
+			current_event.GetSignatureForError ());
+	  } 
+	| remove_accessor_declaration
+	  {
+		report.Error (65, lexer.Location, "`{0}': event property must have both add and remove accessors",
+			current_event.GetSignatureForError ());
+	  }	
+	| error
+	  { 
+		report.Error (1055, GetLocation ($1), "An add or remove accessor expected");
+		$$ = null;
+	  }
+	;
+
+add_accessor_declaration
+	: opt_attributes opt_modifiers ADD
+	  {
+	  	if ($2 != ModifierNone) {
+			report.Error (1609, GetLocation ($2), "Modifiers cannot be placed on event accessor declarations");
+	  	}
+	  	
+	  	current_event.Add = new EventProperty.AddDelegateMethod (current_event, (Attributes) $1, GetLocation ($3));
+		current_local_parameters = current_event.Add.ParameterInfo;
+		
+		lbag.AddMember (current_event.Add, GetModifierLocations ());
+		lexer.EventParsing = false;		
+	  }
+	  event_accessor_block
+	  {
+		lexer.EventParsing = true;
+	  
+	  	current_event.Add.Block = (ToplevelBlock) $5;
+		
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (531, current_event.Add.Block.StartLocation,
+				"`{0}': interface members cannot have a definition", current_event.Add.GetSignatureForError ());
+		}
+		
+		current_local_parameters = null;
+	  }
+	;
+	
+remove_accessor_declaration
+	: opt_attributes opt_modifiers REMOVE
+	  {
+	  	if ($2 != ModifierNone) {
+			report.Error (1609, GetLocation ($2), "Modifiers cannot be placed on event accessor declarations");
+	  	}
+	  	
+	  	current_event.Remove = new EventProperty.RemoveDelegateMethod (current_event, (Attributes) $1, GetLocation ($3));
+		current_local_parameters = current_event.Remove.ParameterInfo;
+
+		lbag.AddMember (current_event.Remove, GetModifierLocations ());
+		lexer.EventParsing = false;		
+	  }
+	  event_accessor_block
+	  {
+		lexer.EventParsing = true;
+	  
+	  	current_event.Remove.Block = (ToplevelBlock) $5;
+		
+		if (current_container.Kind == MemberKind.Interface) {
+			report.Error (531, current_event.Remove.Block.StartLocation,
+				"`{0}': interface members cannot have a definition", current_event.Remove.GetSignatureForError ());
+		}
+		
+		current_local_parameters = null;
+	  }
+	;
+
+event_accessor_block
+	: opt_semicolon
+	  {
+		report.Error (73, lexer.Location, "An add or remove accessor must have a body");
+		$$ = null;
+	  }
+	| block;
+	;
+
+attributes_without_members
+	: attribute_sections CLOSE_BRACE
+	  {
+		current_type.UnattachedAttributes = (Attributes) $1;
+		report.Error (1519, GetLocation ($1), "An attribute is missing member declaration");
+		lexer.putback ('}');
+	  }
+	;
+
+// For full ast try to recover incomplete ambiguous member
+// declaration in form on class X { public int }
+incomplete_member
+	: opt_attributes opt_modifiers member_type CLOSE_BRACE
+	  {
+		report.Error (1519, lexer.Location, "Unexpected symbol `}' in class, struct, or interface member declaration");
+ 
+		lexer.putback ('}');
+
+	  	lexer.parsing_generic_declaration = false;
+		FullNamedExpression type = (FullNamedExpression) $3;
+		current_field = new Field (current_type, type, (Modifiers) $2, MemberName.Null, (Attributes) $1);
+		current_type.AddField (current_field);
+		lbag.AddMember (current_field, GetModifierLocations ());
+		$$ = current_field;
+	  }
+	;
+	  
+enum_declaration
+	: opt_attributes
+	  opt_modifiers
+	  ENUM
+	  type_declaration_name
+	  opt_enum_base
+	  {
+		if (doc_support)
+			enumTypeComment = Lexer.consume_doc_comment ();
+	  }
+	  OPEN_BRACE
+	  {
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+
+		MemberName name = (MemberName) $4;
+		if (name.IsGeneric) {
+			report.Error (1675, name.Location, "Enums cannot have type parameters");
+		}
+		
+		push_current_container (new Enum (current_container, (FullNamedExpression) $5, (Modifiers) $2, name, (Attributes) $1), null);
+		if ($5 != null) {
+			lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($3), savedLocation, GetLocation ($7));
+		} else {
+			lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($3), GetLocation ($7));
+		}
+	  }
+	  opt_enum_member_declarations
+	  {
+		lexer.parsing_modifiers = true;
+	  
+	  	// here will be evaluated after CLOSE_BLACE is consumed.
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	  CLOSE_BRACE opt_semicolon
+	  {
+		lbag.AppendToMember (current_container, GetLocation ($11));
+		if ($12 != null) {
+			lbag.AppendToMember (current_container, GetLocation ($12));
+		}
+		if (doc_support)
+			current_container.DocComment = enumTypeComment;
+			
+		--lexer.parsing_declaration;
+
+//			if (doc_support)
+//				em.DocComment = ev.DocComment;
+
+		$$ = pop_current_class ();
+	  }
+	;
+
+opt_enum_base
+	: /* empty */
+	| COLON type
+	 {
+		savedLocation = GetLocation ($1);
+		$$ = $2;
+	 }
+	| COLON error
+	 {
+	 	Error_TypeExpected (GetLocation ($1));
+		$$ = null;
+	 }
+	;
+
+opt_enum_member_declarations
+	: /* empty */
+	| enum_member_declarations
+	| enum_member_declarations COMMA
+	  {
+		lbag.AppendToMember (current_container, GetLocation ($2));
+	  }
+	;
+
+enum_member_declarations
+	: enum_member_declaration
+	| enum_member_declarations COMMA enum_member_declaration
+	  {
+		lbag.AppendToMember (current_container, GetLocation ($2));
+	  	$$ = $3;
+	  }
+	;
+
+enum_member_declaration
+	: opt_attributes IDENTIFIER
+	  {
+		var lt = (LocatedToken) $2;
+	  	var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) $1);
+	  	((Enum) current_type).AddEnumMember (em);
+
+		if (doc_support) {
+			em.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+
+		$$ = em;
+	  }
+	| opt_attributes IDENTIFIER
+	  {
+	  	++lexer.parsing_block;
+		if (doc_support) {
+			tmpComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.NotAllowed;
+		}
+	  }
+	  ASSIGN constant_expression
+	  { 
+		--lexer.parsing_block;
+		
+		var lt = (LocatedToken) $2;
+	  	var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) $1);
+	  	em.Initializer = new ConstInitializer (em, (Expression) $5, GetLocation ($4));
+	  	((Enum) current_type).AddEnumMember (em);
+		
+		if (doc_support)
+			em.DocComment = ConsumeStoredComment ();
+
+		$$ = em;
+	  }
+	| opt_attributes IDENTIFIER error
+	  {
+		Error_SyntaxError (yyToken);
+	  
+		var lt = (LocatedToken) $2;
+	  	var em = new EnumMember ((Enum) current_type, new MemberName (lt.Value, lt.Location), (Attributes) $1);
+	  	((Enum) current_type).AddEnumMember (em);
+
+		if (doc_support) {
+			em.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+
+		$$ = em;
+	  }
+	| attributes_without_members
+	;
+
+delegate_declaration
+	: opt_attributes
+	  opt_modifiers
+	  DELEGATE
+	  member_type type_declaration_name
+	  OPEN_PARENS
+	  {
+		valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out | ParameterModifierType.Params | ParameterModifierType.DefaultValue;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+
+		ParametersCompiled p = (ParametersCompiled) $8;
+
+		Delegate del = new Delegate (current_container, (FullNamedExpression) $4, (Modifiers) $2, (MemberName) $5, p, (Attributes) $1);
+
+		p.CheckParameters (del);
+
+		current_container.AddTypeContainer (del);
+
+		current_delegate = del;
+		lexer.ConstraintsParsing = true;
+	  }
+	  opt_type_parameter_constraints_clauses
+	  {
+		lexer.ConstraintsParsing = false;
+	  }
+	  SEMICOLON
+	  {
+		if (doc_support) {
+			current_delegate.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+	  
+		if ($11 != null)
+			current_delegate.SetConstraints ((List<Constraints>) $11);
+		lbag.AddMember (current_delegate, GetModifierLocations (), GetLocation ($3), GetLocation ($6), GetLocation ($9), GetLocation ($13));
+
+		$$ = current_delegate;
+
+		current_delegate = null;
+	  }
+	;
+
+opt_nullable
+	: /* empty */
+	| INTERR_NULLABLE
+	  {
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "nullable types");
+	  
+	  	$$ = ComposedTypeSpecifier.CreateNullable (GetLocation ($1));
+	  }
+	;
+
+namespace_or_type_expr
+	: member_name
+	| qualified_alias_member IDENTIFIER opt_type_argument_list
+	  {
+		var lt1 = (LocatedToken) $1;
+		var lt2 = (LocatedToken) $2;
+		
+		$$ = new QualifiedAliasMember (lt1.Value, lt2.Value, (TypeArguments) $3, lt1.Location);
+		lbag.AddLocation ($$, savedLocation, GetLocation ($2));
+	  }
+	| qualified_alias_member IDENTIFIER generic_dimension
+	  {
+		var lt1 = (LocatedToken) $1;
+		var lt2 = (LocatedToken) $2;
+		var qam = new QualifiedAliasMember (lt1.Value, lt2.Value, (int) $3, lt1.Location);
+		lbag.AddLocation (qam.TypeArguments, Lexer.GenericDimensionLocations);
+		$$ = qam;
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+member_name
+	: simple_name_expr
+	| namespace_or_type_expr DOT IDENTIFIER opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberAccess ((Expression) $1, lt.Value, (TypeArguments) $4, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| namespace_or_type_expr DOT IDENTIFIER generic_dimension
+	  {
+		var lt = (LocatedToken) $3;
+		var ma = new MemberAccess ((Expression) $1, lt.Value, (int) $4, lt.Location);
+		lbag.AddLocation (ma.TypeArguments, Lexer.GenericDimensionLocations);
+		$$ = ma;
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+simple_name_expr
+	: IDENTIFIER opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $1;
+		$$ = new SimpleName (lt.Value, (TypeArguments)$2, lt.Location);
+	  }
+	| IDENTIFIER generic_dimension
+	  {  
+		var lt = (LocatedToken) $1;
+		var sn = new SimpleName (lt.Value, (int) $2, lt.Location);
+		lbag.AddLocation (sn.TypeArguments, Lexer.GenericDimensionLocations);
+		$$ = sn;
+	  }
+	;
+
+//
+// Generics arguments  (any type, without attributes)
+//
+opt_type_argument_list
+	: /* empty */
+	| OP_GENERICS_LT type_arguments OP_GENERICS_GT
+	  {
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "generics");
+		var list = locationListStack.Pop ();
+		list.Add (GetLocation ($1));
+		list.Add (GetLocation ($2));
+		lbag.AddLocation ($2, list);
+	
+		$$ = $2;;
+	  }
+	| OP_GENERICS_LT error
+	  {
+		Error_TypeExpected (lexer.Location);
+		$$ = new TypeArguments ();
+	  }
+	;
+
+type_arguments
+	: type
+	  {
+		TypeArguments type_args = new TypeArguments ();
+		type_args.Add ((FullNamedExpression) $1);
+		$$ = type_args;
+		locationListStack.Push (new List<Location> ());
+	  }
+	| type_arguments COMMA type
+	  {
+		TypeArguments type_args = (TypeArguments) $1;
+		type_args.Add ((FullNamedExpression) $3);
+		$$ = type_args;
+		locationListStack.Peek ().Add (GetLocation ($2));
+	  }
+	;
+
+//
+// Generics parameters (identifiers only, with attributes), used in type or method declarations
+//
+type_declaration_name
+	: IDENTIFIER
+	  {
+		lexer.parsing_generic_declaration = true;
+	  }
+	  opt_type_parameter_list
+	  {
+		lexer.parsing_generic_declaration = false;
+		var lt = (LocatedToken) $1;
+		$$ = new MemberName (lt.Value, (TypeParameters)$3, lt.Location);
+	  }
+	;
+
+member_declaration_name
+	: method_declaration_name
+	  {
+	  	MemberName mn = (MemberName)$1;
+	  	if (mn.TypeParameters != null)
+	  		syntax_error (mn.Location, string.Format ("Member `{0}' cannot declare type arguments",
+	  			mn.GetSignatureForError ()));
+	  }
+	;
+
+method_declaration_name
+	: type_declaration_name
+	| explicit_interface IDENTIFIER opt_type_parameter_list
+	  {
+		lexer.parsing_generic_declaration = false;	  
+		var lt = (LocatedToken) $2;
+		$$ = new MemberName (lt.Value, (TypeParameters) $3, (ATypeNameExpression) $1, lt.Location);
+	  }
+	;
+	
+indexer_declaration_name
+	: THIS
+	  {
+		lexer.parsing_generic_declaration = false;	  
+		$$ = new MemberName (TypeDefinition.DefaultIndexerName, GetLocation ($1));
+	  }
+	| explicit_interface THIS
+	  {
+		lexer.parsing_generic_declaration = false;
+		$$ = new MemberName (TypeDefinition.DefaultIndexerName, null, (ATypeNameExpression) $1, GetLocation ($2));
+	  }
+	;
+
+explicit_interface
+	: IDENTIFIER opt_type_argument_list DOT
+	  {
+		var lt = (LocatedToken) $1;
+		$$ = new SimpleName (lt.Value, (TypeArguments) $2, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	| qualified_alias_member IDENTIFIER opt_type_argument_list DOT
+	  {
+		var lt1 = (LocatedToken) $1;
+		var lt2 = (LocatedToken) $2;
+
+		$$ = new QualifiedAliasMember (lt1.Value, lt2.Value, (TypeArguments) $3, lt1.Location);
+		lbag.AddLocation ($$, savedLocation, GetLocation ($4));
+	  }
+	| explicit_interface IDENTIFIER opt_type_argument_list DOT
+	  {
+		var lt = (LocatedToken) $2;
+		$$ = new MemberAccess ((ATypeNameExpression) $1, lt.Value, (TypeArguments) $3, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	;
+	
+opt_type_parameter_list
+	: /* empty */
+	| OP_GENERICS_LT_DECL type_parameters OP_GENERICS_GT
+	  {
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "generics");
+	  
+		$$ = $2;
+		var list = locationListStack.Pop ();
+		list.Add (GetLocation ($1));
+		list.Add (GetLocation ($2));
+		lbag.AddLocation ($2, list);
+	  }
+	;
+
+type_parameters
+	: type_parameter
+	  {
+		var tparams = new TypeParameters ();
+		tparams.Add ((TypeParameter)$1);
+		$$ = tparams;
+		locationListStack.Push (new List<Location> ());
+	  }
+	| type_parameters COMMA type_parameter
+	  {
+		var tparams = (TypeParameters) $1;
+		tparams.Add ((TypeParameter)$3);
+		$$ = tparams;
+		locationListStack.Peek ().Add (GetLocation ($2));
+	  }	  
+	;
+
+type_parameter
+	: opt_attributes opt_type_parameter_variance IDENTIFIER
+	  {
+		var lt = (LocatedToken)$3;
+		var variance = (VarianceDecl) $2;
+		$$ = new TypeParameter (new MemberName (lt.Value, lt.Location), (Attributes)$1, variance);
+		if (variance != null)
+			lbag.AddLocation ($$, savedLocation);
+  	  }
+  	| error
+  	  {
+  	  	if (GetTokenName (yyToken) == "type")
+			report.Error (81, GetLocation ($1), "Type parameter declaration must be an identifier not a type");
+		else
+			Error_SyntaxError (yyToken);
+			
+  	  	$$ = new TypeParameter (MemberName.Null, null, null);
+  	  }
+ 	;
+
+//
+// All types where void is allowed
+//
+type_and_void
+	: type_expression_or_array
+	| VOID
+	  {
+		$$ = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1));
+	  }
+	;
+	
+member_type
+	: type_and_void
+	  {
+		lexer.parsing_generic_declaration = true;
+	  }
+	;
+	
+//
+// A type which does not allow `void' to be used
+//
+type
+	: type_expression_or_array
+	| void_invalid
+	;
+	
+simple_type
+	: type_expression
+	| void_invalid
+	;
+	
+parameter_type
+	: type_expression_or_array
+	| VOID
+	  {
+		report.Error (1536, GetLocation ($1), "Invalid parameter type `void'");
+		$$ = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1));
+	  }
+	;
+
+type_expression_or_array
+	: type_expression
+	| type_expression rank_specifiers
+	  {
+		$$ = new ComposedCast ((FullNamedExpression) $1, (ComposedTypeSpecifier) $2);
+	  }
+	;
+	
+type_expression
+	: namespace_or_type_expr opt_nullable
+	  {
+		if ($2 != null) {
+			$$ = new ComposedCast ((ATypeNameExpression) $1, (ComposedTypeSpecifier) $2);
+		} else {
+			var sn = $1 as SimpleName;
+			if (sn != null && sn.Name == "var")
+				$$ = new VarExpr (sn.Location);
+			else
+				$$ = $1;
+		}
+	  }
+	| namespace_or_type_expr pointer_stars
+	  {
+		$$ = new ComposedCast ((ATypeNameExpression) $1, (ComposedTypeSpecifier) $2);
+	  }
+	| builtin_type_expression
+	;
+
+void_invalid
+	: VOID
+	  {
+		Expression.Error_VoidInvalidInTheContext (GetLocation ($1), report);
+		$$ = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1));
+	  }
+	;
+
+builtin_type_expression
+	: builtin_types opt_nullable
+	  {
+		if ($2 != null)
+			$$ = new ComposedCast ((FullNamedExpression) $1, (ComposedTypeSpecifier) $2);
+	  }
+	| builtin_types pointer_stars
+	  {
+		$$ = new ComposedCast ((FullNamedExpression) $1, (ComposedTypeSpecifier) $2);
+	  }
+	| VOID pointer_stars
+	  {
+		$$ = new ComposedCast (new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1)), (ComposedTypeSpecifier) $2);
+	  }
+	;
+
+type_list
+	: base_type_name
+	  {
+		var types = new List<FullNamedExpression> (2);
+		types.Add ((FullNamedExpression) $1);
+		$$ = types;
+	  }
+	| type_list COMMA base_type_name
+	  {
+		var types = (List<FullNamedExpression>) $1;
+		types.Add ((FullNamedExpression) $3);
+		lbag.AddLocation (types, GetLocation ($2));
+		$$ = types;
+	  }
+	;
+
+base_type_name
+	: type
+	  {
+		if ($1 is ComposedCast) {
+			report.Error (1521, GetLocation ($1), "Invalid base type `{0}'", ((ComposedCast)$1).GetSignatureForError ());
+		}
+		$$ = $1;
+	  }
+	;
+	
+/*
+ * replaces all the productions for isolating the various
+ * simple types, but we need this to reuse it easily in variable_type
+ */
+builtin_types
+	: OBJECT	{ $$ = new TypeExpression (compiler.BuiltinTypes.Object, GetLocation ($1)); }
+	| STRING	{ $$ = new TypeExpression (compiler.BuiltinTypes.String, GetLocation ($1)); }
+	| BOOL		{ $$ = new TypeExpression (compiler.BuiltinTypes.Bool, GetLocation ($1)); }
+	| DECIMAL	{ $$ = new TypeExpression (compiler.BuiltinTypes.Decimal, GetLocation ($1)); }
+	| FLOAT		{ $$ = new TypeExpression (compiler.BuiltinTypes.Float, GetLocation ($1)); }
+	| DOUBLE	{ $$ = new TypeExpression (compiler.BuiltinTypes.Double, GetLocation ($1)); }
+	| integral_type
+	;
+
+integral_type
+	: SBYTE		{ $$ = new TypeExpression (compiler.BuiltinTypes.SByte, GetLocation ($1)); }
+	| BYTE		{ $$ = new TypeExpression (compiler.BuiltinTypes.Byte, GetLocation ($1)); }
+	| SHORT		{ $$ = new TypeExpression (compiler.BuiltinTypes.Short, GetLocation ($1)); }
+	| USHORT	{ $$ = new TypeExpression (compiler.BuiltinTypes.UShort, GetLocation ($1)); }
+	| INT		{ $$ = new TypeExpression (compiler.BuiltinTypes.Int, GetLocation ($1)); }
+	| UINT		{ $$ = new TypeExpression (compiler.BuiltinTypes.UInt, GetLocation ($1)); }
+	| LONG		{ $$ = new TypeExpression (compiler.BuiltinTypes.Long, GetLocation ($1)); }
+	| ULONG		{ $$ = new TypeExpression (compiler.BuiltinTypes.ULong, GetLocation ($1)); }
+	| CHAR		{ $$ = new TypeExpression (compiler.BuiltinTypes.Char, GetLocation ($1)); }
+	;
+
+//
+// Expressions, section 7.5
+//
+
+
+primary_expression
+	: primary_expression_or_type
+	| literal
+	| array_creation_expression
+	| parenthesized_expression
+	| default_value_expression
+	| invocation_expression
+	| element_access
+	| this_access
+	| base_access
+	| post_increment_expression
+	| post_decrement_expression
+	| object_or_delegate_creation_expression
+	| anonymous_type_expression
+	| typeof_expression
+	| sizeof_expression
+	| checked_expression
+	| unchecked_expression
+	| pointer_member_access
+	| anonymous_method_expression
+	| undocumented_expressions
+	;
+
+primary_expression_or_type
+	: simple_name_expr
+	| IDENTIFIER GENERATE_COMPLETION {
+		var lt = (LocatedToken) $1;
+	       $$ = new CompletionSimpleName (MemberName.MakeName (lt.Value, null), lt.Location);
+	  }
+	| member_access
+	;
+
+literal
+	: boolean_literal
+	| LITERAL
+	| NULL			{ $$ = new NullLiteral (GetLocation ($1)); }
+	;
+
+boolean_literal
+	: TRUE			{ $$ = new BoolLiteral (compiler.BuiltinTypes, true, GetLocation ($1)); }
+	| FALSE			{ $$ = new BoolLiteral (compiler.BuiltinTypes, false, GetLocation ($1)); }
+	;
+
+
+//
+// Here is the trick, tokenizer may think that parens is a special but
+// parser is interested in open parens only, so we merge them.
+// Consider: if (a)foo ();
+//
+open_parens_any
+	: OPEN_PARENS
+	| OPEN_PARENS_CAST
+	;
+
+// 
+// Use this production to accept closing parenthesis or 
+// performing completion
+//
+close_parens
+	: CLOSE_PARENS
+	| COMPLETE_COMPLETION
+	;
+
+
+parenthesized_expression
+	: OPEN_PARENS expression CLOSE_PARENS
+	  {
+		$$ = new ParenthesizedExpression ((Expression) $2, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3));
+	  }
+	| OPEN_PARENS expression COMPLETE_COMPLETION
+	  {
+		$$ = new ParenthesizedExpression ((Expression) $2, GetLocation ($1));
+	  }
+	;
+
+member_access
+	: primary_expression DOT identifier_inside_body opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberAccess ((Expression) $1, lt.Value, (TypeArguments) $4, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| primary_expression DOT identifier_inside_body generic_dimension
+	  {
+		var lt = (LocatedToken) $3;
+		var ma = new MemberAccess ((Expression) $1, lt.Value, (int) $4, lt.Location);
+		lbag.AddLocation (ma.TypeArguments, Lexer.GenericDimensionLocations);
+		$$ = ma;
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| primary_expression INTERR_OPERATOR DOT identifier_inside_body opt_type_argument_list
+	  {
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation ($2), "null propagating operator");
+
+		var lt = (LocatedToken) $4;
+		$$ = new ConditionalMemberAccess ((Expression) $1, lt.Value, (TypeArguments) $5, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($3));
+	  }
+	| builtin_types DOT identifier_inside_body opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberAccess ((Expression) $1, lt.Value, (TypeArguments) $4, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| BASE DOT identifier_inside_body opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberAccess (new BaseThis (GetLocation ($1)), lt.Value, (TypeArguments) $4, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| AWAIT DOT identifier_inside_body opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberAccess (new SimpleName ("await", ((LocatedToken) $1).Location), lt.Value, (TypeArguments) $4, lt.Location);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| qualified_alias_member identifier_inside_body opt_type_argument_list
+	  {
+		var lt1 = (LocatedToken) $1;
+		var lt2 = (LocatedToken) $2;
+
+		$$ = new QualifiedAliasMember (lt1.Value, lt2.Value, (TypeArguments) $3, lt1.Location);
+		lbag.AddLocation ($$, savedLocation, GetLocation ($2));
+	  }
+	| qualified_alias_member identifier_inside_body generic_dimension
+	  {
+		var lt1 = (LocatedToken) $1;
+		var lt2 = (LocatedToken) $2;
+		var qam = new QualifiedAliasMember (lt1.Value, lt2.Value, (int) $3, lt1.Location);
+		lbag.AddLocation (qam.TypeArguments, Lexer.GenericDimensionLocations);
+		$$ = qam;
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| primary_expression DOT GENERATE_COMPLETION {
+		$$ = new CompletionMemberAccess ((Expression) $1, null,GetLocation ($3));
+	  }
+	| primary_expression DOT IDENTIFIER GENERATE_COMPLETION {
+		var lt = (LocatedToken) $3;
+		$$ = new CompletionMemberAccess ((Expression) $1, lt.Value, lt.Location);
+	  }
+	| builtin_types DOT GENERATE_COMPLETION
+	  {
+		$$ = new CompletionMemberAccess ((Expression) $1, null, lexer.Location);
+	  }
+	| builtin_types DOT IDENTIFIER GENERATE_COMPLETION {
+		var lt = (LocatedToken) $3;
+		$$ = new CompletionMemberAccess ((Expression) $1, lt.Value, lt.Location);
+ 	  }
+	;
+
+invocation_expression
+	: primary_expression open_parens_any opt_argument_list close_parens
+	  {
+		$$ = new Invocation ((Expression) $1, (Arguments) $3);
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| primary_expression open_parens_any argument_list error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Invocation ((Expression) $1, (Arguments) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| primary_expression open_parens_any error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Invocation ((Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+opt_object_or_collection_initializer
+	: /* empty */		{ $$ = null; }
+	| object_or_collection_initializer
+	;
+
+object_or_collection_initializer
+	: OPEN_BRACE opt_member_initializer_list close_brace_or_complete_completion
+	  {
+	  	if ($2 == null) {
+	  		$$ = new CollectionOrObjectInitializers (GetLocation ($1));
+	  	} else {
+	  		$$ = new CollectionOrObjectInitializers ((List<Expression>) $2, GetLocation ($1));
+	  	}
+ 		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	| OPEN_BRACE member_initializer_list COMMA CLOSE_BRACE
+	  {
+	  	$$ = new CollectionOrObjectInitializers ((List<Expression>) $2, GetLocation ($1));
+	  	lbag.AddLocation ($$, GetLocation ($3), GetLocation ($4));
+	  }
+	;
+
+opt_member_initializer_list
+	: /* empty */		{ $$ = null; }
+	| member_initializer_list
+	{
+		$$ = $1;
+	}
+	;
+
+member_initializer_list
+	: member_initializer
+	  {
+	  	var a = new List<Expression> ();
+	  	a.Add ((Expression) $1);
+	  	$$ = a;
+	  }
+	| member_initializer_list COMMA member_initializer
+	  {
+	  	var a = (List<Expression>)$1;
+	  	a.Add ((Expression) $3);
+		lbag.AddLocation (a, GetLocation ($2));
+	  	$$ = a;
+	  }
+	| member_initializer_list error {
+	  	Error_SyntaxError (yyToken);
+		$$ = $1;
+	  }
+	;
+
+member_initializer
+	: IDENTIFIER ASSIGN initializer_value
+	  {
+	  	var lt = (LocatedToken) $1;
+	  	$$ = new ElementInitializer (lt.Value, (Expression)$3, lt.Location);
+	  	lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| AWAIT ASSIGN initializer_value
+	  {
+	  	var lt = (LocatedToken) Error_AwaitAsIdentifier ($1);
+	  	$$ = new ElementInitializer (lt.Value, (Expression)$3, lt.Location);
+	  	lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| GENERATE_COMPLETION 
+	  {
+		$$ = new CompletionElementInitializer (null, GetLocation ($1));
+	  }
+	| non_assignment_expression opt_COMPLETE_COMPLETION  {
+		CompletionSimpleName csn = $1 as CompletionSimpleName;
+		if (csn == null)
+			$$ = new CollectionElementInitializer ((Expression)$1);
+		else
+			$$ = new CompletionElementInitializer (csn.Prefix, csn.Location);
+	  }
+	| OPEN_BRACE expression_list CLOSE_BRACE
+	  {
+		if ($2 == null)
+			$$ = new CollectionElementInitializer (GetLocation ($1));
+		else {
+	  		$$ = new CollectionElementInitializer ((List<Expression>)$2, GetLocation ($1));
+			lbag.AddLocation ($$, GetLocation ($2));
+		}
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	| OPEN_BRACKET_EXPR expression_list CLOSE_BRACKET ASSIGN initializer_value
+	  {
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation ($1), "dictionary initializer");
+
+		$$ = new DictionaryElementInitializer ((List<Expression>)$2, (Expression) $5, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3), GetLocation ($4));
+	  }
+	| OPEN_BRACE CLOSE_BRACE
+	  {
+	  	report.Error (1920, GetLocation ($1), "An element initializer cannot be empty");
+		$$ = new CollectionElementInitializer (GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+initializer_value
+	: expression
+	| object_or_collection_initializer
+	;
+
+opt_argument_list
+	: /* empty */		{ $$ = null; }
+	| argument_list
+	;
+
+argument_list
+	: argument_or_named_argument
+	  { 
+		Arguments list = new Arguments (4);
+		list.Add ((Argument) $1);
+		$$ = list;
+	  }
+	| argument_list COMMA argument
+	  {
+		Arguments list = (Arguments) $1;
+		if (list [list.Count - 1] is NamedArgument)
+			Error_NamedArgumentExpected ((NamedArgument) list [list.Count - 1]);
+		
+		list.Add ((Argument) $3);
+		lbag.AddLocation (list, GetLocation ($2));
+		$$ = list;
+	  }
+	| argument_list COMMA named_argument
+	  {
+		Arguments list = (Arguments) $1;
+		NamedArgument a = (NamedArgument) $3;
+		for (int i = 0; i < list.Count; ++i) {
+			NamedArgument na = list [i] as NamedArgument;
+			if (na != null && na.Name == a.Name)
+				report.Error (1740, na.Location, "Named argument `{0}' specified multiple times",
+					na.Name);
+		}
+		
+		list.Add (a);
+		lbag.AddLocation (list, GetLocation ($2));
+		$$ = list;
+	  }
+	| argument_list COMMA error
+	  {
+	  	if (lexer.putback_char == -1)
+	  		lexer.putback (')'); // TODO: Wrong but what can I do
+		Error_SyntaxError (yyToken);
+		$$ = $1;
+	  }
+	| COMMA error
+	  {
+	  	report.Error (839, GetLocation ($1), "An argument is missing");
+	  	$$ = null;
+	  }
+	;
+
+argument
+	: expression
+	  {
+		$$ = new Argument ((Expression) $1);
+	  }
+	| non_simple_argument
+	;
+
+argument_or_named_argument
+	: argument
+	| named_argument
+	;
+
+non_simple_argument
+	: REF variable_reference 
+	  { 
+		$$ = new Argument ((Expression) $2, Argument.AType.Ref);
+		lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	| OUT variable_reference 
+	  { 
+		$$ = new Argument ((Expression) $2, Argument.AType.Out);
+		lbag.AddLocation ($$, GetLocation ($1));
+	  }
+	| ARGLIST OPEN_PARENS argument_list CLOSE_PARENS
+	  {
+		$$ = new Argument (new Arglist ((Arguments) $3, GetLocation ($1)));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| ARGLIST OPEN_PARENS CLOSE_PARENS
+	  {
+		$$ = new Argument (new Arglist (GetLocation ($1)));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($3));
+	  }	  
+	;
+
+variable_reference
+	: expression
+	;
+
+element_access
+	: primary_expression OPEN_BRACKET_EXPR expression_list_arguments CLOSE_BRACKET	
+	  {
+		$$ = new ElementAccess ((Expression) $1, (Arguments) $3, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	| primary_expression INTERR_OPERATOR OPEN_BRACKET_EXPR expression_list_arguments CLOSE_BRACKET	
+	  {
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation ($2), "null propagating operator");
+
+		$$ = new ElementAccess ((Expression) $1, (Arguments) $4, GetLocation ($3)) {
+			ConditionalAccess = true
+		};
+
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($5));
+	  }
+	| primary_expression OPEN_BRACKET_EXPR expression_list_arguments error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new ElementAccess ((Expression) $1, (Arguments) $3, GetLocation ($2));
+	  }
+	| primary_expression OPEN_BRACKET_EXPR error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new ElementAccess ((Expression) $1, null, GetLocation ($2));
+	  }
+	;
+
+expression_list
+	: expression_or_error
+	  {
+		var list = new List<Expression> (4);
+		list.Add ((Expression) $1);
+		$$ = list;
+	  }
+	| expression_list COMMA expression_or_error
+	  {
+		var list = (List<Expression>) $1;
+		list.Add ((Expression) $3);
+		lbag.AddLocation (list, GetLocation ($2));
+		$$ = list;
+	  }
+	;
+	
+expression_list_arguments
+	: expression_list_argument
+	  {
+		Arguments args = new Arguments (4);
+		args.Add ((Argument) $1);
+		$$ = args;
+	  }
+	| expression_list_arguments COMMA expression_list_argument
+	  {
+		Arguments args = (Arguments) $1;
+		if (args [args.Count - 1] is NamedArgument && !($3 is NamedArgument))
+			Error_NamedArgumentExpected ((NamedArgument) args [args.Count - 1]);
+	  
+		args.Add ((Argument) $3);
+		lbag.AddLocation (args, GetLocation ($2));
+		$$ = args;	  
+	  }
+	;
+	
+expression_list_argument
+	: expression
+	  {
+	  	$$ = new Argument ((Expression) $1);
+	  }
+	| named_argument
+	;
+
+this_access
+	: THIS
+	  {
+		$$ = new This (GetLocation ($1));
+	  }
+	;
+
+base_access
+	: BASE OPEN_BRACKET_EXPR expression_list_arguments CLOSE_BRACKET
+	  {
+	  	$$ = new ElementAccess (new BaseThis (GetLocation ($1)), (Arguments) $3, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	| BASE OPEN_BRACKET error
+	  {
+	  	Error_SyntaxError (yyToken);
+		$$ = new ElementAccess (null, null, GetLocation ($2));
+	  }
+	;
+
+post_increment_expression
+	: primary_expression OP_INC
+	  {
+		$$ = new UnaryMutator (UnaryMutator.Mode.PostIncrement, (Expression) $1, GetLocation ($2));
+	  }
+	;
+
+post_decrement_expression
+	: primary_expression OP_DEC
+	  {
+		$$ = new UnaryMutator (UnaryMutator.Mode.PostDecrement, (Expression) $1, GetLocation ($2));
+	  }
+	;
+	
+object_or_delegate_creation_expression
+	: NEW new_expr_type open_parens_any opt_argument_list CLOSE_PARENS opt_object_or_collection_initializer
+	  {
+		if ($6 != null) {
+			if (lang_version <= LanguageVersion.ISO_2)
+				FeatureIsNotAvailable (GetLocation ($1), "object initializers");
+				
+			$$ = new NewInitialize ((FullNamedExpression) $2, (Arguments) $4, (CollectionOrObjectInitializers) $6, GetLocation ($1));
+		} else {
+			$$ = new New ((FullNamedExpression) $2, (Arguments) $4, GetLocation ($1));
+		}
+		
+		lbag.AddLocation ($$, GetLocation ($3), GetLocation ($5));
+	  }
+	| NEW new_expr_type object_or_collection_initializer
+	  {
+		if (lang_version <= LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "collection initializers");
+	  
+		$$ = new NewInitialize ((FullNamedExpression) $2, null, (CollectionOrObjectInitializers) $3, GetLocation ($1));
+	  }
+	;
+
+array_creation_expression
+	: NEW new_expr_type OPEN_BRACKET_EXPR expression_list CLOSE_BRACKET
+	  opt_rank_specifier
+	  opt_array_initializer
+	  {
+		$$ = new ArrayCreation ((FullNamedExpression) $2, (List<Expression>) $4,
+				new ComposedTypeSpecifier (((List<Expression>) $4).Count, GetLocation ($3)) {
+	  				Next = (ComposedTypeSpecifier) $6
+			  	}, (ArrayInitializer) $7, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3), GetLocation ($5));
+	  }
+	| NEW new_expr_type rank_specifiers opt_array_initializer
+	  {
+	  	if ($4 == null)
+	  		report.Error (1586, GetLocation ($1), "Array creation must have array size or array initializer");
+
+		$$ = new ArrayCreation ((FullNamedExpression) $2, (ComposedTypeSpecifier) $3, (ArrayInitializer) $4, GetLocation ($1));
+	  }
+	| NEW rank_specifier array_initializer
+	  {
+		if (lang_version <= LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "implicitly typed arrays");
+	  
+		$$ = new ImplicitlyTypedArrayCreation ((ComposedTypeSpecifier) $2, (ArrayInitializer) $3, GetLocation ($1));
+	  }
+	| NEW new_expr_type OPEN_BRACKET CLOSE_BRACKET OPEN_BRACKET_EXPR error CLOSE_BRACKET
+	  {
+		report.Error (178, GetLocation ($6), "Invalid rank specifier, expecting `,' or `]'");
+		$$ = new ArrayCreation ((FullNamedExpression) $2, null, GetLocation ($1));
+	  }
+	| NEW new_expr_type error
+	  {
+		Error_SyntaxError (yyToken);
+		// It can be any of new expression, create the most common one
+		$$ = new New ((FullNamedExpression) $2, null, GetLocation ($1));
+	  }
+	;
+
+new_expr_type
+	: {
+		++lexer.parsing_type;
+	  }
+	  simple_type
+	  {
+		--lexer.parsing_type;
+		$$ = $2;
+	  }
+	;
+
+anonymous_type_expression
+	: NEW OPEN_BRACE anonymous_type_parameters_opt_comma CLOSE_BRACE
+	  {
+		if (lang_version <= LanguageVersion.ISO_2)
+	  		FeatureIsNotAvailable (GetLocation ($1), "anonymous types");
+
+		$$ = new NewAnonymousType ((List<AnonymousTypeParameter>) $3, current_container, GetLocation ($1));
+		
+		// TODO: lbag comma location
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| NEW OPEN_BRACE GENERATE_COMPLETION
+	  {
+		$$ = new EmptyCompletion ();
+	  }
+	;
+
+anonymous_type_parameters_opt_comma
+	: anonymous_type_parameters_opt
+	| anonymous_type_parameters COMMA
+	;
+
+anonymous_type_parameters_opt
+	: { $$ = null; }
+	| anonymous_type_parameters
+	;
+
+anonymous_type_parameters
+	: anonymous_type_parameter
+	  {
+	  	var a = new List<AnonymousTypeParameter> (4);
+	  	a.Add ((AnonymousTypeParameter) $1);
+	  	$$ = a;
+	  }
+	| anonymous_type_parameters COMMA anonymous_type_parameter
+	  {
+	  	var a = (List<AnonymousTypeParameter>) $1;
+	  	a.Add ((AnonymousTypeParameter) $3);
+	  	lbag.AddLocation (a, GetLocation ($2));
+
+	  	$$ = a;
+	  }
+	| COMPLETE_COMPLETION
+	  {
+		$$ = new EmptyCompletion ();
+	  }
+	| anonymous_type_parameter COMPLETE_COMPLETION
+	  {
+	  	$$ = $1;
+	  }
+	;
+
+anonymous_type_parameter
+	: identifier_inside_body ASSIGN variable_initializer
+	  {
+		var lt = (LocatedToken)$1;
+	  	$$ = new AnonymousTypeParameter ((Expression)$3, lt.Value, lt.Location);
+	  	lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| identifier_inside_body
+	  {
+		var lt = (LocatedToken)$1;
+	  	$$ = new AnonymousTypeParameter (new SimpleName (lt.Value, lt.Location),
+	  		lt.Value, lt.Location);
+	  }
+	| member_access
+	  {
+	  	MemberAccess ma = (MemberAccess) $1;
+	  	$$ = new AnonymousTypeParameter (ma, ma.Name, ma.Location);
+	  }
+	| error
+	  {
+		report.Error (746, lexer.Location,
+			"Invalid anonymous type member declarator. Anonymous type members must be a member assignment, simple name or member access expression");
+		$$ = null;
+	  }
+	;
+
+opt_rank_specifier
+	: /* empty */
+	| rank_specifiers
+	;
+
+rank_specifiers
+	: rank_specifier
+	| rank_specifier rank_specifiers
+	  {
+	  	((ComposedTypeSpecifier) $1).Next = (ComposedTypeSpecifier) $2;
+	  	$$ = $1;
+	  }
+	;
+
+rank_specifier
+	: OPEN_BRACKET CLOSE_BRACKET
+	  {
+		$$ = ComposedTypeSpecifier.CreateArrayDimension (1, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| OPEN_BRACKET dim_separators CLOSE_BRACKET
+	  {
+		$$ = ComposedTypeSpecifier.CreateArrayDimension ((int)$2, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	;
+
+dim_separators
+	: COMMA
+	  {
+		$$ = 2;
+	  }
+	| dim_separators COMMA
+	  {
+		$$ = ((int) $1) + 1;
+	  }
+	;
+
+opt_array_initializer
+	: /* empty */
+	  {
+		$$ = null;
+	  }
+	| array_initializer
+	  {
+		$$ = $1;
+	  }
+	;
+
+array_initializer
+	: OPEN_BRACE CLOSE_BRACE
+	  {
+		var ai = new ArrayInitializer (0, GetLocation ($1));
+		ai.VariableDeclaration = current_variable;
+		lbag.AddLocation (ai, GetLocation ($2));
+		$$ = ai;
+	  }
+	| OPEN_BRACE variable_initializer_list opt_comma CLOSE_BRACE
+	  {
+		var ai = new ArrayInitializer ((List<Expression>) $2, GetLocation ($1));
+		ai.VariableDeclaration = current_variable;
+		if ($3 != null) {
+			lbag.AddLocation (ai, GetLocation ($3), GetLocation ($4));
+		} else {
+			lbag.AddLocation (ai, GetLocation ($4));
+		}
+		$$ = ai;
+	  }
+	;
+
+variable_initializer_list
+	: variable_initializer
+	  {
+		var list = new List<Expression> (4);
+		list.Add ((Expression) $1);
+		$$ = list;
+	  }
+	| variable_initializer_list COMMA variable_initializer
+	  {
+		var list = (List<Expression>) $1;
+		list.Add ((Expression) $3);
+		lbag.AddLocation (list, GetLocation ($2));
+		$$ = list;
+	  }
+	;
+
+typeof_expression
+	: TYPEOF open_parens_any typeof_type_expression CLOSE_PARENS
+	  {
+		$$ = new TypeOf ((FullNamedExpression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	;
+	
+typeof_type_expression
+	: type_and_void
+	| error
+	 {
+	 	Error_TypeExpected (lexer.Location);
+	 	$$ = null;
+	 }
+	;
+
+generic_dimension
+	: GENERIC_DIMENSION
+	  {
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "generics");
+
+		$$ = $1;
+	  }
+	;
+	
+qualified_alias_member
+	: IDENTIFIER DOUBLE_COLON
+	  {
+		var lt = (LocatedToken) $1;
+		if (lang_version == LanguageVersion.ISO_1)
+			FeatureIsNotAvailable (lt.Location, "namespace alias qualifier");
+		savedLocation = GetLocation ($2);
+		$$ = lt;		
+	  }
+	;
+
+sizeof_expression
+	: SIZEOF open_parens_any type CLOSE_PARENS
+	  { 
+		$$ = new SizeOf ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| SIZEOF open_parens_any type error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new SizeOf ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+checked_expression
+	: CHECKED open_parens_any expression CLOSE_PARENS
+	  {
+		$$ = new CheckedExpr ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| CHECKED error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new CheckedExpr (null, GetLocation ($1));
+	  }
+	;
+
+unchecked_expression
+	: UNCHECKED open_parens_any expression CLOSE_PARENS
+	  {
+		$$ = new UnCheckedExpr ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| UNCHECKED error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new UnCheckedExpr (null, GetLocation ($1));
+	  }
+	;
+
+pointer_member_access
+	: primary_expression OP_PTR IDENTIFIER opt_type_argument_list
+	  {
+		var lt = (LocatedToken) $3;
+		$$ = new MemberAccess (new Indirection ((Expression) $1, GetLocation ($2)), lt.Value, (TypeArguments) $4, lt.Location);
+	  }
+	;
+
+anonymous_method_expression
+	: DELEGATE opt_anonymous_method_signature
+	  {
+		start_anonymous (false, (ParametersCompiled) $2, false, GetLocation ($1));
+	  }
+	  block
+	  {
+		$$ = end_anonymous ((ParametersBlock) $4);
+		if ((ParametersCompiled) $2 != ParametersCompiled.Undefined) {
+			lbag.AddLocation ($$, GetLocation ($1), PopLocation (), PopLocation ());
+		} else {
+			lbag.AddLocation ($$, GetLocation ($1));
+		}
+	  }
+	| ASYNC DELEGATE opt_anonymous_method_signature
+	  {
+		start_anonymous (false, (ParametersCompiled) $3, true, GetLocation ($1));
+	  }
+	  block
+	  {
+		$$ = end_anonymous ((ParametersBlock) $5);
+		
+		if ((ParametersCompiled) $3 != ParametersCompiled.Undefined) {
+			lbag.AddLocation ($$, GetLocation ($1), GetLocation ($2), PopLocation (), PopLocation ());
+		} else {
+			lbag.AddLocation ($$, GetLocation ($1), GetLocation ($2));
+		}
+	  }
+	;
+
+opt_anonymous_method_signature
+	: 
+	  {
+		$$ = ParametersCompiled.Undefined;
+	  } 
+	| anonymous_method_signature
+	;
+
+anonymous_method_signature
+	: OPEN_PARENS
+	  {
+	  	valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+	  opt_formal_parameter_list CLOSE_PARENS
+	  {
+		valid_param_mod = 0;
+	  	$$ = $3;
+	  	PushLocation (GetLocation ($3));
+	  	PushLocation (GetLocation ($1));
+	  }
+	;
+
+default_value_expression
+	: DEFAULT open_parens_any type CLOSE_PARENS
+	  {
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($1), "default value expression");
+
+		$$ = new DefaultValueExpression ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	;
+
+unary_expression
+	: primary_expression
+	| BANG prefixed_unary_expression
+	  {
+		$$ = new Unary (Unary.Operator.LogicalNot, (Expression) $2, GetLocation ($1));
+	  }
+	| TILDE prefixed_unary_expression
+	  {
+		$$ = new Unary (Unary.Operator.OnesComplement, (Expression) $2, GetLocation ($1));
+	  }
+	| OPEN_PARENS_CAST type CLOSE_PARENS prefixed_unary_expression
+	  {
+		$$ = new Cast ((FullNamedExpression) $2, (Expression) $4, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	| AWAIT prefixed_unary_expression
+	  {
+		if (!async_block) {
+			 if (current_anonymous_method is LambdaExpression) {
+				report.Error (4034, GetLocation ($1),
+					"The `await' operator can only be used when its containing lambda expression is marked with the `async' modifier");
+			} else if (current_anonymous_method != null) {
+				report.Error (4035, GetLocation ($1),
+					"The `await' operator can only be used when its containing anonymous method is marked with the `async' modifier");
+			} else if (interactive_async != null) {
+				current_block.Explicit.RegisterAsyncAwait ();
+				interactive_async = true;
+			} else {
+				report.Error (4033, GetLocation ($1),
+					"The `await' operator can only be used when its containing method is marked with the `async' modifier");
+			}
+		} else {
+			current_block.Explicit.RegisterAsyncAwait ();
+		}
+		
+		$$ = new Await ((Expression) $2, GetLocation ($1));
+	  }
+	| BANG error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Unary (Unary.Operator.LogicalNot, null, GetLocation ($1));
+	  }
+	| TILDE error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Unary (Unary.Operator.OnesComplement, null, GetLocation ($1));
+	  }
+	| OPEN_PARENS_CAST type CLOSE_PARENS error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Cast ((FullNamedExpression) $2, null, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	| AWAIT error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Await (null, GetLocation ($1));
+	  }
+	;
+
+	//
+	// The idea to split this out is from Rhys' grammar
+	// to solve the problem with casts.
+	//
+prefixed_unary_expression
+	: unary_expression
+	| PLUS prefixed_unary_expression
+	  { 
+	  	$$ = new Unary (Unary.Operator.UnaryPlus, (Expression) $2, GetLocation ($1));
+	  } 
+	| MINUS prefixed_unary_expression 
+	  { 
+		$$ = new Unary (Unary.Operator.UnaryNegation, (Expression) $2, GetLocation ($1));
+	  }
+	| OP_INC prefixed_unary_expression 
+	  {
+		$$ = new UnaryMutator (UnaryMutator.Mode.PreIncrement, (Expression) $2, GetLocation ($1));
+	  }
+	| OP_DEC prefixed_unary_expression 
+	  {
+		$$ = new UnaryMutator (UnaryMutator.Mode.PreDecrement, (Expression) $2, GetLocation ($1));
+	  }
+	| STAR prefixed_unary_expression
+	  {
+		$$ = new Indirection ((Expression) $2, GetLocation ($1));
+	  }
+	| BITWISE_AND prefixed_unary_expression
+	  {
+		$$ = new Unary (Unary.Operator.AddressOf, (Expression) $2, GetLocation ($1));
+	  }
+	| PLUS error
+	  { 
+		Error_SyntaxError (yyToken);
+
+	  	$$ = new Unary (Unary.Operator.UnaryPlus, null, GetLocation ($1));
+	  } 
+	| MINUS error 
+	  { 
+		Error_SyntaxError (yyToken);
+
+		$$ = new Unary (Unary.Operator.UnaryNegation, null, GetLocation ($1));
+	  }
+	| OP_INC error 
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new UnaryMutator (UnaryMutator.Mode.PreIncrement, null, GetLocation ($1));
+	  }
+	| OP_DEC error 
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new UnaryMutator (UnaryMutator.Mode.PreDecrement, null, GetLocation ($1));
+	  }
+	| STAR error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Indirection (null, GetLocation ($1));
+	  }
+	| BITWISE_AND error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Unary (Unary.Operator.AddressOf, null, GetLocation ($1));
+	  }
+	;
+
+multiplicative_expression
+	: prefixed_unary_expression
+	| multiplicative_expression STAR prefixed_unary_expression
+	  {
+		$$ = new Binary (Binary.Operator.Multiply, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| multiplicative_expression DIV prefixed_unary_expression
+	  {
+		$$ = new Binary (Binary.Operator.Division, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| multiplicative_expression PERCENT prefixed_unary_expression 
+	  {
+		$$ = new Binary (Binary.Operator.Modulus, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| multiplicative_expression STAR error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Multiply, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| multiplicative_expression DIV error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Division, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| multiplicative_expression PERCENT error 
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Modulus, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+additive_expression
+	: multiplicative_expression
+	| additive_expression PLUS multiplicative_expression 
+	  {
+		$$ = new Binary (Binary.Operator.Addition, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| additive_expression MINUS multiplicative_expression
+	  {
+		$$ = new Binary (Binary.Operator.Subtraction, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| additive_expression PLUS error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Addition, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| additive_expression MINUS error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Subtraction, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| additive_expression AS type
+	  {
+		$$ = new As ((Expression) $1, (Expression) $3, GetLocation ($2));
+	  }
+	| additive_expression IS is_match_expr opt_identifier
+	  {
+		var is_expr = new Is ((Expression) $1, (Expression) $3, GetLocation ($2));
+		if ($4 != null) {
+			if (lang_version != LanguageVersion.Experimental)
+				FeatureIsNotAvailable (GetLocation ($4), "type pattern matching");
+
+			var lt = (LocatedToken) $4;
+			is_expr.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+			current_block.AddLocalName (is_expr.Variable);
+		}
+
+		$$ = is_expr;
+	  }
+	| additive_expression AS error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new As ((Expression) $1, null, GetLocation ($2));
+	  }
+	| additive_expression IS error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Is ((Expression) $1, null, GetLocation ($2));
+	  }
+	| AWAIT IS type
+	  {
+		var lt = (LocatedToken) $1;
+		$$ = new Is (new SimpleName (lt.Value, lt.Location), (Expression) $3, GetLocation ($2));
+	  }
+	| AWAIT AS type
+	  {
+		var lt = (LocatedToken) $1;
+		$$ = new As (new SimpleName (lt.Value, lt.Location), (Expression) $3, GetLocation ($2));
+	  }
+	;
+
+is_match_expr
+	: match_type
+	| match_type rank_specifiers
+	  {
+		if ($1 is VarExpr)
+			$1 = new SimpleName ("var", ((VarExpr) $1).Location);
+
+		$$ = new ComposedCast ((FullNamedExpression) $1, (ComposedTypeSpecifier) $2);
+	  }
+	| literal
+	| PLUS prefixed_unary_expression
+	  {
+		$$ = new Unary (Unary.Operator.UnaryPlus, (Expression) $2, GetLocation ($1));
+	  }
+	| MINUS prefixed_unary_expression
+	  {
+		$$ = new Unary (Unary.Operator.UnaryNegation, (Expression) $2, GetLocation ($1));
+	  }
+	;
+
+match_type
+	: primary_expression_or_type opt_nullable
+	  {
+		Expression expr = (Expression) $1;
+		if ($2 == null) {
+			SimpleName sn = expr as SimpleName;
+			if (sn != null && sn.Name == "var")
+				$$ = new VarExpr (sn.Location);
+			else
+				$$ = $1;
+		} else if (expr is ATypeNameExpression) {
+			$$ = new ComposedCast ((ATypeNameExpression)expr, (ComposedTypeSpecifier) $2);
+		} else {
+			Error_ExpectingTypeName (expr);
+			$$ = null;
+		}
+	  }
+	| primary_expression_or_type pointer_stars
+	  {
+		ATypeNameExpression expr = $1 as ATypeNameExpression;
+
+		if (expr != null) {
+			$$ = new ComposedCast (expr, (ComposedTypeSpecifier) $2);
+		} else {
+			Error_ExpectingTypeName ((Expression)$1);
+			$$ = expr;
+		}
+	  }
+	| builtin_type_expression
+	| void_invalid
+	;
+
+shift_expression
+	: additive_expression
+	| shift_expression OP_SHIFT_LEFT additive_expression
+	  {
+		$$ = new Binary (Binary.Operator.LeftShift, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| shift_expression OP_SHIFT_RIGHT additive_expression
+	  {
+		$$ = new Binary (Binary.Operator.RightShift, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| shift_expression OP_SHIFT_LEFT error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.LeftShift, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| shift_expression OP_SHIFT_RIGHT error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.RightShift, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	; 
+
+relational_expression
+	: shift_expression
+	| relational_expression OP_LT shift_expression
+	  {
+		$$ = new Binary (Binary.Operator.LessThan, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_GT shift_expression
+	  {
+		$$ = new Binary (Binary.Operator.GreaterThan, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_LE shift_expression
+	  {
+		$$ = new Binary (Binary.Operator.LessThanOrEqual, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_GE shift_expression
+	  {
+		$$ = new Binary (Binary.Operator.GreaterThanOrEqual, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_LT error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.LessThan, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_GT error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.GreaterThan, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_LE error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.LessThanOrEqual, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| relational_expression OP_GE error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.GreaterThanOrEqual, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+equality_expression
+	: relational_expression
+	| equality_expression OP_EQ relational_expression
+	  {
+		$$ = new Binary (Binary.Operator.Equality, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| equality_expression OP_NE relational_expression
+	  {
+		$$ = new Binary (Binary.Operator.Inequality, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| equality_expression OP_EQ error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Equality, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| equality_expression OP_NE error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.Inequality, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	; 
+
+and_expression
+	: equality_expression
+	| and_expression BITWISE_AND equality_expression
+	  {
+		$$ = new Binary (Binary.Operator.BitwiseAnd, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| and_expression BITWISE_AND error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.BitwiseAnd, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+exclusive_or_expression
+	: and_expression
+	| exclusive_or_expression CARRET and_expression
+	  {
+		$$ = new Binary (Binary.Operator.ExclusiveOr, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| exclusive_or_expression CARRET error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.ExclusiveOr, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+inclusive_or_expression
+	: exclusive_or_expression
+	| inclusive_or_expression BITWISE_OR exclusive_or_expression
+	  {
+		$$ = new Binary (Binary.Operator.BitwiseOr, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| inclusive_or_expression BITWISE_OR error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.BitwiseOr, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+conditional_and_expression
+	: inclusive_or_expression
+	| conditional_and_expression OP_AND inclusive_or_expression
+	  {
+		$$ = new Binary (Binary.Operator.LogicalAnd, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| conditional_and_expression OP_AND error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.LogicalAnd, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+conditional_or_expression
+	: conditional_and_expression
+	| conditional_or_expression OP_OR conditional_and_expression
+	  {
+		$$ = new Binary (Binary.Operator.LogicalOr, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| conditional_or_expression OP_OR error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Binary (Binary.Operator.LogicalOr, (Expression) $1, null);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+	
+null_coalescing_expression
+	: conditional_or_expression
+	| conditional_or_expression OP_COALESCING null_coalescing_expression
+	  {
+		if (lang_version < LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (GetLocation ($2), "null coalescing operator");
+			
+		$$ = new Nullable.NullCoalescingOperator ((Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+conditional_expression
+	: null_coalescing_expression
+	| null_coalescing_expression INTERR expression COLON expression
+	  {
+		$$ = new Conditional (new BooleanExpression ((Expression) $1), (Expression) $3, (Expression) $5, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	| null_coalescing_expression INTERR expression error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Conditional (new BooleanExpression ((Expression) $1), (Expression) $3, null, GetLocation ($2));
+	  }
+	| null_coalescing_expression INTERR expression COLON error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Conditional (new BooleanExpression ((Expression) $1), (Expression) $3, null, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	| null_coalescing_expression INTERR expression COLON CLOSE_BRACE
+	  {
+		Error_SyntaxError (Token.CLOSE_BRACE);
+
+		$$ = new Conditional (new BooleanExpression ((Expression) $1), (Expression) $3, null, GetLocation ($2));
+		lbag.AddLocation ($$, GetLocation ($4));
+		lexer.putback ('}');
+	  }
+	;
+
+assignment_expression
+	: prefixed_unary_expression ASSIGN expression
+	  {
+		$$ = new SimpleAssign ((Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_MULT_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.Multiply, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_DIV_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.Division, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_MOD_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.Modulus, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_ADD_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.Addition, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_SUB_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.Subtraction, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_SHIFT_LEFT_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.LeftShift, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_SHIFT_RIGHT_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.RightShift, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_AND_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.BitwiseAnd, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_OR_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.BitwiseOr, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| prefixed_unary_expression OP_XOR_ASSIGN expression
+	  {
+		$$ = new CompoundAssign (Binary.Operator.ExclusiveOr, (Expression) $1, (Expression) $3);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+lambda_parameter_list
+	: lambda_parameter
+	  {
+		var pars = new List<Parameter> (4);
+		pars.Add ((Parameter) $1);
+		parameterListCommas.Clear ();
+		$$ = pars;
+	  }
+	| lambda_parameter_list COMMA lambda_parameter
+	  {
+		var pars = (List<Parameter>) $1;
+		Parameter p = (Parameter)$3;
+		if (pars[0].GetType () != p.GetType ()) {
+			report.Error (748, p.Location, "All lambda parameters must be typed either explicitly or implicitly");
+		}
+		
+		pars.Add (p);
+		parameterListCommas.Add (GetLocation ($2));
+
+		$$ = pars;
+	  }
+	;
+
+lambda_parameter
+	: parameter_modifier parameter_type identifier_inside_body
+	  {
+		var lt = (LocatedToken) $3;
+
+		$$ = new Parameter ((FullNamedExpression) $2, lt.Value, (Parameter.Modifier) $1, null, lt.Location);
+	  }
+	| parameter_type identifier_inside_body
+	  {
+		var lt = (LocatedToken) $2;
+
+		$$ = new Parameter ((FullNamedExpression) $1, lt.Value, Parameter.Modifier.NONE, null, lt.Location);
+	  }
+	| IDENTIFIER
+	  {
+	  	var lt = (LocatedToken) $1;
+		$$ = new ImplicitLambdaParameter (lt.Value, lt.Location);
+	  }
+	| AWAIT
+	  {
+	  	var lt = (LocatedToken) Error_AwaitAsIdentifier ($1);
+		$$ = new ImplicitLambdaParameter (lt.Value, lt.Location);
+	  }
+	;
+
+opt_lambda_parameter_list
+	: /* empty */			{ $$ = ParametersCompiled.EmptyReadOnlyParameters; }
+	| lambda_parameter_list		{ 
+		var pars_list = (List<Parameter>) $1;
+		$$ = new ParametersCompiled (pars_list.ToArray ());
+		lbag.AddLocation ($$, parameterListCommas);
+	  }
+	;
+
+lambda_expression_body
+	: {
+		start_block (Location.Null);
+	  }
+	  expression	// All expressions must handle error or current block won't be restored and breaking ast completely
+	  {
+		Block b = end_block (Location.Null);
+		b.IsCompilerGenerated = true;
+		b.AddStatement (new ContextualReturn ((Expression) $2));
+		$$ = b;
+	  } 
+	| block
+	| error
+	  {
+	  	// Handles only cases like foo = x.FirstOrDefault (l => );
+	  	// where we must restore current_variable
+		Block b = end_block (Location.Null);
+		b.IsCompilerGenerated = true;
+
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	  }
+	;
+
+expression_or_error
+	: expression
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	  }
+	;
+	
+lambda_expression
+	: IDENTIFIER ARROW 
+	  {
+		var lt = (LocatedToken) $1;	
+		Parameter p = new ImplicitLambdaParameter (lt.Value, lt.Location);
+		start_anonymous (true, new ParametersCompiled (p), false, lt.Location);
+	  }
+	  lambda_expression_body
+	  {
+		$$ = end_anonymous ((ParametersBlock) $4);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| AWAIT ARROW
+	  {
+		var lt = (LocatedToken) Error_AwaitAsIdentifier ($1);
+		Parameter p = new ImplicitLambdaParameter (lt.Value, lt.Location);
+		start_anonymous (true, new ParametersCompiled (p), false, lt.Location);
+	  }
+	  lambda_expression_body
+	  {
+		$$ = end_anonymous ((ParametersBlock) $4);
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| ASYNC identifier_inside_body ARROW
+	  {
+		var lt = (LocatedToken) $2;
+		Parameter p = new ImplicitLambdaParameter (lt.Value, lt.Location);
+		start_anonymous (true, new ParametersCompiled (p), true, lt.Location);
+	  }
+	  lambda_expression_body
+	  {
+		$$ = end_anonymous ((ParametersBlock) $5);
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($3));
+	  }
+	| OPEN_PARENS_LAMBDA
+	  {
+	  	valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+	  opt_lambda_parameter_list CLOSE_PARENS ARROW 
+	  {
+	  	valid_param_mod = 0;
+		start_anonymous (true, (ParametersCompiled) $3, false, GetLocation ($1));
+	  }
+	  lambda_expression_body
+	  {
+		$$ = end_anonymous ((ParametersBlock) $7);
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($4), GetLocation ($5));
+	  }
+	| ASYNC OPEN_PARENS_LAMBDA
+	  {
+	  	valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;	  
+	  }
+	  opt_lambda_parameter_list CLOSE_PARENS ARROW 
+	  {
+	  	valid_param_mod = 0;
+		start_anonymous (true, (ParametersCompiled) $4, true, GetLocation ($1));
+	  }
+	  lambda_expression_body
+	  {
+		$$ = end_anonymous ((ParametersBlock) $8);
+		lbag.AddLocation ($$, GetLocation ($1), GetLocation ($2), GetLocation ($5), GetLocation ($6));
+	  }
+	;
+
+expression
+	: assignment_expression 
+	| non_assignment_expression
+	;
+	
+non_assignment_expression
+	: conditional_expression
+	| lambda_expression
+	| query_expression
+	| ARGLIST
+	  {
+		$$ = new ArglistAccess (GetLocation ($1));
+	  }
+	;
+	
+undocumented_expressions
+	: REFVALUE OPEN_PARENS non_assignment_expression COMMA type CLOSE_PARENS
+	  {
+		$$ = new RefValueExpr ((Expression) $3, (FullNamedExpression) $5, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4), GetLocation ($6));
+	  }
+	| REFTYPE open_parens_any expression CLOSE_PARENS
+	  {
+		$$ = new RefTypeExpr ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| MAKEREF open_parens_any expression CLOSE_PARENS
+	  {
+		$$ = new MakeRefExpr ((Expression) $3, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));	  
+	  }
+	;
+
+constant_expression
+	: expression
+	;
+
+boolean_expression
+	: expression
+	  {
+		$$ = new BooleanExpression ((Expression) $1);
+	  }
+	;
+
+opt_primary_parameters
+	: /* empty */
+	  {
+	  	$$ = null;
+	  }
+	| primary_parameters
+	;
+
+primary_parameters
+	: OPEN_PARENS opt_formal_parameter_list CLOSE_PARENS
+	  {
+		$$ = $2;
+
+		// Cannot use opt_formal_parameter_list because it can be shared instance for empty parameters
+	  	lbag.AppendToMember (current_container, GetLocation ($1), GetLocation ($3));
+
+		if (lang_version < LanguageVersion.V_6)
+			FeatureIsNotAvailable (GetLocation ($1), "primary constructor");
+	  }
+	;
+
+opt_primary_parameters_with_class_base
+	: /* empty */
+	  {
+	  	$$ = null;
+	  }
+	| class_base
+	  {
+		$$ = null;
+	  }
+	| primary_parameters
+	  {
+		$$ = $1;
+	  }
+	| primary_parameters class_base
+	  {
+		$$ = $1;
+	  }
+	| primary_parameters class_base OPEN_PARENS
+	  {
+		++lexer.parsing_block;
+		current_type.PrimaryConstructorBaseArgumentsStart = GetLocation ($3);
+	  }
+	  opt_argument_list CLOSE_PARENS
+	  {
+		lbag.AppendToMember (current_container, GetLocation ($6));
+		current_type.PrimaryConstructorBaseArguments = (Arguments) $5;
+		--lexer.parsing_block;
+
+		$$ = $1;
+	  }
+	;
+
+//
+// 10 classes
+//
+class_declaration
+	: opt_attributes
+	  opt_modifiers
+	  opt_partial
+	  CLASS
+	  {
+	  }
+	  type_declaration_name
+	  {
+		lexer.ConstraintsParsing = true;
+
+		Class c = new Class (current_container, (MemberName) $6, (Modifiers) $2, (Attributes) $1);
+		if (((c.ModFlags & Modifiers.STATIC) != 0) && lang_version == LanguageVersion.ISO_1) {
+			FeatureIsNotAvailable (c.Location, "static classes");
+		}
+			
+		push_current_container (c, $3);
+		lbag.AddMember (current_container, GetModifierLocations (), GetLocation ($4));
+		valid_param_mod = ParameterModifierType.PrimaryConstructor;
+	  }
+	  opt_primary_parameters_with_class_base
+	  opt_type_parameter_constraints_clauses
+	  {
+		valid_param_mod = 0;
+		lexer.ConstraintsParsing = false;
+
+		if ($8 != null)
+			current_type.PrimaryConstructorParameters = (ParametersCompiled) $8;
+
+		if ($9 != null)
+			current_container.SetConstraints ((List<Constraints>) $9);
+
+		if (doc_support) {
+			current_container.PartialContainer.DocComment = Lexer.consume_doc_comment ();
+			Lexer.doc_state = XmlCommentState.Allowed;
+		}
+		
+		lexer.parsing_modifiers = true;
+	  }
+	  OPEN_BRACE opt_class_member_declarations CLOSE_BRACE
+	  {
+		--lexer.parsing_declaration;
+		if (doc_support)
+			Lexer.doc_state = XmlCommentState.Allowed;
+	  }
+	  opt_semicolon 
+	  {
+		if ($15 == null) {
+			lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13));
+		} else {
+			lbag.AppendToMember (current_container, GetLocation ($11), GetLocation ($13), GetLocation ($15));
+		}
+		$$ = pop_current_class ();
+	  }
+	;	
+
+opt_partial
+	: /* empty */
+	  { $$ = null; }
+	| PARTIAL
+	  { $$ = $1; StoreModifierLocation (Modifiers.PARTIAL, GetLocation ($1)); } // location
+	;
+
+opt_modifiers
+	: /* empty */
+	  {
+	    mod_locations = null;
+		$$ = ModifierNone;
+		lexer.parsing_modifiers = false;
+	  }
+	| modifiers
+	  {
+		lexer.parsing_modifiers = false;		
+	  }
+	;
+
+modifiers
+	: modifier
+	| modifiers modifier
+	  { 
+		var m1 = (Modifiers) $1;
+		var m2 = (Modifiers) $2;
+
+		if ((m1 & m2) != 0) {
+			report.Error (1004, lexer.Location - ModifiersExtensions.Name (m2).Length,
+				"Duplicate `{0}' modifier", ModifiersExtensions.Name (m2));
+		} else if ((m2 & Modifiers.AccessibilityMask) != 0 && (m1 & Modifiers.AccessibilityMask) != 0 &&
+			((m2 | m1 & Modifiers.AccessibilityMask) != (Modifiers.PROTECTED | Modifiers.INTERNAL))) {
+			report.Error (107, lexer.Location - ModifiersExtensions.Name (m2).Length,
+				"More than one protection modifier specified");
+		}
+		
+		$$ = m1 | m2;
+	  }
+	;
+
+modifier
+	: NEW
+	  {
+		$$ = Modifiers.NEW;
+		StoreModifierLocation ($$, GetLocation ($1));
+		
+		if (current_container.Kind == MemberKind.Namespace)
+			report.Error (1530, GetLocation ($1), "Keyword `new' is not allowed on namespace elements");
+	  }
+	| PUBLIC
+	  {
+		$$ = Modifiers.PUBLIC;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| PROTECTED
+	  {
+		$$ = Modifiers.PROTECTED;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| INTERNAL
+	  {
+		$$ = Modifiers.INTERNAL;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| PRIVATE
+	  {
+		$$ = Modifiers.PRIVATE;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| ABSTRACT
+	  {
+		$$ = Modifiers.ABSTRACT;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| SEALED
+	  {
+		$$ = Modifiers.SEALED;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| STATIC
+	  {
+		$$ = Modifiers.STATIC;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| READONLY
+	  {
+		$$ = Modifiers.READONLY;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| VIRTUAL
+	  {
+		$$ = Modifiers.VIRTUAL;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| OVERRIDE
+	  {
+		$$ = Modifiers.OVERRIDE;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| EXTERN
+	  {
+		$$ = Modifiers.EXTERN;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| VOLATILE
+	  {
+		$$ = Modifiers.VOLATILE;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	| UNSAFE
+	  {
+		$$ = Modifiers.UNSAFE;
+		StoreModifierLocation ($$, GetLocation ($1));
+		if (!settings.Unsafe)
+			Error_UnsafeCodeNotAllowed (GetLocation ($1));
+	  }
+	| ASYNC
+	  {
+		$$ = Modifiers.ASYNC;
+		StoreModifierLocation ($$, GetLocation ($1));
+	  }
+	;
+	
+opt_class_base
+	: /* empty */
+	| class_base
+	;
+
+class_base
+	: COLON type_list
+	 {
+		current_type.SetBaseTypes ((List<FullNamedExpression>) $2);
+		lbag.AppendToMember (current_type, GetLocation ($1));
+	 }
+	| COLON type_list error
+	  {
+		Error_SyntaxError (yyToken);
+
+		current_type.SetBaseTypes ((List<FullNamedExpression>) $2);
+	  }
+	;
+
+opt_type_parameter_constraints_clauses
+	: /* empty */
+	| type_parameter_constraints_clauses 
+	  {
+		$$ = $1;
+	  }
+	;
+
+type_parameter_constraints_clauses
+	: type_parameter_constraints_clause
+	  {
+		var constraints = new List<Constraints> (1);
+		constraints.Add ((Constraints) $1);
+		$$ = constraints;
+	  }
+	| type_parameter_constraints_clauses type_parameter_constraints_clause
+	  {
+		var constraints = (List<Constraints>) $1;
+		Constraints new_constraint = (Constraints)$2;
+
+		foreach (Constraints c in constraints) {
+			if (new_constraint.TypeParameter.Value == c.TypeParameter.Value) {
+				report.Error (409, new_constraint.Location,
+					"A constraint clause has already been specified for type parameter `{0}'",
+					new_constraint.TypeParameter.Value);
+			}
+		}
+
+		constraints.Add (new_constraint);
+		$$ = constraints;
+	  }
+	; 
+
+type_parameter_constraints_clause
+	: WHERE IDENTIFIER COLON type_parameter_constraints
+	  {
+		var lt = (LocatedToken) $2;
+		$$ = new Constraints (new SimpleMemberName (lt.Value, lt.Location), (List<FullNamedExpression>) $4, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }
+	| WHERE IDENTIFIER error
+	  {
+		Error_SyntaxError (yyToken);
+	  
+		var lt = (LocatedToken) $2;
+		$$ = new Constraints (new SimpleMemberName (lt.Value, lt.Location), null, GetLocation ($1));
+	  }
+	; 
+
+type_parameter_constraints
+	: type_parameter_constraint
+	  {
+		var constraints = new List<FullNamedExpression> (1);
+		constraints.Add ((FullNamedExpression) $1);
+		$$ = constraints;
+	  }
+	| type_parameter_constraints COMMA type_parameter_constraint
+	  {
+		var constraints = (List<FullNamedExpression>) $1;
+		var prev = constraints [constraints.Count - 1] as SpecialContraintExpr;
+		if (prev != null && (prev.Constraint & SpecialConstraint.Constructor) != 0) {			
+			report.Error (401, GetLocation ($2), "The `new()' constraint must be the last constraint specified");
+		}
+		
+		prev = $3 as SpecialContraintExpr;
+		if (prev != null) {
+			if ((prev.Constraint & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0) {
+				report.Error (449, prev.Location, "The `class' or `struct' constraint must be the first constraint specified");			
+			} else {
+			 	prev = constraints [0] as SpecialContraintExpr;
+			 	if (prev != null && (prev.Constraint & SpecialConstraint.Struct) != 0) {			
+					report.Error (451, GetLocation ($3), "The `new()' constraint cannot be used with the `struct' constraint");
+				}
+			}
+		}
+
+		constraints.Add ((FullNamedExpression) $3);
+		lbag.AddLocation (constraints, GetLocation ($2));
+		$$ = constraints;
+	  }
+	;
+
+type_parameter_constraint
+	: type
+	  {
+		if ($1 is ComposedCast)
+			report.Error (706, GetLocation ($1), "Invalid constraint type `{0}'", ((ComposedCast)$1).GetSignatureForError ());
+	  
+	  	$$ = $1;
+	  }
+	| NEW OPEN_PARENS CLOSE_PARENS
+	  {
+		$$ = new SpecialContraintExpr (SpecialConstraint.Constructor, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($2), GetLocation ($3));
+	  }
+	| CLASS
+	  {
+		$$ = new SpecialContraintExpr (SpecialConstraint.Class, GetLocation ($1));
+	  }
+	| STRUCT
+	  {
+		$$ = new SpecialContraintExpr (SpecialConstraint.Struct, GetLocation ($1));
+	  }
+	;
+
+opt_type_parameter_variance
+	: /* empty */
+	  {
+		$$ = null;
+	  }
+	| type_parameter_variance
+	  {
+		if (lang_version <= LanguageVersion.V_3)
+			FeatureIsNotAvailable (lexer.Location, "generic type variance");
+		
+		$$ = $1;
+	  }
+	;
+
+type_parameter_variance
+	: OUT
+	  {
+		$$ = new VarianceDecl (Variance.Covariant, GetLocation ($1));
+		savedLocation = GetLocation ($1);
+	  }
+	| IN
+	  {
+		$$ = new VarianceDecl (Variance.Contravariant, GetLocation ($1));
+		savedLocation = GetLocation ($1);
+	  }
+	;
+
+//
+// Statements (8.2)
+//
+
+//
+// A block is "contained" on the following places:
+//	method_body
+//	property_declaration as part of the accessor body (get/set)
+//      operator_declaration
+//	constructor_declaration
+//	destructor_declaration
+//	event_declaration as part of add_accessor_declaration or remove_accessor_declaration
+//      
+block
+	: OPEN_BRACE  
+	  {
+		++lexer.parsing_block;
+		start_block (GetLocation ($1));
+	  } 
+	  opt_statement_list block_end
+	  {
+		$$ = $4;
+	  }
+	;
+
+block_end 
+	: CLOSE_BRACE 
+	  {
+	 	--lexer.parsing_block;
+		$$ = end_block (GetLocation ($1));
+	  }
+	| COMPLETE_COMPLETION
+	  {
+	 	--lexer.parsing_block;
+		$$ = end_block (lexer.Location);
+	  }
+	;
+
+
+block_prepared
+	: OPEN_BRACE
+	  {
+		++lexer.parsing_block;
+		current_block.StartLocation = GetLocation ($1);
+	  }
+	  opt_statement_list CLOSE_BRACE 
+	  {
+		--lexer.parsing_block;
+		$$ = end_block (GetLocation ($4));
+	  } | CLOSE_BRACE
+	  {
+		report.Error (1525, GetLocation ($1), "Unexpected symbol '}', expected '{'");
+		lexer.putback ('}');
+		$$ = end_block (GetLocation ($1));
+	  }
+	;
+
+block_prepared_strict
+	: OPEN_BRACE
+	  {
+		++lexer.parsing_block;
+		current_block.StartLocation = GetLocation ($1);
+	  }
+	  opt_statement_list CLOSE_BRACE 
+	  {
+		--lexer.parsing_block;
+		$$ = end_block (GetLocation ($4));
+	  }
+	;
+
+opt_statement_list
+	: /* empty */
+	| statement_list 
+	;
+
+statement_list
+	: statement
+	| statement_list statement
+	;
+
+statement
+	: block_variable_declaration
+	  {
+		current_block.AddStatement ((Statement) $1);
+	  }
+	| valid_declaration_statement
+	  {
+		current_block.AddStatement ((Statement) $1);
+	  }
+	| labeled_statement
+// WORKAROUND:Remove that rule, if it is >really< fixed.
+	| IDENTIFIER error
+	{
+		Error_SyntaxError (yyToken);
+		var lt =(LocatedToken) $1;
+		var sn = new SimpleName (lt.Value, lt.Location);
+		current_block.AddStatement(new StatementErrorExpression (sn));
+		$$ = null;
+	}
+////////
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	  }
+	;
+
+//
+// The interactive_statement and its derivatives are only 
+// used to provide a special version of `expression_statement'
+// that has a side effect of assigning the expression to
+// $retval
+//
+interactive_statement_list
+	: interactive_statement
+	| interactive_statement_list interactive_statement
+	;
+
+interactive_statement
+	: block_variable_declaration
+	  {
+		current_block.AddStatement ((Statement) $1);
+	  }
+	| interactive_valid_declaration_statement
+	  {
+		current_block.AddStatement ((Statement) $1);
+	  }
+	| labeled_statement
+	;
+
+valid_declaration_statement
+	: block
+	| empty_statement
+	| expression_statement
+	| selection_statement
+	| iteration_statement
+	| jump_statement		  
+	| try_statement
+	| checked_statement
+	| unchecked_statement
+	| lock_statement
+	| using_statement
+	| unsafe_statement
+	| fixed_statement
+	;
+
+interactive_valid_declaration_statement
+	: block
+	| empty_statement
+        | interactive_expression_statement
+	| selection_statement
+	| iteration_statement
+	| jump_statement		  
+	| try_statement
+	| checked_statement
+	| unchecked_statement
+	| lock_statement
+	| using_statement
+	| unsafe_statement
+	| fixed_statement
+	;
+
+embedded_statement
+	: valid_declaration_statement
+	| block_variable_declaration
+	  {
+		  report.Error (1023, GetLocation ($1), "An embedded statement may not be a declaration or labeled statement");
+		  $$ = null;
+	  }
+	| labeled_statement
+	  {
+		  report.Error (1023, GetLocation ($1), "An embedded statement may not be a declaration or labeled statement");
+		  $$ = null;
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new EmptyStatement (GetLocation ($1));
+	  }
+	;
+
+empty_statement
+	: SEMICOLON
+	  {
+		// Uses lexer.Location because semicolon location is not kept in quick mode
+		$$ = new EmptyStatement (lexer.Location);
+	  }
+	;
+
+labeled_statement
+	: identifier_inside_body COLON 
+	  {
+		var lt = (LocatedToken) $1;
+		LabeledStatement labeled = new LabeledStatement (lt.Value, current_block, lt.Location);
+		lbag.AddLocation (labeled, GetLocation ($2));
+		current_block.AddLabel (labeled);
+		current_block.AddStatement (labeled);
+	  }
+	  statement
+	;
+
+variable_type
+	: variable_type_simple
+	| variable_type_simple rank_specifiers
+	  {
+		if ($1 is VarExpr)
+			$1 = new SimpleName ("var", ((VarExpr) $1).Location);
+	  
+		$$ = new ComposedCast ((FullNamedExpression) $1, (ComposedTypeSpecifier) $2);
+	  }
+	;
+
+/* 
+ * The following is from Rhys' grammar:
+ * > Types in local variable declarations must be recognized as 
+ * > expressions to prevent reduce/reduce errors in the grammar.
+ * > The expressions are converted into types during semantic analysis.
+ */
+variable_type_simple
+	: primary_expression_or_type opt_nullable
+	  { 
+		// Ok, the above "primary_expression" is there to get rid of
+		// both reduce/reduce and shift/reduces in the grammar, it should
+		// really just be "type_name".  If you use type_name, a reduce/reduce
+		// creeps up.  If you use namespace_or_type_name (which is all we need
+		// really) two shift/reduces appear.
+		// 
+
+		// So the super-trick is that primary_expression
+		// can only be either a SimpleName or a MemberAccess. 
+		// The MemberAccess case arises when you have a fully qualified type-name like :
+		// Foo.Bar.Blah i;
+		// SimpleName is when you have
+		// Blah i;
+		
+		Expression expr = (Expression) $1;
+		if ($2 == null) {
+			SimpleName sn = expr as SimpleName;
+			if (sn != null && sn.Name == "var")
+				$$ = new VarExpr (sn.Location);
+			else
+				$$ = $1;
+		} else if (expr is ATypeNameExpression) {
+			$$ = new ComposedCast ((ATypeNameExpression)expr, (ComposedTypeSpecifier) $2);
+		} else {
+			Error_ExpectingTypeName (expr);
+			$$ = null;
+		}
+	  }
+	| primary_expression_or_type pointer_stars
+	  {
+		ATypeNameExpression expr = $1 as ATypeNameExpression;
+
+		if (expr != null) {
+			$$ = new ComposedCast (expr, (ComposedTypeSpecifier) $2);
+		} else {
+			Error_ExpectingTypeName ((Expression)$1);
+			$$ = expr;
+		}
+	  }
+	| builtin_type_expression
+	| void_invalid
+	;
+	
+pointer_stars
+	: pointer_star
+	| pointer_star pointer_stars
+	  {
+	  	((ComposedTypeSpecifier) $1).Next = (ComposedTypeSpecifier) $2;
+	  	$$ = $1;
+	  }	  
+	;
+
+pointer_star
+	: STAR
+	  {
+		$$ = ComposedTypeSpecifier.CreatePointer (GetLocation ($1));
+	  }
+	;
+
+identifier_inside_body
+	: IDENTIFIER
+	| AWAIT
+	  {
+	  	$$ = Error_AwaitAsIdentifier ($1);
+	  }
+	;
+
+block_variable_declaration
+	: variable_type identifier_inside_body
+	  {
+		var lt = (LocatedToken) $2;
+		var li = new LocalVariable (current_block, lt.Value, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new BlockVariable ((FullNamedExpression) $1, li);
+	  }
+	  opt_local_variable_initializer opt_variable_declarators semicolon_or_handle_error_close_brace
+	  {
+		$$ = current_variable;
+		current_variable = null;
+		if ($4 != null)
+			lbag.AddLocation ($$, PopLocation (), GetLocation ($6));
+		else
+			lbag.AddLocation ($$, GetLocation ($6));
+	  }
+	| CONST variable_type identifier_inside_body
+	  {
+		var lt = (LocatedToken) $3;
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.Constant, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new BlockConstant ((FullNamedExpression) $2, li);
+	  }
+	  const_variable_initializer opt_const_declarators SEMICOLON
+	  {
+		if (current_variable.Initializer != null) {
+			lbag.AddLocation (current_variable, GetLocation ($1), savedLocation, GetLocation ($7));
+		} else {
+			lbag.AddLocation (current_variable, GetLocation ($1), GetLocation ($7));
+		}
+		$$ = current_variable;;
+		current_variable = null;
+	  }
+	;
+
+semicolon_or_handle_error_close_brace 
+	: SEMICOLON
+	| CLOSE_BRACE {
+		// Redundant, but wont regress
+		report.Error (1525, lexer.Location, "Unexpected symbol }");
+		lexer.putback ('}');
+		$$ = $1;
+	  }
+	;
+
+opt_local_variable_initializer
+	: /* empty */
+	| ASSIGN block_variable_initializer
+	  {
+		current_variable.Initializer = (Expression) $2;
+		PushLocation (GetLocation ($1));
+		$$ = current_variable;
+	  }
+	| error
+	  {
+	  	if (yyToken == Token.OPEN_BRACKET_EXPR) {
+			report.Error (650, lexer.Location,
+				"Syntax error, bad array declarator. To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type");
+		} else {
+			Error_SyntaxError (yyToken);
+		}
+	  }
+	;
+
+opt_variable_declarators
+	: /* empty */
+	| variable_declarators
+	;
+	
+opt_using_or_fixed_variable_declarators
+	: /* empty */
+	| variable_declarators
+	  {
+		foreach (var d in current_variable.Declarators) {
+			if (d.Initializer == null)
+				Error_MissingInitializer (d.Variable.Location);
+		}
+	  }
+	;	
+	
+variable_declarators
+	: variable_declarator
+	| variable_declarators variable_declarator
+	;
+	
+variable_declarator
+	: COMMA identifier_inside_body
+	  {
+		var lt = (LocatedToken) $2;	  
+		var li = new LocalVariable (current_variable.Variable, lt.Value, lt.Location);
+		var d = new BlockVariableDeclarator (li, null);
+		current_variable.AddDeclarator (d);
+		current_block.AddLocalName (li);
+	  	lbag.AddLocation (d, GetLocation ($1));
+	  }
+	| COMMA identifier_inside_body ASSIGN block_variable_initializer
+	  {
+		var lt = (LocatedToken) $2;	  
+		var li = new LocalVariable (current_variable.Variable, lt.Value, lt.Location);
+		var d = new BlockVariableDeclarator (li, (Expression) $4);
+		current_variable.AddDeclarator (d);
+		current_block.AddLocalName (li);
+	  	lbag.AddLocation (d, GetLocation ($1), GetLocation ($3));
+	  }
+	;
+	
+const_variable_initializer
+	: /* empty */
+	  {
+		report.Error (145, lexer.Location, "A const field requires a value to be provided");
+	  }
+	| ASSIGN constant_initializer_expr 
+	  {
+		savedLocation = GetLocation ($1);
+		current_variable.Initializer = (Expression) $2;
+	  }
+	;
+	
+opt_const_declarators
+	: /* empty */
+	| const_declarators
+	;
+	
+const_declarators
+	: const_declarator
+	| const_declarators const_declarator
+	;
+	
+const_declarator
+	: COMMA identifier_inside_body ASSIGN constant_initializer_expr
+	  {
+		var lt = (LocatedToken) $2;	  
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.Constant, lt.Location);
+		var d = new BlockVariableDeclarator (li, (Expression) $4);
+		current_variable.AddDeclarator (d);
+		current_block.AddLocalName (li);
+	  	lbag.AddLocation (d, GetLocation ($1), GetLocation ($3));
+	  }
+	;
+	
+block_variable_initializer
+	: variable_initializer
+	| STACKALLOC simple_type OPEN_BRACKET_EXPR expression CLOSE_BRACKET
+	  {
+		$$ = new StackAlloc ((Expression) $2, (Expression) $4, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3), GetLocation ($5));
+	  }
+	| STACKALLOC simple_type
+	  {
+		report.Error (1575, GetLocation ($1), "A stackalloc expression requires [] after type");
+		$$ = new StackAlloc ((Expression) $2, null, GetLocation ($1));		
+	  }
+	;
+
+expression_statement
+	: statement_expression SEMICOLON
+	  {
+		$$ = $1;
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	| statement_expression COMPLETE_COMPLETION { $$ = $1; }
+	| statement_expression CLOSE_BRACE
+	  {
+		$$ = $1;
+		report.Error (1002, GetLocation ($2), "; expected");
+		lexer.putback ('}');
+	  }
+	;
+
+interactive_expression_statement
+	: interactive_statement_expression SEMICOLON { $$ = $1; }
+	| interactive_statement_expression COMPLETE_COMPLETION { $$ = $1; }
+	;
+
+	//
+	// We have to do the wrapping here and not in the case above,
+	// because statement_expression is used for example in for_statement
+	//
+statement_expression
+	: expression
+	  {
+		ExpressionStatement s = $1 as ExpressionStatement;
+		if (s == null) {
+			var expr = $1 as Expression;
+			$$ = new StatementErrorExpression (expr);
+		} else {
+			$$ = new StatementExpression (s);
+		}
+	  }
+	;
+
+interactive_statement_expression
+	: expression
+	  {
+		Expression expr = (Expression) $1;
+		$$ = new StatementExpression (new OptionalAssign (expr, lexer.Location));
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new EmptyStatement (GetLocation ($1));
+	  }
+	;
+	
+selection_statement
+	: if_statement
+	| switch_statement
+	; 
+
+if_statement
+	: IF open_parens_any boolean_expression CLOSE_PARENS 
+	  embedded_statement
+	  { 
+		if ($5 is EmptyStatement)
+			Warning_EmptyStatement (GetLocation ($5));
+		
+		$$ = new If ((BooleanExpression) $3, (Statement) $5, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| IF open_parens_any boolean_expression CLOSE_PARENS
+	  embedded_statement ELSE embedded_statement
+	  {
+		$$ = new If ((BooleanExpression) $3, (Statement) $5, (Statement) $7, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4), GetLocation ($6));
+		
+		if ($5 is EmptyStatement)
+			Warning_EmptyStatement (GetLocation ($5));
+		if ($7 is EmptyStatement)
+			Warning_EmptyStatement (GetLocation ($7));
+	  }
+	| IF open_parens_any boolean_expression error
+	  {
+		Error_SyntaxError (yyToken);
+		
+		$$ = new If ((BooleanExpression) $3, null, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	;
+
+switch_statement
+	: SWITCH open_parens_any expression CLOSE_PARENS OPEN_BRACE
+	  {
+		start_block (GetLocation ($5));
+	  }
+	  opt_switch_sections CLOSE_BRACE
+	  {
+		$$ = new Switch ((Expression) $3, (ExplicitBlock) current_block.Explicit, GetLocation ($1));	
+		end_block (GetLocation ($8));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4), GetLocation ($5), GetLocation ($8));
+	  }
+	| SWITCH open_parens_any expression error
+	  {
+		Error_SyntaxError (yyToken);
+	  
+		$$ = new Switch ((Expression) $3, null, GetLocation ($1));	
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	;
+
+opt_switch_sections
+	: /* empty */ 		
+      {
+		report.Warning (1522, 1, current_block.StartLocation, "Empty switch block"); 
+	  }
+	| switch_sections
+	;
+
+switch_sections
+	: switch_section 
+	| switch_sections switch_section
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+	  } 
+	;
+
+switch_section
+	: switch_labels statement_list 
+	;
+
+switch_labels
+	: switch_label 
+	  {
+	  	var label = (SwitchLabel) $1;
+	  	label.SectionStart = true;
+		current_block.AddStatement (label);
+	  }
+	| switch_labels switch_label 
+	  {
+		current_block.AddStatement ((Statement) $2);
+	  }
+	;
+
+switch_label
+	: CASE constant_expression COLON
+	 {
+	 	$$ = new SwitchLabel ((Expression) $2, GetLocation ($1));
+	 	lbag.AddLocation ($$, GetLocation ($3));
+	 }
+	| CASE constant_expression error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new SwitchLabel ((Expression) $2, GetLocation ($1));
+	  }
+	| DEFAULT_COLON
+	  {
+		$$ = new SwitchLabel (null, GetLocation ($1));
+	  }
+	;
+
+iteration_statement
+	: while_statement
+	| do_statement
+	| for_statement
+	| foreach_statement
+	;
+
+while_statement
+	: WHILE open_parens_any boolean_expression CLOSE_PARENS embedded_statement
+	  {
+		if ($5 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($5));
+	  
+		$$ = new While ((BooleanExpression) $3, (Statement) $5, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| WHILE open_parens_any boolean_expression error
+	  {
+		Error_SyntaxError (yyToken);
+		
+		$$ = new While ((BooleanExpression) $3, null, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	;
+
+do_statement
+	: DO embedded_statement WHILE open_parens_any boolean_expression CLOSE_PARENS SEMICOLON
+	  {
+		$$ = new Do ((Statement) $2, (BooleanExpression) $5, GetLocation ($1), GetLocation ($3));
+		lbag.AddStatement ($$, GetLocation ($3), GetLocation ($4), GetLocation ($6), GetLocation ($7));
+	  }
+	| DO embedded_statement error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new Do ((Statement) $2, null, GetLocation ($1), Location.Null);
+	  }
+	| DO embedded_statement WHILE open_parens_any boolean_expression error
+	  {
+		Error_SyntaxError (yyToken);
+	  
+		$$ = new Do ((Statement) $2, (BooleanExpression) $5, GetLocation ($1), GetLocation ($3));
+		lbag.AddStatement ($$, GetLocation ($3), GetLocation ($4));
+	  }
+	;
+
+for_statement
+	: FOR open_parens_any
+	  {
+		start_block (GetLocation ($2));
+		current_block.IsCompilerGenerated = true;
+		For f = new For (GetLocation ($1));
+		current_block.AddStatement (f);
+		lbag.AddStatement (f, current_block.StartLocation);
+		$$ = f;
+	  }
+	  for_statement_cont
+	  {
+		$$ = $4;
+	  }
+	;
+	
+// Has to use be extra rule to recover started block
+for_statement_cont
+	: opt_for_initializer SEMICOLON
+	  {
+		For f =  (For) $0;
+		f.Initializer = (Statement) $1;
+		lbag.AddLocation (f, GetLocation ($2));
+		$$ = f;
+	  }
+	  for_statement_condition
+	  {
+		$$ = $4;
+	  }
+	| opt_for_initializer CLOSE_PARENS {
+		report.Error (1525, GetLocation ($2), "Unexpected symbol ')', expected ';'");
+		For f =  (For) $0;
+		f.Initializer = (Statement) $1;
+		lbag.AddLocation (f, GetLocation ($2));
+		$$ = end_block (GetLocation ($2));
+	}
+	;
+
+for_statement_condition
+	: opt_for_condition SEMICOLON
+	  {
+		For f =  (For) $0;
+		f.Condition = (BooleanExpression) $1;
+		lbag.AddLocation (f, GetLocation ($2));
+		$$ = f;
+	  }
+	  for_statement_end
+	  {
+		$$ = $4;
+	  }
+
+	| boolean_expression CLOSE_PARENS {
+		report.Error (1525, GetLocation ($2), "Unexpected symbol ')', expected ';'");
+		For f =  (For) $0;
+		f.Condition = (BooleanExpression) $1;
+		lbag.AddLocation (f, GetLocation ($2));
+		$$ = end_block (GetLocation ($2));
+	}
+	;
+
+for_statement_end
+	: opt_for_iterator CLOSE_PARENS
+	  embedded_statement
+	  {
+		For f =  (For) $0;
+		f.Iterator = (Statement) $1;
+		
+		if ($3 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($3));
+	  
+		f.Statement = (Statement) $3;
+		lbag.AddLocation (f, GetLocation ($2));
+
+		$$ = end_block (GetLocation ($2));
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = end_block (current_block.StartLocation);
+	  }
+	;
+
+opt_for_initializer
+	: /* empty */		{ $$ = new EmptyStatement (lexer.Location); }
+	| for_initializer	
+	;
+
+for_initializer
+	: variable_type identifier_inside_body
+	  {
+		var lt = (LocatedToken) $2;
+		var li = new LocalVariable (current_block, lt.Value, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new BlockVariable ((FullNamedExpression) $1, li);
+	  }
+	  opt_local_variable_initializer opt_variable_declarators
+	  {
+		$$ = current_variable;
+		if ($4 != null)
+			lbag.AddLocation (current_variable, PopLocation ());
+
+		current_variable = null;
+	  }
+	| statement_expression_list
+	;
+
+opt_for_condition
+	: /* empty */		{ $$ = null; }
+	| boolean_expression
+	;
+
+opt_for_iterator
+	: /* empty */		{ $$ = new EmptyStatement (lexer.Location); }
+	| for_iterator
+	;
+
+for_iterator
+	: statement_expression_list
+	;
+
+statement_expression_list
+	: statement_expression
+	| statement_expression_list COMMA statement_expression
+	  {
+	  	var sl = $1 as StatementList;
+	  	if (sl == null) {
+	  		sl = new StatementList ((Statement) $1, (Statement) $3);
+			lbag.AddStatement (sl, GetLocation ($2));
+	  	} else {
+	  		sl.Add ((Statement) $3);
+	  		lbag.AddLocation (sl, GetLocation ($2));
+	  		
+	  	}
+	  		
+		$$ = sl;
+	  }
+	;
+
+foreach_statement
+	: FOREACH open_parens_any type error
+	  {
+		report.Error (230, GetLocation ($1), "Type and identifier are both required in a foreach statement");
+
+		start_block (GetLocation ($2));
+		current_block.IsCompilerGenerated = true;
+		
+		Foreach f = new Foreach ((Expression) $3, null, null, null, null, GetLocation ($1));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation ($2));
+		$$ = end_block (GetLocation ($4));
+	  }
+	| FOREACH open_parens_any type identifier_inside_body error
+	  {
+		Error_SyntaxError (yyToken);
+	
+		start_block (GetLocation ($2));
+		current_block.IsCompilerGenerated = true;
+		
+		var lt = (LocatedToken) $4;
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.ForeachVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		
+		Foreach f = new Foreach ((Expression) $3, li, null, null, null, GetLocation ($1));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation ($2));
+		$$ = end_block (GetLocation ($5));
+	  }
+	| FOREACH open_parens_any type identifier_inside_body IN expression CLOSE_PARENS 
+	  {
+		start_block (GetLocation ($2));
+		current_block.IsCompilerGenerated = true;
+		
+		var lt = (LocatedToken) $4;
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.ForeachVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		$$ = li;
+	  } 
+	  embedded_statement
+	  {
+		if ($9 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($9));
+		
+		Foreach f = new Foreach ((Expression) $3, (LocalVariable) $8, (Expression) $6, (Statement) $9, current_block, GetLocation ($1));
+		lbag.AddStatement (f, GetLocation ($2), GetLocation ($5), GetLocation ($7));
+		end_block (GetLocation ($7));
+		
+		$$ = f;
+	  }
+	| FOREACH open_parens_any type identifier_inside_body error
+	  {
+		start_block (GetLocation ($2));
+		current_block.IsCompilerGenerated = true;
+		var lt = $4 as LocatedToken;
+		var li = lt != null ? new LocalVariable (current_block, lt.Value, LocalVariable.Flags.ForeachVariable | LocalVariable.Flags.Used, lt.Location) : null;
+		
+		Foreach f = new Foreach ((Expression) $3, li, null, null, null, GetLocation ($1));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation ($2));
+		$$ = end_block (GetLocation ($5));
+	  }
+	| FOREACH open_parens_any type error
+	  {
+		Foreach f = new Foreach ((Expression) $3, null, null, null, null, GetLocation ($1));
+		current_block.AddStatement (f);
+		
+		lbag.AddStatement (f, GetLocation ($2));
+		$$ = f;
+	  }
+	;
+
+jump_statement
+	: break_statement
+	| continue_statement
+	| goto_statement
+	| return_statement
+	| throw_statement
+	| yield_statement
+	;
+
+break_statement
+	: BREAK SEMICOLON
+	  {
+		$$ = new Break (GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	;
+
+continue_statement
+	: CONTINUE SEMICOLON
+	  {
+		$$ = new Continue (GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	| CONTINUE error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new Continue (GetLocation ($1));
+	  }
+	;
+
+goto_statement
+	: GOTO identifier_inside_body SEMICOLON 
+	  {
+		var lt = (LocatedToken) $2;
+		$$ = new Goto (lt.Value, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($3));
+	  }
+	| GOTO CASE constant_expression SEMICOLON
+	  {
+		$$ = new GotoCase ((Expression) $3, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| GOTO DEFAULT SEMICOLON 
+	  {
+		$$ = new GotoDefault (GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($3));
+	  }
+	; 
+
+return_statement
+	: RETURN opt_expression SEMICOLON
+	  {
+		$$ = new Return ((Expression) $2, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($3));
+	  }
+	| RETURN expression error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new Return ((Expression) $2, GetLocation ($1));
+	  }
+	| RETURN error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new Return (null, GetLocation ($1));
+	  }
+	;
+
+throw_statement
+	: THROW opt_expression SEMICOLON
+	  {
+		$$ = new Throw ((Expression) $2, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($3));
+	  }
+	| THROW expression error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new Throw ((Expression) $2, GetLocation ($1));
+	  }
+	| THROW error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new Throw (null, GetLocation ($1));
+	  }
+	;
+
+yield_statement 
+	: identifier_inside_body RETURN opt_expression SEMICOLON
+	  {
+		var lt = (LocatedToken) $1;
+		string s = lt.Value;
+		if (s != "yield"){
+			report.Error (1003, lt.Location, "; expected");
+		} else if ($3 == null) {
+			report.Error (1627, GetLocation ($4), "Expression expected after yield return");
+		} else if (lang_version == LanguageVersion.ISO_1){
+			FeatureIsNotAvailable (lt.Location, "iterators");
+		}
+		
+		current_block.Explicit.RegisterIteratorYield ();
+		$$ = new Yield ((Expression) $3, lt.Location);
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| identifier_inside_body RETURN expression error
+	  {
+		Error_SyntaxError (yyToken);
+
+		var lt = (LocatedToken) $1;
+		string s = lt.Value;
+		if (s != "yield"){
+			report.Error (1003, lt.Location, "; expected");
+		} else if ($3 == null) {
+			report.Error (1627, GetLocation ($4), "Expression expected after yield return");
+		} else if (lang_version == LanguageVersion.ISO_1){
+			FeatureIsNotAvailable (lt.Location, "iterators");
+		}
+		
+		current_block.Explicit.RegisterIteratorYield ();
+		$$ = new Yield ((Expression) $3, lt.Location);
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	| identifier_inside_body BREAK SEMICOLON
+	  {
+		var lt = (LocatedToken) $1;
+		string s = lt.Value;
+		if (s != "yield"){
+			report.Error (1003, lt.Location, "; expected");
+		} else if (lang_version == LanguageVersion.ISO_1){
+			FeatureIsNotAvailable (lt.Location, "iterators");
+		}
+		
+		current_block.ParametersBlock.TopBlock.IsIterator = true;
+		$$ = new YieldBreak (lt.Location);
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($3));
+	  }
+	;
+
+opt_expression
+	: /* empty */
+	| expression
+	;
+
+try_statement
+	: TRY block catch_clauses
+	  {
+		$$ = new TryCatch ((Block) $2, (List<Catch>) $3, GetLocation ($1), false);
+	  }
+	| TRY block FINALLY block
+	  {
+		$$ = new TryFinally ((Statement) $2, (ExplicitBlock) $4, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($3));
+	  }
+	| TRY block catch_clauses FINALLY block
+	  {
+		$$ = new TryFinally (new TryCatch ((Block) $2, (List<Catch>) $3, GetLocation ($1), true), (ExplicitBlock) $5, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($4));
+	  }
+	| TRY block error
+	  {
+		Error_SyntaxError (1524, yyToken);
+		$$ = new TryCatch ((Block) $2, null, GetLocation ($1), false);
+	  }
+	;
+
+catch_clauses
+	: catch_clause 
+	  {
+		var l = new List<Catch> (2);
+
+		l.Add ((Catch) $1);
+		$$ = l;
+	  }
+	| catch_clauses catch_clause
+	  {
+		var l = (List<Catch>) $1;
+		
+		Catch c = (Catch) $2;
+		var prev_catch = l [l.Count - 1];
+		if (prev_catch.IsGeneral && prev_catch.Filter == null) {
+			report.Error (1017, c.loc, "Try statement already has an empty catch block");
+		}
+		
+		l.Add (c);
+		$$ = l;
+	  }
+	;
+
+opt_identifier
+	: /* empty */
+	| identifier_inside_body
+	;
+
+catch_clause 
+	: CATCH opt_catch_filter block
+	  {
+	  	var c = new Catch ((ExplicitBlock) $3, GetLocation ($1));
+	  	c.Filter = (CatchFilterExpression) $2;
+	  	$$ = c;
+	  }
+	| CATCH open_parens_any type opt_identifier CLOSE_PARENS
+	  {
+		start_block (GetLocation ($2));
+		var c = new Catch ((ExplicitBlock) current_block, GetLocation ($1));
+		c.TypeExpression = (FullNamedExpression) $3;
+
+		if ($4 != null) {
+			var lt = (LocatedToken) $4;
+			c.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+			current_block.AddLocalName (c.Variable);
+		}
+
+		lbag.AddLocation (c, GetLocation ($2), GetLocation ($5));
+		$$ = c;
+	  }
+	  opt_catch_filter block_prepared
+	  {
+	  	((Catch) $6).Filter = (CatchFilterExpression) $7;
+		$$ = $6;
+	  }
+	| CATCH open_parens_any error
+	  {
+	  	if (yyToken == Token.CLOSE_PARENS) {
+			report.Error (1015, lexer.Location,
+				"A type that derives from `System.Exception', `object', or `string' expected");
+		} else {
+			Error_SyntaxError (yyToken);
+		}
+		
+		$$ = new Catch (null, GetLocation ($1));
+	  }
+	| CATCH open_parens_any type opt_identifier CLOSE_PARENS error
+	  {
+		Error_SyntaxError (yyToken);
+
+		// Required otherwise missing block could not be detected because
+		// start_block is run early
+		var c = new Catch (null, GetLocation ($1));
+		c.TypeExpression = (FullNamedExpression) $3;
+		
+		if ($4 != null) {
+			var lt = (LocatedToken) $4;
+			c.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+		}
+
+		if ($4 != null) {
+			var lt = (LocatedToken) $4;
+			c.Variable = new LocalVariable (current_block, lt.Value, lt.Location);
+		}
+
+		lbag.AddLocation (c, GetLocation ($2), GetLocation ($5));
+
+		$$ = c;
+	  }
+	;
+
+opt_catch_filter
+	: /* empty */
+	| IF open_parens_any expression CLOSE_PARENS
+	  {
+		if (lang_version <= LanguageVersion.V_5)
+			FeatureIsNotAvailable (GetLocation ($1), "exception filter");
+
+	  	$$ = new CatchFilterExpression ((Expression) $3, GetLocation ($1));
+	  	lbag.AddLocation ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	;
+
+checked_statement
+	: CHECKED block
+	  {
+		$$ = new Checked ((Block) $2, GetLocation ($1));
+	  }
+	;
+
+unchecked_statement
+	: UNCHECKED block
+	  {
+		$$ = new Unchecked ((Block) $2, GetLocation ($1));
+	  }
+	;
+
+unsafe_statement
+	: UNSAFE
+	  {
+		if (!settings.Unsafe)
+			Error_UnsafeCodeNotAllowed (GetLocation ($1));
+	  } block {
+		$$ = new Unsafe ((Block) $3, GetLocation ($1));
+	  }
+	;
+
+lock_statement
+	: LOCK open_parens_any expression CLOSE_PARENS embedded_statement
+	  {
+		if ($5 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($5));
+	  
+		$$ = new Lock ((Expression) $3, (Statement) $5, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| LOCK open_parens_any expression error
+	  {
+		Error_SyntaxError (yyToken);
+
+		$$ = new Lock ((Expression) $3, null, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	;
+
+fixed_statement
+	: FIXED open_parens_any variable_type identifier_inside_body
+	  {
+	    start_block (GetLocation ($2));
+	    
+		current_block.IsCompilerGenerated = true;
+		var lt = (LocatedToken) $4;
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.FixedVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new Fixed.VariableDeclaration ((FullNamedExpression) $3, li);
+	  }
+	  using_or_fixed_variable_initializer opt_using_or_fixed_variable_declarators CLOSE_PARENS
+	  {
+		$$ = current_variable;
+		current_variable = null;
+	  }
+	  embedded_statement
+	  {
+		if ($10 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($10));
+	  
+		Fixed f = new Fixed ((Fixed.VariableDeclaration) $9, (Statement) $10, GetLocation ($1));
+		current_block.AddStatement (f);
+		lbag.AddStatement (f, GetLocation ($2), GetLocation ($8));
+		$$ = end_block (GetLocation ($8));
+	  }
+	;
+
+using_statement
+	: USING open_parens_any variable_type identifier_inside_body
+	  {
+	    start_block (GetLocation ($2));
+	    
+		current_block.IsCompilerGenerated = true;
+		var lt = (LocatedToken) $4;
+		var li = new LocalVariable (current_block, lt.Value, LocalVariable.Flags.UsingVariable | LocalVariable.Flags.Used, lt.Location);
+		current_block.AddLocalName (li);
+		current_variable = new Using.VariableDeclaration ((FullNamedExpression) $3, li);
+	  }
+	  using_initialization CLOSE_PARENS
+	  {
+		$$ = current_variable;	  
+		current_variable = null;
+	  }
+	  embedded_statement
+	  {
+		if ($9 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($9));
+	  
+		Using u = new Using ((Using.VariableDeclaration) $8, (Statement) $9, GetLocation ($1));
+		lbag.AddStatement (u, GetLocation ($2), GetLocation ($7));
+		current_block.AddStatement (u);
+		$$ = end_block (GetLocation ($7));
+	  }
+	| USING open_parens_any expression CLOSE_PARENS embedded_statement
+	  {
+		if ($5 is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
+			Warning_EmptyStatement (GetLocation ($5));
+	  
+		$$ = new Using ((Expression) $3, (Statement) $5, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2), GetLocation ($4));
+	  }
+	| USING open_parens_any expression error
+	  {
+		Error_SyntaxError (yyToken);
+		
+		$$ = new Using ((Expression) $3, null, GetLocation ($1));
+		lbag.AddStatement ($$, GetLocation ($2));
+	  }
+	;
+	
+using_initialization
+	: using_or_fixed_variable_initializer opt_using_or_fixed_variable_declarators
+	| error
+	  {
+		// It has to be here for the parent to safely restore artificial block
+	  	Error_SyntaxError (yyToken);
+	  }
+	;
+	
+using_or_fixed_variable_initializer
+	: /* empty */
+	  {
+		Error_MissingInitializer (lexer.Location);
+	  }
+	| ASSIGN variable_initializer
+	  {
+		current_variable.Initializer = (Expression) $2;
+		lbag.AddLocation (current_variable, GetLocation ($1));
+		$$ = current_variable;
+	  }
+	;
+
+
+// LINQ
+
+query_expression
+	: first_from_clause query_body 
+	  {
+		lexer.query_parsing = false;
+			
+		Linq.AQueryClause from = $1 as Linq.AQueryClause;
+			
+		from.Tail.Next = (Linq.AQueryClause)$2;
+		$$ = from;
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+	| nested_from_clause query_body
+	  {
+		Linq.AQueryClause from = $1 as Linq.AQueryClause;
+			
+		from.Tail.Next = (Linq.AQueryClause)$2;
+		$$ = from;
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }	
+
+	// Bubble up COMPLETE_COMPLETION productions
+	| first_from_clause COMPLETE_COMPLETION {
+	        lexer.query_parsing = false;
+		$$ = $1;
+
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+	| nested_from_clause COMPLETE_COMPLETION {
+	        $$ = $1;
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+	;
+	
+first_from_clause
+	: FROM_FIRST identifier_inside_body IN expression
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) $2;
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)$4, rv, GetLocation ($1));
+		lbag.AddLocation (clause, GetLocation ($3));
+		$$ = new Linq.QueryExpression (clause);
+	  }
+	| FROM_FIRST type identifier_inside_body IN expression
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) $3;
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)$5, rv, GetLocation ($1)) {
+				IdentifierType = (FullNamedExpression)$2
+		};
+		lbag.AddLocation (clause, GetLocation ($4));
+		$$ = new Linq.QueryExpression (clause);
+	  }
+	;
+
+nested_from_clause
+	: FROM identifier_inside_body IN expression
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) $2;
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)$4, rv, GetLocation ($1));
+		lbag.AddLocation (clause, GetLocation ($3));
+		$$ = new Linq.QueryExpression (clause);
+	  }
+	| FROM type identifier_inside_body IN expression
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  
+		var lt = (LocatedToken) $3;
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+		var clause = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, (Expression)$5, rv, GetLocation ($1)) {
+				IdentifierType = (FullNamedExpression)$2
+		};
+		lbag.AddLocation (clause, GetLocation ($4));
+		$$ = new Linq.QueryExpression (clause);
+	  }
+	;
+	
+from_clause
+	: FROM identifier_inside_body IN
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error
+	  {
+		var lt = (LocatedToken) $2;
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+		$$ = new Linq.SelectMany ((Linq.QueryBlock)current_block, sn, (Expression)$5, GetLocation ($1));
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+		((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		lbag.AddLocation ($$, GetLocation ($3));
+	  }	  
+	| FROM type identifier_inside_body IN
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error
+	  {
+		var lt = (LocatedToken) $3;
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+
+		$$ = new Linq.SelectMany ((Linq.QueryBlock)current_block, sn, (Expression)$6, GetLocation ($1)) {
+			IdentifierType = (FullNamedExpression)$2
+		};
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+		
+		((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		
+		lbag.AddLocation ($$, GetLocation ($4));
+	  }
+	;	
+
+query_body
+	: query_body_clauses select_or_group_clause opt_query_continuation 
+	  {
+	  	Linq.AQueryClause head = (Linq.AQueryClause)$2;
+		
+		if ($3 != null)
+			head.Next = (Linq.AQueryClause)$3;
+				
+		if ($1 != null) {
+			Linq.AQueryClause clause = (Linq.AQueryClause)$1;
+			clause.Tail.Next = head;
+			head = clause;
+		}
+		
+		$$ = head;
+	  }
+	| select_or_group_clause opt_query_continuation
+	  {
+	  	Linq.AQueryClause head = (Linq.AQueryClause)$2;
+
+		if ($1 != null) {
+			Linq.AQueryClause clause = (Linq.AQueryClause)$1;
+			clause.Tail.Next = head;
+			head = clause;
+		}
+		
+		$$ = head;
+	  }
+	| query_body_clauses COMPLETE_COMPLETION
+	| query_body_clauses error
+	  {
+		report.Error (742, GetLocation ($2), "Unexpected symbol `{0}'. A query body must end with select or group clause", GetSymbolName (yyToken));
+		$$ = $1;
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = null;
+	  }
+	;
+	
+select_or_group_clause
+	: SELECT
+	  {
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error
+	  {
+		$$ = new Linq.Select ((Linq.QueryBlock)current_block, (Expression)$3, GetLocation ($1));
+
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+	| GROUP
+	  {
+	  	if (linq_clause_blocks == null)
+	  		linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  	linq_clause_blocks.Push ((Linq.QueryBlock)current_block);
+	  }
+	  expression_or_error
+	  {
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  by_expression
+	  {
+		var obj = (object[]) $5;
+
+		$$ = new Linq.GroupBy ((Linq.QueryBlock)current_block, (Expression)$3, linq_clause_blocks.Pop (), (Expression)obj[0], GetLocation ($1));
+		lbag.AddLocation ($$, (Location) obj[1]);
+		
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+	;
+
+by_expression
+	: BY expression_or_error
+	  {
+	  	$$ = new object[] { $2, GetLocation ($1) };
+	  }
+	| error
+	  {
+		Error_SyntaxError (yyToken);
+		$$ = new object[2] { null, Location.Null };
+	  }
+	;
+	
+query_body_clauses
+	: query_body_clause
+	| query_body_clauses query_body_clause
+	  {
+		((Linq.AQueryClause)$1).Tail.Next = (Linq.AQueryClause)$2;
+		$$ = $1;
+	  }
+	;
+	
+query_body_clause
+	: from_clause
+	| let_clause 
+	| where_clause
+	| join_clause
+	| orderby_clause
+	;
+	
+let_clause
+	: LET identifier_inside_body ASSIGN 
+	  {
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error
+	  {
+		var lt = (LocatedToken) $2;
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+	  	$$ = new Linq.Let ((Linq.QueryBlock) current_block, sn, (Expression)$5, GetLocation ($1));
+		lbag.AddLocation ($$, GetLocation ($3));
+	  	
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+		
+		((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+	  }
+	;
+
+where_clause
+	: WHERE
+	  {
+	  	current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error
+	  {
+		$$ = new Linq.Where ((Linq.QueryBlock)current_block, (Expression)$3, GetLocation ($1));
+
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  }
+	;
+	
+join_clause
+	: JOIN identifier_inside_body IN
+	  {
+		if (linq_clause_blocks == null)
+			linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+	  expression_or_error ON
+	  {
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+	  expression_or_error EQUALS
+	  {
+		current_block.AddStatement (new ContextualReturn ((Expression) $8));
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error opt_join_into
+	  {
+		current_block.AddStatement (new ContextualReturn ((Expression) $11));
+		current_block.SetEndLocation (lexer.Location);
+	  
+		var outer_selector = linq_clause_blocks.Pop ();
+		var block = linq_clause_blocks.Pop ();
+
+		var lt = (LocatedToken) $2;	
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+		Linq.RangeVariable into;
+		
+		if ($12 == null) {
+			into = sn;
+	  		$$ = new Linq.Join (block, sn, (Expression)$5, outer_selector, (Linq.QueryBlock) current_block, GetLocation ($1));
+			lbag.AddLocation ($$, GetLocation ($3), GetLocation ($6), GetLocation ($9));
+		} else {
+			//
+			// Set equals right side parent to beginning of linq query, it is not accessible therefore cannot cause name collisions
+			//
+			var parent = block.Parent;
+			while (parent is Linq.QueryBlock) {
+				parent = parent.Parent;
+			}
+			current_block.Parent = parent;
+			
+			((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		
+			lt = (LocatedToken) $12;
+			into = new Linq.RangeVariable (lt.Value, lt.Location);
+
+			$$ = new Linq.GroupJoin (block, sn, (Expression)$5, outer_selector, (Linq.QueryBlock) current_block, into, GetLocation ($1));	
+			lbag.AddLocation ($$, GetLocation ($3), GetLocation ($6), GetLocation ($9), opt_intoStack.Pop ());
+		}
+
+		current_block = block.Parent;
+		((Linq.QueryBlock)current_block).AddRangeVariable (into);
+	  }
+	| JOIN type identifier_inside_body IN
+	  {
+		if (linq_clause_blocks == null)
+			linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+	  expression_or_error ON
+	  {
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);
+	  }
+	  expression_or_error EQUALS
+	  {
+		current_block.AddStatement (new ContextualReturn ((Expression) $9));
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  expression_or_error opt_join_into
+	  {
+		current_block.AddStatement (new ContextualReturn ((Expression) $12));
+		current_block.SetEndLocation (lexer.Location);
+	  
+		var outer_selector = linq_clause_blocks.Pop ();
+		var block = linq_clause_blocks.Pop ();
+		
+		var lt = (LocatedToken) $3;
+		var sn = new Linq.RangeVariable (lt.Value, lt.Location);
+		Linq.RangeVariable into;
+		
+		if ($13 == null) {
+			into = sn;		
+	  		$$ = new Linq.Join (block, sn, (Expression)$6, outer_selector, (Linq.QueryBlock) current_block, GetLocation ($1)) {
+	  			IdentifierType = (FullNamedExpression)$2
+	  		};
+			lbag.AddLocation ($$, GetLocation ($3), GetLocation ($6), GetLocation ($9));
+		} else {
+			//
+			// Set equals right side parent to beginning of linq query, it is not accessible therefore cannot cause name collisions
+			//
+			var parent = block.Parent;
+			while (parent is Linq.QueryBlock) {
+				parent = parent.Parent;
+			}
+			current_block.Parent = parent;
+		
+			((Linq.QueryBlock)current_block).AddRangeVariable (sn);
+		
+			lt = (LocatedToken) $13;
+			into = new Linq.RangeVariable (lt.Value, lt.Location); // TODO:
+			
+			$$ = new Linq.GroupJoin (block, sn, (Expression)$6, outer_selector, (Linq.QueryBlock) current_block, into, GetLocation ($1)) {
+	  			IdentifierType = (FullNamedExpression)$2
+	  		};			
+			lbag.AddLocation ($$, GetLocation ($3), GetLocation ($6), GetLocation ($9), opt_intoStack.Pop ());
+		}
+		
+		current_block = block.Parent;
+		((Linq.QueryBlock)current_block).AddRangeVariable (into);		
+	  }
+	;
+	
+opt_join_into
+	: /* empty */
+	| INTO identifier_inside_body
+	  {
+		opt_intoStack.Push (GetLocation ($1));
+		$$ = $2;
+	  }
+	;
+	
+orderby_clause
+	: ORDERBY
+	  {
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		lbag.AddLocation (current_block, GetLocation ($1));
+	  }
+	  orderings
+	  {
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		$$ = $3;
+	  }
+	;
+	
+orderings
+	: order_by
+	| order_by COMMA
+	  {
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+	  }
+	  orderings_then_by
+	  {
+		((Linq.AQueryClause)$1).Next = (Linq.AQueryClause)$4;
+		$$ = $1;
+	  }
+	;
+	
+orderings_then_by
+	: then_by
+	| orderings_then_by COMMA
+	 {
+		current_block.SetEndLocation (lexer.Location);
+		current_block = current_block.Parent;
+	  
+		current_block = new Linq.QueryBlock ((Linq.QueryBlock) current_block, lexer.Location);	 
+	 }
+	 then_by
+	 {
+		((Linq.AQueryClause)$1).Tail.Next = (Linq.AQueryClause)$4;
+		$$ = $1;
+	 }
+	;	
+	
+order_by
+	: expression
+	  {
+		$$ = new Linq.OrderByAscending ((Linq.QueryBlock) current_block, (Expression)$1);	
+	  }
+	| expression ASCENDING
+	  {
+		$$ = new Linq.OrderByAscending ((Linq.QueryBlock) current_block, (Expression)$1);	
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| expression DESCENDING
+	  {
+		$$ = new Linq.OrderByDescending ((Linq.QueryBlock) current_block, (Expression)$1);	
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	;
+
+then_by
+	: expression
+	  {
+		$$ = new Linq.ThenByAscending ((Linq.QueryBlock) current_block, (Expression)$1);	
+	  }
+	| expression ASCENDING
+	  {
+		$$ = new Linq.ThenByAscending ((Linq.QueryBlock) current_block, (Expression)$1);	
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }
+	| expression DESCENDING
+	  {
+		$$ = new Linq.ThenByDescending ((Linq.QueryBlock) current_block, (Expression)$1);	
+		lbag.AddLocation ($$, GetLocation ($2));
+	  }	
+	;
+
+
+opt_query_continuation
+	: /* empty */
+	| INTO identifier_inside_body
+	  {
+		// query continuation block is not linked with query block but with block
+		// before. This means each query can use same range variable names for
+		// different identifiers.
+
+		current_block.SetEndLocation (GetLocation ($1));
+		current_block = current_block.Parent;
+	
+		current_block = new Linq.QueryBlock (current_block, lexer.Location);
+		
+		if (linq_clause_blocks == null)
+			linq_clause_blocks = new Stack<Linq.QueryBlock> ();
+	  		
+		linq_clause_blocks.Push ((Linq.QueryBlock) current_block);		
+	  }
+	  query_body
+	  {
+		var current_block = linq_clause_blocks.Pop ();	  
+		var lt = (LocatedToken) $2;
+		var rv = new Linq.RangeVariable (lt.Value, lt.Location);
+  		$$ = new Linq.QueryStartClause ((Linq.QueryBlock)current_block, null, rv, GetLocation ($1)) {
+  			next = (Linq.AQueryClause)$4
+  		};
+	  }
+	;
+	
+//
+// Support for using the compiler as an interactive parser
+//
+// The INTERACTIVE_PARSER token is first sent to parse our
+// productions;  If the result is a Statement, the parsing
+// is repeated, this time with INTERACTIVE_PARSE_WITH_BLOCK
+// to setup the blocks in advance.
+//
+// This setup is here so that in the future we can add 
+// support for other constructs (type parsing, namespaces, etc)
+// that do not require a block to be setup in advance
+//
+
+interactive_parsing
+	: EVAL_STATEMENT_PARSER EOF 
+	| EVAL_USING_DECLARATIONS_UNIT_PARSER using_directives opt_COMPLETE_COMPLETION
+	| EVAL_STATEMENT_PARSER
+	 { 
+		current_container = current_type = new Class (current_container, new MemberName ("<InteractiveExpressionClass>"), Modifiers.PUBLIC, null);
+
+		// (ref object retval)
+		Parameter [] mpar = new Parameter [1];
+		mpar [0] = new Parameter (new TypeExpression (compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null);
+
+		ParametersCompiled pars = new ParametersCompiled (mpar);
+		var mods = Modifiers.PUBLIC | Modifiers.STATIC;
+		if (settings.Unsafe)
+			mods |= Modifiers.UNSAFE;
+
+		current_local_parameters = pars;
+		var method = new InteractiveMethod (
+			current_type,
+			new TypeExpression (compiler.BuiltinTypes.Void, Location.Null),
+			mods,
+			pars);
+			
+		current_type.AddMember (method);			
+		oob_stack.Push (method);
+
+		interactive_async = false;
+
+		++lexer.parsing_block;
+		start_block (lexer.Location);
+	  }		
+	  interactive_statement_list opt_COMPLETE_COMPLETION
+	  {
+		--lexer.parsing_block;
+		var method = (InteractiveMethod) oob_stack.Pop ();
+		method.Block = (ToplevelBlock) end_block(lexer.Location);
+
+		if (interactive_async == true) {
+			method.ChangeToAsync ();
+		}
+
+		InteractiveResult = (Class) pop_current_class ();
+		current_local_parameters = null;
+	  } 
+	| EVAL_COMPILATION_UNIT_PARSER interactive_compilation_unit
+	;
+
+interactive_compilation_unit
+	: opt_extern_alias_directives opt_using_directives
+	| opt_extern_alias_directives opt_using_directives namespace_or_type_declarations
+	;
+
+opt_COMPLETE_COMPLETION
+	: /* nothing */
+	| COMPLETE_COMPLETION
+	;
+
+close_brace_or_complete_completion
+	: CLOSE_BRACE
+	| COMPLETE_COMPLETION
+	;
+	
+//
+// XML documentation code references micro parser
+//
+documentation_parsing
+	: DOC_SEE doc_cref
+	  {
+		module.DocumentationBuilder.ParsedName = (MemberName) $2;
+	  }
+	;
+
+doc_cref
+	: doc_type_declaration_name opt_doc_method_sig
+	  {
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$2;
+	  }
+	| builtin_types opt_doc_method_sig
+	  {
+		module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)$1;
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$2;
+		$$ = null;
+	  }
+	| VOID opt_doc_method_sig
+	  {
+		module.DocumentationBuilder.ParsedBuiltinType = new TypeExpression (compiler.BuiltinTypes.Void, GetLocation ($1));
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$2;
+		$$ = null;
+	  }
+	| builtin_types DOT IDENTIFIER opt_doc_method_sig
+	  {
+		module.DocumentationBuilder.ParsedBuiltinType = (TypeExpression)$1;
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$4;
+		var lt = (LocatedToken) $3;
+		$$ = new MemberName (lt.Value);
+	  }
+	| doc_type_declaration_name DOT THIS
+	  {
+		$$ = new MemberName ((MemberName) $1, MemberCache.IndexerNameAlias, Location.Null);
+	  }
+	| doc_type_declaration_name DOT THIS OPEN_BRACKET
+	  {
+		valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+	  opt_doc_parameters CLOSE_BRACKET
+	  {
+		module.DocumentationBuilder.ParsedParameters = (List<DocumentationParameter>)$6;
+		$$ = new MemberName ((MemberName) $1, MemberCache.IndexerNameAlias, Location.Null);
+	  }
+	| EXPLICIT OPERATOR type opt_doc_method_sig
+	  {
+		var p = (List<DocumentationParameter>)$4 ?? new List<DocumentationParameter> (1);
+		p.Add (new DocumentationParameter ((FullNamedExpression) $3));
+		module.DocumentationBuilder.ParsedParameters = p;
+		module.DocumentationBuilder.ParsedOperator = Operator.OpType.Explicit;
+		$$ = null;
+	  }
+	| IMPLICIT OPERATOR type opt_doc_method_sig
+	  {
+		var p = (List<DocumentationParameter>)$4 ?? new List<DocumentationParameter> (1);
+		p.Add (new DocumentationParameter ((FullNamedExpression) $3));
+		module.DocumentationBuilder.ParsedParameters = p;
+		module.DocumentationBuilder.ParsedOperator = Operator.OpType.Implicit;
+		$$ = null;
+	  }	  
+	| OPERATOR overloadable_operator opt_doc_method_sig
+	  {
+		var p = (List<DocumentationParameter>)$3;
+		module.DocumentationBuilder.ParsedParameters = p;
+		module.DocumentationBuilder.ParsedOperator = (Operator.OpType) $2;
+		$$ = null;
+	  }
+	;
+	
+doc_type_declaration_name
+	: type_declaration_name
+	| doc_type_declaration_name DOT type_declaration_name
+	  {
+		$$ = new MemberName (((MemberName) $1), (MemberName) $3);
+	  }
+	;
+	
+opt_doc_method_sig
+	: /* empty */
+	| OPEN_PARENS
+	  {
+		valid_param_mod = ParameterModifierType.Ref | ParameterModifierType.Out;
+	  }
+	  opt_doc_parameters CLOSE_PARENS
+	  {
+		$$ = $3;
+	  }
+	;
+	
+opt_doc_parameters
+	: /* empty */
+	  {
+		$$ = new List<DocumentationParameter> (0);
+	  }
+	| doc_parameters
+	;
+	
+doc_parameters
+	: doc_parameter
+	  {
+		var parameters = new List<DocumentationParameter> ();
+		parameters.Add ((DocumentationParameter) $1);
+		$$ = parameters;
+	  }
+	| doc_parameters COMMA doc_parameter
+	  {
+		var parameters = $1 as List<DocumentationParameter>;
+		parameters.Add ((DocumentationParameter) $3);
+		$$ = parameters;
+	  }
+	;
+	
+doc_parameter
+	: opt_parameter_modifier parameter_type
+	  {
+		if ($1 != null)
+			$$ = new DocumentationParameter ((Parameter.Modifier) $1, (FullNamedExpression) $2);
+		else
+			$$ = new DocumentationParameter ((FullNamedExpression) $2);
+	  }
+	;
+	
+%%
+
+// <summary>
+//  A class used to hold info about an operator declarator
+// </summary>
+class OperatorDeclaration {
+	public readonly Operator.OpType optype;
+	public readonly FullNamedExpression ret_type;
+	public readonly Location location;
+
+	public OperatorDeclaration (Operator.OpType op, FullNamedExpression ret_type, Location location)
+	{
+		optype = op;
+		this.ret_type = ret_type;
+		this.location = location;
+	}
+}
+
+void Error_ExpectingTypeName (Expression expr)
+{
+	if (expr is Invocation){
+		report.Error (1002, expr.Location, "Expecting `;'");
+	} else {
+		expr.Error_InvalidExpressionStatement (report);
+	}
+}
+
+void Error_ParameterModifierNotValid (string modifier, Location loc)
+{
+	report.Error (631, loc, "The parameter modifier `{0}' is not valid in this context",
+			              modifier);
+}
+
+void Error_DuplicateParameterModifier (Location loc, Parameter.Modifier mod)
+{
+	report.Error (1107, loc, "Duplicate parameter modifier `{0}'",
+  		Parameter.GetModifierSignature (mod));
+}
+
+void Error_TypeExpected (Location loc)
+{
+	report.Error (1031, loc, "Type expected");
+}
+
+void Error_UnsafeCodeNotAllowed (Location loc)
+{
+	report.Error (227, loc, "Unsafe code requires the `unsafe' command line option to be specified");
+}
+
+void Warning_EmptyStatement (Location loc)
+{
+	report.Warning (642, 3, loc, "Possible mistaken empty statement");
+}
+
+void Error_NamedArgumentExpected (NamedArgument a)
+{
+	report.Error (1738, a.Location, "Named arguments must appear after the positional arguments");
+}
+
+void Error_MissingInitializer (Location loc)
+{
+	report.Error (210, loc, "You must provide an initializer in a fixed or using statement declaration");
+}
+
+object Error_AwaitAsIdentifier (object token)
+{
+	if (async_block) {
+		report.Error (4003, GetLocation (token), "`await' cannot be used as an identifier within an async method or lambda expression");
+		return new LocatedToken ("await", GetLocation (token));
+	}
+
+	return token;
+}
+
+void push_current_container (TypeDefinition tc, object partial_token)
+{
+	if (module.Evaluator != null){
+		tc.Definition.Modifiers = tc.ModFlags = (tc.ModFlags & ~Modifiers.AccessibilityMask) | Modifiers.PUBLIC;
+		if (undo == null)
+			undo = new Undo ();
+
+		undo.AddTypeContainer (current_container, tc);
+	}
+	
+	if (partial_token != null)
+		current_container.AddPartial (tc);
+	else
+		current_container.AddTypeContainer (tc);
+		
+	++lexer.parsing_declaration;
+	current_container = tc;
+	current_type = tc;
+}
+
+TypeContainer pop_current_class ()
+{
+	var retval = current_container;
+
+	current_container = current_container.Parent;
+	current_type = current_type.Parent as TypeDefinition;
+
+	return retval;
+}
+
+[System.Diagnostics.Conditional ("FULL_AST")]
+void StoreModifierLocation (object token, Location loc)
+{
+	if (lbag == null)
+		return;
+
+	if (mod_locations == null)
+  		mod_locations = new List<Tuple<Modifiers, Location>> ();
+
+	mod_locations.Add (Tuple.Create ((Modifiers) token, loc));
+}
+
+List<Tuple<Modifiers, Location>> GetModifierLocations ()
+{
+	var result = mod_locations;
+	mod_locations = null;
+	return result;
+}
+
+[System.Diagnostics.Conditional ("FULL_AST")]
+void PushLocation (Location loc)
+{
+	if (location_stack == null)
+		location_stack = new Stack<Location> ();
+
+	location_stack.Push (loc);
+}
+
+Location PopLocation ()
+{
+	if (location_stack == null)
+		return Location.Null;
+
+	return location_stack.Pop ();
+}
+
+string CheckAttributeTarget (int token, string a, Location l)
+{
+	switch (a) {
+	case "assembly" : case "module" : case "field" : case "method" : case "param" : case "property" : case "type" :
+			return a;
+	}
+
+	if (!Tokenizer.IsValidIdentifier (a)) {
+		Error_SyntaxError (token);
+	} else {
+		report.Warning (658, 1, l,
+			 "`{0}' is invalid attribute target. All attributes in this attribute section will be ignored", a);
+	}
+
+	return string.Empty;
+}
+
+static bool IsUnaryOperator (Operator.OpType op)
+{
+	switch (op) {
+		
+	case Operator.OpType.LogicalNot: 
+	case Operator.OpType.OnesComplement: 
+	case Operator.OpType.Increment:
+	case Operator.OpType.Decrement:
+	case Operator.OpType.True: 
+	case Operator.OpType.False: 
+	case Operator.OpType.UnaryPlus: 
+	case Operator.OpType.UnaryNegation:
+		return true;
+	}
+	return false;
+}
+
+void syntax_error (Location l, string msg)
+{
+	report.Error (1003, l, "Syntax error, " + msg);
+}
+
+Tokenizer lexer;
+
+public Tokenizer Lexer {
+	get {
+		return lexer;
+	}
+}		   
+
+public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, ParserSession session)
+	: this (reader, file, file.Compiler.Report, session)
+{
+}
+
+public CSharpParser (SeekableStreamReader reader, CompilationSourceFile file, Report report, ParserSession session)
+{
+	this.file = file;
+	current_container = current_namespace = file;
+	
+	this.module = file.Module;
+	this.compiler = file.Compiler;
+	this.settings = compiler.Settings;
+	this.report = report;
+	
+	lang_version = settings.Version;
+	yacc_verbose_flag = settings.VerboseParserFlag;
+	doc_support = settings.DocumentationFile != null;
+	lexer = new Tokenizer (reader, file, session, report);
+	oob_stack = new Stack<object> ();
+	lbag = session.LocationsBag;
+	use_global_stacks = session.UseJayGlobalArrays;
+	parameters_bucket = session.ParametersStack;
+}
+
+public void parse ()
+{
+	eof_token = Token.EOF;
+	
+	try {
+		if (yacc_verbose_flag > 1)
+			yyparse (lexer, new yydebug.yyDebugSimple ());
+		else
+			yyparse (lexer);
+			
+		Tokenizer tokenizer = lexer as Tokenizer;
+		tokenizer.cleanup ();		
+	} catch (Exception e){
+	  	if (e is yyParser.yyUnexpectedEof) {
+			Error_SyntaxError (yyToken);
+			UnexpectedEOF = true;
+			return;
+		}
+			
+		if (e is yyParser.yyException) {
+			if (report.Errors == 0)
+				report.Error (-25, lexer.Location, "Parsing error");
+		} else {
+			// Used by compiler-tester to test internal errors
+			if (yacc_verbose_flag > 0 || e is FatalException)
+				throw;
+		
+			report.Error (589, lexer.Location, "Internal compiler error during parsing" + e);
+		}
+	}
+}
+
+void CheckToken (int error, int yyToken, string msg, Location loc)
+{
+	if (yyToken >= Token.FIRST_KEYWORD && yyToken <= Token.LAST_KEYWORD)
+		report.Error (error, loc, "{0}: `{1}' is a keyword", msg, GetTokenName (yyToken));
+	else
+		report.Error (error, loc, msg);
+}
+
+string ConsumeStoredComment ()
+{
+	string s = tmpComment;
+	tmpComment = null;
+	Lexer.doc_state = XmlCommentState.Allowed;
+	return s;
+}
+
+void FeatureIsNotAvailable (Location loc, string feature)
+{
+	report.FeatureIsNotAvailable (compiler, loc, feature);
+}
+
+Location GetLocation (object obj)
+{
+	var lt = obj as LocatedToken;
+	if (lt != null)
+		return lt.Location;
+		
+	var mn = obj as MemberName;
+	if (mn != null)
+		return mn.Location;
+		
+	var expr = obj as Expression;
+	if (expr != null)
+		return expr.Location;
+
+	return lexer.Location;
+}
+
+void start_block (Location loc)
+{
+	if (current_block == null) {
+		current_block = new ToplevelBlock (compiler, current_local_parameters, loc);
+		parsing_anonymous_method = false;
+	} else if (parsing_anonymous_method) {
+		current_block = new ParametersBlock (current_block, current_local_parameters, loc);
+		parsing_anonymous_method = false;
+	} else {
+		current_block = new ExplicitBlock (current_block, loc, Location.Null);
+	}
+}
+
+Block
+end_block (Location loc)
+{
+	Block retval = current_block.Explicit;
+	retval.SetEndLocation (loc);
+	current_block = retval.Parent;
+	return retval;
+}
+
+void start_anonymous (bool isLambda, ParametersCompiled parameters, bool isAsync, Location loc)
+{
+	oob_stack.Push (current_anonymous_method);
+	oob_stack.Push (current_local_parameters);
+	oob_stack.Push (current_variable);
+	oob_stack.Push (async_block);
+
+	current_local_parameters = parameters;
+	if (isLambda) {
+		if (lang_version <= LanguageVersion.ISO_2)
+			FeatureIsNotAvailable (loc, "lambda expressions");
+
+		current_anonymous_method = new LambdaExpression (loc);
+	} else {
+		if (lang_version == LanguageVersion.ISO_1)
+			FeatureIsNotAvailable (loc, "anonymous methods");
+			
+		current_anonymous_method = new AnonymousMethodExpression (loc);
+	}
+	current_anonymous_method.IsAsync = isAsync;
+	
+	async_block = isAsync;
+	// Force the next block to be created as a ToplevelBlock
+	parsing_anonymous_method = true;
+}
+
+/*
+ * Completes the anonymous method processing, if lambda_expr is null, this
+ * means that we have a Statement instead of an Expression embedded 
+ */
+AnonymousMethodExpression end_anonymous (ParametersBlock anon_block)
+{
+	AnonymousMethodExpression retval;
+
+	if (async_block)
+		anon_block.IsAsync = true;
+
+	current_anonymous_method.Block = anon_block;
+	retval = current_anonymous_method;
+
+	async_block = (bool) oob_stack.Pop ();
+	current_variable = (BlockVariable) oob_stack.Pop ();
+	current_local_parameters = (ParametersCompiled) oob_stack.Pop ();
+	current_anonymous_method = (AnonymousMethodExpression) oob_stack.Pop ();
+
+	return retval;
+}
+
+void Error_SyntaxError (int token)
+{
+	Error_SyntaxError (0, token);
+}
+
+void Error_SyntaxError (int error_code, int token)
+{
+	Error_SyntaxError (error_code, token, "Unexpected symbol");
+}
+
+void Error_SyntaxError (int error_code, int token, string msg)
+{
+	Lexer.CompleteOnEOF = false;
+
+	// An error message has been reported by tokenizer
+	if (token == Token.ERROR)
+		return;
+	
+	// Avoid duplicit error message after unterminated string literals
+	if (token == Token.LITERAL && lexer.Location.Column == 0)
+		return;
+
+	string symbol = GetSymbolName (token);
+	string expecting = GetExpecting ();
+	var loc = lexer.Location - symbol.Length;
+	
+	if (error_code == 0) {
+		if (expecting == "`identifier'") {
+			if (token > Token.FIRST_KEYWORD && token < Token.LAST_KEYWORD) {
+				report.Error (1041, loc, "Identifier expected, `{0}' is a keyword", symbol);
+				return;
+			}
+			
+			error_code = 1001;
+			expecting = "identifier";
+		} else if (expecting == "`)'") {
+			error_code = 1026;
+		} else {
+			error_code = 1525;
+		}
+	}
+	
+	if (string.IsNullOrEmpty (expecting))
+		report.Error (error_code, loc, "{1} `{0}'", symbol, msg);
+	else
+		report.Error (error_code, loc, "{2} `{0}', expecting {1}", symbol, expecting, msg);	  
+}
+
+string GetExpecting ()
+{
+	int [] tokens = yyExpectingTokens (yyExpectingState);
+	var names = new List<string> (tokens.Length);
+	bool has_type = false;
+	bool has_identifier = false;
+	for (int i = 0; i < tokens.Length; i++){
+		int token = tokens [i];
+		has_identifier |= token == Token.IDENTIFIER;
+		
+		string name = GetTokenName (token);
+		if (name == "<internal>")
+			continue;
+			
+		has_type |= name == "type";
+		if (names.Contains (name))
+			continue;
+		
+		names.Add (name);
+	}
+
+	//
+	// Too many tokens to enumerate
+	//
+	if (names.Count > 8)
+		return null;
+
+	if (has_type && has_identifier)
+		names.Remove ("identifier");
+
+	if (names.Count == 1)
+		return "`" + GetTokenName (tokens [0]) + "'";
+	
+	StringBuilder sb = new StringBuilder ();
+	names.Sort ();
+	int count = names.Count;
+	for (int i = 0; i < count; i++){
+		bool last = i + 1 == count;
+		if (last)
+			sb.Append ("or ");
+		sb.Append ('`');
+		sb.Append (names [i]);
+		sb.Append (last ? "'" : count < 3 ? "' " : "', ");
+	}
+	return sb.ToString ();
+}
+
+
+string GetSymbolName (int token)
+{
+	switch (token){
+	case Token.LITERAL:
+		return ((Constant)lexer.Value).GetValue ().ToString ();
+	case Token.IDENTIFIER:
+		return ((LocatedToken)lexer.Value).Value;
+
+	case Token.BOOL:
+		return "bool";
+	case Token.BYTE:
+		return "byte";
+	case Token.CHAR:
+		return "char";
+	case Token.VOID:
+		return "void";
+	case Token.DECIMAL:
+		return "decimal";
+	case Token.DOUBLE:
+		return "double";
+	case Token.FLOAT:
+		return "float";
+	case Token.INT:
+		return "int";
+	case Token.LONG:
+		return "long";
+	case Token.SBYTE:
+		return "sbyte";
+	case Token.SHORT:
+		return "short";
+	case Token.STRING:
+		return "string";
+	case Token.UINT:
+		return "uint";
+	case Token.ULONG:
+		return "ulong";
+	case Token.USHORT:
+		return "ushort";
+	case Token.OBJECT:
+		return "object";
+		
+	case Token.PLUS:
+		return "+";
+	case Token.UMINUS:
+	case Token.MINUS:
+		return "-";
+	case Token.BANG:
+		return "!";
+	case Token.BITWISE_AND:
+		return "&";
+	case Token.BITWISE_OR:
+		return "|";
+	case Token.STAR:
+		return "*";
+	case Token.PERCENT:
+		return "%";
+	case Token.DIV:
+		return "/";
+	case Token.CARRET:
+		return "^";
+	case Token.OP_INC:
+		return "++";
+	case Token.OP_DEC:
+		return "--";
+	case Token.OP_SHIFT_LEFT:
+		return "<<";
+	case Token.OP_SHIFT_RIGHT:
+		return ">>";
+	case Token.OP_LT:
+		return "<";
+	case Token.OP_GT:
+		return ">";
+	case Token.OP_LE:
+		return "<=";
+	case Token.OP_GE:
+		return ">=";
+	case Token.OP_EQ:
+		return "==";
+	case Token.OP_NE:
+		return "!=";
+	case Token.OP_AND:
+		return "&&";
+	case Token.OP_OR:
+		return "||";
+	case Token.OP_PTR:
+		return "->";
+	case Token.OP_COALESCING:	
+		return "??";
+	case Token.OP_MULT_ASSIGN:
+		return "*=";
+	case Token.OP_DIV_ASSIGN:
+		return "/=";
+	case Token.OP_MOD_ASSIGN:
+		return "%=";
+	case Token.OP_ADD_ASSIGN:
+		return "+=";
+	case Token.OP_SUB_ASSIGN:
+		return "-=";
+	case Token.OP_SHIFT_LEFT_ASSIGN:
+		return "<<=";
+	case Token.OP_SHIFT_RIGHT_ASSIGN:
+		return ">>=";
+	case Token.OP_AND_ASSIGN:
+		return "&=";
+	case Token.OP_XOR_ASSIGN:
+		return "^=";
+	case Token.OP_OR_ASSIGN:
+		return "|=";
+	}
+
+	return GetTokenName (token);
+}
+
+static string GetTokenName (int token)
+{
+	switch (token){
+	case Token.ABSTRACT:
+		return "abstract";
+	case Token.AS:
+		return "as";
+	case Token.ADD:
+		return "add";
+	case Token.ASYNC:
+		return "async";
+	case Token.BASE:
+		return "base";
+	case Token.BREAK:
+		return "break";
+	case Token.CASE:
+		return "case";
+	case Token.CATCH:
+		return "catch";
+	case Token.CHECKED:
+		return "checked";
+	case Token.CLASS:
+		return "class";
+	case Token.CONST:
+		return "const";
+	case Token.CONTINUE:
+		return "continue";
+	case Token.DEFAULT:
+		return "default";
+	case Token.DELEGATE:
+		return "delegate";
+	case Token.DO:
+		return "do";
+	case Token.ELSE:
+		return "else";
+	case Token.ENUM:
+		return "enum";
+	case Token.EVENT:
+		return "event";
+	case Token.EXPLICIT:
+		return "explicit";
+	case Token.EXTERN:
+	case Token.EXTERN_ALIAS:
+		return "extern";
+	case Token.FALSE:
+		return "false";
+	case Token.FINALLY:
+		return "finally";
+	case Token.FIXED:
+		return "fixed";
+	case Token.FOR:
+		return "for";
+	case Token.FOREACH:
+		return "foreach";
+	case Token.GOTO:
+		return "goto";
+	case Token.IF:
+		return "if";
+	case Token.IMPLICIT:
+		return "implicit";
+	case Token.IN:
+		return "in";
+	case Token.INTERFACE:
+		return "interface";
+	case Token.INTERNAL:
+		return "internal";
+	case Token.IS:
+		return "is";
+	case Token.LOCK:
+		return "lock";
+	case Token.NAMESPACE:
+		return "namespace";
+	case Token.NEW:
+		return "new";
+	case Token.NULL:
+		return "null";
+	case Token.OPERATOR:
+		return "operator";
+	case Token.OUT:
+		return "out";
+	case Token.OVERRIDE:
+		return "override";
+	case Token.PARAMS:
+		return "params";
+	case Token.PRIVATE:
+		return "private";
+	case Token.PROTECTED:
+		return "protected";
+	case Token.PUBLIC:
+		return "public";
+	case Token.READONLY:
+		return "readonly";
+	case Token.REF:
+		return "ref";
+	case Token.RETURN:
+		return "return";
+	case Token.REMOVE:
+		return "remove";
+	case Token.SEALED:
+		return "sealed";
+	case Token.SIZEOF:
+		return "sizeof";
+	case Token.STACKALLOC:
+		return "stackalloc";
+	case Token.STATIC:
+		return "static";
+	case Token.STRUCT:
+		return "struct";
+	case Token.SWITCH:
+		return "switch";
+	case Token.THIS:
+		return "this";
+	case Token.THROW:
+		return "throw";
+	case Token.TRUE:
+		return "true";
+	case Token.TRY:
+		return "try";
+	case Token.TYPEOF:
+		return "typeof";
+	case Token.UNCHECKED:
+		return "unchecked";
+	case Token.UNSAFE:
+		return "unsafe";
+	case Token.USING:
+		return "using";
+	case Token.VIRTUAL:
+		return "virtual";
+	case Token.VOLATILE:
+		return "volatile";
+	case Token.WHERE:
+		return "where";
+	case Token.WHILE:
+		return "while";
+	case Token.ARGLIST:
+		return "__arglist";
+	case Token.REFVALUE:
+		return "__refvalue";
+	case Token.REFTYPE:
+		return "__reftype";
+	case Token.MAKEREF:
+		return "__makeref";
+	case Token.PARTIAL:
+		return "partial";
+	case Token.ARROW:
+		return "=>";
+	case Token.FROM:
+	case Token.FROM_FIRST:
+		return "from";
+	case Token.JOIN:
+		return "join";
+	case Token.ON:
+		return "on";
+	case Token.EQUALS:
+		return "equals";
+	case Token.SELECT:
+		return "select";
+	case Token.GROUP:
+		return "group";
+	case Token.BY:
+		return "by";
+	case Token.LET:
+		return "let";
+	case Token.ORDERBY:
+		return "orderby";
+	case Token.ASCENDING:
+		return "ascending";
+	case Token.DESCENDING:
+		return "descending";
+	case Token.INTO:
+		return "into";
+	case Token.GET:
+		return "get";
+	case Token.SET:
+		return "set";
+	case Token.OPEN_BRACE:
+		return "{";
+	case Token.CLOSE_BRACE:
+		return "}";
+	case Token.OPEN_BRACKET:
+	case Token.OPEN_BRACKET_EXPR:
+		return "[";
+	case Token.CLOSE_BRACKET:
+		return "]";
+	case Token.OPEN_PARENS_CAST:
+	case Token.OPEN_PARENS_LAMBDA:
+	case Token.OPEN_PARENS:
+		return "(";
+	case Token.CLOSE_PARENS:
+		return ")";
+	case Token.DOT:
+		return ".";
+	case Token.COMMA:
+		return ",";
+	case Token.DEFAULT_COLON:
+		return "default:";
+	case Token.COLON:
+		return ":";
+	case Token.SEMICOLON:
+		return ";";
+	case Token.TILDE:
+		return "~";
+		
+	case Token.PLUS:
+	case Token.UMINUS:
+	case Token.MINUS:
+	case Token.BANG:
+	case Token.OP_LT:
+	case Token.OP_GT:
+	case Token.BITWISE_AND:
+	case Token.BITWISE_OR:
+	case Token.STAR:
+	case Token.PERCENT:
+	case Token.DIV:
+	case Token.CARRET:
+	case Token.OP_INC:
+	case Token.OP_DEC:
+	case Token.OP_SHIFT_LEFT:
+	case Token.OP_SHIFT_RIGHT:
+	case Token.OP_LE:
+	case Token.OP_GE:
+	case Token.OP_EQ:
+	case Token.OP_NE:
+	case Token.OP_AND:
+	case Token.OP_OR:
+	case Token.OP_PTR:
+	case Token.OP_COALESCING:	
+	case Token.OP_MULT_ASSIGN:
+	case Token.OP_DIV_ASSIGN:
+	case Token.OP_MOD_ASSIGN:
+	case Token.OP_ADD_ASSIGN:
+	case Token.OP_SUB_ASSIGN:
+	case Token.OP_SHIFT_LEFT_ASSIGN:
+	case Token.OP_SHIFT_RIGHT_ASSIGN:
+	case Token.OP_AND_ASSIGN:
+	case Token.OP_XOR_ASSIGN:
+	case Token.OP_OR_ASSIGN:
+		return "<operator>";
+
+	case Token.BOOL:
+	case Token.BYTE:
+	case Token.CHAR:
+	case Token.VOID:
+	case Token.DECIMAL:
+	case Token.DOUBLE:
+	case Token.FLOAT:
+	case Token.INT:
+	case Token.LONG:
+	case Token.SBYTE:
+	case Token.SHORT:
+	case Token.STRING:
+	case Token.UINT:
+	case Token.ULONG:
+	case Token.USHORT:
+	case Token.OBJECT:
+		return "type";
+	
+	case Token.ASSIGN:
+		return "=";
+	case Token.OP_GENERICS_LT:
+	case Token.GENERIC_DIMENSION:
+		return "<";
+	case Token.OP_GENERICS_GT:
+		return ">";
+	case Token.INTERR:
+	case Token.INTERR_NULLABLE:
+		return "?";
+	case Token.DOUBLE_COLON:
+		return "::";
+	case Token.LITERAL:
+		return "value";
+	case Token.IDENTIFIER:
+	case Token.AWAIT:
+		return "identifier";
+
+	case Token.EOF:
+		return "end-of-file";
+
+		// All of these are internal.
+	case Token.NONE:
+	case Token.ERROR:
+	case Token.FIRST_KEYWORD:
+	case Token.EVAL_COMPILATION_UNIT_PARSER:
+	case Token.EVAL_USING_DECLARATIONS_UNIT_PARSER:
+	case Token.EVAL_STATEMENT_PARSER:
+	case Token.LAST_KEYWORD:
+	case Token.GENERATE_COMPLETION:
+	case Token.COMPLETE_COMPLETION:
+		return "<internal>";
+
+		// A bit more robust.
+	default:
+		return yyNames [token];
+        }
+}
+
+/* end end end */
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-tokenizer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-tokenizer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/cs-tokenizer.cs	(revision 11807)
@@ -0,0 +1,4033 @@
+//
+// cs-tokenizer.cs: The Tokenizer for the C# compiler
+//                  This also implements the preprocessor
+//
+// Author: Miguel de Icaza (miguel@gnu.org)
+//         Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
+//
+using System;
+using System.Text;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Diagnostics;
+using System.Collections;
+
+namespace Mono.CSharp
+{
+	//
+	// This class has to be used by parser only, it reuses token
+	// details once a file is parsed
+	//
+	public class LocatedToken
+	{
+		public int row, column;
+		public string value;
+		public SourceFile file;
+
+		public LocatedToken ()
+		{
+		}
+
+		public LocatedToken (string value, Location loc)
+		{
+			this.value = value;
+			file = loc.SourceFile;
+			row = loc.Row;
+			column = loc.Column;
+		}
+
+		public override string ToString ()
+		{
+			return string.Format ("Token '{0}' at {1},{2}", Value, row, column);
+		}
+
+		public Location Location
+		{
+			get { return new Location (file, row, column); }
+		}
+
+		public string Value
+		{
+			get { return value; }
+		}
+	}
+
+	/// <summary>
+	///    Tokenizer for C# source code. 
+	/// </summary>
+	public class Tokenizer : yyParser.yyInput
+	{
+		class KeywordEntry<T>
+		{
+			public readonly T Token;
+			public KeywordEntry<T> Next;
+			public readonly char[] Value;
+
+			public KeywordEntry (string value,T token)
+			{
+				this.Value = value.ToCharArray ();
+				this.Token = token;
+			}
+		}
+
+		sealed class IdentifiersComparer : IEqualityComparer<char[]>
+		{
+			readonly int length;
+
+			public IdentifiersComparer (int length)
+			{
+				this.length = length;
+			}
+
+			public bool Equals (char[] x, char[] y)
+			{
+				for (int i = 0; i < length; ++i)
+					if (x [i] != y [i])
+						return false;
+
+				return true;
+			}
+
+			public int GetHashCode (char[] obj)
+			{
+				int h = 0;
+				for (int i = 0; i < length; ++i)
+					h = (h << 5) - h + obj [i];
+
+				return h;
+			}
+		}
+
+		public class LocatedTokenBuffer
+		{
+			readonly LocatedToken[] buffer;
+			public int pos;
+
+			public LocatedTokenBuffer ()
+			{
+				buffer = new LocatedToken[0];
+			}
+
+			public LocatedTokenBuffer (LocatedToken[] buffer)
+			{
+				this.buffer = buffer ?? new LocatedToken[0];
+			}
+
+			public LocatedToken Create (SourceFile file, int row, int column)
+			{
+				return Create (null, file, row, column);
+			}
+
+			public LocatedToken Create (string value, SourceFile file, int row, int column)
+			{
+				//
+				// TODO: I am not very happy about the logic but it's the best
+				// what I could come up with for now.
+				// Ideally we should be using just tiny buffer (256 elements) which
+				// is enough to hold all details for currect stack and recycle elements
+				// poped from the stack but there is a trick needed to recycle
+				// them properly.
+				//
+				LocatedToken entry;
+				if (pos >= buffer.Length) {
+					entry = new LocatedToken ();
+				} else {
+					entry = buffer[pos];
+					if (entry == null) {
+						entry = new LocatedToken ();
+						buffer[pos] = entry;
+					}
+
+					++pos;
+				}
+				entry.value = value;
+				entry.file = file;
+				entry.row = row;
+				entry.column = column;
+				return entry;
+			}
+
+			//
+			// Used for token not required by expression evaluator
+			//
+			[Conditional ("FULL_AST")]
+			public void CreateOptional (SourceFile file, int row, int col, ref object token)
+			{
+				token = Create (file, row, col);
+			}
+		}
+
+		public enum PreprocessorDirective
+		{
+			Invalid = 0,
+
+			Region = 1,
+			Endregion = 2,
+			If = 3 | RequiresArgument,
+			Endif = 4,
+			Elif = 5 | RequiresArgument,
+			Else = 6,
+			Define = 7 | RequiresArgument,
+			Undef = 8 | RequiresArgument,
+			Error = 9,
+			Warning = 10,
+			Pragma = 11 | CustomArgumentsParsing,
+			Line = 12 | CustomArgumentsParsing,
+
+			CustomArgumentsParsing = 1 << 10,
+			RequiresArgument = 1 << 11
+		}
+
+		readonly SeekableStreamReader reader;
+		readonly CompilationSourceFile source_file;
+		public CompilationSourceFile SourceFile { get { return source_file; } }
+		readonly CompilerContext context;
+		readonly Report Report;
+
+
+		SourceFile current_source;
+		Location hidden_block_start;
+		int ref_line = 1;
+		int line = 1;
+		int col = 0;
+		int previous_col;
+		int current_token;
+		readonly int tab_size;
+		bool handle_get_set = false;
+		bool handle_remove_add = false;
+		bool handle_where;
+		bool lambda_arguments_parsing;
+		List<Location> escaped_identifiers;
+		int parsing_generic_less_than;
+		readonly bool doc_processing;
+		readonly LocatedTokenBuffer ltb;
+		
+		//
+		// Used mainly for parser optimizations. Some expressions for instance
+		// can appear only in block (including initializer, base initializer)
+		// scope only
+		//
+		public int parsing_block;
+		internal bool query_parsing;
+		
+		// 
+		// When parsing type only, useful for ambiguous nullable types
+		//
+		public int parsing_type;
+		
+		//
+		// Set when parsing generic declaration (type or method header)
+		//
+		public bool parsing_generic_declaration;
+		public bool parsing_generic_declaration_doc;
+		
+		//
+		// The value indicates that we have not reach any declaration or
+		// namespace yet
+		//
+		public int parsing_declaration;
+		public bool parsing_attribute_section;
+
+		public bool parsing_modifiers;
+
+		//
+		// The special characters to inject on streams to run the unit parser
+		// in the special expression mode. Using private characters from
+		// Plane Sixteen (U+100000 to U+10FFFD)
+		//
+		// This character is only tested just before the tokenizer is about to report
+		// an error;   So on the regular operation mode, this addition will have no
+		// impact on the tokenizer's performance.
+		//
+		
+		public const int EvalStatementParserCharacter = 0x100000;
+		public const int EvalCompilationUnitParserCharacter = 0x100001;
+		public const int EvalUsingDeclarationsParserCharacter = 0x100002;
+		public const int DocumentationXref = 0x100003;
+
+		const int UnicodeLS = 0x2028;
+		const int UnicodePS = 0x2029;
+		
+		//
+		// XML documentation buffer. The save point is used to divide
+		// comments on types and comments on members.
+		//
+		StringBuilder xml_comment_buffer;
+
+		//
+		// See comment on XmlCommentState enumeration.
+		//
+		XmlCommentState xml_doc_state = XmlCommentState.Allowed;
+
+		//
+		// Whether tokens have been seen on this line
+		//
+		bool tokens_seen = false;
+
+		//
+		// Set to true once the GENERATE_COMPLETION token has bee
+		// returned.   This helps produce one GENERATE_COMPLETION,
+		// as many COMPLETE_COMPLETION as necessary to complete the
+		// AST tree and one final EOF.
+		//
+		bool generated;
+		
+		//
+		// Whether a token has been seen on the file
+		// This is needed because `define' is not allowed to be used
+		// after a token has been seen.
+		//
+		bool any_token_seen;
+
+		//
+		// Class variables
+		// 
+		static readonly KeywordEntry<int>[][] keywords;
+		static readonly KeywordEntry<PreprocessorDirective>[][] keywords_preprocessor;
+		static readonly HashSet<string> keyword_strings;
+		static readonly NumberStyles styles;
+		static readonly NumberFormatInfo csharp_format_info;
+
+		// Pragma arguments
+		static readonly char[] pragma_warning = "warning".ToCharArray ();
+		static readonly char[] pragma_warning_disable = "disable".ToCharArray ();
+		static readonly char[] pragma_warning_restore = "restore".ToCharArray ();
+		static readonly char[] pragma_checksum = "checksum".ToCharArray ();
+		static readonly char[] line_hidden = "hidden".ToCharArray ();
+		static readonly char[] line_default = "default".ToCharArray ();
+
+		static readonly char[] simple_whitespaces = new char[] { ' ', '\t' };
+		bool startsLine = true;
+		internal SpecialsBag sbag;
+
+		public bool PropertyParsing {
+			get { return handle_get_set; }
+			set { handle_get_set = value; }
+		}
+
+		public bool EventParsing {
+			get { return handle_remove_add; }
+			set { handle_remove_add = value; }
+		}
+
+		public bool ConstraintsParsing {
+			get { return handle_where; }
+			set { handle_where = value; }
+		}
+	
+		public XmlCommentState doc_state {
+			get { return xml_doc_state; }
+			set {
+				if (value == XmlCommentState.Allowed) {
+					check_incorrect_doc_comment ();
+					reset_doc_comment ();
+				}
+				xml_doc_state = value;
+			}
+		}
+
+		//
+		// This is used to trigger completion generation on the parser
+		public bool CompleteOnEOF;
+
+		void AddEscapedIdentifier (Location loc)
+		{
+			if (escaped_identifiers == null)
+				escaped_identifiers = new List<Location> ();
+
+			escaped_identifiers.Add (loc);
+		}
+
+		public bool IsEscapedIdentifier (ATypeNameExpression name)
+		{
+			return escaped_identifiers != null && escaped_identifiers.Contains (name.Location);
+		}
+
+		//
+		// Values for the associated token returned
+		//
+		internal int putback_char; 	// Used by repl only
+		object val;
+
+		//
+		// Pre-processor
+		//
+		const int TAKING        = 1;
+		const int ELSE_SEEN = 4;
+		const int PARENT_TAKING = 8;
+		const int REGION = 16;		
+
+		//
+		// pre-processor if stack state:
+		//
+		Stack<int> ifstack;
+
+		public const int MaxIdentifierLength = 512;
+		public const int MaxNumberLength = 512;
+
+		readonly char[] id_builder;
+		readonly Dictionary<char[], string>[] identifiers;
+		readonly char[] number_builder;
+		int number_pos;
+
+		char[] value_builder = new char[64];
+
+		public int Line {
+			get {
+				return ref_line;
+			}
+			set {
+				ref_line = value;
+			}
+		}
+
+		public int Column {
+			get {
+				return col;
+			}
+			set {
+				col = value;
+			}
+		}
+
+		//
+		// This is used when the tokenizer needs to save
+		// the current position as it needs to do some parsing
+		// on its own to deamiguate a token in behalf of the
+		// parser.
+		//
+		Stack<Position> position_stack = new Stack<Position> (2);
+
+		class Position
+		{
+			public int position;
+			public int line;
+			public int ref_line;
+			public int col;
+			public Location hidden;
+			public int putback_char;
+			public int previous_col;
+			public Stack<int> ifstack;
+			public int parsing_generic_less_than;
+			public int current_token;
+			public object val;
+
+			public Position (Tokenizer t)
+			{
+				position = t.reader.Position;
+				line = t.line;
+				ref_line = t.ref_line;
+				col = t.col;
+				hidden = t.hidden_block_start;
+				putback_char = t.putback_char;
+				previous_col = t.previous_col;
+				if (t.ifstack != null && t.ifstack.Count != 0) {
+					// There is no simple way to clone Stack<T> all
+					// methods reverse the order
+					var clone = t.ifstack.ToArray ();
+					Array.Reverse (clone);
+					ifstack = new Stack<int> (clone);
+				}
+				parsing_generic_less_than = t.parsing_generic_less_than;
+				current_token = t.current_token;
+				val = t.val;
+			}
+		}
+
+		public Tokenizer (SeekableStreamReader input, CompilationSourceFile file, ParserSession session, Report report)
+		{
+			this.source_file = file;
+			this.context = file.Compiler;
+			this.current_source = file.SourceFile;
+			this.identifiers = session.Identifiers;
+			this.id_builder = session.IDBuilder;
+			this.number_builder = session.NumberBuilder;
+			this.ltb = new LocatedTokenBuffer (session.LocatedTokens);
+			this.Report = report;
+
+			reader = input;
+
+			putback_char = -1;
+
+			xml_comment_buffer = new StringBuilder ();
+			doc_processing = context.Settings.DocumentationFile != null;
+
+			tab_size = context.Settings.TabSize;
+		}
+		
+		public void PushPosition ()
+		{
+			position_stack.Push (new Position (this));
+		}
+
+		public void PopPosition ()
+		{
+			Position p = position_stack.Pop ();
+
+			reader.Position = p.position;
+			ref_line = p.ref_line;
+			line = p.line;
+			col = p.col;
+			hidden_block_start = p.hidden;
+			putback_char = p.putback_char;
+			previous_col = p.previous_col;
+			ifstack = p.ifstack;
+			parsing_generic_less_than = p.parsing_generic_less_than;
+			current_token = p.current_token;
+			val = p.val;
+		}
+
+		// Do not reset the position, ignore it.
+		public void DiscardPosition ()
+		{
+			position_stack.Pop ();
+	}
+		
+		static void AddKeyword (string kw, int token)
+		{
+			keyword_strings.Add (kw);
+
+			AddKeyword (keywords, kw, token);
+}
+
+		static void AddPreprocessorKeyword (string kw, PreprocessorDirective directive)
+		{
+			AddKeyword (keywords_preprocessor, kw, directive);
+		}
+
+		static void AddKeyword<T> (KeywordEntry<T>[][] keywords, string kw, T token)
+		{
+			int length = kw.Length;
+			if (keywords[length] == null) {
+				keywords[length] = new KeywordEntry<T>['z' - '_' + 1];
+			}
+
+			int char_index = kw[0] - '_';
+			var kwe = keywords[length][char_index];
+			if (kwe == null) {
+				keywords[length][char_index] = new KeywordEntry<T> (kw, token);
+				return;
+			}
+
+			while (kwe.Next != null) {
+				kwe = kwe.Next;
+			}
+
+			kwe.Next = new KeywordEntry<T> (kw, token);
+		}
+
+		//
+		// Class initializer
+		// 
+		static Tokenizer ()
+		{
+			keyword_strings = new HashSet<string> ();
+
+			// 11 is the length of the longest keyword for now
+			keywords = new KeywordEntry<int>[11][];
+
+			AddKeyword ("__arglist", Token.ARGLIST);
+			AddKeyword ("__makeref", Token.MAKEREF);
+			AddKeyword ("__reftype", Token.REFTYPE);
+			AddKeyword ("__refvalue", Token.REFVALUE);
+			AddKeyword ("abstract", Token.ABSTRACT);
+			AddKeyword ("as", Token.AS);
+			AddKeyword ("add", Token.ADD);
+			AddKeyword ("base", Token.BASE);
+			AddKeyword ("bool", Token.BOOL);
+			AddKeyword ("break", Token.BREAK);
+			AddKeyword ("byte", Token.BYTE);
+			AddKeyword ("case", Token.CASE);
+			AddKeyword ("catch", Token.CATCH);
+			AddKeyword ("char", Token.CHAR);
+			AddKeyword ("checked", Token.CHECKED);
+			AddKeyword ("class", Token.CLASS);
+			AddKeyword ("const", Token.CONST);
+			AddKeyword ("continue", Token.CONTINUE);
+			AddKeyword ("decimal", Token.DECIMAL);
+			AddKeyword ("default", Token.DEFAULT);
+			AddKeyword ("delegate", Token.DELEGATE);
+			AddKeyword ("do", Token.DO);
+			AddKeyword ("double", Token.DOUBLE);
+			AddKeyword ("else", Token.ELSE);
+			AddKeyword ("enum", Token.ENUM);
+			AddKeyword ("event", Token.EVENT);
+			AddKeyword ("explicit", Token.EXPLICIT);
+			AddKeyword ("extern", Token.EXTERN);
+			AddKeyword ("false", Token.FALSE);
+			AddKeyword ("finally", Token.FINALLY);
+			AddKeyword ("fixed", Token.FIXED);
+			AddKeyword ("float", Token.FLOAT);
+			AddKeyword ("for", Token.FOR);
+			AddKeyword ("foreach", Token.FOREACH);
+			AddKeyword ("goto", Token.GOTO);
+			AddKeyword ("get", Token.GET);
+			AddKeyword ("if", Token.IF);
+			AddKeyword ("implicit", Token.IMPLICIT);
+			AddKeyword ("in", Token.IN);
+			AddKeyword ("int", Token.INT);
+			AddKeyword ("interface", Token.INTERFACE);
+			AddKeyword ("internal", Token.INTERNAL);
+			AddKeyword ("is", Token.IS);
+			AddKeyword ("lock", Token.LOCK);
+			AddKeyword ("long", Token.LONG);
+			AddKeyword ("namespace", Token.NAMESPACE);
+			AddKeyword ("new", Token.NEW);
+			AddKeyword ("null", Token.NULL);
+			AddKeyword ("object", Token.OBJECT);
+			AddKeyword ("operator", Token.OPERATOR);
+			AddKeyword ("out", Token.OUT);
+			AddKeyword ("override", Token.OVERRIDE);
+			AddKeyword ("params", Token.PARAMS);
+			AddKeyword ("private", Token.PRIVATE);
+			AddKeyword ("protected", Token.PROTECTED);
+			AddKeyword ("public", Token.PUBLIC);
+			AddKeyword ("readonly", Token.READONLY);
+			AddKeyword ("ref", Token.REF);
+			AddKeyword ("remove", Token.REMOVE);
+			AddKeyword ("return", Token.RETURN);
+			AddKeyword ("sbyte", Token.SBYTE);
+			AddKeyword ("sealed", Token.SEALED);
+			AddKeyword ("set", Token.SET);
+			AddKeyword ("short", Token.SHORT);
+			AddKeyword ("sizeof", Token.SIZEOF);
+			AddKeyword ("stackalloc", Token.STACKALLOC);
+			AddKeyword ("static", Token.STATIC);
+			AddKeyword ("string", Token.STRING);
+			AddKeyword ("struct", Token.STRUCT);
+			AddKeyword ("switch", Token.SWITCH);
+			AddKeyword ("this", Token.THIS);
+			AddKeyword ("throw", Token.THROW);
+			AddKeyword ("true", Token.TRUE);
+			AddKeyword ("try", Token.TRY);
+			AddKeyword ("typeof", Token.TYPEOF);
+			AddKeyword ("uint", Token.UINT);
+			AddKeyword ("ulong", Token.ULONG);
+			AddKeyword ("unchecked", Token.UNCHECKED);
+			AddKeyword ("unsafe", Token.UNSAFE);
+			AddKeyword ("ushort", Token.USHORT);
+			AddKeyword ("using", Token.USING);
+			AddKeyword ("virtual", Token.VIRTUAL);
+			AddKeyword ("void", Token.VOID);
+			AddKeyword ("volatile", Token.VOLATILE);
+			AddKeyword ("while", Token.WHILE);
+			AddKeyword ("partial", Token.PARTIAL);
+			AddKeyword ("where", Token.WHERE);
+
+			// LINQ keywords
+			AddKeyword ("from", Token.FROM);
+			AddKeyword ("join", Token.JOIN);
+			AddKeyword ("on", Token.ON);
+			AddKeyword ("equals", Token.EQUALS);
+			AddKeyword ("select", Token.SELECT);
+			AddKeyword ("group", Token.GROUP);
+			AddKeyword ("by", Token.BY);
+			AddKeyword ("let", Token.LET);
+			AddKeyword ("orderby", Token.ORDERBY);
+			AddKeyword ("ascending", Token.ASCENDING);
+			AddKeyword ("descending", Token.DESCENDING);
+			AddKeyword ("into", Token.INTO);
+
+			// Contextual async keywords
+			AddKeyword ("async", Token.ASYNC);
+			AddKeyword ("await", Token.AWAIT);
+
+			keywords_preprocessor = new KeywordEntry<PreprocessorDirective>[10][];
+
+			AddPreprocessorKeyword ("region", PreprocessorDirective.Region);
+			AddPreprocessorKeyword ("endregion", PreprocessorDirective.Endregion);
+			AddPreprocessorKeyword ("if", PreprocessorDirective.If);
+			AddPreprocessorKeyword ("endif", PreprocessorDirective.Endif);
+			AddPreprocessorKeyword ("elif", PreprocessorDirective.Elif);
+			AddPreprocessorKeyword ("else", PreprocessorDirective.Else);
+			AddPreprocessorKeyword ("define", PreprocessorDirective.Define);
+			AddPreprocessorKeyword ("undef", PreprocessorDirective.Undef);
+			AddPreprocessorKeyword ("error", PreprocessorDirective.Error);
+			AddPreprocessorKeyword ("warning", PreprocessorDirective.Warning);
+			AddPreprocessorKeyword ("pragma", PreprocessorDirective.Pragma);
+			AddPreprocessorKeyword ("line", PreprocessorDirective.Line);
+
+			csharp_format_info = NumberFormatInfo.InvariantInfo;
+			styles = NumberStyles.Float;
+		}
+
+		int GetKeyword (char[] id, int id_len)
+		{
+			//
+			// Keywords are stored in an array of arrays grouped by their
+			// length and then by the first character
+			//
+			if (id_len >= keywords.Length || keywords [id_len] == null)
+				return -1;
+
+			int first_index = id [0] - '_';
+			if (first_index > 'z' - '_')
+				return -1;
+
+			var kwe = keywords [id_len] [first_index];
+			if (kwe == null)
+				return -1;
+
+			int res;
+			do {
+				res = kwe.Token;
+				for (int i = 1; i < id_len; ++i) {
+					if (id [i] != kwe.Value [i]) {
+						res = 0;
+						kwe = kwe.Next;
+						break;
+					}
+				}
+			} while (res == 0 && kwe != null);
+
+			if (res == 0)
+				return -1;
+
+			int next_token;
+			switch (res) {
+			case Token.GET:
+			case Token.SET:
+				if (!handle_get_set)
+					res = -1;
+				break;
+			case Token.REMOVE:
+			case Token.ADD:
+				if (!handle_remove_add)
+					res = -1;
+				break;
+			case Token.EXTERN:
+				if (parsing_declaration == 0)
+					res = Token.EXTERN_ALIAS;
+				break;
+			case Token.DEFAULT:
+				if (peek_token () == Token.COLON) {
+					token ();
+					res = Token.DEFAULT_COLON;
+				}
+				break;
+			case Token.WHERE:
+				if (!(handle_where && current_token != Token.COLON) && !query_parsing)
+					res = -1;
+				break;
+			case Token.FROM:
+				//
+				// A query expression is any expression that starts with `from identifier'
+				// followed by any token except ; , =
+				// 
+				if (!query_parsing) {
+					if (lambda_arguments_parsing || parsing_block == 0) {
+						res = -1;
+						break;
+					}
+
+					PushPosition ();
+					// HACK: to disable generics micro-parser, because PushPosition does not
+					// store identifiers array
+					parsing_generic_less_than = 1;
+					switch (xtoken ()) {
+					case Token.IDENTIFIER:
+					case Token.INT:
+					case Token.BOOL:
+					case Token.BYTE:
+					case Token.CHAR:
+					case Token.DECIMAL:
+					case Token.DOUBLE:
+					case Token.FLOAT:
+					case Token.LONG:
+					case Token.OBJECT:
+					case Token.STRING:
+					case Token.UINT:
+					case Token.ULONG:
+						next_token = xtoken ();
+						if (next_token == Token.SEMICOLON || next_token == Token.COMMA || next_token == Token.EQUALS || next_token == Token.ASSIGN)
+							goto default;
+						
+						res = Token.FROM_FIRST;
+						query_parsing = true;
+						if (context.Settings.Version <= LanguageVersion.ISO_2)
+							Report.FeatureIsNotAvailable (context, Location, "query expressions");
+						break;
+					case Token.VOID:
+						Expression.Error_VoidInvalidInTheContext (Location, Report);
+						break;
+					default:
+						PopPosition ();
+						// HACK: A token is not a keyword so we need to restore identifiers buffer
+						// which has been overwritten before we grabbed the identifier
+						id_builder [0] = 'f'; id_builder [1] = 'r'; id_builder [2] = 'o'; id_builder [3] = 'm';
+						return -1;
+					}
+					PopPosition ();
+				}
+				break;
+			case Token.JOIN:
+			case Token.ON:
+			case Token.EQUALS:
+			case Token.SELECT:
+			case Token.GROUP:
+			case Token.BY:
+			case Token.LET:
+			case Token.ORDERBY:
+			case Token.ASCENDING:
+			case Token.DESCENDING:
+			case Token.INTO:
+				if (!query_parsing)
+					res = -1;
+				break;
+				
+			case Token.USING:
+			case Token.NAMESPACE:
+				// TODO: some explanation needed
+				check_incorrect_doc_comment ();
+				parsing_modifiers = false;
+				break;
+				
+			case Token.PARTIAL:
+				if (parsing_block > 0) {
+					res = -1;
+					break;
+				}
+
+				// Save current position and parse next token.
+				PushPosition ();
+
+				next_token = token ();
+				bool ok = (next_token == Token.CLASS) ||
+					(next_token == Token.STRUCT) ||
+					(next_token == Token.INTERFACE) ||
+					(next_token == Token.VOID);
+
+				PopPosition ();
+
+				if (ok) {
+					if (next_token == Token.VOID) {
+						if (context.Settings.Version <= LanguageVersion.ISO_2)
+							Report.FeatureIsNotAvailable (context, Location, "partial methods");
+					} else if (context.Settings.Version == LanguageVersion.ISO_1)
+						Report.FeatureIsNotAvailable (context, Location, "partial types");
+
+					return res;
+				}
+
+				if (next_token < Token.LAST_KEYWORD) {
+					Report.Error (267, Location,
+						"The `partial' modifier can be used only immediately before `class', `struct', `interface', or `void' keyword");
+					return token ();
+				}
+
+				// HACK: A token is not a keyword so we need to restore identifiers buffer
+				// which has been overwritten before we grabbed the identifier
+				id_builder[0] = 'p';
+				id_builder[1] = 'a';
+				id_builder[2] = 'r';
+				id_builder[3] = 't';
+				id_builder[4] = 'i';
+				id_builder[5] = 'a';
+				id_builder[6] = 'l';
+				res = -1;
+				break;
+
+			case Token.ASYNC:
+				if (parsing_modifiers) {
+					//
+					// Skip attributes section or constructor called async
+					//
+					if (parsing_attribute_section || peek_token () == Token.OPEN_PARENS) {
+						res = -1;
+					} else {
+						// async is keyword
+					}
+				} else if (parsing_block > 0) {
+					switch (peek_token ()) {
+					case Token.DELEGATE:
+					case Token.OPEN_PARENS_LAMBDA:
+						// async is keyword
+						break;
+					case Token.IDENTIFIER:
+						PushPosition ();
+						xtoken ();
+						if (xtoken () != Token.ARROW) {
+							PopPosition ();
+							goto default;
+						}
+
+						PopPosition ();
+						break;
+					default:
+						// peek_token could overwrite id_buffer
+						id_builder [0] = 'a'; id_builder [1] = 's'; id_builder [2] = 'y'; id_builder [3] = 'n'; id_builder [4] = 'c';
+						res = -1;
+						break;
+					}
+				} else {
+					res = -1;
+				}
+
+				if (res == Token.ASYNC && context.Settings.Version <= LanguageVersion.V_4) {
+					Report.FeatureIsNotAvailable (context, Location, "asynchronous functions");
+				}
+				
+				break;
+
+			case Token.AWAIT:
+				if (parsing_block == 0)
+					res = -1;
+
+				break;
+			}
+
+			return res;
+		}
+
+		static PreprocessorDirective GetPreprocessorDirective (char[] id, int id_len)
+		{
+			//
+			// Keywords are stored in an array of arrays grouped by their
+			// length and then by the first character
+			//
+			if (id_len >= keywords_preprocessor.Length || keywords_preprocessor[id_len] == null)
+				return PreprocessorDirective.Invalid;
+
+			int first_index = id[0] - '_';
+			if (first_index > 'z' - '_')
+				return PreprocessorDirective.Invalid;
+
+			var kwe = keywords_preprocessor[id_len][first_index];
+			if (kwe == null)
+				return PreprocessorDirective.Invalid;
+
+			PreprocessorDirective res = PreprocessorDirective.Invalid;
+			do {
+				res = kwe.Token;
+				for (int i = 1; i < id_len; ++i) {
+					if (id[i] != kwe.Value[i]) {
+						res = 0;
+						kwe = kwe.Next;
+						break;
+					}
+				}
+			} while (res == PreprocessorDirective.Invalid && kwe != null);
+
+			return res;
+		}
+
+		public Location Location {
+			get {
+				return new Location (current_source, ref_line, col);
+			}
+		}
+
+		static bool is_identifier_start_character (int c)
+		{
+			return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter ((char)c);
+		}
+
+		static bool is_identifier_part_character (char c)
+		{
+			if (c >= 'a' && c <= 'z')
+				return true;
+
+			if (c >= 'A' && c <= 'Z')
+				return true;
+
+			if (c == '_' || (c >= '0' && c <= '9'))
+				return true;
+
+			if (c < 0x80)
+				return false;
+
+			return is_identifier_part_character_slow_part (c);
+		}
+
+		static bool is_identifier_part_character_slow_part (char c)
+		{
+			if (Char.IsLetter (c))
+				return true;
+
+			switch (Char.GetUnicodeCategory (c)) {
+				case UnicodeCategory.ConnectorPunctuation:
+
+				// combining-character: A Unicode character of classes Mn or Mc
+				case UnicodeCategory.NonSpacingMark:
+				case UnicodeCategory.SpacingCombiningMark:
+
+				// decimal-digit-character: A Unicode character of the class Nd 
+				case UnicodeCategory.DecimalDigitNumber:
+				return true;
+			}
+
+			return false;
+		}
+
+		public static bool IsKeyword (string s)
+		{
+			return keyword_strings.Contains (s);
+		}
+
+		//
+		// Open parens micro parser. Detects both lambda and cast ambiguity.
+		//	
+		int TokenizeOpenParens ()
+		{
+			int ptoken;
+			current_token = -1;
+
+			int bracket_level = 0;
+			bool is_type = false;
+			bool can_be_type = false;
+			
+			while (true) {
+				ptoken = current_token;
+				token ();
+
+				switch (current_token) {
+				case Token.CLOSE_PARENS:
+					token ();
+					
+					//
+					// Expression inside parens is lambda, (int i) => 
+					//
+					if (current_token == Token.ARROW)
+						return Token.OPEN_PARENS_LAMBDA;
+
+					//
+					// Expression inside parens is single type, (int[])
+					//
+					if (is_type) {
+						if (current_token == Token.SEMICOLON)
+							return Token.OPEN_PARENS;
+
+						return Token.OPEN_PARENS_CAST;
+					}
+
+					//
+					// Expression is possible cast, look at next token, (T)null
+					//
+					if (can_be_type) {
+						switch (current_token) {
+						case Token.OPEN_PARENS:
+						case Token.BANG:
+						case Token.TILDE:
+						case Token.IDENTIFIER:
+						case Token.LITERAL:
+						case Token.BASE:
+						case Token.CHECKED:
+						case Token.DELEGATE:
+						case Token.FALSE:
+						case Token.FIXED:
+						case Token.NEW:
+						case Token.NULL:
+						case Token.SIZEOF:
+						case Token.THIS:
+						case Token.THROW:
+						case Token.TRUE:
+						case Token.TYPEOF:
+						case Token.UNCHECKED:
+						case Token.UNSAFE:
+						case Token.DEFAULT:
+						case Token.AWAIT:
+
+						//
+						// These can be part of a member access
+						//
+						case Token.INT:
+						case Token.UINT:
+						case Token.SHORT:
+						case Token.USHORT:
+						case Token.LONG:
+						case Token.ULONG:
+						case Token.DOUBLE:
+						case Token.FLOAT:
+						case Token.CHAR:
+						case Token.BYTE:
+						case Token.DECIMAL:
+						case Token.BOOL:
+							return Token.OPEN_PARENS_CAST;
+						}
+					}
+					return Token.OPEN_PARENS;
+					
+				case Token.DOT:
+				case Token.DOUBLE_COLON:
+					if (ptoken != Token.IDENTIFIER && ptoken != Token.OP_GENERICS_GT)
+						goto default;
+
+					continue;
+
+				case Token.IDENTIFIER:
+				case Token.AWAIT:
+					switch (ptoken) {
+					case Token.DOT:
+						if (bracket_level == 0) {
+							is_type = false;
+							can_be_type = true;
+						}
+
+						continue;
+					case Token.OP_GENERICS_LT:
+					case Token.COMMA:
+					case Token.DOUBLE_COLON:
+					case -1:
+						if (bracket_level == 0)
+							can_be_type = true;
+						continue;
+					default:
+						can_be_type = is_type = false;
+						continue;
+					}
+
+				case Token.OBJECT:
+				case Token.STRING:
+				case Token.BOOL:
+				case Token.DECIMAL:
+				case Token.FLOAT:
+				case Token.DOUBLE:
+				case Token.SBYTE:
+				case Token.BYTE:
+				case Token.SHORT:
+				case Token.USHORT:
+				case Token.INT:
+				case Token.UINT:
+				case Token.LONG:
+				case Token.ULONG:
+				case Token.CHAR:
+				case Token.VOID:
+					if (bracket_level == 0)
+						is_type = true;
+					continue;
+
+				case Token.COMMA:
+					if (bracket_level == 0) {
+						bracket_level = 100;
+						can_be_type = is_type = false;
+					}
+					continue;
+
+				case Token.OP_GENERICS_LT:
+				case Token.OPEN_BRACKET:
+					if (bracket_level++ == 0)
+						is_type = true;
+					continue;
+
+				case Token.OP_GENERICS_GT:
+				case Token.CLOSE_BRACKET:
+					--bracket_level;
+					continue;
+
+				case Token.INTERR_NULLABLE:
+				case Token.STAR:
+					if (bracket_level == 0)
+						is_type = true;
+					continue;
+
+				case Token.REF:
+				case Token.OUT:
+					can_be_type = is_type = false;
+					continue;
+
+				default:
+					return Token.OPEN_PARENS;
+				}
+			}
+		}
+
+		public static bool IsValidIdentifier (string s)
+		{
+			if (s == null || s.Length == 0)
+				return false;
+
+			if (!is_identifier_start_character (s [0]))
+				return false;
+			
+			for (int i = 1; i < s.Length; i ++)
+				if (! is_identifier_part_character (s [i]))
+					return false;
+			
+			return true;
+		}
+
+		Stack<List<Location>> genericDimensionLocations = new Stack<List<Location>> ();
+
+		public List<Location> GenericDimensionLocations {
+			get {
+				if (genericDimensionLocations.Count == 0)
+					return null;
+				return genericDimensionLocations.Pop ();
+			}
+		}
+
+		bool parse_less_than (ref int genericDimension)
+		{
+			genericDimensionLocations.Push (new List<Location> ()); 
+			genericDimensionLocations.Peek ().Add (Location);
+			start:
+			int the_token = token ();
+			if (the_token == Token.OPEN_BRACKET) {
+				while (true) {
+					the_token = token ();
+					if (the_token == Token.EOF)
+						return true;
+
+					if (the_token == Token.CLOSE_BRACKET)
+						break;
+				}
+				the_token = token ();
+			} else if (the_token == Token.IN || the_token == Token.OUT) {
+				the_token = token ();
+			}
+			switch (the_token) {
+			case Token.IDENTIFIER:
+			case Token.OBJECT:
+			case Token.STRING:
+			case Token.BOOL:
+			case Token.DECIMAL:
+			case Token.FLOAT:
+			case Token.DOUBLE:
+			case Token.SBYTE:
+			case Token.BYTE:
+			case Token.SHORT:
+			case Token.USHORT:
+			case Token.INT:
+			case Token.UINT:
+			case Token.LONG:
+			case Token.ULONG:
+			case Token.CHAR:
+			case Token.VOID:
+				break;
+			case Token.OP_GENERICS_GT:
+				genericDimension = 1;
+				genericDimensionLocations.Peek ().Add (Location);
+				return true;
+			case Token.IN:
+			case Token.OUT:
+				genericDimensionLocations.Pop ();
+				return true;
+			case Token.COMMA:
+				do {
+					++genericDimension;
+					if (genericDimensionLocations.Count > 0)
+						genericDimensionLocations.Peek ().Add (Location);
+					the_token = token ();
+				} while (the_token == Token.COMMA);
+
+				if (the_token == Token.OP_GENERICS_GT) {
+					++genericDimension;
+					if (genericDimensionLocations.Count > 0)
+						genericDimensionLocations.Peek ().Add (Location);
+					return true;
+				}
+
+				genericDimensionLocations.Pop ();
+				return false;
+			default:
+				genericDimensionLocations.Pop ();
+				return false;
+			}
+			again:
+			the_token = token ();
+			if (the_token == Token.OP_GENERICS_GT) {
+				genericDimensionLocations.Peek ().Add (Location);
+				return true;
+			}
+			else if (the_token == Token.COMMA || the_token == Token.DOT || the_token == Token.DOUBLE_COLON)
+				goto start;
+			else if (the_token == Token.INTERR_NULLABLE || the_token == Token.STAR)
+				goto again;
+			else if (the_token == Token.OP_GENERICS_LT) {
+				if (!parse_less_than (ref genericDimension)) {
+					genericDimensionLocations.Pop ();
+					return false;
+				}
+				goto again;
+			} else if (the_token == Token.OPEN_BRACKET) {
+				rank_specifiers:
+				the_token = token ();
+				if (the_token == Token.CLOSE_BRACKET)
+					goto again;
+				else if (the_token == Token.COMMA)
+					goto rank_specifiers;
+				genericDimensionLocations.Pop ();
+				return false;
+			}
+
+			genericDimensionLocations.Pop ();
+			return false;
+		}
+
+
+		public int peek_token ()
+		{
+			int the_token;
+
+			PushPosition ();
+			sbag.Suppress = true;
+			the_token = token ();
+			sbag.Suppress = false;
+			PopPosition ();
+			
+			return the_token;
+		}
+					
+		//
+		// Tonizes `?' using custom disambiguous rules to return one
+		// of following tokens: INTERR_NULLABLE, OP_COALESCING, INTERR
+		//
+		// Tricky expression looks like:
+		//
+		// Foo ? a = x ? b : c;
+		//
+		int TokenizePossibleNullableType ()
+		{
+			if (parsing_block == 0 || parsing_type > 0)
+				return Token.INTERR_NULLABLE;
+
+			int d = peek_char ();
+			if (d == '?') {
+				get_char ();
+				return Token.OP_COALESCING;
+			}
+
+			if (d == '.') {
+				return Token.INTERR_OPERATOR;
+			}
+
+			if (d != ' ') {
+				if (d == ',' || d == ';' || d == '>')
+					return Token.INTERR_NULLABLE;
+				if (d == '*' || (d >= '0' && d <= '9'))
+					return Token.INTERR;
+			}
+
+			PushPosition ();
+			current_token = Token.NONE;
+			int next_token;
+			int parens = 0;
+			int generics = 0;
+
+			var nt = xtoken ();
+			switch (nt) {
+			case Token.DOT:
+			case Token.OPEN_BRACKET_EXPR:
+				next_token = Token.INTERR_OPERATOR;
+				break;
+			case Token.LITERAL:
+			case Token.TRUE:
+			case Token.FALSE:
+			case Token.NULL:
+			case Token.THIS:
+			case Token.NEW:
+				next_token = Token.INTERR;
+				break;
+				
+			case Token.SEMICOLON:
+			case Token.COMMA:
+			case Token.CLOSE_PARENS:
+			case Token.OPEN_BRACKET:
+			case Token.OP_GENERICS_GT:
+			case Token.INTERR:
+			case Token.OP_COALESCING:
+			case Token.COLON:
+				next_token = Token.INTERR_NULLABLE;
+				break;
+
+			case Token.OPEN_PARENS:
+			case Token.OPEN_PARENS_CAST:
+			case Token.OPEN_PARENS_LAMBDA:
+				next_token = -1;
+				++parens;
+				break;
+
+			case Token.OP_GENERICS_LT:
+			case Token.OP_GENERICS_LT_DECL:
+			case Token.GENERIC_DIMENSION:
+				next_token = -1;
+				++generics;
+				break;
+
+			default:
+				next_token = -1;
+				break;
+			}
+
+			if (next_token == -1) {
+				switch (xtoken ()) {
+				case Token.COMMA:
+				case Token.SEMICOLON:
+				case Token.OPEN_BRACE:
+				case Token.IN:
+					next_token = Token.INTERR_NULLABLE;
+					break;
+					
+				case Token.COLON:
+					next_token = Token.INTERR;
+					break;
+
+				case Token.OPEN_PARENS:
+				case Token.OPEN_PARENS_CAST:
+				case Token.OPEN_PARENS_LAMBDA:
+					++parens;
+					goto default;
+
+				case Token.CLOSE_PARENS:
+					--parens;
+					goto default;
+
+				case Token.OP_GENERICS_LT:
+				case Token.OP_GENERICS_LT_DECL:
+				case Token.GENERIC_DIMENSION:
+					++generics;
+					goto default;
+
+				default:
+					int ntoken;
+					int interrs = 1;
+					int colons = 0;
+					int braces = 0;
+					int brackets = 0;
+					//
+					// All shorcuts failed, do it hard way
+					//
+					while ((ntoken = xtoken ()) != Token.EOF) {
+						switch (ntoken) {
+						case Token.OPEN_BRACE:
+							++braces;
+							continue;
+						case Token.OPEN_PARENS:
+						case Token.OPEN_PARENS_CAST:
+						case Token.OPEN_PARENS_LAMBDA:
+							++parens;
+							continue;
+						case Token.CLOSE_BRACE:
+							--braces;
+							continue;
+						case Token.OP_GENERICS_LT:
+						case Token.OP_GENERICS_LT_DECL:
+						case Token.GENERIC_DIMENSION:
+							++generics;
+							continue;
+						case Token.OPEN_BRACKET:
+						case Token.OPEN_BRACKET_EXPR:
+							++brackets;
+							continue;
+						case Token.CLOSE_BRACKET:
+							--brackets;
+							continue;
+						case Token.CLOSE_PARENS:
+							if (parens > 0) {
+								--parens;
+								continue;
+							}
+
+							PopPosition ();
+							return Token.INTERR_NULLABLE;
+
+						case Token.OP_GENERICS_GT:
+							if (generics > 0) {
+								--generics;
+								continue;
+							}
+
+							PopPosition ();
+							return Token.INTERR_NULLABLE;
+						}
+
+						if (braces != 0)
+							continue;
+
+						if (ntoken == Token.SEMICOLON)
+							break;
+
+						if (parens != 0)
+							continue;
+
+						if (ntoken == Token.COMMA) {
+							if (generics != 0 || brackets != 0)
+								continue;
+
+							PopPosition ();
+							return Token.INTERR_NULLABLE;
+						}
+						
+						if (ntoken == Token.COLON) {
+							if (++colons == interrs)
+								break;
+							continue;
+						}
+						
+						if (ntoken == Token.INTERR) {
+							++interrs;
+							continue;
+						}
+					}
+					
+					next_token = colons != interrs && braces == 0 ? Token.INTERR_NULLABLE : Token.INTERR;
+					break;
+				}
+			}
+			
+			PopPosition ();
+			return next_token;
+		}
+
+		bool decimal_digits (int c)
+		{
+			int d;
+			bool seen_digits = false;
+			
+			if (c != -1){
+				if (number_pos == MaxNumberLength)
+					Error_NumericConstantTooLong ();
+				number_builder [number_pos++] = (char) c;
+			}
+			
+			//
+			// We use peek_char2, because decimal_digits needs to do a 
+			// 2-character look-ahead (5.ToString for example).
+			//
+			while ((d = peek_char2 ()) != -1){
+				if (d >= '0' && d <= '9'){
+					if (number_pos == MaxNumberLength)
+						Error_NumericConstantTooLong ();
+					number_builder [number_pos++] = (char) d;
+					get_char ();
+					seen_digits = true;
+				} else
+					break;
+			}
+			
+			return seen_digits;
+		}
+
+		static bool is_hex (int e)
+		{
+			return (e >= '0' && e <= '9') || (e >= 'A' && e <= 'F') || (e >= 'a' && e <= 'f');
+		}
+
+		static TypeCode real_type_suffix (int c)
+		{
+			switch (c){
+			case 'F': case 'f':
+				return TypeCode.Single;
+			case 'D': case 'd':
+				return TypeCode.Double;
+			case 'M': case 'm':
+				return TypeCode.Decimal;
+			default:
+				return TypeCode.Empty;
+			}
+		}
+
+		ILiteralConstant integer_type_suffix (ulong ul, int c, Location loc)
+		{
+			bool is_unsigned = false;
+			bool is_long = false;
+
+			if (c != -1){
+				bool scanning = true;
+				do {
+					switch (c){
+					case 'U': case 'u':
+						if (is_unsigned)
+							scanning = false;
+						is_unsigned = true;
+						get_char ();
+						break;
+
+					case 'l':
+						if (!is_unsigned){
+							//
+							// if we have not seen anything in between
+							// report this error
+							//
+							Report.Warning (78, 4, Location, "The `l' suffix is easily confused with the digit `1' (use `L' for clarity)");
+						}
+
+						goto case 'L';
+
+					case 'L': 
+						if (is_long)
+							scanning = false;
+						is_long = true;
+						get_char ();
+						break;
+						
+					default:
+						scanning = false;
+						break;
+					}
+					c = peek_char ();
+				} while (scanning);
+			}
+
+			if (is_long && is_unsigned){
+				return new ULongLiteral (context.BuiltinTypes, ul, loc);
+			}
+			
+			if (is_unsigned){
+				// uint if possible, or ulong else.
+
+				if ((ul & 0xffffffff00000000) == 0)
+					return new UIntLiteral (context.BuiltinTypes, (uint) ul, loc);
+				else
+					return new ULongLiteral (context.BuiltinTypes, ul, loc);
+			} else if (is_long){
+				// long if possible, ulong otherwise
+				if ((ul & 0x8000000000000000) != 0)
+					return new ULongLiteral (context.BuiltinTypes, ul, loc);
+				else
+					return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
+			} else {
+				// int, uint, long or ulong in that order
+				if ((ul & 0xffffffff00000000) == 0){
+					uint ui = (uint) ul;
+					
+					if ((ui & 0x80000000) != 0)
+						return new UIntLiteral (context.BuiltinTypes, ui, loc);
+					else
+						return new IntLiteral (context.BuiltinTypes, (int) ui, loc);
+				} else {
+					if ((ul & 0x8000000000000000) != 0)
+						return new ULongLiteral (context.BuiltinTypes, ul, loc);
+					else
+						return new LongLiteral (context.BuiltinTypes, (long) ul, loc);
+				}
+			}
+		}
+				
+		//
+		// given `c' as the next char in the input decide whether
+		// we need to convert to a special type, and then choose
+		// the best representation for the integer
+		//
+		ILiteralConstant adjust_int (int c, Location loc)
+		{
+			try {
+				if (number_pos > 9){
+					ulong ul = (uint) (number_builder [0] - '0');
+
+					for (int i = 1; i < number_pos; i++){
+						ul = checked ((ul * 10) + ((uint)(number_builder [i] - '0')));
+					}
+
+					return integer_type_suffix (ul, c, loc);
+				} else {
+					uint ui = (uint) (number_builder [0] - '0');
+
+					for (int i = 1; i < number_pos; i++){
+						ui = checked ((ui * 10) + ((uint)(number_builder [i] - '0')));
+					}
+
+					return integer_type_suffix (ui, c, loc);
+				}
+			} catch (OverflowException) {
+				Error_NumericConstantTooLong ();
+				return new IntLiteral (context.BuiltinTypes, 0, loc);
+			}
+			catch (FormatException) {
+				Report.Error (1013, Location, "Invalid number");
+				return new IntLiteral (context.BuiltinTypes, 0, loc);
+			}
+		}
+		
+		ILiteralConstant adjust_real (TypeCode t, Location loc)
+		{
+			string s = new string (number_builder, 0, number_pos);
+			const string error_details = "Floating-point constant is outside the range of type `{0}'";
+
+			switch (t){
+			case TypeCode.Decimal:
+				try {
+					return new DecimalLiteral (context.BuiltinTypes, decimal.Parse (s, styles, csharp_format_info), loc);
+				} catch (OverflowException) {
+					Report.Error (594, Location, error_details, "decimal");
+					return new DecimalLiteral (context.BuiltinTypes, 0, loc);
+				}
+			case TypeCode.Single:
+				try {
+					return new FloatLiteral (context.BuiltinTypes, float.Parse (s, styles, csharp_format_info), loc);
+				} catch (OverflowException) {
+					Report.Error (594, Location, error_details, "float");
+					return new FloatLiteral (context.BuiltinTypes, 0, loc);
+				}
+			default:
+				try {
+					return new DoubleLiteral (context.BuiltinTypes, double.Parse (s, styles, csharp_format_info), loc);
+				} catch (OverflowException) {
+					Report.Error (594, loc, error_details, "double");
+					return new DoubleLiteral (context.BuiltinTypes, 0, loc);
+				}
+			}
+		}
+
+		ILiteralConstant handle_hex (Location loc)
+		{
+			int d;
+			ulong ul;
+			
+			get_char ();
+			while ((d = peek_char ()) != -1){
+				if (is_hex (d)){
+					number_builder [number_pos++] = (char) d;
+					get_char ();
+				} else
+					break;
+			}
+			
+			string s = new String (number_builder, 0, number_pos);
+
+			try {
+				if (number_pos <= 8)
+					ul = System.UInt32.Parse (s, NumberStyles.HexNumber);
+				else
+					ul = System.UInt64.Parse (s, NumberStyles.HexNumber);
+
+				return integer_type_suffix (ul, peek_char (), loc);
+			} catch (OverflowException){
+				Error_NumericConstantTooLong ();
+				return new IntLiteral (context.BuiltinTypes, 0, loc);
+			}
+			catch (FormatException) {
+				Report.Error (1013, Location, "Invalid number");
+				return new IntLiteral (context.BuiltinTypes, 0, loc);
+			}
+		}
+
+		//
+		// Invoked if we know we have .digits or digits
+		//
+		int is_number (int c, bool dotLead)
+		{
+			ILiteralConstant res;
+
+#if FULL_AST
+			int read_start = reader.Position - 1;
+			if (dotLead) {
+				//
+				// Caller did peek_char
+				//
+				--read_start;
+			}
+#endif
+			number_pos = 0;
+			var loc = Location;
+			bool hasLeadingDot = c == '.';
+
+			if (!dotLead){
+				if (c == '0'){
+					int peek = peek_char ();
+
+					if (peek == 'x' || peek == 'X') {
+						val = res = handle_hex (loc);
+#if FULL_AST
+						res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
+#endif
+
+						return Token.LITERAL;
+					}
+				}
+				decimal_digits (c);
+				c = peek_char ();
+			}
+
+			//
+			// We need to handle the case of
+			// "1.1" vs "1.string" (LITERAL_FLOAT vs NUMBER DOT IDENTIFIER)
+			//
+			bool is_real = false;
+			if (c == '.'){
+				if (!dotLead)
+					get_char ();
+
+				if (decimal_digits ('.')){
+					is_real = true;
+					c = peek_char ();
+				} else {
+					putback ('.');
+					number_pos--;
+					val = res = adjust_int (-1, loc);
+#if FULL_AST
+					res.ParsedValue = reader.ReadChars (read_start, reader.Position - 1);
+#endif
+					return Token.LITERAL;
+				}
+			}
+			
+			if (c == 'e' || c == 'E'){
+				is_real = true;
+				get_char ();
+				if (number_pos == MaxNumberLength)
+					Error_NumericConstantTooLong ();
+				number_builder [number_pos++] = (char) c;
+				c = get_char ();
+				
+				if (c == '+'){
+					if (number_pos == MaxNumberLength)
+						Error_NumericConstantTooLong ();
+					number_builder [number_pos++] = '+';
+					c = -1;
+				} else if (c == '-') {
+					if (number_pos == MaxNumberLength)
+						Error_NumericConstantTooLong ();
+					number_builder [number_pos++] = '-';
+					c = -1;
+				} else {
+					if (number_pos == MaxNumberLength)
+						Error_NumericConstantTooLong ();
+					number_builder [number_pos++] = '+';
+				}
+					
+				decimal_digits (c);
+				c = peek_char ();
+			}
+
+			var type = real_type_suffix (c);
+			if (type == TypeCode.Empty && !is_real) {
+				res = adjust_int (c, loc);
+			} else {
+				is_real = true;
+
+				if (type != TypeCode.Empty) {
+					get_char ();
+				}
+
+				res = adjust_real (type, loc);
+			}
+
+			val = res;
+#if FULL_AST
+			var chars = reader.ReadChars (read_start, reader.Position - (type == TypeCode.Empty && c > 0 ? 1 : 0));
+			if (chars[chars.Length - 1] == '\r')
+				Array.Resize (ref chars, chars.Length - 1);
+			res.ParsedValue = chars;
+#endif
+
+			return Token.LITERAL;
+		}
+
+		//
+		// Accepts exactly count (4 or 8) hex, no more no less
+		//
+		int getHex (int count, out int surrogate, out bool error)
+		{
+			int i;
+			int total = 0;
+			int c;
+			int top = count != -1 ? count : 4;
+			
+			get_char ();
+			error = false;
+			surrogate = 0;
+			for (i = 0; i < top; i++){
+				c = get_char ();
+
+				if (c >= '0' && c <= '9')
+					c = (int) c - (int) '0';
+				else if (c >= 'A' && c <= 'F')
+					c = (int) c - (int) 'A' + 10;
+				else if (c >= 'a' && c <= 'f')
+					c = (int) c - (int) 'a' + 10;
+				else {
+					error = true;
+					return 0;
+				}
+				
+				total = (total * 16) + c;
+				if (count == -1){
+					int p = peek_char ();
+					if (p == -1)
+						break;
+					if (!is_hex ((char)p))
+						break;
+				}
+			}
+
+			if (top == 8) {
+				if (total > 0x0010FFFF) {
+					error = true;
+					return 0;
+				}
+
+				if (total >= 0x00010000) {
+					surrogate = ((total - 0x00010000) % 0x0400 + 0xDC00);					
+					total = ((total - 0x00010000) / 0x0400 + 0xD800);
+				}
+			}
+
+			return total;
+		}
+
+		int escape (int c, out int surrogate)
+		{
+			bool error;
+			int d;
+			int v;
+
+			d = peek_char ();
+			if (c != '\\') {
+				surrogate = 0;
+				return c;
+			}
+			
+			switch (d){
+			case 'a':
+				v = '\a'; break;
+			case 'b':
+				v = '\b'; break;
+			case 'n':
+				v = '\n'; break;
+			case 't':
+				v = '\t'; break;
+			case 'v':
+				v = '\v'; break;
+			case 'r':
+				v = '\r'; break;
+			case '\\':
+				v = '\\'; break;
+			case 'f':
+				v = '\f'; break;
+			case '0':
+				v = 0; break;
+			case '"':
+				v = '"'; break;
+			case '\'':
+				v = '\''; break;
+			case 'x':
+				v = getHex (-1, out surrogate, out error);
+				if (error)
+					goto default;
+				return v;
+			case 'u':
+			case 'U':
+				return EscapeUnicode (d, out surrogate);
+			default:
+				surrogate = 0;
+				Report.Error (1009, Location, "Unrecognized escape sequence `\\{0}'", ((char)d).ToString ());
+				return d;
+			}
+
+			get_char ();
+			surrogate = 0;
+			return v;
+		}
+
+		int EscapeUnicode (int ch, out int surrogate)
+		{
+			bool error;
+			if (ch == 'U') {
+				ch = getHex (8, out surrogate, out error);
+			} else {
+				ch = getHex (4, out surrogate, out error);
+			}
+
+			if (error)
+				Report.Error (1009, Location, "Unrecognized escape sequence");
+
+			return ch;
+		}
+
+		int get_char ()
+		{
+			int x;
+			if (putback_char != -1) {
+				x = putback_char;
+				putback_char = -1;
+			} else {
+				x = reader.Read ();
+			}
+			
+			if (x <= 13) {
+				if (x == '\r') {
+					if (peek_char () == '\n') {
+						putback_char = -1;
+						advance_line (SpecialsBag.NewLine.Windows);
+					} else {
+						advance_line (SpecialsBag.NewLine.Unix);
+					}
+
+					x = '\n';
+				} else if (x == '\n') {
+					advance_line (SpecialsBag.NewLine.Unix);
+				} else {
+					col++;
+				}
+			} else if (x >= UnicodeLS && x <= UnicodePS) {
+				advance_line (SpecialsBag.NewLine.Unix);
+			} else {
+				col++;
+			}
+
+			return x;
+		}
+
+		bool recordNewLine = true;
+		void advance_line (SpecialsBag.NewLine newLine)
+		{
+			if (recordNewLine)
+				sbag.AddNewLine (line, col, newLine);
+			line++;
+			ref_line++;
+			previous_col = col;
+			col = 0;
+			startsLine = true;
+		}
+
+		int peek_char ()
+		{
+			if (putback_char == -1)
+				putback_char = reader.Read ();
+			return putback_char;
+		}
+
+		int peek_char2 ()
+		{
+			if (putback_char != -1)
+				return putback_char;
+			return reader.Peek ();
+		}
+		
+		public void putback (int c)
+		{
+			if (putback_char != -1) {
+				throw new InternalErrorException (string.Format ("Secondary putback [{0}] putting back [{1}] is not allowed", (char)putback_char, (char) c), Location);
+			}
+
+			if (c == '\n' || col == 0 || (c >= UnicodeLS && c <= UnicodePS)) {
+				// It won't happen though.
+				line--;
+				ref_line--;
+				col = previous_col;
+			}
+			else
+				col--;
+			putback_char = c;
+		}
+
+		public bool advance ()
+		{
+			return peek_char () != -1 || CompleteOnEOF;
+		}
+
+		public Object Value {
+			get {
+				return val;
+			}
+		}
+
+		public Object value ()
+		{
+			return val;
+		}
+
+		public int token ()
+		{
+			current_token = xtoken ();
+			return current_token;
+		}
+
+		int TokenizePreprocessorIdentifier (out int c)
+		{
+			int startCol, endLine, endCol;
+			return TokenizePreprocessorIdentifier (out c, out startCol, out endLine, out endCol);
+		}
+
+		int TokenizePreprocessorIdentifier (out int c, out int startCol, out int endLine, out int endCol)
+		{
+			// skip over white space
+			do {
+				endLine = line;
+				endCol = col;
+				c = get_char ();
+			} while (c == ' ' || c == '\t');
+			startCol = col;
+			int pos = 0;
+			while (c != -1 && c >= 'a' && c <= 'z') {
+				id_builder[pos++] = (char) c;
+				endCol = col + 1;
+				c = get_char ();
+				if (c == '\\') {
+					int peek = peek_char ();
+					if (peek == 'U' || peek == 'u') {
+						int surrogate;
+						c = EscapeUnicode (c, out surrogate);
+						if (surrogate != 0) {
+							if (is_identifier_part_character ((char) c)) {
+								id_builder[pos++] = (char) c;
+							}
+							c = surrogate;
+						}
+					}
+				}
+			}
+
+			return pos;
+		}
+
+		PreprocessorDirective get_cmd_arg (out string arg)
+		{
+			int c;
+			int startLine = line, startCol = col;
+
+			tokens_seen = false;
+			arg = "";
+			
+			int startCol2, endLine, endCol;
+			var cmd = GetPreprocessorDirective (id_builder, TokenizePreprocessorIdentifier (out c, out startCol2, out endLine, out endCol));
+			
+			if ((cmd & PreprocessorDirective.CustomArgumentsParsing) != 0) {
+				if (position_stack.Count == 0)
+					sbag.AddPreProcessorDirective (startLine, startCol, line, col, cmd, null);
+				return cmd;
+			}
+			
+			// skip over white space
+			while (c == ' ' || c == '\t') {
+				c = get_char ();
+			}
+			int has_identifier_argument = (int)(cmd & PreprocessorDirective.RequiresArgument);
+			int pos = 0;
+			while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
+				if (c == '\\' && has_identifier_argument >= 0) {
+					if (has_identifier_argument != 0) {
+						has_identifier_argument = 1;
+
+						int peek = peek_char ();
+						if (peek == 'U' || peek == 'u') {
+							int surrogate;
+							c = EscapeUnicode (c, out surrogate);
+							if (surrogate != 0) {
+								if (is_identifier_part_character ((char)c)) {
+									if (pos == value_builder.Length)
+										Array.Resize (ref value_builder, pos * 2);
+
+									value_builder [pos++] = (char)c;
+								}
+								c = surrogate;
+							}
+						}
+					} else {
+						has_identifier_argument = -1;
+					}
+				} else if (c == '/' && peek_char () == '/') {
+					//
+					// Eat single-line comments
+					//
+					get_char ();
+					ReadToEndOfLine ();
+					break;
+				}
+				
+				endLine = line;
+				endCol = col + 1;
+				
+				if (pos == value_builder.Length)
+					Array.Resize (ref value_builder, pos * 2);
+
+				value_builder[pos++] = (char) c;
+				c = get_char ();
+			}
+
+			if (pos != 0) {
+				if (pos > MaxIdentifierLength)
+					arg = new string (value_builder, 0, pos);
+				else
+					arg = InternIdentifier (value_builder, pos);
+
+				// Eat any trailing whitespaces
+				arg = arg.Trim (simple_whitespaces);
+			}
+			if (position_stack.Count == 0)
+				sbag.AddPreProcessorDirective (startLine, startCol, endLine, endCol, cmd, arg);
+
+			return cmd;
+		}
+
+		//
+		// Handles the #line directive
+		//
+		bool PreProcessLine ()
+		{
+			Location loc = Location;
+			#if FULL_AST
+			var lineDirective = sbag.GetCurrentLineProcessorDirective();
+			#endif
+
+			int c;
+
+			int length = TokenizePreprocessorIdentifier (out c);
+			if (length == line_default.Length) {
+				if (!IsTokenIdentifierEqual (line_default))
+					return false;
+
+				current_source = source_file.SourceFile;
+				if (!hidden_block_start.IsNull) {
+					current_source.RegisterHiddenScope (hidden_block_start, loc);
+					hidden_block_start = Location.Null;
+				}
+
+				//ref_line = line;
+				return true;
+			}
+
+			if (length == line_hidden.Length) {
+				if (!IsTokenIdentifierEqual (line_hidden))
+					return false;
+
+				if (hidden_block_start.IsNull)
+					hidden_block_start = loc;
+
+				return true;
+			}
+
+			if (length != 0 || c < '0' || c > '9') {
+				//
+				// Eat any remaining characters to continue parsing on next line
+				//
+				ReadToEndOfLine ();
+				return false;
+			}
+
+			int new_line = TokenizeNumber (c);
+			if (new_line < 1) {
+				//
+				// Eat any remaining characters to continue parsing on next line
+				//
+				ReadToEndOfLine ();
+				return new_line != 0;
+			}
+			#if FULL_AST
+			lineDirective.LineNumber = new_line;
+			#endif
+
+			c = get_char ();
+			if (c == ' ') {
+				// skip over white space
+				do {
+					c = get_char ();
+				} while (c == ' ' || c == '\t');
+			} else if (c == '"') {
+				c = 0;
+			}
+
+			if (c != '\n' && c != '/' && c != '"' && c != UnicodeLS && c != UnicodePS) {
+				//
+				// Eat any remaining characters to continue parsing on next line
+				//
+				ReadToEndOfLine ();
+
+				Report.Error (1578, loc, "Filename, single-line comment or end-of-line expected");
+				return true;
+			}
+
+			string new_file_name = null;
+			if (c == '"') {
+				new_file_name = TokenizeFileName (ref c);
+				#if FULL_AST
+				lineDirective.FileName = new_file_name;
+				#endif
+
+				// skip over white space
+				while (c == ' ' || c == '\t') {
+					c = get_char ();
+				}
+			}
+
+			if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
+
+			} else if (c == '/') {
+				ReadSingleLineComment ();
+			} else {
+				//
+				// Eat any remaining characters to continue parsing on next line
+				//
+				ReadToEndOfLine ();
+
+				Error_EndLineExpected ();
+				return true;
+			}
+
+			if (new_file_name != null) {
+				current_source = context.LookupFile (source_file, new_file_name);
+				source_file.AddIncludeFile (current_source);
+			}
+
+			if (!hidden_block_start.IsNull) {
+				current_source.RegisterHiddenScope (hidden_block_start, loc);
+				hidden_block_start = Location.Null;
+			}
+
+			//ref_line = new_line;
+			return true;
+		}
+
+		//
+		// Handles #define and #undef
+		//
+		void PreProcessDefinition (bool is_define, string ident, bool caller_is_taking)
+		{
+			if (ident.Length == 0 || ident == "true" || ident == "false"){
+				Report.Error (1001, Location, "Missing identifier to pre-processor directive");
+				return;
+			}
+
+			if (ident.IndexOfAny (simple_whitespaces) != -1){
+				Error_EndLineExpected ();
+				return;
+			}
+
+			if (!is_identifier_start_character (ident [0]))
+				Report.Error (1001, Location, "Identifier expected: {0}", ident);
+			
+			foreach (char c in ident.Substring (1)){
+				if (!is_identifier_part_character (c)){
+					Report.Error (1001, Location, "Identifier expected: {0}",  ident);
+					return;
+				}
+			}
+
+			if (!caller_is_taking)
+				return;
+
+			if (is_define) {
+				//
+				// #define ident
+				//
+				if (context.Settings.IsConditionalSymbolDefined (ident))
+					return;
+
+				source_file.AddDefine (ident);
+			} else {
+				//
+				// #undef ident
+				//
+				source_file.AddUndefine (ident);
+			}
+		}
+
+		byte read_hex (out bool error)
+		{
+			int total;
+			int c = get_char ();
+
+			if ((c >= '0') && (c <= '9'))
+				total = (int) c - (int) '0';
+			else if ((c >= 'A') && (c <= 'F'))
+				total = (int) c - (int) 'A' + 10;
+			else if ((c >= 'a') && (c <= 'f'))
+				total = (int) c - (int) 'a' + 10;
+			else {
+				error = true;
+				return 0;
+			}
+
+			total *= 16;
+			c = get_char ();
+
+			if ((c >= '0') && (c <= '9'))
+				total += (int) c - (int) '0';
+			else if ((c >= 'A') && (c <= 'F'))
+				total += (int) c - (int) 'A' + 10;
+			else if ((c >= 'a') && (c <= 'f'))
+				total += (int) c - (int) 'a' + 10;
+			else {
+				error = true;
+				return 0;
+			}
+
+			error = false;
+			return (byte) total;
+		}
+
+		//
+		// Parses #pragma checksum
+		//
+		bool ParsePragmaChecksum ()
+		{
+			//
+			// The syntax is ` "foo.txt" "{guid}" "hash"'
+			//
+			// guid is predefined hash algorithm guid {406ea660-64cf-4c82-b6f0-42d48172a799} for md5
+			//
+			int c = get_char ();
+
+			if (c != '"')
+				return false;
+
+			string file_name = TokenizeFileName (ref c);
+
+			// TODO: Any white-spaces count
+			if (c != ' ')
+				return false;
+
+			SourceFile file = context.LookupFile (source_file, file_name);
+
+			if (get_char () != '"' || get_char () != '{')
+				return false;
+
+			bool error;
+			byte[] guid_bytes = new byte [16];
+			int i = 0;
+
+			for (; i < 4; i++) {
+				guid_bytes [i] = read_hex (out error);
+				if (error)
+					return false;
+			}
+
+			if (get_char () != '-')
+				return false;
+
+			for (; i < 10; i++) {
+				guid_bytes [i] = read_hex (out error);
+				if (error)
+					return false;
+
+				guid_bytes [i++] = read_hex (out error);
+				if (error)
+					return false;
+
+				if (get_char () != '-')
+					return false;
+			}
+
+			for (; i < 16; i++) {
+				guid_bytes [i] = read_hex (out error);
+				if (error)
+					return false;
+			}
+
+			if (get_char () != '}' || get_char () != '"')
+				return false;
+
+			// TODO: Any white-spaces count
+			c = get_char ();
+			if (c != ' ')
+				return false;
+
+			if (get_char () != '"')
+				return false;
+
+			// Any length of checksum
+			List<byte> checksum_bytes = new List<byte> (16);
+
+			var checksum_location = Location;
+			c = peek_char ();
+			while (c != '"' && c != -1) {
+				checksum_bytes.Add (read_hex (out error));
+				if (error)
+					return false;
+
+				c = peek_char ();
+			}
+
+			if (c == '/') {
+				ReadSingleLineComment ();
+			} else if (get_char () != '"') {
+				return false;
+			}
+
+			if (context.Settings.GenerateDebugInfo) {
+				var chsum = checksum_bytes.ToArray ();
+
+				if (file.HasChecksum) {
+					if (!ArrayComparer.IsEqual (file.Checksum, chsum)) {
+						// TODO: Report.SymbolRelatedToPreviousError
+						Report.Warning (1697, 1, checksum_location, "Different checksum values specified for file `{0}'", file.Name);
+					}
+				}
+
+				file.SetChecksum (guid_bytes, chsum);
+				current_source.AutoGenerated = true;
+			}
+
+			return true;
+		}
+
+		bool IsTokenIdentifierEqual (char[] identifier)
+		{
+			for (int i = 0; i < identifier.Length; ++i) {
+				if (identifier[i] != id_builder[i])
+					return false;
+			}
+
+			return true;
+		}
+
+		int TokenizeNumber (int value)
+		{
+			number_pos = 0;
+
+			decimal_digits (value);
+			uint ui = (uint) (number_builder[0] - '0');
+
+			try {
+				for (int i = 1; i < number_pos; i++) {
+					ui = checked ((ui * 10) + ((uint) (number_builder[i] - '0')));
+				}
+
+				return (int) ui;
+			} catch (OverflowException) {
+				Error_NumericConstantTooLong ();
+				return -1;
+			}
+		}
+
+		string TokenizeFileName (ref int c)
+		{
+			var string_builder = new StringBuilder ();
+			while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS) {
+				c = get_char ();
+				if (c == '"') {
+					c = get_char ();
+					break;
+				}
+
+				string_builder.Append ((char) c);
+			}
+
+			if (string_builder.Length == 0) {
+				Report.Warning (1709, 1, Location, "Filename specified for preprocessor directive is empty");
+			}
+
+		
+			return string_builder.ToString ();
+		}
+
+		int TokenizePragmaNumber (ref int c)
+		{
+			number_pos = 0;
+
+			int number;
+
+			if (c >= '0' && c <= '9') {
+				number = TokenizeNumber (c);
+
+				c = get_char ();
+
+				// skip over white space
+				while (c == ' ' || c == '\t')
+					c = get_char ();
+
+				if (c == ',') {
+					c = get_char ();
+				}
+
+				// skip over white space
+				while (c == ' ' || c == '\t')
+					c = get_char ();
+			} else {
+				number = -1;
+				if (c == '/') {
+					ReadSingleLineComment ();
+				} else {
+					Report.Warning (1692, 1, Location, "Invalid number");
+
+					// Read everything till the end of the line or file
+					ReadToEndOfLine ();
+				}
+			}
+
+			return number;
+		}
+
+		void ReadToEndOfLine ()
+		{
+			int c;
+			do {
+				c = get_char ();
+			} while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
+		}
+
+		void ReadSingleLineComment ()
+		{
+			if (peek_char () != '/')
+				Report.Warning (1696, 1, Location, "Single-line comment or end-of-line expected");
+			if (position_stack.Count == 0)
+				sbag.StartComment (SpecialsBag.CommentType.Single, startsLine, line, col - 1);
+			// Read everything till the end of the line or file
+			int c;
+			do {
+				c = get_char ();
+				if (position_stack.Count == 0)
+					sbag.PushCommentChar (c);
+				var pc = peek_char ();
+				if ((pc == '\n' || pc == -1 || pc == UnicodeLS || pc == UnicodePS) && position_stack.Count == 0) 
+					sbag.EndComment (line, col + 1);
+			} while (c != -1 && c != '\n' && c != UnicodeLS && c != UnicodePS);
+		}
+
+		/// <summary>
+		/// Handles #pragma directive
+		/// </summary>
+		void ParsePragmaDirective ()
+		{
+			int c;
+			int startCol, endLine, endCol;
+			int length = TokenizePreprocessorIdentifier (out c, out startCol, out endLine, out endCol);
+			#if FULL_AST
+			var pragmaDirective = sbag.GetPragmaPreProcessorDirective();
+			if (pragmaDirective != null)
+				pragmaDirective.WarningColumn = startCol;
+			#endif
+			if (length == pragma_warning.Length && IsTokenIdentifierEqual (pragma_warning)) {
+				length = TokenizePreprocessorIdentifier (out c, out startCol, out endLine, out endCol);
+				#if FULL_AST
+				if (pragmaDirective != null)
+					pragmaDirective.DisableRestoreColumn = startCol;
+				#endif
+
+				//
+				// #pragma warning disable
+				// #pragma warning restore
+				//
+				if (length == pragma_warning_disable.Length) {
+					bool disable = IsTokenIdentifierEqual (pragma_warning_disable);
+					#if FULL_AST
+					if (pragmaDirective != null)
+						pragmaDirective.Disalbe = disable;
+					#endif
+					if (disable || IsTokenIdentifierEqual (pragma_warning_restore)) {
+						// skip over white space
+						while (c == ' ' || c == '\t')
+							c = get_char ();
+
+						var loc = Location;
+
+						if (c == '\n' || c == '/' || c == UnicodeLS || c == UnicodePS) {
+							if (c == '/')
+								ReadSingleLineComment ();
+
+							//
+							// Disable/Restore all warnings
+							//
+							if (disable) {
+								Report.RegisterWarningRegion (loc).WarningDisable (loc.Row);
+							} else {
+								Report.RegisterWarningRegion (loc).WarningEnable (loc.Row);
+							}
+						} else {
+							//
+							// Disable/Restore a warning or group of warnings
+							//
+							int code;
+							do {
+								var startLoc = loc;
+								#if FULL_AST
+								// int read_start = reader.Position;
+								#endif
+								code = TokenizePragmaNumber (ref c);
+								if (code > 0) {
+									#if FULL_AST
+									var literal = new IntConstant(context.BuiltinTypes, code, startLoc);
+									if (pragmaDirective != null)
+										pragmaDirective.Codes.Add (literal);
+								//	literal.ParsedValue = reader.ReadChars (read_start, reader.Position + 1);
+									#endif
+									if (disable) {
+										Report.RegisterWarningRegion (loc).WarningDisable (loc, code, context.Report);
+									} else {
+										Report.RegisterWarningRegion (loc).WarningEnable (loc, code, context);
+									}
+								}
+							} while (code >= 0 && c != '\n' && c != -1 && c != UnicodeLS && c != UnicodePS);
+						}
+
+						return;
+					}
+				}
+
+				Report.Warning (1634, 1, Location, "Expected disable or restore");
+
+				// Eat any remaining characters on the line
+				ReadToEndOfLine ();
+
+				return;
+			}
+
+
+			//
+			// #pragma checksum
+			//
+			if (length == pragma_checksum.Length && IsTokenIdentifierEqual (pragma_checksum)) {
+				if (c != ' ' || !ParsePragmaChecksum ()) {
+					Report.Warning (1695, 1, Location,
+						"Invalid #pragma checksum syntax. Expected \"filename\" \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\" \"XXXX...\"");
+				}
+
+				return;
+			}
+
+			Report.Warning (1633, 1, Location, "Unrecognized #pragma directive");
+		}
+
+		bool eval_val (string s)
+		{
+			if (s == "true")
+				return true;
+			if (s == "false")
+				return false;
+
+			return source_file.IsConditionalDefined (s);
+		}
+
+		bool pp_primary (ref string s)
+		{
+			s = s.Trim ();
+			int len = s.Length;
+
+			if (len > 0){
+				char c = s [0];
+				
+				if (c == '('){
+					s = s.Substring (1);
+					bool val = pp_expr (ref s, false);
+					if (s.Length > 0 && s [0] == ')'){
+						s = s.Substring (1);
+						return val;
+					}
+					Error_InvalidDirective ();
+					return false;
+				}
+				
+				if (is_identifier_start_character (c)){
+					int j = 1;
+
+					while (j < len){
+						c = s [j];
+						
+						if (is_identifier_part_character (c)){
+							j++;
+							continue;
+						}
+						bool v = eval_val (s.Substring (0, j));
+						s = s.Substring (j);
+						return v;
+					}
+					bool vv = eval_val (s);
+					s = "";
+					return vv;
+				}
+			}
+			Error_InvalidDirective ();
+			return false;
+		}
+		
+		bool pp_unary (ref string s)
+		{
+			s = s.Trim ();
+			int len = s.Length;
+
+			if (len > 0){
+				if (s [0] == '!'){
+					if (len > 1 && s [1] == '='){
+						Error_InvalidDirective ();
+						return false;
+					}
+					s = s.Substring (1);
+					return ! pp_primary (ref s);
+				} else
+					return pp_primary (ref s);
+			} else {
+				Error_InvalidDirective ();
+				return false;
+			}
+		}
+		
+		bool pp_eq (ref string s)
+		{
+			bool va = pp_unary (ref s);
+
+			s = s.Trim ();
+			int len = s.Length;
+			if (len > 0){
+				if (s [0] == '='){
+					if (len > 2 && s [1] == '='){
+						s = s.Substring (2);
+						return va == pp_unary (ref s);
+					} else {
+						Error_InvalidDirective ();
+						return false;
+					}
+				} else if (s [0] == '!' && len > 1 && s [1] == '='){
+					s = s.Substring (2);
+
+					return va != pp_unary (ref s);
+
+				} 
+			}
+
+			return va;
+				
+		}
+		
+		bool pp_and (ref string s)
+		{
+			bool va = pp_eq (ref s);
+
+			s = s.Trim ();
+			int len = s.Length;
+			if (len > 0){
+				if (s [0] == '&'){
+					if (len > 2 && s [1] == '&'){
+						s = s.Substring (2);
+						return (va & pp_and (ref s));
+					} else {
+						Error_InvalidDirective ();
+						return false;
+					}
+				} 
+			}
+			return va;
+		}
+		
+		//
+		// Evaluates an expression for `#if' or `#elif'
+		//
+		bool pp_expr (ref string s, bool isTerm)
+		{
+			bool va = pp_and (ref s);
+			s = s.Trim ();
+			int len = s.Length;
+			if (len > 0){
+				char c = s [0];
+				
+				if (c == '|'){
+					if (len > 2 && s [1] == '|'){
+						s = s.Substring (2);
+						return va | pp_expr (ref s, isTerm);
+					} else {
+						Error_InvalidDirective ();
+						return false;
+					}
+				}
+				if (isTerm) {
+					Error_EndLineExpected ();
+					return false;
+				}
+			}
+			
+			return va;
+		}
+
+		bool eval (string s)
+		{
+			bool v = pp_expr (ref s, true);
+			s = s.Trim ();
+			if (s.Length != 0){
+				return false;
+			}
+
+			return v;
+		}
+
+		void Error_NumericConstantTooLong ()
+		{
+			Report.Error (1021, Location, "Integral constant is too large");			
+		}
+		
+		void Error_InvalidDirective ()
+		{
+			Report.Error (1517, Location, "Invalid preprocessor directive");
+		}
+
+		void Error_UnexpectedDirective (string extra)
+		{
+			Report.Error (
+				1028, Location,
+				"Unexpected processor directive ({0})", extra);
+		}
+
+		void Error_TokensSeen ()
+		{
+			Report.Error (1032, Location,
+				"Cannot define or undefine preprocessor symbols after first token in file");
+		}
+
+		void Eror_WrongPreprocessorLocation ()
+		{
+			Report.Error (1040, Location,
+				"Preprocessor directives must appear as the first non-whitespace character on a line");
+		}
+
+		void Error_EndLineExpected ()
+		{
+			Report.Error (1025, Location, "Single-line comment or end-of-line expected");
+		}
+
+		//
+		// Raises a warning when tokenizer found documentation comment
+		// on unexpected place
+		//
+		void WarningMisplacedComment (Location loc)
+		{
+			if (doc_state != XmlCommentState.Error) {
+				doc_state = XmlCommentState.Error;
+				Report.Warning (1587, 2, loc, "XML comment is not placed on a valid language element");
+			}
+		}
+		
+		//
+		// if true, then the code continues processing the code
+		// if false, the code stays in a loop until another directive is
+		// reached.
+		// When caller_is_taking is false we ignore all directives except the ones
+		// which can help us to identify where the #if block ends
+		bool ParsePreprocessingDirective (bool caller_is_taking)
+		{
+			string arg;
+			bool region_directive = false;
+
+			var directive = get_cmd_arg (out arg);
+
+			//
+			// The first group of pre-processing instructions is always processed
+			//
+			switch (directive) {
+			case PreprocessorDirective.Region:
+				region_directive = true;
+				arg = "true";
+				goto case PreprocessorDirective.If;
+
+			case PreprocessorDirective.Endregion:
+				if (ifstack == null || ifstack.Count == 0){
+					Error_UnexpectedDirective ("no #region for this #endregion");
+					return true;
+				}
+				int pop = ifstack.Pop ();
+					
+				if ((pop & REGION) == 0)
+					Report.Error (1027, Location, "Expected `#endif' directive");
+					
+				return caller_is_taking;
+				
+			case PreprocessorDirective.If:
+				if (ifstack == null)
+					ifstack = new Stack<int> (2);
+
+				int flags = region_directive ? REGION : 0;
+				if (ifstack.Count == 0){
+					flags |= PARENT_TAKING;
+				} else {
+					int state = ifstack.Peek ();
+					if ((state & TAKING) != 0) {
+						flags |= PARENT_TAKING;
+					}
+				}
+
+				if (eval (arg) && caller_is_taking) {
+					ifstack.Push (flags | TAKING);
+					return true;
+				}
+				sbag.SkipIf ();
+				ifstack.Push (flags);
+				return false;
+
+			case PreprocessorDirective.Endif:
+				if (ifstack == null || ifstack.Count == 0){
+					Error_UnexpectedDirective ("no #if for this #endif");
+					return true;
+				} else {
+					pop = ifstack.Pop ();
+					
+					if ((pop & REGION) != 0)
+						Report.Error (1038, Location, "#endregion directive expected");
+					
+					if (arg.Length != 0) {
+						Error_EndLineExpected ();
+					}
+					
+					if (ifstack.Count == 0)
+						return true;
+
+					int state = ifstack.Peek ();
+					return (state & TAKING) != 0;
+				}
+
+			case PreprocessorDirective.Elif:
+				if (ifstack == null || ifstack.Count == 0){
+					Error_UnexpectedDirective ("no #if for this #elif");
+					return true;
+				} else {
+					int state = ifstack.Pop ();
+
+					if ((state & REGION) != 0) {
+						Report.Error (1038, Location, "#endregion directive expected");
+						return true;
+					}
+
+					if ((state & ELSE_SEEN) != 0){
+						Error_UnexpectedDirective ("#elif not valid after #else");
+						return true;
+					}
+
+					if ((state & TAKING) != 0) {
+						sbag.SkipIf ();
+						ifstack.Push (0);
+						return false;
+					}
+
+					if (eval (arg) && ((state & PARENT_TAKING) != 0)){
+						ifstack.Push (state | TAKING);
+						return true;
+					}
+
+					sbag.SkipIf ();
+					ifstack.Push (state);
+					return false;
+				}
+
+			case PreprocessorDirective.Else:
+				if (ifstack == null || ifstack.Count == 0){
+					Error_UnexpectedDirective ("no #if for this #else");
+					return true;
+				} else {
+					int state = ifstack.Peek ();
+
+					if ((state & REGION) != 0) {
+						Report.Error (1038, Location, "#endregion directive expected");
+						return true;
+					}
+
+					if ((state & ELSE_SEEN) != 0){
+						Error_UnexpectedDirective ("#else within #else");
+						return true;
+					}
+
+					ifstack.Pop ();
+
+					if (arg.Length != 0) {
+						Error_EndLineExpected ();
+						return true;
+					}
+
+					bool ret = false;
+					if ((state & PARENT_TAKING) != 0) {
+						ret = (state & TAKING) == 0;
+					
+						if (ret)
+							state |= TAKING;
+						else
+							state &= ~TAKING;
+					}
+	
+					ifstack.Push (state | ELSE_SEEN);
+					
+					return ret;
+				}
+			case PreprocessorDirective.Define:
+				if (any_token_seen){
+					if (caller_is_taking)
+						Error_TokensSeen ();
+					return caller_is_taking;
+				}
+				PreProcessDefinition (true, arg, caller_is_taking);
+				return caller_is_taking;
+
+			case PreprocessorDirective.Undef:
+				if (any_token_seen){
+					if (caller_is_taking)
+						Error_TokensSeen ();
+					return caller_is_taking;
+				}
+				PreProcessDefinition (false, arg, caller_is_taking);
+				return caller_is_taking;
+
+			case PreprocessorDirective.Invalid:
+				Report.Error (1024, Location, "Wrong preprocessor directive");
+				return true;
+			}
+
+			//
+			// These are only processed if we are in a `taking' block
+			//
+			if (!caller_is_taking)
+				return false;
+					
+			switch (directive){
+			case PreprocessorDirective.Error:
+				Report.Error (1029, Location, "#error: '{0}'", arg);
+				return true;
+
+			case PreprocessorDirective.Warning:
+				Report.Warning (1030, 1, Location, "#warning: `{0}'", arg);
+				return true;
+
+			case PreprocessorDirective.Pragma:
+				if (context.Settings.Version == LanguageVersion.ISO_1) {
+					Report.FeatureIsNotAvailable (context, Location, "#pragma");
+				}
+
+				ParsePragmaDirective ();
+				return true;
+
+			case PreprocessorDirective.Line:
+				Location loc = Location;
+				if (!PreProcessLine ())
+					Report.Error (1576, loc, "The line number specified for #line directive is missing or invalid");
+
+				return caller_is_taking;
+			}
+
+			throw new NotImplementedException (directive.ToString ());
+		}
+
+		private int consume_string (bool quoted)
+		{
+			int c;
+			int pos = 0;
+			Location start_location = Location;
+			if (quoted) {
+				start_location = start_location - 1;
+				recordNewLine = false;
+			}
+
+#if FULL_AST
+			int reader_pos = reader.Position;
+#endif
+
+			while (true){
+				// Cannot use get_char because of \r in quoted strings
+				if (putback_char != -1) {
+					c = putback_char;
+					putback_char = -1;
+				} else {
+					c = reader.Read ();
+				}
+
+				if (c == '"') {
+					++col;
+
+					if (quoted && peek_char () == '"') {
+						if (pos == value_builder.Length)
+							Array.Resize (ref value_builder, pos * 2);
+
+						value_builder[pos++] = (char) c;
+						get_char ();
+						continue;
+					}
+
+					string s;
+					if (pos == 0)
+						s = string.Empty;
+					else if (pos <= 4)
+						s = InternIdentifier (value_builder, pos);
+					else
+						s = new string (value_builder, 0, pos);
+
+					ILiteralConstant res = new StringLiteral (context.BuiltinTypes, s, start_location);
+					val = res;
+#if FULL_AST
+					res.ParsedValue = quoted ?
+						reader.ReadChars (reader_pos - 2, reader.Position - 1) :
+						reader.ReadChars (reader_pos - 1, reader.Position);
+#endif
+					recordNewLine = true;
+					return Token.LITERAL;
+				}
+
+				if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
+					if (!quoted) {
+						Report.Error (1010, Location, "Newline in constant");
+
+
+						// Don't add \r to string literal
+						if (pos > 1 && value_builder [pos - 1] == '\r') {
+							advance_line (SpecialsBag.NewLine.Windows);
+							--pos;
+						} else {
+							advance_line (SpecialsBag.NewLine.Unix);
+						}
+
+						val = new StringLiteral (context.BuiltinTypes, new string (value_builder, 0, pos), start_location);
+						recordNewLine = true;
+						return Token.LITERAL;
+					}
+
+					advance_line (SpecialsBag.NewLine.Unix);
+				} else if (c == '\\' && !quoted) {
+					++col;
+					int surrogate;
+					c = escape (c, out surrogate);
+					if (c == -1) {
+						recordNewLine = true;
+						return Token.ERROR;
+					}
+					if (surrogate != 0) {
+						if (pos == value_builder.Length)
+							Array.Resize (ref value_builder, pos * 2);
+
+						value_builder[pos++] = (char) c;
+						c = surrogate;
+					}
+				} else if (c == -1) {
+					Report.Error (1039, Location, "Unterminated string literal");
+					recordNewLine = true;
+					return Token.EOF;
+				} else {
+					++col;
+				}
+
+				if (pos == value_builder.Length)
+					Array.Resize (ref value_builder, pos * 2);
+
+				value_builder[pos++] = (char) c;
+			}
+			recordNewLine = true;
+		}
+
+		private int consume_identifier (int s)
+		{
+			int res = consume_identifier (s, false);
+
+			if (doc_state == XmlCommentState.Allowed)
+				doc_state = XmlCommentState.NotAllowed;
+			startsLine = false;
+			return res;
+		}
+
+		int consume_identifier (int c, bool quoted) 
+		{
+			//
+			// This method is very performance sensitive. It accounts
+			// for approximately 25% of all parser time
+			//
+
+			int pos = 0;
+			int column = col;
+			if (quoted)
+				--column;
+
+			if (c == '\\') {
+				int surrogate;
+				c = escape (c, out surrogate);
+				if (surrogate != 0) {
+					id_builder [pos++] = (char) c;
+					c = surrogate;
+				}
+			}
+
+			id_builder [pos++] = (char) c;
+
+			try {
+				while (true) {
+					c = reader.Read ();
+
+					if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9')) {
+						id_builder [pos++] = (char) c;
+						continue;
+					}
+
+					if (c < 0x80) {
+						if (c == '\\') {
+							int surrogate;
+							c = escape (c, out surrogate);
+							if (is_identifier_part_character ((char) c))
+								id_builder[pos++] = (char) c;
+
+							if (surrogate != 0) {
+								c = surrogate;
+							}
+
+							continue;
+						}
+					} else if (is_identifier_part_character_slow_part ((char) c)) {
+						id_builder [pos++] = (char) c;
+						continue;
+					}
+
+					putback_char = c;
+					break;
+				}
+			} catch (IndexOutOfRangeException) {
+				Report.Error (645, Location, "Identifier too long (limit is 512 chars)");
+				--pos;
+				col += pos;
+			}
+
+			col += pos - 1;
+
+			//
+			// Optimization: avoids doing the keyword lookup
+			// on uppercase letters
+			//
+			if (id_builder [0] >= '_' && !quoted) {
+				int keyword = GetKeyword (id_builder, pos);
+				if (keyword != -1) {
+					val = ltb.Create (keyword == Token.AWAIT ? "await" : null, current_source, ref_line, column);
+					return keyword;
+				}
+			}
+
+			string s = InternIdentifier (id_builder, pos);
+#if FULL_AST
+			if (quoted) {
+				val = ltb.Create ("@" + s, current_source, ref_line, column - 1);
+			} else {
+				val = ltb.Create (s, current_source, ref_line, column);
+			}
+#else
+			val = ltb.Create (s, current_source, ref_line, column);
+#endif
+			if (quoted && parsing_attribute_section)
+				AddEscapedIdentifier (((LocatedToken) val).Location);
+
+			return Token.IDENTIFIER;
+		}
+
+		string InternIdentifier (char[] charBuffer, int length)
+		{
+			//
+			// Keep identifiers in an array of hashtables to avoid needless
+			// allocations
+			//
+			var identifiers_group = identifiers [length];
+			string s;
+			if (identifiers_group != null) {
+				if (identifiers_group.TryGetValue (charBuffer, out s)) {
+					return s;
+				}
+			} else {
+				// TODO: this should be number of files dependant
+				// corlib compilation peaks at 1000 and System.Core at 150
+				int capacity = length > 20 ? 10 : 100;
+				identifiers_group = new Dictionary<char[], string> (capacity, new IdentifiersComparer (length));
+				identifiers [length] = identifiers_group;
+			}
+
+			char[] chars = new char[length];
+			Array.Copy (charBuffer, chars, length);
+
+			s = new string (charBuffer, 0, length);
+			identifiers_group.Add (chars, s);
+
+			return s;
+		}
+		
+		public int xtoken ()
+		{
+			int d, c;
+
+			// Whether we have seen comments on the current line
+			bool comments_seen = false;
+			while ((c = get_char ()) != -1) {
+				switch (c) {
+				case '\t':
+					col = ((col - 1 + tab_size) / tab_size) * tab_size;
+					continue;
+
+				case ' ':
+				case '\f':
+				case '\v':
+				case 0xa0:
+				case 0:
+				case 0xFEFF:	// Ignore BOM anywhere in the file
+					continue;
+
+/*				This is required for compatibility with .NET
+				case 0xEF:
+					if (peek_char () == 0xBB) {
+						PushPosition ();
+						get_char ();
+						if (get_char () == 0xBF)
+							continue;
+						PopPosition ();
+					}
+					break;
+*/
+				case '\\':
+					tokens_seen = true;
+					return consume_identifier (c);
+
+				case '{':
+					val = ltb.Create (current_source, ref_line, col);
+					return Token.OPEN_BRACE;
+				case '}':
+					val = ltb.Create (current_source, ref_line, col);
+					return Token.CLOSE_BRACE;
+				case '[':
+					// To block doccomment inside attribute declaration.
+					if (doc_state == XmlCommentState.Allowed)
+						doc_state = XmlCommentState.NotAllowed;
+
+					val = ltb.Create (current_source, ref_line, col);
+
+					if (parsing_block == 0 || lambda_arguments_parsing)
+						return Token.OPEN_BRACKET;
+
+					int next = peek_char ();
+					switch (next) {
+					case ']':
+					case ',':
+						return Token.OPEN_BRACKET;
+
+					case ' ':
+					case '\f':
+					case '\v':
+					case '\r':
+					case '\n':
+					case UnicodeLS:
+					case UnicodePS:
+					case '/':
+						next = peek_token ();
+						if (next == Token.COMMA || next == Token.CLOSE_BRACKET)
+							return Token.OPEN_BRACKET;
+
+						return Token.OPEN_BRACKET_EXPR;
+					default:
+						return Token.OPEN_BRACKET_EXPR;
+					}
+				case ']':
+					ltb.CreateOptional (current_source, ref_line, col, ref val);
+					return Token.CLOSE_BRACKET;
+				case '(':
+					val = ltb.Create (current_source, ref_line, col);
+					//
+					// An expression versions of parens can appear in block context only
+					//
+					if (parsing_block != 0 && !lambda_arguments_parsing) {
+						
+						//
+						// Optmize most common case where we know that parens
+						// is not special
+						//
+						switch (current_token) {
+						case Token.IDENTIFIER:
+						case Token.IF:
+						case Token.FOR:
+						case Token.FOREACH:
+						case Token.TYPEOF:
+						case Token.WHILE:
+						case Token.SWITCH:
+						case Token.USING:
+						case Token.DEFAULT:
+						case Token.DELEGATE:
+						case Token.OP_GENERICS_GT:
+							return Token.OPEN_PARENS;
+						}
+
+						// Optimize using peek
+						int xx = peek_char ();
+						switch (xx) {
+						case '(':
+						case '\'':
+						case '"':
+						case '0':
+						case '1':
+							return Token.OPEN_PARENS;
+						}
+
+						lambda_arguments_parsing = true;
+						PushPosition ();
+						d = TokenizeOpenParens ();
+						PopPosition ();
+						lambda_arguments_parsing = false;
+						return d;
+					}
+
+					return Token.OPEN_PARENS;
+				case ')':
+					ltb.CreateOptional (current_source, ref_line, col, ref val);
+					return Token.CLOSE_PARENS;
+				case ',':
+					ltb.CreateOptional (current_source, ref_line, col, ref val);
+					return Token.COMMA;
+				case ';':
+					ltb.CreateOptional (current_source, ref_line, col, ref val);
+					return Token.SEMICOLON;
+				case '~':
+					val = ltb.Create (current_source, ref_line, col);
+					return Token.TILDE;
+				case '?':
+					val = ltb.Create (current_source, ref_line, col);
+					return TokenizePossibleNullableType ();
+				case '<':
+					val = ltb.Create (current_source, ref_line, col);
+					if (parsing_generic_less_than++ > 0)
+						return Token.OP_GENERICS_LT;
+
+					return TokenizeLessThan ();
+
+				case '>':
+					val = ltb.Create (current_source, ref_line, col);
+					d = peek_char ();
+
+					if (d == '=') {
+						get_char ();
+						return Token.OP_GE;
+					}
+
+					if (parsing_generic_less_than > 1 || (parsing_generic_less_than == 1 && d != '>')) {
+						parsing_generic_less_than--;
+						return Token.OP_GENERICS_GT;
+					}
+
+					if (d == '>') {
+						get_char ();
+						d = peek_char ();
+
+						if (d == '=') {
+							get_char ();
+							return Token.OP_SHIFT_RIGHT_ASSIGN;
+						}
+						return Token.OP_SHIFT_RIGHT;
+					}
+
+					return Token.OP_GT;
+
+				case '+':
+					val = ltb.Create (current_source, ref_line, col);
+					d = peek_char ();
+					if (d == '+') {
+						d = Token.OP_INC;
+					} else if (d == '=') {
+						d = Token.OP_ADD_ASSIGN;
+					} else {
+						return Token.PLUS;
+					}
+					get_char ();
+					return d;
+
+				case '-':
+					val = ltb.Create (current_source, ref_line, col);
+					d = peek_char ();
+					if (d == '-') {
+						d = Token.OP_DEC;
+					} else if (d == '=')
+						d = Token.OP_SUB_ASSIGN;
+					else if (d == '>')
+						d = Token.OP_PTR;
+					else {
+						return Token.MINUS;
+					}
+					get_char ();
+					return d;
+
+				case '!':
+					val = ltb.Create (current_source, ref_line, col);
+					if (peek_char () == '='){
+						get_char ();
+						return Token.OP_NE;
+					}
+					return Token.BANG;
+
+				case '=':
+					val = ltb.Create (current_source, ref_line, col);
+					d = peek_char ();
+					if (d == '=') {
+						get_char ();
+						return Token.OP_EQ;
+					}
+					if (d == '>') {
+						get_char ();
+						return Token.ARROW;
+					}
+
+					return Token.ASSIGN;
+
+				case '&':
+					val = ltb.Create (current_source, ref_line, col);
+					d = peek_char ();
+					if (d == '&') {
+						get_char ();
+						return Token.OP_AND;
+					}
+					if (d == '=') {
+						get_char ();
+						return Token.OP_AND_ASSIGN;
+					}
+					return Token.BITWISE_AND;
+
+				case '|':
+					val = ltb.Create (current_source, ref_line, col);
+					d = peek_char ();
+					if (d == '|') {
+						get_char ();
+						return Token.OP_OR;
+					}
+					if (d == '=') {
+						get_char ();
+						return Token.OP_OR_ASSIGN;
+					}
+					return Token.BITWISE_OR;
+
+				case '*':
+					val = ltb.Create (current_source, ref_line, col);
+					if (peek_char () == '='){
+						get_char ();
+						return Token.OP_MULT_ASSIGN;
+					}
+					return Token.STAR;
+
+				case '/':
+					d = peek_char ();
+					if (d == '='){
+						val = ltb.Create (current_source, ref_line, col);
+						get_char ();
+						return Token.OP_DIV_ASSIGN;
+					}
+					// Handle double-slash comments.
+					if (d == '/') {
+						get_char ();
+						if (doc_processing) {
+							if (peek_char () == '/') {
+								get_char ();
+								// Don't allow ////.
+								if ((d = peek_char ()) != '/') {
+									if (position_stack.Count == 0)
+										sbag.PushCommentChar (d);
+									if (doc_state == XmlCommentState.Allowed)
+										handle_one_line_xml_comment ();
+									else if (doc_state == XmlCommentState.NotAllowed)
+										WarningMisplacedComment (Location - 3);
+								}
+							} else {
+								if (xml_comment_buffer.Length > 0)
+									doc_state = XmlCommentState.NotAllowed;
+							}
+						} else {
+							bool isDoc = peek_char () == '/';
+							if (position_stack.Count == 0)
+								sbag.StartComment (isDoc ? SpecialsBag.CommentType.Documentation : SpecialsBag.CommentType.Single, startsLine, line, col - 1);
+							if (isDoc)
+								get_char ();
+						}
+						
+						d = peek_char ();
+						int endLine = line, endCol = col;
+						while ((d = get_char ()) != -1 && (d != '\n') && d != '\r' && d != UnicodePS && d != UnicodeLS) {
+							if (position_stack.Count == 0)
+								sbag.PushCommentChar (d);
+							endLine = line;
+							endCol = col;
+						}
+						if (position_stack.Count == 0)
+							sbag.EndComment (endLine, endCol + 1);
+						any_token_seen |= tokens_seen;
+						tokens_seen = false;
+						comments_seen = false;
+						continue;
+					} else if (d == '*'){
+						if (position_stack.Count == 0) {
+							sbag.StartComment (SpecialsBag.CommentType.Multi, startsLine, line, col);
+							recordNewLine = false;
+						}
+						get_char ();
+						bool docAppend = false;
+						if (doc_processing && peek_char () == '*') {
+							int ch = get_char ();
+							// But when it is /**/, just do nothing.
+							if (peek_char () == '/') {
+								ch = get_char ();
+								if (position_stack.Count == 0) {
+									recordNewLine = true;
+									sbag.EndComment (line, col + 1);
+								}
+								continue;
+							} else {
+								if (position_stack.Count == 0)
+									sbag.PushCommentChar (ch);
+							}
+							if (doc_state == XmlCommentState.Allowed)
+								docAppend = true;
+							else if (doc_state == XmlCommentState.NotAllowed) {
+								WarningMisplacedComment (Location - 2);
+							}
+						}
+
+						int current_comment_start = 0;
+						if (docAppend) {
+							current_comment_start = xml_comment_buffer.Length;
+							xml_comment_buffer.Append (Environment.NewLine);
+						}
+
+						while ((d = get_char ()) != -1){
+							if (d == '*' && peek_char () == '/'){
+								get_char ();
+								if (position_stack.Count == 0) {
+									recordNewLine = true;
+									sbag.EndComment (line, col + 1);
+								}
+								comments_seen = true;
+								break;
+							} else {
+								if (position_stack.Count == 0)
+									sbag.PushCommentChar (d);
+							}
+							if (docAppend)
+								xml_comment_buffer.Append ((char) d);
+							
+							if (d == '\n' || d == UnicodeLS || d == UnicodePS){
+								any_token_seen |= tokens_seen;
+								tokens_seen = false;
+								// 
+								// Reset 'comments_seen' just to be consistent.
+								// It doesn't matter either way, here.
+								//
+								comments_seen = false;
+							}
+						}
+						
+						if (!comments_seen)
+							Report.Error (1035, Location, "End-of-file found, '*/' expected");
+
+						if (docAppend)
+							update_formatted_doc_comment (current_comment_start);
+						continue;
+					}
+					val = ltb.Create (current_source, ref_line, col);
+					return Token.DIV;
+
+				case '%':
+					val = ltb.Create (current_source, ref_line, col);
+					if (peek_char () == '='){
+						get_char ();
+						return Token.OP_MOD_ASSIGN;
+					}
+					return Token.PERCENT;
+
+				case '^':
+					val = ltb.Create (current_source, ref_line, col);
+					if (peek_char () == '='){
+						get_char ();
+						return Token.OP_XOR_ASSIGN;
+					}
+					return Token.CARRET;
+
+				case ':':
+					val = ltb.Create (current_source, ref_line, col);
+					if (peek_char () == ':') {
+						get_char ();
+						return Token.DOUBLE_COLON;
+					}
+					return Token.COLON;
+
+				case '0': case '1': case '2': case '3': case '4':
+				case '5': case '6': case '7': case '8': case '9':
+					tokens_seen = true;
+					return is_number (c, false);
+
+				case '\n': // white space
+				case UnicodeLS:
+				case UnicodePS:
+					any_token_seen |= tokens_seen;
+					tokens_seen = false;
+					comments_seen = false;
+					continue;
+
+				case '.':
+					tokens_seen = true;
+					d = peek_char ();
+					if (d >= '0' && d <= '9')
+						return is_number (c, true);
+
+					ltb.CreateOptional (current_source, ref_line, col, ref val);
+					return Token.DOT;
+				
+				case '#':
+					if (tokens_seen || comments_seen) {
+						Eror_WrongPreprocessorLocation();
+						return Token.ERROR;
+					}
+				
+					if (ParsePreprocessingDirective(true))
+						continue;
+					sbag.StartComment(SpecialsBag.CommentType.InactiveCode, false, line, 1);
+					recordNewLine = false;
+					bool directive_expected = false;
+					while ((c = get_char ()) != -1) {
+						if (col == 1) {
+							directive_expected = true;
+						} else if (!directive_expected) {
+							// TODO: Implement comment support for disabled code and uncomment this code
+//							if (c == '#') {
+//								Eror_WrongPreprocessorLocation ();
+//								return Token.ERROR;
+//							}
+							if (c != '#')
+								sbag.PushCommentChar (c);
+							continue;
+						}
+
+						if (c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\v' || c == UnicodeLS || c == UnicodePS) {
+							sbag.PushCommentChar (c);
+							continue;
+						}
+
+						if (c == '#') {
+							var oldNL = recordNewLine;
+							recordNewLine = true;
+							var continueNormalLexing = ParsePreprocessingDirective(false);
+							recordNewLine = oldNL;
+							if (continueNormalLexing)
+								break;
+							sbag.StartComment(SpecialsBag.CommentType.InactiveCode, false, line, 1);
+						}
+						sbag.PushCommentChar (c);
+						directive_expected = false;
+					}
+					recordNewLine = true;
+					sbag.EndComment (line, col);
+					if (c != -1) {
+						tokens_seen = false;
+						continue;
+					}
+
+					return Token.EOF;
+								
+				case '"':
+					return consume_string (false);
+
+				case '\'':
+					return TokenizeBackslash ();
+				
+				case '@':
+					c = get_char ();
+					if (c == '"') {
+						tokens_seen = true;
+						return consume_string (true);
+					}
+
+					if (is_identifier_start_character (c)){
+						return consume_identifier (c, true);
+					}
+
+					Report.Error (1646, Location, "Keyword, identifier, or string expected after verbatim specifier: @");
+					return Token.ERROR;
+
+				case EvalStatementParserCharacter:
+					return Token.EVAL_STATEMENT_PARSER;
+				case EvalCompilationUnitParserCharacter:
+					return Token.EVAL_COMPILATION_UNIT_PARSER;
+				case EvalUsingDeclarationsParserCharacter:
+					return Token.EVAL_USING_DECLARATIONS_UNIT_PARSER;
+				case DocumentationXref:
+					return Token.DOC_SEE;
+				}
+
+				if (is_identifier_start_character (c)) {
+					tokens_seen = true;
+					return consume_identifier (c);
+				}
+
+				if (char.IsWhiteSpace ((char) c))
+					continue;
+
+				Report.Error (1056, Location, "Unexpected character `{0}'", ((char) c).ToString ());
+			}
+
+			if (CompleteOnEOF){
+				if (generated)
+					return Token.COMPLETE_COMPLETION;
+				
+				generated = true;
+				return Token.GENERATE_COMPLETION;
+			}
+			
+
+			return Token.EOF;
+		}
+
+		int TokenizeBackslash ()
+		{
+#if FULL_AST
+			int read_start = reader.Position;
+#endif
+			Location start_location = Location;
+			int c = get_char ();
+			tokens_seen = true;
+			if (c == '\'') {
+				val = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
+				Report.Error (1011, start_location, "Empty character literal");
+				return Token.LITERAL;
+			}
+
+			if (c == '\n' || c == UnicodeLS || c == UnicodePS) {
+				Report.Error (1010, start_location, "Newline in constant");
+				return Token.ERROR;
+			}
+
+			int d;
+			c = escape (c, out d);
+			if (c == -1)
+				return Token.ERROR;
+			if (d != 0)
+				throw new NotImplementedException ();
+
+			ILiteralConstant res = new CharLiteral (context.BuiltinTypes, (char) c, start_location);
+			val = res;
+			c = get_char ();
+
+			if (c != '\'') {
+				Report.Error (1012, start_location, "Too many characters in character literal");
+
+				// Try to recover, read until newline or next "'"
+				while ((c = get_char ()) != -1) {
+					if (c == '\n' || c == '\'' || c == UnicodeLS || c == UnicodePS)
+						break;
+				}
+			}
+
+#if FULL_AST
+			res.ParsedValue = reader.ReadChars (read_start - 1, reader.Position);
+#endif
+
+			return Token.LITERAL;
+		}
+
+		int TokenizeLessThan ()
+		{
+			int d;
+
+			// Save current position and parse next token.
+			PushPosition ();
+			int generic_dimension = 0;
+			if (parse_less_than (ref generic_dimension)) {
+				if (parsing_generic_declaration && (parsing_generic_declaration_doc || token () != Token.DOT)) {
+					d = Token.OP_GENERICS_LT_DECL;
+				} else {
+					if (generic_dimension > 0) {
+						val = generic_dimension;
+						DiscardPosition ();
+						return Token.GENERIC_DIMENSION;
+					}
+
+					d = Token.OP_GENERICS_LT;
+				}
+				PopPosition ();
+				return d;
+			}
+
+			PopPosition ();
+			parsing_generic_less_than = 0;
+
+			d = peek_char ();
+			if (d == '<') {
+				get_char ();
+				d = peek_char ();
+
+				if (d == '=') {
+					get_char ();
+					return Token.OP_SHIFT_LEFT_ASSIGN;
+				}
+				return Token.OP_SHIFT_LEFT;
+			}
+
+			if (d == '=') {
+				get_char ();
+				return Token.OP_LE;
+			}
+			return Token.OP_LT;
+		}
+
+		//
+		// Handles one line xml comment
+		//
+		private void handle_one_line_xml_comment ()
+		{
+			int c;
+			while ((c = peek_char ()) == ' ') {
+				if (position_stack.Count == 0)
+					sbag.PushCommentChar (c);
+				get_char (); // skip heading whitespaces.
+			}
+			while ((c = peek_char ()) != -1 && c != '\n' && c != '\r') {
+				if (position_stack.Count == 0)
+					sbag.PushCommentChar (c);
+				xml_comment_buffer.Append ((char) get_char ());
+			}
+			if (c == '\r' || c == '\n')
+				xml_comment_buffer.Append (Environment.NewLine);
+		}
+
+		//
+		// Remove heading "*" in Javadoc-like xml documentation.
+		//
+		private void update_formatted_doc_comment (int current_comment_start)
+		{
+			int length = xml_comment_buffer.Length - current_comment_start;
+			string [] lines = xml_comment_buffer.ToString (
+				current_comment_start,
+				length).Replace ("\r", "").Split ('\n');
+			
+			// The first line starts with /**, thus it is not target
+			// for the format check.
+			for (int i = 1; i < lines.Length; i++) {
+				string s = lines [i];
+				int idx = s.IndexOf ('*');
+				string head = null;
+				if (idx < 0) {
+					if (i < lines.Length - 1)
+						return;
+					head = s;
+				} else
+					head = s.Substring (0, idx);
+				foreach (char c in head)
+					if (c != ' ')
+						return;
+				lines [i] = s.Substring (idx + 1);
+			}
+			xml_comment_buffer.Remove (current_comment_start, length);
+			xml_comment_buffer.Insert (current_comment_start, String.Join (Environment.NewLine, lines));
+		}
+
+		//
+		// Checks if there was incorrect doc comments and raise
+		// warnings.
+		//
+		public void check_incorrect_doc_comment ()
+		{
+			if (xml_comment_buffer.Length > 0)
+				WarningMisplacedComment (Location);
+		}
+
+		//
+		// Consumes the saved xml comment lines (if any)
+		// as for current target member or type.
+		//
+		public string consume_doc_comment ()
+		{
+			if (xml_comment_buffer.Length > 0) {
+				string ret = xml_comment_buffer.ToString ();
+				reset_doc_comment ();
+				return ret;
+			}
+			return null;
+		}
+
+		void reset_doc_comment ()
+		{
+			xml_comment_buffer.Length = 0;
+		}
+
+		public void cleanup ()
+		{
+			if (ifstack != null && ifstack.Count >= 1) {
+				int state = ifstack.Pop ();
+				if ((state & REGION) != 0)
+					Report.Error (1038, Location, "#endregion directive expected");
+				else 
+					Report.Error (1027, Location, "Expected `#endif' directive");
+			}
+		}
+	}
+
+	//
+	// Indicates whether it accepts XML documentation or not.
+	//
+	public enum XmlCommentState {
+		// comment is allowed in this state.
+		Allowed,
+		// comment is not allowed in this state.
+		NotAllowed,
+		// once comments appeared when it is NotAllowed, then the
+		// state is changed to it, until the state is changed to
+		// .Allowed.
+		Error
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/decl.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/decl.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/decl.cs	(revision 11807)
@@ -0,0 +1,1297 @@
+//
+// decl.cs: Declaration base class for structs, classes, enums and interfaces.
+//
+// Author: Miguel de Icaza (miguel@gnu.org)
+//         Marek Safar (marek.safar@seznam.cz)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+//
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+using Mono.CompilerServices.SymbolWriter;
+
+#if NET_2_1
+using XmlElement = System.Object;
+#else
+using System.Xml;
+#endif
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	//
+	// Better name would be DottenName
+	//
+	[DebuggerDisplay ("{GetSignatureForError()}")]
+	public class MemberName
+	{
+		public static readonly MemberName Null = new MemberName ("");
+
+		public readonly string Name;
+		public TypeParameters TypeParameters;
+		public readonly FullNamedExpression ExplicitInterface;
+		public readonly Location Location;
+
+		public readonly MemberName Left;
+
+		public MemberName (string name)
+			: this (name, Location.Null)
+		{ }
+
+		public MemberName (string name, Location loc)
+			: this (null, name, loc)
+		{ }
+
+		public MemberName (string name, TypeParameters tparams, Location loc)
+		{
+			this.Name = name;
+			this.Location = loc;
+
+			this.TypeParameters = tparams;
+		}
+
+		public MemberName (string name, TypeParameters tparams, FullNamedExpression explicitInterface, Location loc)
+			: this (name, tparams, loc)
+		{
+			this.ExplicitInterface = explicitInterface;
+		}
+
+		public MemberName (MemberName left, string name, Location loc)
+		{
+			this.Name = name;
+			this.Location = loc;
+			this.Left = left;
+		}
+
+		public MemberName (MemberName left, string name, FullNamedExpression explicitInterface, Location loc)
+			: this (left, name, loc)
+		{
+			this.ExplicitInterface = explicitInterface;
+		}
+
+		public MemberName (MemberName left, MemberName right)
+		{
+			this.Name = right.Name;
+			this.Location = right.Location;
+			this.TypeParameters = right.TypeParameters;
+			this.Left = left;
+		}
+
+		public int Arity {
+			get {
+				return TypeParameters == null ? 0 : TypeParameters.Count;
+			}
+		}
+
+		public bool IsGeneric {
+			get {
+				return TypeParameters != null;
+			}
+		}
+
+		public string Basename {
+			get {
+				if (TypeParameters != null)
+					return MakeName (Name, TypeParameters);
+				return Name;
+			}
+		}
+
+		public void CreateMetadataName (StringBuilder sb)
+		{
+			if (Left != null)
+				Left.CreateMetadataName (sb);
+
+			if (sb.Length != 0) {
+				sb.Append (".");
+			}
+
+			sb.Append (Basename);
+		}
+
+		public string GetSignatureForDocumentation ()
+		{
+			var s = Basename;
+
+			if (ExplicitInterface != null)
+				s = ExplicitInterface.GetSignatureForError () + "." + s;
+
+			if (Left == null)
+				return s;
+
+			return Left.GetSignatureForDocumentation () + "." + s;
+		}
+
+		public string GetSignatureForError ()
+		{
+			string s = TypeParameters == null ? null : "<" + TypeParameters.GetSignatureForError () + ">";
+			s = Name + s;
+
+			if (ExplicitInterface != null)
+				s = ExplicitInterface.GetSignatureForError () + "." + s;
+
+			if (Left == null)
+				return s;
+
+			return Left.GetSignatureForError () + "." + s;
+		}
+
+		public override bool Equals (object other)
+		{
+			return Equals (other as MemberName);
+		}
+
+		public bool Equals (MemberName other)
+		{
+			if (this == other)
+				return true;
+			if (other == null || Name != other.Name)
+				return false;
+
+			if ((TypeParameters != null) &&
+			    (other.TypeParameters == null || TypeParameters.Count != other.TypeParameters.Count))
+				return false;
+
+			if ((TypeParameters == null) && (other.TypeParameters != null))
+				return false;
+
+			if (Left == null)
+				return other.Left == null;
+
+			return Left.Equals (other.Left);
+		}
+
+		public override int GetHashCode ()
+		{
+			int hash = Name.GetHashCode ();
+			for (MemberName n = Left; n != null; n = n.Left)
+				hash ^= n.Name.GetHashCode ();
+
+			if (TypeParameters != null)
+				hash ^= TypeParameters.Count << 5;
+
+			return hash & 0x7FFFFFFF;
+		}
+
+		public static string MakeName (string name, TypeParameters args)
+		{
+			if (args == null)
+				return name;
+
+			return name + "`" + args.Count;
+		}
+
+		public static string MakeName (string name, int count)
+		{
+			return name + "`" + count;
+		}
+	}
+
+	public class SimpleMemberName
+	{
+		public string Value;
+		public Location Location;
+
+		public SimpleMemberName (string name, Location loc)
+		{
+			this.Value = name;
+			this.Location = loc;
+		}
+	}
+
+	/// <summary>
+	///   Base representation for members.  This is used to keep track
+	///   of Name, Location and Modifier flags, and handling Attributes.
+	/// </summary>
+	[System.Diagnostics.DebuggerDisplay ("{GetSignatureForError()}")]
+	public abstract class MemberCore : Attributable, IMemberContext, IMemberDefinition
+	{
+		string IMemberDefinition.Name {
+			get {
+				return member_name.Name;
+			}
+		}
+
+                // Is not readonly because of IndexerName attribute
+		private MemberName member_name;
+		public MemberName MemberName {
+			get { return member_name; }
+		}
+
+		/// <summary>
+		///   Modifier flags that the user specified in the source code
+		/// </summary>
+		private Modifiers mod_flags;
+		public Modifiers ModFlags {
+			set {
+				mod_flags = value;
+				if ((value & Modifiers.COMPILER_GENERATED) != 0)
+					caching_flags = Flags.IsUsed | Flags.IsAssigned;
+			}
+			get {
+				return mod_flags;
+			}
+		}
+
+		public virtual ModuleContainer Module {
+			get {
+				return Parent.Module;
+			}
+		}
+
+		public /*readonly*/ TypeContainer Parent;
+
+		/// <summary>
+		///   Location where this declaration happens
+		/// </summary>
+		public Location Location {
+			get { return member_name.Location; }
+		}
+
+		/// <summary>
+		///   XML documentation comment
+		/// </summary>
+		protected string comment;
+
+		/// <summary>
+		///   Represents header string for documentation comment 
+		///   for each member types.
+		/// </summary>
+		public abstract string DocCommentHeader { get; }
+
+		[Flags]
+		public enum Flags {
+			Obsolete_Undetected = 1,		// Obsolete attribute has not been detected yet
+			Obsolete = 1 << 1,			// Type has obsolete attribute
+			ClsCompliance_Undetected = 1 << 2,	// CLS Compliance has not been detected yet
+			ClsCompliant = 1 << 3,			// Type is CLS Compliant
+			CloseTypeCreated = 1 << 4,		// Tracks whether we have Closed the type
+			HasCompliantAttribute_Undetected = 1 << 5,	// Presence of CLSCompliantAttribute has not been detected
+			HasClsCompliantAttribute = 1 << 6,			// Type has CLSCompliantAttribute
+			ClsCompliantAttributeFalse = 1 << 7,			// Member has CLSCompliant(false)
+			Excluded_Undetected = 1 << 8,		// Conditional attribute has not been detected yet
+			Excluded = 1 << 9,					// Method is conditional
+			MethodOverloadsExist = 1 << 10,		// Test for duplication must be performed
+			IsUsed = 1 << 11,
+			IsAssigned = 1 << 12,				// Field is assigned
+			HasExplicitLayout	= 1 << 13,
+			PartialDefinitionExists	= 1 << 14,	// Set when corresponding partial method definition exists
+			HasStructLayout	= 1 << 15,			// Has StructLayoutAttribute
+			HasInstanceConstructor = 1 << 16,
+			HasUserOperators = 1 << 17,
+			CanBeReused = 1 << 18,
+			InterfacesExpanded = 1 << 19
+		}
+
+		/// <summary>
+		///   MemberCore flags at first detected then cached
+		/// </summary>
+		internal Flags caching_flags;
+
+		protected MemberCore (TypeContainer parent, MemberName name, Attributes attrs)
+		{
+			this.Parent = parent;
+			member_name = name;
+			caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
+			AddAttributes (attrs, this);
+		}
+
+		protected virtual void SetMemberName (MemberName new_name)
+		{
+			member_name = new_name;
+		}
+
+		public virtual void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		protected bool CheckAbstractAndExtern (bool has_block)
+		{
+			if (Parent.PartialContainer.Kind == MemberKind.Interface)
+				return true;
+
+			if (has_block) {
+				if ((ModFlags & Modifiers.EXTERN) != 0) {
+					Report.Error (179, Location, "`{0}' cannot declare a body because it is marked extern",
+						GetSignatureForError ());
+					return false;
+				}
+
+				if ((ModFlags & Modifiers.ABSTRACT) != 0) {
+					Report.Error (500, Location, "`{0}' cannot declare a body because it is marked abstract",
+						GetSignatureForError ());
+					return false;
+				}
+			} else {
+				if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN | Modifiers.PARTIAL)) == 0 && !(Parent is Delegate)) {
+					if (Compiler.Settings.Version >= LanguageVersion.V_3) {
+						Property.PropertyMethod pm = this as Property.PropertyMethod;
+						if (pm is Indexer.GetIndexerMethod || pm is Indexer.SetIndexerMethod)
+							pm = null;
+
+						if (pm != null && pm.Property.AccessorSecond == null) {
+							Report.Error (840, Location,
+								"`{0}' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors",
+								GetSignatureForError ());
+							return false;
+						}
+					}
+
+					Report.Error (501, Location, "`{0}' must have a body because it is not marked abstract, extern, or partial",
+					              GetSignatureForError ());
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		protected void CheckProtectedModifier ()
+		{
+			if ((ModFlags & Modifiers.PROTECTED) == 0)
+				return;
+
+			if (Parent.PartialContainer.Kind == MemberKind.Struct) {
+				Report.Error (666, Location, "`{0}': Structs cannot contain protected members",
+					GetSignatureForError ());
+				return;
+			}
+
+			if ((Parent.ModFlags & Modifiers.STATIC) != 0) {
+				Report.Error (1057, Location, "`{0}': Static classes cannot contain protected members",
+					GetSignatureForError ());
+				return;
+			}
+
+			if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & Modifiers.OVERRIDE) == 0 &&
+				!(this is Destructor)) {
+				Report.Warning (628, 4, Location, "`{0}': new protected member declared in sealed class",
+					GetSignatureForError ());
+				return;
+			}
+		}
+
+		public abstract bool Define ();
+
+		public virtual string DocComment {
+			get {
+				return comment;
+			}
+			set {
+				comment = value;
+			}
+		}
+
+		// 
+		// Returns full member name for error message
+		//
+		public virtual string GetSignatureForError ()
+		{
+			var parent = Parent.GetSignatureForError ();
+			if (parent == null)
+				return member_name.GetSignatureForError ();
+
+			return parent + "." + member_name.GetSignatureForError ();
+		}
+
+		/// <summary>
+		/// Base Emit method. This is also entry point for CLS-Compliant verification.
+		/// </summary>
+		public virtual void Emit ()
+		{
+			if (!Compiler.Settings.VerifyClsCompliance)
+				return;
+
+			VerifyClsCompliance ();
+		}
+
+		public bool IsAvailableForReuse {
+			get {
+				return (caching_flags & Flags.CanBeReused) != 0;
+			}
+			set {
+				caching_flags = value ? (caching_flags | Flags.CanBeReused) : (caching_flags & ~Flags.CanBeReused);
+			}
+		}
+
+		public bool IsCompilerGenerated {
+			get	{
+				if ((mod_flags & Modifiers.COMPILER_GENERATED) != 0)
+					return true;
+
+				return Parent != null && Parent.IsCompilerGenerated;
+			}
+		}
+
+		public bool IsImported {
+			get {
+				return false;
+			}
+		}
+
+		public virtual bool IsUsed {
+			get {
+				return (caching_flags & Flags.IsUsed) != 0;
+			}
+		}
+
+		protected Report Report {
+			get {
+				return Compiler.Report;
+			}
+		}
+
+		public void SetIsUsed ()
+		{
+			caching_flags |= Flags.IsUsed;
+		}
+
+		public void SetIsAssigned ()
+		{
+			caching_flags |= Flags.IsAssigned;
+		}
+
+		public virtual void SetConstraints (List<Constraints> constraints_list)
+		{
+			var tparams = member_name.TypeParameters;
+			if (tparams == null) {
+				Report.Error (80, Location, "Constraints are not allowed on non-generic declarations");
+				return;
+			}
+
+			foreach (var c in constraints_list) {
+				var tp = tparams.Find (c.TypeParameter.Value);
+				if (tp == null) {
+					Report.Error (699, c.Location, "`{0}': A constraint references nonexistent type parameter `{1}'",
+						GetSignatureForError (), c.TypeParameter.Value);
+					continue;
+				}
+
+				tp.Constraints = c;
+			}
+		}
+
+		/// <summary>
+		/// Returns instance of ObsoleteAttribute for this MemberCore
+		/// </summary>
+		public virtual ObsoleteAttribute GetAttributeObsolete ()
+		{
+			if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
+				return null;
+
+			caching_flags &= ~Flags.Obsolete_Undetected;
+
+			if (OptAttributes == null)
+				return null;
+
+			Attribute obsolete_attr = OptAttributes.Search (Module.PredefinedAttributes.Obsolete);
+			if (obsolete_attr == null)
+				return null;
+
+			caching_flags |= Flags.Obsolete;
+
+			ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
+			if (obsolete == null)
+				return null;
+
+			return obsolete;
+		}
+
+		/// <summary>
+		/// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
+		/// </summary>
+		public virtual void CheckObsoleteness (Location loc)
+		{
+			ObsoleteAttribute oa = GetAttributeObsolete ();
+			if (oa != null)
+				AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
+		}
+
+		//
+		// Checks whether the type P is as accessible as this member
+		//
+		public bool IsAccessibleAs (TypeSpec p)
+		{
+			//
+			// if M is private, its accessibility is the same as this declspace.
+			// we already know that P is accessible to T before this method, so we
+			// may return true.
+			//
+			if ((mod_flags & Modifiers.PRIVATE) != 0)
+				return true;
+
+			while (TypeManager.HasElementType (p))
+				p = TypeManager.GetElementType (p);
+
+			if (p.IsGenericParameter)
+				return true;
+
+			for (TypeSpec p_parent; p != null; p = p_parent) {
+				p_parent = p.DeclaringType;
+
+				if (p.IsGeneric) {
+					foreach (TypeSpec t in p.TypeArguments) {
+						if (!IsAccessibleAs (t))
+							return false;
+					}
+				}
+
+				var pAccess = p.Modifiers & Modifiers.AccessibilityMask;
+				if (pAccess == Modifiers.PUBLIC)
+					continue;
+
+				bool same_access_restrictions = false;
+				for (MemberCore mc = this; !same_access_restrictions && mc != null && mc.Parent != null; mc = mc.Parent) {
+					var al = mc.ModFlags & Modifiers.AccessibilityMask;
+					switch (pAccess) {
+					case Modifiers.INTERNAL:
+						if (al == Modifiers.PRIVATE || al == Modifiers.INTERNAL)
+							same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
+						
+						break;
+
+					case Modifiers.PROTECTED:
+						if (al == Modifiers.PROTECTED) {
+							same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent);
+							break;
+						}
+
+						if (al == Modifiers.PRIVATE) {
+							//
+							// When type is private and any of its parents derives from
+							// protected type then the type is accessible
+							//
+							while (mc.Parent != null && mc.Parent.PartialContainer != null) {
+								if (mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent))
+									same_access_restrictions = true;
+								mc = mc.Parent; 
+							}
+						}
+						
+						break;
+
+					case Modifiers.PROTECTED | Modifiers.INTERNAL:
+						if (al == Modifiers.INTERNAL)
+							same_access_restrictions = p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
+						else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
+							same_access_restrictions = mc.Parent.PartialContainer.IsBaseTypeDefinition (p_parent) && p.MemberDefinition.IsInternalAsPublic (mc.Module.DeclaringAssembly);
+						else
+							goto case Modifiers.PROTECTED;
+
+						break;
+
+					case Modifiers.PRIVATE:
+						//
+						// Both are private and share same parent
+						//
+						if (al == Modifiers.PRIVATE) {
+							var decl = mc.Parent;
+							do {
+								same_access_restrictions = decl.CurrentType.MemberDefinition == p_parent.MemberDefinition;
+							} while (!same_access_restrictions && !decl.PartialContainer.IsTopLevel && (decl = decl.Parent) != null);
+						}
+						
+						break;
+						
+					default:
+						throw new InternalErrorException (al.ToString ());
+					}
+				}
+				
+				if (!same_access_restrictions)
+					return false;
+			}
+
+			return true;
+		}
+
+		/// <summary>
+		/// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
+		/// </summary>
+		public override bool IsClsComplianceRequired ()
+		{
+			if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
+				return (caching_flags & Flags.ClsCompliant) != 0;
+
+			caching_flags &= ~Flags.ClsCompliance_Undetected;
+
+			if (HasClsCompliantAttribute) {
+				if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0)
+					return false;
+
+				caching_flags |= Flags.ClsCompliant;
+				return true;
+			}
+
+			if (Parent.IsClsComplianceRequired ()) {
+				caching_flags |= Flags.ClsCompliant;
+				return true;
+			}
+
+			return false;
+		}
+
+		public virtual string[] ConditionalConditions ()
+		{
+			return null;
+		}
+
+		/// <summary>
+		/// Returns true when MemberCore is exposed from assembly.
+		/// </summary>
+		public bool IsExposedFromAssembly ()
+		{
+			if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
+				return this is NamespaceContainer;
+			
+			var parentContainer = Parent.PartialContainer;
+			while (parentContainer != null) {
+				if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
+					return false;
+
+				parentContainer = parentContainer.Parent.PartialContainer;
+			}
+
+			return true;
+		}
+
+		//
+		// Does extension methods look up to find a method which matches name and extensionType.
+		// Search starts from this namespace and continues hierarchically up to top level.
+		//
+		public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
+		{
+			var m = Parent;
+			do {
+				var ns = m as NamespaceContainer;
+				if (ns != null)
+					return ns.LookupExtensionMethod (this, extensionType, name, arity, 0);
+
+				m = m.Parent;
+			} while (m != null);
+
+			return null;
+		}
+
+		public virtual FullNamedExpression LookupNamespaceAlias (string name)
+		{
+			return Parent.LookupNamespaceAlias (name);
+		}
+
+		public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			return Parent.LookupNamespaceOrType (name, arity, mode, loc);
+		}
+
+		/// <summary>
+		/// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
+		/// If no is attribute exists then assembly CLSCompliantAttribute is returned.
+		/// </summary>
+		public bool? CLSAttributeValue {
+			get {
+				if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0) {
+					if ((caching_flags & Flags.HasClsCompliantAttribute) == 0)
+						return null;
+
+					return (caching_flags & Flags.ClsCompliantAttributeFalse) == 0;
+				}
+
+				caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
+
+				if (OptAttributes != null) {
+					Attribute cls_attribute = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
+					if (cls_attribute != null) {
+						caching_flags |= Flags.HasClsCompliantAttribute;
+						if (cls_attribute.GetClsCompliantAttributeValue ())
+							return true;
+
+						caching_flags |= Flags.ClsCompliantAttributeFalse;
+						return false;
+					}
+				}
+
+				return null;
+			}
+		}
+
+		/// <summary>
+		/// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
+		/// </summary>
+		protected bool HasClsCompliantAttribute {
+			get {
+				return CLSAttributeValue.HasValue;
+			}
+		}
+
+		/// <summary>
+		/// Returns true when a member supports multiple overloads (methods, indexers, etc)
+		/// </summary>
+		public virtual bool EnableOverloadChecks (MemberCore overload)
+		{
+			return false;
+		}
+
+		/// <summary>
+		/// The main virtual method for CLS-Compliant verifications.
+		/// The method returns true if member is CLS-Compliant and false if member is not
+		/// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
+		/// and add their extra verifications.
+		/// </summary>
+		protected virtual bool VerifyClsCompliance ()
+		{
+			if (HasClsCompliantAttribute) {
+				if (!Module.DeclaringAssembly.HasCLSCompliantAttribute) {
+					Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
+					if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
+						Report.Warning (3021, 2, a.Location,
+							"`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant",
+							GetSignatureForError ());
+					} else {
+						Report.Warning (3014, 1, a.Location,
+							"`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
+							GetSignatureForError ());
+					}
+					return false;
+				}
+
+				if (!IsExposedFromAssembly ()) {
+					Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
+					Report.Warning (3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
+					return false;
+				}
+
+				if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
+					if (Parent is Interface && Parent.IsClsComplianceRequired ()) {
+						Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
+					} else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
+						Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
+					}
+
+					return false;
+				}
+
+				if (Parent.Kind != MemberKind.Namespace && Parent.Kind != 0 && !Parent.IsClsComplianceRequired ()) {
+					Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CLSCompliant);
+					Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
+						GetSignatureForError (), Parent.GetSignatureForError ());
+					return false;
+				}
+			} else {
+				if (!IsExposedFromAssembly ())
+					return false;
+
+				if (!Parent.IsClsComplianceRequired ())
+					return false;
+			}
+
+			if (member_name.Name [0] == '_') {
+				Warning_IdentifierNotCompliant ();
+			}
+
+			if (member_name.TypeParameters != null)
+				member_name.TypeParameters.VerifyClsCompliance ();
+
+			return true;
+		}
+
+		protected void Warning_IdentifierNotCompliant ()
+		{
+			Report.Warning (3008, 1, MemberName.Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError ());
+		}
+
+		public virtual string GetCallerMemberName ()
+		{
+			return MemberName.Name;
+		}
+
+		//
+		// Returns a string that represents the signature for this 
+		// member which should be used in XML documentation.
+		//
+		public abstract string GetSignatureForDocumentation ();
+
+		public virtual void GetCompletionStartingWith (string prefix, List<string> results)
+		{
+			Parent.GetCompletionStartingWith (prefix, results);
+		}
+
+		//
+		// Generates xml doc comments (if any), and if required,
+		// handle warning report.
+		//
+		internal virtual void GenerateDocComment (DocumentationBuilder builder)
+		{
+			if (DocComment == null) {
+				if (IsExposedFromAssembly ()) {
+					Constructor c = this as Constructor;
+					if (c == null || !c.IsDefault ())
+						Report.Warning (1591, 4, Location,
+							"Missing XML comment for publicly visible type or member `{0}'", GetSignatureForError ());
+				}
+
+				return;
+			}
+
+			try {
+				builder.GenerateDocumentationForMember (this);
+			} catch (Exception e) {
+				throw new InternalErrorException (this, e);
+			}
+		}
+
+		public virtual void WriteDebugSymbol (MonoSymbolFile file)
+		{
+		}
+
+		#region IMemberContext Members
+
+		public virtual CompilerContext Compiler {
+			get {
+				return Module.Compiler;
+			}
+		}
+
+		public virtual TypeSpec CurrentType {
+			get { return Parent.CurrentType; }
+		}
+
+		public MemberCore CurrentMemberDefinition {
+			get { return this; }
+		}
+
+		public virtual TypeParameters CurrentTypeParameters {
+			get { return null; }
+		}
+
+		public bool IsObsolete {
+			get {
+				if (GetAttributeObsolete () != null)
+					return true;
+
+				return Parent != null && Parent.IsObsolete;
+			}
+		}
+
+		public bool IsUnsafe {
+			get {
+				if ((ModFlags & Modifiers.UNSAFE) != 0)
+					return true;
+
+				return Parent != null && Parent.IsUnsafe;
+			}
+		}
+
+		public bool IsStatic {
+			get {
+				return (ModFlags & Modifiers.STATIC) != 0;
+			}
+		}
+
+		#endregion
+	}
+
+	//
+	// Base member specification. A member specification contains
+	// member details which can alter in the context (e.g. generic instances)
+	//
+	public abstract class MemberSpec
+	{
+		[Flags]
+		public enum StateFlags
+		{
+			Obsolete_Undetected = 1,	// Obsolete attribute has not been detected yet
+			Obsolete = 1 << 1,			// Member has obsolete attribute
+			CLSCompliant_Undetected = 1 << 2,	// CLSCompliant attribute has not been detected yet
+			CLSCompliant = 1 << 3,		// Member is CLS Compliant
+			MissingDependency_Undetected = 1 << 4,
+			MissingDependency = 1 << 5,
+			HasDynamicElement = 1 << 6,
+			ConstraintsChecked = 1 << 7,
+
+			IsAccessor = 1 << 9,		// Method is an accessor
+			IsGeneric = 1 << 10,		// Member contains type arguments
+
+			PendingMetaInflate = 1 << 12,
+			PendingMakeMethod = 1 << 13,
+			PendingMemberCacheMembers = 1 << 14,
+			PendingBaseTypeInflate = 1 << 15,
+			InterfacesExpanded = 1 << 16,
+			IsNotCSharpCompatible = 1 << 17,
+			SpecialRuntimeType = 1 << 18,
+			InflatedExpressionType = 1 << 19,
+			InflatedNullableType = 1 << 20,
+			GenericIterateInterface = 1 << 21,
+			GenericTask = 1 << 22,
+			InterfacesImported = 1 << 23,
+		}
+
+		//
+		// Some flags can be copied directly from other member
+		//
+		protected const StateFlags SharedStateFlags =
+			StateFlags.CLSCompliant | StateFlags.CLSCompliant_Undetected |
+			StateFlags.Obsolete | StateFlags.Obsolete_Undetected |
+			StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected |
+			StateFlags.HasDynamicElement;
+
+		protected Modifiers modifiers;
+		public StateFlags state;
+		protected IMemberDefinition definition;
+		public readonly MemberKind Kind;
+		protected TypeSpec declaringType;
+
+#if DEBUG
+		static int counter;
+		public int ID = counter++;
+#endif
+
+		protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
+		{
+			this.Kind = kind;
+			this.declaringType = declaringType;
+			this.definition = definition;
+			this.modifiers = modifiers;
+
+			if (kind == MemberKind.MissingType)
+				state = StateFlags.MissingDependency;
+			else
+				state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected | StateFlags.MissingDependency_Undetected;
+		}
+
+		#region Properties
+
+		public virtual int Arity {
+			get {
+				return 0;
+			}
+		}
+
+		public TypeSpec DeclaringType {
+			get {
+				return declaringType;
+			}
+			set {
+				declaringType = value;
+			}
+		}
+
+		public IMemberDefinition MemberDefinition {
+			get {
+				return definition;
+			}
+		}
+
+		public Modifiers Modifiers {
+			get {
+				return modifiers;
+			}
+			set {
+				modifiers = value;
+			}
+		}
+		
+		public virtual string Name {
+			get {
+				return definition.Name;
+			}
+		}
+
+		public bool IsAbstract {
+			get { return (modifiers & Modifiers.ABSTRACT) != 0; }
+		}
+
+		public bool IsAccessor {
+			get {
+				return (state & StateFlags.IsAccessor) != 0;
+			}
+			set {
+				state = value ? state | StateFlags.IsAccessor : state & ~StateFlags.IsAccessor;
+			}
+		}
+
+		//
+		// Return true when this member is a generic in C# terms
+		// A nested non-generic type of generic type will return false
+		//
+		public bool IsGeneric {
+			get {
+				return (state & StateFlags.IsGeneric) != 0;
+			}
+			set {
+				state = value ? state | StateFlags.IsGeneric : state & ~StateFlags.IsGeneric;
+			}
+		}
+
+		//
+		// Returns true for imported members which are not compatible with C# language
+		//
+		public bool IsNotCSharpCompatible {
+			get {
+				return (state & StateFlags.IsNotCSharpCompatible) != 0;
+			}
+			set {
+				state = value ? state | StateFlags.IsNotCSharpCompatible : state & ~StateFlags.IsNotCSharpCompatible;
+			}
+		}
+
+		public bool IsPrivate {
+			get { return (modifiers & Modifiers.PRIVATE) != 0; }
+		}
+
+		public bool IsPublic {
+			get { return (modifiers & Modifiers.PUBLIC) != 0; }
+		}
+
+		public bool IsStatic {
+			get { 
+				return (modifiers & Modifiers.STATIC) != 0;
+			}
+		}
+
+		#endregion
+
+		public virtual ObsoleteAttribute GetAttributeObsolete ()
+		{
+			if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
+				return null;
+
+			state &= ~StateFlags.Obsolete_Undetected;
+
+			var oa = definition.GetAttributeObsolete ();
+			if (oa != null)
+				state |= StateFlags.Obsolete;
+
+			return oa;
+		}
+
+		//
+		// Returns a list of missing dependencies of this member. The list
+		// will contain types only but it can have numerous values for members
+		// like methods where both return type and all parameters are checked
+		//
+		public List<MissingTypeSpecReference> GetMissingDependencies ()
+		{
+			return GetMissingDependencies (this);
+		}
+
+		public List<MissingTypeSpecReference> GetMissingDependencies (MemberSpec caller)
+		{
+			if ((state & (StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected)) == 0)
+				return null;
+
+			state &= ~StateFlags.MissingDependency_Undetected;
+
+			var imported = definition as ImportedDefinition;
+			List<MissingTypeSpecReference> missing;
+			if (imported != null) {
+				missing = ResolveMissingDependencies (caller);
+			} else if (this is ElementTypeSpec) {
+				missing = ((ElementTypeSpec) this).Element.GetMissingDependencies (caller);
+			} else {
+				missing = null;
+			}
+
+			if (missing != null) {
+				state |= StateFlags.MissingDependency;
+			}
+
+			return missing;
+		}
+
+		public abstract List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller);
+
+		protected virtual bool IsNotCLSCompliant (out bool attrValue)
+		{
+			var cls = MemberDefinition.CLSAttributeValue;
+			attrValue = cls ?? false;
+			return cls == false;
+		}
+
+		public virtual string GetSignatureForDocumentation ()
+		{
+			return DeclaringType.GetSignatureForDocumentation () + "." + Name;
+		}
+
+		public virtual string GetSignatureForError ()
+		{
+			var bf = MemberDefinition as Property.BackingField;
+			string name;
+			if (bf == null) {
+				name = Name;
+			} else {
+				name = bf.OriginalProperty.MemberName.Name;
+			}
+
+			return DeclaringType.GetSignatureForError () + "." + name;
+		}
+
+		public virtual MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var inflated = (MemberSpec) MemberwiseClone ();
+			inflated.declaringType = inflator.TypeInstance;
+			if (DeclaringType.IsGenericOrParentIsGeneric)
+				inflated.state |= StateFlags.PendingMetaInflate;
+#if DEBUG
+			inflated.ID += 1000000;
+#endif
+			return inflated;
+		}
+
+		//
+		// Is this member accessible from invocation context
+		//
+		public bool IsAccessible (IMemberContext ctx)
+		{
+			var ma = Modifiers & Modifiers.AccessibilityMask;
+			if (ma == Modifiers.PUBLIC)
+				return true;
+
+			var parentType = /* this as TypeSpec ?? */ DeclaringType;
+			var ctype = ctx.CurrentType;
+
+			if (ma == Modifiers.PRIVATE) {
+				if (ctype == null || parentType == null)
+					return false;
+				//
+				// It's only accessible to the current class or children
+				//
+				if (parentType.MemberDefinition == ctype.MemberDefinition)
+					return true;
+
+				return TypeManager.IsNestedChildOf (ctype, parentType.MemberDefinition);
+			}
+
+			if ((ma & Modifiers.INTERNAL) != 0) {
+				bool b;
+				var assembly = ctype == null ? ctx.Module.DeclaringAssembly : ctype.MemberDefinition.DeclaringAssembly;
+
+				if (parentType == null) {
+					b = ((ITypeDefinition) MemberDefinition).IsInternalAsPublic (assembly);
+				} else {
+					b = DeclaringType.MemberDefinition.IsInternalAsPublic (assembly);
+				}
+
+				if (b || ma == Modifiers.INTERNAL)
+					return b;
+			}
+
+			//
+			// Checks whether `ctype' is a subclass or nested child of `parentType'.
+			//
+			while (ctype != null) {
+				if (TypeManager.IsFamilyAccessible (ctype, parentType))
+					return true;
+
+				// Handle nested types.
+				ctype = ctype.DeclaringType;	// TODO: Untested ???
+			}
+
+			return false;
+		}
+
+		//
+		// Returns member CLS compliance based on full member hierarchy
+		//
+		public bool IsCLSCompliant ()
+		{
+			if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
+				state &= ~StateFlags.CLSCompliant_Undetected;
+
+				bool compliant;
+				if (IsNotCLSCompliant (out compliant))
+					return false;
+
+				if (!compliant) {
+					if (DeclaringType != null) {
+						compliant = DeclaringType.IsCLSCompliant ();
+					} else {
+						compliant = ((ITypeDefinition) MemberDefinition).DeclaringAssembly.IsCLSCompliant;
+					}
+				}
+
+				if (compliant)
+					state |= StateFlags.CLSCompliant;
+			}
+
+			return (state & StateFlags.CLSCompliant) != 0;
+		}
+
+		public bool IsConditionallyExcluded (IMemberContext ctx)
+		{
+			if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
+				return false;
+
+			var conditions = MemberDefinition.ConditionalConditions ();
+			if (conditions == null)
+				return false;
+
+			var m = ctx.CurrentMemberDefinition;
+			CompilationSourceFile unit = null;
+			while (m != null && unit == null) {
+				unit = m as CompilationSourceFile;
+				m = m.Parent;
+			}
+
+			if (unit != null) {
+				foreach (var condition in conditions) {
+					if (unit.IsConditionalDefined (condition))
+						return false;
+				}
+			}
+
+			return true;
+		}
+
+		public override string ToString ()
+		{
+			return GetSignatureForError ();
+		}
+	}
+
+	//
+	// Member details which are same between all member
+	// specifications
+	//
+	public interface IMemberDefinition
+	{
+		bool? CLSAttributeValue { get; }
+		string Name { get; }
+		bool IsImported { get; }
+
+		string[] ConditionalConditions ();
+		ObsoleteAttribute GetAttributeObsolete ();
+		void SetIsAssigned ();
+		void SetIsUsed ();
+	}
+
+	public interface IMethodDefinition : IMemberDefinition
+	{
+		MethodBase Metadata { get; }
+	}
+
+	public interface IParametersMember : IInterfaceMemberSpec
+	{
+		AParametersCollection Parameters { get; }
+	}
+
+	public interface IInterfaceMemberSpec
+	{
+		TypeSpec MemberType { get; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/delegate.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/delegate.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/delegate.cs	(revision 11807)
@@ -0,0 +1,952 @@
+//
+// delegate.cs: Delegate Handler
+//
+// Authors:
+//     Ravi Pratap (ravi@ximian.com)
+//     Miguel de Icaza (miguel@ximian.com)
+//     Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2009 Novell, Inc (http://www.novell.com)
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	//
+	// Delegate container implementation
+	//
+	public class Delegate : TypeDefinition, IParametersMember
+	{
+ 		public FullNamedExpression ReturnType;
+		readonly ParametersCompiled parameters;
+
+		Constructor Constructor;
+		Method InvokeBuilder;
+		Method BeginInvokeBuilder;
+		Method EndInvokeBuilder;
+
+		static readonly string[] attribute_targets = new string [] { "type", "return" };
+
+		public static readonly string InvokeMethodName = "Invoke";
+		
+		Expression instance_expr;
+		ReturnParameter return_attributes;
+
+		const Modifiers MethodModifiers = Modifiers.PUBLIC | Modifiers.VIRTUAL;
+
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.UNSAFE |
+			Modifiers.PRIVATE;
+
+ 		public Delegate (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, ParametersCompiled param_list,
+				 Attributes attrs)
+			: base (parent, name, attrs, MemberKind.Delegate)
+
+		{
+			this.ReturnType = type;
+			ModFlags        = ModifiersExtensions.Check (AllowedModifiers, mod_flags,
+							   IsTopLevel ? Modifiers.INTERNAL :
+							   Modifiers.PRIVATE, name.Location, Report);
+			parameters      = param_list;
+			spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
+		}
+
+		#region Properties
+		public TypeSpec MemberType {
+			get {
+				return ReturnType.Type;
+			}
+		}
+
+		public AParametersCollection Parameters {
+			get {
+				return parameters;
+			}
+		}
+
+		public FullNamedExpression TypExpression {
+			get {
+				return ReturnType;
+			}
+		}
+
+		#endregion
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Target == AttributeTargets.ReturnValue) {
+				if (return_attributes == null)
+					return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
+
+				return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Delegate;
+			}
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			var builtin_types = Compiler.BuiltinTypes;
+
+			var ctor_parameters = ParametersCompiled.CreateFullyResolved (
+				new [] {
+					new Parameter (new TypeExpression (builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location),
+					new Parameter (new TypeExpression (builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location)
+				},
+				new [] {
+					builtin_types.Object,
+					builtin_types.IntPtr
+				}
+			);
+
+			Constructor = new Constructor (this, Constructor.ConstructorName,
+				Modifiers.PUBLIC, null, ctor_parameters, Location);
+			Constructor.Define ();
+
+			//
+			// Here the various methods like Invoke, BeginInvoke etc are defined
+			//
+			// First, call the `out of band' special method for
+			// defining recursively any types we need:
+			//
+			var p = parameters;
+
+			if (!p.Resolve (this))
+				return false;
+
+			//
+			// Invoke method
+			//
+
+			// Check accessibility
+			foreach (var partype in p.Types) {
+				if (!IsAccessibleAs (partype)) {
+					Report.SymbolRelatedToPreviousError (partype);
+					Report.Error (59, Location,
+						"Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'",
+						partype.GetSignatureForError (), GetSignatureForError ());
+				}
+			}
+
+			var ret_type = ReturnType.ResolveAsType (this);
+			if (ret_type == null)
+				return false;
+
+			//
+			// We don't have to check any others because they are all
+			// guaranteed to be accessible - they are standard types.
+			//
+			if (!IsAccessibleAs (ret_type)) {
+				Report.SymbolRelatedToPreviousError (ret_type);
+				Report.Error (58, Location,
+						  "Inconsistent accessibility: return type `" +
+						  ret_type.GetSignatureForError () + "' is less " +
+						  "accessible than delegate `" + GetSignatureForError () + "'");
+				return false;
+			}
+
+			CheckProtectedModifier ();
+
+			if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) {
+				Method.Error1599 (Location, ret_type, Report);
+				return false;
+			}
+
+			VarianceDecl.CheckTypeVariance (ret_type, Variance.Covariant, this);
+
+			var resolved_rt = new TypeExpression (ret_type, Location);
+			InvokeBuilder = new Method (this, resolved_rt, MethodModifiers, new MemberName (InvokeMethodName), p, null);
+			InvokeBuilder.Define ();
+
+			//
+			// Don't emit async method for compiler generated delegates (e.g. dynamic site containers)
+			//
+			if (!IsCompilerGenerated) {
+				DefineAsyncMethods (resolved_rt);
+			}
+
+			return true;
+		}
+
+		void DefineAsyncMethods (TypeExpression returnType)
+		{
+			var iasync_result = Module.PredefinedTypes.IAsyncResult;
+			var async_callback = Module.PredefinedTypes.AsyncCallback;
+
+			//
+			// It's ok when async types don't exist, the delegate will have Invoke method only
+			//
+			if (!iasync_result.Define () || !async_callback.Define ())
+				return;
+
+			//
+			// BeginInvoke
+			//
+			ParametersCompiled async_parameters;
+			if (Parameters.Count == 0) {
+				async_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+			} else {
+				var compiled = new Parameter[Parameters.Count];
+				for (int i = 0; i < compiled.Length; ++i) {
+					var p = parameters[i];
+					compiled[i] = new Parameter (new TypeExpression (parameters.Types[i], Location),
+						p.Name,
+						p.ModFlags & Parameter.Modifier.RefOutMask,
+						p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
+				}
+
+				async_parameters = new ParametersCompiled (compiled);
+			}
+
+			async_parameters = ParametersCompiled.MergeGenerated (Compiler, async_parameters, false,
+				new Parameter[] {
+					new Parameter (new TypeExpression (async_callback.TypeSpec, Location), "callback", Parameter.Modifier.NONE, null, Location),
+					new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, Location), "object", Parameter.Modifier.NONE, null, Location)
+				},
+				new [] {
+					async_callback.TypeSpec,
+					Compiler.BuiltinTypes.Object
+				}
+			);
+
+			BeginInvokeBuilder = new Method (this,
+				new TypeExpression (iasync_result.TypeSpec, Location), MethodModifiers,
+				new MemberName ("BeginInvoke"), async_parameters, null);
+			BeginInvokeBuilder.Define ();
+
+			//
+			// EndInvoke is a bit more interesting, all the parameters labeled as
+			// out or ref have to be duplicated here.
+			//
+
+			//
+			// Define parameters, and count out/ref parameters
+			//
+			ParametersCompiled end_parameters;
+			int out_params = 0;
+
+			foreach (Parameter p in Parameters.FixedParameters) {
+				if ((p.ModFlags & Parameter.Modifier.RefOutMask) != 0)
+					++out_params;
+			}
+
+			if (out_params > 0) {
+				Parameter[] end_params = new Parameter[out_params];
+
+				int param = 0;
+				for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
+					Parameter p = parameters [i];
+					if ((p.ModFlags & Parameter.Modifier.RefOutMask) == 0)
+						continue;
+
+					end_params [param++] = new Parameter (new TypeExpression (p.Type, Location),
+						p.Name,
+						p.ModFlags & Parameter.Modifier.RefOutMask,
+						p.OptAttributes == null ? null : p.OptAttributes.Clone (), Location);
+				}
+
+				end_parameters = new ParametersCompiled (end_params);
+			} else {
+				end_parameters = ParametersCompiled.EmptyReadOnlyParameters;
+			}
+
+			end_parameters = ParametersCompiled.MergeGenerated (Compiler, end_parameters, false,
+				new Parameter (
+					new TypeExpression (iasync_result.TypeSpec, Location),
+					"result", Parameter.Modifier.NONE, null, Location),
+				iasync_result.TypeSpec);
+
+			//
+			// Create method, define parameters, register parameters with type system
+			//
+			EndInvokeBuilder = new Method (this, returnType, MethodModifiers, new MemberName ("EndInvoke"), end_parameters, null);
+			EndInvokeBuilder.Define ();
+		}
+
+		public override void PrepareEmit ()
+		{
+			if (!Parameters.IsEmpty) {
+				parameters.ResolveDefaultValues (this);
+			}
+
+			InvokeBuilder.PrepareEmit ();
+			if (BeginInvokeBuilder != null) {
+				BeginInvokeBuilder.PrepareEmit ();
+				EndInvokeBuilder.PrepareEmit ();
+			}
+		}
+
+		public override void Emit ()
+		{
+			base.Emit ();
+
+			if (ReturnType.Type != null) {
+				if (ReturnType.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
+					Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
+				} else if (ReturnType.Type.HasDynamicElement) {
+					return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
+					Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType.Type, Location);
+				}
+
+				ConstraintChecker.Check (this, ReturnType.Type, ReturnType.Location);
+			}
+
+			Constructor.ParameterInfo.ApplyAttributes (this, Constructor.ConstructorBuilder);
+			Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
+
+			parameters.CheckConstraints (this);
+			parameters.ApplyAttributes (this, InvokeBuilder.MethodBuilder);
+			InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
+
+			if (BeginInvokeBuilder != null) {
+				BeginInvokeBuilder.ParameterInfo.ApplyAttributes (this, BeginInvokeBuilder.MethodBuilder);
+				EndInvokeBuilder.ParameterInfo.ApplyAttributes (this, EndInvokeBuilder.MethodBuilder);
+
+				BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
+				EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
+			}
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			base_type = Compiler.BuiltinTypes.MulticastDelegate;
+			base_class = null;
+			return null;
+		}
+
+		protected override TypeAttributes TypeAttr {
+			get {
+				return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+
+		//TODO: duplicate
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ()) {
+				return false;
+			}
+
+			parameters.VerifyClsCompliance (this);
+
+			if (!InvokeBuilder.MemberType.IsCLSCompliant ()) {
+				Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
+					GetSignatureForError ());
+			}
+			return true;
+		}
+
+
+		public static MethodSpec GetConstructor (TypeSpec delType)
+		{
+			var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
+			return (MethodSpec) ctor;
+		}
+
+		//
+		// Returns the "Invoke" from a delegate type
+		//
+		public static MethodSpec GetInvokeMethod (TypeSpec delType)
+		{
+			var invoke = MemberCache.FindMember (delType,
+				MemberFilter.Method (InvokeMethodName, 0, null, null),
+				BindingRestriction.DeclaredOnly);
+
+			return (MethodSpec) invoke;
+		}
+
+		public static AParametersCollection GetParameters (TypeSpec delType)
+		{
+			var invoke_mb = GetInvokeMethod (delType);
+			return invoke_mb.Parameters;
+		}
+
+		//
+		// 15.2 Delegate compatibility
+		//
+		public static bool IsTypeCovariant (ResolveContext rc, TypeSpec a, TypeSpec b)
+		{
+			//
+			// For each value parameter (a parameter with no ref or out modifier), an 
+			// identity conversion or implicit reference conversion exists from the
+			// parameter type in D to the corresponding parameter type in M
+			//
+			if (a == b)
+				return true;
+
+			if (rc.Module.Compiler.Settings.Version == LanguageVersion.ISO_1)
+				return false;
+
+			if (a.IsGenericParameter && b.IsGenericParameter)
+				return a == b;
+
+			return Convert.ImplicitReferenceConversionExists (a, b);
+		}
+
+		public static string FullDelegateDesc (MethodSpec invoke_method)
+		{
+			return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
+		}
+		
+		public Expression InstanceExpression {
+			get {
+				return instance_expr;
+			}
+			set {
+				instance_expr = value;
+			}
+		}
+	}
+
+	//
+	// Base class for `NewDelegate' and `ImplicitDelegateCreation'
+	//
+	public abstract class DelegateCreation : Expression, OverloadResolver.IErrorHandler
+	{
+		bool conditional_access_receiver;
+		protected MethodSpec constructor_method;
+		protected MethodGroupExpr method_group;
+
+		public bool AllowSpecialMethodsInvocation { get; set; }
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			var instance = method_group.InstanceExpression;
+			return instance != null && instance.ContainsEmitWithAwait ();
+		}
+
+		public static Arguments CreateDelegateMethodArguments (ResolveContext rc, AParametersCollection pd, TypeSpec[] types, Location loc)
+		{
+			Arguments delegate_arguments = new Arguments (pd.Count);
+			for (int i = 0; i < pd.Count; ++i) {
+				Argument.AType atype_modifier;
+				switch (pd.FixedParameters [i].ModFlags & Parameter.Modifier.RefOutMask) {
+				case Parameter.Modifier.REF:
+					atype_modifier = Argument.AType.Ref;
+					break;
+				case Parameter.Modifier.OUT:
+					atype_modifier = Argument.AType.Out;
+					break;
+				default:
+					atype_modifier = 0;
+					break;
+				}
+
+				var ptype = types[i];
+				if (ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					ptype = rc.BuiltinTypes.Object;
+
+				delegate_arguments.Add (new Argument (new TypeExpression (ptype, loc), atype_modifier));
+			}
+
+			return delegate_arguments;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			MemberAccess ma = new MemberAccess (new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Delegate", loc), "CreateDelegate", loc);
+
+			Arguments args = new Arguments (3);
+			args.Add (new Argument (new TypeOf (type, loc)));
+
+			if (method_group.InstanceExpression == null)
+				args.Add (new Argument (new NullLiteral (loc)));
+			else
+				args.Add (new Argument (method_group.InstanceExpression));
+
+			args.Add (new Argument (method_group.CreateExpressionTree (ec)));
+			Expression e = new Invocation (ma, args).Resolve (ec);
+			if (e == null)
+				return null;
+
+			e = Convert.ExplicitConversion (ec, e, type, loc);
+			if (e == null)
+				return null;
+
+			return e.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			constructor_method = Delegate.GetConstructor (type);
+
+			var invoke_method = Delegate.GetInvokeMethod (type);
+
+			if (!ec.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) {
+				if (method_group.HasConditionalAccess ()) {
+					conditional_access_receiver = true;
+					ec.Set (ResolveContext.Options.ConditionalAccessReceiver);
+				}
+			}
+
+			Arguments arguments = CreateDelegateMethodArguments (ec, invoke_method.Parameters, invoke_method.Parameters.Types, loc);
+			method_group = method_group.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.CovariantDelegate);
+
+			if (conditional_access_receiver)
+				ec.With (ResolveContext.Options.ConditionalAccessReceiver, false);
+
+			if (method_group == null)
+				return null;
+
+			var delegate_method = method_group.BestCandidate;
+			
+			if (delegate_method.DeclaringType.IsNullableType) {
+				ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
+					delegate_method.GetSignatureForError ());
+				return null;
+			}		
+			
+			if (!AllowSpecialMethodsInvocation)
+				Invocation.IsSpecialMethodInvocation (ec, delegate_method, loc);
+
+			ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
+			if (emg != null) {
+				method_group.InstanceExpression = emg.ExtensionExpression;
+				TypeSpec e_type = emg.ExtensionExpression.Type;
+				if (TypeSpec.IsValueType (e_type)) {
+					ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
+						delegate_method.GetSignatureForError (), e_type.GetSignatureForError ());
+				}
+			}
+
+			TypeSpec rt = method_group.BestCandidateReturnType;
+			if (rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+				rt = ec.BuiltinTypes.Object;
+
+			if (!Delegate.IsTypeCovariant (ec, rt, invoke_method.ReturnType)) {
+				Expression ret_expr = new TypeExpression (delegate_method.ReturnType, loc);
+				Error_ConversionFailed (ec, delegate_method, ret_expr);
+			}
+
+			if (method_group.IsConditionallyExcluded) {
+				ec.Report.SymbolRelatedToPreviousError (delegate_method);
+				MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
+				if (m != null && m.IsPartialDefinition) {
+					ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
+						delegate_method.GetSignatureForError ());
+				} else {
+					ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
+						TypeManager.CSharpSignature (delegate_method));
+				}
+			}
+
+			var expr = method_group.InstanceExpression;
+			if (expr != null && (expr.Type.IsGenericParameter || !TypeSpec.IsReferenceType (expr.Type)))
+				method_group.InstanceExpression = new BoxedCast (expr, ec.BuiltinTypes.Object);
+
+			eclass = ExprClass.Value;
+			return this;
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			if (conditional_access_receiver)
+				ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+
+			if (method_group.InstanceExpression == null) {
+				ec.EmitNull ();
+			} else {
+				var ie = new InstanceEmitter (method_group.InstanceExpression, false);
+				ie.Emit (ec, method_group.ConditionalAccess);
+			}
+
+			var delegate_method = method_group.BestCandidate;
+
+			// Any delegate must be sealed
+			if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
+				ec.Emit (OpCodes.Dup);
+				ec.Emit (OpCodes.Ldvirtftn, delegate_method);
+			} else {
+				ec.Emit (OpCodes.Ldftn, delegate_method);
+			}
+
+			ec.Emit (OpCodes.Newobj, constructor_method);
+
+			if (conditional_access_receiver)
+				ec.CloseConditionalAccess (null);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.FlowAnalysis (fc);
+			method_group.FlowAnalysis (fc);
+
+			if (conditional_access_receiver)
+				fc.ConditionalAccessEnd ();
+		}
+
+		void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
+		{
+			var invoke_method = Delegate.GetInvokeMethod (type);
+			string member_name = method_group.InstanceExpression != null ?
+				Delegate.FullDelegateDesc (method) :
+				TypeManager.GetFullNameSignature (method);
+
+			ec.Report.SymbolRelatedToPreviousError (type);
+			ec.Report.SymbolRelatedToPreviousError (method);
+			if (ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
+				ec.Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
+					method.ReturnType.GetSignatureForError (), member_name,
+					invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
+				return;
+			}
+
+			if (return_type == null) {
+				ec.Report.Error (123, loc, "A method or delegate `{0}' parameters do not match delegate `{1}' parameters",
+					member_name, Delegate.FullDelegateDesc (invoke_method));
+				return;
+			}
+
+			ec.Report.Error (407, loc, "A method or delegate `{0} {1}' return type does not match delegate `{2} {3}' return type",
+				return_type.GetSignatureForError (), member_name,
+				invoke_method.ReturnType.GetSignatureForError (), Delegate.FullDelegateDesc (invoke_method));
+		}
+
+		public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
+		{
+//			if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
+//				return false;
+
+			var invoke = Delegate.GetInvokeMethod (target_type);
+
+			Arguments arguments = CreateDelegateMethodArguments (ec, invoke.Parameters, invoke.Parameters.Types, mg.Location);
+			return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly) != null;
+		}
+
+		#region IErrorHandler Members
+
+		bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
+		{
+			return false;
+		}
+
+		bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
+		{
+			Error_ConversionFailed (rc, best as MethodSpec, null);
+			return true;
+		}
+
+		bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
+		{
+			Error_ConversionFailed (rc, best as MethodSpec, null);
+			return true;
+		}
+
+		bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
+		{
+			return false;
+		}
+
+		#endregion
+	}
+
+	//
+	// Created from the conversion code
+	//
+	public class ImplicitDelegateCreation : DelegateCreation
+	{
+		Field mg_cache;
+
+		public ImplicitDelegateCreation (TypeSpec delegateType, MethodGroupExpr mg, Location loc)
+		{
+			type = delegateType;
+			this.method_group = mg;
+			this.loc = loc;
+		}
+
+		//
+		// Returns true when type is MVAR or has MVAR reference
+		//
+		public static bool ContainsMethodTypeParameter (TypeSpec type)
+		{
+			var tps = type as TypeParameterSpec;
+			if (tps != null)
+				return tps.IsMethodOwned;
+
+			var ec = type as ElementTypeSpec;
+			if (ec != null)
+				return ContainsMethodTypeParameter (ec.Element);
+
+			foreach (var t in type.TypeArguments) {
+				if (ContainsMethodTypeParameter (t)) {
+					return true;
+				}
+			}
+
+			if (type.IsNested)
+				return ContainsMethodTypeParameter (type.DeclaringType);
+
+			return false;
+		}
+		
+		bool HasMvar ()
+		{
+			if (ContainsMethodTypeParameter (type))
+				return false;
+
+			var best = method_group.BestCandidate;
+			if (ContainsMethodTypeParameter (best.DeclaringType))
+				return false;
+
+			if (best.TypeArguments != null) {
+				foreach (var ta in best.TypeArguments) {
+					if (ContainsMethodTypeParameter (ta))
+						return false;
+				}
+			}
+
+			return true;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			var expr = base.DoResolve (ec);
+			if (expr == null)
+				return ErrorExpression.Instance;
+
+			if (ec.IsInProbingMode)
+				return expr;
+
+			//
+			// Cache any static delegate creation
+			//
+			if (method_group.InstanceExpression != null)
+				return expr;
+
+			//
+			// Cannot easily cache types with MVAR
+			//
+			if (!HasMvar ())
+				return expr;
+
+			//
+			// Create type level cache for a delegate instance
+			//
+			var parent = ec.CurrentMemberDefinition.Parent.PartialContainer;
+			int id = parent.MethodGroupsCounter++;
+
+			mg_cache = new Field (parent, new TypeExpression (type, loc),
+				Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
+				new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "mg$cache", id), loc), null);
+			mg_cache.Define ();
+			parent.AddField (mg_cache);
+
+			return expr;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Label l_initialized = ec.DefineLabel ();
+
+			if (mg_cache != null) {
+				ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
+				ec.Emit (OpCodes.Brtrue_S, l_initialized);
+			}
+
+			base.Emit (ec);
+
+			if (mg_cache != null) {
+				ec.Emit (OpCodes.Stsfld, mg_cache.Spec);
+				ec.MarkLabel (l_initialized);
+				ec.Emit (OpCodes.Ldsfld, mg_cache.Spec);
+			}
+		}
+	}
+	
+	//
+	// A delegate-creation-expression, invoked from the `New' class 
+	//
+	public class NewDelegate : DelegateCreation
+	{
+		public Arguments Arguments;
+
+		//
+		// This constructor is invoked from the `New' expression
+		//
+		public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
+		{
+			this.type = type;
+			this.Arguments = Arguments;
+			this.loc  = loc; 
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (Arguments == null || Arguments.Count != 1) {
+				ec.Report.Error (149, loc, "Method name expected");
+				return null;
+			}
+
+			Argument a = Arguments [0];
+			if (!a.ResolveMethodGroup (ec))
+				return null;
+
+			Expression e = a.Expr;
+
+			AnonymousMethodExpression ame = e as AnonymousMethodExpression;
+			if (ame != null && ec.Module.Compiler.Settings.Version != LanguageVersion.ISO_1) {
+				e = ame.Compatible (ec, type);
+				if (e == null)
+					return null;
+
+				return e.Resolve (ec);
+			}
+
+			method_group = e as MethodGroupExpr;
+			if (method_group == null) {
+				if (e.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					e = Convert.ImplicitConversionRequired (ec, e, type, loc);
+				} else if (!e.Type.IsDelegate) {
+					e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
+					return null;
+				}
+
+				//
+				// An argument is not a method but another delegate
+				//
+				method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (e.Type), e.Type, loc);
+				method_group.InstanceExpression = e;
+			}
+
+			return base.DoResolve (ec);
+		}
+	}
+
+	//
+	// Invocation converted to delegate Invoke call
+	//
+	class DelegateInvocation : ExpressionStatement
+	{
+		readonly Expression InstanceExpr;
+		readonly bool conditionalAccessReceiver;
+		Arguments arguments;
+		MethodSpec method;
+		
+		public DelegateInvocation (Expression instance_expr, Arguments args, bool conditionalAccessReceiver, Location loc)
+		{
+			this.InstanceExpr = instance_expr;
+			this.arguments = args;
+			this.conditionalAccessReceiver = conditionalAccessReceiver;
+			this.loc = loc;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return InstanceExpr.ContainsEmitWithAwait () || (arguments != null && arguments.ContainsEmitWithAwait ());
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = Arguments.CreateForExpressionTree (ec, this.arguments,
+				InstanceExpr.CreateExpressionTree (ec));
+
+			return CreateExpressionFactoryCall (ec, "Invoke", args);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			InstanceExpr.FlowAnalysis (fc);
+			if (arguments != null)
+				arguments.FlowAnalysis (fc);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{		
+			TypeSpec del_type = InstanceExpr.Type;
+			if (del_type == null)
+				return null;
+
+			//
+			// Do only core overload resolution the rest of the checks has been
+			// done on primary expression
+			//
+			method = Delegate.GetInvokeMethod (del_type);
+			var res = new OverloadResolver (new MemberSpec[] { method }, OverloadResolver.Restrictions.DelegateInvoke, loc);
+			var valid = res.ResolveMember<MethodSpec> (ec, ref arguments);
+			if (valid == null && !res.BestCandidateIsDynamic)
+				return null;
+
+			type = method.ReturnType;
+			if (conditionalAccessReceiver)
+				type = LiftMemberType (ec, type);
+
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (conditionalAccessReceiver) {
+				ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+			}
+
+			//
+			// Invocation on delegates call the virtual Invoke member
+			// so we are always `instance' calls
+			//
+			var call = new CallEmitter ();
+			call.InstanceExpression = InstanceExpr;
+			call.Emit (ec, method, arguments, loc);
+
+			if (conditionalAccessReceiver)
+				ec.CloseConditionalAccess (type.IsNullableType && type !=  method.ReturnType ? type : null);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			if (conditionalAccessReceiver) {
+				ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()) {
+					Statement = true
+				};
+			}
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = InstanceExpr;
+			call.EmitStatement (ec, method, arguments, loc);
+
+			if (conditionalAccessReceiver)
+				ec.CloseConditionalAccess (null);
+		}
+
+		public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
+		{
+			return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/doc.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/doc.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/doc.cs	(revision 11807)
@@ -0,0 +1,755 @@
+//
+// doc.cs: Support for XML documentation comment.
+//
+// Authors:
+//	Atsushi Enomoto <atsushi@ximian.com>
+//  Marek Safar (marek.safar@gmail.com>
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2004 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+//
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Xml;
+using System.Linq;
+
+namespace Mono.CSharp
+{
+	//
+	// Implements XML documentation generation.
+	//
+	class DocumentationBuilder
+	{
+		//
+		// Used to create element which helps well-formedness checking.
+		//
+		readonly XmlDocument XmlDocumentation;
+
+		readonly ModuleContainer module;
+		readonly ModuleContainer doc_module;
+
+		//
+		// The output for XML documentation.
+		//
+		XmlWriter XmlCommentOutput;
+
+		static readonly string line_head = Environment.NewLine + "            ";
+
+		//
+		// Stores XmlDocuments that are included in XML documentation.
+		// Keys are included filenames, values are XmlDocuments.
+		//
+		Dictionary<string, XmlDocument> StoredDocuments = new Dictionary<string, XmlDocument> ();
+
+		ParserSession session;
+
+		public DocumentationBuilder (ModuleContainer module)
+		{
+			doc_module = new ModuleContainer (module.Compiler);
+			doc_module.DocumentationBuilder = this;
+
+			this.module = module;
+			XmlDocumentation = new XmlDocument ();
+			XmlDocumentation.PreserveWhitespace = false;
+		}
+
+		Report Report {
+			get {
+				return module.Compiler.Report;
+			}
+		}
+
+		public MemberName ParsedName {
+			get; set;
+		}
+
+		public List<DocumentationParameter> ParsedParameters {
+			get; set;
+		}
+
+		public TypeExpression ParsedBuiltinType {
+			get; set;
+		}
+
+		public Operator.OpType? ParsedOperator {
+			get; set;
+		}
+
+		XmlNode GetDocCommentNode (MemberCore mc, string name)
+		{
+			// FIXME: It could be even optimizable as not
+			// to use XmlDocument. But anyways the nodes
+			// are not kept in memory.
+			XmlDocument doc = XmlDocumentation;
+			try {
+				XmlElement el = doc.CreateElement ("member");
+				el.SetAttribute ("name", name);
+				string normalized = mc.DocComment;
+				el.InnerXml = normalized;
+				// csc keeps lines as written in the sources
+				// and inserts formatting indentation (which 
+				// is different from XmlTextWriter.Formatting
+				// one), but when a start tag contains an 
+				// endline, it joins the next line. We don't
+				// have to follow such a hacky behavior.
+				string [] split =
+					normalized.Split ('\n');
+				int j = 0;
+				for (int i = 0; i < split.Length; i++) {
+					string s = split [i].TrimEnd ();
+					if (s.Length > 0)
+						split [j++] = s;
+				}
+				el.InnerXml = line_head + String.Join (
+					line_head, split, 0, j);
+				return el;
+			} catch (Exception ex) {
+				Report.Warning (1570, 1, mc.Location, "XML documentation comment on `{0}' is not well-formed XML markup ({1})",
+					mc.GetSignatureForError (), ex.Message);
+
+				return doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name));
+			}
+		}
+
+		//
+		// Generates xml doc comments (if any), and if required,
+		// handle warning report.
+		//
+		internal void GenerateDocumentationForMember (MemberCore mc)
+		{
+			string name = mc.DocCommentHeader + mc.GetSignatureForDocumentation ();
+
+			XmlNode n = GetDocCommentNode (mc, name);
+
+			XmlElement el = n as XmlElement;
+			if (el != null) {
+				var pm = mc as IParametersMember;
+				if (pm != null) {
+					CheckParametersComments (mc, pm, el);
+				}
+
+				// FIXME: it could be done with XmlReader
+				XmlNodeList nl = n.SelectNodes (".//include");
+				if (nl.Count > 0) {
+					// It could result in current node removal, so prepare another list to iterate.
+					var al = new List<XmlNode> (nl.Count);
+					foreach (XmlNode inc in nl)
+						al.Add (inc);
+					foreach (XmlElement inc in al)
+						if (!HandleInclude (mc, inc))
+							inc.ParentNode.RemoveChild (inc);
+				}
+
+				// FIXME: it could be done with XmlReader
+
+				foreach (XmlElement see in n.SelectNodes (".//see"))
+					HandleSee (mc, see);
+				foreach (XmlElement seealso in n.SelectNodes (".//seealso"))
+					HandleSeeAlso (mc, seealso);
+				foreach (XmlElement see in n.SelectNodes (".//exception"))
+					HandleException (mc, see);
+				foreach (XmlElement node in n.SelectNodes (".//typeparam"))
+					HandleTypeParam (mc, node);
+				foreach (XmlElement node in n.SelectNodes (".//typeparamref"))
+					HandleTypeParamRef (mc, node);
+			}
+
+			n.WriteTo (XmlCommentOutput);
+		}
+
+		//
+		// Processes "include" element. Check included file and
+		// embed the document content inside this documentation node.
+		//
+		bool HandleInclude (MemberCore mc, XmlElement el)
+		{
+			bool keep_include_node = false;
+			string file = el.GetAttribute ("file");
+			string path = el.GetAttribute ("path");
+
+			if (file == "") {
+				Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `file' attribute");
+				el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
+				keep_include_node = true;
+			} else if (path.Length == 0) {
+				Report.Warning (1590, 1, mc.Location, "Invalid XML `include' element. Missing `path' attribute");
+				el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Include tag is invalid "), el);
+				keep_include_node = true;
+			} else {
+				XmlDocument doc;
+				Exception exception = null;
+				var full_path = Path.Combine (Path.GetDirectoryName (mc.Location.NameFullPath), file);
+
+				if (!StoredDocuments.TryGetValue (full_path, out doc)) {
+					try {
+						doc = new XmlDocument ();
+						doc.Load (full_path);
+						StoredDocuments.Add (full_path, doc);
+					} catch (Exception e) {
+						exception = e;
+						el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (String.Format (" Badly formed XML in at comment file `{0}': cannot be included ", file)), el);
+					}
+				}
+
+				if (doc != null) {
+					try {
+						XmlNodeList nl = doc.SelectNodes (path);
+						if (nl.Count == 0) {
+							el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" No matching elements were found for the include tag embedded here. "), el);
+					
+							keep_include_node = true;
+						}
+						foreach (XmlNode n in nl)
+							el.ParentNode.InsertBefore (el.OwnerDocument.ImportNode (n, true), el);
+					} catch (Exception ex) {
+						exception = ex;
+						el.ParentNode.InsertBefore (el.OwnerDocument.CreateComment (" Failed to insert some or all of included XML "), el);
+					}
+				}
+
+				if (exception != null) {
+					Report.Warning (1589, 1, mc.Location, "Unable to include XML fragment `{0}' of file `{1}'. {2}",
+						path, file, exception.Message);
+				}
+			}
+
+			return keep_include_node;
+		}
+
+		//
+		// Handles <see> elements.
+		//
+		void HandleSee (MemberCore mc, XmlElement see)
+		{
+			HandleXrefCommon (mc, see);
+		}
+
+		//
+		// Handles <seealso> elements.
+		//
+		void HandleSeeAlso (MemberCore mc, XmlElement seealso)
+		{
+			HandleXrefCommon (mc, seealso);
+		}
+
+		//
+		// Handles <exception> elements.
+		//
+		void HandleException (MemberCore mc, XmlElement seealso)
+		{
+			HandleXrefCommon (mc, seealso);
+		}
+
+		//
+		// Handles <typeparam /> node
+		//
+		static void HandleTypeParam (MemberCore mc, XmlElement node)
+		{
+			if (!node.HasAttribute ("name"))
+				return;
+
+			string tp_name = node.GetAttribute ("name");
+			if (mc.CurrentTypeParameters != null) {
+				if (mc.CurrentTypeParameters.Find (tp_name) != null)
+					return;
+			}
+			
+			// TODO: CS1710, CS1712
+			
+			mc.Compiler.Report.Warning (1711, 2, mc.Location,
+				"XML comment on `{0}' has a typeparam name `{1}' but there is no type parameter by that name",
+				mc.GetSignatureForError (), tp_name);
+		}
+
+		//
+		// Handles <typeparamref /> node
+		//
+		static void HandleTypeParamRef (MemberCore mc, XmlElement node)
+		{
+			if (!node.HasAttribute ("name"))
+				return;
+
+			string tp_name = node.GetAttribute ("name");
+			var member = mc;
+			do {
+				if (member.CurrentTypeParameters != null) {
+					if (member.CurrentTypeParameters.Find (tp_name) != null)
+						return;
+				}
+
+				member = member.Parent;
+			} while (member != null);
+
+			mc.Compiler.Report.Warning (1735, 2, mc.Location,
+				"XML comment on `{0}' has a typeparamref name `{1}' that could not be resolved",
+				mc.GetSignatureForError (), tp_name);
+		}
+
+		FullNamedExpression ResolveMemberName (IMemberContext context, MemberName mn)
+		{
+			if (mn.Left == null)
+				return context.LookupNamespaceOrType (mn.Name, mn.Arity, LookupMode.Probing, Location.Null);
+
+			var left = ResolveMemberName (context, mn.Left);
+			var ns = left as NamespaceExpression;
+			if (ns != null)
+				return ns.LookupTypeOrNamespace (context, mn.Name, mn.Arity, LookupMode.Probing, Location.Null);
+
+			TypeExpr texpr = left as TypeExpr;
+			if (texpr != null) {
+				var found = MemberCache.FindNestedType (texpr.Type, mn.Name, mn.Arity);
+				if (found != null)
+					return new TypeExpression (found, Location.Null);
+
+				return null;
+			}
+
+			return left;
+		}
+
+		//
+		// Processes "see" or "seealso" elements from cref attribute.
+		//
+		void HandleXrefCommon (MemberCore mc, XmlElement xref)
+		{
+			string cref = xref.GetAttribute ("cref");
+			// when, XmlReader, "if (cref == null)"
+			if (!xref.HasAttribute ("cref"))
+				return;
+
+			// Nothing to be resolved the reference is marked explicitly
+			if (cref.Length > 2 && cref [1] == ':')
+				return;
+
+			// Additional symbols for < and > are allowed for easier XML typing
+			cref = cref.Replace ('{', '<').Replace ('}', '>');
+
+			var encoding = module.Compiler.Settings.Encoding;
+			var s = new MemoryStream (encoding.GetBytes (cref));
+
+			var source_file = new CompilationSourceFile (doc_module, mc.Location.SourceFile);
+			var report = new Report (doc_module.Compiler, new NullReportPrinter ());
+
+			if (session == null)
+				session = new ParserSession {
+					UseJayGlobalArrays = true
+				};
+
+			SeekableStreamReader seekable = new SeekableStreamReader (s, encoding, session.StreamReaderBuffer);
+
+			var parser = new CSharpParser (seekable, source_file, report, session);
+			ParsedParameters = null;
+			ParsedName = null;
+			ParsedBuiltinType = null;
+			ParsedOperator = null;
+			parser.Lexer.putback_char = Tokenizer.DocumentationXref;
+			parser.Lexer.parsing_generic_declaration_doc = true;
+			parser.parse ();
+			if (report.Errors > 0) {
+				Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'",
+					mc.GetSignatureForError (), cref);
+
+				xref.SetAttribute ("cref", "!:" + cref);
+				return;
+			}
+
+			MemberSpec member;
+			string prefix = null;
+			FullNamedExpression fne = null;
+
+			//
+			// Try built-in type first because we are using ParsedName as identifier of
+			// member names on built-in types
+			//
+			if (ParsedBuiltinType != null && (ParsedParameters == null || ParsedName != null)) {
+				member = ParsedBuiltinType.Type;
+			} else {
+				member = null;
+			}
+
+			if (ParsedName != null || ParsedOperator.HasValue) {
+				TypeSpec type = null;
+				string member_name = null;
+
+				if (member == null) {
+					if (ParsedOperator.HasValue) {
+						type = mc.CurrentType;
+					} else if (ParsedName.Left != null) {
+						fne = ResolveMemberName (mc, ParsedName.Left);
+						if (fne != null) {
+							var ns = fne as NamespaceExpression;
+							if (ns != null) {
+								fne = ns.LookupTypeOrNamespace (mc, ParsedName.Name, ParsedName.Arity, LookupMode.Probing, Location.Null);
+								if (fne != null) {
+									member = fne.Type;
+								}
+							} else {
+								type = fne.Type;
+							}
+						}
+					} else {
+						fne = ResolveMemberName (mc, ParsedName);
+						if (fne == null) {
+							type = mc.CurrentType;
+						} else if (ParsedParameters == null) {
+							member = fne.Type;
+						} else if (fne.Type.MemberDefinition == mc.CurrentType.MemberDefinition) {
+							member_name = Constructor.ConstructorName;
+							type = fne.Type;
+						}
+					}
+				} else {
+					type = (TypeSpec) member;
+					member = null;
+				}
+
+				if (ParsedParameters != null) {
+					var old_printer = mc.Module.Compiler.Report.SetPrinter (new NullReportPrinter ());
+					try {
+						var context = new DocumentationMemberContext (mc, ParsedName ?? MemberName.Null);
+
+						foreach (var pp in ParsedParameters) {
+							pp.Resolve (context);
+						}
+					} finally {
+						mc.Module.Compiler.Report.SetPrinter (old_printer);
+					}
+				}
+
+				if (type != null) {
+					if (member_name == null)
+						member_name = ParsedOperator.HasValue ?
+							Operator.GetMetadataName (ParsedOperator.Value) : ParsedName.Name;
+
+					int parsed_param_count;
+					if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit) {
+						parsed_param_count = ParsedParameters.Count - 1;
+					} else if (ParsedParameters != null) {
+						parsed_param_count = ParsedParameters.Count;
+					} else {
+						parsed_param_count = 0;
+					}
+
+					int parameters_match = -1;
+					do {
+						var members = MemberCache.FindMembers (type, member_name, true);
+						if (members != null) {
+							foreach (var m in members) {
+								if (ParsedName != null && m.Arity != ParsedName.Arity)
+									continue;
+
+								if (ParsedParameters != null) {
+									IParametersMember pm = m as IParametersMember;
+									if (pm == null)
+										continue;
+
+									if (m.Kind == MemberKind.Operator && !ParsedOperator.HasValue)
+										continue;
+
+									var pm_params = pm.Parameters;
+
+									int i;
+									for (i = 0; i < parsed_param_count; ++i) {
+										var pparam = ParsedParameters[i];
+
+										if (i >= pm_params.Count || pparam == null || pparam.TypeSpec == null ||
+											!TypeSpecComparer.Override.IsEqual (pparam.TypeSpec, pm_params.Types[i]) ||
+											(pparam.Modifier & Parameter.Modifier.RefOutMask) != (pm_params.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask)) {
+
+											if (i > parameters_match) {
+												parameters_match = i;
+											}
+
+											i = -1;
+											break;
+										}
+									}
+
+									if (i < 0)
+										continue;
+
+									if (ParsedOperator == Operator.OpType.Explicit || ParsedOperator == Operator.OpType.Implicit) {
+										if (pm.MemberType != ParsedParameters[parsed_param_count].TypeSpec) {
+											parameters_match = parsed_param_count + 1;
+											continue;
+										}
+									} else {
+										if (parsed_param_count != pm_params.Count)
+											continue;
+									}
+								}
+
+								if (member != null) {
+									Report.Warning (419, 3, mc.Location,
+										"Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
+										cref, member.GetSignatureForError (), m.GetSignatureForError ());
+
+									break;
+								}
+
+								member = m;
+							}
+						}
+
+						// Continue with parent type for nested types
+						if (member == null) {
+							type = type.DeclaringType;
+						} else {
+							type = null;
+						}
+					} while (type != null);
+
+					if (member == null && parameters_match >= 0) {
+						for (int i = parameters_match; i < parsed_param_count; ++i) {
+							Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
+									(i + 1).ToString (), cref);
+						}
+
+						if (parameters_match == parsed_param_count + 1) {
+							Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
+						}
+					}
+				}
+			}
+
+			if (member == null) {
+				Report.Warning (1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved",
+					mc.GetSignatureForError (), cref);
+				cref = "!:" + cref;
+			} else if (member == InternalType.Namespace) {
+				cref = "N:" + fne.GetSignatureForError ();
+			} else {
+				prefix = GetMemberDocHead (member);
+				cref = prefix + member.GetSignatureForDocumentation ();
+			}
+
+			xref.SetAttribute ("cref", cref);
+		}
+
+		//
+		// Get a prefix from member type for XML documentation (used
+		// to formalize cref target name).
+		//
+		static string GetMemberDocHead (MemberSpec type)
+		{
+			if (type is FieldSpec)
+				return "F:";
+			if (type is MethodSpec)
+				return "M:";
+			if (type is EventSpec)
+				return "E:";
+			if (type is PropertySpec)
+				return "P:";
+			if (type is TypeSpec)
+				return "T:";
+
+			throw new NotImplementedException (type.GetType ().ToString ());
+		}
+
+		//
+		// Raised (and passed an XmlElement that contains the comment)
+		// when GenerateDocComment is writing documentation expectedly.
+		//
+		// FIXME: with a few effort, it could be done with XmlReader,
+		// that means removal of DOM use.
+		//
+		void CheckParametersComments (MemberCore member, IParametersMember paramMember, XmlElement el)
+		{
+			HashSet<string> found_tags = null;
+			foreach (XmlElement pelem in el.SelectNodes ("param")) {
+				string xname = pelem.GetAttribute ("name");
+				if (xname.Length == 0)
+					continue; // really? but MS looks doing so
+
+				if (found_tags == null) {
+					found_tags = new HashSet<string> ();
+				}
+
+				if (xname != "" && paramMember.Parameters.GetParameterIndexByName (xname) < 0) {
+					Report.Warning (1572, 2, member.Location,
+						"XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
+						member.GetSignatureForError (), xname);
+					continue;
+				}
+
+				if (found_tags.Contains (xname)) {
+					Report.Warning (1571, 2, member.Location,
+						"XML comment on `{0}' has a duplicate param tag for `{1}'",
+						member.GetSignatureForError (), xname);
+					continue;
+				}
+
+				found_tags.Add (xname);
+			}
+
+			if (found_tags != null) {
+				foreach (Parameter p in paramMember.Parameters.FixedParameters) {
+					if (!found_tags.Contains (p.Name) && !(p is ArglistParameter))
+						Report.Warning (1573, 4, member.Location,
+							"Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
+							p.Name, member.GetSignatureForError ());
+				}
+			}
+		}
+
+		//
+		// Outputs XML documentation comment from tokenized comments.
+		//
+		public bool OutputDocComment (string asmfilename, string xmlFileName)
+		{
+			XmlTextWriter w = null;
+			try {
+				w = new XmlTextWriter (xmlFileName, null);
+				w.Indentation = 4;
+				w.Formatting = Formatting.Indented;
+				w.WriteStartDocument ();
+				w.WriteStartElement ("doc");
+				w.WriteStartElement ("assembly");
+				w.WriteStartElement ("name");
+				w.WriteString (Path.GetFileNameWithoutExtension (asmfilename));
+				w.WriteEndElement (); // name
+				w.WriteEndElement (); // assembly
+				w.WriteStartElement ("members");
+				XmlCommentOutput = w;
+				module.GenerateDocComment (this);
+				w.WriteFullEndElement (); // members
+				w.WriteEndElement ();
+				w.WriteWhitespace (Environment.NewLine);
+				w.WriteEndDocument ();
+				return true;
+			} catch (Exception ex) {
+				Report.Error (1569, "Error generating XML documentation file `{0}' (`{1}')", xmlFileName, ex.Message);
+				return false;
+			} finally {
+				if (w != null)
+					w.Close ();
+			}
+		}
+	}
+
+	//
+	// Type lookup of documentation references uses context of type where
+	// the reference is used but type parameters from cref value
+	//
+	sealed class DocumentationMemberContext : IMemberContext
+	{
+		readonly MemberCore host;
+		MemberName contextName;
+
+		public DocumentationMemberContext (MemberCore host, MemberName contextName)
+		{
+			this.host = host;
+			this.contextName = contextName;
+		}
+
+		public TypeSpec CurrentType {
+			get {
+				return host.CurrentType;
+			}
+		}
+
+		public TypeParameters CurrentTypeParameters {
+			get {
+				return contextName.TypeParameters;
+			}
+		}
+
+		public MemberCore CurrentMemberDefinition {
+			get {
+				return host.CurrentMemberDefinition;
+			}
+		}
+
+		public bool IsObsolete {
+			get {
+				return false;
+			}
+		}
+
+		public bool IsUnsafe {
+			get {
+				return host.IsStatic;
+			}
+		}
+
+		public bool IsStatic {
+			get {
+				return host.IsStatic;
+			}
+		}
+
+		public ModuleContainer Module {
+			get {
+				return host.Module;
+			}
+		}
+
+		public string GetSignatureForError ()
+		{
+			return host.GetSignatureForError ();
+		}
+
+		public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
+		{
+			return null;
+		}
+
+		public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			if (arity == 0) {
+				var tp = CurrentTypeParameters;
+				if (tp != null) {
+					for (int i = 0; i < tp.Count; ++i) {
+						var t = tp[i];
+						if (t.Name == name) {
+							t.Type.DeclaredPosition = i;
+							return new TypeParameterExpr (t, loc);
+						}
+					}
+				}
+			}
+
+			return host.Parent.LookupNamespaceOrType (name, arity, mode, loc);
+		}
+
+		public FullNamedExpression LookupNamespaceAlias (string name)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+	class DocumentationParameter
+	{
+		public readonly Parameter.Modifier Modifier;
+		public FullNamedExpression Type;
+		TypeSpec type;
+
+		public DocumentationParameter (Parameter.Modifier modifier, FullNamedExpression type)
+			: this (type)
+		{
+			this.Modifier = modifier;
+		}
+
+		public DocumentationParameter (FullNamedExpression type)
+		{
+			this.Type = type;
+		}
+
+		public TypeSpec TypeSpec {
+			get {
+				return type;
+			}
+		}
+
+		public void Resolve (IMemberContext context)
+		{
+			type = Type.ResolveAsType (context);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/driver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/driver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/driver.cs	(revision 11807)
@@ -0,0 +1,475 @@
+//
+// driver.cs: The compiler command line driver.
+//
+// Authors:
+//   Miguel de Icaza (miguel@gnu.org)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Globalization;
+using System.Diagnostics;
+using System.Threading;
+
+namespace Mono.CSharp
+{
+	/// <summary>
+	///    The compiler driver.
+	/// </summary>
+	class Driver
+	{
+		readonly CompilerContext ctx;
+
+		public Driver (CompilerContext ctx)
+		{
+			this.ctx = ctx;
+		}
+
+		Report Report {
+			get {
+				return ctx.Report;
+			}
+		}
+
+		void tokenize_file (SourceFile sourceFile, ModuleContainer module, ParserSession session)
+		{
+			Stream input;
+
+			try {
+				input = File.OpenRead (sourceFile.Name);
+			} catch {
+				Report.Error (2001, "Source file `" + sourceFile.Name + "' could not be found");
+				return;
+			}
+
+			using (input){
+				SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding);
+				var file = new CompilationSourceFile (module, sourceFile);
+
+				Tokenizer lexer = new Tokenizer (reader, file, session, ctx.Report);
+				int token, tokens = 0, errors = 0;
+
+				while ((token = lexer.token ()) != Token.EOF){
+					tokens++;
+					if (token == Token.ERROR)
+						errors++;
+				}
+				Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
+			}
+			
+			return;
+		}
+
+		void Parse (ModuleContainer module)
+		{
+			bool tokenize_only = module.Compiler.Settings.TokenizeOnly;
+			var sources = module.Compiler.SourceFiles;
+
+			Location.Initialize (sources);
+
+			var session = new ParserSession {
+				UseJayGlobalArrays = true,
+				LocatedTokens = new LocatedToken[15000]
+			};
+
+			for (int i = 0; i < sources.Count; ++i) {
+				if (tokenize_only) {
+					tokenize_file (sources[i], module, session);
+				} else {
+					Parse (sources[i], module, session, Report);
+				}
+			}
+		}
+
+#if false
+		void ParseParallel (ModuleContainer module)
+		{
+			var sources = module.Compiler.SourceFiles;
+
+			Location.Initialize (sources);
+
+			var pcount = Environment.ProcessorCount;
+			var threads = new Thread[System.Math.Max (2, pcount - 1)];
+
+			for (int i = 0; i < threads.Length; ++i) {
+				var t = new Thread (l => {
+					var session = new ParserSession () {
+						//UseJayGlobalArrays = true,
+					};
+
+					var report = new Report (ctx, Report.Printer); // TODO: Implement flush at once printer
+
+					for (int ii = (int) l; ii < sources.Count; ii += threads.Length) {
+						Parse (sources[ii], module, session, report);
+					}
+
+					// TODO: Merge warning regions
+				});
+
+				t.Start (i);
+				threads[i] = t;
+			}
+
+			for (int t = 0; t < threads.Length; ++t) {
+				threads[t].Join ();
+			}
+		}
+#endif
+
+		public void Parse (SourceFile file, ModuleContainer module, ParserSession session, Report report)
+		{
+			Stream input;
+
+			try {
+				input = File.OpenRead (file.Name);
+			} catch {
+				report.Error (2001, "Source file `{0}' could not be found", file.Name);
+				return;
+			}
+
+			// Check 'MZ' header
+			if (input.ReadByte () == 77 && input.ReadByte () == 90) {
+
+				report.Error (2015, "Source file `{0}' is a binary file and not a text file", file.Name);
+				input.Close ();
+				return;
+			}
+
+			input.Position = 0;
+			SeekableStreamReader reader = new SeekableStreamReader (input, ctx.Settings.Encoding, session.StreamReaderBuffer);
+
+			Parse (reader, file, module, session, report);
+
+			if (ctx.Settings.GenerateDebugInfo && report.Errors == 0 && !file.HasChecksum) {
+				input.Position = 0;
+				var checksum = session.GetChecksumAlgorithm ();
+				file.SetChecksum (checksum.ComputeHash (input));
+			}
+
+			reader.Dispose ();
+			input.Close ();
+		}
+
+		public static CSharpParser Parse (SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report, int lineModifier = 0, int colModifier = 0)
+		{
+			var file = new CompilationSourceFile (module, sourceFile);
+			module.AddTypeContainer(file);
+
+			CSharpParser parser = new CSharpParser (reader, file, report, session);
+			parser.Lexer.Line += lineModifier;
+			parser.Lexer.Column += colModifier;
+			parser.Lexer.sbag = new SpecialsBag ();
+			parser.parse ();
+			return parser;
+		}
+
+		public static int Main (string[] args)
+		{
+			Location.InEmacs = Environment.GetEnvironmentVariable ("EMACS") == "t";
+
+			CommandLineParser cmd = new CommandLineParser (Console.Out);
+			var settings = cmd.ParseArguments (args);
+			if (settings == null)
+				return 1;
+
+			if (cmd.HasBeenStopped)
+				return 0;
+
+			Driver d = new Driver (new CompilerContext (settings, new ConsoleReportPrinter ()));
+
+			if (d.Compile () && d.Report.Errors == 0) {
+				if (d.Report.Warnings > 0) {
+					Console.WriteLine ("Compilation succeeded - {0} warning(s)", d.Report.Warnings);
+				}
+				Environment.Exit (0);
+				return 0;
+			}
+			
+			
+			Console.WriteLine("Compilation failed: {0} error(s), {1} warnings",
+				d.Report.Errors, d.Report.Warnings);
+			Environment.Exit (1);
+			return 1;
+		}
+
+		public static string GetPackageFlags (string packages, Report report)
+		{
+			ProcessStartInfo pi = new ProcessStartInfo ();
+			pi.FileName = "pkg-config";
+			pi.RedirectStandardOutput = true;
+			pi.UseShellExecute = false;
+			pi.Arguments = "--libs " + packages;
+			Process p = null;
+			try {
+				p = Process.Start (pi);
+			} catch (Exception e) {
+				if (report == null)
+					throw;
+
+				report.Error (-27, "Couldn't run pkg-config: " + e.Message);
+				return null;
+			}
+			
+			if (p.StandardOutput == null) {
+				if (report == null)
+					throw new ApplicationException ("Specified package did not return any information");
+
+				report.Warning (-27, 1, "Specified package did not return any information");
+				p.Close ();
+				return null;
+			}
+
+			string pkgout = p.StandardOutput.ReadToEnd ();
+			p.WaitForExit ();
+			if (p.ExitCode != 0) {
+				if (report == null)
+					throw new ApplicationException (pkgout);
+
+				report.Error (-27, "Error running pkg-config. Check the above output.");
+				p.Close ();
+				return null;
+			}
+
+			p.Close ();
+			return pkgout;
+		}
+
+		//
+		// Main compilation method
+		//
+		public bool Compile ()
+		{
+			var settings = ctx.Settings;
+
+			//
+			// If we are an exe, require a source file for the entry point or
+			// if there is nothing to put in the assembly, and we are not a library
+			//
+			if (settings.FirstSourceFile == null &&
+				((settings.Target == Target.Exe || settings.Target == Target.WinExe || settings.Target == Target.Module) ||
+				settings.Resources == null)) {
+				Report.Error (2008, "No files to compile were specified");
+				return false;
+			}
+
+			if (settings.Platform == Platform.AnyCPU32Preferred && (settings.Target == Target.Library || settings.Target == Target.Module)) {
+				Report.Error (4023, "Platform option `anycpu32bitpreferred' is valid only for executables");
+				return false;
+			}
+
+			TimeReporter tr = new TimeReporter (settings.Timestamps);
+			ctx.TimeReporter = tr;
+			tr.StartTotal ();
+
+			var module = new ModuleContainer (ctx);
+			RootContext.ToplevelTypes = module;
+
+			tr.Start (TimeReporter.TimerType.ParseTotal);
+			Parse (module);
+			tr.Stop (TimeReporter.TimerType.ParseTotal);
+
+			if (Report.Errors > 0)
+				return false;
+
+			if (settings.TokenizeOnly || settings.ParseOnly) {
+				tr.StopTotal ();
+				tr.ShowStats ();
+				return true;
+			}
+
+			var output_file = settings.OutputFile;
+			string output_file_name;
+			if (output_file == null) {
+				var source_file = settings.FirstSourceFile;
+
+				if (source_file == null) {
+					Report.Error (1562, "If no source files are specified you must specify the output file with -out:");
+					return false;
+				}
+
+				output_file_name = source_file.Name;
+				int pos = output_file_name.LastIndexOf ('.');
+
+				if (pos > 0)
+					output_file_name = output_file_name.Substring (0, pos);
+				
+				output_file_name += settings.TargetExt;
+				output_file = output_file_name;
+			} else {
+				output_file_name = Path.GetFileName (output_file);
+
+				if (string.IsNullOrEmpty (Path.GetFileNameWithoutExtension (output_file_name)) ||
+					output_file_name.IndexOfAny (Path.GetInvalidFileNameChars ()) >= 0) {
+					Report.Error (2021, "Output file name is not valid");
+					return false;
+				}
+			}
+
+#if STATIC
+			var importer = new StaticImporter (module);
+			var references_loader = new StaticLoader (importer, ctx);
+
+			tr.Start (TimeReporter.TimerType.AssemblyBuilderSetup);
+			var assembly = new AssemblyDefinitionStatic (module, references_loader, output_file_name, output_file);
+			assembly.Create (references_loader.Domain);
+			tr.Stop (TimeReporter.TimerType.AssemblyBuilderSetup);
+
+			// Create compiler types first even before any referenced
+			// assembly is loaded to allow forward referenced types from
+			// loaded assembly into compiled builder to be resolved
+			// correctly
+			tr.Start (TimeReporter.TimerType.CreateTypeTotal);
+			module.CreateContainer ();
+			importer.AddCompiledAssembly (assembly);
+			references_loader.CompiledAssembly = assembly;
+			tr.Stop (TimeReporter.TimerType.CreateTypeTotal);
+
+			references_loader.LoadReferences (module);
+
+			tr.Start (TimeReporter.TimerType.PredefinedTypesInit);
+			if (!ctx.BuiltinTypes.CheckDefinitions (module))
+				return false;
+
+			tr.Stop (TimeReporter.TimerType.PredefinedTypesInit);
+
+			references_loader.LoadModules (assembly, module.GlobalRootNamespace);
+#else
+			var assembly = new AssemblyDefinitionDynamic (module, output_file_name, output_file);
+			module.SetDeclaringAssembly (assembly);
+
+			var importer = new ReflectionImporter (module, ctx.BuiltinTypes);
+			assembly.Importer = importer;
+
+			var loader = new DynamicLoader (importer, ctx);
+			loader.LoadReferences (module);
+
+			if (!ctx.BuiltinTypes.CheckDefinitions (module))
+				return false;
+
+			if (!assembly.Create (AppDomain.CurrentDomain, AssemblyBuilderAccess.Save))
+				return false;
+
+			module.CreateContainer ();
+
+			loader.LoadModules (assembly, module.GlobalRootNamespace);
+#endif
+			module.InitializePredefinedTypes ();
+
+			tr.Start (TimeReporter.TimerType.ModuleDefinitionTotal);
+			module.Define ();
+			tr.Stop (TimeReporter.TimerType.ModuleDefinitionTotal);
+
+			if (Report.Errors > 0)
+				return false;
+
+			if (settings.DocumentationFile != null) {
+				var doc = new DocumentationBuilder (module);
+				doc.OutputDocComment (output_file, settings.DocumentationFile);
+			}
+
+			assembly.Resolve ();
+			
+			if (Report.Errors > 0)
+				return false;
+
+
+			tr.Start (TimeReporter.TimerType.EmitTotal);
+			assembly.Emit ();
+			tr.Stop (TimeReporter.TimerType.EmitTotal);
+
+			if (Report.Errors > 0){
+				return false;
+			}
+
+			tr.Start (TimeReporter.TimerType.CloseTypes);
+			module.CloseContainer ();
+			tr.Stop (TimeReporter.TimerType.CloseTypes);
+
+			tr.Start (TimeReporter.TimerType.Resouces);
+			if (!settings.WriteMetadataOnly)
+				assembly.EmbedResources ();
+			tr.Stop (TimeReporter.TimerType.Resouces);
+
+			if (Report.Errors > 0)
+				return false;
+
+			assembly.Save ();
+
+#if STATIC
+			references_loader.Dispose ();
+#endif
+			tr.StopTotal ();
+			tr.ShowStats ();
+
+			return Report.Errors == 0;
+		}
+	}
+
+	public class CompilerCompilationUnit {
+		public ModuleContainer ModuleCompiled { get; set; }
+		public LocationsBag LocationsBag { get; set; }
+		public SpecialsBag SpecialsBag { get; set; }
+		public IDictionary<string, bool> Conditionals { get; set; }
+		public object LastYYValue { get; set; }
+	}
+
+	//
+	// This is the only public entry point
+	//
+	public class CompilerCallableEntryPoint : MarshalByRefObject
+	{
+		public static bool InvokeCompiler (string [] args, TextWriter error)
+		{
+			try {
+				CommandLineParser cmd = new CommandLineParser (error);
+				var setting = cmd.ParseArguments (args);
+				if (setting == null)
+					return false;
+
+				var d = new Driver (new CompilerContext (setting, new StreamReportPrinter (error)));
+				return d.Compile ();
+			} finally {
+				Reset ();
+			}
+		}
+
+		public static int[] AllWarningNumbers {
+			get {
+				return Report.AllWarnings;
+			}
+		}
+
+		public static void Reset ()
+		{
+			Reset (true);
+		}
+
+		public static void PartialReset ()
+		{
+			Reset (false);
+		}
+		
+		public static void Reset (bool full_flag)
+		{
+			Location.Reset ();
+			
+			if (!full_flag)
+				return;
+
+			Linq.QueryBlock.TransparentParameter.Reset ();
+			TypeInfo.Reset ();
+		}
+	}
+	
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/dynamic.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/dynamic.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/dynamic.cs	(revision 11807)
@@ -0,0 +1,986 @@
+﻿//
+// dynamic.cs: support for dynamic expressions
+//
+// Authors: Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2009 Novell, Inc
+// Copyright 2011 Xamarin Inc.
+//
+
+using System;
+using System.Linq;
+using SLE = System.Linq.Expressions;
+
+#if NET_4_0 || MOBILE_DYNAMIC
+using System.Dynamic;
+#endif
+
+namespace Mono.CSharp
+{
+	//
+	// A copy of Microsoft.CSharp/Microsoft.CSharp.RuntimeBinder/CSharpBinderFlags.cs
+	// has to be kept in sync
+	//
+	[Flags]
+	public enum CSharpBinderFlags
+	{
+		None = 0,
+		CheckedContext = 1,
+		InvokeSimpleName = 1 << 1,
+		InvokeSpecialName = 1 << 2,
+		BinaryOperationLogical = 1 << 3,
+		ConvertExplicit = 1 << 4,
+		ConvertArrayIndex = 1 << 5,
+		ResultIndexed = 1 << 6,
+		ValueFromCompoundAssignment = 1 << 7,
+		ResultDiscarded = 1 << 8
+	}
+
+	//
+	// Type expression with internal dynamic type symbol
+	//
+	class DynamicTypeExpr : TypeExpr
+	{
+		public DynamicTypeExpr (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments)
+		{
+			eclass = ExprClass.Type;
+			type = ec.Module.Compiler.BuiltinTypes.Dynamic;
+			return type;
+		}
+	}
+
+	#region Dynamic runtime binder expressions
+
+	//
+	// Expression created from runtime dynamic object value by dynamic binder
+	//
+	public class RuntimeValueExpression : Expression, IDynamicAssign, IMemoryLocation
+	{
+#if !NET_4_0 && !MOBILE_DYNAMIC
+		public class DynamicMetaObject
+		{
+			public TypeSpec RuntimeType;
+			public TypeSpec LimitType;
+			public SLE.Expression Expression;
+		}
+#endif
+
+		readonly DynamicMetaObject obj;
+
+		public RuntimeValueExpression (DynamicMetaObject obj, TypeSpec type)
+		{
+			this.obj = obj;
+			this.type = type;
+			this.eclass = ExprClass.Variable;
+		}
+
+		#region Properties
+
+		public bool IsSuggestionOnly { get; set; }
+
+		public DynamicMetaObject MetaObject {
+			get { return obj; }
+		}
+
+		#endregion
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ();
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new NotImplementedException ();
+		}
+
+		#region IAssignMethod Members
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			throw new NotImplementedException ();
+		}
+
+		#endregion
+
+		public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
+		{
+			return obj.Expression;
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+
+#if NET_4_0 || MOBILE_DYNAMIC
+				if (type.IsStruct && !obj.Expression.Type.IsValueType)
+					return SLE.Expression.Unbox (obj.Expression, type.GetMetaInfo ());
+
+				if (obj.Expression.NodeType == SLE.ExpressionType.Parameter) {
+					if (((SLE.ParameterExpression) obj.Expression).IsByRef)
+						return obj.Expression;
+				}
+	#endif
+
+				return SLE.Expression.Convert (obj.Expression, type.GetMetaInfo ());
+#endif
+		}
+	}
+
+	//
+	// Wraps runtime dynamic expression into expected type. Needed
+	// to satify expected type check by dynamic binder and no conversion
+	// is required (ResultDiscarded).
+	//
+	public class DynamicResultCast : ShimExpression
+	{
+		public DynamicResultCast (TypeSpec type, Expression expr)
+			: base (expr)
+		{
+			this.type = type;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			expr = expr.Resolve (ec);
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+#if NET_4_0 || MOBILE_DYNAMIC
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.Block (expr.MakeExpression (ctx), SLE.Expression.Default (type.GetMetaInfo ()));
+#endif
+		}
+#endif
+	}
+
+	#endregion
+
+	//
+	// Creates dynamic binder expression
+	//
+	interface IDynamicBinder
+	{
+		Expression CreateCallSiteBinder (ResolveContext ec, Arguments args);
+	}
+
+	//
+	// Extends standard assignment interface for expressions
+	// supported by dynamic resolver
+	//
+	interface IDynamicAssign : IAssignMethod
+	{
+		SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source);
+	}
+
+	//
+	// Base dynamic expression statement creator
+	//
+	class DynamicExpressionStatement : ExpressionStatement
+	{
+		//
+		// Binder flag dynamic constant, the value is combination of
+		// flags known at resolve stage and flags known only at emit
+		// stage
+		//
+		protected class BinderFlags : EnumConstant
+		{
+			readonly DynamicExpressionStatement statement;
+			readonly CSharpBinderFlags flags;
+
+			public BinderFlags (CSharpBinderFlags flags, DynamicExpressionStatement statement)
+				: base (statement.loc)
+			{
+				this.flags = flags;
+				this.statement = statement;
+				eclass = 0;
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				Child = new IntConstant (ec.BuiltinTypes, (int) (flags | statement.flags), statement.loc);
+
+				type = ec.Module.PredefinedTypes.BinderFlags.Resolve ();
+				eclass = Child.eclass;
+				return this;
+			}
+		}
+
+		readonly Arguments arguments;
+		protected IDynamicBinder binder;
+		protected Expression binder_expr;
+
+		// Used by BinderFlags
+		protected CSharpBinderFlags flags;
+
+		TypeSpec binder_type;
+		TypeParameters context_mvars;
+
+		public DynamicExpressionStatement (IDynamicBinder binder, Arguments args, Location loc)
+		{
+			this.binder = binder;
+			this.arguments = args;
+			this.loc = loc;
+		}
+
+		public Arguments Arguments {
+			get {
+				return arguments;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return arguments.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (1963, loc, "An expression tree cannot contain a dynamic operation");
+			return null;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			if (DoResolveCore (rc))
+				binder_expr = binder.CreateCallSiteBinder (rc, arguments);
+
+			return this;
+		}
+
+		protected bool DoResolveCore (ResolveContext rc)
+		{
+			if (rc.CurrentTypeParameters != null && rc.CurrentTypeParameters[0].IsMethodTypeParameter)
+				context_mvars = rc.CurrentTypeParameters;
+
+			int errors = rc.Report.Errors;
+			var pt = rc.Module.PredefinedTypes;
+
+			binder_type = pt.Binder.Resolve ();
+			pt.CallSite.Resolve ();
+			pt.CallSiteGeneric.Resolve ();
+
+			eclass = ExprClass.Value;
+
+			if (type == null)
+				type = rc.BuiltinTypes.Dynamic;
+
+			if (rc.Report.Errors == errors)
+				return true;
+
+			rc.Report.Error (1969, loc,
+				"Dynamic operation cannot be compiled without `Microsoft.CSharp.dll' assembly reference");
+			return false;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			EmitCall (ec, binder_expr, arguments,  false);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			EmitCall (ec, binder_expr, arguments, true);
+		}
+
+		protected void EmitCall (EmitContext ec, Expression binder, Arguments arguments, bool isStatement)
+		{
+			//
+			// This method generates all internal infrastructure for a dynamic call. The
+			// reason why it's quite complicated is the mixture of dynamic and anonymous
+			// methods. Dynamic itself requires a temporary class (ContainerX) and anonymous
+			// methods can generate temporary storey as well (AnonStorey). Handling MVAR
+			// type parameters rewrite is non-trivial in such case as there are various
+			// combinations possible therefore the mutator is not straightforward. Secondly
+			// we need to keep both MVAR(possibly VAR for anon storey) and type VAR to emit
+			// correct Site field type and its access from EmitContext.
+			//
+
+			int dyn_args_count = arguments == null ? 0 : arguments.Count;
+			int default_args = isStatement ? 1 : 2;
+			var module = ec.Module;
+
+			bool has_ref_out_argument = false;
+			var targs = new TypeExpression[dyn_args_count + default_args];
+			targs[0] = new TypeExpression (module.PredefinedTypes.CallSite.TypeSpec, loc);
+
+			TypeExpression[] targs_for_instance = null;
+			TypeParameterMutator mutator;
+
+			var site_container = ec.CreateDynamicSite ();
+
+			if (context_mvars != null) {
+				TypeParameters tparam;
+				TypeContainer sc = site_container;
+				do {
+					tparam = sc.CurrentTypeParameters;
+					sc = sc.Parent;
+				} while (tparam == null);
+
+				mutator = new TypeParameterMutator (context_mvars, tparam);
+
+				if (!ec.IsAnonymousStoreyMutateRequired) {
+					targs_for_instance = new TypeExpression[targs.Length];
+					targs_for_instance[0] = targs[0];
+				}
+			} else {
+				mutator = null;
+			}
+
+			for (int i = 0; i < dyn_args_count; ++i) {
+				Argument a = arguments[i];
+				if (a.ArgType == Argument.AType.Out || a.ArgType == Argument.AType.Ref)
+					has_ref_out_argument = true;
+
+				var t = a.Type;
+
+				// Convert any internal type like dynamic or null to object
+				if (t.Kind == MemberKind.InternalCompilerType)
+					t = ec.BuiltinTypes.Object;
+
+				if (targs_for_instance != null)
+					targs_for_instance[i + 1] = new TypeExpression (t, loc);
+
+				if (mutator != null)
+					t = t.Mutate (mutator);
+
+				targs[i + 1] = new TypeExpression (t, loc);
+			}
+
+			TypeExpr del_type = null;
+			TypeExpr del_type_instance_access = null;
+			if (!has_ref_out_argument) {
+				string d_name = isStatement ? "Action" : "Func";
+
+				TypeSpec te = null;
+				Namespace type_ns = module.GlobalRootNamespace.GetNamespace ("System", true);
+				if (type_ns != null) {
+					te = type_ns.LookupType (module, d_name, dyn_args_count + default_args, LookupMode.Normal, loc);
+				}
+
+				if (te != null) {
+					if (!isStatement) {
+						var t = type;
+						if (t.Kind == MemberKind.InternalCompilerType)
+							t = ec.BuiltinTypes.Object;
+
+						if (targs_for_instance != null)
+							targs_for_instance[targs_for_instance.Length - 1] = new TypeExpression (t, loc);
+
+						if (mutator != null)
+							t = t.Mutate (mutator);
+
+						targs[targs.Length - 1] = new TypeExpression (t, loc);
+					}
+
+					del_type = new GenericTypeExpr (te, new TypeArguments (targs), loc);
+					if (targs_for_instance != null)
+						del_type_instance_access = new GenericTypeExpr (te, new TypeArguments (targs_for_instance), loc);
+					else
+						del_type_instance_access = del_type;
+				}
+			}
+
+			//
+			// Create custom delegate when no appropriate predefined delegate has been found
+			//
+			Delegate d;
+			if (del_type == null) {
+				TypeSpec rt = isStatement ? ec.BuiltinTypes.Void : type;
+				Parameter[] p = new Parameter[dyn_args_count + 1];
+				p[0] = new Parameter (targs[0], "p0", Parameter.Modifier.NONE, null, loc);
+
+				var site = ec.CreateDynamicSite ();
+				int index = site.Containers == null ? 0 : site.Containers.Count;
+
+				if (mutator != null)
+					rt = mutator.Mutate (rt);
+
+				for (int i = 1; i < dyn_args_count + 1; ++i) {
+					p[i] = new Parameter (targs[i], "p" + i.ToString ("X"), arguments[i - 1].Modifier, null, loc);
+				}
+
+				d = new Delegate (site, new TypeExpression (rt, loc),
+					Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED,
+					new MemberName ("Container" + index.ToString ("X")),
+					new ParametersCompiled (p), null);
+
+				d.CreateContainer ();
+				d.DefineContainer ();
+				d.Define ();
+				d.PrepareEmit ();
+
+				site.AddTypeContainer (d);
+
+				//
+				// Add new container to inflated site container when the
+				// member cache already exists
+				//
+				if (site.CurrentType is InflatedTypeSpec && index > 0)
+					site.CurrentType.MemberCache.AddMember (d.CurrentType);
+
+				del_type = new TypeExpression (d.CurrentType, loc);
+				if (targs_for_instance != null) {
+					del_type_instance_access = null;
+				} else {
+					del_type_instance_access = del_type;
+				}
+			} else {
+				d = null;
+			}
+
+			var site_type_decl = new GenericTypeExpr (module.PredefinedTypes.CallSiteGeneric.TypeSpec, new TypeArguments (del_type), loc);
+			var field = site_container.CreateCallSiteField (site_type_decl, loc);
+			if (field == null)
+				return;
+
+			if (del_type_instance_access == null) {
+				var dt = d.CurrentType.DeclaringType.MakeGenericType (module, context_mvars.Types);
+				del_type_instance_access = new TypeExpression (MemberCache.GetMember (dt, d.CurrentType), loc);
+			}
+
+			var instanceAccessExprType = new GenericTypeExpr (module.PredefinedTypes.CallSiteGeneric.TypeSpec,
+				new TypeArguments (del_type_instance_access), loc);
+
+			if (instanceAccessExprType.ResolveAsType (ec.MemberContext) == null)
+				return;
+
+			bool inflate_using_mvar = context_mvars != null && ec.IsAnonymousStoreyMutateRequired;
+
+			TypeSpec gt;
+			if (inflate_using_mvar || context_mvars == null) {
+				gt = site_container.CurrentType;
+			} else {
+				gt = site_container.CurrentType.MakeGenericType (module, context_mvars.Types);
+			}
+
+			// When site container already exists the inflated version has to be
+			// updated manually to contain newly created field
+			if (gt is InflatedTypeSpec && site_container.AnonymousMethodsCounter > 1) {
+				var tparams = gt.MemberDefinition.TypeParametersCount > 0 ? gt.MemberDefinition.TypeParameters : TypeParameterSpec.EmptyTypes;
+				var inflator = new TypeParameterInflator (module, gt, tparams, gt.TypeArguments);
+				gt.MemberCache.AddMember (field.InflateMember (inflator));
+			}
+
+			FieldExpr site_field_expr = new FieldExpr (MemberCache.GetMember (gt, field), loc);
+
+			BlockContext bc = new BlockContext (ec.MemberContext, null, ec.BuiltinTypes.Void);
+
+			Arguments args = new Arguments (1);
+			args.Add (new Argument (binder));
+			StatementExpression s = new StatementExpression (new SimpleAssign (site_field_expr, new Invocation (new MemberAccess (instanceAccessExprType, "Create"), args)));
+
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				if (s.Resolve (bc)) {
+					Statement init = new If (new Binary (Binary.Operator.Equality, site_field_expr, new NullLiteral (loc)), s, loc);
+					init.Emit (ec);
+				}
+
+				args = new Arguments (1 + dyn_args_count);
+				args.Add (new Argument (site_field_expr));
+				if (arguments != null) {
+					int arg_pos = 1;
+					foreach (Argument a in arguments) {
+						if (a is NamedArgument) {
+							// Name is not valid in this context
+							args.Add (new Argument (a.Expr, a.ArgType));
+						} else {
+							args.Add (a);
+						}
+
+						if (inflate_using_mvar && a.Type != targs[arg_pos].Type)
+							a.Expr.Type = targs[arg_pos].Type;
+
+						++arg_pos;
+					}
+				}
+
+				Expression target = new DelegateInvocation (new MemberAccess (site_field_expr, "Target", loc).Resolve (bc), args, false, loc).Resolve (bc);
+				if (target != null)
+					target.Emit (ec);
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			arguments.FlowAnalysis (fc);
+		}
+
+		public static MemberAccess GetBinderNamespace (Location loc)
+		{
+			return new MemberAccess (new MemberAccess (
+				new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "Microsoft", loc), "CSharp", loc), "RuntimeBinder", loc);
+		}
+
+		protected MemberAccess GetBinder (string name, Location loc)
+		{
+			return new MemberAccess (new TypeExpression (binder_type, loc), name, loc);
+		}
+	}
+
+	//
+	// Dynamic member access compound assignment for events
+	//
+	class DynamicEventCompoundAssign : ExpressionStatement
+	{
+		class IsEvent : DynamicExpressionStatement, IDynamicBinder
+		{
+			string name;
+
+			public IsEvent (string name, Arguments args, Location loc)
+				: base (null, args, loc)
+			{
+				this.name = name;
+				binder = this;
+			}
+
+			public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+			{
+				type = ec.BuiltinTypes.Bool;
+
+				Arguments binder_args = new Arguments (3);
+
+				binder_args.Add (new Argument (new BinderFlags (0, this)));
+				binder_args.Add (new Argument (new StringLiteral (ec.BuiltinTypes, name, loc)));
+				binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+
+				return new Invocation (GetBinder ("IsEvent", loc), binder_args);
+			}
+		}
+
+		Expression condition;
+		ExpressionStatement invoke, assign;
+
+		public DynamicEventCompoundAssign (string name, Arguments args, ExpressionStatement assignment, ExpressionStatement invoke, Location loc)
+		{
+			condition = new IsEvent (name, args, loc);
+			this.invoke = invoke;
+			this.assign = assignment;
+			this.loc = loc;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return condition.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			type = rc.BuiltinTypes.Dynamic;
+			eclass = ExprClass.Value;
+			condition = condition.Resolve (rc);
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			var rc = new ResolveContext (ec.MemberContext);
+			var expr = new Conditional (new BooleanExpression (condition), invoke, assign, loc).Resolve (rc);
+			expr.Emit (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			var stmt = new If (condition, new StatementExpression (invoke), new StatementExpression (assign), loc);
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				stmt.Emit (ec);
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			invoke.FlowAnalysis (fc);
+		}
+	}
+
+	class DynamicConversion : DynamicExpressionStatement, IDynamicBinder
+	{
+		public DynamicConversion (TypeSpec targetType, CSharpBinderFlags flags, Arguments args, Location loc)
+			: base (null, args, loc)
+		{
+			type = targetType;
+			base.flags = flags;
+			base.binder = this;
+		}
+
+		public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+		{
+			Arguments binder_args = new Arguments (3);
+
+			flags |= ec.HasSet (ResolveContext.Options.CheckedScope) ? CSharpBinderFlags.CheckedContext : 0;
+
+			binder_args.Add (new Argument (new BinderFlags (flags, this)));
+			binder_args.Add (new Argument (new TypeOf (type, loc)));
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+			return new Invocation (GetBinder ("Convert", loc), binder_args);
+		}
+	}
+
+	class DynamicConstructorBinder : DynamicExpressionStatement, IDynamicBinder
+	{
+		public DynamicConstructorBinder (TypeSpec type, Arguments args, Location loc)
+			: base (null, args, loc)
+		{
+			this.type = type;
+			base.binder = this;
+		}
+
+		public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+		{
+			Arguments binder_args = new Arguments (3);
+
+			binder_args.Add (new Argument (new BinderFlags (0, this)));
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+			binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
+
+			return new Invocation (GetBinder ("InvokeConstructor", loc), binder_args);
+		}
+	}
+
+	class DynamicIndexBinder : DynamicMemberAssignable
+	{
+		bool can_be_mutator;
+
+		public DynamicIndexBinder (Arguments args, Location loc)
+			: base (args, loc)
+		{
+		}
+
+		public DynamicIndexBinder (CSharpBinderFlags flags, Arguments args, Location loc)
+			: this (args, loc)
+		{
+			base.flags = flags;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			can_be_mutator = true;
+			return base.DoResolve (ec);
+		}
+
+		protected override Expression CreateCallSiteBinder (ResolveContext ec, Arguments args, bool isSet)
+		{
+			Arguments binder_args = new Arguments (3);
+
+			binder_args.Add (new Argument (new BinderFlags (flags, this)));
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+			binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
+
+			isSet |= (flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0;
+			return new Invocation (GetBinder (isSet ? "SetIndex" : "GetIndex", loc), binder_args);
+		}
+
+		protected override Arguments CreateSetterArguments (ResolveContext rc, Expression rhs)
+		{
+			//
+			// Indexer has arguments which complicates things as the setter and getter
+			// are called in two steps when unary mutator is used. We have to make a
+			// copy of all variable arguments to not duplicate any side effect.
+			//
+			// ++d[++arg, Foo ()]
+			//
+
+			if (!can_be_mutator)
+				return base.CreateSetterArguments (rc, rhs);
+
+			var setter_args = new Arguments (Arguments.Count + 1);
+			for (int i = 0; i < Arguments.Count; ++i) {
+				var expr = Arguments[i].Expr;
+
+				if (expr is Constant || expr is VariableReference || expr is This) {
+					setter_args.Add (Arguments [i]);
+					continue;
+				}
+
+				LocalVariable temp = LocalVariable.CreateCompilerGenerated (expr.Type, rc.CurrentBlock, loc);
+				expr = new SimpleAssign (temp.CreateReferenceExpression (rc, expr.Location), expr).Resolve (rc);
+				Arguments[i].Expr = temp.CreateReferenceExpression (rc, expr.Location).Resolve (rc);
+				setter_args.Add (Arguments [i].Clone (expr));
+			}
+
+			setter_args.Add (new Argument (rhs));
+			return setter_args;
+		}
+	}
+
+	class DynamicInvocation : DynamicExpressionStatement, IDynamicBinder
+	{
+		readonly ATypeNameExpression member;
+
+		public DynamicInvocation (ATypeNameExpression member, Arguments args, Location loc)
+			: base (null, args, loc)
+		{
+			base.binder = this;
+			this.member = member;
+		}
+
+		public static DynamicInvocation CreateSpecialNameInvoke (ATypeNameExpression member, Arguments args, Location loc)
+		{
+			return new DynamicInvocation (member, args, loc) {
+				flags = CSharpBinderFlags.InvokeSpecialName
+			};
+		}
+
+		public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+		{
+			Arguments binder_args = new Arguments (member != null ? 5 : 3);
+			bool is_member_access = member is MemberAccess;
+
+			CSharpBinderFlags call_flags;
+			if (!is_member_access && member is SimpleName) {
+				call_flags = CSharpBinderFlags.InvokeSimpleName;
+				is_member_access = true;
+			} else {
+				call_flags = 0;
+			}
+
+			binder_args.Add (new Argument (new BinderFlags (call_flags, this)));
+
+			if (is_member_access)
+				binder_args.Add (new Argument (new StringLiteral (ec.BuiltinTypes, member.Name, member.Location)));
+
+			if (member != null && member.HasTypeArguments) {
+				TypeArguments ta = member.TypeArguments;
+				if (ta.Resolve (ec)) {
+					var targs = new ArrayInitializer (ta.Count, loc);
+					foreach (TypeSpec t in ta.Arguments)
+						targs.Add (new TypeOf (t, loc));
+
+					binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (targs, loc)));
+				}
+			} else if (is_member_access) {
+				binder_args.Add (new Argument (new NullLiteral (loc)));
+			}
+
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+
+			Expression real_args;
+			if (args == null) {
+				// Cannot be null because .NET trips over
+				real_args = new ArrayCreation (
+					new MemberAccess (GetBinderNamespace (loc), "CSharpArgumentInfo", loc),
+					new ArrayInitializer (0, loc), loc);
+			} else {
+				real_args = new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc);
+			}
+
+			binder_args.Add (new Argument (real_args));
+
+			return new Invocation (GetBinder (is_member_access ? "InvokeMember" : "Invoke", loc), binder_args);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			flags |= CSharpBinderFlags.ResultDiscarded;
+			base.EmitStatement (ec);
+		}
+	}
+
+	class DynamicMemberBinder : DynamicMemberAssignable
+	{
+		readonly string name;
+
+		public DynamicMemberBinder (string name, Arguments args, Location loc)
+			: base (args, loc)
+		{
+			this.name = name;
+		}
+
+		public DynamicMemberBinder (string name, CSharpBinderFlags flags, Arguments args, Location loc)
+			: this (name, args, loc)
+		{
+			base.flags = flags;
+		}
+
+		protected override Expression CreateCallSiteBinder (ResolveContext ec, Arguments args, bool isSet)
+		{
+			Arguments binder_args = new Arguments (4);
+
+			binder_args.Add (new Argument (new BinderFlags (flags, this)));
+			binder_args.Add (new Argument (new StringLiteral (ec.BuiltinTypes, name, loc)));
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+			binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
+
+			isSet |= (flags & CSharpBinderFlags.ValueFromCompoundAssignment) != 0;
+			return new Invocation (GetBinder (isSet ? "SetMember" : "GetMember", loc), binder_args);
+		}
+	}
+
+	//
+	// Any member binder which can be source and target of assignment
+	//
+	abstract class DynamicMemberAssignable : DynamicExpressionStatement, IDynamicBinder, IAssignMethod
+	{
+		Expression setter;
+		Arguments setter_args;
+
+		protected DynamicMemberAssignable (Arguments args, Location loc)
+			: base (null, args, loc)
+		{
+			base.binder = this;
+		}
+
+		public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+		{
+			//
+			// DoResolve always uses getter
+			//
+			return CreateCallSiteBinder (ec, args, false);
+		}
+
+		protected abstract Expression CreateCallSiteBinder (ResolveContext ec, Arguments args, bool isSet);
+
+		protected virtual Arguments CreateSetterArguments (ResolveContext rc, Expression rhs)
+		{
+			var setter_args = new Arguments (Arguments.Count + 1);
+			setter_args.AddRange (Arguments);
+			setter_args.Add (new Argument (rhs));
+			return setter_args;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			if (right_side == EmptyExpression.OutAccess) {
+				right_side.DoResolveLValue (rc, this);
+				return null;
+			}
+
+			if (DoResolveCore (rc)) {
+				setter_args = CreateSetterArguments (rc, right_side);
+				setter = CreateCallSiteBinder (rc, setter_args, true);
+			}
+
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// It's null for ResolveLValue used without assignment
+			if (binder_expr == null)
+				EmitCall (ec, setter, Arguments, false);
+			else
+				base.Emit (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			// It's null for ResolveLValue used without assignment
+			if (binder_expr == null)
+				EmitCall (ec, setter, Arguments, true);
+			else
+				base.EmitStatement (ec);
+		}
+
+		#region IAssignMethod Members
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			EmitCall (ec, setter, setter_args, !leave_copy);
+		}
+
+		#endregion
+	}
+
+	class DynamicUnaryConversion : DynamicExpressionStatement, IDynamicBinder
+	{
+		readonly string name;
+
+		public DynamicUnaryConversion (string name, Arguments args, Location loc)
+			: base (null, args, loc)
+		{
+			this.name = name;
+			base.binder = this;
+		}
+
+		public static DynamicUnaryConversion CreateIsTrue (ResolveContext rc, Arguments args, Location loc)
+		{
+			return new DynamicUnaryConversion ("IsTrue", args, loc) { type = rc.BuiltinTypes.Bool };
+		}
+
+		public static DynamicUnaryConversion CreateIsFalse (ResolveContext rc, Arguments args, Location loc)
+		{
+			return new DynamicUnaryConversion ("IsFalse", args, loc) { type = rc.BuiltinTypes.Bool };
+		}
+
+		public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+		{
+			Arguments binder_args = new Arguments (4);
+
+			MemberAccess sle = new MemberAccess (new MemberAccess (
+				new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
+
+			var flags = ec.HasSet (ResolveContext.Options.CheckedScope) ? CSharpBinderFlags.CheckedContext : 0;
+
+			binder_args.Add (new Argument (new BinderFlags (flags, this)));
+			binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), name, loc)));
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));
+			binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
+
+			return new Invocation (GetBinder ("UnaryOperation", loc), binder_args);
+		}
+	}
+
+	sealed class DynamicSiteClass : HoistedStoreyClass
+	{
+		public DynamicSiteClass (TypeDefinition parent, MemberBase host, TypeParameters tparams)
+			: base (parent, MakeMemberName (host, "DynamicSite", parent.DynamicSitesCounter, tparams, Location.Null), tparams, Modifiers.STATIC, MemberKind.Class)
+		{
+			parent.DynamicSitesCounter++;
+		}
+
+		public FieldSpec CreateCallSiteField (FullNamedExpression type, Location loc)
+		{
+			int index = AnonymousMethodsCounter++;
+			Field f = new HoistedField (this, type, Modifiers.PUBLIC | Modifiers.STATIC, "Site" + index.ToString ("X"), null, loc);
+			f.Define ();
+
+			AddField (f);
+			return f.Spec;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/ecore.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/ecore.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/ecore.cs	(revision 11807)
@@ -0,0 +1,7426 @@
+//
+// ecore.cs: Core of the Expression representation for the intermediate tree.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011-2012 Xamarin Inc.
+//
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using SLE = System.Linq.Expressions;
+using System.Linq;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	/// <remarks>
+	///   The ExprClass class contains the is used to pass the 
+	///   classification of an expression (value, variable, namespace,
+	///   type, method group, property access, event access, indexer access,
+	///   nothing).
+	/// </remarks>
+	public enum ExprClass : byte {
+		Unresolved	= 0,
+		
+		Value,
+		Variable,
+		Namespace,
+		Type,
+		TypeParameter,
+		MethodGroup,
+		PropertyAccess,
+		EventAccess,
+		IndexerAccess,
+		Nothing, 
+	}
+
+	/// <remarks>
+	///   This is used to tell Resolve in which types of expressions we're
+	///   interested.
+	/// </remarks>
+	[Flags]
+	public enum ResolveFlags {
+		// Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
+		VariableOrValue		= 1,
+
+		// Returns a type expression.
+		Type			= 1 << 1,
+
+		// Returns a method group.
+		MethodGroup		= 1 << 2,
+
+		TypeParameter	= 1 << 3,
+
+		// Mask of all the expression class flags.
+		MaskExprClass = VariableOrValue | Type | MethodGroup | TypeParameter,
+	}
+
+	//
+	// This is just as a hint to AddressOf of what will be done with the
+	// address.
+	[Flags]
+	public enum AddressOp {
+		Store = 1,
+		Load  = 2,
+		LoadStore = 3
+	};
+	
+	/// <summary>
+	///   This interface is implemented by variables
+	/// </summary>
+	public interface IMemoryLocation {
+		/// <summary>
+		///   The AddressOf method should generate code that loads
+		///   the address of the object and leaves it on the stack.
+		///
+		///   The `mode' argument is used to notify the expression
+		///   of whether this will be used to read from the address or
+		///   write to the address.
+		///
+		///   This is just a hint that can be used to provide good error
+		///   reporting, and should have no other side effects. 
+		/// </summary>
+		void AddressOf (EmitContext ec, AddressOp mode);
+	}
+
+	//
+	// An expressions resolved as a direct variable reference
+	//
+	public interface IVariableReference : IFixedExpression
+	{
+		bool IsHoisted { get; }
+		string Name { get; }
+		VariableInfo VariableInfo { get; }
+
+		void SetHasAddressTaken ();
+	}
+
+	//
+	// Implemented by an expression which could be or is always
+	// fixed
+	//
+	public interface IFixedExpression
+	{
+		bool IsFixed { get; }
+	}
+
+	public interface IExpressionCleanup
+	{
+		void EmitCleanup (EmitContext ec);
+	}
+
+	/// <remarks>
+	///   Base class for expressions
+	/// </remarks>
+	public abstract class Expression {
+		public ExprClass eclass;
+		protected TypeSpec type;
+		protected Location loc;
+		
+		public TypeSpec Type {
+			get { return type; }
+			set { type = value; }
+		}
+
+		public virtual bool IsSideEffectFree {
+			get {
+				return false;
+			}
+		}
+
+		public Location Location {
+			get { return loc; }
+		}
+
+		public virtual bool IsNull {
+			get {
+				return false;
+			}
+		}
+
+		//
+		// Used to workaround parser limitation where we cannot get
+		// start of statement expression location
+		//
+		public virtual Location StartLocation {
+			get {
+				return loc;
+			}
+		}
+
+		public virtual MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
+		{
+			//
+			// Return method-group expression when the expression can be used as
+			// lambda replacement. A good example is array sorting where instead of
+			// code like
+			//
+			//  Array.Sort (s, (a, b) => String.Compare (a, b));
+			//
+			// we can use method group directly
+			//
+			//  Array.Sort (s, String.Compare);
+			//
+			// Correct overload will be used because we do the reduction after
+			// best candidate was found.
+			//
+			return null;
+		}
+
+		//
+		// Returns true when the expression during Emit phase breaks stack
+		// by using await expression
+		//
+		public virtual bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		/// <summary>
+		///   Performs semantic analysis on the Expression
+		/// </summary>
+		///
+		/// <remarks>
+		///   The Resolve method is invoked to perform the semantic analysis
+		///   on the node.
+		///
+		///   The return value is an expression (it can be the
+		///   same expression in some cases) or a new
+		///   expression that better represents this node.
+		///   
+		///   For example, optimizations of Unary (LiteralInt)
+		///   would return a new LiteralInt with a negated
+		///   value.
+		///   
+		///   If there is an error during semantic analysis,
+		///   then an error should be reported (using Report)
+		///   and a null value should be returned.
+		///   
+		///   There are two side effects expected from calling
+		///   Resolve(): the the field variable "eclass" should
+		///   be set to any value of the enumeration
+		///   `ExprClass' and the type variable should be set
+		///   to a valid type (this is the type of the
+		///   expression).
+		/// </remarks>
+		protected abstract Expression DoResolve (ResolveContext rc);
+
+		public virtual Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			return null;
+		}
+
+		//
+		// This is used if the expression should be resolved as a type or namespace name.
+		// the default implementation fails.   
+		//
+		public virtual TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false)
+		{
+			ResolveContext ec = new ResolveContext (mc);
+			Expression e = Resolve (ec);
+			if (e != null)
+				e.Error_UnexpectedKind (ec, ResolveFlags.Type, loc);
+
+			return null;
+		}
+
+		public static void ErrorIsInaccesible (IMemberContext rc, string member, Location loc)
+		{
+			rc.Module.Compiler.Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", member);
+		}
+
+		public void Error_ExpressionMustBeConstant (ResolveContext rc, Location loc, string e_name)
+		{
+			rc.Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
+		}
+
+		public void Error_ConstantCanBeInitializedWithNullOnly (ResolveContext rc, TypeSpec type, Location loc, string name)
+		{
+			rc.Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
+				name, type.GetSignatureForError ());
+		}
+
+		protected virtual void Error_InvalidExpressionStatement (Report report, Location loc)
+		{
+			report.Error (201, loc, "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement");
+		}
+		
+		public void Error_InvalidExpressionStatement (BlockContext bc)
+		{
+			Error_InvalidExpressionStatement (bc.Report, loc);
+		}
+
+		public void Error_InvalidExpressionStatement (Report report)
+		{
+			Error_InvalidExpressionStatement (report, loc);
+		}
+
+		public static void Error_VoidInvalidInTheContext (Location loc, Report Report)
+		{
+			Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
+		}
+
+		public virtual void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
+		{
+			Error_ValueCannotBeConvertedCore (ec, loc, target, expl);
+		}
+
+		protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, TypeSpec target, bool expl)
+		{
+			// The error was already reported as CS1660
+			if (type == InternalType.AnonymousMethod)
+				return;
+
+			if (type == InternalType.ErrorType || target == InternalType.ErrorType)
+				return;
+
+			string from_type = type.GetSignatureForError ();
+			string to_type = target.GetSignatureForError ();
+			if (from_type == to_type) {
+				from_type = type.GetSignatureForErrorIncludingAssemblyName ();
+				to_type = target.GetSignatureForErrorIncludingAssemblyName ();
+			}
+
+			if (expl) {
+				ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
+					from_type, to_type);
+				return;
+			}
+
+			ec.Report.DisableReporting ();
+			bool expl_exists = Convert.ExplicitConversion (ec, this, target, Location.Null) != null;
+			ec.Report.EnableReporting ();
+
+			if (expl_exists) {
+				ec.Report.Error (266, loc,
+					"Cannot implicitly convert type `{0}' to `{1}'. An explicit conversion exists (are you missing a cast?)",
+					from_type, to_type);
+			} else {
+				ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
+					from_type, to_type);
+			}
+		}
+
+		public void Error_TypeArgumentsCannotBeUsed (IMemberContext context, MemberSpec member, Location loc)
+		{
+			// Better message for possible generic expressions
+			if (member != null && (member.Kind & MemberKind.GenericMask) != 0) {
+				var report = context.Module.Compiler.Report;
+				report.SymbolRelatedToPreviousError (member);
+				if (member is TypeSpec)
+					member = ((TypeSpec) member).GetDefinition ();
+				else
+					member = ((MethodSpec) member).GetGenericMethodDefinition ();
+
+				string name = member.Kind == MemberKind.Method ? "method" : "type";
+				if (member.IsGeneric) {
+					report.Error (305, loc, "Using the generic {0} `{1}' requires `{2}' type argument(s)",
+						name, member.GetSignatureForError (), member.Arity.ToString ());
+				} else {
+					report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
+						name, member.GetSignatureForError ());
+				}
+			} else {
+				Error_TypeArgumentsCannotBeUsed (context, ExprClassName, GetSignatureForError (), loc);
+			}
+		}
+
+		public static void Error_TypeArgumentsCannotBeUsed (IMemberContext context, string exprType, string name, Location loc)
+		{
+			context.Module.Compiler.Report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
+				exprType, name);
+		}
+
+		protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
+		{
+			Error_TypeDoesNotContainDefinition (ec, loc, type, name);
+		}
+
+		public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, TypeSpec type, string name)
+		{
+			ec.Report.SymbolRelatedToPreviousError (type);
+			ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
+				type.GetSignatureForError (), name);
+		}
+
+		public virtual void Error_ValueAssignment (ResolveContext rc, Expression rhs)
+		{
+			if (rhs == EmptyExpression.LValueMemberAccess || rhs == EmptyExpression.LValueMemberOutAccess) {
+				// Already reported as CS1612
+			} else if (rhs == EmptyExpression.OutAccess) {
+				rc.Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
+			} else {
+				rc.Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
+			}
+		}
+
+		protected void Error_VoidPointerOperation (ResolveContext rc)
+		{
+			rc.Report.Error (242, loc, "The operation in question is undefined on void pointers");
+		}
+
+		public static void Warning_UnreachableExpression (ResolveContext rc, Location loc)
+		{
+			rc.Report.Warning (429, 4, loc, "Unreachable expression code detected");
+		}
+
+		public ResolveFlags ExprClassToResolveFlags {
+			get {
+				switch (eclass) {
+				case ExprClass.Type:
+				case ExprClass.Namespace:
+					return ResolveFlags.Type;
+					
+				case ExprClass.MethodGroup:
+					return ResolveFlags.MethodGroup;
+					
+				case ExprClass.TypeParameter:
+					return ResolveFlags.TypeParameter;
+					
+				case ExprClass.Value:
+				case ExprClass.Variable:
+				case ExprClass.PropertyAccess:
+				case ExprClass.EventAccess:
+				case ExprClass.IndexerAccess:
+					return ResolveFlags.VariableOrValue;
+					
+				default:
+					throw new InternalErrorException (loc.ToString () + " " +  GetType () + " ExprClass is Invalid after resolve");
+				}
+			}
+		}
+
+		//
+		// Implements identical simple name and type-name resolution
+		//
+		public Expression ProbeIdenticalTypeName (ResolveContext rc, Expression left, SimpleName name)
+		{
+			var t = left.Type;
+			if (t.Kind == MemberKind.InternalCompilerType || t is ElementTypeSpec || t.Arity > 0)
+				return left;
+
+			// In a member access of the form E.I, if E is a single identifier, and if the meaning of E as a simple-name is
+			// a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name
+
+			if (left is MemberExpr || left is VariableReference) {
+				var identical_type = rc.LookupNamespaceOrType (name.Name, 0, LookupMode.Probing, loc) as TypeExpr;
+				if (identical_type != null && identical_type.Type == left.Type)
+					return identical_type;
+			}
+
+			return left;
+		}
+
+		public virtual string GetSignatureForError ()
+		{
+			return type.GetDefinition ().GetSignatureForError ();
+		}
+
+		public static bool IsNeverNull (Expression expr)
+		{
+			if (expr is This || expr is New || expr is ArrayCreation || expr is DelegateCreation || expr is ConditionalMemberAccess)
+				return true;
+
+			var c = expr as Constant;
+			if (c != null)
+				return !c.IsNull;
+
+			var tc = expr as TypeCast;
+			if (tc != null)
+				return IsNeverNull (tc.Child);
+
+			return false;
+		}
+
+		protected static bool IsNullPropagatingValid (TypeSpec type)
+		{
+			switch (type.Kind) {
+			case MemberKind.Struct:
+				return type.IsNullableType;
+			case MemberKind.Enum:
+			case MemberKind.Void:
+			case MemberKind.PointerType:
+				return false;
+			case MemberKind.InternalCompilerType:
+				return type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+			default:
+				return true;
+			}
+		}
+
+		public virtual bool HasConditionalAccess ()
+		{
+			return false;
+		}
+
+		protected static TypeSpec LiftMemberType (ResolveContext rc, TypeSpec type)
+		{
+			return TypeSpec.IsValueType (type) && !type.IsNullableType ?
+				Nullable.NullableInfo.MakeType (rc.Module, type) :
+				type;
+		}
+	       
+		/// <summary>
+		///   Resolves an expression and performs semantic analysis on it.
+		/// </summary>
+		///
+		/// <remarks>
+		///   Currently Resolve wraps DoResolve to perform sanity
+		///   checking and assertion checking on what we expect from Resolve.
+		/// </remarks>
+		public Expression Resolve (ResolveContext ec, ResolveFlags flags)
+		{
+			if (eclass != ExprClass.Unresolved) {
+				if ((flags & ExprClassToResolveFlags) == 0) {
+					Error_UnexpectedKind (ec, flags, loc);
+					return null;
+				}
+
+				return this;
+			}
+			
+			Expression e;
+			try {
+				e = DoResolve (ec);
+
+				if (e == null)
+					return null;
+
+				if ((flags & e.ExprClassToResolveFlags) == 0) {
+					e.Error_UnexpectedKind (ec, flags, loc);
+					return null;
+				}
+
+				if (e.type == null)
+					throw new InternalErrorException ("Expression `{0}' didn't set its type in DoResolve", e.GetType ());
+
+				return e;
+			} catch (Exception ex) {
+				if (loc.IsNull || ec.Module.Compiler.Settings.BreakOnInternalError || ex is CompletionResult || ec.Report.IsDisabled || ex is FatalException ||
+					ec.Report.Printer is NullReportPrinter)
+					throw;
+
+				ec.Report.Error (584, loc, "Internal compiler error: {0}", ex.Message);
+				return ErrorExpression.Instance;	// TODO: Add location
+			}
+		}
+
+		/// <summary>
+		///   Resolves an expression and performs semantic analysis on it.
+		/// </summary>
+		public Expression Resolve (ResolveContext rc)
+		{
+			return Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
+		}
+
+		/// <summary>
+		///   Resolves an expression for LValue assignment
+		/// </summary>
+		///
+		/// <remarks>
+		///   Currently ResolveLValue wraps DoResolveLValue to perform sanity
+		///   checking and assertion checking on what we expect from Resolve
+		/// </remarks>
+		public Expression ResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			int errors = ec.Report.Errors;
+			bool out_access = right_side == EmptyExpression.OutAccess;
+
+			Expression e = DoResolveLValue (ec, right_side);
+
+			if (e != null && out_access && !(e is IMemoryLocation)) {
+				// FIXME: There's no problem with correctness, the 'Expr = null' handles that.
+				//        Enabling this 'throw' will "only" result in deleting useless code elsewhere,
+
+				//throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
+				//				  e.GetType () + " " + e.GetSignatureForError ());
+				e = null;
+			}
+
+			if (e == null) {
+				if (errors == ec.Report.Errors) {
+					Error_ValueAssignment (ec, right_side);
+				}
+				return null;
+			}
+
+			if (e.eclass == ExprClass.Unresolved)
+				throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve");
+
+			if ((e.type == null) && !(e is GenericTypeExpr))
+				throw new Exception ("Expression " + e + " did not set its type after Resolve");
+
+			return e;
+		}
+
+		public Constant ResolveLabelConstant (ResolveContext rc)
+		{
+			var expr = Resolve (rc);
+			if (expr == null)
+				return null;
+
+			Constant c = expr as Constant;
+			if (c == null) {
+				if (expr.type != InternalType.ErrorType)
+					rc.Report.Error (150, expr.StartLocation, "A constant value is expected");
+
+				return null;
+			}
+
+			return c;
+		}
+
+		public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			if (Attribute.IsValidArgumentType (parameterType)) {
+				rc.Module.Compiler.Report.Error (182, loc,
+					"An attribute argument must be a constant expression, typeof expression or array creation expression");
+			} else {
+				rc.Module.Compiler.Report.Error (181, loc,
+					"Attribute constructor parameter has type `{0}', which is not a valid attribute parameter type",
+					targetType.GetSignatureForError ());
+			}
+		}
+
+		/// <summary>
+		///   Emits the code for the expression
+		/// </summary>
+		///
+		/// <remarks>
+		///   The Emit method is invoked to generate the code
+		///   for the expression.  
+		/// </remarks>
+		public abstract void Emit (EmitContext ec);
+
+
+		// Emit code to branch to @target if this expression is equivalent to @on_true.
+		// The default implementation is to emit the value, and then emit a brtrue or brfalse.
+		// Subclasses can provide more efficient implementations, but those MUST be equivalent,
+		// including the use of conditional branches.  Note also that a branch MUST be emitted
+		public virtual void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			Emit (ec);
+			ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
+		}
+
+		// Emit this expression for its side effects, not for its value.
+		// The default implementation is to emit the value, and then throw it away.
+		// Subclasses can provide more efficient implementations, but those MUST be equivalent
+		public virtual void EmitSideEffect (EmitContext ec)
+		{
+			Emit (ec);
+			ec.Emit (OpCodes.Pop);
+		}
+
+		//
+		// Emits the expression into temporary field variable. The method
+		// should be used for await expressions only
+		//
+		public virtual Expression EmitToField (EmitContext ec)
+		{
+			//
+			// This is the await prepare Emit method. When emitting code like
+			// a + b we emit code like
+			//
+			// a.Emit ()
+			// b.Emit ()
+			// Opcodes.Add
+			//
+			// For await a + await b we have to interfere the flow to keep the
+			// stack clean because await yields from the expression. The emit
+			// then changes to
+			//
+			// a = a.EmitToField ()	// a is changed to temporary field access
+			// b = b.EmitToField ()
+			// a.Emit ()
+			// b.Emit ()
+			// Opcodes.Add
+			//
+			//
+			// The idea is to emit expression and leave the stack empty with
+			// result value still available.
+			//
+			// Expressions should override this default implementation when
+			// optimized version can be provided (e.g. FieldExpr)
+			//
+			//
+			// We can optimize for side-effect free expressions, they can be
+			// emitted out of order
+			//
+			if (IsSideEffectFree)
+				return this;
+
+			bool needs_temporary = ContainsEmitWithAwait ();
+			if (!needs_temporary)
+				ec.EmitThis ();
+
+			// Emit original code
+			var field = EmitToFieldSource (ec);
+			if (field == null) {
+				//
+				// Store the result to temporary field when we
+				// cannot load `this' directly
+				//
+				field = ec.GetTemporaryField (type);
+				if (needs_temporary) {
+					//
+					// Create temporary local (we cannot load `this' before Emit)
+					//
+					var temp = ec.GetTemporaryLocal (type);
+					ec.Emit (OpCodes.Stloc, temp);
+
+					ec.EmitThis ();
+					ec.Emit (OpCodes.Ldloc, temp);
+					field.EmitAssignFromStack (ec);
+
+					ec.FreeTemporaryLocal (temp, type);
+				} else {
+					field.EmitAssignFromStack (ec);
+				}
+			}
+
+			return field;
+		}
+
+		protected virtual FieldExpr EmitToFieldSource (EmitContext ec)
+		{
+			//
+			// Default implementation calls Emit method
+			//
+			Emit (ec);
+			return null;
+		}
+
+		protected static void EmitExpressionsList (EmitContext ec, List<Expression> expressions)
+		{
+			if (ec.HasSet (BuilderContext.Options.AsyncBody)) {
+				bool contains_await = false;
+
+				for (int i = 1; i < expressions.Count; ++i) {
+					if (expressions[i].ContainsEmitWithAwait ()) {
+						contains_await = true;
+						break;
+					}
+				}
+
+				if (contains_await) {
+					for (int i = 0; i < expressions.Count; ++i) {
+						expressions[i] = expressions[i].EmitToField (ec);
+					}
+				}
+			}
+
+			for (int i = 0; i < expressions.Count; ++i) {
+				expressions[i].Emit (ec);
+			}
+		}
+
+		/// <summary>
+		///   Protected constructor.  Only derivate types should
+		///   be able to be created
+		/// </summary>
+
+		protected Expression ()
+		{
+		}
+
+		/// <summary>
+		///   Returns a fully formed expression after a MemberLookup
+		/// </summary>
+		/// 
+		static Expression ExprClassFromMemberInfo (MemberSpec spec, Location loc)
+		{
+			if (spec is EventSpec)
+				return new EventExpr ((EventSpec) spec, loc);
+			if (spec is ConstSpec)
+				return new ConstantExpr ((ConstSpec) spec, loc);
+			if (spec is FieldSpec)
+				return new FieldExpr ((FieldSpec) spec, loc);
+			if (spec is PropertySpec)
+				return new PropertyExpr ((PropertySpec) spec, loc);
+			if (spec is TypeSpec)
+				return new TypeExpression (((TypeSpec) spec), loc);
+
+			return null;
+		}
+
+		public static MethodSpec ConstructorLookup (ResolveContext rc, TypeSpec type, ref Arguments args, Location loc)
+		{
+			var ctors = MemberCache.FindMembers (type, Constructor.ConstructorName, true);
+			if (ctors == null) {
+				switch (type.Kind) {
+				case MemberKind.Struct:
+					rc.Report.SymbolRelatedToPreviousError (type);
+					// Report meaningful error for struct as they always have default ctor in C# context
+					OverloadResolver.Error_ConstructorMismatch (rc, type, args == null ? 0 : args.Count, loc);
+					break;
+				case MemberKind.MissingType:
+				case MemberKind.InternalCompilerType:
+// LAMESPEC: dynamic is not really object
+//					if (type.BuiltinType == BuiltinTypeSpec.Type.Object)
+//						goto default;
+					break;
+				default:
+					rc.Report.SymbolRelatedToPreviousError (type);
+					rc.Report.Error (143, loc, "The class `{0}' has no constructors defined",
+						type.GetSignatureForError ());
+					break;
+				}
+
+				return null;
+			}
+
+			var r = new OverloadResolver (ctors, OverloadResolver.Restrictions.NoBaseMembers, loc);
+			if (!rc.HasSet (ResolveContext.Options.BaseInitializer)) {
+				r.InstanceQualifier = new ConstructorInstanceQualifier (type);
+			}
+
+			return r.ResolveMember<MethodSpec> (rc, ref args);
+		}
+
+		[Flags]
+		public enum MemberLookupRestrictions
+		{
+			None = 0,
+			InvocableOnly = 1,
+			ExactArity = 1 << 2,
+			ReadAccess = 1 << 3,
+			EmptyArguments = 1 << 4,
+			IgnoreArity = 1 << 5,
+			IgnoreAmbiguity = 1 << 6
+		}
+
+		//
+		// Lookup type `queried_type' for code in class `container_type' with a qualifier of
+		// `qualifier_type' or null to lookup members in the current class.
+		//
+		public static Expression MemberLookup (IMemberContext rc, bool errorMode, TypeSpec queried_type, string name, int arity, MemberLookupRestrictions restrictions, Location loc)
+		{
+			var members = MemberCache.FindMembers (queried_type, name, false);
+			if (members == null)
+				return null;
+
+			MemberSpec non_method = null;
+			MemberSpec ambig_non_method = null;
+			do {
+				for (int i = 0; i < members.Count; ++i) {
+					var member = members[i];
+
+					// HACK: for events because +=/-= can appear at same class only, should use OverrideToBase there
+					if ((member.Modifiers & Modifiers.OVERRIDE) != 0 && member.Kind != MemberKind.Event)
+						continue;
+
+					if ((member.Modifiers & Modifiers.BACKING_FIELD) != 0 || member.Kind == MemberKind.Operator)
+						continue;
+
+					if ((arity > 0 || (restrictions & MemberLookupRestrictions.ExactArity) != 0) && member.Arity != arity)
+						continue;
+
+					if (!errorMode) {
+						if (!member.IsAccessible (rc))
+							continue;
+
+						//
+						// With runtime binder we can have a situation where queried type is inaccessible
+						// because it came via dynamic object, the check about inconsisted accessibility
+						// had no effect as the type was unknown during compilation
+						//
+						// class A {
+						//		private class N { }
+						//
+						//		public dynamic Foo ()
+						//		{
+						//			return new N ();
+						//		}
+						//	}
+						//
+						if (rc.Module.Compiler.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc))
+							continue;
+					}
+
+					if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) {
+						if (member is MethodSpec) {
+							//
+							// Interface members that are hidden by class members are removed from the set. This
+							// step only has an effect if T is a type parameter and T has both an effective base 
+							// class other than object and a non-empty effective interface set
+							//
+							var tps = queried_type as TypeParameterSpec;
+							if (tps != null && tps.HasTypeConstraint)
+								members = RemoveHiddenTypeParameterMethods (members);
+
+							return new MethodGroupExpr (members, queried_type, loc);
+						}
+
+						if (!Invocation.IsMemberInvocable (member))
+							continue;
+					}
+
+					if (non_method == null || member is MethodSpec || non_method.IsNotCSharpCompatible) {
+						non_method = member;
+					} else if (!errorMode && !member.IsNotCSharpCompatible) {
+						//
+						// Interface members that are hidden by class members are removed from the set when T is a type parameter and
+						// T has both an effective base class other than object and a non-empty effective interface set.
+						//
+						// The spec has more complex rules but we simply remove all members declared in an interface declaration.
+						//
+						var tps = queried_type as TypeParameterSpec;
+						if (tps != null && tps.HasTypeConstraint) {
+							if (non_method.DeclaringType.IsClass && member.DeclaringType.IsInterface)
+								continue;
+
+							if (non_method.DeclaringType.IsInterface && member.DeclaringType.IsInterface) {
+								non_method = member;
+								continue;
+							}
+						}
+
+						ambig_non_method = member;
+					}
+				}
+
+				if (non_method != null) {
+					if (ambig_non_method != null && rc != null && (restrictions & MemberLookupRestrictions.IgnoreAmbiguity) == 0) {
+						var report = rc.Module.Compiler.Report;
+						report.SymbolRelatedToPreviousError (non_method);
+						report.SymbolRelatedToPreviousError (ambig_non_method);
+						report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
+							non_method.GetSignatureForError (), ambig_non_method.GetSignatureForError ());
+					}
+
+					if (non_method is MethodSpec)
+						return new MethodGroupExpr (members, queried_type, loc);
+
+					return ExprClassFromMemberInfo (non_method, loc);
+				}
+
+				if (members[0].DeclaringType.BaseType == null)
+					members = null;
+				else
+					members = MemberCache.FindMembers (members[0].DeclaringType.BaseType, name, false);
+
+			} while (members != null);
+
+			return null;
+		}
+
+		static IList<MemberSpec> RemoveHiddenTypeParameterMethods (IList<MemberSpec> members)
+		{
+			if (members.Count < 2)
+				return members;
+
+			//
+			// If M is a method, then all non-method members declared in an interface declaration
+			// are removed from the set, and all methods with the same signature as M declared in
+			// an interface declaration are removed from the set
+			//
+
+			bool copied = false;
+			for (int i = 0; i < members.Count; ++i) {
+				var method = members[i] as MethodSpec;
+				if (method == null) {
+					if (!copied) {
+						copied = true;
+						members = new List<MemberSpec> (members);
+					} 
+					
+					members.RemoveAt (i--);
+					continue;
+				}
+
+				if (!method.DeclaringType.IsInterface)
+					continue;
+
+				for (int ii = 0; ii < members.Count; ++ii) {
+					var candidate = members[ii] as MethodSpec;
+					if (candidate == null || !candidate.DeclaringType.IsClass)
+						continue;
+
+					if (!TypeSpecComparer.Override.IsEqual (candidate.Parameters, method.Parameters))
+						continue;
+
+					if (!copied) {
+						copied = true;
+						members = new List<MemberSpec> (members);
+					}
+
+					members.RemoveAt (i--);
+					break;
+				}
+			}
+
+			return members;
+		}
+
+		protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public virtual void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t)
+		{
+			if (t == InternalType.ErrorType)
+				return;
+
+			rc.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
+				oper, t.GetSignatureForError ());
+		}
+
+		protected void Error_PointerInsideExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation");
+		}
+
+		protected void Error_NullShortCircuitInsideExpressionTree (ResolveContext rc)
+		{
+			rc.Report.Error (8072, loc, "An expression tree cannot contain a null propagating operator");
+		}
+
+		public virtual void FlowAnalysis (FlowAnalysisContext fc)
+		{
+		}
+
+		//
+		// Special version of flow analysis for expressions which can return different
+		// on-true and on-false result. Used by &&, ||, ?: expressions
+		//
+		public virtual void FlowAnalysisConditional (FlowAnalysisContext fc)
+		{
+			FlowAnalysis (fc);
+			fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment;
+		}
+
+		/// <summary>
+		///   Returns an expression that can be used to invoke operator true
+		///   on the expression if it exists.
+		/// </summary>
+		protected static Expression GetOperatorTrue (ResolveContext ec, Expression e, Location loc)
+		{
+			return GetOperatorTrueOrFalse (ec, e, true, loc);
+		}
+
+		/// <summary>
+		///   Returns an expression that can be used to invoke operator false
+		///   on the expression if it exists.
+		/// </summary>
+		protected static Expression GetOperatorFalse (ResolveContext ec, Expression e, Location loc)
+		{
+			return GetOperatorTrueOrFalse (ec, e, false, loc);
+		}
+
+		static Expression GetOperatorTrueOrFalse (ResolveContext ec, Expression e, bool is_true, Location loc)
+		{
+			var op = is_true ? Operator.OpType.True : Operator.OpType.False;
+			var methods = MemberCache.GetUserOperator (e.type, op, false);
+			if (methods == null)
+				return null;
+
+			Arguments arguments = new Arguments (1);
+			arguments.Add (new Argument (e));
+
+			var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
+			var oper = res.ResolveOperator (ec, ref arguments);
+
+			if (oper == null)
+				return null;
+
+			return new UserOperatorCall (oper, arguments, null, loc);
+		}
+		
+		public virtual string ExprClassName
+		{
+			get {
+				switch (eclass){
+				case ExprClass.Unresolved:
+					return "Unresolved";
+				case ExprClass.Value:
+					return "value";
+				case ExprClass.Variable:
+					return "variable";
+				case ExprClass.Namespace:
+					return "namespace";
+				case ExprClass.Type:
+					return "type";
+				case ExprClass.MethodGroup:
+					return "method group";
+				case ExprClass.PropertyAccess:
+					return "property access";
+				case ExprClass.EventAccess:
+					return "event access";
+				case ExprClass.IndexerAccess:
+					return "indexer access";
+				case ExprClass.Nothing:
+					return "null";
+				case ExprClass.TypeParameter:
+					return "type parameter";
+				}
+				throw new Exception ("Should not happen");
+			}
+		}
+		
+		/// <summary>
+		///   Reports that we were expecting `expr' to be of class `expected'
+		/// </summary>
+		public static void Error_UnexpectedKind (IMemberContext ctx, Expression memberExpr, string expected, string was, Location loc)
+		{
+			var name = memberExpr.GetSignatureForError ();
+
+			ctx.Module.Compiler.Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected", name, was, expected);
+		}
+
+		public virtual void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
+		{
+			string [] valid = new string [4];
+			int count = 0;
+
+			if ((flags & ResolveFlags.VariableOrValue) != 0) {
+				valid [count++] = "variable";
+				valid [count++] = "value";
+			}
+
+			if ((flags & ResolveFlags.Type) != 0)
+				valid [count++] = "type";
+
+			if ((flags & ResolveFlags.MethodGroup) != 0)
+				valid [count++] = "method group";
+
+			if (count == 0)
+				valid [count++] = "unknown";
+
+			StringBuilder sb = new StringBuilder (valid [0]);
+			for (int i = 1; i < count - 1; i++) {
+				sb.Append ("', `");
+				sb.Append (valid [i]);
+			}
+			if (count > 1) {
+				sb.Append ("' or `");
+				sb.Append (valid [count - 1]);
+			}
+
+			ec.Report.Error (119, loc, 
+				"Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
+		}
+		
+		public static void UnsafeError (ResolveContext ec, Location loc)
+		{
+			UnsafeError (ec.Report, loc);
+		}
+
+		public static void UnsafeError (Report Report, Location loc)
+		{
+			Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
+		}
+
+		//
+		// Converts `source' to an int, uint, long or ulong.
+		//
+		protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source, bool pointerArray = false)
+		{
+			var btypes = ec.BuiltinTypes;
+
+			if (source.type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (source));
+				return new DynamicConversion (btypes.Int, CSharpBinderFlags.ConvertArrayIndex, args, loc).Resolve (ec);
+			}
+
+			Expression converted;
+			
+			using (ec.Set (ResolveContext.Options.CheckedScope)) {
+				converted = Convert.ImplicitConversion (ec, source, btypes.Int, source.loc);
+				if (converted == null)
+					converted = Convert.ImplicitConversion (ec, source, btypes.UInt, source.loc);
+				if (converted == null)
+					converted = Convert.ImplicitConversion (ec, source, btypes.Long, source.loc);
+				if (converted == null)
+					converted = Convert.ImplicitConversion (ec, source, btypes.ULong, source.loc);
+
+				if (converted == null) {
+					source.Error_ValueCannotBeConverted (ec, btypes.Int, false);
+					return null;
+				}
+			}
+
+			if (pointerArray)
+				return converted;
+
+			//
+			// Only positive constants are allowed at compile time
+			//
+			Constant c = converted as Constant;
+			if (c != null && c.IsNegative)
+				Error_NegativeArrayIndex (ec, source.loc);
+
+			// No conversion needed to array index
+			if (converted.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
+				return converted;
+
+			return new ArrayIndexCast (converted, btypes.Int).Resolve (ec);
+		}
+
+		//
+		// Derived classes implement this method by cloning the fields that
+		// could become altered during the Resolve stage
+		//
+		// Only expressions that are created for the parser need to implement
+		// this.
+		//
+		protected virtual void CloneTo (CloneContext clonectx, Expression target)
+		{
+			throw new NotImplementedException (
+				String.Format (
+					"CloneTo not implemented for expression {0}", this.GetType ()));
+		}
+
+		//
+		// Clones an expression created by the parser.
+		//
+		// We only support expressions created by the parser so far, not
+		// expressions that have been resolved (many more classes would need
+		// to implement CloneTo).
+		//
+		// This infrastructure is here merely for Lambda expressions which
+		// compile the same code using different type values for the same
+		// arguments to find the correct overload
+		//
+		public virtual Expression Clone (CloneContext clonectx)
+		{
+			Expression cloned = (Expression) MemberwiseClone ();
+			CloneTo (clonectx, cloned);
+
+			return cloned;
+		}
+
+		//
+		// Implementation of expression to expression tree conversion
+		//
+		public abstract Expression CreateExpressionTree (ResolveContext ec);
+
+		protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, Arguments args)
+		{
+			return CreateExpressionFactoryCall (ec, name, null, args, loc);
+		}
+
+		protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args)
+		{
+			return CreateExpressionFactoryCall (ec, name, typeArguments, args, loc);
+		}
+
+		public static Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args, Location loc)
+		{
+			return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec, loc), name, typeArguments, loc), args);
+		}
+
+		protected static TypeExpr CreateExpressionTypeExpression (ResolveContext ec, Location loc)
+		{
+			var t = ec.Module.PredefinedTypes.Expression.Resolve ();
+			if (t == null)
+				return null;
+
+			return new TypeExpression (t, loc);
+		}
+
+		//
+		// Implemented by all expressions which support conversion from
+		// compiler expression to invokable runtime expression. Used by
+		// dynamic C# binder.
+		//
+		public virtual SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			throw new NotImplementedException ("MakeExpression for " + GetType ());
+		}
+			
+		public virtual object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   This is just a base class for expressions that can
+	///   appear on statements (invocations, object creation,
+	///   assignments, post/pre increment and decrement).  The idea
+	///   being that they would support an extra Emition interface that
+	///   does not leave a result on the stack.
+	/// </summary>
+	public abstract class ExpressionStatement : Expression
+	{
+		public virtual void MarkReachable (Reachability rc)
+		{
+		}
+
+		public ExpressionStatement ResolveStatement (BlockContext ec)
+		{
+			Expression e = Resolve (ec);
+			if (e == null)
+				return null;
+
+			ExpressionStatement es = e as ExpressionStatement;
+			if (es == null || e is AnonymousMethodBody)
+				Error_InvalidExpressionStatement (ec);
+
+			//
+			// This is quite expensive warning, try to limit the damage
+			//
+			if (MemberAccess.IsValidDotExpression (e.Type) && !(e is Assign || e is Await)) {
+				WarningAsyncWithoutWait (ec, e);
+			}
+
+			return es;
+		}
+
+		static void WarningAsyncWithoutWait (BlockContext bc, Expression e)
+		{
+			if (bc.CurrentAnonymousMethod is AsyncInitializer) {
+				var awaiter = new AwaitStatement.AwaitableMemberAccess (e) {
+					ProbingMode = true
+				};
+
+				//
+				// Need to do full resolve because GetAwaiter can be extension method
+				// available only in this context
+				//
+				var mg = awaiter.Resolve (bc) as MethodGroupExpr;
+				if (mg == null)
+					return;
+
+				var arguments = new Arguments (0);
+				mg = mg.OverloadResolve (bc, ref arguments, null, OverloadResolver.Restrictions.ProbingOnly);
+				if (mg == null)
+					return;
+
+				//
+				// Use same check rules as for real await
+				//
+				var awaiter_definition = bc.Module.GetAwaiter (mg.BestCandidateReturnType);
+				if (!awaiter_definition.IsValidPattern || !awaiter_definition.INotifyCompletion)
+					return;
+
+				bc.Report.Warning (4014, 1, e.Location,
+					"The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator");
+				return;
+			}
+
+			var inv = e as Invocation;
+			if (inv != null && inv.MethodGroup != null && inv.MethodGroup.BestCandidate.IsAsync) {
+				// The warning won't be reported for imported methods to maintain warning compatiblity with csc 
+				bc.Report.Warning (4014, 1, e.Location,
+					"The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator or calling `Wait' method");
+				return;
+			}
+		}
+
+		/// <summary>
+		///   Requests the expression to be emitted in a `statement'
+		///   context.  This means that no new value is left on the
+		///   stack after invoking this method (constrasted with
+		///   Emit that will always leave a value on the stack).
+		/// </summary>
+		public abstract void EmitStatement (EmitContext ec);
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			EmitStatement (ec);
+		}
+	}
+
+	/// <summary>
+	///   This kind of cast is used to encapsulate the child
+	///   whose type is child.Type into an expression that is
+	///   reported to return "return_type".  This is used to encapsulate
+	///   expressions which have compatible types, but need to be dealt
+	///   at higher levels with.
+	///
+	///   For example, a "byte" expression could be encapsulated in one
+	///   of these as an "unsigned int".  The type for the expression
+	///   would be "unsigned int".
+	///
+	/// </summary>
+	public abstract class TypeCast : Expression
+	{
+		protected readonly Expression child;
+
+		protected TypeCast (Expression child, TypeSpec return_type)
+		{
+			eclass = child.eclass;
+			loc = child.Location;
+			type = return_type;
+			this.child = child;
+		}
+
+		public Expression Child {
+			get {
+				return child;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return child.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (child.CreateExpressionTree (ec)));
+			args.Add (new Argument (new TypeOf (type, loc)));
+
+			if (type.IsPointer || child.Type.IsPointer)
+				Error_PointerInsideExpressionTree (ec);
+
+			return CreateExpressionFactoryCall (ec, ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// This should never be invoked, we are born in fully
+			// initialized state.
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			child.Emit (ec);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			child.FlowAnalysis (fc);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return ctx.HasSet (BuilderContext.Options.CheckedScope) ?
+				SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type.GetMetaInfo ()) :
+				SLE.Expression.Convert (child.MakeExpression (ctx), type.GetMetaInfo ());
+#endif
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			// Nothing to clone
+		}
+
+		public override bool IsNull {
+			get { return child.IsNull; }
+		}
+	}
+
+	public class EmptyCast : TypeCast {
+		EmptyCast (Expression child, TypeSpec target_type)
+			: base (child, target_type)
+		{
+		}
+
+		public static Expression Create (Expression child, TypeSpec type)
+		{
+			Constant c = child as Constant;
+			if (c != null) {
+				var enum_constant = c as EnumConstant;
+				if (enum_constant != null)
+					c = enum_constant.Child;
+
+				if (!(c is ReducedExpression.ReducedConstantExpression)) {
+					if (c.Type == type)
+						return c;
+
+					var res = c.ConvertImplicitly (type);
+					if (res != null)
+						return res;
+				}
+			}
+
+			EmptyCast e = child as EmptyCast;
+			if (e != null)
+				return new EmptyCast (e.child, type);
+
+			return new EmptyCast (child, type);
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
+		{
+			child.EmitBranchable (ec, label, on_true);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			child.EmitSideEffect (ec);
+		}
+	}
+
+	//
+	// Used for predefined type user operator (no obsolete check, etc.)
+	//
+	public class OperatorCast : TypeCast
+	{
+		readonly MethodSpec conversion_operator;
+
+		public OperatorCast (Expression expr, TypeSpec target_type)
+			: this (expr, target_type, target_type, false)
+		{
+		}
+		
+		public OperatorCast (Expression expr, TypeSpec target_type, bool find_explicit)
+			: this (expr, target_type, target_type, find_explicit)
+		{
+		}
+		
+		public OperatorCast (Expression expr, TypeSpec declaringType, TypeSpec returnType, bool isExplicit)
+			: base (expr, returnType)
+		{
+			var op = isExplicit ? Operator.OpType.Explicit : Operator.OpType.Implicit;
+			var mi = MemberCache.GetUserOperator (declaringType, op, true);
+
+			if (mi != null) {
+				foreach (MethodSpec oper in mi) {
+					if (oper.ReturnType != returnType)
+						continue;
+
+					if (oper.Parameters.Types[0] == expr.Type) {
+						conversion_operator = oper;
+						return;
+					}
+				}
+			}
+
+			throw new InternalErrorException ("Missing predefined user operator between `{0}' and `{1}'",
+				returnType.GetSignatureForError (), expr.Type.GetSignatureForError ());
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			child.Emit (ec);
+			ec.Emit (OpCodes.Call, conversion_operator);
+		}
+	}
+	
+	//
+	// Constant specialization of EmptyCast.
+	// We need to special case this since an empty cast of
+	// a constant is still a constant. 
+	//
+	public class EmptyConstantCast : Constant
+	{
+		public readonly Constant child;
+
+		public EmptyConstantCast (Constant child, TypeSpec type)
+			: base (child.Location)
+		{
+			if (child == null)
+				throw new ArgumentNullException ("child");
+
+			this.child = child;
+			this.eclass = child.eclass;
+			this.type = type;
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			if (child.Type == target_type)
+				return child;
+
+			// FIXME: check that 'type' can be converted to 'target_type' first
+			return child.ConvertExplicitly (in_checked_context, target_type);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = Arguments.CreateForExpressionTree (ec, null,
+				child.CreateExpressionTree (ec),
+				new TypeOf (type, loc));
+
+			if (type.IsPointer)
+				Error_PointerInsideExpressionTree (ec);
+
+			return CreateExpressionFactoryCall (ec, "Convert", args);
+		}
+
+		public override bool IsDefaultValue {
+			get { return child.IsDefaultValue; }
+		}
+
+		public override bool IsNegative {
+			get { return child.IsNegative; }
+		}
+
+		public override bool IsNull {
+			get { return child.IsNull; }
+		}
+		
+		public override bool IsOneInteger {
+			get { return child.IsOneInteger; }
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return child.IsSideEffectFree;
+			}
+		}
+
+		public override bool IsZeroInteger {
+			get { return child.IsZeroInteger; }
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			child.Emit (ec);			
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
+		{
+			child.EmitBranchable (ec, label, on_true);
+
+			// Only to make verifier happy
+			if (TypeManager.IsGenericParameter (type) && child.IsNull)
+				ec.Emit (OpCodes.Unbox_Any, type);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			child.EmitSideEffect (ec);
+		}
+
+		public override object GetValue ()
+		{
+			return child.GetValue ();
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return child.GetValueAsLiteral ();
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return child.GetValueAsLong ();
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec target_type)
+		{
+			if (type == target_type)
+				return this;
+
+			// FIXME: Do we need to check user conversions?
+			if (!Convert.ImplicitStandardConversionExists (this, target_type))
+				return null;
+
+			return child.ConvertImplicitly (target_type);
+		}
+	}
+
+	/// <summary>
+	///  This class is used to wrap literals which belong inside Enums
+	/// </summary>
+	public class EnumConstant : Constant
+	{
+		public Constant Child;
+
+		public EnumConstant (Constant child, TypeSpec enum_type)
+			: base (child.Location)
+		{
+			this.Child = child;
+
+			this.eclass = ExprClass.Value;
+			this.type = enum_type;
+		}
+
+		protected EnumConstant (Location loc)
+			: base (loc)
+		{
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Child.Emit (ec);
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			Child.EncodeAttributeValue (rc, enc, Child.Type, parameterType);
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
+		{
+			Child.EmitBranchable (ec, label, on_true);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			Child.EmitSideEffect (ec);
+		}
+
+		public override string GetSignatureForError()
+		{
+			return Type.GetSignatureForError ();
+		}
+
+		public override object GetValue ()
+		{
+			return Child.GetValue ();
+		}
+
+#if !STATIC
+		public override object GetTypedValue ()
+		{
+			//
+			// The method can be used in dynamic context only (on closed types)
+			//
+			// System.Enum.ToObject cannot be called on dynamic types
+			// EnumBuilder has to be used, but we cannot use EnumBuilder
+			// because it does not properly support generics
+			//
+			return System.Enum.ToObject (type.GetMetaInfo (), Child.GetValue ());
+		}
+#endif
+
+		public override string GetValueAsLiteral ()
+		{
+			return Child.GetValueAsLiteral ();
+		}
+
+		public override long GetValueAsLong ()
+		{
+			return Child.GetValueAsLong ();
+		}
+
+		public EnumConstant Increment()
+		{
+			return new EnumConstant (((IntegralConstant) Child).Increment (), type);
+		}
+
+		public override bool IsDefaultValue {
+			get {
+				return Child.IsDefaultValue;
+			}
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return Child.IsSideEffectFree;
+			}
+		}
+
+		public override bool IsZeroInteger {
+			get { return Child.IsZeroInteger; }
+		}
+
+		public override bool IsNegative {
+			get {
+				return Child.IsNegative;
+			}
+		}
+
+		public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+		{
+			if (Child.Type == target_type)
+				return Child;
+
+			return Child.ConvertExplicitly (in_checked_context, target_type);
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec type)
+		{
+			if (this.type == type) {
+				return this;
+			}
+
+			if (!Convert.ImplicitStandardConversionExists (this, type)){
+				return null;
+			}
+
+			return Child.ConvertImplicitly (type);
+		}
+	}
+
+	/// <summary>
+	///   This kind of cast is used to encapsulate Value Types in objects.
+	///
+	///   The effect of it is to box the value type emitted by the previous
+	///   operation.
+	/// </summary>
+	public class BoxedCast : TypeCast {
+
+		public BoxedCast (Expression expr, TypeSpec target_type)
+			: base (expr, target_type)
+		{
+			eclass = ExprClass.Value;
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// This should never be invoked, we are born in fully
+			// initialized state.
+
+			return this;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			// Only boxing to object type is supported
+			if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
+				base.EncodeAttributeValue (rc, enc, targetType, parameterType);
+				return;
+			}
+
+			enc.Encode (child.Type);
+			child.EncodeAttributeValue (rc, enc, child.Type, parameterType);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+			
+			ec.Emit (OpCodes.Box, child.Type);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			// boxing is side-effectful, since it involves runtime checks, except when boxing to Object or ValueType
+			// so, we need to emit the box+pop instructions in most cases
+			if (child.Type.IsStruct &&
+			    (type.BuiltinType == BuiltinTypeSpec.Type.Object || type.BuiltinType == BuiltinTypeSpec.Type.ValueType))
+				child.EmitSideEffect (ec);
+			else
+				base.EmitSideEffect (ec);
+		}
+	}
+
+	public class UnboxCast : TypeCast {
+		public UnboxCast (Expression expr, TypeSpec return_type)
+			: base (expr, return_type)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// This should never be invoked, we are born in fully
+			// initialized state.
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+
+			ec.Emit (OpCodes.Unbox_Any, type);
+		}
+	}
+	
+	/// <summary>
+	///   This is used to perform explicit numeric conversions.
+	///
+	///   Explicit numeric conversions might trigger exceptions in a checked
+	///   context, so they should generate the conv.ovf opcodes instead of
+	///   conv opcodes.
+	/// </summary>
+	public class ConvCast : TypeCast {
+		public enum Mode : byte {
+			I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
+			U1_I1, U1_CH,
+			I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
+			U2_I1, U2_U1, U2_I2, U2_CH,
+			I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
+			U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
+			I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH, I8_I,
+			U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH, U8_I,
+			CH_I1, CH_U1, CH_I2,
+			R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
+			R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4,
+			I_I8,
+		}
+
+		Mode mode;
+		
+		public ConvCast (Expression child, TypeSpec return_type, Mode m)
+			: base (child, return_type)
+		{
+			mode = m;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// This should never be invoked, we are born in fully
+			// initialized state.
+
+			return this;
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("ConvCast ({0}, {1})", mode, child);
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+			Emit (ec, mode);
+		}
+
+		public static void Emit (EmitContext ec, Mode mode)
+		{
+			if (ec.HasSet (EmitContext.Options.CheckedScope)) {
+				switch (mode){
+				case Mode.I1_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+				case Mode.I1_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.I1_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+				case Mode.I1_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+				case Mode.I1_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+
+				case Mode.U1_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+				case Mode.U1_CH: /* nothing */ break;
+
+				case Mode.I2_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+				case Mode.I2_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+				case Mode.I2_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.I2_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+				case Mode.I2_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+				case Mode.I2_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+
+				case Mode.U2_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+				case Mode.U2_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+				case Mode.U2_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+				case Mode.U2_CH: /* nothing */ break;
+
+				case Mode.I4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+				case Mode.I4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+				case Mode.I4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+				case Mode.I4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+				case Mode.I4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.I4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+				case Mode.I4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+
+				case Mode.U4_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+				case Mode.U4_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+				case Mode.U4_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+				case Mode.U4_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+				case Mode.U4_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
+				case Mode.U4_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+
+				case Mode.I8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+				case Mode.I8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+				case Mode.I8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+				case Mode.I8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.I8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
+				case Mode.I8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+				case Mode.I8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+				case Mode.I8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.I8_I: ec.Emit (OpCodes.Conv_Ovf_U); break;
+
+				case Mode.U8_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+				case Mode.U8_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+				case Mode.U8_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+				case Mode.U8_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+				case Mode.U8_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
+				case Mode.U8_U4: ec.Emit (OpCodes.Conv_Ovf_U4_Un); break;
+				case Mode.U8_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
+				case Mode.U8_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+				case Mode.U8_I: ec.Emit (OpCodes.Conv_Ovf_U_Un); break;
+
+				case Mode.CH_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+				case Mode.CH_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+				case Mode.CH_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+
+				case Mode.R4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+				case Mode.R4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+				case Mode.R4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+				case Mode.R4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.R4_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
+				case Mode.R4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+				case Mode.R4_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
+				case Mode.R4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+				case Mode.R4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+
+				case Mode.R8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+				case Mode.R8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+				case Mode.R8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+				case Mode.R8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.R8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
+				case Mode.R8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+				case Mode.R8_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
+				case Mode.R8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+				case Mode.R8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+				case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
+
+				case Mode.I_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
+				}
+			} else {
+				switch (mode){
+				case Mode.I1_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.I1_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.I1_U4: ec.Emit (OpCodes.Conv_U4); break;
+				case Mode.I1_U8: ec.Emit (OpCodes.Conv_I8); break;
+				case Mode.I1_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+				case Mode.U1_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.U1_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+				case Mode.I2_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.I2_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.I2_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.I2_U4: ec.Emit (OpCodes.Conv_U4); break;
+				case Mode.I2_U8: ec.Emit (OpCodes.Conv_I8); break;
+				case Mode.I2_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+				case Mode.U2_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.U2_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.U2_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.U2_CH: /* nothing */ break;
+
+				case Mode.I4_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.I4_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.I4_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.I4_U4: /* nothing */ break;
+				case Mode.I4_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.I4_U8: ec.Emit (OpCodes.Conv_I8); break;
+				case Mode.I4_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+				case Mode.U4_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.U4_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.U4_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.U4_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.U4_I4: /* nothing */ break;
+				case Mode.U4_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+				case Mode.I8_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.I8_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.I8_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.I8_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.I8_I4: ec.Emit (OpCodes.Conv_I4); break;
+				case Mode.I8_U4: ec.Emit (OpCodes.Conv_U4); break;
+				case Mode.I8_U8: /* nothing */ break;
+				case Mode.I8_CH: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.I8_I: ec.Emit (OpCodes.Conv_U); break;
+
+				case Mode.U8_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.U8_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.U8_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.U8_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.U8_I4: ec.Emit (OpCodes.Conv_I4); break;
+				case Mode.U8_U4: ec.Emit (OpCodes.Conv_U4); break;
+				case Mode.U8_I8: /* nothing */ break;
+				case Mode.U8_CH: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.U8_I: ec.Emit (OpCodes.Conv_U); break;
+
+				case Mode.CH_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.CH_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.CH_I2: ec.Emit (OpCodes.Conv_I2); break;
+
+				case Mode.R4_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.R4_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.R4_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.R4_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.R4_I4: ec.Emit (OpCodes.Conv_I4); break;
+				case Mode.R4_U4: ec.Emit (OpCodes.Conv_U4); break;
+				case Mode.R4_I8: ec.Emit (OpCodes.Conv_I8); break;
+				case Mode.R4_U8: ec.Emit (OpCodes.Conv_U8); break;
+				case Mode.R4_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+				case Mode.R8_I1: ec.Emit (OpCodes.Conv_I1); break;
+				case Mode.R8_U1: ec.Emit (OpCodes.Conv_U1); break;
+				case Mode.R8_I2: ec.Emit (OpCodes.Conv_I2); break;
+				case Mode.R8_U2: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.R8_I4: ec.Emit (OpCodes.Conv_I4); break;
+				case Mode.R8_U4: ec.Emit (OpCodes.Conv_U4); break;
+				case Mode.R8_I8: ec.Emit (OpCodes.Conv_I8); break;
+				case Mode.R8_U8: ec.Emit (OpCodes.Conv_U8); break;
+				case Mode.R8_CH: ec.Emit (OpCodes.Conv_U2); break;
+				case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
+
+				case Mode.I_I8: ec.Emit (OpCodes.Conv_U8); break;
+				}
+			}
+		}
+	}
+	
+	class OpcodeCast : TypeCast
+	{
+		readonly OpCode op;
+		
+		public OpcodeCast (Expression child, TypeSpec return_type, OpCode op)
+			: base (child, return_type)
+		{
+			this.op = op;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// This should never be invoked, we are born in fully
+			// initialized state.
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+			ec.Emit (op);
+		}
+
+		public TypeSpec UnderlyingType {
+			get { return child.Type; }
+		}
+	}
+
+	//
+	// Opcode casts expression with 2 opcodes but only
+	// single expression tree node
+	//
+	class OpcodeCastDuplex : OpcodeCast
+	{
+		readonly OpCode second;
+
+		public OpcodeCastDuplex (Expression child, TypeSpec returnType, OpCode first, OpCode second)
+			: base (child, returnType, first)
+		{
+			this.second = second;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+			ec.Emit (second);
+		}
+	}
+
+	/// <summary>
+	///   This kind of cast is used to encapsulate a child and cast it
+	///   to the class requested
+	/// </summary>
+	public sealed class ClassCast : TypeCast {
+		readonly bool forced;
+		
+		public ClassCast (Expression child, TypeSpec return_type)
+			: base (child, return_type)
+		{
+		}
+		
+		public ClassCast (Expression child, TypeSpec return_type, bool forced)
+			: base (child, return_type)
+		{
+			this.forced = forced;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+
+			bool gen = TypeManager.IsGenericParameter (child.Type);
+			if (gen)
+				ec.Emit (OpCodes.Box, child.Type);
+			
+			if (type.IsGenericParameter) {
+				ec.Emit (OpCodes.Unbox_Any, type);
+				return;
+			}
+			
+			if (gen && !forced)
+				return;
+			
+			ec.Emit (OpCodes.Castclass, type);
+		}
+	}
+
+	//
+	// Created during resolving pahse when an expression is wrapped or constantified
+	// and original expression can be used later (e.g. for expression trees)
+	//
+	public class ReducedExpression : Expression
+	{
+		public sealed class ReducedConstantExpression : EmptyConstantCast
+		{
+			readonly Expression orig_expr;
+
+			public ReducedConstantExpression (Constant expr, Expression orig_expr)
+				: base (expr, expr.Type)
+			{
+				this.orig_expr = orig_expr;
+			}
+
+			public Expression OriginalExpression {
+				get {
+					return orig_expr;
+				}
+			}
+
+			public override Constant ConvertImplicitly (TypeSpec target_type)
+			{
+				Constant c = base.ConvertImplicitly (target_type);
+				if (c != null)
+					c = new ReducedConstantExpression (c, orig_expr);
+
+				return c;
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				return orig_expr.CreateExpressionTree (ec);
+			}
+
+			public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
+			{
+				Constant c = base.ConvertExplicitly (in_checked_context, target_type);
+				if (c != null)
+					c = new ReducedConstantExpression (c, orig_expr);
+				return c;
+			}
+
+			public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+			{
+				//
+				// LAMESPEC: Reduced conditional expression is allowed as an attribute argument
+				//
+				if (orig_expr is Conditional)
+					child.EncodeAttributeValue (rc, enc, targetType,parameterType);
+				else
+					base.EncodeAttributeValue (rc, enc, targetType, parameterType);
+			}
+		}
+
+		sealed class ReducedExpressionStatement : ExpressionStatement
+		{
+			readonly Expression orig_expr;
+			readonly ExpressionStatement stm;
+
+			public ReducedExpressionStatement (ExpressionStatement stm, Expression orig)
+			{
+				this.orig_expr = orig;
+				this.stm = stm;
+				this.eclass = stm.eclass;
+				this.type = stm.Type;
+
+				this.loc = orig.Location;
+			}
+
+			public override bool ContainsEmitWithAwait ()
+			{
+				return stm.ContainsEmitWithAwait ();
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				return orig_expr.CreateExpressionTree (ec);
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				return this;
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				stm.Emit (ec);
+			}
+
+			public override void EmitStatement (EmitContext ec)
+			{
+				stm.EmitStatement (ec);
+			}
+
+			public override void FlowAnalysis (FlowAnalysisContext fc)
+			{
+				stm.FlowAnalysis (fc);
+			}
+		}
+
+		readonly Expression expr, orig_expr;
+
+		private ReducedExpression (Expression expr, Expression orig_expr)
+		{
+			this.expr = expr;
+			this.eclass = expr.eclass;
+			this.type = expr.Type;
+			this.orig_expr = orig_expr;
+			this.loc = orig_expr.Location;
+		}
+
+		#region Properties
+
+		public override bool IsSideEffectFree {
+			get {
+				return expr.IsSideEffectFree;
+			}
+		}
+
+		public Expression OriginalExpression {
+			get {
+				return orig_expr;
+			}
+		}
+
+		#endregion
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return expr.ContainsEmitWithAwait ();
+		}
+
+		//
+		// Creates fully resolved expression switcher
+		//
+		public static Constant Create (Constant expr, Expression original_expr)
+		{
+			if (expr.eclass == ExprClass.Unresolved)
+				throw new ArgumentException ("Unresolved expression");
+
+			return new ReducedConstantExpression (expr, original_expr);
+		}
+
+		public static ExpressionStatement Create (ExpressionStatement s, Expression orig)
+		{
+			return new ReducedExpressionStatement (s, orig);
+		}
+
+		public static Expression Create (Expression expr, Expression original_expr)
+		{
+			return Create (expr, original_expr, true);
+		}
+
+		//
+		// Creates unresolved reduce expression. The original expression has to be
+		// already resolved. Created expression is constant based based on `expr'
+		// value unless canBeConstant is used
+		//
+		public static Expression Create (Expression expr, Expression original_expr, bool canBeConstant)
+		{
+			if (canBeConstant) {
+				Constant c = expr as Constant;
+				if (c != null)
+					return Create (c, original_expr);
+			}
+
+			ExpressionStatement s = expr as ExpressionStatement;
+			if (s != null)
+				return Create (s, original_expr);
+
+			if (expr.eclass == ExprClass.Unresolved)
+				throw new ArgumentException ("Unresolved expression");
+
+			return new ReducedExpression (expr, original_expr);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return orig_expr.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			expr.Emit (ec);
+		}
+
+		public override Expression EmitToField (EmitContext ec)
+		{
+ 			return expr.EmitToField(ec);
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			expr.EmitBranchable (ec, target, on_true);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return orig_expr.MakeExpression (ctx);
+		}
+	}
+
+	//
+	// Standard composite pattern
+	//
+	public abstract class CompositeExpression : Expression
+	{
+		protected Expression expr;
+
+		protected CompositeExpression (Expression expr)
+		{
+			this.expr = expr;
+			this.loc = expr.Location;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return expr.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext rc)
+		{
+			return expr.CreateExpressionTree (rc);
+		}
+
+		public Expression Child {
+			get { return expr; }
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			expr = expr.Resolve (rc);
+			if (expr == null)
+				return null;
+
+			type = expr.Type;
+			eclass = expr.eclass;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			expr.Emit (ec);
+		}
+
+		public override bool IsNull {
+			get { return expr.IsNull; }
+		}
+	}
+
+	//
+	// Base of expressions used only to narrow resolve flow
+	//
+	public abstract class ShimExpression : Expression
+	{
+		protected Expression expr;
+
+		protected ShimExpression (Expression expr)
+		{
+			this.expr = expr;
+		}
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			if (expr == null)
+				return;
+
+			ShimExpression target = (ShimExpression) t;
+			target.expr = expr.Clone (clonectx);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return expr.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new InternalErrorException ("Missing Resolve call");
+		}
+	}
+
+	public class UnreachableExpression : Expression
+	{
+		public UnreachableExpression (Expression expr)
+		{
+			this.loc = expr.Location;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			// TODO: is it ok
+			throw new NotImplementedException ();
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			fc.Report.Warning (429, 4, loc, "Unreachable expression code detected");
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+		}
+	}
+
+	//
+	// Unresolved type name expressions
+	//
+	public abstract class ATypeNameExpression : FullNamedExpression
+	{
+		string name;
+		protected TypeArguments targs;
+
+		protected ATypeNameExpression (string name, Location l)
+		{
+			this.name = name;
+			loc = l;
+		}
+
+		protected ATypeNameExpression (string name, TypeArguments targs, Location l)
+		{
+			this.name = name;
+			this.targs = targs;
+			loc = l;
+		}
+
+		protected ATypeNameExpression (string name, int arity, Location l)
+			: this (name, new UnboundTypeArguments (arity), l)
+		{
+		}
+
+		#region Properties
+
+		protected int Arity {
+			get {
+				return targs == null ? 0 : targs.Count;
+			}
+		}
+
+		public bool HasTypeArguments {
+			get {
+				return targs != null && !targs.IsEmpty;
+			}
+		}
+
+		public string Name {
+			get {
+				return name;
+			}
+			set {
+				name = value;
+			}
+		}
+
+		public TypeArguments TypeArguments {
+			get {
+				return targs;
+			}
+		}
+
+		#endregion
+
+		public override bool Equals (object obj)
+		{
+			ATypeNameExpression atne = obj as ATypeNameExpression;
+			return atne != null && atne.Name == Name &&
+				(targs == null || targs.Equals (atne.targs));
+		}
+
+		protected void Error_OpenGenericTypeIsNotAllowed (IMemberContext mc)
+		{
+			mc.Module.Compiler.Report.Error (7003, Location, "Unbound generic name is not valid in this context");
+		}
+
+		public override int GetHashCode ()
+		{
+			return Name.GetHashCode ();
+		}
+
+		// TODO: Move it to MemberCore
+		public static string GetMemberType (MemberCore mc)
+		{
+			if (mc is Property)
+				return "property";
+			if (mc is Indexer)
+				return "indexer";
+			if (mc is FieldBase)
+				return "field";
+			if (mc is MethodCore)
+				return "method";
+			if (mc is EnumMember)
+				return "enum";
+			if (mc is Event)
+				return "event";
+
+			return "type";
+		}
+
+		public override string GetSignatureForError ()
+		{
+			if (targs != null) {
+				return Name + "<" + targs.GetSignatureForError () + ">";
+			}
+
+			return Name;
+		}
+
+		public abstract Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restriction);
+	}
+	
+	/// <summary>
+	///   SimpleName expressions are formed of a single word and only happen at the beginning 
+	///   of a dotted-name.
+	/// </summary>
+	public class SimpleName : ATypeNameExpression
+	{
+		public SimpleName (string name, Location l)
+			: base (name, l)
+		{
+		}
+
+		public SimpleName (string name, TypeArguments args, Location l)
+			: base (name, args, l)
+		{
+		}
+
+		public SimpleName (string name, int arity, Location l)
+			: base (name, arity, l)
+		{
+		}
+
+		public SimpleName GetMethodGroup ()
+		{
+			return new SimpleName (Name, targs, loc);
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			return SimpleNameResolve (rc, null);
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			return SimpleNameResolve (ec, right_side);
+		}
+
+		public void Error_NameDoesNotExist (ResolveContext rc)
+		{
+			rc.Report.Error (103, loc, "The name `{0}' does not exist in the current context", Name);
+		}
+
+		protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ctx)
+		{
+			if (ctx.CurrentType != null) {
+				var member = MemberLookup (ctx, false, ctx.CurrentType, Name, 0, MemberLookupRestrictions.ExactArity, loc) as MemberExpr;
+				if (member != null) {
+					Error_UnexpectedKind (ctx, member, "type", member.KindName, loc);
+					return;
+				}
+			}
+
+			var report = ctx.Module.Compiler.Report;
+
+			var retval = ctx.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
+			if (retval != null) {
+				report.SymbolRelatedToPreviousError (retval.Type);
+				ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
+				return;
+			}
+
+			retval = ctx.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc);
+			if (retval != null) {
+				Error_TypeArgumentsCannotBeUsed (ctx, retval.Type, loc);
+				return;
+			}
+
+			var ns_candidates = ctx.Module.GlobalRootNamespace.FindTypeNamespaces (ctx, Name, Arity);
+			if (ns_candidates != null) {
+				if (ctx is UsingAliasNamespace.AliasContext) {
+					report.Error (246, loc,
+						"The type or namespace name `{1}' could not be found. Consider using fully qualified name `{0}.{1}'",
+						ns_candidates[0], Name);
+				} else {
+					string usings = string.Join ("' or `", ns_candidates.ToArray ());
+					report.Error (246, loc,
+						"The type or namespace name `{0}' could not be found. Are you missing `{1}' using directive?",
+						Name, usings);
+				}
+			} else {
+				report.Error (246, loc,
+					"The type or namespace name `{0}' could not be found. Are you missing an assembly reference?",
+					Name);
+			}
+		}
+
+		public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments)
+		{
+			FullNamedExpression fne = mc.LookupNamespaceOrType (Name, Arity, LookupMode.Normal, loc);
+
+			if (fne != null) {
+				if (fne.Type != null && Arity > 0) {
+					if (HasTypeArguments) {
+						GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
+						if (ct.ResolveAsType (mc) == null)
+							return null;
+
+						return ct;
+					}
+
+					if (!allowUnboundTypeArguments)
+						Error_OpenGenericTypeIsNotAllowed (mc);
+
+					return new GenericOpenTypeExpr (fne.Type, loc);
+				}
+
+				//
+				// dynamic namespace is ignored when dynamic is allowed (does not apply to types)
+				//
+				if (!(fne is NamespaceExpression))
+					return fne;
+			}
+
+			if (Arity == 0 && Name == "dynamic" && mc.Module.Compiler.Settings.Version > LanguageVersion.V_3) {
+				if (!mc.Module.PredefinedAttributes.Dynamic.IsDefined) {
+					mc.Module.Compiler.Report.Error (1980, Location,
+						"Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
+						mc.Module.PredefinedAttributes.Dynamic.GetSignatureForError ());
+				}
+
+				fne = new DynamicTypeExpr (loc);
+				fne.ResolveAsType (mc);
+			}
+
+			if (fne != null)
+				return fne;
+
+			Error_TypeOrNamespaceNotFound (mc);
+			return null;
+		}
+
+		public bool IsPossibleTypeOrNamespace (IMemberContext mc)
+		{
+			return mc.LookupNamespaceOrType (Name, Arity, LookupMode.Probing, loc) != null;
+		}
+
+		public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
+		{
+			int lookup_arity = Arity;
+			bool errorMode = false;
+			Expression e;
+			Block current_block = rc.CurrentBlock;
+			INamedBlockVariable variable = null;
+			bool variable_found = false;
+
+			while (true) {
+				//
+				// Stage 1: binding to local variables or parameters
+				//
+				// LAMESPEC: It should take invocableOnly into account but that would break csc compatibility
+				//
+				if (current_block != null && lookup_arity == 0) {
+					if (current_block.ParametersBlock.TopBlock.GetLocalName (Name, current_block.Original, ref variable)) {
+						if (!variable.IsDeclared) {
+							// We found local name in accessible block but it's not
+							// initialized yet, maybe the user wanted to bind to something else
+							errorMode = true;
+							variable_found = true;
+						} else {
+							e = variable.CreateReferenceExpression (rc, loc);
+							if (e != null) {
+								if (Arity > 0)
+									Error_TypeArgumentsCannotBeUsed (rc, "variable", Name, loc);
+
+								return e;
+							}
+						}
+					}
+				}
+
+				//
+				// Stage 2: Lookup members if we are inside a type up to top level type for nested types
+				//
+				TypeSpec member_type = rc.CurrentType;
+				for (; member_type != null; member_type = member_type.DeclaringType) {
+					e = MemberLookup (rc, errorMode, member_type, Name, lookup_arity, restrictions, loc);
+					if (e == null)
+						continue;
+
+					var me = e as MemberExpr;
+					if (me == null) {
+						// The name matches a type, defer to ResolveAsTypeStep
+						if (e is TypeExpr)
+							break;
+
+						continue;
+					}
+
+					if (errorMode) {
+						if (variable != null) {
+							if (me is FieldExpr || me is ConstantExpr || me is EventExpr || me is PropertyExpr) {
+								rc.Report.Error (844, loc,
+									"A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the member `{1}'",
+									Name, me.GetSignatureForError ());
+							} else {
+								break;
+							}
+						} else if (me is MethodGroupExpr || me is PropertyExpr || me is IndexerExpr) {
+							// Leave it to overload resolution to report correct error
+						} else {
+							// TODO: rc.Report.SymbolRelatedToPreviousError ()
+							ErrorIsInaccesible (rc, me.GetSignatureForError (), loc);
+						}
+					} else {
+						// LAMESPEC: again, ignores InvocableOnly
+						if (variable != null) {
+							rc.Report.SymbolRelatedToPreviousError (variable.Location, Name);
+							rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name);
+						}
+
+						//
+						// MemberLookup does not check accessors availability, this is actually needed for properties only
+						//
+						var pe = me as PropertyExpr;
+						if (pe != null) {
+
+							// Break as there is no other overload available anyway
+							if ((restrictions & MemberLookupRestrictions.ReadAccess) != 0) {
+								if (!pe.PropertyInfo.HasGet || !pe.PropertyInfo.Get.IsAccessible (rc))
+									break;
+
+								pe.Getter = pe.PropertyInfo.Get;
+							} else {
+								if (!pe.PropertyInfo.HasSet || !pe.PropertyInfo.Set.IsAccessible (rc))
+									break;
+
+								pe.Setter = pe.PropertyInfo.Set;
+							}
+						}
+					}
+
+					// TODO: It's used by EventExpr -> FieldExpr transformation only
+					// TODO: Should go to MemberAccess
+					me = me.ResolveMemberAccess (rc, null, null);
+
+					if (Arity > 0) {
+						targs.Resolve (rc);
+						me.SetTypeArguments (rc, targs);
+					}
+
+					return me;
+				}
+
+				//
+				// Stage 3: Lookup nested types, namespaces and type parameters in the context
+				//
+				if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0 && !variable_found) {
+					if (IsPossibleTypeOrNamespace (rc)) {
+						if (variable != null) {
+							rc.Report.SymbolRelatedToPreviousError (variable.Location, Name);
+							rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name);
+						}
+
+						return ResolveAsTypeOrNamespace (rc, false);
+					}
+				}
+
+				var mg = NamespaceContainer.LookupStaticUsings (rc, Name, Arity, loc);
+				if (mg != null) {
+					if (Arity > 0) {
+						targs.Resolve (rc);
+						mg.SetTypeArguments (rc, targs);
+					}
+					return mg;
+				}
+
+				if (Name == "nameof")
+					return new NameOf (this);
+
+				if (errorMode) {
+					if (variable_found) {
+						rc.Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", Name);
+					} else {
+						if (Arity > 0) {
+							var tparams = rc.CurrentTypeParameters;
+							if (tparams != null) {
+								if (tparams.Find (Name) != null) {
+									Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc);
+									return null;
+								}
+							}
+
+							var ct = rc.CurrentType;
+							do {
+								if (ct.MemberDefinition.TypeParametersCount > 0) {
+									foreach (var ctp in ct.MemberDefinition.TypeParameters) {
+										if (ctp.Name == Name) {
+											Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc);
+											return null;
+										}
+									}
+								}
+
+								ct = ct.DeclaringType;
+							} while (ct != null);
+						}
+
+						if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0) {
+							e = rc.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
+							if (e != null) {
+								rc.Report.SymbolRelatedToPreviousError (e.Type);
+								ErrorIsInaccesible (rc, e.GetSignatureForError (), loc);
+								return e;
+							}
+						} else {
+							var me = MemberLookup (rc, false, rc.CurrentType, Name, Arity, restrictions & ~MemberLookupRestrictions.InvocableOnly, loc) as MemberExpr;
+							if (me != null) {
+								Error_UnexpectedKind (rc, me, "method group", me.KindName, loc);
+								return ErrorExpression.Instance;
+							}
+						}
+
+						e = rc.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc);
+						if (e != null) {
+							if (e.Type.Arity != Arity && (restrictions & MemberLookupRestrictions.IgnoreArity) == 0) {
+								Error_TypeArgumentsCannotBeUsed (rc, e.Type, loc);
+								return e;
+							}
+
+							if (e is TypeExpr) {
+								// TypeExpression does not have correct location
+								if (e is TypeExpression)
+									e = new TypeExpression (e.Type, loc);
+
+								return e;
+							}
+						}
+
+						Error_NameDoesNotExist (rc);
+					}
+
+					return ErrorExpression.Instance;
+				}
+
+				if (rc.Module.Evaluator != null) {
+					var fi = rc.Module.Evaluator.LookupField (Name);
+					if (fi != null)
+						return new FieldExpr (fi.Item1, loc);
+				}
+
+				lookup_arity = 0;
+				errorMode = true;
+			}
+		}
+		
+		Expression SimpleNameResolve (ResolveContext ec, Expression right_side)
+		{
+			Expression e = LookupNameExpression (ec, right_side == null ? MemberLookupRestrictions.ReadAccess : MemberLookupRestrictions.None);
+
+			if (e == null)
+				return null;
+
+			if (e is FullNamedExpression && e.eclass != ExprClass.Unresolved) {
+				Error_UnexpectedKind (ec, e, "variable", e.ExprClassName, loc);
+				return e;
+			}
+
+			if (right_side != null) {
+				e = e.ResolveLValue (ec, right_side);
+			} else {
+				e = e.Resolve (ec);
+			}
+
+			return e;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Represents a namespace or a type.  The name of the class was inspired by
+	///   section 10.8.1 (Fully Qualified Names).
+	/// </summary>
+	public abstract class FullNamedExpression : Expression
+	{
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			// Do nothing, most unresolved type expressions cannot be
+			// resolved to different type
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		public abstract FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments);
+
+		//
+		// This is used to resolve the expression as a type, a null
+		// value will be returned if the expression is not a type
+		// reference
+		//
+		public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false)
+		{
+			FullNamedExpression fne = ResolveAsTypeOrNamespace (mc, allowUnboundTypeArguments);
+
+			if (fne == null)
+				return null;
+
+			TypeExpr te = fne as TypeExpr;
+			if (te == null) {
+				Error_UnexpectedKind (mc, fne, "type", fne.ExprClassName, loc);
+				return null;
+			}
+
+			te.loc = loc;
+
+			type = te.Type;
+
+			var dep = type.GetMissingDependencies ();
+			if (dep != null) {
+				ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
+			}
+
+			if (type.Kind == MemberKind.Void) {
+				mc.Module.Compiler.Report.Error (673, loc, "System.Void cannot be used from C#. Consider using `void'");
+			}
+
+			//
+			// Obsolete checks cannot be done when resolving base context as they
+			// require type dependencies to be set but we are in process of resolving them
+			//
+			if (!(mc is TypeDefinition.BaseContext) && !(mc is UsingAliasNamespace.AliasContext)) {
+				ObsoleteAttribute obsolete_attr = type.GetAttributeObsolete ();
+				if (obsolete_attr != null && !mc.IsObsolete) {
+					AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, mc.Module.Compiler.Report);
+				}
+			}
+
+			return type;
+		}
+
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
+				GetSignatureForError ());
+		}
+	}
+	
+	/// <summary>
+	///   Expression that evaluates to a type
+	/// </summary>
+	public abstract class TypeExpr : FullNamedExpression
+	{
+		public sealed override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments)
+		{
+			ResolveAsType (mc);
+			return this;
+		}
+
+		protected sealed override Expression DoResolve (ResolveContext ec)
+		{
+			ResolveAsType (ec);
+			return this;
+		}
+
+		public override bool Equals (object obj)
+		{
+			TypeExpr tobj = obj as TypeExpr;
+			if (tobj == null)
+				return false;
+
+			return Type == tobj.Type;
+		}
+
+		public override int GetHashCode ()
+		{
+			return Type.GetHashCode ();
+		}
+	}
+
+	/// <summary>
+	///   Fully resolved Expression that already evaluated to a type
+	/// </summary>
+	public class TypeExpression : TypeExpr
+	{
+		public TypeExpression (TypeSpec t, Location l)
+		{
+			Type = t;
+			eclass = ExprClass.Type;
+			loc = l;
+		}
+
+		public sealed override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false)
+		{
+			return type;
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class NamespaceExpression : FullNamedExpression
+	{
+		readonly Namespace ns;
+
+		public NamespaceExpression (Namespace ns, Location loc)
+		{
+			this.ns = ns;
+			this.Type = InternalType.Namespace;
+			this.eclass = ExprClass.Namespace;
+			this.loc = loc;
+		}
+
+		public Namespace Namespace {
+			get {
+				return ns;
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments)
+		{
+			return this;
+		}
+
+		public void Error_NamespaceDoesNotExist (IMemberContext ctx, string name, int arity)
+		{
+			var retval = Namespace.LookupType (ctx, name, arity, LookupMode.IgnoreAccessibility, loc);
+			if (retval != null) {
+//				ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.MemberDefinition);
+				ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
+				return;
+			}
+
+			retval = Namespace.LookupType (ctx, name, -System.Math.Max (1, arity), LookupMode.Probing, loc);
+			if (retval != null) {
+				Error_TypeArgumentsCannotBeUsed (ctx, retval, loc);
+				return;
+			}
+
+			Namespace ns;
+			if (arity > 0 && Namespace.TryGetNamespace (name, out ns)) {
+				Error_TypeArgumentsCannotBeUsed (ctx, ExprClassName, ns.GetSignatureForError (), loc);
+				return;
+			}
+
+			string assembly = null;
+			string possible_name = Namespace.GetSignatureForError () + "." + name;
+
+			// Only assembly unique name should be added
+			switch (possible_name) {
+			case "System.Drawing":
+			case "System.Web.Services":
+			case "System.Web":
+			case "System.Data":
+			case "System.Configuration":
+			case "System.Data.Services":
+			case "System.DirectoryServices":
+			case "System.Json":
+			case "System.Net.Http":
+			case "System.Numerics":
+			case "System.Runtime.Caching":
+			case "System.ServiceModel":
+			case "System.Transactions":
+			case "System.Web.Routing":
+			case "System.Xml.Linq":
+			case "System.Xml":
+				assembly = possible_name;
+				break;
+
+			case "System.Linq":
+			case "System.Linq.Expressions":
+				assembly = "System.Core";
+				break;
+
+			case "System.Windows.Forms":
+			case "System.Windows.Forms.Layout":
+				assembly = "System.Windows.Forms";
+				break;
+			}
+
+			assembly = assembly == null ? "an" : "`" + assembly + "'";
+
+			if (Namespace is GlobalRootNamespace) {
+				ctx.Module.Compiler.Report.Error (400, loc,
+					"The type or namespace name `{0}' could not be found in the global namespace. Are you missing {1} assembly reference?",
+					name, assembly);
+			} else {
+				ctx.Module.Compiler.Report.Error (234, loc,
+					"The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing {2} assembly reference?",
+					name, GetSignatureForError (), assembly);
+			}
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return ns.GetSignatureForError ();
+		}
+
+		public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
+		{
+			return ns.LookupTypeOrNamespace (ctx, name, arity, mode, loc);
+		}
+    }
+
+	/// <summary>
+	///   This class denotes an expression which evaluates to a member
+	///   of a struct or a class.
+	/// </summary>
+	public abstract class MemberExpr : Expression, OverloadResolver.IInstanceQualifier
+	{
+		protected bool conditional_access_receiver;
+
+		//
+		// An instance expression associated with this member, if it's a
+		// non-static member
+		//
+		public Expression InstanceExpression;
+
+		/// <summary>
+		///   The name of this member.
+		/// </summary>
+		public abstract string Name {
+			get;
+		}
+
+		//
+		// When base.member is used
+		//
+		public bool IsBase {
+			get { return InstanceExpression is BaseThis; }
+		}
+
+		/// <summary>
+		///   Whether this is an instance member.
+		/// </summary>
+		public abstract bool IsInstance {
+			get;
+		}
+
+		/// <summary>
+		///   Whether this is a static member.
+		/// </summary>
+		public abstract bool IsStatic {
+			get;
+		}
+
+		public abstract string KindName {
+			get;
+		}
+
+		public bool ConditionalAccess { get; set; }
+
+		protected abstract TypeSpec DeclaringType {
+			get;
+		}
+
+		TypeSpec OverloadResolver.IInstanceQualifier.InstanceType {
+			get {
+				return InstanceExpression.Type;
+			}
+		}
+
+		//
+		// Converts best base candidate for virtual method starting from QueriedBaseType
+		//
+		protected MethodSpec CandidateToBaseOverride (ResolveContext rc, MethodSpec method)
+		{
+			//
+			// Only when base.member is used and method is virtual
+			//
+			if (!IsBase)
+				return method;
+
+			//
+			// Overload resulution works on virtual or non-virtual members only (no overrides). That
+			// means for base.member access we have to find the closest match after we found best candidate
+			//
+			if ((method.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
+				//
+				// The method could already be what we are looking for
+				//
+				TypeSpec[] targs = null;
+				if (method.DeclaringType != InstanceExpression.Type) {
+					//
+					// Candidate can have inflated MVAR parameters and we need to find
+					// base match for original definition not inflated parameter types
+					//
+					var parameters = method.Parameters;
+					if (method.Arity > 0) {
+						parameters = ((IParametersMember) method.MemberDefinition).Parameters;
+						var inflated = method.DeclaringType as InflatedTypeSpec;
+						if (inflated != null) {
+							parameters = parameters.Inflate (inflated.CreateLocalInflator (rc));
+						}
+					}
+
+					var filter = new MemberFilter (method.Name, method.Arity, MemberKind.Method, parameters, null);
+					var base_override = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as MethodSpec;
+					if (base_override != null && base_override.DeclaringType != method.DeclaringType) {
+						if (base_override.IsGeneric)
+							targs = method.TypeArguments;
+
+						method = base_override;
+					}
+				}
+
+				//
+				// When base access is used inside anonymous method/iterator/etc we need to
+				// get back to the context of original type. We do it by emiting proxy
+				// method in original class and rewriting base call to this compiler
+				// generated method call which does the actual base invocation. This may
+				// introduce redundant storey but with `this' only but it's tricky to avoid
+				// at this stage as we don't know what expressions follow base
+				//
+				if (rc.CurrentAnonymousMethod != null) {
+					if (targs == null && method.IsGeneric) {
+						targs = method.TypeArguments;
+						method = method.GetGenericMethodDefinition ();
+					}
+
+					if (method.Parameters.HasArglist)
+						throw new NotImplementedException ("__arglist base call proxy");
+
+					method = rc.CurrentMemberDefinition.Parent.PartialContainer.CreateHoistedBaseCallProxy (rc, method);
+
+					// Ideally this should apply to any proxy rewrite but in the case of unary mutators on
+					// get/set member expressions second call would fail to proxy because left expression
+					// would be of 'this' and not 'base' because we share InstanceExpression for get/set
+					// FIXME: The async check is another hack but will probably fail with mutators
+					if (rc.CurrentType.IsStruct || rc.CurrentAnonymousMethod.Storey is AsyncTaskStorey)
+						InstanceExpression = new This (loc).Resolve (rc);
+				}
+
+				if (targs != null)
+					method = method.MakeGenericMethod (rc, targs);
+			}
+
+			//
+			// Only base will allow this invocation to happen.
+			//
+			if (method.IsAbstract) {
+				rc.Report.SymbolRelatedToPreviousError (method);
+				Error_CannotCallAbstractBase (rc, method.GetSignatureForError ());
+			}
+
+			return method;
+		}
+
+		protected void CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
+		{
+			if (InstanceExpression == null)
+				return;
+
+			if ((member.Modifiers & Modifiers.PROTECTED) != 0 && !(InstanceExpression is This)) {
+				if (!CheckProtectedMemberAccess (rc, member, InstanceExpression.Type)) {
+					Error_ProtectedMemberAccess (rc, member, InstanceExpression.Type, loc);
+				}
+			}
+		}
+
+		bool OverloadResolver.IInstanceQualifier.CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
+		{
+			if (InstanceExpression == null)
+				return true;
+
+			return InstanceExpression is This || CheckProtectedMemberAccess (rc, member, InstanceExpression.Type);
+		}
+
+		public static bool CheckProtectedMemberAccess<T> (ResolveContext rc, T member, TypeSpec qualifier) where T : MemberSpec
+		{
+			var ct = rc.CurrentType;
+			if (ct == qualifier)
+				return true;
+
+			if ((member.Modifiers & Modifiers.INTERNAL) != 0 && member.DeclaringType.MemberDefinition.IsInternalAsPublic (ct.MemberDefinition.DeclaringAssembly))
+				return true;
+
+			qualifier = qualifier.GetDefinition ();
+			if (ct != qualifier && !IsSameOrBaseQualifier (ct, qualifier)) {
+				return false;
+			}
+
+			return true;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return InstanceExpression != null && InstanceExpression.ContainsEmitWithAwait ();
+		}
+
+		public override bool HasConditionalAccess ()
+		{
+			return ConditionalAccess || (InstanceExpression != null && InstanceExpression.HasConditionalAccess ());
+		}
+
+		static bool IsSameOrBaseQualifier (TypeSpec type, TypeSpec qtype)
+		{
+			do {
+				type = type.GetDefinition ();
+
+				if (type == qtype || TypeManager.IsFamilyAccessible (qtype, type))
+					return true;
+
+				type = type.DeclaringType;
+			} while (type != null);
+
+			return false;
+		}
+
+		protected void DoBestMemberChecks<T> (ResolveContext rc, T member) where T : MemberSpec, IInterfaceMemberSpec
+		{
+			if (InstanceExpression != null) {
+				InstanceExpression = InstanceExpression.Resolve (rc);
+				CheckProtectedMemberAccess (rc, member);
+			}
+
+			if (member.MemberType.IsPointer && !rc.IsUnsafe) {
+				UnsafeError (rc, loc);
+			}
+
+			var dep = member.GetMissingDependencies ();
+			if (dep != null) {
+				ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
+			}
+
+			if (!rc.IsObsolete) {
+				ObsoleteAttribute oa = member.GetAttributeObsolete ();
+				if (oa != null)
+					AttributeTester.Report_ObsoleteMessage (oa, member.GetSignatureForError (), loc, rc.Report);
+			}
+
+			if (!(member is FieldSpec))
+				member.MemberDefinition.SetIsUsed ();
+		}
+
+		protected virtual void Error_CannotCallAbstractBase (ResolveContext rc, string name)
+		{
+			rc.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
+		}
+
+		public static void Error_ProtectedMemberAccess (ResolveContext rc, MemberSpec member, TypeSpec qualifier, Location loc)
+		{
+			rc.Report.SymbolRelatedToPreviousError (member);
+			rc.Report.Error (1540, loc,
+				"Cannot access protected member `{0}' via a qualifier of type `{1}'. The qualifier must be of type `{2}' or derived from it",
+				member.GetSignatureForError (), qualifier.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (InstanceExpression != null) {
+				InstanceExpression.FlowAnalysis (fc);
+
+				if (ConditionalAccess) {
+					fc.BranchConditionalAccessDefiniteAssignment ();
+				}
+			}
+		}
+
+		protected void ResolveConditionalAccessReceiver (ResolveContext rc)
+		{
+			if (!rc.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) {
+				if (HasConditionalAccess ()) {
+					conditional_access_receiver = true;
+					rc.Set (ResolveContext.Options.ConditionalAccessReceiver);
+				}
+			}
+		}
+
+		public bool ResolveInstanceExpression (ResolveContext rc, Expression rhs)
+		{
+			if (!ResolveInstanceExpressionCore (rc, rhs))
+				return false;
+
+			//
+			// Check intermediate value modification which won't have any effect
+			//
+			if (rhs != null && TypeSpec.IsValueType (InstanceExpression.Type)) {
+				var fexpr = InstanceExpression as FieldExpr;
+				if (fexpr != null) {
+					if (!fexpr.Spec.IsReadOnly || rc.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
+						return true;
+
+					if (fexpr.IsStatic) {
+						rc.Report.Error (1650, loc, "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
+							fexpr.GetSignatureForError ());
+					} else {
+						rc.Report.Error (1648, loc, "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
+							fexpr.GetSignatureForError ());
+					}
+
+					return true;
+				}
+
+				if (InstanceExpression is PropertyExpr || InstanceExpression is IndexerExpr || InstanceExpression is Invocation) {
+					if (rc.CurrentInitializerVariable != null) {
+						rc.Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
+							InstanceExpression.Type.GetSignatureForError (), InstanceExpression.GetSignatureForError ());
+					} else {
+						rc.Report.Error (1612, loc,
+							"Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
+							InstanceExpression.GetSignatureForError ());
+					}
+
+					return true;
+				}
+
+				var lvr = InstanceExpression as LocalVariableReference;
+				if (lvr != null) {
+
+					if (!lvr.local_info.IsReadonly)
+						return true;
+
+					rc.Report.Error (1654, loc, "Cannot assign to members of `{0}' because it is a `{1}'",
+						InstanceExpression.GetSignatureForError (), lvr.local_info.GetReadOnlyContext ());
+				}
+			}
+
+			return true;
+		}
+
+		bool ResolveInstanceExpressionCore (ResolveContext rc, Expression rhs)
+		{
+			if (IsStatic) {
+				if (InstanceExpression != null) {
+					if (InstanceExpression is TypeExpr) {
+						var t = InstanceExpression.Type;
+						do {
+							ObsoleteAttribute oa = t.GetAttributeObsolete ();
+							if (oa != null && !rc.IsObsolete) {
+								AttributeTester.Report_ObsoleteMessage (oa, t.GetSignatureForError (), loc, rc.Report);
+							}
+
+							t = t.DeclaringType;
+						} while (t != null);
+					} else {
+						var runtime_expr = InstanceExpression as RuntimeValueExpression;
+						if (runtime_expr == null || !runtime_expr.IsSuggestionOnly) {
+							rc.Report.Error (176, loc,
+								"Static member `{0}' cannot be accessed with an instance reference, qualify it with a type name instead",
+								GetSignatureForError ());
+						}
+					}
+
+					InstanceExpression = null;
+				}
+
+				return false;
+			}
+
+			if (InstanceExpression == null || InstanceExpression is TypeExpr) {
+				if (InstanceExpression != null || !This.IsThisAvailable (rc, true)) {
+					if (rc.HasSet (ResolveContext.Options.FieldInitializerScope)) {
+						rc.Report.Error (236, loc,
+							"A field initializer cannot reference the nonstatic field, method, or property `{0}'",
+							GetSignatureForError ());
+					} else {
+						var fe = this as FieldExpr;
+						if (fe != null && fe.Spec.MemberDefinition is PrimaryConstructorField) {
+							if (rc.HasSet (ResolveContext.Options.BaseInitializer)) {
+								rc.Report.Error (9005, loc, "Constructor initializer cannot access primary constructor parameters");
+							} else  {
+								rc.Report.Error (9006, loc, "An object reference is required to access primary constructor parameter `{0}'",
+									fe.Name);
+							}
+						} else {
+							rc.Report.Error (120, loc,
+								"An object reference is required to access non-static member `{0}'",
+								GetSignatureForError ());
+						}
+					}
+
+					InstanceExpression = new CompilerGeneratedThis (rc.CurrentType, loc).Resolve (rc);
+					return false;
+				}
+
+				if (!TypeManager.IsFamilyAccessible (rc.CurrentType, DeclaringType)) {
+					rc.Report.Error (38, loc,
+						"Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
+						DeclaringType.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
+				}
+
+				InstanceExpression = new This (loc).Resolve (rc);
+				return false;
+			}
+
+			var me = InstanceExpression as MemberExpr;
+			if (me != null) {
+				me.ResolveInstanceExpressionCore (rc, rhs);
+
+				var fe = me as FieldExpr;
+				if (fe != null && fe.IsMarshalByRefAccess (rc)) {
+					rc.Report.SymbolRelatedToPreviousError (me.DeclaringType);
+					rc.Report.Warning (1690, 1, loc,
+						"Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
+						me.GetSignatureForError ());
+				}
+
+				return true;
+			}
+
+			//
+			// Additional checks for l-value member access
+			//
+			if (rhs != null) {
+				if (InstanceExpression is UnboxCast) {
+					rc.Report.Error (445, InstanceExpression.Location, "Cannot modify the result of an unboxing conversion");
+				}
+			}
+
+			return true;
+		}
+
+		public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
+		{
+			if (left != null && !ConditionalAccess && left.IsNull && TypeSpec.IsReferenceType (left.Type)) {
+				ec.Report.Warning (1720, 1, left.Location,
+					"Expression will always cause a `{0}'", "System.NullReferenceException");
+			}
+
+			InstanceExpression = left;
+			return this;
+		}
+
+		protected void EmitInstance (EmitContext ec, bool prepare_for_load)
+		{
+			var inst = new InstanceEmitter (InstanceExpression, TypeSpec.IsValueType (InstanceExpression.Type));
+			inst.Emit (ec, ConditionalAccess);
+
+			if (prepare_for_load)
+				ec.Emit (OpCodes.Dup);
+		}
+
+		public abstract void SetTypeArguments (ResolveContext ec, TypeArguments ta);
+	}
+
+	public class ExtensionMethodCandidates
+	{
+		readonly NamespaceContainer container;
+		readonly IList<MethodSpec> methods;
+		readonly int index;
+		readonly IMemberContext context;
+
+		public ExtensionMethodCandidates (IMemberContext context, IList<MethodSpec> methods, NamespaceContainer nsContainer, int lookupIndex)
+		{
+			this.context = context;
+			this.methods = methods;
+			this.container = nsContainer;
+			this.index = lookupIndex;
+		}
+
+		public NamespaceContainer Container {
+			get {
+				return container;
+			}
+		}
+
+		public IMemberContext Context {
+			get {
+				return context;
+			}
+		}
+
+		public int LookupIndex {
+			get {
+				return index;
+			}
+		}
+
+		public IList<MethodSpec> Methods {
+			get {
+				return methods;
+			}
+		}
+	}
+
+	// 
+	// Represents a group of extension method candidates for whole namespace
+	// 
+	class ExtensionMethodGroupExpr : MethodGroupExpr, OverloadResolver.IErrorHandler
+	{
+		ExtensionMethodCandidates candidates;
+		public Expression ExtensionExpression;
+
+		public ExtensionMethodGroupExpr (ExtensionMethodCandidates candidates, Expression extensionExpr, Location loc)
+			: base (candidates.Methods.Cast<MemberSpec>().ToList (), extensionExpr.Type, loc)
+		{
+			this.candidates = candidates;
+			this.ExtensionExpression = extensionExpr;
+		}
+
+		public override bool IsStatic {
+			get { return true; }
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (ConditionalAccess) {
+				fc.BranchConditionalAccessDefiniteAssignment ();
+			}
+		}
+
+		//
+		// For extension methodgroup we are not looking for base members but parent
+		// namespace extension methods
+		//
+		public override IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
+		{
+			// TODO: candidates are null only when doing error reporting, that's
+			// incorrect. We have to discover same extension methods in error mode
+			if (candidates == null)
+				return null;
+
+			int arity = type_arguments == null ? 0 : type_arguments.Count;
+
+			candidates = candidates.Container.LookupExtensionMethod (candidates.Context, ExtensionExpression.Type, Name, arity, candidates.LookupIndex);
+			if (candidates == null)
+				return null;
+
+			return candidates.Methods.Cast<MemberSpec> ().ToList ();
+		}
+
+		public override MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
+		{
+			// We are already here
+			return null;
+		}
+
+		public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, OverloadResolver.IErrorHandler ehandler, OverloadResolver.Restrictions restr)
+		{
+			if (arguments == null)
+				arguments = new Arguments (1);
+
+			ExtensionExpression = ExtensionExpression.Resolve (ec);
+			if (ExtensionExpression == null)
+				return null;
+
+			var cand = candidates;
+			var atype = ConditionalAccess ? Argument.AType.ExtensionTypeConditionalAccess : Argument.AType.ExtensionType;
+			arguments.Insert (0, new Argument (ExtensionExpression, atype));
+			var res = base.OverloadResolve (ec, ref arguments, ehandler ?? this, restr);
+			
+			// Restore candidates in case we are running in probing mode 
+			candidates = cand;
+
+			// Store resolved argument and restore original arguments
+			if (res == null) {
+				// Clean-up modified arguments for error reporting
+				arguments.RemoveAt (0);
+				return null;
+			}
+
+			var me = ExtensionExpression as MemberExpr;
+			if (me != null) {
+				me.ResolveInstanceExpression (ec, null);
+				var fe = me as FieldExpr;
+				if (fe != null)
+					fe.Spec.MemberDefinition.SetIsUsed ();
+			}
+
+			InstanceExpression = null;
+			return this;
+		}
+
+		#region IErrorHandler Members
+
+		bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous)
+		{
+			return false;
+		}
+
+		bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
+		{
+			rc.Report.SymbolRelatedToPreviousError (best);
+			rc.Report.Error (1928, loc,
+				"Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
+				queried_type.GetSignatureForError (), Name, best.GetSignatureForError ());
+
+			if (index == 0) {
+				rc.Report.Error (1929, loc,
+					"Extension method instance type `{0}' cannot be converted to `{1}'",
+					arg.Type.GetSignatureForError (), ((MethodSpec)best).Parameters.ExtensionMethodType.GetSignatureForError ());
+			}
+
+			return true;
+		}
+
+		bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
+		{
+			return false;
+		}
+
+		bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
+		{
+			return false;
+		}
+
+		#endregion
+	}
+
+	/// <summary>
+	///   MethodGroupExpr represents a group of method candidates which
+	///   can be resolved to the best method overload
+	/// </summary>
+	public class MethodGroupExpr : MemberExpr, OverloadResolver.IBaseMembersProvider
+	{
+		static readonly MemberSpec[] Excluded = new MemberSpec[0];
+
+		protected IList<MemberSpec> Methods;
+		MethodSpec best_candidate;
+		TypeSpec best_candidate_return;
+		protected TypeArguments type_arguments;
+
+ 		SimpleName simple_name;
+		protected TypeSpec queried_type;
+
+		public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location loc)
+		{
+			Methods = mi;
+			this.loc = loc;
+			this.type = InternalType.MethodGroup;
+
+			eclass = ExprClass.MethodGroup;
+			queried_type = type;
+		}
+
+		public MethodGroupExpr (MethodSpec m, TypeSpec type, Location loc)
+			: this (new MemberSpec[] { m }, type, loc)
+		{
+		}
+
+		#region Properties
+
+		public MethodSpec BestCandidate {
+			get {
+				return best_candidate;
+			}
+		}
+
+		public TypeSpec BestCandidateReturnType {
+			get {
+				return best_candidate_return;
+			}
+		}
+
+		public IList<MemberSpec> Candidates {
+			get {
+				return Methods;
+			}
+		}
+
+		protected override TypeSpec DeclaringType {
+			get {
+				return queried_type;
+			}
+		}
+
+		public bool IsConditionallyExcluded {
+			get {
+				return Methods == Excluded;
+			}
+		}
+
+		public override bool IsInstance {
+			get {
+				if (best_candidate != null)
+					return !best_candidate.IsStatic;
+
+				return false;
+			}
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return InstanceExpression == null || InstanceExpression.IsSideEffectFree;
+			}
+		}
+
+		public override bool IsStatic {
+			get {
+				if (best_candidate != null)
+					return best_candidate.IsStatic;
+
+				return false;
+			}
+		}
+
+		public override string KindName {
+			get { return "method"; }
+		}
+
+		public override string Name {
+			get {
+				if (best_candidate != null)
+					return best_candidate.Name;
+
+				// TODO: throw ?
+				return Methods.First ().Name;
+			}
+		}
+
+		#endregion
+
+		//
+		// When best candidate is already know this factory can be used
+		// to avoid expensive overload resolution to be called
+		//
+		// NOTE: InstanceExpression has to be set manually
+		//
+		public static MethodGroupExpr CreatePredefined (MethodSpec best, TypeSpec queriedType, Location loc)
+		{
+			return new MethodGroupExpr (best, queriedType, loc) {
+				best_candidate = best,
+				best_candidate_return = best.ReturnType
+			};
+		}
+
+		public override string GetSignatureForError ()
+		{
+			if (best_candidate != null)
+				return best_candidate.GetSignatureForError ();
+
+			return Methods.First ().GetSignatureForError ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (best_candidate == null) {
+				ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
+				return null;
+			}
+
+			if (IsConditionallyExcluded)
+				ec.Report.Error (765, loc,
+					"Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
+
+			if (ConditionalAccess)
+				Error_NullShortCircuitInsideExpressionTree (ec);
+
+			return new TypeOfMethod (best_candidate, loc);
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			this.eclass = ExprClass.MethodGroup;
+
+			if (InstanceExpression != null) {
+				InstanceExpression = InstanceExpression.Resolve (ec);
+				if (InstanceExpression == null)
+					return null;
+			}
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public void EmitCall (EmitContext ec, Arguments arguments, bool statement)
+		{
+			var call = new CallEmitter ();
+			call.InstanceExpression = InstanceExpression;
+			call.ConditionalAccess = ConditionalAccess;
+
+			if (statement)
+				call.EmitStatement (ec, best_candidate, arguments, loc);
+			else
+				call.Emit (ec, best_candidate, arguments, loc);
+		}
+
+		public void EmitCall (EmitContext ec, Arguments arguments, TypeSpec conditionalAccessReceiver, bool statement)
+		{
+			ec.ConditionalAccess = new ConditionalAccessContext (conditionalAccessReceiver, ec.DefineLabel ()) {
+				Statement = statement
+			};
+
+			EmitCall (ec, arguments, statement);
+
+			ec.CloseConditionalAccess (!statement && best_candidate_return != conditionalAccessReceiver && conditionalAccessReceiver.IsNullableType ? conditionalAccessReceiver : null);
+		}
+
+		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
+		{
+			ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
+				Name, target.GetSignatureForError ());
+		}
+
+		public static bool IsExtensionMethodArgument (Expression expr)
+		{
+			//
+			// LAMESPEC: No details about which expressions are not allowed
+			//
+			return !(expr is TypeExpr) && !(expr is BaseThis);
+		}
+
+		/// <summary>
+		///   Find the Applicable Function Members (7.4.2.1)
+		///
+		///   me: Method Group expression with the members to select.
+		///       it might contain constructors or methods (or anything
+		///       that maps to a method).
+		///
+		///   Arguments: ArrayList containing resolved Argument objects.
+		///
+		///   loc: The location if we want an error to be reported, or a Null
+		///        location for "probing" purposes.
+		///
+		///   Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
+		///            that is the best match of me on Arguments.
+		///
+		/// </summary>
+		public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments args, OverloadResolver.IErrorHandler cerrors, OverloadResolver.Restrictions restr)
+		{
+			// TODO: causes issues with probing mode, remove explicit Kind check
+			if (best_candidate != null && best_candidate.Kind == MemberKind.Destructor)
+				return this;
+
+			var r = new OverloadResolver (Methods, type_arguments, restr, loc);
+			if ((restr & OverloadResolver.Restrictions.NoBaseMembers) == 0) {
+				r.BaseMembersProvider = this;
+				r.InstanceQualifier = this;
+			}
+
+			if (cerrors != null)
+				r.CustomErrors = cerrors;
+
+			// TODO: When in probing mode do IsApplicable only and when called again do VerifyArguments for full error reporting
+			best_candidate = r.ResolveMember<MethodSpec> (ec, ref args);
+			if (best_candidate == null) {
+				if (!r.BestCandidateIsDynamic)
+					return null;
+
+				if (simple_name != null && ec.IsStatic)
+					InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name);
+
+				return this;
+			}
+
+			// Overload resolver had to create a new method group, all checks bellow have already been executed
+			if (r.BestCandidateNewMethodGroup != null)
+				return r.BestCandidateNewMethodGroup;
+
+			if (best_candidate.Kind == MemberKind.Method && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0) {
+				if (InstanceExpression != null) {
+					if (best_candidate.IsExtensionMethod && args[0].Expr == InstanceExpression) {
+						InstanceExpression = null;
+					} else {
+						if (simple_name != null && best_candidate.IsStatic) {
+							InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name);
+						}
+
+						InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup | ResolveFlags.Type);
+					}
+				}
+
+				ResolveInstanceExpression (ec, null);
+			}
+
+			var base_override = CandidateToBaseOverride (ec, best_candidate);
+			if (base_override == best_candidate) {
+				best_candidate_return = r.BestCandidateReturnType;
+			} else {
+				best_candidate = base_override;
+				best_candidate_return = best_candidate.ReturnType;
+			}
+
+			if (best_candidate.IsGeneric && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0 && TypeParameterSpec.HasAnyTypeParameterConstrained (best_candidate.GenericDefinition)) {
+				ConstraintChecker cc = new ConstraintChecker (ec);
+				cc.CheckAll (best_candidate.GetGenericMethodDefinition (), best_candidate.TypeArguments, best_candidate.Constraints, loc);
+			}
+
+			//
+			// Additional check for possible imported base override method which
+			// could not be done during IsOverrideMethodBaseTypeAccessible
+			//
+			if (best_candidate.IsVirtual && (best_candidate.DeclaringType.Modifiers & Modifiers.PROTECTED) != 0 &&
+				best_candidate.MemberDefinition.IsImported && !best_candidate.DeclaringType.IsAccessible (ec)) {
+				ec.Report.SymbolRelatedToPreviousError (best_candidate);
+				ErrorIsInaccesible (ec, best_candidate.GetSignatureForError (), loc);
+			}
+
+			// Speed up the check by not doing it on disallowed targets
+			if (best_candidate_return.Kind == MemberKind.Void && best_candidate.IsConditionallyExcluded (ec))
+				Methods = Excluded;
+
+			return this;
+		}
+
+		public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
+		{
+			var fe = left as FieldExpr;
+			if (fe != null) {
+				//
+				// Using method-group on struct fields makes the struct assigned. I am not sure
+				// why but that's what .net does
+				//
+				fe.Spec.MemberDefinition.SetIsAssigned ();
+			}
+
+			simple_name = original;
+			return base.ResolveMemberAccess (ec, left, original);
+		}
+
+		public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
+		{
+			type_arguments = ta;
+		}
+
+		#region IBaseMembersProvider Members
+
+		public virtual IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
+		{
+			return baseType == null ? null : MemberCache.FindMembers (baseType, Methods [0].Name, false);
+		}
+
+		public IParametersMember GetOverrideMemberParameters (MemberSpec member)
+		{
+			if (queried_type == member.DeclaringType)
+				return null;
+
+			return MemberCache.FindMember (queried_type, new MemberFilter ((MethodSpec) member),
+				BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
+		}
+
+		//
+		// Extension methods lookup after ordinary methods candidates failed to apply
+		//
+		public virtual MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
+		{
+			if (InstanceExpression == null || InstanceExpression.eclass == ExprClass.Type)
+				return null;
+
+			if (!IsExtensionMethodArgument (InstanceExpression))
+				return null;
+
+			int arity = type_arguments == null ? 0 : type_arguments.Count;
+			var methods = rc.LookupExtensionMethod (InstanceExpression.Type, Methods[0].Name, arity);
+			if (methods == null)
+				return null;
+
+			var emg = new ExtensionMethodGroupExpr (methods, InstanceExpression, loc);
+			emg.SetTypeArguments (rc, type_arguments);
+			return emg;
+		}
+
+		#endregion
+	}
+
+	struct ConstructorInstanceQualifier : OverloadResolver.IInstanceQualifier
+	{
+		public ConstructorInstanceQualifier (TypeSpec type)
+			: this ()
+		{
+			InstanceType = type;
+		}
+
+		public TypeSpec InstanceType { get; private set; }
+
+		public bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
+		{
+			return MemberExpr.CheckProtectedMemberAccess (rc, member, InstanceType);
+		}
+	}
+
+	public struct OverloadResolver
+	{
+		[Flags]
+		public enum Restrictions
+		{
+			None = 0,
+			DelegateInvoke = 1,
+			ProbingOnly	= 1 << 1,
+			CovariantDelegate = 1 << 2,
+			NoBaseMembers = 1 << 3,
+			BaseMembersIncluded = 1 << 4,
+			GetEnumeratorLookup = 1 << 5
+		}
+
+		public interface IBaseMembersProvider
+		{
+			IList<MemberSpec> GetBaseMembers (TypeSpec baseType);
+			IParametersMember GetOverrideMemberParameters (MemberSpec member);
+			MethodGroupExpr LookupExtensionMethod (ResolveContext rc);
+		}
+
+		public interface IErrorHandler
+		{
+			bool AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous);
+			bool ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument a, int index);
+			bool NoArgumentMatch (ResolveContext rc, MemberSpec best);
+			bool TypeInferenceFailed (ResolveContext rc, MemberSpec best);
+		}
+
+		public interface IInstanceQualifier
+		{
+			TypeSpec InstanceType { get; }
+			bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member);
+		}
+
+		sealed class NoBaseMembers : IBaseMembersProvider
+		{
+			public static readonly IBaseMembersProvider Instance = new NoBaseMembers ();
+
+			public IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
+			{
+				return null;
+			}
+
+			public IParametersMember GetOverrideMemberParameters (MemberSpec member)
+			{
+				return null;
+			}
+
+			public MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
+			{
+				return null;
+			}
+		}
+
+		struct AmbiguousCandidate
+		{
+			public readonly MemberSpec Member;
+			public readonly bool Expanded;
+			public readonly AParametersCollection Parameters;
+
+			public AmbiguousCandidate (MemberSpec member, AParametersCollection parameters, bool expanded)
+			{
+				Member = member;
+				Parameters = parameters;
+				Expanded = expanded;
+			}
+		}
+
+		Location loc;
+		IList<MemberSpec> members;
+		TypeArguments type_arguments;
+		IBaseMembersProvider base_provider;
+		IErrorHandler custom_errors;
+		IInstanceQualifier instance_qualifier;
+		Restrictions restrictions;
+		MethodGroupExpr best_candidate_extension_group;
+		TypeSpec best_candidate_return_type;
+
+		SessionReportPrinter lambda_conv_msgs;
+
+		public OverloadResolver (IList<MemberSpec> members, Restrictions restrictions, Location loc)
+			: this (members, null, restrictions, loc)
+		{
+		}
+
+		public OverloadResolver (IList<MemberSpec> members, TypeArguments targs, Restrictions restrictions, Location loc)
+			: this ()
+		{
+			if (members == null || members.Count == 0)
+				throw new ArgumentException ("empty members set");
+
+			this.members = members;
+			this.loc = loc;
+			type_arguments = targs;
+			this.restrictions = restrictions;
+			if (IsDelegateInvoke)
+				this.restrictions |= Restrictions.NoBaseMembers;
+
+			base_provider = NoBaseMembers.Instance;
+		}
+
+		#region Properties
+
+		public IBaseMembersProvider BaseMembersProvider {
+			get {
+				return base_provider;
+			}
+			set {
+				base_provider = value;
+			}
+		}
+
+		public bool BestCandidateIsDynamic { get; set; }
+
+		//
+		// Best candidate was found in newly created MethodGroupExpr, used by extension methods
+		//
+		public MethodGroupExpr BestCandidateNewMethodGroup {
+			get {
+				return best_candidate_extension_group;
+			}
+		}
+
+		//
+		// Return type can be different between best candidate and closest override
+		//
+		public TypeSpec BestCandidateReturnType {
+			get {
+				return best_candidate_return_type;
+			}
+		}
+
+		public IErrorHandler CustomErrors {
+			get {
+				return custom_errors;
+			}
+			set {
+				custom_errors = value;
+			}
+		}
+
+		TypeSpec DelegateType {
+			get {
+				if ((restrictions & Restrictions.DelegateInvoke) == 0)
+					throw new InternalErrorException ("Not running in delegate mode", loc);
+
+				return members [0].DeclaringType;
+			}
+		}
+
+		public IInstanceQualifier InstanceQualifier {
+			get {
+				return instance_qualifier;
+			}
+			set {
+				instance_qualifier = value;
+			}
+		}
+
+		bool IsProbingOnly {
+			get {
+				return (restrictions & Restrictions.ProbingOnly) != 0;
+			}
+		}
+
+		bool IsDelegateInvoke {
+			get {
+				return (restrictions & Restrictions.DelegateInvoke) != 0;
+			}
+		}
+
+		#endregion
+
+		//
+		//  7.4.3.3  Better conversion from expression
+		//  Returns :   1    if a->p is better,
+		//              2    if a->q is better,
+		//              0 if neither is better
+		//
+		static int BetterExpressionConversion (ResolveContext ec, Argument a, TypeSpec p, TypeSpec q)
+		{
+			TypeSpec argument_type = a.Type;
+
+			//
+			// If argument is an anonymous function
+			//
+			if (argument_type == InternalType.AnonymousMethod && ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2) {
+				//
+				// p and q are delegate types or expression tree types
+				//
+				if (p.IsExpressionTreeType || q.IsExpressionTreeType) {
+					if (q.MemberDefinition != p.MemberDefinition) {
+						return 0;
+					}
+
+					//
+					// Uwrap delegate from Expression<T>
+					//
+					q = TypeManager.GetTypeArguments (q)[0];
+					p = TypeManager.GetTypeArguments (p)[0];
+				}
+
+				var p_m = Delegate.GetInvokeMethod (p);
+				var q_m = Delegate.GetInvokeMethod (q);
+
+				//
+				// With identical parameter lists
+				//
+				if (!TypeSpecComparer.Equals (p_m.Parameters.Types, q_m.Parameters.Types))
+					return 0;
+
+				p = p_m.ReturnType;
+				var orig_q = q;
+				q = q_m.ReturnType;
+
+				//
+				// if p is void returning, and q has a return type Y, then C2 is the better conversion.
+				//
+				if (p.Kind == MemberKind.Void) {
+					return q.Kind != MemberKind.Void ? 2 : 0;
+				}
+
+				//
+				// if p has a return type Y, and q is void returning, then C1 is the better conversion.
+				//
+				if (q.Kind == MemberKind.Void) {
+					return p.Kind != MemberKind.Void ? 1: 0;
+				}
+
+				var am = (AnonymousMethodExpression) a.Expr;
+
+				//
+				// When anonymous method is an asynchronous, and P has a return type Task<Y1>, and Q has a return type Task<Y2>
+				// better conversion is performed between underlying types Y1 and Y2
+				//
+				if (p.IsGenericTask || q.IsGenericTask) {
+					if (am.Block.IsAsync && p.IsGenericTask && q.IsGenericTask) {
+						q = q.TypeArguments[0];
+						p = p.TypeArguments[0];
+					}
+				}
+
+				if (q != p) {
+					//
+					// An inferred return type X exists for E in the context of that parameter list, and 
+					// the conversion from X to Y1 is better than the conversion from X to Y2
+					//
+					argument_type = am.InferReturnType (ec, null, orig_q);
+					if (argument_type == null) {
+						// TODO: Can this be hit?
+						return 1;
+					}
+
+					if (argument_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+						argument_type = ec.BuiltinTypes.Object;
+				}
+			}
+
+			if (argument_type == p)
+				return 1;
+
+			if (argument_type == q)
+				return 2;
+
+			//
+			// The parameters are identicial and return type is not void, use better type conversion
+			// on return type to determine better one
+			//
+			return BetterTypeConversion (ec, p, q);
+		}
+
+		//
+		// 7.4.3.4  Better conversion from type
+		//
+		public static int BetterTypeConversion (ResolveContext ec, TypeSpec p, TypeSpec q)
+		{
+			if (p == null || q == null)
+				throw new InternalErrorException ("BetterTypeConversion got a null conversion");
+
+			switch (p.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+				if (q.BuiltinType == BuiltinTypeSpec.Type.UInt || q.BuiltinType == BuiltinTypeSpec.Type.ULong)
+					return 1;
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				if (q.BuiltinType == BuiltinTypeSpec.Type.ULong)
+					return 1;
+				break;
+			case BuiltinTypeSpec.Type.SByte:
+				switch (q.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.ULong:
+					return 1;
+				}
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				switch (q.BuiltinType) {
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.ULong:
+					return 1;
+				}
+				break;
+			case BuiltinTypeSpec.Type.Dynamic:
+				// Dynamic is never better
+				return 2;
+			}
+
+			switch (q.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+				if (p.BuiltinType == BuiltinTypeSpec.Type.UInt || p.BuiltinType == BuiltinTypeSpec.Type.ULong)
+					return 2;
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				if (p.BuiltinType == BuiltinTypeSpec.Type.ULong)
+					return 2;
+				break;
+			case BuiltinTypeSpec.Type.SByte:
+				switch (p.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.ULong:
+					return 2;
+				}
+				break;
+			case BuiltinTypeSpec.Type.Short:
+				switch (p.BuiltinType) {
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.ULong:
+					return 2;
+				}
+				break;
+			case BuiltinTypeSpec.Type.Dynamic:
+				// Dynamic is never better
+				return 1;
+			}
+
+			// FIXME: handle lifted operators
+
+			// TODO: this is expensive
+			Expression p_tmp = new EmptyExpression (p);
+			Expression q_tmp = new EmptyExpression (q);
+
+			bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
+			bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
+
+			if (p_to_q && !q_to_p)
+				return 1;
+
+			if (q_to_p && !p_to_q)
+				return 2;
+
+			return 0;
+		}
+
+		/// <summary>
+		///   Determines "Better function" between candidate
+		///   and the current best match
+		/// </summary>
+		/// <remarks>
+		///    Returns a boolean indicating :
+		///     false if candidate ain't better
+		///     true  if candidate is better than the current best match
+		/// </remarks>
+		static bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params,
+			MemberSpec best, AParametersCollection bparam, bool best_params)
+		{
+			AParametersCollection candidate_pd = ((IParametersMember) candidate).Parameters;
+			AParametersCollection best_pd = ((IParametersMember) best).Parameters;
+
+			bool better_at_least_one = false;
+			bool are_equivalent = true;
+			int args_count = args == null ? 0 : args.Count;
+			int j = 0;
+			Argument a = null;
+			TypeSpec ct, bt;
+			for (int c_idx = 0, b_idx = 0; j < args_count; ++j, ++c_idx, ++b_idx) {
+				a = args[j];
+
+				// Default arguments are ignored for better decision
+				if (a.IsDefaultArgument)
+					break;
+
+				//
+				// When comparing named argument the parameter type index has to be looked up
+				// in original parameter set (override version for virtual members)
+				//
+				NamedArgument na = a as NamedArgument;
+				if (na != null) {
+					int idx = cparam.GetParameterIndexByName (na.Name);
+					ct = candidate_pd.Types[idx];
+					if (candidate_params && candidate_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
+						ct = TypeManager.GetElementType (ct);
+
+					idx = bparam.GetParameterIndexByName (na.Name);
+					bt = best_pd.Types[idx];
+					if (best_params && best_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
+						bt = TypeManager.GetElementType (bt);
+				} else {
+					ct = candidate_pd.Types[c_idx];
+					bt = best_pd.Types[b_idx];
+
+					if (candidate_params && candidate_pd.FixedParameters[c_idx].ModFlags == Parameter.Modifier.PARAMS) {
+						ct = TypeManager.GetElementType (ct);
+						--c_idx;
+					}
+
+					if (best_params && best_pd.FixedParameters[b_idx].ModFlags == Parameter.Modifier.PARAMS) {
+						bt = TypeManager.GetElementType (bt);
+						--b_idx;
+					}
+				}
+
+				if (TypeSpecComparer.IsEqual (ct, bt))
+					continue;
+
+				are_equivalent = false;
+				int result = BetterExpressionConversion (ec, a, ct, bt);
+
+				// for each argument, the conversion to 'ct' should be no worse than 
+				// the conversion to 'bt'.
+				if (result == 2)
+					return false;
+
+				// for at least one argument, the conversion to 'ct' should be better than 
+				// the conversion to 'bt'.
+				if (result != 0)
+					better_at_least_one = true;
+			}
+
+			if (better_at_least_one)
+				return true;
+
+			//
+			// Tie-breaking rules are applied only for equivalent parameter types
+			//
+			if (!are_equivalent)
+				return false;
+
+			//
+			// If candidate is applicable in its normal form and best has a params array and is applicable
+			// only in its expanded form, then candidate is better
+			//
+			if (candidate_params != best_params)
+				return !candidate_params;
+
+			//
+			// We have not reached end of parameters list due to params or used default parameters
+			//
+			while (j < candidate_pd.Count && j < best_pd.Count) {
+				var cand_param = candidate_pd.FixedParameters [j];
+				var best_param = best_pd.FixedParameters [j];
+
+				if (candidate_pd.Count == best_pd.Count) {
+					//
+					// LAMESPEC:
+					//
+					// void Foo (int i = 0) is better than void Foo (params int[]) for Foo ()
+					// void Foo (string[] s, string value = null) is better than Foo (string s, params string[]) for Foo (null) or Foo ()
+					//
+					if (cand_param.HasDefaultValue != best_param.HasDefaultValue)
+						return cand_param.HasDefaultValue;
+
+					if (cand_param.HasDefaultValue) {
+						++j;
+						continue;
+					}
+				} else {
+					//
+					// Neither is better when not all arguments are provided
+					//
+					// void Foo (string s, int i = 0) <-> Foo (string s, int i = 0, int i2 = 0)
+					// void Foo (string s, int i = 0) <-> Foo (string s, byte i = 0)
+					// void Foo (string s, params int[]) <-> Foo (string s, params byte[])
+					//
+					if (cand_param.HasDefaultValue && best_param.HasDefaultValue)
+						return false;
+				}
+
+				break;
+			}
+
+			if (candidate_pd.Count != best_pd.Count)
+				return candidate_pd.Count < best_pd.Count;
+
+			//
+			// One is a non-generic method and second is a generic method, then non-generic is better
+			//
+			if (best.IsGeneric != candidate.IsGeneric)
+				return best.IsGeneric;
+
+			//
+			// Both methods have the same number of parameters, and the parameters have equal types
+			// Pick the "more specific" signature using rules over original (non-inflated) types
+			//
+			var candidate_def_pd = ((IParametersMember) candidate.MemberDefinition).Parameters;
+			var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters;
+
+			bool specific_at_least_once = false;
+			for (j = 0; j < args_count; ++j) {
+				NamedArgument na = args_count == 0 ? null : args [j] as NamedArgument;
+				if (na != null) {
+					ct = candidate_def_pd.Types[cparam.GetParameterIndexByName (na.Name)];
+					bt = best_def_pd.Types[bparam.GetParameterIndexByName (na.Name)];
+				} else {
+					ct = candidate_def_pd.Types[j];
+					bt = best_def_pd.Types[j];
+				}
+
+				if (ct == bt)
+					continue;
+				TypeSpec specific = MoreSpecific (ct, bt);
+				if (specific == bt)
+					return false;
+				if (specific == ct)
+					specific_at_least_once = true;
+			}
+
+			if (specific_at_least_once)
+				return true;
+
+			return false;
+		}
+
+		static bool CheckInflatedArguments (MethodSpec ms)
+		{
+			if (!TypeParameterSpec.HasAnyTypeParameterTypeConstrained (ms.GenericDefinition))
+				return true;
+
+			// Setup constraint checker for probing only
+			ConstraintChecker cc = new ConstraintChecker (null);
+
+			var mp = ms.Parameters.Types;
+			for (int i = 0; i < mp.Length; ++i) {
+				var type = mp[i] as InflatedTypeSpec;
+				if (type == null)
+					continue;
+
+				var targs = type.TypeArguments;
+				if (targs.Length == 0)
+					continue;
+
+				// TODO: Checking inflated MVAR arguments should be enough
+				if (!cc.CheckAll (type.GetDefinition (), targs, type.Constraints, Location.Null))
+					return false;
+			}
+
+			return true;
+		}
+
+		public static void Error_ConstructorMismatch (ResolveContext rc, TypeSpec type, int argCount, Location loc)
+		{
+			rc.Report.Error (1729, loc,
+				"The type `{0}' does not contain a constructor that takes `{1}' arguments",
+				type.GetSignatureForError (), argCount.ToString ());
+		}
+
+		//
+		// Determines if the candidate method is applicable to the given set of arguments
+		// There could be two different set of parameters for same candidate where one
+		// is the closest override for default values and named arguments checks and second
+		// one being the virtual base for the parameter types and modifiers.
+		//
+		// A return value rates candidate method compatibility,
+		// 0 = the best, int.MaxValue = the worst
+		// -1 = fatal error
+		//
+		int IsApplicable (ResolveContext ec, ref Arguments arguments, int arg_count, ref MemberSpec candidate, IParametersMember pm, ref bool params_expanded_form, ref bool dynamicArgument, ref TypeSpec returnType, bool errorMode)
+		{
+			// Parameters of most-derived type used mainly for named and optional parameters
+			var pd = pm.Parameters;
+
+			// Used for params modifier only, that's legacy of C# 1.0 which uses base type for
+			// params modifier instead of most-derived type
+			var cpd = ((IParametersMember) candidate).Parameters;
+			int param_count = pd.Count;
+			int optional_count = 0;
+			int score;
+			Arguments orig_args = arguments;
+
+			if (arg_count != param_count) {
+				//
+				// No arguments expansion when doing exact match for delegates
+				//
+				if ((restrictions & Restrictions.CovariantDelegate) == 0) {
+					for (int i = 0; i < pd.Count; ++i) {
+						if (pd.FixedParameters[i].HasDefaultValue) {
+							optional_count = pd.Count - i;
+							break;
+						}
+					}
+				}
+
+				if (optional_count != 0) {
+					// Readjust expected number when params used
+					if (cpd.HasParams) {
+						optional_count--;
+						if (arg_count < param_count)
+							param_count--;
+					} else if (arg_count > param_count) {
+						int args_gap = System.Math.Abs (arg_count - param_count);
+						return int.MaxValue - 10000 + args_gap;
+					} else if (arg_count < param_count - optional_count) {
+						int args_gap = System.Math.Abs (param_count - optional_count - arg_count);
+						return int.MaxValue - 10000 + args_gap;
+					}
+				} else if (arg_count != param_count) {
+					int args_gap = System.Math.Abs (arg_count - param_count);
+					if (!cpd.HasParams)
+						return int.MaxValue - 10000 + args_gap;
+					if (arg_count < param_count - 1)
+						return int.MaxValue - 10000 + args_gap;
+				}
+
+				// Resize to fit optional arguments
+				if (optional_count != 0) {
+					if (arguments == null) {
+						arguments = new Arguments (optional_count);
+					} else {
+						// Have to create a new container, so the next run can do same
+						var resized = new Arguments (param_count);
+						resized.AddRange (arguments);
+						arguments = resized;
+					}
+
+					for (int i = arg_count; i < param_count; ++i)
+						arguments.Add (null);
+				}
+			}
+
+			if (arg_count > 0) {
+				//
+				// Shuffle named arguments to the right positions if there are any
+				//
+				if (arguments[arg_count - 1] is NamedArgument) {
+					arg_count = arguments.Count;
+
+					for (int i = 0; i < arg_count; ++i) {
+						bool arg_moved = false;
+						while (true) {
+							NamedArgument na = arguments[i] as NamedArgument;
+							if (na == null)
+								break;
+
+							int index = pd.GetParameterIndexByName (na.Name);
+
+							// Named parameter not found
+							if (index < 0)
+								return (i + 1) * 3;
+
+							// already reordered
+							if (index == i)
+								break;
+
+							Argument temp;
+							if (index >= param_count) {
+								// When using parameters which should not be available to the user
+								if ((cpd.FixedParameters[index].ModFlags & Parameter.Modifier.PARAMS) == 0)
+									break;
+
+								arguments.Add (null);
+								++arg_count;
+								temp = null;
+							} else {
+								if (index == arg_count) 
+									return (i + 1) * 3;
+
+								temp = arguments [index];
+
+								// The slot has been taken by positional argument
+								if (temp != null && !(temp is NamedArgument))
+									break;
+							}
+
+							if (!arg_moved) {
+								arguments = arguments.MarkOrderedArgument (na);
+								arg_moved = true;
+							}
+
+							if (arguments == orig_args) {
+								arguments = new Arguments (orig_args.Count);
+								arguments.AddRange (orig_args);
+							}
+
+							arguments[index] = arguments[i];
+							arguments[i] = temp;
+
+							if (temp == null)
+								break;
+						}
+					}
+				} else {
+					arg_count = arguments.Count;
+				}
+			} else if (arguments != null) {
+				arg_count = arguments.Count;
+			}
+
+			//
+			// Don't do any expensive checks when the candidate cannot succeed
+			//
+			if (arg_count != param_count && !cpd.HasParams)
+				return (param_count - arg_count) * 2 + 1;
+
+			var dep = candidate.GetMissingDependencies ();
+			if (dep != null) {
+				ImportedTypeDefinition.Error_MissingDependency (ec, dep, loc);
+				return -1;
+			}
+
+			//
+			// 1. Handle generic method using type arguments when specified or type inference
+			//
+			TypeSpec[] ptypes;
+			var ms = candidate as MethodSpec;
+			if (ms != null && ms.IsGeneric) {
+				if (type_arguments != null) {
+					var g_args_count = ms.Arity;
+					if (g_args_count != type_arguments.Count)
+						return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count);
+
+					if (type_arguments.Arguments != null)
+						ms = ms.MakeGenericMethod (ec, type_arguments.Arguments);
+				} else {
+					//
+					// Deploy custom error reporting for infered anonymous expression or lambda methods. When
+					// probing lambda methods keep all errors reported in separate set and once we are done and no best
+					// candidate was found use the set to report more details about what was wrong with lambda body.
+					// The general idea is to distinguish between code errors and errors caused by
+					// trial-and-error type inference
+					//
+					if (lambda_conv_msgs == null) {
+						for (int i = 0; i < arg_count; i++) {
+							Argument a = arguments[i];
+							if (a == null)
+								continue;
+
+							var am = a.Expr as AnonymousMethodExpression;
+							if (am != null) {
+								if (lambda_conv_msgs == null)
+									lambda_conv_msgs = new SessionReportPrinter ();
+
+								am.TypeInferenceReportPrinter = lambda_conv_msgs;
+							}
+						}
+					}
+
+					var ti = new TypeInference (arguments);
+					TypeSpec[] i_args = ti.InferMethodArguments (ec, ms);
+
+					if (i_args == null)
+						return ti.InferenceScore - 20000;
+
+					//
+					// Clear any error messages when the result was success
+					//
+					if (lambda_conv_msgs != null)
+						lambda_conv_msgs.ClearSession ();
+
+					if (i_args.Length != 0) {
+						if (!errorMode) {
+							foreach (var ta in i_args) {
+								if (!ta.IsAccessible (ec))
+									return ti.InferenceScore - 10000;
+							}
+						}
+
+						ms = ms.MakeGenericMethod (ec, i_args);
+					}
+				}
+
+				//
+				// Type arguments constraints have to match for the method to be applicable
+				//
+				if (!CheckInflatedArguments (ms)) {
+					candidate = ms;
+					return int.MaxValue - 25000;
+				}
+
+				//
+				// We have a generic return type and at same time the method is override which
+				// means we have to also inflate override return type in case the candidate is
+				// best candidate and override return type is different to base return type.
+				// 
+				// virtual Foo<T, object> with override Foo<T, dynamic>
+				//
+				if (candidate != pm) {
+					MethodSpec override_ms = (MethodSpec) pm;
+					var inflator = new TypeParameterInflator (ec, ms.DeclaringType, override_ms.GenericDefinition.TypeParameters, ms.TypeArguments);
+					returnType = inflator.Inflate (returnType);
+				} else {
+					returnType = ms.ReturnType;
+				}
+
+				candidate = ms;
+				pd = ms.Parameters;
+				ptypes = pd.Types;
+			} else {
+				if (type_arguments != null)
+					return int.MaxValue - 15000;
+
+				ptypes = cpd.Types;
+			}
+
+			//
+			// 2. Each argument has to be implicitly convertible to method parameter
+			//
+			Parameter.Modifier p_mod = 0;
+			TypeSpec pt = null;
+
+			for (int i = 0; i < arg_count; i++) {
+				Argument a = arguments[i];
+				if (a == null) {
+					var fp = pd.FixedParameters[i];
+					if (!fp.HasDefaultValue) {
+						arguments = orig_args;
+						return arg_count * 2 + 2;
+					}
+
+					//
+					// Get the default value expression, we can use the same expression
+					// if the type matches
+					//
+					Expression e = fp.DefaultValue;
+					if (e != null) {
+						e = ResolveDefaultValueArgument (ec, ptypes[i], e, loc);
+						if (e == null) {
+							// Restore for possible error reporting
+							for (int ii = i; ii < arg_count; ++ii)
+								arguments.RemoveAt (i);
+
+							return (arg_count - i) * 2 + 1;
+						}
+					}
+
+					if ((fp.ModFlags & Parameter.Modifier.CallerMask) != 0) {
+						//
+						// LAMESPEC: Attributes can be mixed together with build-in priority
+						//
+						if ((fp.ModFlags & Parameter.Modifier.CallerLineNumber) != 0) {
+							e = new IntLiteral (ec.BuiltinTypes, loc.Row, loc);
+						} else if ((fp.ModFlags & Parameter.Modifier.CallerFilePath) != 0) {
+							e = new StringLiteral (ec.BuiltinTypes, loc.NameFullPath, loc);
+						} else if (ec.MemberContext.CurrentMemberDefinition != null) {
+							e = new StringLiteral (ec.BuiltinTypes, ec.MemberContext.CurrentMemberDefinition.GetCallerMemberName (), loc);
+						}
+					}
+
+					arguments[i] = new Argument (e, Argument.AType.Default);
+					continue;
+				}
+
+				if (p_mod != Parameter.Modifier.PARAMS) {
+					p_mod = (pd.FixedParameters[i].ModFlags & ~Parameter.Modifier.PARAMS) | (cpd.FixedParameters[i].ModFlags & Parameter.Modifier.PARAMS);
+					pt = ptypes [i];
+				} else if (!params_expanded_form) {
+					params_expanded_form = true;
+					pt = ((ElementTypeSpec) pt).Element;
+					i -= 2;
+					continue;
+				}
+
+				score = 1;
+				if (!params_expanded_form) {
+					if (a.IsExtensionType) {
+						//
+						// Indentity, implicit reference or boxing conversion must exist for the extension parameter
+						//
+						// LAMESPEC: or implicit type parameter conversion
+						//
+						var at = a.Type;
+						if (at == pt || TypeSpecComparer.IsEqual (at, pt) ||
+							Convert.ImplicitReferenceConversionExists (at, pt, false) ||
+							Convert.ImplicitBoxingConversion (null, at, pt) != null) {
+							score = 0;
+							continue;
+						}
+					} else {
+						score = IsArgumentCompatible (ec, a, p_mod, pt);
+
+						if (score < 0)
+							dynamicArgument = true;
+					}
+				}
+
+				//
+				// It can be applicable in expanded form (when not doing exact match like for delegates)
+				//
+				if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && (restrictions & Restrictions.CovariantDelegate) == 0) {
+					if (!params_expanded_form) {
+						pt = ((ElementTypeSpec) pt).Element;
+					}
+
+					if (score > 0)
+						score = IsArgumentCompatible (ec, a, Parameter.Modifier.NONE, pt);
+
+					if (score < 0) {
+						params_expanded_form = true;
+						dynamicArgument = true;
+					} else if (score == 0 || arg_count > pd.Count) {
+						params_expanded_form = true;
+					}
+				}
+
+				if (score > 0) {
+					if (params_expanded_form)
+						++score;
+					return (arg_count - i) * 2 + score;
+				}
+			}
+
+			//
+			// Restore original arguments for dynamic binder to keep the intention of original source code
+			//
+			if (dynamicArgument)
+				arguments = orig_args;
+
+			return 0;
+		}
+
+		public static Expression ResolveDefaultValueArgument (ResolveContext ec, TypeSpec ptype, Expression e, Location loc)
+		{
+			if (e is Constant && e.Type == ptype)
+				return e;
+
+			//
+			// LAMESPEC: No idea what the exact rules are for System.Reflection.Missing.Value instead of null
+			//
+			if (e == EmptyExpression.MissingValue && ptype.BuiltinType == BuiltinTypeSpec.Type.Object || ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				e = new MemberAccess (new MemberAccess (new MemberAccess (
+					new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Reflection", loc), "Missing", loc), "Value", loc);
+			} else if (e is Constant) {
+				//
+				// Handles int to int? conversions, DefaultParameterValue check
+				//
+				e = Convert.ImplicitConversionStandard (ec, e, ptype, loc);
+				if (e == null)
+					return null;
+			} else {
+				e = new DefaultValueExpression (new TypeExpression (ptype, loc), loc);
+			}
+
+			return e.Resolve (ec);
+		}
+
+		//
+		// Tests argument compatibility with the parameter
+		// The possible return values are
+		// 0 - success
+		// 1 - modifier mismatch
+		// 2 - type mismatch
+		// -1 - dynamic binding required
+		//
+		int IsArgumentCompatible (ResolveContext ec, Argument argument, Parameter.Modifier param_mod, TypeSpec parameter)
+		{
+			//
+			// Types have to be identical when ref or out modifer
+			// is used and argument is not of dynamic type
+			//
+			if (((argument.Modifier | param_mod) & Parameter.Modifier.RefOutMask) != 0) {
+				if (argument.Type != parameter) {
+					//
+					// Do full equality check after quick path
+					//
+					if (!TypeSpecComparer.IsEqual (argument.Type, parameter)) {
+						//
+						// Using dynamic for ref/out parameter can still succeed at runtime
+						//
+						if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
+							return -1;
+
+						return 2;
+					}
+				}
+
+				if ((argument.Modifier & Parameter.Modifier.RefOutMask) != (param_mod & Parameter.Modifier.RefOutMask)) {
+					//
+					// Using dynamic for ref/out parameter can still succeed at runtime
+					//
+					if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
+						return -1;
+
+					return 1;
+				}
+
+			} else {
+				if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (restrictions & Restrictions.CovariantDelegate) == 0)
+					return -1;
+
+				//
+				// Use implicit conversion in all modes to return same candidates when the expression
+				// is used as argument or delegate conversion
+				//
+				if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
+					return parameter.IsDelegate && argument.Expr is AnonymousMethodExpression ? 2 : 3;
+				}
+			}
+
+			return 0;
+		}
+
+		static TypeSpec MoreSpecific (TypeSpec p, TypeSpec q)
+		{
+			if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
+				return q;
+			if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
+				return p;
+
+			var ac_p = p as ArrayContainer;
+			if (ac_p != null) {
+				var ac_q = q as ArrayContainer;
+				if (ac_q == null)
+					return null;
+
+				TypeSpec specific = MoreSpecific (ac_p.Element, ac_q.Element);
+				if (specific == ac_p.Element)
+					return p;
+				if (specific == ac_q.Element)
+					return q;
+			} else if (p.IsGeneric && q.IsGeneric) {
+				var pargs = TypeManager.GetTypeArguments (p);
+				var qargs = TypeManager.GetTypeArguments (q);
+
+				bool p_specific_at_least_once = false;
+				bool q_specific_at_least_once = false;
+
+				for (int i = 0; i < pargs.Length; i++) {
+					TypeSpec specific = MoreSpecific (pargs[i], qargs[i]);
+					if (specific == pargs[i])
+						p_specific_at_least_once = true;
+					if (specific == qargs[i])
+						q_specific_at_least_once = true;
+				}
+
+				if (p_specific_at_least_once && !q_specific_at_least_once)
+					return p;
+				if (!p_specific_at_least_once && q_specific_at_least_once)
+					return q;
+			}
+
+			return null;
+		}
+
+		//
+		// Find the best method from candidate list
+		//
+		public T ResolveMember<T> (ResolveContext rc, ref Arguments args) where T : MemberSpec, IParametersMember
+		{
+			List<AmbiguousCandidate> ambiguous_candidates = null;
+
+			MemberSpec best_candidate;
+			Arguments best_candidate_args = null;
+			bool best_candidate_params = false;
+			bool best_candidate_dynamic = false;
+			int best_candidate_rate;
+			IParametersMember best_parameter_member = null;
+
+			int args_count = args != null ? args.Count : 0;
+
+			Arguments candidate_args = args;
+			bool error_mode = false;
+			MemberSpec invocable_member = null;
+
+			while (true) {
+				best_candidate = null;
+				best_candidate_rate = int.MaxValue;
+
+				var type_members = members;
+				do {
+					for (int i = 0; i < type_members.Count; ++i) {
+						var member = type_members[i];
+
+						//
+						// Methods in a base class are not candidates if any method in a derived
+						// class is applicable
+						//
+						if ((member.Modifiers & Modifiers.OVERRIDE) != 0)
+							continue;
+
+						if (!error_mode) {
+							if (!member.IsAccessible (rc))
+								continue;
+
+							if (rc.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc))
+								continue;
+
+							if ((member.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED &&
+								instance_qualifier != null && !instance_qualifier.CheckProtectedMemberAccess (rc, member)) {
+								continue;
+							}
+						}
+
+						IParametersMember pm = member as IParametersMember;
+						if (pm == null) {
+							//
+							// Will use it later to report ambiguity between best method and invocable member
+							//
+							if (Invocation.IsMemberInvocable (member))
+								invocable_member = member;
+
+							continue;
+						}
+
+						//
+						// Overload resolution is looking for base member but using parameter names
+						// and default values from the closest member. That means to do expensive lookup
+						// for the closest override for virtual or abstract members
+						//
+						if ((member.Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
+							var override_params = base_provider.GetOverrideMemberParameters (member);
+							if (override_params != null)
+								pm = override_params;
+						}
+
+						//
+						// Check if the member candidate is applicable
+						//
+						bool params_expanded_form = false;
+						bool dynamic_argument = false;
+						TypeSpec rt = pm.MemberType;
+						int candidate_rate = IsApplicable (rc, ref candidate_args, args_count, ref member, pm, ref params_expanded_form, ref dynamic_argument, ref rt, error_mode);
+
+						if (lambda_conv_msgs != null)
+							lambda_conv_msgs.EndSession ();
+
+						//
+						// How does it score compare to others
+						//
+						if (candidate_rate < best_candidate_rate) {
+
+							// Fatal error (missing dependency), cannot continue
+							if (candidate_rate < 0)
+								return null;
+
+							if ((restrictions & Restrictions.GetEnumeratorLookup) != 0 && candidate_args.Count != 0) {
+								// Only parameterless methods are considered
+							} else {
+								best_candidate_rate = candidate_rate;
+								best_candidate = member;
+								best_candidate_args = candidate_args;
+								best_candidate_params = params_expanded_form;
+								best_candidate_dynamic = dynamic_argument;
+								best_parameter_member = pm;
+								best_candidate_return_type = rt;
+							}
+						} else if (candidate_rate == 0) {
+							//
+							// The member look is done per type for most operations but sometimes
+							// it's not possible like for binary operators overload because they
+							// are unioned between 2 sides
+							//
+							if ((restrictions & Restrictions.BaseMembersIncluded) != 0) {
+								if (TypeSpec.IsBaseClass (best_candidate.DeclaringType, member.DeclaringType, true))
+									continue;
+							}
+
+							bool is_better;
+							if (best_candidate.DeclaringType.IsInterface && member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) {
+								//
+								// We pack all interface members into top level type which makes the overload resolution
+								// more complicated for interfaces. We compensate it by removing methods with same
+								// signature when building the cache hence this path should not really be hit often
+								//
+								// Example:
+								// interface IA { void Foo (int arg); }
+								// interface IB : IA { void Foo (params int[] args); }
+								//
+								// IB::Foo is the best overload when calling IB.Foo (1)
+								//
+								is_better = true;
+								if (ambiguous_candidates != null) {
+									foreach (var amb_cand in ambiguous_candidates) {
+										if (member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) {
+											continue;
+										}
+
+										is_better = false;
+										break;
+									}
+
+									if (is_better)
+										ambiguous_candidates = null;
+								}
+							} else {
+								// Is the new candidate better
+								is_better = BetterFunction (rc, candidate_args, member, pm.Parameters, params_expanded_form, best_candidate, best_parameter_member.Parameters, best_candidate_params);
+							}
+
+							if (is_better) {
+								best_candidate = member;
+								best_candidate_args = candidate_args;
+								best_candidate_params = params_expanded_form;
+								best_candidate_dynamic = dynamic_argument;
+								best_parameter_member = pm;
+								best_candidate_return_type = rt;
+							} else {
+								// It's not better but any other found later could be but we are not sure yet
+								if (ambiguous_candidates == null)
+									ambiguous_candidates = new List<AmbiguousCandidate> ();
+
+								ambiguous_candidates.Add (new AmbiguousCandidate (member, pm.Parameters, params_expanded_form));
+							}
+						}
+
+						// Restore expanded arguments
+						candidate_args = args;
+					}
+				} while (best_candidate_rate != 0 && (type_members = base_provider.GetBaseMembers (type_members[0].DeclaringType.BaseType)) != null);
+
+				//
+				// We've found exact match
+				//
+				if (best_candidate_rate == 0)
+					break;
+
+				//
+				// Try extension methods lookup when no ordinary method match was found and provider enables it
+				//
+				if (!error_mode) {
+					var emg = base_provider.LookupExtensionMethod (rc);
+					if (emg != null) {
+						emg = emg.OverloadResolve (rc, ref args, null, restrictions);
+						if (emg != null) {
+							best_candidate_extension_group = emg;
+							return (T) (MemberSpec) emg.BestCandidate;
+						}
+					}
+				}
+
+				// Don't run expensive error reporting mode for probing
+				if (IsProbingOnly)
+					return null;
+
+				if (error_mode)
+					break;
+
+				if (lambda_conv_msgs != null && !lambda_conv_msgs.IsEmpty)
+					break;
+
+				lambda_conv_msgs = null;
+				error_mode = true;
+			}
+
+			//
+			// No best member match found, report an error
+			//
+			if (best_candidate_rate != 0 || error_mode) {
+				ReportOverloadError (rc, best_candidate, best_parameter_member, best_candidate_args, best_candidate_params);
+				return null;
+			}
+
+			if (best_candidate_dynamic) {
+				if (args[0].IsExtensionType) {
+					rc.Report.Error (1973, loc,
+						"Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' cannot be dynamically dispatched. Consider calling the method without the extension method syntax",
+						args [0].Type.GetSignatureForError (), best_candidate.Name, best_candidate.GetSignatureForError ());
+				}
+
+				//
+				// Check type constraints only when explicit type arguments are used
+				//
+				if (best_candidate.IsGeneric && type_arguments != null) {
+					MethodSpec bc = best_candidate as MethodSpec;
+					if (bc != null && TypeParameterSpec.HasAnyTypeParameterConstrained (bc.GenericDefinition)) {
+						ConstraintChecker cc = new ConstraintChecker (rc);
+						cc.CheckAll (bc.GetGenericMethodDefinition (), bc.TypeArguments, bc.Constraints, loc);
+					}
+				}
+
+				BestCandidateIsDynamic = true;
+				return null;
+			}
+
+			//
+			// These flags indicates we are running delegate probing conversion. No need to
+			// do more expensive checks
+			// 
+			if ((restrictions & (Restrictions.ProbingOnly | Restrictions.CovariantDelegate)) == (Restrictions.CovariantDelegate | Restrictions.ProbingOnly))
+				return (T) best_candidate;
+
+			if (ambiguous_candidates != null) {
+				//
+				// Now check that there are no ambiguities i.e the selected method
+				// should be better than all the others
+				//
+				for (int ix = 0; ix < ambiguous_candidates.Count; ix++) {
+					var candidate = ambiguous_candidates [ix];
+
+					if (!BetterFunction (rc, best_candidate_args, best_candidate, best_parameter_member.Parameters, best_candidate_params, candidate.Member, candidate.Parameters, candidate.Expanded)) {
+						var ambiguous = candidate.Member;
+						if (custom_errors == null || !custom_errors.AmbiguousCandidates (rc, best_candidate, ambiguous)) {
+							rc.Report.SymbolRelatedToPreviousError (best_candidate);
+							rc.Report.SymbolRelatedToPreviousError (ambiguous);
+							rc.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
+								best_candidate.GetSignatureForError (), ambiguous.GetSignatureForError ());
+						}
+
+						return (T) best_candidate;
+					}
+				}
+			}
+
+			if (invocable_member != null && !IsProbingOnly) {
+				rc.Report.SymbolRelatedToPreviousError (best_candidate);
+				rc.Report.SymbolRelatedToPreviousError (invocable_member);
+				rc.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and invocable non-method `{1}'. Using method group",
+					best_candidate.GetSignatureForError (), invocable_member.GetSignatureForError ());
+			}
+
+			//
+			// And now check if the arguments are all
+			// compatible, perform conversions if
+			// necessary etc. and return if everything is
+			// all right
+			//
+			if (!VerifyArguments (rc, ref best_candidate_args, best_candidate, best_parameter_member, best_candidate_params))
+				return null;
+
+			if (best_candidate == null)
+				return null;
+
+			//
+			// Don't run possibly expensive checks in probing mode
+			//
+			if (!IsProbingOnly && !rc.IsInProbingMode) {
+				//
+				// Check ObsoleteAttribute on the best method
+				//
+				ObsoleteAttribute oa = best_candidate.GetAttributeObsolete ();
+				if (oa != null && !rc.IsObsolete)
+					AttributeTester.Report_ObsoleteMessage (oa, best_candidate.GetSignatureForError (), loc, rc.Report);
+
+				best_candidate.MemberDefinition.SetIsUsed ();
+			}
+
+			args = best_candidate_args;
+			return (T) best_candidate;
+		}
+
+		public MethodSpec ResolveOperator (ResolveContext rc, ref Arguments args)
+		{
+			return ResolveMember<MethodSpec> (rc, ref args);
+		}
+
+		void ReportArgumentMismatch (ResolveContext ec, int idx, MemberSpec method,
+													Argument a, AParametersCollection expected_par, TypeSpec paramType)
+		{
+			if (custom_errors != null && custom_errors.ArgumentMismatch (ec, method, a, idx))
+				return;
+
+			if (a.Type == InternalType.ErrorType)
+				return;
+
+			if (a is CollectionElementInitializer.ElementInitializerArgument) {
+				ec.Report.SymbolRelatedToPreviousError (method);
+				if ((expected_par.FixedParameters[idx].ModFlags & Parameter.Modifier.RefOutMask) != 0) {
+					ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have `ref' or `out' modifier",
+						TypeManager.CSharpSignature (method));
+					return;
+				}
+				ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
+					  TypeManager.CSharpSignature (method));
+			} else if (IsDelegateInvoke) {
+				ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
+					DelegateType.GetSignatureForError ());
+			} else {
+				ec.Report.SymbolRelatedToPreviousError (method);
+				ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
+					method.GetSignatureForError ());
+			}
+
+			Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters[idx].ModFlags;
+
+			string index = (idx + 1).ToString ();
+			if (((mod & Parameter.Modifier.RefOutMask) ^ (a.Modifier & Parameter.Modifier.RefOutMask)) != 0) {
+				if ((mod & Parameter.Modifier.RefOutMask) == 0)
+					ec.Report.Error (1615, a.Expr.Location, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
+						index, Parameter.GetModifierSignature (a.Modifier));
+				else
+					ec.Report.Error (1620, a.Expr.Location, "Argument `#{0}' is missing `{1}' modifier",
+						index, Parameter.GetModifierSignature (mod));
+			} else {
+				string p1 = a.GetSignatureForError ();
+				string p2 = paramType.GetSignatureForError ();
+
+				if (p1 == p2) {
+					p1 = a.Type.GetSignatureForErrorIncludingAssemblyName ();
+					p2 = paramType.GetSignatureForErrorIncludingAssemblyName ();
+				}
+
+				if ((mod & Parameter.Modifier.RefOutMask) != 0) {
+					p1 = Parameter.GetModifierSignature (a.Modifier) + " " + p1;
+					p2 = Parameter.GetModifierSignature (a.Modifier) + " " + p2;
+				}
+
+				ec.Report.Error (1503, a.Expr.Location,
+					"Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
+			}
+		}
+
+		//
+		// We have failed to find exact match so we return error info about the closest match
+		//
+		void ReportOverloadError (ResolveContext rc, MemberSpec best_candidate, IParametersMember pm, Arguments args, bool params_expanded)
+		{
+			int ta_count = type_arguments == null ? 0 : type_arguments.Count;
+			int arg_count = args == null ? 0 : args.Count;
+
+			if (ta_count != best_candidate.Arity && (ta_count > 0 || ((IParametersMember) best_candidate).Parameters.IsEmpty)) {
+				var mg = new MethodGroupExpr (new [] { best_candidate }, best_candidate.DeclaringType, loc);
+				mg.Error_TypeArgumentsCannotBeUsed (rc, best_candidate, loc);
+				return;
+			}
+
+			if (lambda_conv_msgs != null && lambda_conv_msgs.Merge (rc.Report.Printer)) {
+				return;
+			}
+
+
+			if ((best_candidate.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED &&
+				InstanceQualifier != null && !InstanceQualifier.CheckProtectedMemberAccess (rc, best_candidate)) {
+				MemberExpr.Error_ProtectedMemberAccess (rc, best_candidate, InstanceQualifier.InstanceType, loc);
+			}
+
+			//
+			// For candidates which match on parameters count report more details about incorrect arguments
+			//
+			if (pm != null) {
+				if (pm.Parameters.Count == arg_count || params_expanded || HasUnfilledParams (best_candidate, pm, args)) {
+					// Reject any inaccessible member
+					if (!best_candidate.IsAccessible (rc) || !best_candidate.DeclaringType.IsAccessible (rc)) {
+						rc.Report.SymbolRelatedToPreviousError (best_candidate);
+						Expression.ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc);
+						return;
+					}
+
+					var ms = best_candidate as MethodSpec;
+					if (ms != null && ms.IsGeneric) {
+						bool constr_ok = true;
+						if (ms.TypeArguments != null)
+							constr_ok = new ConstraintChecker (rc.MemberContext).CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc);
+
+						if (ta_count == 0 && ms.TypeArguments == null) {
+							if (custom_errors != null && custom_errors.TypeInferenceFailed (rc, best_candidate))
+								return;
+
+							if (constr_ok) {
+								rc.Report.Error (411, loc,
+									"The type arguments for method `{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly",
+									ms.GetGenericMethodDefinition ().GetSignatureForError ());
+							}
+
+							return;
+						}
+					}
+
+					VerifyArguments (rc, ref args, best_candidate, pm, params_expanded);
+					return;
+				}
+			}
+
+			//
+			// We failed to find any method with correct argument count, report best candidate
+			//
+			if (custom_errors != null && custom_errors.NoArgumentMatch (rc, best_candidate))
+				return;
+
+			if (best_candidate.Kind == MemberKind.Constructor) {
+				rc.Report.SymbolRelatedToPreviousError (best_candidate);
+				Error_ConstructorMismatch (rc, best_candidate.DeclaringType, arg_count, loc);
+			} else if (IsDelegateInvoke) {
+				rc.Report.SymbolRelatedToPreviousError (DelegateType);
+				rc.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
+					DelegateType.GetSignatureForError (), arg_count.ToString ());
+			} else {
+				string name = best_candidate.Kind == MemberKind.Indexer ? "this" : best_candidate.Name;
+				rc.Report.SymbolRelatedToPreviousError (best_candidate);
+				rc.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
+					name, arg_count.ToString ());
+			}
+		}
+
+		static bool HasUnfilledParams (MemberSpec best_candidate, IParametersMember pm, Arguments args)
+		{
+			var p = ((IParametersMember)best_candidate).Parameters;
+			if (!p.HasParams)
+				return false;
+
+			string name = null;
+			for (int i = p.Count - 1; i != 0; --i) {
+				var fp = p.FixedParameters [i];
+				if ((fp.ModFlags & Parameter.Modifier.PARAMS) == 0)
+					continue;
+
+				name = fp.Name;
+				break;
+			}
+
+			if (args == null)
+				return false;
+
+			foreach (var arg in args) {
+				var na = arg as NamedArgument;
+				if (na == null)
+					continue;
+
+				if (na.Name == name) {
+					name = null;
+					break;
+				}
+			}
+
+			if (name == null)
+				return false;
+
+			return args.Count + 1 == pm.Parameters.Count;
+		}
+
+		bool VerifyArguments (ResolveContext ec, ref Arguments args, MemberSpec member, IParametersMember pm, bool chose_params_expanded)
+		{
+			var pd = pm.Parameters;
+			var cpd = ((IParametersMember) member).Parameters;
+			var ptypes = cpd.Types;
+
+			Parameter.Modifier p_mod = 0;
+			TypeSpec pt = null;
+			int a_idx = 0, a_pos = 0;
+			Argument a = null;
+			ArrayInitializer params_initializers = null;
+			bool has_unsafe_arg = pm.MemberType.IsPointer;
+			int arg_count = args == null ? 0 : args.Count;
+
+			for (; a_idx < arg_count; a_idx++, ++a_pos) {
+				a = args[a_idx];
+				if (a == null)
+					continue;
+
+				if (p_mod != Parameter.Modifier.PARAMS) {
+					p_mod = cpd.FixedParameters [a_idx].ModFlags;
+					pt = ptypes[a_idx];
+					has_unsafe_arg |= pt.IsPointer;
+
+					if (p_mod == Parameter.Modifier.PARAMS) {
+						if (chose_params_expanded) {
+							params_initializers = new ArrayInitializer (arg_count - a_idx, a.Expr.Location);
+							pt = TypeManager.GetElementType (pt);
+						}
+					}
+				}
+
+				//
+				// Types have to be identical when ref or out modifer is used 
+				//
+				if (((a.Modifier | p_mod) & Parameter.Modifier.RefOutMask) != 0) {
+					if ((a.Modifier & Parameter.Modifier.RefOutMask) != (p_mod & Parameter.Modifier.RefOutMask))
+						break;
+
+					if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt))
+						continue;
+
+					break;
+				}
+
+				NamedArgument na = a as NamedArgument;
+				if (na != null) {
+					int name_index = pd.GetParameterIndexByName (na.Name);
+					if (name_index < 0 || name_index >= pd.Count) {
+						if (IsDelegateInvoke) {
+							ec.Report.SymbolRelatedToPreviousError (DelegateType);
+							ec.Report.Error (1746, na.Location,
+								"The delegate `{0}' does not contain a parameter named `{1}'",
+								DelegateType.GetSignatureForError (), na.Name);
+						} else {
+							ec.Report.SymbolRelatedToPreviousError (member);
+							ec.Report.Error (1739, na.Location,
+								"The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
+								TypeManager.CSharpSignature (member), na.Name);
+						}
+					} else if (args[name_index] != a && args[name_index] != null) {
+						if (IsDelegateInvoke)
+							ec.Report.SymbolRelatedToPreviousError (DelegateType);
+						else
+							ec.Report.SymbolRelatedToPreviousError (member);
+
+						ec.Report.Error (1744, na.Location,
+							"Named argument `{0}' cannot be used for a parameter which has positional argument specified",
+							na.Name);
+					}
+				}
+				
+				if (a.Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					continue;
+
+				if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (ec, a.Expr.Type, pt)) {
+					custom_errors.NoArgumentMatch (ec, member);
+					return false;
+				}
+
+				Expression conv;
+				if (a.IsExtensionType) {
+					if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt)) {
+						conv = a.Expr;
+					} else {
+						conv = Convert.ImplicitReferenceConversion (a.Expr, pt, false);
+						if (conv == null)
+							conv = Convert.ImplicitBoxingConversion (a.Expr, a.Expr.Type, pt);
+					}
+				} else {
+					conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
+				}
+
+				if (conv == null)
+					break;
+
+				//
+				// Convert params arguments to an array initializer
+				//
+				if (params_initializers != null) {
+					// we choose to use 'a.Expr' rather than 'conv' so that
+					// we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
+					params_initializers.Add (a.Expr);
+					args.RemoveAt (a_idx--);
+					--arg_count;
+					a.Expr = conv;
+					continue;
+				}
+
+				// Update the argument with the implicit conversion
+				a.Expr = conv;
+			}
+
+			if (a_idx != arg_count) {
+				ReportArgumentMismatch (ec, a_pos, member, a, pd, pt);
+				return false;
+			}
+
+			//
+			// Fill not provided arguments required by params modifier
+			//
+			if (params_initializers == null && arg_count + 1 == pd.Count) {
+				if (args == null)
+					args = new Arguments (1);
+
+				pt = ptypes[pd.Count - 1];
+				pt = TypeManager.GetElementType (pt);
+				has_unsafe_arg |= pt.IsPointer;
+				params_initializers = new ArrayInitializer (0, loc);
+			}
+
+			//
+			// Append an array argument with all params arguments
+			//
+			if (params_initializers != null) {
+				args.Add (new Argument (
+					new ArrayCreation (new TypeExpression (pt, loc), params_initializers, loc).Resolve (ec)));
+				arg_count++;
+			}
+
+			if (has_unsafe_arg && !ec.IsUnsafe) {
+				Expression.UnsafeError (ec, loc);
+			}
+
+			//
+			// We could infer inaccesible type arguments
+			//
+			if (type_arguments == null && member.IsGeneric) {
+				var ms = (MethodSpec) member;
+				foreach (var ta in ms.TypeArguments) {
+					if (!ta.IsAccessible (ec)) {
+						ec.Report.SymbolRelatedToPreviousError (ta);
+						Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
+						break;
+					}
+				}
+			}
+
+			return true;
+		}
+	}
+
+	public class ConstantExpr : MemberExpr
+	{
+		readonly ConstSpec constant;
+
+		public ConstantExpr (ConstSpec constant, Location loc)
+		{
+			this.constant = constant;
+			this.loc = loc;
+		}
+
+		public override string Name {
+			get { throw new NotImplementedException (); }
+		}
+
+		public override string KindName {
+			get { return "constant"; }
+		}
+
+		public override bool IsInstance {
+			get { return !IsStatic; }
+		}
+
+		public override bool IsStatic {
+			get { return true; }
+		}
+
+		protected override TypeSpec DeclaringType {
+			get { return constant.DeclaringType; }
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			ResolveInstanceExpression (rc, null);
+			DoBestMemberChecks (rc, constant);
+
+			var c = constant.GetConstant (rc);
+
+			// Creates reference expression to the constant value
+			return Constant.CreateConstantFromValue (constant.MemberType, c.GetValue (), loc);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return constant.GetSignatureForError ();
+		}
+
+		public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
+		{
+			Error_TypeArgumentsCannotBeUsed (ec, "constant", GetSignatureForError (), loc);
+		}
+	}
+
+	//
+	// Fully resolved expression that references a Field
+	//
+	public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference
+	{
+		protected FieldSpec spec;
+		VariableInfo variable_info;
+		
+		LocalTemporary temp;
+		bool prepared;
+		
+		protected FieldExpr (Location l)
+		{
+			loc = l;
+		}
+
+		public FieldExpr (FieldSpec spec, Location loc)
+		{
+			this.spec = spec;
+			this.loc = loc;
+
+			type = spec.MemberType;
+		}
+		
+		public FieldExpr (FieldBase fi, Location l)
+			: this (fi.Spec, l)
+		{
+		}
+
+		#region Properties
+
+		public override string Name {
+			get {
+				return spec.Name;
+			}
+		}
+
+		public bool IsHoisted {
+			get {
+				IVariableReference hv = InstanceExpression as IVariableReference;
+				return hv != null && hv.IsHoisted;
+			}
+		}
+
+		public override bool IsInstance {
+			get {
+				return !spec.IsStatic;
+			}
+		}
+
+		public override bool IsStatic {
+			get {
+				return spec.IsStatic;
+			}
+		}
+
+		public override string KindName {
+			get { return "field"; }
+		}
+
+		public FieldSpec Spec {
+			get {
+				return spec;
+			}
+		}
+
+		protected override TypeSpec DeclaringType {
+			get {
+				return spec.DeclaringType;
+			}
+		}
+
+		public VariableInfo VariableInfo {
+			get {
+				return variable_info;
+			}
+		}
+
+#endregion
+
+		public override string GetSignatureForError ()
+		{
+			return spec.GetSignatureForError ();
+		}
+
+		public bool IsMarshalByRefAccess (ResolveContext rc)
+		{
+			// Checks possible ldflda of field access expression
+			return !spec.IsStatic && TypeSpec.IsValueType (spec.MemberType) && !(InstanceExpression is This) &&
+				rc.Module.PredefinedTypes.MarshalByRefObject.Define () &&
+				TypeSpec.IsBaseClass (spec.DeclaringType, rc.Module.PredefinedTypes.MarshalByRefObject.TypeSpec, false);
+		}
+
+		public void SetHasAddressTaken ()
+		{
+			IVariableReference vr = InstanceExpression as IVariableReference;
+			if (vr != null) {
+				vr.SetHasAddressTaken ();
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			var t = (FieldExpr) target;
+
+			if (InstanceExpression != null)
+				t.InstanceExpression = InstanceExpression.Clone (clonectx);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (ConditionalAccess) {
+				Error_NullShortCircuitInsideExpressionTree (ec);
+			}
+
+			return CreateExpressionTree (ec, true);
+		}
+
+		public Expression CreateExpressionTree (ResolveContext ec, bool convertInstance)
+		{
+			Arguments args;
+			Expression instance;
+
+			if (InstanceExpression == null) {
+				instance = new NullLiteral (loc);
+			} else if (convertInstance) {
+				instance = InstanceExpression.CreateExpressionTree (ec);
+			} else {
+				args = new Arguments (1);
+				args.Add (new Argument (InstanceExpression));
+				instance = CreateExpressionFactoryCall (ec, "Constant", args);
+			}
+
+			args = Arguments.CreateForExpressionTree (ec, null,
+				instance,
+				CreateTypeOfExpression ());
+
+			return CreateExpressionFactoryCall (ec, "Field", args);
+		}
+
+		public Expression CreateTypeOfExpression ()
+		{
+			return new TypeOfField (spec, loc);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			spec.MemberDefinition.SetIsUsed ();
+
+			return DoResolve (ec, null);
+		}
+
+		Expression DoResolve (ResolveContext ec, Expression rhs)
+		{
+			bool lvalue_instance = rhs != null && IsInstance && spec.DeclaringType.IsStruct;
+
+			if (rhs != this) {
+				ResolveConditionalAccessReceiver (ec);
+
+				if (ResolveInstanceExpression (ec, rhs)) {
+					// Resolve the field's instance expression while flow analysis is turned
+					// off: when accessing a field "a.b", we must check whether the field
+					// "a.b" is initialized, not whether the whole struct "a" is initialized.
+
+					if (lvalue_instance) {
+						bool out_access = rhs == EmptyExpression.OutAccess || rhs == EmptyExpression.LValueMemberOutAccess;
+
+						Expression right_side =
+							out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
+
+						InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side);
+					} else {
+						InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue);
+					}
+
+					if (InstanceExpression == null)
+						return null;
+				}
+
+				DoBestMemberChecks (ec, spec);
+
+				if (conditional_access_receiver)
+					ec.With (ResolveContext.Options.ConditionalAccessReceiver, false);
+			}
+
+			var fb = spec as FixedFieldSpec;
+			IVariableReference var = InstanceExpression as IVariableReference;
+
+			if (fb != null) {
+				IFixedExpression fe = InstanceExpression as IFixedExpression;
+				if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
+					ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
+				}
+
+				if (InstanceExpression.eclass != ExprClass.Variable) {
+					ec.Report.SymbolRelatedToPreviousError (spec);
+					ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
+						TypeManager.GetFullNameSignature (spec));
+				} else if (var != null && var.IsHoisted) {
+					AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
+				}
+
+				return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
+			}
+
+			//
+			// Set flow-analysis variable info for struct member access. It will be check later
+			// for precise error reporting
+			//
+			if (var != null && var.VariableInfo != null && InstanceExpression.Type.IsStruct) {
+				variable_info = var.VariableInfo.GetStructFieldInfo (Name);
+			}
+
+			if (ConditionalAccess) {
+				if (conditional_access_receiver)
+					type = LiftMemberType (ec, type);
+
+				if (InstanceExpression.IsNull)
+					return Constant.CreateConstantFromValue (type, null, loc);
+			}
+
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public void SetFieldAssigned (FlowAnalysisContext fc)
+		{
+			if (!IsInstance)
+				return;
+
+			bool lvalue_instance = spec.DeclaringType.IsStruct;
+			if (lvalue_instance) {
+				var var = InstanceExpression as IVariableReference;
+				if (var != null && var.VariableInfo != null) {
+					fc.SetStructFieldAssigned (var.VariableInfo, Name);
+				}
+			}
+
+			var fe = InstanceExpression as FieldExpr;
+			if (fe != null) {
+				Expression instance;
+
+				do {
+					instance = fe.InstanceExpression;
+					var fe_instance = instance as FieldExpr;
+					if ((fe_instance != null && !fe_instance.IsStatic) || instance is LocalVariableReference) {
+						if (TypeSpec.IsReferenceType (fe.Type) && instance.Type.IsStruct) {
+							var var = InstanceExpression as IVariableReference;
+							if (var != null && var.VariableInfo == null) {
+								var var_inst = instance as IVariableReference;
+								if (var_inst == null || (var_inst.VariableInfo != null && !fc.IsDefinitelyAssigned (var_inst.VariableInfo)))
+									fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
+							}
+						}
+
+						if (fe_instance != null) {
+							fe = fe_instance;
+							continue;
+						}
+					}
+
+					break;
+				} while (true);
+
+				if (instance != null && TypeSpec.IsReferenceType (instance.Type))
+					instance.FlowAnalysis (fc);
+			} else {
+				if (TypeSpec.IsReferenceType (InstanceExpression.Type))
+					InstanceExpression.FlowAnalysis (fc);
+			}
+		}
+
+		Expression Error_AssignToReadonly (ResolveContext rc, Expression right_side)
+		{
+			// The return value is always null.  Returning a value simplifies calling code.
+	
+			if (right_side == EmptyExpression.OutAccess) {
+				if (IsStatic) {
+					rc.Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
+						GetSignatureForError ());
+				} else {
+					rc.Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
+						GetSignatureForError ());
+				}
+
+				return null;
+			}
+
+			if (right_side == EmptyExpression.LValueMemberAccess) {
+				// Already reported as CS1648/CS1650
+				return null;
+			}
+
+			if (right_side == EmptyExpression.LValueMemberOutAccess) {
+				if (IsStatic) {
+					rc.Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
+						GetSignatureForError ());
+				} else {
+					rc.Report.Error (1649, loc, "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
+						GetSignatureForError ());
+				}
+				return null;
+			}
+
+			if (IsStatic) {
+				rc.Report.Error (198, loc, "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
+					GetSignatureForError ());
+			} else {
+				rc.Report.Error (191, loc, "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
+					GetSignatureForError ());
+			}
+
+			return null;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			if (ConditionalAccess)
+				throw new NotSupportedException ("null propagating operator assignment");
+
+			if (spec is FixedFieldSpec) {
+				// It could be much better error message but we want to be error compatible
+				Error_ValueAssignment (ec, right_side);
+			}
+
+			Expression e = DoResolve (ec, right_side);
+
+			if (e == null)
+				return null;
+
+			spec.MemberDefinition.SetIsAssigned ();
+
+			if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess) &&
+					(spec.Modifiers & Modifiers.VOLATILE) != 0) {
+				ec.Report.Warning (420, 1, loc,
+					"`{0}': A volatile field references will not be treated as volatile",
+					spec.GetSignatureForError ());
+			}
+
+			if (spec.IsReadOnly) {
+				// InitOnly fields can only be assigned in constructors or initializers
+				if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
+					return Error_AssignToReadonly (ec, right_side);
+
+				if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
+
+					// InitOnly fields cannot be assigned-to in a different constructor from their declaring type
+					if (ec.CurrentMemberDefinition.Parent.PartialContainer.Definition != spec.DeclaringType.GetDefinition ())
+						return Error_AssignToReadonly (ec, right_side);
+					// static InitOnly fields cannot be assigned-to in an instance constructor
+					if (IsStatic && !ec.IsStatic)
+						return Error_AssignToReadonly (ec, right_side);
+					// instance constructors can't modify InitOnly fields of other instances of the same type
+					if (!IsStatic && !(InstanceExpression is This))
+						return Error_AssignToReadonly (ec, right_side);
+				}
+			}
+
+			if (right_side == EmptyExpression.OutAccess && IsMarshalByRefAccess (ec)) {
+				ec.Report.SymbolRelatedToPreviousError (spec.DeclaringType);
+				ec.Report.Warning (197, 1, loc,
+						"Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
+						GetSignatureForError ());
+			}
+
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			var var = InstanceExpression as IVariableReference;
+			if (var != null) {
+				var vi = var.VariableInfo;
+				if (vi != null && !fc.IsStructFieldDefinitelyAssigned (vi, Name)) {
+					fc.Report.Error (170, loc, "Use of possibly unassigned field `{0}'", Name);
+					return;
+				}
+
+				if (TypeSpec.IsValueType (InstanceExpression.Type) && InstanceExpression is VariableReference)
+					return;
+			}
+
+			base.FlowAnalysis (fc);
+
+			if (conditional_access_receiver)
+				fc.ConditionalAccessEnd ();
+		}
+
+		public override int GetHashCode ()
+		{
+			return spec.GetHashCode ();
+		}
+		
+		public bool IsFixed {
+			get {
+				//
+				// A variable of the form V.I is fixed when V is a fixed variable of a struct type
+				//
+				IVariableReference variable = InstanceExpression as IVariableReference;
+				if (variable != null)
+					return InstanceExpression.Type.IsStruct && variable.IsFixed;
+
+				IFixedExpression fe = InstanceExpression as IFixedExpression;
+				return fe != null && fe.IsFixed;
+			}
+		}
+
+		public override bool Equals (object obj)
+		{
+			FieldExpr fe = obj as FieldExpr;
+			if (fe == null)
+				return false;
+
+			if (spec != fe.spec)
+				return false;
+
+			if (InstanceExpression == null || fe.InstanceExpression == null)
+				return true;
+
+			return InstanceExpression.Equals (fe.InstanceExpression);
+		}
+		
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
+
+			if (IsStatic){
+				if (is_volatile)
+					ec.Emit (OpCodes.Volatile);
+
+				ec.Emit (OpCodes.Ldsfld, spec);
+			} else {
+				if (!prepared) {
+					if (conditional_access_receiver)
+						ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+
+					EmitInstance (ec, false);
+				}
+
+				// Optimization for build-in types
+				if (type.IsStruct && type == ec.CurrentType && InstanceExpression.Type == type) {
+					ec.EmitLoadFromPtr (type);
+				} else {
+					var ff = spec as FixedFieldSpec;
+					if (ff != null) {
+						ec.Emit (OpCodes.Ldflda, spec);
+						ec.Emit (OpCodes.Ldflda, ff.Element);
+					} else {
+						if (is_volatile)
+							ec.Emit (OpCodes.Volatile);
+
+						ec.Emit (OpCodes.Ldfld, spec);
+					}
+				}
+
+				if (conditional_access_receiver) {
+					ec.CloseConditionalAccess (type.IsNullableType && type != spec.MemberType ? type : null);
+				}
+			}
+
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				if (!IsStatic) {
+					temp = new LocalTemporary (this.Type);
+					temp.Store (ec);
+				}
+			}
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			bool has_await_source = ec.HasSet (BuilderContext.Options.AsyncBody) && source.ContainsEmitWithAwait ();
+			if (isCompound && !(source is DynamicExpressionStatement) && !has_await_source) {
+				prepared = true;
+			}
+
+			if (IsInstance) {
+				if (ConditionalAccess)
+					throw new NotImplementedException ("null operator assignment");
+
+				if (has_await_source)
+					source = source.EmitToField (ec);
+
+				EmitInstance (ec, prepared);
+			}
+
+			source.Emit (ec);
+
+			if (leave_copy || ec.NotifyEvaluatorOnStore) {
+				ec.Emit (OpCodes.Dup);
+				if (!IsStatic) {
+					temp = new LocalTemporary (this.Type);
+					temp.Store (ec);
+				}
+			}
+
+			if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
+				ec.Emit (OpCodes.Volatile);
+					
+			spec.MemberDefinition.SetIsAssigned ();
+
+			if (IsStatic)
+				ec.Emit (OpCodes.Stsfld, spec);
+			else
+				ec.Emit (OpCodes.Stfld, spec);
+
+			if (ec.NotifyEvaluatorOnStore) {
+				if (!IsStatic)
+					throw new NotImplementedException ("instance field write");
+
+				if (leave_copy)
+					ec.Emit (OpCodes.Dup);
+
+				ec.Module.Evaluator.EmitValueChangedCallback (ec, Name, type, loc);
+			}
+			
+			if (temp != null) {
+				temp.Emit (ec);
+				temp.Release (ec);
+				temp = null;
+			}
+		}
+
+		//
+		// Emits store to field with prepared values on stack
+		//
+		public void EmitAssignFromStack (EmitContext ec)
+		{
+			if (IsStatic) {
+				ec.Emit (OpCodes.Stsfld, spec);
+			} else {
+				ec.Emit (OpCodes.Stfld, spec);
+			}
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Emit (ec, false);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
+
+			if (is_volatile) // || is_marshal_by_ref ())
+				base.EmitSideEffect (ec);
+		}
+
+		public virtual void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			if ((mode & AddressOp.Store) != 0)
+				spec.MemberDefinition.SetIsAssigned ();
+			if ((mode & AddressOp.Load) != 0)
+				spec.MemberDefinition.SetIsUsed ();
+
+			//
+			// Handle initonly fields specially: make a copy and then
+			// get the address of the copy.
+			//
+			bool need_copy;
+			if (spec.IsReadOnly){
+				need_copy = true;
+				if (ec.HasSet (EmitContext.Options.ConstructorScope) && spec.DeclaringType == ec.CurrentType) {
+					if (IsStatic){
+						if (ec.IsStatic)
+							need_copy = false;
+					} else
+						need_copy = false;
+				}
+			} else
+				need_copy = false;
+			
+			if (need_copy) {
+				Emit (ec);
+				var temp = ec.GetTemporaryLocal (type);
+				ec.Emit (OpCodes.Stloc, temp);
+				ec.Emit (OpCodes.Ldloca, temp);
+				return;
+			}
+
+
+			if (IsStatic){
+				ec.Emit (OpCodes.Ldsflda, spec);
+			} else {
+				if (!prepared)
+					EmitInstance (ec, false);
+				ec.Emit (OpCodes.Ldflda, spec);
+			}
+		}
+
+		public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
+		{
+			return MakeExpression (ctx);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.Field (
+				IsStatic ? null : InstanceExpression.MakeExpression (ctx),
+				spec.GetMetaInfo ());
+#endif
+		}
+
+		public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
+		{
+			Error_TypeArgumentsCannotBeUsed (ec, "field", GetSignatureForError (), loc);
+		}
+	}
+
+	
+	//
+	// Expression that evaluates to a Property.
+	//
+	// This is not an LValue because we need to re-write the expression. We
+	// can not take data from the stack and store it.
+	//
+	sealed class PropertyExpr : PropertyOrIndexerExpr<PropertySpec>
+	{
+		Arguments arguments;
+
+		public PropertyExpr (PropertySpec spec, Location l)
+			: base (l)
+		{
+			best_candidate = spec;
+			type = spec.MemberType;
+		}
+
+		#region Properties
+
+		protected override Arguments Arguments {
+			get {
+				return arguments;
+			}
+			set {
+				arguments = value;
+			}
+		}
+
+		protected override TypeSpec DeclaringType {
+			get {
+				return best_candidate.DeclaringType;
+			}
+		}
+
+		public override string Name {
+			get {
+				return best_candidate.Name;
+			}
+		}
+
+		public override bool IsInstance {
+			get {
+				return !IsStatic;
+			}
+		}
+
+		public override bool IsStatic {
+			get {
+				return best_candidate.IsStatic;
+			}
+		}
+
+		public override string KindName {
+			get { return "property"; }
+		}
+
+		public PropertySpec PropertyInfo {
+			get {
+				return best_candidate;
+			}
+		}
+
+		#endregion
+
+		public override MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
+		{
+			if (best_candidate == null || !(best_candidate.IsStatic || InstanceExpression is This))
+				return null;
+
+			var args_count = arguments == null ? 0 : arguments.Count;
+			if (args_count != body.Parameters.Count && args_count == 0)
+				return null;
+
+			var mg = MethodGroupExpr.CreatePredefined (best_candidate.Get, DeclaringType, loc);
+			mg.InstanceExpression = InstanceExpression;
+
+			return mg;
+		}
+
+		public static PropertyExpr CreatePredefined (PropertySpec spec, Location loc)
+		{
+			return new PropertyExpr (spec, loc) {
+				Getter = spec.Get,
+				Setter = spec.Set
+			};
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (ConditionalAccess) {
+				Error_NullShortCircuitInsideExpressionTree (ec);
+			}
+
+			Arguments args;
+			if (IsSingleDimensionalArrayLength ()) {
+				args = new Arguments (1);
+				args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
+				return CreateExpressionFactoryCall (ec, "ArrayLength", args);
+			}
+
+			args = new Arguments (2);
+			if (InstanceExpression == null)
+				args.Add (new Argument (new NullLiteral (loc)));
+			else
+				args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
+			args.Add (new Argument (new TypeOfMethod (Getter, loc)));
+			return CreateExpressionFactoryCall (ec, "Property", args);
+		}
+
+		public Expression CreateSetterTypeOfExpression (ResolveContext rc)
+		{
+			DoResolveLValue (rc, null);
+			return new TypeOfMethod (Setter, loc);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return best_candidate.GetSignatureForError ();
+		}
+
+		public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo ());
+#endif
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo ());
+#endif
+		}
+
+		void Error_PropertyNotValid (ResolveContext ec)
+		{
+			ec.Report.SymbolRelatedToPreviousError (best_candidate);
+			ec.Report.Error (1546, loc, "Property or event `{0}' is not supported by the C# language",
+				GetSignatureForError ());
+		}
+
+		bool IsSingleDimensionalArrayLength ()
+		{
+			if (best_candidate.DeclaringType.BuiltinType != BuiltinTypeSpec.Type.Array || !best_candidate.HasGet || Name != "Length")
+				return false;
+
+			ArrayContainer ac = InstanceExpression.Type as ArrayContainer;
+			return ac != null && ac.Rank == 1;
+		}
+
+		public override void Emit (EmitContext ec, bool leave_copy)
+		{
+			//
+			// Special case: length of single dimension array property is turned into ldlen
+			//
+			if (IsSingleDimensionalArrayLength ()) {
+				if (conditional_access_receiver) {
+					ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+				}
+
+				EmitInstance (ec, false);
+
+				ec.Emit (OpCodes.Ldlen);
+				ec.Emit (OpCodes.Conv_I4);
+
+				if (conditional_access_receiver) {
+					ec.CloseConditionalAccess (type);
+				}
+
+				return;
+			}
+
+			base.Emit (ec, leave_copy);
+		}
+
+		public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			Arguments args;
+			LocalTemporary await_source_arg = null;
+
+			if (isCompound && !(source is DynamicExpressionStatement)) {
+				emitting_compound_assignment = true;
+				source.Emit (ec);
+
+				if (has_await_arguments) {
+					await_source_arg = new LocalTemporary (Type);
+					await_source_arg.Store (ec);
+
+					args = new Arguments (1);
+					args.Add (new Argument (await_source_arg));
+
+					if (leave_copy) {
+						temp = await_source_arg;
+					}
+
+					has_await_arguments = false;
+				} else {
+					args = null;
+
+					if (leave_copy) {
+						ec.Emit (OpCodes.Dup);
+						temp = new LocalTemporary (this.Type);
+						temp.Store (ec);
+					}
+				}
+			} else {
+				args = arguments ?? new Arguments (1);
+
+				if (leave_copy) {
+					source.Emit (ec);
+					temp = new LocalTemporary (this.Type);
+					temp.Store (ec);
+					args.Add (new Argument (temp));
+				} else {
+					args.Add (new Argument (source));
+				}
+			}
+
+			emitting_compound_assignment = false;
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = InstanceExpression;
+			if (args == null)
+				call.InstanceExpressionOnStack = true;
+
+			if (ConditionalAccess) {
+				call.ConditionalAccess = true;
+			}
+
+			if (leave_copy)
+				call.Emit (ec, Setter, args, loc);
+			else
+				call.EmitStatement (ec, Setter, args, loc);
+
+			if (temp != null) {
+				temp.Emit (ec);
+				temp.Release (ec);
+			}
+
+			if (await_source_arg != null) {
+				await_source_arg.Release (ec);
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.FlowAnalysis (fc);
+
+			if (conditional_access_receiver)
+				fc.ConditionalAccessEnd ();
+		}
+
+		protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
+		{
+			eclass = ExprClass.PropertyAccess;
+
+			if (best_candidate.IsNotCSharpCompatible) {
+				Error_PropertyNotValid (rc);
+			}
+
+			ResolveInstanceExpression (rc, right_side);
+
+			if ((best_candidate.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0 && best_candidate.DeclaringType != InstanceExpression.Type) {
+				var filter = new MemberFilter (best_candidate.Name, 0, MemberKind.Property, null, null);
+				var p = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as PropertySpec;
+				if (p != null) {
+					type = p.MemberType;
+				}
+			}
+
+			DoBestMemberChecks (rc, best_candidate);
+
+			// Handling of com-imported properties with any number of default property parameters
+			if (best_candidate.HasGet && !best_candidate.Get.Parameters.IsEmpty) {
+				var p = best_candidate.Get.Parameters;
+				arguments = new Arguments (p.Count);
+				for (int i = 0; i < p.Count; ++i) {
+					arguments.Add (new Argument (OverloadResolver.ResolveDefaultValueArgument (rc, p.Types [i], p.FixedParameters [i].DefaultValue, loc)));
+				}
+			} else if (best_candidate.HasSet && best_candidate.Set.Parameters.Count > 1) {
+				var p = best_candidate.Set.Parameters;
+				arguments = new Arguments (p.Count - 1);
+				for (int i = 0; i < p.Count - 1; ++i) {
+					arguments.Add (new Argument (OverloadResolver.ResolveDefaultValueArgument (rc, p.Types [i], p.FixedParameters [i].DefaultValue, loc)));
+				}
+			}
+
+			return this;
+		}
+
+		public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
+		{
+			Error_TypeArgumentsCannotBeUsed (ec, "property", GetSignatureForError (), loc);
+		}
+	}
+
+	abstract class PropertyOrIndexerExpr<T> : MemberExpr, IDynamicAssign where T : PropertySpec
+	{
+		// getter and setter can be different for base calls
+		MethodSpec getter, setter;
+		protected T best_candidate;
+
+		protected LocalTemporary temp;
+		protected bool emitting_compound_assignment;
+		protected bool has_await_arguments;
+
+		protected PropertyOrIndexerExpr (Location l)
+		{
+			loc = l;
+		}
+
+		#region Properties
+
+		protected abstract Arguments Arguments { get; set; }
+
+		public MethodSpec Getter {
+			get {
+				return getter;
+			}
+			set {
+				getter = value;
+			}
+		}
+
+		public MethodSpec Setter {
+			get {
+				return setter;
+			}
+			set {
+				setter = value;
+			}
+		}
+
+		#endregion
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (eclass == ExprClass.Unresolved) {
+				ResolveConditionalAccessReceiver (ec);
+
+				var expr = OverloadResolve (ec, null);
+				if (expr == null)
+					return null;
+
+				if (expr != this)
+					return expr.Resolve (ec);
+
+				if (conditional_access_receiver) {
+					type = LiftMemberType (ec, type);
+					ec.With (ResolveContext.Options.ConditionalAccessReceiver, false);
+				}
+			}
+
+			if (!ResolveGetter (ec))
+				return null;
+
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			if (ConditionalAccess)
+				throw new NotSupportedException ("null propagating operator assignment");
+
+			if (right_side == EmptyExpression.OutAccess) {
+				// TODO: best_candidate can be null at this point
+				INamedBlockVariable variable = null;
+				if (best_candidate != null && ec.CurrentBlock.ParametersBlock.TopBlock.GetLocalName (best_candidate.Name, ec.CurrentBlock, ref variable) && variable is Linq.RangeVariable) {
+					ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
+						best_candidate.Name);
+				} else {
+					right_side.DoResolveLValue (ec, this);
+				}
+				return null;
+			}
+
+			if (eclass == ExprClass.Unresolved) {
+				var expr = OverloadResolve (ec, right_side);
+				if (expr == null)
+					return null;
+
+				if (expr != this)
+					return expr.ResolveLValue (ec, right_side);
+			} else {
+				ResolveInstanceExpression (ec, right_side);
+			}
+
+			if (!ResolveSetter (ec))
+				return null;
+
+			return this;
+		}
+
+		void EmitConditionalAccess (EmitContext ec, ref CallEmitter call, MethodSpec method, Arguments arguments)
+		{
+			ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+
+			call.Emit (ec, method, arguments, loc);
+
+			ec.CloseConditionalAccess (method.ReturnType != type && type.IsNullableType ? type : null);
+		}
+
+		//
+		// Implements the IAssignMethod interface for assignments
+		//
+		public virtual void Emit (EmitContext ec, bool leave_copy)
+		{
+			var call = new CallEmitter ();
+			call.ConditionalAccess = ConditionalAccess;
+			call.InstanceExpression = InstanceExpression;
+			if (has_await_arguments)
+				call.HasAwaitArguments = true;
+			else
+				call.DuplicateArguments = emitting_compound_assignment;
+
+			if (conditional_access_receiver)
+				EmitConditionalAccess (ec, ref call, Getter, Arguments);
+			else
+				call.Emit (ec, Getter, Arguments, loc);
+
+			if (call.HasAwaitArguments) {
+				InstanceExpression = call.InstanceExpression;
+				Arguments = call.EmittedArguments;
+				has_await_arguments = true;
+			}
+
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				temp = new LocalTemporary (Type);
+				temp.Store (ec);
+			}
+		}
+
+		public abstract void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound);
+
+		public override void Emit (EmitContext ec)
+		{
+			Emit (ec, false);
+		}
+
+		protected override FieldExpr EmitToFieldSource (EmitContext ec)
+		{
+			has_await_arguments = true;
+			Emit (ec, false);
+			return null;
+		}
+
+		public abstract SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source);
+
+		protected abstract Expression OverloadResolve (ResolveContext rc, Expression right_side);
+
+		bool ResolveGetter (ResolveContext rc)
+		{
+			if (!best_candidate.HasGet) {
+				if (InstanceExpression != EmptyExpression.Null) {
+					rc.Report.SymbolRelatedToPreviousError (best_candidate);
+					rc.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
+						best_candidate.GetSignatureForError ());
+					return false;
+				}
+			} else if (!best_candidate.Get.IsAccessible (rc) || !best_candidate.Get.DeclaringType.IsAccessible (rc)) {
+				if (best_candidate.HasDifferentAccessibility) {
+					rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
+					rc.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
+						TypeManager.CSharpSignature (best_candidate));
+				} else {
+					rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
+					ErrorIsInaccesible (rc, best_candidate.Get.GetSignatureForError (), loc);
+				}
+			}
+
+			if (best_candidate.HasDifferentAccessibility) {
+				CheckProtectedMemberAccess (rc, best_candidate.Get);
+			}
+
+			getter = CandidateToBaseOverride (rc, best_candidate.Get);
+			return true;
+		}
+
+		bool ResolveSetter (ResolveContext rc)
+		{
+			if (!best_candidate.HasSet) {
+				rc.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read-only)",
+					GetSignatureForError ());
+				return false;
+			}
+
+			if (!best_candidate.Set.IsAccessible (rc) || !best_candidate.Set.DeclaringType.IsAccessible (rc)) {
+				if (best_candidate.HasDifferentAccessibility) {
+					rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
+					rc.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
+						GetSignatureForError ());
+				} else {
+					rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
+					ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc);
+				}
+			}
+
+			if (best_candidate.HasDifferentAccessibility)
+				CheckProtectedMemberAccess (rc, best_candidate.Set);
+
+			setter = CandidateToBaseOverride (rc, best_candidate.Set);
+			return true;
+		}
+	}
+
+	/// <summary>
+	///   Fully resolved expression that evaluates to an Event
+	/// </summary>
+	public class EventExpr : MemberExpr, IAssignMethod
+	{
+		readonly EventSpec spec;
+		MethodSpec op;
+
+		public EventExpr (EventSpec spec, Location loc)
+		{
+			this.spec = spec;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		protected override TypeSpec DeclaringType {
+			get {
+				return spec.DeclaringType;
+			}
+		}
+
+		public override string Name {
+			get {
+				return spec.Name;
+			}
+		}
+
+		public override bool IsInstance {
+			get {
+				return !spec.IsStatic;
+			}
+		}
+
+		public override bool IsStatic {
+			get {
+				return spec.IsStatic;
+			}
+		}
+
+		public override string KindName {
+			get { return "event"; }
+		}
+
+		public MethodSpec Operator {
+			get {
+				return op;
+			}
+		}
+
+		#endregion
+
+		public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
+		{
+			//
+			// If the event is local to this class and we are not lhs of +=/-= we transform ourselves into a FieldExpr
+			//
+			if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
+				if (spec.BackingField != null &&
+					(spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition))) {
+
+					spec.MemberDefinition.SetIsUsed ();
+
+					if (!ec.IsObsolete) {
+						ObsoleteAttribute oa = spec.GetAttributeObsolete ();
+						if (oa != null)
+							AttributeTester.Report_ObsoleteMessage (oa, spec.GetSignatureForError (), loc, ec.Report);
+					}
+
+					if ((spec.Modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
+						Error_AssignmentEventOnly (ec);
+
+					FieldExpr ml = new FieldExpr (spec.BackingField, loc);
+
+					InstanceExpression = null;
+
+					return ml.ResolveMemberAccess (ec, left, original);
+				}
+			}
+
+			return base.ResolveMemberAccess (ec, left, original);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			if (right_side == EmptyExpression.EventAddition) {
+				op = spec.AccessorAdd;
+			} else if (right_side == EmptyExpression.EventSubtraction) {
+				op = spec.AccessorRemove;
+			}
+
+			if (op == null) {
+				Error_AssignmentEventOnly (ec);
+				return null;
+			}
+
+			op = CandidateToBaseOverride (ec, op);
+			return this;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.EventAccess;
+			type = spec.MemberType;
+
+			ResolveInstanceExpression (ec, null);
+
+			if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
+				Error_AssignmentEventOnly (ec);
+			}
+
+			DoBestMemberChecks (ec, spec);
+			return this;
+		}		
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new NotSupportedException ();
+			//Error_CannotAssign ();
+		}
+
+		#region IAssignMethod Members
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			if (leave_copy || !isCompound)
+				throw new NotImplementedException ("EventExpr::EmitAssign");
+
+			Arguments args = new Arguments (1);
+			args.Add (new Argument (source));
+
+			// TODO: Wrong, needs receiver
+//			if (NullShortCircuit) {
+//				ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+//			}
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = InstanceExpression;
+			call.ConditionalAccess = ConditionalAccess;
+			call.EmitStatement (ec, op, args, loc);
+
+//			if (NullShortCircuit)
+//				ec.CloseConditionalAccess (null);
+		}
+
+		#endregion
+
+		void Error_AssignmentEventOnly (ResolveContext ec)
+		{
+			if (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition)) {
+				ec.Report.Error (79, loc,
+					"The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
+					GetSignatureForError ());
+			} else {
+				ec.Report.Error (70, loc,
+					"The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
+					GetSignatureForError (), spec.DeclaringType.GetSignatureForError ());
+			}
+		}
+
+		protected override void Error_CannotCallAbstractBase (ResolveContext rc, string name)
+		{
+			name = name.Substring (0, name.LastIndexOf ('.'));
+			base.Error_CannotCallAbstractBase (rc, name);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return TypeManager.CSharpSignature (spec);
+		}
+
+		public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
+		{
+			Error_TypeArgumentsCannotBeUsed (ec, "event", GetSignatureForError (), loc);
+		}
+	}
+
+	public class TemporaryVariableReference : VariableReference
+	{
+		public class Declarator : Statement
+		{
+			TemporaryVariableReference variable;
+
+			public Declarator (TemporaryVariableReference variable)
+			{
+				this.variable = variable;
+				loc = variable.loc;
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				variable.li.CreateBuilder (ec);
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				// Don't create sequence point
+				DoEmit (ec);
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				return false;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+				// Nothing
+			}
+		}
+
+		LocalVariable li;
+
+		public TemporaryVariableReference (LocalVariable li, Location loc)
+		{
+			this.li = li;
+			this.type = li.Type;
+			this.loc = loc;
+		}
+
+		public override bool IsLockedByStatement {
+			get {
+				return false;
+			}
+			set {
+			}
+		}
+
+		public LocalVariable LocalInfo {
+		    get {
+		        return li;
+		    }
+		}
+
+		public static TemporaryVariableReference Create (TypeSpec type, Block block, Location loc)
+		{
+			var li = LocalVariable.CreateCompilerGenerated (type, block, loc);
+			return new TemporaryVariableReference (li, loc);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Variable;
+
+			//
+			// Don't capture temporary variables except when using
+			// state machine redirection and block yields
+			//
+			if (ec.CurrentAnonymousMethod is StateMachineInitializer &&
+				(ec.CurrentBlock.Explicit.HasYield || ec.CurrentBlock.Explicit.HasAwait) &&
+				ec.IsVariableCapturingRequired) {
+				AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
+				storey.CaptureLocalVariable (ec, li);
+			}
+
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			return Resolve (ec);
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			li.CreateBuilder (ec);
+
+			Emit (ec, false);
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source)
+		{
+			li.CreateBuilder (ec);
+
+			EmitAssign (ec, source, false, false);
+		}
+
+		public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
+		{
+			return li.HoistedVariant;
+		}
+
+		public override bool IsFixed {
+			get { return true; }
+		}
+
+		public override bool IsRef {
+			get { return false; }
+		}
+
+		public override string Name {
+			get { throw new NotImplementedException (); }
+		}
+
+		public override void SetHasAddressTaken ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		protected override ILocalVariable Variable {
+			get { return li; }
+		}
+
+		public override VariableInfo VariableInfo {
+			get { return null; }
+		}
+	}
+
+	/// 
+	/// Handles `var' contextual keyword; var becomes a keyword only
+	/// if no type called var exists in a variable scope
+	/// 
+	class VarExpr : SimpleName
+	{
+		public VarExpr (Location loc)
+			: base ("var", loc)
+		{
+		}
+
+		public bool InferType (ResolveContext ec, Expression right_side)
+		{
+			if (type != null)
+				throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
+			
+			type = right_side.Type;
+			if (type == InternalType.NullLiteral || type.Kind == MemberKind.Void || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) {
+				ec.Report.Error (815, loc,
+					"An implicitly typed local variable declaration cannot be initialized with `{0}'",
+					type.GetSignatureForError ());
+				return false;
+			}
+
+			eclass = ExprClass.Variable;
+			return true;
+		}
+
+		protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
+		{
+			if (ec.Module.Compiler.Settings.Version < LanguageVersion.V_3)
+				base.Error_TypeOrNamespaceNotFound (ec);
+			else
+				ec.Module.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
+		}
+	}
+	
+	public class InvalidStatementExpression : Statement
+	{
+		public Expression Expression {
+			get;
+			private set;
+		}
+		
+		public InvalidStatementExpression (Expression expr)
+		{
+			this.Expression = expr;
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			// nothing
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			// nothing
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			// nothing
+		}
+		
+		public override Mono.CSharp.Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return null;
+		}
+		
+		public override object Accept (Mono.CSharp.StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		protected override bool DoFlowAnalysis(FlowAnalysisContext fc)
+		{
+			return false;
+		}
+	}
+}	
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/enum.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/enum.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/enum.cs	(revision 11807)
@@ -0,0 +1,339 @@
+//
+// enum.cs: Enum handling.
+//
+// Author: Miguel de Icaza (miguel@gnu.org)
+//         Ravi Pratap     (ravi@ximian.com)
+//         Marek Safar     (marek.safar@seznam.cz)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2003 Novell, Inc (http://www.novell.com)
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+#endif
+
+namespace Mono.CSharp {
+
+	public class EnumMember : Const
+	{
+		class EnumTypeExpr : TypeExpr
+		{
+			public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments)
+			{
+				type = ec.CurrentType;
+				eclass = ExprClass.Type;
+				return type;
+			}
+		}
+
+		public EnumMember (Enum parent, MemberName name, Attributes attrs)
+			: base (parent, new EnumTypeExpr (), Modifiers.PUBLIC, name, attrs)
+		{
+		}
+
+		static bool IsValidEnumType (TypeSpec t)
+		{
+			switch (t.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.Char:
+				return true;
+			default:
+				return t.IsEnum;
+			}
+		}
+
+		public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
+		{
+			if (expr is EnumConstant)
+				expr = ((EnumConstant) expr).Child;
+
+			var en = (Enum)Parent;
+			var underlying = en.UnderlyingType;
+			if (expr != null) {
+				expr = expr.ImplicitConversionRequired (rc, underlying);
+				if (expr != null && !IsValidEnumType (expr.Type)) {
+					en.Error_UnderlyingType (Location);
+					expr = null;
+				}
+			}
+
+			if (expr == null)
+				expr = New.Constantify (underlying, Location);
+
+			return new EnumConstant (expr, MemberType);
+		}
+
+		public override bool Define ()
+		{
+			if (!ResolveMemberType ())
+				return false;
+
+			const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal;
+			FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), attr);
+			spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer);
+
+			Parent.MemberCache.AddMember (spec);
+			return true;
+		}
+		
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+	}
+
+	/// <summary>
+	///   Enumeration container
+	/// </summary>
+	public class Enum : TypeDefinition
+	{
+		//
+		// Implicit enum member initializer, used when no constant value is provided
+		//
+		sealed class ImplicitInitializer : Expression
+		{
+			readonly EnumMember prev;
+			readonly EnumMember current;
+
+			public ImplicitInitializer (EnumMember current, EnumMember prev)
+			{
+				this.current = current;
+				this.prev = prev;
+			}
+
+			public override bool ContainsEmitWithAwait ()
+			{
+				return false;
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				throw new NotSupportedException ("Missing Resolve call");
+			}
+
+			protected override Expression DoResolve (ResolveContext rc)
+			{
+				// We are the first member
+				if (prev == null) {
+					return New.Constantify (current.Parent.Definition, Location);
+				}
+
+				var c = ((ConstSpec) prev.Spec).GetConstant (rc) as EnumConstant;
+				try {
+					return c.Increment ();
+				} catch (OverflowException) {
+					rc.Report.Error (543, current.Location,
+						"The enumerator value `{0}' is outside the range of enumerator underlying type `{1}'",
+						current.GetSignatureForError (), ((Enum) current.Parent).UnderlyingType.GetSignatureForError ());
+
+					return New.Constantify (current.Parent.Definition, current.Location);
+				}
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				throw new NotSupportedException ("Missing Resolve call");
+			}
+		}
+
+		public static readonly string UnderlyingValueField = "value__";
+
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE;
+
+		readonly FullNamedExpression underlying_type_expr;
+
+		public Enum (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
+			: base (parent, name, attrs, MemberKind.Enum)
+		{
+			underlying_type_expr = type;
+			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+			ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags, accmods, Location, Report);
+			spec = new EnumSpec (null, this, null, null, ModFlags);
+		}
+
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Enum;
+			}
+		}
+
+		public FullNamedExpression BaseTypeExpression {
+			get {
+				return underlying_type_expr;
+			}
+		}
+
+		protected override TypeAttributes TypeAttr {
+			get {
+				return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed;
+			}
+		}
+
+		public TypeSpec UnderlyingType {
+			get {
+				return ((EnumSpec) spec).UnderlyingType;
+			}
+		}
+
+		#endregion
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public void AddEnumMember (EnumMember em)
+		{
+			if (em.Name == UnderlyingValueField) {
+				Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `{0}'",
+					UnderlyingValueField);
+				return;
+			}
+
+			AddMember (em);
+		}
+
+		public void Error_UnderlyingType (Location loc)
+		{
+			Report.Error (1008, loc,
+				"Type byte, sbyte, short, ushort, int, uint, long or ulong expected");
+		}
+
+		protected override void DoDefineContainer ()
+		{
+			TypeSpec ut;
+			if (underlying_type_expr != null) {
+				ut = underlying_type_expr.ResolveAsType (this);
+				if (!EnumSpec.IsValidUnderlyingType (ut)) {
+					Error_UnderlyingType (underlying_type_expr.Location);
+					ut = null;
+				}
+			} else {
+				ut = null;
+			}
+
+			if (ut == null)
+				ut = Compiler.BuiltinTypes.Int;
+
+			((EnumSpec) spec).UnderlyingType = ut;
+
+			TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType.GetMetaInfo (),
+				FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
+
+			DefineBaseTypes ();
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			for (int i = 0; i < Members.Count; ++i) {
+				EnumMember em = (EnumMember) Members[i];
+				if (em.Initializer == null) {
+					em.Initializer = new ImplicitInitializer (em, i == 0 ? null : (EnumMember) Members[i - 1]);
+				}
+
+				em.Define ();
+			}
+
+			return true;
+		}
+
+		public override bool IsUnmanagedType ()
+		{
+			return true;
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			base_type = Compiler.BuiltinTypes.Enum;
+			base_class = null;
+			return null;
+		}
+		
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			switch (UnderlyingType.BuiltinType) {
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.UShort:
+				Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
+					GetSignatureForError (), UnderlyingType.GetSignatureForError ());
+				break;
+			}
+
+			return true;
+		}
+	}
+
+	class EnumSpec : TypeSpec
+	{
+		TypeSpec underlying;
+
+		public EnumSpec (TypeSpec declaringType, ITypeDefinition definition, TypeSpec underlyingType, MetaType info, Modifiers modifiers)
+			: base (MemberKind.Enum, declaringType, definition, info, modifiers | Modifiers.SEALED)
+		{
+			this.underlying = underlyingType;
+		}
+
+		public TypeSpec UnderlyingType {
+			get {
+				return underlying;
+			}
+			set {
+				if (underlying != null)
+					throw new InternalErrorException ("UnderlyingType reset");
+
+				underlying = value;
+			}
+		}
+
+		public static TypeSpec GetUnderlyingType (TypeSpec t)
+		{
+			return ((EnumSpec) t.GetDefinition ()).UnderlyingType;
+		}
+
+		public static bool IsValidUnderlyingType (TypeSpec type)
+		{
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.ULong:
+				return true;
+			}
+
+			return false;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/eval.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/eval.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/eval.cs	(revision 11807)
@@ -0,0 +1,1333 @@
+//
+// eval.cs: Evaluation and Hosting API for the C# compiler
+//
+// Authors:
+//   Miguel de Icaza (miguel@gnome.org)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2011 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Threading;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.IO;
+using System.Text;
+using System.Linq;
+
+namespace Mono.CSharp
+{
+
+	/// <summary>
+	/// Experimental!
+	/// </summary>
+	public delegate void ValueModificationHandler (string variableName, int row, int column, object value);
+
+	/// <summary>
+	///   Evaluator: provides an API to evaluate C# statements and
+	///   expressions dynamically.
+	/// </summary>
+	/// <remarks>
+	///   This class exposes static methods to evaluate expressions in the
+	///   current program.
+	///
+	///   To initialize the evaluator with a number of compiler
+	///   options call the Init(string[]args) method with a set of
+	///   command line options that the compiler recognizes.
+	///
+	///   To interrupt execution of a statement, you can invoke the
+	///   Evaluator.Interrupt method.
+	/// </remarks>
+	public class Evaluator {
+
+		enum ParseMode {
+			// Parse silently, do not output any error messages
+			Silent,
+
+			// Report errors during parse
+			ReportErrors,
+
+			// Auto-complete, means that the tokenizer will start producing
+			// GETCOMPLETIONS tokens when it reaches a certain point.
+			GetCompletions
+		}
+
+		static object evaluator_lock = new object ();
+		static volatile bool invoking;
+		
+#if !STATIC
+		static int count;
+#endif
+		static Thread invoke_thread;
+
+		readonly Dictionary<string, Tuple<FieldSpec, FieldInfo>> fields;
+
+		Type base_class;
+		bool inited;
+		int startup_files;
+
+		readonly CompilerContext ctx;
+		readonly ModuleContainer module;
+		readonly ReflectionImporter importer;
+		readonly CompilationSourceFile source_file;
+
+		int? listener_id;
+		
+		public Evaluator (CompilerContext ctx)
+		{
+			this.ctx = ctx;
+
+			module = new ModuleContainer (ctx);
+			module.Evaluator = this;
+
+			source_file = new CompilationSourceFile (module, null);
+			module.AddTypeContainer (source_file);
+
+			startup_files = ctx.SourceFiles.Count;
+
+			// FIXME: Importer needs this assembly for internalsvisibleto
+			module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
+			importer = new ReflectionImporter (module, ctx.BuiltinTypes);
+
+			InteractiveBaseClass = typeof (InteractiveBase);
+			fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
+		}
+
+		void Init ()
+		{
+			var loader = new DynamicLoader (importer, ctx);
+
+			RootContext.ToplevelTypes = module;
+
+			//var startup_files = new List<string> ();
+			//foreach (CompilationUnit file in Location.SourceFiles)
+			//    startup_files.Add (file.Path);
+
+			loader.LoadReferences (module);
+			ctx.BuiltinTypes.CheckDefinitions (module);
+			module.InitializePredefinedTypes ();
+
+			inited = true;
+		}
+
+		void ParseStartupFiles ()
+		{
+			Driver d = new Driver (ctx);
+
+			Location.Initialize (ctx.SourceFiles);
+
+			var parser_session = new ParserSession ();
+			for (int i = 0; i < startup_files; ++i) {
+				var sf = ctx.SourceFiles [i];
+				d.Parse (sf, module, parser_session, ctx.Report);
+			}
+		}
+
+		void Reset ()
+		{
+			Location.Reset ();
+			Location.Initialize (ctx.SourceFiles);
+		}
+
+		/// <summary>
+		/// When set evaluator will automatically wait on Task of async methods. When not
+		/// set it's called responsibility to handle Task execution
+		/// </summary>
+		public bool WaitOnTask { get; set; }
+
+		/// <summary>
+		///   If true, turns type expressions into valid expressions
+		///   and calls the describe method on it
+		/// </summary>
+		public bool DescribeTypeExpressions;
+
+		/// <summary>
+		///   Whether the evaluator will use terse syntax, and the semicolons at the end are optional
+		/// </summary>
+		public bool Terse = true;
+
+		/// <summary>
+		///   The base class for the classes that host the user generated code
+		/// </summary>
+		/// <remarks>
+		///
+		///   This is the base class that will host the code
+		///   executed by the Evaluator.  By default
+		///   this is the Mono.CSharp.InteractiveBase class
+		///   which is useful for interactive use.
+		///
+		///   By changing this property you can control the
+		///   base class and the static members that are
+		///   available to your evaluated code.
+		/// </remarks>
+		public Type InteractiveBaseClass {
+			get {
+				return base_class;
+			}
+			set {
+				base_class = value;
+
+				if (value != null && typeof (InteractiveBase).IsAssignableFrom (value))
+					InteractiveBase.Evaluator = this;
+			}
+		}
+
+		/// <summary>
+		///   Interrupts the evaluation of an expression executing in Evaluate.
+		/// </summary>
+		/// <remarks>
+		///   Use this method to interrupt long-running invocations.
+		/// </remarks>
+		public void Interrupt ()
+		{
+			if (!inited || !invoking)
+				return;
+			
+			if (invoke_thread != null)
+				invoke_thread.Abort ();
+		}
+
+		/// <summary>
+		///   Compiles the input string and returns a delegate that represents the compiled code.
+		/// </summary>
+		/// <remarks>
+		///
+		///   Compiles the input string as a C# expression or
+		///   statement, unlike the Evaluate method, the
+		///   resulting delegate can be invoked multiple times
+		///   without incurring in the compilation overhead.
+		///
+		///   If the return value of this function is null,
+		///   this indicates that the parsing was complete.
+		///   If the return value is a string it indicates
+		///   that the input string was partial and that the
+		///   invoking code should provide more code before
+		///   the code can be successfully compiled.
+		///
+		///   If you know that you will always get full expressions or
+		///   statements and do not care about partial input, you can use
+		///   the other Compile overload. 
+		///
+		///   On success, in addition to returning null, the
+		///   compiled parameter will be set to the delegate
+		///   that can be invoked to execute the code.
+		///
+		/// </remarks>
+		public string Compile (string input, out CompiledMethod compiled)
+		{
+			if (input == null || input.Length == 0){
+				compiled = null;
+				return null;
+			}
+
+			lock (evaluator_lock){
+				if (!inited) {
+					Init ();
+					ParseStartupFiles ();
+				} else {
+					ctx.Report.Printer.Reset ();
+				}
+
+				bool partial_input;
+				CSharpParser parser = ParseString (ParseMode.Silent, input, out partial_input);
+
+				// Terse mode, try to provide the trailing semicolon automatically.
+				if (parser == null && Terse && partial_input){
+					bool ignore;
+
+					// check if the source would compile with a block, if so, we should not
+					// add the semicolon.
+					var needs_block = ParseString (ParseMode.Silent, input + "{}", out ignore) != null;
+					if (!needs_block)
+						parser = ParseString (ParseMode.Silent, input + ";", out ignore);
+				}
+				if (parser == null){
+					compiled = null;
+					if (partial_input)
+						return input;
+					
+					ParseString (ParseMode.ReportErrors, input, out partial_input);
+					return null;
+				}
+				
+				Class parser_result = parser.InteractiveResult;
+				compiled = CompileBlock (parser_result, parser.undo, ctx.Report);
+				return null;
+			}
+		}
+
+		/// <summary>
+		///   Compiles the input string and returns a delegate that represents the compiled code.
+		/// </summary>
+		/// <remarks>
+		///
+		///   Compiles the input string as a C# expression or
+		///   statement, unlike the Evaluate method, the
+		///   resulting delegate can be invoked multiple times
+		///   without incurring in the compilation overhead.
+		///
+		///   This method can only deal with fully formed input
+		///   strings and does not provide a completion mechanism.
+		///   If you must deal with partial input (for example for
+		///   interactive use) use the other overload. 
+		///
+		///   On success, a delegate is returned that can be used
+		///   to invoke the method.
+		///
+		/// </remarks>
+		public CompiledMethod Compile (string input)
+		{
+			CompiledMethod compiled;
+
+			// Ignore partial inputs
+			if (Compile (input, out compiled) != null){
+				// Error, the input was partial.
+				return null;
+			}
+
+			// Either null (on error) or the compiled method.
+			return compiled;
+		}
+
+		static MethodInfo listener_proxy_value;
+		internal void EmitValueChangedCallback (EmitContext ec, string name, TypeSpec type, Location loc)
+		{
+			if (listener_id == null)
+				listener_id = ListenerProxy.Register (ModificationListener);
+
+			if (listener_proxy_value == null)
+				listener_proxy_value = typeof (ListenerProxy).GetMethod ("ValueChanged");
+
+#if STATIC
+			throw new NotSupportedException ();
+#else
+			// object value, int row, int col, string name, int listenerId
+			if (type.IsStructOrEnum)
+				ec.Emit (OpCodes.Box, type);
+
+			ec.EmitInt (loc.Row);
+			ec.EmitInt (loc.Column);
+			ec.Emit (OpCodes.Ldstr, name);
+			ec.EmitInt (listener_id.Value);
+			ec.Emit (OpCodes.Call, listener_proxy_value);
+#endif
+		}
+
+		/// <summary>
+		///   Evaluates and expression or statement and returns any result values.
+		/// </summary>
+		/// <remarks>
+		///   Evaluates the input string as a C# expression or
+		///   statement.  If the input string is an expression
+		///   the result will be stored in the result variable
+		///   and the result_set variable will be set to true.
+		///
+		///   It is necessary to use the result/result_set
+		///   pair to identify when a result was set (for
+		///   example, execution of user-provided input can be
+		///   an expression, a statement or others, and
+		///   result_set would only be set if the input was an
+		///   expression.
+		///
+		///   If the return value of this function is null,
+		///   this indicates that the parsing was complete.
+		///   If the return value is a string, it indicates
+		///   that the input is partial and that the user
+		///   should provide an updated string.
+		/// </remarks>
+		public string Evaluate (string input, out object result, out bool result_set)
+		{
+			CompiledMethod compiled;
+
+			result_set = false;
+			result = null;
+
+			input = Compile (input, out compiled);
+			if (input != null)
+				return input;
+			
+			if (compiled == null)
+				return null;
+				
+			//
+			// The code execution does not need to keep the compiler lock
+			//
+			object retval = typeof (QuitValue);
+
+			try {
+				invoke_thread = System.Threading.Thread.CurrentThread;
+				invoking = true;
+				compiled (ref retval);
+			} catch (ThreadAbortException e){
+				Thread.ResetAbort ();
+				Console.WriteLine ("Interrupted!\n{0}", e);
+			} finally {
+				invoking = false;
+
+				if (listener_id != null) {
+					ListenerProxy.Unregister (listener_id.Value);
+					listener_id = null;
+				}
+			}
+
+			//
+			// We use a reference to a compiler type, in this case
+			// Driver as a flag to indicate that this was a statement
+			//
+			if (!ReferenceEquals (retval, typeof (QuitValue))) {
+				result_set = true;
+				result = retval; 
+			}
+
+			return null;
+		}
+
+		public string [] GetCompletions (string input, out string prefix)
+		{
+			prefix = "";
+			if (input == null || input.Length == 0)
+				return null;
+			
+			lock (evaluator_lock){
+				if (!inited)
+					Init ();
+				
+				bool partial_input;
+				CSharpParser parser = ParseString (ParseMode.GetCompletions, input, out partial_input);
+				if (parser == null){
+					return null;
+				}
+
+				Class host = parser.InteractiveResult;
+
+				var base_class_imported = importer.ImportType (base_class);
+				var baseclass_list = new List<FullNamedExpression> (1) {
+					new TypeExpression (base_class_imported, host.Location)
+				};
+				host.SetBaseTypes (baseclass_list);
+
+#if NET_4_0
+				var access = AssemblyBuilderAccess.RunAndCollect;
+#else
+				var access = AssemblyBuilderAccess.Run;
+#endif
+				var a = new AssemblyDefinitionDynamic (module, "completions");
+				a.Create (AppDomain.CurrentDomain, access);
+				module.SetDeclaringAssembly (a);
+
+				// Need to setup MemberCache
+				host.CreateContainer ();
+				// Need to setup base type
+				host.DefineContainer ();
+
+				var method = host.Members[0] as Method;
+				BlockContext bc = new BlockContext (method, method.Block, ctx.BuiltinTypes.Void);
+
+				try {
+					method.Block.Resolve (bc, method);
+				} catch (CompletionResult cr) {
+					prefix = cr.BaseText;
+					return cr.Result;
+				} 
+			}
+			return null;
+		}
+
+		/// <summary>
+		///   Executes the given expression or statement.
+		/// </summary>
+		/// <remarks>
+		///    Executes the provided statement, returns true
+		///    on success, false on parsing errors.  Exceptions
+		///    might be thrown by the called code.
+		/// </remarks>
+		public bool Run (string statement)
+		{
+			object result;
+			bool result_set;
+
+			return Evaluate (statement, out result, out result_set) == null;
+		}
+
+		/// <summary>
+		///   Evaluates and expression or statement and returns the result.
+		/// </summary>
+		/// <remarks>
+		///   Evaluates the input string as a C# expression or
+		///   statement and returns the value.   
+		///
+		///   This method will throw an exception if there is a syntax error,
+		///   of if the provided input is not an expression but a statement.
+		/// </remarks>
+		public object Evaluate (string input)
+		{
+			object result;
+			bool result_set;
+			
+			string r = Evaluate (input, out result, out result_set);
+
+			if (r != null)
+				throw new ArgumentException ("Syntax error on input: partial input");
+			
+			if (result_set == false)
+				throw new ArgumentException ("The expression failed to resolve");
+
+			return result;
+		}
+
+		/// <summary>
+		/// Experimental!
+		/// </summary>
+		public ValueModificationHandler ModificationListener { get; set; }
+
+		enum InputKind {
+			EOF,
+			StatementOrExpression,
+			CompilationUnit,
+			Error
+		}
+
+		//
+		// Deambiguates the input string to determine if we
+		// want to process a statement or if we want to
+		// process a compilation unit.
+		//
+		// This is done using a top-down predictive parser,
+		// since the yacc/jay parser can not deambiguage this
+		// without more than one lookahead token.   There are very
+		// few ambiguities.
+		//
+		InputKind ToplevelOrStatement (SeekableStreamReader seekable)
+		{
+			Tokenizer tokenizer = new Tokenizer (seekable, source_file, new ParserSession (), ctx.Report);
+			
+			// Prefer contextual block keywords over identifiers
+			tokenizer.parsing_block++;
+
+			int t = tokenizer.token ();
+			switch (t){
+			case Token.EOF:
+				return InputKind.EOF;
+				
+			// These are toplevels
+			case Token.EXTERN:
+			case Token.OPEN_BRACKET:
+			case Token.ABSTRACT:
+			case Token.CLASS:
+			case Token.ENUM:
+			case Token.INTERFACE:
+			case Token.INTERNAL:
+			case Token.NAMESPACE:
+			case Token.PRIVATE:
+			case Token.PROTECTED:
+			case Token.PUBLIC:
+			case Token.SEALED:
+			case Token.STATIC:
+			case Token.STRUCT:
+				return InputKind.CompilationUnit;
+				
+			// Definitely expression
+			case Token.FIXED:
+			case Token.BOOL:
+			case Token.BYTE:
+			case Token.CHAR:
+			case Token.DECIMAL:
+			case Token.DOUBLE:
+			case Token.FLOAT:
+			case Token.INT:
+			case Token.LONG:
+			case Token.NEW:
+			case Token.OBJECT:
+			case Token.SBYTE:
+			case Token.SHORT:
+			case Token.STRING:
+			case Token.UINT:
+			case Token.ULONG:
+				return InputKind.StatementOrExpression;
+
+			// These need deambiguation help
+			case Token.USING:
+				t = tokenizer.token ();
+				if (t == Token.EOF)
+					return InputKind.EOF;
+
+				if (t == Token.IDENTIFIER)
+					return InputKind.CompilationUnit;
+				return InputKind.StatementOrExpression;
+
+
+			// Distinguish between:
+			//    delegate opt_anonymous_method_signature block
+			//    delegate type 
+			case Token.DELEGATE:
+				t = tokenizer.token ();
+				if (t == Token.EOF)
+					return InputKind.EOF;
+				if (t == Token.OPEN_PARENS || t == Token.OPEN_BRACE)
+					return InputKind.StatementOrExpression;
+				return InputKind.CompilationUnit;
+
+			// Distinguih between:
+			//    unsafe block
+			//    unsafe as modifier of a type declaration
+			case Token.UNSAFE:
+				t = tokenizer.token ();
+				if (t == Token.EOF)
+					return InputKind.EOF;
+				if (t == Token.OPEN_PARENS)
+					return InputKind.StatementOrExpression;
+				return InputKind.CompilationUnit;
+				
+		        // These are errors: we list explicitly what we had
+			// from the grammar, ERROR and then everything else
+
+			case Token.READONLY:
+			case Token.OVERRIDE:
+			case Token.ERROR:
+				return InputKind.Error;
+
+			// This catches everything else allowed by
+			// expressions.  We could add one-by-one use cases
+			// if needed.
+			default:
+				return InputKind.StatementOrExpression;
+			}
+		}
+		
+		//
+		// Parses the string @input and returns a CSharpParser if succeeful.
+		//
+		// if @silent is set to true then no errors are
+		// reported to the user.  This is used to do various calls to the
+		// parser and check if the expression is parsable.
+		//
+		// @partial_input: if @silent is true, then it returns whether the
+		// parsed expression was partial, and more data is needed
+		//
+		CSharpParser ParseString (ParseMode mode, string input, out bool partial_input)
+		{
+			partial_input = false;
+			Reset ();
+
+			var enc = ctx.Settings.Encoding;
+			var s = new MemoryStream (enc.GetBytes (input));
+			SeekableStreamReader seekable = new SeekableStreamReader (s, enc);
+
+			InputKind kind = ToplevelOrStatement (seekable);
+			if (kind == InputKind.Error){
+				if (mode == ParseMode.ReportErrors)
+					ctx.Report.Error (-25, "Detection Parsing Error");
+				partial_input = false;
+				return null;
+			}
+
+			if (kind == InputKind.EOF){
+				if (mode == ParseMode.ReportErrors)
+					Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true");
+				partial_input = true;
+				return null;
+				
+			}
+			seekable.Position = 0;
+
+			source_file.DeclarationFound = false;
+			CSharpParser parser = new CSharpParser (seekable, source_file, new ParserSession ());
+
+			if (kind == InputKind.StatementOrExpression){
+				parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter;
+				parser.Lexer.parsing_block++;
+				ctx.Settings.StatementMode = true;
+			} else {
+				parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter;
+				ctx.Settings.StatementMode = false;
+			}
+
+			if (mode == ParseMode.GetCompletions)
+				parser.Lexer.CompleteOnEOF = true;
+
+			ReportPrinter old_printer = null;
+			if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions))
+				old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null));
+
+			try {
+				parser.parse ();
+			} finally {
+				if (ctx.Report.Errors != 0){
+					if (mode != ParseMode.ReportErrors  && parser.UnexpectedEOF)
+						partial_input = true;
+
+					if (parser.undo != null)
+						parser.undo.ExecuteUndo ();
+
+					parser = null;
+				}
+
+				if (old_printer != null)
+					ctx.Report.SetPrinter (old_printer);
+			}
+			return parser;
+		}
+
+		CompiledMethod CompileBlock (Class host, Undo undo, Report Report)
+		{
+#if STATIC
+			throw new NotSupportedException ();
+#else
+			string current_debug_name = "eval-" + count + ".dll";
+			++count;
+
+			AssemblyDefinitionDynamic assembly;
+			AssemblyBuilderAccess access;
+
+			if (Environment.GetEnvironmentVariable ("SAVE") != null) {
+				access = AssemblyBuilderAccess.RunAndSave;
+				assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name);
+				assembly.Importer = importer;
+			} else {
+#if NET_4_0
+				access = AssemblyBuilderAccess.RunAndCollect;
+#else
+				access = AssemblyBuilderAccess.Run;
+#endif
+				assembly = new AssemblyDefinitionDynamic (module, current_debug_name);
+			}
+
+			assembly.Create (AppDomain.CurrentDomain, access);
+
+			Method expression_method;
+			if (host != null) {
+				var base_class_imported = importer.ImportType (base_class);
+				var baseclass_list = new List<FullNamedExpression> (1) {
+					new TypeExpression (base_class_imported, host.Location)
+				};
+
+				host.SetBaseTypes (baseclass_list);
+
+				expression_method = (Method) host.Members[0];
+
+				if ((expression_method.ModFlags & Modifiers.ASYNC) != 0) {
+					//
+					// Host method is async. When WaitOnTask is set we wrap it with wait
+					//
+					// void AsyncWait (ref object $retval) {
+					//	$retval = Host();
+					//	((Task)$retval).Wait();  // When WaitOnTask is set
+					// }
+					//
+					var p = new ParametersCompiled (
+						new Parameter (new TypeExpression (module.Compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null)
+					);
+
+					var method = new Method(host, new TypeExpression(module.Compiler.BuiltinTypes.Void, Location.Null),
+						Modifiers.PUBLIC | Modifiers.STATIC, new MemberName("AsyncWait"), p, null);
+
+					method.Block = new ToplevelBlock(method.Compiler, p, Location.Null);
+					method.Block.AddStatement(new StatementExpression (new SimpleAssign(
+						new SimpleName(p [0].Name, Location.Null),
+						new Invocation(new SimpleName(expression_method.MemberName.Name, Location.Null), new Arguments(0)),
+						Location.Null), Location.Null));
+
+					if (WaitOnTask) {
+						var task = new Cast (expression_method.TypeExpression, new SimpleName (p [0].Name, Location.Null), Location.Null);
+
+						method.Block.AddStatement (new StatementExpression (new Invocation (
+								new MemberAccess (task, "Wait", Location.Null),
+							new Arguments (0)), Location.Null));
+					}
+
+					host.AddMember(method);
+
+					expression_method = method;
+				}
+
+				host.CreateContainer();
+				host.DefineContainer();
+				host.Define();
+
+			} else {
+				expression_method = null;
+			}
+
+			module.CreateContainer ();
+
+			// Disable module and source file re-definition checks
+			module.EnableRedefinition ();
+			source_file.EnableRedefinition ();
+
+			module.Define ();
+
+			if (Report.Errors != 0){
+				if (undo != null)
+					undo.ExecuteUndo ();
+
+				return null;
+			}
+
+			if (host != null){
+				host.PrepareEmit ();
+				host.EmitContainer ();
+			}
+			
+			module.EmitContainer ();
+
+			if (Report.Errors != 0){
+				if (undo != null)
+					undo.ExecuteUndo ();
+				return null;
+			}
+
+			module.CloseContainer ();
+			if (host != null)
+				host.CloseContainer ();
+
+			if (access == AssemblyBuilderAccess.RunAndSave)
+				assembly.Save ();
+
+			if (host == null)
+				return null;
+			
+			//
+			// Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
+			// work from MethodBuilders.   Retarded, I know.
+			//
+			var tt = assembly.Builder.GetType (host.TypeBuilder.Name);
+			var mi = tt.GetMethod (expression_method.MemberName.Name);
+
+			//
+			// We need to then go from FieldBuilder to FieldInfo
+			// or reflection gets confused (it basically gets confused, and variables override each
+			// other).
+			//
+			foreach (var member in host.Members) {
+				var field = member as Field;
+				if (field == null)
+					continue;
+
+				var fi = tt.GetField (field.Name);
+
+				Tuple<FieldSpec, FieldInfo> old;
+
+				// If a previous value was set, nullify it, so that we do
+				// not leak memory
+				if (fields.TryGetValue (field.Name, out old)) {
+					if (old.Item1.MemberType.IsStruct) {
+						//
+						// TODO: Clear fields for structs
+						//
+					} else {
+						try {
+							old.Item2.SetValue (null, null);
+						} catch {
+						}
+					}
+				}
+
+				fields[field.Name] = Tuple.Create (field.Spec, fi);
+			}
+			
+			return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi);
+#endif
+		}
+
+		/// <summary>
+		///   A sentinel value used to indicate that no value was
+		///   was set by the compiled function.   This is used to
+		///   differentiate between a function not returning a
+		///   value and null.
+		/// </summary>
+		internal static class QuitValue { }
+
+		internal Tuple<FieldSpec, FieldInfo> LookupField (string name)
+		{
+			Tuple<FieldSpec, FieldInfo> fi;
+			fields.TryGetValue (name, out fi);
+			return fi;
+		}
+
+		static string Quote (string s)
+		{
+			if (s.IndexOf ('"') != -1)
+				s = s.Replace ("\"", "\\\"");
+			
+			return "\"" + s + "\"";
+		}
+
+		public string GetUsing ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			// TODO:
+			//foreach (object x in ns.using_alias_list)
+			//    sb.AppendFormat ("using {0};\n", x);
+
+			foreach (var ue in source_file.Usings) {
+				sb.AppendFormat ("using {0};", ue.ToString ());
+				sb.Append (Environment.NewLine);
+			}
+
+			return sb.ToString ();
+		}
+
+		internal List<string> GetUsingList ()
+		{
+			var res = new List<string> ();
+
+			foreach (var ue in source_file.Usings) {
+				if (ue.Alias != null || ue.ResolvedExpression == null)
+					continue;
+
+				res.Add (ue.NamespaceExpression.Name);
+			}
+
+			return res;
+		}
+		
+		internal string [] GetVarNames ()
+		{
+			lock (evaluator_lock){
+				return new List<string> (fields.Keys).ToArray ();
+			}
+		}
+		
+		public string GetVars ()
+		{
+			lock (evaluator_lock){
+				StringBuilder sb = new StringBuilder ();
+				
+				foreach (var de in fields){
+					var fi = LookupField (de.Key);
+					object value;
+					try {
+						value = fi.Item2.GetValue (null);
+						if (value is string)
+							value = Quote ((string)value);
+					} catch {
+						value = "<error reading value>";
+					}
+
+					sb.AppendFormat ("{0} {1} = {2}", fi.Item1.MemberType.GetSignatureForError (), de.Key, value);
+					sb.AppendLine ();
+				}
+				
+				return sb.ToString ();
+			}
+		}
+
+		/// <summary>
+		///    Loads the given assembly and exposes the API to the user.
+		/// </summary>
+		public void LoadAssembly (string file)
+		{
+			var loader = new DynamicLoader (importer, ctx);
+			var assembly = loader.LoadAssemblyFile (file, false);
+			if (assembly == null)
+				return;
+
+			lock (evaluator_lock){
+				importer.ImportAssembly (assembly, module.GlobalRootNamespace);
+			}
+		}
+
+		/// <summary>
+		///    Exposes the API of the given assembly to the Evaluator
+		/// </summary>
+		public void ReferenceAssembly (Assembly a)
+		{
+			lock (evaluator_lock){
+				importer.ImportAssembly (a, module.GlobalRootNamespace);
+			}
+		}
+	}
+
+	
+	/// <summary>
+	///   A delegate that can be used to invoke the
+	///   compiled expression or statement.
+	/// </summary>
+	/// <remarks>
+	///   Since the Compile methods will compile
+	///   statements and expressions into the same
+	///   delegate, you can tell if a value was returned
+	///   by checking whether the returned value is of type
+	///   NoValueSet.   
+	/// </remarks>
+	
+	public delegate void CompiledMethod (ref object retvalue);
+
+	/// <summary>
+	///   The default base class for every interaction line
+	/// </summary>
+	/// <remarks>
+	///   The expressions and statements behave as if they were
+	///   a static method of this class.   The InteractiveBase class
+	///   contains a number of useful methods, but can be overwritten
+	///   by setting the InteractiveBaseType property in the Evaluator
+	/// </remarks>
+	public class InteractiveBase {
+		/// <summary>
+		///   Determines where the standard output of methods in this class will go. 
+		/// </summary>
+		public static TextWriter Output = Console.Out;
+
+		/// <summary>
+		///   Determines where the standard error of methods in this class will go. 
+		/// </summary>
+		public static TextWriter Error = Console.Error;
+
+		/// <summary>
+		///   The primary prompt used for interactive use.
+		/// </summary>
+		public static string Prompt             = "csharp> ";
+
+		/// <summary>
+		///   The secondary prompt used for interactive use (used when
+		///   an expression is incomplete).
+		/// </summary>
+		public static string ContinuationPrompt = "      > ";
+
+		/// <summary>
+		///   Used to signal that the user has invoked the  `quit' statement.
+		/// </summary>
+		public static bool QuitRequested;
+
+		public static Evaluator Evaluator;
+		
+		/// <summary>
+		///   Shows all the variables defined so far.
+		/// </summary>
+		static public void ShowVars ()
+		{
+			Output.Write (Evaluator.GetVars ());
+			Output.Flush ();
+		}
+
+		/// <summary>
+		///   Displays the using statements in effect at this point. 
+		/// </summary>
+		static public void ShowUsing ()
+		{
+			Output.Write (Evaluator.GetUsing ());
+			Output.Flush ();
+		}
+	
+		/// <summary>
+		///   Times the execution of the given delegate
+		/// </summary>
+		static public TimeSpan Time (Action a)
+		{
+			DateTime start = DateTime.Now;
+			a ();
+			return DateTime.Now - start;
+		}
+		
+		/// <summary>
+		///   Loads the assemblies from a package
+		/// </summary>
+		/// <remarks>
+		///   Loads the assemblies from a package.   This is equivalent
+		///   to passing the -pkg: command line flag to the C# compiler
+		///   on the command line. 
+		/// </remarks>
+		static public void LoadPackage (string pkg)
+		{
+			if (pkg == null){
+				Error.WriteLine ("Invalid package specified");
+				return;
+			}
+
+			string pkgout = Driver.GetPackageFlags (pkg, null);
+
+			string [] xargs = pkgout.Trim (new Char [] {' ', '\n', '\r', '\t'}).
+				Split (new Char [] { ' ', '\t'});
+
+			foreach (string s in xargs){
+				if (s.StartsWith ("-r:") || s.StartsWith ("/r:") || s.StartsWith ("/reference:")){
+					string lib = s.Substring (s.IndexOf (':')+1);
+
+					Evaluator.LoadAssembly (lib);
+					continue;
+				}
+			}
+		}
+
+		/// <summary>
+		///   Loads the assembly
+		/// </summary>
+		/// <remarks>
+		///   Loads the specified assembly and makes its types
+		///   available to the evaluator.  This is equivalent
+		///   to passing the -pkg: command line flag to the C#
+		///   compiler on the command line.
+		/// </remarks>
+		static public void LoadAssembly (string assembly)
+		{
+			Evaluator.LoadAssembly (assembly);
+		}
+
+		static public void print (object obj)
+		{
+			Output.WriteLine (obj);
+		}
+
+		static public void print (string fmt, params object [] args)
+		{
+			Output.WriteLine (fmt, args);
+		}
+		
+		/// <summary>
+		///   Returns a list of available static methods. 
+		/// </summary>
+		static public string help {
+			get {
+				return "Static methods:\n" +
+					"  Describe (object);       - Describes the object's type\n" +
+					"  LoadPackage (package);   - Loads the given Package (like -pkg:FILE)\n" +
+					"  LoadAssembly (assembly); - Loads the given assembly (like -r:ASSEMBLY)\n" +
+					"  ShowVars ();             - Shows defined local variables.\n" +
+					"  ShowUsing ();            - Show active using declarations.\n" +
+					"  Prompt                   - The prompt used by the C# shell\n" +
+					"  ContinuationPrompt       - The prompt for partial input\n" +
+					"  Time (() => { });        - Times the specified code\n" +
+					"  print (obj);             - Shorthand for Console.WriteLine\n" +
+					"  quit;                    - You'll never believe it - this quits the repl!\n" +
+					"  help;                    - This help text\n";
+			}
+		}
+
+		/// <summary>
+		///   Indicates to the read-eval-print-loop that the interaction should be finished. 
+		/// </summary>
+		static public object quit {
+			get {
+				QuitRequested = true;
+
+				// To avoid print null at the exit
+				return typeof (Evaluator.QuitValue);
+			}
+		}
+
+		/// <summary>
+		///   Same as quit - useful in script scenerios
+		/// </summary>
+		static public void Quit () {
+			QuitRequested = true;
+		}
+
+#if !NET_2_1
+		/// <summary>
+		///   Describes an object or a type.
+		/// </summary>
+		/// <remarks>
+		///   This method will show a textual representation
+		///   of the object's type.  If the object is a
+		///   System.Type it renders the type directly,
+		///   otherwise it renders the type returned by
+		///   invoking GetType on the object.
+		/// </remarks>
+		static public string Describe (object x)
+		{
+			if (x == null)
+				return "<null>";
+
+			var type = x as Type ?? x.GetType ();
+
+			StringWriter sw = new StringWriter ();
+			new Outline (type, sw, true, false, false).OutlineType ();
+			return sw.ToString ();
+		}
+#endif
+	}
+
+	class InteractiveMethod : Method
+	{
+		public InteractiveMethod(TypeDefinition parent, FullNamedExpression returnType, Modifiers mod, ParametersCompiled parameters)
+			: base(parent, returnType, mod, new MemberName("Host"), parameters, null)
+		{
+		}
+
+		public void ChangeToAsync ()
+		{
+			ModFlags |= Modifiers.ASYNC;
+			ModFlags &= ~Modifiers.UNSAFE;
+			type_expr = new TypeExpression(Module.PredefinedTypes.Task.TypeSpec, Location);
+			parameters = ParametersCompiled.EmptyReadOnlyParameters;
+		}
+
+		public override string GetSignatureForError()
+		{
+			return "InteractiveHost";
+		}
+	}
+
+	class HoistedEvaluatorVariable : HoistedVariable
+	{
+		public HoistedEvaluatorVariable (Field field)
+			: base (null, field)
+		{
+		}
+
+		protected override FieldExpr GetFieldExpression (EmitContext ec)
+		{
+			return new FieldExpr (field, field.Location);
+		}
+	}
+
+	/// <summary>
+	///    A class used to assign values if the source expression is not void
+	///
+	///    Used by the interactive shell to allow it to call this code to set
+	///    the return value for an invocation.
+	/// </summary>
+	class OptionalAssign : SimpleAssign {
+		public OptionalAssign (Expression s, Location loc)
+			: base (null, s, loc)
+		{
+		}
+
+		public override Location StartLocation {
+			get {
+				return Location.Null;
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			Expression clone = source.Clone (new CloneContext ());
+
+			clone = clone.Resolve (ec);
+			if (clone == null)
+				return null;
+
+			//
+			// A useful feature for the REPL: if we can resolve the expression
+			// as a type, Describe the type;
+			//
+			if (ec.Module.Evaluator.DescribeTypeExpressions && !(ec.CurrentAnonymousMethod is AsyncInitializer)) {
+				var old_printer = ec.Report.SetPrinter (new SessionReportPrinter ());
+				Expression tclone;
+				try {
+					// Note: clone context cannot be shared otherwise block mapping would leak
+					tclone = source.Clone (new CloneContext ());
+					tclone = tclone.Resolve (ec, ResolveFlags.Type);
+					if (ec.Report.Errors > 0)
+						tclone = null;
+				} finally {
+					ec.Report.SetPrinter (old_printer);
+				}
+
+				if (tclone is TypeExpr) {
+					Arguments args = new Arguments (1);
+					args.Add (new Argument (new TypeOf ((TypeExpr) clone, Location)));
+					return new Invocation (new SimpleName ("Describe", Location), args).Resolve (ec);
+				}
+			}
+
+			// This means its really a statement.
+			if (clone.Type.Kind == MemberKind.Void || clone is DynamicInvocation || clone is Assign) {
+				return clone;
+			}
+
+			source = clone;
+
+			var host = (Method) ec.MemberContext.CurrentMemberDefinition;
+
+			if (host.ParameterInfo.IsEmpty) {
+				eclass = ExprClass.Value;
+				type = InternalType.FakeInternalType;
+				return this;
+			}
+
+			target = new SimpleName (host.ParameterInfo[0].Name, Location);
+
+			return base.DoResolve (ec);
+		}
+
+		public override void EmitStatement(EmitContext ec)
+		{
+			if (target == null) {
+				source.Emit (ec);
+				return;
+			}
+
+			base.EmitStatement(ec);
+		}
+	}
+
+	public class Undo
+	{
+		List<Action> undo_actions;
+
+		public void AddTypeContainer (TypeContainer current_container, TypeDefinition tc)
+		{
+			if (current_container == tc){
+				Console.Error.WriteLine ("Internal error: inserting container into itself");
+				return;
+			}
+
+			if (undo_actions == null)
+				undo_actions = new List<Action> ();
+
+			if (current_container.Containers != null)
+			{
+				var existing = current_container.Containers.FirstOrDefault (l => l.Basename == tc.Basename);
+				if (existing != null) {
+					current_container.RemoveContainer (existing);
+					undo_actions.Add (() => current_container.AddTypeContainer (existing));
+				}
+			}
+
+			undo_actions.Add (() => current_container.RemoveContainer (tc));
+		}
+
+		public void ExecuteUndo ()
+		{
+			if (undo_actions == null)
+				return;
+
+			foreach (var p in undo_actions){
+				p ();
+			}
+
+			undo_actions = null;
+		}
+	}
+
+	static class ListenerProxy
+	{
+		static readonly Dictionary<int, ValueModificationHandler> listeners = new Dictionary<int, ValueModificationHandler> ();
+
+		static int counter;
+
+		public static int Register (ValueModificationHandler listener)
+		{
+			lock (listeners) {
+				var id = counter++;
+				listeners.Add (id, listener);
+				return id;
+			}
+		}
+
+		public static void Unregister (int listenerId)
+		{
+			lock (listeners) {
+				listeners.Remove (listenerId);
+			}
+		}
+
+		public static void ValueChanged (object value, int row, int col, string name, int listenerId)
+		{
+			ValueModificationHandler action;
+			lock (listeners) {
+				if (!listeners.TryGetValue (listenerId, out action))
+					return;
+			}
+
+			action (name, row, col, value);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/expression.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/expression.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/expression.cs	(revision 11807)
@@ -0,0 +1,11921 @@
+//
+// expression.cs: Expression representation for the IL tree.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using SLE = System.Linq.Expressions;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	//
+	// This is an user operator expression, automatically created during
+	// resolve phase
+	//
+	public class UserOperatorCall : Expression {
+		protected readonly Arguments arguments;
+		protected readonly MethodSpec oper;
+		readonly Func<ResolveContext, Expression, Expression> expr_tree;
+
+		public UserOperatorCall (MethodSpec oper, Arguments args, Func<ResolveContext, Expression, Expression> expr_tree, Location loc)
+		{
+			this.oper = oper;
+			this.arguments = args;
+			this.expr_tree = expr_tree;
+
+			type = oper.ReturnType;
+			eclass = ExprClass.Value;
+			this.loc = loc;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return arguments.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (expr_tree != null)
+				return expr_tree (ec, new TypeOfMethod (oper, loc));
+
+			Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
+				new NullLiteral (loc),
+				new TypeOfMethod (oper, loc));
+
+			return CreateExpressionFactoryCall (ec, "Call", args);
+		}
+
+		protected override void CloneTo (CloneContext context, Expression target)
+		{
+			// Nothing to clone
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			//
+			// We are born fully resolved
+			//
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			var call = new CallEmitter ();
+			call.Emit (ec, oper, arguments, loc);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			arguments.FlowAnalysis (fc);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.Call ((MethodInfo) oper.GetMetaInfo (), Arguments.MakeExpression (arguments, ctx));
+#endif
+		}
+	}
+
+	public class ParenthesizedExpression : ShimExpression
+	{
+		public ParenthesizedExpression (Expression expr, Location loc)
+			: base (expr)
+		{
+			this.loc = loc;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			var res = expr.Resolve (ec);
+			var constant = res as Constant;
+			if (constant != null && constant.IsLiteral)
+				return Constant.CreateConstantFromValue (res.Type, constant.GetValue (), expr.Location);
+
+			return res;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			return expr.DoResolveLValue (ec, right_side);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+	
+	//
+	//   Unary implements unary expressions.
+	//
+	public class Unary : Expression
+	{
+		public enum Operator : byte {
+			UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
+			AddressOf,  TOP
+		}
+
+		public readonly Operator Oper;
+		public Expression Expr;
+		ConvCast.Mode enum_conversion;
+
+		public Unary (Operator op, Expression expr, Location loc)
+		{
+			Oper = op;
+			Expr = expr;
+			this.loc = loc;
+		}
+
+		// <summary>
+		//   This routine will attempt to simplify the unary expression when the
+		//   argument is a constant.
+		// </summary>
+		Constant TryReduceConstant (ResolveContext ec, Constant constant)
+		{
+			var e = constant;
+
+			while (e is EmptyConstantCast)
+				e = ((EmptyConstantCast) e).child;
+			
+			if (e is SideEffectConstant) {
+				Constant r = TryReduceConstant (ec, ((SideEffectConstant) e).value);
+				return r == null ? null : new SideEffectConstant (r, e, r.Location);
+			}
+
+			TypeSpec expr_type = e.Type;
+			
+			switch (Oper){
+			case Operator.UnaryPlus:
+				// Unary numeric promotions
+				switch (expr_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+					return new IntConstant (ec.BuiltinTypes, ((ByteConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.SByte:
+					return new IntConstant (ec.BuiltinTypes, ((SByteConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Short:
+					return new IntConstant (ec.BuiltinTypes, ((ShortConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.UShort:
+					return new IntConstant (ec.BuiltinTypes, ((UShortConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Char:
+					return new IntConstant (ec.BuiltinTypes, ((CharConstant) e).Value, e.Location);
+				
+				// Predefined operators
+				case BuiltinTypeSpec.Type.Int:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.Long:
+				case BuiltinTypeSpec.Type.ULong:
+				case BuiltinTypeSpec.Type.Float:
+				case BuiltinTypeSpec.Type.Double:
+				case BuiltinTypeSpec.Type.Decimal:
+					return e;
+				}
+				
+				return null;
+				
+			case Operator.UnaryNegation:
+				// Unary numeric promotions
+				switch (expr_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+					return new IntConstant (ec.BuiltinTypes, -((ByteConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.SByte:
+					return new IntConstant (ec.BuiltinTypes, -((SByteConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Short:
+					return new IntConstant (ec.BuiltinTypes, -((ShortConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.UShort:
+					return new IntConstant (ec.BuiltinTypes, -((UShortConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Char:
+					return new IntConstant (ec.BuiltinTypes, -((CharConstant) e).Value, e.Location);
+
+				// Predefined operators
+				case BuiltinTypeSpec.Type.Int:
+					int ivalue = ((IntConstant) e).Value;
+					if (ivalue == int.MinValue) {
+						if (ec.ConstantCheckState) {
+							ConstantFold.Error_CompileTimeOverflow (ec, loc);
+							return null;
+						}
+						return e;
+					}
+					return new IntConstant (ec.BuiltinTypes, -ivalue, e.Location);
+
+				case BuiltinTypeSpec.Type.Long:
+					long lvalue = ((LongConstant) e).Value;
+					if (lvalue == long.MinValue) {
+						if (ec.ConstantCheckState) {
+							ConstantFold.Error_CompileTimeOverflow (ec, loc);
+							return null;
+						}
+						return e;
+					}
+					return new LongConstant (ec.BuiltinTypes, -lvalue, e.Location);
+
+				case BuiltinTypeSpec.Type.UInt:
+					UIntLiteral uil = constant as UIntLiteral;
+					if (uil != null) {
+						if (uil.Value == int.MaxValue + (uint) 1)
+							return new IntLiteral (ec.BuiltinTypes, int.MinValue, e.Location);
+						return new LongLiteral (ec.BuiltinTypes, -uil.Value, e.Location);
+					}
+					return new LongConstant (ec.BuiltinTypes, -((UIntConstant) e).Value, e.Location);
+
+
+				case BuiltinTypeSpec.Type.ULong:
+					ULongLiteral ull = constant as ULongLiteral;
+					if (ull != null && ull.Value == 9223372036854775808)
+						return new LongLiteral (ec.BuiltinTypes, long.MinValue, e.Location);
+					return null;
+
+				case BuiltinTypeSpec.Type.Float:
+					FloatLiteral fl = constant as FloatLiteral;
+					// For better error reporting
+					if (fl != null)
+						return new FloatLiteral (ec.BuiltinTypes, -fl.Value, e.Location);
+
+					return new FloatConstant (ec.BuiltinTypes, -((FloatConstant) e).Value, e.Location);
+
+				case BuiltinTypeSpec.Type.Double:
+					DoubleLiteral dl = constant as DoubleLiteral;
+					// For better error reporting
+					if (dl != null)
+						return new DoubleLiteral (ec.BuiltinTypes, -dl.Value, e.Location);
+
+					return new DoubleConstant (ec.BuiltinTypes, -((DoubleConstant) e).Value, e.Location);
+
+				case BuiltinTypeSpec.Type.Decimal:
+					return new DecimalConstant (ec.BuiltinTypes, -((DecimalConstant) e).Value, e.Location);
+				}
+
+				return null;
+				
+			case Operator.LogicalNot:
+				if (expr_type.BuiltinType != BuiltinTypeSpec.Type.Bool)
+					return null;
+				
+				bool b = (bool)e.GetValue ();
+				return new BoolConstant (ec.BuiltinTypes, !b, e.Location);
+				
+			case Operator.OnesComplement:
+				// Unary numeric promotions
+				switch (expr_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+					return new IntConstant (ec.BuiltinTypes, ~((ByteConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.SByte:
+					return new IntConstant (ec.BuiltinTypes, ~((SByteConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Short:
+					return new IntConstant (ec.BuiltinTypes, ~((ShortConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.UShort:
+					return new IntConstant (ec.BuiltinTypes, ~((UShortConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Char:
+					return new IntConstant (ec.BuiltinTypes, ~((CharConstant) e).Value, e.Location);
+				
+				// Predefined operators
+				case BuiltinTypeSpec.Type.Int:
+					return new IntConstant (ec.BuiltinTypes, ~((IntConstant)e).Value, e.Location);
+				case BuiltinTypeSpec.Type.UInt:
+					return new UIntConstant (ec.BuiltinTypes, ~((UIntConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.Long:
+					return new LongConstant (ec.BuiltinTypes, ~((LongConstant) e).Value, e.Location);
+				case BuiltinTypeSpec.Type.ULong:
+					return new ULongConstant (ec.BuiltinTypes, ~((ULongConstant) e).Value, e.Location);
+				}
+				if (e is EnumConstant) {
+					var res = TryReduceConstant (ec, ((EnumConstant)e).Child);
+					if (res != null) {
+						//
+						// Numeric promotion upgraded types to int but for enum constant
+						// original underlying constant type is needed
+						//
+						if (res.Type.BuiltinType == BuiltinTypeSpec.Type.Int) {
+							int v = ((IntConstant) res).Value;
+							switch (((EnumConstant) e).Child.Type.BuiltinType) {
+								case BuiltinTypeSpec.Type.UShort:
+								res = new UShortConstant (ec.BuiltinTypes, (ushort) v, e.Location);
+								break;
+								case BuiltinTypeSpec.Type.Short:
+								res = new ShortConstant (ec.BuiltinTypes, (short) v, e.Location);
+								break;
+								case BuiltinTypeSpec.Type.Byte:
+								res = new ByteConstant (ec.BuiltinTypes, (byte) v, e.Location);
+								break;
+								case BuiltinTypeSpec.Type.SByte:
+								res = new SByteConstant (ec.BuiltinTypes, (sbyte) v, e.Location);
+								break;
+							}
+						}
+
+						res = new EnumConstant (res, expr_type);
+					}
+					return res;
+				}
+				return null;
+			}
+			throw new Exception ("Can not constant fold: " + Oper.ToString());
+		}
+		
+		protected virtual Expression ResolveOperator (ResolveContext ec, Expression expr)
+		{
+			eclass = ExprClass.Value;
+
+			TypeSpec expr_type = expr.Type;
+			Expression best_expr;
+
+			TypeSpec[] predefined = ec.BuiltinTypes.OperatorsUnary [(int) Oper];
+
+			//
+			// Primitive types first
+			//
+			if (BuiltinTypeSpec.IsPrimitiveType (expr_type)) {
+				best_expr = ResolvePrimitivePredefinedType (ec, expr, predefined);
+				if (best_expr == null)
+					return null;
+
+				type = best_expr.Type;
+				Expr = best_expr;
+				return this;
+			}
+
+			//
+			// E operator ~(E x);
+			//
+			if (Oper == Operator.OnesComplement && expr_type.IsEnum)
+				return ResolveEnumOperator (ec, expr, predefined);
+
+			return ResolveUserType (ec, expr, predefined);
+		}
+
+		protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
+		{
+			TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
+			Expression best_expr = ResolvePrimitivePredefinedType (ec, EmptyCast.Create (expr, underlying_type), predefined);
+			if (best_expr == null)
+				return null;
+
+			Expr = best_expr;
+			enum_conversion = Binary.GetEnumResultCast (underlying_type);
+			type = expr.Type;
+			return EmptyCast.Create (this, type);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return Expr.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return CreateExpressionTree (ec, null);
+		}
+
+		Expression CreateExpressionTree (ResolveContext ec, Expression user_op)
+		{
+			string method_name;
+			switch (Oper) {
+			case Operator.AddressOf:
+				Error_PointerInsideExpressionTree (ec);
+				return null;
+			case Operator.UnaryNegation:
+				if (ec.HasSet (ResolveContext.Options.CheckedScope) && user_op == null && !IsFloat (type))
+					method_name = "NegateChecked";
+				else
+					method_name = "Negate";
+				break;
+			case Operator.OnesComplement:
+			case Operator.LogicalNot:
+				method_name = "Not";
+				break;
+			case Operator.UnaryPlus:
+				method_name = "UnaryPlus";
+				break;
+			default:
+				throw new InternalErrorException ("Unknown unary operator " + Oper.ToString ());
+			}
+
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (Expr.CreateExpressionTree (ec)));
+			if (user_op != null)
+				args.Add (new Argument (user_op));
+
+			return CreateExpressionFactoryCall (ec, method_name, args);
+		}
+
+		public static TypeSpec[][] CreatePredefinedOperatorsTable (BuiltinTypes types)
+		{
+			var predefined_operators = new TypeSpec[(int) Operator.TOP][];
+
+			//
+			// 7.6.1 Unary plus operator
+			//
+			predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
+				types.Int, types.UInt,
+				types.Long, types.ULong,
+				types.Float, types.Double,
+				types.Decimal
+			};
+
+			//
+			// 7.6.2 Unary minus operator
+			//
+			predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
+				types.Int,  types.Long,
+				types.Float, types.Double,
+				types.Decimal
+			};
+
+			//
+			// 7.6.3 Logical negation operator
+			//
+			predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
+				types.Bool
+			};
+
+			//
+			// 7.6.4 Bitwise complement operator
+			//
+			predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
+				types.Int, types.UInt,
+				types.Long, types.ULong
+			};
+
+			return predefined_operators;
+		}
+
+		//
+		// Unary numeric promotions
+		//
+		static Expression DoNumericPromotion (ResolveContext rc, Operator op, Expression expr)
+		{
+			TypeSpec expr_type = expr.Type;
+			if (op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) {
+				switch (expr_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Byte:
+				case BuiltinTypeSpec.Type.SByte:
+				case BuiltinTypeSpec.Type.Short:
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.Char:
+					return Convert.ImplicitNumericConversion (expr, rc.BuiltinTypes.Int);
+				}
+			}
+
+			if (op == Operator.UnaryNegation && expr_type.BuiltinType == BuiltinTypeSpec.Type.UInt)
+				return Convert.ImplicitNumericConversion (expr, rc.BuiltinTypes.Long);
+
+			return expr;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (Oper == Operator.AddressOf) {
+				return ResolveAddressOf (ec);
+			}
+
+			Expr = Expr.Resolve (ec);
+			if (Expr == null)
+				return null;
+
+			if (Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (Expr));
+				return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
+			}
+
+			if (Expr.Type.IsNullableType)
+				return new Nullable.LiftedUnaryOperator (Oper, Expr, loc).Resolve (ec);
+
+			//
+			// Attempt to use a constant folding operation.
+			//
+			Constant cexpr = Expr as Constant;
+			if (cexpr != null) {
+				cexpr = TryReduceConstant (ec, cexpr);
+				if (cexpr != null)
+					return cexpr;
+			}
+
+			Expression expr = ResolveOperator (ec, Expr);
+			if (expr == null)
+				Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
+			
+			//
+			// Reduce unary operator on predefined types
+			//
+			if (expr == this && Oper == Operator.UnaryPlus)
+				return Expr;
+
+			return expr;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right)
+		{
+			return null;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			EmitOperator (ec, type);
+		}
+
+		protected void EmitOperator (EmitContext ec, TypeSpec type)
+		{
+			switch (Oper) {
+			case Operator.UnaryPlus:
+				Expr.Emit (ec);
+				break;
+				
+			case Operator.UnaryNegation:
+				if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
+					if (ec.HasSet (BuilderContext.Options.AsyncBody) && Expr.ContainsEmitWithAwait ())
+						Expr = Expr.EmitToField (ec);
+
+					ec.EmitInt (0);
+					if (type.BuiltinType == BuiltinTypeSpec.Type.Long)
+						ec.Emit (OpCodes.Conv_U8);
+					Expr.Emit (ec);
+					ec.Emit (OpCodes.Sub_Ovf);
+				} else {
+					Expr.Emit (ec);
+					ec.Emit (OpCodes.Neg);
+				}
+				
+				break;
+				
+			case Operator.LogicalNot:
+				Expr.Emit (ec);
+				ec.EmitInt (0);
+				ec.Emit (OpCodes.Ceq);
+				break;
+				
+			case Operator.OnesComplement:
+				Expr.Emit (ec);
+				ec.Emit (OpCodes.Not);
+				break;
+				
+			case Operator.AddressOf:
+				((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
+				break;
+				
+			default:
+				throw new Exception ("This should not happen: Operator = "
+						     + Oper.ToString ());
+			}
+
+			//
+			// Same trick as in Binary expression
+			//
+			if (enum_conversion != 0) {
+				using (ec.With (BuilderContext.Options.CheckedScope, false)) {
+					ConvCast.Emit (ec, enum_conversion);
+				}
+			}
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			if (Oper == Operator.LogicalNot)
+				Expr.EmitBranchable (ec, target, !on_true);
+			else
+				base.EmitBranchable (ec, target, on_true);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			Expr.EmitSideEffect (ec);
+		}
+
+		public static void Error_Ambiguous (ResolveContext rc, string oper, TypeSpec type, Location loc)
+		{
+			rc.Report.Error (35, loc, "Operator `{0}' is ambiguous on an operand of type `{1}'",
+				oper, type.GetSignatureForError ());
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			FlowAnalysis (fc, false);
+		}
+
+		public override void FlowAnalysisConditional (FlowAnalysisContext fc)
+		{
+			FlowAnalysis (fc, true);
+		}
+
+		void FlowAnalysis (FlowAnalysisContext fc, bool conditional)
+		{
+			if (Oper == Operator.AddressOf) {
+				var vr = Expr as VariableReference;
+				if (vr != null && vr.VariableInfo != null)
+					fc.SetVariableAssigned (vr.VariableInfo);
+
+				return;
+			}
+
+			if (Oper == Operator.LogicalNot && conditional) {
+				Expr.FlowAnalysisConditional (fc);
+
+				var temp = fc.DefiniteAssignmentOnTrue;
+				fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse;
+				fc.DefiniteAssignmentOnFalse = temp;
+			} else {
+				Expr.FlowAnalysis (fc);
+			}
+		}
+
+		//
+		// Converts operator to System.Linq.Expressions.ExpressionType enum name
+		//
+		string GetOperatorExpressionTypeName ()
+		{
+			switch (Oper) {
+			case Operator.OnesComplement:
+				return "OnesComplement";
+			case Operator.LogicalNot:
+				return "Not";
+			case Operator.UnaryNegation:
+				return "Negate";
+			case Operator.UnaryPlus:
+				return "UnaryPlus";
+			default:
+				throw new NotImplementedException ("Unknown express type operator " + Oper.ToString ());
+			}
+		}
+
+		static bool IsFloat (TypeSpec t)
+		{
+			return t.BuiltinType == BuiltinTypeSpec.Type.Double || t.BuiltinType == BuiltinTypeSpec.Type.Float;
+		}
+
+		//
+		// Returns a stringified representation of the Operator
+		//
+		public static string OperName (Operator oper)
+		{
+			switch (oper) {
+			case Operator.UnaryPlus:
+				return "+";
+			case Operator.UnaryNegation:
+				return "-";
+			case Operator.LogicalNot:
+				return "!";
+			case Operator.OnesComplement:
+				return "~";
+			case Operator.AddressOf:
+				return "&";
+			}
+
+			throw new NotImplementedException (oper.ToString ());
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			var expr = Expr.MakeExpression (ctx);
+			bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
+
+			switch (Oper) {
+			case Operator.UnaryNegation:
+				return is_checked ? SLE.Expression.NegateChecked (expr) : SLE.Expression.Negate (expr);
+			case Operator.LogicalNot:
+				return SLE.Expression.Not (expr);
+#if NET_4_0 || MOBILE_DYNAMIC
+			case Operator.OnesComplement:
+				return SLE.Expression.OnesComplement (expr);
+#endif
+			default:
+				throw new NotImplementedException (Oper.ToString ());
+			}
+		}
+
+		Expression ResolveAddressOf (ResolveContext ec)
+		{
+			if (!ec.IsUnsafe)
+				UnsafeError (ec, loc);
+
+			Expr = Expr.DoResolveLValue (ec, EmptyExpression.UnaryAddress);
+			if (Expr == null || Expr.eclass != ExprClass.Variable) {
+				ec.Report.Error (211, loc, "Cannot take the address of the given expression");
+				return null;
+			}
+
+			if (!TypeManager.VerifyUnmanaged (ec.Module, Expr.Type, loc)) {
+				return null;
+			}
+
+			IVariableReference vr = Expr as IVariableReference;
+			bool is_fixed;
+			if (vr != null) {
+				is_fixed = vr.IsFixed;
+				vr.SetHasAddressTaken ();
+
+				if (vr.IsHoisted) {
+					AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, vr, loc);
+				}
+			} else {
+				IFixedExpression fe = Expr as IFixedExpression;
+				is_fixed = fe != null && fe.IsFixed;
+			}
+
+			if (!is_fixed && !ec.HasSet (ResolveContext.Options.FixedInitializerScope)) {
+				ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
+			}
+
+			type = PointerContainer.MakeType (ec.Module, Expr.Type);
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		Expression ResolvePrimitivePredefinedType (ResolveContext rc, Expression expr, TypeSpec[] predefined)
+		{
+			expr = DoNumericPromotion (rc, Oper, expr);
+			TypeSpec expr_type = expr.Type;
+			foreach (TypeSpec t in predefined) {
+				if (t == expr_type)
+					return expr;
+			}
+			return null;
+		}
+
+		//
+		// Perform user-operator overload resolution
+		//
+		protected virtual Expression ResolveUserOperator (ResolveContext ec, Expression expr)
+		{
+			CSharp.Operator.OpType op_type;
+			switch (Oper) {
+			case Operator.LogicalNot:
+				op_type = CSharp.Operator.OpType.LogicalNot; break;
+			case Operator.OnesComplement:
+				op_type = CSharp.Operator.OpType.OnesComplement; break;
+			case Operator.UnaryNegation:
+				op_type = CSharp.Operator.OpType.UnaryNegation; break;
+			case Operator.UnaryPlus:
+				op_type = CSharp.Operator.OpType.UnaryPlus; break;
+			default:
+				throw new InternalErrorException (Oper.ToString ());
+			}
+
+			var methods = MemberCache.GetUserOperator (expr.Type, op_type, false);
+			if (methods == null)
+				return null;
+
+			Arguments args = new Arguments (1);
+			args.Add (new Argument (expr));
+
+			var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
+			var oper = res.ResolveOperator (ec, ref args);
+
+			if (oper == null)
+				return null;
+
+			Expr = args [0].Expr;
+			return new UserOperatorCall (oper, args, CreateExpressionTree, expr.Location);
+		}
+
+		//
+		// Unary user type overload resolution
+		//
+		Expression ResolveUserType (ResolveContext ec, Expression expr, TypeSpec[] predefined)
+		{
+			Expression best_expr = ResolveUserOperator (ec, expr);
+			if (best_expr != null)
+				return best_expr;
+
+			foreach (TypeSpec t in predefined) {
+				Expression oper_expr = Convert.ImplicitUserConversion (ec, expr, t, expr.Location);
+				if (oper_expr == null)
+					continue;
+
+				if (oper_expr == ErrorExpression.Instance)
+					return oper_expr;
+
+				//
+				// decimal type is predefined but has user-operators
+				//
+				if (oper_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal)
+					oper_expr = ResolveUserType (ec, oper_expr, predefined);
+				else
+					oper_expr = ResolvePrimitivePredefinedType (ec, oper_expr, predefined);
+
+				if (oper_expr == null)
+					continue;
+
+				if (best_expr == null) {
+					best_expr = oper_expr;
+					continue;
+				}
+
+				int result = OverloadResolver.BetterTypeConversion (ec, best_expr.Type, t);
+				if (result == 0) {
+					if ((oper_expr is UserOperatorCall || oper_expr is UserCast) && (best_expr is UserOperatorCall || best_expr is UserCast)) {
+						Error_Ambiguous (ec, OperName (Oper), expr.Type, loc);
+					} else {
+						Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), expr.Type);
+					}
+
+					break;
+				}
+
+				if (result == 2)
+					best_expr = oper_expr;
+			}
+			
+			if (best_expr == null)
+				return null;
+			
+			//
+			// HACK: Decimal user-operator is included in standard operators
+			//
+			if (best_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal)
+				return best_expr;
+
+			Expr = best_expr;
+			type = best_expr.Type;
+			return this;			
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Unary target = (Unary) t;
+
+			target.Expr = Expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+	}
+
+	//
+	// Unary operators are turned into Indirection expressions
+	// after semantic analysis (this is so we can take the address
+	// of an indirection).
+	//
+	public class Indirection : Expression, IMemoryLocation, IAssignMethod, IFixedExpression {
+		Expression expr;
+		LocalTemporary temporary;
+		bool prepared;
+		
+		public Indirection (Expression expr, Location l)
+		{
+			this.expr = expr;
+			loc = l;
+		}
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		public bool IsFixed {
+			get { return true; }
+		}
+
+		public override Location StartLocation {
+			get {
+				return expr.StartLocation;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Indirection target = (Indirection) t;
+			target.expr = expr.Clone (clonectx);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Error_PointerInsideExpressionTree (ec);
+			return null;
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			if (!prepared)
+				expr.Emit (ec);
+			
+			ec.EmitLoadFromPtr (Type);
+		}
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			Emit (ec);
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				temporary = new LocalTemporary (expr.Type);
+				temporary.Store (ec);
+			}
+		}
+		
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			prepared = isCompound;
+			
+			expr.Emit (ec);
+
+			if (isCompound)
+				ec.Emit (OpCodes.Dup);
+			
+			source.Emit (ec);
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				temporary = new LocalTemporary (source.Type);
+				temporary.Store (ec);
+			}
+			
+			ec.EmitStoreFromPtr (type);
+			
+			if (temporary != null) {
+				temporary.Emit (ec);
+				temporary.Release (ec);
+			}
+		}
+		
+		public void AddressOf (EmitContext ec, AddressOp Mode)
+		{
+			expr.Emit (ec);
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			return DoResolve (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			expr = expr.Resolve (ec);
+			if (expr == null)
+				return null;
+
+			if (!ec.IsUnsafe)
+				UnsafeError (ec, loc);
+
+			var pc = expr.Type as PointerContainer;
+
+			if (pc == null) {
+				ec.Report.Error (193, loc, "The * or -> operator must be applied to a pointer");
+				return null;
+			}
+
+			type = pc.Element;
+
+			if (type.Kind == MemberKind.Void) {
+				Error_VoidPointerOperation (ec);
+				return null;
+			}
+
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+	
+	/// <summary>
+	///   Unary Mutator expressions (pre and post ++ and --)
+	/// </summary>
+	///
+	/// <remarks>
+	///   UnaryMutator implements ++ and -- expressions.   It derives from
+	///   ExpressionStatement becuase the pre/post increment/decrement
+	///   operators can be used in a statement context.
+	///
+	/// FIXME: Idea, we could split this up in two classes, one simpler
+	/// for the common case, and one with the extra fields for more complex
+	/// classes (indexers require temporary access;  overloaded require method)
+	///
+	/// </remarks>
+	public class UnaryMutator : ExpressionStatement
+	{
+		class DynamicPostMutator : Expression, IAssignMethod
+		{
+			LocalTemporary temp;
+			Expression expr;
+
+			public DynamicPostMutator (Expression expr)
+			{
+				this.expr = expr;
+				this.type = expr.Type;
+				this.loc = expr.Location;
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				throw new NotImplementedException ("ET");
+			}
+
+			protected override Expression DoResolve (ResolveContext rc)
+			{
+				eclass = expr.eclass;
+				return this;
+			}
+
+			public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+			{
+				expr.DoResolveLValue (ec, right_side);
+				return DoResolve (ec);
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				temp.Emit (ec);
+			}
+
+			public void Emit (EmitContext ec, bool leave_copy)
+			{
+				throw new NotImplementedException ();
+			}
+
+			//
+			// Emits target assignment using unmodified source value
+			//
+			public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+			{
+				//
+				// Allocate temporary variable to keep original value before it's modified
+				//
+				temp = new LocalTemporary (type);
+				expr.Emit (ec);
+				temp.Store (ec);
+
+				((IAssignMethod) expr).EmitAssign (ec, source, false, isCompound);
+
+				if (leave_copy)
+					Emit (ec);
+
+				temp.Release (ec);
+				temp = null;
+			}
+		}
+
+		[Flags]
+		public enum Mode : byte {
+			IsIncrement    = 0,
+			IsDecrement    = 1,
+			IsPre          = 0,
+			IsPost         = 2,
+			
+			PreIncrement   = 0,
+			PreDecrement   = IsDecrement,
+			PostIncrement  = IsPost,
+			PostDecrement  = IsPost | IsDecrement
+		}
+
+		Mode mode;
+		bool is_expr, recurse;
+
+		protected Expression expr;
+
+		// Holds the real operation
+		Expression operation;
+		
+		public UnaryMutator (Mode m, Expression e, Location loc)
+		{
+			mode = m;
+			this.loc = loc;
+			expr = e;
+		}
+
+		public Mode UnaryMutatorMode {
+			get {
+				return mode;
+			}
+		}
+		
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		public override Location StartLocation {
+			get {
+				return (mode & Mode.IsPost) != 0 ? expr.Location : loc;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return expr.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return new SimpleAssign (this, this).CreateExpressionTree (ec);
+		}
+
+		public static TypeSpec[] CreatePredefinedOperatorsTable (BuiltinTypes types)
+		{
+			//
+			// Predefined ++ and -- operators exist for the following types: 
+			// sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal
+			//
+			return new TypeSpec[] {
+				types.Int,
+				types.Long,
+
+				types.SByte,
+				types.Byte,
+				types.Short,
+				types.UInt,
+				types.ULong,
+				types.Char,
+				types.Float,
+				types.Double,
+				types.Decimal
+			};
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			expr = expr.Resolve (ec);
+			
+			if (expr == null || expr.Type == InternalType.ErrorType)
+				return null;
+
+			if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				//
+				// Handle postfix unary operators using local
+				// temporary variable
+				//
+				if ((mode & Mode.IsPost) != 0)
+					expr = new DynamicPostMutator (expr);
+
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (expr));
+				return new SimpleAssign (expr, new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc)).Resolve (ec);
+			}
+
+			if (expr.Type.IsNullableType)
+				return new Nullable.LiftedUnaryMutator (mode, expr, loc).Resolve (ec);
+
+			return DoResolveOperation (ec);
+		}
+
+		protected Expression DoResolveOperation (ResolveContext ec)
+		{
+			eclass = ExprClass.Value;
+			type = expr.Type;
+
+			if (expr is RuntimeValueExpression) {
+				operation = expr;
+			} else {
+				// Use itself at the top of the stack
+				operation = new EmptyExpression (type);
+			}
+
+			//
+			// The operand of the prefix/postfix increment decrement operators
+			// should be an expression that is classified as a variable,
+			// a property access or an indexer access
+			//
+			// TODO: Move to parser, expr is ATypeNameExpression
+			if (expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.IndexerAccess || expr.eclass == ExprClass.PropertyAccess) {
+				expr = expr.ResolveLValue (ec, expr);
+			} else {
+				ec.Report.Error (1059, loc, "The operand of an increment or decrement operator must be a variable, property or indexer");
+			}
+
+			//
+			// Step 1: Try to find a user operator, it has priority over predefined ones
+			//
+			var user_op = IsDecrement ? Operator.OpType.Decrement : Operator.OpType.Increment;
+			var methods = MemberCache.GetUserOperator (type, user_op, false);
+
+			if (methods != null) {
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (expr));
+
+				var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
+				var method = res.ResolveOperator (ec, ref args);
+				if (method == null)
+					return null;
+
+				args[0].Expr = operation;
+				operation = new UserOperatorCall (method, args, null, loc);
+				operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
+				return this;
+			}
+
+			//
+			// Step 2: Try predefined types
+			//
+
+			Expression source = null;
+			bool primitive_type;
+
+			//
+			// Predefined without user conversion first for speed-up
+			//
+			// Predefined ++ and -- operators exist for the following types: 
+			// sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal
+			//
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.Char:
+			case BuiltinTypeSpec.Type.Float:
+			case BuiltinTypeSpec.Type.Double:
+			case BuiltinTypeSpec.Type.Decimal:
+				source = operation;
+				primitive_type = true;
+				break;
+			default:
+				primitive_type = false;
+
+				// ++/-- on pointer variables of all types except void*
+				if (type.IsPointer) {
+					if (((PointerContainer) type).Element.Kind == MemberKind.Void) {
+						Error_VoidPointerOperation (ec);
+						return null;
+					}
+
+					source = operation;
+				} else {
+					Expression best_source = null;
+					foreach (var t in ec.BuiltinTypes.OperatorsUnaryMutator) {
+						source = Convert.ImplicitUserConversion (ec, operation, t, loc);
+
+						// LAMESPEC: It should error on ambiguous operators but that would make us incompatible
+						if (source == null)
+							continue;
+
+						if (best_source == null) {
+							best_source = source;
+							continue;
+						}
+
+						var better = OverloadResolver.BetterTypeConversion (ec, best_source.Type, source.Type);
+						if (better == 1)
+							continue;
+
+						if (better == 2) {
+							best_source = source;
+							continue;
+						}
+
+						Unary.Error_Ambiguous (ec, OperName (mode), type, loc);
+						break;
+					}
+
+					source = best_source;
+				}
+
+				// ++/-- on enum types
+				if (source == null && type.IsEnum)
+					source = operation;
+
+				if (source == null) {
+					expr.Error_OperatorCannotBeApplied (ec, loc, Operator.GetName (user_op), type);
+					return null;
+				}
+
+				break;
+			}
+
+			var one = new IntConstant (ec.BuiltinTypes, 1, loc);
+			var op = IsDecrement ? Binary.Operator.Subtraction : Binary.Operator.Addition;
+			operation = new Binary (op, source, one);
+			operation = operation.Resolve (ec);
+			if (operation == null)
+				throw new NotImplementedException ("should not be reached");
+
+			if (operation.Type != type) {
+				if (primitive_type)
+					operation = Convert.ExplicitNumericConversion (ec, operation, type);
+				else
+					operation = Convert.ImplicitConversionRequired (ec, operation, type, loc);
+			}
+
+			return this;
+		}
+
+		void EmitCode (EmitContext ec, bool is_expr)
+		{
+			recurse = true;
+			this.is_expr = is_expr;
+			((IAssignMethod) expr).EmitAssign (ec, this, is_expr && (mode == Mode.PreIncrement || mode == Mode.PreDecrement), true);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// We use recurse to allow ourselfs to be the source
+			// of an assignment. This little hack prevents us from
+			// having to allocate another expression
+			//
+			if (recurse) {
+				((IAssignMethod) expr).Emit (ec, is_expr && (mode == Mode.PostIncrement || mode == Mode.PostDecrement));
+
+				EmitOperation (ec);
+
+				recurse = false;
+				return;
+			}
+
+			EmitCode (ec, true);
+		}
+
+		protected virtual void EmitOperation (EmitContext ec)
+		{
+			operation.Emit (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			EmitCode (ec, false);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+		}
+
+		//
+		// Converts operator to System.Linq.Expressions.ExpressionType enum name
+		//
+		string GetOperatorExpressionTypeName ()
+		{
+			return IsDecrement ? "Decrement" : "Increment";
+		}
+
+		bool IsDecrement {
+			get { return (mode & Mode.IsDecrement) != 0; }
+		}
+
+
+#if NET_4_0 || MOBILE_DYNAMIC
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			var target = ((RuntimeValueExpression) expr).MetaObject.Expression;
+			var source = SLE.Expression.Convert (operation.MakeExpression (ctx), target.Type);
+			return SLE.Expression.Assign (target, source);
+		}
+#endif
+
+		public static string OperName (Mode oper)
+		{
+			return (oper & Mode.IsDecrement) != 0 ? "--" : "++";
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			UnaryMutator target = (UnaryMutator) t;
+
+			target.expr = expr.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+	}
+
+	//
+	// Base class for the `is' and `as' operators
+	//
+	public abstract class Probe : Expression
+	{
+		public Expression ProbeType;
+		protected Expression expr;
+		protected TypeSpec probe_type_expr;
+		
+		protected Probe (Expression expr, Expression probe_type, Location l)
+		{
+			ProbeType = probe_type;
+			loc = l;
+			this.expr = expr;
+		}
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return expr.ContainsEmitWithAwait ();
+		}
+
+		protected Expression ResolveCommon (ResolveContext rc)
+		{
+			expr = expr.Resolve (rc);
+			if (expr == null)
+				return null;
+
+			ResolveProbeType (rc);
+			if (probe_type_expr == null)
+				return this;
+
+			if (probe_type_expr.IsStatic) {
+				rc.Report.Error (7023, loc, "The second operand of `is' or `as' operator cannot be static type `{0}'",
+					probe_type_expr.GetSignatureForError ());
+				return null;
+			}
+			
+			if (expr.Type.IsPointer || probe_type_expr.IsPointer) {
+				rc.Report.Error (244, loc, "The `{0}' operator cannot be applied to an operand of pointer type",
+					OperatorName);
+				return null;
+			}
+
+			if (expr.Type == InternalType.AnonymousMethod || expr.Type == InternalType.MethodGroup) {
+				rc.Report.Error (837, loc, "The `{0}' operator cannot be applied to a lambda expression, anonymous method, or method group",
+					OperatorName);
+				return null;
+			}
+
+			return this;
+		}
+
+		protected virtual void ResolveProbeType (ResolveContext rc)
+		{
+			probe_type_expr = ProbeType.ResolveAsType (rc);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			expr.EmitSideEffect (ec);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+		}
+
+		protected abstract string OperatorName { get; }
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Probe target = (Probe) t;
+
+			target.expr = expr.Clone (clonectx);
+			target.ProbeType = ProbeType.Clone (clonectx);
+		}
+
+	}
+
+	/// <summary>
+	///   Implementation of the `is' operator.
+	/// </summary>
+	public class Is : Probe
+	{
+		Nullable.Unwrap expr_unwrap;
+		MethodSpec number_mg;
+		Arguments number_args;
+
+		public Is (Expression expr, Expression probe_type, Location l)
+			: base (expr, probe_type, l)
+		{
+		}
+
+		protected override string OperatorName {
+			get { return "is"; }
+		}
+
+		public LocalVariable Variable { get; set; }
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (Variable != null)
+				throw new NotSupportedException ();
+
+			Arguments args = Arguments.CreateForExpressionTree (ec, null,
+				expr.CreateExpressionTree (ec),
+				new TypeOf (probe_type_expr, loc));
+
+			return CreateExpressionFactoryCall (ec, "TypeIs", args);
+		}
+
+		Expression CreateConstantResult (ResolveContext rc, bool result)
+		{
+			if (result)
+				rc.Report.Warning (183, 1, loc, "The given expression is always of the provided (`{0}') type",
+					probe_type_expr.GetSignatureForError ());
+			else
+				rc.Report.Warning (184, 1, loc, "The given expression is never of the provided (`{0}') type",
+					probe_type_expr.GetSignatureForError ());
+
+			var c = new BoolConstant (rc.BuiltinTypes, result, loc);
+			return expr.IsSideEffectFree ?
+				ReducedExpression.Create (c, this) :
+				new SideEffectConstant (c, this, loc);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (probe_type_expr == null) {
+				EmitConstantMatch (ec);
+				return;
+			}
+
+			EmitLoad (ec);
+
+			if (expr_unwrap == null) {
+				ec.EmitNull ();
+				ec.Emit (OpCodes.Cgt_Un);
+			}
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			if (probe_type_expr == null) {
+				EmitConstantMatch (ec);
+			} else {
+				EmitLoad (ec);
+			}
+
+			ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
+		}
+
+		void EmitConstantMatch (EmitContext ec)
+		{
+			var no_match = ec.DefineLabel ();
+			var end = ec.DefineLabel ();
+
+			if (expr_unwrap != null) {
+				expr_unwrap.EmitCheck (ec);
+
+				if (ProbeType.IsNull) {
+					ec.EmitInt (0);
+					ec.Emit (OpCodes.Ceq);
+					return;
+				}
+
+				ec.Emit (OpCodes.Brfalse_S, no_match);
+				expr_unwrap.Emit (ec);
+				ProbeType.Emit (ec);
+				ec.Emit (OpCodes.Ceq);
+				ec.Emit (OpCodes.Br_S, end);
+				ec.MarkLabel (no_match);
+				ec.EmitInt (0);
+				ec.MarkLabel (end);
+				return;
+			}
+
+			if (number_args != null && number_args.Count == 3) {
+				var ce = new CallEmitter ();
+				ce.Emit (ec, number_mg, number_args, loc);
+				return;
+			}
+
+			Expr.Emit (ec);
+			ec.Emit (OpCodes.Isinst, ProbeType.Type);
+			ec.Emit (OpCodes.Dup);
+			ec.Emit (OpCodes.Brfalse, no_match);
+
+			if (number_mg != null) {
+				var ce = new CallEmitter ();
+				ce.Emit (ec, number_mg, number_args, loc);
+			} else {
+				ProbeType.Emit (ec);
+				ec.Emit (OpCodes.Ceq);
+			}
+			ec.Emit (OpCodes.Br_S, end);
+			ec.MarkLabel (no_match);
+
+			ec.Emit (OpCodes.Pop);
+			ec.EmitInt (0);
+			ec.MarkLabel (end);
+		}
+
+		void EmitLoad (EmitContext ec)
+		{
+			Label no_value_label = new Label ();
+
+			if (expr_unwrap != null) {
+				expr_unwrap.EmitCheck (ec);
+
+				if (Variable == null)
+					return;
+
+				ec.Emit (OpCodes.Dup);
+				no_value_label = ec.DefineLabel ();
+				ec.Emit (OpCodes.Brfalse_S, no_value_label);
+				expr_unwrap.Emit (ec);
+			} else {
+				expr.Emit (ec);
+
+				// Only to make verifier happy
+				if (probe_type_expr.IsGenericParameter && TypeSpec.IsValueType (expr.Type))
+					ec.Emit (OpCodes.Box, expr.Type);
+
+				ec.Emit (OpCodes.Isinst, probe_type_expr);
+			}
+
+			if (Variable != null) {
+				bool value_on_stack;
+				if (probe_type_expr.IsGenericParameter || probe_type_expr.IsNullableType) {
+					ec.Emit (OpCodes.Dup);
+					ec.Emit (OpCodes.Unbox_Any, probe_type_expr);
+					value_on_stack = true;
+				} else {
+					value_on_stack = false;
+				}
+
+				Variable.CreateBuilder (ec);
+				Variable.EmitAssign (ec);
+
+				if (expr_unwrap != null) {
+					ec.MarkLabel (no_value_label);
+				} else if (!value_on_stack) {
+					Variable.Emit (ec);
+				}
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			if (ResolveCommon (rc) == null)
+				return null;
+
+			type = rc.BuiltinTypes.Bool;
+			eclass = ExprClass.Value;
+
+			if (probe_type_expr == null)
+				return ResolveMatchingExpression (rc);
+
+			var res = ResolveResultExpression (rc);
+			if (Variable != null) {
+				if (res is Constant)
+					throw new NotImplementedException ("constant in type pattern matching");
+
+				Variable.Type = probe_type_expr;
+				var bc = rc as BlockContext;
+				if (bc != null)
+					Variable.PrepareAssignmentAnalysis (bc);
+			}
+
+			return res;
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.FlowAnalysis (fc);
+
+			if (Variable != null)
+				fc.SetVariableAssigned (Variable.VariableInfo, true);
+		}
+
+		protected override void ResolveProbeType (ResolveContext rc)
+		{
+			if (!(ProbeType is TypeExpr) && rc.Module.Compiler.Settings.Version == LanguageVersion.Experimental) {
+				ProbeType = ProbeType.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup | ResolveFlags.Type);
+				if (ProbeType == null)
+					return;
+
+				if (ProbeType.eclass == ExprClass.Type) {
+					probe_type_expr = ProbeType.Type;
+				}
+
+				return;
+			}
+
+			base.ResolveProbeType (rc);
+		}
+
+		Expression ResolveMatchingExpression (ResolveContext rc)
+		{
+			var mc = ProbeType as Constant;
+			if (mc != null) {
+				if (!Convert.ImplicitConversionExists (rc, ProbeType, Expr.Type)) {
+					ProbeType.Error_ValueCannotBeConverted (rc, Expr.Type, false);
+					return null;
+				}
+
+				if (mc.IsNull)
+					return new Binary (Binary.Operator.Equality, Expr, mc).Resolve (rc);
+
+				var c = Expr as Constant;
+				if (c != null) {
+					c = ConstantFold.BinaryFold (rc, Binary.Operator.Equality, c, mc, loc);
+					if (c != null)
+						return c;
+				}
+
+				if (Expr.Type.IsNullableType) {
+					expr_unwrap = new Nullable.Unwrap (Expr);
+					expr_unwrap.Resolve (rc);
+				} else if (ProbeType.Type.IsEnum || (ProbeType.Type.BuiltinType >= BuiltinTypeSpec.Type.Byte && ProbeType.Type.BuiltinType <= BuiltinTypeSpec.Type.Decimal)) {
+					var helper = rc.Module.CreatePatterMatchingHelper ();
+					number_mg = helper.NumberMatcher.Spec;
+
+					//
+					// There are actually 3 arguments but the first one is already on the stack
+					//
+					number_args = new Arguments (3);
+					if (!ProbeType.Type.IsEnum)
+						number_args.Add (new Argument (Expr));
+
+					number_args.Add (new Argument (Convert.ImplicitConversion (rc, ProbeType, rc.BuiltinTypes.Object, loc)));
+					number_args.Add (new Argument (new BoolLiteral (rc.BuiltinTypes, ProbeType.Type.IsEnum, loc)));
+				}
+
+				return this;
+			}
+
+			throw new NotImplementedException ();
+		}
+
+		Expression ResolveResultExpression (ResolveContext ec)
+		{
+			TypeSpec d = expr.Type;
+			bool d_is_nullable = false;
+
+			//
+			// If E is a method group or the null literal, or if the type of E is a reference
+			// type or a nullable type and the value of E is null, the result is false
+			//
+			if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
+				return CreateConstantResult (ec, false);
+
+			if (d.IsNullableType) {
+				var ut = Nullable.NullableInfo.GetUnderlyingType (d);
+				if (!ut.IsGenericParameter) {
+					d = ut;
+					d_is_nullable = true;
+				}
+			}
+				
+			TypeSpec t = probe_type_expr;
+			bool t_is_nullable = false;
+			if (t.IsNullableType) {
+				var ut = Nullable.NullableInfo.GetUnderlyingType (t);
+				if (!ut.IsGenericParameter) {
+					t = ut;
+					t_is_nullable = true;
+				}
+			}
+
+			if (t.IsStruct) {
+				if (d == t) {
+					//
+					// D and T are the same value types but D can be null
+					//
+					if (d_is_nullable && !t_is_nullable) {
+						expr_unwrap = Nullable.Unwrap.Create (expr, true);
+						return this;
+					}
+					
+					//
+					// The result is true if D and T are the same value types
+					//
+					return CreateConstantResult (ec, true);
+				}
+
+				var tp = d as TypeParameterSpec;
+				if (tp != null)
+					return ResolveGenericParameter (ec, t, tp);
+
+				//
+				// An unboxing conversion exists
+				//
+				if (Convert.ExplicitReferenceConversionExists (d, t))
+					return this;
+
+				//
+				// open generic type
+				//
+				if (d is InflatedTypeSpec && InflatedTypeSpec.ContainsTypeParameter (d))
+					return this;
+			} else {
+				var tps = t as TypeParameterSpec;
+				if (tps != null)
+					return ResolveGenericParameter (ec, d, tps);
+
+				if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					ec.Report.Warning (1981, 3, loc,
+						"Using `{0}' to test compatibility with `{1}' is identical to testing compatibility with `object'",
+						OperatorName, t.GetSignatureForError ());
+				}
+
+				if (TypeManager.IsGenericParameter (d))
+					return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
+
+				if (TypeSpec.IsValueType (d)) {
+					if (Convert.ImplicitBoxingConversion (null, d, t) != null) {
+						if (d_is_nullable && !t_is_nullable) {
+							expr_unwrap = Nullable.Unwrap.Create (expr, false);
+							return this;
+						}
+
+						return CreateConstantResult (ec, true);
+					}
+				} else {
+					if (Convert.ImplicitReferenceConversionExists (d, t)) {
+						var c = expr as Constant;
+						if (c != null)
+							return CreateConstantResult (ec, !c.IsNull);
+
+						//
+						// Do not optimize for imported type or dynamic type
+						//
+						if (d.MemberDefinition.IsImported && d.BuiltinType != BuiltinTypeSpec.Type.None &&
+							d.MemberDefinition.DeclaringAssembly != t.MemberDefinition.DeclaringAssembly) {
+							return this;
+						}
+
+						if (d.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+							return this;
+						
+						//
+						// Turn is check into simple null check for implicitly convertible reference types
+						//
+						return ReducedExpression.Create (
+							new Binary (Binary.Operator.Inequality, expr, new NullLiteral (loc)).Resolve (ec),
+							this).Resolve (ec);
+					}
+
+					if (Convert.ExplicitReferenceConversionExists (d, t))
+						return this;
+
+					//
+					// open generic type
+					//
+					if ((d is InflatedTypeSpec || d.IsArray) && InflatedTypeSpec.ContainsTypeParameter (d))
+						return this;
+				}
+			}
+
+			return CreateConstantResult (ec, false);
+		}
+
+		Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
+		{
+			if (t.IsReferenceType) {
+				if (d.IsStruct)
+					return CreateConstantResult (ec, false);
+			}
+
+			if (expr.Type.IsGenericParameter) {
+				if (expr.Type == d && TypeSpec.IsValueType (t) && TypeSpec.IsValueType (d))
+					return CreateConstantResult (ec, true);
+
+				expr = new BoxedCast (expr, d);
+			}
+
+			return this;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implementation of the `as' operator.
+	/// </summary>
+	public class As : Probe {
+
+		public As (Expression expr, Expression probe_type, Location l)
+			: base (expr, probe_type, l)
+		{
+		}
+
+		protected override string OperatorName {
+			get { return "as"; }
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = Arguments.CreateForExpressionTree (ec, null,
+				expr.CreateExpressionTree (ec),
+				new TypeOf (probe_type_expr, loc));
+
+			return CreateExpressionFactoryCall (ec, "TypeAs", args);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			expr.Emit (ec);
+
+			ec.Emit (OpCodes.Isinst, type);
+
+			if (TypeManager.IsGenericParameter (type) || type.IsNullableType)
+				ec.Emit (OpCodes.Unbox_Any, type);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (ResolveCommon (ec) == null)
+				return null;
+
+			type = probe_type_expr;
+			eclass = ExprClass.Value;
+			TypeSpec etype = expr.Type;
+
+			if (!TypeSpec.IsReferenceType (type) && !type.IsNullableType) {
+				if (TypeManager.IsGenericParameter (type)) {
+					ec.Report.Error (413, loc,
+						"The `as' operator cannot be used with a non-reference type parameter `{0}'. Consider adding `class' or a reference type constraint",
+						probe_type_expr.GetSignatureForError ());
+				} else {
+					ec.Report.Error (77, loc,
+						"The `as' operator cannot be used with a non-nullable value type `{0}'",
+						type.GetSignatureForError ());
+				}
+				return null;
+			}
+
+			if (expr.IsNull && type.IsNullableType) {
+				return Nullable.LiftedNull.CreateFromExpression (ec, this);
+			}
+
+			// If the compile-time type of E is dynamic, unlike the cast operator the as operator is not dynamically bound
+			if (etype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				return this;
+			}
+			
+			Expression e = Convert.ImplicitConversionStandard (ec, expr, type, loc);
+			if (e != null) {
+				e = EmptyCast.Create (e, type);
+				return ReducedExpression.Create (e, this).Resolve (ec);
+			}
+
+			if (Convert.ExplicitReferenceConversionExists (etype, type)){
+				if (TypeManager.IsGenericParameter (etype))
+					expr = new BoxedCast (expr, etype);
+
+				return this;
+			}
+
+			if (InflatedTypeSpec.ContainsTypeParameter (etype) || InflatedTypeSpec.ContainsTypeParameter (type)) {
+				expr = new BoxedCast (expr, etype);
+				return this;
+			}
+
+			if (etype != InternalType.ErrorType) {
+				ec.Report.Error (39, loc, "Cannot convert type `{0}' to `{1}' via a built-in conversion",
+					etype.GetSignatureForError (), type.GetSignatureForError ());
+			}
+
+			return null;
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+	
+	//
+	// This represents a typecast in the source language.
+	//
+	public class Cast : ShimExpression {
+		Expression target_type;
+
+		public Cast (Expression cast_type, Expression expr, Location loc)
+			: base (expr)
+		{
+			this.target_type = cast_type;
+			this.loc = loc;
+		}
+
+		public Expression TargetType {
+			get { return target_type; }
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			expr = expr.Resolve (ec);
+			if (expr == null)
+				return null;
+
+			type = target_type.ResolveAsType (ec);
+			if (type == null)
+				return null;
+
+			if (type.IsStatic) {
+				ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", type.GetSignatureForError ());
+				return null;
+			}
+
+			if (type.IsPointer && !ec.IsUnsafe) {
+				UnsafeError (ec, loc);
+			}
+
+			eclass = ExprClass.Value;
+			
+			Constant c = expr as Constant;
+			if (c != null) {
+				c = c.Reduce (ec, type);
+				if (c != null)
+					return c;
+			}
+
+			var res = Convert.ExplicitConversion (ec, expr, type, loc);
+			if (res == expr)
+				return EmptyCast.Create (res, type);
+
+			return res;
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Cast target = (Cast) t;
+
+			target.target_type = target_type.Clone (clonectx);
+			target.expr = expr.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ImplicitCast : ShimExpression
+	{
+		bool arrayAccess;
+
+		public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
+			: base (expr)
+		{
+			this.loc = expr.Location;
+			this.type = target;
+			this.arrayAccess = arrayAccess;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			expr = expr.Resolve (ec);
+			if (expr == null)
+				return null;
+
+			if (arrayAccess)
+				expr = ConvertExpressionToArrayIndex (ec, expr);
+			else
+				expr = Convert.ImplicitConversionRequired (ec, expr, type, loc);
+
+			return expr;
+		}
+	}
+	
+	//
+	// C# 2.0 Default value expression
+	//
+	public class DefaultValueExpression : Expression
+	{
+		Expression expr;
+
+		public DefaultValueExpression (Expression expr, Location loc)
+		{
+			this.expr = expr;
+			this.loc = loc;
+		}
+
+		public Expression Expr {
+			get {
+				return this.expr; 
+			}
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (this));
+			args.Add (new Argument (new TypeOf (type, loc)));
+			return CreateExpressionFactoryCall (ec, "Constant", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			type = expr.ResolveAsType (ec);
+			if (type == null)
+				return null;
+
+			if (type.IsStatic) {
+				ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
+			}
+
+			if (type.IsPointer)
+				return new NullLiteral (Location).ConvertImplicitly (type);
+
+			if (TypeSpec.IsReferenceType (type))
+				return new NullConstant (type, loc);
+
+			Constant c = New.Constantify (type, expr.Location);
+			if (c != null)
+				return c;
+
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			LocalTemporary temp_storage = new LocalTemporary(type);
+
+			temp_storage.AddressOf(ec, AddressOp.LoadStore);
+			ec.Emit(OpCodes.Initobj, type);
+			temp_storage.Emit(ec);
+			temp_storage.Release (ec);
+		}
+
+#if (NET_4_0 || MOBILE_DYNAMIC) && !STATIC
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return SLE.Expression.Default (type.GetMetaInfo ());
+		}
+#endif
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			DefaultValueExpression target = (DefaultValueExpression) t;
+			
+			target.expr = expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Binary operators
+	/// </summary>
+	public class Binary : Expression, IDynamicBinder
+	{
+		public class PredefinedOperator
+		{
+			protected readonly TypeSpec left;
+			protected readonly TypeSpec right;
+			protected readonly TypeSpec left_unwrap;
+			protected readonly TypeSpec right_unwrap;
+			public readonly Operator OperatorsMask;
+			public TypeSpec ReturnType;
+
+			public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
+				: this (ltype, rtype, op_mask, ltype)
+			{
+			}
+
+			public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
+				: this (type, type, op_mask, return_type)
+			{
+			}
+
+			public PredefinedOperator (TypeSpec type, Operator op_mask)
+				: this (type, type, op_mask, type)
+			{
+			}
+
+			public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
+			{
+				if ((op_mask & Operator.ValuesOnlyMask) != 0)
+					throw new InternalErrorException ("Only masked values can be used");
+
+				if ((op_mask & Operator.NullableMask) != 0) {
+					left_unwrap = Nullable.NullableInfo.GetUnderlyingType (ltype);
+					right_unwrap = Nullable.NullableInfo.GetUnderlyingType (rtype);
+				} else {
+					left_unwrap = ltype;
+					right_unwrap = rtype;
+				}
+
+				this.left = ltype;
+				this.right = rtype;
+				this.OperatorsMask = op_mask;
+				this.ReturnType = return_type;
+			}
+
+			public bool IsLifted {
+				get {
+					return (OperatorsMask & Operator.NullableMask) != 0;
+				}
+			}
+
+			public virtual Expression ConvertResult (ResolveContext rc, Binary b)
+			{
+				Constant c;
+
+				var left_expr = b.left;
+				var right_expr = b.right;
+
+				b.type = ReturnType;
+
+				if (IsLifted) {
+					if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
+						b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
+						b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
+					}
+
+					if (right_expr.IsNull) {
+						if ((b.oper & Operator.EqualityMask) != 0) {
+							if (!left_expr.Type.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (left_expr.Type))
+								return b.CreateLiftedValueTypeResult (rc, left_expr.Type);
+						} else if ((b.oper & Operator.BitwiseMask) != 0) {
+							if (left_unwrap.BuiltinType != BuiltinTypeSpec.Type.Bool)
+								return Nullable.LiftedNull.CreateFromExpression (rc, b);
+						} else {
+							b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
+							b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
+
+							if ((b.Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
+								return Nullable.LiftedNull.CreateFromExpression (rc, b);
+
+							return b.CreateLiftedValueTypeResult (rc, left);
+						}
+					} else if (left_expr.IsNull) {
+						if ((b.oper & Operator.EqualityMask) != 0) {
+							if (!right_expr.Type.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (right_expr.Type))
+								return b.CreateLiftedValueTypeResult (rc, right_expr.Type);
+						} else if ((b.oper & Operator.BitwiseMask) != 0) {
+							if (right_unwrap.BuiltinType != BuiltinTypeSpec.Type.Bool)
+								return Nullable.LiftedNull.CreateFromExpression (rc, b);
+						} else {
+							b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
+							b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
+
+							if ((b.Oper & (Operator.ArithmeticMask | Operator.ShiftMask)) != 0)
+								return Nullable.LiftedNull.CreateFromExpression (rc, b);
+
+							return b.CreateLiftedValueTypeResult (rc, right);
+						}
+					}
+				}
+
+				//
+				// A user operators does not support multiple user conversions, but decimal type
+				// is considered to be predefined type therefore we apply predefined operators rules
+				// and then look for decimal user-operator implementation
+				//
+				if (left.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+					b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
+					b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
+
+					return b.ResolveUserOperator (rc, b.left, b.right);
+				}
+
+				c = right_expr as Constant;
+				if (c != null) {
+					if (c.IsDefaultValue) {
+						//
+						// Optimizes
+						// 
+						// (expr + 0) to expr
+						// (expr - 0) to expr
+						// (bool? | false) to bool?
+						//
+						if (b.oper == Operator.Addition || b.oper == Operator.Subtraction ||
+							(b.oper == Operator.BitwiseOr && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && c is BoolConstant)) {
+							b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
+							return ReducedExpression.Create (b.left, b).Resolve (rc);
+						}
+
+						//
+						// Optimizes (value &/&& 0) to 0
+						//
+						if ((b.oper == Operator.BitwiseAnd || b.oper == Operator.LogicalAnd) && !IsLifted) {
+							Constant side_effect = new SideEffectConstant (c, b.left, c.Location);
+							return ReducedExpression.Create (side_effect, b);
+						}
+					} else {
+						//
+						// Optimizes (bool? & true) to bool?
+						//
+						if (IsLifted && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && b.oper == Operator.BitwiseAnd) {
+							return ReducedExpression.Create (b.left, b).Resolve (rc);
+						}
+					}
+
+					if ((b.oper == Operator.Multiply || b.oper == Operator.Division) && c.IsOneInteger)
+						return ReducedExpression.Create (b.left, b).Resolve (rc);
+
+					if ((b.oper & Operator.ShiftMask) != 0 && c is IntConstant) {
+						b.right = new IntConstant (rc.BuiltinTypes, ((IntConstant) c).Value & GetShiftMask (left_unwrap), b.right.Location);
+					}
+				}
+
+				c = b.left as Constant;
+				if (c != null) {
+					if (c.IsDefaultValue) {
+						//
+						// Optimizes
+						// 
+						// (0 + expr) to expr
+						// (false | bool?) to bool?
+						//
+						if (b.oper == Operator.Addition ||
+							(b.oper == Operator.BitwiseOr && right_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && c is BoolConstant)) {
+							b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
+							return ReducedExpression.Create (b.right, b).Resolve (rc);
+						}
+
+						//
+						// Optimizes (false && expr) to false
+						//
+						if (b.oper == Operator.LogicalAnd && c.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
+							// No rhs side-effects
+							Expression.Warning_UnreachableExpression (rc, b.right.StartLocation);
+							return ReducedExpression.Create (c, b);
+						}
+
+						//
+						// Optimizes (0 & value) to 0
+						//
+						if (b.oper == Operator.BitwiseAnd && !IsLifted) {
+							Constant side_effect = new SideEffectConstant (c, b.right, c.Location);
+							return ReducedExpression.Create (side_effect, b);
+						}
+					} else {
+						//
+						// Optimizes (true & bool?) to bool?
+						//
+						if (IsLifted && left_unwrap.BuiltinType == BuiltinTypeSpec.Type.Bool && b.oper == Operator.BitwiseAnd) {
+							return ReducedExpression.Create (b.right, b).Resolve (rc);
+						}
+
+						//
+						// Optimizes (true || expr) to true
+						//
+						if (b.oper == Operator.LogicalOr && c.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
+							// No rhs side-effects
+							Expression.Warning_UnreachableExpression (rc, b.right.StartLocation);
+							return ReducedExpression.Create (c, b);
+						}
+					}
+
+					if (b.oper == Operator.Multiply && c.IsOneInteger)
+						return ReducedExpression.Create (b.right, b).Resolve (rc);
+				}
+
+				if (IsLifted) {
+					var lifted = new Nullable.LiftedBinaryOperator (b);
+
+					TypeSpec ltype, rtype;
+					if (b.left.Type.IsNullableType) {
+						lifted.UnwrapLeft = new Nullable.Unwrap (b.left);
+						ltype = left_unwrap;
+					} else {
+						ltype = left;
+					}
+
+					if (b.right.Type.IsNullableType) {
+						lifted.UnwrapRight = new Nullable.Unwrap (b.right);
+						rtype = right_unwrap;
+					} else {
+						rtype = right;
+					}
+
+					lifted.Left = b.left.IsNull ?
+						b.left :
+						Convert.ImplicitConversion (rc, lifted.UnwrapLeft ?? b.left, ltype, b.left.Location);
+
+					lifted.Right = b.right.IsNull ?
+						b.right :
+						Convert.ImplicitConversion (rc, lifted.UnwrapRight ?? b.right, rtype, b.right.Location);
+
+					return lifted.Resolve (rc);
+				}
+
+				b.left = Convert.ImplicitConversion (rc, b.left, left, b.left.Location);
+				b.right = Convert.ImplicitConversion (rc, b.right, right, b.right.Location);
+
+				return b;
+			}
+
+			public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
+			{
+				//
+				// We are dealing with primitive types only
+				//
+				return left == ltype && ltype == rtype;
+			}
+
+			public virtual bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
+			{
+				// Quick path
+				if (left == lexpr.Type && right == rexpr.Type)
+					return true;
+
+				return Convert.ImplicitConversionExists (ec, lexpr, left) &&
+					Convert.ImplicitConversionExists (ec, rexpr, right);
+			}
+
+			public PredefinedOperator ResolveBetterOperator (ResolveContext ec, PredefinedOperator best_operator)
+			{
+				if ((OperatorsMask & Operator.DecomposedMask) != 0)
+					return best_operator;
+
+				if ((best_operator.OperatorsMask & Operator.DecomposedMask) != 0)
+					return this;
+
+				int result = 0;
+				if (left != null && best_operator.left != null) {
+					result = OverloadResolver.BetterTypeConversion (ec, best_operator.left_unwrap, left_unwrap);
+				}
+
+				//
+				// When second argument is same as the first one, the result is same
+				//
+				if (right != null && (left != right || best_operator.left != best_operator.right)) {
+					result |= OverloadResolver.BetterTypeConversion (ec, best_operator.right_unwrap, right_unwrap);
+				}
+
+				if (result == 0 || result > 2)
+					return null;
+
+				return result == 1 ? best_operator : this;
+			}
+		}
+
+		sealed class PredefinedStringOperator : PredefinedOperator
+		{
+			public PredefinedStringOperator (TypeSpec type, Operator op_mask, TypeSpec retType)
+				: base (type, type, op_mask, retType)
+			{
+			}
+
+			public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
+				: base (ltype, rtype, op_mask, retType)
+			{
+			}
+
+			public override Expression ConvertResult (ResolveContext ec, Binary b)
+			{
+				//
+				// Use original expression for nullable arguments
+				//
+				Nullable.Unwrap unwrap = b.left as Nullable.Unwrap;
+				if (unwrap != null)
+					b.left = unwrap.Original;
+
+				unwrap = b.right as Nullable.Unwrap;
+				if (unwrap != null)
+					b.right = unwrap.Original;
+
+				b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
+				b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
+
+				//
+				// Start a new concat expression using converted expression
+				//
+				return StringConcat.Create (ec, b.left, b.right, b.loc);
+			}
+		}
+
+		sealed class PredefinedEqualityOperator : PredefinedOperator
+		{
+			MethodSpec equal_method, inequal_method;
+
+			public PredefinedEqualityOperator (TypeSpec arg, TypeSpec retType)
+				: base (arg, arg, Operator.EqualityMask, retType)
+			{
+			}
+
+			public override Expression ConvertResult (ResolveContext ec, Binary b)
+			{
+				b.type = ReturnType;
+
+				b.left = Convert.ImplicitConversion (ec, b.left, left, b.left.Location);
+				b.right = Convert.ImplicitConversion (ec, b.right, right, b.right.Location);
+
+				Arguments args = new Arguments (2);
+				args.Add (new Argument (b.left));
+				args.Add (new Argument (b.right));
+
+				MethodSpec method;
+				if (b.oper == Operator.Equality) {
+					if (equal_method == null) {
+						if (left.BuiltinType == BuiltinTypeSpec.Type.String)
+							equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (b.loc);
+						else if (left.BuiltinType == BuiltinTypeSpec.Type.Delegate)
+							equal_method = ec.Module.PredefinedMembers.DelegateEqual.Resolve (b.loc);
+						else
+							throw new NotImplementedException (left.GetSignatureForError ());
+					}
+
+					method = equal_method;
+				} else {
+					if (inequal_method == null) {
+						if (left.BuiltinType == BuiltinTypeSpec.Type.String)
+							inequal_method = ec.Module.PredefinedMembers.StringInequal.Resolve (b.loc);
+						else if (left.BuiltinType == BuiltinTypeSpec.Type.Delegate)
+							inequal_method = ec.Module.PredefinedMembers.DelegateInequal.Resolve (b.loc);
+						else
+							throw new NotImplementedException (left.GetSignatureForError ());
+					}
+
+					method = inequal_method;
+				}
+
+				return new UserOperatorCall (method, args, b.CreateExpressionTree, b.loc);
+			}
+		}
+
+		class PredefinedPointerOperator : PredefinedOperator
+		{
+			public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
+				: base (ltype, rtype, op_mask)
+			{
+			}
+
+			public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
+				: base (ltype, rtype, op_mask, retType)
+			{
+			}
+
+			public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
+				: base (type, op_mask, return_type)
+			{
+			}
+
+			public override bool IsApplicable (ResolveContext ec, Expression lexpr, Expression rexpr)
+			{
+				if (left == null) {
+					if (!lexpr.Type.IsPointer)
+						return false;
+				} else {
+					if (!Convert.ImplicitConversionExists (ec, lexpr, left))
+						return false;
+				}
+
+				if (right == null) {
+					if (!rexpr.Type.IsPointer)
+						return false;
+				} else {
+					if (!Convert.ImplicitConversionExists (ec, rexpr, right))
+						return false;
+				}
+
+				return true;
+			}
+
+			public override Expression ConvertResult (ResolveContext ec, Binary b)
+			{
+				if (left != null) {
+					b.left = EmptyCast.Create (b.left, left);
+				} else if (right != null) {
+					b.right = EmptyCast.Create (b.right, right);
+				}
+
+				TypeSpec r_type = ReturnType;
+				Expression left_arg, right_arg;
+				if (r_type == null) {
+					if (left == null) {
+						left_arg = b.left;
+						right_arg = b.right;
+						r_type = b.left.Type;
+					} else {
+						left_arg = b.right;
+						right_arg = b.left;
+						r_type = b.right.Type;
+					}
+				} else {
+					left_arg = b.left;
+					right_arg = b.right;
+				}
+
+				return new PointerArithmetic (b.oper, left_arg, right_arg, r_type, b.loc).Resolve (ec);
+			}
+		}
+
+		[Flags]
+		public enum Operator {
+			Multiply	= 0 | ArithmeticMask,
+			Division	= 1 | ArithmeticMask,
+			Modulus		= 2 | ArithmeticMask,
+			Addition	= 3 | ArithmeticMask | AdditionMask,
+			Subtraction = 4 | ArithmeticMask | SubtractionMask,
+
+			LeftShift	= 5 | ShiftMask,
+			RightShift	= 6 | ShiftMask,
+
+			LessThan	= 7 | ComparisonMask | RelationalMask,
+			GreaterThan	= 8 | ComparisonMask | RelationalMask,
+			LessThanOrEqual		= 9 | ComparisonMask | RelationalMask,
+			GreaterThanOrEqual	= 10 | ComparisonMask | RelationalMask,
+			Equality	= 11 | ComparisonMask | EqualityMask,
+			Inequality	= 12 | ComparisonMask | EqualityMask,
+
+			BitwiseAnd	= 13 | BitwiseMask,
+			ExclusiveOr	= 14 | BitwiseMask,
+			BitwiseOr	= 15 | BitwiseMask,
+
+			LogicalAnd	= 16 | LogicalMask,
+			LogicalOr	= 17 | LogicalMask,
+
+			//
+			// Operator masks
+			//
+			ValuesOnlyMask	= ArithmeticMask - 1,
+			ArithmeticMask	= 1 << 5,
+			ShiftMask		= 1 << 6,
+			ComparisonMask	= 1 << 7,
+			EqualityMask	= 1 << 8,
+			BitwiseMask		= 1 << 9,
+			LogicalMask		= 1 << 10,
+			AdditionMask	= 1 << 11,
+			SubtractionMask	= 1 << 12,
+			RelationalMask	= 1 << 13,
+
+			DecomposedMask	= 1 << 19,
+			NullableMask	= 1 << 20,
+		}
+
+		[Flags]
+		enum State : byte
+		{
+			None = 0,
+			Compound = 1 << 1,
+		}
+
+		readonly Operator oper;
+		Expression left, right;
+		State state;
+		ConvCast.Mode enum_conversion;
+
+		public Binary (Operator oper, Expression left, Expression right, bool isCompound)
+			: this (oper, left, right)
+		{
+			if (isCompound)
+				state |= State.Compound;
+		}
+
+		public Binary (Operator oper, Expression left, Expression right)
+		{
+			this.oper = oper;
+			this.left = left;
+			this.right = right;
+			this.loc = left.Location;
+		}
+
+		#region Properties
+
+		public bool IsCompound {
+			get {
+				return (state & State.Compound) != 0;
+			}
+		}
+
+		public Operator Oper {
+			get {
+				return oper;
+			}
+		}
+
+		public Expression Left {
+			get {
+				return this.left;
+			}
+		}
+
+		public Expression Right {
+			get {
+				return this.right;
+			}
+		}
+
+		public override Location StartLocation {
+			get {
+				return left.StartLocation;
+			}
+		}
+
+		#endregion
+
+		/// <summary>
+		///   Returns a stringified representation of the Operator
+		/// </summary>
+		string OperName (Operator oper)
+		{
+			string s;
+			switch (oper){
+			case Operator.Multiply:
+				s = "*";
+				break;
+			case Operator.Division:
+				s = "/";
+				break;
+			case Operator.Modulus:
+				s = "%";
+				break;
+			case Operator.Addition:
+				s = "+";
+				break;
+			case Operator.Subtraction:
+				s = "-";
+				break;
+			case Operator.LeftShift:
+				s = "<<";
+				break;
+			case Operator.RightShift:
+				s = ">>";
+				break;
+			case Operator.LessThan:
+				s = "<";
+				break;
+			case Operator.GreaterThan:
+				s = ">";
+				break;
+			case Operator.LessThanOrEqual:
+				s = "<=";
+				break;
+			case Operator.GreaterThanOrEqual:
+				s = ">=";
+				break;
+			case Operator.Equality:
+				s = "==";
+				break;
+			case Operator.Inequality:
+				s = "!=";
+				break;
+			case Operator.BitwiseAnd:
+				s = "&";
+				break;
+			case Operator.BitwiseOr:
+				s = "|";
+				break;
+			case Operator.ExclusiveOr:
+				s = "^";
+				break;
+			case Operator.LogicalOr:
+				s = "||";
+				break;
+			case Operator.LogicalAnd:
+				s = "&&";
+				break;
+			default:
+				s = oper.ToString ();
+				break;
+			}
+
+			if (IsCompound)
+				return s + "=";
+
+			return s;
+		}
+
+		public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, Operator oper, Location loc)
+		{
+			new Binary (oper, left, right).Error_OperatorCannotBeApplied (ec, left, right);
+		}
+
+		public static void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right, string oper, Location loc)
+		{
+			if (left.Type == InternalType.ErrorType || right.Type == InternalType.ErrorType)
+				return;
+
+			string l, r;
+			l = left.Type.GetSignatureForError ();
+			r = right.Type.GetSignatureForError ();
+
+			ec.Report.Error (19, loc, "Operator `{0}' cannot be applied to operands of type `{1}' and `{2}'",
+				oper, l, r);
+		}
+		
+		void Error_OperatorCannotBeApplied (ResolveContext ec, Expression left, Expression right)
+		{
+			Error_OperatorCannotBeApplied (ec, left, right, OperName (oper), loc);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			//
+			// Optimized version when on-true/on-false data are not needed
+			//
+			if ((oper & Operator.LogicalMask) == 0) {
+				left.FlowAnalysis (fc);
+				right.FlowAnalysis (fc);
+				return;
+			}
+
+			left.FlowAnalysisConditional (fc);
+			var left_fc_ontrue = fc.DefiniteAssignmentOnTrue;
+			var left_fc_onfalse = fc.DefiniteAssignmentOnFalse;
+
+			fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (
+				oper == Operator.LogicalOr ? left_fc_onfalse : left_fc_ontrue);
+			right.FlowAnalysisConditional (fc);
+
+			if (oper == Operator.LogicalOr)
+				fc.DefiniteAssignment = (left_fc_onfalse | (fc.DefiniteAssignmentOnFalse & fc.DefiniteAssignmentOnTrue)) & left_fc_ontrue;
+			else
+				fc.DefiniteAssignment = (left_fc_ontrue | (fc.DefiniteAssignmentOnFalse & fc.DefiniteAssignmentOnTrue)) & left_fc_onfalse;
+		}
+
+		public override void FlowAnalysisConditional (FlowAnalysisContext fc)
+		{
+			if ((oper & Operator.LogicalMask) == 0) {
+				base.FlowAnalysisConditional (fc);
+				return;
+			}
+
+			left.FlowAnalysisConditional (fc);
+			var left_fc_ontrue = fc.DefiniteAssignmentOnTrue;
+			var left_fc_onfalse = fc.DefiniteAssignmentOnFalse;
+
+			fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (
+				oper == Operator.LogicalOr ? left_fc_onfalse : left_fc_ontrue);
+			right.FlowAnalysisConditional (fc);
+
+			var lc = left as Constant;
+			if (oper == Operator.LogicalOr) {
+				fc.DefiniteAssignmentOnFalse = left_fc_onfalse | fc.DefiniteAssignmentOnFalse;
+				if (lc != null && lc.IsDefaultValue)
+					fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse;
+				else
+					fc.DefiniteAssignmentOnTrue = new DefiniteAssignmentBitSet (left_fc_ontrue & (left_fc_onfalse | fc.DefiniteAssignmentOnTrue));
+			} else {
+				fc.DefiniteAssignmentOnTrue = left_fc_ontrue | fc.DefiniteAssignmentOnTrue;
+				if (lc != null && !lc.IsDefaultValue)
+					fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignmentOnTrue;
+				else
+					fc.DefiniteAssignmentOnFalse = new DefiniteAssignmentBitSet ((left_fc_ontrue | fc.DefiniteAssignmentOnFalse) & left_fc_onfalse);
+			}
+		}
+
+		//
+		// Converts operator to System.Linq.Expressions.ExpressionType enum name
+		//
+		string GetOperatorExpressionTypeName ()
+		{
+			switch (oper) {
+			case Operator.Addition:
+				return IsCompound ? "AddAssign" : "Add";
+			case Operator.BitwiseAnd:
+				return IsCompound ? "AndAssign" : "And";
+			case Operator.BitwiseOr:
+				return IsCompound ? "OrAssign" : "Or";
+			case Operator.Division:
+				return IsCompound ? "DivideAssign" : "Divide";
+			case Operator.ExclusiveOr:
+				return IsCompound ? "ExclusiveOrAssign" : "ExclusiveOr";
+			case Operator.Equality:
+				return "Equal";
+			case Operator.GreaterThan:
+				return "GreaterThan";
+			case Operator.GreaterThanOrEqual:
+				return "GreaterThanOrEqual";
+			case Operator.Inequality:
+				return "NotEqual";
+			case Operator.LeftShift:
+				return IsCompound ? "LeftShiftAssign" : "LeftShift";
+			case Operator.LessThan:
+				return "LessThan";
+			case Operator.LessThanOrEqual:
+				return "LessThanOrEqual";
+			case Operator.LogicalAnd:
+				return "And";
+			case Operator.LogicalOr:
+				return "Or";
+			case Operator.Modulus:
+				return IsCompound ? "ModuloAssign" : "Modulo";
+			case Operator.Multiply:
+				return IsCompound ? "MultiplyAssign" : "Multiply";
+			case Operator.RightShift:
+				return IsCompound ? "RightShiftAssign" : "RightShift";
+			case Operator.Subtraction:
+				return IsCompound ? "SubtractAssign" : "Subtract";
+			default:
+				throw new NotImplementedException ("Unknown expression type operator " + oper.ToString ());
+			}
+		}
+
+		static CSharp.Operator.OpType ConvertBinaryToUserOperator (Operator op)
+		{
+			switch (op) {
+			case Operator.Addition:
+				return CSharp.Operator.OpType.Addition;
+			case Operator.BitwiseAnd:
+			case Operator.LogicalAnd:
+				return CSharp.Operator.OpType.BitwiseAnd;
+			case Operator.BitwiseOr:
+			case Operator.LogicalOr:
+				return CSharp.Operator.OpType.BitwiseOr;
+			case Operator.Division:
+				return CSharp.Operator.OpType.Division;
+			case Operator.Equality:
+				return CSharp.Operator.OpType.Equality;
+			case Operator.ExclusiveOr:
+				return CSharp.Operator.OpType.ExclusiveOr;
+			case Operator.GreaterThan:
+				return CSharp.Operator.OpType.GreaterThan;
+			case Operator.GreaterThanOrEqual:
+				return CSharp.Operator.OpType.GreaterThanOrEqual;
+			case Operator.Inequality:
+				return CSharp.Operator.OpType.Inequality;
+			case Operator.LeftShift:
+				return CSharp.Operator.OpType.LeftShift;
+			case Operator.LessThan:
+				return CSharp.Operator.OpType.LessThan;
+			case Operator.LessThanOrEqual:
+				return CSharp.Operator.OpType.LessThanOrEqual;
+			case Operator.Modulus:
+				return CSharp.Operator.OpType.Modulus;
+			case Operator.Multiply:
+				return CSharp.Operator.OpType.Multiply;
+			case Operator.RightShift:
+				return CSharp.Operator.OpType.RightShift;
+			case Operator.Subtraction:
+				return CSharp.Operator.OpType.Subtraction;
+			default:
+				throw new InternalErrorException (op.ToString ());
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
+		}
+
+		public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l, Expression right)
+		{
+			OpCode opcode;
+
+			switch (oper){
+			case Operator.Multiply:
+				if (ec.HasSet (EmitContext.Options.CheckedScope)) {
+					if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
+						opcode = OpCodes.Mul_Ovf;
+					else if (!IsFloat (l))
+						opcode = OpCodes.Mul_Ovf_Un;
+					else
+						opcode = OpCodes.Mul;
+				} else
+					opcode = OpCodes.Mul;
+				
+				break;
+				
+			case Operator.Division:
+				if (IsUnsigned (l))
+					opcode = OpCodes.Div_Un;
+				else
+					opcode = OpCodes.Div;
+				break;
+				
+			case Operator.Modulus:
+				if (IsUnsigned (l))
+					opcode = OpCodes.Rem_Un;
+				else
+					opcode = OpCodes.Rem;
+				break;
+
+			case Operator.Addition:
+				if (ec.HasSet (EmitContext.Options.CheckedScope)) {
+					if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
+						opcode = OpCodes.Add_Ovf;
+					else if (!IsFloat (l))
+						opcode = OpCodes.Add_Ovf_Un;
+					else
+						opcode = OpCodes.Add;
+				} else
+					opcode = OpCodes.Add;
+				break;
+
+			case Operator.Subtraction:
+				if (ec.HasSet (EmitContext.Options.CheckedScope)) {
+					if (l.BuiltinType == BuiltinTypeSpec.Type.Int || l.BuiltinType == BuiltinTypeSpec.Type.Long)
+						opcode = OpCodes.Sub_Ovf;
+					else if (!IsFloat (l))
+						opcode = OpCodes.Sub_Ovf_Un;
+					else
+						opcode = OpCodes.Sub;
+				} else
+					opcode = OpCodes.Sub;
+				break;
+
+			case Operator.RightShift:
+				if (!(right is IntConstant)) {
+					ec.EmitInt (GetShiftMask (l));
+					ec.Emit (OpCodes.And);
+				}
+
+				if (IsUnsigned (l))
+					opcode = OpCodes.Shr_Un;
+				else
+					opcode = OpCodes.Shr;
+				break;
+				
+			case Operator.LeftShift:
+				if (!(right is IntConstant)) {
+					ec.EmitInt (GetShiftMask (l));
+					ec.Emit (OpCodes.And);
+				}
+
+				opcode = OpCodes.Shl;
+				break;
+
+			case Operator.Equality:
+				opcode = OpCodes.Ceq;
+				break;
+
+			case Operator.Inequality:
+				ec.Emit (OpCodes.Ceq);
+				ec.EmitInt (0);
+				
+				opcode = OpCodes.Ceq;
+				break;
+
+			case Operator.LessThan:
+				if (IsUnsigned (l))
+					opcode = OpCodes.Clt_Un;
+				else
+					opcode = OpCodes.Clt;
+				break;
+
+			case Operator.GreaterThan:
+				if (IsUnsigned (l))
+					opcode = OpCodes.Cgt_Un;
+				else
+					opcode = OpCodes.Cgt;
+				break;
+
+			case Operator.LessThanOrEqual:
+				if (IsUnsigned (l) || IsFloat (l))
+					ec.Emit (OpCodes.Cgt_Un);
+				else
+					ec.Emit (OpCodes.Cgt);
+				ec.EmitInt (0);
+				
+				opcode = OpCodes.Ceq;
+				break;
+
+			case Operator.GreaterThanOrEqual:
+				if (IsUnsigned (l) || IsFloat (l))
+					ec.Emit (OpCodes.Clt_Un);
+				else
+					ec.Emit (OpCodes.Clt);
+				
+				ec.EmitInt (0);
+				
+				opcode = OpCodes.Ceq;
+				break;
+
+			case Operator.BitwiseOr:
+				opcode = OpCodes.Or;
+				break;
+
+			case Operator.BitwiseAnd:
+				opcode = OpCodes.And;
+				break;
+
+			case Operator.ExclusiveOr:
+				opcode = OpCodes.Xor;
+				break;
+
+			default:
+				throw new InternalErrorException (oper.ToString ());
+			}
+
+			ec.Emit (opcode);
+		}
+
+		static int GetShiftMask (TypeSpec type)
+		{
+			return type.BuiltinType == BuiltinTypeSpec.Type.Int || type.BuiltinType == BuiltinTypeSpec.Type.UInt ? 0x1f : 0x3f;
+		}
+
+		static bool IsUnsigned (TypeSpec t)
+		{
+			switch (t.BuiltinType) {
+			case BuiltinTypeSpec.Type.Char:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Byte:
+				return true;
+			}
+
+			return t.IsPointer;
+		}
+
+		static bool IsFloat (TypeSpec t)
+		{
+			return t.BuiltinType == BuiltinTypeSpec.Type.Float || t.BuiltinType == BuiltinTypeSpec.Type.Double;
+		}
+
+		public Expression ResolveOperator (ResolveContext rc)
+		{
+			eclass = ExprClass.Value;
+
+			TypeSpec l = left.Type;
+			TypeSpec r = right.Type;
+			Expression expr;
+			bool primitives_only = false;
+
+			//
+			// Handles predefined primitive types
+			//
+			if ((BuiltinTypeSpec.IsPrimitiveType (l) || (l.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (Nullable.NullableInfo.GetUnderlyingType (l)))) &&
+				(BuiltinTypeSpec.IsPrimitiveType (r) || (r.IsNullableType && BuiltinTypeSpec.IsPrimitiveType (Nullable.NullableInfo.GetUnderlyingType (r))))) {
+				if ((oper & Operator.ShiftMask) == 0) {
+					if (!DoBinaryOperatorPromotion (rc))
+						return null;
+
+					primitives_only = BuiltinTypeSpec.IsPrimitiveType (l) && BuiltinTypeSpec.IsPrimitiveType (r);
+				}
+			} else {
+				// Pointers
+				if (l.IsPointer || r.IsPointer)
+					return ResolveOperatorPointer (rc, l, r);
+
+				// User operators
+				expr = ResolveUserOperator (rc, left, right);
+				if (expr != null)
+					return expr;
+
+
+				bool lenum = l.IsEnum;
+				bool renum = r.IsEnum;
+				if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
+					//
+					// Enumerations
+					//
+					if (IsEnumOrNullableEnum (l) || IsEnumOrNullableEnum (r)) {
+						expr = ResolveSingleEnumOperators (rc, lenum, renum, l, r);
+
+						if (expr == null)
+							return null;
+
+						if ((oper & Operator.BitwiseMask) != 0) {
+							expr = EmptyCast.Create (expr, type);
+							enum_conversion = GetEnumResultCast (type);
+
+							if (oper == Operator.BitwiseAnd && left.Type.IsEnum && right.Type.IsEnum) {
+								expr = OptimizeAndOperation (expr);
+							}
+						}
+
+						left = ConvertEnumOperandToUnderlyingType (rc, left, r.IsNullableType);
+						right = ConvertEnumOperandToUnderlyingType (rc, right, l.IsNullableType);
+						return expr;
+					}
+				} else if ((oper == Operator.Addition || oper == Operator.Subtraction)) {
+					if (IsEnumOrNullableEnum (l) || IsEnumOrNullableEnum (r)) {
+						//
+						// Enumerations
+						//
+						expr = ResolveEnumOperators (rc, lenum, renum, l, r);
+
+						//
+						// We cannot break here there is also Enum + String possible match
+						// which is not ambiguous with predefined enum operators
+						//
+						if (expr != null) {
+							left = ConvertEnumOperandToUnderlyingType (rc, left, false);
+							right = ConvertEnumOperandToUnderlyingType (rc, right, false);
+
+							return expr;
+						}
+					} else if (l.IsDelegate || r.IsDelegate) {
+						//
+						// Delegates
+						//
+						expr = ResolveOperatorDelegate (rc, l, r);
+
+						// TODO: Can this be ambiguous
+						if (expr != null)
+							return expr;
+					}
+				}
+			}
+			
+			//
+			// Equality operators are more complicated
+			//
+			if ((oper & Operator.EqualityMask) != 0) {
+				return ResolveEquality (rc, l, r, primitives_only);
+			}
+
+			expr = ResolveOperatorPredefined (rc, rc.BuiltinTypes.OperatorsBinaryStandard, primitives_only);
+			if (expr != null)
+				return expr;
+
+			if (primitives_only)
+				return null;
+
+			//
+			// Lifted operators have lower priority
+			//
+			return ResolveOperatorPredefined (rc, rc.Module.OperatorsBinaryLifted, false);
+		}
+
+		static bool IsEnumOrNullableEnum (TypeSpec type)
+		{
+			return type.IsEnum || (type.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (type).IsEnum);
+		}
+
+
+		// at least one of 'left' or 'right' is an enumeration constant (EnumConstant or SideEffectConstant or ...)
+		// if 'left' is not an enumeration constant, create one from the type of 'right'
+		Constant EnumLiftUp (ResolveContext ec, Constant left, Constant right)
+		{
+			switch (oper) {
+			case Operator.BitwiseOr:
+			case Operator.BitwiseAnd:
+			case Operator.ExclusiveOr:
+			case Operator.Equality:
+			case Operator.Inequality:
+			case Operator.LessThan:
+			case Operator.LessThanOrEqual:
+			case Operator.GreaterThan:
+			case Operator.GreaterThanOrEqual:
+				if (left.Type.IsEnum)
+					return left;
+				
+				if (left.IsZeroInteger)
+					return left.Reduce (ec, right.Type);
+				
+				break;
+				
+			case Operator.Addition:
+			case Operator.Subtraction:
+				return left;
+				
+			case Operator.Multiply:
+			case Operator.Division:
+			case Operator.Modulus:
+			case Operator.LeftShift:
+			case Operator.RightShift:
+				if (right.Type.IsEnum || left.Type.IsEnum)
+					break;
+				return left;
+			}
+
+			return null;
+		}
+
+		//
+		// The `|' operator used on types which were extended is dangerous
+		//
+		void CheckBitwiseOrOnSignExtended (ResolveContext ec)
+		{
+			OpcodeCast lcast = left as OpcodeCast;
+			if (lcast != null) {
+				if (IsUnsigned (lcast.UnderlyingType))
+					lcast = null;
+			}
+
+			OpcodeCast rcast = right as OpcodeCast;
+			if (rcast != null) {
+				if (IsUnsigned (rcast.UnderlyingType))
+					rcast = null;
+			}
+
+			if (lcast == null && rcast == null)
+				return;
+
+			// FIXME: consider constants
+
+			var ltype = lcast != null ? lcast.UnderlyingType : rcast.UnderlyingType;
+			ec.Report.Warning (675, 3, loc,
+				"The operator `|' used on the sign-extended type `{0}'. Consider casting to a smaller unsigned type first",
+				ltype.GetSignatureForError ());
+		}
+
+		public static PredefinedOperator[] CreatePointerOperatorsTable (BuiltinTypes types)
+		{
+			return new PredefinedOperator[] {
+				//
+				// Pointer arithmetic:
+				//
+				// T* operator + (T* x, int y);		T* operator - (T* x, int y);
+				// T* operator + (T* x, uint y);	T* operator - (T* x, uint y);
+				// T* operator + (T* x, long y);	T* operator - (T* x, long y);
+				// T* operator + (T* x, ulong y);	T* operator - (T* x, ulong y);
+				//
+				new PredefinedPointerOperator (null, types.Int, Operator.AdditionMask | Operator.SubtractionMask),
+				new PredefinedPointerOperator (null, types.UInt, Operator.AdditionMask | Operator.SubtractionMask),
+				new PredefinedPointerOperator (null, types.Long, Operator.AdditionMask | Operator.SubtractionMask),
+				new PredefinedPointerOperator (null, types.ULong, Operator.AdditionMask | Operator.SubtractionMask),
+
+				//
+				// T* operator + (int y,   T* x);
+				// T* operator + (uint y,  T *x);
+				// T* operator + (long y,  T *x);
+				// T* operator + (ulong y, T *x);
+				//
+				new PredefinedPointerOperator (types.Int, null, Operator.AdditionMask, null),
+				new PredefinedPointerOperator (types.UInt, null, Operator.AdditionMask, null),
+				new PredefinedPointerOperator (types.Long, null, Operator.AdditionMask, null),
+				new PredefinedPointerOperator (types.ULong, null, Operator.AdditionMask, null),
+
+				//
+				// long operator - (T* x, T *y)
+				//
+				new PredefinedPointerOperator (null, Operator.SubtractionMask, types.Long)
+			};
+		}
+
+		public static PredefinedOperator[] CreateStandardOperatorsTable (BuiltinTypes types)
+		{
+			TypeSpec bool_type = types.Bool;
+
+			return new [] {
+				new PredefinedOperator (types.Int, Operator.ArithmeticMask | Operator.BitwiseMask | Operator.ShiftMask),
+				new PredefinedOperator (types.UInt, Operator.ArithmeticMask | Operator.BitwiseMask),
+				new PredefinedOperator (types.Long, Operator.ArithmeticMask | Operator.BitwiseMask),
+				new PredefinedOperator (types.ULong, Operator.ArithmeticMask | Operator.BitwiseMask),
+				new PredefinedOperator (types.Float, Operator.ArithmeticMask),
+				new PredefinedOperator (types.Double, Operator.ArithmeticMask),
+				new PredefinedOperator (types.Decimal, Operator.ArithmeticMask),
+
+				new PredefinedOperator (types.Int, Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (types.UInt, Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (types.Long, Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (types.ULong, Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (types.Float, Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (types.Double, Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (types.Decimal, Operator.ComparisonMask, bool_type),
+
+				new PredefinedStringOperator (types.String, Operator.AdditionMask, types.String),
+				// Remaining string operators are in lifted tables
+
+				new PredefinedOperator (bool_type, Operator.BitwiseMask | Operator.LogicalMask | Operator.EqualityMask, bool_type),
+
+				new PredefinedOperator (types.UInt, types.Int, Operator.ShiftMask),
+				new PredefinedOperator (types.Long, types.Int, Operator.ShiftMask),
+				new PredefinedOperator (types.ULong, types.Int, Operator.ShiftMask)
+			};
+
+		}
+		public static PredefinedOperator[] CreateStandardLiftedOperatorsTable (ModuleContainer module)
+		{
+			var types = module.Compiler.BuiltinTypes;
+
+			//
+			// Not strictly lifted but need to be in second group otherwise expressions like
+			// int + null would resolve to +(object, string) instead of +(int?, int?)
+			//
+			var string_operators = new [] {
+				new PredefinedStringOperator (types.String, types.Object, Operator.AdditionMask, types.String),
+				new PredefinedStringOperator (types.Object, types.String, Operator.AdditionMask, types.String),
+			};
+
+			var nullable = module.PredefinedTypes.Nullable.TypeSpec;
+			if (nullable == null)
+				return string_operators;
+
+			var bool_type = types.Bool;
+
+			var nullable_bool = nullable.MakeGenericType (module, new[] { bool_type });
+			var nullable_int = nullable.MakeGenericType (module, new[] { types.Int });
+			var nullable_uint = nullable.MakeGenericType (module, new[] { types.UInt });
+			var nullable_long = nullable.MakeGenericType (module, new[] { types.Long });
+			var nullable_ulong = nullable.MakeGenericType (module, new[] { types.ULong });
+			var nullable_float = nullable.MakeGenericType (module, new[] { types.Float });
+			var nullable_double = nullable.MakeGenericType (module, new[] { types.Double });
+			var nullable_decimal = nullable.MakeGenericType (module, new[] { types.Decimal });
+
+			return new[] {
+				new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask | Operator.ShiftMask),
+				new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
+				new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
+				new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.ArithmeticMask | Operator.BitwiseMask),
+				new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.ArithmeticMask),
+				new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.ArithmeticMask),
+				new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.ArithmeticMask),
+
+				new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+				new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.ComparisonMask, bool_type),
+
+				new PredefinedOperator (nullable_bool, Operator.NullableMask | Operator.BitwiseMask, nullable_bool),
+
+				new PredefinedOperator (nullable_uint, nullable_int, Operator.NullableMask | Operator.ShiftMask),
+				new PredefinedOperator (nullable_long, nullable_int, Operator.NullableMask | Operator.ShiftMask),
+				new PredefinedOperator (nullable_ulong, nullable_int, Operator.NullableMask | Operator.ShiftMask),
+
+				string_operators [0],
+				string_operators [1]
+			};
+		}
+
+		public static PredefinedOperator[] CreateEqualityOperatorsTable (BuiltinTypes types)
+		{
+			TypeSpec bool_type = types.Bool;
+
+			return new[] {
+				new PredefinedEqualityOperator (types.String, bool_type),
+				new PredefinedEqualityOperator (types.Delegate, bool_type),
+				new PredefinedOperator (bool_type, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.Int, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.UInt, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.Long, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.ULong, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.Float, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.Double, Operator.EqualityMask, bool_type),
+				new PredefinedOperator (types.Decimal, Operator.EqualityMask, bool_type),
+			};
+		}
+
+		public static PredefinedOperator[] CreateEqualityLiftedOperatorsTable (ModuleContainer module)
+		{
+			var nullable = module.PredefinedTypes.Nullable.TypeSpec;
+
+			if (nullable == null)
+				return new PredefinedOperator [0];
+
+			var types = module.Compiler.BuiltinTypes;
+			var bool_type = types.Bool;
+			var nullable_bool = nullable.MakeGenericType (module, new [] { bool_type });
+			var nullable_int = nullable.MakeGenericType (module, new[] { types.Int });
+			var nullable_uint = nullable.MakeGenericType (module, new[] { types.UInt });
+			var nullable_long = nullable.MakeGenericType (module, new[] { types.Long });
+			var nullable_ulong = nullable.MakeGenericType (module, new[] { types.ULong });
+			var nullable_float = nullable.MakeGenericType (module, new[] { types.Float });
+			var nullable_double = nullable.MakeGenericType (module, new[] { types.Double });
+			var nullable_decimal = nullable.MakeGenericType (module, new[] { types.Decimal });
+
+			return new [] {
+				new PredefinedOperator (nullable_bool, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_int, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_uint, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_long, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_ulong, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_float, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_double, Operator.NullableMask | Operator.EqualityMask, bool_type),
+				new PredefinedOperator (nullable_decimal, Operator.NullableMask | Operator.EqualityMask, bool_type)
+			};
+		}
+
+		//
+		// 7.2.6.2 Binary numeric promotions
+		//
+		bool DoBinaryOperatorPromotion (ResolveContext rc)
+		{
+			TypeSpec ltype = left.Type;
+			if (ltype.IsNullableType) {
+				ltype = Nullable.NullableInfo.GetUnderlyingType (ltype);
+			}
+
+			//
+			// This is numeric promotion code only
+			//
+			if (ltype.BuiltinType == BuiltinTypeSpec.Type.Bool)
+				return true;
+
+			TypeSpec rtype = right.Type;
+			if (rtype.IsNullableType) {
+				rtype = Nullable.NullableInfo.GetUnderlyingType (rtype);
+			}
+
+			var lb = ltype.BuiltinType;
+			var rb = rtype.BuiltinType;
+			TypeSpec type;
+			Expression expr;
+
+			if (lb == BuiltinTypeSpec.Type.Decimal || rb == BuiltinTypeSpec.Type.Decimal) {
+				type = rc.BuiltinTypes.Decimal;
+			} else if (lb == BuiltinTypeSpec.Type.Double || rb == BuiltinTypeSpec.Type.Double) {
+				type = rc.BuiltinTypes.Double;
+			} else if (lb == BuiltinTypeSpec.Type.Float || rb == BuiltinTypeSpec.Type.Float) {
+				type = rc.BuiltinTypes.Float;
+			} else if (lb == BuiltinTypeSpec.Type.ULong || rb == BuiltinTypeSpec.Type.ULong) {
+				type = rc.BuiltinTypes.ULong;
+
+				if (IsSignedType (lb)) {
+					expr = ConvertSignedConstant (left, type);
+					if (expr == null)
+						return false;
+					left = expr;
+				} else if (IsSignedType (rb)) {
+					expr = ConvertSignedConstant (right, type);
+					if (expr == null)
+						return false;
+					right = expr;
+				}
+
+			} else if (lb == BuiltinTypeSpec.Type.Long || rb == BuiltinTypeSpec.Type.Long) {
+				type = rc.BuiltinTypes.Long;
+			} else if (lb == BuiltinTypeSpec.Type.UInt || rb == BuiltinTypeSpec.Type.UInt) {
+				type = rc.BuiltinTypes.UInt;
+
+				if (IsSignedType (lb)) {
+					expr = ConvertSignedConstant (left, type);
+					if (expr == null)
+						type = rc.BuiltinTypes.Long;
+				} else if (IsSignedType (rb)) {
+					expr = ConvertSignedConstant (right, type);
+					if (expr == null)
+						type = rc.BuiltinTypes.Long;
+				}
+			} else {
+				type = rc.BuiltinTypes.Int;
+			}
+
+			if (ltype != type) {
+				expr = PromoteExpression (rc, left, type);
+				if (expr == null)
+					return false;
+
+				left = expr;
+			}
+
+			if (rtype != type) {
+				expr = PromoteExpression (rc, right, type);
+				if (expr == null)
+					return false;
+
+				right = expr;
+			}
+
+			return true;
+		}
+
+		static bool IsSignedType (BuiltinTypeSpec.Type type)
+		{
+			switch (type) {
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Long:
+				return true;
+			default:
+				return false;
+			}
+		}
+
+		static Expression ConvertSignedConstant (Expression expr, TypeSpec type)
+		{
+			var c = expr as Constant;
+			if (c == null)
+				return null;
+
+			return c.ConvertImplicitly (type);
+		}
+
+		static Expression PromoteExpression (ResolveContext rc, Expression expr, TypeSpec type)
+		{
+			if (expr.Type.IsNullableType) {
+				return Convert.ImplicitConversionStandard (rc, expr,
+					rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc, new[] { type }), expr.Location);
+			}
+
+			var c = expr as Constant;
+			if (c != null)
+				return c.ConvertImplicitly (type);
+
+			return Convert.ImplicitNumericConversion (expr, type);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (left == null)
+				return null;
+
+			if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
+				left = ((ParenthesizedExpression) left).Expr;
+				left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
+				if (left == null)
+					return null;
+
+				if (left.eclass == ExprClass.Type) {
+					ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
+					return null;
+				}
+			} else
+				left = left.Resolve (ec);
+
+			if (left == null)
+				return null;
+
+			right = right.Resolve (ec);
+			if (right == null)
+				return null;
+
+			Constant lc = left as Constant;
+			Constant rc = right as Constant;
+
+			// The conversion rules are ignored in enum context but why
+			if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (left.Type.IsEnum || right.Type.IsEnum)) {
+				lc = EnumLiftUp (ec, lc, rc);
+				if (lc != null)
+					rc = EnumLiftUp (ec, rc, lc);
+			}
+
+			if (rc != null && lc != null) {
+				int prev_e = ec.Report.Errors;
+				Expression e = ConstantFold.BinaryFold (ec, oper, lc, rc, loc);
+				if (e != null || ec.Report.Errors != prev_e)
+					return e;
+			}
+
+			// Comparison warnings
+			if ((oper & Operator.ComparisonMask) != 0) {
+				if (left.Equals (right)) {
+					ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
+				}
+				CheckOutOfRangeComparison (ec, lc, right.Type);
+				CheckOutOfRangeComparison (ec, rc, left.Type);
+			}
+
+			if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic || right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+				return DoResolveDynamic (ec);
+
+			return DoResolveCore (ec, left, right);
+		}
+
+		Expression DoResolveDynamic (ResolveContext rc)
+		{
+			var lt = left.Type;
+			var rt = right.Type;
+			if (lt.Kind == MemberKind.Void || lt == InternalType.MethodGroup || lt == InternalType.AnonymousMethod ||
+				rt.Kind == MemberKind.Void || rt == InternalType.MethodGroup || rt == InternalType.AnonymousMethod) {
+				Error_OperatorCannotBeApplied (rc, left, right);
+				return null;
+			}
+
+			Arguments args;
+
+			//
+			// Special handling for logical boolean operators which require rhs not to be
+			// evaluated based on lhs value
+			//
+			if ((oper & Operator.LogicalMask) != 0) {
+				Expression cond_left, cond_right, expr;
+
+				args = new Arguments (2);
+
+				if (lt.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					LocalVariable temp = LocalVariable.CreateCompilerGenerated (lt, rc.CurrentBlock, loc);
+
+					var cond_args = new Arguments (1);
+					cond_args.Add (new Argument (new SimpleAssign (temp.CreateReferenceExpression (rc, loc), left).Resolve (rc)));
+
+					//
+					// dynamic && bool => IsFalse (temp = left) ? temp : temp && right;
+					// dynamic || bool => IsTrue (temp = left) ? temp : temp || right;
+					//
+					left = temp.CreateReferenceExpression (rc, loc);
+					if (oper == Operator.LogicalAnd) {
+						expr = DynamicUnaryConversion.CreateIsFalse (rc, cond_args, loc);
+						cond_left = left;
+					} else {
+						expr = DynamicUnaryConversion.CreateIsTrue (rc, cond_args, loc);
+						cond_left = left;
+					}
+
+					args.Add (new Argument (left));
+					args.Add (new Argument (right));
+					cond_right = new DynamicExpressionStatement (this, args, loc);
+				} else {
+					LocalVariable temp = LocalVariable.CreateCompilerGenerated (rc.BuiltinTypes.Bool, rc.CurrentBlock, loc);
+
+					if (!Convert.ImplicitConversionExists (rc, left, temp.Type) && (oper == Operator.LogicalAnd ? GetOperatorFalse (rc, left, loc) : GetOperatorTrue (rc, left, loc)) == null) {
+						rc.Report.Error (7083, left.Location,
+							"Expression must be implicitly convertible to Boolean or its type `{0}' must define operator `{1}'",
+							lt.GetSignatureForError (), oper == Operator.LogicalAnd ? "false" : "true");
+						return null;
+					}
+
+					args.Add (new Argument (temp.CreateReferenceExpression (rc, loc).Resolve (rc)));
+					args.Add (new Argument (right));
+					right = new DynamicExpressionStatement (this, args, loc);
+
+					//
+					// bool && dynamic => (temp = left) ? temp && right : temp;
+					// bool || dynamic => (temp = left) ? temp : temp || right;
+					//
+					if (oper == Operator.LogicalAnd) {
+						cond_left = right;
+						cond_right = temp.CreateReferenceExpression (rc, loc);
+					} else {
+						cond_left = temp.CreateReferenceExpression (rc, loc);
+						cond_right = right;
+					}
+
+					expr = new BooleanExpression (new SimpleAssign (temp.CreateReferenceExpression (rc, loc), left));
+				}
+
+				return new Conditional (expr, cond_left, cond_right, loc).Resolve (rc);
+			}
+
+			args = new Arguments (2);
+			args.Add (new Argument (left));
+			args.Add (new Argument (right));
+			return new DynamicExpressionStatement (this, args, loc).Resolve (rc);
+		}
+
+		Expression DoResolveCore (ResolveContext ec, Expression left_orig, Expression right_orig)
+		{
+			Expression expr = ResolveOperator (ec);
+			if (expr == null)
+				Error_OperatorCannotBeApplied (ec, left_orig, right_orig);
+
+			if (left == null || right == null)
+				throw new InternalErrorException ("Invalid conversion");
+
+			if (oper == Operator.BitwiseOr)
+				CheckBitwiseOrOnSignExtended (ec);
+
+			return expr;
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return MakeExpression (ctx, left, right);
+		}
+
+		public SLE.Expression MakeExpression (BuilderContext ctx, Expression left, Expression right)
+		{
+			var le = left.MakeExpression (ctx);
+			var re = right.MakeExpression (ctx);
+			bool is_checked = ctx.HasSet (BuilderContext.Options.CheckedScope);
+
+			switch (oper) {
+			case Operator.Addition:
+				return is_checked ? SLE.Expression.AddChecked (le, re) : SLE.Expression.Add (le, re);
+			case Operator.BitwiseAnd:
+				return SLE.Expression.And (le, re);
+			case Operator.BitwiseOr:
+				return SLE.Expression.Or (le, re);
+			case Operator.Division:
+				return SLE.Expression.Divide (le, re);
+			case Operator.Equality:
+				return SLE.Expression.Equal (le, re);
+			case Operator.ExclusiveOr:
+				return SLE.Expression.ExclusiveOr (le, re);
+			case Operator.GreaterThan:
+				return SLE.Expression.GreaterThan (le, re);
+			case Operator.GreaterThanOrEqual:
+				return SLE.Expression.GreaterThanOrEqual (le, re);
+			case Operator.Inequality:
+				return SLE.Expression.NotEqual (le, re);
+			case Operator.LeftShift:
+				return SLE.Expression.LeftShift (le, re);
+			case Operator.LessThan:
+				return SLE.Expression.LessThan (le, re);
+			case Operator.LessThanOrEqual:
+				return SLE.Expression.LessThanOrEqual (le, re);
+			case Operator.LogicalAnd:
+				return SLE.Expression.AndAlso (le, re);
+			case Operator.LogicalOr:
+				return SLE.Expression.OrElse (le, re);
+			case Operator.Modulus:
+				return SLE.Expression.Modulo (le, re);
+			case Operator.Multiply:
+				return is_checked ? SLE.Expression.MultiplyChecked (le, re) : SLE.Expression.Multiply (le, re);
+			case Operator.RightShift:
+				return SLE.Expression.RightShift (le, re);
+			case Operator.Subtraction:
+				return is_checked ? SLE.Expression.SubtractChecked (le, re) : SLE.Expression.Subtract (le, re);
+			default:
+				throw new NotImplementedException (oper.ToString ());
+			}
+		}
+
+		//
+		// D operator + (D x, D y)
+		// D operator - (D x, D y)
+		//
+		Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
+		{
+			if (l != r && !TypeSpecComparer.Variant.IsEqual (r, l)) {
+				Expression tmp;
+				if (right.eclass == ExprClass.MethodGroup || r == InternalType.AnonymousMethod || r == InternalType.NullLiteral) {
+					tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
+					if (tmp == null)
+						return null;
+					right = tmp;
+					r = right.Type;
+				} else if (left.eclass == ExprClass.MethodGroup || (l == InternalType.AnonymousMethod || l == InternalType.NullLiteral)) {
+					tmp = Convert.ImplicitConversionRequired (ec, left, r, loc);
+					if (tmp == null)
+						return null;
+					left = tmp;
+					l = left.Type;
+				} else {
+					return null;
+				}
+			}
+
+			MethodSpec method = null;
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (left));
+			args.Add (new Argument (right));
+
+			if (oper == Operator.Addition) {
+				method = ec.Module.PredefinedMembers.DelegateCombine.Resolve (loc);
+			} else if (oper == Operator.Subtraction) {
+				method = ec.Module.PredefinedMembers.DelegateRemove.Resolve (loc);
+			}
+
+			if (method == null)
+				return new EmptyExpression (ec.BuiltinTypes.Decimal);
+
+			Expression expr = new UserOperatorCall (method, args, CreateExpressionTree, loc);
+			return new ClassCast (expr, l);
+		}
+
+		//
+		// Resolves enumeration operators where only single predefined overload exists, handles lifted versions too
+		//
+		Expression ResolveSingleEnumOperators (ResolveContext rc, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
+		{
+			//
+			// bool operator == (E x, E y);
+			// bool operator != (E x, E y);
+			// bool operator < (E x, E y);
+			// bool operator > (E x, E y);
+			// bool operator <= (E x, E y);
+			// bool operator >= (E x, E y);
+			//
+			// E operator & (E x, E y);
+			// E operator | (E x, E y);
+			// E operator ^ (E x, E y);
+			//
+			Expression expr;
+			if ((oper & Operator.ComparisonMask) != 0) {
+				type = rc.BuiltinTypes.Bool;
+			} else {
+				if (lenum)
+					type = ltype;
+				else if (renum)
+					type = rtype;
+				else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum)
+					type = ltype;
+				else
+					type = rtype;
+			}
+
+			if (ltype == rtype) {
+				if (lenum || renum)
+					return this;
+
+				var lifted = new Nullable.LiftedBinaryOperator (this);
+				lifted.Left = left;
+				lifted.Right = right;
+				return lifted.Resolve (rc);
+			}
+
+			if (renum && !ltype.IsNullableType) {
+				expr = Convert.ImplicitConversion (rc, left, rtype, loc);
+				if (expr != null) {
+					left = expr;
+					return this;
+				}
+			} else if (lenum && !rtype.IsNullableType) {
+				expr = Convert.ImplicitConversion (rc, right, ltype, loc);
+				if (expr != null) {
+					right = expr;
+					return this;
+				}
+			}
+
+			//
+			// Now try lifted version of predefined operator
+			//
+			var nullable_type = rc.Module.PredefinedTypes.Nullable.TypeSpec;
+			if (nullable_type != null) {
+				if (renum && !ltype.IsNullableType) {
+					var lifted_type = nullable_type.MakeGenericType (rc.Module, new[] { rtype });
+
+					expr = Convert.ImplicitConversion (rc, left, lifted_type, loc);
+					if (expr != null) {
+						left = expr;
+						right = Convert.ImplicitConversion (rc, right, lifted_type, loc);
+					}
+
+					if ((oper & Operator.BitwiseMask) != 0)
+						type = lifted_type;
+
+					if (left.IsNull) {
+						if ((oper & Operator.BitwiseMask) != 0)
+							return Nullable.LiftedNull.CreateFromExpression (rc, this);
+
+						return CreateLiftedValueTypeResult (rc, rtype);
+					}
+
+					if (expr != null) {
+						var lifted = new Nullable.LiftedBinaryOperator (this);
+						lifted.Left = expr;
+						lifted.Right = right;
+						return lifted.Resolve (rc);
+					}
+				} else if (lenum && !rtype.IsNullableType) {
+					var lifted_type = nullable_type.MakeGenericType (rc.Module, new[] { ltype });
+
+					expr = Convert.ImplicitConversion (rc, right, lifted_type, loc);
+					if (expr != null) {
+						right = expr;
+						left = Convert.ImplicitConversion (rc, left, lifted_type, loc);
+					}
+
+					if ((oper & Operator.BitwiseMask) != 0)
+						type = lifted_type;
+
+					if (right.IsNull) {
+						if ((oper & Operator.BitwiseMask) != 0)
+							return Nullable.LiftedNull.CreateFromExpression (rc, this);
+
+						return CreateLiftedValueTypeResult (rc, ltype);
+					}
+
+					if (expr != null) {
+						var lifted = new Nullable.LiftedBinaryOperator (this);
+						lifted.Left = left;
+						lifted.Right = expr;
+						return lifted.Resolve (rc);
+					}
+				} else if (rtype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (rtype).IsEnum) {
+					Nullable.Unwrap unwrap = null;
+					if (left.IsNull || right.IsNull) {
+						if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
+							left = Convert.ImplicitConversion (rc, left, rtype, left.Location);
+
+						if ((oper & Operator.RelationalMask) != 0)
+							return CreateLiftedValueTypeResult (rc, rtype);
+
+						if ((oper & Operator.BitwiseMask) != 0)
+							return Nullable.LiftedNull.CreateFromExpression (rc, this);
+
+						if (right.IsNull)
+							return CreateLiftedValueTypeResult (rc, left.Type);
+
+						// Equality operators are valid between E? and null
+						expr = left;
+						unwrap = new Nullable.Unwrap (right);
+					} else {
+						expr = Convert.ImplicitConversion (rc, left, Nullable.NullableInfo.GetUnderlyingType (rtype), loc);
+						if (expr == null)
+							return null;
+					}
+
+					if (expr != null) {
+						var lifted = new Nullable.LiftedBinaryOperator (this);
+						lifted.Left = expr;
+						lifted.Right = right;
+						lifted.UnwrapRight = unwrap;
+						return lifted.Resolve (rc);
+					}
+				} else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum) {
+					Nullable.Unwrap unwrap = null;
+					if (right.IsNull || left.IsNull) {
+						if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
+							right = Convert.ImplicitConversion (rc, right, ltype, right.Location);
+
+						if ((oper & Operator.RelationalMask) != 0)
+							return CreateLiftedValueTypeResult (rc, ltype);
+
+						if ((oper & Operator.BitwiseMask) != 0)
+							return Nullable.LiftedNull.CreateFromExpression (rc, this);
+
+						if (left.IsNull)
+							return CreateLiftedValueTypeResult (rc, right.Type);
+
+						// Equality operators are valid between E? and null
+						expr = right;
+						unwrap = new Nullable.Unwrap (left);
+					} else {
+						expr = Convert.ImplicitConversion (rc, right, Nullable.NullableInfo.GetUnderlyingType (ltype), loc);
+						if (expr == null)
+							return null;
+					}
+
+					if (expr != null) {
+						var lifted = new Nullable.LiftedBinaryOperator (this);
+						lifted.Left = left;
+						lifted.UnwrapLeft = unwrap;
+						lifted.Right = expr;
+						return lifted.Resolve (rc);
+					}
+				}
+			}
+
+			return null;
+		}
+
+		static Expression ConvertEnumOperandToUnderlyingType (ResolveContext rc, Expression expr, bool liftType)
+		{
+			TypeSpec underlying_type;
+			if (expr.Type.IsNullableType) {
+				var nt = Nullable.NullableInfo.GetUnderlyingType (expr.Type);
+				if (nt.IsEnum)
+					underlying_type = EnumSpec.GetUnderlyingType (nt);
+				else
+					underlying_type = nt;
+			} else if (expr.Type.IsEnum) {
+				underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
+			} else {
+				underlying_type = expr.Type;
+			}
+
+			switch (underlying_type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+				underlying_type = rc.BuiltinTypes.Int;
+				break;
+			}
+
+			if (expr.Type.IsNullableType || liftType)
+				underlying_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { underlying_type });
+
+			if (expr.Type == underlying_type)
+				return expr;
+
+			return EmptyCast.Create (expr, underlying_type);
+		}
+
+		Expression ResolveEnumOperators (ResolveContext rc, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
+		{
+			//
+			// U operator - (E e, E f)
+			// E operator - (E e, U x)  // Internal decomposition operator
+			// E operator - (U x, E e)	// Internal decomposition operator
+			//
+			// E operator + (E e, U x)
+			// E operator + (U x, E e)
+			//
+
+			TypeSpec enum_type;
+
+			if (lenum)
+				enum_type = ltype;
+			else if (renum)
+				enum_type = rtype;
+			else if (ltype.IsNullableType && Nullable.NullableInfo.GetUnderlyingType (ltype).IsEnum)
+				enum_type = ltype;
+			else
+				enum_type = rtype;
+
+			Expression expr;
+			if (!enum_type.IsNullableType) {
+				expr = ResolveOperatorPredefined (rc, rc.Module.GetPredefinedEnumAritmeticOperators (enum_type, false), false);
+				if (expr != null) {
+					if (oper == Operator.Subtraction)
+						expr = ConvertEnumSubtractionResult (rc, expr);
+					else
+						expr = ConvertEnumAdditionalResult (expr, enum_type);
+
+					enum_conversion = GetEnumResultCast (expr.Type);
+
+					return expr;
+				}
+
+				enum_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { enum_type });
+			}
+
+			expr = ResolveOperatorPredefined (rc, rc.Module.GetPredefinedEnumAritmeticOperators (enum_type, true), false);
+			if (expr != null) {
+				if (oper == Operator.Subtraction)
+					expr = ConvertEnumSubtractionResult (rc, expr);
+				else
+					expr = ConvertEnumAdditionalResult (expr, enum_type);
+
+				enum_conversion = GetEnumResultCast (expr.Type);
+			}
+
+			return expr;
+		}
+
+		static Expression ConvertEnumAdditionalResult (Expression expr, TypeSpec enumType)
+		{
+			return EmptyCast.Create (expr, enumType);
+		}
+
+		Expression ConvertEnumSubtractionResult (ResolveContext rc, Expression expr)
+		{
+			//
+			// Enumeration subtraction has different result type based on
+			// best overload
+			//
+			TypeSpec result_type;
+			if (left.Type == right.Type) {
+				var c = right as EnumConstant;
+				if (c != null && c.IsZeroInteger && !right.Type.IsEnum) {
+					//
+					// LAMESPEC: This is quite unexpected for expression E - 0 the return type is
+					// E which is not what expressions E - 1 or 0 - E return
+					//
+					result_type = left.Type;
+				} else {
+					result_type = left.Type.IsNullableType ?
+						Nullable.NullableInfo.GetEnumUnderlyingType (rc.Module, left.Type) :
+						EnumSpec.GetUnderlyingType (left.Type);
+				}
+			} else {
+				if (IsEnumOrNullableEnum (left.Type)) {
+					result_type = left.Type;
+				} else {
+					result_type = right.Type;
+				}
+
+				if (expr is Nullable.LiftedBinaryOperator && !result_type.IsNullableType)
+					result_type = rc.Module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (rc.Module, new[] { result_type });
+			}
+
+			return EmptyCast.Create (expr, result_type);
+		}
+
+		public static ConvCast.Mode GetEnumResultCast (TypeSpec type)
+		{
+			if (type.IsNullableType)
+				type = Nullable.NullableInfo.GetUnderlyingType (type);
+
+			if (type.IsEnum)
+				type = EnumSpec.GetUnderlyingType (type);
+
+			switch (type.BuiltinType) {
+			case BuiltinTypeSpec.Type.SByte:
+				return ConvCast.Mode.I4_I1;
+			case BuiltinTypeSpec.Type.Byte:
+				return ConvCast.Mode.I4_U1;
+			case BuiltinTypeSpec.Type.Short:
+				return ConvCast.Mode.I4_I2;
+			case BuiltinTypeSpec.Type.UShort:
+				return ConvCast.Mode.I4_U2;
+			}
+
+			return 0;
+		}
+
+		//
+		// Equality operators rules
+		//
+		Expression ResolveEquality (ResolveContext ec, TypeSpec l, TypeSpec r, bool primitives_only)
+		{
+			Expression result;
+			type = ec.BuiltinTypes.Bool;
+			bool no_arg_conv = false;
+
+			if (!primitives_only) {
+
+				//
+				// a, Both operands are reference-type values or the value null
+				// b, One operand is a value of type T where T is a type-parameter and
+				// the other operand is the value null. Furthermore T does not have the
+				// value type constraint
+				//
+				// LAMESPEC: Very confusing details in the specification, basically any
+				// reference like type-parameter is allowed
+				//
+				var tparam_l = l as TypeParameterSpec;
+				var tparam_r = r as TypeParameterSpec;
+				if (tparam_l != null) {
+					if (right is NullLiteral) {
+						if (tparam_l.GetEffectiveBase ().BuiltinType == BuiltinTypeSpec.Type.ValueType)
+							return null;
+
+						left = new BoxedCast (left, ec.BuiltinTypes.Object);
+						return this;
+					}
+
+					if (!tparam_l.IsReferenceType)
+						return null;
+
+					l = tparam_l.GetEffectiveBase ();
+					left = new BoxedCast (left, l);
+				} else if (left is NullLiteral && tparam_r == null) {
+					if (TypeSpec.IsReferenceType (r))
+						return this;
+
+					if (r.Kind == MemberKind.InternalCompilerType)
+						return null;
+				}
+
+				if (tparam_r != null) {
+					if (left is NullLiteral) {
+						if (tparam_r.GetEffectiveBase ().BuiltinType == BuiltinTypeSpec.Type.ValueType)
+							return null;
+
+						right = new BoxedCast (right, ec.BuiltinTypes.Object);
+						return this;
+					}
+
+					if (!tparam_r.IsReferenceType)
+						return null;
+
+					r = tparam_r.GetEffectiveBase ();
+					right = new BoxedCast (right, r);
+				} else if (right is NullLiteral) {
+					if (TypeSpec.IsReferenceType (l))
+						return this;
+
+					if (l.Kind == MemberKind.InternalCompilerType)
+						return null;
+				}
+
+				//
+				// LAMESPEC: method groups can be compared when they convert to other side delegate
+				//
+				if (l.IsDelegate) {
+					if (right.eclass == ExprClass.MethodGroup) {
+						result = Convert.ImplicitConversion (ec, right, l, loc);
+						if (result == null)
+							return null;
+
+						right = result;
+						r = l;
+					} else if (r.IsDelegate && l != r) {
+						return null;
+					}
+				} else if (left.eclass == ExprClass.MethodGroup && r.IsDelegate) {
+					result = Convert.ImplicitConversionRequired (ec, left, r, loc);
+					if (result == null)
+						return null;
+
+					left = result;
+					l = r;
+				} else {
+					no_arg_conv = l == r && !l.IsStruct;
+				}
+			}
+
+			//
+			// bool operator != (string a, string b)
+			// bool operator == (string a, string b)
+			//
+			// bool operator != (Delegate a, Delegate b)
+			// bool operator == (Delegate a, Delegate b)
+			//
+			// bool operator != (bool a, bool b)
+			// bool operator == (bool a, bool b)
+			//
+			// LAMESPEC: Reference equality comparison can apply to value/reference types when
+			// they implement an implicit conversion to any of types above. This does
+			// not apply when both operands are of same reference type
+			//
+			if (r.BuiltinType != BuiltinTypeSpec.Type.Object && l.BuiltinType != BuiltinTypeSpec.Type.Object) {
+				result = ResolveOperatorPredefined (ec, ec.BuiltinTypes.OperatorsBinaryEquality, no_arg_conv);	
+				if (result != null)
+					return result;
+
+				//
+				// Now try lifted version of predefined operators
+				//
+				if (no_arg_conv && !l.IsNullableType) {
+					//
+					// Optimizes cases which won't match
+					//
+				} else {
+					result = ResolveOperatorPredefined (ec, ec.Module.OperatorsBinaryEqualityLifted, no_arg_conv);
+					if (result != null)
+						return result;
+				}
+
+				//
+				// The == and != operators permit one operand to be a value of a nullable
+				// type and the other to be the null literal, even if no predefined or user-defined
+				// operator (in unlifted or lifted form) exists for the operation.
+				//
+				if ((l.IsNullableType && right.IsNull) || (r.IsNullableType && left.IsNull)) {
+					var lifted = new Nullable.LiftedBinaryOperator (this);
+					lifted.Left = left;
+					lifted.Right = right;
+					return lifted.Resolve (ec);
+				}
+			}
+
+			//
+			// bool operator != (object a, object b)
+			// bool operator == (object a, object b)
+			//
+			// An explicit reference conversion exists from the
+			// type of either operand to the type of the other operand.
+			//
+
+			// Optimize common path
+			if (l == r) {
+				return l.Kind == MemberKind.InternalCompilerType || l.Kind == MemberKind.Struct ? null : this;
+			}
+
+			if (!Convert.ExplicitReferenceConversionExists (l, r) &&
+				!Convert.ExplicitReferenceConversionExists (r, l))
+				return null;
+
+			// Reject allowed explicit conversions like int->object
+			if (!TypeSpec.IsReferenceType (l) || !TypeSpec.IsReferenceType (r))
+				return null;
+
+			if (l.BuiltinType == BuiltinTypeSpec.Type.String || l.BuiltinType == BuiltinTypeSpec.Type.Delegate || l.IsDelegate || MemberCache.GetUserOperator (l, CSharp.Operator.OpType.Equality, false) != null)
+				ec.Report.Warning (253, 2, loc,
+					"Possible unintended reference comparison. Consider casting the right side expression to type `{0}' to get value comparison",
+					l.GetSignatureForError ());
+
+			if (r.BuiltinType == BuiltinTypeSpec.Type.String || r.BuiltinType == BuiltinTypeSpec.Type.Delegate || r.IsDelegate || MemberCache.GetUserOperator (r, CSharp.Operator.OpType.Equality, false) != null)
+				ec.Report.Warning (252, 2, loc,
+					"Possible unintended reference comparison. Consider casting the left side expression to type `{0}' to get value comparison",
+					r.GetSignatureForError ());
+
+			return this;
+		}
+
+
+		Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
+		{
+			//
+			// bool operator == (void* x, void* y);
+			// bool operator != (void* x, void* y);
+			// bool operator < (void* x, void* y);
+			// bool operator > (void* x, void* y);
+			// bool operator <= (void* x, void* y);
+			// bool operator >= (void* x, void* y);
+			//
+			if ((oper & Operator.ComparisonMask) != 0) {
+				Expression temp;
+				if (!l.IsPointer) {
+					temp = Convert.ImplicitConversion (ec, left, r, left.Location);
+					if (temp == null)
+						return null;
+					left = temp;
+				}
+
+				if (!r.IsPointer) {
+					temp = Convert.ImplicitConversion (ec, right, l, right.Location);
+					if (temp == null)
+						return null;
+					right = temp;
+				}
+
+				type = ec.BuiltinTypes.Bool;
+				return this;
+			}
+
+			return ResolveOperatorPredefined (ec, ec.BuiltinTypes.OperatorsBinaryUnsafe, false);
+		}
+
+		//
+		// Build-in operators method overloading
+		//
+		Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only)
+		{
+			PredefinedOperator best_operator = null;
+			TypeSpec l = left.Type;
+			TypeSpec r = right.Type;
+			Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
+
+			foreach (PredefinedOperator po in operators) {
+				if ((po.OperatorsMask & oper_mask) == 0)
+					continue;
+
+				if (primitives_only) {
+					if (!po.IsPrimitiveApplicable (l, r))
+						continue;
+				} else {
+					if (!po.IsApplicable (ec, left, right))
+						continue;
+				}
+
+				if (best_operator == null) {
+					best_operator = po;
+					if (primitives_only)
+						break;
+
+					continue;
+				}
+
+				best_operator = po.ResolveBetterOperator (ec, best_operator);
+
+				if (best_operator == null) {
+					ec.Report.Error (34, loc, "Operator `{0}' is ambiguous on operands of type `{1}' and `{2}'",
+						OperName (oper), l.GetSignatureForError (), r.GetSignatureForError ());
+
+					best_operator = po;
+					break;
+				}
+			}
+
+			if (best_operator == null)
+				return null;
+
+			return best_operator.ConvertResult (ec, this);
+		}
+
+		//
+		// Optimize & constant expressions with 0 value
+		//
+		Expression OptimizeAndOperation (Expression expr)
+		{
+			Constant rc = right as Constant;
+			Constant lc = left as Constant;
+			if ((lc != null && lc.IsDefaultValue) || (rc != null && rc.IsDefaultValue)) {
+				//
+				// The result is a constant with side-effect
+				//
+				Constant side_effect = rc == null ?
+					new SideEffectConstant (lc, right, loc) :
+					new SideEffectConstant (rc, left, loc);
+
+				return ReducedExpression.Create (side_effect, expr);
+			}
+
+			return expr;
+		}
+
+		//
+		// Value types can be compared with the null literal because of the lifting
+		// language rules. However the result is always true or false.
+		//
+		public Expression CreateLiftedValueTypeResult (ResolveContext rc, TypeSpec valueType)
+		{
+			if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
+				type = rc.BuiltinTypes.Bool;
+				return this;
+			}
+
+			// FIXME: Handle side effect constants
+			Constant c = new BoolConstant (rc.BuiltinTypes, Oper == Operator.Inequality, loc);
+
+			if ((Oper & Operator.EqualityMask) != 0) {
+				rc.Report.Warning (472, 2, loc, "The result of comparing value type `{0}' with null is always `{1}'",
+					valueType.GetSignatureForError (), c.GetValueAsLiteral ());
+			} else {
+				rc.Report.Warning (464, 2, loc, "The result of comparing type `{0}' with null is always `{1}'",
+					valueType.GetSignatureForError (), c.GetValueAsLiteral ());
+			}
+
+			return c;
+		}
+
+		//
+		// Performs user-operator overloading
+		//
+		Expression ResolveUserOperator (ResolveContext rc, Expression left, Expression right)
+		{
+			Expression oper_expr;
+
+			var op = ConvertBinaryToUserOperator (oper);
+			var l = left.Type;
+			if (l.IsNullableType)
+				l = Nullable.NullableInfo.GetUnderlyingType (l);
+			var r = right.Type;
+			if (r.IsNullableType)
+				r = Nullable.NullableInfo.GetUnderlyingType (r);
+
+			IList<MemberSpec> left_operators = MemberCache.GetUserOperator (l, op, false);
+			IList<MemberSpec> right_operators = null;
+
+			if (l != r) {
+				right_operators = MemberCache.GetUserOperator (r, op, false);
+				if (right_operators == null && left_operators == null)
+					return null;
+			} else if (left_operators == null) {
+				return null;
+			}
+
+			Arguments args = new Arguments (2);
+			Argument larg = new Argument (left);
+			args.Add (larg);	
+			Argument rarg = new Argument (right);
+			args.Add (rarg);
+
+			//
+			// User-defined operator implementations always take precedence
+			// over predefined operator implementations
+			//
+			if (left_operators != null && right_operators != null) {
+				left_operators = CombineUserOperators (left_operators, right_operators);
+			} else if (right_operators != null) {
+				left_operators = right_operators;
+			}
+
+			const OverloadResolver.Restrictions restr = OverloadResolver.Restrictions.ProbingOnly |
+				OverloadResolver.Restrictions.NoBaseMembers | OverloadResolver.Restrictions.BaseMembersIncluded;
+
+			var res = new OverloadResolver (left_operators, restr, loc);
+
+			var oper_method = res.ResolveOperator (rc, ref args);
+			if (oper_method == null) {
+				//
+				// Logical && and || cannot be lifted
+				//
+				if ((oper & Operator.LogicalMask) != 0)
+					return null;
+
+				//
+				// Apply lifted user operators only for liftable types. Implicit conversion
+				// to nullable types is not allowed
+				//
+				if (!IsLiftedOperatorApplicable ())
+					return null;
+
+				// TODO: Cache the result in module container
+				var lifted_methods = CreateLiftedOperators (rc, left_operators);
+				if (lifted_methods == null)
+					return null;
+
+				res = new OverloadResolver (lifted_methods, restr | OverloadResolver.Restrictions.ProbingOnly, loc);
+
+				oper_method = res.ResolveOperator (rc, ref args);
+				if (oper_method == null)
+					return null;
+
+				MethodSpec best_original = null;
+				foreach (MethodSpec ms in left_operators) {
+					if (ms.MemberDefinition == oper_method.MemberDefinition) {
+						best_original = ms;
+						break;
+					}
+				}
+
+				if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
+					//
+					// Expression trees use lifted notation in this case
+					//
+					this.left = Convert.ImplicitConversion (rc, left, oper_method.Parameters.Types[0], left.Location);
+					this.right = Convert.ImplicitConversion (rc, right, oper_method.Parameters.Types[1], left.Location);
+				}
+
+				var ptypes = best_original.Parameters.Types;
+
+				if (left.IsNull || right.IsNull) {
+					//
+					// The lifted operator produces a null value if one or both operands are null
+					//
+					if ((oper & (Operator.ArithmeticMask | Operator.ShiftMask | Operator.BitwiseMask)) != 0) {
+						type = oper_method.ReturnType;
+						return Nullable.LiftedNull.CreateFromExpression (rc, this);
+					}
+
+					//
+					// The lifted operator produces the value false if one or both operands are null for
+					// relational operators.
+					//
+					if ((oper & Operator.RelationalMask) != 0) {
+						//
+						// CSC BUG: This should be different warning, csc reports CS0458 with bool? which is wrong
+						// because return type is actually bool
+						//
+						return CreateLiftedValueTypeResult (rc, left.IsNull ? ptypes [1] : ptypes [0]);
+					}
+
+					if ((oper & Operator.EqualityMask) != 0 && ((left.IsNull && !right.Type.IsNullableType) || !left.Type.IsNullableType)) {
+						return CreateLiftedValueTypeResult (rc, left.IsNull ? ptypes [1] : ptypes [0]);
+					}
+				}
+
+				type = oper_method.ReturnType;
+				var lifted = new Nullable.LiftedBinaryOperator (this);
+				lifted.UserOperator = best_original;
+
+				if (left.Type.IsNullableType && !ptypes[0].IsNullableType) {
+					lifted.UnwrapLeft = new Nullable.Unwrap (left);
+				}
+
+				if (right.Type.IsNullableType && !ptypes[1].IsNullableType) {
+					lifted.UnwrapRight = new Nullable.Unwrap (right);
+				}
+
+				lifted.Left = Convert.ImplicitConversion (rc, lifted.UnwrapLeft ?? left, ptypes[0], left.Location);
+				lifted.Right = Convert.ImplicitConversion (rc, lifted.UnwrapRight ?? right, ptypes[1], right.Location);
+
+				return lifted.Resolve (rc);
+			}
+			
+			if ((oper & Operator.LogicalMask) != 0) {
+				// TODO: CreateExpressionTree is allocated every time		
+				oper_expr = new ConditionalLogicalOperator (oper_method, args, CreateExpressionTree,
+					oper == Operator.LogicalAnd, loc).Resolve (rc);
+			} else {
+				oper_expr = new UserOperatorCall (oper_method, args, CreateExpressionTree, loc);
+			}
+
+			this.left = larg.Expr;
+			this.right = rarg.Expr;
+
+			return oper_expr;
+		}
+
+		bool IsLiftedOperatorApplicable ()
+		{
+			if (left.Type.IsNullableType) {
+				if ((oper & Operator.EqualityMask) != 0)
+					return !right.IsNull;
+
+				return true;
+			}
+
+			if (right.Type.IsNullableType) {
+				if ((oper & Operator.EqualityMask) != 0)
+					return !left.IsNull;
+
+				return true;
+			}
+
+			if (TypeSpec.IsValueType (left.Type))
+				return right.IsNull;
+
+			if (TypeSpec.IsValueType (right.Type))
+				return left.IsNull;
+
+			return false;
+		}
+
+		List<MemberSpec> CreateLiftedOperators (ResolveContext rc, IList<MemberSpec> operators)
+		{
+			var nullable_type = rc.Module.PredefinedTypes.Nullable.TypeSpec;
+			if (nullable_type == null)
+				return null;
+
+			//
+			// Lifted operators permit predefined and user-defined operators that operate
+			// on non-nullable value types to also be used with nullable forms of those types.
+			// Lifted operators are constructed from predefined and user-defined operators
+			// that meet certain requirements
+			//
+			List<MemberSpec> lifted = null;
+			foreach (MethodSpec oper in operators) {
+				TypeSpec rt;
+				if ((Oper & Operator.ComparisonMask) != 0) {
+					//
+					// Result type must be of type bool for lifted comparison operators
+					//
+					rt = oper.ReturnType;
+					if (rt.BuiltinType != BuiltinTypeSpec.Type.Bool)
+						continue;
+				} else {
+					if (!TypeSpec.IsNonNullableValueType (oper.ReturnType))
+						continue;
+
+					rt = null;
+				}
+
+				var ptypes = oper.Parameters.Types;
+				if (!TypeSpec.IsNonNullableValueType (ptypes [0]) || !TypeSpec.IsNonNullableValueType (ptypes [1]))
+					continue;
+
+				//
+				// LAMESPEC: I am not sure why but for equality operators to be lifted
+				// both types have to match
+				//
+				if ((Oper & Operator.EqualityMask) != 0 && ptypes [0] != ptypes [1])
+					continue;
+
+				if (lifted == null)
+					lifted = new List<MemberSpec> ();
+
+				//
+				// The lifted form is constructed by adding a single ? modifier to each operand and
+				// result type except for comparison operators where return type is bool
+				//
+				if (rt == null)
+					rt = nullable_type.MakeGenericType (rc.Module, new[] { oper.ReturnType });
+
+				var parameters = ParametersCompiled.CreateFullyResolved (
+					nullable_type.MakeGenericType (rc.Module, new [] { ptypes[0] }),
+					nullable_type.MakeGenericType (rc.Module, new [] { ptypes[1] }));
+
+				var lifted_op = new MethodSpec (oper.Kind, oper.DeclaringType, oper.MemberDefinition,
+					rt, parameters, oper.Modifiers);
+
+				lifted.Add (lifted_op);
+			}
+
+			return lifted;
+		}
+
+		//
+		// Merge two sets of user operators into one, they are mostly distinguish
+		// except when they share base type and it contains an operator
+		//
+		static IList<MemberSpec> CombineUserOperators (IList<MemberSpec> left, IList<MemberSpec> right)
+		{
+			var combined = new List<MemberSpec> (left.Count + right.Count);
+			combined.AddRange (left);
+			foreach (var r in right) {
+				bool same = false;
+				foreach (var l in left) {
+					if (l.DeclaringType == r.DeclaringType) {
+						same = true;
+						break;
+					}
+				}
+
+				if (!same)
+					combined.Add (r);
+			}
+
+			return combined;
+		}
+
+		void CheckOutOfRangeComparison (ResolveContext ec, Constant c, TypeSpec type)
+		{
+			if (c is IntegralConstant || c is CharConstant) {
+				try {
+					c.ConvertExplicitly (true, type);
+				} catch (OverflowException) {
+					ec.Report.Warning (652, 2, loc,
+						"A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
+						type.GetSignatureForError ());
+				}
+			}
+		}
+
+		/// <remarks>
+		///   EmitBranchable is called from Statement.EmitBoolExpression in the
+		///   context of a conditional bool expression.  This function will return
+		///   false if it is was possible to use EmitBranchable, or true if it was.
+		///
+		///   The expression's code is generated, and we will generate a branch to `target'
+		///   if the resulting expression value is equal to isTrue
+		/// </remarks>
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
+				left = left.EmitToField (ec);
+
+				if ((oper & Operator.LogicalMask) == 0) {
+					right = right.EmitToField (ec);
+				}
+			}
+
+			//
+			// This is more complicated than it looks, but its just to avoid
+			// duplicated tests: basically, we allow ==, !=, >, <, >= and <=
+			// but on top of that we want for == and != to use a special path
+			// if we are comparing against null
+			//
+			if ((oper & Operator.EqualityMask) != 0 && (left is Constant || right is Constant)) {
+				bool my_on_true = oper == Operator.Inequality ? on_true : !on_true;
+				
+				//
+				// put the constant on the rhs, for simplicity
+				//
+				if (left is Constant) {
+					Expression swap = right;
+					right = left;
+					left = swap;
+				}
+				
+				//
+				// brtrue/brfalse works with native int only
+				//
+				if (((Constant) right).IsZeroInteger && right.Type.BuiltinType != BuiltinTypeSpec.Type.Long && right.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
+					left.EmitBranchable (ec, target, my_on_true);
+					return;
+				}
+				if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) {
+					// right is a boolean, and it's not 'false' => it is 'true'
+					left.EmitBranchable (ec, target, !my_on_true);
+					return;
+				}
+
+			} else if (oper == Operator.LogicalAnd) {
+
+				if (on_true) {
+					Label tests_end = ec.DefineLabel ();
+					
+					left.EmitBranchable (ec, tests_end, false);
+					right.EmitBranchable (ec, target, true);
+					ec.MarkLabel (tests_end);					
+				} else {
+					//
+					// This optimizes code like this 
+					// if (true && i > 4)
+					//
+					if (!(left is Constant))
+						left.EmitBranchable (ec, target, false);
+
+					if (!(right is Constant)) 
+						right.EmitBranchable (ec, target, false);
+				}
+				
+				return;
+				
+			} else if (oper == Operator.LogicalOr){
+				if (on_true) {
+					left.EmitBranchable (ec, target, true);
+					right.EmitBranchable (ec, target, true);
+					
+				} else {
+					Label tests_end = ec.DefineLabel ();
+					left.EmitBranchable (ec, tests_end, true);
+					right.EmitBranchable (ec, target, false);
+					ec.MarkLabel (tests_end);
+				}
+				
+				return;
+
+			} else if ((oper & Operator.ComparisonMask) == 0) {
+				base.EmitBranchable (ec, target, on_true);
+				return;
+			}
+			
+			left.Emit (ec);
+			right.Emit (ec);
+
+			TypeSpec t = left.Type;
+			bool is_float = IsFloat (t);
+			bool is_unsigned = is_float || IsUnsigned (t);
+			
+			switch (oper){
+			case Operator.Equality:
+				if (on_true)
+					ec.Emit (OpCodes.Beq, target);
+				else
+					ec.Emit (OpCodes.Bne_Un, target);
+				break;
+
+			case Operator.Inequality:
+				if (on_true)
+					ec.Emit (OpCodes.Bne_Un, target);
+				else
+					ec.Emit (OpCodes.Beq, target);
+				break;
+
+			case Operator.LessThan:
+				if (on_true)
+					if (is_unsigned && !is_float)
+						ec.Emit (OpCodes.Blt_Un, target);
+					else
+						ec.Emit (OpCodes.Blt, target);
+				else
+					if (is_unsigned)
+						ec.Emit (OpCodes.Bge_Un, target);
+					else
+						ec.Emit (OpCodes.Bge, target);
+				break;
+
+			case Operator.GreaterThan:
+				if (on_true)
+					if (is_unsigned && !is_float)
+						ec.Emit (OpCodes.Bgt_Un, target);
+					else
+						ec.Emit (OpCodes.Bgt, target);
+				else
+					if (is_unsigned)
+						ec.Emit (OpCodes.Ble_Un, target);
+					else
+						ec.Emit (OpCodes.Ble, target);
+				break;
+
+			case Operator.LessThanOrEqual:
+				if (on_true)
+					if (is_unsigned && !is_float)
+						ec.Emit (OpCodes.Ble_Un, target);
+					else
+						ec.Emit (OpCodes.Ble, target);
+				else
+					if (is_unsigned)
+						ec.Emit (OpCodes.Bgt_Un, target);
+					else
+						ec.Emit (OpCodes.Bgt, target);
+				break;
+
+
+			case Operator.GreaterThanOrEqual:
+				if (on_true)
+					if (is_unsigned && !is_float)
+						ec.Emit (OpCodes.Bge_Un, target);
+					else
+						ec.Emit (OpCodes.Bge, target);
+				else
+					if (is_unsigned)
+						ec.Emit (OpCodes.Blt_Un, target);
+					else
+						ec.Emit (OpCodes.Blt, target);
+				break;
+			default:
+				throw new InternalErrorException (oper.ToString ());
+			}
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			if (ec.HasSet (BuilderContext.Options.AsyncBody) && right.ContainsEmitWithAwait ()) {
+				left = left.EmitToField (ec);
+
+				if ((oper & Operator.LogicalMask) == 0) {
+					right = right.EmitToField (ec);
+				}
+			}
+
+			//
+			// Handle short-circuit operators differently
+			// than the rest
+			//
+			if ((oper & Operator.LogicalMask) != 0) {
+				Label load_result = ec.DefineLabel ();
+				Label end = ec.DefineLabel ();
+
+				bool is_or = oper == Operator.LogicalOr;
+				left.EmitBranchable (ec, load_result, is_or);
+				right.Emit (ec);
+				ec.Emit (OpCodes.Br_S, end);
+				
+				ec.MarkLabel (load_result);
+				ec.EmitInt (is_or ? 1 : 0);
+				ec.MarkLabel (end);
+				return;
+			}
+
+			//
+			// Optimize zero-based operations which cannot be optimized at expression level
+			//
+			if (oper == Operator.Subtraction) {
+				var lc = left as IntegralConstant;
+				if (lc != null && lc.IsDefaultValue) {
+					right.Emit (ec);
+					ec.Emit (OpCodes.Neg);
+					return;
+				}
+			}
+
+			EmitOperator (ec, left, right);
+		}
+
+		public void EmitOperator (EmitContext ec, Expression left, Expression right)
+		{
+			left.Emit (ec);
+			right.Emit (ec);
+
+			EmitOperatorOpcode (ec, oper, left.Type, right);
+
+			//
+			// Emit result enumerable conversion this way because it's quite complicated get it
+			// to resolved tree because expression tree cannot see it.
+			//
+			if (enum_conversion != 0)
+				ConvCast.Emit (ec, enum_conversion);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			if ((oper & Operator.LogicalMask) != 0 ||
+				(ec.HasSet (EmitContext.Options.CheckedScope) && (oper == Operator.Multiply || oper == Operator.Addition || oper == Operator.Subtraction))) {
+				base.EmitSideEffect (ec);
+			} else {
+				left.EmitSideEffect (ec);
+				right.EmitSideEffect (ec);
+			}
+		}
+
+		public override Expression EmitToField (EmitContext ec)
+		{
+			if ((oper & Operator.LogicalMask) == 0) {
+				var await_expr = left as Await;
+				if (await_expr != null && right.IsSideEffectFree) {
+					await_expr.Statement.EmitPrologue (ec);
+					left = await_expr.Statement.GetResultExpression (ec);
+					return this;
+				}
+
+				await_expr = right as Await;
+				if (await_expr != null && left.IsSideEffectFree) {
+					await_expr.Statement.EmitPrologue (ec);
+					right = await_expr.Statement.GetResultExpression (ec);
+					return this;
+				}
+			}
+
+			return base.EmitToField (ec);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Binary target = (Binary) t;
+
+			target.left = left.Clone (clonectx);
+			target.right = right.Clone (clonectx);
+		}
+
+		public Expression CreateCallSiteBinder (ResolveContext ec, Arguments args)
+		{
+			Arguments binder_args = new Arguments (4);
+
+			MemberAccess sle = new MemberAccess (new MemberAccess (
+				new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Linq", loc), "Expressions", loc);
+
+			CSharpBinderFlags flags = 0;
+			if (ec.HasSet (ResolveContext.Options.CheckedScope))
+				flags = CSharpBinderFlags.CheckedContext;
+
+			if ((oper & Operator.LogicalMask) != 0)
+				flags |= CSharpBinderFlags.BinaryOperationLogical;
+
+			binder_args.Add (new Argument (new EnumConstant (new IntLiteral (ec.BuiltinTypes, (int) flags, loc), ec.Module.PredefinedTypes.BinderFlags.Resolve ())));
+			binder_args.Add (new Argument (new MemberAccess (new MemberAccess (sle, "ExpressionType", loc), GetOperatorExpressionTypeName (), loc)));
+			binder_args.Add (new Argument (new TypeOf (ec.CurrentType, loc)));									
+			binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation (args.CreateDynamicBinderArguments (ec), loc)));
+
+			return new Invocation (new MemberAccess (new TypeExpression (ec.Module.PredefinedTypes.Binder.TypeSpec, loc), "BinaryOperation", loc), binder_args);
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return CreateExpressionTree (ec, null);
+		}
+
+		public Expression CreateExpressionTree (ResolveContext ec, Expression method)		
+		{
+			string method_name;
+			bool lift_arg = false;
+			
+			switch (oper) {
+			case Operator.Addition:
+				if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
+					method_name = "AddChecked";
+				else
+					method_name = "Add";
+				break;
+			case Operator.BitwiseAnd:
+				method_name = "And";
+				break;
+			case Operator.BitwiseOr:
+				method_name = "Or";
+				break;
+			case Operator.Division:
+				method_name = "Divide";
+				break;
+			case Operator.Equality:
+				method_name = "Equal";
+				lift_arg = true;
+				break;
+			case Operator.ExclusiveOr:
+				method_name = "ExclusiveOr";
+				break;				
+			case Operator.GreaterThan:
+				method_name = "GreaterThan";
+				lift_arg = true;
+				break;
+			case Operator.GreaterThanOrEqual:
+				method_name = "GreaterThanOrEqual";
+				lift_arg = true;
+				break;
+			case Operator.Inequality:
+				method_name = "NotEqual";
+				lift_arg = true;
+				break;
+			case Operator.LeftShift:
+				method_name = "LeftShift";
+				break;
+			case Operator.LessThan:
+				method_name = "LessThan";
+				lift_arg = true;
+				break;
+			case Operator.LessThanOrEqual:
+				method_name = "LessThanOrEqual";
+				lift_arg = true;
+				break;
+			case Operator.LogicalAnd:
+				method_name = "AndAlso";
+				break;
+			case Operator.LogicalOr:
+				method_name = "OrElse";
+				break;
+			case Operator.Modulus:
+				method_name = "Modulo";
+				break;
+			case Operator.Multiply:
+				if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
+					method_name = "MultiplyChecked";
+				else
+					method_name = "Multiply";
+				break;
+			case Operator.RightShift:
+				method_name = "RightShift";
+				break;
+			case Operator.Subtraction:
+				if (method == null && ec.HasSet (ResolveContext.Options.CheckedScope) && !IsFloat (type))
+					method_name = "SubtractChecked";
+				else
+					method_name = "Subtract";
+				break;
+
+			default:
+				throw new InternalErrorException ("Unknown expression tree binary operator " + oper);
+			}
+
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (left.CreateExpressionTree (ec)));
+			args.Add (new Argument (right.CreateExpressionTree (ec)));
+			if (method != null) {
+				if (lift_arg)
+					args.Add (new Argument (new BoolLiteral (ec.BuiltinTypes, false, loc)));
+
+				args.Add (new Argument (method));
+			}
+			
+			return CreateExpressionFactoryCall (ec, method_name, args);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+	}
+	
+	//
+	// Represents the operation a + b [+ c [+ d [+ ...]]], where a is a string
+	// b, c, d... may be strings or objects.
+	//
+	public class StringConcat : Expression
+	{
+		Arguments arguments;
+		
+		StringConcat (Location loc)
+		{
+			this.loc = loc;
+			arguments = new Arguments (2);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return arguments.ContainsEmitWithAwait ();
+		}
+
+		public static StringConcat Create (ResolveContext rc, Expression left, Expression right, Location loc)
+		{
+			if (left.eclass == ExprClass.Unresolved || right.eclass == ExprClass.Unresolved)
+				throw new ArgumentException ();
+
+			var s = new StringConcat (loc);
+			s.type = rc.BuiltinTypes.String;
+			s.eclass = ExprClass.Value;
+
+			s.Append (rc, left);
+			s.Append (rc, right);
+			return s;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Argument arg = arguments [0];
+			return CreateExpressionAddCall (ec, arg, arg.CreateExpressionTree (ec), 1);
+		}
+
+		//
+		// Creates nested calls tree from an array of arguments used for IL emit
+		//
+		Expression CreateExpressionAddCall (ResolveContext ec, Argument left, Expression left_etree, int pos)
+		{
+			Arguments concat_args = new Arguments (2);
+			Arguments add_args = new Arguments (3);
+
+			concat_args.Add (left);
+			add_args.Add (new Argument (left_etree));
+
+			concat_args.Add (arguments [pos]);
+			add_args.Add (new Argument (arguments [pos].CreateExpressionTree (ec)));
+
+			var methods = GetConcatMethodCandidates ();
+			if (methods == null)
+				return null;
+
+			var res = new OverloadResolver (methods, OverloadResolver.Restrictions.NoBaseMembers, loc);
+			var method = res.ResolveMember<MethodSpec> (ec, ref concat_args);
+			if (method == null)
+				return null;
+
+			add_args.Add (new Argument (new TypeOfMethod (method, loc)));
+
+			Expression expr = CreateExpressionFactoryCall (ec, "Add", add_args);
+			if (++pos == arguments.Count)
+				return expr;
+
+			left = new Argument (new EmptyExpression (method.ReturnType));
+			return CreateExpressionAddCall (ec, left, expr, pos);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return this;
+		}
+		
+		void Append (ResolveContext rc, Expression operand)
+		{
+			//
+			// Constant folding
+			//
+			StringConstant sc = operand as StringConstant;
+			if (sc != null) {
+				if (arguments.Count != 0) {
+					Argument last_argument = arguments [arguments.Count - 1];
+					StringConstant last_expr_constant = last_argument.Expr as StringConstant;
+					if (last_expr_constant != null) {
+						last_argument.Expr = new StringConstant (rc.BuiltinTypes, last_expr_constant.Value + sc.Value, sc.Location);
+						return;
+					}
+				}
+			} else {
+				//
+				// Multiple (3+) concatenation are resolved as multiple StringConcat instances
+				//
+				StringConcat concat_oper = operand as StringConcat;
+				if (concat_oper != null) {
+					arguments.AddRange (concat_oper.arguments);
+					return;
+				}
+			}
+
+			arguments.Add (new Argument (operand));
+		}
+
+		IList<MemberSpec> GetConcatMethodCandidates ()
+		{
+			return MemberCache.FindMembers (type, "Concat", true);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// Optimize by removing any extra null arguments, they are no-op
+			for (int i = 0; i < arguments.Count; ++i) {
+				if (arguments[i].Expr is NullConstant)
+					arguments.RemoveAt (i--);
+			}
+
+			var members = GetConcatMethodCandidates ();
+			var res = new OverloadResolver (members, OverloadResolver.Restrictions.NoBaseMembers, loc);
+			var method = res.ResolveMember<MethodSpec> (new ResolveContext (ec.MemberContext), ref arguments);
+			if (method != null) {
+				var call = new CallEmitter ();
+				call.EmitPredefined (ec, method, arguments, false);
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			arguments.FlowAnalysis (fc);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			if (arguments.Count != 2)
+				throw new NotImplementedException ("arguments.Count != 2");
+
+			var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
+			return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
+		}
+	}
+
+	//
+	// User-defined conditional logical operator
+	//
+	public class ConditionalLogicalOperator : UserOperatorCall
+	{
+		readonly bool is_and;
+		Expression oper_expr;
+
+		public ConditionalLogicalOperator (MethodSpec oper, Arguments arguments, Func<ResolveContext, Expression, Expression> expr_tree, bool is_and, Location loc)
+			: base (oper, arguments, expr_tree, loc)
+		{
+			this.is_and = is_and;
+			eclass = ExprClass.Unresolved;
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			AParametersCollection pd = oper.Parameters;
+			if (!TypeSpecComparer.IsEqual (type, pd.Types[0]) || !TypeSpecComparer.IsEqual (type, pd.Types[1])) {
+				ec.Report.Error (217, loc,
+					"A user-defined operator `{0}' must have each parameter type and return type of the same type in order to be applicable as a short circuit operator",
+					oper.GetSignatureForError ());
+				return null;
+			}
+
+			Expression left_dup = new EmptyExpression (type);
+			Expression op_true = GetOperatorTrue (ec, left_dup, loc);
+			Expression op_false = GetOperatorFalse (ec, left_dup, loc);
+			if (op_true == null || op_false == null) {
+				ec.Report.Error (218, loc,
+					"The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
+					type.GetSignatureForError (), oper.GetSignatureForError ());
+				return null;
+			}
+
+			oper_expr = is_and ? op_false : op_true;
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Label end_target = ec.DefineLabel ();
+
+			//
+			// Emit and duplicate left argument
+			//
+			bool right_contains_await = ec.HasSet (BuilderContext.Options.AsyncBody) && arguments[1].Expr.ContainsEmitWithAwait ();
+			if (right_contains_await) {
+				arguments[0] = arguments[0].EmitToField (ec, false);
+				arguments[0].Expr.Emit (ec);
+			} else {
+				arguments[0].Expr.Emit (ec);
+				ec.Emit (OpCodes.Dup);
+				arguments.RemoveAt (0);
+			}
+
+			oper_expr.EmitBranchable (ec, end_target, true);
+
+			base.Emit (ec);
+
+			if (right_contains_await) {
+				//
+				// Special handling when right expression contains await and left argument
+				// could not be left on stack before logical branch
+				//
+				Label skip_left_load = ec.DefineLabel ();
+				ec.Emit (OpCodes.Br_S, skip_left_load);
+				ec.MarkLabel (end_target);
+				arguments[0].Expr.Emit (ec);
+				ec.MarkLabel (skip_left_load);
+			} else {
+				ec.MarkLabel (end_target);
+			}
+		}
+	}
+
+	public class PointerArithmetic : Expression {
+		Expression left, right;
+		readonly Binary.Operator op;
+
+		//
+		// We assume that `l' is always a pointer
+		//
+		public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
+		{
+			type = t;
+			this.loc = loc;
+			left = l;
+			right = r;
+			this.op = op;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Error_PointerInsideExpressionTree (ec);
+			return null;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Variable;
+
+			var pc = left.Type as PointerContainer;
+			if (pc != null && pc.Element.Kind == MemberKind.Void) {
+				Error_VoidPointerOperation (ec);
+				return null;
+			}
+			
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			TypeSpec op_type = left.Type;
+			
+			// It must be either array or fixed buffer
+			TypeSpec element;
+			if (TypeManager.HasElementType (op_type)) {
+				element = TypeManager.GetElementType (op_type);
+			} else {
+				FieldExpr fe = left as FieldExpr;
+				if (fe != null)
+					element = ((FixedFieldSpec) (fe.Spec)).ElementType;
+				else
+					element = op_type;
+			}
+
+			int size = BuiltinTypeSpec.GetSize(element);
+			TypeSpec rtype = right.Type;
+			
+			if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
+				//
+				// handle (pointer - pointer)
+				//
+				left.Emit (ec);
+				right.Emit (ec);
+				ec.Emit (OpCodes.Sub);
+
+				if (size != 1){
+					if (size == 0)
+						ec.Emit (OpCodes.Sizeof, element);
+					else 
+						ec.EmitInt (size);
+					ec.Emit (OpCodes.Div);
+				}
+				ec.Emit (OpCodes.Conv_I8);
+			} else {
+				//
+				// handle + and - on (pointer op int)
+				//
+				Constant left_const = left as Constant;
+				if (left_const != null) {
+					//
+					// Optimize ((T*)null) pointer operations
+					//
+					if (left_const.IsDefaultValue) {
+						left = EmptyExpression.Null;
+					} else {
+						left_const = null;
+					}
+				}
+
+				left.Emit (ec);
+
+				var right_const = right as Constant;
+				if (right_const != null) {
+					//
+					// Optimize 0-based arithmetic
+					//
+					if (right_const.IsDefaultValue)
+						return;
+
+					if (size != 0)
+						right = new IntConstant (ec.BuiltinTypes, size, right.Location);
+					else
+						right = new SizeOf (new TypeExpression (element, right.Location), right.Location);
+					
+					// TODO: Should be the checks resolve context sensitive?
+					ResolveContext rc = new ResolveContext (ec.MemberContext, ResolveContext.Options.UnsafeScope);
+					right = new Binary (Binary.Operator.Multiply, right, right_const).Resolve (rc);
+					if (right == null)
+						return;
+				}
+
+				right.Emit (ec);
+				switch (rtype.BuiltinType) {
+				case BuiltinTypeSpec.Type.SByte:
+				case BuiltinTypeSpec.Type.Byte:
+				case BuiltinTypeSpec.Type.Short:
+				case BuiltinTypeSpec.Type.UShort:
+					ec.Emit (OpCodes.Conv_I);
+					break;
+				case BuiltinTypeSpec.Type.UInt:
+					ec.Emit (OpCodes.Conv_U);
+					break;
+				}
+
+				if (right_const == null && size != 1){
+					if (size == 0)
+						ec.Emit (OpCodes.Sizeof, element);
+					else 
+						ec.EmitInt (size);
+					if (rtype.BuiltinType == BuiltinTypeSpec.Type.Long || rtype.BuiltinType == BuiltinTypeSpec.Type.ULong)
+						ec.Emit (OpCodes.Conv_I8);
+
+					Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype, right);
+				}
+
+				if (left_const == null) {
+					if (rtype.BuiltinType == BuiltinTypeSpec.Type.Long)
+						ec.Emit (OpCodes.Conv_I);
+					else if (rtype.BuiltinType == BuiltinTypeSpec.Type.ULong)
+						ec.Emit (OpCodes.Conv_U);
+
+					Binary.EmitOperatorOpcode (ec, op, op_type, right);
+				}
+			}
+		}
+	}
+
+	//
+	// A boolean-expression is an expression that yields a result
+	// of type bool
+	//
+	public class BooleanExpression : ShimExpression
+	{
+		public BooleanExpression (Expression expr)
+			: base (expr)
+		{
+			this.loc = expr.Location;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			// TODO: We should emit IsTrue (v4) instead of direct user operator
+			// call but that would break csc compatibility
+			return base.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// A boolean-expression is required to be of a type
+			// that can be implicitly converted to bool or of
+			// a type that implements operator true
+
+			expr = expr.Resolve (ec);
+			if (expr == null)
+				return null;
+
+			Assign ass = expr as Assign;
+			if (ass != null && ass.Source is Constant) {
+				ec.Report.Warning (665, 3, loc,
+					"Assignment in conditional expression is always constant. Did you mean to use `==' instead ?");
+			}
+
+			if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Bool)
+				return expr;
+
+			if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (expr));
+				return DynamicUnaryConversion.CreateIsTrue (ec, args, loc).Resolve (ec);
+			}
+
+			type = ec.BuiltinTypes.Bool;
+			Expression converted = Convert.ImplicitConversion (ec, expr, type, loc);
+			if (converted != null)
+				return converted;
+
+			//
+			// If no implicit conversion to bool exists, try using `operator true'
+			//
+			converted = GetOperatorTrue (ec, expr, loc);
+			if (converted == null) {
+				expr.Error_ValueCannotBeConverted (ec, type, false);
+				return null;
+			}
+
+			return converted;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class BooleanExpressionFalse : Unary
+	{
+		public BooleanExpressionFalse (Expression expr)
+			: base (Operator.LogicalNot, expr, expr.Location)
+		{
+		}
+
+		protected override Expression ResolveOperator (ResolveContext ec, Expression expr)
+		{
+			return GetOperatorFalse (ec, expr, loc) ?? base.ResolveOperator (ec, expr);
+		}
+	}
+	
+	/// <summary>
+	///   Implements the ternary conditional operator (?:)
+	/// </summary>
+	public class Conditional : Expression {
+		Expression expr, true_expr, false_expr;
+
+		public Conditional (Expression expr, Expression true_expr, Expression false_expr, Location loc)
+		{
+			this.expr = expr;
+			this.true_expr = true_expr;
+			this.false_expr = false_expr;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		public Expression TrueExpr {
+			get {
+				return true_expr;
+			}
+		}
+
+		public Expression FalseExpr {
+			get {
+				return false_expr;
+			}
+		}
+
+		#endregion
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return Expr.ContainsEmitWithAwait () || true_expr.ContainsEmitWithAwait () || false_expr.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (3);
+			args.Add (new Argument (expr.CreateExpressionTree (ec)));
+			args.Add (new Argument (true_expr.CreateExpressionTree (ec)));
+			args.Add (new Argument (false_expr.CreateExpressionTree (ec)));
+			return CreateExpressionFactoryCall (ec, "Condition", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			expr = expr.Resolve (ec);
+			true_expr = true_expr.Resolve (ec);
+			false_expr = false_expr.Resolve (ec);
+
+			if (true_expr == null || false_expr == null || expr == null)
+				return null;
+
+			eclass = ExprClass.Value;
+			TypeSpec true_type = true_expr.Type;
+			TypeSpec false_type = false_expr.Type;
+			type = true_type;
+
+			//
+			// First, if an implicit conversion exists from true_expr
+			// to false_expr, then the result type is of type false_expr.Type
+			//
+			if (!TypeSpecComparer.IsEqual (true_type, false_type)) {
+				Expression conv = Convert.ImplicitConversion (ec, true_expr, false_type, loc);
+				if (conv != null && true_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
+					//
+					// Check if both can convert implicitly to each other's type
+					//
+					type = false_type;
+
+					if (false_type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
+						var conv_false_expr = Convert.ImplicitConversion (ec, false_expr, true_type, loc);
+						//
+						// LAMESPEC: There seems to be hardcoded promotition to int type when
+						// both sides are numeric constants and one side is int constant and
+						// other side is numeric constant convertible to int.
+						//
+						// var res = condition ? (short)1 : 1;
+						//
+						// Type of res is int even if according to the spec the conversion is
+						// ambiguous because 1 literal can be converted to short.
+						//
+						if (conv_false_expr != null) {
+							if (conv_false_expr.Type.BuiltinType == BuiltinTypeSpec.Type.Int && conv is Constant) {
+								type = true_type;
+								conv_false_expr = null;
+							} else if (type.BuiltinType == BuiltinTypeSpec.Type.Int && conv_false_expr is Constant) {
+								conv_false_expr = null;
+							}
+						}
+
+						if (conv_false_expr != null) {
+							ec.Report.Error (172, true_expr.Location,
+								"Type of conditional expression cannot be determined as `{0}' and `{1}' convert implicitly to each other",
+									true_type.GetSignatureForError (), false_type.GetSignatureForError ());
+						}
+					}
+
+					true_expr = conv;
+					if (true_expr.Type != type)
+						true_expr = EmptyCast.Create (true_expr, type);
+				} else if ((conv = Convert.ImplicitConversion (ec, false_expr, true_type, loc)) != null) {
+					false_expr = conv;
+				} else {
+					ec.Report.Error (173, true_expr.Location,
+						"Type of conditional expression cannot be determined because there is no implicit conversion between `{0}' and `{1}'",
+						true_type.GetSignatureForError (), false_type.GetSignatureForError ());
+					return null;
+				}
+			}
+
+			Constant c = expr as Constant;
+			if (c != null) {
+				bool is_false = c.IsDefaultValue;
+
+				//
+				// Don't issue the warning for constant expressions
+				//
+				if (!(is_false ? true_expr is Constant : false_expr is Constant)) {
+					// CSC: Missing warning
+					Warning_UnreachableExpression (ec, is_false ? true_expr.Location : false_expr.Location);
+				}
+
+				return ReducedExpression.Create (
+					is_false ? false_expr : true_expr, this,
+					false_expr is Constant && true_expr is Constant).Resolve (ec);
+			}
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Label false_target = ec.DefineLabel ();
+			Label end_target = ec.DefineLabel ();
+
+			expr.EmitBranchable (ec, false_target, false);
+			true_expr.Emit (ec);
+
+			//
+			// Verifier doesn't support interface merging. When there are two types on
+			// the stack without common type hint and the common type is an interface.
+			// Use temporary local to give verifier hint on what type to unify the stack
+			//
+			if (type.IsInterface && true_expr is EmptyCast && false_expr is EmptyCast) {
+				var temp = ec.GetTemporaryLocal (type);
+				ec.Emit (OpCodes.Stloc, temp);
+				ec.Emit (OpCodes.Ldloc, temp);
+				ec.FreeTemporaryLocal (temp, type);
+			}
+
+			ec.Emit (OpCodes.Br, end_target);
+			ec.MarkLabel (false_target);
+			false_expr.Emit (ec);
+			ec.MarkLabel (end_target);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysisConditional (fc);
+			var expr_true = fc.DefiniteAssignmentOnTrue;
+			var expr_false = fc.DefiniteAssignmentOnFalse;
+
+			fc.DefiniteAssignment = new DefiniteAssignmentBitSet (expr_true);
+			true_expr.FlowAnalysis (fc);
+			var true_fc = fc.DefiniteAssignment;
+
+			fc.DefiniteAssignment = new DefiniteAssignmentBitSet (expr_false);
+			false_expr.FlowAnalysis (fc);
+
+			fc.DefiniteAssignment &= true_fc;
+		}
+
+		public override void FlowAnalysisConditional (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysisConditional (fc);
+			var expr_true = fc.DefiniteAssignmentOnTrue;
+			var expr_false = fc.DefiniteAssignmentOnFalse;
+
+			fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (expr_true);
+			true_expr.FlowAnalysisConditional (fc);
+			var true_fc = fc.DefiniteAssignment;
+			var true_da_true = fc.DefiniteAssignmentOnTrue;
+			var true_da_false = fc.DefiniteAssignmentOnFalse;
+
+			fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment = new DefiniteAssignmentBitSet (expr_false);
+			false_expr.FlowAnalysisConditional (fc);
+
+			fc.DefiniteAssignment &= true_fc;
+			fc.DefiniteAssignmentOnTrue = true_da_true & fc.DefiniteAssignmentOnTrue;
+			fc.DefiniteAssignmentOnFalse = true_da_false & fc.DefiniteAssignmentOnFalse;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Conditional target = (Conditional) t;
+
+			target.expr = expr.Clone (clonectx);
+			target.true_expr = true_expr.Clone (clonectx);
+			target.false_expr = false_expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public abstract class VariableReference : Expression, IAssignMethod, IMemoryLocation, IVariableReference
+	{
+		LocalTemporary temp;
+
+		#region Abstract
+		public abstract HoistedVariable GetHoistedVariable (AnonymousExpression ae);
+		public abstract void SetHasAddressTaken ();
+
+		public abstract bool IsLockedByStatement { get; set; }
+
+		public abstract bool IsFixed { get; }
+		public abstract bool IsRef { get; }
+		public abstract string Name { get; }
+
+		//
+		// Variable IL data, it has to be protected to encapsulate hoisted variables
+		//
+		protected abstract ILocalVariable Variable { get; }
+		
+		//
+		// Variable flow-analysis data
+		//
+		public abstract VariableInfo VariableInfo { get; }
+		#endregion
+
+		public virtual void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			HoistedVariable hv = GetHoistedVariable (ec);
+			if (hv != null) {
+				hv.AddressOf (ec, mode);
+				return;
+			}
+
+			Variable.EmitAddressOf (ec);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			HoistedVariable hv = GetHoistedVariable (ec);
+			if (hv != null)
+				return hv.CreateExpressionTree ();
+
+			Arguments arg = new Arguments (1);
+			arg.Add (new Argument (this));
+			return CreateExpressionFactoryCall (ec, "Constant", arg);
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			if (IsLockedByStatement) {
+				rc.Report.Warning (728, 2, loc,
+					"Possibly incorrect assignment to `{0}' which is the argument to a using or lock statement",
+					Name);
+			}
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Emit (ec, false);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			// do nothing
+		}
+
+		//
+		// This method is used by parameters that are references, that are
+		// being passed as references:  we only want to pass the pointer (that
+		// is already stored in the parameter, not the address of the pointer,
+		// and not the value of the variable).
+		//
+		public void EmitLoad (EmitContext ec)
+		{
+			Variable.Emit (ec);
+		}
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			HoistedVariable hv = GetHoistedVariable (ec);
+			if (hv != null) {
+				hv.Emit (ec, leave_copy);
+				return;
+			}
+
+			EmitLoad (ec);
+
+			if (IsRef) {
+				//
+				// If we are a reference, we loaded on the stack a pointer
+				// Now lets load the real value
+				//
+				ec.EmitLoadFromPtr (type);
+			}
+
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+
+				if (IsRef) {
+					temp = new LocalTemporary (Type);
+					temp.Store (ec);
+				}
+			}
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy,
+					bool prepare_for_load)
+		{
+			HoistedVariable hv = GetHoistedVariable (ec);
+			if (hv != null) {
+				hv.EmitAssign (ec, source, leave_copy, prepare_for_load);
+				return;
+			}
+
+			New n_source = source as New;
+			if (n_source != null) {
+				if (!n_source.Emit (ec, this)) {
+					if (leave_copy) {
+						EmitLoad (ec);
+						if (IsRef)
+							ec.EmitLoadFromPtr (type);
+					}
+					return;
+				}
+			} else {
+				if (IsRef)
+					EmitLoad (ec);
+
+				source.Emit (ec);
+			}
+
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				if (IsRef) {
+					temp = new LocalTemporary (Type);
+					temp.Store (ec);
+				}
+			}
+
+			if (IsRef)
+				ec.EmitStoreFromPtr (type);
+			else
+				Variable.EmitAssign (ec);
+
+			if (temp != null) {
+				temp.Emit (ec);
+				temp.Release (ec);
+			}
+		}
+
+		public override Expression EmitToField (EmitContext ec)
+		{
+			HoistedVariable hv = GetHoistedVariable (ec);
+			if (hv != null) {
+				return hv.EmitToField (ec);
+			}
+
+			return base.EmitToField (ec);
+		}
+
+		public HoistedVariable GetHoistedVariable (ResolveContext rc)
+		{
+			return GetHoistedVariable (rc.CurrentAnonymousMethod);
+		}
+
+		public HoistedVariable GetHoistedVariable (EmitContext ec)
+		{
+			return GetHoistedVariable (ec.CurrentAnonymousMethod);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return Name;
+		}
+
+		public bool IsHoisted {
+			get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
+		}
+	}
+
+	//
+	// Resolved reference to a local variable
+	//
+	public class LocalVariableReference : VariableReference
+	{
+		public LocalVariable local_info;
+
+		public LocalVariableReference (LocalVariable li, Location l)
+		{
+			this.local_info = li;
+			loc = l;
+		}
+
+		public override VariableInfo VariableInfo {
+			get { return local_info.VariableInfo; }
+		}
+
+		public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
+		{
+			return local_info.HoistedVariant;
+		}
+
+		#region Properties
+
+		//		
+		// A local variable is always fixed
+		//
+		public override bool IsFixed {
+			get {
+				return true;
+			}
+		}
+
+		public override bool IsLockedByStatement {
+			get {
+				return local_info.IsLocked;
+			}
+			set {
+				local_info.IsLocked = value;
+			}
+		}
+
+		public override bool IsRef {
+			get { return false; }
+		}
+
+		public override string Name {
+			get { return local_info.Name; }
+		}
+
+		#endregion
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			VariableInfo variable_info = VariableInfo;
+			if (variable_info == null)
+				return;
+
+			if (fc.IsDefinitelyAssigned (variable_info))
+				return;
+
+			fc.Report.Error (165, loc, "Use of unassigned local variable `{0}'", Name);
+			variable_info.SetAssigned (fc.DefiniteAssignment, true);
+		}
+
+		public override void SetHasAddressTaken ()
+		{
+			local_info.SetHasAddressTaken ();
+		}
+
+		void DoResolveBase (ResolveContext ec)
+		{
+			//
+			// If we are referencing a variable from the external block
+			// flag it for capturing
+			//
+			if (ec.MustCaptureVariable (local_info)) {
+				if (local_info.AddressTaken) {
+					AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
+				} else if (local_info.IsFixed) {
+					ec.Report.Error (1764, loc,
+						"Cannot use fixed local `{0}' inside an anonymous method, lambda expression or query expression",
+						GetSignatureForError ());
+				}
+
+				if (ec.IsVariableCapturingRequired) {
+					AnonymousMethodStorey storey = local_info.Block.Explicit.CreateAnonymousMethodStorey (ec);
+					storey.CaptureLocalVariable (ec, local_info);
+				}
+			}
+
+			eclass = ExprClass.Variable;
+			type = local_info.Type;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			local_info.SetIsUsed ();
+
+			DoResolveBase (ec);
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression rhs)
+		{
+			//
+			// Don't be too pedantic when variable is used as out param or for some broken code
+			// which uses property/indexer access to run some initialization
+			//
+			if (rhs == EmptyExpression.OutAccess || rhs.eclass == ExprClass.PropertyAccess || rhs.eclass == ExprClass.IndexerAccess)
+				local_info.SetIsUsed ();
+
+			if (local_info.IsReadonly && !ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.UsingInitializerScope)) {
+				if (rhs == EmptyExpression.LValueMemberAccess) {
+					// CS1654 already reported
+				} else {
+					int code;
+					string msg;
+					if (rhs == EmptyExpression.OutAccess) {
+						code = 1657; msg = "Cannot pass `{0}' as a ref or out argument because it is a `{1}'";
+					} else if (rhs == EmptyExpression.LValueMemberOutAccess) {
+						code = 1655; msg = "Cannot pass members of `{0}' as ref or out arguments because it is a `{1}'";
+					} else if (rhs == EmptyExpression.UnaryAddress) {
+						code = 459; msg = "Cannot take the address of {1} `{0}'";
+					} else {
+						code = 1656; msg = "Cannot assign to `{0}' because it is a `{1}'";
+					}
+					ec.Report.Error (code, loc, msg, Name, local_info.GetReadOnlyContext ());
+				}
+			}
+
+			if (eclass == ExprClass.Unresolved)
+				DoResolveBase (ec);
+
+			return base.DoResolveLValue (ec, rhs);
+		}
+
+		public override int GetHashCode ()
+		{
+			return local_info.GetHashCode ();
+		}
+
+		public override bool Equals (object obj)
+		{
+			LocalVariableReference lvr = obj as LocalVariableReference;
+			if (lvr == null)
+				return false;
+
+			return local_info == lvr.local_info;
+		}
+
+		protected override ILocalVariable Variable {
+			get { return local_info; }
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("{0} ({1}:{2})", GetType (), Name, loc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			// Nothing
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   This represents a reference to a parameter in the intermediate
+	///   representation.
+	/// </summary>
+	public class ParameterReference : VariableReference
+	{
+		protected ParametersBlock.ParameterInfo pi;
+
+		public ParameterReference (ParametersBlock.ParameterInfo pi, Location loc)
+		{
+			this.pi = pi;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public override bool IsLockedByStatement {
+			get {
+				return pi.IsLocked;
+			}
+			set	{
+				pi.IsLocked = value;
+			}
+		}
+
+		public override bool IsRef {
+			get { return (pi.Parameter.ModFlags & Parameter.Modifier.RefOutMask) != 0; }
+		}
+
+		bool HasOutModifier {
+			get { return (pi.Parameter.ModFlags & Parameter.Modifier.OUT) != 0; }
+		}
+
+		public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
+		{
+			return pi.Parameter.HoistedVariant;
+		}
+
+		//
+		// A ref or out parameter is classified as a moveable variable, even 
+		// if the argument given for the parameter is a fixed variable
+		//		
+		public override bool IsFixed {
+			get { return !IsRef; }
+		}
+
+		public override string Name {
+			get { return Parameter.Name; }
+		}
+
+		public Parameter Parameter {
+			get { return pi.Parameter; }
+		}
+
+		public override VariableInfo VariableInfo {
+			get { return pi.VariableInfo; }
+		}
+
+		protected override ILocalVariable Variable {
+			get { return Parameter; }
+		}
+
+		#endregion
+
+		public override void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			//
+			// ParameterReferences might already be a reference
+			//
+			if (IsRef) {
+				EmitLoad (ec);
+				return;
+			}
+
+			base.AddressOf (ec, mode);
+		}
+
+		public override void SetHasAddressTaken ()
+		{
+			Parameter.HasAddressTaken = true;
+		}
+
+		bool DoResolveBase (ResolveContext ec)
+		{
+			if (eclass != ExprClass.Unresolved)
+				return true;
+
+			type = pi.ParameterType;
+			eclass = ExprClass.Variable;
+
+			//
+			// If we are referencing a parameter from the external block
+			// flag it for capturing
+			//
+			if (ec.MustCaptureVariable (pi)) {
+				if (Parameter.HasAddressTaken)
+					AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, this, loc);
+
+				if (IsRef) {
+					ec.Report.Error (1628, loc,
+						"Parameter `{0}' cannot be used inside `{1}' when using `ref' or `out' modifier",
+						Name, ec.CurrentAnonymousMethod.ContainerType);
+				}
+
+				if (ec.IsVariableCapturingRequired && !pi.Block.ParametersBlock.IsExpressionTree) {
+					AnonymousMethodStorey storey = pi.Block.Explicit.CreateAnonymousMethodStorey (ec);
+					storey.CaptureParameter (ec, pi, this);
+				}
+			}
+
+			return true;
+		}
+
+		public override int GetHashCode ()
+		{
+			return Name.GetHashCode ();
+		}
+
+		public override bool Equals (object obj)
+		{
+			ParameterReference pr = obj as ParameterReference;
+			if (pr == null)
+				return false;
+
+			return Name == pr.Name;
+		}
+	
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			// Nothing to clone
+			return;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			HoistedVariable hv = GetHoistedVariable (ec);
+			if (hv != null)
+				return hv.CreateExpressionTree ();
+
+			return Parameter.ExpressionTreeVariableReference ();
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (!DoResolveBase (ec))
+				return null;
+
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			if (!DoResolveBase (ec))
+				return null;
+
+			if (Parameter.HoistedVariant != null)
+				Parameter.HoistedVariant.IsAssigned = true;
+
+			return base.DoResolveLValue (ec, right_side);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			VariableInfo variable_info = VariableInfo;
+			if (variable_info == null)
+				return;
+
+			if (fc.IsDefinitelyAssigned (variable_info))
+				return;
+
+			fc.Report.Error (269, loc, "Use of unassigned out parameter `{0}'", Name);
+			fc.SetVariableAssigned (variable_info);
+		}
+	}
+
+	/// <summary>
+	///   Invocation of methods or delegates.
+	/// </summary>
+	public class Invocation : ExpressionStatement
+	{
+		public class Predefined : Invocation
+		{
+			public Predefined (MethodGroupExpr expr, Arguments arguments)
+				: base (expr, arguments)
+			{
+				this.mg = expr;
+			}
+
+			protected override MethodGroupExpr DoResolveOverload (ResolveContext rc)
+			{
+				if (!rc.IsObsolete) {
+					var member = mg.BestCandidate;
+					ObsoleteAttribute oa = member.GetAttributeObsolete ();
+					if (oa != null)
+						AttributeTester.Report_ObsoleteMessage (oa, member.GetSignatureForError (), loc, rc.Report);
+				}
+
+				return mg;
+			}
+		}
+
+		protected Arguments arguments;
+		protected Expression expr;
+		protected MethodGroupExpr mg;
+		bool conditional_access_receiver;
+		
+		public Invocation (Expression expr, Arguments arguments)
+		{
+			this.expr = expr;		
+			this.arguments = arguments;
+			if (expr != null) {
+				loc = expr.Location;
+			}
+		}
+
+		#region Properties
+		public Arguments Arguments {
+			get {
+				return arguments;
+			}
+		}
+		
+		public Expression Exp {
+			get {
+				return expr;
+			}
+		}
+
+		public MethodGroupExpr MethodGroup {
+			get {
+				return mg;
+			}
+		}
+
+		public override Location StartLocation {
+			get {
+				return expr.StartLocation;
+			}
+		}
+
+		#endregion
+
+		public override MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
+		{
+			if (MethodGroup == null)
+				return null;
+
+			var candidate = MethodGroup.BestCandidate;
+			if (candidate == null || !(candidate.IsStatic || Exp is This))
+				return null;
+
+			var args_count = arguments == null ? 0 : arguments.Count;
+			if (args_count != body.Parameters.Count)
+				return null;
+
+			var lambda_parameters = body.Block.Parameters.FixedParameters;
+			for (int i = 0; i < args_count; ++i) {
+				var pr = arguments[i].Expr as ParameterReference;
+				if (pr == null)
+					return null;
+
+				if (lambda_parameters[i] != pr.Parameter)
+					return null;
+
+				if ((lambda_parameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (pr.Parameter.ModFlags & Parameter.Modifier.RefOutMask))
+					return null;
+			}
+
+			var emg = MethodGroup as ExtensionMethodGroupExpr;
+			if (emg != null) {
+				var mg = MethodGroupExpr.CreatePredefined (candidate, candidate.DeclaringType, MethodGroup.Location);
+				if (candidate.IsGeneric) {
+					var targs = new TypeExpression [candidate.Arity];
+					for (int i = 0; i < targs.Length; ++i) {
+						targs[i] = new TypeExpression (candidate.TypeArguments[i], MethodGroup.Location);
+					}
+
+					mg.SetTypeArguments (null, new TypeArguments (targs));
+				}
+
+				return mg;
+			}
+
+			return MethodGroup;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Invocation target = (Invocation) t;
+
+			if (arguments != null)
+				target.arguments = arguments.Clone (clonectx);
+
+			target.expr = expr.Clone (clonectx);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			if (arguments != null && arguments.ContainsEmitWithAwait ())
+				return true;
+
+			return mg.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Expression instance = mg.IsInstance ?
+				mg.InstanceExpression.CreateExpressionTree (ec) :
+				new NullLiteral (loc);
+
+			var args = Arguments.CreateForExpressionTree (ec, arguments,
+				instance,
+				mg.CreateExpressionTree (ec));
+
+			return CreateExpressionFactoryCall (ec, "Call", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			if (!rc.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) {
+				if (expr.HasConditionalAccess ()) {
+					conditional_access_receiver = true;
+					using (rc.Set (ResolveContext.Options.ConditionalAccessReceiver)) {
+						return DoResolveInvocation (rc);
+					}
+				}
+			}
+
+			return DoResolveInvocation (rc);
+		}
+
+		Expression DoResolveInvocation (ResolveContext ec)
+		{
+			Expression member_expr;
+			var atn = expr as ATypeNameExpression;
+			if (atn != null) {
+				member_expr = atn.LookupNameExpression (ec, MemberLookupRestrictions.InvocableOnly | MemberLookupRestrictions.ReadAccess);
+				if (member_expr != null) {
+					var name_of = member_expr as NameOf;
+					if (name_of != null) {
+						return name_of.ResolveOverload (ec, arguments);
+					}
+
+					member_expr = member_expr.Resolve (ec);
+				}
+			} else {
+				member_expr = expr.Resolve (ec);
+			}
+
+			if (member_expr == null)
+				return null;
+
+			//
+			// Next, evaluate all the expressions in the argument list
+			//
+			bool dynamic_arg = false;
+			if (arguments != null)
+				arguments.Resolve (ec, out dynamic_arg);
+
+			TypeSpec expr_type = member_expr.Type;
+			if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+				return DoResolveDynamic (ec, member_expr);
+
+			mg = member_expr as MethodGroupExpr;
+			Expression invoke = null;
+
+			if (mg == null) {
+				if (expr_type != null && expr_type.IsDelegate) {
+					invoke = new DelegateInvocation (member_expr, arguments, conditional_access_receiver, loc);
+					invoke = invoke.Resolve (ec);
+					if (invoke == null || !dynamic_arg)
+						return invoke;
+				} else {
+					if (member_expr is RuntimeValueExpression) {
+						ec.Report.Error (Report.RuntimeErrorId, loc, "Cannot invoke a non-delegate type `{0}'",
+							member_expr.Type.GetSignatureForError ());
+						return null;
+					}
+
+					MemberExpr me = member_expr as MemberExpr;
+					if (me == null) {
+						member_expr.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup, loc);
+						return null;
+					}
+
+					ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
+							member_expr.GetSignatureForError ());
+					return null;
+				}
+			}
+
+			if (invoke == null) {
+				mg = DoResolveOverload (ec);
+				if (mg == null)
+					return null;
+			}
+
+			if (dynamic_arg)
+				return DoResolveDynamic (ec, member_expr);
+
+			var method = mg.BestCandidate;
+			type = mg.BestCandidateReturnType;
+			if (conditional_access_receiver)
+				type = LiftMemberType (ec, type);
+
+			if (arguments == null && method.DeclaringType.BuiltinType == BuiltinTypeSpec.Type.Object && method.Name == Destructor.MetadataName) {
+				if (mg.IsBase)
+					ec.Report.Error (250, loc, "Do not directly call your base class Finalize method. It is called automatically from your destructor");
+				else
+					ec.Report.Error (245, loc, "Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available");
+				return null;
+			}
+
+			IsSpecialMethodInvocation (ec, method, loc);
+			
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		protected virtual Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
+		{
+			Arguments args;
+			DynamicMemberBinder dmb = memberExpr as DynamicMemberBinder;
+			if (dmb != null) {
+				args = dmb.Arguments;
+				if (arguments != null)
+					args.AddRange (arguments);
+			} else if (mg == null) {
+				if (arguments == null)
+					args = new Arguments (1);
+				else
+					args = arguments;
+
+				args.Insert (0, new Argument (memberExpr));
+				this.expr = null;
+			} else {
+				if (mg.IsBase) {
+					ec.Report.Error (1971, loc,
+						"The base call to method `{0}' cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access",
+						mg.Name);
+					return null;
+				}
+
+				if (arguments == null)
+					args = new Arguments (1);
+				else
+					args = arguments;
+
+				MemberAccess ma = expr as MemberAccess;
+				if (ma != null) {
+					var inst = mg.InstanceExpression;
+					var left_type = inst as TypeExpr;
+					if (left_type != null) {
+						args.Insert (0, new Argument (new TypeOf (left_type.Type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
+					} else if (inst != null) {
+						//
+						// Any value type has to be pass as by-ref to get back the same
+						// instance on which the member was called
+						//
+						var mod = inst is IMemoryLocation && TypeSpec.IsValueType (inst.Type) ?
+							Argument.AType.Ref : Argument.AType.None;
+						args.Insert (0, new Argument (inst.Resolve (ec), mod));
+					}
+				} else {	// is SimpleName
+					if (ec.IsStatic) {
+						args.Insert (0, new Argument (new TypeOf (ec.CurrentType, loc).Resolve (ec), Argument.AType.DynamicTypeName));
+					} else {
+						args.Insert (0, new Argument (new This (loc).Resolve (ec)));
+					}
+				}
+			}
+
+			return new DynamicInvocation (expr as ATypeNameExpression, args, loc).Resolve (ec);
+		}
+
+		protected virtual MethodGroupExpr DoResolveOverload (ResolveContext ec)
+		{
+			return mg.OverloadResolve (ec, ref arguments, null, OverloadResolver.Restrictions.None);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (mg.IsConditionallyExcluded)
+				return;
+
+  			mg.FlowAnalysis (fc);
+
+			if (arguments != null)
+				arguments.FlowAnalysis (fc);
+
+			if (conditional_access_receiver)
+				fc.ConditionalAccessEnd ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return mg.GetSignatureForError ();
+		}
+
+		public override bool HasConditionalAccess ()
+		{
+			return expr.HasConditionalAccess ();
+		}
+
+		//
+		// If a member is a method or event, or if it is a constant, field or property of either a delegate type
+		// or the type dynamic, then the member is invocable
+		//
+		public static bool IsMemberInvocable (MemberSpec member)
+		{
+			switch (member.Kind) {
+			case MemberKind.Event:
+				return true;
+			case MemberKind.Field:
+			case MemberKind.Property:
+				var m = member as IInterfaceMemberSpec;
+				return m.MemberType.IsDelegate || m.MemberType.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+			default:
+				return false;
+			}
+		}
+
+		public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
+		{
+			if (!method.IsReservedMethod)
+				return false;
+
+			if (ec.HasSet (ResolveContext.Options.InvokeSpecialName) || ec.CurrentMemberDefinition.IsCompilerGenerated)
+				return false;
+
+			ec.Report.SymbolRelatedToPreviousError (method);
+			ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
+				method.GetSignatureForError ());
+	
+			return true;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (mg.IsConditionallyExcluded)
+				return;
+
+			if (conditional_access_receiver)
+				mg.EmitCall (ec, arguments, type, false);
+			else
+				mg.EmitCall (ec, arguments, false);
+		}
+		
+		public override void EmitStatement (EmitContext ec)
+		{
+			if (mg.IsConditionallyExcluded)
+				return;
+
+			if (conditional_access_receiver)
+				mg.EmitCall (ec, arguments, type, true);
+			else
+				mg.EmitCall (ec, arguments, true);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return MakeExpression (ctx, mg.InstanceExpression, mg.BestCandidate, arguments);
+		}
+
+		public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
+		{
+#if STATIC
+			throw new NotSupportedException ();
+#else
+			var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
+			return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
+#endif
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// Implements simple new expression 
+	//
+	public class New : ExpressionStatement, IMemoryLocation
+	{
+		protected Arguments arguments;
+
+		//
+		// During bootstrap, it contains the RequestedType,
+		// but if `type' is not null, it *might* contain a NewDelegate
+		// (because of field multi-initialization)
+		//
+		protected Expression RequestedType;
+
+		protected MethodSpec method;
+
+		public New (Expression requested_type, Arguments arguments, Location l)
+		{
+			RequestedType = requested_type;
+			this.arguments = arguments;
+			loc = l;
+		}
+
+		#region Properties
+		public Arguments Arguments {
+			get {
+				return arguments;
+			}
+		}
+
+		public Expression TypeRequested {
+			get {
+				return RequestedType;
+			}
+		}
+
+		//
+		// Returns true for resolved `new S()'
+		//
+		public bool IsDefaultStruct {
+			get {
+				return arguments == null && type.IsStruct && GetType () == typeof (New);
+			}
+		}
+
+		public Expression TypeExpression {
+			get {
+				return RequestedType;
+			}
+		}
+
+		#endregion
+
+		/// <summary>
+		/// Converts complex core type syntax like 'new int ()' to simple constant
+		/// </summary>
+		public static Constant Constantify (TypeSpec t, Location loc)
+		{
+			switch (t.BuiltinType) {
+			case BuiltinTypeSpec.Type.Int:
+				return new IntConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.UInt:
+				return new UIntConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.Long:
+				return new LongConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.ULong:
+				return new ULongConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.Float:
+				return new FloatConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.Double:
+				return new DoubleConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.Short:
+				return new ShortConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.UShort:
+				return new UShortConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.SByte:
+				return new SByteConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.Byte:
+				return new ByteConstant (t, 0, loc);
+			case BuiltinTypeSpec.Type.Char:
+				return new CharConstant (t, '\0', loc);
+			case BuiltinTypeSpec.Type.Bool:
+				return new BoolConstant (t, false, loc);
+			case BuiltinTypeSpec.Type.Decimal:
+				return new DecimalConstant (t, 0, loc);
+			}
+
+			if (t.IsEnum)
+				return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t), loc), t);
+
+			if (t.IsNullableType)
+				return Nullable.LiftedNull.Create (t, loc);
+
+			return null;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return arguments != null && arguments.ContainsEmitWithAwait ();
+		}
+
+		//
+		// Checks whether the type is an interface that has the
+		// [ComImport, CoClass] attributes and must be treated
+		// specially
+		//
+		public Expression CheckComImport (ResolveContext ec)
+		{
+			if (!type.IsInterface)
+				return null;
+
+			//
+			// Turn the call into:
+			// (the-interface-stated) (new class-referenced-in-coclassattribute ())
+			//
+			var real_class = type.MemberDefinition.GetAttributeCoClass ();
+			if (real_class == null)
+				return null;
+
+			New proxy = new New (new TypeExpression (real_class, loc), arguments, loc);
+			Cast cast = new Cast (new TypeExpression (type, loc), proxy, loc);
+			return cast.Resolve (ec);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args;
+			if (method == null) {
+				args = new Arguments (1);
+				args.Add (new Argument (new TypeOf (type, loc)));
+			} else {
+				args = Arguments.CreateForExpressionTree (ec,
+					arguments, new TypeOfMethod (method, loc));
+			}
+
+			return CreateExpressionFactoryCall (ec, "New", args);
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			type = RequestedType.ResolveAsType (ec);
+			if (type == null)
+				return null;
+
+			eclass = ExprClass.Value;
+
+			if (type.IsPointer) {
+				ec.Report.Error (1919, loc, "Unsafe type `{0}' cannot be used in an object creation expression",
+					type.GetSignatureForError ());
+				return null;
+			}
+
+			if (arguments == null) {
+				Constant c = Constantify (type, RequestedType.Location);
+				if (c != null)
+					return ReducedExpression.Create (c, this);
+			}
+
+			if (type.IsDelegate) {
+				return (new NewDelegate (type, arguments, loc)).Resolve (ec);
+			}
+
+			var tparam = type as TypeParameterSpec;
+			if (tparam != null) {
+				//
+				// Check whether the type of type parameter can be constructed. BaseType can be a struct for method overrides
+				// where type parameter constraint is inflated to struct
+				//
+				if ((tparam.SpecialConstraint & (SpecialConstraint.Struct | SpecialConstraint.Constructor)) == 0 && !TypeSpec.IsValueType (tparam)) {
+					ec.Report.Error (304, loc,
+						"Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
+						type.GetSignatureForError ());
+				}
+
+				if ((arguments != null) && (arguments.Count != 0)) {
+					ec.Report.Error (417, loc,
+						"`{0}': cannot provide arguments when creating an instance of a variable type",
+						type.GetSignatureForError ());
+				}
+
+				return this;
+			}
+
+			if (type.IsStatic) {
+				ec.Report.SymbolRelatedToPreviousError (type);
+				ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", type.GetSignatureForError ());
+				return null;
+			}
+
+			if (type.IsInterface || type.IsAbstract){
+				if (!TypeManager.IsGenericType (type)) {
+					RequestedType = CheckComImport (ec);
+					if (RequestedType != null)
+						return RequestedType;
+				}
+				
+				ec.Report.SymbolRelatedToPreviousError (type);
+				ec.Report.Error (144, loc, "Cannot create an instance of the abstract class or interface `{0}'", type.GetSignatureForError ());
+				return null;
+			}
+
+			//
+			// Any struct always defines parameterless constructor
+			//
+			if (type.IsStruct && arguments == null)
+				return this;
+
+			bool dynamic;
+			if (arguments != null) {
+				arguments.Resolve (ec, out dynamic);
+			} else {
+				dynamic = false;
+			}
+
+			method = ConstructorLookup (ec, type, ref arguments, loc);
+
+			if (dynamic) {
+				arguments.Insert (0, new Argument (new TypeOf (type, loc).Resolve (ec), Argument.AType.DynamicTypeName));
+				return new DynamicConstructorBinder (type, arguments, loc).Resolve (ec);
+			}
+
+			return this;
+		}
+
+		bool DoEmitTypeParameter (EmitContext ec)
+		{
+			var m = ec.Module.PredefinedMembers.ActivatorCreateInstance.Resolve (loc);
+			if (m == null)
+				return true;
+
+			var ctor_factory = m.MakeGenericMethod (ec.MemberContext, type);
+			var tparam = (TypeParameterSpec) type;
+
+			if (tparam.IsReferenceType) {
+				ec.Emit (OpCodes.Call, ctor_factory);
+				return true;
+			}
+
+			// Allow DoEmit() to be called multiple times.
+			// We need to create a new LocalTemporary each time since
+			// you can't share LocalBuilders among ILGeneators.
+			LocalTemporary temp = new LocalTemporary (type);
+
+			Label label_activator = ec.DefineLabel ();
+			Label label_end = ec.DefineLabel ();
+
+			temp.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Initobj, type);
+
+			temp.Emit (ec);
+			ec.Emit (OpCodes.Box, type);
+			ec.Emit (OpCodes.Brfalse, label_activator);
+
+			temp.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Initobj, type);
+			temp.Emit (ec);
+			temp.Release (ec);
+			ec.Emit (OpCodes.Br_S, label_end);
+
+			ec.MarkLabel (label_activator);
+
+			ec.Emit (OpCodes.Call, ctor_factory);
+			ec.MarkLabel (label_end);
+			return true;
+		}
+
+		//
+		// This Emit can be invoked in two contexts:
+		//    * As a mechanism that will leave a value on the stack (new object)
+		//    * As one that wont (init struct)
+		//
+		// If we are dealing with a ValueType, we have a few
+		// situations to deal with:
+		//
+		//    * The target is a ValueType, and we have been provided
+		//      the instance (this is easy, we are being assigned).
+		//
+		//    * The target of New is being passed as an argument,
+		//      to a boxing operation or a function that takes a
+		//      ValueType.
+		//
+		//      In this case, we need to create a temporary variable
+		//      that is the argument of New.
+		//
+		// Returns whether a value is left on the stack
+		//
+		// *** Implementation note ***
+		//
+		// To benefit from this optimization, each assignable expression
+		// has to manually cast to New and call this Emit.
+		//
+		// TODO: It's worth to implement it for arrays and fields
+		//
+		public virtual bool Emit (EmitContext ec, IMemoryLocation target)
+		{
+			bool is_value_type = TypeSpec.IsValueType (type);
+			VariableReference vr = target as VariableReference;
+
+			if (target != null && is_value_type && (vr != null || method == null)) {
+				target.AddressOf (ec, AddressOp.Store);
+			} else if (vr != null && vr.IsRef) {
+				vr.EmitLoad (ec);
+			}
+
+			if (arguments != null) {
+				if (ec.HasSet (BuilderContext.Options.AsyncBody) && (arguments.Count > (this is NewInitialize ? 0 : 1)) && arguments.ContainsEmitWithAwait ())
+					arguments = arguments.Emit (ec, false, true);
+
+				arguments.Emit (ec);
+			}
+
+			if (is_value_type) {
+				if (method == null) {
+					ec.Emit (OpCodes.Initobj, type);
+					return false;
+				}
+
+				if (vr != null) {
+					ec.MarkCallEntry (loc);
+					ec.Emit (OpCodes.Call, method);
+					return false;
+				}
+			}
+			
+			if (type is TypeParameterSpec)
+				return DoEmitTypeParameter (ec);
+
+			ec.MarkCallEntry (loc);
+			ec.Emit (OpCodes.Newobj, method);
+			return true;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			LocalTemporary v = null;
+			if (method == null && TypeSpec.IsValueType (type)) {
+				// TODO: Use temporary variable from pool
+				v = new LocalTemporary (type);
+			}
+
+			if (!Emit (ec, v))
+				v.Emit (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			LocalTemporary v = null;
+			if (method == null && TypeSpec.IsValueType (type)) {
+				// TODO: Use temporary variable from pool
+				v = new LocalTemporary (type);
+			}
+
+			if (Emit (ec, v))
+				ec.Emit (OpCodes.Pop);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (arguments != null)
+				arguments.FlowAnalysis (fc);
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			EmitAddressOf (ec, mode);
+		}
+
+		protected virtual IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp mode)
+		{
+			LocalTemporary value_target = new LocalTemporary (type);
+
+			if (type is TypeParameterSpec) {
+				DoEmitTypeParameter (ec);
+				value_target.Store (ec);
+				value_target.AddressOf (ec, mode);
+				return value_target;
+			}
+
+			value_target.AddressOf (ec, AddressOp.Store);
+
+			if (method == null) {
+				ec.Emit (OpCodes.Initobj, type);
+			} else {
+				if (arguments != null)
+					arguments.Emit (ec);
+
+				ec.Emit (OpCodes.Call, method);
+			}
+			
+			value_target.AddressOf (ec, mode);
+			return value_target;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			New target = (New) t;
+
+			target.RequestedType = RequestedType.Clone (clonectx);
+			if (arguments != null){
+				target.arguments = arguments.Clone (clonectx);
+			}
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.New ((ConstructorInfo) method.GetMetaInfo (), Arguments.MakeExpression (arguments, ctx));
+#endif
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// Array initializer expression, the expression is allowed in
+	// variable or field initialization only which makes it tricky as
+	// the type has to be infered based on the context either from field
+	// type or variable type (think of multiple declarators)
+	//
+	public class ArrayInitializer : Expression
+	{
+		List<Expression> elements;
+		BlockVariable variable;
+
+		public ArrayInitializer (List<Expression> init, Location loc)
+		{
+			elements = init;
+			this.loc = loc;
+		}
+
+		public ArrayInitializer (int count, Location loc)
+			: this (new List<Expression> (count), loc)
+		{
+		}
+
+		public ArrayInitializer (Location loc)
+			: this (4, loc)
+		{
+		}
+
+		#region Properties
+
+		public int Count {
+			get { return elements.Count; }
+		}
+
+		public List<Expression> Elements {
+			get {
+				return elements;
+			}
+		}
+
+		public Expression this [int index] {
+			get {
+				return elements [index];
+			}
+		}
+
+		public BlockVariable VariableDeclaration {
+			get {
+				return variable;
+			}
+			set {
+				variable = value;
+			}
+		}
+		#endregion
+
+		public void Add (Expression expr)
+		{
+			elements.Add (expr);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			var target = (ArrayInitializer) t;
+
+			target.elements = new List<Expression> (elements.Count);
+			foreach (var element in elements)
+				target.elements.Add (element.Clone (clonectx));
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			var current_field = rc.CurrentMemberDefinition as FieldBase;
+			TypeExpression type;
+			if (current_field != null && rc.CurrentAnonymousMethod == null) {
+				type = new TypeExpression (current_field.MemberType, current_field.Location);
+			} else if (variable != null) {
+				if (variable.TypeExpression is VarExpr) {
+					rc.Report.Error (820, loc, "An implicitly typed local variable declarator cannot use an array initializer");
+					return EmptyExpression.Null;
+				}
+
+				type = new TypeExpression (variable.Variable.Type, variable.Variable.Location);
+			} else {
+				throw new NotImplementedException ("Unexpected array initializer context");
+			}
+
+			return new ArrayCreation (type, this).Resolve (rc);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			throw new InternalErrorException ("Missing Resolve call");
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			throw new InternalErrorException ("Missing Resolve call");
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   14.5.10.2: Represents an array creation expression.
+	/// </summary>
+	///
+	/// <remarks>
+	///   There are two possible scenarios here: one is an array creation
+	///   expression that specifies the dimensions and optionally the
+	///   initialization data and the other which does not need dimensions
+	///   specified but where initialization data is mandatory.
+	/// </remarks>
+	public class ArrayCreation : Expression
+	{
+		FullNamedExpression requested_base_type;
+		ArrayInitializer initializers;
+
+		//
+		// The list of Argument types.
+		// This is used to construct the `newarray' or constructor signature
+		//
+		protected List<Expression> arguments;
+		
+		protected TypeSpec array_element_type;
+		int num_arguments;
+		protected int dimensions;
+		protected readonly ComposedTypeSpecifier rank;
+		Expression first_emit;
+		LocalTemporary first_emit_temp;
+
+		protected List<Expression> array_data;
+
+		Dictionary<int, int> bounds;
+
+#if STATIC
+		// The number of constants in array initializers
+		int const_initializers_count;
+		bool only_constant_initializers;
+#endif
+		public ArrayCreation (FullNamedExpression requested_base_type, List<Expression> exprs, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location l)
+			: this (requested_base_type, rank, initializers, l)
+		{
+			arguments = exprs;
+			num_arguments = arguments.Count;
+		}
+
+		//
+		// For expressions like int[] foo = new int[] { 1, 2, 3 };
+		//
+		public ArrayCreation (FullNamedExpression requested_base_type, ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
+		{
+			this.requested_base_type = requested_base_type;
+			this.rank = rank;
+			this.initializers = initializers;
+			this.loc = loc;
+
+			if (rank != null)
+				num_arguments = rank.Dimension;
+		}
+
+		//
+		// For compiler generated single dimensional arrays only
+		//
+		public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers, Location loc)
+			: this (requested_base_type, ComposedTypeSpecifier.SingleDimension, initializers, loc)
+		{
+		}
+
+		//
+		// For expressions like int[] foo = { 1, 2, 3 };
+		//
+		public ArrayCreation (FullNamedExpression requested_base_type, ArrayInitializer initializers)
+			: this (requested_base_type, null, initializers, initializers.Location)
+		{
+		}
+
+		public ComposedTypeSpecifier Rank {
+			get {
+				return this.rank;
+			}
+		}
+		
+		public FullNamedExpression TypeExpression {
+			get {
+				return this.requested_base_type;
+			}
+		}
+		
+		public ArrayInitializer Initializers {
+			get {
+				return this.initializers;
+			}
+		}
+		
+		public List<Expression> Arguments {
+			get { return this.arguments; }
+		}
+		
+		bool CheckIndices (ResolveContext ec, ArrayInitializer probe, int idx, bool specified_dims, int child_bounds)
+		{
+			if (initializers != null && bounds == null) {
+				//
+				// We use this to store all the data values in the order in which we
+				// will need to store them in the byte blob later
+				//
+				array_data = new List<Expression> (probe.Count);
+				bounds = new Dictionary<int, int> ();
+			}
+
+			if (specified_dims) { 
+				Expression a = arguments [idx];
+				a = a.Resolve (ec);
+				if (a == null)
+					return false;
+
+				a = ConvertExpressionToArrayIndex (ec, a);
+				if (a == null)
+					return false;
+
+				arguments[idx] = a;
+
+				if (initializers != null) {
+					Constant c = a as Constant;
+					if (c == null && a is ArrayIndexCast)
+						c = ((ArrayIndexCast) a).Child as Constant;
+
+					if (c == null) {
+						ec.Report.Error (150, a.Location, "A constant value is expected");
+						return false;
+					}
+
+					int value;
+					try {
+						value = System.Convert.ToInt32 (c.GetValue ());
+					} catch {
+						ec.Report.Error (150, a.Location, "A constant value is expected");
+						return false;
+					}
+
+					// TODO: probe.Count does not fit ulong in
+					if (value != probe.Count) {
+						ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
+						return false;
+					}
+
+					bounds[idx] = value;
+				}
+			}
+
+			if (initializers == null)
+				return true;
+
+			for (int i = 0; i < probe.Count; ++i) {
+				var o = probe [i];
+				if (o is ArrayInitializer) {
+					var sub_probe = o as ArrayInitializer;
+					if (idx + 1 >= dimensions){
+						ec.Report.Error (623, loc, "Array initializers can only be used in a variable or field initializer. Try using a new expression instead");
+						return false;
+					}
+
+					// When we don't have explicitly specified dimensions, record whatever dimension we first encounter at each level
+					if (!bounds.ContainsKey(idx + 1))
+						bounds[idx + 1] = sub_probe.Count;
+
+					if (bounds[idx + 1] != sub_probe.Count) {
+						ec.Report.Error(847, sub_probe.Location, "An array initializer of length `{0}' was expected", bounds[idx + 1].ToString());
+						return false;
+					}
+
+					bool ret = CheckIndices (ec, sub_probe, idx + 1, specified_dims, child_bounds - 1);
+					if (!ret)
+						return false;
+				} else if (child_bounds > 1) {
+					ec.Report.Error (846, o.Location, "A nested array initializer was expected");
+				} else {
+					Expression element = ResolveArrayElement (ec, o);
+					if (element == null)
+						continue;
+#if STATIC
+					// Initializers with the default values can be ignored
+					Constant c = element as Constant;
+					if (c != null) {
+						if (!c.IsDefaultInitializer (array_element_type)) {
+							++const_initializers_count;
+						}
+					} else {
+						only_constant_initializers = false;
+					}
+#endif					
+					array_data.Add (element);
+				}
+			}
+
+			return true;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			foreach (var arg in arguments) {
+				if (arg.ContainsEmitWithAwait ())
+					return true;
+			}
+
+			return InitializersContainAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args;
+
+			if (array_data == null) {
+				args = new Arguments (arguments.Count + 1);
+				args.Add (new Argument (new TypeOf (array_element_type, loc)));
+				foreach (Expression a in arguments)
+					args.Add (new Argument (a.CreateExpressionTree (ec)));
+
+				return CreateExpressionFactoryCall (ec, "NewArrayBounds", args);
+			}
+
+			if (dimensions > 1) {
+				ec.Report.Error (838, loc, "An expression tree cannot contain a multidimensional array initializer");
+				return null;
+			}
+
+			args = new Arguments (array_data == null ? 1 : array_data.Count + 1);
+			args.Add (new Argument (new TypeOf (array_element_type, loc)));
+			if (array_data != null) {
+				for (int i = 0; i < array_data.Count; ++i) {
+					Expression e = array_data [i];
+					args.Add (new Argument (e.CreateExpressionTree (ec)));
+				}
+			}
+
+			return CreateExpressionFactoryCall (ec, "NewArrayInit", args);
+		}		
+		
+		void UpdateIndices (ResolveContext rc)
+		{
+			int i = 0;
+			for (var probe = initializers; probe != null;) {
+				Expression e = new IntConstant (rc.BuiltinTypes, probe.Count, Location.Null);
+				arguments.Add (e);
+				bounds[i++] = probe.Count;
+
+				if (probe.Count > 0 && probe [0] is ArrayInitializer) {
+					probe = (ArrayInitializer) probe[0];
+				} else if (dimensions > i) {
+					continue;
+				} else {
+					return;
+				}
+			}
+		}
+
+		protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
+		{
+			ec.Report.Error (248, loc, "Cannot create an array with a negative size");
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			foreach (var arg in arguments)
+				arg.FlowAnalysis (fc);
+
+			if (array_data != null) {
+				foreach (var ad in array_data)
+					ad.FlowAnalysis (fc);
+			}
+		}
+
+		bool InitializersContainAwait ()
+		{
+			if (array_data == null)
+				return false;
+
+			foreach (var expr in array_data) {
+				if (expr.ContainsEmitWithAwait ())
+					return true;
+			}
+
+			return false;
+		}
+
+		protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
+		{
+			element = element.Resolve (ec);
+			if (element == null)
+				return null;
+
+			if (element is CompoundAssign.TargetExpression) {
+				if (first_emit != null)
+					throw new InternalErrorException ("Can only handle one mutator at a time");
+				first_emit = element;
+				element = first_emit_temp = new LocalTemporary (element.Type);
+			}
+
+			return Convert.ImplicitConversionRequired (
+				ec, element, array_element_type, loc);
+		}
+
+		protected bool ResolveInitializers (ResolveContext ec)
+		{
+#if STATIC
+			only_constant_initializers = true;
+#endif
+
+			if (arguments != null) {
+				bool res = true;
+				for (int i = 0; i < arguments.Count; ++i) {
+					res &= CheckIndices (ec, initializers, i, true, dimensions);
+					if (initializers != null)
+						break;
+				}
+
+				return res;
+			}
+
+			arguments = new List<Expression> ();
+
+			if (!CheckIndices (ec, initializers, 0, false, dimensions))
+				return false;
+				
+			UpdateIndices (ec);
+				
+			return true;
+		}
+
+		//
+		// Resolved the type of the array
+		//
+		bool ResolveArrayType (ResolveContext ec)
+		{
+			//
+			// Lookup the type
+			//
+			FullNamedExpression array_type_expr;
+			if (num_arguments > 0) {
+				array_type_expr = new ComposedCast (requested_base_type, rank);
+			} else {
+				array_type_expr = requested_base_type;
+			}
+
+			type = array_type_expr.ResolveAsType (ec);
+			if (array_type_expr == null)
+				return false;
+
+			var ac = type as ArrayContainer;
+			if (ac == null) {
+				ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
+				return false;
+			}
+
+			array_element_type = ac.Element;
+			dimensions = ac.Rank;
+
+			return true;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (type != null)
+				return this;
+
+			if (!ResolveArrayType (ec))
+				return null;
+
+			//
+			// validate the initializers and fill in any missing bits
+			//
+			if (!ResolveInitializers (ec))
+				return null;
+
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		byte [] MakeByteBlob ()
+		{
+			int factor;
+			byte [] data;
+			byte [] element;
+			int count = array_data.Count;
+
+			TypeSpec element_type = array_element_type;
+			if (element_type.IsEnum)
+				element_type = EnumSpec.GetUnderlyingType (element_type);
+
+			factor = BuiltinTypeSpec.GetSize (element_type);
+			if (factor == 0)
+				throw new Exception ("unrecognized type in MakeByteBlob: " + element_type);
+
+			data = new byte [(count * factor + 3) & ~3];
+			int idx = 0;
+
+			for (int i = 0; i < count; ++i) {
+				var c = array_data[i] as Constant;
+				if (c == null) {
+					idx += factor;
+					continue;
+				}
+
+				object v = c.GetValue ();
+
+				switch (element_type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Long:
+					long lval = (long) v;
+
+					for (int j = 0; j < factor; ++j) {
+						data[idx + j] = (byte) (lval & 0xFF);
+						lval = (lval >> 8);
+					}
+					break;
+				case BuiltinTypeSpec.Type.ULong:
+					ulong ulval = (ulong) v;
+
+					for (int j = 0; j < factor; ++j) {
+						data[idx + j] = (byte) (ulval & 0xFF);
+						ulval = (ulval >> 8);
+					}
+					break;
+				case BuiltinTypeSpec.Type.Float:
+					var fval = SingleConverter.SingleToInt32Bits((float) v);
+
+					data[idx] = (byte) (fval & 0xff);
+					data[idx + 1] = (byte) ((fval >> 8) & 0xff);
+					data[idx + 2] = (byte) ((fval >> 16) & 0xff);
+					data[idx + 3] = (byte) (fval >> 24);
+					break;
+				case BuiltinTypeSpec.Type.Double:
+					element = BitConverter.GetBytes ((double) v);
+
+					for (int j = 0; j < factor; ++j)
+						data[idx + j] = element[j];
+
+					// FIXME: Handle the ARM float format.
+					if (!BitConverter.IsLittleEndian)
+						System.Array.Reverse (data, idx, 8);
+					break;
+				case BuiltinTypeSpec.Type.Char:
+					int chval = (int) ((char) v);
+
+					data[idx] = (byte) (chval & 0xff);
+					data[idx + 1] = (byte) (chval >> 8);
+					break;
+				case BuiltinTypeSpec.Type.Short:
+					int sval = (int) ((short) v);
+
+					data[idx] = (byte) (sval & 0xff);
+					data[idx + 1] = (byte) (sval >> 8);
+					break;
+				case BuiltinTypeSpec.Type.UShort:
+					int usval = (int) ((ushort) v);
+
+					data[idx] = (byte) (usval & 0xff);
+					data[idx + 1] = (byte) (usval >> 8);
+					break;
+				case BuiltinTypeSpec.Type.Int:
+					int val = (int) v;
+
+					data[idx] = (byte) (val & 0xff);
+					data[idx + 1] = (byte) ((val >> 8) & 0xff);
+					data[idx + 2] = (byte) ((val >> 16) & 0xff);
+					data[idx + 3] = (byte) (val >> 24);
+					break;
+				case BuiltinTypeSpec.Type.UInt:
+					uint uval = (uint) v;
+
+					data[idx] = (byte) (uval & 0xff);
+					data[idx + 1] = (byte) ((uval >> 8) & 0xff);
+					data[idx + 2] = (byte) ((uval >> 16) & 0xff);
+					data[idx + 3] = (byte) (uval >> 24);
+					break;
+				case BuiltinTypeSpec.Type.SByte:
+					data[idx] = (byte) (sbyte) v;
+					break;
+				case BuiltinTypeSpec.Type.Byte:
+					data[idx] = (byte) v;
+					break;
+				case BuiltinTypeSpec.Type.Bool:
+					data[idx] = (byte) ((bool) v ? 1 : 0);
+					break;
+				case BuiltinTypeSpec.Type.Decimal:
+					int[] bits = Decimal.GetBits ((decimal) v);
+					int p = idx;
+
+					// FIXME: For some reason, this doesn't work on the MS runtime.
+					int[] nbits = new int[4];
+					nbits[0] = bits[3];
+					nbits[1] = bits[2];
+					nbits[2] = bits[0];
+					nbits[3] = bits[1];
+
+					for (int j = 0; j < 4; j++) {
+						data[p++] = (byte) (nbits[j] & 0xff);
+						data[p++] = (byte) ((nbits[j] >> 8) & 0xff);
+						data[p++] = (byte) ((nbits[j] >> 16) & 0xff);
+						data[p++] = (byte) (nbits[j] >> 24);
+					}
+					break;
+				default:
+					throw new Exception ("Unrecognized type in MakeByteBlob: " + element_type);
+				}
+
+				idx += factor;
+			}
+
+			return data;
+		}
+
+#if NET_4_0 || MOBILE_DYNAMIC
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			var initializers = new SLE.Expression [array_data.Count];
+			for (var i = 0; i < initializers.Length; i++) {
+				if (array_data [i] == null)
+					initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
+				else
+					initializers [i] = array_data [i].MakeExpression (ctx);
+			}
+
+			return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
+#endif
+		}
+#endif
+#if STATIC
+		//
+		// Emits the initializers for the array
+		//
+		void EmitStaticInitializers (EmitContext ec, FieldExpr stackArray)
+		{
+			var m = ec.Module.PredefinedMembers.RuntimeHelpersInitializeArray.Resolve (loc);
+			if (m == null)
+				return;
+
+			//
+			// First, the static data
+			//
+			byte [] data = MakeByteBlob ();
+			var fb = ec.CurrentTypeDefinition.Module.MakeStaticData (data, loc);
+
+			if (stackArray == null) {
+				ec.Emit (OpCodes.Dup);
+			} else {
+				stackArray.Emit (ec);
+			}
+
+			ec.Emit (OpCodes.Ldtoken, fb);
+			ec.Emit (OpCodes.Call, m);
+		}
+#endif
+
+		//
+		// Emits pieces of the array that can not be computed at compile
+		// time (variables and string locations).
+		//
+		// This always expect the top value on the stack to be the array
+		//
+		void EmitDynamicInitializers (EmitContext ec, bool emitConstants, StackFieldExpr stackArray)
+		{
+			int dims = bounds.Count;
+			var current_pos = new int [dims];
+
+			for (int i = 0; i < array_data.Count; i++){
+
+				Expression e = array_data [i];
+				var c = e as Constant;
+
+				// Constant can be initialized via StaticInitializer
+				if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
+
+					var etype = e.Type;
+
+					if (stackArray != null) {
+						if (e.ContainsEmitWithAwait ()) {
+							e = e.EmitToField (ec);
+						}
+
+						stackArray.EmitLoad (ec);
+					} else {
+						ec.Emit (OpCodes.Dup);
+					}
+
+					for (int idx = 0; idx < dims; idx++) 
+						ec.EmitInt (current_pos [idx]);
+
+					//
+					// If we are dealing with a struct, get the
+					// address of it, so we can store it.
+					//
+					if (dims == 1 && etype.IsStruct && !BuiltinTypeSpec.IsPrimitiveType (etype))
+						ec.Emit (OpCodes.Ldelema, etype);
+
+					e.Emit (ec);
+
+					ec.EmitArrayStore ((ArrayContainer) type);
+				}
+				
+				//
+				// Advance counter
+				//
+				for (int j = dims - 1; j >= 0; j--){
+					current_pos [j]++;
+					if (current_pos [j] < bounds [j])
+						break;
+					current_pos [j] = 0;
+				}
+			}
+
+			if (stackArray != null)
+				stackArray.PrepareCleanup (ec);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			var await_field = EmitToFieldSource (ec);
+			if (await_field != null)
+				await_field.Emit (ec);
+		}
+
+		protected sealed override FieldExpr EmitToFieldSource (EmitContext ec)
+		{
+			if (first_emit != null) {
+				first_emit.Emit (ec);
+				first_emit_temp.Store (ec);
+			}
+
+			StackFieldExpr await_stack_field;
+			if (ec.HasSet (BuilderContext.Options.AsyncBody) && InitializersContainAwait ()) {
+				await_stack_field = ec.GetTemporaryField (type);
+				ec.EmitThis ();
+			} else {
+				await_stack_field = null;
+			}
+
+			EmitExpressionsList (ec, arguments);
+
+			ec.EmitArrayNew ((ArrayContainer) type);
+			
+			if (initializers == null)
+				return await_stack_field;
+
+			if (await_stack_field != null)
+				await_stack_field.EmitAssignFromStack (ec);
+
+#if STATIC
+			//
+			// Emit static initializer for arrays which contain more than 2 items and
+			// the static initializer will initialize at least 25% of array values or there
+			// is more than 10 items to be initialized
+			//
+			// NOTE: const_initializers_count does not contain default constant values.
+			//
+			if (const_initializers_count > 2 && (array_data.Count > 10 || const_initializers_count * 4 > (array_data.Count)) &&
+				(BuiltinTypeSpec.IsPrimitiveType (array_element_type) || array_element_type.IsEnum)) {
+				EmitStaticInitializers (ec, await_stack_field);
+
+				if (!only_constant_initializers)
+					EmitDynamicInitializers (ec, false, await_stack_field);
+			} else
+#endif
+			{
+				EmitDynamicInitializers (ec, true, await_stack_field);
+			}
+
+			if (first_emit_temp != null)
+				first_emit_temp.Release (ec);
+
+			return await_stack_field;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			// no multi dimensional or jagged arrays
+			if (arguments.Count != 1 || array_element_type.IsArray) {
+				base.EncodeAttributeValue (rc, enc, targetType, parameterType);
+				return;
+			}
+
+			// No array covariance, except for array -> object
+			if (type != targetType) {
+				if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
+					base.EncodeAttributeValue (rc, enc, targetType, parameterType);
+					return;
+				}
+
+				if (enc.Encode (type) == AttributeEncoder.EncodedTypeProperties.DynamicType) {
+					Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
+					return;
+				}
+			}
+
+			// Single dimensional array of 0 size
+			if (array_data == null) {
+				IntConstant ic = arguments[0] as IntConstant;
+				if (ic == null || !ic.IsDefaultValue) {
+					base.EncodeAttributeValue (rc, enc, targetType, parameterType);
+				} else {
+					enc.Encode (0);
+				}
+
+				return;
+			}
+
+			enc.Encode (array_data.Count);
+			foreach (var element in array_data) {
+				element.EncodeAttributeValue (rc, enc, array_element_type, parameterType);
+			}
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			ArrayCreation target = (ArrayCreation) t;
+
+			if (requested_base_type != null)
+				target.requested_base_type = (FullNamedExpression)requested_base_type.Clone (clonectx);
+
+			if (arguments != null){
+				target.arguments = new List<Expression> (arguments.Count);
+				foreach (Expression e in arguments)
+					target.arguments.Add (e.Clone (clonectx));
+			}
+
+			if (initializers != null)
+				target.initializers = (ArrayInitializer) initializers.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+	
+	//
+	// Represents an implicitly typed array epxression
+	//
+	class ImplicitlyTypedArrayCreation : ArrayCreation
+	{
+		TypeInferenceContext best_type_inference;
+
+		public ImplicitlyTypedArrayCreation (ComposedTypeSpecifier rank, ArrayInitializer initializers, Location loc)
+			: base (null, rank, initializers, loc)
+		{			
+		}
+
+		public ImplicitlyTypedArrayCreation (ArrayInitializer initializers, Location loc)
+			: base (null, initializers, loc)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (type != null)
+				return this;
+
+			dimensions = rank.Dimension;
+
+			best_type_inference = new TypeInferenceContext ();
+
+			if (!ResolveInitializers (ec))
+				return null;
+
+			best_type_inference.FixAllTypes (ec);
+			array_element_type = best_type_inference.InferredTypeArguments[0];
+			best_type_inference = null;
+
+			if (array_element_type == null ||
+				array_element_type == InternalType.NullLiteral || array_element_type == InternalType.MethodGroup || array_element_type == InternalType.AnonymousMethod ||
+				arguments.Count != rank.Dimension) {
+				ec.Report.Error (826, loc,
+					"The type of an implicitly typed array cannot be inferred from the initializer. Try specifying array type explicitly");
+				return null;
+			}
+
+			//
+			// At this point we found common base type for all initializer elements
+			// but we have to be sure that all static initializer elements are of
+			// same type
+			//
+			UnifyInitializerElement (ec);
+
+			type = ArrayContainer.MakeType (ec.Module, array_element_type, dimensions);
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		//
+		// Converts static initializer only
+		//
+		void UnifyInitializerElement (ResolveContext ec)
+		{
+			for (int i = 0; i < array_data.Count; ++i) {
+				Expression e = array_data[i];
+				if (e != null)
+					array_data [i] = Convert.ImplicitConversion (ec, e, array_element_type, Location.Null);
+			}
+		}
+
+		protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
+		{
+			element = element.Resolve (ec);
+			if (element != null)
+				best_type_inference.AddCommonTypeBound (element.Type);
+
+			return element;
+		}
+	}	
+	
+	sealed class CompilerGeneratedThis : This
+	{
+		public CompilerGeneratedThis (TypeSpec type, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			eclass = ExprClass.Variable;
+
+			var block = rc.CurrentBlock;
+			if (block != null) {
+				var top = block.ParametersBlock.TopBlock;
+				if (top.ThisVariable != null)
+					variable_info = top.ThisVariable.VariableInfo;
+
+			}
+
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			return DoResolve (rc);
+		}
+
+		public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
+		{
+			return null;
+		}
+	}
+	
+	/// <summary>
+	///   Represents the `this' construct
+	/// </summary>
+
+	public class This : VariableReference
+	{
+		sealed class ThisVariable : ILocalVariable
+		{
+			public static readonly ILocalVariable Instance = new ThisVariable ();
+
+			public void Emit (EmitContext ec)
+			{
+				ec.EmitThis ();
+			}
+
+			public void EmitAssign (EmitContext ec)
+			{
+				throw new InvalidOperationException ();
+			}
+
+			public void EmitAddressOf (EmitContext ec)
+			{
+				ec.EmitThis ();
+			}
+		}
+
+		protected VariableInfo variable_info;
+
+		public This (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public override string Name {
+			get { return "this"; }
+		}
+
+		public override bool IsLockedByStatement {
+			get {
+				return false;
+			}
+			set {
+			}
+		}
+
+		public override bool IsRef {
+			get { return type.IsStruct; }
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		protected override ILocalVariable Variable {
+			get { return ThisVariable.Instance; }
+		}
+
+		public override VariableInfo VariableInfo {
+			get { return variable_info; }
+		}
+
+		public override bool IsFixed {
+			get { return false; }
+		}
+
+		#endregion
+
+		void CheckStructThisDefiniteAssignment (FlowAnalysisContext fc)
+		{
+			//
+			// It's null for all cases when we don't need to check `this'
+			// definitive assignment
+			//
+			if (variable_info == null)
+				return;
+
+			if (fc.IsDefinitelyAssigned (variable_info))
+				return;
+
+			fc.Report.Error (188, loc, "The `this' object cannot be used before all of its fields are assigned to");
+		}
+
+		protected virtual void Error_ThisNotAvailable (ResolveContext ec)
+		{
+			if (ec.IsStatic && !ec.HasSet (ResolveContext.Options.ConstantScope)) {
+				ec.Report.Error (26, loc, "Keyword `this' is not valid in a static property, static method, or static field initializer");
+			} else if (ec.CurrentAnonymousMethod != null) {
+				ec.Report.Error (1673, loc,
+					"Anonymous methods inside structs cannot access instance members of `this'. " +
+					"Consider copying `this' to a local variable outside the anonymous method and using the local instead");
+			} else {
+				ec.Report.Error (27, loc, "Keyword `this' is not available in the current context");
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			CheckStructThisDefiniteAssignment (fc);
+		}
+
+		public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
+		{
+			if (ae == null)
+				return null;
+
+			AnonymousMethodStorey storey = ae.Storey;
+			return storey != null ? storey.HoistedThis : null;
+		}
+
+		public static bool IsThisAvailable (ResolveContext ec, bool ignoreAnonymous)
+		{
+			if (ec.IsStatic || ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.BaseInitializer | ResolveContext.Options.ConstantScope))
+				return false;
+
+			if (ignoreAnonymous || ec.CurrentAnonymousMethod == null)
+				return true;
+
+			if (ec.CurrentType.IsStruct && !(ec.CurrentAnonymousMethod is StateMachineInitializer))
+				return false;
+
+			return true;
+		}
+
+		public virtual void ResolveBase (ResolveContext ec)
+		{
+			eclass = ExprClass.Variable;
+			type = ec.CurrentType;
+
+			if (!IsThisAvailable (ec, false)) {
+				Error_ThisNotAvailable (ec);
+				return;
+			}
+
+			var block = ec.CurrentBlock;
+			if (block != null) {
+				var top = block.ParametersBlock.TopBlock;
+				if (top.ThisVariable != null)
+					variable_info = top.ThisVariable.VariableInfo;
+
+				AnonymousExpression am = ec.CurrentAnonymousMethod;
+				if (am != null && ec.IsVariableCapturingRequired && !block.Explicit.HasCapturedThis) {
+					//
+					// Hoisted this is almost like hoisted variable but not exactly. When
+					// there is no variable hoisted we can simply emit an instance method
+					// without lifting this into a storey. Unfotunatelly this complicates
+					// things in other cases because we don't know where this will be hoisted
+					// until top-level block is fully resolved
+					//
+					top.AddThisReferenceFromChildrenBlock (block.Explicit);
+					am.SetHasThisAccess ();
+				}
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			ResolveBase (ec);
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			if (eclass == ExprClass.Unresolved)
+				ResolveBase (ec);
+
+			if (type.IsClass){
+				if (right_side == EmptyExpression.UnaryAddress)
+					ec.Report.Error (459, loc, "Cannot take the address of `this' because it is read-only");
+				else if (right_side == EmptyExpression.OutAccess)
+					ec.Report.Error (1605, loc, "Cannot pass `this' as a ref or out argument because it is read-only");
+				else
+					ec.Report.Error (1604, loc, "Cannot assign to `this' because it is read-only");
+			}
+
+			return this;
+		}
+
+		public override int GetHashCode()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override bool Equals (object obj)
+		{
+			This t = obj as This;
+			if (t == null)
+				return false;
+
+			return true;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			// Nothing
+		}
+
+		public override void SetHasAddressTaken ()
+		{
+			// Nothing
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Represents the `__arglist' construct
+	/// </summary>
+	public class ArglistAccess : Expression
+	{
+		public ArglistAccess (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			// nothing.
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Variable;
+			type = ec.Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
+
+			if (ec.HasSet (ResolveContext.Options.FieldInitializerScope) || !ec.CurrentBlock.ParametersBlock.Parameters.HasArglist) {
+				ec.Report.Error (190, loc,
+					"The __arglist construct is valid only within a variable argument method");
+			}
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Arglist);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Represents the `__arglist (....)' construct
+	/// </summary>
+	public class Arglist : Expression
+	{
+		Arguments arguments;
+
+		public Arglist (Location loc)
+			: this (null, loc)
+		{
+		}
+
+		public Arglist (Arguments args, Location l)
+		{
+			arguments = args;
+			loc = l;
+		}
+
+		public Arguments Arguments {
+			get {
+				return arguments;
+			}
+		}
+
+		public MetaType[] ArgumentTypes {
+		    get {
+				if (arguments == null)
+					return MetaType.EmptyTypes;
+
+				var retval = new MetaType[arguments.Count];
+				for (int i = 0; i < retval.Length; i++)
+					retval[i] = arguments[i].Expr.Type.GetMetaInfo ();
+
+		        return retval;
+		    }
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotImplementedException ();
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (1952, loc, "An expression tree cannot contain a method with variable arguments");
+			return null;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Variable;
+			type = InternalType.Arglist;
+			if (arguments != null) {
+				bool dynamic;	// Can be ignored as there is always only 1 overload
+				arguments.Resolve (ec, out dynamic);
+			}
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (arguments != null)
+				arguments.Emit (ec);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			Arglist target = (Arglist) t;
+
+			if (arguments != null)
+				target.arguments = arguments.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class RefValueExpr : ShimExpression, IAssignMethod
+	{
+		FullNamedExpression texpr;
+		
+		public FullNamedExpression FullNamedExpression {
+			get { return texpr;}
+		}
+		
+		public RefValueExpr (Expression expr, FullNamedExpression texpr, Location loc)
+			: base (expr)
+		{
+			this.texpr = texpr;
+			this.loc = loc;
+		}
+
+		public FullNamedExpression TypeExpression {
+			get {
+				return texpr;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			expr = expr.Resolve (rc);
+			type = texpr.ResolveAsType (rc);
+			if (expr == null || type == null)
+				return null;
+
+			expr = Convert.ImplicitConversionRequired (rc, expr, rc.Module.PredefinedTypes.TypedReference.Resolve (), loc);
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			return DoResolve (rc);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			expr.Emit (ec);
+			ec.Emit (OpCodes.Refanyval, type);
+			ec.EmitLoadFromPtr (type);
+		}
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			expr.Emit (ec);
+			ec.Emit (OpCodes.Refanyval, type);
+			source.Emit (ec);
+
+			LocalTemporary temporary = null;
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				temporary = new LocalTemporary (source.Type);
+				temporary.Store (ec);
+			}
+
+			ec.EmitStoreFromPtr (type);
+
+			if (temporary != null) {
+				temporary.Emit (ec);
+				temporary.Release (ec);
+			}
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class RefTypeExpr : ShimExpression
+	{
+		public RefTypeExpr (Expression expr, Location loc)
+			: base (expr)
+		{
+			this.loc = loc;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			expr = expr.Resolve (rc);
+			if (expr == null)
+				return null;
+
+			expr = Convert.ImplicitConversionRequired (rc, expr, rc.Module.PredefinedTypes.TypedReference.Resolve (), loc);
+			if (expr == null)
+				return null;
+
+			type = rc.BuiltinTypes.Type;
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			expr.Emit (ec);
+			ec.Emit (OpCodes.Refanytype);
+			var m = ec.Module.PredefinedMembers.TypeGetTypeFromHandle.Resolve (loc);
+			if (m != null)
+				ec.Emit (OpCodes.Call, m);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class MakeRefExpr : ShimExpression
+	{
+		public MakeRefExpr (Expression expr, Location loc)
+			: base (expr)
+		{
+			this.loc = loc;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			expr = expr.ResolveLValue (rc, EmptyExpression.LValueMemberAccess);
+			type = rc.Module.PredefinedTypes.TypedReference.Resolve ();
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			((IMemoryLocation) expr).AddressOf (ec, AddressOp.Load);
+			ec.Emit (OpCodes.Mkrefany, expr.Type);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implements the typeof operator
+	/// </summary>
+	public class TypeOf : Expression {
+		FullNamedExpression QueriedType;
+		TypeSpec typearg;
+
+		public TypeOf (FullNamedExpression queried_type, Location l)
+		{
+			QueriedType = queried_type;
+			loc = l;
+		}
+
+		//
+		// Use this constructor for any compiler generated typeof expression
+		//
+		public TypeOf (TypeSpec type, Location loc)
+		{
+			this.typearg = type;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		public TypeSpec TypeArgument {
+			get {
+				return typearg;
+			}
+		}
+
+		public FullNamedExpression TypeExpression {
+			get {
+				return QueriedType;
+			}
+		}
+
+		#endregion
+
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			TypeOf target = (TypeOf) t;
+			if (QueriedType != null)
+				target.QueriedType = (FullNamedExpression) QueriedType.Clone (clonectx);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (this));
+			args.Add (new Argument (new TypeOf (new TypeExpression (type, loc), loc)));
+			return CreateExpressionFactoryCall (ec, "Constant", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (eclass != ExprClass.Unresolved)
+				return this;
+
+			if (typearg == null) {
+				//
+				// Pointer types are allowed without explicit unsafe, they are just tokens
+				//
+				using (ec.Set (ResolveContext.Options.UnsafeScope)) {
+					typearg = QueriedType.ResolveAsType (ec, true);
+				}
+
+				if (typearg == null)
+					return null;
+
+				if (typearg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					ec.Report.Error (1962, QueriedType.Location,
+						"The typeof operator cannot be used on the dynamic type");
+				}
+			}
+
+			type = ec.BuiltinTypes.Type;
+
+			// Even though what is returned is a type object, it's treated as a value by the compiler.
+			// In particular, 'typeof (Foo).X' is something totally different from 'Foo.X'.
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		static bool ContainsDynamicType (TypeSpec type)
+		{
+			if (type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+				return true;
+
+			var element_container = type as ElementTypeSpec;
+			if (element_container != null)
+				return ContainsDynamicType (element_container.Element);
+
+			foreach (var t in type.TypeArguments) {
+				if (ContainsDynamicType (t)) {
+					return true;
+				}
+			}
+
+			return false;
+		}
+
+		public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType)
+		{
+			// Target type is not System.Type therefore must be object
+			// and we need to use different encoding sequence
+			if (targetType != type)
+				enc.Encode (type);
+
+			if (typearg is InflatedTypeSpec) {
+				var gt = typearg;
+				do {
+					if (InflatedTypeSpec.ContainsTypeParameter (gt)) {
+						rc.Module.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
+							typearg.GetSignatureForError ());
+						return;
+					}
+
+					gt = gt.DeclaringType;
+				} while (gt != null);
+			}
+
+			if (ContainsDynamicType (typearg)) {
+				Attribute.Error_AttributeArgumentIsDynamic (rc, loc);
+				return;
+			}
+
+			enc.EncodeTypeName (typearg);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Ldtoken, typearg);
+			var m = ec.Module.PredefinedMembers.TypeGetTypeFromHandle.Resolve (loc);
+			if (m != null)
+				ec.Emit (OpCodes.Call, m);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	sealed class TypeOfMethod : TypeOfMember<MethodSpec>
+	{
+		public TypeOfMethod (MethodSpec method, Location loc)
+			: base (method, loc)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (member.IsConstructor) {
+				type = ec.Module.PredefinedTypes.ConstructorInfo.Resolve ();
+			} else {
+				type = ec.Module.PredefinedTypes.MethodInfo.Resolve ();
+			}
+
+			if (type == null)
+				return null;
+
+			return base.DoResolve (ec);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Ldtoken, member);
+
+			base.Emit (ec);
+			ec.Emit (OpCodes.Castclass, type);
+		}
+
+		protected override PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec)
+		{
+			return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle;
+		}
+
+		protected override PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec)
+		{
+			return ec.Module.PredefinedMembers.MethodInfoGetMethodFromHandle2;
+		}
+	}
+
+	abstract class TypeOfMember<T> : Expression where T : MemberSpec
+	{
+		protected readonly T member;
+
+		protected TypeOfMember (T member, Location loc)
+		{
+			this.member = member;
+			this.loc = loc;
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (this));
+			args.Add (new Argument (new TypeOf (type, loc)));
+			return CreateExpressionFactoryCall (ec, "Constant", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
+			PredefinedMember<MethodSpec> p;
+			if (is_generic) {
+				p = GetTypeFromHandleGeneric (ec);
+				ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
+			} else {
+				p = GetTypeFromHandle (ec);
+			}
+
+			var mi = p.Resolve (loc);
+			if (mi != null)
+				ec.Emit (OpCodes.Call, mi);
+		}
+
+		protected abstract PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec);
+		protected abstract PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec);
+	}
+
+	sealed class TypeOfField : TypeOfMember<FieldSpec>
+	{
+		public TypeOfField (FieldSpec field, Location loc)
+			: base (field, loc)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			type = ec.Module.PredefinedTypes.FieldInfo.Resolve ();
+			if (type == null)
+				return null;
+
+			return base.DoResolve (ec);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Ldtoken, member);
+			base.Emit (ec);
+		}
+
+		protected override PredefinedMember<MethodSpec> GetTypeFromHandle (EmitContext ec)
+		{
+			return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle;
+		}
+
+		protected override PredefinedMember<MethodSpec> GetTypeFromHandleGeneric (EmitContext ec)
+		{
+			return ec.Module.PredefinedMembers.FieldInfoGetFieldFromHandle2;
+		}
+	}
+
+	/// <summary>
+	///   Implements the sizeof expression
+	/// </summary>
+	public class SizeOf : Expression {
+		readonly Expression texpr;
+		TypeSpec type_queried;
+		
+		public SizeOf (Expression queried_type, Location l)
+		{
+			this.texpr = queried_type;
+			loc = l;
+		}
+
+		public override bool IsSideEffectFree {
+			get {
+				return true;
+			}
+		}
+
+		public Expression TypeExpression {
+			get {
+				return texpr;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Error_PointerInsideExpressionTree (ec);
+			return null;
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			type_queried = texpr.ResolveAsType (ec);
+			if (type_queried == null)
+				return null;
+
+			if (type_queried.IsEnum)
+				type_queried = EnumSpec.GetUnderlyingType (type_queried);
+
+			int size_of = BuiltinTypeSpec.GetSize (type_queried);
+			if (size_of > 0) {
+				return new IntConstant (ec.BuiltinTypes, size_of, loc);
+			}
+
+			if (!TypeManager.VerifyUnmanaged (ec.Module, type_queried, loc)){
+				return null;
+			}
+
+			if (!ec.IsUnsafe) {
+				ec.Report.Error (233, loc,
+					"`{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)",
+					type_queried.GetSignatureForError ());
+			}
+			
+			type = ec.BuiltinTypes.Int;
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			ec.Emit (OpCodes.Sizeof, type_queried);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implements the qualified-alias-member (::) expression.
+	/// </summary>
+	public class QualifiedAliasMember : MemberAccess
+	{
+		public readonly string alias;
+		public static readonly string GlobalAlias = "global";
+
+		public QualifiedAliasMember (string alias, string identifier, Location l)
+			: base (null, identifier, l)
+		{
+			this.alias = alias;
+		}
+
+		public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
+			: base (null, identifier, targs, l)
+		{
+			this.alias = alias;
+		}
+
+		public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
+			: base (null, identifier, arity, l)
+		{
+			this.alias = alias;
+		}
+
+		public string Alias {
+			get {
+				return alias;
+			}
+		}
+
+		public FullNamedExpression CreateExpressionFromAlias (IMemberContext mc)
+		{
+			if (alias == GlobalAlias)
+				return new NamespaceExpression (mc.Module.GlobalRootNamespace, loc);
+
+			int errors = mc.Module.Compiler.Report.Errors;
+			var expr = mc.LookupNamespaceAlias (alias);
+			if (expr == null) {
+				if (errors == mc.Module.Compiler.Report.Errors)
+					mc.Module.Compiler.Report.Error (432, loc, "Alias `{0}' not found", alias);
+
+				return null;
+			}
+
+			return expr;
+		}
+
+		public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments)
+		{
+			expr = CreateExpressionFromAlias (mc);
+			if (expr == null)
+				return null;
+
+			return base.ResolveAsTypeOrNamespace (mc, allowUnboundTypeArguments);
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			return ResolveAsTypeOrNamespace (rc, false);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			string name = Name;
+			if (targs != null) {
+				name = Name + "<" + targs.GetSignatureForError () + ">";
+			}
+
+			return alias + "::" + name;
+		}
+
+		public override bool HasConditionalAccess ()
+		{
+			return false;
+		}
+
+		public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
+		{
+			if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) {
+				rc.Module.Compiler.Report.Error (687, loc,
+					"The namespace alias qualifier `::' cannot be used to invoke a method. Consider using `.' instead",
+					GetSignatureForError ());
+
+				return null;
+			}
+
+			return DoResolve (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			// Nothing 
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implements the member access expression
+	/// </summary>
+	public class MemberAccess : ATypeNameExpression
+	{
+		protected Expression expr;
+		
+		public MemberAccess (Expression expr, string id)
+			: base (id, expr.Location)
+		{
+			this.expr = expr;
+		}
+
+		public MemberAccess (Expression expr, string identifier, Location loc)
+			: base (identifier, loc)
+		{
+			this.expr = expr;
+		}
+
+		public MemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
+			: base (identifier, args, loc)
+		{
+			this.expr = expr;
+		}
+
+		public MemberAccess (Expression expr, string identifier, int arity, Location loc)
+			: base (identifier, arity, loc)
+		{
+			this.expr = expr;
+		}
+
+		public Expression LeftExpression {
+			get {
+				return expr;
+			}
+		}
+
+		public override Location StartLocation {
+			get {
+				return expr == null ? loc : expr.StartLocation;
+			}
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			var e = LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess);
+			if (e != null)
+				e = e.Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.Type | ResolveFlags.MethodGroup);
+
+			return e;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression rhs)
+		{
+			var e = LookupNameExpression (rc, MemberLookupRestrictions.None);
+
+			if (e is TypeExpr) {
+				e.Error_UnexpectedKind (rc, ResolveFlags.VariableOrValue, loc);
+				return null;
+			}
+
+			if (e != null)
+				e = e.ResolveLValue (rc, rhs);
+
+			return e;
+		}
+
+		protected virtual void Error_OperatorCannotBeApplied (ResolveContext rc, TypeSpec type)
+		{
+			if (type == InternalType.NullLiteral && rc.IsRuntimeBinder)
+				rc.Report.Error (Report.RuntimeErrorId, loc, "Cannot perform member binding on `null' value");
+			else
+				expr.Error_OperatorCannotBeApplied (rc, loc, ".", type);
+		}
+
+		public override bool HasConditionalAccess ()
+		{
+			return LeftExpression.HasConditionalAccess ();
+		}
+
+		public static bool IsValidDotExpression (TypeSpec type)
+		{
+			const MemberKind dot_kinds = MemberKind.Class | MemberKind.Struct | MemberKind.Delegate | MemberKind.Enum |
+				MemberKind.Interface | MemberKind.TypeParameter | MemberKind.ArrayType;
+
+			return (type.Kind & dot_kinds) != 0 || type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+		}
+
+		public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
+		{
+			var sn = expr as SimpleName;
+			const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;
+
+			if (sn != null) {
+				expr = sn.LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);
+
+				//
+				// Resolve expression which does have type set as we need expression type
+				// with disable flow analysis as we don't know whether left side expression
+				// is used as variable or type
+				//
+				if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess || expr is EventExpr) {
+					expr = expr.Resolve (rc);
+				} else if (expr is TypeParameterExpr) {
+					expr.Error_UnexpectedKind (rc, flags, sn.Location);
+					expr = null;
+				}
+			} else {
+				using (rc.Set (ResolveContext.Options.ConditionalAccessReceiver)) {
+					expr = expr.Resolve (rc, flags);
+				}
+			}
+
+			if (expr == null)
+				return null;
+
+			var ns = expr as NamespaceExpression;
+			if (ns != null) {
+				var retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
+
+				if (retval == null) {
+					ns.Error_NamespaceDoesNotExist (rc, Name, Arity);
+					return null;
+				}
+
+				if (HasTypeArguments)
+					return new GenericTypeExpr (retval.Type, targs, loc);
+
+				return retval;
+			}
+
+			MemberExpr me;
+			TypeSpec expr_type = expr.Type;
+			if (expr_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				me = expr as MemberExpr;
+				if (me != null)
+					me.ResolveInstanceExpression (rc, null);
+
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (expr));
+				return new DynamicMemberBinder (Name, args, loc);
+			}
+
+			var cma = this as ConditionalMemberAccess;
+			if (cma != null) {
+				if (!IsNullPropagatingValid (expr.Type)) {
+					expr.Error_OperatorCannotBeApplied (rc, loc, "?", expr.Type);
+					return null;
+				}
+
+				if (expr_type.IsNullableType) {
+					expr = Nullable.Unwrap.Create (expr, true).Resolve (rc);
+					expr_type = expr.Type;
+				}
+			}
+
+			if (!IsValidDotExpression (expr_type)) {
+				Error_OperatorCannotBeApplied (rc, expr_type);
+				return null;
+			}
+
+			var lookup_arity = Arity;
+			bool errorMode = false;
+			Expression member_lookup;
+			while (true) {
+				member_lookup = MemberLookup (rc, errorMode, expr_type, Name, lookup_arity, restrictions, loc);
+				if (member_lookup == null) {
+					//
+					// Try to look for extension method when member lookup failed
+					//
+					if (MethodGroupExpr.IsExtensionMethodArgument (expr)) {
+						var methods = rc.LookupExtensionMethod (expr_type, Name, lookup_arity);
+						if (methods != null) {
+							var emg = new ExtensionMethodGroupExpr (methods, expr, loc);
+							if (HasTypeArguments) {
+								if (!targs.Resolve (rc))
+									return null;
+
+								emg.SetTypeArguments (rc, targs);
+							}
+
+							if (cma != null)
+								emg.ConditionalAccess = true;
+
+							// TODO: it should really skip the checks bellow
+							return emg.Resolve (rc);
+						}
+					}
+				}
+
+				if (errorMode) {
+					if (member_lookup == null) {
+						var dep = expr_type.GetMissingDependencies ();
+						if (dep != null) {
+							ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
+						} else if (expr is TypeExpr) {
+							base.Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
+						} else {
+							Error_TypeDoesNotContainDefinition (rc, expr_type, Name);
+						}
+
+						return null;
+					}
+
+					if (member_lookup is MethodGroupExpr || member_lookup is PropertyExpr) {
+						// Leave it to overload resolution to report correct error
+					} else if (!(member_lookup is TypeExpr)) {
+						// TODO: rc.SymbolRelatedToPreviousError
+						ErrorIsInaccesible (rc, member_lookup.GetSignatureForError (), loc);
+					}
+					break;
+				}
+
+				if (member_lookup != null)
+					break;
+
+				lookup_arity = 0;
+				restrictions &= ~MemberLookupRestrictions.InvocableOnly;
+				errorMode = true;
+			}
+
+			TypeExpr texpr = member_lookup as TypeExpr;
+			if (texpr != null) {
+				if (!(expr is TypeExpr) && (sn == null || expr.ProbeIdenticalTypeName (rc, expr, sn) == expr)) {
+					rc.Report.Error (572, loc, "`{0}': cannot reference a type through an expression. Consider using `{1}' instead",
+						Name, texpr.GetSignatureForError ());
+				}
+
+				if (!texpr.Type.IsAccessible (rc)) {
+					rc.Report.SymbolRelatedToPreviousError (member_lookup.Type);
+					ErrorIsInaccesible (rc, member_lookup.Type.GetSignatureForError (), loc);
+					return null;
+				}
+
+				if (HasTypeArguments) {
+					return new GenericTypeExpr (member_lookup.Type, targs, loc);
+				}
+
+				return member_lookup;
+			}
+
+			me = member_lookup as MemberExpr;
+
+			if (sn != null && me.IsStatic && (expr = me.ProbeIdenticalTypeName (rc, expr, sn)) != expr) {
+				sn = null;
+			}
+
+			if (cma != null) {
+				me.ConditionalAccess = true;
+			}
+
+			me = me.ResolveMemberAccess (rc, expr, sn);
+
+			if (Arity > 0) {
+				if (!targs.Resolve (rc))
+					return null;
+
+				me.SetTypeArguments (rc, targs);
+			}
+
+			return me;
+		}
+
+		public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext rc, bool allowUnboundTypeArguments)
+		{
+			FullNamedExpression fexpr = expr as FullNamedExpression;
+			if (fexpr == null) {
+				expr.ResolveAsType (rc);
+				return null;
+			}
+
+			FullNamedExpression expr_resolved = fexpr.ResolveAsTypeOrNamespace (rc, allowUnboundTypeArguments);
+
+			if (expr_resolved == null)
+				return null;
+
+			var ns = expr_resolved as NamespaceExpression;
+			if (ns != null) {
+				FullNamedExpression retval = ns.LookupTypeOrNamespace (rc, Name, Arity, LookupMode.Normal, loc);
+
+				if (retval == null) {
+					ns.Error_NamespaceDoesNotExist (rc, Name, Arity);
+				} else if (Arity > 0) {
+					if (HasTypeArguments) {
+						retval = new GenericTypeExpr (retval.Type, targs, loc);
+						if (retval.ResolveAsType (rc) == null)
+							return null;
+					} else {
+						if (!allowUnboundTypeArguments)
+							Error_OpenGenericTypeIsNotAllowed (rc);
+
+						retval = new GenericOpenTypeExpr (retval.Type, loc);
+					}
+				}
+
+				return retval;
+			}
+
+			var tnew_expr = expr_resolved.ResolveAsType (rc);
+			if (tnew_expr == null)
+				return null;
+
+			TypeSpec expr_type = tnew_expr;
+			if (TypeManager.IsGenericParameter (expr_type)) {
+				rc.Module.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
+					tnew_expr.GetSignatureForError ());
+				return null;
+			}
+
+			var qam = this as QualifiedAliasMember;
+			if (qam != null) {
+				rc.Module.Compiler.Report.Error (431, loc,
+					"Alias `{0}' cannot be used with `::' since it denotes a type. Consider replacing `::' with `.'",
+					qam.Alias);
+
+			}
+
+			TypeSpec nested = null;
+			while (expr_type != null) {
+				nested = MemberCache.FindNestedType (expr_type, Name, Arity);
+				if (nested == null) {
+					if (expr_type == tnew_expr) {
+						Error_IdentifierNotFound (rc, expr_type);
+						return null;
+					}
+
+					expr_type = tnew_expr;
+					nested = MemberCache.FindNestedType (expr_type, Name, Arity);
+					ErrorIsInaccesible (rc, nested.GetSignatureForError (), loc);
+					break;
+				}
+
+				if (nested.IsAccessible (rc))
+					break;
+
+				//
+				// Keep looking after inaccessible candidate but only if
+				// we are not in same context as the definition itself
+ 				//
+				if (expr_type.MemberDefinition == rc.CurrentMemberDefinition)
+					break;
+
+				expr_type = expr_type.BaseType;
+			}
+			
+			TypeExpr texpr;
+			if (Arity > 0) {
+				if (HasTypeArguments) {
+					texpr = new GenericTypeExpr (nested, targs, loc);
+				} else {
+					if (!allowUnboundTypeArguments || expr_resolved is GenericTypeExpr) // && HasTypeArguments
+						Error_OpenGenericTypeIsNotAllowed (rc);
+
+					texpr = new GenericOpenTypeExpr (nested, loc);
+				}
+			} else if (expr_resolved is GenericOpenTypeExpr) {
+				texpr = new GenericOpenTypeExpr (nested, loc);
+			} else {
+				texpr = new TypeExpression (nested, loc);
+			}
+
+			if (texpr.ResolveAsType (rc) == null)
+				return null;
+
+			return texpr;
+		}
+
+		public void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type)
+		{
+			var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
+
+			if (nested != null) {
+				Error_TypeArgumentsCannotBeUsed (rc, nested, expr.Location);
+				return;
+			}
+
+			var any_other_member = MemberLookup (rc, false, expr_type, Name, 0, MemberLookupRestrictions.None, loc);
+			if (any_other_member != null) {
+				Error_UnexpectedKind (rc, any_other_member, "type", any_other_member.ExprClassName, loc);
+				return;
+			}
+
+			rc.Module.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
+				Name, expr_type.GetSignatureForError ());
+		}
+
+		protected override void Error_InvalidExpressionStatement (Report report, Location loc)
+		{
+			base.Error_InvalidExpressionStatement (report, LeftExpression.Location);
+		}
+
+		protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
+		{
+			if (ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2 && !ec.IsRuntimeBinder && MethodGroupExpr.IsExtensionMethodArgument (expr)) {
+				ec.Report.SymbolRelatedToPreviousError (type);
+
+				var cand = ec.Module.GlobalRootNamespace.FindExtensionMethodNamespaces (ec, name, Arity);
+				string missing;
+				// a using directive or an assembly reference
+				if (cand != null) {
+					missing = "`" + string.Join ("' or `", cand.ToArray ()) + "' using directive";
+				} else {
+					missing = "an assembly reference";
+				}
+
+				ec.Report.Error (1061, loc,
+					"Type `{0}' does not contain a definition for `{1}' and no extension method `{1}' of type `{0}' could be found. Are you missing {2}?",
+					type.GetSignatureForError (), name, missing);
+				return;
+			}
+
+			base.Error_TypeDoesNotContainDefinition (ec, type, name);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return expr.GetSignatureForError () + "." + base.GetSignatureForError ();
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			MemberAccess target = (MemberAccess) t;
+
+			target.expr = expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ConditionalMemberAccess : MemberAccess
+	{
+		public ConditionalMemberAccess (Expression expr, string identifier, TypeArguments args, Location loc)
+			: base (expr, identifier, args, loc)
+		{
+		}
+
+		public override bool HasConditionalAccess ()
+		{
+			return true;
+		}
+	}
+
+	/// <summary>
+	///   Implements checked expressions
+	/// </summary>
+	public class CheckedExpr : Expression {
+
+		public Expression Expr;
+		
+		public CheckedExpr (Expression e, Location l)
+		{
+			Expr = e;
+			loc = l;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return Expr.ContainsEmitWithAwait ();
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
+				return Expr.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
+				Expr = Expr.Resolve (ec);
+			
+			if (Expr == null)
+				return null;
+
+			if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
+				return Expr;
+			
+			eclass = Expr.eclass;
+			type = Expr.Type;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			using (ec.With (EmitContext.Options.CheckedScope, true))
+				Expr.Emit (ec);
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			using (ec.With (EmitContext.Options.CheckedScope, true))
+				Expr.EmitBranchable (ec, target, on_true);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			Expr.FlowAnalysis (fc);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			using (ctx.With (BuilderContext.Options.CheckedScope, true)) {
+				return Expr.MakeExpression (ctx);
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			CheckedExpr target = (CheckedExpr) t;
+
+			target.Expr = Expr.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implements the unchecked expression
+	/// </summary>
+	public class UnCheckedExpr : Expression {
+
+		public Expression Expr;
+
+		public UnCheckedExpr (Expression e, Location l)
+		{
+			Expr = e;
+			loc = l;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return Expr.ContainsEmitWithAwait ();
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
+				return Expr.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
+				Expr = Expr.Resolve (ec);
+
+			if (Expr == null)
+				return null;
+
+			if (Expr is Constant || Expr is MethodGroupExpr || Expr is AnonymousMethodExpression || Expr is DefaultValueExpression)
+				return Expr;
+			
+			eclass = Expr.eclass;
+			type = Expr.Type;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			using (ec.With (EmitContext.Options.CheckedScope, false))
+				Expr.Emit (ec);
+		}
+
+		public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
+		{
+			using (ec.With (EmitContext.Options.CheckedScope, false))
+				Expr.EmitBranchable (ec, target, on_true);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			Expr.FlowAnalysis (fc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			UnCheckedExpr target = (UnCheckedExpr) t;
+
+			target.Expr = Expr.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   An Element Access expression.
+	///
+	///   During semantic analysis these are transformed into 
+	///   IndexerAccess, ArrayAccess or a PointerArithmetic.
+	/// </summary>
+	public class ElementAccess : Expression
+	{
+		public Arguments Arguments;
+		public Expression Expr;
+
+		public ElementAccess (Expression e, Arguments args, Location loc)
+		{
+			Expr = e;
+			this.loc = loc;
+			this.Arguments = args;
+		}
+
+		public bool ConditionalAccess { get; set; }
+
+		public override Location StartLocation {
+			get {
+				return Expr.StartLocation;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return Expr.ContainsEmitWithAwait () || Arguments.ContainsEmitWithAwait ();
+		}
+
+		//
+		// We perform some simple tests, and then to "split" the emit and store
+		// code we create an instance of a different class, and return that.
+		//
+		Expression CreateAccessExpression (ResolveContext ec, bool conditionalAccessReceiver)
+		{
+			Expr = Expr.Resolve (ec);
+			if (Expr == null)
+				return null;
+
+			type = Expr.Type;
+
+			if (ConditionalAccess && !IsNullPropagatingValid (type)) {
+				Error_OperatorCannotBeApplied (ec, loc, "?", type);
+				return null;
+			}
+
+			if (type.IsArray)
+				return new ArrayAccess (this, loc) {
+					ConditionalAccess = ConditionalAccess,
+					ConditionalAccessReceiver = conditionalAccessReceiver
+				};
+
+			if (type.IsPointer)
+				return MakePointerAccess (ec, type);
+
+			FieldExpr fe = Expr as FieldExpr;
+			if (fe != null) {
+				var ff = fe.Spec as FixedFieldSpec;
+				if (ff != null) {
+					return MakePointerAccess (ec, ff.ElementType);
+				}
+			}
+
+			var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
+			if (indexers != null || type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				var indexer = new IndexerExpr (indexers, type, this) {
+					ConditionalAccess = ConditionalAccess
+				};
+
+				if (conditionalAccessReceiver)
+					indexer.SetConditionalAccessReceiver ();
+
+				return indexer;
+			}
+
+			Error_CannotApplyIndexing (ec, type, loc);
+
+			return null;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = Arguments.CreateForExpressionTree (ec, Arguments,
+				Expr.CreateExpressionTree (ec));
+
+			return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
+		}
+
+		public static void Error_CannotApplyIndexing (ResolveContext rc, TypeSpec type, Location loc)
+		{
+			if (type != InternalType.ErrorType) {
+				rc.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
+					type.GetSignatureForError ());
+			}
+		}
+
+		public override bool HasConditionalAccess ()
+		{
+			return ConditionalAccess || Expr.HasConditionalAccess ();
+		}
+
+		Expression MakePointerAccess (ResolveContext rc, TypeSpec type)
+		{
+			if (Arguments.Count != 1){
+				rc.Report.Error (196, loc, "A pointer must be indexed by only one value");
+				return null;
+			}
+
+			var arg = Arguments[0];
+			if (arg is NamedArgument)
+				Error_NamedArgument ((NamedArgument) arg, rc.Report);
+
+			var index = arg.Expr.Resolve (rc);
+			if (index == null)
+				return null;
+
+			index = ConvertExpressionToArrayIndex (rc, index, true);
+
+			Expression p = new PointerArithmetic (Binary.Operator.Addition, Expr, index, type, loc);
+			return new Indirection (p, loc);
+		}
+		
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			Expression expr;
+			if (!rc.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) {
+				if (HasConditionalAccess ()) {
+					using (rc.Set (ResolveContext.Options.ConditionalAccessReceiver)) {
+						expr = CreateAccessExpression (rc, true);
+						if (expr == null)
+							return null;
+
+						return expr.Resolve (rc);
+					}
+				}
+			}
+
+			expr = CreateAccessExpression (rc, false);
+			if (expr == null)
+				return null;
+
+			return expr.Resolve (rc);
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression rhs)
+		{
+			var res = CreateAccessExpression (ec, false);
+			if (res == null)
+				return null;
+
+			return res.ResolveLValue (ec, rhs);
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			throw new Exception ("Should never be reached");
+		}
+
+		public static void Error_NamedArgument (NamedArgument na, Report Report)
+		{
+			Report.Error (1742, na.Location, "An element access expression cannot use named argument");
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			Expr.FlowAnalysis (fc);
+
+			if (ConditionalAccess)
+				fc.BranchConditionalAccessDefiniteAssignment ();
+
+			Arguments.FlowAnalysis (fc);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return Expr.GetSignatureForError ();
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			ElementAccess target = (ElementAccess) t;
+
+			target.Expr = Expr.Clone (clonectx);
+			if (Arguments != null)
+				target.Arguments = Arguments.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implements array access 
+	/// </summary>
+	public class ArrayAccess : Expression, IDynamicAssign, IMemoryLocation {
+		//
+		// Points to our "data" repository
+		//
+		ElementAccess ea;
+
+		LocalTemporary temp;
+		bool prepared;
+		bool? has_await_args;
+		
+		public ArrayAccess (ElementAccess ea_data, Location l)
+		{
+			ea = ea_data;
+			loc = l;
+		}
+
+		public bool ConditionalAccess { get; set; }
+
+		public bool ConditionalAccessReceiver { get; set; }
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			var ac = (ArrayContainer) ea.Expr.Type;
+
+			if (!has_await_args.HasValue && ec.HasSet (BuilderContext.Options.AsyncBody) && ea.Arguments.ContainsEmitWithAwait ()) {
+				LoadInstanceAndArguments (ec, false, true);
+			}
+
+			LoadInstanceAndArguments (ec, false, false);
+
+			if (ac.Element.IsGenericParameter && mode == AddressOp.Load)
+				ec.Emit (OpCodes.Readonly);
+
+			ec.EmitArrayAddress (ac);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (ConditionalAccess)
+				Error_NullShortCircuitInsideExpressionTree (ec);
+
+			return ea.CreateExpressionTree (ec);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return ea.ContainsEmitWithAwait ();
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			if (ConditionalAccess)
+				throw new NotSupportedException ("null propagating operator assignment");
+
+			return DoResolve (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			// dynamic is used per argument in ConvertExpressionToArrayIndex case
+			bool dynamic;
+			ea.Arguments.Resolve (ec, out dynamic);
+
+			var ac = ea.Expr.Type as ArrayContainer;
+			int rank = ea.Arguments.Count;
+			if (ac.Rank != rank) {
+				ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
+					  rank.ToString (), ac.Rank.ToString ());
+				return null;
+			}
+
+			type = ac.Element;
+			if (type.IsPointer && !ec.IsUnsafe) {
+				UnsafeError (ec, ea.Location);
+			}
+
+			if (ConditionalAccessReceiver)
+				type = LiftMemberType (ec, type);
+
+			foreach (Argument a in ea.Arguments) {
+				var na = a as NamedArgument;
+				if (na != null)
+					ElementAccess.Error_NamedArgument (na, ec.Report);
+
+				a.Expr = ConvertExpressionToArrayIndex (ec, a.Expr);
+			}
+			
+			eclass = ExprClass.Variable;
+
+			return this;
+		}
+
+		protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
+		{
+			ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			ea.FlowAnalysis (fc);
+		}
+
+		//
+		// Load the array arguments into the stack.
+		//
+		void LoadInstanceAndArguments (EmitContext ec, bool duplicateArguments, bool prepareAwait)
+		{
+			if (prepareAwait) {
+				ea.Expr = ea.Expr.EmitToField (ec);
+			} else {
+				var ie = new InstanceEmitter (ea.Expr, false);
+				ie.Emit (ec, ConditionalAccess);
+
+				if (duplicateArguments) {
+					ec.Emit (OpCodes.Dup);
+
+					var copy = new LocalTemporary (ea.Expr.Type);
+					copy.Store (ec);
+					ea.Expr = copy;
+				}
+			}
+
+			var dup_args = ea.Arguments.Emit (ec, duplicateArguments, prepareAwait);
+			if (dup_args != null)
+				ea.Arguments = dup_args;
+		}
+
+		public void Emit (EmitContext ec, bool leave_copy)
+		{
+			if (prepared) {
+				ec.EmitLoadFromPtr (type);
+			} else {
+				if (!has_await_args.HasValue && ec.HasSet (BuilderContext.Options.AsyncBody) && ea.Arguments.ContainsEmitWithAwait ()) {
+					LoadInstanceAndArguments (ec, false, true);
+				}
+
+				if (ConditionalAccessReceiver)
+					ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ());
+
+				var ac = (ArrayContainer) ea.Expr.Type;
+				LoadInstanceAndArguments (ec, false, false);
+				ec.EmitArrayLoad (ac);
+
+				if (ConditionalAccessReceiver)
+					ec.CloseConditionalAccess (type.IsNullableType && type != ac.Element ? type : null);
+			}	
+
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				temp = new LocalTemporary (this.type);
+				temp.Store (ec);
+			}
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			Emit (ec, false);
+		}
+
+		public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			var ac = (ArrayContainer) ea.Expr.Type;
+			TypeSpec t = source.Type;
+
+			has_await_args = ec.HasSet (BuilderContext.Options.AsyncBody) && (ea.Arguments.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ());
+
+			//
+			// When we are dealing with a struct, get the address of it to avoid value copy
+			// Same cannot be done for reference type because array covariance and the
+			// check in ldelema requires to specify the type of array element stored at the index
+			//
+			if (t.IsStruct && ((isCompound && !(source is DynamicExpressionStatement)) || !BuiltinTypeSpec.IsPrimitiveType (t))) {
+				LoadInstanceAndArguments (ec, false, has_await_args.Value);
+
+				if (has_await_args.Value) {
+					if (source.ContainsEmitWithAwait ()) {
+						source = source.EmitToField (ec);
+						isCompound = false;
+						prepared = true;
+					}
+
+					LoadInstanceAndArguments (ec, isCompound, false);
+				} else {
+					prepared = true;
+				}
+
+				ec.EmitArrayAddress (ac);
+
+				if (isCompound) {
+					ec.Emit (OpCodes.Dup);
+					prepared = true;
+				}
+			} else {
+				LoadInstanceAndArguments (ec, isCompound, has_await_args.Value);
+
+				if (has_await_args.Value) {
+					if (source.ContainsEmitWithAwait ())
+						source = source.EmitToField (ec);
+
+					LoadInstanceAndArguments (ec, false, false);
+				}
+			}
+
+			source.Emit (ec);
+
+			if (isCompound) {
+				var lt = ea.Expr as LocalTemporary;
+				if (lt != null)
+					lt.Release (ec);
+			}
+
+			if (leave_copy) {
+				ec.Emit (OpCodes.Dup);
+				temp = new LocalTemporary (this.type);
+				temp.Store (ec);
+			}
+
+			if (prepared) {
+				ec.EmitStoreFromPtr (t);
+			} else {
+				ec.EmitArrayStore (ac);
+			}
+			
+			if (temp != null) {
+				temp.Emit (ec);
+				temp.Release (ec);
+			}
+		}
+
+		public override Expression EmitToField (EmitContext ec)
+		{
+			//
+			// Have to be specialized for arrays to get access to
+			// underlying element. Instead of another result copy we
+			// need direct access to element 
+			//
+			// Consider:
+			//
+			// CallRef (ref a[await Task.Factory.StartNew (() => 1)]);
+			//
+			ea.Expr = ea.Expr.EmitToField (ec);
+			ea.Arguments = ea.Arguments.Emit (ec, false, true);
+			return this;
+		}
+
+		public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
+		{
+#if NET_4_0 || MOBILE_DYNAMIC
+			return SLE.Expression.ArrayAccess (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
+#else
+			throw new NotImplementedException ();
+#endif
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return SLE.Expression.ArrayIndex (ea.Expr.MakeExpression (ctx), MakeExpressionArguments (ctx));
+		}
+
+		SLE.Expression[] MakeExpressionArguments (BuilderContext ctx)
+		{
+			using (ctx.With (BuilderContext.Options.CheckedScope, true)) {
+				return Arguments.MakeExpression (ea.Arguments, ctx);
+			}
+		}
+	}
+
+	//
+	// Indexer access expression
+	//
+	class IndexerExpr : PropertyOrIndexerExpr<IndexerSpec>, OverloadResolver.IBaseMembersProvider
+	{
+		IList<MemberSpec> indexers;
+		Arguments arguments;
+		TypeSpec queried_type;
+		
+		public IndexerExpr (IList<MemberSpec> indexers, TypeSpec queriedType, ElementAccess ea)
+			: this (indexers, queriedType, ea.Expr, ea.Arguments, ea.Location)
+		{
+		}
+
+		public IndexerExpr (IList<MemberSpec> indexers, TypeSpec queriedType, Expression instance, Arguments args, Location loc)
+			: base (loc)
+		{
+			this.indexers = indexers;
+			this.queried_type = queriedType;
+			this.InstanceExpression = instance;
+			this.arguments = args;
+		}
+
+		#region Properties
+
+		protected override Arguments Arguments {
+			get {
+				return arguments;
+			}
+			set {
+				arguments = value;
+			}
+		}
+
+		protected override TypeSpec DeclaringType {
+			get {
+				return best_candidate.DeclaringType;
+			}
+		}
+
+		public override bool IsInstance {
+			get {
+				return true;
+			}
+		}
+
+		public override bool IsStatic {
+			get {
+				return false;
+			}
+		}
+
+		public override string KindName {
+			get { return "indexer"; }
+		}
+
+		public override string Name {
+			get {
+				return "this";
+			}
+		}
+
+		#endregion
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return base.ContainsEmitWithAwait () || arguments.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (ConditionalAccess) {
+				Error_NullShortCircuitInsideExpressionTree (ec);
+			}
+
+			Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
+				InstanceExpression.CreateExpressionTree (ec),
+				new TypeOfMethod (Getter, loc));
+
+			return CreateExpressionFactoryCall (ec, "Call", args);
+		}
+	
+		public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
+		{
+			LocalTemporary await_source_arg = null;
+
+			if (isCompound) {
+				emitting_compound_assignment = true;
+				if (source is DynamicExpressionStatement) {
+					Emit (ec, false);
+				} else {
+					source.Emit (ec);
+				}
+				emitting_compound_assignment = false;
+
+				if (has_await_arguments) {
+					await_source_arg = new LocalTemporary (Type);
+					await_source_arg.Store (ec);
+
+					arguments.Add (new Argument (await_source_arg));
+
+					if (leave_copy) {
+						temp = await_source_arg;
+					}
+
+					has_await_arguments = false;
+				} else {
+					arguments = null;
+
+					if (leave_copy) {
+						ec.Emit (OpCodes.Dup);
+						temp = new LocalTemporary (Type);
+						temp.Store (ec);
+					}
+				}
+			} else {
+				if (leave_copy) {
+					if (ec.HasSet (BuilderContext.Options.AsyncBody) && (arguments.ContainsEmitWithAwait () || source.ContainsEmitWithAwait ())) {
+						source = source.EmitToField (ec);
+					} else {
+						temp = new LocalTemporary (Type);
+						source.Emit (ec);
+						temp.Store (ec);
+						source = temp;
+					}
+				}
+
+				arguments.Add (new Argument (source));
+			}
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = InstanceExpression;
+			if (arguments == null)
+				call.InstanceExpressionOnStack = true;
+
+			call.Emit (ec, Setter, arguments, loc);
+
+			if (temp != null) {
+				temp.Emit (ec);
+				temp.Release (ec);
+			} else if (leave_copy) {
+				source.Emit (ec);
+			}
+
+			if (await_source_arg != null) {
+				await_source_arg.Release (ec);
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.FlowAnalysis (fc);
+			arguments.FlowAnalysis (fc);
+
+			if (conditional_access_receiver)
+				fc.ConditionalAccessEnd ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return best_candidate.GetSignatureForError ();
+		}
+		
+		public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
+		{
+#if STATIC
+			throw new NotSupportedException ();
+#else
+			var value = new[] { source.MakeExpression (ctx) };
+			var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
+#if NET_4_0 || MOBILE_DYNAMIC
+			return SLE.Expression.Block (
+					SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo (), args),
+					value [0]);
+#else
+			return args.First ();
+#endif
+#endif
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			var args = Arguments.MakeExpression (arguments, ctx);
+			return SLE.Expression.Call (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo (), args);
+#endif
+		}
+
+		protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
+		{
+			if (best_candidate != null)
+				return this;
+
+			eclass = ExprClass.IndexerAccess;
+
+			bool dynamic;
+			arguments.Resolve (rc, out dynamic);
+
+			if (indexers == null && InstanceExpression.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				dynamic = true;
+			} else {
+				var res = new OverloadResolver (indexers, OverloadResolver.Restrictions.None, loc);
+				res.BaseMembersProvider = this;
+				res.InstanceQualifier = this;
+
+				// TODO: Do I need 2 argument sets?
+				best_candidate = res.ResolveMember<IndexerSpec> (rc, ref arguments);
+				if (best_candidate != null)
+					type = res.BestCandidateReturnType;
+				else if (!res.BestCandidateIsDynamic)
+					return null;
+			}
+
+			//
+			// It has dynamic arguments
+			//
+			if (dynamic) {
+				Arguments args = new Arguments (arguments.Count + 1);
+				if (IsBase) {
+					rc.Report.Error (1972, loc,
+						"The indexer base access cannot be dynamically dispatched. Consider casting the dynamic arguments or eliminating the base access");
+				} else {
+					args.Add (new Argument (InstanceExpression));
+				}
+				args.AddRange (arguments);
+
+				best_candidate = null;
+				return new DynamicIndexBinder (args, loc);
+			}
+
+			//
+			// Try to avoid resolving left expression again
+			//
+			if (right_side != null)
+				ResolveInstanceExpression (rc, right_side);
+
+			return this;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			IndexerExpr target = (IndexerExpr) t;
+
+			if (arguments != null)
+				target.arguments = arguments.Clone (clonectx);
+		}
+
+		public void SetConditionalAccessReceiver ()
+		{
+			conditional_access_receiver = true;
+		}
+
+		public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
+		{
+			Error_TypeArgumentsCannotBeUsed (ec, "indexer", GetSignatureForError (), loc);
+		}
+
+		#region IBaseMembersProvider Members
+
+		IList<MemberSpec> OverloadResolver.IBaseMembersProvider.GetBaseMembers (TypeSpec baseType)
+		{
+			return baseType == null ? null : MemberCache.FindMembers (baseType, MemberCache.IndexerNameAlias, false);
+		}
+
+		IParametersMember OverloadResolver.IBaseMembersProvider.GetOverrideMemberParameters (MemberSpec member)
+		{
+			if (queried_type == member.DeclaringType)
+				return null;
+
+			var filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, MemberKind.Indexer, ((IndexerSpec) member).Parameters, null);
+			return MemberCache.FindMember (queried_type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
+		}
+
+		MethodGroupExpr OverloadResolver.IBaseMembersProvider.LookupExtensionMethod (ResolveContext rc)
+		{
+			return null;
+		}
+
+		#endregion
+	}
+
+	//
+	// A base access expression
+	//
+	public class BaseThis : This
+	{
+		public BaseThis (Location loc)
+			: base (loc)
+		{
+		}
+
+		public BaseThis (TypeSpec type, Location loc)
+			: base (loc)
+		{
+			this.type = type;
+			eclass = ExprClass.Variable;
+		}
+
+		#region Properties
+
+		public override string Name {
+			get {
+				return "base";
+			}
+		}
+
+		#endregion
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (831, loc, "An expression tree may not contain a base access");
+			return base.CreateExpressionTree (ec);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+
+			if (type == ec.Module.Compiler.BuiltinTypes.ValueType) {
+				var context_type = ec.CurrentType;
+				ec.Emit (OpCodes.Ldobj, context_type);
+				ec.Emit (OpCodes.Box, context_type);
+			}
+		}
+
+		protected override void Error_ThisNotAvailable (ResolveContext ec)
+		{
+			if (ec.IsStatic) {
+				ec.Report.Error (1511, loc, "Keyword `base' is not available in a static method");
+			} else {
+				ec.Report.Error (1512, loc, "Keyword `base' is not available in the current context");
+			}
+		}
+
+		public override void ResolveBase (ResolveContext ec)
+		{
+			base.ResolveBase (ec);
+			type = ec.CurrentType.BaseType;
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   This class exists solely to pass the Type around and to be a dummy
+	///   that can be passed to the conversion functions (this is used by
+	///   foreach implementation to typecast the object return value from
+	///   get_Current into the proper type.  All code has been generated and
+	///   we only care about the side effect conversions to be performed
+	///
+	///   This is also now used as a placeholder where a no-action expression
+	///   is needed (the `New' class).
+	/// </summary>
+	public class EmptyExpression : Expression
+	{
+		sealed class OutAccessExpression : EmptyExpression
+		{
+			public OutAccessExpression (TypeSpec t)
+				: base (t)
+			{
+			}
+
+			public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+			{
+				rc.Report.Error (206, right_side.Location,
+					"A property, indexer or dynamic member access may not be passed as `ref' or `out' parameter");
+
+				return null;
+			}
+		}
+
+		public static readonly EmptyExpression LValueMemberAccess = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly EmptyExpression LValueMemberOutAccess = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly EmptyExpression UnaryAddress = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly EmptyExpression EventAddition = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly EmptyExpression EventSubtraction = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly EmptyExpression MissingValue = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly Expression Null = new EmptyExpression (InternalType.FakeInternalType);
+		public static readonly EmptyExpression OutAccess = new OutAccessExpression (InternalType.FakeInternalType);
+
+		public EmptyExpression (TypeSpec t)
+		{
+			type = t;
+			eclass = ExprClass.Value;
+			loc = Location.Null;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// nothing, as we only exist to not do anything.
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+	
+	sealed class EmptyAwaitExpression : EmptyExpression
+	{
+		public EmptyAwaitExpression (TypeSpec type)
+			: base (type)
+		{
+		}
+		
+		public override bool ContainsEmitWithAwait ()
+		{
+			return true;
+		}
+	}
+	
+	//
+	// Empty statement expression
+	//
+	public sealed class EmptyExpressionStatement : ExpressionStatement
+	{
+		public static readonly EmptyExpressionStatement Instance = new EmptyExpressionStatement ();
+
+		private EmptyExpressionStatement ()
+		{
+			loc = Location.Null;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return null;
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			// Do nothing
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Value;
+			type = ec.BuiltinTypes.Object;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// Do nothing
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ErrorExpression : EmptyExpression
+	{
+		public static readonly ErrorExpression Instance = new ErrorExpression ();
+		public readonly int ErrorCode;
+		public readonly string Error;
+		
+		private ErrorExpression ()
+			: base (InternalType.ErrorType)
+		{
+		}
+		
+		ErrorExpression (int errorCode, Location location, string error)
+			: base (InternalType.ErrorType)
+		{
+			this.ErrorCode = errorCode;
+			base.loc = location;
+			this.Error = error;
+		}
+		
+		public static ErrorExpression Create (int errorCode, Location location, string error)
+		{
+			return new ErrorExpression (errorCode, location, error);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			return this;
+		}
+
+		public override void Error_ValueAssignment (ResolveContext rc, Expression rhs)
+		{
+		}
+
+		public override void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
+		{
+		}
+
+		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
+		{
+		}
+
+		public override void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t)
+		{
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class UserCast : Expression {
+		MethodSpec method;
+		Expression source;
+		
+		public UserCast (MethodSpec method, Expression source, Location l)
+		{
+			if (source == null)
+				throw new ArgumentNullException ("source");
+
+			this.method = method;
+			this.source = source;
+			type = method.ReturnType;
+			loc = l;
+		}
+
+		public Expression Source {
+			get {
+				return source;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return source.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (3);
+			args.Add (new Argument (source.CreateExpressionTree (ec)));
+			args.Add (new Argument (new TypeOf (type, loc)));
+			args.Add (new Argument (new TypeOfMethod (method, loc)));
+			return CreateExpressionFactoryCall (ec, "Convert", args);
+		}
+			
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			ObsoleteAttribute oa = method.GetAttributeObsolete ();
+			if (oa != null)
+				AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
+
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			source.Emit (ec);
+			ec.MarkCallEntry (loc);
+			ec.Emit (OpCodes.Call, method);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			source.FlowAnalysis (fc);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return TypeManager.CSharpSignature (method);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+#if STATIC
+			return base.MakeExpression (ctx);
+#else
+			return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
+#endif
+		}
+	}
+
+	//
+	// Holds additional type specifiers like ?, *, []
+	//
+	public class ComposedTypeSpecifier
+	{
+		public static readonly ComposedTypeSpecifier SingleDimension = new ComposedTypeSpecifier (1, Location.Null);
+
+		public readonly int Dimension;
+		public readonly Location Location;
+
+		public ComposedTypeSpecifier (int specifier, Location loc)
+		{
+			this.Dimension = specifier;
+			this.Location = loc;
+		}
+
+		#region Properties
+		public bool IsNullable {
+			get {
+				return Dimension == -1;
+			}
+		}
+
+		public bool IsPointer {
+			get {
+				return Dimension == -2;
+			}
+		}
+
+		public ComposedTypeSpecifier Next { get; set; }
+
+		#endregion
+
+		public static ComposedTypeSpecifier CreateArrayDimension (int dimension, Location loc)
+		{
+			return new ComposedTypeSpecifier (dimension, loc);
+		}
+
+		public static ComposedTypeSpecifier CreateNullable (Location loc)
+		{
+			return new ComposedTypeSpecifier (-1, loc);
+		}
+
+		public static ComposedTypeSpecifier CreatePointer (Location loc)
+		{
+			return new ComposedTypeSpecifier (-2, loc);
+		}
+
+		public string GetSignatureForError ()
+		{
+			string s =
+				IsPointer ? "*" :
+				IsNullable ? "?" :
+				ArrayContainer.GetPostfixSignature (Dimension);
+
+			return Next != null ? s + Next.GetSignatureForError () : s;
+		}
+	}
+
+	// <summary>
+	//   This class is used to "construct" the type during a typecast
+	//   operation.  Since the Type.GetType class in .NET can parse
+	//   the type specification, we just use this to construct the type
+	//   one bit at a time.
+	// </summary>
+	public class ComposedCast : TypeExpr {
+		FullNamedExpression left;
+		ComposedTypeSpecifier spec;
+
+		public FullNamedExpression Left {
+			get { return this.left; }
+		}
+
+		public ComposedTypeSpecifier Spec {
+			get {
+				return this.spec;
+			}
+		}
+
+		public ComposedCast (FullNamedExpression left, ComposedTypeSpecifier spec)
+		{
+			if (spec == null)
+				throw new ArgumentNullException ("spec");
+
+			this.left = left;
+			this.spec = spec;
+			this.loc = left.Location;
+		}
+
+		public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments)
+		{
+			type = left.ResolveAsType (ec);
+			if (type == null)
+				return null;
+
+			eclass = ExprClass.Type;
+
+			var single_spec = spec;
+
+			if (single_spec.IsNullable) {
+				type = new Nullable.NullableType (type, loc).ResolveAsType (ec);
+				if (type == null)
+					return null;
+
+				single_spec = single_spec.Next;
+			} else if (single_spec.IsPointer) {
+				if (!TypeManager.VerifyUnmanaged (ec.Module, type, loc))
+					return null;
+
+				if (!ec.IsUnsafe) {
+					UnsafeError (ec.Module.Compiler.Report, loc);
+				}
+
+				do {
+					type = PointerContainer.MakeType (ec.Module, type);
+					single_spec = single_spec.Next;
+				} while (single_spec != null && single_spec.IsPointer);
+			}
+
+			if (single_spec != null && single_spec.Dimension > 0) {
+				if (type.IsSpecialRuntimeType) {
+					ec.Module.Compiler.Report.Error (611, loc, "Array elements cannot be of type `{0}'", type.GetSignatureForError ());
+				} else if (type.IsStatic) {
+					ec.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
+					ec.Module.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'",
+						type.GetSignatureForError ());
+				} else {
+					MakeArray (ec.Module, single_spec);
+				}
+			}
+
+			return type;
+		}
+
+		void MakeArray (ModuleContainer module, ComposedTypeSpecifier spec)
+		{
+			if (spec.Next != null)
+				MakeArray (module, spec.Next);
+
+			type = ArrayContainer.MakeType (module, type, spec.Dimension);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return left.GetSignatureForError () + spec.GetSignatureForError ();
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	class FixedBufferPtr : Expression
+	{
+		readonly Expression array;
+
+		public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
+		{
+			this.type = array_type;
+			this.array = array;
+			this.loc = l;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Error_PointerInsideExpressionTree (ec);
+			return null;
+		}
+
+		public override void Emit(EmitContext ec)
+		{
+			array.Emit (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			type = PointerContainer.MakeType (ec.Module, type);
+			eclass = ExprClass.Value;
+			return this;
+		}
+	}
+
+
+	//
+	// This class is used to represent the address of an array, used
+	// only by the Fixed statement, this generates "&a [0]" construct
+	// for fixed (char *pa = a)
+	//
+	class ArrayPtr : FixedBufferPtr
+	{
+		public ArrayPtr (Expression array, TypeSpec array_type, Location l):
+			base (array, array_type, l)
+		{
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			base.Emit (ec);
+			
+			ec.EmitInt (0);
+			ec.Emit (OpCodes.Ldelema, ((PointerContainer) type).Element);
+		}
+	}
+
+	//
+	// Encapsulates a conversion rules required for array indexes
+	//
+	public class ArrayIndexCast : TypeCast
+	{
+		public ArrayIndexCast (Expression expr, TypeSpec returnType)
+			: base (expr, returnType)
+		{
+			if (expr.Type == returnType) // int -> int
+				throw new ArgumentException ("unnecessary array index conversion");
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			using (ec.Set (ResolveContext.Options.CheckedScope)) {
+				return base.CreateExpressionTree (ec);
+			}
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			child.Emit (ec);
+
+			switch (child.Type.BuiltinType) {
+			case BuiltinTypeSpec.Type.UInt:
+				ec.Emit (OpCodes.Conv_U);
+				break;
+			case BuiltinTypeSpec.Type.Long:
+				ec.Emit (OpCodes.Conv_Ovf_I);
+				break;
+			case BuiltinTypeSpec.Type.ULong:
+				ec.Emit (OpCodes.Conv_Ovf_I_Un);
+				break;
+			default:
+				throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
+			}
+		}
+	}
+
+	//
+	// Implements the `stackalloc' keyword
+	//
+	public class StackAlloc : Expression {
+		TypeSpec otype;
+		Expression t;
+		Expression count;
+
+		public StackAlloc (Expression type, Expression count, Location l)
+		{
+			t = type;
+			this.count = count;
+			loc = l;
+		}
+
+		public Expression TypeExpression {
+			get {
+				return this.t;
+			}
+		}
+
+		public Expression CountExpression {
+			get {
+				return this.count;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			count = count.Resolve (ec);
+			if (count == null)
+				return null;
+			
+			if (count.Type.BuiltinType != BuiltinTypeSpec.Type.UInt){
+				count = Convert.ImplicitConversionRequired (ec, count, ec.BuiltinTypes.Int, loc);
+				if (count == null)
+					return null;
+			}
+
+			Constant c = count as Constant;
+			if (c != null && c.IsNegative) {
+				ec.Report.Error (247, loc, "Cannot use a negative size with stackalloc");
+			}
+
+			if (ec.HasAny (ResolveContext.Options.CatchScope | ResolveContext.Options.FinallyScope)) {
+				ec.Report.Error (255, loc, "Cannot use stackalloc in finally or catch");
+			}
+
+			otype = t.ResolveAsType (ec);
+			if (otype == null)
+				return null;
+
+			if (!TypeManager.VerifyUnmanaged (ec.Module, otype, loc))
+				return null;
+
+			type = PointerContainer.MakeType (ec.Module, otype);
+			eclass = ExprClass.Value;
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			int size = BuiltinTypeSpec.GetSize (otype);
+
+			count.Emit (ec);
+
+			if (size == 0)
+				ec.Emit (OpCodes.Sizeof, otype);
+			else
+				ec.EmitInt (size);
+
+			ec.Emit (OpCodes.Mul_Ovf_Un);
+			ec.Emit (OpCodes.Localloc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			StackAlloc target = (StackAlloc) t;
+			target.count = count.Clone (clonectx);
+			target.t = t.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// An object initializer expression
+	//
+	public class ElementInitializer : Assign
+	{
+		public readonly string Name;
+
+		public ElementInitializer (string name, Expression initializer, Location loc)
+			: base (null, initializer, loc)
+		{
+			this.Name = name;
+		}
+
+		public bool IsDictionaryInitializer {
+			get {
+				return Name == null;
+			}
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			ElementInitializer target = (ElementInitializer) t;
+			target.source = source.Clone (clonectx);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			FieldExpr fe = target as FieldExpr;
+			if (fe != null)
+				args.Add (new Argument (fe.CreateTypeOfExpression ()));
+			else
+				args.Add (new Argument (((PropertyExpr) target).CreateSetterTypeOfExpression (ec)));
+
+			string mname;
+			Expression arg_expr;
+			var cinit = source as CollectionOrObjectInitializers;
+			if (cinit == null) {
+				mname = "Bind";
+				arg_expr = source.CreateExpressionTree (ec);
+			} else {
+				mname = cinit.IsEmpty || cinit.Initializers[0] is ElementInitializer ? "MemberBind" : "ListBind";
+				arg_expr = cinit.CreateExpressionTree (ec, !cinit.IsEmpty);
+			}
+
+			args.Add (new Argument (arg_expr));
+			return CreateExpressionFactoryCall (ec, mname, args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (source == null)
+				return EmptyExpressionStatement.Instance;
+
+			if (!ResolveElement (ec))
+				return null;
+
+			if (source is CollectionOrObjectInitializers) {
+				Expression previous = ec.CurrentInitializerVariable;
+				ec.CurrentInitializerVariable = target;
+				source = source.Resolve (ec);
+				ec.CurrentInitializerVariable = previous;
+				if (source == null)
+					return null;
+					
+				eclass = source.eclass;
+				type = source.Type;
+				return this;
+			}
+
+			return base.DoResolve (ec);
+		}
+	
+		public override void EmitStatement (EmitContext ec)
+		{
+			if (source is CollectionOrObjectInitializers)
+				source.Emit (ec);
+			else
+				base.EmitStatement (ec);
+		}
+
+		protected virtual bool ResolveElement (ResolveContext rc)
+		{
+			var t = rc.CurrentInitializerVariable.Type;
+			if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Arguments args = new Arguments (1);
+				args.Add (new Argument (rc.CurrentInitializerVariable));
+				target = new DynamicMemberBinder (Name, args, loc);
+			} else {
+
+				var member = MemberLookup (rc, false, t, Name, 0, MemberLookupRestrictions.ExactArity, loc);
+				if (member == null) {
+					member = Expression.MemberLookup (rc, true, t, Name, 0, MemberLookupRestrictions.ExactArity, loc);
+
+					if (member != null) {
+						// TODO: ec.Report.SymbolRelatedToPreviousError (member);
+						ErrorIsInaccesible (rc, member.GetSignatureForError (), loc);
+						return false;
+					}
+				}
+
+				if (member == null) {
+					Error_TypeDoesNotContainDefinition (rc, loc, t, Name);
+					return false;
+				}
+
+				var me = member as MemberExpr;
+				if (me is EventExpr) {
+					me = me.ResolveMemberAccess (rc, null, null);
+				} else if (!(member is PropertyExpr || member is FieldExpr)) {
+					rc.Report.Error (1913, loc,
+						"Member `{0}' cannot be initialized. An object initializer may only be used for fields, or properties",
+						member.GetSignatureForError ());
+
+					return false;
+				}
+
+				if (me.IsStatic) {
+					rc.Report.Error (1914, loc,
+						"Static field or property `{0}' cannot be assigned in an object initializer",
+						me.GetSignatureForError ());
+				}
+
+				target = me;
+				me.InstanceExpression = rc.CurrentInitializerVariable;
+			}
+
+			return true;
+		}
+	}
+	
+	//
+	// A collection initializer expression
+	//
+	class CollectionElementInitializer : Invocation
+	{
+		public readonly bool IsSingle;
+
+
+		public class ElementInitializerArgument : Argument
+		{
+			public ElementInitializerArgument (Expression e)
+				: base (e)
+			{
+			}
+		}
+
+		sealed class AddMemberAccess : MemberAccess
+		{
+			public AddMemberAccess (Expression expr, Location loc)
+				: base (expr, "Add", loc)
+			{
+			}
+
+			protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
+			{
+				if (TypeManager.HasElementType (type))
+					return;
+
+				base.Error_TypeDoesNotContainDefinition (ec, type, name);
+			}
+		}
+
+		public CollectionElementInitializer (Expression argument)
+			: base (null, new Arguments (1))
+		{
+			IsSingle = true;
+			base.arguments.Add (new ElementInitializerArgument (argument));
+			this.loc = argument.Location;
+		}
+
+		public CollectionElementInitializer (List<Expression> arguments, Location loc)
+			: base (null, new Arguments (arguments.Count))
+		{
+			IsSingle = false;
+			foreach (Expression e in arguments)
+				base.arguments.Add (new ElementInitializerArgument (e));
+
+			this.loc = loc;
+		}
+
+		public CollectionElementInitializer (Location loc)
+			: base (null, null)
+		{
+			this.loc = loc;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (mg.CreateExpressionTree (ec)));
+
+			var expr_initializers = new ArrayInitializer (arguments.Count, loc);
+			foreach (Argument a in arguments)
+				expr_initializers.Add (a.CreateExpressionTree (ec));
+
+			args.Add (new Argument (new ArrayCreation (
+				CreateExpressionTypeExpression (ec, loc), expr_initializers, loc)));
+			return CreateExpressionFactoryCall (ec, "ElementInit", args);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			CollectionElementInitializer target = (CollectionElementInitializer) t;
+			if (arguments != null)
+				target.arguments = arguments.Clone (clonectx);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			base.expr = new AddMemberAccess (ec.CurrentInitializerVariable, loc);
+
+			return base.DoResolve (ec);
+		}
+	}
+
+	class DictionaryElementInitializer : ElementInitializer
+	{
+		readonly Arguments args;
+
+		public DictionaryElementInitializer (List<Expression> arguments, Expression initializer, Location loc)
+			: base (null, initializer, loc)
+		{
+			this.args = new Arguments (arguments.Count);
+			foreach (var arg in arguments)
+				this.args.Add (new Argument (arg));
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (8074, loc, "Expression tree cannot contain a dictionary initializer");
+			return null;
+		}
+
+		protected override bool ResolveElement (ResolveContext rc)
+		{
+			var init = rc.CurrentInitializerVariable;
+			var type = init.Type;
+
+			var indexers = MemberCache.FindMembers (type, MemberCache.IndexerNameAlias, false);
+			if (indexers == null && type.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
+				ElementAccess.Error_CannotApplyIndexing (rc, type, loc);
+				return false;
+			}
+
+			target = new IndexerExpr (indexers, type, init, args, loc).Resolve (rc);
+			return true;
+		}
+	}
+	
+	//
+	// A block of object or collection initializers
+	//
+	public class CollectionOrObjectInitializers : ExpressionStatement
+	{
+		IList<Expression> initializers;
+		bool is_collection_initialization;
+
+		public CollectionOrObjectInitializers (Location loc)
+			: this (new Expression[0], loc)
+		{
+		}
+
+		public CollectionOrObjectInitializers (IList<Expression> initializers, Location loc)
+		{
+			this.initializers = initializers;
+			this.loc = loc;
+		}
+		
+		public bool IsEmpty {
+			get {
+				return initializers.Count == 0;
+			}
+		}
+
+		public bool IsCollectionInitializer {
+			get {
+				return is_collection_initialization;
+			}
+		}
+
+		public IList<Expression> Initializers {
+			get {
+				return initializers;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			CollectionOrObjectInitializers t = (CollectionOrObjectInitializers) target;
+
+			t.initializers = new List<Expression> (initializers.Count);
+			foreach (var e in initializers)
+				t.initializers.Add (e.Clone (clonectx));
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			foreach (var e in initializers) {
+				if (e.ContainsEmitWithAwait ())
+					return true;
+			}
+
+			return false;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return CreateExpressionTree (ec, false);
+		}
+
+		public Expression CreateExpressionTree (ResolveContext ec, bool inferType)
+		{
+			var expr_initializers = new ArrayInitializer (initializers.Count, loc);
+			foreach (Expression e in initializers) {
+				Expression expr = e.CreateExpressionTree (ec);
+				if (expr != null)
+					expr_initializers.Add (expr);
+			}
+
+			if (inferType)
+				return new ImplicitlyTypedArrayCreation (expr_initializers, loc);
+
+			return new ArrayCreation (new TypeExpression (ec.Module.PredefinedTypes.MemberBinding.Resolve (), loc), expr_initializers, loc); 
+		}
+		
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			List<string> element_names = null;
+			for (int i = 0; i < initializers.Count; ++i) {
+				Expression initializer = initializers [i];
+				ElementInitializer element_initializer = initializer as ElementInitializer;
+
+				if (i == 0) {
+					if (element_initializer != null) {
+						element_names = new List<string> (initializers.Count);
+						if (!element_initializer.IsDictionaryInitializer)
+							element_names.Add (element_initializer.Name);
+					} else if (initializer is CompletingExpression) {
+						initializer.Resolve (ec);
+						throw new InternalErrorException ("This line should never be reached");
+					} else {
+						var t = ec.CurrentInitializerVariable.Type;
+						// LAMESPEC: The collection must implement IEnumerable only, no dynamic support
+						if (!t.ImplementsInterface (ec.BuiltinTypes.IEnumerable, false) && t.BuiltinType != BuiltinTypeSpec.Type.Dynamic) {
+							ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
+								"object initializer because type `{1}' does not implement `{2}' interface",
+								ec.CurrentInitializerVariable.GetSignatureForError (),
+								ec.CurrentInitializerVariable.Type.GetSignatureForError (),
+								ec.BuiltinTypes.IEnumerable.GetSignatureForError ());
+							return null;
+						}
+						is_collection_initialization = true;
+					}
+				} else {
+					if (is_collection_initialization != (element_initializer == null)) {
+						ec.Report.Error (747, initializer.Location, "Inconsistent `{0}' member declaration",
+							is_collection_initialization ? "collection initializer" : "object initializer");
+						continue;
+					}
+
+					if (!is_collection_initialization && !element_initializer.IsDictionaryInitializer) {
+						if (element_names.Contains (element_initializer.Name)) {
+							ec.Report.Error (1912, element_initializer.Location,
+								"An object initializer includes more than one member `{0}' initialization",
+								element_initializer.Name);
+						} else {
+							element_names.Add (element_initializer.Name);
+						}
+					}
+				}
+
+				Expression e = initializer.Resolve (ec);
+				if (e == EmptyExpressionStatement.Instance)
+					initializers.RemoveAt (i--);
+				else
+					initializers [i] = e;
+			}
+
+			type = ec.CurrentInitializerVariable.Type;
+			if (is_collection_initialization) {
+				if (TypeManager.HasElementType (type)) {
+					ec.Report.Error (1925, loc, "Cannot initialize object of type `{0}' with a collection initializer",
+						type.GetSignatureForError ());
+				}
+			}
+
+			eclass = ExprClass.Variable;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			EmitStatement (ec);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			foreach (ExpressionStatement e in initializers) {
+				// TODO: need location region
+				ec.Mark (e.Location);
+				e.EmitStatement (ec);
+			}
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			foreach (var initializer in initializers) {
+				if (initializer != null)
+					initializer.FlowAnalysis (fc);
+			}
+		}
+	}
+	
+	//
+	// New expression with element/object initializers
+	//
+	public class NewInitialize : New
+	{
+		//
+		// This class serves as a proxy for variable initializer target instances.
+		// A real variable is assigned later when we resolve left side of an
+		// assignment
+		//
+		sealed class InitializerTargetExpression : Expression, IMemoryLocation
+		{
+			NewInitialize new_instance;
+
+			public InitializerTargetExpression (NewInitialize newInstance)
+			{
+				this.type = newInstance.type;
+				this.loc = newInstance.loc;
+				this.eclass = newInstance.eclass;
+				this.new_instance = newInstance;
+			}
+
+			public override bool ContainsEmitWithAwait ()
+			{
+				return false;
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				// Should not be reached
+				throw new NotSupportedException ("ET");
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				return this;
+			}
+
+			public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+			{
+				return this;
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				Expression e = (Expression) new_instance.instance;
+				e.Emit (ec);
+			}
+
+			public override Expression EmitToField (EmitContext ec)
+			{
+				return (Expression) new_instance.instance;
+			}
+
+			#region IMemoryLocation Members
+
+			public void AddressOf (EmitContext ec, AddressOp mode)
+			{
+				new_instance.instance.AddressOf (ec, mode);
+			}
+
+			#endregion
+		}
+
+		CollectionOrObjectInitializers initializers;
+		IMemoryLocation instance;
+		DynamicExpressionStatement dynamic;
+
+		public NewInitialize (FullNamedExpression requested_type, Arguments arguments, CollectionOrObjectInitializers initializers, Location l)
+			: base (requested_type, arguments, l)
+		{
+			this.initializers = initializers;
+		}
+
+		public CollectionOrObjectInitializers Initializers {
+			get {
+				return initializers;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			base.CloneTo (clonectx, t);
+
+			NewInitialize target = (NewInitialize) t;
+			target.initializers = (CollectionOrObjectInitializers) initializers.Clone (clonectx);
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return base.ContainsEmitWithAwait () || initializers.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			Arguments args = new Arguments (2);
+			args.Add (new Argument (base.CreateExpressionTree (ec)));
+			if (!initializers.IsEmpty)
+				args.Add (new Argument (initializers.CreateExpressionTree (ec, initializers.IsCollectionInitializer)));
+
+			return CreateExpressionFactoryCall (ec,
+				initializers.IsCollectionInitializer ? "ListInit" : "MemberInit",
+				args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			Expression e = base.DoResolve (ec);
+			if (type == null)
+				return null;
+
+			if (type.IsDelegate) {
+				ec.Report.Error (1958, Initializers.Location,
+					"Object and collection initializers cannot be used to instantiate a delegate");
+			}
+
+			Expression previous = ec.CurrentInitializerVariable;
+			ec.CurrentInitializerVariable = new InitializerTargetExpression (this);
+			initializers.Resolve (ec);
+			ec.CurrentInitializerVariable = previous;
+
+			dynamic = e as DynamicExpressionStatement;
+			if (dynamic != null)
+				return this;
+
+			return e;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (method == null && TypeSpec.IsValueType (type) && initializers.Initializers.Count > 1 && ec.HasSet (BuilderContext.Options.AsyncBody) && initializers.ContainsEmitWithAwait ()) {
+				var fe = ec.GetTemporaryField (type);
+
+				if (!Emit (ec, fe))
+					fe.Emit (ec);
+
+				return;
+			}
+
+			base.Emit (ec);
+		}
+
+		public override bool Emit (EmitContext ec, IMemoryLocation target)
+		{
+			bool left_on_stack;
+			if (dynamic != null) {
+				dynamic.Emit (ec);
+				left_on_stack = true;
+			} else {
+				left_on_stack = base.Emit (ec, target);
+			}
+
+			if (initializers.IsEmpty)
+				return left_on_stack;
+
+			LocalTemporary temp = null;
+
+			instance = target as LocalTemporary;
+			if (instance == null)
+				instance = target as StackFieldExpr;
+
+			if (instance == null) {
+				if (!left_on_stack) {
+					VariableReference vr = target as VariableReference;
+
+					// FIXME: This still does not work correctly for pre-set variables
+					if (vr != null && vr.IsRef)
+						target.AddressOf (ec, AddressOp.Load);
+
+					((Expression) target).Emit (ec);
+					left_on_stack = true;
+				}
+
+				if (ec.HasSet (BuilderContext.Options.AsyncBody) && initializers.ContainsEmitWithAwait ()) {
+					instance = new EmptyAwaitExpression (Type).EmitToField (ec) as IMemoryLocation;
+				} else {
+					temp = new LocalTemporary (type);
+					instance = temp;
+				}
+			}
+
+			if (left_on_stack && temp != null)
+				temp.Store (ec);
+
+			initializers.Emit (ec);
+
+			if (left_on_stack) {
+				if (temp != null) {
+					temp.Emit (ec);
+					temp.Release (ec);
+				} else {
+					((Expression) instance).Emit (ec);
+				}
+			}
+
+			return left_on_stack;
+		}
+
+		protected override IMemoryLocation EmitAddressOf (EmitContext ec, AddressOp Mode)
+		{
+			instance = base.EmitAddressOf (ec, Mode);
+
+			if (!initializers.IsEmpty)
+				initializers.Emit (ec);
+
+			return instance;
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			base.FlowAnalysis (fc);
+			initializers.FlowAnalysis (fc);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class NewAnonymousType : New
+	{
+		static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
+
+		List<AnonymousTypeParameter> parameters;
+		readonly TypeContainer parent;
+		AnonymousTypeClass anonymous_type;
+
+		public NewAnonymousType (List<AnonymousTypeParameter> parameters, TypeContainer parent, Location loc)
+			 : base (null, null, loc)
+		{
+			this.parameters = parameters;
+			this.parent = parent;
+		}
+
+		public List<AnonymousTypeParameter> Parameters {
+			get {
+				return this.parameters;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			if (parameters == null)
+				return;
+
+			NewAnonymousType t = (NewAnonymousType) target;
+			t.parameters = new List<AnonymousTypeParameter> (parameters.Count);
+			foreach (AnonymousTypeParameter atp in parameters)
+				t.parameters.Add ((AnonymousTypeParameter) atp.Clone (clonectx));
+		}
+
+		AnonymousTypeClass CreateAnonymousType (ResolveContext ec, IList<AnonymousTypeParameter> parameters)
+		{
+			AnonymousTypeClass type = parent.Module.GetAnonymousType (parameters);
+			if (type != null)
+				return type;
+
+			type = AnonymousTypeClass.Create (parent, parameters, loc);
+			if (type == null)
+				return null;
+
+			int errors = ec.Report.Errors;
+			type.CreateContainer ();
+			type.DefineContainer ();
+			type.Define ();
+			if ((ec.Report.Errors - errors) == 0) {
+				parent.Module.AddAnonymousType (type);
+				type.PrepareEmit ();
+			}
+
+			return type;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (parameters == null)
+				return base.CreateExpressionTree (ec);
+
+			var init = new ArrayInitializer (parameters.Count, loc);
+			foreach (var m in anonymous_type.Members) {
+				var p = m as Property;
+				if (p != null)
+					init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
+			}
+
+			var ctor_args = new ArrayInitializer (arguments.Count, loc);
+			foreach (Argument a in arguments)
+				ctor_args.Add (a.CreateExpressionTree (ec));
+
+			Arguments args = new Arguments (3);
+			args.Add (new Argument (new TypeOfMethod (method, loc)));
+			args.Add (new Argument (new ArrayCreation (CreateExpressionTypeExpression (ec, loc), ctor_args, loc)));
+			args.Add (new Argument (new ImplicitlyTypedArrayCreation (init, loc)));
+
+			return CreateExpressionFactoryCall (ec, "New", args);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
+				ec.Report.Error (836, loc, "Anonymous types cannot be used in this expression");
+				return null;
+			}
+
+			if (parameters == null) {
+				anonymous_type = CreateAnonymousType (ec, EmptyParameters);
+				RequestedType = new TypeExpression (anonymous_type.Definition, loc);
+				return base.DoResolve (ec);
+			}
+
+			bool error = false;
+			arguments = new Arguments (parameters.Count);
+			var t_args = new TypeSpec [parameters.Count];
+			for (int i = 0; i < parameters.Count; ++i) {
+				Expression e = parameters [i].Resolve (ec);
+				if (e == null) {
+					error = true;
+					continue;
+				}
+
+				arguments.Add (new Argument (e));
+				t_args [i] = e.Type;
+			}
+
+			if (error)
+				return null;
+
+			anonymous_type = CreateAnonymousType (ec, parameters);
+			if (anonymous_type == null)
+				return null;
+
+			type = anonymous_type.Definition.MakeGenericType (ec.Module, t_args);
+			method = (MethodSpec) MemberCache.FindMember (type, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
+			eclass = ExprClass.Value;
+			return this;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class AnonymousTypeParameter : ShimExpression
+	{
+		public readonly string Name;
+
+		public AnonymousTypeParameter (Expression initializer, string name, Location loc)
+			: base (initializer)
+		{
+			this.Name = name;
+			this.loc = loc;
+		}
+		
+		public AnonymousTypeParameter (Parameter parameter)
+			: base (new SimpleName (parameter.Name, parameter.Location))
+		{
+			this.Name = parameter.Name;
+			this.loc = parameter.Location;
+		}		
+
+		public override bool Equals (object o)
+		{
+			AnonymousTypeParameter other = o as AnonymousTypeParameter;
+			return other != null && Name == other.Name;
+		}
+
+		public override int GetHashCode ()
+		{
+			return Name.GetHashCode ();
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			Expression e = expr.Resolve (ec);
+			if (e == null)
+				return null;
+
+			if (e.eclass == ExprClass.MethodGroup) {
+				Error_InvalidInitializer (ec, e.ExprClassName);
+				return null;
+			}
+
+			type = e.Type;
+			if (type.Kind == MemberKind.Void || type == InternalType.NullLiteral || type == InternalType.AnonymousMethod || type.IsPointer) {
+				Error_InvalidInitializer (ec, type.GetSignatureForError ());
+				return null;
+			}
+
+			return e;
+		}
+
+		protected virtual void Error_InvalidInitializer (ResolveContext ec, string initializer)
+		{
+			ec.Report.Error (828, loc, "An anonymous type property `{0}' cannot be initialized with `{1}'",
+				Name, initializer);
+		}
+	}
+
+	public class CatchFilterExpression : BooleanExpression
+	{
+		public CatchFilterExpression (Expression expr, Location loc)
+			: base (expr)
+		{
+			this.loc = loc;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/field.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/field.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/field.cs	(revision 11807)
@@ -0,0 +1,733 @@
+//
+// field.cs: All field handlers
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Martin Baulig (martin@ximian.com)
+//          Marek Safar (marek.safar@seznam.cz)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	public class FieldDeclarator
+	{
+		public FieldDeclarator (SimpleMemberName name, Expression initializer)
+		{
+			this.Name = name;
+			this.Initializer = initializer;
+		}
+
+		#region Properties
+
+		public SimpleMemberName Name { get; private set; }
+		public Expression Initializer { get; private set; }
+
+		#endregion
+
+		public virtual FullNamedExpression GetFieldTypeExpression (FieldBase field)
+		{
+			return new TypeExpression (field.MemberType, Name.Location); 
+		}
+	}
+
+	//
+	// Abstract class for all fields
+	//
+	abstract public class FieldBase : MemberBase
+	{
+		protected FieldBuilder FieldBuilder;
+		protected FieldSpec spec;
+		public Status status;
+		protected Expression initializer;
+		protected List<FieldDeclarator> declarators;
+
+		[Flags]
+		public enum Status : byte {
+			HAS_OFFSET = 4		// Used by FieldMember.
+		}
+
+		static readonly string[] attribute_targets = new string [] { "field" };
+
+		protected FieldBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
+			: base (parent, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE, name, attrs)
+		{
+			if ((mod & Modifiers.ABSTRACT) != 0)
+				Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
+		}
+
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Field;
+			}
+		}
+
+		public Expression Initializer {
+			get {
+				return initializer;
+			}
+			set {
+				this.initializer = value;
+			}
+		}
+
+		public string Name {
+			get {
+				return MemberName.Name;
+			}
+		}
+
+		public FieldSpec Spec {
+			get {
+				return spec;
+			}
+		}
+
+		public override string[] ValidAttributeTargets  {
+			get {
+				return attribute_targets;
+			}
+		}
+		
+		public List<FieldDeclarator> Declarators {
+			get {
+				return this.declarators;
+			}
+		}
+		#endregion
+
+		public void AddDeclarator (FieldDeclarator declarator)
+		{
+			if (declarators == null)
+				declarators = new List<FieldDeclarator> (2);
+
+			declarators.Add (declarator);
+
+			Parent.AddNameToContainer (this, declarator.Name.Value);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.FieldOffset) {
+				status |= Status.HAS_OFFSET;
+
+				if (!Parent.PartialContainer.HasExplicitLayout) {
+					Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
+					return;
+				}
+
+				if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
+					Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
+					return;
+				}
+			}
+
+			if (a.Type == pa.FixedBuffer) {
+				Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
+				return;
+			}
+
+#if false
+			if (a.Type == pa.MarshalAs) {
+				UnmanagedMarshal marshal = a.GetMarshal (this);
+				if (marshal != null) {
+					FieldBuilder.SetMarshal (marshal);
+				}
+				return;
+			}
+#endif
+			if ((a.HasSecurityAttribute)) {
+				a.Error_InvalidSecurityParent ();
+				return;
+			}
+
+			if (a.Type == pa.Dynamic) {
+				a.Error_MisusedDynamicAttribute ();
+				return;
+			}
+
+			FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		public void SetCustomAttribute (MethodSpec ctor, byte[] data)
+		{
+			FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
+		}
+
+ 		protected override bool CheckBase ()
+		{
+ 			if (!base.CheckBase ())
+ 				return false;
+
+			MemberSpec candidate;
+			bool overrides = false;
+			var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides);
+			if (conflict_symbol == null)
+				conflict_symbol = candidate;
+
+ 			if (conflict_symbol == null) {
+ 				if ((ModFlags & Modifiers.NEW) != 0) {
+ 					Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
+						GetSignatureForError ());
+ 				}
+ 			} else {
+				if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
+					Report.SymbolRelatedToPreviousError (conflict_symbol);
+					Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+						GetSignatureForError (), conflict_symbol.GetSignatureForError ());
+				}
+
+				if (conflict_symbol.IsAbstract) {
+					Report.SymbolRelatedToPreviousError (conflict_symbol);
+					Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
+						GetSignatureForError (), conflict_symbol.GetSignatureForError ());
+				}
+			}
+ 
+ 			return true;
+ 		}
+
+		public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
+		{
+			return expr.ConvertImplicitly (MemberType);
+		}
+
+		protected override void DoMemberTypeDependentChecks ()
+		{
+			base.DoMemberTypeDependentChecks ();
+
+			if (MemberType.IsGenericParameter)
+				return;
+
+			if (MemberType.IsStatic)
+				Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
+
+			if (!IsCompilerGenerated)
+				CheckBase ();
+
+			IsTypePermitted ();
+		}
+
+		//
+		//   Represents header string for documentation comment.
+		//
+		public override string DocCommentHeader {
+			get { return "F:"; }
+		}
+
+		public override void Emit ()
+		{
+			if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder);
+			} else if (!Parent.IsCompilerGenerated && member_type.HasDynamicElement) {
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder, member_type, Location);
+			}
+
+			if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
+				Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
+			if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
+				Module.PredefinedAttributes.DebuggerBrowsable.EmitAttribute (FieldBuilder, System.Diagnostics.DebuggerBrowsableState.Never);
+
+			if (OptAttributes != null) {
+				OptAttributes.Emit ();
+			}
+
+			if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
+				Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
+			}
+
+			ConstraintChecker.Check (this, member_type, type_expr.Location);
+
+			base.Emit ();
+		}
+
+		public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
+		{
+			Report.SymbolRelatedToPreviousError (static_class);
+			Report.Error (723, loc, "`{0}': cannot declare variables of static types",
+				variable_name);
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			if (!MemberType.IsCLSCompliant () || this is FixedField) {
+				Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
+					GetSignatureForError ());
+			}
+			return true;
+		}
+	}
+
+	//
+	// Field specification
+	//
+	public class FieldSpec : MemberSpec, IInterfaceMemberSpec
+	{
+		FieldInfo metaInfo;
+		TypeSpec memberType;
+
+		public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
+			: base (MemberKind.Field, declaringType, definition, modifiers)
+		{
+			this.metaInfo = info;
+			this.memberType = memberType;
+		}
+
+		#region Properties
+
+		public bool IsReadOnly {
+			get {
+				return (Modifiers & Modifiers.READONLY) != 0;
+			}
+		}
+
+		public TypeSpec MemberType {
+			get {
+				return memberType;
+			}
+		}
+
+#endregion
+
+		public FieldInfo GetMetaInfo ()
+		{
+			if ((state & StateFlags.PendingMetaInflate) != 0) {
+				var decl_meta = DeclaringType.GetMetaInfo ();
+				if (DeclaringType.IsTypeBuilder) {
+					metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
+				} else {
+					var orig_token = metaInfo.MetadataToken;
+					metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
+					if (metaInfo.MetadataToken != orig_token)
+						throw new NotImplementedException ("Resolved to wrong meta token");
+
+					// What a stupid API, does not work because field handle is imported
+					// metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
+				}
+
+				state &= ~StateFlags.PendingMetaInflate;
+			}
+
+			return metaInfo;
+		}
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var fs = (FieldSpec) base.InflateMember (inflator);
+			fs.memberType = inflator.Inflate (memberType);
+			return fs;
+		}
+
+		public FieldSpec Mutate (TypeParameterMutator mutator)
+		{
+			var decl = DeclaringType;
+			if (DeclaringType.IsGenericOrParentIsGeneric)
+				decl = mutator.Mutate (decl);
+
+			if (decl == DeclaringType)
+				return this;
+
+			var fs = (FieldSpec) MemberwiseClone ();
+			fs.declaringType = decl;
+			fs.state |= StateFlags.PendingMetaInflate;
+
+			// Gets back FieldInfo in case of metaInfo was inflated
+			fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
+			return fs;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			return memberType.ResolveMissingDependencies (this);
+		}
+	}
+
+	/// <summary>
+	/// Fixed buffer implementation
+	/// </summary>
+	public class FixedField : FieldBase
+	{
+		public const string FixedElementName = "FixedElementField";
+		static int GlobalCounter;
+
+		TypeBuilder fixed_buffer_type;
+
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE |
+			Modifiers.UNSAFE;
+
+		public FixedField (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
+			: base (parent, type, mod, AllowedModifiers, name, attrs)
+		{
+		}
+
+		#region Properties
+
+		//
+		// Explicit struct layout set by parent
+		//
+		public CharSet? CharSet {
+			get; set;
+		}		
+
+		#endregion
+
+		public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
+		{
+			return expr.ImplicitConversionRequired (rc, rc.BuiltinTypes.Int);
+		}
+
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			if (!BuiltinTypeSpec.IsPrimitiveType (MemberType)) {
+				Report.Error (1663, Location,
+					"`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
+					GetSignatureForError ());
+			} else if (declarators != null) {
+				foreach (var d in declarators) {
+					var f = new FixedField (Parent, d.GetFieldTypeExpression (this), ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
+					f.initializer = d.Initializer;
+					((ConstInitializer) f.initializer).Name = d.Name.Value;
+					f.Define ();
+					Parent.PartialContainer.Members.Add (f);
+				}
+			}
+			
+			// Create nested fixed buffer container
+			string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
+			fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
+				TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
+				Compiler.BuiltinTypes.ValueType.GetMetaInfo ());
+
+			var ffield = fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
+			
+			FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
+
+			var element_spec = new FieldSpec (null, this, MemberType, ffield, ModFlags);
+			spec = new FixedFieldSpec (Module, Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
+
+			Parent.MemberCache.AddMember (spec);
+			return true;
+		}
+
+		protected override void DoMemberTypeIndependentChecks ()
+		{
+			base.DoMemberTypeIndependentChecks ();
+
+			if (!IsUnsafe)
+				Expression.UnsafeError (Report, Location);
+
+			if (Parent.PartialContainer.Kind != MemberKind.Struct) {
+				Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
+					GetSignatureForError ());
+			}
+		}
+		
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void Emit()
+		{
+			ResolveContext rc = new ResolveContext (this);
+			IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
+			if (buffer_size_const == null)
+				return;
+
+			int buffer_size = buffer_size_const.Value;
+
+			if (buffer_size <= 0) {
+				Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
+				return;
+			}
+
+			EmitFieldSize (buffer_size);
+
+#if STATIC
+			if (Module.HasDefaultCharSet)
+				fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | Module.DefaultCharSetType);
+#endif
+
+			Module.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
+			Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
+			fixed_buffer_type.CreateType ();
+
+			base.Emit ();
+		}
+
+		void EmitFieldSize (int buffer_size)
+		{
+			int type_size = BuiltinTypeSpec.GetSize (MemberType);
+
+			if (buffer_size > int.MaxValue / type_size) {
+				Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
+					GetSignatureForError (), buffer_size.ToString (), MemberType.GetSignatureForError ());
+				return;
+			}
+
+			AttributeEncoder encoder;
+
+			var ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve (Location);
+			if (ctor == null)
+				return;
+
+			var field_size = Module.PredefinedMembers.StructLayoutSize.Resolve (Location);
+			var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve (Location);
+			if (field_size == null || field_charset == null)
+				return;
+
+			var char_set = CharSet ?? Module.DefaultCharSet ?? 0;
+
+			encoder = new AttributeEncoder ();
+			encoder.Encode ((short)LayoutKind.Sequential);
+			encoder.EncodeNamedArguments (
+				new [] { field_size, field_charset },
+				new Constant [] { 
+					new IntConstant (Compiler.BuiltinTypes, buffer_size * type_size, Location),
+					new IntConstant (Compiler.BuiltinTypes, (int) char_set, Location)
+				}
+			);
+
+			fixed_buffer_type.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+
+			//
+			// Don't emit FixedBufferAttribute attribute for private types
+			//
+			if ((ModFlags & Modifiers.PRIVATE) != 0)
+				return;
+
+			ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve (Location);
+			if (ctor == null)
+				return;
+
+			encoder = new AttributeEncoder ();
+			encoder.EncodeTypeName (MemberType);
+			encoder.Encode (buffer_size);
+			encoder.EncodeEmptyNamedArguments ();
+
+			FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
+		}
+	}
+
+	class FixedFieldSpec : FieldSpec
+	{
+		readonly FieldSpec element;
+
+		public FixedFieldSpec (ModuleContainer module, TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
+			: base (declaringType, definition, PointerContainer.MakeType (module, element.MemberType), info, modifiers)
+		{
+			this.element = element;
+
+			// It's never CLS-Compliant
+			state &= ~StateFlags.CLSCompliant_Undetected;
+		}
+
+		public FieldSpec Element {
+			get {
+				return element;
+			}
+		}
+		
+		public TypeSpec ElementType {
+			get {
+				return element.MemberType;
+			}
+		}
+	}
+
+	//
+	// The Field class is used to represents class/struct fields during parsing.
+	//
+	public class Field : FieldBase {
+		// <summary>
+		//   Modifiers allowed in a class declaration
+		// </summary>
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE |
+			Modifiers.STATIC |
+			Modifiers.VOLATILE |
+			Modifiers.UNSAFE |
+			Modifiers.READONLY;
+
+		public Field (TypeDefinition parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
+			: base (parent, type, mod, AllowedModifiers, name, attrs)
+		{
+		}
+
+		bool CanBeVolatile ()
+		{
+			switch (MemberType.BuiltinType) {
+			case BuiltinTypeSpec.Type.Bool:
+			case BuiltinTypeSpec.Type.Char:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.Float:
+			case BuiltinTypeSpec.Type.UIntPtr:
+			case BuiltinTypeSpec.Type.IntPtr:
+				return true;
+			}
+
+			if (TypeSpec.IsReferenceType (MemberType))
+				return true;
+
+			if (MemberType.IsEnum)
+				return true;
+
+			return false;
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+		
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			MetaType[] required_modifier = null;
+			if ((ModFlags & Modifiers.VOLATILE) != 0) {
+				var mod = Module.PredefinedTypes.IsVolatile.Resolve ();
+				if (mod != null)
+					required_modifier = new MetaType[] { mod.GetMetaInfo () };
+			}
+
+			FieldBuilder = Parent.TypeBuilder.DefineField (
+				Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
+
+			spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
+
+			//
+			// Don't cache inaccessible fields except for struct where we
+			// need them for definitive assignment checks
+			//
+			if ((ModFlags & Modifiers.BACKING_FIELD) == 0 || Parent.Kind == MemberKind.Struct) {
+				Parent.MemberCache.AddMember (spec);
+			}
+
+			if (initializer != null) {
+				Parent.RegisterFieldForInitialization (this, new FieldInitializer (this, initializer, TypeExpression.Location));
+			}
+
+			if (declarators != null) {
+				foreach (var d in declarators) {
+					var f = new Field (Parent, d.GetFieldTypeExpression (this), ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
+					if (d.Initializer != null)
+						f.initializer = d.Initializer;
+
+					f.Define ();
+					Parent.PartialContainer.Members.Add (f);
+				}
+			}
+
+			return true;
+		}
+
+		protected override void DoMemberTypeDependentChecks ()
+		{
+			if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
+				return;
+
+			base.DoMemberTypeDependentChecks ();
+
+			if ((ModFlags & Modifiers.VOLATILE) != 0) {
+				if (!CanBeVolatile ()) {
+					Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
+						GetSignatureForError (), MemberType.GetSignatureForError ());
+				}
+
+				if ((ModFlags & Modifiers.READONLY) != 0) {
+					Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
+						GetSignatureForError ());
+				}
+			}
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			if ((ModFlags & Modifiers.VOLATILE) != 0) {
+				Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
+			}
+
+			return true;
+		}
+	}
+
+	class PrimaryConstructorField : Field
+	{
+		//
+		// Proxy resolved parameter type expression to avoid type double resolve
+		// and problems with correct resolve context on partial classes
+		//
+		sealed class TypeExpressionFromParameter : TypeExpr
+		{
+			Parameter parameter;
+
+			public TypeExpressionFromParameter (Parameter parameter)
+			{
+				this.parameter = parameter;
+				eclass = ExprClass.Type;
+				loc = parameter.Location;
+			}
+
+			public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments)
+			{
+				return parameter.Type;
+			}
+		}
+
+		public PrimaryConstructorField (TypeDefinition parent, Parameter parameter)
+			: base (parent, new TypeExpressionFromParameter (parameter), Modifiers.PRIVATE, new MemberName (parameter.Name, parameter.Location), null)
+		{
+			caching_flags |= Flags.IsUsed | Flags.IsAssigned;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return MemberName.Name;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/flowanalysis.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/flowanalysis.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/flowanalysis.cs	(revision 11807)
@@ -0,0 +1,685 @@
+//
+// flowanalyis.cs: The control flow analysis code
+//
+// Authors:
+//   Martin Baulig (martin@ximian.com)
+//   Raja R Harinath (rharinath@novell.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin, Inc.
+//
+
+using System;
+using System.Text;
+using System.Collections.Generic;
+
+namespace Mono.CSharp
+{
+	// <summary>
+	//   This is used by the flow analysis code to keep track of the type of local variables.
+	//
+	//   The flow code uses a BitVector to keep track of whether a variable has been assigned
+	//   or not.  This is easy for fundamental types (int, char etc.) or reference types since
+	//   you can only assign the whole variable as such.
+	//
+	//   For structs, we also need to keep track of all its fields.  To do this, we allocate one
+	//   bit for the struct itself (it's used if you assign/access the whole struct) followed by
+	//   one bit for each of its fields.
+	//
+	//   This class computes this `layout' for each type.
+	// </summary>
+	public class TypeInfo
+	{
+		// <summary>
+		//   Total number of bits a variable of this type consumes in the flow vector.
+		// </summary>
+		public readonly int TotalLength;
+
+		// <summary>
+		//   Number of bits the simple fields of a variable of this type consume
+		//   in the flow vector.
+		// </summary>
+		public readonly int Length;
+
+		// <summary>
+		//   This is only used by sub-structs.
+		// </summary>
+		public readonly int Offset;
+
+		// <summary>
+		//   If this is a struct.
+		// </summary>
+		public readonly bool IsStruct;
+
+		// <summary>
+		//   If this is a struct, all fields which are structs theirselves.
+		// </summary>
+		public TypeInfo[] SubStructInfo;
+
+		readonly StructInfo struct_info;
+		private static Dictionary<TypeSpec, TypeInfo> type_hash;
+
+		static readonly TypeInfo simple_type = new TypeInfo (1);
+		
+		static TypeInfo ()
+		{
+			Reset ();
+		}
+		
+		public static void Reset ()
+		{
+			type_hash = new Dictionary<TypeSpec, TypeInfo> ();
+			StructInfo.field_type_hash = new Dictionary<TypeSpec, StructInfo> ();
+		}
+
+		TypeInfo (int totalLength)
+		{
+			this.TotalLength = totalLength;
+		}
+		
+		TypeInfo (StructInfo struct_info, int offset)
+		{
+			this.struct_info = struct_info;
+			this.Offset = offset;
+			this.Length = struct_info.Length;
+			this.TotalLength = struct_info.TotalLength;
+			this.SubStructInfo = struct_info.StructFields;
+			this.IsStruct = true;
+		}
+		
+		public int GetFieldIndex (string name)
+		{
+			if (struct_info == null)
+				return 0;
+
+			return struct_info [name];
+		}
+
+		public TypeInfo GetStructField (string name)
+		{
+			if (struct_info == null)
+				return null;
+
+			return struct_info.GetStructField (name);
+		}
+
+		public static TypeInfo GetTypeInfo (TypeSpec type)
+		{
+			if (!type.IsStruct)
+				return simple_type;
+
+			TypeInfo info;
+			if (type_hash.TryGetValue (type, out info))
+				return info;
+
+			var struct_info = StructInfo.GetStructInfo (type);
+			if (struct_info != null) {
+				info = new TypeInfo (struct_info, 0);
+			} else {
+				info = simple_type;
+			}
+
+			type_hash.Add (type, info);
+			return info;
+		}
+
+		// <summary>
+		//   A struct's constructor must always assign all fields.
+		//   This method checks whether it actually does so.
+		// </summary>
+		public bool IsFullyInitialized (FlowAnalysisContext fc, VariableInfo vi, Location loc)
+		{
+			if (struct_info == null)
+				return true;
+
+			bool ok = true;
+			for (int i = 0; i < struct_info.Count; i++) {
+				var field = struct_info.Fields[i];
+
+				if (!fc.IsStructFieldDefinitelyAssigned (vi, field.Name)) {
+					var bf = field.MemberDefinition as Property.BackingField;
+					if (bf != null) {
+						if (bf.Initializer != null)
+							continue;
+
+						fc.Report.Error (843, loc,
+							"An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling the default struct contructor from a constructor initializer",
+							field.GetSignatureForError ());
+
+						ok = false;
+						continue;
+					}
+
+					fc.Report.Error (171, loc,
+						"Field `{0}' must be fully assigned before control leaves the constructor",
+						field.GetSignatureForError ());
+					ok = false;
+				}
+			}
+
+			return ok;
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("TypeInfo ({0}:{1}:{2})",
+					      Offset, Length, TotalLength);
+		}
+
+		class StructInfo
+		{
+			readonly List<FieldSpec> fields;
+			public readonly TypeInfo[] StructFields;
+			public readonly int Length;
+			public readonly int TotalLength;
+
+			public static Dictionary<TypeSpec, StructInfo> field_type_hash;
+			private Dictionary<string, TypeInfo> struct_field_hash;
+			private Dictionary<string, int> field_hash;
+
+			bool InTransit;
+
+			//
+			// We only need one instance per type
+			//
+			StructInfo (TypeSpec type)
+			{
+				field_type_hash.Add (type, this);
+
+				fields = MemberCache.GetAllFieldsForDefiniteAssignment (type);
+
+				struct_field_hash = new Dictionary<string, TypeInfo> ();
+				field_hash = new Dictionary<string, int> (fields.Count);
+
+				StructFields = new TypeInfo[fields.Count];
+				StructInfo[] sinfo = new StructInfo[fields.Count];
+
+				InTransit = true;
+
+				for (int i = 0; i < fields.Count; i++) {
+					var field = fields [i];
+
+					if (field.MemberType.IsStruct)
+						sinfo [i] = GetStructInfo (field.MemberType);
+
+					if (sinfo [i] == null)
+						field_hash.Add (field.Name, ++Length);
+					else if (sinfo [i].InTransit) {
+						sinfo [i] = null;
+						return;
+					}
+				}
+
+				InTransit = false;
+
+				TotalLength = Length + 1;
+				for (int i = 0; i < fields.Count; i++) {
+					var field = fields [i];
+
+					if (sinfo [i] == null)
+						continue;
+
+					field_hash.Add (field.Name, TotalLength);
+
+					StructFields [i] = new TypeInfo (sinfo [i], TotalLength);
+					struct_field_hash.Add (field.Name, StructFields [i]);
+					TotalLength += sinfo [i].TotalLength;
+				}
+			}
+
+			public int Count {
+				get {
+					return fields.Count;
+				}
+			}
+
+			public List<FieldSpec> Fields {
+				get {
+					return fields;
+				}
+			}
+
+			public int this [string name] {
+				get {
+					int val;
+					if (!field_hash.TryGetValue (name, out val))
+						return 0;
+
+					return val;
+				}
+			}
+
+			public TypeInfo GetStructField (string name)
+			{
+				TypeInfo ti;
+				if (struct_field_hash.TryGetValue (name, out ti))
+					return ti;
+
+				return null;
+			}
+
+			public static StructInfo GetStructInfo (TypeSpec type)
+			{
+				if (type.BuiltinType > 0)
+					return null;
+
+				StructInfo info;
+				if (field_type_hash.TryGetValue (type, out info))
+					return info;
+
+				return new StructInfo (type);
+			}
+		}
+	}
+
+	//
+	// This is used by definite assignment analysis code to store information about a local variable
+	// or parameter.  Depending on the variable's type, we need to allocate one or more elements
+	// in the BitVector - if it's a fundamental or reference type, we just need to know whether
+	// it has been assigned or not, but for structs, we need this information for each of its fields.
+	//
+	public class VariableInfo
+	{
+		readonly string Name;
+
+		readonly TypeInfo TypeInfo;
+
+		// <summary>
+		//   The bit offset of this variable in the flow vector.
+		// </summary>
+		readonly int Offset;
+
+		// <summary>
+		//   The number of bits this variable needs in the flow vector.
+		//   The first bit always specifies whether the variable as such has been assigned while
+		//   the remaining bits contain this information for each of a struct's fields.
+		// </summary>
+		readonly int Length;
+
+		// <summary>
+		//   If this is a parameter of local variable.
+		// </summary>
+		public bool IsParameter;
+
+		VariableInfo[] sub_info;
+
+		VariableInfo (string name, TypeSpec type, int offset)
+		{
+			this.Name = name;
+			this.Offset = offset;
+			this.TypeInfo = TypeInfo.GetTypeInfo (type);
+
+			Length = TypeInfo.TotalLength;
+
+			Initialize ();
+		}
+
+		VariableInfo (VariableInfo parent, TypeInfo type)
+		{
+			this.Name = parent.Name;
+			this.TypeInfo = type;
+			this.Offset = parent.Offset + type.Offset;
+			this.Length = type.TotalLength;
+
+			this.IsParameter = parent.IsParameter;
+
+			Initialize ();
+		}
+
+		void Initialize ()
+		{
+			TypeInfo[] sub_fields = TypeInfo.SubStructInfo;
+			if (sub_fields != null) {
+				sub_info = new VariableInfo [sub_fields.Length];
+				for (int i = 0; i < sub_fields.Length; i++) {
+					if (sub_fields [i] != null)
+						sub_info [i] = new VariableInfo (this, sub_fields [i]);
+				}
+			} else
+				sub_info = new VariableInfo [0];
+		}
+
+		public static VariableInfo Create (BlockContext bc, LocalVariable variable)
+		{
+			var info = new VariableInfo (variable.Name, variable.Type, bc.AssignmentInfoOffset);
+			bc.AssignmentInfoOffset += info.Length;
+			return info;
+		}
+
+		public static VariableInfo Create (BlockContext bc, Parameter parameter)
+		{
+			var info = new VariableInfo (parameter.Name, parameter.Type, bc.AssignmentInfoOffset) {
+				IsParameter = true
+			};
+
+			bc.AssignmentInfoOffset += info.Length;
+			return info;
+		}
+
+		public bool IsAssigned (DefiniteAssignmentBitSet vector)
+		{
+			if (vector == null)
+				return true;
+
+			if (vector [Offset])
+				return true;
+
+			// Unless this is a struct
+			if (!TypeInfo.IsStruct)
+				return false;
+
+			//
+			// Following case cannot be handled fully by SetStructFieldAssigned
+			// because we may encounter following case
+			// 
+			// struct A { B b }
+			// struct B { int value; }
+			//
+			// setting a.b.value is propagated only to B's vector and not upwards to possible parents
+			//
+			//
+			// Each field must be assigned
+			//
+			for (int i = Offset + 1; i <= TypeInfo.Length + Offset; i++) {
+				if (!vector[i])
+					return false;
+			}
+
+			// Ok, now check all fields which are structs.
+			for (int i = 0; i < sub_info.Length; i++) {
+				VariableInfo sinfo = sub_info[i];
+				if (sinfo == null)
+					continue;
+
+				if (!sinfo.IsAssigned (vector))
+					return false;
+			}
+			
+			vector.Set (Offset);
+			return true;
+		}
+
+		public bool IsEverAssigned { get; set; }
+
+		public bool IsFullyInitialized (FlowAnalysisContext fc, Location loc)
+		{
+			return TypeInfo.IsFullyInitialized (fc, this, loc);
+		}
+
+		public bool IsStructFieldAssigned (DefiniteAssignmentBitSet vector, string field_name)
+		{
+			int field_idx = TypeInfo.GetFieldIndex (field_name);
+
+			if (field_idx == 0)
+				return true;
+
+			return vector [Offset + field_idx];
+		}
+
+		public void SetAssigned (DefiniteAssignmentBitSet vector, bool generatedAssignment)
+		{
+			if (Length == 1)
+				vector.Set (Offset);
+			else
+				vector.Set (Offset, Length);
+
+			if (!generatedAssignment)
+				IsEverAssigned = true;
+		}
+
+		public void SetStructFieldAssigned (DefiniteAssignmentBitSet vector, string field_name)
+		{
+			if (vector [Offset])
+				return;
+
+			int field_idx = TypeInfo.GetFieldIndex (field_name);
+
+			if (field_idx == 0)
+				return;
+
+			var complex_field = TypeInfo.GetStructField (field_name);
+			if (complex_field != null) {
+				vector.Set (Offset + complex_field.Offset, complex_field.TotalLength);
+			} else {
+				vector.Set (Offset + field_idx);
+			}
+
+			IsEverAssigned = true;
+
+			//
+			// Each field must be assigned before setting master bit
+			//
+			for (int i = Offset + 1; i < TypeInfo.TotalLength + Offset; i++) {
+				if (!vector[i])
+					return;
+			}
+
+			//
+			// Set master struct flag to assigned when all tested struct
+			// fields have been assigned
+			//
+			vector.Set (Offset);
+		}
+
+		public VariableInfo GetStructFieldInfo (string fieldName)
+		{
+			TypeInfo type = TypeInfo.GetStructField (fieldName);
+
+			if (type == null)
+				return null;
+
+			return new VariableInfo (this, type);
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("Name={0} Offset={1} Length={2} {3})", Name, Offset, Length, TypeInfo);
+		}
+	}
+
+	public struct Reachability
+	{
+		readonly bool unreachable;
+
+		Reachability (bool unreachable)
+		{
+			this.unreachable = unreachable;
+		}
+
+		public bool IsUnreachable {
+			get {
+				return unreachable;
+			}
+		}
+
+		public static Reachability CreateUnreachable ()
+		{
+			return new Reachability (true);
+		}
+
+		public static Reachability operator & (Reachability a, Reachability b)
+		{
+		    return new Reachability (a.unreachable && b.unreachable);
+		}
+
+		public static Reachability operator | (Reachability a, Reachability b)
+		{
+			return new Reachability (a.unreachable | b.unreachable);
+		}
+	}
+
+	//
+	// Special version of bit array. Many operations can be simplified because
+	// we are always dealing with arrays of same sizes
+	//
+	public class DefiniteAssignmentBitSet
+	{
+		const uint copy_on_write_flag = 1u << 31;
+
+		uint bits;
+
+		// Used when bits overflows
+		int[] large_bits;
+
+		public static readonly DefiniteAssignmentBitSet Empty = new DefiniteAssignmentBitSet (0);
+
+		public DefiniteAssignmentBitSet (int length)
+		{
+			if (length > 31)
+				large_bits = new int[(length + 31) / 32];
+		}
+
+		public DefiniteAssignmentBitSet (DefiniteAssignmentBitSet source)
+		{
+			if (source.large_bits != null) {
+				large_bits = source.large_bits;
+				bits = source.bits | copy_on_write_flag;
+			} else {
+				bits = source.bits & ~copy_on_write_flag;
+			}
+		}
+
+		public static DefiniteAssignmentBitSet operator & (DefiniteAssignmentBitSet a, DefiniteAssignmentBitSet b)
+		{
+			if (AreEqual (a, b))
+				return a;
+
+			DefiniteAssignmentBitSet res;
+			if (a.large_bits == null) {
+				res = new DefiniteAssignmentBitSet (a);
+				res.bits &= (b.bits & ~copy_on_write_flag);
+				return res;
+			}
+
+			res = new DefiniteAssignmentBitSet (a);
+			res.Clone ();
+			var dest = res.large_bits;
+			var src = b.large_bits;
+			for (int i = 0; i < dest.Length; ++i) {
+				dest[i] &= src[i];
+			}
+
+			return res;
+		}
+
+		public static DefiniteAssignmentBitSet operator | (DefiniteAssignmentBitSet a, DefiniteAssignmentBitSet b)
+		{
+			if (AreEqual (a, b))
+				return a;
+
+			DefiniteAssignmentBitSet res;
+			if (a.large_bits == null) {
+				res = new DefiniteAssignmentBitSet (a);
+				res.bits |= b.bits;
+				res.bits &= ~copy_on_write_flag;
+				return res;
+			}
+
+			res = new DefiniteAssignmentBitSet (a);
+			res.Clone ();
+			var dest = res.large_bits;
+			var src = b.large_bits;
+
+			for (int i = 0; i < dest.Length; ++i) {
+				dest[i] |= src[i];
+			}
+
+			return res;
+		}
+
+		public static DefiniteAssignmentBitSet And (List<DefiniteAssignmentBitSet> das)
+		{
+			if (das.Count == 0)
+				throw new ArgumentException ("Empty das");
+
+			DefiniteAssignmentBitSet res = das[0];
+			for (int i = 1; i < das.Count; ++i) {
+				res &= das[i];
+			}
+
+			return res;
+		}
+
+		bool CopyOnWrite {
+			get {
+				return (bits & copy_on_write_flag) != 0;
+			}
+		}
+
+		int Length {
+			get {
+				return large_bits == null ? 31 : large_bits.Length * 32;
+			}
+		}
+
+		public void Set (int index)
+		{
+			if (CopyOnWrite && !this[index])
+				Clone ();
+
+			SetBit (index);
+		}
+
+		public void Set (int index, int length)
+		{
+			for (int i = 0; i < length; ++i) {
+				if (CopyOnWrite && !this[index + i])
+					Clone ();
+
+				SetBit (index + i);
+			}
+		}
+
+		public bool this[int index] {
+			get {
+				return GetBit (index);
+			}
+		}
+
+		public override string ToString ()
+		{
+			var length = Length;
+			StringBuilder sb = new StringBuilder (length);
+			for (int i = 0; i < length; ++i) {
+				sb.Append (this[i] ? '1' : '0');
+			}
+
+			return sb.ToString ();
+		}
+
+		void Clone ()
+		{
+			large_bits = (int[]) large_bits.Clone ();
+		}
+
+		bool GetBit (int index)
+		{
+			return large_bits == null ?
+				(bits & (1 << index)) != 0 :
+				(large_bits[index >> 5] & (1 << (index & 31))) != 0;
+		}
+
+		void SetBit (int index)
+		{
+			if (large_bits == null)
+				bits = (uint) ((int) bits | (1 << index));
+			else
+				large_bits[index >> 5] |= (1 << (index & 31));
+		}
+
+		static bool AreEqual (DefiniteAssignmentBitSet a, DefiniteAssignmentBitSet b)
+		{
+			if (a.large_bits == null)
+				return (a.bits & ~copy_on_write_flag) == (b.bits & ~copy_on_write_flag);
+
+			for (int i = 0; i < a.large_bits.Length; ++i) {
+				if (a.large_bits[i] != b.large_bits[i])
+					return false;
+			}
+
+			return true;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/generic.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/generic.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/generic.cs	(revision 11807)
@@ -0,0 +1,3660 @@
+//
+// generic.cs: Generics support
+//
+// Authors: Martin Baulig (martin@ximian.com)
+//          Miguel de Icaza (miguel@ximian.com)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Linq;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+	public class VarianceDecl
+	{
+		public VarianceDecl (Variance variance, Location loc)
+		{
+			this.Variance = variance;
+			this.Location = loc;
+		}
+
+		public Variance Variance { get; private set; }
+		public Location Location { get; private set; }
+
+		public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
+		{
+			var tp = t as TypeParameterSpec;
+			if (tp != null) {
+				var v = tp.Variance;
+				if (expected == Variance.None && v != expected ||
+					expected == Variance.Covariant && v == Variance.Contravariant ||
+					expected == Variance.Contravariant && v == Variance.Covariant) {
+					((TypeParameter) tp.MemberDefinition).ErrorInvalidVariance (member, expected);
+				}
+
+				return expected;
+			}
+
+			if (t.TypeArguments.Length > 0) {
+				var targs_definition = t.MemberDefinition.TypeParameters;
+				TypeSpec[] targs = TypeManager.GetTypeArguments (t);
+				for (int i = 0; i < targs.Length; ++i) {
+					var v = targs_definition[i].Variance;
+					CheckTypeVariance (targs[i], (Variance) ((int) v * (int) expected), member);
+				}
+
+				return expected;
+			}
+
+			var ac = t as ArrayContainer;
+			if (ac != null)
+				return CheckTypeVariance (ac.Element, expected, member);
+
+			return Variance.None;
+		}
+	}
+
+	public enum Variance
+	{
+		//
+		// Don't add or modify internal values, they are used as -/+ calculation signs
+		//
+		None			= 0,
+		Covariant		= 1,
+		Contravariant	= -1
+	}
+
+	[Flags]
+	public enum SpecialConstraint
+	{
+		None		= 0,
+		Constructor = 1 << 2,
+		Class		= 1 << 3,
+		Struct		= 1 << 4
+	}
+
+	public class SpecialContraintExpr : FullNamedExpression
+	{
+		public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
+		{
+			this.loc = loc;
+			this.Constraint = constraint;
+		}
+
+		public SpecialConstraint Constraint { get; private set; }
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+	//
+	// A set of parsed constraints for a type parameter
+	//
+	public class Constraints
+	{
+		readonly SimpleMemberName tparam;
+		readonly List<FullNamedExpression> constraints;
+		readonly Location loc;
+		bool resolved;
+		bool resolving;
+		
+		public IEnumerable<FullNamedExpression> ConstraintExpressions {
+			get {
+				return constraints;
+			}
+		}
+
+		public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
+		{
+			this.tparam = tparam;
+			this.constraints = constraints;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public List<FullNamedExpression> TypeExpressions {
+			get {
+				return constraints;
+			}
+		}
+
+		public Location Location {
+			get {
+				return loc;
+			}
+		}
+
+		public SimpleMemberName TypeParameter {
+			get {
+				return tparam;
+			}
+		}
+
+		#endregion
+
+		public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
+		{
+			if (spec.HasSpecialClass && bb.IsStruct) {
+				context.Module.Compiler.Report.Error (455, loc,
+					"Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
+					spec.Name, "class", bb.GetSignatureForError ());
+
+				return false;
+			}
+
+			return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
+		}
+
+		static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
+		{
+			if (ba == bb)
+				return true;
+
+			if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
+				return true;
+
+			Error_ConflictingConstraints (context, spec, ba, bb, loc);
+			return false;
+		}
+
+		public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
+		{
+			context.Module.Compiler.Report.Error (455, loc,
+				"Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
+				tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
+		}
+
+		public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
+		{
+			foreach (var c in constraints) {
+				if (c == null)
+					continue;
+
+				var t = c.Type;
+				if (t == null)
+					continue;
+
+				if (obsoleteCheck) {
+					ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
+					if (obsolete_attr != null)
+						AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
+				}
+
+				ConstraintChecker.Check (context, t, c.Location);
+			}
+		}
+
+		//
+		// Resolve the constraints types with only possible early checks, return
+		// value `false' is reserved for recursive failure
+		//
+		public bool Resolve (IMemberContext context, TypeParameter tp)
+		{
+			if (resolved)
+				return true;
+
+			if (resolving)
+				return false;
+
+			resolving = true;
+			var spec = tp.Type;
+			List<TypeParameterSpec> tparam_types = null;
+			bool iface_found = false;
+
+			spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
+
+			for (int i = 0; i < constraints.Count; ++i) {
+				var constraint = constraints[i];
+
+				if (constraint is SpecialContraintExpr) {
+					spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
+					if (spec.HasSpecialStruct)
+						spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
+
+					// Set to null as it does not have a type
+					constraints[i] = null;
+					continue;
+				}
+
+				var type = constraint.ResolveAsType (context);
+				if (type == null)
+					continue;
+
+				if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
+					context.Module.Compiler.Report.Error (1968, constraint.Location,
+						"A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
+					continue;
+				}
+
+				if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
+					context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
+					context.Module.Compiler.Report.Error (703, loc,
+						"Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
+						type.GetSignatureForError (), context.GetSignatureForError ());
+				}
+
+				if (type.IsInterface) {
+					if (!spec.AddInterface (type)) {
+						context.Module.Compiler.Report.Error (405, constraint.Location,
+							"Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
+					}
+
+					iface_found = true;
+					continue;
+				}
+					
+				var constraint_tp = type as TypeParameterSpec;
+				if (constraint_tp != null) {
+					if (tparam_types == null) {
+						tparam_types = new List<TypeParameterSpec> (2);
+					} else if (tparam_types.Contains (constraint_tp)) {
+						context.Module.Compiler.Report.Error (405, constraint.Location,
+							"Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
+						continue;
+					}
+
+					//
+					// Checks whether each generic method parameter constraint type
+					// is valid with respect to T
+					//
+					if (tp.IsMethodTypeParameter) {
+						VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
+					}
+
+					var tp_def = constraint_tp.MemberDefinition as TypeParameter;
+					if (tp_def != null && !tp_def.ResolveConstraints (context)) {
+						context.Module.Compiler.Report.Error (454, constraint.Location,
+							"Circular constraint dependency involving `{0}' and `{1}'",
+							constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
+						continue;
+					}
+
+					//
+					// Checks whether there are no conflicts between type parameter constraints
+					//
+					// class Foo<T, U>
+					//      where T : A
+					//      where U : B, T
+					//
+					// A and B are not convertible and only 1 class constraint is allowed
+					//
+					if (constraint_tp.HasTypeConstraint) {
+						if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
+							if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
+								continue;
+						} else {
+							for (int ii = 0; ii < tparam_types.Count; ++ii) {
+								if (!tparam_types[ii].HasTypeConstraint)
+									continue;
+
+								if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
+									break;
+							}
+						}
+					}
+
+					if (constraint_tp.TypeArguments != null) {
+						var eb = constraint_tp.GetEffectiveBase ();
+						if (eb != null && !CheckConflictingInheritedConstraint (spec, eb, spec.BaseType, context, constraint.Location))
+							break;
+					}
+
+					if (constraint_tp.HasSpecialStruct) {
+						context.Module.Compiler.Report.Error (456, constraint.Location,
+							"Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
+							constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
+						continue;
+					}
+
+					tparam_types.Add (constraint_tp);
+					continue;
+				}
+
+				if (iface_found || spec.HasTypeConstraint) {
+					context.Module.Compiler.Report.Error (406, constraint.Location,
+						"The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
+						type.GetSignatureForError ());
+				}
+
+				if (spec.HasSpecialStruct || spec.HasSpecialClass) {
+					context.Module.Compiler.Report.Error (450, constraint.Location,
+						"`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
+						type.GetSignatureForError ());
+				}
+
+				switch (type.BuiltinType) {
+				case BuiltinTypeSpec.Type.Array:
+				case BuiltinTypeSpec.Type.Delegate:
+				case BuiltinTypeSpec.Type.MulticastDelegate:
+				case BuiltinTypeSpec.Type.Enum:
+				case BuiltinTypeSpec.Type.ValueType:
+				case BuiltinTypeSpec.Type.Object:
+					context.Module.Compiler.Report.Error (702, constraint.Location,
+						"A constraint cannot be special class `{0}'", type.GetSignatureForError ());
+					continue;
+				case BuiltinTypeSpec.Type.Dynamic:
+					context.Module.Compiler.Report.Error (1967, constraint.Location,
+						"A constraint cannot be the dynamic type");
+					continue;
+				}
+
+				if (type.IsSealed || !type.IsClass) {
+					context.Module.Compiler.Report.Error (701, loc,
+						"`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
+						type.GetSignatureForError ());
+					continue;
+				}
+
+				if (type.IsStatic) {
+					context.Module.Compiler.Report.Error (717, constraint.Location,
+						"`{0}' is not a valid constraint. Static classes cannot be used as constraints",
+						type.GetSignatureForError ());
+				}
+
+				spec.BaseType = type;
+			}
+
+			if (tparam_types != null)
+				spec.TypeArguments = tparam_types.ToArray ();
+
+			resolving = false;
+			resolved = true;
+			return true;
+		}
+
+		public void VerifyClsCompliance (Report report)
+		{
+			foreach (var c in constraints)
+			{
+				if (c == null)
+					continue;
+
+				if (!c.Type.IsCLSCompliant ()) {
+					report.SymbolRelatedToPreviousError (c.Type);
+					report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
+						c.Type.GetSignatureForError ());
+				}
+			}
+		}
+	}
+
+	//
+	// A type parameter for a generic type or generic method definition
+	//
+	public class TypeParameter : MemberCore, ITypeDefinition
+	{
+		static readonly string[] attribute_target = { "type parameter" };
+		
+		Constraints constraints;
+		GenericTypeParameterBuilder builder;
+		readonly TypeParameterSpec spec;
+
+		public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
+			: base (null, name, attrs)
+		{
+			this.constraints = constraints;
+			this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
+		}
+
+		//
+		// Used by parser
+		//
+		public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
+			: base (null, name, attrs)
+		{
+			var var = variance == null ? Variance.None : variance.Variance;
+			this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
+			this.VarianceDecl = variance;
+		}
+		
+		public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
+			: base (null, name, attrs)
+		{
+			this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
+				BaseType = spec.BaseType,
+				InterfacesDefined = spec.InterfacesDefined,
+				TypeArguments = spec.TypeArguments
+			};
+		}
+		
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.GenericParameter;
+			}
+		}
+
+		public Constraints Constraints {
+			get {
+				return constraints;
+			}
+			set {
+				constraints = value;
+			}
+		}
+
+		public IAssemblyDefinition DeclaringAssembly {
+			get	{
+				return Module.DeclaringAssembly;
+			}
+		}
+
+		public override string DocCommentHeader {
+			get {
+				throw new InvalidOperationException (
+					"Unexpected attempt to get doc comment from " + this.GetType ());
+			}
+		}
+
+		bool ITypeDefinition.IsComImport {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsPartial {
+			get {
+				return false;
+			}
+		}
+
+		public bool IsMethodTypeParameter {
+			get {
+				return spec.IsMethodOwned;
+			}
+		}
+
+		bool ITypeDefinition.IsTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsCyclicTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		public string Name {
+			get {
+				return MemberName.Name;
+			}
+		}
+
+		public string Namespace {
+			get {
+				return null;
+			}
+		}
+
+		public TypeParameterSpec Type {
+			get {
+				return spec;
+			}
+		}
+
+		public int TypeParametersCount {
+			get {
+				return 0;
+			}
+		}
+
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				return null;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_target;
+			}
+		}
+
+		public Variance Variance {
+			get {
+				return spec.Variance;
+			}
+		}
+
+		public VarianceDecl VarianceDecl { get; private set; }
+
+		#endregion
+
+		//
+		// This is called for each part of a partial generic type definition.
+		//
+		// If partial type parameters constraints are not null and we don't
+		// already have constraints they become our constraints. If we already
+		// have constraints, we must check that they're same.
+		//
+		public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
+		{
+			if (builder == null)
+				throw new InvalidOperationException ();
+
+			var new_constraints = tp.constraints;
+			if (new_constraints == null)
+				return true;
+
+			// TODO: could create spec only
+			//tp.Define (null, -1, part.Definition);
+			tp.spec.DeclaringType = part.Definition;
+			if (!tp.ResolveConstraints (part))
+				return false;
+
+			if (constraints != null)
+				return spec.HasSameConstraintsDefinition (tp.Type);
+
+			// Copy constraint from resolved part to partial container
+			spec.SpecialConstraint = tp.spec.SpecialConstraint;
+			spec.InterfacesDefined = tp.spec.InterfacesDefined;
+			spec.TypeArguments = tp.spec.TypeArguments;
+			spec.BaseType = tp.spec.BaseType;
+			
+			return true;
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		public void CheckGenericConstraints (bool obsoleteCheck)
+		{
+			if (constraints != null)
+				constraints.CheckGenericConstraints (this, obsoleteCheck);
+		}
+
+		public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
+		{
+			return new TypeParameter (spec, declaringSpec, MemberName, null);
+		}
+
+		public override bool Define ()
+		{
+			return true;
+		}
+
+		//
+		// This is the first method which is called during the resolving
+		// process; we're called immediately after creating the type parameters
+		// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
+		// MethodBuilder).
+		//
+		public void Create (TypeSpec declaringType, TypeContainer parent)
+		{
+			if (builder != null)
+				throw new InternalErrorException ();
+
+			// Needed to get compiler reference
+			this.Parent = parent;
+			spec.DeclaringType = declaringType;
+		}
+
+		public void Define (GenericTypeParameterBuilder type)
+		{
+			this.builder = type;
+			spec.SetMetaInfo (type);
+		}
+
+		public void Define (TypeParameter tp)
+		{
+			builder = tp.builder;
+		}
+
+		public void EmitConstraints (GenericTypeParameterBuilder builder)
+		{
+			var attr = GenericParameterAttributes.None;
+			if (spec.Variance == Variance.Contravariant)
+				attr |= GenericParameterAttributes.Contravariant;
+			else if (spec.Variance == Variance.Covariant)
+				attr |= GenericParameterAttributes.Covariant;
+
+			if (spec.HasSpecialClass)
+				attr |= GenericParameterAttributes.ReferenceTypeConstraint;
+			else if (spec.HasSpecialStruct)
+				attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
+
+			if (spec.HasSpecialConstructor)
+				attr |= GenericParameterAttributes.DefaultConstructorConstraint;
+
+			if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
+				builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
+
+			if (spec.InterfacesDefined != null)
+				builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
+
+			if (spec.TypeArguments != null) {
+				var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
+				foreach (var c in spec.TypeArguments) {
+					//
+					// Inflated type parameters can collide with special constraint types, don't
+					// emit any such type parameter.
+					//
+					if (c.BuiltinType == BuiltinTypeSpec.Type.Object || c.BuiltinType == BuiltinTypeSpec.Type.ValueType)
+						continue;
+
+					meta_constraints.Add (c.GetMetaInfo ());
+				}
+
+				builder.SetInterfaceConstraints (meta_constraints.ToArray ());
+			}
+
+			builder.SetGenericParameterAttributes (attr);
+		}
+
+		public override void Emit ()
+		{
+			EmitConstraints (builder);
+
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			base.Emit ();
+		}
+
+		public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
+		{
+			Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
+			string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
+			string gtype_variance;
+			switch (expected) {
+			case Variance.Contravariant: gtype_variance = "contravariantly"; break;
+			case Variance.Covariant: gtype_variance = "covariantly"; break;
+			default: gtype_variance = "invariantly"; break;
+			}
+
+			Delegate d = mc as Delegate;
+			string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
+
+			Report.Error (1961, Location,
+				"The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
+					GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
+		}
+
+		public TypeSpec GetAttributeCoClass ()
+		{
+			return null;
+		}
+
+		public string GetAttributeDefaultMember ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return MemberName.Name;
+		}
+
+		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
+		{
+			return spec.MemberDefinition.DeclaringAssembly == assembly;
+		}
+
+		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+		{
+			throw new NotSupportedException ("Not supported for compiled definition");
+		}
+
+		//
+		// Resolves all type parameter constraints
+		//
+		public bool ResolveConstraints (IMemberContext context)
+		{
+			if (constraints != null)
+				return constraints.Resolve (context, this);
+
+			if (spec.BaseType == null)
+				spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
+
+			return true;
+		}
+
+		public override bool IsClsComplianceRequired ()
+		{
+			return false;
+		}
+
+		public new void VerifyClsCompliance ()
+		{
+			if (constraints != null)
+				constraints.VerifyClsCompliance (Report);
+		}
+
+		public void WarningParentNameConflict (TypeParameter conflict)
+		{
+			conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
+			conflict.Report.Warning (693, 3, Location,
+				"Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
+				GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
+		}
+	}
+
+	[System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
+	public class TypeParameterSpec : TypeSpec
+	{
+		public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
+
+		Variance variance;
+		SpecialConstraint spec;
+		int tp_pos;
+		TypeSpec[] targs;
+		TypeSpec[] ifaces_defined;
+		TypeSpec effective_base;
+
+		//
+		// Creates type owned type parameter
+		//
+		public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
+			: base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
+		{
+			this.variance = variance;
+			this.spec = spec;
+			state &= ~StateFlags.Obsolete_Undetected;
+			tp_pos = index;
+		}
+
+		//
+		// Creates method owned type parameter
+		//
+		public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
+			: this (null, index, definition, spec, variance, info)
+		{
+		}
+
+		#region Properties
+
+		public int DeclaredPosition {
+			get {
+				return tp_pos;
+			}
+			set {
+				tp_pos = value;
+			}
+		}
+
+		public bool HasSpecialConstructor {
+			get {
+				return (spec & SpecialConstraint.Constructor) != 0;
+			}
+		}
+
+		public bool HasSpecialClass {
+			get {
+				return (spec & SpecialConstraint.Class) != 0;
+			}
+		}
+
+		public bool HasSpecialStruct {
+			get {
+				return (spec & SpecialConstraint.Struct) != 0;
+			}
+		}
+
+		public bool HasAnyTypeConstraint {
+			get {
+				return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
+			}
+		}
+
+		public bool HasTypeConstraint {
+			get {
+				var bt = BaseType.BuiltinType;
+				return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
+			}
+		}
+
+		public override IList<TypeSpec> Interfaces {
+			get {
+				if ((state & StateFlags.InterfacesExpanded) == 0) {
+					if (ifaces != null) {
+						if (ifaces_defined == null)
+							ifaces_defined = ifaces.ToArray ();
+
+						for (int i = 0; i < ifaces_defined.Length; ++i ) {
+							var iface_type = ifaces_defined[i];
+							var td = iface_type.MemberDefinition as TypeDefinition;
+							if (td != null)
+								td.DoExpandBaseInterfaces ();
+
+							if (iface_type.Interfaces != null) {
+								for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
+									var ii_iface_type = iface_type.Interfaces [ii];
+									AddInterface (ii_iface_type);
+								}
+							}
+						}
+					} else if (ifaces_defined == null) {
+						ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
+					}
+
+					//
+					// Include all base type interfaces too, see ImportTypeBase for details
+					//
+					if (BaseType != null) {
+						var td = BaseType.MemberDefinition as TypeDefinition;
+						if (td != null)
+							td.DoExpandBaseInterfaces ();
+
+						if (BaseType.Interfaces != null) {
+							foreach (var iface in BaseType.Interfaces) {
+								AddInterface (iface);
+							}
+						}
+					}
+
+					state |= StateFlags.InterfacesExpanded;
+				}
+
+				return ifaces;
+			}
+		}
+
+		//
+		// Unexpanded interfaces list
+		//
+		public TypeSpec[] InterfacesDefined {
+			get {
+				if (ifaces_defined == null) {
+					ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
+				}
+
+				return ifaces_defined.Length == 0 ? null : ifaces_defined;
+			}
+			set {
+				ifaces_defined = value;
+				if (value != null && value.Length != 0)
+					ifaces = new List<TypeSpec> (value);
+			}
+		}
+
+		public bool IsConstrained {
+			get {
+				return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
+			}
+		}
+
+		//
+		// Returns whether the type parameter is known to be a reference type
+		//
+		public new bool IsReferenceType {
+			get {
+				if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
+					return (spec & SpecialConstraint.Class) != 0;
+
+				//
+				// Full check is needed (see IsValueType for details)
+				//
+				if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
+					return true;
+
+				if (targs != null) {
+					foreach (var ta in targs) {
+						//
+						// Secondary special constraints are ignored (I am not sure why)
+						//
+						var tp = ta as TypeParameterSpec;
+						if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
+							continue;
+
+						if (TypeSpec.IsReferenceType (ta))
+							return true;
+					}
+				}
+
+				return false;
+			}
+		}
+
+		//
+		// Returns whether the type parameter is known to be a value type
+		//
+		public new bool IsValueType {
+			get {
+				//
+				// Even if structs/enums cannot be used directly as constraints
+				// they can apear as constraint type when inheriting base constraint
+				// which has dependant type parameter constraint which has been
+				// inflated using value type
+				//
+				// class A : B<int> { override void Foo<U> () {} }
+				// class B<T> { virtual void Foo<U> () where U : T {} }
+				//
+				if (HasSpecialStruct)
+					return true;
+
+				if (targs != null) {
+					foreach (var ta in targs) {
+						if (TypeSpec.IsValueType (ta))
+							return true;
+					}
+				}
+
+				return false;
+			}
+		}
+
+		public override string Name {
+			get {
+				return definition.Name;
+			}
+		}
+
+		public bool IsMethodOwned {
+			get {
+				return DeclaringType == null;
+			}
+		}
+
+		public SpecialConstraint SpecialConstraint {
+			get {
+				return spec;
+			}
+			set {
+				spec = value;
+			}
+		}
+
+		//
+		// Types used to inflate the generic type
+		//
+		public new TypeSpec[] TypeArguments {
+			get {
+				return targs;
+			}
+			set {
+				targs = value;
+			}
+		}
+
+		public Variance Variance {
+			get {
+				return variance;
+			}
+		}
+
+		#endregion
+
+		public string DisplayDebugInfo ()
+		{
+			var s = GetSignatureForError ();
+			return IsMethodOwned ? s + "!!" : s + "!";
+		}
+
+		//
+		// Finds effective base class. The effective base class is always a class-type
+		//
+		public TypeSpec GetEffectiveBase ()
+		{
+			if (HasSpecialStruct)
+				return BaseType;
+
+			//
+			// If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
+			//
+			if (BaseType != null && targs == null) {
+				//
+				// If T has a constraint V that is a value-type, use instead the most specific base type of V that is a class-type.
+				// 
+				// LAMESPEC: Is System.ValueType always the most specific base type in this case?
+				//
+				// Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
+				// are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
+				//
+				return BaseType.IsStruct ? BaseType.BaseType : BaseType;
+			}
+
+			if (effective_base != null)
+				return effective_base;
+
+			var types = new TypeSpec [HasTypeConstraint ? targs.Length + 1 : targs.Length];
+
+			for (int i = 0; i < targs.Length; ++i) {
+				var t = targs [i];
+
+				// Same issue as above, inherited constraints can be of struct type
+				if (t.IsStruct) {
+					types [i] = t.BaseType;
+					continue;
+				}
+
+				var tps = t as TypeParameterSpec;
+				types [i] = tps != null ? tps.GetEffectiveBase () : t;
+			}
+
+			if (HasTypeConstraint)
+				types [types.Length - 1] = BaseType;
+
+			return effective_base = Convert.FindMostEncompassedType (types);
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			var prefix = IsMethodOwned ? "``" : "`";
+			return prefix + DeclaredPosition;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return Name;
+		}
+
+		//
+		// Constraints have to match by definition but not position, used by
+		// partial classes or methods
+		//
+		public bool HasSameConstraintsDefinition (TypeParameterSpec other)
+		{
+			if (spec != other.spec)
+				return false;
+
+			if (BaseType != other.BaseType)
+				return false;
+
+			if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
+				return false;
+
+			if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
+				return false;
+
+			return true;
+		}
+
+		//
+		// Constraints have to match by using same set of types, used by
+		// implicit interface implementation
+		//
+		public bool HasSameConstraintsImplementation (TypeParameterSpec other)
+		{
+			if (spec != other.spec)
+				return false;
+
+			//
+			// It can be same base type or inflated type parameter
+			//
+			// interface I<T> { void Foo<U> where U : T; }
+			// class A : I<int> { void Foo<X> where X : int {} }
+			//
+			bool found;
+			if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
+				if (other.targs == null)
+					return false;
+
+				found = false;
+				foreach (var otarg in other.targs) {
+					if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
+						found = true;
+						break;
+					}
+				}
+
+				if (!found)
+					return false;
+			}
+
+			// Check interfaces implementation -> definition
+			if (InterfacesDefined != null) {
+				//
+				// Iterate over inflated interfaces
+				//
+				foreach (var iface in Interfaces) {
+					found = false;
+					if (other.InterfacesDefined != null) {
+						foreach (var oiface in other.Interfaces) {
+							if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
+								found = true;
+								break;
+							}
+						}
+					}
+
+					if (found)
+						continue;
+
+					if (other.targs != null) {
+						foreach (var otarg in other.targs) {
+							if (TypeSpecComparer.Override.IsEqual (iface, otarg)) {
+								found = true;
+								break;
+							}
+						}
+					}
+
+					if (!found)
+						return false;
+				}
+			}
+
+			// Check interfaces implementation <- definition
+			if (other.InterfacesDefined != null) {
+				if (InterfacesDefined == null)
+					return false;
+
+				//
+				// Iterate over inflated interfaces
+				//
+				foreach (var oiface in other.Interfaces) {
+					found = false;
+					foreach (var iface in Interfaces) {
+						if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
+							found = true;
+							break;
+						}
+					}
+
+					if (!found)
+						return false;
+				}
+			}
+
+			// Check type parameters implementation -> definition
+			if (targs != null) {
+				if (other.targs == null)
+					return false;
+
+				foreach (var targ in targs) {
+					found = false;
+					foreach (var otarg in other.targs) {
+						if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
+							found = true;
+							break;
+						}
+					}
+
+					if (!found)
+						return false;
+				}
+			}
+
+			// Check type parameters implementation <- definition
+			if (other.targs != null) {
+				foreach (var otarg in other.targs) {
+					// Ignore inflated type arguments, were checked above
+					if (!otarg.IsGenericParameter)
+						continue;
+
+					if (targs == null)
+						return false;
+
+					found = false;
+					foreach (var targ in targs) {
+						if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
+							found = true;
+							break;
+						}
+					}
+
+					if (!found)
+						return false;
+				}				
+			}
+
+			return true;
+		}
+
+		public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
+		{
+			return InflateConstraints (tparams, l => l, inflator);
+		}
+
+		public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
+		{
+			TypeParameterSpec[] constraints = null;
+			TypeParameterInflator? inflator = null;
+
+			for (int i = 0; i < tparams.Length; ++i) {
+				var tp = tparams[i];
+				if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
+					if (constraints == null) {
+						constraints = new TypeParameterSpec[tparams.Length];
+						Array.Copy (tparams, constraints, constraints.Length);
+					}
+
+					//
+					// Using a factory to avoid possibly expensive inflator build up
+					//
+					if (inflator == null)
+						inflator = inflatorFactory (arg);
+
+					constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
+				}
+			}
+
+			if (constraints == null)
+				constraints = tparams;
+
+			return constraints;
+		}
+
+		public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
+		{
+			tps.BaseType = inflator.Inflate (BaseType);
+
+			var defined = InterfacesDefined;
+			if (defined != null) {
+				tps.ifaces_defined = new TypeSpec[defined.Length];
+				for (int i = 0; i < defined.Length; ++i)
+					tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
+			} else if (ifaces_defined == TypeSpec.EmptyTypes) {
+				tps.ifaces_defined = TypeSpec.EmptyTypes;
+			}
+
+			var ifaces = Interfaces;
+			if (ifaces != null) {
+				tps.ifaces = new List<TypeSpec> (ifaces.Count);
+				for (int i = 0; i < ifaces.Count; ++i)
+					tps.ifaces.Add (inflator.Inflate (ifaces[i]));
+				tps.state |= StateFlags.InterfacesExpanded;
+			}
+
+			if (targs != null) {
+				tps.targs = new TypeSpec[targs.Length];
+				for (int i = 0; i < targs.Length; ++i)
+					tps.targs[i] = inflator.Inflate (targs[i]);
+			}
+		}
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var tps = (TypeParameterSpec) MemberwiseClone ();
+#if DEBUG
+			tps.ID += 1000000;
+#endif
+
+			InflateConstraints (inflator, tps);
+			return tps;
+		}
+
+		//
+		// Populates type parameter members using type parameter constraints
+		// The trick here is to be called late enough but not too late to
+		// populate member cache with all members from other types
+		//
+		protected override void InitializeMemberCache (bool onlyTypes)
+		{
+			cache = new MemberCache ();
+
+			//
+			// For a type parameter the membercache is the union of the sets of members of the types
+			// specified as a primary constraint or secondary constraint
+			//
+			if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
+				cache.AddBaseType (BaseType);
+
+			if (InterfacesDefined != null) {
+				foreach (var iface_type in InterfacesDefined) {
+					cache.AddInterface (iface_type);
+				}
+			}
+
+			if (targs != null) {
+				foreach (var ta in targs) {
+					var tps = ta as TypeParameterSpec;
+					IList<TypeSpec> ifaces;
+					if (tps != null) {
+						var b_type = tps.GetEffectiveBase ();
+						if (b_type != null && b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
+							cache.AddBaseType (b_type);
+
+						ifaces = tps.InterfacesDefined;
+					} else {
+						ifaces = ta.Interfaces;
+					}
+
+					if (ifaces != null) {
+						foreach (var iface_type in ifaces) {
+							cache.AddInterface (iface_type);
+						}
+					}
+				}
+			}
+		}
+
+		public bool IsConvertibleToInterface (TypeSpec iface)
+		{
+			if (Interfaces != null) {
+				foreach (var t in Interfaces) {
+					if (t == iface)
+						return true;
+				}
+			}
+
+			if (TypeArguments != null) {
+				foreach (var t in TypeArguments) {
+					var tps = t as TypeParameterSpec;
+					if (tps != null) {
+						if (tps.IsConvertibleToInterface (iface))
+							return true;
+
+						continue;
+					}
+
+					if (t.ImplementsInterface (iface, false))
+						return true;
+				}
+			}
+
+			return false;
+		}
+
+		public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
+		{
+			var tps = md.TypeParameters;
+			for (int i = 0; i < md.TypeParametersCount; ++i) {
+				if (tps[i].HasAnyTypeConstraint) {
+					return true;
+				}
+			}
+
+			return false;
+		}
+
+		public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
+		{
+			var tps = md.TypeParameters;
+			for (int i = 0; i < md.TypeParametersCount; ++i) {
+				if (tps[i].IsConstrained) {
+					return true;
+				}
+			}
+
+			return false;
+		}
+
+		public bool HasDependencyOn (TypeSpec type)
+		{
+			if (TypeArguments != null) {
+				foreach (var targ in TypeArguments) {
+					if (TypeSpecComparer.Override.IsEqual (targ, type))
+						return true;
+
+					var tps = targ as TypeParameterSpec;
+					if (tps != null && tps.HasDependencyOn (type))
+						return true;
+				}
+			}
+
+			return false;
+		}
+
+		public override TypeSpec Mutate (TypeParameterMutator mutator)
+		{
+			return mutator.Mutate (this);
+		}
+	}
+
+	public struct TypeParameterInflator
+	{
+		readonly TypeSpec type;
+		readonly TypeParameterSpec[] tparams;
+		readonly TypeSpec[] targs;
+		readonly IModuleContext context;
+
+		public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
+			: this (nested.context, type, nested.tparams, nested.targs)
+		{
+		}
+
+		public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
+		{
+			if (tparams.Length != targs.Length)
+				throw new ArgumentException ("Invalid arguments");
+
+			this.context = context;
+			this.tparams = tparams;
+			this.targs = targs;
+			this.type = type;
+		}
+
+		#region Properties
+
+		public IModuleContext Context {
+			get {
+				return context;
+			}
+		}
+
+		public TypeSpec TypeInstance {
+			get {
+				return type;
+			}
+		}
+
+		//
+		// Type parameters to inflate
+		//
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				return tparams;
+			}
+		}
+
+		#endregion
+
+		public TypeSpec Inflate (TypeSpec type)
+		{
+			var tp = type as TypeParameterSpec;
+			if (tp != null)
+				return Inflate (tp);
+
+			var ec = type as ElementTypeSpec;
+			if (ec != null) {
+				var et = Inflate (ec.Element);
+				if (et != ec.Element) {
+					var ac = ec as ArrayContainer;
+					if (ac != null)
+						return ArrayContainer.MakeType (context.Module, et, ac.Rank);
+
+					if (ec is PointerContainer)
+						return PointerContainer.MakeType (context.Module, et);
+
+					throw new NotImplementedException ();
+				}
+
+				return ec;
+			}
+
+			if (type.Kind == MemberKind.MissingType)
+				return type;
+
+			//
+			// When inflating a nested type, inflate its parent first
+			// in case it's using same type parameters (was inflated within the type)
+			//
+			TypeSpec[] targs;
+			int i = 0;
+			if (type.IsNested) {
+				var parent = Inflate (type.DeclaringType);
+
+				//
+				// Keep the inflated type arguments
+				// 
+				targs = type.TypeArguments;
+
+				//
+				// When inflating imported nested type used inside same declaring type, we get TypeSpec
+				// because the import cache helps us to catch it. However, that means we have to look at
+				// type definition to get type argument (they are in fact type parameter in this case)
+				//
+				if (targs.Length == 0 && type.Arity > 0)
+					targs = type.MemberDefinition.TypeParameters;
+
+				//
+				// Parent was inflated, find the same type on inflated type
+				// to use same cache for nested types on same generic parent
+				//
+				type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
+
+				//
+				// Handle the tricky case where parent shares local type arguments
+				// which means inflating inflated type
+				//
+				// class Test<T> {
+				//		public static Nested<T> Foo () { return null; }
+				//
+				//		public class Nested<U> {}
+				//	}
+				//
+				//  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
+				//
+				if (targs.Length > 0) {
+					var inflated_targs = new TypeSpec[targs.Length];
+					for (; i < targs.Length; ++i)
+						inflated_targs[i] = Inflate (targs[i]);
+
+					type = type.MakeGenericType (context, inflated_targs);
+				}
+
+				return type;
+			}
+
+			// Nothing to do for non-generic type
+			if (type.Arity == 0)
+				return type;
+
+			targs = new TypeSpec[type.Arity];
+
+			//
+			// Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
+			//
+			if (type is InflatedTypeSpec) {
+				for (; i < targs.Length; ++i)
+					targs[i] = Inflate (type.TypeArguments[i]);
+
+				type = type.GetDefinition ();
+			} else {
+				//
+				// Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
+				//
+				var args = type.MemberDefinition.TypeParameters;
+				foreach (var ds_tp in args)
+					targs[i++] = Inflate (ds_tp);
+			}
+
+			return type.MakeGenericType (context, targs);
+		}
+
+		public TypeSpec Inflate (TypeParameterSpec tp)
+		{
+			for (int i = 0; i < tparams.Length; ++i)
+				if (tparams [i] == tp)
+					return targs[i];
+
+			// This can happen when inflating nested types
+			// without type arguments specified
+			return tp;
+		}
+	}
+
+	//
+	// Before emitting any code we have to change all MVAR references to VAR
+	// when the method is of generic type and has hoisted variables
+	//
+	public class TypeParameterMutator
+	{
+		readonly TypeParameters mvar;
+		readonly TypeParameters var;
+		readonly TypeParameterSpec[] src;
+		Dictionary<TypeSpec, TypeSpec> mutated_typespec;
+
+		public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
+		{
+			if (mvar.Count != var.Count)
+				throw new ArgumentException ();
+
+			this.mvar = mvar;
+			this.var = var;
+		}
+
+		public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
+		{
+			if (srcVar.Length != destVar.Count)
+				throw new ArgumentException ();
+
+			this.src = srcVar;
+			this.var = destVar;
+		}
+
+		#region Properties
+
+		public TypeParameters MethodTypeParameters {
+			get {
+				return mvar;
+			}
+		}
+
+		#endregion
+
+		public static TypeSpec GetMemberDeclaringType (TypeSpec type)
+		{
+			if (type is InflatedTypeSpec) {
+				if (type.DeclaringType == null)
+					return type.GetDefinition ();
+
+				var parent = GetMemberDeclaringType (type.DeclaringType);
+				type = MemberCache.GetMember<TypeSpec> (parent, type);
+			}
+
+			return type;
+		}
+
+		public TypeSpec Mutate (TypeSpec ts)
+		{
+			TypeSpec value;
+			if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
+				return value;
+
+			value = ts.Mutate (this);
+			if (mutated_typespec == null)
+				mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
+
+			mutated_typespec.Add (ts, value);
+			return value;
+		}
+
+		public TypeParameterSpec Mutate (TypeParameterSpec tp)
+		{
+			if (mvar != null) {
+				for (int i = 0; i < mvar.Count; ++i) {
+					if (mvar[i].Type == tp)
+						return var[i].Type;
+				}
+			} else {
+				for (int i = 0; i < src.Length; ++i) {
+					if (src[i] == tp)
+						return var[i].Type;
+				}
+			}
+
+			return tp;
+		}
+
+		public TypeSpec[] Mutate (TypeSpec[] targs)
+		{
+			TypeSpec[] mutated = new TypeSpec[targs.Length];
+			bool changed = false;
+			for (int i = 0; i < targs.Length; ++i) {
+				mutated[i] = Mutate (targs[i]);
+				changed |= targs[i] != mutated[i];
+			}
+
+			return changed ? mutated : targs;
+		}
+	}
+
+	/// <summary>
+	///   A TypeExpr which already resolved to a type parameter.
+	/// </summary>
+	public class TypeParameterExpr : TypeExpression
+	{
+		public TypeParameterExpr (TypeParameter type_parameter, Location loc)
+			: base (type_parameter.Type, loc)
+		{
+			this.eclass = ExprClass.TypeParameter;
+		}
+	}
+
+	public class InflatedTypeSpec : TypeSpec
+	{
+		TypeSpec[] targs;
+		TypeParameterSpec[] constraints;
+		readonly TypeSpec open_type;
+		readonly IModuleContext context;
+
+		public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
+			: base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
+		{
+			if (targs == null)
+				throw new ArgumentNullException ("targs");
+
+			this.state &= ~SharedStateFlags;
+			this.state |= (openType.state & SharedStateFlags);
+
+			this.context = context;
+			this.open_type = openType;
+			this.targs = targs;
+
+			foreach (var arg in targs) {
+				if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					state |= StateFlags.HasDynamicElement;
+					break;
+				}
+			}
+
+			if (open_type.Kind == MemberKind.MissingType)
+				MemberCache = MemberCache.Empty;
+
+			if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
+				state |= StateFlags.ConstraintsChecked;
+		}
+
+		#region Properties
+
+		public override TypeSpec BaseType {
+			get {
+				if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
+					InitializeMemberCache (true);
+
+				return base.BaseType;
+			}
+		}
+
+		//
+		// Inflated type parameters with constraints array, mapping with type arguments is based on index
+		//
+		public TypeParameterSpec[] Constraints {
+			get {
+				if (constraints == null) {
+					constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
+				}
+
+				return constraints;
+			}
+		}
+
+		//
+		// Used to cache expensive constraints validation on constructed types
+		//
+		public bool HasConstraintsChecked {
+			get {
+				return (state & StateFlags.ConstraintsChecked) != 0;
+			}
+			set {
+				state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
+			}
+		}
+
+		public override IList<TypeSpec> Interfaces {
+			get {
+				if (cache == null)
+					InitializeMemberCache (true);
+
+				return base.Interfaces;
+			}
+		}
+
+		public override bool IsExpressionTreeType {
+			get {
+				return (open_type.state & StateFlags.InflatedExpressionType) != 0;
+			}
+		}
+
+		public override bool IsArrayGenericInterface {
+			get {
+				return (open_type.state & StateFlags.GenericIterateInterface) != 0;
+			}
+		}
+
+		public override bool IsGenericTask {
+			get {
+				return (open_type.state & StateFlags.GenericTask) != 0;
+			}
+		}
+
+		public override bool IsNullableType {
+			get {
+				return (open_type.state & StateFlags.InflatedNullableType) != 0;
+			}
+		}
+
+		//
+		// Types used to inflate the generic  type
+		//
+		public override TypeSpec[] TypeArguments {
+			get {
+				return targs;
+			}
+		}
+
+		#endregion
+
+		public override bool AddInterface (TypeSpec iface)
+		{
+			var inflator = CreateLocalInflator (context);
+			iface = inflator.Inflate (iface);
+			if (iface == null)
+				return false;
+
+			return base.AddInterface (iface);
+		}
+
+		public static bool ContainsTypeParameter (TypeSpec type)
+		{
+			if (type.Kind == MemberKind.TypeParameter)
+				return true;
+
+			var element_container = type as ElementTypeSpec;
+			if (element_container != null)
+				return ContainsTypeParameter (element_container.Element);
+
+			foreach (var t in type.TypeArguments) {
+				if (ContainsTypeParameter (t)) {
+					return true;
+				}
+			}
+
+			return false;
+		}
+
+		public TypeParameterInflator CreateLocalInflator (IModuleContext context)
+		{
+			TypeParameterSpec[] tparams_full;
+			TypeSpec[] targs_full = targs;
+			if (IsNested) {
+				//
+				// Special case is needed when we are inflating an open type (nested type definition)
+				// on inflated parent. Consider following case
+				//
+				// Foo<T>.Bar<U> => Foo<string>.Bar<U>
+				//
+				// Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
+				//
+				List<TypeSpec> merged_targs = null;
+				List<TypeParameterSpec> merged_tparams = null;
+
+				var type = DeclaringType;
+
+				do {
+					if (type.TypeArguments.Length > 0) {
+						if (merged_targs == null) {
+							merged_targs = new List<TypeSpec> ();
+							merged_tparams = new List<TypeParameterSpec> ();
+							if (targs.Length > 0) {
+								merged_targs.AddRange (targs);
+								merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
+							}
+						}
+						merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
+						merged_targs.AddRange (type.TypeArguments);
+					}
+					type = type.DeclaringType;
+				} while (type != null);
+
+				if (merged_targs != null) {
+					// Type arguments are not in the right order but it should not matter in this case
+					targs_full = merged_targs.ToArray ();
+					tparams_full = merged_tparams.ToArray ();
+				} else if (targs.Length == 0) {
+					tparams_full = TypeParameterSpec.EmptyTypes;
+				} else {
+					tparams_full = open_type.MemberDefinition.TypeParameters;
+				}
+			} else if (targs.Length == 0) {
+				tparams_full = TypeParameterSpec.EmptyTypes;
+			} else {
+				tparams_full = open_type.MemberDefinition.TypeParameters;
+			}
+
+			return new TypeParameterInflator (context, this, tparams_full, targs_full);
+		}
+
+		MetaType CreateMetaInfo ()
+		{
+			//
+			// Converts nested type arguments into right order
+			// Foo<string, bool>.Bar<int> => string, bool, int
+			//
+			var all = new List<MetaType> ();
+			TypeSpec type = this;
+			TypeSpec definition = type;
+			do {
+				if (type.GetDefinition().IsGeneric) {
+					all.InsertRange (0,
+						type.TypeArguments != TypeSpec.EmptyTypes ?
+						type.TypeArguments.Select (l => l.GetMetaInfo ()) :
+						type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
+				}
+
+				definition = definition.GetDefinition ();
+				type = type.DeclaringType;
+			} while (type != null);
+
+			return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
+		}
+
+		public override ObsoleteAttribute GetAttributeObsolete ()
+		{
+			return open_type.GetAttributeObsolete ();
+		}
+
+		protected override bool IsNotCLSCompliant (out bool attrValue)
+		{
+			if (base.IsNotCLSCompliant (out attrValue))
+				return true;
+
+			foreach (var ta in TypeArguments) {
+				if (ta.MemberDefinition.CLSAttributeValue == false)
+					return true;
+			}
+
+			return false;
+		}
+
+		public override TypeSpec GetDefinition ()
+		{
+			return open_type;
+		}
+
+		public override MetaType GetMetaInfo ()
+		{
+			if (info == null)
+				info = CreateMetaInfo ();
+
+			return info;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			if (IsNullableType)
+				return targs[0].GetSignatureForError () + "?";
+
+			return base.GetSignatureForError ();
+		}
+
+		protected override string GetTypeNameSignature ()
+		{
+			if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
+				return null;
+
+			return "<" + TypeManager.CSharpName (targs) + ">";
+		}
+
+		public bool HasDynamicArgument ()
+		{
+			for (int i = 0; i < targs.Length; ++i) {
+				var item = targs[i];
+
+				if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					return true;
+
+				if (item is InflatedTypeSpec) {
+					if (((InflatedTypeSpec) item).HasDynamicArgument ())
+						return true;
+
+					continue;
+				}
+
+				if (item.IsArray) {
+					while (item.IsArray) {
+						item = ((ArrayContainer) item).Element;
+					}
+
+					if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+						return true;
+				}
+			}
+
+			return false;
+		}
+
+		protected override void InitializeMemberCache (bool onlyTypes)
+		{
+			if (cache == null) {
+				var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
+
+				// Surprisingly, calling MemberCache on open type could meantime create cache on this type
+				// for imported type parameter constraints referencing nested type of this declaration
+				if (cache == null)
+					cache = new MemberCache (open_cache);
+			}
+
+			var inflator = CreateLocalInflator (context);
+
+			//
+			// Two stage inflate due to possible nested types recursive
+			// references
+			//
+			// class A<T> {
+			//    B b;
+			//    class B {
+			//      T Value;
+			//    }
+			// }
+			//
+			// When resolving type of `b' members of `B' cannot be 
+			// inflated because are not yet available in membercache
+			//
+			if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
+				open_type.MemberCacheTypes.InflateTypes (cache, inflator);
+
+				//
+				// Inflate any implemented interfaces
+				//
+				if (open_type.Interfaces != null) {
+					ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
+					foreach (var iface in open_type.Interfaces) {
+						var iface_inflated = inflator.Inflate (iface);
+						if (iface_inflated == null)
+							continue;
+
+						base.AddInterface (iface_inflated);
+					}
+				}
+
+				//
+				// Handles the tricky case of recursive nested base generic type
+				//
+				// class A<T> : Base<A<T>.Nested> {
+				//    class Nested {}
+				// }
+				//
+				// When inflating A<T>. base type is not yet known, secondary
+				// inflation is required (not common case) once base scope
+				// is known
+				//
+				if (open_type.BaseType == null) {
+					if (IsClass)
+						state |= StateFlags.PendingBaseTypeInflate;
+				} else {
+					BaseType = inflator.Inflate (open_type.BaseType);
+				}
+			} else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
+				//
+				// It can happen when resolving base type without being defined
+				// which is not allowed to happen and will always lead to an error
+				//
+				// class B { class N {} }
+				// class A<T> : A<B.N> {}
+				//
+				if (open_type.BaseType == null)
+					return;
+
+				BaseType = inflator.Inflate (open_type.BaseType);
+				state &= ~StateFlags.PendingBaseTypeInflate;
+			}
+
+			if (onlyTypes) {
+				state |= StateFlags.PendingMemberCacheMembers;
+				return;
+			}
+
+			var tc = open_type.MemberDefinition as TypeDefinition;
+			if (tc != null && !tc.HasMembersDefined) {
+				//
+				// Inflating MemberCache with undefined members
+				//
+				return;
+			}
+
+			if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
+				BaseType = inflator.Inflate (open_type.BaseType);
+				state &= ~StateFlags.PendingBaseTypeInflate;
+			}
+
+			state &= ~StateFlags.PendingMemberCacheMembers;
+			open_type.MemberCache.InflateMembers (cache, open_type, inflator);
+		}
+
+		public override TypeSpec Mutate (TypeParameterMutator mutator)
+		{
+			var targs = TypeArguments;
+			if (targs != null)
+				targs = mutator.Mutate (targs);
+
+			var decl = DeclaringType;
+			if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
+				decl = mutator.Mutate (decl);
+
+			if (targs == TypeArguments && decl == DeclaringType)
+				return this;
+
+			var mutated = (InflatedTypeSpec) MemberwiseClone ();
+			if (decl != DeclaringType) {
+				// Gets back MethodInfo in case of metaInfo was inflated
+				//mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
+
+				mutated.declaringType = decl;
+				mutated.state |= StateFlags.PendingMetaInflate;
+			}
+
+			if (targs != null) {
+				mutated.targs = targs;
+				mutated.info = null;
+			}
+
+			return mutated;
+		}
+	}
+
+
+	//
+	// Tracks the type arguments when instantiating a generic type. It's used
+	// by both type arguments and type parameters
+	//
+	public class TypeArguments
+	{
+		List<FullNamedExpression> args;
+		TypeSpec[] atypes;
+
+		public List<FullNamedExpression> Args {
+			get { return this.args; }
+		}
+
+		public TypeArguments (params FullNamedExpression[] types)
+		{
+			this.args = new List<FullNamedExpression> (types);
+		}
+
+		public void Add (FullNamedExpression type)
+		{
+			args.Add (type);
+		}
+
+		/// <summary>
+		///   We may only be used after Resolve() is called and return the fully
+		///   resolved types.
+		/// </summary>
+		// TODO: Not needed, just return type from resolve
+		public TypeSpec[] Arguments {
+			get {
+				return atypes;
+			}
+			set {
+				atypes = value;
+			}
+		}
+
+		public int Count {
+			get {
+				return args.Count;
+			}
+		}
+
+		public virtual bool IsEmpty {
+			get {
+				return false;
+			}
+		}
+
+		public List<FullNamedExpression> TypeExpressions {
+			get {
+				return this.args;
+ 			}
+		}
+
+		public string GetSignatureForError()
+		{
+			StringBuilder sb = new StringBuilder ();
+			for (int i = 0; i < Count; ++i) {
+				var expr = args[i];
+				if (expr != null)
+					sb.Append (expr.GetSignatureForError ());
+
+				if (i + 1 < Count)
+					sb.Append (',');
+			}
+
+			return sb.ToString ();
+		}
+
+		/// <summary>
+		///   Resolve the type arguments.
+		/// </summary>
+		public virtual bool Resolve (IMemberContext ec)
+		{
+			if (atypes != null)
+			    return true;
+
+			int count = args.Count;
+			bool ok = true;
+
+			atypes = new TypeSpec [count];
+
+			var errors = ec.Module.Compiler.Report.Errors;
+
+			for (int i = 0; i < count; i++){
+				var te = args[i].ResolveAsType (ec);
+				if (te == null) {
+					ok = false;
+					continue;
+				}
+
+				atypes[i] = te;
+
+				if (te.IsStatic) {
+					ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
+						te.GetSignatureForError ());
+					ok = false;
+				}
+
+				if (te.IsPointer || te.IsSpecialRuntimeType) {
+					ec.Module.Compiler.Report.Error (306, args[i].Location,
+						"The type `{0}' may not be used as a type argument",
+						te.GetSignatureForError ());
+					ok = false;
+				}
+			}
+
+			if (!ok || errors != ec.Module.Compiler.Report.Errors)
+				atypes = null;
+
+			return ok;
+		}
+
+		public TypeArguments Clone ()
+		{
+			TypeArguments copy = new TypeArguments ();
+			foreach (var ta in args)
+				copy.args.Add (ta);
+
+			return copy;
+		}
+	}
+
+	public class UnboundTypeArguments : TypeArguments
+	{
+		public UnboundTypeArguments (int arity)
+			: base (new FullNamedExpression[arity])
+		{
+		}
+
+		public override bool IsEmpty {
+			get {
+				return true;
+			}
+		}
+
+		public override bool Resolve (IMemberContext ec)
+		{
+			// Nothing to be resolved
+			return true;
+		}
+	}
+
+	public class TypeParameters
+	{
+		List<TypeParameter> names;
+		TypeParameterSpec[] types;
+
+		public TypeParameters ()
+		{
+			names = new List<TypeParameter> ();
+		}
+
+		public TypeParameters (int count)
+		{
+			names = new List<TypeParameter> (count);
+		}
+
+		#region Properties
+
+		public int Count {
+			get {
+				return names.Count;
+			}
+		}
+
+		public TypeParameterSpec[] Types {
+			get {
+				return types;
+			}
+		}
+
+		#endregion
+
+		public void Add (TypeParameter tparam)
+		{
+			names.Add (tparam);
+		}
+
+		public void Add (TypeParameters tparams)
+		{
+			names.AddRange (tparams.names);
+		}
+
+		public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
+		{
+			types = new TypeParameterSpec[Count];
+			for (int i = 0; i < types.Length; ++i) {
+				var tp = names[i];
+
+				tp.Create (declaringType, parent);
+				types[i] = tp.Type;
+				types[i].DeclaredPosition = i + parentOffset;
+
+				if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
+					parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
+				}
+			}
+		}
+
+		public void Define (GenericTypeParameterBuilder[] builders)
+		{
+			for (int i = 0; i < types.Length; ++i) {
+				var tp = names[i];
+				tp.Define (builders [types [i].DeclaredPosition]);
+			}
+		}
+
+		public TypeParameter this[int index] {
+			get {
+				return names [index];
+			}
+			set {
+				names[index] = value;
+			}
+		}
+
+		public TypeParameter Find (string name)
+		{
+			foreach (var tp in names) {
+				if (tp.Name == name)
+					return tp;
+			}
+
+			return null;
+		}
+
+		public string[] GetAllNames ()
+		{
+			return names.Select (l => l.Name).ToArray ();
+		}
+
+		public string GetSignatureForError ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			for (int i = 0; i < Count; ++i) {
+				if (i > 0)
+					sb.Append (',');
+
+				var name = names[i];
+				if (name != null)
+					sb.Append (name.GetSignatureForError ());
+			}
+
+			return sb.ToString ();
+		}
+
+
+		public void CheckPartialConstraints (Method part)
+		{
+			var partTypeParameters = part.CurrentTypeParameters;
+
+			for (int i = 0; i < Count; i++) {
+				var tp_a = names[i];
+				var tp_b = partTypeParameters [i];
+				if (tp_a.Constraints == null) {
+					if (tp_b.Constraints == null)
+						continue;
+				} else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
+					continue;
+				}
+
+				part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
+				part.Compiler.Report.Error (761, part.Location,
+					"Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
+					part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
+			}
+		}
+
+		public void UpdateConstraints (TypeDefinition part)
+		{
+			var partTypeParameters = part.MemberName.TypeParameters;
+
+			for (int i = 0; i < Count; i++) {
+				var tp = names [i];
+				if (tp.AddPartialConstraints (part, partTypeParameters [i]))
+					continue;
+
+				part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
+				part.Compiler.Report.Error (265, part.Location,
+					"Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
+					part.GetSignatureForError (), tp.GetSignatureForError ());
+			}
+		}
+
+		public void VerifyClsCompliance ()
+		{
+			foreach (var tp in names) {
+				tp.VerifyClsCompliance ();
+			}
+		}
+	}
+
+	//
+	// A type expression of generic type with type arguments
+	//
+	class GenericTypeExpr : TypeExpr
+	{
+		TypeArguments args;
+		TypeSpec open_type;
+
+		/// <summary>
+		///   Instantiate the generic type `t' with the type arguments `args'.
+		///   Use this constructor if you already know the fully resolved
+		///   generic type.
+		/// </summary>		
+		public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
+		{
+			this.open_type = open_type;
+			loc = l;
+			this.args = args;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return type.GetSignatureForError ();
+		}
+
+		public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false)
+		{
+			if (eclass != ExprClass.Unresolved)
+				return type;
+
+			if (!args.Resolve (mc))
+				return null;
+
+			TypeSpec[] atypes = args.Arguments;
+			if (atypes == null)
+				return null;
+
+			//
+			// Now bind the parameters
+			//
+			var inflated = open_type.MakeGenericType (mc, atypes);
+			type = inflated;
+			eclass = ExprClass.Type;
+
+			//
+			// The constraints can be checked only when full type hierarchy is known
+			//
+			if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
+				var constraints = inflated.Constraints;
+				if (constraints != null) {
+					var cc = new ConstraintChecker (mc);
+					if (cc.CheckAll (open_type, atypes, constraints, loc)) {
+						inflated.HasConstraintsChecked = true;
+					}
+				}
+			}
+
+			return type;
+		}
+
+		public override bool Equals (object obj)
+		{
+			GenericTypeExpr cobj = obj as GenericTypeExpr;
+			if (cobj == null)
+				return false;
+
+			if ((type == null) || (cobj.type == null))
+				return false;
+
+			return type == cobj.type;
+		}
+
+		public override int GetHashCode ()
+		{
+			return base.GetHashCode ();
+		}
+	}
+
+	//
+	// Generic type with unbound type arguments, used for typeof (G<,,>)
+	//
+	class GenericOpenTypeExpr : TypeExpression
+	{
+		public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
+			: base (type.GetDefinition (), loc)
+		{
+		}
+	}
+
+	struct ConstraintChecker
+	{
+		IMemberContext mc;
+		bool recursive_checks;
+
+		public ConstraintChecker (IMemberContext ctx)
+		{
+			this.mc = ctx;
+			recursive_checks = false;
+		}
+
+		//
+		// Checks the constraints of open generic type against type
+		// arguments. This version is used for types which could not be
+		// checked immediatelly during construction because the type
+		// hierarchy was not yet fully setup (before Emit phase)
+		//
+		public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
+		{
+			//
+			// Check declaring type first if there is any
+			//
+			if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
+				return false;
+
+			while (type is ElementTypeSpec)
+				type = ((ElementTypeSpec) type).Element;
+
+			if (type.Arity == 0)
+				return true;
+
+			var gtype = type as InflatedTypeSpec;
+			if (gtype == null)
+				return true;
+
+			var constraints = gtype.Constraints;
+			if (constraints == null)
+				return true;
+
+			if (gtype.HasConstraintsChecked)
+				return true;
+
+			var cc = new ConstraintChecker (mc);
+			cc.recursive_checks = true;
+
+			if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
+				gtype.HasConstraintsChecked = true;
+				return true;
+			}
+
+			return false;
+		}
+
+		//
+		// Checks all type arguments againts type parameters constraints
+		// NOTE: It can run in probing mode when `this.mc' is null
+		//
+		public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
+		{
+			for (int i = 0; i < tparams.Length; i++) {
+				var targ = targs[i];
+				if (!CheckConstraint (context, targ, tparams [i], loc))
+					return false;
+
+				if (!recursive_checks)
+					continue;
+
+				if (!Check (mc, targ, loc))
+					return false;
+			}
+
+			return true;
+		}
+
+		bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
+		{
+			//
+			// First, check the `class' and `struct' constraints.
+			//
+			if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
+				if (mc != null) {
+					mc.Module.Compiler.Report.Error (452, loc,
+						"The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
+						atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
+				}
+
+				return false;
+			}
+
+			if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
+				if (mc != null) {
+					mc.Module.Compiler.Report.Error (453, loc,
+						"The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
+						atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
+				}
+
+				return false;
+			}
+
+			bool ok = true;
+
+			//
+			// Check the class constraint
+			//
+			if (tparam.HasTypeConstraint) {
+				if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
+					if (mc == null)
+						return false;
+
+					ok = false;
+				}
+			}
+
+			//
+			// Check the interfaces constraints
+			//
+			if (tparam.InterfacesDefined != null) {
+				foreach (TypeSpec iface in tparam.InterfacesDefined) {
+					if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
+						if (mc == null)
+							return false;
+
+						ok = false;
+						break;
+					}
+				}
+			}
+
+			//
+			// Check the type parameter constraint
+			//
+			if (tparam.TypeArguments != null) {
+				foreach (var ta in tparam.TypeArguments) {
+					if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
+						if (mc == null)
+							return false;
+
+						ok = false;
+						break;
+					}
+				}
+			}
+
+			//
+			// Finally, check the constructor constraint.
+			//
+			if (!tparam.HasSpecialConstructor)
+				return ok;
+
+			if (!HasDefaultConstructor (atype)) {
+				if (mc != null) {
+					mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
+					mc.Module.Compiler.Report.Error (310, loc,
+						"The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
+						atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
+				}
+				return false;
+			}
+
+			return ok;
+		}
+
+		static bool HasDynamicTypeArgument (TypeSpec[] targs)
+		{
+			for (int i = 0; i < targs.Length; ++i) {
+				var targ = targs [i];
+				if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					return true;
+
+				if (HasDynamicTypeArgument (targ.TypeArguments))
+					return true;
+			}
+
+			return false;
+		}
+
+		bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
+		{
+			if (atype == ttype)
+				return true;
+
+			if (atype.IsGenericParameter) {
+				var tps = (TypeParameterSpec) atype;
+				if (tps.HasDependencyOn (ttype))
+					return true;
+
+				if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
+					return true;
+
+			} else if (TypeSpec.IsValueType (atype)) {
+				if (atype.IsNullableType) {
+					//
+					// LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
+					//
+					if (TypeSpec.IsBaseClass (atype, ttype, false))
+						return true;
+				} else {
+					if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
+						return true;
+				}
+			} else {
+				if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
+					return true;
+			}
+
+			if (mc != null) {
+				mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
+				if (atype.IsGenericParameter) {
+					mc.Module.Compiler.Report.Error (314, loc,
+						"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
+						atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+				} else if (TypeSpec.IsValueType (atype)) {
+					if (atype.IsNullableType) {
+						if (ttype.IsInterface) {
+							mc.Module.Compiler.Report.Error (313, loc,
+								"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint `{3}'",
+								atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+						} else {
+							mc.Module.Compiler.Report.Error (312, loc,
+								"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' does not satisfy constraint `{3}'",
+								atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+						}
+					} else {
+						mc.Module.Compiler.Report.Error (315, loc,
+							"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
+							atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+					}
+				} else {
+					mc.Module.Compiler.Report.Error (311, loc,
+						"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
+						atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+				}
+			}
+
+			return false;
+		}
+
+		static bool HasDefaultConstructor (TypeSpec atype)
+		{
+			var tp = atype as TypeParameterSpec;
+			if (tp != null) {
+				return tp.HasSpecialConstructor || tp.HasSpecialStruct;
+			}
+
+			if (atype.IsStruct || atype.IsEnum)
+				return true;
+
+			if (atype.IsAbstract)
+				return false;
+
+			var tdef = atype.GetDefinition ();
+
+			var found = MemberCache.FindMember (tdef,
+				MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
+				BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
+
+			return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
+		}
+	}
+
+	//
+	// Implements C# type inference
+	//
+	class TypeInference
+	{
+		//
+		// Tracks successful rate of type inference
+		//
+		int score = int.MaxValue;
+		readonly Arguments arguments;
+		readonly int arg_count;
+
+		public TypeInference (Arguments arguments)
+		{
+			this.arguments = arguments;
+			if (arguments != null)
+				arg_count = arguments.Count;
+		}
+
+		public int InferenceScore {
+			get {
+				return score;
+			}
+		}
+
+		public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
+		{
+			var method_generic_args = method.GenericDefinition.TypeParameters;
+			TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
+			if (!context.UnfixedVariableExists)
+				return TypeSpec.EmptyTypes;
+
+			AParametersCollection pd = method.Parameters;
+			if (!InferInPhases (ec, context, pd))
+				return null;
+
+			return context.InferredTypeArguments;
+		}
+
+		//
+		// Implements method type arguments inference
+		//
+		bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
+		{
+			int params_arguments_start;
+			if (methodParameters.HasParams) {
+				params_arguments_start = methodParameters.Count - 1;
+			} else {
+				params_arguments_start = arg_count;
+			}
+
+			TypeSpec [] ptypes = methodParameters.Types;
+			
+			//
+			// The first inference phase
+			//
+			TypeSpec method_parameter = null;
+			for (int i = 0; i < arg_count; i++) {
+				Argument a = arguments [i];
+				if (a == null)
+					continue;
+				
+				if (i < params_arguments_start) {
+					method_parameter = methodParameters.Types [i];
+				} else if (i == params_arguments_start) {
+					if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
+						method_parameter = methodParameters.Types [params_arguments_start];
+					else
+						method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
+
+					ptypes = (TypeSpec[]) ptypes.Clone ();
+					ptypes [i] = method_parameter;
+				}
+
+				//
+				// When a lambda expression, an anonymous method
+				// is used an explicit argument type inference takes a place
+				//
+				AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
+				if (am != null) {
+					if (am.ExplicitTypeInference (tic, method_parameter))
+						--score; 
+					continue;
+				}
+
+				if (a.IsByRef) {
+					score -= tic.ExactInference (a.Type, method_parameter);
+					continue;
+				}
+
+				if (a.Expr.Type == InternalType.NullLiteral)
+					continue;
+
+				if (TypeSpec.IsValueType (method_parameter)) {
+					score -= tic.LowerBoundInference (a.Type, method_parameter);
+					continue;
+				}
+
+				//
+				// Otherwise an output type inference is made
+				//
+				score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
+			}
+
+			//
+			// Part of the second phase but because it happens only once
+			// we don't need to call it in cycle
+			//
+			bool fixed_any = false;
+			if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
+				return false;
+
+			return DoSecondPhase (ec, tic, ptypes, !fixed_any);
+		}
+
+		bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
+		{
+			bool fixed_any = false;
+			if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
+				return false;
+
+			// If no further unfixed type variables exist, type inference succeeds
+			if (!tic.UnfixedVariableExists)
+				return true;
+
+			if (!fixed_any && fixDependent)
+				return false;
+			
+			// For all arguments where the corresponding argument output types
+			// contain unfixed type variables but the input types do not,
+			// an output type inference is made
+			for (int i = 0; i < arg_count; i++) {
+				
+				// Align params arguments
+				TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
+				
+				if (!t_i.IsDelegate) {
+					if (!t_i.IsExpressionTreeType)
+						continue;
+
+					t_i = TypeManager.GetTypeArguments (t_i) [0];
+				}
+
+				var mi = Delegate.GetInvokeMethod (t_i);
+				TypeSpec rtype = mi.ReturnType;
+
+				if (tic.IsReturnTypeNonDependent (mi, rtype)) {
+					// It can be null for default arguments
+					if (arguments[i] == null)
+						continue;
+
+					score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
+				}
+			}
+
+
+			return DoSecondPhase (ec, tic, methodParameters, true);
+		}
+	}
+
+	public class TypeInferenceContext
+	{
+		protected enum BoundKind
+		{
+			Exact	= 0,
+			Lower	= 1,
+			Upper	= 2
+		}
+
+		struct BoundInfo : IEquatable<BoundInfo>
+		{
+			public readonly TypeSpec Type;
+			public readonly BoundKind Kind;
+
+			public BoundInfo (TypeSpec type, BoundKind kind)
+			{
+				this.Type = type;
+				this.Kind = kind;
+			}
+			
+			public override int GetHashCode ()
+			{
+				return Type.GetHashCode ();
+			}
+
+			public Expression GetTypeExpression ()
+			{
+				return new TypeExpression (Type, Location.Null);
+			}
+
+			#region IEquatable<BoundInfo> Members
+
+			public bool Equals (BoundInfo other)
+			{
+				return Type == other.Type && Kind == other.Kind;
+			}
+
+			#endregion
+		}
+
+		readonly TypeSpec[] tp_args;
+		readonly TypeSpec[] fixed_types;
+		readonly List<BoundInfo>[] bounds;
+
+		// TODO MemberCache: Could it be TypeParameterSpec[] ??
+		public TypeInferenceContext (TypeSpec[] typeArguments)
+		{
+			if (typeArguments.Length == 0)
+				throw new ArgumentException ("Empty generic arguments");
+
+			fixed_types = new TypeSpec [typeArguments.Length];
+			for (int i = 0; i < typeArguments.Length; ++i) {
+				if (typeArguments [i].IsGenericParameter) {
+					if (bounds == null) {
+						bounds = new List<BoundInfo> [typeArguments.Length];
+						tp_args = new TypeSpec [typeArguments.Length];
+					}
+					tp_args [i] = typeArguments [i];
+				} else {
+					fixed_types [i] = typeArguments [i];
+				}
+			}
+		}
+
+		// 
+		// Used together with AddCommonTypeBound fo implement
+		// 7.4.2.13 Finding the best common type of a set of expressions
+		//
+		public TypeInferenceContext ()
+		{
+			fixed_types = new TypeSpec [1];
+			tp_args = new TypeSpec [1];
+			tp_args[0] = InternalType.Arglist; // it can be any internal type
+			bounds = new List<BoundInfo> [1];
+		}
+
+		public TypeSpec[] InferredTypeArguments {
+			get {
+				return fixed_types;
+			}
+		}
+
+		public void AddCommonTypeBound (TypeSpec type)
+		{
+			AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
+		}
+
+		public void AddCommonTypeBoundAsync (TypeSpec type)
+		{
+			AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
+		}
+
+		void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
+		{
+			//
+			// Some types cannot be used as type arguments
+			//
+			if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
+				bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
+				return;
+
+			var a = bounds [index];
+			if (a == null) {
+				a = new List<BoundInfo> (2);
+				a.Add (bound);
+				bounds [index] = a;
+				return;
+			}
+
+			if (a.Contains (bound))
+				return;
+
+			a.Add (bound);
+		}
+		
+		bool AllTypesAreFixed (TypeSpec[] types)
+		{
+			foreach (TypeSpec t in types) {
+				if (t.IsGenericParameter) {
+					if (!IsFixed (t))
+						return false;
+					continue;
+				}
+
+				if (TypeManager.IsGenericType (t))
+					return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
+			}
+			
+			return true;
+		}		
+
+		//
+		// 26.3.3.8 Exact Inference
+		//
+		public int ExactInference (TypeSpec u, TypeSpec v)
+		{
+			// If V is an array type
+			if (v.IsArray) {
+				if (!u.IsArray)
+					return 0;
+
+				var ac_u = (ArrayContainer) u;
+				var ac_v = (ArrayContainer) v;
+				if (ac_u.Rank != ac_v.Rank)
+					return 0;
+
+				return ExactInference (ac_u.Element, ac_v.Element);
+			}
+
+			// If V is constructed type and U is constructed type
+			if (TypeManager.IsGenericType (v)) {
+				if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
+					return 0;
+
+				TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
+				TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
+				if (ga_u.Length != ga_v.Length)
+					return 0;
+
+				int score = 0;
+				for (int i = 0; i < ga_u.Length; ++i)
+					score += ExactInference (ga_u [i], ga_v [i]);
+
+				return System.Math.Min (1, score);
+			}
+
+			// If V is one of the unfixed type arguments
+			int pos = IsUnfixed (v);
+			if (pos == -1)
+				return 0;
+
+			AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
+			return 1;
+		}
+
+		public bool FixAllTypes (ResolveContext ec)
+		{
+			for (int i = 0; i < tp_args.Length; ++i) {
+				if (!FixType (ec, i))
+					return false;
+			}
+			return true;
+		}
+
+		//
+		// All unfixed type variables Xi are fixed for which all of the following hold:
+		// a, There is at least one type variable Xj that depends on Xi
+		// b, Xi has a non-empty set of bounds
+		// 
+		public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
+		{
+			for (int i = 0; i < tp_args.Length; ++i) {
+				if (fixed_types[i] != null)
+					continue;
+
+				if (bounds[i] == null)
+					continue;
+
+				if (!FixType (ec, i))
+					return false;
+				
+				fixed_any = true;
+			}
+
+			return true;
+		}
+
+		//
+		// All unfixed type variables Xi which depend on no Xj are fixed
+		//
+		public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
+		{
+			var types_to_fix = new List<TypeSpec> (tp_args);
+			for (int i = 0; i < methodParameters.Length; ++i) {
+				TypeSpec t = methodParameters[i];
+
+				if (!t.IsDelegate) {
+					if (!t.IsExpressionTreeType)
+						continue;
+
+					t =  TypeManager.GetTypeArguments (t) [0];
+				}
+
+				if (t.IsGenericParameter)
+					continue;
+
+				var invoke = Delegate.GetInvokeMethod (t);
+				TypeSpec rtype = invoke.ReturnType;
+				while (rtype.IsArray)
+					rtype = ((ArrayContainer) rtype).Element;
+
+				if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
+					continue;
+
+				// Remove dependent types, they cannot be fixed yet
+				RemoveDependentTypes (types_to_fix, rtype);
+			}
+
+			foreach (TypeSpec t in types_to_fix) {
+				if (t == null)
+					continue;
+
+				int idx = IsUnfixed (t);
+				if (idx >= 0 && !FixType (ec, idx)) {
+					return false;
+				}
+			}
+
+			fixed_any = types_to_fix.Count > 0;
+			return true;
+		}
+
+		//
+		// 26.3.3.10 Fixing
+		//
+		public bool FixType (ResolveContext ec, int i)
+		{
+			// It's already fixed
+			if (fixed_types[i] != null)
+				throw new InternalErrorException ("Type argument has been already fixed");
+
+			var candidates = bounds [i];
+			if (candidates == null)
+				return false;
+
+			if (candidates.Count == 1) {
+				TypeSpec t = candidates[0].Type;
+				if (t == InternalType.NullLiteral)
+					return false;
+
+				fixed_types [i] = t;
+				return true;
+			}
+
+			//
+			// The set of candidate types Uj starts out as the set of
+			// all types in the set of bounds for Xi
+			//
+			var applicable = new bool [candidates.Count];
+			for (int ci = 0; ci < applicable.Length; ++ci)
+				applicable [ci] = true;
+
+			for (int ci = 0; ci < applicable.Length; ++ci) {
+				var bound = candidates [ci];
+				int cii = 0;
+
+				switch (bound.Kind) {
+				case BoundKind.Exact:
+					for (; cii != applicable.Length; ++cii) {
+						if (ci == cii)
+							continue;
+
+						if (!applicable[cii])
+							break;
+
+						//
+						// For each exact bound U of Xi all types Uj which are not identical
+						// to U are removed from the candidate set
+						//
+						if (candidates [cii].Type != bound.Type)
+							applicable[cii] = false;
+					}
+
+					break;
+				case BoundKind.Lower:
+					for (; cii != applicable.Length; ++cii) {
+						if (ci == cii)
+							continue;
+
+						if (!applicable[cii])
+							break;
+
+						//
+						// For each lower bound U of Xi all types Uj to which there is not an implicit conversion
+						// from U are removed from the candidate set
+						//
+						if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
+							applicable[cii] = false;
+						}
+					}
+
+					break;
+
+				case BoundKind.Upper:
+					for (; cii != applicable.Length; ++cii) {
+						if (ci == cii)
+							continue;
+
+						if (!applicable[cii])
+							break;
+
+						//
+						// For each upper bound U of Xi all types Uj from which there is not an implicit conversion
+						// to U are removed from the candidate set
+						//
+						if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
+							applicable[cii] = false;
+					}
+
+					break;
+				}
+			}
+
+			TypeSpec best_candidate = null;
+			for (int ci = 0; ci < applicable.Length; ++ci) {
+				if (!applicable[ci])
+					continue;
+
+				var bound = candidates [ci];
+				if (bound.Type == best_candidate)
+					continue;
+
+				int cii = 0;
+				for (; cii < applicable.Length; ++cii) {
+					if (ci == cii)
+						continue;
+
+					if (!applicable[cii])
+						continue;
+
+					if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
+						break;
+				}
+
+				if (cii != applicable.Length)
+					continue;
+
+				//
+				// We already have the best candidate, break if it's different (non-unique)
+				//
+				// Dynamic is never ambiguous as we prefer dynamic over other best candidate types
+				//
+				if (best_candidate != null) {
+
+					if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+						continue;
+
+					if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
+						return false;
+				}
+
+				best_candidate = bound.Type;
+			}
+
+			if (best_candidate == null)
+				return false;
+
+			fixed_types[i] = best_candidate;
+			return true;
+		}
+
+		public bool HasBounds (int pos)
+		{
+			return bounds[pos] != null;
+		}
+		
+		//
+		// Uses inferred or partially infered types to inflate delegate type argument. Returns
+		// null when type parameter has not been fixed
+		//
+		public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
+		{
+			var tp = parameter as TypeParameterSpec;
+			if (tp != null) {
+				//
+				// Type inference works on generic arguments (MVAR) only
+				//
+				if (!tp.IsMethodOwned)
+					return parameter;
+
+				//
+				// Ensure the type parameter belongs to same container
+				//
+				if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
+					return fixed_types[tp.DeclaredPosition] ?? parameter;
+
+				return parameter;
+			}
+
+			var gt = parameter as InflatedTypeSpec;
+			if (gt != null) {
+				var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
+				for (int ii = 0; ii < inflated_targs.Length; ++ii) {
+					var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
+					if (inflated == null)
+						return null;
+
+					inflated_targs[ii] = inflated;
+				}
+
+				return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
+			}
+
+			var ac = parameter as ArrayContainer;
+			if (ac != null) {
+				var inflated = InflateGenericArgument (context, ac.Element);
+				if (inflated != ac.Element)
+					return ArrayContainer.MakeType (context.Module, inflated);
+			}
+
+			return parameter;
+		}
+		
+		//
+		// Tests whether all delegate input arguments are fixed and generic output type
+		// requires output type inference 
+		//
+		public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
+		{
+			AParametersCollection d_parameters = invoke.Parameters;
+
+			if (d_parameters.IsEmpty)
+				return true;
+
+			while (returnType.IsArray)
+				returnType = ((ArrayContainer) returnType).Element;
+
+			if (returnType.IsGenericParameter) {
+				if (IsFixed (returnType))
+				    return false;
+			} else if (TypeManager.IsGenericType (returnType)) {
+				TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
+				
+				// At least one unfixed return type has to exist 
+				if (AllTypesAreFixed (g_args))
+					return false;
+			} else {
+				return false;
+			}
+
+			// All generic input arguments have to be fixed
+			return AllTypesAreFixed (d_parameters.Types);
+		}
+
+		bool IsFixed (TypeSpec type)
+		{
+			return IsUnfixed (type) == -1;
+		}		
+
+		int IsUnfixed (TypeSpec type)
+		{
+			if (!type.IsGenericParameter)
+				return -1;
+
+			for (int i = 0; i < tp_args.Length; ++i) {
+				if (tp_args[i] == type) {
+					if (fixed_types[i] != null)
+						break;
+
+					return i;
+				}
+			}
+
+			return -1;
+		}
+
+		//
+		// 26.3.3.9 Lower-bound Inference
+		//
+		public int LowerBoundInference (TypeSpec u, TypeSpec v)
+		{
+			return LowerBoundInference (u, v, false);
+		}
+
+		//
+		// Lower-bound (false) or Upper-bound (true) inference based on inversed argument
+		//
+		int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
+		{
+			// If V is one of the unfixed type arguments
+			int pos = IsUnfixed (v);
+			if (pos != -1) {
+				AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
+				return 1;
+			}			
+
+			// If U is an array type
+			var u_ac = u as ArrayContainer;
+			if (u_ac != null) {
+				var v_ac = v as ArrayContainer;
+				if (v_ac != null) {
+					if (u_ac.Rank != v_ac.Rank)
+						return 0;
+
+					if (TypeSpec.IsValueType (u_ac.Element))
+						return ExactInference (u_ac.Element, v_ac.Element);
+
+					return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
+				}
+
+				if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
+					return 0;
+
+				var v_i = TypeManager.GetTypeArguments (v) [0];
+				if (TypeSpec.IsValueType (u_ac.Element))
+					return ExactInference (u_ac.Element, v_i);
+
+				return LowerBoundInference (u_ac.Element, v_i);
+			}
+			
+			if (v.IsGenericOrParentIsGeneric) {
+				//
+				// if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
+				// such that U is identical to, inherits from (directly or indirectly),
+				// or implements (directly or indirectly) C<U1..Uk>
+				//
+				var u_candidates = new List<TypeSpec> ();
+				var open_v = v.MemberDefinition;
+
+				for (TypeSpec t = u; t != null; t = t.BaseType) {
+					if (open_v == t.MemberDefinition)
+						u_candidates.Add (t);
+
+					//
+					// Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
+					// that would complicate the process a lot, instead I treat them as dynamic
+					//
+					if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+						u_candidates.Add (t);
+				}
+
+				if (u.Interfaces != null) {
+					foreach (var iface in u.Interfaces) {
+						if (open_v == iface.MemberDefinition)
+							u_candidates.Add (iface);
+					}
+				}
+
+				TypeSpec[] unique_candidate_targs = null;
+				var ga_v = TypeSpec.GetAllTypeArguments (v);
+				foreach (TypeSpec u_candidate in u_candidates) {
+					//
+					// The unique set of types U1..Uk means that if we have an interface I<T>,
+					// class U : I<int>, I<long> then no type inference is made when inferring
+					// type I<T> by applying type U because T could be int or long
+					//
+					if (unique_candidate_targs != null) {
+						TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
+						if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
+							unique_candidate_targs = second_unique_candidate_targs;
+							continue;
+						}
+
+						//
+						// Break when candidate arguments are ambiguous
+						//
+						return 0;
+					}
+
+					//
+					// A candidate is dynamic type expression, to simplify things use dynamic
+					// for all type parameter of this type. For methods like this one
+					// 
+					// void M<T, U> (IList<T>, IList<U[]>)
+					//
+					// dynamic becomes both T and U when the arguments are of dynamic type
+					//
+					if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+						unique_candidate_targs = new TypeSpec[ga_v.Length];
+						for (int i = 0; i < unique_candidate_targs.Length; ++i)
+							unique_candidate_targs[i] = u_candidate;
+					} else {
+						unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
+					}
+				}
+
+				if (unique_candidate_targs != null) {
+					int score = 0;
+					int tp_index = -1;
+					TypeParameterSpec[] tps = null;
+
+					for (int i = 0; i < unique_candidate_targs.Length; ++i) {
+						if (tp_index < 0) {
+							while (v.Arity == 0)
+								v = v.DeclaringType;
+
+							tps = v.MemberDefinition.TypeParameters;
+							tp_index = tps.Length - 1;
+						}
+
+						Variance variance = tps [tp_index--].Variance;
+
+						TypeSpec u_i = unique_candidate_targs [i];
+						if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
+							if (ExactInference (u_i, ga_v [i]) == 0)
+								++score;
+						} else {
+							bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
+								(variance == Variance.Covariant && inversed);
+
+							if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
+								++score;
+						}
+					}
+
+					return score;
+				}
+			}
+
+			return 0;
+		}
+
+		//
+		// 26.3.3.6 Output Type Inference
+		//
+		public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
+		{
+			// If e is a lambda or anonymous method with inferred return type
+			AnonymousMethodExpression ame = e as AnonymousMethodExpression;
+			if (ame != null) {
+				TypeSpec rt = ame.InferReturnType (ec, this, t);
+				var invoke = Delegate.GetInvokeMethod (t);
+
+				if (rt == null) {
+					AParametersCollection pd = invoke.Parameters;
+					return ame.Parameters.Count == pd.Count ? 1 : 0;
+				}
+
+				TypeSpec rtype = invoke.ReturnType;
+				return LowerBoundInference (rt, rtype) + 1;
+			}
+
+			//
+			// if E is a method group and T is a delegate type or expression tree type
+			// return type Tb with parameter types T1..Tk and return type Tb, and overload
+			// resolution of E with the types T1..Tk yields a single method with return type U,
+			// then a lower-bound inference is made from U for Tb.
+			//
+			if (e is MethodGroupExpr) {
+				if (!t.IsDelegate) {
+					if (!t.IsExpressionTreeType)
+						return 0;
+
+					t = TypeManager.GetTypeArguments (t)[0];
+				}
+
+				var invoke = Delegate.GetInvokeMethod (t);
+				TypeSpec rtype = invoke.ReturnType;
+
+				if (!IsReturnTypeNonDependent (invoke, rtype))
+					return 0;
+
+				// LAMESPEC: Standard does not specify that all methodgroup arguments
+				// has to be fixed but it does not specify how to do recursive type inference
+				// either. We choose the simple option and infer return type only
+				// if all delegate generic arguments are fixed.
+				TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
+				for (int i = 0; i < param_types.Length; ++i) {
+					var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
+					if (inflated == null)
+						return 0;
+
+					param_types[i] = inflated;
+				}
+
+				MethodGroupExpr mg = (MethodGroupExpr) e;
+				Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
+				mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
+				if (mg == null)
+					return 0;
+
+				return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
+			}
+
+			//
+			// if e is an expression with type U, then
+			// a lower-bound inference is made from U for T
+			//
+			return LowerBoundInference (e.Type, t) * 2;
+		}
+
+		void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
+		{
+			int idx = IsUnfixed (returnType);
+			if (idx >= 0) {
+				types [idx] = null;
+				return;
+			}
+
+			if (TypeManager.IsGenericType (returnType)) {
+				foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
+					RemoveDependentTypes (types, t);
+				}
+			}
+		}
+
+		public bool UnfixedVariableExists {
+			get {
+				foreach (TypeSpec ut in fixed_types) {
+					if (ut == null)
+						return true;
+				}
+
+				return false;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/import.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/import.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/import.cs	(revision 11807)
@@ -0,0 +1,2352 @@
+//
+// import.cs: System.Reflection conversions
+//
+// Authors: Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2009-2011 Novell, Inc
+// Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
+//
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Linq;
+using System.Collections.Generic;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	public abstract class MetadataImporter
+	{
+		//
+		// Dynamic types reader with additional logic to reconstruct a dynamic
+		// type using DynamicAttribute values
+		//
+		protected struct DynamicTypeReader
+		{
+			static readonly bool[] single_attribute = { true };
+
+			public int Position;
+			bool[] flags;
+
+			// There is no common type for CustomAttributeData and we cannot
+			// use ICustomAttributeProvider
+			object provider;
+
+			//
+			// A member provider which can be used to get CustomAttributeData
+			//
+			public DynamicTypeReader (object provider)
+			{
+				Position = 0;
+				flags = null;
+				this.provider = provider;
+			}
+
+			//
+			// Returns true when object at local position has dynamic attribute flag
+			//
+			public bool IsDynamicObject ()
+			{
+				if (provider != null)
+					ReadAttribute ();
+
+				return flags != null && Position < flags.Length && flags[Position];
+			}
+
+			//
+			// Returns true when DynamicAttribute exists
+			//
+			public bool HasDynamicAttribute ()
+			{
+				if (provider != null)
+					ReadAttribute ();
+
+				return flags != null;
+			}
+
+			IList<CustomAttributeData> GetCustomAttributes ()
+			{
+				var mi = provider as MemberInfo;
+				if (mi != null)
+					return CustomAttributeData.GetCustomAttributes (mi);
+
+				var pi = provider as ParameterInfo;
+				if (pi != null)
+					return CustomAttributeData.GetCustomAttributes (pi);
+
+				provider = null;
+				return null;
+			}
+
+			void ReadAttribute ()
+			{
+				var cad = GetCustomAttributes ();
+				if (cad == null) {
+					return;
+				}
+
+				if (cad.Count > 0) {
+					foreach (var ca in cad) {
+						var dt = ca.Constructor.DeclaringType;
+						if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
+							continue;
+
+						if (ca.ConstructorArguments.Count == 0) {
+							flags = single_attribute;
+							break;
+						}
+
+						var arg_type = ca.ConstructorArguments[0].ArgumentType;
+
+						if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
+							var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
+							flags = new bool[carg.Count];
+							for (int i = 0; i < flags.Length; ++i) {
+								if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
+									flags[i] = (bool) carg[i].Value;
+							}
+
+							break;
+						}
+					}
+				}
+
+				provider = null;
+			}
+		}
+
+		protected readonly Dictionary<MetaType, TypeSpec> import_cache;
+		protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
+		protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
+		protected readonly ModuleContainer module;
+
+		public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
+
+		protected MetadataImporter (ModuleContainer module)
+		{
+			this.module = module;
+
+			import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
+			compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
+			assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
+			IgnorePrivateMembers = true;
+		}
+
+		#region Properties
+
+		public ICollection<IAssemblyDefinition> Assemblies {
+			get {
+				return assembly_2_definition.Values;
+			}
+		}
+
+		public bool IgnorePrivateMembers { get; set; }
+
+		#endregion
+
+		public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
+		protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
+		protected abstract bool HasVolatileModifier (MetaType[] modifiers);
+
+		public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
+		{
+			Modifiers mod;
+			var fa = fi.Attributes;
+			switch (fa & FieldAttributes.FieldAccessMask) {
+				case FieldAttributes.Public:
+					mod = Modifiers.PUBLIC;
+					break;
+				case FieldAttributes.Assembly:
+					mod = Modifiers.INTERNAL;
+					break;
+				case FieldAttributes.Family:
+					mod = Modifiers.PROTECTED;
+					break;
+				case FieldAttributes.FamORAssem:
+					mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
+					break;
+				default:
+					// Ignore private fields (even for error reporting) to not require extra dependencies
+					if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
+						HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
+						return null;
+
+					mod = Modifiers.PRIVATE;
+					break;
+			}
+
+			TypeSpec field_type;
+
+			try {
+				field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
+
+				//
+				// Private field has private type which is not fixed buffer
+				//
+				if (field_type == null)
+					return null;
+			} catch (Exception e) {
+				// TODO: I should construct fake TypeSpec based on TypeRef signature
+				// but there is no way to do it with System.Reflection
+				throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
+					declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
+			}
+
+			var definition = new ImportedMemberDefinition (fi, field_type, this);
+
+			if ((fa & FieldAttributes.Literal) != 0) {
+				Constant c = field_type.Kind == MemberKind.MissingType ?
+					new NullConstant (InternalType.ErrorType, Location.Null) :
+					Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
+				return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
+			}
+
+			if ((fa & FieldAttributes.InitOnly) != 0) {
+				if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+					var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
+					if (dc != null)
+						return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
+				}
+
+				mod |= Modifiers.READONLY;
+			} else {
+				var req_mod = fi.GetRequiredCustomModifiers ();
+				if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
+					mod |= Modifiers.VOLATILE;
+			}
+
+			if ((fa & FieldAttributes.Static) != 0) {
+				mod |= Modifiers.STATIC;
+			} else {
+				// Fixed buffers cannot be static
+				if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
+					HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
+
+					// TODO: Sanity check on field_type (only few types are allowed)
+					var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
+					return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
+				}
+			}
+
+			return new FieldSpec (declaringType, definition, field_type, fi, mod);
+		}
+
+		public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
+		{
+			add.IsAccessor = true;
+			remove.IsAccessor = true;
+
+			if (add.Modifiers != remove.Modifiers)
+				throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
+
+			var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
+			var definition = new ImportedMemberDefinition (ei, event_type,  this);
+			return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
+		}
+
+		TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
+		{
+			var tparams = type.GetGenericArguments ();
+
+			int parent_owned_count;
+			if (type.IsNested) {
+				parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
+
+				//
+				// System.Reflection duplicates parent type parameters for each
+				// nested type with slightly modified properties (eg. different owner)
+				// This just makes things more complicated (think of cloned constraints)
+				// therefore we remap any nested type owned by parent using `type_cache'
+				// to the single TypeParameterSpec
+				//
+				if (declaringType != null && parent_owned_count > 0) {
+					int read_count = 0;
+					while (read_count != parent_owned_count) {
+						var tparams_count = declaringType.Arity;
+						if (tparams_count != 0) {
+							var parent_tp = declaringType.MemberDefinition.TypeParameters;
+							read_count += tparams_count;
+							for (int i = 0; i < tparams_count; i++) {
+								import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
+							}
+						}
+
+						declaringType = declaringType.DeclaringType;
+					}
+				}			
+			} else {
+				parent_owned_count = 0;
+			}
+
+			if (tparams.Length - parent_owned_count == 0)
+				return null;
+
+			return CreateGenericParameters (parent_owned_count, tparams);
+		}
+
+		TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
+		{
+			var tspec = new TypeParameterSpec[tparams.Length - first];
+			for (int pos = first; pos < tparams.Length; ++pos) {
+				var type = tparams[pos];
+				int index = pos - first;
+
+				tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
+			}
+
+			return tspec;
+		}
+
+		TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
+		{
+			++dtype.Position;
+
+			var tspec = new TypeSpec [tparams.Length - first];
+			for (int pos = first; pos < tparams.Length; ++pos) {
+				var type = tparams[pos];
+				int index = pos - first;
+
+				TypeSpec spec;
+				if (type.HasElementType) {
+					var element = type.GetElementType ();
+					++dtype.Position;
+					spec = ImportType (element, dtype);
+
+					if (!type.IsArray) {
+						throw new NotImplementedException ("Unknown element type " + type.ToString ());
+					}
+
+					spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
+				} else {
+					spec = CreateType (type, dtype, true);
+
+					//
+					// We treat nested generic types as inflated internally where
+					// reflection uses type definition
+					//
+					// class A<T> {
+					//    IFoo<A<T>> foo;	// A<T> is definition in this case
+					// }
+					//
+					if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
+						var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
+						var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
+						spec = spec.MakeGenericType (module, targs);
+					}
+				}
+
+				if (spec == null)
+					return null;
+
+				++dtype.Position;
+				tspec[index] = spec;
+			}
+
+			return tspec;
+		}
+
+		public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
+		{
+			Modifiers mod = ReadMethodModifiers (mb, declaringType);
+			TypeParameterSpec[] tparams;
+
+			var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
+
+			if (mb.IsGenericMethod) {
+				if (!mb.IsGenericMethodDefinition)
+					throw new NotSupportedException ("assert");
+
+				tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
+			} else {
+				tparams = null;
+			}
+
+			MemberKind kind;
+			TypeSpec returnType;
+			if (mb.MemberType == MemberTypes.Constructor) {
+				kind = MemberKind.Constructor;
+				returnType = module.Compiler.BuiltinTypes.Void;
+			} else {
+				//
+				// Detect operators and destructors
+				//
+				string name = mb.Name;
+				kind = MemberKind.Method;
+				if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
+					if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
+						if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
+							var op_type = Operator.GetType (name);
+							if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
+								kind = MemberKind.Operator;
+							}
+						}
+					} else if (parameters.IsEmpty && name == Destructor.MetadataName) {
+						kind = MemberKind.Destructor;
+						if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
+							mod &= ~Modifiers.OVERRIDE;
+							mod |= Modifiers.VIRTUAL;
+						}
+					}
+				}
+
+				var mi = (MethodInfo) mb;
+				returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
+
+				// Cannot set to OVERRIDE without full hierarchy checks
+				// this flag indicates that the method could be override
+				// but further validation is needed
+				if ((mod & Modifiers.OVERRIDE) != 0) {
+					bool is_real_override = false;
+					if (kind == MemberKind.Method && declaringType.BaseType != null) {
+						var btype = declaringType.BaseType;
+						if (IsOverrideMethodBaseTypeAccessible (btype)) {
+							var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
+							var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
+
+							//
+							// For imported class method do additional validation to be sure that metadata
+							// override flag was correct
+							// 
+							// Difference between protected internal and protected is ok
+							//
+							const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
+							if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
+								is_real_override = true;
+							}
+						}
+					}
+
+					if (!is_real_override) {
+						mod &= ~Modifiers.OVERRIDE;
+						if ((mod & Modifiers.SEALED) != 0)
+							mod &= ~Modifiers.SEALED;
+						else
+							mod |= Modifiers.VIRTUAL;
+					}
+				} else if (parameters.HasExtensionMethodType) {
+					mod |= Modifiers.METHOD_EXTENSION;
+				}
+			}
+
+			IMethodDefinition definition;
+			if (tparams != null) {
+				var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
+				foreach (var tp in gmd.TypeParameters) {
+					ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
+				}
+
+				definition = gmd;
+			} else {
+				definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
+			}
+
+			MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
+			if (tparams != null)
+				ms.IsGeneric = true;
+
+			return ms;
+		}
+
+		bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
+		{
+			switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
+			case Modifiers.PUBLIC:
+				return true;
+			case Modifiers.INTERNAL:
+				//
+				// Check whether imported method in base type is accessible from compiled
+				// context
+				//
+				return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
+			case Modifiers.PRIVATE:
+				return false;
+			default:
+				// protected
+				// protected internal
+				// 
+				// Method accessibility checks will be done later based on context
+				// where the method is called (CS0122 error will be reported for inaccessible)
+				//
+				return true;
+			}
+		}
+
+		//
+		// Imports System.Reflection parameters
+		//
+		AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
+		{
+			int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
+
+			if (pi.Length == 0 && varargs == 0)
+				return ParametersCompiled.EmptyReadOnlyParameters;
+
+			TypeSpec[] types = new TypeSpec[pi.Length + varargs];
+			IParameterData[] par = new IParameterData[pi.Length + varargs];
+			bool is_params = false;
+			for (int i = 0; i < pi.Length; i++) {
+				ParameterInfo p = pi[i];
+				Parameter.Modifier mod = 0;
+				Expression default_value = null;
+				if (p.ParameterType.IsByRef) {
+					if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
+						mod = Parameter.Modifier.OUT;
+					else
+						mod = Parameter.Modifier.REF;
+
+					//
+					// Strip reference wrapping
+					//
+					var el = p.ParameterType.GetElementType ();
+					types[i] = ImportType (el, new DynamicTypeReader (p));	// TODO: 1-based positio to be csc compatible
+				} else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
+					HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
+					mod = Parameter.Modifier.This;
+					types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
+				} else {
+					types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
+
+					if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
+						if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
+							mod = Parameter.Modifier.PARAMS;
+							is_params = true;
+						}
+					}
+
+					if (!is_params && p.IsOptional) {
+						object value = p.RawDefaultValue;
+						var ptype = types[i];
+						if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
+							if (value == null) {
+								default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
+							} else {
+								default_value = ImportParameterConstant (value);
+
+								if (ptype.IsEnum) {
+									default_value = new EnumConstant ((Constant) default_value, ptype);
+								}
+							}
+
+							var attrs = CustomAttributeData.GetCustomAttributes (p);
+							for (int ii = 0; ii < attrs.Count; ++ii) {
+								var attr = attrs[ii];
+								var dt = attr.Constructor.DeclaringType;
+								if (dt.Namespace != CompilerServicesNamespace)
+									continue;
+
+								if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
+									mod |= Parameter.Modifier.CallerLineNumber;
+								else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
+									mod |= Parameter.Modifier.CallerFilePath;
+								else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
+									mod |= Parameter.Modifier.CallerMemberName;
+							}
+						} else if (value == Missing.Value) {
+							default_value = EmptyExpression.MissingValue;
+						} else if (value == null) {
+							default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
+						} else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+							default_value = ImportParameterConstant (value);
+						}
+					}
+				}
+
+				par[i] = new ParameterData (p.Name, mod, default_value);
+			}
+
+			if (varargs != 0) {
+				par[par.Length - 1] = new ArglistParameter (Location.Null);
+				types[types.Length - 1] = InternalType.Arglist;
+			}
+
+			return method != null ?
+				new ParametersImported (par, types, varargs != 0, is_params) :
+				new ParametersImported (par, types, is_params);
+		}
+
+		//
+		// Returns null when the property is not valid C# property
+		//
+		public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
+		{
+			Modifiers mod = 0;
+			AParametersCollection param = null;
+			TypeSpec type = null;
+			if (get != null) {
+				mod = get.Modifiers;
+				param = get.Parameters;
+				type = get.ReturnType;
+			}
+
+			bool is_valid_property = true;
+			if (set != null) {
+				if (set.ReturnType.Kind != MemberKind.Void)
+					is_valid_property = false;
+
+				var set_param_count = set.Parameters.Count - 1;
+
+				if (set_param_count < 0) {
+					set_param_count = 0;
+					is_valid_property = false;
+				}
+
+				var set_type = set.Parameters.Types[set_param_count];
+
+				if (mod == 0) {
+					AParametersCollection set_based_param;
+
+					if (set_param_count == 0) {
+						set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
+					} else {
+						//
+						// Create indexer parameters based on setter method parameters (the last parameter has to be removed)
+						//
+						var data = new IParameterData[set_param_count];
+						var types = new TypeSpec[set_param_count];
+						Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
+						Array.Copy (set.Parameters.Types, types, set_param_count);
+						set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
+					}
+
+					mod = set.Modifiers;
+					param = set_based_param;
+					type = set_type;
+				} else {
+					if (set_param_count != get.Parameters.Count)
+						is_valid_property = false;
+
+					if (get.ReturnType != set_type)
+						is_valid_property = false;
+
+					// Possible custom accessor modifiers
+					if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
+						var get_acc = mod & Modifiers.AccessibilityMask;
+						if (get_acc != Modifiers.PUBLIC) {
+							var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
+							// If the accessor modifiers are not same, do extra restriction checks
+							if (get_acc != set_acc) {
+								var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
+								var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
+								if (get_restr && set_restr) {
+									is_valid_property = false; // Neither is more restrictive
+								}
+
+								if (get_restr) {
+									mod &= ~Modifiers.AccessibilityMask;
+									mod |= set_acc;
+								}
+							}
+						}
+					}
+				}
+			}
+
+			PropertySpec spec = null;
+			if (!param.IsEmpty) {
+				if (is_valid_property) {
+					var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
+					if (index_name == null) {
+						is_valid_property = false;
+					} else {
+						if (get != null) {
+							if (get.IsStatic)
+								is_valid_property = false;
+							if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
+								is_valid_property = false;
+						}
+						if (set != null) {
+							if (set.IsStatic)
+								is_valid_property = false;
+							if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
+								is_valid_property = false;
+						}
+					}
+
+					if (is_valid_property) {
+						spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
+					} else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
+						//
+						// Enables support for properties with parameters (must have default value) of COM-imported types
+						//
+						is_valid_property = true;
+
+						for (int i = 0; i < param.FixedParameters.Length; ++i) {
+							if (!param.FixedParameters[i].HasDefaultValue) {
+								is_valid_property = false;
+								break;
+							}
+						}
+					}
+				}
+			}
+
+			if (spec == null)
+				spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
+
+			if (!is_valid_property) {
+				spec.IsNotCSharpCompatible = true;
+				return spec;
+			}
+
+			if (set != null)
+				spec.Set = set;
+			if (get != null)
+				spec.Get = get;
+
+			return spec;
+		}
+
+		public TypeSpec CreateType (MetaType type)
+		{
+			return CreateType (type, new DynamicTypeReader (), true);
+		}
+
+		public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
+		{
+			return CreateType (type, declaringType, new DynamicTypeReader (type), false);
+		}
+
+		TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
+		{
+			TypeSpec declaring_type;
+			if (type.IsNested && !type.IsGenericParameter)
+				declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
+			else
+				declaring_type = null;
+
+			return CreateType (type, declaring_type, dtype, canImportBaseType);
+		}
+
+		protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
+		{
+			TypeSpec spec;
+			if (import_cache.TryGetValue (type, out spec)) {
+				if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
+					if (dtype.IsDynamicObject ())
+						return module.Compiler.BuiltinTypes.Dynamic;
+
+					return spec;
+				}
+
+				if (!spec.IsGeneric || type.IsGenericTypeDefinition)
+					return spec;
+
+				if (!dtype.HasDynamicAttribute ())
+					return spec;
+
+				// We've found same object in the cache but this one has a dynamic custom attribute
+				// and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
+				// Do type resolve process again in that case
+
+				// TODO: Handle cases where they still unify
+			}
+
+			if (IsMissingType (type)) {
+				spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
+				spec.MemberCache = MemberCache.Empty;
+				import_cache.Add (type, spec);
+				return spec;
+			}
+
+			if (type.IsGenericType && !type.IsGenericTypeDefinition) {
+				var type_def = type.GetGenericTypeDefinition ();
+
+				// Generic type definition can also be forwarded
+				if (compiled_types.TryGetValue (type_def, out spec))
+					return spec;
+
+				var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
+				if (targs == null)
+					return null;
+				if (declaringType == null) {
+					// Simple case, no nesting
+					spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
+					spec = spec.MakeGenericType (module, targs);
+				} else {
+					//
+					// Nested type case, converting .NET types like
+					// A`1.B`1.C`1<int, long, string> to typespec like
+					// A<int>.B<long>.C<string>
+					//
+					var nested_hierarchy = new List<TypeSpec> ();
+					while (declaringType.IsNested) {
+						nested_hierarchy.Add (declaringType);
+						declaringType = declaringType.DeclaringType;
+					}
+
+					int targs_pos = 0;
+					if (declaringType.Arity > 0) {
+						spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
+						targs_pos = spec.Arity;
+					} else {
+						spec = declaringType;
+					}
+
+					for (int i = nested_hierarchy.Count; i != 0; --i) {
+						var t = nested_hierarchy [i - 1];
+						if (t.Kind == MemberKind.MissingType)
+							spec = t;
+						else
+							spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
+
+						if (t.Arity > 0) {
+							spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
+							targs_pos += t.Arity;
+						}
+					}
+
+					if (spec.Kind == MemberKind.MissingType) {
+						spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
+						spec.MemberCache = MemberCache.Empty;
+					} else {
+						if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
+							return null;
+
+						string name = type.Name;
+						int index = name.IndexOf ('`');
+						if (index > 0)
+							name = name.Substring (0, index);
+
+						spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
+
+						if (spec.Arity > 0) {
+							spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
+						}
+					}
+				}
+
+				// Don't add generic type with dynamic arguments, they can interfere with same type
+				// using object type arguments
+				if (!spec.HasDynamicElement) {
+
+					// Add to reading cache to speed up reading
+					if (!import_cache.ContainsKey (type))
+						import_cache.Add (type, spec);
+				}
+
+				return spec;
+			}
+
+			Modifiers mod;
+			MemberKind kind;
+
+			var ma = type.Attributes;
+			switch (ma & TypeAttributes.VisibilityMask) {
+			case TypeAttributes.Public:
+			case TypeAttributes.NestedPublic:
+				mod = Modifiers.PUBLIC;
+				break;
+			case TypeAttributes.NestedPrivate:
+				mod = Modifiers.PRIVATE;
+				break;
+			case TypeAttributes.NestedFamily:
+				mod = Modifiers.PROTECTED;
+				break;
+			case TypeAttributes.NestedFamORAssem:
+				mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
+				break;
+			default:
+				mod = Modifiers.INTERNAL;
+				break;
+			}
+
+			if ((ma & TypeAttributes.Interface) != 0) {
+				kind = MemberKind.Interface;
+			} else if (type.IsGenericParameter) {
+				kind = MemberKind.TypeParameter;
+			} else {
+				var base_type = type.BaseType;
+				if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
+					kind = MemberKind.Class;
+				} else {
+					kind = DetermineKindFromBaseType (base_type);
+					if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
+						mod |= Modifiers.SEALED;
+					}
+				}
+
+				if (kind == MemberKind.Class) {
+					if ((ma & TypeAttributes.Sealed) != 0) {
+						if ((ma & TypeAttributes.Abstract) != 0)
+							mod |= Modifiers.STATIC;
+						else
+							mod |= Modifiers.SEALED;
+					} else if ((ma & TypeAttributes.Abstract) != 0) {
+						mod |= Modifiers.ABSTRACT;
+					}
+				}
+			}
+
+			var definition = new ImportedTypeDefinition (type, this);
+			TypeSpec pt;
+
+			if (kind == MemberKind.Enum) {
+				const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
+					BindingFlags.Instance |
+					BindingFlags.Public | BindingFlags.NonPublic;
+
+				var type_members = type.GetFields (underlying_member);
+				foreach (var type_member in type_members) {
+					spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
+					break;
+				}
+
+				if (spec == null)
+					kind = MemberKind.Class;
+
+			} else if (kind == MemberKind.TypeParameter) {
+				spec = CreateTypeParameter (type, declaringType);
+			} else if (type.IsGenericTypeDefinition) {
+				definition.TypeParameters = CreateGenericParameters (type, declaringType);
+			} else if (compiled_types.TryGetValue (type, out pt)) {
+				//
+				// Same type was found in inside compiled types. It's
+				// either build-in type or forward referenced typed
+				// which point into just compiled assembly.
+				//
+				spec = pt;
+				BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
+				if (bts != null)
+					bts.SetDefinition (definition, type, mod);
+			}
+
+			if (spec == null)
+				spec = new TypeSpec (kind, declaringType, definition, type, mod);
+
+			import_cache.Add (type, spec);
+
+			if (kind == MemberKind.TypeParameter) {
+				if (canImportBaseType)
+					ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
+
+				return spec;
+			}
+
+			//
+			// Two stage setup as the base type can be inflated declaring type or
+			// another nested type inside same declaring type which has not been
+			// loaded, therefore we can import a base type of nested types once
+			// the types have been imported
+			//
+			if (canImportBaseType)
+				ImportTypeBase (spec, type);
+
+			return spec;
+		}
+
+		public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
+		{
+			IAssemblyDefinition found;
+			if (!assembly_2_definition.TryGetValue (assembly, out found)) {
+
+				// This can happen in dynamic context only
+				var def = new ImportedAssemblyDefinition (assembly);
+				assembly_2_definition.Add (assembly, def);
+				def.ReadAttributes ();
+				found = def;
+			}
+
+			return found;
+		}
+
+		public void ImportTypeBase (MetaType type)
+		{
+			TypeSpec spec = import_cache[type];
+			if (spec != null)
+				ImportTypeBase (spec, type);
+		}
+
+		TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
+		{
+			Variance variance;
+			switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
+			case GenericParameterAttributes.Covariant:
+				variance = Variance.Covariant;
+				break;
+			case GenericParameterAttributes.Contravariant:
+				variance = Variance.Contravariant;
+				break;
+			default:
+				variance = Variance.None;
+				break;
+			}
+
+			SpecialConstraint special = SpecialConstraint.None;
+			var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
+
+			if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
+				special |= SpecialConstraint.Struct;
+			} else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
+				special = SpecialConstraint.Constructor;
+			}
+
+			if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
+				special |= SpecialConstraint.Class;
+			}
+
+			TypeParameterSpec spec;
+			var def = new ImportedTypeParameterDefinition (type, this);
+			if (type.DeclaringMethod != null) {
+				spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
+			} else {
+				spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
+			}
+
+			return spec;
+		}
+
+		//
+		// Test for a custom attribute type match. Custom attributes are not really predefined globaly 
+		// they can be assembly specific therefore we do check based on names only
+		//
+		public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
+		{
+			if (attributesData.Count == 0)
+				return false;
+
+			foreach (var attr in attributesData) {
+				var dt = attr.Constructor.DeclaringType;
+				if (dt.Name == attrName && dt.Namespace == attrNamespace)
+					return true;
+			}
+
+			return false;
+		}
+
+		void ImportTypeBase (TypeSpec spec, MetaType type)
+		{
+			if (spec.Kind == MemberKind.Interface)
+				spec.BaseType = module.Compiler.BuiltinTypes.Object;
+			else if (type.BaseType != null) {
+				TypeSpec base_type;
+				if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
+					base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
+				else
+					base_type = CreateType (type.BaseType);
+
+				spec.BaseType = base_type;
+			}
+
+			if (spec.MemberDefinition.TypeParametersCount > 0) {
+				foreach (var tp in spec.MemberDefinition.TypeParameters) {
+					ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
+				}
+			}
+		}
+
+		protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
+		{
+			Namespace ns = targetNamespace;
+			string prev_namespace = null;
+			foreach (var t in types) {
+				if (t == null)
+					continue;
+
+				// Be careful not to trigger full parent type loading
+				if (t.MemberType == MemberTypes.NestedType)
+					continue;
+
+				if (t.Name[0] == '<')
+					continue;
+
+				var it = CreateType (t, null, new DynamicTypeReader (t), true);
+				if (it == null)
+					continue;
+
+				if (prev_namespace != t.Namespace) {
+					ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
+					prev_namespace = t.Namespace;
+				}
+
+				// Cannot rely on assembly level Extension attribute or static modifier because they
+				// are not followed by other compilers (e.g. F#).
+				if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
+					HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
+					it.SetExtensionMethodContainer ();
+				}
+
+				ns.AddType (module, it);
+			}
+		}
+
+		void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
+		{
+			var constraints = type.GetGenericParameterConstraints ();
+			List<TypeSpec> tparams = null;
+			foreach (var ct in constraints) {
+				if (ct.IsGenericParameter) {
+					if (tparams == null)
+						tparams = new List<TypeSpec> ();
+
+					tparams.Add (CreateType (ct));
+					continue;
+				}
+
+				var constraint_type = CreateType (ct);
+				if (constraint_type.IsClass) {
+					spec.BaseType = constraint_type;
+					continue;
+				}
+
+				spec.AddInterface (constraint_type);
+			}
+
+			if (spec.BaseType == null)
+				spec.BaseType = module.Compiler.BuiltinTypes.Object;
+
+			if (tparams != null)
+				spec.TypeArguments = tparams.ToArray ();
+		}
+
+		Constant ImportParameterConstant (object value)
+		{
+			//
+			// Get type of underlying value as int constant can be used for object
+			// parameter type. This is not allowed in C# but other languages can do that
+			//
+			var types = module.Compiler.BuiltinTypes;
+			switch (System.Type.GetTypeCode (value.GetType ())) {
+			case TypeCode.Boolean:
+				return new BoolConstant (types, (bool) value, Location.Null);
+			case TypeCode.Byte:
+				return new ByteConstant (types, (byte) value, Location.Null);
+			case TypeCode.Char:
+				return new CharConstant (types, (char) value, Location.Null);
+			case TypeCode.Decimal:
+				return new DecimalConstant (types, (decimal) value, Location.Null);
+			case TypeCode.Double:
+				return new DoubleConstant (types, (double) value, Location.Null);
+			case TypeCode.Int16:
+				return new ShortConstant (types, (short) value, Location.Null);
+			case TypeCode.Int32:
+				return new IntConstant (types, (int) value, Location.Null);
+			case TypeCode.Int64:
+				return new LongConstant (types, (long) value, Location.Null);
+			case TypeCode.SByte:
+				return new SByteConstant (types, (sbyte) value, Location.Null);
+			case TypeCode.Single:
+				return new FloatConstant (types, (float) value, Location.Null);
+			case TypeCode.String:
+				return new StringConstant (types, (string) value, Location.Null);
+			case TypeCode.UInt16:
+				return new UShortConstant (types, (ushort) value, Location.Null);
+			case TypeCode.UInt32:
+				return new UIntConstant (types, (uint) value, Location.Null);
+			case TypeCode.UInt64:
+				return new ULongConstant (types, (ulong) value, Location.Null);
+			}
+
+			throw new NotImplementedException (value.GetType ().ToString ());
+		}
+
+		public TypeSpec ImportType (MetaType type)
+		{
+			return ImportType (type, new DynamicTypeReader (type));
+		}
+
+		TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
+		{
+			if (type.HasElementType) {
+				var element = type.GetElementType ();
+				++dtype.Position;
+				var spec = ImportType (element, dtype);
+
+				if (type.IsArray)
+					return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
+				if (type.IsByRef)
+					return ReferenceContainer.MakeType (module, spec);
+				if (type.IsPointer)
+					return PointerContainer.MakeType (module, spec);
+
+				throw new NotImplementedException ("Unknown element type " + type.ToString ());
+			}
+
+			TypeSpec compiled_type;
+			if (compiled_types.TryGetValue (type, out compiled_type)) {
+				if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
+					return module.Compiler.BuiltinTypes.Dynamic;
+
+				return compiled_type;
+			}
+
+			return CreateType (type, dtype, true);
+		}
+
+		static bool IsMissingType (MetaType type)
+		{
+#if STATIC
+			return type.__IsMissing;
+#else
+			return false;
+#endif
+		}
+
+		//
+		// Decimal constants cannot be encoded in the constant blob, and thus are marked
+		// as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
+		// DecimalConstantAttribute metadata.
+		//
+		Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
+		{
+			if (attrs.Count == 0)
+				return null;
+
+			foreach (var ca in attrs) {
+				var dt = ca.Constructor.DeclaringType;
+				if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
+					continue;
+
+				var value = new decimal (
+					(int) (uint) ca.ConstructorArguments[4].Value,
+					(int) (uint) ca.ConstructorArguments[3].Value,
+					(int) (uint) ca.ConstructorArguments[2].Value,
+					(byte) ca.ConstructorArguments[1].Value != 0,
+					(byte) ca.ConstructorArguments[0].Value);
+
+				return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
+			}
+
+			return null;
+		}
+
+		static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
+		{
+			Modifiers mod;
+			var ma = mb.Attributes;
+			switch (ma & MethodAttributes.MemberAccessMask) {
+			case MethodAttributes.Public:
+				mod = Modifiers.PUBLIC;
+				break;
+			case MethodAttributes.Assembly:
+				mod = Modifiers.INTERNAL;
+				break;
+			case MethodAttributes.Family:
+				mod = Modifiers.PROTECTED;
+				break;
+			case MethodAttributes.FamORAssem:
+				mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
+				break;
+			default:
+				mod = Modifiers.PRIVATE;
+				break;
+			}
+
+			if ((ma & MethodAttributes.Static) != 0) {
+				mod |= Modifiers.STATIC;
+				return mod;
+			}
+			if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
+				mod |= Modifiers.ABSTRACT;
+				return mod;
+			}
+
+			// It can be sealed and override
+			if ((ma & MethodAttributes.Final) != 0)
+				mod |= Modifiers.SEALED;
+
+			if ((ma & MethodAttributes.Virtual) != 0) {
+				// Not every member can be detected based on MethodAttribute, we
+				// set virtual or non-virtual only when we are certain. Further checks
+				// to really find out what `virtual' means for this member are done
+				// later
+				if ((ma & MethodAttributes.NewSlot) != 0) {
+					if ((mod & Modifiers.SEALED) != 0) {
+						mod &= ~Modifiers.SEALED;
+					} else {
+						mod |= Modifiers.VIRTUAL;
+					}
+				} else {
+					mod |= Modifiers.OVERRIDE;
+				}
+			}
+
+			return mod;
+		}
+	}
+
+	abstract class ImportedDefinition : IMemberDefinition
+	{
+		protected class AttributesBag
+		{
+			public static readonly AttributesBag Default = new AttributesBag ();
+
+			public AttributeUsageAttribute AttributeUsage;
+			public ObsoleteAttribute Obsolete;
+			public string[] Conditionals;
+			public string DefaultIndexerName;
+			public bool? CLSAttributeValue;
+			public TypeSpec CoClass;
+
+			static bool HasMissingType (ConstructorInfo ctor)
+			{
+#if STATIC
+				//
+				// Mimic odd csc behaviour where missing type on predefined
+				// attributes means the attribute is silently ignored. This can
+				// happen with PCL facades
+				//
+				foreach (var p in ctor.GetParameters ()) {
+					if (p.ParameterType.__ContainsMissingType)
+						return true;
+				}
+#endif
+
+				return false;
+			}
+			
+			public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
+			{
+				AttributesBag bag = null;
+				List<string> conditionals = null;
+
+				// It should not throw any loading exception
+				IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
+
+				foreach (var a in attrs) {
+					var dt = a.Constructor.DeclaringType;
+					string name = dt.Name;
+					if (name == "ObsoleteAttribute") {
+						if (dt.Namespace != "System")
+							continue;
+
+						if (bag == null)
+							bag = new AttributesBag ();
+
+						var args = a.ConstructorArguments;
+
+						if (args.Count == 1) {
+							bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
+						} else if (args.Count == 2) {
+							bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
+						} else {
+							bag.Obsolete = new ObsoleteAttribute ();
+						}
+
+						continue;
+					}
+
+					if (name == "ConditionalAttribute") {
+						if (dt.Namespace != "System.Diagnostics")
+							continue;
+
+						if (bag == null)
+							bag = new AttributesBag ();
+
+						if (conditionals == null)
+							conditionals = new List<string> (2);
+
+						conditionals.Add ((string) a.ConstructorArguments[0].Value);
+						continue;
+					}
+
+					if (name == "CLSCompliantAttribute") {
+						if (dt.Namespace != "System")
+							continue;
+
+						if (bag == null)
+							bag = new AttributesBag ();
+
+						bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
+						continue;
+					}
+
+					// Type only attributes
+					if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
+						if (name == "DefaultMemberAttribute") {
+							if (dt.Namespace != "System.Reflection")
+								continue;
+
+							if (bag == null)
+								bag = new AttributesBag ();
+
+							bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
+							continue;
+						}
+
+						if (name == "AttributeUsageAttribute") {
+							if (dt.Namespace != "System")
+								continue;
+
+							if (HasMissingType (a.Constructor))
+								continue;
+
+							if (bag == null)
+								bag = new AttributesBag ();
+
+							bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
+							foreach (var named in a.NamedArguments) {
+								if (named.MemberInfo.Name == "AllowMultiple")
+									bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
+								else if (named.MemberInfo.Name == "Inherited")
+									bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
+							}
+							continue;
+						}
+
+						// Interface only attribute
+						if (name == "CoClassAttribute") {
+							if (dt.Namespace != "System.Runtime.InteropServices")
+								continue;
+
+							if (HasMissingType (a.Constructor))
+								continue;
+
+							if (bag == null)
+								bag = new AttributesBag ();
+
+							bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
+							continue;
+						}
+					}
+				}
+
+				if (bag == null)
+					return Default;
+
+				if (conditionals != null)
+					bag.Conditionals = conditionals.ToArray ();
+				
+				return bag;
+			}
+		}
+
+		protected readonly MemberInfo provider;
+		protected AttributesBag cattrs;
+		protected readonly MetadataImporter importer;
+
+		protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
+		{
+			this.provider = provider;
+			this.importer = importer;
+		}
+
+		#region Properties
+
+		public bool IsImported {
+			get {
+				return true;
+			}
+		}
+
+		public virtual string Name {
+			get {
+				return provider.Name;
+			}
+		}
+
+		#endregion
+
+		public string[] ConditionalConditions ()
+		{
+			if (cattrs == null)
+				ReadAttributes ();
+
+			return cattrs.Conditionals;
+		}
+
+		public ObsoleteAttribute GetAttributeObsolete ()
+		{
+			if (cattrs == null)
+				ReadAttributes ();
+
+			return cattrs.Obsolete;
+		}
+
+		public bool? CLSAttributeValue {
+			get {
+				if (cattrs == null)
+					ReadAttributes ();
+
+				return cattrs.CLSAttributeValue;
+			}
+		}
+
+		protected void ReadAttributes ()
+		{
+			cattrs = AttributesBag.Read (provider, importer);
+		}
+
+		public void SetIsAssigned ()
+		{
+			// Unused for imported members
+		}
+
+		public void SetIsUsed ()
+		{
+			// Unused for imported members
+		}
+	}
+
+	public class ImportedModuleDefinition
+	{
+		readonly Module module;
+		bool cls_compliant;
+		
+		public ImportedModuleDefinition (Module module)
+		{
+			this.module = module;
+		}
+
+		#region Properties
+
+		public bool IsCLSCompliant {
+			get {
+				return cls_compliant;
+			}
+		}
+
+		public string Name {
+			get {
+				return module.Name;
+			}
+		}
+
+		#endregion
+
+		public void ReadAttributes ()
+		{
+			IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
+
+			foreach (var a in attrs) {
+				var dt = a.Constructor.DeclaringType;
+				if (dt.Name == "CLSCompliantAttribute") {
+					if (dt.Namespace != "System")
+						continue;
+
+					cls_compliant = (bool) a.ConstructorArguments[0].Value;
+					continue;
+				}
+			}
+		}
+
+		//
+		// Reads assembly attributes which where attached to a special type because
+		// module does have assembly manifest
+		//
+		public List<Attribute> ReadAssemblyAttributes ()
+		{
+			var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
+			if (t == null)
+				return null;
+
+			var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
+			if (field == null)
+				return null;
+
+			// TODO: implement, the idea is to fabricate specil Attribute class and
+			// add it to OptAttributes before resolving the source code attributes
+			// Need to build module location as well for correct error reporting
+
+			//var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
+			//var attrs = new List<Attribute> (assembly_attributes.Count);
+			//foreach (var a in assembly_attributes)
+			//{
+			//    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
+			//    var ctor = metaImporter.CreateMethod (a.Constructor, type);
+
+			//    foreach (var carg in a.ConstructorArguments) {
+			//        carg.Value
+			//    }
+
+			//    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
+			//}
+
+			return null;
+		}
+	}
+
+	public class ImportedAssemblyDefinition : IAssemblyDefinition
+	{
+		readonly Assembly assembly;
+		readonly AssemblyName aname;
+		bool cls_compliant;
+
+		List<AssemblyName> internals_visible_to;
+		Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
+
+		public ImportedAssemblyDefinition (Assembly assembly)
+		{
+			this.assembly = assembly;
+			this.aname = assembly.GetName ();
+		}
+
+		#region Properties
+
+		public Assembly Assembly {
+			get {
+				return assembly;
+			}
+		}
+
+		public string FullName {
+			get {
+				return aname.FullName;
+			}
+		}
+
+		public bool HasStrongName {
+			get {
+				return aname.GetPublicKey ().Length != 0;
+			}
+		}
+
+		public bool IsMissing {
+			get {
+#if STATIC
+				return assembly.__IsMissing;
+#else
+				return false;
+#endif
+			}
+		}
+
+		public bool IsCLSCompliant {
+			get {
+				return cls_compliant;
+			}
+		}
+
+		public string Location {
+			get {
+				return assembly.Location;
+			}
+		}
+
+		public string Name {
+			get {
+				return aname.Name;
+			}
+		}
+
+		#endregion
+
+		public byte[] GetPublicKeyToken ()
+		{
+			return aname.GetPublicKeyToken ();
+		}
+
+		public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
+		{
+			return internals_visible_to_cache [assembly];
+		}
+
+		public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
+		{
+			if (internals_visible_to == null)
+				return false;
+
+			AssemblyName is_visible = null;
+			if (internals_visible_to_cache == null) {
+				internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
+			} else {
+				if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
+					return is_visible != null;
+			}
+
+			var token = assembly.GetPublicKeyToken ();
+			if (token != null && token.Length == 0)
+				token = null;
+
+			foreach (var internals in internals_visible_to) {
+				if (internals.Name != assembly.Name)
+					continue;
+
+				if (token == null && assembly is AssemblyDefinition) {
+					is_visible = internals;
+					break;
+				}
+
+				if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
+					continue;
+
+				is_visible = internals;
+				break;
+			}
+
+			internals_visible_to_cache.Add (assembly, is_visible);
+			return is_visible != null;
+		}
+
+		public void ReadAttributes ()
+		{
+#if STATIC
+			if (assembly.__IsMissing)
+				return;
+#endif
+
+			IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
+
+			foreach (var a in attrs) {
+				var dt = a.Constructor.DeclaringType;
+				var name = dt.Name;
+				if (name == "CLSCompliantAttribute") {
+					if (dt.Namespace == "System") {
+						cls_compliant = (bool) a.ConstructorArguments[0].Value;
+					}
+					continue;
+				}
+
+				if (name == "InternalsVisibleToAttribute") {
+					if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
+						continue;
+
+					string s = a.ConstructorArguments[0].Value as string;
+					if (s == null)
+						continue;
+
+					var an = new AssemblyName (s);
+					if (internals_visible_to == null)
+						internals_visible_to = new List<AssemblyName> ();
+
+					internals_visible_to.Add (an);
+					continue;
+				}
+			}
+		}
+
+		public override string ToString ()
+		{
+			return FullName;
+		}
+	}
+
+	class ImportedMemberDefinition : ImportedDefinition
+	{
+		readonly TypeSpec type;
+
+		public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
+			: base (member, importer)
+		{
+			this.type = type;
+		}
+
+		#region Properties
+
+		public TypeSpec MemberType {
+			get {
+				return type;
+			}
+		}
+
+		#endregion
+	}
+
+	class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
+	{
+		readonly AParametersCollection parameters;
+
+		protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
+			: base (provider, type, importer)
+		{
+			this.parameters = parameters;
+		}
+
+		public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
+			: base (provider, type, importer)
+		{
+			this.parameters = parameters;
+		}
+
+		#region Properties
+
+		public AParametersCollection Parameters {
+			get {
+				return parameters;
+			}
+		}
+
+		#endregion
+	}
+
+	class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
+	{
+		public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
+			: base (provider, type, parameters, importer)
+		{
+		}
+
+		MethodBase IMethodDefinition.Metadata {
+			get {
+				return (MethodBase) provider;
+			}
+		}
+	}
+
+	class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
+	{
+		readonly TypeParameterSpec[] tparams;
+
+		public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
+			: base (provider, type, parameters, importer)
+		{
+			this.tparams = tparams;
+		}
+
+		#region Properties
+
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				return tparams;
+			}
+		}
+
+		public int TypeParametersCount {
+			get {
+				return tparams.Length;
+			}
+		}
+
+		#endregion
+	}
+
+	class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
+	{
+		TypeParameterSpec[] tparams;
+		string name;
+
+		public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
+			: base (type, importer)
+		{
+		}
+
+		#region Properties
+
+		public IAssemblyDefinition DeclaringAssembly {
+			get {
+				return importer.GetAssemblyDefinition (provider.Module.Assembly);
+			}
+		}
+
+		bool ITypeDefinition.IsComImport {
+			get {
+				return ((MetaType) provider).IsImport;
+			}
+		}
+
+
+		bool ITypeDefinition.IsPartial {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsTypeForwarder {
+			get {
+#if STATIC
+				return ((MetaType) provider).__IsTypeForwarder;
+#else
+				return false;
+#endif
+			}
+		}
+
+		bool ITypeDefinition.IsCyclicTypeForwarder {
+			get {
+#if STATIC
+				return ((MetaType) provider).__IsCyclicTypeForwarder;
+#else
+				return false;
+#endif
+			}
+		}
+
+		public override string Name {
+			get {
+				if (name == null) {
+					name = base.Name;
+					if (tparams != null) {
+						int arity_start = name.IndexOf ('`');
+						if (arity_start > 0)
+							name = name.Substring (0, arity_start);
+					}
+				}
+
+				return name;
+			}
+		}
+
+		public string Namespace {
+			get {
+				return ((MetaType) provider).Namespace;
+			}
+		}
+
+		public int TypeParametersCount {
+			get {
+				return tparams == null ? 0 : tparams.Length;
+			}
+		}
+
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				return tparams;
+			}
+			set {
+				tparams = value;
+			}
+		}
+
+		#endregion
+
+		public void DefineInterfaces (TypeSpec spec)
+		{
+			var type = (MetaType) provider;
+			MetaType[] ifaces;
+#if STATIC
+			ifaces = type.__GetDeclaredInterfaces ();
+			if (ifaces.Length != 0) {
+				foreach (var iface in ifaces) {
+					var it = importer.CreateType (iface);
+					if (it == null)
+						continue;
+
+					spec.AddInterfaceDefined (it);
+
+					// Unfortunately not all languages expand inherited interfaces
+					var bifaces = it.Interfaces;
+					if (bifaces != null) {
+						foreach (var biface in bifaces) {
+							spec.AddInterfaceDefined (biface);
+						}
+					}
+				}
+			}
+			
+			//
+			// It's impossible to get declared interfaces only using System.Reflection
+			// hence we need to mimic the behavior with ikvm-reflection too to keep
+			// our type look-up logic same
+			//
+			if (spec.BaseType != null) {
+				var bifaces = spec.BaseType.Interfaces;
+				if (bifaces != null) {
+					//
+					// Before adding base class interfaces close defined interfaces
+					// on type parameter
+					//
+					var tp = spec as TypeParameterSpec;
+					if (tp != null && tp.InterfacesDefined == null) {
+						tp.InterfacesDefined = TypeSpec.EmptyTypes;
+					}
+
+					foreach (var iface in bifaces)
+						spec.AddInterfaceDefined (iface);
+				}
+			}
+#else
+			ifaces = type.GetInterfaces ();
+
+			if (ifaces.Length > 0) {
+				foreach (var iface in ifaces) {
+					spec.AddInterface (importer.CreateType (iface));
+				}
+			}
+#endif
+
+		}
+
+		public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
+		{
+			// 
+			// Report details about missing type and most likely cause of the problem.
+			// csc reports 1683, 1684 as warnings but we report them only when used
+			// or referenced from the user core in which case compilation error has to
+			// be reported because compiler cannot continue anyway
+			//
+
+			var report = ctx.Module.Compiler.Report;
+
+			for (int i = 0; i < missing.Count; ++i) {
+				var t = missing [i].Type;
+
+				//
+				// Report missing types only once
+				//
+				if (report.Printer.MissingTypeReported (t.MemberDefinition))
+					continue;
+
+				string name = t.GetSignatureForError ();
+
+				var caller = missing[i].Caller;
+				if (caller.Kind != MemberKind.MissingType)
+					report.SymbolRelatedToPreviousError (caller);
+
+				var definition = t.MemberDefinition;
+				if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
+					report.Error (1683, loc,
+						"Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
+						name);
+				} else if (definition.DeclaringAssembly.IsMissing) {
+					if (definition.IsTypeForwarder) {
+						report.Error (1070, loc,
+							"The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
+							name, definition.DeclaringAssembly.FullName);
+					} else {
+						report.Error (12, loc,
+							"The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
+							name, definition.DeclaringAssembly.FullName);
+					}
+				} else if (definition.IsTypeForwarder) {
+					report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
+						name, definition.DeclaringAssembly.FullName);
+				} else {
+					report.Error (1684, loc,
+						"Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
+						name, t.MemberDefinition.DeclaringAssembly.FullName);
+				}
+			}
+		}
+
+		public TypeSpec GetAttributeCoClass ()
+		{
+			if (cattrs == null)
+				ReadAttributes ();
+
+			return cattrs.CoClass;
+		}
+
+		public string GetAttributeDefaultMember ()
+		{
+			if (cattrs == null)
+				ReadAttributes ();
+
+			return cattrs.DefaultIndexerName;
+		}
+
+		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+		{
+			if (cattrs == null)
+				ReadAttributes ();
+
+			return cattrs.AttributeUsage;
+		}
+
+		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
+		{
+			var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
+			return a == assembly || a.IsFriendAssemblyTo (assembly);
+		}
+
+		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+		{
+			//
+			// Not interested in members of nested private types unless the importer needs them
+			//
+			if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
+				cache = MemberCache.Empty;
+				return;
+			}
+
+			var loading_type = (MetaType) provider;
+			const BindingFlags all_members = BindingFlags.DeclaredOnly |
+				BindingFlags.Static | BindingFlags.Instance |
+				BindingFlags.Public | BindingFlags.NonPublic;
+
+			const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
+					MethodAttributes.Virtual | MethodAttributes.HideBySig |
+					MethodAttributes.Final;
+
+			Dictionary<MethodBase, MethodSpec> possible_accessors = null;
+			List<EventSpec> imported_events = null;
+			EventSpec event_spec;
+			MemberSpec imported;
+			MethodInfo m;
+			MemberInfo[] all;
+			try {
+				all = loading_type.GetMembers (all_members);
+			} catch (Exception e) {
+				throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
+					declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
+			}
+
+			if (cache == null) {
+				cache = new MemberCache (all.Length);
+
+				//
+				// Do the types first as they can be referenced by the members before
+				// they are found or inflated
+				//
+				foreach (var member in all) {
+					if (member.MemberType != MemberTypes.NestedType)
+						continue;
+
+					var t = (MetaType) member;
+
+					// Ignore compiler generated types, mostly lambda containers
+					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
+						continue;
+
+					try {
+						imported = importer.CreateNestedType (t, declaringType);
+					} catch (Exception e) {
+						throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
+							t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
+					}
+
+					cache.AddMemberImported (imported);
+				}
+
+				foreach (var member in all) {
+					if (member.MemberType != MemberTypes.NestedType)
+						continue;
+
+					var t = (MetaType) member;
+
+					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
+						continue;
+
+					importer.ImportTypeBase (t);
+				}
+			}
+
+			//
+			// Load base interfaces first to minic behaviour of compiled members
+			//
+			if (declaringType.IsInterface && declaringType.Interfaces != null) {
+				foreach (var iface in declaringType.Interfaces) {
+					cache.AddInterface (iface);
+				}
+			}
+
+			if (!onlyTypes) {
+				//
+				// The logic here requires methods to be returned first which seems to work for both Mono and .NET
+				//
+				foreach (var member in all) {
+					switch (member.MemberType) {
+					case MemberTypes.Constructor:
+						if (declaringType.IsInterface)
+							continue;
+
+						goto case MemberTypes.Method;
+					case MemberTypes.Method:
+						MethodBase mb = (MethodBase) member;
+						var attrs = mb.Attributes;
+
+						if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
+							if (importer.IgnorePrivateMembers)
+								continue;
+
+							// Ignore explicitly implemented members
+							if ((attrs & explicit_impl) == explicit_impl)
+								continue;
+
+							// Ignore compiler generated methods
+							if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
+								continue;
+						}
+
+						imported = importer.CreateMethod (mb, declaringType);
+						if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
+							if (possible_accessors == null)
+								possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
+
+							// There are no metadata rules for accessors, we have to consider any method as possible candidate
+							possible_accessors.Add (mb, (MethodSpec) imported);
+						}
+
+						break;
+					case MemberTypes.Property:
+						if (possible_accessors == null)
+							continue;
+
+						var p = (PropertyInfo) member;
+						//
+						// Links possible accessors with property
+						//
+						MethodSpec get, set;
+						m = p.GetGetMethod (true);
+						if (m == null || !possible_accessors.TryGetValue (m, out get))
+							get = null;
+
+						m = p.GetSetMethod (true);
+						if (m == null || !possible_accessors.TryGetValue (m, out set))
+							set = null;
+
+						// No accessors registered (e.g. explicit implementation)
+						if (get == null && set == null)
+							continue;
+
+						try {
+							imported = importer.CreateProperty (p, declaringType, get, set);
+						} catch (Exception ex) {
+							throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
+								p.Name, declaringType.GetSignatureForError ());
+						}
+
+						if (imported == null)
+							continue;
+
+						break;
+					case MemberTypes.Event:
+						if (possible_accessors == null)
+							continue;
+
+						var e = (EventInfo) member;
+						//
+						// Links accessors with event
+						//
+						MethodSpec add, remove;
+						m = e.GetAddMethod (true);
+						if (m == null || !possible_accessors.TryGetValue (m, out add))
+							add = null;
+
+						m = e.GetRemoveMethod (true);
+						if (m == null || !possible_accessors.TryGetValue (m, out remove))
+							remove = null;
+
+						// Both accessors are required
+						if (add == null || remove == null)
+							continue;
+
+						event_spec = importer.CreateEvent (e, declaringType, add, remove);
+						if (!importer.IgnorePrivateMembers) {
+							if (imported_events == null)
+								imported_events = new List<EventSpec> ();
+
+							imported_events.Add (event_spec);
+						}
+
+						imported = event_spec;
+						break;
+					case MemberTypes.Field:
+						var fi = (FieldInfo) member;
+
+						imported = importer.CreateField (fi, declaringType);
+						if (imported == null)
+							continue;
+
+						//
+						// For dynamic binder event has to be fully restored to allow operations
+						// within the type container to work correctly
+						//
+						if (imported_events != null) {
+							// The backing event field should be private but it may not
+							int i;
+							for (i = 0; i < imported_events.Count; ++i) {
+								var ev = imported_events[i];
+								if (ev.Name == fi.Name) {
+									ev.BackingField = (FieldSpec) imported;
+									imported_events.RemoveAt (i);
+									i = -1;
+									break;
+								}
+							}
+
+							if (i < 0)
+								continue;
+						}
+
+						break;
+					case MemberTypes.NestedType:
+						// Already in the cache from the first pass
+						continue;
+					default:
+						throw new NotImplementedException (member.ToString ());
+					}
+
+					if (imported.IsStatic && declaringType.IsInterface)
+						continue;
+
+					cache.AddMemberImported (imported);
+				}
+			}
+		}
+	}
+
+	class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
+	{
+		public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
+			: base (type, importer)
+		{
+		}
+
+		#region Properties
+
+		public IAssemblyDefinition DeclaringAssembly {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		bool ITypeDefinition.IsComImport {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsPartial {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsCyclicTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		public string Namespace {
+			get {
+				return null;
+			}
+		}
+
+		public int TypeParametersCount {
+			get {
+				return 0;
+			}
+		}
+
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				return null;
+			}
+		}
+
+		#endregion
+
+		public TypeSpec GetAttributeCoClass ()
+		{
+			return null;
+		}
+
+		public string GetAttributeDefaultMember ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+		{
+			throw new NotSupportedException ();
+		}
+
+		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/iterators.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/iterators.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/iterators.cs	(revision 11807)
@@ -0,0 +1,1260 @@
+//
+// iterators.cs: Support for implementing iterators
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+// Copyright 2003 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
+	{
+		protected Expression expr;
+		protected bool unwind_protect;
+		protected T machine_initializer;
+		int resume_pc;
+		ExceptionStatement inside_try_block;
+
+		protected YieldStatement (Expression expr, Location l)
+		{
+			this.expr = expr;
+			loc = l;
+		}
+
+		public Expression Expr {
+			get { return this.expr; }
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			var target = (YieldStatement<T>) t;
+			target.expr = expr.Clone (clonectx);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+
+			RegisterResumePoint ();
+
+			return false;
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			expr = expr.Resolve (bc);
+			if (expr == null)
+				return false;
+
+			machine_initializer = bc.CurrentAnonymousMethod as T;
+			inside_try_block = bc.CurrentTryBlock;
+			return true;
+		}
+
+		public void RegisterResumePoint ()
+		{
+			if (resume_pc != 0)
+				return;
+
+			if (inside_try_block == null) {
+				resume_pc = machine_initializer.AddResumePoint (this);
+			} else {
+				resume_pc = inside_try_block.AddResumePoint (this, resume_pc, machine_initializer);
+				unwind_protect = true;
+				inside_try_block = null;
+			}
+		}
+	}
+
+	public class Yield : YieldStatement<Iterator>
+	{
+		public Yield (Expression expr, Location loc)
+			: base (expr, loc)
+		{
+		}
+
+		public static bool CheckContext (BlockContext bc, Location loc)
+		{
+			if (!bc.CurrentAnonymousMethod.IsIterator) {
+				bc.Report.Error (1621, loc,
+					"The yield statement cannot be used inside anonymous method blocks");
+				return false;
+			}
+
+			if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
+				bc.Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
+				return false;
+			}
+
+			return true;
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			if (!CheckContext (bc, loc))
+				return false;
+
+			if (bc.HasAny (ResolveContext.Options.TryWithCatchScope)) {
+				bc.Report.Error (1626, loc, "Cannot yield a value in the body of a try block with a catch clause");
+			}
+
+			if (bc.HasSet (ResolveContext.Options.CatchScope)) {
+				bc.Report.Error (1631, loc, "Cannot yield a value in the body of a catch clause");
+			}
+
+			if (!base.Resolve (bc))
+				return false;
+
+			var otype = bc.CurrentIterator.OriginalIteratorType;
+			if (expr.Type != otype) {
+				expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
+				if (expr == null)
+					return false;
+			}
+
+			return true;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class YieldBreak : ExitStatement
+	{
+		Iterator iterator;
+
+		public YieldBreak (Location l)
+		{
+			loc = l;
+		}
+
+		protected override bool IsLocalExit {
+			get {
+				return false;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			throw new NotSupportedException ();
+		}
+
+		protected override bool DoResolve (BlockContext bc)
+		{
+			iterator = bc.CurrentIterator;
+			return Yield.CheckContext (bc, loc);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			iterator.EmitYieldBreak (ec, unwind_protect);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Reachability.CreateUnreachable ();
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public abstract class StateMachine : AnonymousMethodStorey
+	{
+		public enum State
+		{
+			Running = -3, // Used only in CurrentPC, never stored into $PC
+			Uninitialized = -2,
+			After = -1,
+			Start = 0
+		}
+
+		Field pc_field;
+		StateMachineMethod method;
+		int local_name_idx;
+
+		protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
+			: base (block, parent, host, tparams, name, kind)
+		{
+			OriginalTypeParameters = tparams;
+		}
+
+		#region Properties
+
+		public TypeParameters OriginalTypeParameters { get; private set; }
+
+		public StateMachineMethod StateMachineMethod {
+			get {
+				return method;
+			}
+		}
+
+		public Field PC {
+			get {
+				return pc_field;
+			}
+		}
+
+		#endregion
+
+		public void AddEntryMethod (StateMachineMethod method)
+		{
+			if (this.method != null)
+				throw new InternalErrorException ();
+
+			this.method = method;
+			Members.Add (method);
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
+
+			return base.DoDefineMembers ();
+		}
+
+		protected override string GetVariableMangledName (LocalVariable local_info)
+		{
+			if (local_info.IsCompilerGenerated)
+				return base.GetVariableMangledName (local_info);
+
+			return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
+		}
+	}
+
+	class IteratorStorey : StateMachine
+	{
+		class GetEnumeratorMethod : StateMachineMethod
+		{
+			sealed class GetEnumeratorStatement : Statement
+			{
+				readonly IteratorStorey host;
+				readonly StateMachineMethod host_method;
+
+				Expression new_storey;
+
+				public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
+				{
+					this.host = host;
+					this.host_method = host_method;
+					loc = host_method.Location;
+				}
+
+				protected override void CloneTo (CloneContext clonectx, Statement target)
+				{
+					throw new NotSupportedException ();
+				}
+
+				public override bool Resolve (BlockContext ec)
+				{
+					TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
+					List<Expression> init = null;
+					if (host.hoisted_this != null) {
+						init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
+						HoistedThis ht = host.hoisted_this;
+						FieldExpr from = new FieldExpr (ht.Field, loc);
+						from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
+						init.Add (new ElementInitializer (ht.Field.Name, from, loc));
+					}
+
+					if (host.hoisted_params != null) {
+						if (init == null)
+							init = new List<Expression> (host.HoistedParameters.Count);
+
+						for (int i = 0; i < host.hoisted_params.Count; ++i) {
+							HoistedParameter hp = host.hoisted_params [i];
+							HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
+
+							FieldExpr from = new FieldExpr (hp_cp.Field, loc);
+							from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
+
+							init.Add (new ElementInitializer (hp.Field.Name, from, loc));
+						}
+					}
+
+					if (init != null) {
+						new_storey = new NewInitialize (storey_type_expr, null,
+							new CollectionOrObjectInitializers (init, loc), loc);
+					} else {
+						new_storey = new New (storey_type_expr, null, loc);
+					}
+
+					new_storey = new_storey.Resolve (ec);
+					if (new_storey != null)
+						new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
+
+					return true;
+				}
+
+				protected override void DoEmit (EmitContext ec)
+				{
+					Label label_init = ec.DefineLabel ();
+
+					ec.EmitThis ();
+					ec.Emit (OpCodes.Ldflda, host.PC.Spec);
+					ec.EmitInt ((int) State.Start);
+					ec.EmitInt ((int) State.Uninitialized);
+
+					var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
+					if (m != null)
+						ec.Emit (OpCodes.Call, m);
+
+					ec.EmitInt ((int) State.Uninitialized);
+					ec.Emit (OpCodes.Bne_Un_S, label_init);
+
+					ec.EmitThis ();
+					ec.Emit (OpCodes.Ret);
+
+					ec.MarkLabel (label_init);
+
+					new_storey.Emit (ec);
+					ec.Emit (OpCodes.Ret);
+				}
+
+				protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+				{
+					throw new NotImplementedException ();
+				}
+
+				public override Reachability MarkReachable (Reachability rc)
+				{
+					base.MarkReachable (rc);
+					return Reachability.CreateUnreachable ();
+				}
+			}
+
+			GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
+				: base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name, ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
+			{
+			}
+
+			public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
+			{
+				return Create (host, returnType, name, null);
+			}
+
+			public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
+			{
+				var m = new GetEnumeratorMethod (host, returnType, name);
+				var stmt = statement ?? new GetEnumeratorStatement (host, m);
+				m.block.AddStatement (stmt);
+				return m;
+			}
+		}
+
+		class DisposeMethod : StateMachineMethod
+		{
+			sealed class DisposeMethodStatement : Statement
+			{
+				Iterator iterator;
+
+				public DisposeMethodStatement (Iterator iterator)
+				{
+					this.iterator = iterator;
+					this.loc = iterator.Location;
+				}
+
+				protected override void CloneTo (CloneContext clonectx, Statement target)
+				{
+					throw new NotSupportedException ();
+				}
+
+				public override bool Resolve (BlockContext ec)
+				{
+					return true;
+				}
+
+				protected override void DoEmit (EmitContext ec)
+				{
+					ec.CurrentAnonymousMethod = iterator;
+					iterator.EmitDispose (ec);
+				}
+
+				protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+				{
+					throw new NotImplementedException ();
+				}
+			}
+
+			public DisposeMethod (IteratorStorey host)
+				: base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
+					new MemberName ("Dispose", host.Location), ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis)
+			{
+				host.Members.Add (this);
+
+				Block.AddStatement (new DisposeMethodStatement (host.Iterator));
+			}
+		}
+
+		//
+		// Uses Method as method info
+		//
+		class DynamicMethodGroupExpr : MethodGroupExpr
+		{
+			readonly Method method;
+
+			public DynamicMethodGroupExpr (Method method, Location loc)
+				: base ((IList<MemberSpec>) null, null, loc)
+			{
+				this.method = method;
+				eclass = ExprClass.Unresolved;
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				Methods = new List<MemberSpec> (1) { method.Spec };
+				type = method.Parent.Definition;
+				InstanceExpression = new CompilerGeneratedThis (type, Location);
+				return base.DoResolve (ec);
+			}
+		}
+
+		class DynamicFieldExpr : FieldExpr
+		{
+			readonly Field field;
+
+			public DynamicFieldExpr (Field field, Location loc)
+				: base (loc)
+			{
+				this.field = field;
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				spec = field.Spec;
+				type = spec.MemberType;
+				InstanceExpression = new CompilerGeneratedThis (type, Location);
+				return base.DoResolve (ec);
+			}
+		}
+
+		public readonly Iterator Iterator;
+
+		List<HoistedParameter> hoisted_params_copy;
+
+		TypeExpr iterator_type_expr;
+		Field current_field;
+		Field disposing_field;
+
+		TypeSpec generic_enumerator_type;
+		TypeSpec generic_enumerable_type;
+
+		public IteratorStorey (Iterator iterator)
+			: base (iterator.Container.ParametersBlock, iterator.Host,
+			  iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
+		{
+			this.Iterator = iterator;
+		}
+
+		public Field CurrentField {
+			get {
+				return current_field;
+			}
+		}
+
+		public Field DisposingField {
+			get {
+				return disposing_field;
+			}
+		}
+
+		public IList<HoistedParameter> HoistedParameters {
+			get { return hoisted_params; }
+		}
+
+		protected override Constructor DefineDefaultConstructor (bool is_static)
+		{
+			var ctor = base.DefineDefaultConstructor (is_static);
+			ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+			return ctor;
+		}
+
+		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
+		{
+			var mtype = Iterator.OriginalIteratorType;
+			if (Mutator != null)
+				mtype = Mutator.Mutate (mtype);
+
+			iterator_type_expr = new TypeExpression (mtype, Location);
+
+			var ifaces = new List<TypeSpec> (5);
+			if (Iterator.IsEnumerable) {
+				ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
+
+				if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
+					generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
+					ifaces.Add (generic_enumerable_type);
+				}
+			}
+
+			ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
+			ifaces.Add (Compiler.BuiltinTypes.IDisposable);
+
+			var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
+			if (ienumerator_generic.Define ()) {
+				generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
+				ifaces.Add (generic_enumerator_type);
+			}
+
+			base_class = null;
+
+			base_type = Compiler.BuiltinTypes.Object;
+			return ifaces.ToArray ();
+		}
+
+		protected override bool DoDefineMembers ()
+		{
+			current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
+			disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
+
+			if (Iterator.IsEnumerable && hoisted_params != null) {
+				//
+				// Iterators are independent, each GetEnumerator call has to
+				// create same enumerator therefore we have to keep original values
+				// around for re-initialization
+				//
+				hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
+				foreach (HoistedParameter hp in hoisted_params) {
+
+					//
+					// Don't create field copy for unmodified captured parameters
+ 					//
+					HoistedParameter hp_copy;
+					if (hp.IsAssigned) {
+						hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
+					} else {
+						hp_copy = null;
+					}
+
+					hoisted_params_copy.Add (hp_copy);
+				}
+			}
+
+			if (generic_enumerator_type != null)
+				Define_Current (true);
+
+			Define_Current (false);
+			new DisposeMethod (this);
+			Define_Reset ();
+
+			if (Iterator.IsEnumerable) {
+				FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
+				var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
+
+				if (generic_enumerator_type != null) {
+					explicit_iface = new TypeExpression (generic_enumerable_type, Location);
+					var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
+					Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
+
+					//
+					// Just call generic GetEnumerator implementation
+					//
+					var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
+					Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
+
+					Members.Add (get_enumerator);
+					Members.Add (gget_enumerator);
+				} else {
+					Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
+				}
+			}
+
+			return base.DoDefineMembers ();
+		}
+
+		void Define_Current (bool is_generic)
+		{
+			TypeExpr type;
+			FullNamedExpression explicit_iface;
+
+			if (is_generic) {
+				explicit_iface = new TypeExpression (generic_enumerator_type, Location);
+				type = iterator_type_expr;
+			} else {
+				explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
+				type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
+			}
+
+			var name = new MemberName ("Current", null, explicit_iface, Location);
+
+			ToplevelBlock get_block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location,
+				Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
+			get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
+				
+			Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
+			current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
+			current.Get.Block = get_block;
+
+			Members.Add (current);
+		}
+
+		void Define_Reset ()
+		{
+			Method reset = new Method (
+				this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
+				Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
+				new MemberName ("Reset", Location),
+				ParametersCompiled.EmptyReadOnlyParameters, null);
+			Members.Add (reset);
+
+			reset.Block = new ToplevelBlock (Compiler, reset.ParameterInfo, Location,
+				Block.Flags.CompilerGenerated | Block.Flags.NoFlowAnalysis);
+
+			TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
+			if (ex_type == null)
+				return;
+
+			reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
+		}
+
+		protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
+		{
+			base.EmitHoistedParameters (ec, hoisted);
+			if (hoisted_params_copy != null)
+				base.EmitHoistedParameters (ec, hoisted_params_copy);
+		}
+	}
+
+	public class StateMachineMethod : Method
+	{
+		readonly StateMachineInitializer expr;
+
+		public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType,
+			Modifiers mod, MemberName name, ToplevelBlock.Flags blockFlags)
+			: base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
+			  name, ParametersCompiled.EmptyReadOnlyParameters, null)
+		{
+			this.expr = expr;
+			Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null, blockFlags);
+		}
+
+		public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
+		{
+			EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
+			ec.CurrentAnonymousMethod = expr;
+
+			if (expr is AsyncInitializer)
+				ec.With (BuilderContext.Options.AsyncBody, true);
+
+			return ec;
+		}
+	}
+
+	public abstract class StateMachineInitializer : AnonymousExpression
+	{
+		sealed class MoveNextBodyStatement : Statement
+		{
+			readonly StateMachineInitializer state_machine;
+
+			public MoveNextBodyStatement (StateMachineInitializer stateMachine)
+			{
+				this.state_machine = stateMachine;
+				this.loc = stateMachine.Location;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+				throw new NotSupportedException ();
+			}
+
+			public override bool Resolve (BlockContext ec)
+			{
+				return true;
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				state_machine.EmitMoveNext (ec);
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				// Don't create sequence point
+				DoEmit (ec);
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				return state_machine.ReturnType.Kind != MemberKind.Void;
+			}
+
+			public override Reachability MarkReachable (Reachability rc)
+			{
+				base.MarkReachable (rc);
+
+				if (state_machine.ReturnType.Kind != MemberKind.Void)
+					rc = Reachability.CreateUnreachable ();
+
+				return rc;
+			}
+		}
+
+		public readonly TypeDefinition Host;
+		protected StateMachine storey;
+
+		//
+		// The state as we generate the machine
+		//
+		protected Label move_next_ok;
+		protected Label move_next_error;
+		LocalBuilder skip_finally;
+		protected LocalBuilder current_pc;
+		protected List<ResumableStatement> resume_points;
+
+		protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
+			: base (block, returnType, block.StartLocation)
+		{
+			this.Host = host;
+		}
+
+		#region Properties
+
+		public Label BodyEnd { get; set; }
+
+		public LocalBuilder CurrentPC
+		{
+			get {
+				return current_pc;
+			}
+		}
+
+		public LocalBuilder SkipFinally {
+			get {
+				return skip_finally;
+			}
+		}
+
+		public override AnonymousMethodStorey Storey {
+			get {
+				return storey;
+			}
+		}
+
+		#endregion
+
+		public int AddResumePoint (ResumableStatement stmt)
+		{
+			if (resume_points == null)
+				resume_points = new List<ResumableStatement> ();
+
+			resume_points.Add (stmt);
+			return resume_points.Count;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		protected virtual BlockContext CreateBlockContext (BlockContext bc)
+		{
+			var ctx = new BlockContext (bc, block, bc.ReturnType);
+			ctx.CurrentAnonymousMethod = this;
+
+			ctx.AssignmentInfoOffset = bc.AssignmentInfoOffset;
+			ctx.EnclosingLoop = bc.EnclosingLoop;
+			ctx.EnclosingLoopOrSwitch = bc.EnclosingLoopOrSwitch;
+			ctx.Switch = bc.Switch;
+
+			return ctx;
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			var bc = (BlockContext) rc;
+			var ctx = CreateBlockContext (bc);
+
+			Block.Resolve (ctx);
+
+			if (!rc.IsInProbingMode) {
+				var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc), 0);
+				move_next.Block.AddStatement (new MoveNextBodyStatement (this));
+				storey.AddEntryMethod (move_next);
+			}
+
+			bc.AssignmentInfoOffset = ctx.AssignmentInfoOffset;
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// Load state machine instance
+			//
+			storey.Instance.Emit (ec);
+		}
+
+		void EmitMoveNext_NoResumePoints (EmitContext ec)
+		{
+			ec.EmitThis ();
+			ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
+
+			ec.EmitThis ();
+			ec.EmitInt ((int) IteratorStorey.State.After);
+			ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+			// We only care if the PC is zero (start executing) or non-zero (don't do anything)
+			ec.Emit (OpCodes.Brtrue, move_next_error);
+
+			BodyEnd = ec.DefineLabel ();
+
+			var async_init = this as AsyncInitializer;
+			if (async_init != null)
+				ec.BeginExceptionBlock ();
+
+			block.EmitEmbedded (ec);
+
+			if (async_init != null)
+				async_init.EmitCatchBlock (ec);
+
+			ec.MarkLabel (BodyEnd);
+
+			EmitMoveNextEpilogue (ec);
+
+			ec.MarkLabel (move_next_error);
+
+			if (ReturnType.Kind != MemberKind.Void) {
+				ec.EmitInt (0);
+				ec.Emit (OpCodes.Ret);
+			}
+
+			ec.MarkLabel (move_next_ok);
+		}
+
+		void EmitMoveNext (EmitContext ec)
+		{
+			move_next_ok = ec.DefineLabel ();
+			move_next_error = ec.DefineLabel ();
+
+			if (resume_points == null) {
+				EmitMoveNext_NoResumePoints (ec);
+				return;
+			}
+			
+			current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
+			ec.EmitThis ();
+			ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
+			ec.Emit (OpCodes.Stloc, current_pc);
+
+			// We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
+			ec.EmitThis ();
+			ec.EmitInt ((int) IteratorStorey.State.After);
+			ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+			Label[] labels = new Label[1 + resume_points.Count];
+			labels[0] = ec.DefineLabel ();
+
+			bool need_skip_finally = false;
+			for (int i = 0; i < resume_points.Count; ++i) {
+				ResumableStatement s = resume_points[i];
+				need_skip_finally |= s is ExceptionStatement;
+				labels[i + 1] = s.PrepareForEmit (ec);
+			}
+
+			if (need_skip_finally) {
+				skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
+				ec.EmitInt (0);
+				ec.Emit (OpCodes.Stloc, skip_finally);
+			}
+
+			var async_init = this as AsyncInitializer;
+			if (async_init != null)
+				ec.BeginExceptionBlock ();
+
+			ec.Emit (OpCodes.Ldloc, current_pc);
+			ec.Emit (OpCodes.Switch, labels);
+
+			ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
+
+			ec.MarkLabel (labels[0]);
+
+			BodyEnd = ec.DefineLabel ();
+
+			block.EmitEmbedded (ec);
+
+			ec.MarkLabel (BodyEnd);
+
+			if (async_init != null) {
+				async_init.EmitCatchBlock (ec);
+			}
+
+			ec.Mark (Block.Original.EndLocation);
+			ec.EmitThis ();
+			ec.EmitInt ((int) IteratorStorey.State.After);
+			ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+			EmitMoveNextEpilogue (ec);
+
+			ec.MarkLabel (move_next_error);
+			
+			if (ReturnType.Kind != MemberKind.Void) {
+				ec.EmitInt (0);
+				ec.Emit (OpCodes.Ret);
+			}
+
+			ec.MarkLabel (move_next_ok);
+
+			if (ReturnType.Kind != MemberKind.Void) {
+				ec.EmitInt (1);
+				ec.Emit (OpCodes.Ret);
+			}
+		}
+
+		protected virtual void EmitMoveNextEpilogue (EmitContext ec)
+		{
+		}
+
+		public void EmitLeave (EmitContext ec, bool unwind_protect)
+		{
+			// Return ok
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
+		}
+
+		//
+		// Called back from YieldStatement
+		//
+		public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
+		{
+			//
+			// Guard against being disposed meantime
+			//
+			Label disposed = ec.DefineLabel ();
+			var iterator = storey as IteratorStorey;
+			if (iterator != null) {
+				ec.EmitThis ();
+				ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
+				ec.Emit (OpCodes.Brtrue_S, disposed);
+			}
+
+			//
+			// store resume program-counter
+			//
+			ec.EmitThis ();
+			ec.EmitInt (resume_pc);
+			ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+			if (iterator != null) {
+				ec.MarkLabel (disposed);
+			}
+
+			// mark finally blocks as disabled
+			if (unwind_protect && skip_finally != null) {
+				ec.EmitInt (1);
+				ec.Emit (OpCodes.Stloc, skip_finally);
+			}
+		}
+
+		public void SetStateMachine (StateMachine stateMachine)
+		{
+			this.storey = stateMachine;
+		}
+	}
+
+	//
+	// Iterators are implemented as state machine blocks
+	//
+	public class Iterator : StateMachineInitializer
+	{
+		sealed class TryFinallyBlockProxyStatement : Statement
+		{
+			TryFinallyBlock block;
+			Iterator iterator;
+
+			public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
+			{
+				this.iterator = iterator;
+				this.block = block;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+				throw new NotSupportedException ();
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				throw new NotSupportedException ();
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				//
+				// Restore redirection for any captured variables
+				//
+				ec.CurrentAnonymousMethod = iterator;
+
+				using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
+					block.EmitFinallyBody (ec);
+				}
+			}
+		}
+
+		public readonly IMethodData OriginalMethod;
+		public readonly bool IsEnumerable;
+		public readonly TypeSpec OriginalIteratorType;
+		int finally_hosts_counter;
+
+		public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
+			: base (block, host, host.Compiler.BuiltinTypes.Bool)
+		{
+			this.OriginalMethod = method;
+			this.OriginalIteratorType = iterator_type;
+			this.IsEnumerable = is_enumerable;
+			this.type = method.ReturnType;
+		}
+
+		#region Properties
+
+		public ToplevelBlock Container {
+			get { return OriginalMethod.Block; }
+		}
+
+		public override string ContainerType {
+			get { return "iterator"; }
+		}
+
+		public override bool IsIterator {
+			get { return true; }
+		}
+
+		#endregion
+
+		public Method CreateFinallyHost (TryFinallyBlock block)
+		{
+			var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
+				Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
+				ParametersCompiled.EmptyReadOnlyParameters, null);
+
+			method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc,
+				ToplevelBlock.Flags.CompilerGenerated | ToplevelBlock.Flags.NoFlowAnalysis);
+			method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
+
+			// Cannot it add to storey because it'd be emitted before nested
+			// anonoymous methods which could capture shared variable
+
+			return method;
+		}
+
+		public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
+		{
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return OriginalMethod.GetSignatureForError ();
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// Load Iterator storey instance
+			//
+			storey.Instance.Emit (ec);
+
+			//
+			// Initialize iterator PC when it's unitialized
+			//
+			if (IsEnumerable) {
+				ec.Emit (OpCodes.Dup);
+				ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
+
+				var field = storey.PC.Spec;
+				if (storey.MemberName.IsGeneric) {
+					field = MemberCache.GetMember (Storey.Instance.Type, field);
+				}
+
+				ec.Emit (OpCodes.Stfld, field);
+			}
+		}
+
+		public void EmitDispose (EmitContext ec)
+		{
+			if (resume_points == null)
+				return;
+
+			Label end = ec.DefineLabel ();
+
+			Label[] labels = null;
+			for (int i = 0; i < resume_points.Count; ++i) {
+				ResumableStatement s = resume_points[i];
+				Label ret = s.PrepareForDispose (ec, end);
+				if (ret.Equals (end) && labels == null)
+					continue;
+				if (labels == null) {
+					labels = new Label[resume_points.Count + 1];
+					for (int j = 0; j <= i; ++j)
+						labels[j] = end;
+				}
+
+				labels[i + 1] = ret;
+			}
+
+			if (labels != null) {
+				current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
+				ec.EmitThis ();
+				ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
+				ec.Emit (OpCodes.Stloc, current_pc);
+			}
+
+			ec.EmitThis ();
+			ec.EmitInt (1);
+			ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
+
+			ec.EmitThis ();
+			ec.EmitInt ((int) IteratorStorey.State.After);
+			ec.Emit (OpCodes.Stfld, storey.PC.Spec);
+
+			if (labels != null) {
+				//SymbolWriter.StartIteratorDispatcher (ec.ig);
+				ec.Emit (OpCodes.Ldloc, current_pc);
+				ec.Emit (OpCodes.Switch, labels);
+				//SymbolWriter.EndIteratorDispatcher (ec.ig);
+
+				foreach (ResumableStatement s in resume_points)
+					s.EmitForDispose (ec, current_pc, end, true);
+			}
+
+			ec.MarkLabel (end);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
+		{
+			// Store the new value into current
+			var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
+			fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
+			fe.EmitAssign (ec, expr, false, false);
+
+			base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
+
+			EmitLeave (ec, unwind_protect);
+
+			ec.MarkLabel (resume_point);
+		}
+
+		public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
+		{
+			bool is_enumerable;
+			TypeSpec iterator_type;
+
+			TypeSpec ret = method.ReturnType;
+			if (ret == null)
+				return;
+
+			if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
+				parent.Compiler.Report.Error (1624, method.Location,
+					      "The body of `{0}' cannot be an iterator block " +
+					      "because `{1}' is not an iterator interface type",
+					      method.GetSignatureForError (),
+					      ret.GetSignatureForError ());
+				return;
+			}
+
+			ParametersCompiled parameters = method.ParameterInfo;
+			for (int i = 0; i < parameters.Count; i++) {
+				Parameter p = parameters [i];
+				Parameter.Modifier mod = p.ModFlags;
+				if ((mod & Parameter.Modifier.RefOutMask) != 0) {
+					parent.Compiler.Report.Error (1623, p.Location,
+						"Iterators cannot have ref or out parameters");
+					return;
+				}
+
+				if (p is ArglistParameter) {
+					parent.Compiler.Report.Error (1636, method.Location,
+						"__arglist is not allowed in parameter list of iterators");
+					return;
+				}
+
+				if (parameters.Types [i].IsPointer) {
+					parent.Compiler.Report.Error (1637, p.Location,
+						"Iterators cannot have unsafe parameters or yield types");
+					return;
+				}
+			}
+
+			if ((modifiers & Modifiers.UNSAFE) != 0) {
+				parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
+			}
+
+			method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
+		}
+
+		static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
+		{
+			original_iterator_type = null;
+			is_enumerable = false;
+
+			if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
+				original_iterator_type = parent.Compiler.BuiltinTypes.Object;
+				is_enumerable = true;
+				return true;
+			}
+			if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
+				original_iterator_type = parent.Compiler.BuiltinTypes.Object;
+				is_enumerable = false;
+				return true;
+			}
+
+			InflatedTypeSpec inflated = ret as InflatedTypeSpec;
+			if (inflated == null)
+				return false;
+
+			var member_definition = inflated.MemberDefinition;
+			PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
+
+			if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
+				original_iterator_type = inflated.TypeArguments[0];
+				is_enumerable = true;
+				return true;
+			}
+
+			ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
+			if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
+				original_iterator_type = inflated.TypeArguments[0];
+				is_enumerable = false;
+				return true;
+			}
+
+			return false;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/lambda.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/lambda.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/lambda.cs	(revision 11807)
@@ -0,0 +1,229 @@
+//
+// lambda.cs: support for lambda expressions
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2007-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+	public class LambdaExpression : AnonymousMethodExpression
+	{
+		//
+		// The parameters can either be:
+		//    A list of Parameters (explicitly typed parameters)
+		//    An ImplicitLambdaParameter
+		//
+		public LambdaExpression (Location loc)
+			: base (loc)
+		{
+		}
+
+		protected override Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
+		{
+			if (ec.IsInProbingMode)
+				return this;
+
+			BlockContext bc = new BlockContext (ec.MemberContext, ec.ConstructorBlock, ec.BuiltinTypes.Void) {
+				CurrentAnonymousMethod = ec.CurrentAnonymousMethod
+			};
+
+			Expression args = Parameters.CreateExpressionTree (bc, loc);
+			Expression expr = Block.CreateExpressionTree (ec);
+			if (expr == null)
+				return null;
+
+			Arguments arguments = new Arguments (2);
+			arguments.Add (new Argument (expr));
+			arguments.Add (new Argument (args));
+			return CreateExpressionFactoryCall (ec, "Lambda",
+				new TypeArguments (new TypeExpression (delegate_type, loc)),
+				arguments);
+		}
+
+		public override bool HasExplicitParameters {
+			get {
+				return Parameters.Count > 0 && !(Parameters.FixedParameters [0] is ImplicitLambdaParameter);
+			}
+		}
+
+		protected override ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegateType)
+		{
+			if (!delegateType.IsDelegate)
+				return null;
+
+			AParametersCollection d_params = Delegate.GetParameters (delegateType);
+
+			if (HasExplicitParameters) {
+				if (!VerifyExplicitParameters (ec, tic, delegateType, d_params))
+					return null;
+
+				return Parameters;
+			}
+
+			//
+			// If L has an implicitly typed parameter list we make implicit parameters explicit
+			// Set each parameter of L is given the type of the corresponding parameter in D
+			//
+			if (!VerifyParameterCompatibility (ec, tic, delegateType, d_params, ec.IsInProbingMode))
+				return null;
+
+			TypeSpec [] ptypes = new TypeSpec [Parameters.Count];
+			for (int i = 0; i < d_params.Count; i++) {
+				// D has no ref or out parameters
+				if ((d_params.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != 0)
+					return null;
+
+				TypeSpec d_param = d_params.Types [i];
+
+				//
+				// When type inference context exists try to apply inferred type arguments
+				//
+				if (tic != null) {
+					d_param = tic.InflateGenericArgument (ec, d_param);
+				}
+
+				ptypes [i] = d_param;
+				ImplicitLambdaParameter ilp = (ImplicitLambdaParameter) Parameters.FixedParameters [i];
+				ilp.SetParameterType (d_param);
+				ilp.Resolve (null, i);
+			}
+
+			Parameters.Types = ptypes;
+			return Parameters;
+		}
+
+		protected override AnonymousMethodBody CompatibleMethodFactory (TypeSpec returnType, TypeSpec delegateType, ParametersCompiled p, ParametersBlock b)
+		{
+			return new LambdaMethod (p, b, returnType, delegateType, loc);
+		}
+
+		protected override bool DoResolveParameters (ResolveContext rc)
+		{
+			//
+			// Only explicit parameters can be resolved at this point
+			//
+			if (HasExplicitParameters) {
+				return Parameters.Resolve (rc);
+			}
+
+			return true;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return "lambda expression";
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	class LambdaMethod : AnonymousMethodBody
+	{
+		public LambdaMethod (ParametersCompiled parameters,
+					ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
+					Location loc)
+			: base (parameters, block, return_type, delegate_type, loc)
+		{
+		}
+
+		#region Properties
+
+		public override string ContainerType {
+			get {
+				return "lambda expression";
+			}
+		}
+
+		#endregion
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			// TODO: nothing ??
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			BlockContext bc = new BlockContext (ec.MemberContext, Block, ReturnType);
+			Expression args = parameters.CreateExpressionTree (bc, loc);
+			Expression expr = Block.CreateExpressionTree (ec);
+			if (expr == null)
+				return null;
+
+			Arguments arguments = new Arguments (2);
+			arguments.Add (new Argument (expr));
+			arguments.Add (new Argument (args));
+			return CreateExpressionFactoryCall (ec, "Lambda",
+				new TypeArguments (new TypeExpression (type, loc)),
+				arguments);
+		}
+	}
+
+	//
+	// This is a return statement that is prepended lambda expression bodies that happen
+	// to be expressions.  Depending on the return type of the delegate this will behave
+	// as either { expr (); return (); } or { return expr (); }
+	//
+	public class ContextualReturn : Return
+	{
+		ExpressionStatement statement;
+
+		public ContextualReturn (Expression expr)
+			: base (expr, expr.StartLocation)
+		{
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return Expr.CreateExpressionTree (ec);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (statement != null) {
+				statement.EmitStatement (ec);
+				if (unwind_protect)
+					ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ());
+				else {
+					ec.Emit (OpCodes.Ret);
+				}
+				return;
+			}
+
+			base.DoEmit (ec);
+		}
+
+		protected override bool DoResolve (BlockContext ec)
+		{
+			//
+			// When delegate returns void, only expression statements can be used
+			//
+			if (ec.ReturnType.Kind == MemberKind.Void) {
+				Expr = Expr.Resolve (ec);
+				if (Expr == null)
+					return false;
+
+				statement = Expr as ExpressionStatement;
+				if (statement == null)
+					Expr.Error_InvalidExpressionStatement (ec);
+
+				return true;
+			}
+
+			return base.DoResolve (ec);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/linq.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/linq.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/linq.cs	(revision 11807)
@@ -0,0 +1,904 @@
+//
+// linq.cs: support for query expressions
+//
+// Authors: Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2007-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+
+namespace Mono.CSharp.Linq
+{
+	public class QueryExpression : AQueryClause
+	{
+		public QueryExpression (AQueryClause start)
+			: base (null, null, start.Location)
+		{
+			this.next = start;
+		}
+
+		public override Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parentParameter)
+		{
+			return next.BuildQueryClause (ec, lSide, parentParameter);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			int counter = QueryBlock.TransparentParameter.Counter;
+
+			Expression e = BuildQueryClause (ec, null, null);
+			if (e != null)
+				e = e.Resolve (ec);
+
+			//
+			// Reset counter in probing mode to ensure that all transparent
+			// identifier anonymous types are created only once
+			//
+			if (ec.IsInProbingMode)
+				QueryBlock.TransparentParameter.Counter = counter;
+
+			return e;
+		}
+
+		protected override string MethodName {
+			get { throw new NotSupportedException (); }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public abstract class AQueryClause : ShimExpression
+	{
+		protected class QueryExpressionAccess : MemberAccess
+		{
+			public QueryExpressionAccess (Expression expr, string methodName, Location loc)
+				: base (expr, methodName, loc)
+			{
+			}
+
+			public QueryExpressionAccess (Expression expr, string methodName, TypeArguments typeArguments, Location loc)
+				: base (expr, methodName, typeArguments, loc)
+			{
+			}
+
+			protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
+			{
+				ec.Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " +
+					"Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?",
+					name);
+			}
+		}
+
+		protected class QueryExpressionInvocation : Invocation, OverloadResolver.IErrorHandler
+		{
+			public QueryExpressionInvocation (QueryExpressionAccess expr, Arguments arguments)
+				: base (expr, arguments)
+			{
+			}
+
+			protected override MethodGroupExpr DoResolveOverload (ResolveContext ec)
+			{
+				MethodGroupExpr rmg = mg.OverloadResolve (ec, ref arguments, this, OverloadResolver.Restrictions.None);
+				return rmg;
+			}
+
+			protected override Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
+			{
+				ec.Report.Error (1979, loc,
+					"Query expressions with a source or join sequence of type `dynamic' are not allowed");
+				return null;
+			}
+
+			#region IErrorHandler Members
+
+			bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
+			{
+				ec.Report.SymbolRelatedToPreviousError (best);
+				ec.Report.SymbolRelatedToPreviousError (ambiguous);
+				ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'",
+					best.Name, mg.InstanceExpression.GetSignatureForError ());
+				return true;
+			}
+
+			bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
+			{
+				return false;
+			}
+
+			bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
+			{
+				return false;
+			}
+
+			bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
+			{
+				var ms = (MethodSpec) best;
+				TypeSpec source_type = ms.Parameters.ExtensionMethodType;
+				if (source_type != null) {
+					Argument a = arguments[0];
+
+					if (TypeManager.IsGenericType (source_type) && InflatedTypeSpec.ContainsTypeParameter (source_type)) {
+						TypeInferenceContext tic = new TypeInferenceContext (source_type.TypeArguments);
+						tic.OutputTypeInference (rc, a.Expr, source_type);
+						if (tic.FixAllTypes (rc)) {
+							source_type = source_type.GetDefinition ().MakeGenericType (rc, tic.InferredTypeArguments);
+						}
+					}
+
+					if (!Convert.ImplicitConversionExists (rc, a.Expr, source_type)) {
+						rc.Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found",
+							best.Name, a.Type.GetSignatureForError ());
+						return true;
+					}
+				}
+
+				if (best.Name == "SelectMany") {
+					rc.Report.Error (1943, loc,
+						"An expression type is incorrect in a subsequent `from' clause in a query expression with source type `{0}'",
+						arguments[0].GetSignatureForError ());
+				} else {
+					rc.Report.Error (1942, loc,
+						"An expression type in `{0}' clause is incorrect. Type inference failed in the call to `{1}'",
+						best.Name.ToLowerInvariant (), best.Name);
+				}
+
+				return true;
+			}
+
+			#endregion
+		}
+
+		public AQueryClause next;
+		public QueryBlock block;
+
+		protected AQueryClause (QueryBlock block, Expression expr, Location loc)
+			 : base (expr)
+		{
+			this.block = block;
+			this.loc = loc;
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			base.CloneTo (clonectx, target);
+
+			AQueryClause t = (AQueryClause) target;
+
+			if (block != null)
+				t.block = (QueryBlock) clonectx.LookupBlock (block);
+
+			if (next != null)
+				t.next = (AQueryClause) next.Clone (clonectx);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return expr.Resolve (ec);
+		}
+
+		public virtual Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parameter)
+		{
+			Arguments args = null;
+			CreateArguments (ec, parameter, ref args);
+			lSide = CreateQueryExpression (lSide, args);
+			if (next != null) {
+				parameter = CreateChildrenParameters (parameter);
+
+				Select s = next as Select;
+				if (s == null || s.IsRequired (parameter))
+					return next.BuildQueryClause (ec, lSide, parameter);
+					
+				// Skip transparent select clause if any clause follows
+				if (next.next != null)
+					return next.next.BuildQueryClause (ec, lSide, parameter);
+			}
+
+			return lSide;
+		}
+
+		protected virtual Parameter CreateChildrenParameters (Parameter parameter)
+		{
+			// Have to clone the parameter for any children use, it carries block sensitive data
+			return parameter.Clone ();
+		}
+
+		protected virtual void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
+		{
+			args = new Arguments (2);
+
+			LambdaExpression selector = new LambdaExpression (loc);
+
+			block.SetParameter (parameter);
+			selector.Block = block;
+			selector.Block.AddStatement (new ContextualReturn (expr));
+
+			args.Add (new Argument (selector));
+		}
+
+		protected Invocation CreateQueryExpression (Expression lSide, Arguments arguments)
+		{
+			return new QueryExpressionInvocation (
+				new QueryExpressionAccess (lSide, MethodName, loc), arguments);
+		}
+
+		protected abstract string MethodName { get; }
+
+		public AQueryClause Next {
+			set {
+				next = value;
+			}
+		}
+
+		public AQueryClause Tail {
+			get {
+				return next == null ? this : next.Tail;
+			}
+		}
+	}
+
+	//
+	// A query clause with an identifier (range variable)
+	//
+	public abstract class ARangeVariableQueryClause : AQueryClause
+	{
+		sealed class RangeAnonymousTypeParameter : AnonymousTypeParameter
+		{
+			public RangeAnonymousTypeParameter (Expression initializer, RangeVariable parameter)
+				: base (initializer, parameter.Name, parameter.Location)
+			{
+			}
+
+			protected override void Error_InvalidInitializer (ResolveContext ec, string initializer)
+			{
+				ec.Report.Error (1932, loc, "A range variable `{0}' cannot be initialized with `{1}'",
+					Name, initializer);
+			}
+		}
+
+		class RangeParameterReference : ParameterReference
+		{
+			Parameter parameter;
+
+			public RangeParameterReference (Parameter p)
+				: base (null, p.Location)
+			{
+				this.parameter = p;
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				pi = ec.CurrentBlock.ParametersBlock.GetParameterInfo (parameter);
+				return base.DoResolve (ec);
+			}
+		}
+
+		protected RangeVariable identifier;
+		
+		public RangeVariable  IntoVariable {
+			get {
+				return identifier;
+			}
+		}
+		
+		protected ARangeVariableQueryClause (QueryBlock block, RangeVariable identifier, Expression expr, Location loc)
+			: base (block, expr, loc)
+		{
+			this.identifier = identifier;
+		}
+
+		public RangeVariable Identifier {
+			get {
+				return identifier;
+			}
+		}
+
+		public FullNamedExpression IdentifierType { get; set; }
+
+		protected Invocation CreateCastExpression (Expression lSide)
+		{
+			return new QueryExpressionInvocation (
+				new QueryExpressionAccess (lSide, "Cast", new TypeArguments (IdentifierType), loc), null);
+		}
+
+		protected override Parameter CreateChildrenParameters (Parameter parameter)
+		{
+			return new QueryBlock.TransparentParameter (parameter.Clone (), GetIntoVariable ());
+		}
+
+		protected static Expression CreateRangeVariableType (ResolveContext rc, Parameter parameter, RangeVariable name, Expression init)
+		{
+			var args = new List<AnonymousTypeParameter> (2);
+
+			//
+			// The first argument is the reference to the parameter
+			//
+			args.Add (new AnonymousTypeParameter (new RangeParameterReference (parameter), parameter.Name, parameter.Location));
+
+			//
+			// The second argument is the linq expression
+			//
+			args.Add (new RangeAnonymousTypeParameter (init, name));
+
+			//
+			// Create unique anonymous type
+			//
+			return new NewAnonymousType (args, rc.MemberContext.CurrentMemberDefinition.Parent, name.Location);
+		}
+
+		protected virtual RangeVariable GetIntoVariable ()
+		{
+			return identifier;
+		}
+	}
+
+	public sealed class RangeVariable : INamedBlockVariable
+	{
+		Block block;
+
+		public RangeVariable (string name, Location loc)
+		{
+			Name = name;
+			Location = loc;
+		}
+
+		#region Properties
+
+		public Block Block {
+			get {
+				return block;
+			}
+			set {
+				block = value;
+			}
+		}
+
+		public bool IsDeclared {
+			get {
+				return true;
+			}
+		}
+
+		public bool IsParameter {
+			get {
+				return false;
+			}
+		}
+
+		public Location Location { get; private set; }
+
+		public string Name { get; private set; }
+
+		#endregion
+
+		public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
+		{
+			// 
+			// We know the variable name is somewhere in the scope. This generates
+			// an access expression from current block
+			//
+			var pb = rc.CurrentBlock.ParametersBlock;
+			while (true) {
+				if (pb is QueryBlock) {
+					for (int i = pb.Parameters.Count - 1; i >= 0; --i) {
+						var p = pb.Parameters[i];
+						if (p.Name == Name)
+							return pb.GetParameterReference (i, loc);
+
+						Expression expr = null;
+						var tp = p as QueryBlock.TransparentParameter;
+						while (tp != null) {
+							if (expr == null)
+								expr = pb.GetParameterReference (i, loc);
+							else
+								expr = new TransparentMemberAccess (expr, tp.Name);
+
+							if (tp.Identifier == Name)
+								return new TransparentMemberAccess (expr, Name);
+
+							if (tp.Parent.Name == Name)
+								return new TransparentMemberAccess (expr, Name);
+
+							tp = tp.Parent as QueryBlock.TransparentParameter;
+						}
+					}
+				}
+
+				if (pb == block)
+					return null;
+
+				pb = pb.Parent.ParametersBlock;
+			}
+		}
+	}
+
+	public class QueryStartClause : ARangeVariableQueryClause
+	{
+		public QueryStartClause (QueryBlock block, Expression expr, RangeVariable identifier, Location loc)
+			: base (block, identifier, expr, loc)
+		{
+			block.AddRangeVariable (identifier);
+		}
+
+		public override Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parameter)
+		{
+			if (IdentifierType != null)
+				expr = CreateCastExpression (expr);
+
+			if (parameter == null)
+				lSide = expr;
+
+			return next.BuildQueryClause (ec, lSide, new ImplicitLambdaParameter (identifier.Name, identifier.Location));
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			Expression e = BuildQueryClause (ec, null, null);
+			return e.Resolve (ec);
+		}
+
+		protected override string MethodName {
+			get { throw new NotSupportedException (); }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+
+	public class GroupBy : AQueryClause
+	{
+		Expression element_selector;
+		QueryBlock element_block;
+
+		public Expression ElementSelector {
+			get { return this.element_selector; }
+		}
+
+		public GroupBy (QueryBlock block, Expression elementSelector, QueryBlock elementBlock, Expression keySelector, Location loc)
+			: base (block, keySelector, loc)
+		{
+			//
+			// Optimizes clauses like `group A by A'
+			//
+			if (!elementSelector.Equals (keySelector)) {
+				this.element_selector = elementSelector;
+				this.element_block = elementBlock;
+			}
+		}
+
+		public Expression SelectorExpression {
+			get {
+ 				return element_selector;
+			}
+		}
+
+		protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
+		{
+			base.CreateArguments (ec, parameter, ref args);
+
+			if (element_selector != null) {
+				LambdaExpression lambda = new LambdaExpression (element_selector.Location);
+
+				element_block.SetParameter (parameter.Clone ());
+				lambda.Block = element_block;
+				lambda.Block.AddStatement (new ContextualReturn (element_selector));
+				args.Add (new Argument (lambda));
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			GroupBy t = (GroupBy) target;
+			if (element_selector != null) {
+				t.element_selector = element_selector.Clone (clonectx);
+				t.element_block = (QueryBlock) element_block.Clone (clonectx);
+			}
+
+			base.CloneTo (clonectx, t);
+		}
+
+		protected override string MethodName {
+			get { return "GroupBy"; }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Join : SelectMany
+	{
+		QueryBlock inner_selector, outer_selector;
+
+		public RangeVariable JoinVariable {
+			get { return this.GetIntoVariable (); }
+		}
+		
+		public Join (QueryBlock block, RangeVariable lt, Expression inner, QueryBlock outerSelector, QueryBlock innerSelector, Location loc)
+			: base (block, lt, inner, loc)
+		{
+			this.outer_selector = outerSelector;
+			this.inner_selector = innerSelector;
+		}
+
+		public QueryBlock InnerSelector {
+			get {
+				return inner_selector;
+			}
+		}
+		
+		public QueryBlock OuterSelector {
+			get {
+				return outer_selector;
+			}
+		}
+
+		protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
+		{
+			args = new Arguments (4);
+
+			if (IdentifierType != null)
+				expr = CreateCastExpression (expr);
+
+			args.Add (new Argument (expr));
+
+			outer_selector.SetParameter (parameter.Clone ());
+			var lambda = new LambdaExpression (outer_selector.StartLocation);
+			lambda.Block = outer_selector;
+			args.Add (new Argument (lambda));
+
+			inner_selector.SetParameter (new ImplicitLambdaParameter (identifier.Name, identifier.Location));
+			lambda = new LambdaExpression (inner_selector.StartLocation);
+			lambda.Block = inner_selector;
+			args.Add (new Argument (lambda));
+
+			base.CreateArguments (ec, parameter, ref args);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression target)
+		{
+			Join t = (Join) target;
+			t.inner_selector = (QueryBlock) inner_selector.Clone (clonectx);
+			t.outer_selector = (QueryBlock) outer_selector.Clone (clonectx);
+			base.CloneTo (clonectx, t);
+		}	
+
+		protected override string MethodName {
+			get { return "Join"; }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class GroupJoin : Join
+	{
+		readonly RangeVariable into;
+
+		public GroupJoin (QueryBlock block, RangeVariable lt, Expression inner,
+			QueryBlock outerSelector, QueryBlock innerSelector, RangeVariable into, Location loc)
+			: base (block, lt, inner, outerSelector, innerSelector, loc)
+		{
+			this.into = into;
+		}
+
+		protected override RangeVariable GetIntoVariable ()
+		{
+			return into;
+		}
+
+		protected override string MethodName {
+			get { return "GroupJoin"; }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Let : ARangeVariableQueryClause
+	{
+		public Let (QueryBlock block, RangeVariable identifier, Expression expr, Location loc)
+			: base (block, identifier, expr, loc)
+		{
+		}
+
+		protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
+		{
+			expr = CreateRangeVariableType (ec, parameter, identifier, expr);
+			base.CreateArguments (ec, parameter, ref args);
+		}
+
+		protected override string MethodName {
+			get { return "Select"; }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Select : AQueryClause
+	{
+		public Select (QueryBlock block, Expression expr, Location loc)
+			: base (block, expr, loc)
+		{
+		}
+		
+		//
+		// For queries like `from a orderby a select a'
+		// the projection is transparent and select clause can be safely removed 
+		//
+		public bool IsRequired (Parameter parameter)
+		{
+			SimpleName sn = expr as SimpleName;
+			if (sn == null)
+				return true;
+
+			return sn.Name != parameter.Name;
+		}
+
+		protected override string MethodName {
+			get { return "Select"; }
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+	}
+
+	public class SelectMany : ARangeVariableQueryClause
+	{
+		public SelectMany (QueryBlock block, RangeVariable identifier, Expression expr, Location loc)
+			: base (block, identifier, expr, loc)
+		{
+		}
+
+		protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
+		{
+			if (args == null) {
+				if (IdentifierType != null)
+					expr = CreateCastExpression (expr);
+
+				base.CreateArguments (ec, parameter.Clone (), ref args);
+			}
+
+			Expression result_selector_expr;
+			QueryBlock result_block;
+
+			var target = GetIntoVariable ();
+			var target_param = new ImplicitLambdaParameter (target.Name, target.Location);
+
+			//
+			// When select follows use it as a result selector
+			//
+			if (next is Select) {
+				result_selector_expr = next.Expr;
+
+				result_block = next.block;
+				result_block.SetParameters (parameter, target_param);
+
+				next = next.next;
+			} else {
+				result_selector_expr = CreateRangeVariableType (ec, parameter, target, new SimpleName (target.Name, target.Location));
+
+				result_block = new QueryBlock (block.Parent, block.StartLocation);
+				result_block.SetParameters (parameter, target_param);
+			}
+
+			LambdaExpression result_selector = new LambdaExpression (Location);
+			result_selector.Block = result_block;
+			result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr));
+
+			args.Add (new Argument (result_selector));
+		}
+
+		protected override string MethodName {
+			get { return "SelectMany"; }
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Where : AQueryClause
+	{
+		public Where (QueryBlock block, Expression expr, Location loc)
+			: base (block, expr, loc)
+		{
+		}
+
+		protected override string MethodName {
+			get { return "Where"; }
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class OrderByAscending : AQueryClause
+	{
+		public OrderByAscending (QueryBlock block, Expression expr)
+			: base (block, expr, expr.Location)
+		{
+		}
+
+		protected override string MethodName {
+			get { return "OrderBy"; }
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class OrderByDescending : AQueryClause
+	{
+		public OrderByDescending (QueryBlock block, Expression expr)
+			: base (block, expr, expr.Location)
+		{
+		}
+
+		protected override string MethodName {
+			get { return "OrderByDescending"; }
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ThenByAscending : OrderByAscending
+	{
+		public ThenByAscending (QueryBlock block, Expression expr)
+			: base (block, expr)
+		{
+		}
+
+		protected override string MethodName {
+			get { return "ThenBy"; }
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ThenByDescending : OrderByDescending
+	{
+		public ThenByDescending (QueryBlock block, Expression expr)
+			: base (block, expr)
+		{
+		}
+
+		protected override string MethodName {
+			get { return "ThenByDescending"; }
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// Implicit query block
+	//
+	public class QueryBlock : ParametersBlock
+	{
+		//
+		// Transparent parameters are used to package up the intermediate results
+		// and pass them onto next clause
+		//
+		public sealed class TransparentParameter : ImplicitLambdaParameter
+		{
+			public static int Counter;
+			const string ParameterNamePrefix = "<>__TranspIdent";
+
+			public readonly Parameter Parent;
+			public readonly string Identifier;
+
+			public TransparentParameter (Parameter parent, RangeVariable identifier)
+				: base (ParameterNamePrefix + Counter++, identifier.Location)
+			{
+				Parent = parent;
+				Identifier = identifier.Name;
+			}
+
+			public static void Reset ()
+			{
+				Counter = 0;
+			}
+		}
+
+		public QueryBlock (Block parent, Location start)
+			: base (parent, ParametersCompiled.EmptyReadOnlyParameters, start, Flags.CompilerGenerated)
+		{
+		}
+
+		public void AddRangeVariable (RangeVariable variable)
+		{
+			variable.Block = this;
+			TopBlock.AddLocalName (variable.Name, variable, true);
+		}
+
+		public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
+		{
+			TopBlock.Report.Error (1931, variable.Location,
+				"A range variable `{0}' conflicts with a previous declaration of `{0}'",
+				name);
+		}
+
+		public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable)
+		{
+			TopBlock.Report.Error (1930, variable.Location,
+				"A range variable `{0}' has already been declared in this scope",
+				name);		
+		}
+
+		public override void Error_AlreadyDeclaredTypeParameter (string name, Location loc)
+		{
+			TopBlock.Report.Error (1948, loc,
+				"A range variable `{0}' conflicts with a method type parameter",
+				name);
+		}
+
+		public void SetParameter (Parameter parameter)
+		{
+			base.parameters = new ParametersCompiled (parameter);
+			base.parameter_info = new ParameterInfo[] {
+				new ParameterInfo (this, 0)
+			};
+		}
+
+		public void SetParameters (Parameter first, Parameter second)
+		{
+			base.parameters = new ParametersCompiled (first, second);
+			base.parameter_info = new ParameterInfo[] {
+				new ParameterInfo (this, 0),
+				new ParameterInfo (this, 1)
+			};
+		}
+	}
+
+	sealed class TransparentMemberAccess : MemberAccess
+	{
+		public TransparentMemberAccess (Expression expr, string name)
+			: base (expr, name)
+		{
+		}
+
+		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
+		{
+			rc.Report.Error (1947, loc,
+				"A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
+				Name);
+
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/literal.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/literal.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/literal.cs	(revision 11807)
@@ -0,0 +1,333 @@
+//
+// literal.cs: Literal representation for the IL tree.
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@seznam.cz)
+//
+// Copyright 2001 Ximian, Inc.
+// Copyright 2011 Xamarin Inc
+//
+//
+// Notice that during parsing we create objects of type Literal, but the
+// types are not loaded (thats why the Resolve method has to assign the
+// type at that point).
+//
+// Literals differ from the constants in that we know we encountered them
+// as a literal in the source code (and some extra rules apply there) and
+// they have to be resolved (since during parsing we have not loaded the
+// types yet) while constants are created only after types have been loaded
+// and are fully resolved when born.
+//
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	public interface ILiteralConstant
+	{
+#if FULL_AST
+		char[] ParsedValue { get; set; }
+#endif
+	}
+
+	//
+	// The null literal
+	//
+	// Note: C# specification null-literal is NullLiteral of NullType type
+	//
+	public class NullLiteral : NullConstant
+	{
+		//
+		// Default type of null is an object
+		//
+		public NullLiteral (Location loc)
+			: base (InternalType.NullLiteral, loc)
+		{
+		}
+
+		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec t, bool expl)
+		{
+			if (t.IsGenericParameter) {
+				ec.Report.Error(403, loc,
+					"Cannot convert null to the type parameter `{0}' because it could be a value " +
+					"type. Consider using `default ({0})' instead", t.Name);
+				return;
+			}
+
+			if (TypeSpec.IsValueType (t)) {
+				ec.Report.Error(37, loc, "Cannot convert null to `{0}' because it is a value type",
+					t.GetSignatureForError ());
+				return;
+			}
+
+			base.Error_ValueCannotBeConverted (ec, t, expl);
+		}
+
+		public override string GetValueAsLiteral ()
+		{
+			return "null";
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+		public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
+		{
+			return System.Linq.Expressions.Expression.Constant (null);
+		}
+	}
+
+	public class BoolLiteral : BoolConstant, ILiteralConstant
+	{
+		public BoolLiteral (BuiltinTypes types, bool val, Location loc)
+			: base (types, val, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class CharLiteral : CharConstant, ILiteralConstant
+	{
+		public CharLiteral (BuiltinTypes types, char c, Location loc)
+			: base (types, c, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class IntLiteral : IntConstant, ILiteralConstant
+	{
+		public IntLiteral (BuiltinTypes types, int l, Location loc)
+			: base (types, l, loc)
+		{
+		}
+
+		public override Constant ConvertImplicitly (TypeSpec type)
+		{
+			//
+			// The 0 literal can be converted to an enum value
+			//
+			if (Value == 0 && type.IsEnum) {
+				Constant c = ConvertImplicitly (EnumSpec.GetUnderlyingType (type));
+				if (c == null)
+					return null;
+
+				return new EnumConstant (c, type);
+			}
+
+			return base.ConvertImplicitly (type);
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class UIntLiteral : UIntConstant, ILiteralConstant
+	{
+		public UIntLiteral (BuiltinTypes types, uint l, Location loc)
+			: base (types, l, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class LongLiteral : LongConstant, ILiteralConstant
+	{
+		public LongLiteral (BuiltinTypes types, long l, Location loc)
+			: base (types, l, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ULongLiteral : ULongConstant, ILiteralConstant
+	{
+		public ULongLiteral (BuiltinTypes types, ulong l, Location loc)
+			: base (types, l, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class FloatLiteral : FloatConstant, ILiteralConstant
+	{
+		public FloatLiteral (BuiltinTypes types, float f, Location loc)
+			: base (types, f, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class DoubleLiteral : DoubleConstant, ILiteralConstant
+	{
+		public DoubleLiteral (BuiltinTypes types, double d, Location loc)
+			: base (types, d, loc)
+		{
+		}
+
+		public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
+		{
+			if (target.BuiltinType == BuiltinTypeSpec.Type.Float) {
+				Error_664 (ec, loc, "float", "f");
+				return;
+			}
+
+			if (target.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+				Error_664 (ec, loc, "decimal", "m");
+				return;
+			}
+
+			base.Error_ValueCannotBeConverted (ec, target, expl);
+		}
+
+		static void Error_664 (ResolveContext ec, Location loc, string type, string suffix)
+		{
+			ec.Report.Error (664, loc,
+				"Literal of type double cannot be implicitly converted to type `{0}'. Add suffix `{1}' to create a literal of this type",
+				type, suffix);
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class DecimalLiteral : DecimalConstant, ILiteralConstant
+	{
+		public DecimalLiteral (BuiltinTypes types, decimal d, Location loc)
+			: base (types, d, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class StringLiteral : StringConstant, ILiteralConstant
+	{
+		public StringLiteral (BuiltinTypes types, string s, Location loc)
+			: base (types, s, loc)
+		{
+		}
+
+		public override bool IsLiteral {
+			get { return true; }
+		}
+
+#if FULL_AST
+		public char[] ParsedValue { get; set; }
+#endif
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/location.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/location.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/location.cs	(revision 11807)
@@ -0,0 +1,883 @@
+//
+// location.cs: Keeps track of the location of source code entity
+//
+// Author:
+//   Miguel de Icaza
+//   Atsushi Enomoto  <atsushi@ximian.com>
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001 Ximian, Inc.
+// Copyright 2005 Novell, Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
+using System.Diagnostics;
+using System.Linq;
+
+namespace Mono.CSharp
+{
+	//
+	//  This is one single source file.
+	//
+	public class SourceFile : IEquatable<SourceFile>
+	{
+		//
+		// Used by #line directive to track hidden sequence point
+		// regions
+		//
+		struct LocationRegion : IComparable<LocationRegion>
+		{
+			public readonly Location Start;
+			public readonly Location End;
+
+			public LocationRegion (Location start, Location end)
+			{
+				this.Start = start;
+				this.End = end;
+			}
+
+			public int CompareTo (LocationRegion other)
+			{
+				if (Start.Row == other.Start.Row)
+					return Start.Column.CompareTo (other.Start.Column);
+
+				return Start.Row.CompareTo (other.Start.Row);
+			}
+
+			public override string ToString ()
+			{
+				return Start.ToString () + " - " + End.ToString ();
+			}
+		}
+
+		static readonly byte[] MD5Algorith = { 96, 166, 110, 64, 207, 100, 130, 76, 182, 240, 66, 212, 129, 114, 167, 153 };
+
+		public readonly string Name;
+		public readonly string FullPathName;
+		public readonly int Index;
+		public bool AutoGenerated;
+
+		SourceFileEntry file;
+		byte[] algGuid, checksum;
+		List<LocationRegion> hidden_lines;
+
+		public SourceFile (string name, string path, int index)
+		{
+			this.Index = index;
+			this.Name = name;
+			this.FullPathName = path;
+		}
+
+		public byte[] Checksum {
+			get {
+				return checksum;
+			}
+		}
+
+		public bool HasChecksum {
+			get {
+				return checksum != null;
+			}
+		}
+
+		public SourceFileEntry SourceFileEntry {
+			get {
+				return file;
+			}
+		}
+
+		public void SetChecksum (byte[] checksum)
+		{
+			SetChecksum (MD5Algorith, checksum);
+		}
+
+		public void SetChecksum (byte[] algorithmGuid, byte[] checksum)
+		{
+			this.algGuid = algorithmGuid;
+			this.checksum = checksum;
+		}
+
+		public SourceFileEntry CreateSymbolInfo (MonoSymbolFile symwriter)
+		{
+			if (hidden_lines != null)
+				hidden_lines.Sort ();
+
+			file = new SourceFileEntry (symwriter, FullPathName, algGuid, checksum);
+			if (AutoGenerated)
+				file.SetAutoGenerated ();
+
+			return file;
+		}
+
+		public bool Equals (SourceFile other)
+		{
+			return FullPathName == other.FullPathName;
+		}
+
+		public bool IsHiddenLocation (Location loc)
+		{
+			if (hidden_lines == null)
+				return false;
+
+			int index = hidden_lines.BinarySearch (new LocationRegion (loc, loc));
+			index = ~index;
+			if (index > 0) {
+				var found = hidden_lines[index - 1];
+				if (loc.Row < found.End.Row)
+					return true;
+			}
+
+			return false;
+		}
+
+		public void RegisterHiddenScope (Location start, Location end)
+		{
+			if (hidden_lines == null)
+				hidden_lines = new List<LocationRegion> ();
+
+			hidden_lines.Add (new LocationRegion (start, end));
+		}
+
+		public override string ToString ()
+		{
+			return String.Format ("SourceFile ({0}:{1}:{2})", Name, FullPathName, Index);
+		}
+	}
+
+	/// <summary>
+	///   Keeps track of the location in the program
+	/// </summary>
+	///
+	/// <remarks>
+	///   This uses a compact representation and a couple of auxiliary
+	///   structures to keep track of tokens to (file,line and column) 
+	///   mappings. The usage of the bits is:
+	///   
+	///     - 16 bits for "checkpoint" which is a mixed concept of
+	///       file and "line segment"
+	///     - 8 bits for line delta (offset) from the line segment
+	///     - 8 bits for column number.
+	///
+	///   http://lists.ximian.com/pipermail/mono-devel-list/2004-December/009508.html
+	/// </remarks>
+	public struct Location : IEquatable<Location>
+	{
+		struct Checkpoint {
+			public readonly int LineOffset;
+			public readonly int File;
+
+			public Checkpoint (int file, int line)
+			{
+				File = file;
+				LineOffset = line - (int) (line % (1 << line_delta_bits));
+			}
+		}
+
+#if FULL_AST
+		readonly long token;
+
+		const int column_bits = 24;
+		const int line_delta_bits = 24;
+#else
+		readonly int token;
+
+		const int column_bits = 8;
+		const int line_delta_bits = 8;
+#endif
+		const int checkpoint_bits = 16;
+
+		const int column_mask = (1 << column_bits) - 1;
+		const int max_column = column_mask;
+
+		static List<SourceFile> source_list;
+		static Checkpoint [] checkpoints;
+		static int checkpoint_index;
+		
+		public readonly static Location Null = new Location ();
+		public static bool InEmacs;
+		
+		static Location ()
+		{
+			Reset ();
+		}
+
+		public static void Reset ()
+		{
+			source_list = new List<SourceFile> ();
+			checkpoint_index = 0;
+		}
+
+		public static void AddFile (SourceFile file)
+		{
+			source_list.Add (file);
+		}
+
+		// <summary>
+		//   After adding all source files we want to compile with AddFile(), this method
+		//   must be called to `reserve' an appropriate number of bits in the token for the
+		//   source file.  We reserve some extra space for files we encounter via #line
+		//   directives while parsing.
+		// </summary>
+		static public void Initialize (List<SourceFile> files)
+		{
+#if NET_4_0 || MOBILE_DYNAMIC
+			source_list.AddRange (files);
+#else
+			source_list.AddRange (files.ToArray ());
+#endif
+
+			checkpoints = new Checkpoint [System.Math.Max (1, source_list.Count * 2)];
+			if (checkpoints.Length > 0)
+				checkpoints [0] = new Checkpoint (0, 0);
+		}
+
+		public Location (SourceFile file, int row, int column)
+		{
+			if (row <= 0)
+				token = 0;
+			else {
+				if (column > max_column)
+					column = max_column;
+
+				long target = -1;
+				long delta = 0;
+
+				// TODO: For eval only, need better handling of empty
+				int file_index = file == null ? 0 : file.Index;
+
+				// FIXME: This value is certainly wrong but what was the intension
+				int max = checkpoint_index < 10 ?
+					checkpoint_index : 10;
+				for (int i = 0; i < max; i++) {
+					int offset = checkpoints [checkpoint_index - i].LineOffset;
+					delta = row - offset;
+					if (delta >= 0 &&
+						delta < (1 << line_delta_bits) &&
+						checkpoints[checkpoint_index - i].File == file_index) {
+						target = checkpoint_index - i;
+						break;
+					}
+				}
+				if (target == -1) {
+					AddCheckpoint (file_index, row);
+					target = checkpoint_index;
+					delta = row % (1 << line_delta_bits);
+				}
+
+				long l = column +
+					(delta << column_bits) +
+					(target << (line_delta_bits + column_bits));
+#if FULL_AST
+				token = l;
+#else
+				token = l > 0xFFFFFFFF ? 0 : (int) l;
+#endif
+			}
+		}
+
+		public static Location operator - (Location loc, int columns)
+		{
+			return new Location (loc.SourceFile, loc.Row, loc.Column - columns);
+		}
+
+		static void AddCheckpoint (int file, int row)
+		{
+			if (checkpoints.Length == ++checkpoint_index) {
+				Array.Resize (ref checkpoints, checkpoint_index * 2);
+			}
+			checkpoints [checkpoint_index] = new Checkpoint (file, row);
+		}
+
+		string FormatLocation (string fileName)
+		{
+			if (column_bits == 0 || InEmacs)
+				return fileName + "(" + Row.ToString () + "):";
+
+			return fileName + "(" + Row.ToString () + "," + Column.ToString () +
+				(Column == max_column ? "+):" : "):");
+		}
+		
+		public override string ToString ()
+		{
+			return FormatLocation (Name);
+		}
+
+		public string ToStringFullName ()
+		{
+			return FormatLocation (NameFullPath);
+		}
+		
+		/// <summary>
+		///   Whether the Location is Null
+		/// </summary>
+		public bool IsNull {
+			get { return token == 0; }
+		}
+
+		public string Name {
+			get {
+				int index = File;
+
+				if (token == 0 || index <= 0)
+					return null;
+
+				SourceFile file = source_list [index - 1];
+				return file.Name;
+			}
+		}
+
+		public string NameFullPath {
+			get {
+				int index = File;
+				if (token == 0 || index <= 0)
+					return null;
+
+				return source_list[index - 1].FullPathName;
+			}
+		}
+
+		int CheckpointIndex {
+			get {
+				const int checkpoint_mask = (1 << checkpoint_bits) - 1;
+				return ((int) (token >> (line_delta_bits + column_bits))) & checkpoint_mask;
+			}
+		}
+
+		public int Row {
+			get {
+				if (token == 0)
+					return 1;
+
+				int offset = checkpoints[CheckpointIndex].LineOffset;
+
+				const int line_delta_mask = (1 << column_bits) - 1;
+				return offset + (((int)(token >> column_bits)) & line_delta_mask);
+			}
+		}
+
+		public int Column {
+			get {
+				if (token == 0)
+					return 1;
+				return (int) (token & column_mask);
+			}
+		}
+
+		public int File {
+			get {
+				if (token == 0)
+					return 0;
+if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("Should not happen. Token is {0:X04}, checkpoints are {1}, index is {2}", token, checkpoints.Length, CheckpointIndex));
+				return checkpoints [CheckpointIndex].File;
+			}
+		}
+
+		// The ISymbolDocumentWriter interface is used by the symbol writer to
+		// describe a single source file - for each source file there's exactly
+		// one corresponding ISymbolDocumentWriter instance.
+		//
+		// This class has an internal hash table mapping source document names
+		// to such ISymbolDocumentWriter instances - so there's exactly one
+		// instance per document.
+		//
+		// This property returns the ISymbolDocumentWriter instance which belongs
+		// to the location's source file.
+		//
+		// If we don't have a symbol writer, this property is always null.
+		public SourceFile SourceFile {
+			get {
+				int index = File;
+				if (index == 0)
+					return null;
+				return source_list [index - 1];
+			}
+		}
+
+		#region IEquatable<Location> Members
+
+		public bool Equals (Location other)
+		{
+			return this.token == other.token;
+		}
+
+		#endregion
+	}
+	
+	public class SpecialsBag
+	{
+		public enum CommentType
+		{
+			Single,
+			Multi,
+			Documentation,
+			InactiveCode
+		}
+
+		public bool Suppress {
+			get;
+			set;
+		}
+
+		public class SpecialVisitor
+		{
+			public virtual void Visit (Comment comment)
+			{
+			}
+			public virtual void Visit (NewLineToken newLineToken)
+			{
+			}
+			public virtual void Visit (PreProcessorDirective preProcessorDirective)
+			{
+			}
+		}
+		public abstract class SpecialBase
+		{
+			public abstract void Accept (SpecialVisitor visitor);
+		}
+		
+		public class Comment : SpecialBase
+		{
+			public readonly CommentType CommentType;
+			public readonly bool StartsLine;
+			public readonly int Line;
+			public readonly int Col;
+			public readonly int EndLine;
+			public readonly int EndCol;
+			public readonly string Content;
+			
+			public Comment (CommentType commentType, bool startsLine, int line, int col, int endLine, int endCol, string content)
+			{
+				this.CommentType = commentType;
+				this.StartsLine = startsLine;
+				this.Line = line;
+				this.Col = col;
+				this.EndLine = endLine;
+				this.EndCol = endCol;
+				this.Content = content;
+			}
+
+			public override string ToString ()
+			{
+				return string.Format ("[Comment: CommentType={0}, Line={1}, Col={2}, EndLine={3}, EndCol={4}, Content={5}]", CommentType, Line, Col, EndLine, EndCol, Content);
+			}
+
+			public override void Accept (SpecialVisitor visitor)
+			{
+				visitor.Visit (this);
+			}
+		}
+
+		public class NewLineToken : SpecialBase
+		{
+			public readonly int Line;
+			public readonly int Col;
+			public readonly NewLine NewLine;
+
+			public NewLineToken (int line, int col, NewLine newLine)
+			{
+				this.Line = line;
+				this.Col = col;
+				this.NewLine = newLine;
+			}
+
+			public override void Accept (SpecialVisitor visitor)
+			{
+				visitor.Visit (this);
+			}
+		}
+
+		public class PragmaPreProcessorDirective : PreProcessorDirective
+		{
+			public bool Disalbe { get; set; }
+
+			public int WarningColumn {
+				get;
+				set;
+			}
+
+			public int DisableRestoreColumn {
+				get;
+				set;
+			}
+
+			public List<Constant> Codes = new List<Constant> ();
+
+			public PragmaPreProcessorDirective (int line, int col, int endLine, int endCol, Tokenizer.PreprocessorDirective cmd, string arg) : base (line, col, endLine, endCol, cmd, arg)
+			{
+			}
+		}
+
+		public class LineProcessorDirective : PreProcessorDirective
+		{
+			public int LineNumber { get; set; }
+			public string FileName { get; set; }
+
+			public LineProcessorDirective (int line, int col, int endLine, int endCol, Tokenizer.PreprocessorDirective cmd, string arg) : base (line, col, endLine, endCol, cmd, arg)
+			{
+			}
+		}
+
+		public class PreProcessorDirective : SpecialBase
+		{
+			public readonly int Line;
+			public readonly int Col;
+			public readonly int EndLine;
+			public readonly int EndCol;
+
+			public readonly Tokenizer.PreprocessorDirective Cmd;
+			public readonly string Arg;
+			
+			public bool Take = true;
+			
+			public PreProcessorDirective (int line, int col, int endLine, int endCol, Tokenizer.PreprocessorDirective cmd, string arg)
+			{
+				this.Line = line;
+				this.Col = col;
+				this.EndLine = endLine;
+				this.EndCol = endCol;
+				this.Cmd = cmd;
+				this.Arg = arg;
+			}
+			
+			public override void Accept (SpecialVisitor visitor)
+			{
+				visitor.Visit (this);
+			}
+
+			public override string ToString ()
+			{
+				return string.Format ("[PreProcessorDirective: Line={0}, Col={1}, EndLine={2}, EndCol={3}, Cmd={4}, Arg={5}]", Line, Col, EndLine, EndCol, Cmd, Arg);
+			}
+		}
+		
+		public readonly List<SpecialBase> Specials = new List<SpecialBase> ();
+		
+		CommentType curComment;
+		bool startsLine;
+		int startLine, startCol;
+		System.Text.StringBuilder contentBuilder = new System.Text.StringBuilder ();
+		
+		[Conditional ("FULL_AST")]
+		public void StartComment (CommentType type, bool startsLine, int startLine, int startCol)
+		{
+			if (Suppress)
+				return;
+			inComment = true;
+			curComment = type;
+			this.startsLine = startsLine;
+			this.startLine = startLine;
+			this.startCol = startCol;
+			contentBuilder.Length = 0;
+		}
+		
+		[Conditional ("FULL_AST")]
+		public void PushCommentChar (int ch)
+		{
+			if (Suppress)
+				return;
+			if (ch < 0)
+				return;
+			contentBuilder.Append ((char)ch);
+		}
+		[Conditional ("FULL_AST")]
+		public void PushCommentString (string str)
+		{
+			if (Suppress)
+				return;
+			contentBuilder.Append (str);
+		}
+		
+		bool inComment;
+		[Conditional ("FULL_AST")]
+		public void EndComment (int endLine, int endColumn)
+		{
+			if (Suppress)
+				return;
+			if (!inComment)
+				return;
+			inComment = false;
+			// Ignore empty comments
+			if (startLine == endLine && startCol == endColumn)
+				return;
+			Specials.Add (new Comment (curComment, startsLine, startLine, startCol, endLine, endColumn, contentBuilder.ToString ()));
+		}
+		
+		[Conditional ("FULL_AST")]
+		public void AddPreProcessorDirective (int startLine, int startCol, int endLine, int endColumn, Tokenizer.PreprocessorDirective cmd, string arg)
+		{
+			if (Suppress)
+				return;
+			if (inComment)
+				EndComment (startLine, startCol);
+			switch (cmd) {
+			case Tokenizer.PreprocessorDirective.Pragma:
+				Specials.Add (new PragmaPreProcessorDirective (startLine, startCol, endLine, endColumn, cmd, arg));
+				break;
+			case Tokenizer.PreprocessorDirective.Line:
+				Specials.Add (new LineProcessorDirective (startLine, startCol, endLine, endColumn, cmd, arg));
+				break;
+			default:
+				Specials.Add (new PreProcessorDirective (startLine, startCol, endLine, endColumn, cmd, arg));
+				break;
+			}
+		}
+
+		#if FULL_AST
+		public PragmaPreProcessorDirective SetPragmaDisable(bool disable)
+		{
+			if (Suppress)
+				return null;
+			var pragmaDirective = Specials [Specials.Count - 1] as PragmaPreProcessorDirective;
+			if (pragmaDirective == null)
+				return null;
+			pragmaDirective.Disalbe = disable;
+			return pragmaDirective;
+		}
+		#endif
+
+		public PragmaPreProcessorDirective GetPragmaPreProcessorDirective()
+		{
+			if (Suppress)
+				return null;
+			return Specials [Specials.Count - 1] as PragmaPreProcessorDirective;
+		}
+
+
+		public LineProcessorDirective GetCurrentLineProcessorDirective()
+		{
+			if (Suppress)
+				return null;
+			return Specials [Specials.Count - 1] as LineProcessorDirective;
+		}
+
+		public enum NewLine { Unix, Windows }
+
+		int lastNewLine = -1;
+		int lastNewCol = -1;
+		[Conditional ("FULL_AST")]
+		public void AddNewLine (int line, int col, NewLine newLine)
+		{
+			if (Suppress)
+				return;
+			if (line == lastNewLine && col == lastNewCol)
+				return;
+			lastNewLine = line;
+			lastNewCol = col;
+			Specials.Add (new NewLineToken (line, col, newLine));
+		}
+
+		public void SkipIf ()
+		{
+			if (Specials.Count > 0) {
+				var directive = Specials[Specials.Count - 1] as PreProcessorDirective;
+				if (directive != null)
+					directive.Take = false;
+			}
+		}
+	}
+
+	//
+	// A bag of additional locations to support full ast tree
+	//
+	public class LocationsBag
+	{
+		public class MemberLocations
+		{
+			public IList<Tuple<Modifiers, Location>> Modifiers { get; internal set; }
+			List<Location> locations;
+			
+			public MemberLocations (IList<Tuple<Modifiers, Location>> mods, IEnumerable<Location> locs)
+			{
+				Modifiers = mods;
+				locations = locs != null ?  new List<Location> (locs) : null;
+/*
+			public readonly IList<Tuple<Modifiers, Location>> Modifiers;
+			List<Location> locations;
+
+			public MemberLocations (IList<Tuple<Modifiers, Location>> mods)
+			{
+				Modifiers = mods;
+			}
+
+			public MemberLocations (IList<Tuple<Modifiers, Location>> mods, Location loc)
+				: this (mods)
+			{
+				AddLocations (loc);
+			}
+
+			public MemberLocations (IList<Tuple<Modifiers, Location>> mods, Location[] locs)
+				: this (mods)
+			{
+				AddLocations (locs);
+			}
+
+			public MemberLocations (IList<Tuple<Modifiers, Location>> mods, List<Location> locs)
+				: this (mods)
+			{
+				locations = locs;*/
+			}
+
+			#region Properties
+
+			public Location this [int index] {
+				get {
+					return locations [index];
+				}
+			}
+			
+			public int Count {
+				get {
+					return locations != null ? locations.Count : 0;
+				}
+			}
+
+			#endregion
+
+			public void AddLocations (Location loc)
+			{
+				if (locations == null) {
+					locations = new List<Location> ();
+				}
+
+				locations.Add (loc);
+			}
+
+			public void AddLocations (params Location[] additional)
+
+			{
+
+				AddLocations ((IEnumerable<Location>)additional);
+
+			}
+			public void AddLocations (IEnumerable<Location> additional)
+			{
+				if (additional == null)
+					return;
+				if (locations == null) {
+					locations = new List<Location> (additional);
+				} else {
+					locations.AddRange (additional);
+				}
+			}
+		}
+		
+		public MemberCore LastMember {
+			get;
+			private set;
+		}
+
+		Dictionary<object, List<Location>> simple_locs = new Dictionary<object, List<Location>> (ReferenceEquality<object>.Default);
+		Dictionary<MemberCore, MemberLocations> member_locs = new Dictionary<MemberCore, MemberLocations> (ReferenceEquality<MemberCore>.Default);
+
+		[Conditional ("FULL_AST")]
+		public void AddLocation (object element, params Location[] locations)
+		{
+			AddLocation (element, (IEnumerable<Location>)locations);
+		}
+
+		[Conditional ("FULL_AST")]
+		public void AddLocation (object element, IEnumerable<Location> locations)
+		{
+			if (element == null || locations == null)
+				return;
+			List<Location> found;
+			if (!simple_locs.TryGetValue (element, out found)) {
+				simple_locs.Add (element, new List<Location> (locations));
+				return;
+			}
+			found.AddRange(locations);
+		}
+
+		[Conditional ("FULL_AST")]
+		public void InsertLocation (object element, int index, Location location)
+		{
+			List<Location> found;
+			if (!simple_locs.TryGetValue (element, out found)) {
+				found = new List<Location> ();
+				simple_locs.Add (element, found);
+			}
+
+			found.Insert (index, location);
+		}
+
+		[Conditional ("FULL_AST")]
+		public void AddStatement (object element, params Location[] locations)
+		{
+			if (element == null)
+				return;
+			if (locations.Length == 0)
+				throw new ArgumentException ("Statement is missing semicolon location");
+			simple_locs.Add (element, new List<Location>(locations));
+		}
+
+		[Conditional ("FULL_AST")]
+		public void AddMember (MemberCore member, IList<Tuple<Modifiers, Location>> modLocations, params Location[] locations)
+		{
+			LastMember = member;
+			if (member == null)
+				return;
+			
+			MemberLocations existing;
+			if (member_locs.TryGetValue (member, out existing)) {
+				existing.Modifiers = modLocations;
+				existing.AddLocations (locations);
+				return;
+			}
+			member_locs.Add (member, new MemberLocations (modLocations, locations));
+		}
+
+		[Conditional ("FULL_AST")]
+		public void AddMember (MemberCore member, IList<Tuple<Modifiers, Location>> modLocations, IEnumerable<Location> locations)
+		{
+			LastMember = member;
+			if (member == null)
+				return;
+			
+			MemberLocations existing;
+			if (member_locs.TryGetValue (member, out existing)) {
+				existing.Modifiers = modLocations;
+				existing.AddLocations (locations);
+				return;
+			}
+			member_locs.Add (member, new MemberLocations (modLocations, locations));
+		}
+
+		[Conditional ("FULL_AST")]
+		public void AppendToMember (MemberCore existing, params Location[] locations)
+		{
+			AppendToMember (existing, (IEnumerable<Location>)locations);
+
+		}
+		
+		[Conditional ("FULL_AST")]
+		public void AppendToMember (MemberCore existing, IEnumerable<Location> locations)
+		{
+			if (existing == null)
+				return;
+			MemberLocations member;
+			if (member_locs.TryGetValue (existing, out member)) {
+				member.AddLocations (locations);
+				return;
+			}
+			member_locs.Add (existing, new MemberLocations (null, locations));
+		}
+
+		public List<Location> GetLocations (object element)
+		{
+			if (element == null)
+				return null;
+			List<Location> found;
+			simple_locs.TryGetValue (element, out found);
+			return found;
+		}
+
+		public MemberLocations GetMemberLocation (MemberCore element)
+		{
+			MemberLocations found;
+			member_locs.TryGetValue (element, out found);
+			return found;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/membercache.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/membercache.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/membercache.cs	(revision 11807)
@@ -0,0 +1,1501 @@
+//
+// membercache.cs: A container for all member lookups
+//
+// Author: Miguel de Icaza (miguel@gnu.org)
+//         Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2010 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+//
+
+using System;
+using System.Collections.Generic;
+
+namespace Mono.CSharp {
+
+	[Flags]
+	public enum MemberKind
+	{
+		Constructor = 1,
+		Event = 1 << 1,
+		Field = 1 << 2,
+		Method = 1 << 3,
+		Property = 1 << 4,
+		Indexer = 1 << 5,
+		Operator = 1 << 6,
+		Destructor	= 1 << 7,
+
+		Class		= 1 << 11,
+		Struct		= 1 << 12,
+		Delegate	= 1 << 13,
+		Enum		= 1 << 14,
+		Interface	= 1 << 15,
+		TypeParameter = 1 << 16,
+
+		ArrayType = 1 << 19,
+		PointerType = 1 << 20,
+		InternalCompilerType = 1 << 21,
+		MissingType = 1 << 22,
+		Void = 1 << 23,
+		Namespace = 1 << 24,
+
+		NestedMask = Class | Struct | Delegate | Enum | Interface,
+		GenericMask = Method | Class | Struct | Delegate | Interface,
+		MaskType = Constructor | Event | Field | Method | Property | Indexer | Operator | Destructor | NestedMask
+	}
+
+	[Flags]
+	public enum BindingRestriction
+	{
+		None = 0,
+
+		// Inspect only queried type members
+		DeclaredOnly = 1 << 1,
+
+		// Exclude static
+		InstanceOnly = 1 << 2,
+
+		NoAccessors = 1 << 3,
+
+		// Member has to be override
+		OverrideOnly = 1 << 4
+	}
+
+	public struct MemberFilter : IEquatable<MemberSpec>
+	{
+		public readonly string Name;
+		public readonly MemberKind Kind;
+		public readonly AParametersCollection Parameters;
+		public readonly TypeSpec MemberType;
+		public readonly int Arity; // -1 to ignore the check
+
+		public MemberFilter (MethodSpec m)
+		{
+			Name = m.Name;
+			Kind = MemberKind.Method;
+			Parameters = m.Parameters;
+			MemberType = m.ReturnType;
+			Arity = m.Arity;
+		}
+
+		public MemberFilter (string name, int arity, MemberKind kind, AParametersCollection param, TypeSpec type)
+		{
+			Name = name;
+			Kind = kind;
+			Parameters = param;
+			MemberType = type;
+			this.Arity = arity;
+		}
+
+		public static MemberFilter Constructor (AParametersCollection param)
+		{
+			return new MemberFilter (Mono.CSharp.Constructor.ConstructorName, 0, MemberKind.Constructor, param, null);
+		}
+
+		public static MemberFilter Property (string name, TypeSpec type)
+		{
+			return new MemberFilter (name, 0, MemberKind.Property, null, type);
+		}
+
+		public static MemberFilter Field (string name, TypeSpec type)
+		{
+			return new MemberFilter (name, 0, MemberKind.Field, null, type);
+		}
+
+		public static MemberFilter Method (string name, int arity, AParametersCollection param, TypeSpec type)
+		{
+			return new MemberFilter (name, arity, MemberKind.Method, param, type);
+		}
+
+		#region IEquatable<MemberSpec> Members
+
+		public bool Equals (MemberSpec other)
+		{
+			// Is the member of the correct type ?
+			// TODO: Isn't this redundant ?
+			if ((other.Kind & Kind & MemberKind.MaskType) == 0)
+				return false;
+
+			// Check arity when not disabled
+			if (Arity >= 0 && Arity != other.Arity)
+				return false;
+
+			if (Parameters != null) {
+				if (other is IParametersMember) {
+					var other_param = ((IParametersMember) other).Parameters;
+					if (!TypeSpecComparer.Override.IsEqual (Parameters, other_param))
+						return false;
+				} else {
+					return false;
+				}
+			}
+
+			if (MemberType != null) {
+				if (other is IInterfaceMemberSpec) {
+					var other_type = ((IInterfaceMemberSpec) other).MemberType;
+					if (!TypeSpecComparer.Override.IsEqual (other_type, MemberType))
+						return false;
+				} else {
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		#endregion
+	}
+
+	//
+	// The MemberCache is the main members container used by compiler. It contains
+	// all members imported or defined during compilation using on demand filling
+	// process. Inflated containers are also using MemberCache to make inflated
+	// members look like normal definition.
+	//
+	// All of the methods are performance and memory sensitive as the MemberCache
+	// is the underlying engine of all member based operations.
+	//
+	public class MemberCache
+	{
+		[Flags]
+		enum StateFlags
+		{
+			HasConversionOperator = 1 << 1,
+			HasUserOperator = 1 << 2
+		}
+
+		readonly Dictionary<string, IList<MemberSpec>> member_hash;
+		Dictionary<string, MemberSpec[]> locase_members;
+		IList<MethodSpec> missing_abstract;
+		StateFlags state;	// TODO: Move to TypeSpec or ITypeDefinition
+
+		public static readonly string IndexerNameAlias = "<this>";
+
+		public static readonly MemberCache Empty = new MemberCache (0);
+
+		public MemberCache ()
+			: this (16)
+		{
+		}
+
+		public MemberCache (int capacity)
+		{
+			member_hash = new Dictionary<string, IList<MemberSpec>> (capacity);
+		}
+
+		public MemberCache (MemberCache cache)
+			: this (cache.member_hash.Count)
+		{
+			this.state = cache.state;
+		}
+
+		//
+		// Creates a new MemberCache for the given `container'.
+		//
+		public MemberCache (TypeContainer container)
+			: this ()				// TODO: Optimize the size
+		{
+		}
+
+		//
+		// For cases where we need to union cache members
+		//
+		public void AddBaseType (TypeSpec baseType)
+		{
+			var cache = baseType.MemberCache;
+
+			IList<MemberSpec> list;
+			foreach (var entry in cache.member_hash) {
+				if (!member_hash.TryGetValue (entry.Key, out list)) {
+					if (entry.Value.Count == 1) {
+						list = entry.Value;
+					} else {
+						list = new List<MemberSpec> (entry.Value);
+					}
+
+					member_hash.Add (entry.Key, list);
+					continue;
+				}
+
+				foreach (var ce in entry.Value) {
+					if (list.Contains (ce))
+						continue;
+
+					if (list is MemberSpec[]) {
+						list = new List<MemberSpec> { list [0] };
+						member_hash[entry.Key] = list;
+					}
+
+					list.Add (ce);
+				}
+			}
+		}
+
+		//
+		// Member-cache does not contain base members but it does
+		// contain all base interface members, so the Lookup code
+		// can use simple inheritance rules.
+		//
+		// Does not work recursively because of generic interfaces
+		//
+		public void AddInterface (TypeSpec iface)
+		{
+			var cache = iface.MemberCache;
+
+			IList<MemberSpec> list;
+			foreach (var entry in cache.member_hash) {
+				if (!member_hash.TryGetValue (entry.Key, out list)) {
+					if (entry.Value.Count == 1) {
+						list = entry.Value;
+					} else {
+						list = new List<MemberSpec> (entry.Value);
+					}
+
+					member_hash.Add (entry.Key, list);
+					continue;
+				}
+
+				foreach (var ce in entry.Value) {
+					//
+					// When two or more different base interfaces implemenent common
+					// interface
+					//
+					// I : IA, IFoo
+					// IA : IFoo
+					//
+					if (list.Contains (ce))
+						continue;
+
+					if (AddInterfaceMember (ce, ref list))
+						member_hash[entry.Key] = list;
+				}
+			}
+		}
+
+		public void AddMember (InterfaceMemberBase imb, string exlicitName, MemberSpec ms)
+		{
+			// Explicit names cannot be looked-up but can be used for
+			// collision checking (no name mangling needed)
+			if (imb.IsExplicitImpl)
+				AddMember (exlicitName, ms, false);
+			else
+				AddMember (ms);
+		}
+
+		//
+		// Add non-explicit member to member cache
+		//
+		public void AddMember (MemberSpec ms)
+		{
+			AddMember (GetLookupName (ms), ms, false);
+		}
+
+		void AddMember (string name, MemberSpec member, bool removeHiddenMembers)
+		{
+			if (member.Kind == MemberKind.Operator) {
+				var dt = member.DeclaringType;
+
+
+				//
+				// Some core types have user operators but they cannot be used like normal
+				// user operators as they are predefined and therefore having different
+				// rules (e.g. binary operators) by not setting the flag we hide them for
+				// user conversions
+				//
+				if (!BuiltinTypeSpec.IsPrimitiveType (dt) || dt.BuiltinType == BuiltinTypeSpec.Type.Char) {
+					switch (dt.BuiltinType) {
+					case BuiltinTypeSpec.Type.String:
+					case BuiltinTypeSpec.Type.Delegate:
+					case BuiltinTypeSpec.Type.MulticastDelegate:
+						break;
+					default:
+						if (name == Operator.GetMetadataName (Operator.OpType.Implicit) || name == Operator.GetMetadataName (Operator.OpType.Explicit)) {
+							state |= StateFlags.HasConversionOperator;
+						} else {
+							state |= StateFlags.HasUserOperator;
+						}
+
+						break;
+					}
+				}
+			}
+
+			IList<MemberSpec> list;
+			if (!member_hash.TryGetValue (name, out list)) {
+				member_hash.Add (name, new MemberSpec[] { member });
+				return;
+			}
+
+			if (removeHiddenMembers && member.DeclaringType.IsInterface) {
+				if (AddInterfaceMember (member, ref list))
+					member_hash[name] = list;
+			} else {
+				if (list.Count == 1) {
+					list = new List<MemberSpec> { list[0] };
+					member_hash[name] = list;
+				}
+
+				list.Add (member);
+			}
+		}
+
+		public void AddMemberImported (MemberSpec ms)
+		{
+			AddMember (GetLookupName (ms), ms, true);
+		}
+
+		//
+		// Ignores any base interface member which can be hidden
+		// by this interface
+		//
+		static bool AddInterfaceMember (MemberSpec member, ref IList<MemberSpec> existing)
+		{
+			var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : ParametersCompiled.EmptyReadOnlyParameters;
+
+			//
+			// interface IA : IB { int Prop { set; } }
+			// interface IB { bool Prop { get; } }
+			//
+			// IB.Prop is never accessible from IA interface
+			//
+			for (int i = 0; i < existing.Count; ++i) {
+				var entry = existing[i];
+
+				if (entry.Arity != member.Arity)
+					continue;
+
+				if (entry is IParametersMember) {
+					var entry_param = ((IParametersMember) entry).Parameters;
+					if (!TypeSpecComparer.Override.IsEqual (entry_param, member_param))
+						continue;
+				}
+
+				if (member.DeclaringType.ImplementsInterface (entry.DeclaringType, false)) {
+					if (existing.Count == 1) {
+						existing = new MemberSpec[] { member };
+						return true;
+					}
+
+					existing.RemoveAt (i--);
+					continue;
+				}
+
+				if ((entry.DeclaringType == member.DeclaringType && entry.IsAccessor == member.IsAccessor) ||
+					entry.DeclaringType.ImplementsInterface (member.DeclaringType, false))
+					return false;
+			}
+
+			if (existing.Count == 1) {
+				existing = new List<MemberSpec> { existing[0], member };
+				return true;
+			}
+
+			existing.Add (member);
+			return false;
+		}
+
+		public static MemberSpec FindMember (TypeSpec container, MemberFilter filter, BindingRestriction restrictions)
+		{
+			do {
+				IList<MemberSpec> applicable;
+				if (container.MemberCache.member_hash.TryGetValue (filter.Name, out applicable)) {
+					// Start from the end because interface members are in reverse order
+					for (int i = applicable.Count - 1; i >= 0; i--) {
+						var entry = applicable [i];
+
+						if ((restrictions & BindingRestriction.InstanceOnly) != 0 && entry.IsStatic)
+							continue;
+
+						if ((restrictions & BindingRestriction.NoAccessors) != 0 && entry.IsAccessor)
+							continue;
+
+						if ((restrictions & BindingRestriction.OverrideOnly) != 0 && (entry.Modifiers & Modifiers.OVERRIDE) == 0)
+							continue;
+
+						if (!filter.Equals (entry))
+							continue;
+
+						if ((restrictions & BindingRestriction.DeclaredOnly) != 0 && container.IsInterface && entry.DeclaringType != container)
+							continue;
+
+						return entry;
+					}
+				}
+
+				if ((restrictions & BindingRestriction.DeclaredOnly) != 0)
+					break;
+
+				container = container.BaseType;
+			} while (container != null);
+
+			return null;
+		}
+
+		//
+		// A special method to work with member lookup only. It returns a list of all members named @name
+		// starting from @container. It's very performance sensitive
+		//
+		// declaredOnlyClass cannot be used interfaces. Manual filtering is required because names are
+		// compacted
+		//
+		public static IList<MemberSpec> FindMembers (TypeSpec container, string name, bool declaredOnlyClass)
+		{
+			IList<MemberSpec> applicable;
+
+			do {
+				if (container.MemberCache.member_hash.TryGetValue (name, out applicable) || declaredOnlyClass)
+					return applicable;
+
+				container = container.BaseType;
+			} while (container != null);
+
+			return null;
+		}
+
+		//
+		// Finds the nested type in container
+		//
+		public static TypeSpec FindNestedType (TypeSpec container, string name, int arity)
+		{
+			IList<MemberSpec> applicable;
+			TypeSpec best_match = null;
+			do {
+#if !FULL_AOT_RUNTIME
+				// TODO: Don't know how to handle this yet
+				// When resolving base type of nested type, parent type must have
+				// base type resolved to scan full hierarchy correctly
+				// Similarly MemberCacheTypes will inflate BaseType and Interfaces
+				// based on type definition
+				var tc = container.MemberDefinition as TypeContainer;
+				if (tc != null)
+					tc.DefineContainer ();
+#endif
+
+				if (container.MemberCacheTypes.member_hash.TryGetValue (name, out applicable)) {
+					for (int i = applicable.Count - 1; i >= 0; i--) {
+						var entry = applicable[i];
+						if ((entry.Kind & MemberKind.NestedMask) == 0)
+							continue;
+
+						var ts = (TypeSpec) entry;
+						if (arity == ts.Arity)
+							return ts;
+
+						if (arity < 0) {
+							if (best_match == null) {
+								best_match = ts;
+							} else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (ts.Arity + arity)) {
+								best_match = ts;
+							}
+						}
+					}
+				}
+
+				container = container.BaseType;
+			} while (container != null);
+
+			return best_match;
+		}
+
+		//
+		// Looks for extension methods with defined name and extension type
+		//
+		public List<MethodSpec> FindExtensionMethods (IMemberContext invocationContext, string name, int arity)
+		{
+			IList<MemberSpec> entries;
+			if (!member_hash.TryGetValue (name, out entries))
+				return null;
+
+			List<MethodSpec> candidates = null;
+			foreach (var entry in entries) {
+				if (entry.Kind != MemberKind.Method || (arity > 0 && entry.Arity != arity))
+					continue;
+
+				var ms = (MethodSpec) entry;
+				if (!ms.IsExtensionMethod)
+					continue;
+
+				if (!ms.IsAccessible (invocationContext))
+					continue;
+
+				//
+				// Extension methods cannot be nested hence checking parent is enough
+				//
+				if ((ms.DeclaringType.Modifiers & Modifiers.INTERNAL) != 0 && !ms.DeclaringType.MemberDefinition.IsInternalAsPublic (invocationContext.Module.DeclaringAssembly))
+					continue;
+
+				if (candidates == null)
+					candidates = new List<MethodSpec> ();
+				candidates.Add (ms);
+			}
+
+			return candidates;
+		}
+
+		//
+		// Returns base members of @member member if no exact match is found @bestCandidate returns
+		// the best match
+		//
+		public static MemberSpec FindBaseMember (MemberCore member, out MemberSpec bestCandidate, ref bool overrides)
+		{
+			bestCandidate = null;
+			var container = member.Parent.PartialContainer.Definition;
+			if (!container.IsInterface) {
+				container = container.BaseType;
+
+				// It can happen for a user definition of System.Object
+				if (container == null)
+					return null;
+			}
+
+			string name = GetLookupName (member);
+			var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : null;
+
+			var mkind = GetMemberCoreKind (member);
+			bool member_with_accessors = mkind == MemberKind.Indexer || mkind == MemberKind.Property;
+
+			IList<MemberSpec> applicable;
+			MemberSpec ambig_candidate = null;
+
+			do {
+				if (container.MemberCache.member_hash.TryGetValue (name, out applicable)) {
+					for (int i = 0; i < applicable.Count; ++i) {
+						var entry = applicable [i];
+
+						if ((entry.Modifiers & Modifiers.PUBLIC) == 0 && !entry.IsAccessible (member))
+							continue;
+
+						//
+						// Isn't the member of same kind ?
+						//
+						if ((entry.Kind & ~MemberKind.Destructor & mkind & MemberKind.MaskType) == 0) {
+							// Destructors are ignored as they cannot be overridden by user
+							if ((entry.Kind & MemberKind.Destructor) != 0)
+								continue;
+
+							// A method with different arity does not hide base member
+							if (mkind != MemberKind.Method && member.MemberName.Arity != entry.Arity)
+								continue;
+
+							bestCandidate = entry;
+							return null;
+						}
+
+						//
+						// Same kind of different arity is valid
+						//
+						if (member.MemberName.Arity != entry.Arity) {
+							continue;
+						}
+
+						if ((entry.Kind & mkind & (MemberKind.Method | MemberKind.Indexer)) != 0) {
+							if (entry.IsAccessor != member is AbstractPropertyEventMethod)
+								continue;
+
+							var pm = entry as IParametersMember;
+							if (!TypeSpecComparer.Override.IsEqual (pm.Parameters, member_param))
+								continue;
+						}
+
+						//
+						// Skip override for member with accessors. It may not fully implement the base member
+						// but keep flag we found an implementation in case the base member is abstract
+						//
+						if (member_with_accessors && ((entry.Modifiers & (Modifiers.OVERRIDE | Modifiers.SEALED)) == Modifiers.OVERRIDE)) {
+							//
+							// Set candidate to override implementation to flag we found an implementation
+							//
+							overrides = true;
+							continue;
+						}
+
+						//
+						// For members with parameters we can encounter an ambiguous candidates (they match exactly)
+						// because generic type parameters could be inflated into same types
+						//
+						if (ambig_candidate == null && (entry.Kind & mkind & (MemberKind.Method | MemberKind.Indexer)) != 0) {
+							bestCandidate = null;
+							ambig_candidate = entry;
+							continue;
+						}
+
+						bestCandidate = ambig_candidate;
+						return entry;
+					}
+				}
+
+				if (container.IsInterface || ambig_candidate != null)
+					break;
+
+				container = container.BaseType;
+			} while (container != null);
+
+			return ambig_candidate;
+		}
+
+		//
+		// Returns inflated version of MemberSpec, it works similarly to
+		// SRE TypeBuilder.GetMethod
+		//
+		public static T GetMember<T> (TypeSpec container, T spec) where T : MemberSpec
+		{
+			IList<MemberSpec> applicable;
+			if (container.MemberCache.member_hash.TryGetValue (GetLookupName (spec), out applicable)) {
+				for (int i = applicable.Count - 1; i >= 0; i--) {
+					var entry = applicable[i];
+					if (entry.MemberDefinition == spec.MemberDefinition)
+						return (T) entry;
+				}
+			}
+
+			throw new InternalErrorException ("Missing member `{0}' on inflated type `{1}'",
+				spec.GetSignatureForError (), container.GetSignatureForError ());
+		}
+
+		static MemberKind GetMemberCoreKind (MemberCore member)
+		{
+			if (member is FieldBase)
+				return MemberKind.Field;
+			if (member is Indexer)
+				return MemberKind.Indexer;
+			if (member is Class)
+				return MemberKind.Class;
+			if (member is Struct)
+				return MemberKind.Struct;
+			if (member is Destructor)
+				return MemberKind.Destructor;
+			if (member is Method)
+				return MemberKind.Method;
+			if (member is Property)
+				return MemberKind.Property;
+			if (member is EventField)
+				return MemberKind.Event;
+			if (member is Interface)
+				return MemberKind.Interface;
+			if (member is EventProperty)
+				return MemberKind.Event;
+			if (member is Delegate)
+				return MemberKind.Delegate;
+			if (member is Enum)
+				return MemberKind.Enum;
+
+			throw new NotImplementedException (member.GetType ().ToString ());
+		}
+
+		public static List<FieldSpec> GetAllFieldsForDefiniteAssignment (TypeSpec container)
+		{
+			List<FieldSpec> fields = null;
+			foreach (var entry in container.MemberCache.member_hash) {
+				foreach (var name_entry in entry.Value) {
+					if (name_entry.Kind != MemberKind.Field)
+						continue;
+
+					if ((name_entry.Modifiers & Modifiers.STATIC) != 0)
+						continue;
+
+					//
+					// Fixed size buffers are not subject to definite assignment checking
+					//
+					if (name_entry is FixedFieldSpec || name_entry is ConstSpec)
+						continue;
+
+					var fs = (FieldSpec) name_entry;
+
+					//
+					// LAMESPEC: Very bizzare hack, definitive assignment is not done
+					// for imported non-public reference fields except array. No idea what the
+					// actual csc rule is
+					//
+					if (!fs.IsPublic && container.MemberDefinition.IsImported && (!fs.MemberType.IsArray && TypeSpec.IsReferenceType (fs.MemberType)))
+						continue;
+
+					//if ((fs.Modifiers & (Modifiers.BACKING_FIELD) != 0)
+					//	continue;
+
+					if (fields == null)
+						fields = new List<FieldSpec> ();
+
+					fields.Add (fs);
+					break;
+				}
+			}
+
+			return fields ?? new List<FieldSpec> (0);
+		}
+
+		public static IList<MemberSpec> GetCompletitionMembers (IMemberContext ctx, TypeSpec container, string name)
+		{
+			var matches = new List<MemberSpec> ();
+			foreach (var entry in container.MemberCache.member_hash) {
+				foreach (var name_entry in entry.Value) {
+					if (name_entry.IsAccessor)
+						continue;
+
+					if ((name_entry.Kind & (MemberKind.Constructor | MemberKind.Destructor | MemberKind.Operator)) != 0)
+						continue;
+
+					if (!name_entry.IsAccessible (ctx))
+						continue;
+
+					if (name == null || name_entry.Name.StartsWith (name)) {
+						matches.Add (name_entry);
+					}
+				}
+			}
+
+			return matches;
+		}
+
+		//
+		// Returns members of @iface only, base members are ignored
+		//
+		public static List<MethodSpec> GetInterfaceMethods (TypeSpec iface)
+		{
+			//
+			// MemberCache flatten interfaces, therefore in cases like this one
+			// 
+			// interface IA : IB {}
+			// interface IB { void Foo () }
+			//
+			// we would return Foo inside IA which is not expected in this case
+			//
+			var methods = new List<MethodSpec> ();
+			foreach (var entry in iface.MemberCache.member_hash.Values) {
+				foreach (var name_entry in entry) {
+					if (iface == name_entry.DeclaringType) {
+						if (name_entry.Kind == MemberKind.Method) {
+							methods.Add ((MethodSpec) name_entry);
+						}
+					}
+				}
+			}
+
+			return methods;
+		}
+
+		//
+		// Returns all not implememted abstract members inside abstract type
+		// NOTE: Returned list is shared and must not be modified
+		//
+		public static IList<MethodSpec> GetNotImplementedAbstractMethods (TypeSpec type)
+		{
+			if (type.MemberCache.missing_abstract != null)
+				return type.MemberCache.missing_abstract;
+				
+			var abstract_methods = new List<MethodSpec> ();
+			List<TypeSpec> hierarchy = null;
+
+			//
+			// Stage 1: top-to-bottom scan for abstract members
+			//
+			var abstract_type = type;
+			while (true) {
+				foreach (var entry in abstract_type.MemberCache.member_hash) {
+					foreach (var name_entry in entry.Value) {
+						if ((name_entry.Modifiers & Modifiers.ABSTRACT) == 0)
+							continue;
+
+						var ms = name_entry as MethodSpec;
+						if (ms == null)
+							continue;
+
+						abstract_methods.Add (ms);
+					}
+				}
+
+				var base_type = abstract_type.BaseType;
+				if (!base_type.IsAbstract)
+					break;
+
+				if (hierarchy == null)
+					hierarchy = new List<TypeSpec> ();
+
+				hierarchy.Add (abstract_type);
+				abstract_type = base_type;
+			}
+
+			int not_implemented_count = abstract_methods.Count;
+			if (not_implemented_count == 0 || hierarchy == null) {
+				type.MemberCache.missing_abstract = abstract_methods;
+				return type.MemberCache.missing_abstract;
+			}
+
+			//
+			// Stage 2: Remove already implemented methods
+			//
+			foreach (var type_up in hierarchy) {
+				var members = type_up.MemberCache.member_hash;
+				if (members.Count == 0)
+					continue;
+
+				for (int i = 0; i < abstract_methods.Count; ++i) {
+					var candidate = abstract_methods [i];
+					if (candidate == null)
+						continue;
+
+					IList<MemberSpec> applicable;
+					if (!members.TryGetValue (candidate.Name, out applicable))
+						continue;
+
+					var filter = new MemberFilter (candidate);
+					foreach (var item in applicable) {
+						if ((item.Modifiers & (Modifiers.OVERRIDE | Modifiers.VIRTUAL)) == 0)
+							continue;
+
+						//
+						// Abstract override does not override anything
+						//
+						if ((item.Modifiers & Modifiers.ABSTRACT) != 0)
+							continue;
+
+						if (filter.Equals (item)) {
+							--not_implemented_count;
+							abstract_methods [i] = null;
+							break;
+						}
+					}
+				}
+			}
+
+			if (not_implemented_count == abstract_methods.Count) {
+				type.MemberCache.missing_abstract = abstract_methods;
+				return type.MemberCache.missing_abstract;
+			}
+
+			var not_implemented = new MethodSpec[not_implemented_count];
+			int counter = 0;
+			foreach (var m in abstract_methods) {
+				if (m == null)
+					continue;
+
+				not_implemented[counter++] = m;
+			}
+
+			type.MemberCache.missing_abstract = not_implemented;
+			return type.MemberCache.missing_abstract;
+		}
+
+		static string GetLookupName (MemberSpec ms)
+		{
+			if (ms.Kind == MemberKind.Indexer)
+				return IndexerNameAlias;
+
+			if (ms.Kind == MemberKind.Constructor) {
+				if (ms.IsStatic)
+					return Constructor.TypeConstructorName;
+
+				return Constructor.ConstructorName;
+			}
+
+			return ms.Name;
+		}
+
+		static string GetLookupName (MemberCore mc)
+		{
+			if (mc is Indexer)
+				return IndexerNameAlias;
+
+			if (mc is Constructor)
+				return mc.IsStatic ? Constructor.TypeConstructorName : Constructor.ConstructorName;
+
+			return mc.MemberName.Name;
+		}
+
+		//
+		// Returns all operators declared on container and its base types (until declaredOnly is used)
+		//
+		public static IList<MemberSpec> GetUserOperator (TypeSpec container, Operator.OpType op, bool declaredOnly)
+		{
+			IList<MemberSpec> found = null;
+			bool shared_list = true;
+			IList<MemberSpec> applicable;
+			do {
+				var mc = container.MemberCache;
+
+				if (((op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) && (mc.state & StateFlags.HasConversionOperator) != 0) ||
+					 (mc.state & StateFlags.HasUserOperator) != 0) {
+
+					if (mc.member_hash.TryGetValue (Operator.GetMetadataName (op), out applicable)) {
+						int i;
+						for (i = 0; i < applicable.Count; ++i) {
+							if (applicable[i].Kind != MemberKind.Operator) {
+								break;
+							}
+						}
+
+						//
+						// Handles very rare case where a method with same name as operator (op_xxxx) exists
+						// and we have to resize the applicable list
+						//
+						if (i != applicable.Count) {
+							for (i = 0; i < applicable.Count; ++i) {
+								if (applicable[i].Kind != MemberKind.Operator) {
+									continue;
+								}
+
+								if (found == null) {
+									found = new List<MemberSpec> ();
+									found.Add (applicable[i]);
+								} else {
+									List<MemberSpec> prev;
+									if (shared_list) {
+										shared_list = false;
+										prev = new List<MemberSpec> (found.Count + 1);
+										prev.AddRange (found);
+									} else {
+										prev = (List<MemberSpec>) found;
+									}
+
+									prev.Add (applicable[i]);
+								}
+							}
+						} else {
+							if (found == null) {
+								found = applicable;
+								shared_list = true;
+							} else {
+								List<MemberSpec> merged;
+								if (shared_list) {
+									shared_list = false;
+									merged = new List<MemberSpec> (found.Count + applicable.Count);
+									merged.AddRange (found);
+									found = merged;
+								} else {
+									merged = (List<MemberSpec>) found;
+								}
+
+								merged.AddRange (applicable);
+							}
+						}
+					}
+				}
+
+				// BaseType call can be expensive
+				if (declaredOnly)
+					break;
+
+				container = container.BaseType;
+			} while (container != null);
+
+			return found;
+		}
+
+		//
+		// Inflates all member cache nested types
+		//
+		public void InflateTypes (MemberCache inflated_cache, TypeParameterInflator inflator)
+		{
+			foreach (var item in member_hash) {
+				IList<MemberSpec> inflated_members = null;
+				for (int i = 0; i < item.Value.Count; ++i ) {
+					var member = item.Value[i];
+
+					// FIXME: When inflating members refering nested types before they are inflated
+					if (member == null)
+						continue;
+
+					if ((member.Kind & MemberKind.NestedMask) != 0 &&
+						(member.Modifiers & Modifiers.COMPILER_GENERATED) == 0) {
+						if (inflated_members == null) {
+							inflated_members = new MemberSpec[item.Value.Count];
+							inflated_cache.member_hash.Add (item.Key, inflated_members);
+						}
+
+						inflated_members [i] = member.InflateMember (inflator);
+					}
+				}
+			}
+		}
+
+		//
+		// Inflates all open type members, requires InflateTypes to be called before
+		//
+		public void InflateMembers (MemberCache cacheToInflate, TypeSpec inflatedType, TypeParameterInflator inflator)
+		{
+			var inflated_member_hash = cacheToInflate.member_hash;
+			Dictionary<MemberSpec, MethodSpec> accessor_relation = null;
+			List<MemberSpec> accessor_members = null;
+
+			// Copy member specific flags when all members were added
+			cacheToInflate.state = state;
+
+			foreach (var item in member_hash) {
+				var members = item.Value;
+				IList<MemberSpec> inflated_members = null;
+				for (int i = 0; i < members.Count; ++i ) {
+					var member = members[i];
+
+					//
+					// All nested types have been inflated earlier except for
+					// compiler types which are created later and could miss InflateTypes
+					//
+					if ((member.Kind & MemberKind.NestedMask) != 0 &&
+						(member.Modifiers & Modifiers.COMPILER_GENERATED) == 0) {
+						if (inflated_members == null)
+							inflated_members = inflated_member_hash[item.Key];
+
+						continue;
+					}
+
+					//
+					// Clone the container first
+					//
+					if (inflated_members == null) {
+						inflated_members = new MemberSpec [item.Value.Count];
+						inflated_member_hash.Add (item.Key, inflated_members);
+					}
+
+					var local_inflator = inflator;
+
+					if (member.DeclaringType != inflatedType) {
+						//
+						// Don't inflate top-level non-generic interface members
+						// merged into generic interface
+						//
+						if (!member.DeclaringType.IsGeneric && !member.DeclaringType.IsNested) {
+							inflated_members [i] = member;
+							continue;
+						}
+
+						//
+						// Needed when inflating flatten interfaces. It inflates
+						// container type only, type parameters are already done
+						//
+						// Handles cases like:
+						//
+						// interface I<T> {}
+						// interface I<U, V> : I<U> {}
+						// 
+						// class C: I<int, bool> {}
+						//
+						var inflated_parent = inflator.Inflate (member.DeclaringType);
+						if (inflated_parent != inflator.TypeInstance)
+							local_inflator = new TypeParameterInflator (inflator, inflated_parent);
+					}
+
+					//
+					// Inflate every member, its parent is now different
+					//
+					var inflated = member.InflateMember (local_inflator);
+					inflated_members [i] = inflated;
+
+					if (member is PropertySpec || member is EventSpec) {
+						if (accessor_members == null)
+							accessor_members = new List<MemberSpec> ();
+
+						accessor_members.Add (inflated);
+						continue;
+					}
+
+					if (member.IsAccessor) {
+						if (accessor_relation == null)
+							accessor_relation = new Dictionary<MemberSpec, MethodSpec> ();
+						accessor_relation.Add (member, (MethodSpec) inflated);
+					}
+				}
+			}
+
+			if (accessor_members != null) {
+				foreach (var member in accessor_members) {
+					var prop = member as PropertySpec;
+					if (prop != null) {
+						if (prop.Get != null)
+							prop.Get = accessor_relation[prop.Get];
+						if (prop.Set != null)
+							prop.Set = accessor_relation[prop.Set];
+
+						continue;
+					}
+
+					var ev = (EventSpec) member;
+					ev.AccessorAdd = accessor_relation[ev.AccessorAdd];
+					ev.AccessorRemove = accessor_relation[ev.AccessorRemove];
+				}
+			}
+		}
+
+		//
+		// Removes hidden base members of an interface. For compiled interfaces we cannot
+		// do name filtering during Add (as we do for import) because we need all base
+		// names to be valid during type definition.
+		// Add replaces hidden base member with current one which means any name collision
+		// (CS0108) of non-first name would be unnoticed because the name was replaced
+		// with the one from compiled type
+		//
+		public void RemoveHiddenMembers (TypeSpec container)
+		{
+			foreach (var entry in member_hash) {
+				var values = entry.Value;
+
+				int container_members_start_at = 0;
+				while (values[container_members_start_at].DeclaringType != container && ++container_members_start_at < entry.Value.Count);
+
+				if (container_members_start_at == 0 || container_members_start_at == values.Count)
+					continue;
+
+				for (int i = 0; i < container_members_start_at; ++i) {
+					var member = values[i];
+
+					if (!container.ImplementsInterface (member.DeclaringType, false))
+						continue;
+
+					var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : ParametersCompiled.EmptyReadOnlyParameters;
+
+					for (int ii = container_members_start_at; ii < values.Count; ++ii) {
+						var container_entry = values[ii];
+
+						if (container_entry.Arity != member.Arity)
+							continue;
+
+						if (container_entry is IParametersMember) {
+							if (!TypeSpecComparer.Override.IsEqual (((IParametersMember) container_entry).Parameters, member_param))
+								continue;
+						}
+
+						values.RemoveAt (i);
+						--container_members_start_at;
+						--ii;
+						--i;
+					}
+				}
+			}
+		}
+
+		//
+		// Checks all appropriate container members for CLS compliance
+		//
+		public void VerifyClsCompliance (TypeSpec container, Report report)
+		{
+			if (locase_members != null)
+				return;
+
+			if (container.BaseType == null) {
+				locase_members = new Dictionary<string, MemberSpec[]> (member_hash.Count); // StringComparer.OrdinalIgnoreCase);
+			} else {
+				var btype = container.BaseType.GetDefinition ();
+				btype.MemberCache.VerifyClsCompliance (btype, report);
+				locase_members = new Dictionary<string, MemberSpec[]> (btype.MemberCache.locase_members); //, StringComparer.OrdinalIgnoreCase);
+			}
+
+			var is_imported_type = container.MemberDefinition.IsImported;
+			foreach (var entry in container.MemberCache.member_hash) {
+				for (int i = 0; i < entry.Value.Count; ++i ) {
+					var name_entry = entry.Value[i];
+					if ((name_entry.Modifiers & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
+						continue;
+
+					if ((name_entry.Modifiers & (Modifiers.OVERRIDE | Modifiers.COMPILER_GENERATED)) != 0)
+						continue;
+
+					if ((name_entry.Kind & MemberKind.MaskType) == 0)
+						continue;
+
+					if (name_entry.MemberDefinition.CLSAttributeValue == false)
+					    continue;
+
+					IParametersMember p_a = null;
+					if (!is_imported_type) {
+						p_a = name_entry as IParametersMember;
+						if (p_a != null && !name_entry.IsAccessor) {
+							var p_a_pd = p_a.Parameters;
+							//
+							// Check differing overloads in @container
+							//
+							for (int ii = i + 1; ii < entry.Value.Count; ++ii) {
+								var checked_entry = entry.Value[ii];
+								IParametersMember p_b = checked_entry as IParametersMember;
+								if (p_b == null)
+									continue;
+
+								if (p_a_pd.Count != p_b.Parameters.Count)
+									continue;
+
+								if (checked_entry.IsAccessor)
+									continue;
+
+								var res = ParametersCompiled.IsSameClsSignature (p_a.Parameters, p_b.Parameters);
+								if (res != 0) {
+									ReportOverloadedMethodClsDifference (name_entry, checked_entry, res, report);
+								}
+							}
+						}
+					}
+
+					if (i > 0 || name_entry.Kind == MemberKind.Constructor || name_entry.Kind == MemberKind.Indexer)
+						continue;
+
+					var name_entry_locase = name_entry.Name.ToLowerInvariant ();
+
+					MemberSpec[] found;
+					if (!locase_members.TryGetValue (name_entry_locase, out found)) {
+						found = new MemberSpec[] { name_entry };
+						locase_members.Add (name_entry_locase, found);
+					} else {
+						bool same_names_only = true;
+						foreach (var f in found) {
+							if (f.Name == name_entry.Name) {
+								if (p_a != null) {
+									IParametersMember p_b = f as IParametersMember;
+									if (p_b == null)
+										continue;
+
+									if (p_a.Parameters.Count != p_b.Parameters.Count)
+										continue;
+
+									if (f.IsAccessor)
+										continue;
+
+									var res = ParametersCompiled.IsSameClsSignature (p_a.Parameters, p_b.Parameters);
+									if (res != 0) {
+										ReportOverloadedMethodClsDifference (f, name_entry, res, report);
+									}
+								}
+
+								continue;
+							}
+
+							same_names_only = false;
+							if (!is_imported_type) {
+								var last = GetLaterDefinedMember (f, name_entry);
+								if (last == f.MemberDefinition) {
+									report.SymbolRelatedToPreviousError (name_entry);
+								} else {
+									report.SymbolRelatedToPreviousError (f);
+								}
+
+								report.Warning (3005, 1, last.Location,
+									"Identifier `{0}' differing only in case is not CLS-compliant", last.GetSignatureForError ());
+							}
+						}
+
+						if (!same_names_only) {
+							Array.Resize (ref found, found.Length + 1);
+							found[found.Length - 1] = name_entry;
+							locase_members[name_entry_locase] = found;
+						}
+					}
+				}
+			}
+		}
+
+		//
+		// Local report helper to issue correctly ordered members stored in hashtable
+		//
+		static MemberCore GetLaterDefinedMember (MemberSpec a, MemberSpec b)
+		{
+			var mc_a = a.MemberDefinition as MemberCore;
+			var mc_b = b.MemberDefinition as MemberCore;
+			if (mc_a == null)
+				return mc_b;
+
+			if (mc_b == null)
+				return mc_a;
+
+			if (a.DeclaringType.MemberDefinition != b.DeclaringType.MemberDefinition)
+				return mc_b;
+
+			if (mc_a.Location.File != mc_a.Location.File)
+				return mc_b;
+
+			return mc_b.Location.Row > mc_a.Location.Row ? mc_b : mc_a;
+		}
+
+		static void ReportOverloadedMethodClsDifference (MemberSpec a, MemberSpec b, int res, Report report)
+		{
+			var last = GetLaterDefinedMember (a, b);
+			if (last == a.MemberDefinition) {
+				report.SymbolRelatedToPreviousError (b);
+			} else {
+				report.SymbolRelatedToPreviousError (a);
+			}
+
+			if ((res & 1) != 0) {
+				report.Warning (3006, 1, last.Location,
+						"Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant",
+						last.GetSignatureForError ());
+			}
+
+			if ((res & 2) != 0) {
+				report.Warning (3007, 1, last.Location,
+					"Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant",
+					last.GetSignatureForError ());
+			}
+		}
+
+		public bool CheckExistingMembersOverloads (MemberCore member, AParametersCollection parameters)
+		{
+			var name = GetLookupName (member);
+			var imb = member as InterfaceMemberBase;
+			if (imb != null && imb.IsExplicitImpl) {
+				name = imb.GetFullName (name);
+			}
+
+			return CheckExistingMembersOverloads (member, name, parameters);
+		}
+
+		public bool CheckExistingMembersOverloads (MemberCore member, string name, AParametersCollection parameters)
+		{
+			IList<MemberSpec> entries;
+			if (!member_hash.TryGetValue (name, out entries))
+				return false;
+
+			var Report = member.Compiler.Report;
+
+			int method_param_count = parameters.Count;
+			for (int i = entries.Count - 1; i >= 0; --i) {
+				var ce = entries[i];
+				var pm = ce as IParametersMember;
+				var pd = pm == null ? ParametersCompiled.EmptyReadOnlyParameters : pm.Parameters;
+				if (pd.Count != method_param_count)
+					continue;
+
+				if (ce.Arity != member.MemberName.Arity)
+					continue;
+
+				// Ignore merged interface members
+				if (member.Parent.PartialContainer != ce.DeclaringType.MemberDefinition)
+					continue;
+
+				var p_types = pd.Types;
+				if (method_param_count > 0) {
+					int ii = method_param_count - 1;
+					TypeSpec type_a, type_b;
+					do {
+						type_a = parameters.Types [ii];
+						type_b = p_types [ii];
+
+						var a_byref = (pd.FixedParameters[ii].ModFlags & Parameter.Modifier.RefOutMask) != 0;
+						var b_byref = (parameters.FixedParameters[ii].ModFlags & Parameter.Modifier.RefOutMask) != 0;
+
+						if (a_byref != b_byref)
+							break;
+
+					} while (TypeSpecComparer.Override.IsEqual (type_a, type_b) && ii-- != 0);
+
+					if (ii >= 0)
+						continue;
+
+					//
+					// Operators can differ in return type only
+					//
+					if (member is Operator && ce.Kind == MemberKind.Operator && ((MethodSpec) ce).ReturnType != ((Operator) member).ReturnType)
+						continue;
+
+					//
+					// Report difference in parameter modifiers only
+					//
+					if (pd != null && member is MethodCore) {
+						ii = method_param_count;
+						while (ii-- != 0 &&
+							(parameters.FixedParameters[ii].ModFlags & Parameter.Modifier.ModifierMask) ==
+							(pd.FixedParameters[ii].ModFlags & Parameter.Modifier.ModifierMask) &&
+							parameters.ExtensionMethodType == pd.ExtensionMethodType) ;
+
+						if (ii >= 0) {
+							var mc = ce as MethodSpec;
+							member.Compiler.Report.SymbolRelatedToPreviousError (ce);
+							if ((member.ModFlags & Modifiers.PARTIAL) != 0 && (mc.Modifiers & Modifiers.PARTIAL) != 0) {
+								if (parameters.HasParams || pd.HasParams) {
+									Report.Error (758, member.Location,
+										"A partial method declaration and partial method implementation cannot differ on use of `params' modifier");
+								} else {
+									Report.Error (755, member.Location,
+										"A partial method declaration and partial method implementation must be both an extension method or neither");
+								}
+							} else if (member is Constructor) {
+								Report.Error (851, member.Location,
+									"Overloaded contructor `{0}' cannot differ on use of parameter modifiers only",
+									member.GetSignatureForError ());
+							} else {
+								Report.Error (663, member.Location,
+									"Overloaded method `{0}' cannot differ on use of parameter modifiers only",
+									member.GetSignatureForError ());
+							}
+							return false;
+						}
+					}
+				}
+
+				if ((ce.Kind & MemberKind.Method) != 0) {
+					Method method_a = member as Method;
+					Method method_b = ce.MemberDefinition as Method;
+					if (method_a != null && method_b != null && (method_a.ModFlags & method_b.ModFlags & Modifiers.PARTIAL) != 0) {
+						const Modifiers partial_modifiers = Modifiers.STATIC | Modifiers.UNSAFE;
+						if (method_a.IsPartialDefinition == method_b.IsPartialImplementation) {
+							if ((method_a.ModFlags & partial_modifiers) == (method_b.ModFlags & partial_modifiers) ||
+								method_a.Parent.IsUnsafe && method_b.Parent.IsUnsafe) {
+								if (method_a.IsPartialImplementation) {
+									method_a.SetPartialDefinition (method_b);
+									if (entries.Count == 1)
+										member_hash.Remove (name);
+									else
+										entries.RemoveAt (i);
+								} else {
+									method_b.SetPartialDefinition (method_a);
+									method_a.caching_flags |= MemberCore.Flags.PartialDefinitionExists;
+								}
+								continue;
+							}
+
+							if (method_a.IsStatic != method_b.IsStatic) {
+								Report.SymbolRelatedToPreviousError (ce);
+								Report.Error (763, member.Location,
+									"A partial method declaration and partial method implementation must be both `static' or neither");
+							}
+
+							if ((method_a.ModFlags & Modifiers.UNSAFE) != (method_b.ModFlags & Modifiers.UNSAFE)) {
+								Report.SymbolRelatedToPreviousError (ce);
+								Report.Error (764, member.Location,
+									"A partial method declaration and partial method implementation must be both `unsafe' or neither");
+							}
+
+							return false;
+						}
+
+						Report.SymbolRelatedToPreviousError (ce);
+						if (method_a.IsPartialDefinition) {
+							Report.Error (756, member.Location, "A partial method `{0}' declaration is already defined",
+								member.GetSignatureForError ());
+						}
+
+						Report.Error (757, member.Location, "A partial method `{0}' implementation is already defined",
+							member.GetSignatureForError ());
+						return false;
+					}
+
+					Report.SymbolRelatedToPreviousError (ce);
+
+					bool is_reserved_a = member is AbstractPropertyEventMethod || member is Operator;
+					bool is_reserved_b = ((MethodSpec) ce).IsReservedMethod;
+
+					if (is_reserved_a || is_reserved_b) {
+						Report.Error (82, member.Location, "A member `{0}' is already reserved",
+							is_reserved_a ?
+							ce.GetSignatureForError () :
+							member.GetSignatureForError ());
+						return false;
+					}
+				} else {
+					Report.SymbolRelatedToPreviousError (ce);
+				}
+
+				if (member is Operator && ce.Kind == MemberKind.Operator) {
+					Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
+						member.Parent.GetSignatureForError ());
+					return false;
+				}
+
+				Report.Error (111, member.Location,
+					"A member `{0}' is already defined. Rename this member or use different parameter types",
+					member.GetSignatureForError ());
+				return false;
+			}
+
+			return true;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/method.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/method.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/method.cs	(revision 11807)
@@ -0,0 +1,2890 @@
+//
+// method.cs: Method based declarations
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Martin Baulig (martin@ximian.com)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Security;
+using System.Security.Permissions;
+using System.Text;
+using System.Linq;
+using Mono.CompilerServices.SymbolWriter;
+using System.Runtime.CompilerServices;
+
+#if NET_2_1
+using XmlElement = System.Object;
+#else
+using System.Xml;
+#endif
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	public abstract class MethodCore : InterfaceMemberBase, IParametersMember
+	{
+		protected ParametersCompiled parameters;
+		protected ToplevelBlock block;
+		protected MethodSpec spec;
+
+		protected MethodCore (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
+			MemberName name, Attributes attrs, ParametersCompiled parameters)
+			: base (parent, type, mod, allowed_mod, name, attrs)
+		{
+			this.parameters = parameters;
+		}
+
+		public override Variance ExpectedMemberTypeVariance {
+			get {
+				return Variance.Covariant;
+			}
+		}
+
+		//
+		//  Returns the System.Type array for the parameters of this method
+		//
+		public TypeSpec [] ParameterTypes {
+			get {
+				return parameters.Types;
+			}
+		}
+
+		public ParametersCompiled ParameterInfo {
+			get {
+				return parameters;
+			}
+		}
+
+		AParametersCollection IParametersMember.Parameters {
+			get { return parameters; }
+		}
+		
+		public ToplevelBlock Block {
+			get {
+				return block;
+			}
+
+			set {
+				block = value;
+			}
+		}
+
+		public CallingConventions CallingConventions {
+			get {
+				CallingConventions cc = parameters.CallingConvention;
+				if (!IsInterface)
+					if ((ModFlags & Modifiers.STATIC) == 0)
+						cc |= CallingConventions.HasThis;
+
+				// FIXME: How is `ExplicitThis' used in C#?
+			
+				return cc;
+			}
+		}
+
+		protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+		{
+			bool res = base.CheckOverrideAgainstBase (base_member);
+
+			//
+			// Check that the permissions are not being changed
+			//
+			if (!CheckAccessModifiers (this, base_member)) {
+				Error_CannotChangeAccessModifiers (this, base_member);
+				res = false;
+			}
+
+			return res;
+		}
+
+		protected override bool CheckBase ()
+		{
+			// Check whether arguments were correct.
+			if (!DefineParameters (parameters))
+				return false;
+
+			return base.CheckBase ();
+		}
+
+		//
+		//   Represents header string for documentation comment.
+		//
+		public override string DocCommentHeader 
+		{
+			get { return "M:"; }
+		}
+
+		public override void Emit ()
+		{
+			if ((ModFlags & Modifiers.COMPILER_GENERATED) == 0) {
+				parameters.CheckConstraints (this);
+			}
+
+			base.Emit ();
+		}
+
+		public override bool EnableOverloadChecks (MemberCore overload)
+		{
+			if (overload is MethodCore) {
+				caching_flags |= Flags.MethodOverloadsExist;
+				return true;
+			}
+
+			if (overload is AbstractPropertyEventMethod)
+				return true;
+
+			return base.EnableOverloadChecks (overload);
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			string s = base.GetSignatureForDocumentation ();
+			if (MemberName.Arity > 0)
+				s += "``" + MemberName.Arity.ToString ();
+
+			return s + parameters.GetSignatureForDocumentation ();
+		}
+
+		public MethodSpec Spec {
+			get { return spec; }
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			if (parameters.HasArglist) {
+				Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
+			}
+
+			if (member_type != null && !member_type.IsCLSCompliant ()) {
+				Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
+					GetSignatureForError ());
+			}
+
+			parameters.VerifyClsCompliance (this);
+			return true;
+		}
+	}
+
+	public interface IGenericMethodDefinition : IMethodDefinition
+	{
+		TypeParameterSpec[] TypeParameters { get; }
+		int TypeParametersCount { get; }
+
+//		MethodInfo MakeGenericMethod (TypeSpec[] targs);
+	}
+
+	public sealed class MethodSpec : MemberSpec, IParametersMember
+	{
+		MethodBase inflatedMetaInfo;
+		AParametersCollection parameters;
+		TypeSpec returnType;
+
+		TypeSpec[] targs;
+		TypeParameterSpec[] constraints;
+
+		public static readonly MethodSpec Excluded = new MethodSpec (MemberKind.Method, InternalType.FakeInternalType, null, null, ParametersCompiled.EmptyReadOnlyParameters, 0);
+
+		public MethodSpec (MemberKind kind, TypeSpec declaringType, IMethodDefinition details, TypeSpec returnType,
+			AParametersCollection parameters, Modifiers modifiers)
+			: base (kind, declaringType, details, modifiers)
+		{
+			this.parameters = parameters;
+			this.returnType = returnType;
+		}
+
+		#region Properties
+
+		public override int Arity {
+			get {
+				return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
+			}
+		}
+
+		public TypeParameterSpec[] Constraints {
+			get {
+				if (constraints == null && IsGeneric)
+					constraints = GenericDefinition.TypeParameters;
+
+				return constraints;
+			}
+		}
+
+		public bool IsConstructor {
+			get {
+				return Kind == MemberKind.Constructor;
+			}
+		}
+
+		public new IMethodDefinition MemberDefinition {
+			get {
+				return (IMethodDefinition) definition;
+			}
+		}
+
+		public IGenericMethodDefinition GenericDefinition {
+			get {
+				return (IGenericMethodDefinition) definition;
+			}
+		}
+
+		public bool IsAsync {
+			get {
+				return (Modifiers & Modifiers.ASYNC) != 0;
+			}
+		}
+
+		public bool IsExtensionMethod {
+			get {
+				return IsStatic && parameters.HasExtensionMethodType;
+			}
+		}
+
+		public bool IsSealed {
+			get {
+				return (Modifiers & Modifiers.SEALED) != 0;
+			}
+		}
+
+		// When is virtual or abstract
+		public bool IsVirtual {
+			get {
+				return (Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) != 0;
+			}
+		}
+
+		public bool IsReservedMethod {
+			get {
+				return Kind == MemberKind.Operator || IsAccessor;
+			}
+		}
+
+		TypeSpec IInterfaceMemberSpec.MemberType {
+			get {
+				return returnType;
+			}
+		}
+
+		public AParametersCollection Parameters {
+			get { 
+				return parameters;
+			}
+		}
+
+		public TypeSpec ReturnType {
+			get {
+				return returnType;
+			}
+		}
+
+		public TypeSpec[] TypeArguments {
+			get {
+				return targs;
+			}
+		}
+
+		#endregion
+
+		public MethodSpec GetGenericMethodDefinition ()
+		{
+			if (!IsGeneric && !DeclaringType.IsGeneric)
+				return this;
+
+			return MemberCache.GetMember (declaringType, this);
+		}
+
+		public MethodBase GetMetaInfo ()
+		{
+			//
+			// inflatedMetaInfo is extra field needed for cases where we
+			// inflate method but another nested type can later inflate
+			// again (the cache would be build with inflated metaInfo) and
+			// TypeBuilder can work with method definitions only
+			//
+			if (inflatedMetaInfo == null) {
+				if ((state & StateFlags.PendingMetaInflate) != 0) {
+					var dt_meta = DeclaringType.GetMetaInfo ();
+
+					if (DeclaringType.IsTypeBuilder) {
+						if (IsConstructor)
+							inflatedMetaInfo = TypeBuilder.GetConstructor (dt_meta, (ConstructorInfo) MemberDefinition.Metadata);
+						else
+							inflatedMetaInfo = TypeBuilder.GetMethod (dt_meta, (MethodInfo) MemberDefinition.Metadata);
+					} else {
+#if STATIC
+						// it should not be reached
+						throw new NotImplementedException ();
+#else
+						inflatedMetaInfo = MethodInfo.GetMethodFromHandle (MemberDefinition.Metadata.MethodHandle, dt_meta.TypeHandle);
+#endif
+					}
+
+					state &= ~StateFlags.PendingMetaInflate;
+				} else {
+					inflatedMetaInfo = MemberDefinition.Metadata;
+				}
+			}
+
+			if ((state & StateFlags.PendingMakeMethod) != 0) {
+				var sre_targs = new MetaType[targs.Length];
+				for (int i = 0; i < sre_targs.Length; ++i)
+					sre_targs[i] = targs[i].GetMetaInfo ();
+
+				inflatedMetaInfo = ((MethodInfo) inflatedMetaInfo).MakeGenericMethod (sre_targs);
+				state &= ~StateFlags.PendingMakeMethod;
+			}
+
+			return inflatedMetaInfo;
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			string name;
+			switch (Kind) {
+			case MemberKind.Constructor:
+				name = "#ctor";
+				break;
+			case MemberKind.Method:
+				if (Arity > 0)
+					name = Name + "``" + Arity.ToString ();
+				else
+					name = Name;
+
+				break;
+			default:
+				name = Name;
+				break;
+			}
+
+			name = DeclaringType.GetSignatureForDocumentation () + "." + name + parameters.GetSignatureForDocumentation ();
+			if (Kind == MemberKind.Operator) {
+				var op = Operator.GetType (Name).Value;
+				if (op == Operator.OpType.Explicit || op == Operator.OpType.Implicit) {
+					name += "~" + ReturnType.GetSignatureForDocumentation ();
+				}
+			}
+
+			return name;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			string name;
+			if (IsConstructor) {
+				name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
+			} else if (Kind == MemberKind.Operator) {
+				var op = Operator.GetType (Name).Value;
+				if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
+					name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
+				} else {
+					name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
+				}
+			} else if (IsAccessor) {
+				int split = Name.IndexOf ('_');
+				name = Name.Substring (split + 1);
+				var postfix = Name.Substring (0, split);
+				if (split == 3) {
+					var pc = parameters.Count;
+					if (pc > 0 && postfix == "get") {
+						name = "this" + parameters.GetSignatureForError ("[", "]", pc);
+					} else if (pc > 1 && postfix == "set") {
+						name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
+					}
+				}
+
+				return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
+			} else {
+				name = base.GetSignatureForError ();
+				if (targs != null)
+					name += "<" + TypeManager.CSharpName (targs) + ">";
+				else if (IsGeneric)
+					name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
+			}
+
+			return name + parameters.GetSignatureForError ();
+		}
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var ms = (MethodSpec) base.InflateMember (inflator);
+			ms.inflatedMetaInfo = null;
+			ms.returnType = inflator.Inflate (returnType);
+			ms.parameters = parameters.Inflate (inflator);
+			if (IsGeneric)
+				ms.constraints = TypeParameterSpec.InflateConstraints (inflator, Constraints);
+
+			return ms;
+		}
+
+		public MethodSpec MakeGenericMethod (IMemberContext context, params TypeSpec[] targs)
+		{
+			if (targs == null)
+				throw new ArgumentNullException ();
+// TODO MemberCache
+//			if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
+//				return ginstance;
+
+			//if (generic_intances == null)
+			//    generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
+
+			var inflator = new TypeParameterInflator (context, DeclaringType, GenericDefinition.TypeParameters, targs);
+
+			var inflated = (MethodSpec) MemberwiseClone ();
+			inflated.declaringType = inflator.TypeInstance;
+			inflated.returnType = inflator.Inflate (returnType);
+			inflated.parameters = parameters.Inflate (inflator);
+			inflated.targs = targs;
+			inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
+			inflated.state |= StateFlags.PendingMakeMethod;
+
+			//			if (inflated.parent == null)
+			//				inflated.parent = parent;
+
+			//generic_intances.Add (targs, inflated);
+			return inflated;
+		}
+
+		public MethodSpec Mutate (TypeParameterMutator mutator)
+		{
+			var targs = TypeArguments;
+			if (targs != null)
+				targs = mutator.Mutate (targs);
+
+			var decl = DeclaringType;
+			if (DeclaringType.IsGenericOrParentIsGeneric) {
+				decl = mutator.Mutate (decl);
+			}
+
+			if (targs == TypeArguments && decl == DeclaringType)
+				return this;
+
+			var ms = (MethodSpec) MemberwiseClone ();
+			if (decl != DeclaringType) {
+				ms.inflatedMetaInfo = null;
+				ms.declaringType = decl;
+				ms.state |= StateFlags.PendingMetaInflate;
+			}
+
+			if (targs != null) {
+				ms.targs = targs;
+				ms.state |= StateFlags.PendingMakeMethod;
+			}
+
+			return ms;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			var missing = returnType.ResolveMissingDependencies (this);
+			foreach (var pt in parameters.Types) {
+				var m = pt.GetMissingDependencies (this);
+				if (m == null)
+					continue;
+
+				if (missing == null)
+					missing = new List<MissingTypeSpecReference> ();
+
+				missing.AddRange (m);
+			}
+
+			if (Arity > 0) {
+				foreach (var tp in GenericDefinition.TypeParameters) {
+					var m = tp.GetMissingDependencies (this);
+
+					if (m == null)
+						continue;
+
+					if (missing == null)
+						missing = new List<MissingTypeSpecReference> ();
+
+					missing.AddRange (m);
+				}
+			}
+
+			return missing;			
+		}
+	}
+
+	public abstract class MethodOrOperator : MethodCore, IMethodData, IMethodDefinition
+	{
+		ReturnParameter return_attributes;
+		SecurityType declarative_security;
+		protected MethodData MethodData;
+
+		static readonly string[] attribute_targets = new string [] { "method", "return" };
+
+		protected MethodOrOperator (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name,
+				Attributes attrs, ParametersCompiled parameters)
+			: base (parent, type, mod, allowed_mod, name, attrs, parameters)
+		{
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Target == AttributeTargets.ReturnValue) {
+				if (return_attributes == null)
+					return_attributes = new ReturnParameter (this, MethodBuilder, Location);
+
+				return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			if (a.Type == pa.MethodImpl) {
+				if ((ModFlags & Modifiers.ASYNC) != 0 && (a.GetMethodImplOptions () & MethodImplOptions.Synchronized) != 0) {
+					Report.Error (4015, a.Location, "`{0}': Async methods cannot use `MethodImplOptions.Synchronized'",
+						GetSignatureForError ());
+				}
+
+				is_external_implementation = a.IsInternalCall ();
+			} else if (a.Type == pa.DllImport) {
+				const Modifiers extern_static = Modifiers.EXTERN | Modifiers.STATIC;
+				if ((ModFlags & extern_static) != extern_static) {
+					Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
+				}
+
+				if (MemberName.IsGeneric || Parent.IsGenericOrParentIsGeneric) {
+					Report.Error (7042, a.Location, 
+						"The DllImport attribute cannot be applied to a method that is generic or contained in a generic type");
+				}
+
+				is_external_implementation = true;
+			}
+
+			if (a.IsValidSecurityAttribute ()) {
+				a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
+				return;
+			}
+
+			if (MethodBuilder != null)
+				MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Method; 
+			}
+		}
+
+		MethodBase IMethodDefinition.Metadata {
+			get {
+				return MethodData.MethodBuilder;
+			}
+		}
+
+		// TODO: Remove and use MethodData abstraction
+		public MethodBuilder MethodBuilder {
+			get {
+				return MethodData.MethodBuilder;
+			}
+		}
+
+		protected override bool CheckForDuplications ()
+		{
+			return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
+		}
+
+		public virtual EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
+		{
+			return new EmitContext (this, ig, MemberType, sourceMethod);
+		}
+
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			if (!CheckBase ())
+				return false;
+
+			MemberKind kind;
+			if (this is Operator)
+				kind = MemberKind.Operator;
+			else if (this is Destructor)
+				kind = MemberKind.Destructor;
+			else
+				kind = MemberKind.Method;
+
+			string explicit_name;
+
+			if (IsPartialDefinition) {
+				caching_flags &= ~Flags.Excluded_Undetected;
+				caching_flags |= Flags.Excluded;
+
+				// Add to member cache only when a partial method implementation has not been found yet
+				if ((caching_flags & Flags.PartialDefinitionExists) != 0)
+					return true;
+
+				if (IsExplicitImpl)
+					return true;
+
+				explicit_name = null;
+			} else {
+				MethodData = new MethodData (this, ModFlags, flags, this, base_method);
+
+				if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
+					return false;
+
+				explicit_name = MethodData.MetadataName;
+			}
+
+			spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, parameters, ModFlags);
+			if (MemberName.Arity > 0)
+				spec.IsGeneric = true;
+
+			Parent.MemberCache.AddMember (this, explicit_name, spec);
+
+			return true;
+		}
+
+		protected override void DoMemberTypeIndependentChecks ()
+		{
+			base.DoMemberTypeIndependentChecks ();
+
+			CheckAbstractAndExtern (block != null);
+
+			if ((ModFlags & Modifiers.PARTIAL) != 0) {
+				for (int i = 0; i < parameters.Count; ++i) {
+					IParameterData p = parameters.FixedParameters [i];
+					if ((p.ModFlags & Parameter.Modifier.OUT) != 0) {
+						Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
+							GetSignatureForError ());
+					}
+
+					if (p.HasDefaultValue && IsPartialImplementation)
+						((Parameter) p).Warning_UselessOptionalParameter (Report);
+				}
+			}
+		}
+
+		protected override void DoMemberTypeDependentChecks ()
+		{
+			base.DoMemberTypeDependentChecks ();
+
+			if (MemberType.IsStatic) {
+				Error_StaticReturnType ();
+			}
+		}
+
+		public override void Emit ()
+		{
+			if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
+				Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (MethodBuilder);
+			if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
+				Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (MethodBuilder);
+			if ((ModFlags & Modifiers.DEBUGGER_STEP_THROUGH) != 0)
+				Module.PredefinedAttributes.DebuggerStepThrough.EmitAttribute (MethodBuilder);
+
+			if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				return_attributes = new ReturnParameter (this, MethodBuilder, Location);
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
+			} else if (ReturnType.HasDynamicElement) {
+				return_attributes = new ReturnParameter (this, MethodBuilder, Location);
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
+			}
+
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			if (declarative_security != null) {
+				foreach (var de in declarative_security) {
+#if STATIC
+					MethodBuilder.__AddDeclarativeSecurity (de);
+#else
+					MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
+				}
+			}
+
+			if (type_expr != null)
+				ConstraintChecker.Check (this, member_type, type_expr.Location);
+
+			base.Emit ();
+
+			if (MethodData != null)
+				MethodData.Emit (Parent);
+
+			if (block != null && block.StateMachine is AsyncTaskStorey) {
+				var psm = Module.PredefinedAttributes.AsyncStateMachine;
+				psm.EmitAttribute (MethodBuilder, block.StateMachine);
+			}
+
+			if ((ModFlags & Modifiers.PARTIAL) == 0)
+				Block = null;
+		}
+
+		protected void Error_ConditionalAttributeIsNotValid ()
+		{
+			Report.Error (577, Location,
+				"Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
+				GetSignatureForError ());
+		}
+
+		public bool IsPartialDefinition {
+			get {
+				return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
+			}
+		}
+
+		public bool IsPartialImplementation {
+			get {
+				return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+
+		#region IMethodData Members
+
+		bool IMethodData.IsAccessor {
+			get {
+				return false;
+			}
+		}
+
+		public TypeSpec ReturnType {
+			get {
+				return MemberType;
+			}
+		}
+
+		public MemberName MethodName {
+			get {
+				return MemberName;
+			}
+		}
+
+		/// <summary>
+		/// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
+		/// </summary>
+		public override string[] ConditionalConditions ()
+		{
+			if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
+				return null;
+
+			if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
+				return new string [0];
+
+			caching_flags &= ~Flags.Excluded_Undetected;
+			string[] conditions;
+
+			if (base_method == null) {
+				if (OptAttributes == null)
+					return null;
+
+				Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
+				if (attrs == null)
+					return null;
+
+				conditions = new string[attrs.Length];
+				for (int i = 0; i < conditions.Length; ++i)
+					conditions[i] = attrs[i].GetConditionalAttributeValue ();
+			} else {
+				conditions = base_method.MemberDefinition.ConditionalConditions();
+			}
+
+			if (conditions != null)
+				caching_flags |= Flags.Excluded;
+
+			return conditions;
+		}
+
+		#endregion
+
+		public virtual void PrepareEmit ()
+		{
+			var mb = MethodData.DefineMethodBuilder (Parent);
+
+			if (CurrentTypeParameters != null) {
+				string[] gnames = new string[CurrentTypeParameters.Count];
+				for (int i = 0; i < gnames.Length; ++i) {
+					gnames[i] = CurrentTypeParameters[i].Name;
+				}
+
+				var gen_params = MethodBuilder.DefineGenericParameters (gnames);
+
+				for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+					var tp = CurrentTypeParameters[i];
+
+					tp.Define (gen_params[i]);
+				}
+			}
+
+			//
+			// Generic method has been already defined to resolve method parameters
+			// correctly when they use type parameters
+			//
+			mb.SetParameters (parameters.GetMetaInfo ());
+			mb.SetReturnType (ReturnType.GetMetaInfo ());
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (MethodData != null && !IsPartialDefinition)
+				MethodData.WriteDebugSymbol (file);
+		}
+	}
+
+	public class Method : MethodOrOperator, IGenericMethodDefinition
+	{
+		Method partialMethodImplementation;
+
+		public Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, MemberName name, ParametersCompiled parameters, Attributes attrs)
+			: base (parent, return_type, mod,
+				parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
+				parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct | Modifiers.ASYNC :
+				AllowedModifiersClass | Modifiers.ASYNC,
+				name, attrs, parameters)
+		{
+		}
+
+		protected Method (TypeDefinition parent, FullNamedExpression return_type, Modifiers mod, Modifiers amod,
+					MemberName name, ParametersCompiled parameters, Attributes attrs)
+			: base (parent, return_type, mod, amod, name, attrs, parameters)
+		{
+		}
+
+		#region Properties
+
+		public override TypeParameters CurrentTypeParameters {
+			get {
+				return MemberName.TypeParameters;
+			}
+		}
+
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				return CurrentTypeParameters.Types;
+			}
+		}
+
+		public int TypeParametersCount {
+			get {
+				return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Count;
+			}
+		}
+
+		#endregion
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public static Method Create (TypeDefinition parent, FullNamedExpression returnType, Modifiers mod,
+				   MemberName name, ParametersCompiled parameters, Attributes attrs)
+		{
+			var m = new Method (parent, returnType, mod, name, parameters, attrs);
+
+			if ((mod & Modifiers.PARTIAL) != 0) {
+				const Modifiers invalid_partial_mod = Modifiers.AccessibilityMask | Modifiers.ABSTRACT | Modifiers.EXTERN |
+					Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.SEALED | Modifiers.VIRTUAL;
+
+				if ((mod & invalid_partial_mod) != 0) {
+					m.Report.Error (750, m.Location,
+						"A partial method cannot define access modifier or any of abstract, extern, new, override, sealed, or virtual modifiers");
+					mod &= ~invalid_partial_mod;
+				}
+
+				if ((parent.ModFlags & Modifiers.PARTIAL) == 0) {
+					m.Report.Error (751, m.Location, 
+						"A partial method must be declared within a partial class or partial struct");
+				}
+			}
+
+			if ((mod & Modifiers.STATIC) == 0 && parameters.HasExtensionMethodType) {
+				m.Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static",
+					m.GetSignatureForError ());
+			}
+
+
+			return m;
+		}
+
+		public override string GetSignatureForError()
+		{
+			return base.GetSignatureForError () + parameters.GetSignatureForError ();
+		}
+
+		void Error_DuplicateEntryPoint (Method b)
+		{
+			Report.Error (17, b.Location,
+				"Program `{0}' has more than one entry point defined: `{1}'",
+				b.Module.Builder.ScopeName, b.GetSignatureForError ());
+		}
+
+		bool IsEntryPoint ()
+		{
+			if (ReturnType.Kind != MemberKind.Void && ReturnType.BuiltinType != BuiltinTypeSpec.Type.Int)
+				return false;
+
+			if (parameters.IsEmpty)
+				return true;
+
+			if (parameters.Count > 1)
+				return false;
+
+			var ac = parameters.Types [0] as ArrayContainer;
+			return ac != null && ac.Rank == 1 && ac.Element.BuiltinType == BuiltinTypeSpec.Type.String &&
+					(parameters[0].ModFlags & Parameter.Modifier.RefOutMask) == 0;
+		}
+
+		public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			if (arity == 0) {
+				var tp = CurrentTypeParameters;
+				if (tp != null) {
+					TypeParameter t = tp.Find (name);
+					if (t != null)
+						return new TypeParameterExpr (t, loc);
+				}
+			}
+
+			return base.LookupNamespaceOrType (name, arity, mode, loc);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.Conditional) {
+				if (IsExplicitImpl) {
+					Error_ConditionalAttributeIsNotValid ();
+					return;
+				}
+
+				if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+					Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
+					return;
+				}
+
+				if (ReturnType.Kind != MemberKind.Void) {
+					Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
+					return;
+				}
+
+				if (IsInterface) {
+					Report.Error (582, Location, "Conditional not valid on interface members");
+					return;
+				}
+
+				if (MethodData.implementing != null) {
+					Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
+					Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
+						GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
+					return;
+				}
+
+				for (int i = 0; i < parameters.Count; ++i) {
+					if ((parameters.FixedParameters [i].ModFlags & Parameter.Modifier.OUT) != 0) {
+						Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
+						return;
+					}
+				}
+			}
+
+			if (a.Type == pa.Extension) {
+				a.Error_MisusedExtensionAttribute ();
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		void CreateTypeParameters ()
+		{
+			var tparams = MemberName.TypeParameters;
+			var parent_tparams = Parent.TypeParametersAll;
+
+			for (int i = 0; i < MemberName.Arity; i++) {
+				string type_argument_name = tparams[i].MemberName.Name;
+
+				if (block == null) {
+					int idx = parameters.GetParameterIndexByName (type_argument_name);
+					if (idx >= 0) {
+						var b = block;
+						if (b == null)
+							b = new ToplevelBlock (Compiler, Location);
+
+						b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
+					}
+				} else {
+					INamedBlockVariable variable = null;
+					block.GetLocalName (type_argument_name, block, ref variable);
+					if (variable != null)
+						variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
+				}
+
+				if (parent_tparams != null) {
+					var tp = parent_tparams.Find (type_argument_name);
+					if (tp != null) {
+						tparams[i].WarningParentNameConflict (tp);
+					}
+				}
+			}
+
+			tparams.Create (null, 0, Parent);
+		}
+
+		protected virtual void DefineTypeParameters ()
+		{
+			var tparams = CurrentTypeParameters;
+
+			TypeParameterSpec[] base_tparams = null;
+			TypeParameterSpec[] base_decl_tparams = TypeParameterSpec.EmptyTypes;
+			TypeSpec[] base_targs = TypeSpec.EmptyTypes;
+			if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
+				MethodSpec base_override = base_method ?? MethodData.implementing;
+
+				if (base_override != null) {
+					base_tparams = base_override.GenericDefinition.TypeParameters;
+
+					if (base_override.DeclaringType.IsGeneric) {
+						base_decl_tparams = base_override.DeclaringType.MemberDefinition.TypeParameters;
+
+						if (base_method != null) {
+							var base_type_parent = CurrentType;
+							while (base_type_parent.BaseType != base_override.DeclaringType) {
+								base_type_parent = base_type_parent.BaseType;
+							}
+
+							base_targs = base_type_parent.BaseType.TypeArguments;
+						} else {
+							foreach (var iface in Parent.CurrentType.Interfaces) {
+								if (iface == base_override.DeclaringType) {
+									base_targs = iface.TypeArguments;
+									break;
+								}
+							}
+						}
+					}
+
+					if (base_override.IsGeneric) {
+						ObsoleteAttribute oa;
+						foreach (var base_tp in base_tparams) {
+							oa = base_tp.BaseType.GetAttributeObsolete ();
+							if (oa != null) {
+								AttributeTester.Report_ObsoleteMessage (oa, base_tp.BaseType.GetSignatureForError (), Location, Report);
+							}
+
+							if (base_tp.InterfacesDefined != null) {
+								foreach (var iface in base_tp.InterfacesDefined) {
+									oa = iface.GetAttributeObsolete ();
+									if (oa != null) {
+										AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
+									}
+								}
+							}
+						}
+
+						if (base_decl_tparams.Length != 0) {
+							base_decl_tparams = base_decl_tparams.Concat (base_tparams).ToArray ();
+							base_targs = base_targs.Concat (tparams.Types).ToArray ();
+						} else {
+							base_decl_tparams = base_tparams;
+							base_targs = tparams.Types;
+						}
+					}
+				}
+			}
+
+			for (int i = 0; i < tparams.Count; ++i) {
+				var tp = tparams [i];
+
+				if (base_tparams == null) {
+					tp.ResolveConstraints (this);
+					continue;
+				}
+
+				//
+				// Copy base constraints for override/explicit methods
+				//
+				var base_tparam = base_tparams [i];
+				var local_tparam = tp.Type;
+				local_tparam.SpecialConstraint = base_tparam.SpecialConstraint;
+
+				var inflator = new TypeParameterInflator (this, CurrentType, base_decl_tparams, base_targs);
+				base_tparam.InflateConstraints (inflator, local_tparam);
+
+				//
+				// Check all type argument constraints for possible collision or unification
+				// introduced by inflating inherited constraints in this context
+				//
+				// Conflict example:
+				//
+				// class A<T> { virtual void Foo<U> () where U : class, T {} }
+				// class B : A<int> { override void Foo<U> {} }
+				//
+				var local_tparam_targs = local_tparam.TypeArguments;
+				if (local_tparam_targs != null) {
+					for (int ii = 0; ii < local_tparam_targs.Length; ++ii) {
+						var ta = local_tparam_targs [ii];
+						if (!ta.IsClass && !ta.IsStruct)
+							continue;
+
+						TypeSpec[] unique_tparams = null;
+						for (int iii = ii + 1; iii < local_tparam_targs.Length; ++iii) {
+							//
+							// Remove any identical or unified constraint types
+							//
+							var tparam_checked = local_tparam_targs [iii];
+							if (TypeSpecComparer.IsEqual (ta, tparam_checked) || TypeSpec.IsBaseClass (ta, tparam_checked, false)) {
+								unique_tparams = new TypeSpec[local_tparam_targs.Length - 1];
+								Array.Copy (local_tparam_targs, 0, unique_tparams, 0, iii);
+								Array.Copy (local_tparam_targs, iii + 1, unique_tparams, iii, local_tparam_targs.Length - iii - 1);
+							} else if (!TypeSpec.IsBaseClass (tparam_checked, ta, false)) {
+								Constraints.Error_ConflictingConstraints (this, local_tparam, ta, tparam_checked, Location);
+							}
+						}
+
+						if (unique_tparams != null) {
+							local_tparam_targs = unique_tparams;
+							local_tparam.TypeArguments = local_tparam_targs;
+							continue;
+						}
+
+						Constraints.CheckConflictingInheritedConstraint (local_tparam, ta, this, Location);
+					}
+				}
+			}
+
+			if (base_tparams == null && MethodData != null && MethodData.implementing != null) {
+				CheckImplementingMethodConstraints (Parent, spec, MethodData.implementing);
+			}
+		}
+
+		public static bool CheckImplementingMethodConstraints (TypeContainer container, MethodSpec method, MethodSpec baseMethod)
+		{
+			var tparams = method.Constraints;
+			var base_tparams = baseMethod.Constraints;
+			for (int i = 0; i < tparams.Length; ++i) {
+				if (!tparams[i].HasSameConstraintsImplementation (base_tparams[i])) {
+					container.Compiler.Report.SymbolRelatedToPreviousError (method);
+					container.Compiler.Report.SymbolRelatedToPreviousError (baseMethod);
+
+					// Using container location because the interface can be implemented
+					// by base class
+					var tp = (tparams [i].MemberDefinition as MemberCore) ?? container;
+					container.Compiler.Report.Error (425, tp.Location,
+						"The constraints for type parameter `{0}' of method `{1}' must match the constraints for type parameter `{2}' of interface method `{3}'. Consider using an explicit interface implementation instead",
+						tparams[i].GetSignatureForError (), method.GetSignatureForError (),
+						base_tparams[i].GetSignatureForError (), baseMethod.GetSignatureForError ());
+ 
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		//
+		// Creates the type
+		//
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			if (member_type.Kind == MemberKind.Void && parameters.IsEmpty && MemberName.Arity == 0 && MemberName.Name == Destructor.MetadataName) {
+				Report.Warning (465, 1, Location,
+					"Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
+			}
+
+			if (Compiler.Settings.StdLib && ReturnType.IsSpecialRuntimeType) {
+				Error1599 (Location, ReturnType, Report);
+				return false;
+			}
+
+			if (CurrentTypeParameters == null) {
+				if (base_method != null && !IsExplicitImpl) {
+					if (parameters.Count == 1 && ParameterTypes[0].BuiltinType == BuiltinTypeSpec.Type.Object && MemberName.Name == "Equals")
+						Parent.PartialContainer.Mark_HasEquals ();
+					else if (parameters.IsEmpty && MemberName.Name == "GetHashCode")
+						Parent.PartialContainer.Mark_HasGetHashCode ();
+				}
+					
+			} else {
+				DefineTypeParameters ();
+			}
+
+			if (block != null) {
+				if (block.IsIterator) {
+					//
+					// Current method is turned into automatically generated
+					// wrapper which creates an instance of iterator
+					//
+					Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+					ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+				}
+
+				if ((ModFlags & Modifiers.ASYNC) != 0) {
+					if (ReturnType.Kind != MemberKind.Void &&
+						ReturnType != Module.PredefinedTypes.Task.TypeSpec &&
+						!ReturnType.IsGenericTask) {
+						Report.Error (1983, Location, "The return type of an async method must be void, Task, or Task<T>");
+					}
+
+					block = (ToplevelBlock) block.ConvertToAsyncTask (this, Parent.PartialContainer, parameters, ReturnType, null, Location);
+					ModFlags |= Modifiers.DEBUGGER_STEP_THROUGH;
+				}
+
+				if (Compiler.Settings.WriteMetadataOnly)
+					block = null;
+			}
+
+			if ((ModFlags & Modifiers.STATIC) == 0)
+				return true;
+
+			if (parameters.HasExtensionMethodType) {
+				if (Parent.PartialContainer.IsStatic && !Parent.IsGenericOrParentIsGeneric) {
+					if (!Parent.IsTopLevel)
+						Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
+							GetSignatureForError ());
+
+					PredefinedAttribute pa = Module.PredefinedAttributes.Extension;
+					if (!pa.IsDefined) {
+						Report.Error (1110, Location,
+							"`{0}': Extension methods require `System.Runtime.CompilerServices.ExtensionAttribute' type to be available. Are you missing an assembly reference?",
+							GetSignatureForError ());
+					}
+
+					ModFlags |= Modifiers.METHOD_EXTENSION;
+					Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
+					Spec.DeclaringType.SetExtensionMethodContainer ();
+					Parent.Module.HasExtensionMethod = true;
+				} else {
+					Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
+						GetSignatureForError ());
+				}
+			}
+
+			//
+			// This is used to track the Entry Point,
+			//
+			var settings = Compiler.Settings;
+			if (settings.NeedsEntryPoint && MemberName.Name == "Main" && !IsPartialDefinition && (settings.MainClass == null || settings.MainClass == Parent.TypeBuilder.FullName)) {
+				if (IsEntryPoint ()) {
+					if (Parent.DeclaringAssembly.EntryPoint == null) {
+						if (Parent.IsGenericOrParentIsGeneric || MemberName.IsGeneric) {
+							Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
+								GetSignatureForError ());
+						} else if ((ModFlags & Modifiers.ASYNC) != 0) {
+							Report.Error (4009, Location, "`{0}': an entry point cannot be async method",
+								GetSignatureForError ());
+						} else {
+							SetIsUsed ();
+							Parent.DeclaringAssembly.EntryPoint = this;
+						}
+					} else {
+						Error_DuplicateEntryPoint (Parent.DeclaringAssembly.EntryPoint);
+						Error_DuplicateEntryPoint (this);
+					}
+				} else {
+					Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
+						GetSignatureForError ());
+				}
+			}
+
+			return true;
+		}
+
+		public override void PrepareEmit ()
+		{
+			if (IsPartialDefinition) {
+				//
+				// Use partial method implementation builder for partial method declaration attributes
+				//
+				if (partialMethodImplementation != null) {
+					MethodData = partialMethodImplementation.MethodData;
+				}
+
+				return;
+			}
+
+			base.PrepareEmit ();
+		}
+
+		//
+		// Emits the code
+		// 
+		public override void Emit ()
+		{
+			try {
+				if (IsPartialDefinition) {
+					if (partialMethodImplementation != null && CurrentTypeParameters != null) {
+						CurrentTypeParameters.CheckPartialConstraints (partialMethodImplementation);
+
+						var otp = partialMethodImplementation.CurrentTypeParameters;
+						for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+							var tp = CurrentTypeParameters [i];
+							tp.Define (otp[i]);
+						}
+					}
+
+					return;
+				}
+				
+				if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0) {
+					Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
+						GetSignatureForError ());
+				}
+
+				if (CurrentTypeParameters != null) {
+					for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+						var tp = CurrentTypeParameters [i];
+
+						tp.CheckGenericConstraints (false);
+						tp.Emit ();
+					}
+				}
+
+				if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
+					Module.PredefinedAttributes.Extension.EmitAttribute (MethodBuilder);
+
+				base.Emit ();
+			} catch (Exception e) {
+				throw new InternalErrorException (this, e);
+			}
+		}
+
+		public override bool EnableOverloadChecks (MemberCore overload)
+		{
+			if (overload is Indexer)
+				return false;
+
+			return base.EnableOverloadChecks (overload);
+		}
+
+		public static void Error1599 (Location loc, TypeSpec t, Report Report)
+		{
+			Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", t.GetSignatureForError ());
+		}
+
+		protected override bool ResolveMemberType ()
+		{
+			if (CurrentTypeParameters != null) {
+				CreateTypeParameters ();
+			}
+
+			return base.ResolveMemberType ();
+		}
+
+		public void SetPartialDefinition (Method methodDefinition)
+		{
+			caching_flags |= Flags.PartialDefinitionExists;
+			methodDefinition.partialMethodImplementation = this;
+
+			// Ensure we are always using method declaration parameters
+			for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
+				var md_p = methodDefinition.parameters [i];
+				var p = parameters [i];
+				p.Name = md_p.Name;
+				p.DefaultValue = md_p.DefaultValue;
+				if (md_p.OptAttributes != null) {
+					if (p.OptAttributes == null) {
+						p.OptAttributes = md_p.OptAttributes;
+					} else {
+						p.OptAttributes.Attrs.AddRange (md_p.OptAttributes.Attrs);
+					}
+				}
+			}
+
+			if (methodDefinition.attributes != null) {
+				if (attributes == null) {
+					attributes = methodDefinition.attributes;
+				} else {
+					attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
+				}
+			}
+
+			if (CurrentTypeParameters != null) {
+				for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
+					var tp_other = methodDefinition.CurrentTypeParameters [i];
+					if (tp_other.OptAttributes == null)
+						continue;
+
+					var tp = CurrentTypeParameters [i];
+					if (tp.OptAttributes == null) {
+						tp.OptAttributes = tp_other.OptAttributes;
+					} else {
+						tp.OptAttributes.Attrs.AddRange (tp.OptAttributes.Attrs);
+					}
+				}
+			}
+		}
+	}
+
+	public abstract class ConstructorInitializer : ExpressionStatement
+	{
+		Arguments argument_list;
+		MethodSpec base_ctor;
+
+		protected ConstructorInitializer (Arguments argument_list, Location loc)
+		{
+			this.argument_list = argument_list;
+			this.loc = loc;
+		}
+
+		public Arguments Arguments {
+			get {
+				return argument_list;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			throw new NotSupportedException ("ET");
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			eclass = ExprClass.Value;
+
+			// FIXME: Hack
+			var caller_builder = (Constructor) ec.MemberContext;
+
+			//
+			// Spec mandates that constructor initializer will not have `this' access
+			//
+			using (ec.Set (ResolveContext.Options.BaseInitializer)) {
+				if (argument_list != null) {
+					bool dynamic;
+					argument_list.Resolve (ec, out dynamic);
+
+					if (dynamic) {
+						ec.Report.Error (1975, loc,
+							"The constructor call cannot be dynamically dispatched within constructor initializer");
+
+						return null;
+					}
+				}
+
+				type = ec.CurrentType;
+				if (this is ConstructorBaseInitializer) {
+					if (ec.CurrentType.BaseType == null)
+						return this;
+
+					type = ec.CurrentType.BaseType;
+					if (ec.CurrentType.IsStruct) {
+						ec.Report.Error (522, loc,
+							"`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
+						return this;
+					}
+				} else {
+					//
+					// It is legal to have "this" initializers that take no arguments
+					// in structs
+					//
+					// struct D { public D (int a) : this () {}
+					//
+					if (ec.CurrentType.IsStruct && argument_list == null)
+						return this;
+				}
+
+				base_ctor = ConstructorLookup (ec, type, ref argument_list, loc);
+			}
+	
+			if (base_ctor != null && base_ctor.MemberDefinition == caller_builder.Spec.MemberDefinition) {
+				ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
+					caller_builder.GetSignatureForError ());
+			}
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// It can be null for struct initializers or System.Object
+			//
+			if (base_ctor == null) {
+				if (type == ec.BuiltinTypes.Object)
+					return;
+
+				ec.Emit (OpCodes.Ldarg_0);
+				ec.Emit (OpCodes.Initobj, type);
+				return;
+			}
+			
+			var call = new CallEmitter ();
+			call.InstanceExpression = new CompilerGeneratedThis (type, loc); 
+			call.EmitPredefined (ec, base_ctor, argument_list, false);
+		}
+
+		public override void EmitStatement (EmitContext ec)
+		{
+			Emit (ec);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (argument_list != null)
+				argument_list.FlowAnalysis (fc);
+		}
+	}
+
+	public class ConstructorBaseInitializer : ConstructorInitializer {
+		public ConstructorBaseInitializer (Arguments argument_list, Location l) :
+			base (argument_list, l)
+		{
+		}
+	}
+
+	class GeneratedBaseInitializer: ConstructorBaseInitializer {
+		public GeneratedBaseInitializer (Location loc, Arguments arguments)
+			: base (arguments, loc)
+		{
+		}
+	}
+
+	public class ConstructorThisInitializer : ConstructorInitializer {
+		public ConstructorThisInitializer (Arguments argument_list, Location l) :
+			base (argument_list, l)
+		{
+		}
+	}
+	
+	public class Constructor : MethodCore, IMethodData, IMethodDefinition
+	{
+		public ConstructorBuilder ConstructorBuilder;
+		public ConstructorInitializer Initializer;
+		SecurityType declarative_security;
+		bool has_compliant_args;
+		SourceMethodBuilder debug_builder;
+
+		// <summary>
+		//   Modifiers allowed for a constructor.
+		// </summary>
+		public const Modifiers AllowedModifiers =
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.STATIC |
+			Modifiers.UNSAFE |
+			Modifiers.EXTERN |		
+			Modifiers.PRIVATE;
+
+		static readonly string[] attribute_targets = new string [] { "method" };
+
+		public static readonly string ConstructorName = ".ctor";
+		public static readonly string TypeConstructorName = ".cctor";
+
+		public Constructor (TypeDefinition parent, string name, Modifiers mod, Attributes attrs, ParametersCompiled args, Location loc)
+			: base (parent, null, mod, AllowedModifiers, new MemberName (name, loc), attrs, args)
+		{
+		}
+
+		public bool HasCompliantArgs {
+			get {
+				return has_compliant_args;
+			}
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Constructor;
+			}
+		}
+
+		bool IMethodData.IsAccessor {
+		    get {
+		        return false;
+		    }
+		}
+
+		public bool IsPrimaryConstructor { get; set; }
+		
+		MethodBase IMethodDefinition.Metadata {
+			get {
+				return ConstructorBuilder;
+			}
+		}
+
+		//
+		// Returns true if this is a default constructor
+		//
+		public bool IsDefault ()
+		{
+			if ((ModFlags & Modifiers.STATIC) != 0)
+				return parameters.IsEmpty;
+
+			return parameters.IsEmpty &&
+					(Initializer is ConstructorBaseInitializer) &&
+					(Initializer.Arguments == null);
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.IsValidSecurityAttribute ()) {
+				a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
+				return;
+			}
+
+			if (a.Type == pa.MethodImpl) {
+				is_external_implementation = a.IsInternalCall ();
+			}
+
+			ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		protected override bool CheckBase ()
+		{
+			if ((ModFlags & Modifiers.STATIC) != 0) {
+				if (!parameters.IsEmpty) {
+					Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
+						GetSignatureForError ());
+					return false;
+				}
+
+				if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+					Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
+
+				// the rest can be ignored
+				return true;
+			}
+
+			// Check whether arguments were correct.
+			if (!DefineParameters (parameters))
+				return false;
+
+			if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+				Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
+
+			if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
+				Report.Error (568, Location, 
+					"Structs cannot contain explicit parameterless constructors");
+				return false;
+			}
+
+			CheckProtectedModifier ();
+			
+			return true;
+		}
+		
+		//
+		// Creates the ConstructorBuilder
+		//
+		public override bool Define ()
+		{
+			if (ConstructorBuilder != null)
+				return true;
+
+			if (!CheckAbstractAndExtern (block != null))
+				return false;
+			
+			// Check if arguments were correct.
+			if (!CheckBase ())
+				return false;
+
+			if (Parent.PrimaryConstructorParameters != null && !IsPrimaryConstructor && !IsStatic) {
+				if (Parent.Kind == MemberKind.Struct && Initializer is ConstructorThisInitializer && Initializer.Arguments == null) {
+					Report.Error (8043, Location, "`{0}': Structs with primary constructor cannot specify default constructor initializer",
+						GetSignatureForError ());
+				} else if (Initializer == null || Initializer is ConstructorBaseInitializer) {
+					Report.Error (8037, Location, "`{0}': Instance constructor of type with primary constructor must specify `this' constructor initializer",
+						GetSignatureForError ());
+				}
+			}
+
+			var ca = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
+
+			ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
+				ca, CallingConventions,
+				parameters.GetMetaInfo ());
+
+			spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, Compiler.BuiltinTypes.Void, parameters, ModFlags);
+			
+			Parent.MemberCache.AddMember (spec);
+			
+			if (block != null) {
+				// It's here only to report an error
+				if (block.IsIterator) {
+					member_type = Compiler.BuiltinTypes.Void;
+					Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+				}
+
+				if (Compiler.Settings.WriteMetadataOnly)
+					block = null;
+			}
+
+			return true;
+		}
+
+		//
+		// Emits the code
+		//
+		public override void Emit ()
+		{
+			if (Parent.PartialContainer.IsComImport) {
+				if (!IsDefault ()) {
+					Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
+						Parent.GetSignatureForError ());
+				}
+
+				// Set as internal implementation and reset block data
+				// to ensure no IL is generated
+				ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
+				block = null;
+			}
+
+			if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
+				Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (ConstructorBuilder);
+
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			base.Emit ();
+			parameters.ApplyAttributes (this, ConstructorBuilder);
+
+
+			BlockContext bc = new BlockContext (this, block, Compiler.BuiltinTypes.Void);
+			bc.Set (ResolveContext.Options.ConstructorScope);
+
+			if (block != null) {
+				if (!IsStatic && Initializer == null && Parent.PartialContainer.Kind == MemberKind.Struct) {
+					//
+					// If this is a non-static `struct' constructor and doesn't have any
+					// initializer, it must initialize all of the struct's fields.
+					//
+					block.AddThisVariable (bc);
+				}
+
+				//
+				// If we use a "this (...)" constructor initializer, then
+				// do not emit field initializers, they are initialized in the other constructor
+				//
+				if (!(Initializer is ConstructorThisInitializer))
+					Parent.PartialContainer.ResolveFieldInitializers (bc);
+
+				if (!IsStatic) {
+					if (Initializer == null && Parent.PartialContainer.Kind == MemberKind.Class) {
+						Initializer = new GeneratedBaseInitializer (Location, null);
+					}
+
+					if (Initializer != null) {
+						//
+						// mdb format does not support reqions. Try to workaround this by emitting the
+						// sequence point at initializer. Any breakpoint at constructor header should
+						// be adjusted to this sequence point as it's the next one which follows.
+						//
+						block.AddScopeStatement (new StatementExpression (Initializer));
+					}
+				}
+
+				if (block.Resolve (bc, this)) {
+					debug_builder = Parent.CreateMethodSymbolEntry ();
+					EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType, debug_builder);
+					ec.With (EmitContext.Options.ConstructorScope, true);
+
+					block.Emit (ec);
+				}
+			}
+
+			if (declarative_security != null) {
+				foreach (var de in declarative_security) {
+#if STATIC
+					ConstructorBuilder.__AddDeclarativeSecurity (de);
+#else
+					ConstructorBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
+				}
+			}
+
+			block = null;
+		}
+
+		protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
+		{
+			// Is never override
+			bestCandidate = null;
+			return null;
+		}
+
+		public override string GetCallerMemberName ()
+		{
+			return IsStatic ? TypeConstructorName : ConstructorName;
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			return Parent.GetSignatureForDocumentation () + ".#ctor" + parameters.GetSignatureForDocumentation ();
+		}
+
+		public override string GetSignatureForError()
+		{
+			return base.GetSignatureForError () + parameters.GetSignatureForError ();
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
+				return false;
+			}
+
+			if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
+				foreach (TypeSpec param in parameters.Types) {
+					if (param.IsArray) {
+						return true;
+					}
+				}
+			}
+
+			has_compliant_args = true;
+			return true;
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (debug_builder == null)
+				return;
+
+			var token = ConstructorBuilder.GetToken ();
+			int t = token.Token;
+#if STATIC
+			if (ModuleBuilder.IsPseudoToken (t))
+				t = Module.Builder.ResolvePseudoToken (t);
+#endif
+
+			debug_builder.DefineMethod (file, t);
+		}
+
+		#region IMethodData Members
+
+		public MemberName MethodName {
+			get {
+				return MemberName;
+			}
+		}
+
+		public TypeSpec ReturnType {
+			get {
+				return MemberType;
+			}
+		}
+
+		EmitContext IMethodData.CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
+		{
+			throw new NotImplementedException ();
+		}
+
+		#endregion
+	}
+
+	/// <summary>
+	/// Interface for MethodData class. Holds links to parent members to avoid member duplication.
+	/// </summary>
+	public interface IMethodData : IMemberContext
+	{
+		CallingConventions CallingConventions { get; }
+		Location Location { get; }
+		MemberName MethodName { get; }
+		TypeSpec ReturnType { get; }
+		ParametersCompiled ParameterInfo { get; }
+		MethodSpec Spec { get; }
+		bool IsAccessor { get; }
+
+		Attributes OptAttributes { get; }
+		ToplevelBlock Block { get; set; }
+
+		EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod);
+	}
+
+	//
+	// Encapsulates most of the Method's state
+	//
+	public class MethodData
+	{
+		public readonly IMethodData method;
+
+		//
+		// Are we implementing an interface ?
+		//
+		public MethodSpec implementing;
+
+		//
+		// Protected data.
+		//
+		protected InterfaceMemberBase member;
+		protected Modifiers modifiers;
+		protected MethodAttributes flags;
+		protected TypeSpec declaring_type;
+		protected MethodSpec parent_method;
+		SourceMethodBuilder debug_builder;
+		string full_name;
+
+		MethodBuilder builder;
+		public MethodBuilder MethodBuilder {
+			get {
+				return builder;
+			}
+		}
+
+		public TypeSpec DeclaringType {
+			get {
+				return declaring_type;
+			}
+		}
+
+		public string MetadataName {
+			get {
+				return full_name;
+			}
+		}
+
+		public MethodData (InterfaceMemberBase member,
+				   Modifiers modifiers, MethodAttributes flags, IMethodData method)
+		{
+			this.member = member;
+			this.modifiers = modifiers;
+			this.flags = flags;
+
+			this.method = method;
+		}
+
+		public MethodData (InterfaceMemberBase member,
+				   Modifiers modifiers, MethodAttributes flags, 
+				   IMethodData method,
+				   MethodSpec parent_method)
+			: this (member, modifiers, flags, method)
+		{
+			this.parent_method = parent_method;
+		}
+
+		public bool Define (TypeDefinition container, string method_full_name)
+		{
+			PendingImplementation pending = container.PendingImplementations;
+			MethodSpec ambig_iface_method;
+			bool optional = false;
+
+			if (pending != null) {
+				implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this, out ambig_iface_method, ref optional);
+
+				if (member.InterfaceType != null) {
+					if (implementing == null) {
+						if (member is PropertyBase) {
+							container.Compiler.Report.Error (550, method.Location,
+								"`{0}' is an accessor not found in interface member `{1}{2}'",
+									  method.GetSignatureForError (), member.InterfaceType.GetSignatureForError (),
+									  member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
+
+						} else {
+							container.Compiler.Report.Error (539, method.Location,
+									  "`{0}.{1}' in explicit interface declaration is not a member of interface",
+									  member.InterfaceType.GetSignatureForError (), member.ShortName);
+						}
+						return false;
+					}
+					if (implementing.IsAccessor && !method.IsAccessor) {
+						container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+						container.Compiler.Report.Error (683, method.Location,
+							"`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
+							member.GetSignatureForError (), implementing.GetSignatureForError ());
+						return false;
+					}
+				} else {
+					if (implementing != null && !optional) {
+						if (!method.IsAccessor) {
+							if (implementing.IsAccessor) {
+								container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+								container.Compiler.Report.Error (470, method.Location,
+									"Method `{0}' cannot implement interface accessor `{1}'",
+									method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
+							}
+						} else if (implementing.DeclaringType.IsInterface) {
+							if (!implementing.IsAccessor) {
+								container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+								container.Compiler.Report.Error (686, method.Location,
+									"Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
+									method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
+							} else {
+								PropertyBase.PropertyMethod pm = method as PropertyBase.PropertyMethod;
+								if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
+									container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+									container.Compiler.Report.Error (277, method.Location,
+										"Accessor `{0}' must be declared public to implement interface member `{1}'",
+										method.GetSignatureForError (), implementing.GetSignatureForError ());
+								}
+							}
+						}
+					}
+				}
+			} else {
+				ambig_iface_method = null;
+			}
+
+			//
+			// For implicit implementations, make sure we are public, for
+			// explicit implementations, make sure we are private.
+			//
+			if (implementing != null){
+				if (member.IsExplicitImpl) {
+					if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
+						container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+						container.Compiler.Report.Error (466, method.Location,
+							"`{0}': the explicit interface implementation cannot introduce the params modifier",
+							method.GetSignatureForError ());
+					}
+
+					if (ambig_iface_method != null) {
+						container.Compiler.Report.SymbolRelatedToPreviousError (ambig_iface_method);
+						container.Compiler.Report.SymbolRelatedToPreviousError (implementing);
+						container.Compiler.Report.Warning (473, 2, method.Location,
+							"Explicit interface implementation `{0}' matches more than one interface member. Consider using a non-explicit implementation instead",
+							method.GetSignatureForError ());
+					}
+				} else {
+					//
+					// Setting implementin to null inside this block will trigger a more
+					// verbose error reporting for missing interface implementations
+					//
+					if (implementing.DeclaringType.IsInterface) {
+						//
+						// If this is an interface method implementation,
+						// check for public accessibility
+						//
+						if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) {
+							implementing = null;
+						} else if (optional && (container.Interfaces == null || !container.Definition.Interfaces.Contains (implementing.DeclaringType))) {
+							//
+							// We are not implementing interface when base class already implemented it
+							//
+							implementing = null;
+						}
+					} else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
+						// We may never be private.
+						implementing = null;
+
+					} else if ((modifiers & Modifiers.OVERRIDE) == 0) {
+						//
+						// We may be protected if we're overriding something.
+						//
+						implementing = null;
+					}
+				}
+					
+				//
+				// Static is not allowed
+				//
+				if ((modifiers & Modifiers.STATIC) != 0){
+					implementing = null;
+				}
+			}
+			
+			//
+			// If implementing is still valid, set flags
+			//
+			if (implementing != null){
+				//
+				// When implementing interface methods, set NewSlot
+				// unless, we are overwriting a method.
+				//
+				if ((modifiers & Modifiers.OVERRIDE) == 0 && implementing.DeclaringType.IsInterface) {
+					flags |= MethodAttributes.NewSlot;
+				}
+
+				flags |= MethodAttributes.Virtual | MethodAttributes.HideBySig;
+
+				// Set Final unless we're virtual, abstract or already overriding a method.
+				if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
+					flags |= MethodAttributes.Final;
+
+				//
+				// clear the pending implementation flag (requires explicit methods to be defined first)
+				//
+				pending.ImplementMethod (method.MethodName,
+					member.InterfaceType, this, member.IsExplicitImpl, out ambig_iface_method, ref optional);
+
+				//
+				// Update indexer accessor name to match implementing abstract accessor
+				//
+				if (!implementing.DeclaringType.IsInterface && !member.IsExplicitImpl && implementing.IsAccessor)
+					method_full_name = implementing.MemberDefinition.Name;
+			}
+
+			full_name = method_full_name;
+			declaring_type = container.Definition;
+
+			return true;
+		}
+
+		void DefineOverride (TypeDefinition container)
+		{
+			if (implementing == null)
+				return;
+
+			if (!member.IsExplicitImpl)
+				return;
+
+			container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
+		}
+
+		//
+		// Creates partial MethodBuilder for the method when has generic parameters used
+		// as arguments or return type
+		//
+		public MethodBuilder DefineMethodBuilder (TypeDefinition container)
+		{
+			if (builder != null)
+				throw new InternalErrorException ();
+
+			builder = container.TypeBuilder.DefineMethod (full_name, flags, method.CallingConventions);
+			return builder;
+		}
+
+		//
+		// Creates full MethodBuilder for the method 
+		//
+		public MethodBuilder DefineMethodBuilder (TypeDefinition container, ParametersCompiled param)
+		{
+			DefineMethodBuilder (container);
+			builder.SetReturnType (method.ReturnType.GetMetaInfo ());
+			builder.SetParameters (param.GetMetaInfo ());
+			return builder;
+		}
+
+		//
+		// Emits the code
+		// 
+		public void Emit (TypeDefinition parent)
+		{
+			DefineOverride (parent);
+
+			method.ParameterInfo.ApplyAttributes (method, MethodBuilder);
+
+			ToplevelBlock block = method.Block;
+			if (block != null) {
+				BlockContext bc = new BlockContext (method, block, method.ReturnType);
+				if (block.Resolve (bc, method)) {
+					debug_builder = member.Parent.CreateMethodSymbolEntry ();
+					EmitContext ec = method.CreateEmitContext (MethodBuilder.GetILGenerator (), debug_builder);
+
+					block.Emit (ec);
+				}
+			}
+		}
+
+		public void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (debug_builder == null)
+				return;
+
+			var token = builder.GetToken ();
+			int t = token.Token;
+#if STATIC
+			if (ModuleBuilder.IsPseudoToken (t))
+				t = member.Module.Builder.ResolvePseudoToken (t);
+#endif
+
+			debug_builder.DefineMethod (file, t);
+		}
+	}
+
+	public class Destructor : MethodOrOperator
+	{
+		const Modifiers AllowedModifiers =
+			Modifiers.UNSAFE |
+			Modifiers.EXTERN;
+
+		static readonly string[] attribute_targets = new string [] { "method" };
+
+		public static readonly string MetadataName = "Finalize";
+
+		public string Identifier {
+			get;
+			set;
+		}
+		
+		public Destructor (TypeDefinition parent, Modifiers mod, ParametersCompiled parameters, Attributes attrs, Location l)
+			: base (parent, null, mod, AllowedModifiers, new MemberName (MetadataName, l), attrs, parameters)
+		{
+			ModFlags &= ~Modifiers.PRIVATE;
+			ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.Conditional) {
+				Error_ConditionalAttributeIsNotValid ();
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+		
+		protected override bool CheckBase ()
+		{
+			if ((caching_flags & Flags.MethodOverloadsExist) != 0)
+				CheckForDuplications ();
+
+			// Don't check base, destructors have special syntax
+			return true;
+		}
+
+		public override bool Define ()
+		{
+			base.Define ();
+
+			if (Compiler.Settings.WriteMetadataOnly)
+				block = null;
+
+			return true;
+		}
+
+		public override void Emit()
+		{
+			var base_type = Parent.PartialContainer.BaseType;
+			if (base_type != null && Block != null) {
+				var base_dtor = MemberCache.FindMember (base_type,
+					new MemberFilter (MetadataName, 0, MemberKind.Destructor, null, null), BindingRestriction.InstanceOnly) as MethodSpec;
+
+				if (base_dtor == null)
+					throw new NotImplementedException ();
+
+				MethodGroupExpr method_expr = MethodGroupExpr.CreatePredefined (base_dtor, base_type, Location);
+				method_expr.InstanceExpression = new BaseThis (base_type, Location);
+
+				var try_block = new ExplicitBlock (block, block.StartLocation, block.EndLocation) {
+					IsCompilerGenerated = true
+				};
+				var finaly_block = new ExplicitBlock (block, Location, Location) {
+					IsCompilerGenerated = true
+				};
+
+				//
+				// 0-size arguments to avoid CS0250 error
+				// TODO: Should use AddScopeStatement or something else which emits correct
+				// debugger scope
+				//
+				finaly_block.AddStatement (new StatementExpression (new Invocation (method_expr, new Arguments (0)), Location.Null));
+
+				var tf = new TryFinally (try_block, finaly_block, Location);
+				block.WrapIntoDestructor (tf, try_block);
+			}
+
+			base.Emit ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
+		}
+
+		protected override bool ResolveMemberType ()
+		{
+			member_type = Compiler.BuiltinTypes.Void;
+			return true;
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+	}
+
+	// Ooouh Martin, templates are missing here.
+	// When it will be possible move here a lot of child code and template method type.
+	public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData, IMethodDefinition {
+		protected MethodData method_data;
+		protected ToplevelBlock block;
+		protected SecurityType declarative_security;
+
+		protected readonly string prefix;
+
+		ReturnParameter return_attributes;
+
+		protected AbstractPropertyEventMethod (InterfaceMemberBase member, string prefix, Attributes attrs, Location loc)
+			: base (member.Parent, SetupName (prefix, member, loc), attrs)
+		{
+			this.prefix = prefix;
+		}
+
+		static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
+		{
+			return new MemberName (member.MemberName.Left, prefix + member.ShortName, member.MemberName.ExplicitInterface, loc);
+		}
+
+		public void UpdateName (InterfaceMemberBase member)
+		{
+			SetMemberName (SetupName (prefix, member, Location));
+		}
+
+		#region IMethodData Members
+
+		public ToplevelBlock Block {
+			get {
+				return block;
+			}
+
+			set {
+				block = value;
+			}
+		}
+
+		public CallingConventions CallingConventions {
+			get {
+				return CallingConventions.Standard;
+			}
+		}
+
+		public EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
+		{
+			return new EmitContext (this, ig, ReturnType, sourceMethod);
+		}
+
+		public bool IsAccessor {
+			get {
+				return true;
+			}
+		}
+
+		public MemberName MethodName {
+			get {
+				return MemberName;
+			}
+		}
+
+		public TypeSpec[] ParameterTypes { 
+			get {
+				return ParameterInfo.Types;
+			}
+		}
+
+		MethodBase IMethodDefinition.Metadata {
+			get {
+				return method_data.MethodBuilder;
+			}
+		}
+
+		public abstract ParametersCompiled ParameterInfo { get ; }
+		public abstract TypeSpec ReturnType { get; }
+
+		#endregion
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
+				Report.Error (1667, a.Location,
+					"Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
+					a.Type.GetSignatureForError (), a.GetValidTargets ());
+				return;
+			}
+
+			if (a.IsValidSecurityAttribute ()) {
+				a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
+				return;
+			}
+
+			if (a.Target == AttributeTargets.Method) {
+				method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+				return;
+			}
+
+			if (a.Target == AttributeTargets.ReturnValue) {
+				if (return_attributes == null)
+					return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
+
+				return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			ApplyToExtraTarget (a, ctor, cdata, pa);
+		}
+
+		protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			throw new NotSupportedException ("You forgot to define special attribute target handling");
+		}
+
+		// It is not supported for the accessors
+		public sealed override bool Define()
+		{
+			throw new NotSupportedException ();
+		}
+
+		public virtual void Emit (TypeDefinition parent)
+		{
+			method_data.Emit (parent);
+
+			if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
+				Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (method_data.MethodBuilder);
+			if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
+				Module.PredefinedAttributes.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
+
+			if (ReturnType.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder);
+			} else if (ReturnType.HasDynamicElement) {
+				return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (return_attributes.Builder, ReturnType, Location);
+			}
+
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			if (declarative_security != null) {
+				foreach (var de in declarative_security) {
+#if STATIC
+					method_data.MethodBuilder.__AddDeclarativeSecurity (de);
+#else
+					method_data.MethodBuilder.AddDeclarativeSecurity (de.Key, de.Value);
+#endif
+				}
+			}
+
+			block = null;
+		}
+
+		public override bool EnableOverloadChecks (MemberCore overload)
+		{
+			if (overload is MethodCore) {
+				caching_flags |= Flags.MethodOverloadsExist;
+				return true;
+			}
+
+			// This can only happen with indexers and it will
+			// be catched as indexer difference
+			if (overload is AbstractPropertyEventMethod)
+				return true;
+
+			return false;
+		}
+
+		public override string GetCallerMemberName ()
+		{
+			return base.GetCallerMemberName ().Substring (prefix.Length);
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			// should not be called
+			throw new NotSupportedException ();
+		}
+
+		public override bool IsClsComplianceRequired()
+		{
+			return false;
+		}
+
+		public void PrepareEmit ()
+		{
+			method_data.DefineMethodBuilder (Parent.PartialContainer, ParameterInfo);
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (method_data != null)
+				method_data.WriteDebugSymbol (file);
+		}
+
+		public MethodSpec Spec { get; protected set; }
+
+		//
+		//   Represents header string for documentation comment.
+		//
+		public override string DocCommentHeader {
+			get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
+		}
+	}
+
+	public class Operator : MethodOrOperator {
+
+		const Modifiers AllowedModifiers =
+			Modifiers.PUBLIC |
+			Modifiers.UNSAFE |
+			Modifiers.EXTERN |
+			Modifiers.STATIC;
+
+		public enum OpType : byte {
+
+			// Unary operators
+			LogicalNot,
+			OnesComplement,
+			Increment,
+			Decrement,
+			True,
+			False,
+
+			// Unary and Binary operators
+			Addition,
+			Subtraction,
+
+			UnaryPlus,
+			UnaryNegation,
+			
+			// Binary operators
+			Multiply,
+			Division,
+			Modulus,
+			BitwiseAnd,
+			BitwiseOr,
+			ExclusiveOr,
+			LeftShift,
+			RightShift,
+			Equality,
+			Inequality,
+			GreaterThan,
+			LessThan,
+			GreaterThanOrEqual,
+			LessThanOrEqual,
+
+			// Implicit and Explicit
+			Implicit,
+			Explicit,
+
+			// Just because of enum
+			TOP
+		};
+
+		public readonly OpType OperatorType;
+
+		static readonly string [] [] names;
+
+		static Operator ()
+		{
+			names = new string[(int)OpType.TOP][];
+			names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
+			names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
+			names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
+			names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
+			names [(int) OpType.True] = new string [] { "true", "op_True" };
+			names [(int) OpType.False] = new string [] { "false", "op_False" };
+			names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
+			names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
+			names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
+			names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
+			names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
+			names [(int) OpType.Division] = new string [] { "/", "op_Division" };
+			names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
+			names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
+			names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
+			names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
+			names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
+			names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
+			names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
+			names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
+			names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
+			names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
+			names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
+			names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
+			names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
+			names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
+		}
+
+		public Operator (TypeDefinition parent, OpType type, FullNamedExpression ret_type, Modifiers mod_flags, ParametersCompiled parameters,
+				 ToplevelBlock block, Attributes attrs, Location loc)
+			: base (parent, ret_type, mod_flags, AllowedModifiers, new MemberName (GetMetadataName (type), loc), attrs, parameters)
+		{
+			OperatorType = type;
+			Block = block;
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.Conditional) {
+				Error_ConditionalAttributeIsNotValid ();
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+		
+		public override bool Define ()
+		{
+			const Modifiers RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
+			if ((ModFlags & RequiredModifiers) != RequiredModifiers){
+				Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
+			}
+
+			if (!base.Define ())
+				return false;
+
+			if (block != null) {
+				if (block.IsIterator) {
+					//
+					// Current method is turned into automatically generated
+					// wrapper which creates an instance of iterator
+					//
+					Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+					ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+				}
+
+				if (Compiler.Settings.WriteMetadataOnly)
+					block = null;
+			}
+
+			// imlicit and explicit operator of same types are not allowed
+			if (OperatorType == OpType.Explicit)
+				Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
+			else if (OperatorType == OpType.Implicit)
+				Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
+
+			TypeSpec declaring_type = Parent.CurrentType;
+			TypeSpec return_type = MemberType;
+			TypeSpec first_arg_type = ParameterTypes [0];
+			
+			TypeSpec first_arg_type_unwrap = first_arg_type;
+			if (first_arg_type.IsNullableType)
+				first_arg_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (first_arg_type);
+			
+			TypeSpec return_type_unwrap = return_type;
+			if (return_type.IsNullableType)
+				return_type_unwrap = Nullable.NullableInfo.GetUnderlyingType (return_type);
+
+			//
+			// Rules for conversion operators
+			//
+			if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
+				if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type) {
+					Report.Error (555, Location,
+						"User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
+					return false;
+				}
+
+				TypeSpec conv_type;
+				if (declaring_type == return_type || declaring_type == return_type_unwrap) {
+					conv_type = first_arg_type;
+				} else if (declaring_type == first_arg_type || declaring_type == first_arg_type_unwrap) {
+					conv_type = return_type;
+				} else {
+					Report.Error (556, Location,
+						"User-defined conversion must convert to or from the enclosing type");
+					return false;
+				}
+
+				if (conv_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					Report.Error (1964, Location,
+						"User-defined conversion `{0}' cannot convert to or from the dynamic type",
+						GetSignatureForError ());
+
+					return false;
+				}
+
+				if (conv_type.IsInterface) {
+					Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
+						GetSignatureForError ());
+					return false;
+				}
+
+				if (conv_type.IsClass) {
+					if (TypeSpec.IsBaseClass (declaring_type, conv_type, true)) {
+						Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
+							GetSignatureForError ());
+						return false;
+					}
+
+					if (TypeSpec.IsBaseClass (conv_type, declaring_type, false)) {
+						Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
+							GetSignatureForError ());
+						return false;
+					}
+				}
+			} else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
+				if (first_arg_type != declaring_type || parameters.Types[1].BuiltinType != BuiltinTypeSpec.Type.Int) {
+					Report.Error (564, Location, "Overloaded shift operator must have the type of the first operand be the containing type, and the type of the second operand must be int");
+					return false;
+				}
+			} else if (parameters.Count == 1) {
+				// Checks for Unary operators
+
+				if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
+					if (return_type != declaring_type && !TypeSpec.IsBaseClass (return_type, declaring_type, false)) {
+						Report.Error (448, Location,
+							"The return type for ++ or -- operator must be the containing type or derived from the containing type");
+						return false;
+					}
+					if (first_arg_type != declaring_type) {
+						Report.Error (
+							559, Location, "The parameter type for ++ or -- operator must be the containing type");
+						return false;
+					}
+				}
+
+				if (first_arg_type_unwrap != declaring_type) {
+					Report.Error (562, Location,
+						"The parameter type of a unary operator must be the containing type");
+					return false;
+				}
+
+				if (OperatorType == OpType.True || OperatorType == OpType.False) {
+					if (return_type.BuiltinType != BuiltinTypeSpec.Type.Bool) {
+						Report.Error (
+							215, Location,
+							"The return type of operator True or False " +
+							"must be bool");
+						return false;
+					}
+				}
+
+			} else if (first_arg_type_unwrap != declaring_type) {
+				// Checks for Binary operators
+
+				var second_arg_type = ParameterTypes[1];
+				if (second_arg_type.IsNullableType)
+					second_arg_type = Nullable.NullableInfo.GetUnderlyingType (second_arg_type);
+
+				if (second_arg_type != declaring_type) {
+					Report.Error (563, Location,
+						"One of the parameters of a binary operator must be the containing type");
+					return false;
+				}
+			}
+
+			return true;
+		}
+
+		protected override bool ResolveMemberType ()
+		{
+			if (!base.ResolveMemberType ())
+				return false;
+
+			flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
+			return true;
+		}
+
+		protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
+		{
+			// Operator cannot be override
+			bestCandidate = null;
+			return null;
+		}
+
+		public static string GetName (OpType ot)
+		{
+			return names [(int) ot] [0];
+		}
+
+		public static string GetName (string metadata_name)
+		{
+			for (int i = 0; i < names.Length; ++i) {
+				if (names [i] [1] == metadata_name)
+					return names [i] [0];
+			}
+			return null;
+		}
+
+		public static string GetMetadataName (OpType ot)
+		{
+			return names [(int) ot] [1];
+		}
+
+		public static string GetMetadataName (string name)
+		{
+			for (int i = 0; i < names.Length; ++i) {
+				if (names [i] [0] == name)
+					return names [i] [1];
+			}
+			return null;
+		}
+
+		public static OpType? GetType (string metadata_name)
+		{
+			for (int i = 0; i < names.Length; ++i) {
+				if (names[i][1] == metadata_name)
+					return (OpType) i;
+			}
+
+			return null;
+		}
+
+		public OpType GetMatchingOperator ()
+		{
+			switch (OperatorType) {
+			case OpType.Equality:
+				return OpType.Inequality;
+			case OpType.Inequality:
+				return OpType.Equality;
+			case OpType.True:
+				return OpType.False;
+			case OpType.False:
+				return OpType.True;
+			case OpType.GreaterThan:
+				return OpType.LessThan;
+			case OpType.LessThan:
+				return OpType.GreaterThan;
+			case OpType.GreaterThanOrEqual:
+				return OpType.LessThanOrEqual;
+			case OpType.LessThanOrEqual:
+				return OpType.GreaterThanOrEqual;
+			default:
+				return OpType.TOP;
+			}
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			string s = base.GetSignatureForDocumentation ();
+			if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
+				s = s + "~" + ReturnType.GetSignatureForDocumentation ();
+			}
+
+			return s;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
+				sb.AppendFormat ("{0}.{1} operator {2}",
+					Parent.GetSignatureForError (), GetName (OperatorType),
+					member_type == null ? type_expr.GetSignatureForError () : member_type.GetSignatureForError ());
+			}
+			else {
+				sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
+			}
+
+			sb.Append (parameters.GetSignatureForError ());
+			return sb.ToString ();
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/modifiers.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/modifiers.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/modifiers.cs	(revision 11807)
@@ -0,0 +1,282 @@
+//
+// modifiers.cs: Modifiers handling
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2010 Novell, Inc
+//
+
+using System;
+
+#if STATIC
+using IKVM.Reflection;
+#else
+using System.Reflection;
+#endif
+
+namespace Mono.CSharp
+{
+	[Flags]
+	public enum Modifiers
+	{
+		PROTECTED = 0x0001,
+		PUBLIC    = 0x0002,
+		PRIVATE   = 0x0004,
+		INTERNAL  = 0x0008,
+		NEW       = 0x0010,
+		ABSTRACT  = 0x0020,
+		SEALED    = 0x0040,
+		STATIC    = 0x0080,
+		READONLY  = 0x0100,
+		VIRTUAL   = 0x0200,
+		OVERRIDE  = 0x0400,
+		EXTERN    = 0x0800,
+		VOLATILE  = 0x1000,
+		UNSAFE    = 0x2000,
+		ASYNC     = 0x4000,
+		TOP       = 0x8000,
+
+		//
+		// Compiler specific flags
+		//
+		PROPERTY_CUSTOM 		= 0x10000,
+
+		PARTIAL					= 0x20000,
+		DEFAULT_ACCESS_MODIFIER	= 0x40000,
+		METHOD_EXTENSION		= 0x80000,
+		COMPILER_GENERATED		= 0x100000,
+		BACKING_FIELD			= 0x200000,
+		DEBUGGER_HIDDEN			= 0x400000,
+		DEBUGGER_STEP_THROUGH	= 0x800000,
+
+		AccessibilityMask = PUBLIC | PROTECTED | INTERNAL | PRIVATE,
+		AllowedExplicitImplFlags = UNSAFE | EXTERN,
+	}
+
+	static class ModifiersExtensions
+	{
+		public static string AccessibilityName (Modifiers mod)
+		{
+			switch (mod & Modifiers.AccessibilityMask) {
+			case Modifiers.PUBLIC:
+				return "public";
+			case Modifiers.PROTECTED:
+				return "protected";
+			case Modifiers.PROTECTED | Modifiers.INTERNAL:
+				return "protected internal";
+			case Modifiers.INTERNAL:
+				return "internal";
+			case Modifiers.PRIVATE:
+				return "private";
+			default:
+				throw new NotImplementedException (mod.ToString ());
+			}
+		}
+
+		static public string Name (Modifiers i)
+		{
+			string s = "";
+			
+			switch (i) {
+			case Modifiers.NEW:
+				s = "new"; break;
+			case Modifiers.PUBLIC:
+				s = "public"; break;
+			case Modifiers.PROTECTED:
+				s = "protected"; break;
+			case Modifiers.INTERNAL:
+				s = "internal"; break;
+			case Modifiers.PRIVATE:
+				s = "private"; break;
+			case Modifiers.ABSTRACT:
+				s = "abstract"; break;
+			case Modifiers.SEALED:
+				s = "sealed"; break;
+			case Modifiers.STATIC:
+				s = "static"; break;
+			case Modifiers.READONLY:
+				s = "readonly"; break;
+			case Modifiers.VIRTUAL:
+				s = "virtual"; break;
+			case Modifiers.OVERRIDE:
+				s = "override"; break;
+			case Modifiers.EXTERN:
+				s = "extern"; break;
+			case Modifiers.VOLATILE:
+				s = "volatile"; break;
+			case Modifiers.UNSAFE:
+				s = "unsafe"; break;
+			case Modifiers.ASYNC:
+				s = "async"; break;
+			}
+
+			return s;
+		}
+
+		//
+		// Used by custom property accessors to check whether @modA is more restrictive than @modB
+		//
+		public static bool IsRestrictedModifier (Modifiers modA, Modifiers modB)
+		{
+			Modifiers flags = 0;
+
+			if ((modB & Modifiers.PUBLIC) != 0) {
+				flags = Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
+			} else if ((modB & Modifiers.PROTECTED) != 0) {
+				if ((modB & Modifiers.INTERNAL) != 0)
+					flags = Modifiers.PROTECTED | Modifiers.INTERNAL;
+
+				flags |= Modifiers.PRIVATE;
+			} else if ((modB & Modifiers.INTERNAL) != 0)
+				flags = Modifiers.PRIVATE;
+
+			return modB != modA && (modA & (~flags)) == 0;
+		}
+
+		public static TypeAttributes TypeAttr (Modifiers mod_flags, bool is_toplevel)
+		{
+			TypeAttributes t = 0;
+
+			if (is_toplevel){
+				if ((mod_flags & Modifiers.PUBLIC) != 0)
+					t = TypeAttributes.Public;
+				else if ((mod_flags & Modifiers.PRIVATE) != 0)
+					t = TypeAttributes.NotPublic;
+			} else {
+				if ((mod_flags & Modifiers.PUBLIC) != 0)
+					t = TypeAttributes.NestedPublic;
+				else if ((mod_flags & Modifiers.PRIVATE) != 0)
+					t = TypeAttributes.NestedPrivate;
+				else if ((mod_flags & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL))
+					t = TypeAttributes.NestedFamORAssem;
+				else if ((mod_flags & Modifiers.PROTECTED) != 0)
+					t = TypeAttributes.NestedFamily;
+				else if ((mod_flags & Modifiers.INTERNAL) != 0)
+					t = TypeAttributes.NestedAssembly;
+			}
+
+			if ((mod_flags & Modifiers.SEALED) != 0)
+				t |= TypeAttributes.Sealed;
+			if ((mod_flags & Modifiers.ABSTRACT) != 0)
+				t |= TypeAttributes.Abstract;
+
+			return t;
+		}
+
+		public static FieldAttributes FieldAttr (Modifiers mod_flags)
+		{
+			FieldAttributes fa = 0;
+
+			if ((mod_flags & Modifiers.PUBLIC) != 0)
+				fa |= FieldAttributes.Public;
+			if ((mod_flags & Modifiers.PRIVATE) != 0)
+				fa |= FieldAttributes.Private;
+			if ((mod_flags & Modifiers.PROTECTED) != 0) {
+				if ((mod_flags & Modifiers.INTERNAL) != 0)
+					fa |= FieldAttributes.FamORAssem;
+				else 
+					fa |= FieldAttributes.Family;
+			} else {
+				if ((mod_flags & Modifiers.INTERNAL) != 0)
+					fa |= FieldAttributes.Assembly;
+			}
+
+			if ((mod_flags & Modifiers.STATIC) != 0)
+				fa |= FieldAttributes.Static;
+			if ((mod_flags & Modifiers.READONLY) != 0)
+				fa |= FieldAttributes.InitOnly;
+
+			return fa;
+		}
+
+		public static MethodAttributes MethodAttr (Modifiers mod_flags)
+		{
+			MethodAttributes ma = MethodAttributes.HideBySig;
+
+			switch (mod_flags & Modifiers.AccessibilityMask) {
+			case Modifiers.PUBLIC:
+				ma |= MethodAttributes.Public;
+				break;
+			case Modifiers.PRIVATE:
+				ma |= MethodAttributes.Private;
+				break;
+			case Modifiers.PROTECTED | Modifiers.INTERNAL:
+				ma |= MethodAttributes.FamORAssem;
+				break;
+			case Modifiers.PROTECTED:
+				ma |= MethodAttributes.Family;
+				break;
+			case Modifiers.INTERNAL:
+				ma |= MethodAttributes.Assembly;
+				break;
+			default:
+				throw new NotImplementedException (mod_flags.ToString ());
+			}
+
+			if ((mod_flags & Modifiers.STATIC) != 0)
+				ma |= MethodAttributes.Static;
+			if ((mod_flags & Modifiers.ABSTRACT) != 0) {
+				ma |= MethodAttributes.Abstract | MethodAttributes.Virtual;
+			}
+			if ((mod_flags & Modifiers.SEALED) != 0)
+				ma |= MethodAttributes.Final;
+
+			if ((mod_flags & Modifiers.VIRTUAL) != 0)
+				ma |= MethodAttributes.Virtual;
+
+			if ((mod_flags & Modifiers.OVERRIDE) != 0) {
+				ma |= MethodAttributes.Virtual;
+			} else {
+				if ((ma & MethodAttributes.Virtual) != 0)
+					ma |= MethodAttributes.NewSlot;
+			}
+			
+			return ma;
+		}
+
+		// <summary>
+		//   Checks the object @mod modifiers to be in @allowed.
+		//   Returns the new mask.  Side effect: reports any
+		//   incorrect attributes. 
+		// </summary>
+		public static Modifiers Check (Modifiers allowed, Modifiers mod, Modifiers def_access, Location l, Report Report)
+		{
+			int invalid_flags = (~(int) allowed) & ((int) mod & ((int) Modifiers.TOP - 1));
+			int i;
+
+			if (invalid_flags == 0){
+				//
+				// If no accessibility bits provided
+				// then provide the defaults.
+				//
+				if ((mod & Modifiers.AccessibilityMask) == 0) {
+					mod |= def_access;
+					if (def_access != 0)
+						mod |= Modifiers.DEFAULT_ACCESS_MODIFIER;
+					return mod;
+				}
+
+				return mod;
+			}
+
+			for (i = 1; i < (int) Modifiers.TOP; i <<= 1) {
+				if ((i & invalid_flags) == 0)
+					continue;
+
+				Error_InvalidModifier ((Modifiers)i, l, Report);
+			}
+
+			return allowed & mod;
+		}
+
+		static void Error_InvalidModifier (Modifiers mod, Location l, Report Report)
+		{
+			Report.Error (106, l, "The modifier `{0}' is not valid for this item",
+				Name (mod));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/module.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/module.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/module.cs	(revision 11807)
@@ -0,0 +1,713 @@
+//
+// module.cs: keeps a tree representation of the generated code
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Marek Safar  (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using Mono.CompilerServices.SymbolWriter;
+using System.Linq;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	//
+	// Module (top-level type) container
+	//
+	public sealed class ModuleContainer : TypeContainer
+	{
+#if STATIC
+		//
+		// Compiler generated container for static data
+		//
+		sealed class StaticDataContainer : CompilerGeneratedContainer
+		{
+			readonly Dictionary<int, Struct> size_types;
+			int fields;
+
+			public StaticDataContainer (ModuleContainer module)
+				: base (module, new MemberName ("<PrivateImplementationDetails>" + module.builder.ModuleVersionId.ToString ("B"), Location.Null),
+					Modifiers.STATIC | Modifiers.INTERNAL)
+			{
+				size_types = new Dictionary<int, Struct> ();
+			}
+
+			public override void CloseContainer ()
+			{
+				base.CloseContainer ();
+
+				foreach (var entry in size_types) {
+					entry.Value.CloseContainer ();
+				}
+			}
+
+			public FieldSpec DefineInitializedData (byte[] data, Location loc)
+			{
+				Struct size_type;
+				if (!size_types.TryGetValue (data.Length, out size_type)) {
+					//
+					// Build common type for this data length. We cannot use
+					// DefineInitializedData because it creates public type,
+					// and its name is not unique among modules
+					//
+					size_type = new Struct (this, new MemberName ("$ArrayType=" + data.Length, loc), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED, null);
+					size_type.CreateContainer ();
+					size_type.DefineContainer ();
+
+					size_types.Add (data.Length, size_type);
+
+					// It has to work even if StructLayoutAttribute does not exist
+					size_type.TypeBuilder.__SetLayout (1, data.Length);
+				}
+
+				var name = "$field-" + fields.ToString ("X");
+				++fields;
+				const Modifiers fmod = Modifiers.STATIC | Modifiers.INTERNAL;
+				var fbuilder = TypeBuilder.DefineField (name, size_type.CurrentType.GetMetaInfo (), ModifiersExtensions.FieldAttr (fmod) | FieldAttributes.HasFieldRVA);
+				fbuilder.__SetDataAndRVA (data);
+
+				return new FieldSpec (CurrentType, null, size_type.CurrentType, fbuilder, fmod);
+			}
+		}
+
+		StaticDataContainer static_data;
+
+		//
+		// Makes const data field inside internal type container
+		//
+		public FieldSpec MakeStaticData (byte[] data, Location loc)
+		{
+			if (static_data == null) {
+				static_data = new StaticDataContainer (this);
+				static_data.CreateContainer ();
+				static_data.DefineContainer ();
+
+				AddCompilerGeneratedClass (static_data);
+			}
+
+			return static_data.DefineInitializedData (data, loc);
+		}
+#endif
+
+		public sealed class PatternMatchingHelper : CompilerGeneratedContainer
+		{
+			public PatternMatchingHelper (ModuleContainer module)
+				: base (module, new MemberName ("<PatternMatchingHelper>", Location.Null),
+					Modifiers.STATIC | Modifiers.INTERNAL | Modifiers.DEBUGGER_HIDDEN)
+			{
+			}
+
+			public Method NumberMatcher { get; private set; }
+
+			protected override bool DoDefineMembers ()
+			{
+				if (!base.DoDefineMembers ())
+					return false;
+
+				NumberMatcher = GenerateNumberMatcher ();
+				return true;
+			}
+
+			Method GenerateNumberMatcher ()
+			{
+				var loc = Location;
+				var parameters = ParametersCompiled.CreateFullyResolved (
+					new [] {
+						new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc),
+						new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "value", 0, null, loc),
+						new Parameter (new TypeExpression (Compiler.BuiltinTypes.Bool, loc), "enumType", 0, null, loc),
+					},
+					new [] {
+						Compiler.BuiltinTypes.Object,
+						Compiler.BuiltinTypes.Object,
+						Compiler.BuiltinTypes.Bool
+					});
+
+				var m = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
+					Modifiers.PUBLIC | Modifiers.STATIC | Modifiers.DEBUGGER_HIDDEN, new MemberName ("NumberMatcher", loc),
+					parameters, null);
+
+				parameters [0].Resolve (m, 0);
+				parameters [1].Resolve (m, 1);
+				parameters [2].Resolve (m, 2);
+
+				ToplevelBlock top_block = new ToplevelBlock (Compiler, parameters, loc);
+				m.Block = top_block;
+
+				//
+				// if (enumType)
+				//		return Equals (obj, value);
+				//
+				var equals_args = new Arguments (2);
+				equals_args.Add (new Argument (top_block.GetParameterReference (0, loc)));
+				equals_args.Add (new Argument (top_block.GetParameterReference (1, loc)));
+
+				var if_type = new If (
+					              top_block.GetParameterReference (2, loc),
+					              new Return (new Invocation (new SimpleName ("Equals", loc), equals_args), loc),
+					              loc);
+
+				top_block.AddStatement (if_type);
+
+				//
+				// if (obj is Enum || obj == null)
+				//		return false;
+				//
+
+				var if_enum = new If (
+					              new Binary (Binary.Operator.LogicalOr,
+						              new Is (top_block.GetParameterReference (0, loc), new TypeExpression (Compiler.BuiltinTypes.Enum, loc), loc),
+						              new Binary (Binary.Operator.Equality, top_block.GetParameterReference (0, loc), new NullLiteral (loc))),
+					              new Return (new BoolLiteral (Compiler.BuiltinTypes, false, loc), loc),
+					              loc);
+
+				top_block.AddStatement (if_enum);
+
+
+				var system_convert = new MemberAccess (new QualifiedAliasMember ("global", "System", loc), "Convert", loc);
+
+				//
+				// var converted = System.Convert.ChangeType (obj, System.Convert.GetTypeCode (value));
+				//
+				var lv_converted = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Object, top_block, loc);
+
+				var arguments_gettypecode = new Arguments (1);
+				arguments_gettypecode.Add (new Argument (top_block.GetParameterReference (1, loc)));
+
+				var gettypecode = new Invocation (new MemberAccess (system_convert, "GetTypeCode", loc), arguments_gettypecode);
+
+				var arguments_changetype = new Arguments (1);
+				arguments_changetype.Add (new Argument (top_block.GetParameterReference (0, loc)));
+				arguments_changetype.Add (new Argument (gettypecode));
+
+				var changetype = new Invocation (new MemberAccess (system_convert, "ChangeType", loc), arguments_changetype);
+
+				top_block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (lv_converted, loc), changetype, loc)));
+
+
+				//
+				// return converted.Equals (value)
+				//
+				var equals_arguments = new Arguments (1);
+				equals_arguments.Add (new Argument (top_block.GetParameterReference (1, loc)));
+				var equals_invocation = new Invocation (new MemberAccess (new LocalVariableReference (lv_converted, loc), "Equals"), equals_arguments);
+				top_block.AddStatement (new Return (equals_invocation, loc));
+
+				m.Define ();
+				m.PrepareEmit ();
+				AddMember (m);
+
+				return m;
+			}
+		}
+
+		PatternMatchingHelper pmh;
+
+		public PatternMatchingHelper CreatePatterMatchingHelper ()
+		{
+			if (pmh == null) {
+				pmh = new PatternMatchingHelper (this);
+
+				pmh.CreateContainer ();
+				pmh.DefineContainer ();
+				pmh.Define ();
+				AddCompilerGeneratedClass (pmh);
+			}
+
+			return pmh;
+		}
+
+		public CharSet? DefaultCharSet;
+		public TypeAttributes DefaultCharSetType = TypeAttributes.AnsiClass;
+
+		readonly Dictionary<int, List<AnonymousTypeClass>> anonymous_types;
+		readonly Dictionary<ArrayContainer.TypeRankPair, ArrayContainer> array_types;
+		readonly Dictionary<TypeSpec, PointerContainer> pointer_types;
+		readonly Dictionary<TypeSpec, ReferenceContainer> reference_types;
+		readonly Dictionary<TypeSpec, MethodSpec> attrs_cache;
+		readonly Dictionary<TypeSpec, AwaiterDefinition> awaiters;
+
+		AssemblyDefinition assembly;
+		readonly CompilerContext context;
+		readonly RootNamespace global_ns;
+		readonly Dictionary<string, RootNamespace> alias_ns;
+
+		ModuleBuilder builder;
+
+		bool has_extenstion_method;
+
+		PredefinedAttributes predefined_attributes;
+		PredefinedTypes predefined_types;
+		PredefinedMembers predefined_members;
+
+		public Binary.PredefinedOperator[] OperatorsBinaryEqualityLifted;
+		public Binary.PredefinedOperator[] OperatorsBinaryLifted;
+
+		static readonly string[] attribute_targets = new string[] { "assembly", "module" };
+
+		public ModuleContainer (CompilerContext context)
+			: base (null, MemberName.Null, null, 0)
+		{
+			this.context = context;
+
+			caching_flags &= ~(Flags.Obsolete_Undetected | Flags.Excluded_Undetected);
+
+			containers = new List<TypeContainer> ();
+			anonymous_types = new Dictionary<int, List<AnonymousTypeClass>> ();
+			global_ns = new GlobalRootNamespace ();
+			alias_ns = new Dictionary<string, RootNamespace> ();
+			array_types = new Dictionary<ArrayContainer.TypeRankPair, ArrayContainer> ();
+			pointer_types = new Dictionary<TypeSpec, PointerContainer> ();
+			reference_types = new Dictionary<TypeSpec, ReferenceContainer> ();
+			attrs_cache = new Dictionary<TypeSpec, MethodSpec> ();
+			awaiters = new Dictionary<TypeSpec, AwaiterDefinition> ();
+		}
+
+		#region Properties
+
+		internal Dictionary<ArrayContainer.TypeRankPair, ArrayContainer> ArrayTypesCache {
+			get {
+				return array_types;
+			}
+		}
+
+		//
+		// Cache for parameter-less attributes
+		//
+		internal Dictionary<TypeSpec, MethodSpec> AttributeConstructorCache {
+			get {
+				return attrs_cache;
+			}
+		}
+
+ 		public override AttributeTargets AttributeTargets {
+ 			get {
+ 				return AttributeTargets.Assembly;
+ 			}
+		}
+
+		public ModuleBuilder Builder {
+			get {
+				return builder;
+			}
+		}
+
+		public override CompilerContext Compiler {
+			get {
+				return context;
+			}
+		}
+
+		public int CounterAnonymousTypes { get; set; }
+
+		public AssemblyDefinition DeclaringAssembly {
+			get {
+				return assembly;
+			}
+		}
+
+		internal DocumentationBuilder DocumentationBuilder {
+			get; set;
+		}
+
+		public override string DocCommentHeader {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		public Evaluator Evaluator {
+			get; set;
+		}
+
+		public bool HasDefaultCharSet {
+			get {
+				return DefaultCharSet.HasValue;
+			}
+		}
+
+		public bool HasExtensionMethod {
+			get {
+				return has_extenstion_method;
+			}
+			set {
+				has_extenstion_method = value;
+			}
+		}
+
+		public bool HasTypesFullyDefined {
+			get; set;
+		}
+
+		//
+		// Returns module global:: namespace
+		//
+		public RootNamespace GlobalRootNamespace {
+		    get {
+		        return global_ns;
+		    }
+		}
+
+		public override ModuleContainer Module {
+			get {
+				return this;
+			}
+		}
+
+		internal Dictionary<TypeSpec, PointerContainer> PointerTypesCache {
+			get {
+				return pointer_types;
+			}
+		}
+
+		internal PredefinedAttributes PredefinedAttributes {
+			get {
+				return predefined_attributes;
+			}
+		}
+
+		internal PredefinedMembers PredefinedMembers {
+			get {
+				return predefined_members;
+			}
+		}
+
+		internal PredefinedTypes PredefinedTypes {
+			get {
+				return predefined_types;
+			}
+		}
+
+		internal Dictionary<TypeSpec, ReferenceContainer> ReferenceTypesCache {
+			get {
+				return reference_types;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+
+		#endregion
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public void AddAnonymousType (AnonymousTypeClass type)
+		{
+			List<AnonymousTypeClass> existing;
+			if (!anonymous_types.TryGetValue (type.Parameters.Count, out existing))
+			if (existing == null) {
+				existing = new List<AnonymousTypeClass> ();
+				anonymous_types.Add (type.Parameters.Count, existing);
+			}
+
+			existing.Add (type);
+		}
+
+		public void AddAttribute (Attribute attr, IMemberContext context)
+		{
+			attr.AttachTo (this, context);
+
+			if (attributes == null) {
+				attributes = new Attributes (attr);
+				return;
+			}
+
+			attributes.AddAttribute (attr);
+		}
+
+		public override void AddTypeContainer (TypeContainer tc)
+		{
+			AddTypeContainerMember (tc);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Target == AttributeTargets.Assembly) {
+				assembly.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			if (a.Type == pa.DefaultCharset) {
+				switch (a.GetCharSetValue ()) {
+				case CharSet.Ansi:
+				case CharSet.None:
+					break;
+				case CharSet.Auto:
+					DefaultCharSet = CharSet.Auto;
+					DefaultCharSetType = TypeAttributes.AutoClass;
+					break;
+				case CharSet.Unicode:
+					DefaultCharSet = CharSet.Unicode;
+					DefaultCharSetType = TypeAttributes.UnicodeClass;
+					break;
+				default:
+					Report.Error (1724, a.Location, "Value specified for the argument to `{0}' is not valid",
+						a.GetSignatureForError ());
+					break;
+				}
+			} else if (a.Type == pa.CLSCompliant) {
+				Attribute cls = DeclaringAssembly.CLSCompliantAttribute;
+				if (cls == null) {
+					Report.Warning (3012, 1, a.Location,
+						"You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
+				} else if (DeclaringAssembly.IsCLSCompliant != a.GetBoolean ()) {
+					Report.SymbolRelatedToPreviousError (cls.Location, cls.GetSignatureForError ());
+					Report.Warning (3017, 1, a.Location,
+						"You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
+					return;
+				}
+			}
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		public override void CloseContainer ()
+		{
+			if (anonymous_types != null) {
+				foreach (var atypes in anonymous_types)
+					foreach (var at in atypes.Value)
+						at.CloseContainer ();
+			}
+
+			base.CloseContainer ();
+		}
+
+		public TypeBuilder CreateBuilder (string name, TypeAttributes attr, int typeSize)
+		{
+			return builder.DefineType (name, attr, null, typeSize);
+		}
+
+		//
+		// Creates alias global namespace
+		//
+		public RootNamespace CreateRootNamespace (string alias)
+		{
+			if (alias == global_ns.Alias) {
+				RootNamespace.Error_GlobalNamespaceRedefined (Report, Location.Null);
+				return global_ns;
+			}
+
+			RootNamespace rn;
+			if (!alias_ns.TryGetValue (alias, out rn)) {
+				rn = new RootNamespace (alias);
+				alias_ns.Add (alias, rn);
+			}
+
+			return rn;
+		}
+
+		public void Create (AssemblyDefinition assembly, ModuleBuilder moduleBuilder)
+		{
+			this.assembly = assembly;
+			builder = moduleBuilder;
+		}
+
+		public override bool Define ()
+		{
+			DefineContainer ();
+
+			ExpandBaseInterfaces ();
+
+			base.Define ();
+
+			HasTypesFullyDefined = true;
+
+			return true;
+		}
+
+		public override bool DefineContainer ()
+		{
+			DefineNamespace ();
+
+			return base.DefineContainer ();
+		}
+
+		public void EnableRedefinition ()
+		{
+			is_defined = false;
+		}
+
+		public override void EmitContainer ()
+		{
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			if (Compiler.Settings.Unsafe && !assembly.IsSatelliteAssembly) {
+				var pa = PredefinedAttributes.UnverifiableCode;
+				if (pa.IsDefined)
+					pa.EmitAttribute (builder);
+			}
+
+			foreach (var tc in containers) {
+				tc.PrepareEmit ();
+			}
+
+			base.EmitContainer ();
+
+			if (Compiler.Report.Errors == 0 && !Compiler.Settings.WriteMetadataOnly)
+				VerifyMembers ();
+
+			if (anonymous_types != null) {
+				foreach (var atypes in anonymous_types)
+					foreach (var at in atypes.Value)
+						at.EmitContainer ();
+			}
+		}
+
+		internal override void GenerateDocComment (DocumentationBuilder builder)
+		{
+			foreach (var tc in containers)
+				tc.GenerateDocComment (builder);
+		}
+
+		public AnonymousTypeClass GetAnonymousType (IList<AnonymousTypeParameter> parameters)
+		{
+			List<AnonymousTypeClass> candidates;
+			if (!anonymous_types.TryGetValue (parameters.Count, out candidates))
+				return null;
+
+			int i;
+			foreach (AnonymousTypeClass at in candidates) {
+				for (i = 0; i < parameters.Count; ++i) {
+					if (!parameters [i].Equals (at.Parameters [i]))
+						break;
+				}
+
+				if (i == parameters.Count)
+					return at;
+			}
+
+			return null;
+		}
+
+		//
+		// Return container with awaiter definition. It never returns null
+		// but all container member can be null for easier error reporting
+		//
+		public AwaiterDefinition GetAwaiter (TypeSpec type)
+		{
+			AwaiterDefinition awaiter;
+			if (awaiters.TryGetValue (type, out awaiter))
+				return awaiter;
+
+			awaiter = new AwaiterDefinition ();
+
+			//
+			// Predefined: bool IsCompleted { get; } 
+			//
+			awaiter.IsCompleted = MemberCache.FindMember (type, MemberFilter.Property ("IsCompleted", Compiler.BuiltinTypes.Bool),
+				BindingRestriction.InstanceOnly) as PropertySpec;
+
+			//
+			// Predefined: GetResult ()
+			//
+			// The method return type is also result type of await expression
+			//
+			awaiter.GetResult = MemberCache.FindMember (type, MemberFilter.Method ("GetResult", 0,
+				ParametersCompiled.EmptyReadOnlyParameters, null),
+				BindingRestriction.InstanceOnly) as MethodSpec;
+
+			//
+			// Predefined: INotifyCompletion.OnCompleted (System.Action)
+			//
+			var nc = PredefinedTypes.INotifyCompletion;
+			awaiter.INotifyCompletion = !nc.Define () || type.ImplementsInterface (nc.TypeSpec, false);
+
+			awaiters.Add (type, awaiter);
+			return awaiter;
+		}
+
+		public override void GetCompletionStartingWith (string prefix, List<string> results)
+		{
+			var names = Evaluator.GetVarNames ();
+			results.AddRange (names.Where (l => l.StartsWith (prefix)));
+		}
+
+		public RootNamespace GetRootNamespace (string name)
+		{
+			RootNamespace rn;
+			alias_ns.TryGetValue (name, out rn);
+			return rn;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return "<module>";
+		}
+
+		public Binary.PredefinedOperator[] GetPredefinedEnumAritmeticOperators (TypeSpec enumType, bool nullable)
+		{
+			TypeSpec underlying;
+			Binary.Operator mask = 0;
+
+			if (nullable) {
+				underlying = Nullable.NullableInfo.GetEnumUnderlyingType (this, enumType);
+				mask = Binary.Operator.NullableMask;
+			} else {
+				underlying = EnumSpec.GetUnderlyingType (enumType);
+			}
+
+			var operators = new[] {
+				new Binary.PredefinedOperator (enumType, underlying,
+					mask | Binary.Operator.AdditionMask | Binary.Operator.SubtractionMask | Binary.Operator.DecomposedMask, enumType),
+				new Binary.PredefinedOperator (underlying, enumType,
+					mask | Binary.Operator.AdditionMask | Binary.Operator.SubtractionMask | Binary.Operator.DecomposedMask, enumType),
+				new Binary.PredefinedOperator (enumType, mask | Binary.Operator.SubtractionMask, underlying)
+			};
+
+			return operators;
+		}
+
+		public void InitializePredefinedTypes ()
+		{
+			predefined_attributes = new PredefinedAttributes (this);
+			predefined_types = new PredefinedTypes (this);
+			predefined_members = new PredefinedMembers (this);
+
+			OperatorsBinaryEqualityLifted = Binary.CreateEqualityLiftedOperatorsTable (this);
+			OperatorsBinaryLifted = Binary.CreateStandardLiftedOperatorsTable (this);
+		}
+
+		public override bool IsClsComplianceRequired ()
+		{
+			return DeclaringAssembly.IsCLSCompliant;
+		}
+
+		public Attribute ResolveAssemblyAttribute (PredefinedAttribute a_type)
+		{
+			Attribute a = OptAttributes.Search ("assembly", a_type);
+			if (a != null) {
+				a.Resolve ();
+			}
+			return a;
+		}
+
+		public void SetDeclaringAssembly (AssemblyDefinition assembly)
+		{
+			// TODO: This setter is quite ugly but I have not found a way around it yet
+			this.assembly = assembly;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/namespace.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/namespace.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/namespace.cs	(revision 11807)
@@ -0,0 +1,1584 @@
+//
+// namespace.cs: Tracks namespaces
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@seznam.cz)
+//
+// Copyright 2001 Ximian, Inc.
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Mono.CompilerServices.SymbolWriter;
+
+namespace Mono.CSharp {
+
+	public class RootNamespace : Namespace {
+
+		readonly string alias_name;
+		readonly Dictionary<string, Namespace> all_namespaces;
+
+		public RootNamespace (string alias_name)
+			: base ()
+		{
+			this.alias_name = alias_name;
+			RegisterNamespace (this);
+
+			all_namespaces = new Dictionary<string, Namespace> ();
+			all_namespaces.Add ("", this);
+		}
+
+		public string Alias {
+			get {
+				return alias_name;
+			}
+		}
+
+		public static void Error_GlobalNamespaceRedefined (Report report, Location loc)
+		{
+			report.Error (1681, loc, "The global extern alias cannot be redefined");
+		}
+
+		//
+		// For better error reporting where we try to guess missing using directive
+		//
+		public List<string> FindTypeNamespaces (IMemberContext ctx, string name, int arity)
+		{
+			List<string> res = null;
+
+			foreach (var ns in all_namespaces) {
+				var type = ns.Value.LookupType (ctx, name, arity, LookupMode.Normal, Location.Null);
+				if (type != null) {
+					if (res == null)
+						res = new List<string> ();
+
+					res.Add (ns.Key);
+				}
+			}
+
+			return res;
+		}
+
+		//
+		// For better error reporting where compiler tries to guess missing using directive
+		//
+		public List<string> FindExtensionMethodNamespaces (IMemberContext ctx, string name, int arity)
+		{
+			List<string> res = null;
+
+			foreach (var ns in all_namespaces) {
+				var methods = ns.Value.LookupExtensionMethod (ctx, name, arity);
+				if (methods != null) {
+					if (res == null)
+						res = new List<string> ();
+
+					res.Add (ns.Key);
+				}
+			}
+
+			return res;
+		}
+
+		public void RegisterNamespace (Namespace child)
+		{
+			if (child != this)
+				all_namespaces.Add (child.Name, child);
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return alias_name + "::";
+		}
+	}
+
+	public sealed class GlobalRootNamespace : RootNamespace
+	{
+		public GlobalRootNamespace ()
+			: base ("global")
+		{
+		}
+	}
+
+	//
+	// Namespace cache for imported and compiled namespaces
+	//
+	public class Namespace
+	{
+		readonly Namespace parent;
+		string fullname;
+		protected Dictionary<string, Namespace> namespaces;
+		protected Dictionary<string, IList<TypeSpec>> types;
+		List<TypeSpec> extension_method_types;
+		Dictionary<string, TypeSpec> cached_types;
+		bool cls_checked;
+
+		/// <summary>
+		///   Constructor Takes the current namespace and the
+		///   name.  This is bootstrapped with parent == null
+		///   and name = ""
+		/// </summary>
+		public Namespace (Namespace parent, string name)
+			: this ()
+		{
+			if (name == null)
+				throw new ArgumentNullException ("name");
+
+			this.parent = parent;
+
+			string pname = parent != null ? parent.fullname : null;
+				
+			if (pname == null)
+				fullname = name;
+			else
+				fullname = pname + "." + name;
+
+			while (parent.parent != null)
+				parent = parent.parent;
+
+			var root = parent as RootNamespace;
+			if (root == null)
+				throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
+
+			root.RegisterNamespace (this);
+		}
+
+		protected Namespace ()
+		{
+			namespaces = new Dictionary<string, Namespace> ();
+			cached_types = new Dictionary<string, TypeSpec> ();
+		}
+
+		#region Properties
+
+		/// <summary>
+		///   The qualified name of the current namespace
+		/// </summary>
+		public string Name {
+			get { return fullname; }
+		}
+
+		/// <summary>
+		///   The parent of this namespace, used by the parser to "Pop"
+		///   the current namespace declaration
+		/// </summary>
+		public Namespace Parent {
+			get { return parent; }
+		}
+
+		#endregion
+
+		public Namespace AddNamespace (MemberName name)
+		{
+			var ns_parent = name.Left == null ? this : AddNamespace (name.Left);
+			return ns_parent.TryAddNamespace (name.Basename);
+		}
+
+		Namespace TryAddNamespace (string name)
+		{
+			Namespace ns;
+
+			if (!namespaces.TryGetValue (name, out ns)) {
+				ns = new Namespace (this, name);
+				namespaces.Add (name, ns);
+			}
+
+			return ns;
+		}
+
+		public bool TryGetNamespace (string name, out Namespace ns)
+		{
+			return namespaces.TryGetValue (name, out ns);
+		}
+
+		// TODO: Replace with CreateNamespace where MemberName is created for the method call
+		public Namespace GetNamespace (string name, bool create)
+		{
+			int pos = name.IndexOf ('.');
+
+			Namespace ns;
+			string first;
+			if (pos >= 0)
+				first = name.Substring (0, pos);
+			else
+				first = name;
+
+			if (!namespaces.TryGetValue (first, out ns)) {
+				if (!create)
+					return null;
+
+				ns = new Namespace (this, first);
+				namespaces.Add (first, ns);
+			}
+
+			if (pos >= 0)
+				ns = ns.GetNamespace (name.Substring (pos + 1), create);
+
+			return ns;
+		}
+
+		public IList<TypeSpec> GetAllTypes (string name)
+		{
+			IList<TypeSpec> found;
+			if (types == null || !types.TryGetValue (name, out found))
+				return null;
+
+			return found;
+		}
+
+		public virtual string GetSignatureForError ()
+		{
+			return fullname;
+		}
+
+		public TypeSpec LookupType (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
+		{
+			if (types == null)
+				return null;
+
+			TypeSpec best = null;
+			if (arity == 0 && cached_types.TryGetValue (name, out best)) {
+				if (best != null || mode != LookupMode.IgnoreAccessibility)
+					return best;
+			}
+
+			IList<TypeSpec> found;
+			if (!types.TryGetValue (name, out found))
+				return null;
+
+			foreach (var ts in found) {
+				if (ts.Arity == arity || mode == LookupMode.NameOf) {
+					if (best == null) {
+						if ((ts.Modifiers & Modifiers.INTERNAL) != 0 && !ts.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly) && mode != LookupMode.IgnoreAccessibility)
+							continue;
+
+						best = ts;
+						continue;
+					}
+
+					if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
+						if (ts.Kind == MemberKind.MissingType)
+							continue;
+
+						if (best.Kind == MemberKind.MissingType) {
+							best = ts;
+							continue;
+						}
+
+						if (mode == LookupMode.Normal) {
+							ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
+							ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
+							ctx.Module.Compiler.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
+						}
+
+						break;
+					}
+
+					if (best.MemberDefinition.IsImported)
+						best = ts;
+
+					if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly))
+						continue;
+
+					if (mode != LookupMode.Normal)
+						continue;
+
+					if (ts.MemberDefinition.IsImported) {
+						ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
+						ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
+					}
+
+					ctx.Module.Compiler.Report.Warning (436, 2, loc,
+						"The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
+						best.GetSignatureForError ());
+				}
+
+				//
+				// Lookup for the best candidate with the closest arity match
+				//
+				if (arity < 0) {
+					if (best == null) {
+						best = ts;
+					} else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
+						best = ts;
+					}
+				}
+			}
+
+			// TODO MemberCache: Cache more
+			if (arity == 0 && mode == LookupMode.Normal)
+				cached_types.Add (name, best);
+
+			if (best != null) {
+				var dep = best.GetMissingDependencies ();
+				if (dep != null)
+					ImportedTypeDefinition.Error_MissingDependency (ctx, dep, loc);
+			}
+
+			return best;
+		}
+
+		public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
+		{
+			var texpr = LookupType (ctx, name, arity, mode, loc);
+
+			Namespace ns;
+			if (arity == 0 && namespaces.TryGetValue (name, out ns)) {
+				if (texpr == null)
+					return new NamespaceExpression (ns, loc);
+
+				if (mode != LookupMode.Probing) {
+					//ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type);
+					// ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ns.loc, "");
+					ctx.Module.Compiler.Report.Warning (437, 2, loc,
+						"The type `{0}' conflicts with the imported namespace `{1}'. Using the definition found in the source file",
+						texpr.GetSignatureForError (), ns.GetSignatureForError ());
+				}
+
+				if (texpr.MemberDefinition.IsImported)
+					return new NamespaceExpression (ns, loc);
+			}
+
+			if (texpr == null)
+				return null;
+
+			return new TypeExpression (texpr, loc);
+		}
+
+		//
+		// Completes types with the given `prefix'
+		//
+		public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
+		{
+			if (types == null)
+				return Enumerable.Empty<string> ();
+
+			var res = from item in types
+					  where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
+					  select item.Key;
+
+			if (namespaces != null)
+				res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
+
+			return res;
+		}
+
+		// 
+		// Looks for extension method in this namespace
+		//
+		public List<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, string name, int arity)
+		{
+			if (extension_method_types == null)
+				return null;
+
+			List<MethodSpec> found = null;
+			for (int i = 0; i < extension_method_types.Count; ++i) {
+				var ts = extension_method_types[i];
+
+				//
+				// When the list was built we didn't know what members the type
+				// contains
+				//
+				if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0) {
+					if (extension_method_types.Count == 1) {
+						extension_method_types = null;
+						return found;
+					}
+
+					extension_method_types.RemoveAt (i--);
+					continue;
+				}
+
+				var res = ts.MemberCache.FindExtensionMethods (invocationContext, name, arity);
+				if (res == null)
+					continue;
+
+				if (found == null) {
+					found = res;
+				} else {
+					found.AddRange (res);
+				}
+			}
+
+			return found;
+		}
+
+		public void AddType (ModuleContainer module, TypeSpec ts)
+		{
+			if (types == null) {
+				types = new Dictionary<string, IList<TypeSpec>> (64);
+			}
+
+			if (ts.IsClass && ts.Arity == 0) {
+				var extension_method_allowed = ts.MemberDefinition.IsImported ? (ts.Modifiers & Modifiers.METHOD_EXTENSION) != 0 : (ts.IsStatic || ts.MemberDefinition.IsPartial);
+				if (extension_method_allowed) {
+					if (extension_method_types == null)
+						extension_method_types = new List<TypeSpec> ();
+
+					extension_method_types.Add (ts);
+				}
+			}
+
+			var name = ts.Name;
+			IList<TypeSpec> existing;
+			if (types.TryGetValue (name, out existing)) {
+				TypeSpec better_type;
+				TypeSpec found;
+				if (existing.Count == 1) {
+					found = existing[0];
+					if (ts.Arity == found.Arity) {
+						better_type = IsImportedTypeOverride (module, ts, found);
+						if (better_type == found)
+							return;
+
+						if (better_type != null) {
+							existing [0] = better_type;
+							return;
+						}
+					}
+
+					existing = new List<TypeSpec> ();
+					existing.Add (found);
+					types[name] = existing;
+				} else {
+					for (int i = 0; i < existing.Count; ++i) {
+						found = existing[i];
+						if (ts.Arity != found.Arity)
+							continue;
+
+						better_type = IsImportedTypeOverride (module, ts, found);
+						if (better_type == found)
+							return;
+
+						if (better_type != null) {
+							existing.RemoveAt (i);
+							--i;
+							continue;
+						}
+					}
+				}
+
+				existing.Add (ts);
+			} else {
+				types.Add (name, new TypeSpec[] { ts });
+			}
+		}
+
+		//
+		// We import any types but in the situation there are same types
+		// but one has better visibility (either public or internal with friend)
+		// the less visible type is removed from the namespace cache
+		//
+		public static TypeSpec IsImportedTypeOverride (ModuleContainer module, TypeSpec ts, TypeSpec found)
+		{
+			var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || ts.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
+			var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || found.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
+
+			if (ts_accessible && !found_accessible)
+				return ts;
+
+			// found is better always better for accessible or inaccessible ts
+			if (!ts_accessible)
+				return found;
+
+			return null;
+		}
+
+		public void RemoveContainer (TypeContainer tc)
+		{
+			types.Remove (tc.Basename);
+			cached_types.Remove (tc.Basename);
+		}
+
+		public void SetBuiltinType (BuiltinTypeSpec pts)
+		{
+			var found = types[pts.Name];
+			cached_types.Remove (pts.Name);
+			if (found.Count == 1) {
+				types[pts.Name][0] = pts;
+			} else {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public void VerifyClsCompliance ()
+		{
+			if (types == null || cls_checked)
+				return;
+
+			cls_checked = true;
+
+			// TODO: This is quite ugly way to check for CLS compliance at namespace level
+
+			var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
+			foreach (var tgroup in types.Values) {
+				foreach (var tm in tgroup) {
+					if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
+						continue;
+
+					List<TypeSpec> found;
+					if (!locase_types.TryGetValue (tm.Name, out found)) {
+						found = new List<TypeSpec> ();
+						locase_types.Add (tm.Name, found);
+					}
+
+					found.Add (tm);
+				}
+			}
+
+			foreach (var locase in locase_types.Values) {
+				if (locase.Count < 2)
+					continue;
+
+				bool all_same = true;
+				foreach (var notcompliant in locase) {
+					all_same = notcompliant.Name == locase[0].Name;
+					if (!all_same)
+						break;
+				}
+
+				if (all_same)
+					continue;
+
+				TypeContainer compiled = null;
+				foreach (var notcompliant in locase) {
+					if (!notcompliant.MemberDefinition.IsImported) {
+						if (compiled != null)
+							compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
+
+						compiled = notcompliant.MemberDefinition as TypeContainer;
+					} else {
+						compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
+					}
+				}
+
+				compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
+					"Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
+			}
+		}
+	}
+
+	public class CompilationSourceFile : NamespaceContainer
+	{
+		readonly SourceFile file;
+		CompileUnitEntry comp_unit;
+		Dictionary<string, SourceFile> include_files;
+		Dictionary<string, bool> conditionals;
+
+		public CompilationSourceFile (ModuleContainer parent, SourceFile sourceFile)
+			: this (parent)
+		{
+			this.file = sourceFile;
+		}
+
+		public CompilationSourceFile (ModuleContainer parent)
+			: base (parent)
+		{
+		}
+
+		public CompileUnitEntry SymbolUnitEntry {
+			get {
+				return comp_unit;
+			}
+		}
+
+		public IDictionary<string, bool> Conditionals {
+			get {
+				return conditionals ?? new Dictionary<string, bool> ();
+			}
+		}
+
+		public string FileName {
+			get {
+				return file.Name;
+			}
+		}
+
+		public SourceFile SourceFile {
+			get {
+				return file;
+			}
+		}
+
+		public void AddIncludeFile (SourceFile file)
+		{
+			if (file == this.file)
+				return;
+
+			if (include_files == null)
+				include_files = new Dictionary<string, SourceFile> ();
+
+			if (!include_files.ContainsKey (file.FullPathName))
+				include_files.Add (file.FullPathName, file);
+		}
+
+		public void AddDefine (string value)
+		{
+			if (conditionals == null)
+				conditionals = new Dictionary<string, bool> (2);
+
+			conditionals[value] = true;
+		}
+
+		public void AddUndefine (string value)
+		{
+			if (conditionals == null)
+				conditionals = new Dictionary<string, bool> (2);
+
+			conditionals[value] = false;
+		}
+
+		public override void PrepareEmit ()
+		{
+			var sw = Module.DeclaringAssembly.SymbolWriter;
+			if (sw != null) {
+				CreateUnitSymbolInfo (sw);
+			}
+
+			base.PrepareEmit ();
+		}
+
+		//
+		// Creates symbol file index in debug symbol file
+		//
+		void CreateUnitSymbolInfo (MonoSymbolFile symwriter)
+		{
+			var si = file.CreateSymbolInfo (symwriter);
+			comp_unit = new CompileUnitEntry (symwriter, si);
+
+			if (include_files != null) {
+				foreach (SourceFile include in include_files.Values) {
+					si = include.CreateSymbolInfo (symwriter);
+					comp_unit.AddFile (si);
+				}
+			}
+		}
+
+		public bool IsConditionalDefined (string value)
+		{
+			if (conditionals != null) {
+				bool res;
+				if (conditionals.TryGetValue (value, out res))
+					return res;
+
+				// When conditional was undefined
+				if (conditionals.ContainsKey (value))
+					return false;
+			}
+
+			return Compiler.Settings.IsConditionalSymbolDefined (value);
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+	}
+
+
+	//
+	// Namespace block as created by the parser
+	//
+	public class NamespaceContainer : TypeContainer, IMemberContext
+	{
+		static readonly Namespace[] empty_namespaces = new Namespace[0];
+
+		readonly Namespace ns;
+
+		public new readonly NamespaceContainer Parent;
+
+		List<UsingNamespace> clauses;
+
+		// Used by parsed to check for parser errors
+		public bool DeclarationFound;
+
+		Namespace[] namespace_using_table;
+		TypeSpec[] types_using_table;
+		Dictionary<string, UsingAliasNamespace> aliases;
+		public readonly MemberName RealMemberName;
+
+		public NamespaceContainer (MemberName name, NamespaceContainer parent)
+			: base (parent, name, null, MemberKind.Namespace)
+		{
+			this.RealMemberName = name;
+			this.Parent = parent;
+			this.ns = parent.NS.AddNamespace (name);
+
+			containers = new List<TypeContainer> ();
+		}
+
+		protected NamespaceContainer (ModuleContainer parent)
+			: base (parent, null, null, MemberKind.Namespace)
+		{
+			ns = parent.GlobalRootNamespace;
+			containers = new List<TypeContainer> (2);
+		}
+
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		public override string DocCommentHeader {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		public Namespace NS {
+			get {
+				return ns;
+			}
+		}
+
+		public List<UsingNamespace> Usings {
+			get {
+				return clauses;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		#endregion
+
+		public void AddUsing (UsingNamespace un)
+		{
+			if (DeclarationFound){
+				Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
+			}
+
+			if (clauses == null)
+				clauses = new List<UsingNamespace> ();
+
+			clauses.Add (un);
+		}
+
+		public void AddUsing (UsingAliasNamespace un)
+		{
+			if (DeclarationFound){
+				Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
+			}
+
+			AddAlias (un);
+		}
+
+		void AddAlias (UsingAliasNamespace un)
+		{
+			if (clauses == null) {
+				clauses = new List<UsingNamespace> ();
+			} else {
+				foreach (var entry in clauses) {
+					var a = entry as UsingAliasNamespace;
+					if (a != null && a.Alias.Value == un.Alias.Value) {
+						Compiler.Report.SymbolRelatedToPreviousError (a.Location, "");
+						Compiler.Report.Error (1537, un.Location,
+							"The using alias `{0}' appeared previously in this namespace", un.Alias.Value);
+					}
+				}
+			}
+
+			clauses.Add (un);
+		}
+
+		public override void AddPartial (TypeDefinition next_part)
+		{
+			var existing = ns.LookupType (this, next_part.MemberName.Name, next_part.MemberName.Arity, LookupMode.Probing, Location.Null);
+			var td = existing != null ? existing.MemberDefinition as TypeDefinition : null;
+			AddPartial (next_part, td);
+		}
+
+		public override void AddTypeContainer (TypeContainer tc)
+		{
+			string name = tc.Basename;
+
+			var mn = tc.MemberName;
+			while (mn.Left != null) {
+				mn = mn.Left;
+				name = mn.Name;
+			}
+
+			var names_container = Parent == null ? Module : (TypeContainer) this;
+
+			MemberCore mc;
+			if (names_container.DefinedNames.TryGetValue (name, out mc)) {
+				if (tc is NamespaceContainer && mc is NamespaceContainer) {
+					AddTypeContainerMember (tc);
+					return;
+				}
+
+				Report.SymbolRelatedToPreviousError (mc);
+				if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (tc is ClassOrStruct || tc is Interface)) {
+					Error_MissingPartialModifier (tc);
+				} else {
+					Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
+						GetSignatureForError (), mn.GetSignatureForError ());
+				}
+			} else {
+				names_container.DefinedNames.Add (name, tc);
+
+				var tdef = tc.PartialContainer;
+				if (tdef != null) {
+					//
+					// Same name conflict in different namespace containers
+					//
+					var conflict = ns.GetAllTypes (name);
+					if (conflict != null) {
+						foreach (var e in conflict) {
+							if (e.Arity == mn.Arity) {
+								mc = (MemberCore) e.MemberDefinition;
+								break;
+							}
+						}
+					}
+
+					if (mc != null) {
+						Report.SymbolRelatedToPreviousError (mc);
+						Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
+							GetSignatureForError (), mn.GetSignatureForError ());
+					} else {
+						ns.AddType (Module, tdef.Definition);
+					}
+				}
+			}
+
+			base.AddTypeContainer (tc);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public override void EmitContainer ()
+		{
+			VerifyClsCompliance ();
+
+			base.EmitContainer ();
+		}
+
+		public ExtensionMethodCandidates LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, int position)
+		{
+			//
+			// Here we try to resume the search for extension method at the point
+			// where the last bunch of candidates was found. It's more tricky than
+			// it seems as we have to check both namespace containers and namespace
+			// in correct order.
+			//
+			// Consider:
+			// 
+			// namespace A {
+			//	using N1;
+			//  namespace B.C.D {
+			//		<our first search found candidates in A.B.C.D
+			//  }
+			// }
+			//
+			// In the example above namespace A.B.C.D, A.B.C and A.B have to be
+			// checked before we hit A.N1 using
+			//
+			ExtensionMethodCandidates candidates;
+			var container = this;
+			do {
+				candidates = container.LookupExtensionMethodCandidates (invocationContext, name, arity, ref position);
+				if (candidates != null || container.MemberName == null)
+					return candidates;
+
+				var container_ns = container.ns.Parent;
+				var mn = container.MemberName.Left;
+				int already_checked = position - 2;
+				while (already_checked-- > 0) {
+					mn = mn.Left;
+					container_ns = container_ns.Parent;
+				}
+
+				while (mn != null) {
+					++position;
+
+					var methods = container_ns.LookupExtensionMethod (invocationContext, name, arity);
+					if (methods != null) {
+						return new ExtensionMethodCandidates (invocationContext, methods, container, position);
+					}
+
+					mn = mn.Left;
+					container_ns = container_ns.Parent;
+				}
+
+				position = 0;
+				container = container.Parent;
+			} while (container != null);
+
+			return null;
+		}
+
+		ExtensionMethodCandidates LookupExtensionMethodCandidates (IMemberContext invocationContext, string name, int arity, ref int position)
+		{
+			List<MethodSpec> candidates = null;
+
+			if (position == 0) {
+				++position;
+
+				candidates = ns.LookupExtensionMethod (invocationContext, name, arity);
+				if (candidates != null) {
+					return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
+				}
+			}
+
+			if (position == 1) {
+				++position;
+
+				foreach (Namespace n in namespace_using_table) {
+					var a = n.LookupExtensionMethod (invocationContext, name, arity);
+					if (a == null)
+						continue;
+
+					if (candidates == null)
+						candidates = a;
+					else
+						candidates.AddRange (a);
+				}
+
+				if (candidates != null)
+					return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
+			}
+
+			// LAMESPEC: TODO no spec about priority over normal extension methods yet
+			if (types_using_table != null) {
+				foreach (var t in types_using_table) {
+
+					var res = t.MemberCache.FindExtensionMethods (invocationContext, name, arity);
+					if (res == null)
+						continue;
+
+					if (candidates == null)
+						candidates = res;
+					else
+						candidates.AddRange (res);
+				}
+
+				if (candidates != null)
+					return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
+			}
+
+			return null;
+		}
+
+		public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			//
+			// Only simple names (no dots) will be looked up with this function
+			//
+			FullNamedExpression resolved;
+			for (NamespaceContainer container = this; container != null; container = container.Parent) {
+				resolved = container.Lookup (name, arity, mode, loc);
+				if (resolved != null || container.MemberName == null)
+					return resolved;
+
+				var container_ns = container.ns.Parent;
+				var mn = container.MemberName.Left;
+				while (mn != null) {
+					resolved = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
+					if (resolved != null)
+						return resolved;
+
+					mn = mn.Left;
+					container_ns = container_ns.Parent;
+				}
+			}
+
+			return null;
+		}
+
+		public override void GetCompletionStartingWith (string prefix, List<string> results)
+		{
+			if (Usings == null)
+				return;
+
+			foreach (var un in Usings) {
+				if (un.Alias != null)
+					continue;
+
+				var name = un.NamespaceExpression.Name;
+				if (name.StartsWith (prefix))
+					results.Add (name);
+			}
+
+
+			IEnumerable<string> all = Enumerable.Empty<string> ();
+
+			foreach (Namespace using_ns in namespace_using_table) {
+				if (prefix.StartsWith (using_ns.Name)) {
+					int ld = prefix.LastIndexOf ('.');
+					if (ld != -1) {
+						string rest = prefix.Substring (ld + 1);
+
+						all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
+					}
+				}
+				all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
+			}
+
+			results.AddRange (all);
+
+			base.GetCompletionStartingWith (prefix, results);
+		}
+
+		
+		//
+		// Looks-up a alias named @name in this and surrounding namespace declarations
+		//
+		public FullNamedExpression LookupExternAlias (string name)
+		{
+			if (aliases == null)
+				return null;
+
+			UsingAliasNamespace uan;
+			if (aliases.TryGetValue (name, out uan) && uan is UsingExternAlias)
+				return uan.ResolvedExpression;
+
+			return null;
+		}
+		
+		//
+		// Looks-up a alias named @name in this and surrounding namespace declarations
+		//
+		public override FullNamedExpression LookupNamespaceAlias (string name)
+		{
+			for (NamespaceContainer n = this; n != null; n = n.Parent) {
+				if (n.aliases == null)
+					continue;
+
+				UsingAliasNamespace uan;
+				if (n.aliases.TryGetValue (name, out uan))
+					return uan.ResolvedExpression;
+			}
+
+			return null;
+		}
+
+		FullNamedExpression Lookup (string name, int arity, LookupMode mode, Location loc)
+		{
+			//
+			// Check whether it's in the namespace.
+			//
+			FullNamedExpression fne = ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
+
+			//
+			// Check aliases. 
+			//
+			if (aliases != null && arity == 0) {
+				UsingAliasNamespace uan;
+				if (aliases.TryGetValue (name, out uan)) {
+					if (fne != null && mode != LookupMode.Probing) {
+						// TODO: Namespace has broken location
+						//Report.SymbolRelatedToPreviousError (fne.Location, null);
+						Compiler.Report.SymbolRelatedToPreviousError (uan.Location, null);
+						Compiler.Report.Error (576, loc,
+							"Namespace `{0}' contains a definition with same name as alias `{1}'",
+							GetSignatureForError (), name);
+					}
+
+					return uan.ResolvedExpression;
+				}
+			}
+
+			if (fne != null)
+				return fne;
+
+			//
+			// Lookup can be called before the namespace is defined from different namespace using alias clause
+			//
+			if (namespace_using_table == null) {
+				DoDefineNamespace ();
+			}
+
+			//
+			// Check using entries.
+			//
+			FullNamedExpression match = null;
+			foreach (Namespace using_ns in namespace_using_table) {
+				//
+				// A using directive imports only types contained in the namespace, it
+				// does not import any nested namespaces
+				//
+				var t = using_ns.LookupType (this, name, arity, mode, loc);
+				if (t == null)
+					continue;
+
+				fne = new TypeExpression (t, loc);
+				if (match == null) {
+					match = fne;
+					continue;
+				}
+
+				// Prefer types over namespaces
+				var texpr_fne = fne as TypeExpr;
+				var texpr_match = match as TypeExpr;
+				if (texpr_fne != null && texpr_match == null) {
+					match = fne;
+					continue;
+				} else if (texpr_fne == null) {
+					continue;
+				}
+
+				// It can be top level accessibility only
+				var better = Namespace.IsImportedTypeOverride (Module, texpr_match.Type, texpr_fne.Type);
+				if (better == null) {
+					if (mode == LookupMode.Normal) {
+						Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
+						Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
+						Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
+							name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
+					}
+
+					return match;
+				}
+
+				if (better == texpr_fne.Type)
+					match = texpr_fne;
+			}
+
+			return match;
+		}
+
+		public static MethodGroupExpr LookupStaticUsings (IMemberContext mc, string name, int arity, Location loc)
+		{
+			for (var m = mc.CurrentMemberDefinition; m != null; m = m.Parent) {
+
+				var nc = m as NamespaceContainer;
+				if (nc == null)
+					continue;
+
+				List<MemberSpec> candidates = null;
+				if (nc.types_using_table != null) {
+					foreach (var using_type in nc.types_using_table) {
+						var members = MemberCache.FindMembers (using_type, name, true);
+						if (members != null) {
+							foreach (var member in members) {
+								if ((member.Modifiers & Modifiers.METHOD_EXTENSION) != 0)
+									continue;
+
+								if (arity > 0 && member.Arity != arity)
+									continue;
+
+								if (candidates == null)
+									candidates = new List<MemberSpec> ();
+
+								candidates.Add (member);
+							}
+						}
+					}
+				}
+
+				if (candidates != null)
+					return new MethodGroupExpr (candidates, null, loc);
+			}
+
+			return null;
+		}
+
+		protected override void DefineNamespace ()
+		{
+			if (namespace_using_table == null)
+				DoDefineNamespace ();
+
+			base.DefineNamespace ();
+		}
+
+		void DoDefineNamespace ()
+		{
+			namespace_using_table = empty_namespaces;
+
+			if (clauses != null) {
+				List<Namespace> namespaces = null;
+				List<TypeSpec> types = null;
+
+				bool post_process_using_aliases = false;
+
+				for (int i = 0; i < clauses.Count; ++i) {
+					var entry = clauses[i];
+
+					if (entry.Alias != null) {
+						if (aliases == null)
+							aliases = new Dictionary<string, UsingAliasNamespace> ();
+
+						//
+						// Aliases are not available when resolving using section
+						// except extern aliases
+						//
+						if (entry is UsingExternAlias) {
+							entry.Define (this);
+							if (entry.ResolvedExpression != null)
+								aliases.Add (entry.Alias.Value, (UsingExternAlias) entry);
+
+							clauses.RemoveAt (i--);
+						} else {
+							post_process_using_aliases = true;
+						}
+
+						continue;
+					}
+
+					entry.Define (this);
+
+					//
+					// It's needed for repl only, when using clause cannot be resolved don't hold it in
+					// global list which is resolved for each evaluation
+					//
+					if (entry.ResolvedExpression == null) {
+						clauses.RemoveAt (i--);
+						continue;
+					}
+
+					var using_ns = entry.ResolvedExpression as NamespaceExpression;
+					if (using_ns == null) {
+
+						var type = ((TypeExpr)entry.ResolvedExpression).Type;
+
+						if (types == null)
+							types = new List<TypeSpec> ();
+
+						if (types.Contains (type)) {
+							Warning_DuplicateEntry (entry);
+						} else {
+							types.Add (type);
+						}
+					} else {
+						if (namespaces == null)
+							namespaces = new List<Namespace> ();
+
+						if (namespaces.Contains (using_ns.Namespace)) {
+							// Ensure we don't report the warning multiple times in repl
+							clauses.RemoveAt (i--);
+
+							Warning_DuplicateEntry (entry);
+						} else {
+							namespaces.Add (using_ns.Namespace);
+						}
+					}
+				}
+
+				namespace_using_table = namespaces == null ? new Namespace [0] : namespaces.ToArray ();
+				if (types != null)
+					types_using_table = types.ToArray ();
+
+				if (post_process_using_aliases) {
+					for (int i = 0; i < clauses.Count; ++i) {
+						var entry = clauses[i];
+						if (entry.Alias != null) {
+							entry.Define (this);
+							if (entry.ResolvedExpression != null) {
+								aliases.Add (entry.Alias.Value, (UsingAliasNamespace) entry);
+							}
+
+							clauses.RemoveAt (i--);
+						}
+					}
+				}
+			}
+		}
+
+		public void EnableRedefinition ()
+		{
+			is_defined = false;
+			namespace_using_table = null;
+		}
+
+		internal override void GenerateDocComment (DocumentationBuilder builder)
+		{
+			if (containers != null) {
+				foreach (var tc in containers)
+					tc.GenerateDocComment (builder);
+			}
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return MemberName == null ? "global::" : base.GetSignatureForError ();
+		}
+
+		public override void RemoveContainer (TypeContainer cont)
+		{
+			base.RemoveContainer (cont);
+			NS.RemoveContainer (cont);
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (Module.IsClsComplianceRequired ()) {
+				if (MemberName != null && MemberName.Name[0] == '_') {
+					Warning_IdentifierNotCompliant ();
+				}
+
+				ns.VerifyClsCompliance ();
+				return true;
+			}
+
+			return false;
+		}
+
+		void Warning_DuplicateEntry (UsingNamespace entry)
+		{
+			Compiler.Report.Warning (105, 3, entry.Location,
+				"The using directive for `{0}' appeared previously in this namespace",
+				entry.ResolvedExpression.GetSignatureForError ());
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+	}
+
+	public class UsingNamespace
+	{
+		readonly ATypeNameExpression expr;
+		readonly Location loc;
+		protected FullNamedExpression resolved;
+
+		public UsingNamespace (ATypeNameExpression expr, Location loc)
+		{
+			this.expr = expr;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public virtual SimpleMemberName Alias {
+			get {
+				return null;
+			}
+		}
+
+		public Location Location {
+			get {
+				return loc;
+			}
+		}
+
+		public ATypeNameExpression NamespaceExpression	{
+			get {
+				return expr;
+			}
+		}
+
+		public FullNamedExpression ResolvedExpression {
+			get {
+				return resolved;
+			}
+		}
+
+		#endregion
+
+		public string GetSignatureForError ()
+		{
+			return expr.GetSignatureForError ();
+		}
+
+		public virtual void Define (NamespaceContainer ctx)
+		{
+			resolved = expr.ResolveAsTypeOrNamespace (ctx, false);
+			var ns = resolved as NamespaceExpression;
+			if (ns != null)
+				return;
+
+			if (resolved != null) {
+				var compiler = ctx.Module.Compiler;
+				var type = resolved.Type;
+				if (compiler.Settings.Version >= LanguageVersion.V_6) {
+					if (!type.IsClass || !type.IsStatic) {
+						compiler.Report.SymbolRelatedToPreviousError (type);
+						compiler.Report.Error (7007, Location,
+							"`{0}' is not a static class. A using namespace directive can only be applied to static classes or namespace",
+							GetSignatureForError ());
+					}
+
+					return;
+				}
+
+				compiler.Report.SymbolRelatedToPreviousError (type);
+				compiler.Report.Error (138, Location,
+					"`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
+					GetSignatureForError ());
+			}
+		}
+		
+		public virtual void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override string ToString()
+		{
+			return resolved.ToString();
+		}
+	}
+
+	public class UsingExternAlias : UsingAliasNamespace
+	{
+		public UsingExternAlias (SimpleMemberName alias, Location loc)
+			: base (alias, null, loc)
+		{
+		}
+
+		public override void Define (NamespaceContainer ctx)
+		{
+			var ns = ctx.Module.GetRootNamespace (Alias.Value);
+			if (ns == null) {
+				ctx.Module.Compiler.Report.Error (430, Location,
+					"The extern alias `{0}' was not specified in -reference option",
+					Alias.Value);
+				return;
+			}
+
+			resolved = new NamespaceExpression (ns, Location);
+		}
+		
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+	}
+
+	public class UsingAliasNamespace : UsingNamespace
+	{
+		readonly SimpleMemberName alias;
+
+		public struct AliasContext : IMemberContext
+		{
+			readonly NamespaceContainer ns;
+
+			public AliasContext (NamespaceContainer ns)
+			{
+				this.ns = ns;
+			}
+
+			public TypeSpec CurrentType {
+				get {
+					return null;
+				}
+			}
+
+			public TypeParameters CurrentTypeParameters {
+				get {
+					return null;
+				}
+			}
+
+			public MemberCore CurrentMemberDefinition {
+				get {
+					return null;
+				}
+			}
+
+			public bool IsObsolete {
+				get {
+					return false;
+				}
+			}
+
+			public bool IsUnsafe {
+				get {
+					throw new NotImplementedException ();
+				}
+			}
+
+			public bool IsStatic {
+				get {
+					throw new NotImplementedException ();
+				}
+			}
+
+			public ModuleContainer Module {
+				get {
+					return ns.Module;
+				}
+			}
+
+			public string GetSignatureForError ()
+			{
+				throw new NotImplementedException ();
+			}
+
+			public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
+			{
+				return null;
+			}
+
+			public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+			{
+				var fne = ns.NS.LookupTypeOrNamespace (ns, name, arity, mode, loc);
+				if (fne != null)
+					return fne;
+
+				//
+				// Only extern aliases are allowed in this context
+				//
+				fne = ns.LookupExternAlias (name);
+				if (fne != null || ns.MemberName == null)
+					return fne;
+
+				var container_ns = ns.NS.Parent;
+				var mn = ns.MemberName.Left;
+				while (mn != null) {
+					fne = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
+					if (fne != null)
+						return fne;
+
+					mn = mn.Left;
+					container_ns = container_ns.Parent;
+				}
+
+				if (ns.Parent != null)
+					return ns.Parent.LookupNamespaceOrType (name, arity, mode, loc);
+
+				return null;
+			}
+
+			public FullNamedExpression LookupNamespaceAlias (string name)
+			{
+				return ns.LookupNamespaceAlias (name);
+			}
+		}
+
+		public UsingAliasNamespace (SimpleMemberName alias, ATypeNameExpression expr, Location loc)
+			: base (expr, loc)
+		{
+			this.alias = alias;
+		}
+
+		public override SimpleMemberName Alias {
+			get {
+				return alias;
+			}
+		}
+
+		public override void Define (NamespaceContainer ctx)
+		{
+			//
+			// The namespace-or-type-name of a using-alias-directive is resolved as if
+			// the immediately containing compilation unit or namespace body had no
+			// using-directives. A using-alias-directive may however be affected
+			// by extern-alias-directives in the immediately containing compilation
+			// unit or namespace body
+			//
+			// We achieve that by introducing alias-context which redirect any local
+			// namespace or type resolve calls to parent namespace
+			//
+			resolved = NamespaceExpression.ResolveAsTypeOrNamespace (new AliasContext (ctx), false);
+		}
+		
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/nullable.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/nullable.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/nullable.cs	(revision 11807)
@@ -0,0 +1,1380 @@
+//
+// nullable.cs: Nullable types support
+//
+// Authors: Martin Baulig (martin@ximian.com)
+//          Miguel de Icaza (miguel@ximian.com)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using SLE = System.Linq.Expressions;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+	
+namespace Mono.CSharp.Nullable
+{
+	public class NullableType : TypeExpr
+	{
+		readonly TypeSpec underlying;
+
+		public NullableType (TypeSpec type, Location loc)
+		{
+			this.underlying = type;
+			this.loc = loc;
+		}
+
+		public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments = false)
+		{
+			eclass = ExprClass.Type;
+
+			var otype = ec.Module.PredefinedTypes.Nullable.Resolve ();
+			if (otype == null)
+				return null;
+
+			TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc));
+			GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc);
+			
+			type = ctype.ResolveAsType (ec);
+			return type;
+		}
+	}
+
+	static class NullableInfo
+	{
+		public static MethodSpec GetConstructor (TypeSpec nullableType)
+		{
+			return (MethodSpec) MemberCache.FindMember (nullableType,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly);
+		}
+
+		public static MethodSpec GetHasValue (TypeSpec nullableType)
+		{
+			return (MethodSpec) MemberCache.FindMember (nullableType,
+				MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+		}
+
+		public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
+		{
+			return (MethodSpec) MemberCache.FindMember (nullableType,
+				MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+		}
+
+		//
+		// Don't use unless really required for correctness, see Unwrap::Emit
+		//
+		public static MethodSpec GetValue (TypeSpec nullableType)
+		{
+			return (MethodSpec) MemberCache.FindMember (nullableType,
+				MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+		}
+
+		public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
+		{
+			return ((InflatedTypeSpec) nullableType).TypeArguments[0];
+		}
+
+		public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum)
+		{
+			return MakeType (module, EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum)));
+		}
+
+		public static TypeSpec MakeType (ModuleContainer module, TypeSpec underlyingType)
+		{
+			return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module,
+				new[] { underlyingType });
+
+		}
+	}
+
+	public class Unwrap : Expression, IMemoryLocation
+	{
+		Expression expr;
+
+		LocalTemporary temp;
+		Expression temp_field;
+		readonly bool useDefaultValue;
+
+		public Unwrap (Expression expr, bool useDefaultValue = true)
+		{
+			this.expr = expr;
+			this.loc = expr.Location;
+			this.useDefaultValue = useDefaultValue;
+
+			type = NullableInfo.GetUnderlyingType (expr.Type);
+			eclass = expr.eclass;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return expr.ContainsEmitWithAwait ();
+		}
+
+		// TODO: REMOVE
+		public static Expression Create (Expression expr)
+		{
+			//
+			// Avoid unwraping and wraping of same type
+			//
+			Wrap wrap = expr as Wrap;
+			if (wrap != null)
+				return wrap.Child;
+
+			return Create (expr, false);
+		}
+
+		public static Expression CreateUnwrapped (Expression expr)
+		{
+			//
+			// Avoid unwraping and wraping of same type
+			//
+			Wrap wrap = expr as Wrap;
+			if (wrap != null)
+				return wrap.Child;
+
+			return Create (expr, true);
+		}
+
+		public static Unwrap Create (Expression expr, bool useDefaultValue)
+		{
+			return new Unwrap (expr, useDefaultValue);
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return expr.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			return this;
+		}
+
+		public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
+		{
+			expr = expr.DoResolveLValue (ec, right_side);
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Store (ec);
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = this;
+
+			//
+			// Using GetGetValueOrDefault is prefered because JIT can possibly
+			// inline it whereas Value property contains a throw which is very
+			// unlikely to be inlined
+			//
+			if (useDefaultValue)
+				call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
+			else
+				call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null);
+		}
+
+		public void EmitCheck (EmitContext ec)
+		{
+			Store (ec);
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = this;
+
+			call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
+		}
+
+		public override void EmitSideEffect (EmitContext ec)
+		{
+			expr.EmitSideEffect (ec);
+		}
+
+		public override Expression EmitToField (EmitContext ec)
+		{
+			if (temp_field == null)
+				temp_field = this.expr.EmitToField (ec);
+			
+			return this;
+		}
+
+		public override bool Equals (object obj)
+		{
+			Unwrap uw = obj as Unwrap;
+			return uw != null && expr.Equals (uw.expr);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+		}
+
+		public Expression Original {
+			get {
+				return expr;
+			}
+		}
+		
+		public override int GetHashCode ()
+		{
+			return expr.GetHashCode ();
+		}
+
+		public override bool IsNull {
+			get {
+				return expr.IsNull;
+			}
+		}
+
+		public void Store (EmitContext ec)
+		{
+			if (temp != null || temp_field != null)
+				return;
+
+			if (expr is VariableReference)
+				return;
+
+			expr.Emit (ec);
+			LocalVariable.Store (ec);
+		}
+
+		public void Load (EmitContext ec)
+		{
+			if (temp_field != null)
+				temp_field.Emit (ec);
+			else if (expr is VariableReference)
+				expr.Emit (ec);
+			else
+				LocalVariable.Emit (ec);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return expr.MakeExpression (ctx);
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			IMemoryLocation ml;
+
+			if (temp_field != null) {
+				ml = temp_field as IMemoryLocation;
+				if (ml == null) {
+					var lt = new LocalTemporary (temp_field.Type);
+					temp_field.Emit (ec);
+					lt.Store (ec);
+					ml = lt;
+				}
+			} else {
+				ml = expr as VariableReference;
+			}
+
+			if (ml != null)
+				ml.AddressOf (ec, mode);
+			else
+				LocalVariable.AddressOf (ec, mode);
+		}
+
+		//
+		// Keeps result of non-variable expression
+		//
+		LocalTemporary LocalVariable {
+			get {
+				if (temp == null && temp_field == null)
+					temp = new LocalTemporary (expr.Type);
+				return temp;
+			}
+		}
+	}
+
+	//
+	// Calls get_Value method on nullable expression
+	//
+	public class UnwrapCall : CompositeExpression
+	{
+		public UnwrapCall (Expression expr)
+			: base (expr)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			base.DoResolve (rc);
+
+			if (type != null)
+				type = NullableInfo.GetUnderlyingType (type);
+
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			var call = new CallEmitter ();
+			call.InstanceExpression = Child;
+			call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null);
+		}
+	}
+
+	public class Wrap : TypeCast
+	{
+		private Wrap (Expression expr, TypeSpec type)
+			: base (expr, type)
+		{
+			eclass = ExprClass.Value;
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			TypeCast child_cast = child as TypeCast;
+			if (child_cast != null) {
+				child.Type = type;
+				return child_cast.CreateExpressionTree (ec);
+			}
+
+			var user_cast = child as UserCast;
+			if (user_cast != null) {
+				child.Type = type;
+				return user_cast.CreateExpressionTree (ec);
+			}
+
+			return base.CreateExpressionTree (ec);
+		}
+
+		public static Expression Create (Expression expr, TypeSpec type)
+		{
+			//
+			// Avoid unwraping and wraping of the same type
+			//
+			Unwrap unwrap = expr as Unwrap;
+			if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type))
+				return unwrap.Original;
+		
+			return new Wrap (expr, type);
+		}
+		
+		public override void Emit (EmitContext ec)
+		{
+			child.Emit (ec);
+			ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+		}
+	}
+
+	//
+	// Represents null literal lifted to nullable type
+	//
+	public class LiftedNull : NullConstant, IMemoryLocation
+	{
+		private LiftedNull (TypeSpec nullable_type, Location loc)
+			: base (nullable_type, loc)
+		{
+			eclass = ExprClass.Value;
+		}
+
+		public static Constant Create (TypeSpec nullable, Location loc)
+		{
+			return new LiftedNull (nullable, loc);
+		}
+
+		public static Constant CreateFromExpression (ResolveContext rc, Expression e)
+		{
+			if (!rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
+				rc.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'",
+					e.Type.GetSignatureForError ());
+			}
+
+			return ReducedExpression.Create (Create (e.Type, e.Location), e);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// TODO: generate less temporary variables
+			LocalTemporary value_target = new LocalTemporary (type);
+
+			value_target.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Initobj, type);
+			value_target.Emit (ec);
+			value_target.Release (ec);
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp Mode)
+		{
+			LocalTemporary value_target = new LocalTemporary (type);
+				
+			value_target.AddressOf (ec, AddressOp.Store);
+			ec.Emit (OpCodes.Initobj, type);
+			value_target.AddressOf (ec, Mode);
+		}
+	}
+
+	//
+	// Generic lifting expression, supports all S/S? -> T/T? cases
+	//
+	public class LiftedConversion : Expression, IMemoryLocation
+	{
+		Expression expr, null_value;
+		Unwrap unwrap;
+
+		public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type)
+		{
+			this.expr = expr;
+			this.unwrap = unwrap;
+			this.loc = expr.Location;
+			this.type = type;
+		}
+
+		public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type)
+			: this (expr, unwrap as Unwrap, type)
+		{
+		}
+
+		public override bool IsNull {
+			get {
+				return expr.IsNull;
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return unwrap.ContainsEmitWithAwait ();
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			return expr.CreateExpressionTree (ec);
+		}			
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			//
+			// It's null when lifting non-nullable type
+			//
+			if (unwrap == null) {
+				// S -> T? is wrap only
+				if (type.IsNullableType)
+					return Wrap.Create (expr, type);
+
+				// S -> T can be simplified
+				return expr;
+			}
+
+			// Wrap target for T?
+			if (type.IsNullableType) {
+				if (!expr.Type.IsNullableType) {
+					expr = Wrap.Create (expr, type);
+					if (expr == null)
+						return null;
+				}
+
+				null_value = LiftedNull.Create (type, loc);
+			} else if (TypeSpec.IsValueType (type)) {
+				null_value = LiftedNull.Create (type, loc);
+			} else {
+				null_value = new NullConstant (type, loc);
+			}
+
+			eclass = ExprClass.Value;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Label is_null_label = ec.DefineLabel ();
+			Label end_label = ec.DefineLabel ();
+
+			unwrap.EmitCheck (ec);
+			ec.Emit (OpCodes.Brfalse, is_null_label);
+
+			expr.Emit (ec);
+
+			ec.Emit (OpCodes.Br, end_label);
+			ec.MarkLabel (is_null_label);
+
+			null_value.Emit (ec);
+
+			ec.MarkLabel (end_label);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			unwrap.AddressOf (ec, mode);
+		}
+	}
+
+	public class LiftedUnaryOperator : Unary, IMemoryLocation
+	{
+		Unwrap unwrap;
+		Expression user_operator;
+
+		public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
+			: base (op, expr, loc)
+		{
+		}
+
+		public void AddressOf (EmitContext ec, AddressOp mode)
+		{
+			unwrap.AddressOf (ec, mode);
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (user_operator != null)
+				return user_operator.CreateExpressionTree (ec);
+
+			if (Oper == Operator.UnaryPlus)
+				return Expr.CreateExpressionTree (ec);
+
+			return base.CreateExpressionTree (ec);
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			unwrap = Unwrap.Create (Expr, false);
+			if (unwrap == null)
+				return null;
+
+			Expression res = base.ResolveOperator (ec, unwrap);
+			if (res == null) {
+				Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type);
+				return null;
+			}
+
+			if (res != this) {
+				if (user_operator == null)
+					return res;
+			} else {
+				res = Expr = LiftExpression (ec, Expr);
+			}
+
+			if (res == null)
+				return null;
+
+			eclass = ExprClass.Value;
+			type = res.Type;
+			return this;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Label is_null_label = ec.DefineLabel ();
+			Label end_label = ec.DefineLabel ();
+
+			unwrap.EmitCheck (ec);
+			ec.Emit (OpCodes.Brfalse, is_null_label);
+
+			if (user_operator != null) {
+				user_operator.Emit (ec);
+			} else {
+				EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
+			}
+
+			ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+			ec.Emit (OpCodes.Br_S, end_label);
+
+			ec.MarkLabel (is_null_label);
+			LiftedNull.Create (type, loc).Emit (ec);
+
+			ec.MarkLabel (end_label);
+		}
+
+		static Expression LiftExpression (ResolveContext ec, Expression expr)
+		{
+			var lifted_type = new NullableType (expr.Type, expr.Location);
+			if (lifted_type.ResolveAsType (ec) == null)
+				return null;
+
+			expr.Type = lifted_type.Type;
+			return expr;
+		}
+
+		protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined)
+		{
+			expr = base.ResolveEnumOperator (ec, expr, predefined);
+			if (expr == null)
+				return null;
+
+			Expr = LiftExpression (ec, Expr);
+			return LiftExpression (ec, expr);
+		}
+
+		protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr)
+		{
+			expr = base.ResolveUserOperator (ec, expr);
+			if (expr == null)
+				return null;
+
+			//
+			// When a user operator is of non-nullable type
+			//
+			if (Expr is Unwrap) {
+				user_operator = LiftExpression (ec, expr);
+				return user_operator;
+			}
+
+			return expr;
+		}
+	}
+
+	//
+	// Lifted version of binary operators
+	//
+	class LiftedBinaryOperator : Expression
+	{
+		public LiftedBinaryOperator (Binary b)
+		{
+			this.Binary = b;
+			this.loc = b.Location;
+		}
+
+		public Binary Binary { get; private set; }
+
+		public Expression Left { get; set; }
+
+		public Expression Right { get; set; }
+
+		public Unwrap UnwrapLeft { get; set; }
+
+		public Unwrap UnwrapRight { get; set; }
+
+		public MethodSpec UserOperator { get; set; }
+
+		bool IsBitwiseBoolean {
+			get {
+				return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) &&
+				((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) ||
+				 (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool));
+			}
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait ();
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext rc)
+		{
+			if (UserOperator != null) {
+				Arguments args = new Arguments (2);
+				args.Add (new Argument (Binary.Left));
+				args.Add (new Argument (Binary.Right));
+
+				var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc);
+				return method.CreateExpressionTree (rc);
+			}
+
+			return Binary.CreateExpressionTree (rc);
+		}
+
+		protected override Expression DoResolve (ResolveContext rc)
+		{
+			if (rc.IsRuntimeBinder) {
+				if (UnwrapLeft == null && !Left.Type.IsNullableType)
+					Left = LiftOperand (rc, Left);
+
+				if (UnwrapRight == null && !Right.Type.IsNullableType)
+					Right = LiftOperand (rc, Right);
+			} else {
+				if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) {
+					Left = Unwrap.CreateUnwrapped (Left);
+					UnwrapLeft = Left as Unwrap;
+				}
+
+				if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) {
+					Right = Unwrap.CreateUnwrapped (Right);
+					UnwrapRight = Right as Unwrap;
+				}
+			}
+
+			type = Binary.Type;
+			eclass = Binary.eclass;	
+
+			return this;
+		}
+
+		Expression LiftOperand (ResolveContext rc, Expression expr)
+		{
+			TypeSpec type;
+			if (expr.IsNull) {
+				type = Left.IsNull ? Right.Type : Left.Type;
+			} else {
+				type = expr.Type;
+			}
+
+			if (!type.IsNullableType)
+				type = NullableInfo.MakeType (rc.Module, type);
+
+			return Wrap.Create (expr, type);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (IsBitwiseBoolean && UserOperator == null) {
+				EmitBitwiseBoolean (ec);
+				return;
+			}
+
+			if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) {
+				EmitEquality (ec);
+				return;
+			}
+
+			Label is_null_label = ec.DefineLabel ();
+			Label end_label = ec.DefineLabel ();
+
+			if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) {
+				Left = Left.EmitToField (ec);
+				Right = Right.EmitToField (ec);
+			}
+
+			if (UnwrapLeft != null) {
+				UnwrapLeft.EmitCheck (ec);
+			}
+
+			//
+			// Don't emit HasValue check when left and right expressions are same
+			//
+			if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) {
+				UnwrapRight.EmitCheck (ec);
+				if (UnwrapLeft != null) {
+					ec.Emit (OpCodes.And);
+				}
+			}
+
+			ec.Emit (OpCodes.Brfalse, is_null_label);
+
+			if (UserOperator != null) {
+				var args = new Arguments (2);
+				args.Add (new Argument (Left));
+				args.Add (new Argument (Right));
+
+				var call = new CallEmitter ();
+				call.EmitPredefined (ec, UserOperator, args);
+			} else {
+				Binary.EmitOperator (ec, Left, Right);
+			}
+
+			//
+			// Wrap the result when the operator return type is nullable type
+			//
+			if (type.IsNullableType)
+				ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+
+			ec.Emit (OpCodes.Br_S, end_label);
+			ec.MarkLabel (is_null_label);
+
+			if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) {
+				ec.EmitInt (0);
+			} else {
+				LiftedNull.Create (type, loc).Emit (ec);
+			}
+
+			ec.MarkLabel (end_label);
+		}
+
+		void EmitBitwiseBoolean (EmitContext ec)
+		{
+			Label load_left = ec.DefineLabel ();
+			Label load_right = ec.DefineLabel ();
+			Label end_label = ec.DefineLabel ();
+			Label is_null_label = ec.DefineLabel ();
+
+			bool or = Binary.Oper == Binary.Operator.BitwiseOr;
+
+			//
+			// Both operands are bool? types
+			//
+			if (UnwrapLeft != null && UnwrapRight != null) {
+				if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
+					Left = Left.EmitToField (ec);
+					Right = Right.EmitToField (ec);
+				} else {
+					UnwrapLeft.Store (ec);
+					UnwrapRight.Store (ec);
+				}
+
+				Left.Emit (ec);
+				ec.Emit (OpCodes.Brtrue_S, load_right);
+
+				Right.Emit (ec);
+				ec.Emit (OpCodes.Brtrue_S, load_left);
+
+				UnwrapLeft.EmitCheck (ec);
+				ec.Emit (OpCodes.Brfalse_S, load_right);
+
+				// load left
+				ec.MarkLabel (load_left);
+				if (or)
+					UnwrapRight.Load (ec);
+				else
+					UnwrapLeft.Load (ec);
+
+				ec.Emit (OpCodes.Br_S, end_label);
+
+				// load right
+				ec.MarkLabel (load_right);
+				if (or)
+					UnwrapLeft.Load (ec);
+				else
+					UnwrapRight.Load (ec);
+
+				ec.MarkLabel (end_label);
+				return;
+			}
+
+			//
+			// Faster version when one operand is bool
+			//
+			if (UnwrapLeft == null) {
+				//
+				// (bool, bool?)
+				//
+				// Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle
+				// in binary expression reduction
+				//
+				var c = Left as BoolConstant;
+				if (c != null) {
+					// Keep evaluation order
+					UnwrapRight.Store (ec);
+
+					ec.EmitInt (or ? 1 : 0);
+					ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+				} else if (Left.IsNull) {
+					UnwrapRight.Emit (ec);
+					ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
+
+					UnwrapRight.Load (ec);
+					ec.Emit (OpCodes.Br_S, end_label);
+
+					ec.MarkLabel (is_null_label);
+					LiftedNull.Create (type, loc).Emit (ec);
+				} else {
+					Left.Emit (ec);
+					ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
+
+					ec.EmitInt (or ? 1 : 0);
+					ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+
+					ec.Emit (OpCodes.Br_S, end_label);
+
+					ec.MarkLabel (load_right);
+					UnwrapRight.Original.Emit (ec);
+				}
+			} else {
+				//
+				// (bool?, bool)
+				//
+				// Keep left-right evaluation order
+				UnwrapLeft.Store (ec);
+
+				//
+				// Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle
+				// in binary expression reduction
+				//
+				var c = Right as BoolConstant;
+				if (c != null) {
+					ec.EmitInt (or ? 1 : 0);
+					ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+				} else if (Right.IsNull) {
+					UnwrapLeft.Emit (ec);
+					ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label);
+
+					UnwrapLeft.Load (ec);
+					ec.Emit (OpCodes.Br_S, end_label);
+
+					ec.MarkLabel (is_null_label);
+					LiftedNull.Create (type, loc).Emit (ec);
+				} else {
+					Right.Emit (ec);
+					ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right);
+
+					ec.EmitInt (or ? 1 : 0);
+					ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+
+					ec.Emit (OpCodes.Br_S, end_label);
+
+					ec.MarkLabel (load_right);
+
+					UnwrapLeft.Load (ec);
+				}
+			}
+
+			ec.MarkLabel (end_label);
+ 		}
+
+		//
+		// Emits optimized equality or inequality operator when possible
+		//
+		void EmitEquality (EmitContext ec)
+		{
+			//
+			// Either left or right is null
+			// 
+			if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable
+				//
+				// left.HasValue == false 
+				//
+				UnwrapLeft.EmitCheck (ec);
+				if (Binary.Oper == Binary.Operator.Equality) {
+					ec.EmitInt (0);
+					ec.Emit (OpCodes.Ceq);
+				}
+				return;
+			}
+
+			if (UnwrapRight != null && Binary.Left.IsNull) {
+				//
+				// right.HasValue == false 
+				//
+				UnwrapRight.EmitCheck (ec);
+				if (Binary.Oper == Binary.Operator.Equality) {
+					ec.EmitInt (0);
+					ec.Emit (OpCodes.Ceq);
+				}
+				return;
+			}
+
+			Label dissimilar_label = ec.DefineLabel ();
+			Label end_label = ec.DefineLabel ();
+
+			if (UserOperator != null) {
+				var left = Left;
+
+				if (UnwrapLeft != null) {
+					UnwrapLeft.EmitCheck (ec);
+				} else {
+					// Keep evaluation order same
+					if (!(Left is VariableReference)) {
+						Left.Emit (ec);
+						var lt = new LocalTemporary (Left.Type);
+						lt.Store (ec);
+						left = lt;
+					}
+				}
+
+				if (UnwrapRight != null) {
+					UnwrapRight.EmitCheck (ec);
+
+					if (UnwrapLeft != null) {
+						ec.Emit (OpCodes.Bne_Un, dissimilar_label);
+
+						Label compare_label = ec.DefineLabel ();
+						UnwrapLeft.EmitCheck (ec);
+						ec.Emit (OpCodes.Brtrue, compare_label);
+
+						if (Binary.Oper == Binary.Operator.Equality)
+							ec.EmitInt (1);
+						else
+							ec.EmitInt (0);
+
+						ec.Emit (OpCodes.Br, end_label);
+
+						ec.MarkLabel (compare_label);
+					} else {
+						ec.Emit (OpCodes.Brfalse, dissimilar_label);
+					}
+				} else {
+					ec.Emit (OpCodes.Brfalse, dissimilar_label);
+				}
+
+				var args = new Arguments (2);
+				args.Add (new Argument (left));
+				args.Add (new Argument (Right));
+
+				var call = new CallEmitter ();
+				call.EmitPredefined (ec, UserOperator, args);
+			} else {
+				if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) {
+					Left = Left.EmitToField (ec);
+					Right = Right.EmitToField (ec);
+				}
+
+				//
+				// Emit underlying value comparison first.
+				//
+				// For this code: int? a = 1; bool b = a == 1;
+				//
+				// We emit something similar to this. Expressions with side effects have local
+				// variable created by Unwrap expression
+				//
+				//	left.GetValueOrDefault ()
+				//	right
+				//	bne.un.s   dissimilar_label
+				//  left.HasValue
+				//	br.s       end_label
+				// dissimilar_label:
+				//	ldc.i4.0
+				// end_label:
+				//
+
+				Left.Emit (ec);
+				Right.Emit (ec);
+
+				ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
+
+				//
+				// Check both left and right expressions for Unwrap call in which
+				// case we need to run get_HasValue() check because the type is
+				// nullable and could have null value
+				//
+				if (UnwrapLeft != null)
+					UnwrapLeft.EmitCheck (ec);
+
+				if (UnwrapRight != null)
+					UnwrapRight.EmitCheck (ec);
+
+				if (UnwrapLeft != null && UnwrapRight != null) {
+					if (Binary.Oper == Binary.Operator.Inequality)
+						ec.Emit (OpCodes.Xor);
+					else
+						ec.Emit (OpCodes.Ceq);
+				} else {
+					if (Binary.Oper == Binary.Operator.Inequality) {
+						ec.EmitInt (0);
+						ec.Emit (OpCodes.Ceq);
+					}
+				}
+			}
+
+			ec.Emit (OpCodes.Br_S, end_label);
+
+			ec.MarkLabel (dissimilar_label);
+			if (Binary.Oper == Binary.Operator.Inequality)
+				ec.EmitInt (1);
+			else
+				ec.EmitInt (0);
+
+			ec.MarkLabel (end_label);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			Binary.FlowAnalysis (fc);
+		}
+
+		public override SLE.Expression MakeExpression (BuilderContext ctx)
+		{
+			return Binary.MakeExpression (ctx, Left, Right);
+		}
+	}
+
+	public class NullCoalescingOperator : Expression
+	{
+		Expression left, right;
+		Unwrap unwrap;
+
+		public NullCoalescingOperator (Expression left, Expression right)
+		{
+			this.left = left;
+			this.right = right;
+			this.loc = left.Location;
+		}
+
+		public Expression LeftExpression {
+			get {
+ 				return left;
+ 			}
+		}
+
+		public Expression RightExpression {
+			get {
+ 				return right;
+ 			}
+		}
+		
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (left is NullLiteral)
+				ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side");
+
+			UserCast uc = left as UserCast;
+			Expression conversion = null;
+			if (uc != null) {
+				left = uc.Source;
+
+				Arguments c_args = new Arguments (2);
+				c_args.Add (new Argument (uc.CreateExpressionTree (ec)));
+				c_args.Add (new Argument (left.CreateExpressionTree (ec)));
+				conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args);
+			}
+
+			Arguments args = new Arguments (3);
+			args.Add (new Argument (left.CreateExpressionTree (ec)));
+			args.Add (new Argument (right.CreateExpressionTree (ec)));
+			if (conversion != null)
+				args.Add (new Argument (conversion));
+			
+			return CreateExpressionFactoryCall (ec, "Coalesce", args);
+		}
+
+		Expression ConvertExpression (ResolveContext ec)
+		{
+			// TODO: ImplicitConversionExists should take care of this
+			if (left.eclass == ExprClass.MethodGroup)
+				return null;
+
+			TypeSpec ltype = left.Type;
+
+			//
+			// If left is a nullable type and an implicit conversion exists from right to underlying type of left,
+			// the result is underlying type of left
+			//
+			if (ltype.IsNullableType) {
+				unwrap = Unwrap.Create (left, false);
+				if (unwrap == null)
+					return null;
+
+				//
+				// Reduce (left ?? null) to left
+				//
+				if (right.IsNull)
+					return ReducedExpression.Create (left, this);
+
+				Expression conv;
+				if (right.Type.IsNullableType) {
+					conv = right.Type == ltype ? right : Convert.ImplicitNulableConversion (ec, right, ltype);
+					if (conv != null) {
+						right = conv;
+						type = ltype;
+						return this;
+					}
+				} else {
+					conv = Convert.ImplicitConversion (ec, right, unwrap.Type, loc);
+					if (conv != null) {
+						left = unwrap;
+						ltype = left.Type;
+
+						//
+						// If right is a dynamic expression, the result type is dynamic
+						//
+						if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+							type = right.Type;
+
+							// Need to box underlying value type
+							left = Convert.ImplicitBoxingConversion (left, ltype, type);
+							return this;
+						}
+
+						right = conv;
+						type = ltype;
+						return this;
+					}
+				}
+			} else if (TypeSpec.IsReferenceType (ltype)) {
+				if (Convert.ImplicitConversionExists (ec, right, ltype)) {
+					//
+					// If right is a dynamic expression, the result type is dynamic
+					//
+					if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+						type = right.Type;
+						return this;
+					}
+
+					//
+					// Reduce ("foo" ?? expr) to expression
+					//
+					Constant lc = left as Constant;
+					if (lc != null && !lc.IsDefaultValue)
+						return ReducedExpression.Create (lc, this, false);
+
+					//
+					// Reduce (left ?? null) to left OR (null-constant ?? right) to right
+					//
+					if (right.IsNull || lc != null) {
+						//
+						// Special case null ?? null
+						//
+						if (right.IsNull && ltype == right.Type)
+							return null;
+
+						return ReducedExpression.Create (lc != null ? right : left, this, false);
+					}
+
+					right = Convert.ImplicitConversion (ec, right, ltype, loc);
+					type = ltype;
+					return this;
+				}
+			} else {
+				return null;
+			}
+
+			TypeSpec rtype = right.Type;
+			if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup)
+				return null;
+
+			//
+			// Reduce (null ?? right) to right
+			//
+			if (left.IsNull)
+				return ReducedExpression.Create (right, this, false).Resolve (ec);
+
+			left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc);
+
+			if (TypeSpec.IsValueType (left.Type) && !left.Type.IsNullableType) {
+				Warning_UnreachableExpression (ec, right.Location);
+				return ReducedExpression.Create (left, this, false).Resolve (ec);
+			}
+
+			type = rtype;
+			return this;
+		}
+
+		public override bool ContainsEmitWithAwait ()
+		{
+			if (unwrap != null)
+				return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
+
+			return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait ();
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			left = left.Resolve (ec);
+			right = right.Resolve (ec);
+
+			if (left == null || right == null)
+				return null;
+
+			eclass = ExprClass.Value;
+
+			Expression e = ConvertExpression (ec);
+			if (e == null) {
+				Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc);
+				return null;
+			}
+
+			return e;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			Label end_label = ec.DefineLabel ();
+
+			if (unwrap != null) {
+				Label is_null_label = ec.DefineLabel ();
+
+				unwrap.EmitCheck (ec);
+				ec.Emit (OpCodes.Brfalse, is_null_label);
+
+				//
+				// When both expressions are nullable the unwrap
+				// is needed only for null check not for value uwrap
+				//
+				if (type.IsNullableType && TypeSpecComparer.IsEqual (NullableInfo.GetUnderlyingType (type), unwrap.Type))
+					unwrap.Load (ec);
+				else
+					left.Emit (ec);
+
+				ec.Emit (OpCodes.Br, end_label);
+
+				ec.MarkLabel (is_null_label);
+				right.Emit (ec);
+
+				ec.MarkLabel (end_label);
+				return;
+			}
+
+			left.Emit (ec);
+			ec.Emit (OpCodes.Dup);
+
+			// Only to make verifier happy
+			if (left.Type.IsGenericParameter)
+				ec.Emit (OpCodes.Box, left.Type);
+
+			ec.Emit (OpCodes.Brtrue, end_label);
+
+			ec.Emit (OpCodes.Pop);
+			right.Emit (ec);
+
+			ec.MarkLabel (end_label);
+		}
+
+		public override void FlowAnalysis (FlowAnalysisContext fc)
+		{
+			left.FlowAnalysis (fc);
+			var left_da = fc.BranchDefiniteAssignment ();
+			right.FlowAnalysis (fc);
+			fc.DefiniteAssignment = left_da;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Expression t)
+		{
+			NullCoalescingOperator target = (NullCoalescingOperator) t;
+
+			target.left = left.Clone (clonectx);
+			target.right = right.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	class LiftedUnaryMutator : UnaryMutator
+	{
+		public LiftedUnaryMutator (Mode mode, Expression expr, Location loc)
+			: base (mode, expr, loc)
+		{
+		}
+
+		protected override Expression DoResolve (ResolveContext ec)
+		{
+			var orig_expr = expr;
+
+			expr = Unwrap.Create (expr);
+
+			var res = base.DoResolveOperation (ec);
+
+			expr = orig_expr;
+			type = expr.Type;
+
+			return res;
+		}
+
+		protected override void EmitOperation (EmitContext ec)
+		{
+			Label is_null_label = ec.DefineLabel ();
+			Label end_label = ec.DefineLabel ();
+
+			LocalTemporary lt = new LocalTemporary (type);
+
+			// Value is on the stack
+			lt.Store (ec);
+
+			var call = new CallEmitter ();
+			call.InstanceExpression = lt;
+			call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null);
+
+			ec.Emit (OpCodes.Brfalse, is_null_label);
+
+			call = new CallEmitter ();
+			call.InstanceExpression = lt;
+			call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null);
+
+			lt.Release (ec);
+
+			base.EmitOperation (ec);
+
+			ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+			ec.Emit (OpCodes.Br_S, end_label);
+
+			ec.MarkLabel (is_null_label);
+			LiftedNull.Create (type, loc).Emit (ec);
+
+			ec.MarkLabel (end_label);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/outline.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/outline.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/outline.cs	(revision 11807)
@@ -0,0 +1,1038 @@
+//
+// outline -- support for rendering in monop
+// Some code stolen from updater.cs in monodoc.
+//
+// Authors:
+//	Ben Maurer (bmaurer@users.sourceforge.net)
+//
+// (C) 2004 Ben Maurer
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Collections;
+using System.CodeDom.Compiler;
+using System.IO;
+using System.Text;
+
+namespace Mono.CSharp {
+public class Outline {
+
+	bool declared_only;
+	bool show_private;
+	bool filter_obsolete;
+	
+	IndentedTextWriter o;
+	Type t;
+	
+	public Outline (Type t, TextWriter output, bool declared_only, bool show_private, bool filter_obsolete)
+	{
+		this.t = t;
+		this.o = new IndentedTextWriter (output, "\t");
+		this.declared_only = declared_only;
+		this.show_private = show_private;
+		this.filter_obsolete = filter_obsolete;
+	}
+
+	public void OutlineType ()
+        {
+		bool first;
+		
+		OutlineAttributes ();
+		o.Write (GetTypeVisibility (t));
+		
+		if (t.IsClass && !t.IsSubclassOf (typeof (System.MulticastDelegate))) {
+			if (t.IsSealed)
+				o.Write (t.IsAbstract ? " static" : " sealed");
+			else if (t.IsAbstract)
+				o.Write (" abstract");
+		}
+		
+		o.Write (" ");
+		o.Write (GetTypeKind (t));
+		o.Write (" ");
+		
+		Type [] interfaces = (Type []) Comparer.Sort (TypeGetInterfaces (t, declared_only));
+		Type parent = t.BaseType;
+
+		if (t.IsSubclassOf (typeof (System.MulticastDelegate))) {
+			MethodInfo method;
+
+			method = t.GetMethod ("Invoke");
+
+			o.Write (FormatType (method.ReturnType));
+			o.Write (" ");
+			o.Write (GetTypeName (t));
+			o.Write (" (");
+			OutlineParams (method.GetParameters ());
+			o.Write (")");
+
+#if NET_2_0
+			WriteGenericConstraints (t.GetGenericArguments ());
+#endif			
+	
+			o.WriteLine (";"); 
+			return;
+		}
+		
+		o.Write (GetTypeName (t));
+		if (((parent != null && parent != typeof (object) && parent != typeof (ValueType)) || interfaces.Length != 0) && ! t.IsEnum) {
+			first = true;
+			o.Write (" : ");
+			
+			if (parent != null && parent != typeof (object) && parent != typeof (ValueType)) {
+				o.Write (FormatType (parent));
+				first = false;
+			}
+			
+			foreach (Type intf in interfaces) {
+				if (!first) o.Write (", ");
+				first = false;
+				
+				o.Write (FormatType (intf));
+			}
+		}
+
+		if (t.IsEnum) {
+			Type underlyingType = System.Enum.GetUnderlyingType (t);
+			if (underlyingType != typeof (int))
+				o.Write (" : {0}", FormatType (underlyingType));
+		}
+#if NET_2_0
+		WriteGenericConstraints (t.GetGenericArguments ());
+#endif		
+		o.WriteLine (" {");
+		o.Indent++;
+
+		if (t.IsEnum) {
+			bool is_first = true;
+			foreach (FieldInfo fi in t.GetFields (BindingFlags.Public | BindingFlags.Static)) {
+				
+				if (! is_first)
+					o.WriteLine (",");
+				is_first = false;
+				o.Write (fi.Name);
+			}
+			o.WriteLine ();
+			o.Indent--; o.WriteLine ("}");
+			return;
+		}
+		
+		first = true;
+		
+		foreach (ConstructorInfo ci in t.GetConstructors (DefaultFlags)) {
+			if (! ShowMember (ci))
+				continue;
+			
+			if (first)
+				o.WriteLine ();
+			first = false;
+			
+			OutlineMemberAttribute (ci);
+			OutlineConstructor (ci);
+			
+			o.WriteLine ();
+		}
+		
+
+		first = true;
+		
+		foreach (MethodInfo m in Comparer.Sort (t.GetMethods (DefaultFlags))) {
+			
+			if (! ShowMember (m))
+				continue;		
+			
+			if ((m.Attributes & MethodAttributes.SpecialName) != 0)
+				continue;
+			
+			if (first)
+				o.WriteLine ();
+			first = false;
+
+			OutlineMemberAttribute (m);
+			OutlineMethod (m);
+			
+			o.WriteLine ();
+		}
+		
+		first = true;
+		
+		foreach (MethodInfo m in t.GetMethods (DefaultFlags)) {
+			
+			if (! ShowMember (m))
+				continue;
+			
+			if ((m.Attributes & MethodAttributes.SpecialName) == 0)
+				continue;
+			if (!(m.Name.StartsWith ("op_")))
+				continue;
+
+			if (first)
+				o.WriteLine ();
+			first = false;
+			
+			OutlineMemberAttribute (m);
+			OutlineOperator (m);
+			
+			o.WriteLine ();
+		}
+
+		first = true;
+		
+		foreach (PropertyInfo pi in Comparer.Sort (t.GetProperties (DefaultFlags))) {
+			
+			if (! ((pi.CanRead  && ShowMember (pi.GetGetMethod (true))) ||
+			       (pi.CanWrite && ShowMember (pi.GetSetMethod (true)))))
+				continue;
+			
+			if (first)
+				o.WriteLine ();
+			first = false;
+			
+			OutlineMemberAttribute (pi);
+			OutlineProperty (pi);
+			
+			o.WriteLine ();
+		}
+		
+		first = true;
+
+		foreach (FieldInfo fi in t.GetFields (DefaultFlags)) {
+			
+			if (! ShowMember (fi))
+				continue;
+			
+			if (first)
+				o.WriteLine ();
+			first = false;
+			
+			OutlineMemberAttribute (fi);
+			OutlineField (fi);
+			
+			o.WriteLine ();
+		}
+
+		first = true;
+		
+		foreach (EventInfo ei in Comparer.Sort (t.GetEvents (DefaultFlags))) {
+			
+			if (! ShowMember (ei.GetAddMethod (true)))
+				continue;
+			
+			if (first)
+				o.WriteLine ();
+			first = false;
+			
+			OutlineMemberAttribute (ei);
+			OutlineEvent (ei);
+			
+			o.WriteLine ();
+		}
+
+		first = true;
+
+		foreach (Type ntype in Comparer.Sort (t.GetNestedTypes (DefaultFlags))) {
+			
+			if (! ShowMember (ntype))
+				continue;
+			
+			if (first)
+				o.WriteLine ();
+			first = false;
+			
+			new Outline (ntype, o, declared_only, show_private, filter_obsolete).OutlineType ();
+		}
+		
+		o.Indent--; o.WriteLine ("}");
+	}
+	
+	BindingFlags DefaultFlags {
+		get {
+			BindingFlags f = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
+			
+			if (declared_only)
+				f |= BindingFlags.DeclaredOnly;
+			
+			return f;
+		}
+	}
+
+	// FIXME: add other interesting attributes?
+	void OutlineAttributes ()
+	{
+		if (t.IsSerializable)
+			o.WriteLine ("[Serializable]");
+
+		if (t.IsDefined (typeof (System.FlagsAttribute), true))
+			o.WriteLine ("[Flags]");
+
+		if (t.IsDefined (typeof (System.ObsoleteAttribute), true))
+			o.WriteLine ("[Obsolete]");
+	}
+
+	void OutlineMemberAttribute (MemberInfo mi)
+	{
+		if (!mi.IsDefined (typeof (System.ObsoleteAttribute), false))
+			return;
+		var oa = mi.GetCustomAttributes (typeof (System.ObsoleteAttribute), false) [0] as ObsoleteAttribute;
+		var msg = oa.Message;
+		o.WriteLine ("[Obsolete{0}]", msg == null || msg == "" ? "" : string.Format ("(\"{0}\")", msg));
+	}
+	
+	void OutlineEvent (EventInfo ei)
+	{
+		MethodBase accessor = ei.GetAddMethod (true);
+		
+		o.Write (GetMethodVisibility (accessor));
+		o.Write ("event ");
+		o.Write (FormatType (ei.EventHandlerType));
+		o.Write (" ");
+		o.Write (ei.Name);
+		o.Write (";");
+	}
+	
+	void OutlineConstructor (ConstructorInfo ci)
+	{
+		o.Write (GetMethodVisibility (ci));
+		o.Write (RemoveGenericArity (t.Name));
+		o.Write (" (");
+		OutlineParams (ci.GetParameters ());
+		o.Write (");");
+	}
+	
+	
+	void OutlineProperty (PropertyInfo pi)
+	{
+		ParameterInfo [] idxp = pi.GetIndexParameters ();
+		MethodBase g = pi.GetGetMethod (true);
+		MethodBase s = pi.GetSetMethod (true);
+		MethodBase accessor = g != null ? g : s;
+		
+		if (pi.CanRead && pi.CanWrite) {
+
+			
+			// Get the more accessible accessor
+			if ((g.Attributes & MethodAttributes.MemberAccessMask) !=
+			    (s.Attributes & MethodAttributes.MemberAccessMask)) {
+				
+				if (g.IsPublic) accessor = g;
+				else if (s.IsPublic) accessor = s;
+				else if (g.IsFamilyOrAssembly) accessor = g;
+				else if (s.IsFamilyOrAssembly) accessor = s;
+				else if (g.IsAssembly || g.IsFamily) accessor = g;
+				else if (s.IsAssembly || s.IsFamily) accessor = s;
+			}
+		}
+		
+		o.Write (GetMethodVisibility (accessor));
+		o.Write (GetMethodModifiers  (accessor));
+		o.Write (FormatType (pi.PropertyType));
+		o.Write (" ");
+		
+		if (idxp.Length == 0)
+			o.Write (pi.Name);
+		else {
+			o.Write ("this [");
+			OutlineParams (idxp);
+			o.Write ("]");
+		}
+		
+		o.WriteLine (" {");
+		o.Indent ++;
+		
+		if (g != null && ShowMember (g)) {
+			if ((g.Attributes & MethodAttributes.MemberAccessMask) !=
+			    (accessor.Attributes & MethodAttributes.MemberAccessMask))
+				o.Write (GetMethodVisibility (g));
+			o.WriteLine ("get;");
+		}
+		
+		if (s != null && ShowMember (s)) {
+			if ((s.Attributes & MethodAttributes.MemberAccessMask) !=
+			    (accessor.Attributes & MethodAttributes.MemberAccessMask))
+				o.Write (GetMethodVisibility (s));
+			o.WriteLine ("set;");
+		}
+		
+		o.Indent --;
+		o.Write ("}");
+	}
+	
+	void OutlineMethod (MethodInfo mi)
+	{
+		if (MethodIsExplicitIfaceImpl (mi)) {
+			o.Write (FormatType (mi.ReturnType));
+			o.Write (" ");
+			// MSFT has no way to get the method that we are overriding
+			// from the interface. this would allow us to pretty print
+			// the type name (and be more correct if there compiler
+			// were to do some strange naming thing).
+		} else {
+			o.Write (GetMethodVisibility (mi));
+			o.Write (GetMethodModifiers  (mi));
+			o.Write (FormatType (mi.ReturnType));
+			o.Write (" ");
+		}
+
+		o.Write (mi.Name);
+#if NET_2_0
+		o.Write (FormatGenericParams (mi.GetGenericArguments ()));
+#endif
+		o.Write (" (");
+		OutlineParams (mi.GetParameters ());
+		o.Write (")");
+#if NET_2_0
+		WriteGenericConstraints (mi.GetGenericArguments ());
+#endif
+		o.Write (";");
+	}
+	
+	void OutlineOperator (MethodInfo mi)
+	{
+		o.Write (GetMethodVisibility (mi));
+		o.Write (GetMethodModifiers  (mi));
+		if (mi.Name == "op_Explicit" || mi.Name == "op_Implicit") {
+			o.Write (mi.Name.Substring (3).ToLower ());
+			o.Write (" operator ");
+			o.Write (FormatType (mi.ReturnType));
+		} else {
+			o.Write (FormatType (mi.ReturnType));
+			o.Write (" operator ");
+			o.Write (OperatorFromName (mi.Name));
+		}
+		o.Write (" (");
+		OutlineParams (mi.GetParameters ());
+		o.Write (");");
+	}
+	
+	void OutlineParams (ParameterInfo [] pi)
+	{
+		int i = 0;
+		foreach (ParameterInfo p in pi) {
+			if (p.ParameterType.IsByRef) {
+				o.Write (p.IsOut ? "out " : "ref ");
+				o.Write (FormatType (p.ParameterType.GetElementType ()));
+			} else if (p.IsDefined (typeof (ParamArrayAttribute), false)) {
+				o.Write ("params ");
+				o.Write (FormatType (p.ParameterType));
+			} else {
+				o.Write (FormatType (p.ParameterType));
+			}
+			
+			o.Write (" ");
+			o.Write (p.Name);
+			if (i + 1 < pi.Length)
+				o.Write (", ");
+			i++;
+		}
+	}
+
+	void OutlineField (FieldInfo fi)
+	{
+		if (fi.IsPublic)   o.Write ("public ");
+		if (fi.IsFamily)   o.Write ("protected ");
+		if (fi.IsPrivate)  o.Write ("private ");
+		if (fi.IsAssembly) o.Write ("internal ");
+		if (fi.IsLiteral)  o.Write ("const ");
+		else if (fi.IsStatic) o.Write ("static ");
+		if (fi.IsInitOnly) o.Write ("readonly ");
+
+		o.Write (FormatType (fi.FieldType));
+		o.Write (" ");
+		o.Write (fi.Name);
+		if (fi.IsLiteral) { 
+			object v = fi.GetValue (this);
+
+			// TODO: Escape values here
+			o.Write (" = ");
+			if (v is char)
+				o.Write ("'{0}'", v);
+			else if (v is string)
+				o.Write ("\"{0}\"", v);
+			else
+				o.Write (fi.GetValue (this));
+		}
+		o.Write (";");
+	}
+
+	static string GetMethodVisibility (MethodBase m)
+	{
+		// itnerfaces have no modifiers here
+		if (m.DeclaringType.IsInterface)
+			return "";
+		
+		if (m.IsPublic)   return "public ";
+		if (m.IsFamily)   return "protected ";
+		if (m.IsPrivate)  return "private ";
+		if (m.IsAssembly) return "internal ";
+			
+		return null;
+	}
+	
+	static string GetMethodModifiers (MethodBase method)
+	{
+		if (method.IsStatic)
+			return "static ";
+
+		if (method.IsFinal) {
+			// This will happen if you have
+			// class X : IA {
+			//   public void A () {}
+			//   static void Main () {}
+			// }
+			// interface IA {
+			//   void A ();
+			// }
+			//
+			// A needs to be virtual (the CLR requires
+			// methods implementing an iface be virtual),
+			// but can not be inherited. It also can not
+			// be inherited. In C# this is represented
+			// with no special modifiers
+
+			if (method.IsVirtual)
+				return null;
+			return "sealed ";
+		}
+		
+		// all interface methods are "virtual" but we don't say that in c#
+		if (method.IsVirtual && !method.DeclaringType.IsInterface) {
+			if (method.IsAbstract)
+				return "abstract ";
+
+			return ((method.Attributes & MethodAttributes.NewSlot) != 0) ?
+				"virtual " :
+				"override ";	
+		}
+				
+		return null;
+	}
+
+	static string GetTypeKind (Type t)
+	{
+		if (t.IsEnum)
+			return "enum";
+		if (t.IsClass) {
+			if (t.IsSubclassOf (typeof (System.MulticastDelegate)))
+				return "delegate";
+			else
+				return "class";
+		}
+		if (t.IsInterface)
+			return "interface";
+		if (t.IsValueType)
+			return "struct";
+		return "class";
+	}
+	
+	static string GetTypeVisibility (Type t)
+	{
+                switch (t.Attributes & TypeAttributes.VisibilityMask){
+                case TypeAttributes.Public:
+                case TypeAttributes.NestedPublic:
+                        return "public";
+
+                case TypeAttributes.NestedFamily:
+                case TypeAttributes.NestedFamANDAssem:
+                case TypeAttributes.NestedFamORAssem:
+                        return "protected";
+
+                default:
+                        return "internal";
+                }
+	}
+
+#if NET_2_0
+	string FormatGenericParams (Type [] args)
+	{
+		StringBuilder sb = new StringBuilder ();
+		if (args.Length == 0)
+			return "";
+		
+		sb.Append ("<");
+		for (int i = 0; i < args.Length; i++) {
+			if (i > 0)
+				sb.Append (",");
+			sb.Append (FormatType (args [i]));
+		}
+		sb.Append (">");
+		return sb.ToString ();
+	}
+#endif
+
+	// TODO: fine tune this so that our output is less verbose. We need to figure
+	// out a way to do this while not making things confusing.
+	string FormatType (Type t)
+	{
+		if (t == null)
+			return "";
+
+		string type = GetFullName (t);
+		if (type == null)
+			return t.ToString ();
+		
+		if (!type.StartsWith ("System.")) {
+			if (t.Namespace == this.t.Namespace)
+				return t.Name;
+			return type;
+		}
+		
+		if (t.HasElementType) {
+			Type et = t.GetElementType ();
+			if (t.IsArray)
+				return FormatType (et) + " []";
+			if (t.IsPointer)
+				return FormatType (et) + " *";
+			if (t.IsByRef)
+				return "ref " + FormatType (et);
+		}
+	
+		switch (type) {
+		case "System.Byte": return "byte";
+		case "System.SByte": return "sbyte";
+		case "System.Int16": return "short";
+		case "System.Int32": return "int";
+		case "System.Int64": return "long";
+			
+		case "System.UInt16": return "ushort";
+		case "System.UInt32": return "uint";
+		case "System.UInt64": return "ulong";
+			
+		case "System.Single":  return "float";
+		case "System.Double":  return "double";
+		case "System.Decimal": return "decimal";
+		case "System.Boolean": return "bool";
+		case "System.Char":    return "char";
+		case "System.String":  return "string";
+			
+		case "System.Object":  return "object";
+		case "System.Void":  return "void";
+		}
+	
+		if (type.LastIndexOf(".") == 6)
+			return type.Substring(7);
+
+		//
+		// If the namespace of the type is the namespace of what
+		// we are printing (or is a member of one if its children
+		// don't print it. This basically means that in C# we would
+		// automatically get the namespace imported by virtue of the
+		// namespace {} block.
+		//	
+		if (this.t.Namespace.StartsWith (t.Namespace + ".") || t.Namespace == this.t.Namespace)
+			return type.Substring (t.Namespace.Length + 1);
+	
+		return type;
+	}
+
+	public static string RemoveGenericArity (string name)
+	{
+		int start = 0;
+		StringBuilder sb = new StringBuilder ();
+		while (start < name.Length) {
+			int pos = name.IndexOf ('`', start);
+			if (pos < 0) {
+				sb.Append (name.Substring (start));
+				break;
+			}
+			sb.Append (name.Substring (start, pos-start));
+
+			pos++;
+
+			while ((pos < name.Length) && Char.IsNumber (name [pos]))
+				pos++;
+
+			start = pos;
+		}
+
+		return sb.ToString ();
+	}
+
+	string GetTypeName (Type t)
+	{
+		StringBuilder sb = new StringBuilder ();
+		GetTypeName (sb, t);
+		return sb.ToString ();
+	}
+
+	void GetTypeName (StringBuilder sb, Type t)
+	{
+		sb.Append (RemoveGenericArity (t.Name));
+#if NET_2_0
+		sb.Append (FormatGenericParams (t.GetGenericArguments ()));
+#endif
+	}
+
+	string GetFullName (Type t)
+	{
+		StringBuilder sb = new StringBuilder ();
+		GetFullName_recursed (sb, t, false);
+		return sb.ToString ();
+	}
+
+	void GetFullName_recursed (StringBuilder sb, Type t, bool recursed)
+	{
+#if NET_2_0
+		if (t.IsGenericParameter) {
+			sb.Append (t.Name);
+			return;
+		}
+#endif
+
+		if (t.DeclaringType != null) {
+			GetFullName_recursed (sb, t.DeclaringType, true);
+			sb.Append (".");
+		}
+
+		if (!recursed) {
+			string ns = t.Namespace;
+			if ((ns != null) && (ns != "")) {
+				sb.Append (ns);
+				sb.Append (".");
+			}
+		}
+
+		GetTypeName (sb, t);
+	}
+
+#if NET_2_0
+	void WriteGenericConstraints (Type [] args)
+	{
+
+		foreach (Type t in args) {
+			bool first = true;
+			Type[] ifaces = TypeGetInterfaces (t, true);
+			
+			GenericParameterAttributes attrs = t.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
+			GenericParameterAttributes [] interesting = {
+				GenericParameterAttributes.ReferenceTypeConstraint,
+				GenericParameterAttributes.NotNullableValueTypeConstraint,
+				GenericParameterAttributes.DefaultConstructorConstraint
+			};
+			
+			if (t.BaseType != typeof (object) || ifaces.Length != 0 || attrs != 0) {
+				o.Write (" where ");
+				o.Write (FormatType (t));
+				o.Write (" : ");
+			}
+
+			if (t.BaseType != typeof (object)) {
+				o.Write (FormatType (t.BaseType));
+				first = false;
+			}
+
+			foreach (Type iface in ifaces) {
+				if (!first)
+					o.Write (", ");
+				first = false;
+				
+				o.Write (FormatType (iface));
+			}
+
+			foreach (GenericParameterAttributes a in interesting) {
+				if ((attrs & a) == 0)
+					continue;
+				
+				if (!first)
+					o.Write (", ");
+				first = false;
+				
+				switch (a) {
+				case GenericParameterAttributes.ReferenceTypeConstraint:
+					o.Write ("class");
+					break;
+				case GenericParameterAttributes.NotNullableValueTypeConstraint:
+					o.Write ("struct");
+					break;
+				case GenericParameterAttributes.DefaultConstructorConstraint:
+					o.Write ("new ()");
+					break;
+				}
+			}
+		}
+	}
+#endif
+ 
+	string OperatorFromName (string name)
+	{
+		switch (name) {
+		case "op_UnaryPlus": return "+";
+		case "op_UnaryNegation": return "-";
+		case "op_LogicalNot": return "!";
+		case "op_OnesComplement": return "~";
+		case "op_Increment": return "++";
+		case "op_Decrement": return "--";
+		case "op_True": return "true";
+		case "op_False": return "false";
+		case "op_Addition": return "+";
+		case "op_Subtraction": return "-";
+		case "op_Multiply": return "*";
+		case "op_Division": return "/";
+		case "op_Modulus": return "%";
+		case "op_BitwiseAnd": return "&";
+		case "op_BitwiseOr": return "|";
+		case "op_ExclusiveOr": return "^";
+		case "op_LeftShift": return "<<";
+		case "op_RightShift": return ">>";
+		case "op_Equality": return "==";
+		case "op_Inequality": return "!=";
+		case "op_GreaterThan": return ">";
+		case "op_LessThan": return "<";
+		case "op_GreaterThanOrEqual": return ">=";
+		case "op_LessThanOrEqual": return "<=";
+		default: return name;
+		}
+	}
+
+	bool MethodIsExplicitIfaceImpl (MethodBase mb)
+	{
+		if (!(mb.IsFinal && mb.IsVirtual && mb.IsPrivate))
+			return false;
+		
+		// UGH msft has no way to get the info about what method is
+		// getting overriden. Another reason to use cecil :-)
+		//
+		//MethodInfo mi = mb as MethodInfo;
+		//if (mi == null)
+		//	return false;
+		//
+		//Console.WriteLine (mi.GetBaseDefinition ().DeclaringType);
+		//return mi.GetBaseDefinition ().DeclaringType.IsInterface;
+		
+		// So, we guess that virtual final private methods only come
+		// from ifaces :-)
+		return true;
+	}
+	
+	bool ShowMember (MemberInfo mi)
+	{
+		if (mi.MemberType == MemberTypes.Constructor && ((MethodBase) mi).IsStatic)
+			return false;
+		
+		if (show_private)
+			return true;
+
+		if (filter_obsolete && mi.IsDefined (typeof (ObsoleteAttribute), false))
+			return false;
+		
+		switch (mi.MemberType) {
+		case MemberTypes.Constructor:
+		case MemberTypes.Method:
+			MethodBase mb = mi as MethodBase;
+		
+			if (mb.IsFamily || mb.IsPublic || mb.IsFamilyOrAssembly)
+				return true;
+			
+			if (MethodIsExplicitIfaceImpl (mb))
+				return true;
+					
+			return false;
+		
+		
+		case MemberTypes.Field:
+			FieldInfo fi = mi as FieldInfo;
+		
+			if (fi.IsFamily || fi.IsPublic || fi.IsFamilyOrAssembly)
+				return true;
+			
+			return false;
+		
+		
+		case MemberTypes.NestedType:
+		case MemberTypes.TypeInfo:
+			Type t = mi as Type;
+		
+			switch (t.Attributes & TypeAttributes.VisibilityMask){
+			case TypeAttributes.Public:
+			case TypeAttributes.NestedPublic:
+			case TypeAttributes.NestedFamily:
+			case TypeAttributes.NestedFamORAssem:
+				return true;
+			}
+			
+			return false;
+		}
+		
+		// What am I !!!
+		return true;
+	}
+
+	static Type [] TypeGetInterfaces (Type t, bool declonly)
+	{
+		if (t.IsGenericParameter)
+			return new Type [0];
+
+		Type [] ifaces = t.GetInterfaces ();
+		if (! declonly)
+			return ifaces;
+
+		// Handle Object. Also, optimize for no interfaces
+		if (t.BaseType == null || ifaces.Length == 0)
+			return ifaces;
+
+		ArrayList ar = new ArrayList ();
+
+		foreach (Type i in ifaces)
+			if (! i.IsAssignableFrom (t.BaseType))
+				ar.Add (i);
+
+		return (Type []) ar.ToArray (typeof (Type));
+	}
+}
+
+public class Comparer : IComparer  {
+	delegate int ComparerFunc (object a, object b);
+	
+	ComparerFunc cmp;
+	
+	Comparer (ComparerFunc f)
+	{
+		this.cmp = f;
+	}
+	
+	public int Compare (object a, object b)
+	{
+		return cmp (a, b);
+	}
+
+	static int CompareType (object a, object b)
+	{
+		Type type1 = (Type) a;
+		Type type2 = (Type) b;
+
+		if (type1.IsSubclassOf (typeof (System.MulticastDelegate)) != type2.IsSubclassOf (typeof (System.MulticastDelegate)))
+				return (type1.IsSubclassOf (typeof (System.MulticastDelegate)))? -1:1;
+		return string.Compare (type1.Name, type2.Name);
+			
+	}
+
+//	static Comparer TypeComparer = new Comparer (new ComparerFunc (CompareType));
+
+//	static Type [] Sort (Type [] types)
+//	{
+//		Array.Sort (types, TypeComparer);
+//		return types;
+//	}
+	
+	static int CompareMemberInfo (object a, object b)
+	{
+		return string.Compare (((MemberInfo) a).Name, ((MemberInfo) b).Name);
+	}
+	
+	static Comparer MemberInfoComparer = new Comparer (new ComparerFunc (CompareMemberInfo));
+	
+	public static MemberInfo [] Sort (MemberInfo [] inf)
+	{
+		Array.Sort (inf, MemberInfoComparer);
+		return inf;
+	}
+	
+	static int CompareMethodBase (object a, object b)
+	{
+		MethodBase aa = (MethodBase) a, bb = (MethodBase) b;
+		
+		if (aa.IsStatic == bb.IsStatic) {
+			int c = CompareMemberInfo (a, b);
+			if (c != 0)
+				return c;
+			ParameterInfo [] ap, bp;
+
+			//
+			// Sort overloads by the names of their types
+			// put methods with fewer params first.
+			//
+			
+			ap = aa.GetParameters ();
+			bp = bb.GetParameters ();
+			int n = System.Math.Min (ap.Length, bp.Length);
+
+			for (int i = 0; i < n; i ++)
+				if ((c = CompareType (ap [i].ParameterType, bp [i].ParameterType)) != 0)
+					return c;
+
+			return ap.Length.CompareTo (bp.Length);
+		}
+		if (aa.IsStatic)
+			return -1;
+		
+		return 1;
+	}
+	
+	static Comparer MethodBaseComparer = new Comparer (new ComparerFunc (CompareMethodBase));
+	
+	public static MethodBase [] Sort (MethodBase [] inf)
+	{
+		Array.Sort (inf, MethodBaseComparer);
+		return inf;
+	}
+	
+	static int ComparePropertyInfo (object a, object b)
+	{
+		PropertyInfo aa = (PropertyInfo) a, bb = (PropertyInfo) b;
+		
+		bool astatic = (aa.CanRead ? aa.GetGetMethod (true) : aa.GetSetMethod (true)).IsStatic;
+		bool bstatic = (bb.CanRead ? bb.GetGetMethod (true) : bb.GetSetMethod (true)).IsStatic;
+		
+		if (astatic == bstatic)
+			return CompareMemberInfo (a, b);
+		
+		if (astatic)
+			return -1;
+		
+		return 1;
+	}
+	
+	static Comparer PropertyInfoComparer = new Comparer (new ComparerFunc (ComparePropertyInfo));
+	
+	public static PropertyInfo [] Sort (PropertyInfo [] inf)
+	{
+		Array.Sort (inf, PropertyInfoComparer);
+		return inf;
+	}
+	
+	static int CompareEventInfo (object a, object b)
+	{
+		EventInfo aa = (EventInfo) a, bb = (EventInfo) b;
+		
+		bool astatic = aa.GetAddMethod (true).IsStatic;
+		bool bstatic = bb.GetAddMethod (true).IsStatic;
+		
+		if (astatic == bstatic)
+			return CompareMemberInfo (a, b);
+		
+		if (astatic)
+			return -1;
+		
+		return 1;
+	}
+	
+	static Comparer EventInfoComparer = new Comparer (new ComparerFunc (CompareEventInfo));
+	
+	public static EventInfo [] Sort (EventInfo [] inf)
+	{
+		Array.Sort (inf, EventInfoComparer);
+		return inf;
+	}
+}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/parameter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/parameter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/parameter.cs	(revision 11807)
@@ -0,0 +1,1472 @@
+//
+// parameter.cs: Parameter definition.
+//
+// Author: Miguel de Icaza (miguel@gnu.org)
+//         Marek Safar (marek.safar@seznam.cz)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc. 
+// Copyright 2011 Xamarin Inc
+//
+//
+using System;
+using System.Text;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	/// <summary>
+	///   Abstract Base class for parameters of a method.
+	/// </summary>
+	public abstract class ParameterBase : Attributable
+	{
+		protected ParameterBuilder builder;
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+#if false
+			if (a.Type == pa.MarshalAs) {
+				UnmanagedMarshal marshal = a.GetMarshal (this);
+				if (marshal != null) {
+					builder.SetMarshal (marshal);
+				}
+				return;
+			}
+#endif
+			if (a.HasSecurityAttribute) {
+				a.Error_InvalidSecurityParent ();
+				return;
+			}
+
+			if (a.Type == pa.Dynamic) {
+				a.Error_MisusedDynamicAttribute ();
+				return;
+			}
+
+			builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		public ParameterBuilder Builder {
+			get {
+				return builder;
+			}
+		}
+
+		public override bool IsClsComplianceRequired()
+		{
+			return false;
+		}
+	}
+
+	/// <summary>
+	/// Class for applying custom attributes on the return type
+	/// </summary>
+	public class ReturnParameter : ParameterBase
+	{
+		MemberCore method;
+
+		// TODO: merge method and mb
+		public ReturnParameter (MemberCore method, MethodBuilder mb, Location location)
+		{
+			this.method = method;
+			try {
+				builder = mb.DefineParameter (0, ParameterAttributes.None, "");			
+			}
+			catch (ArgumentOutOfRangeException) {
+				method.Compiler.Report.RuntimeMissingSupport (location, "custom attributes on the return type");
+			}
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.CLSCompliant) {
+				method.Compiler.Report.Warning (3023, 1, a.Location,
+					"CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead");
+			}
+
+			// This occurs after Warning -28
+			if (builder == null)
+				return;
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.ReturnValue;
+			}
+		}
+
+		/// <summary>
+		/// Is never called
+		/// </summary>
+		public override string[] ValidAttributeTargets {
+			get {
+				return null;
+			}
+		}
+	}
+
+	public class ImplicitLambdaParameter : Parameter
+	{
+		public ImplicitLambdaParameter (string name, Location loc)
+			: base (null, name, Modifier.NONE, null, loc)
+		{
+		}
+
+		public override TypeSpec Resolve (IMemberContext ec, int index)
+		{
+			if (parameter_type == null)
+				throw new InternalErrorException ("A type of implicit lambda parameter `{0}' is not set",
+					Name);
+
+			base.idx = index;
+			return parameter_type;
+		}
+
+		public void SetParameterType (TypeSpec type)
+		{
+			parameter_type = type;
+		}
+	}
+
+	public class ParamsParameter : Parameter {
+		public ParamsParameter (FullNamedExpression type, string name, Attributes attrs, Location loc):
+			base (type, name, Parameter.Modifier.PARAMS, attrs, loc)
+		{
+		}
+
+		public override TypeSpec Resolve (IMemberContext ec, int index)
+		{
+			if (base.Resolve (ec, index) == null)
+				return null;
+
+			var ac = parameter_type as ArrayContainer;
+			if (ac == null || ac.Rank != 1) {
+				ec.Module.Compiler.Report.Error (225, Location, "The params parameter must be a single dimensional array");
+				return null;
+			}
+
+			return parameter_type;
+		}
+
+		public override void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
+		{
+			base.ApplyAttributes (mb, cb, index, pa);
+			pa.ParamArray.EmitAttribute (builder);
+		}
+	}
+
+	public class ArglistParameter : Parameter {
+		// Doesn't have proper type because it's never chosen for better conversion
+		public ArglistParameter (Location loc) :
+			base (null, String.Empty, Parameter.Modifier.NONE, null, loc)
+		{
+			parameter_type = InternalType.Arglist;
+		}
+
+		public override void  ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
+		{
+			// Nothing to do
+		}
+
+		public override bool CheckAccessibility (InterfaceMemberBase member)
+		{
+			return true;
+		}
+
+		public override TypeSpec Resolve (IMemberContext ec, int index)
+		{
+			return parameter_type;
+		}
+	}
+
+	public interface IParameterData
+	{
+		Expression DefaultValue { get; }
+		bool HasExtensionMethodModifier { get; }
+		bool HasDefaultValue { get; }
+		Parameter.Modifier ModFlags { get; }
+		string Name { get; }
+	}
+
+	//
+	// Parameter information created by parser
+	//
+	public class Parameter : ParameterBase, IParameterData, ILocalVariable // TODO: INamedBlockVariable
+	{
+		[Flags]
+		public enum Modifier : byte {
+			NONE    = 0,
+			PARAMS  = 1 << 0,
+			REF = 1 << 1,
+			OUT = 1 << 2,
+			This = 1 << 3,
+			CallerMemberName = 1 << 4,
+			CallerLineNumber = 1 << 5,
+			CallerFilePath = 1 << 6,
+
+			RefOutMask = REF | OUT,
+			ModifierMask = PARAMS | REF | OUT | This,
+			CallerMask = CallerMemberName | CallerLineNumber | CallerFilePath
+		}
+
+		static readonly string[] attribute_targets = new [] { "param" };
+
+		FullNamedExpression texpr;
+		Modifier modFlags;
+		string name;
+		Expression default_expr;
+		protected TypeSpec parameter_type;
+		readonly Location loc;
+		protected int idx;
+		public bool HasAddressTaken;
+
+		TemporaryVariableReference expr_tree_variable;
+
+		HoistedParameter hoisted_variant;
+
+		public Parameter (FullNamedExpression type, string name, Modifier mod, Attributes attrs, Location loc)
+		{
+			this.name = name;
+			modFlags = mod;
+			this.loc = loc;
+			texpr = type;
+
+			// Only assign, attributes will be attached during resolve
+			base.attributes = attrs;
+		}
+
+		#region Properties
+
+		public Expression DefaultExpression {
+			get {
+				return default_expr;
+			}
+		}
+
+		public DefaultParameterValueExpression DefaultValue {
+			get {
+				return default_expr as DefaultParameterValueExpression;
+			}
+			set {
+				default_expr = value;
+			}
+		}
+
+		Expression IParameterData.DefaultValue {
+			get {
+				var expr = default_expr as DefaultParameterValueExpression;
+				return expr == null ? default_expr : expr.Child;
+			}
+		}
+
+		bool HasOptionalExpression {
+			get {
+				return default_expr is DefaultParameterValueExpression;
+			}
+		}
+
+		public Location Location {
+			get {
+				return loc;
+			}
+		}
+
+		public Modifier ParameterModifier {
+			get {
+				return modFlags;
+			}
+		}
+
+		public TypeSpec Type {
+			get {
+				return parameter_type;
+			}
+			set {
+				parameter_type = value;
+			}
+		}
+
+		public FullNamedExpression TypeExpression  {
+			get {
+				return texpr;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+
+		#endregion
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.In && ModFlags == Modifier.OUT) {
+				a.Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
+				return;
+			}
+
+			if (a.Type == pa.ParamArray) {
+				a.Report.Error (674, a.Location, "Do not use `System.ParamArrayAttribute'. Use the `params' keyword instead");
+				return;
+			}
+
+			if (a.Type == pa.Out && (ModFlags & Modifier.REF) != 0 &&
+			    !OptAttributes.Contains (pa.In)) {
+				a.Report.Error (662, a.Location,
+					"Cannot specify only `Out' attribute on a ref parameter. Use both `In' and `Out' attributes or neither");
+				return;
+			}
+
+			if (a.Type == pa.CLSCompliant) {
+				a.Report.Warning (3022, 1, a.Location, "CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead");
+			} else if (a.Type == pa.DefaultParameterValue || a.Type == pa.OptionalParameter) {
+				if (HasOptionalExpression) {
+					a.Report.Error (1745, a.Location,
+						"Cannot specify `{0}' attribute on optional parameter `{1}'",
+						a.Type.GetSignatureForError ().Replace ("Attribute", ""), Name);
+				}
+
+				if (a.Type == pa.DefaultParameterValue)
+					return;
+			} else if (a.Type == pa.CallerMemberNameAttribute) {
+				if ((modFlags & Modifier.CallerMemberName) == 0) {
+					a.Report.Error (4022, a.Location,
+						"The CallerMemberName attribute can only be applied to parameters with default value");
+				}
+			} else if (a.Type == pa.CallerLineNumberAttribute) {
+				if ((modFlags & Modifier.CallerLineNumber) == 0) {
+					a.Report.Error (4020, a.Location,
+						"The CallerLineNumber attribute can only be applied to parameters with default value");
+				}
+			} else if (a.Type == pa.CallerFilePathAttribute) {
+				if ((modFlags & Modifier.CallerFilePath) == 0) {
+					a.Report.Error (4021, a.Location,
+						"The CallerFilePath attribute can only be applied to parameters with default value");
+				}
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+		
+		public virtual bool CheckAccessibility (InterfaceMemberBase member)
+		{
+			if (parameter_type == null)
+				return true;
+
+			return member.IsAccessibleAs (parameter_type);
+		}
+
+		bool IsValidCallerContext (MemberCore memberContext)
+		{
+			var m = memberContext as Method;
+			if (m != null)
+				return !m.IsPartialImplementation;
+
+			return true;
+		}
+
+		// <summary>
+		//   Resolve is used in method definitions
+		// </summary>
+		public virtual TypeSpec Resolve (IMemberContext rc, int index)
+		{
+			if (parameter_type != null)
+				return parameter_type;
+
+			if (attributes != null)
+				attributes.AttachTo (this, rc);
+
+			parameter_type = texpr.ResolveAsType (rc);
+			if (parameter_type == null)
+				return null;
+
+			this.idx = index;
+
+			if ((modFlags & Parameter.Modifier.RefOutMask) != 0 && parameter_type.IsSpecialRuntimeType) {
+				rc.Module.Compiler.Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
+					GetSignatureForError ());
+				return null;
+			}
+
+			VarianceDecl.CheckTypeVariance (parameter_type,
+				(modFlags & Parameter.Modifier.RefOutMask) != 0 ? Variance.None : Variance.Contravariant,
+				rc);
+
+			if (parameter_type.IsStatic) {
+				rc.Module.Compiler.Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
+					texpr.GetSignatureForError ());
+				return parameter_type;
+			}
+
+			if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)) {
+				rc.Module.Compiler.Report.Error (1103, Location, "The extension method cannot be of type `{0}'",
+					parameter_type.GetSignatureForError ());
+			}
+
+			return parameter_type;
+		}
+
+		void ResolveCallerAttributes (ResolveContext rc)
+		{
+			var pa = rc.Module.PredefinedAttributes;
+			TypeSpec caller_type;
+			Attribute callerMemberName = null, callerFilePath = null;
+
+			foreach (var attr in attributes.Attrs) {
+				var atype = attr.ResolveTypeForComparison ();
+				if (atype == null)
+					continue;
+
+				if (atype == pa.CallerMemberNameAttribute) {
+					caller_type = rc.BuiltinTypes.String;
+					if (caller_type != parameter_type && !Convert.ImplicitReferenceConversionExists (caller_type, parameter_type)) {
+						rc.Report.Error (4019, attr.Location,
+							"The CallerMemberName attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'",
+							caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ());
+					}
+
+					if (!IsValidCallerContext (rc.CurrentMemberDefinition)) {
+						rc.Report.Warning (4026, 1, attr.Location,
+							"The CallerMemberName applied to parameter `{0}' will have no effect because it applies to a member that is used in context that do not allow optional arguments",
+							name);
+					}
+
+					modFlags |= Modifier.CallerMemberName;
+					callerMemberName = attr;
+					continue;
+				}
+
+				if (atype == pa.CallerLineNumberAttribute) {
+					caller_type = rc.BuiltinTypes.Int;
+					if (caller_type != parameter_type && !Convert.ImplicitStandardConversionExists (new IntConstant (caller_type, int.MaxValue, Location.Null), parameter_type)) {
+						rc.Report.Error (4017, attr.Location,
+							"The CallerLineNumberAttribute attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'",
+							caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ());
+					}
+
+					if (!IsValidCallerContext (rc.CurrentMemberDefinition)) {
+						rc.Report.Warning (4024, 1, attr.Location,
+							"The CallerLineNumberAttribute applied to parameter `{0}' will have no effect because it applies to a member that is used in context that do not allow optional arguments",
+							name);
+					}
+
+					modFlags |= Modifier.CallerLineNumber;
+					continue;
+				}
+
+				if (atype == pa.CallerFilePathAttribute) {
+					caller_type = rc.BuiltinTypes.String;
+					if (caller_type != parameter_type && !Convert.ImplicitReferenceConversionExists (caller_type, parameter_type)) {
+						rc.Report.Error (4018, attr.Location,
+							"The CallerFilePath attribute cannot be applied because there is no standard conversion from `{0}' to `{1}'",
+							caller_type.GetSignatureForError (), parameter_type.GetSignatureForError ());
+					}
+
+					if (!IsValidCallerContext (rc.CurrentMemberDefinition)) {
+						rc.Report.Warning (4025, 1, attr.Location,
+							"The CallerFilePath applied to parameter `{0}' will have no effect because it applies to a member that is used in context that do not allow optional arguments",
+							name);
+					}
+
+					modFlags |= Modifier.CallerFilePath;
+					callerFilePath = attr;
+					continue;
+				}
+			}
+
+			if ((modFlags & Modifier.CallerLineNumber) != 0) {
+				if (callerMemberName != null) {
+					rc.Report.Warning (7081, 1, callerMemberName.Location,
+						"The CallerMemberNameAttribute applied to parameter `{0}' will have no effect. It is overridden by the CallerLineNumberAttribute",
+						Name);
+				}
+
+				if (callerFilePath != null) {
+					rc.Report.Warning (7082, 1, callerFilePath.Location,
+						"The CallerFilePathAttribute applied to parameter `{0}' will have no effect. It is overridden by the CallerLineNumberAttribute",
+						name);
+				}
+			}
+
+			if ((modFlags & Modifier.CallerMemberName) != 0) {
+				if (callerFilePath != null) {
+					rc.Report.Warning (7080, 1, callerFilePath.Location,
+						"The CallerMemberNameAttribute applied to parameter `{0}' will have no effect. It is overridden by the CallerFilePathAttribute",
+						name);
+				}
+
+			}
+		}
+
+		public void ResolveDefaultValue (ResolveContext rc)
+		{
+			//
+			// Default value was specified using an expression
+			//
+			if (default_expr != null) {
+				((DefaultParameterValueExpression)default_expr).Resolve (rc, this);
+				if (attributes != null)
+					ResolveCallerAttributes (rc);
+
+				return;
+			}
+
+			if (attributes == null)
+				return;
+
+			var pa = rc.Module.PredefinedAttributes;
+			var def_attr = attributes.Search (pa.DefaultParameterValue);
+			if (def_attr != null) {
+				if (def_attr.Resolve () == null)
+					return;
+
+				var default_expr_attr = def_attr.GetParameterDefaultValue ();
+				if (default_expr_attr == null)
+					return;
+
+				var dpa_rc = def_attr.CreateResolveContext ();
+				default_expr = default_expr_attr.Resolve (dpa_rc);
+
+				if (default_expr is BoxedCast)
+					default_expr = ((BoxedCast) default_expr).Child;
+
+				Constant c = default_expr as Constant;
+				if (c == null) {
+					if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
+						rc.Report.Error (1910, default_expr.Location,
+							"Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
+							default_expr.Type.GetSignatureForError ());
+					} else {
+						rc.Report.Error (1909, default_expr.Location,
+							"The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
+							default_expr.Type.GetSignatureForError ());
+					}
+
+					default_expr = null;
+					return;
+				}
+
+				if (TypeSpecComparer.IsEqual (default_expr.Type, parameter_type) ||
+					(default_expr is NullConstant && TypeSpec.IsReferenceType (parameter_type) && !parameter_type.IsGenericParameter) ||
+					parameter_type.BuiltinType == BuiltinTypeSpec.Type.Object) {
+					return;
+				}
+
+				//
+				// LAMESPEC: Some really weird csc behaviour which we have to mimic
+				// User operators returning same type as parameter type are considered
+				// valid for this attribute only
+				//
+				// struct S { public static implicit operator S (int i) {} }
+				//
+				// void M ([DefaultParameterValue (3)]S s)
+				//
+				var expr = Convert.ImplicitUserConversion (dpa_rc, default_expr, parameter_type, loc);
+				if (expr != null && TypeSpecComparer.IsEqual (expr.Type, parameter_type)) {
+					return;
+				}
+				
+				rc.Report.Error (1908, default_expr.Location, "The type of the default value should match the type of the parameter");
+				return;
+			}
+
+			var opt_attr = attributes.Search (pa.OptionalParameter);
+			if (opt_attr != null) {
+				default_expr = EmptyExpression.MissingValue;
+			}
+		}
+
+		public bool HasDefaultValue {
+			get { return default_expr != null; }
+		}
+
+		public bool HasExtensionMethodModifier {
+			get { return (modFlags & Modifier.This) != 0; }
+		}
+
+		//
+		// Hoisted parameter variant
+		//
+		public HoistedParameter HoistedVariant {
+			get {
+				return hoisted_variant;
+			}
+			set {
+				hoisted_variant = value;
+			}
+		}
+
+		public Modifier ModFlags {
+			get { return modFlags & ~Modifier.This; }
+		}
+
+		public string Name {
+			get { return name; }
+			set { name = value; }
+		}
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Parameter;
+			}
+		}
+
+		public void Error_DuplicateName (Report r)
+		{
+			r.Error (100, Location, "The parameter name `{0}' is a duplicate", Name);
+		}
+
+		public virtual string GetSignatureForError ()
+		{
+			string type_name;
+			if (parameter_type != null)
+				type_name = parameter_type.GetSignatureForError ();
+			else
+				type_name = texpr.GetSignatureForError ();
+
+			string mod = GetModifierSignature (modFlags);
+			if (mod.Length > 0)
+				return String.Concat (mod, " ", type_name);
+
+			return type_name;
+		}
+
+		public static string GetModifierSignature (Modifier mod)
+		{
+			switch (mod) {
+			case Modifier.OUT:
+				return "out";
+			case Modifier.PARAMS:
+				return "params";
+			case Modifier.REF:
+				return "ref";
+			case Modifier.This:
+				return "this";
+			default:
+				return "";
+			}
+		}
+
+		public void IsClsCompliant (IMemberContext ctx)
+		{
+			if (parameter_type.IsCLSCompliant ())
+				return;
+
+			ctx.Module.Compiler.Report.Warning (3001, 1, Location,
+				"Argument type `{0}' is not CLS-compliant", parameter_type.GetSignatureForError ());
+		}
+
+		public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
+		{
+			if (builder != null)
+				throw new InternalErrorException ("builder already exists");
+
+			var pattrs = ParametersCompiled.GetParameterAttribute (modFlags);
+			if (HasOptionalExpression)
+				pattrs |= ParameterAttributes.Optional;
+
+			if (mb == null)
+				builder = cb.DefineParameter (index, pattrs, Name);
+			else
+				builder = mb.DefineParameter (index, pattrs, Name);
+
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			if (HasDefaultValue && default_expr.Type != null) {
+				//
+				// Emit constant values for true constants only, the other
+				// constant-like expressions will rely on default value expression
+				//
+				var def_value = DefaultValue;
+				Constant c = def_value != null ? def_value.Child as Constant : default_expr as Constant;
+				if (c != null) {
+					if (c.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
+						pa.DecimalConstant.EmitAttribute (builder, (decimal) c.GetValue (), c.Location);
+					} else {
+						builder.SetConstant (c.GetValue ());
+					}
+				} else if (default_expr.Type.IsStruct || default_expr.Type.IsGenericParameter) {
+					//
+					// Handles special case where default expression is used with value-type or type parameter
+					//
+					// void Foo (S s = default (S)) {}
+					//
+					builder.SetConstant (null);
+				}
+			}
+
+			if (parameter_type != null) {
+				if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					pa.Dynamic.EmitAttribute (builder);
+				} else if (parameter_type.HasDynamicElement) {
+					pa.Dynamic.EmitAttribute (builder, parameter_type, Location);
+				}
+			}
+		}
+
+		public Parameter Clone ()
+		{
+			Parameter p = (Parameter) MemberwiseClone ();
+			if (attributes != null)
+				p.attributes = attributes.Clone ();
+
+			return p;
+		}
+
+		public ExpressionStatement CreateExpressionTreeVariable (BlockContext ec)
+		{
+			if ((modFlags & Modifier.RefOutMask) != 0)
+				ec.Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");
+
+			expr_tree_variable = TemporaryVariableReference.Create (ResolveParameterExpressionType (ec, Location).Type, ec.CurrentBlock.ParametersBlock, Location);
+			expr_tree_variable = (TemporaryVariableReference) expr_tree_variable.Resolve (ec);
+
+			Arguments arguments = new Arguments (2);
+			arguments.Add (new Argument (new TypeOf (parameter_type, Location)));
+			arguments.Add (new Argument (new StringConstant (ec.BuiltinTypes, Name, Location)));
+			return new SimpleAssign (ExpressionTreeVariableReference (),
+				Expression.CreateExpressionFactoryCall (ec, "Parameter", null, arguments, Location));
+		}
+
+		public void Emit (EmitContext ec)
+		{
+			ec.EmitArgumentLoad (idx);
+		}
+
+		public void EmitAssign (EmitContext ec)
+		{
+			ec.EmitArgumentStore (idx);
+		}
+
+		public void EmitAddressOf (EmitContext ec)
+		{
+			if ((ModFlags & Modifier.RefOutMask) != 0) {
+				ec.EmitArgumentLoad (idx);
+			} else {
+				ec.EmitArgumentAddress (idx);
+			}
+		}
+
+		public TemporaryVariableReference ExpressionTreeVariableReference ()
+		{
+			return expr_tree_variable;
+		}
+
+		//
+		// System.Linq.Expressions.ParameterExpression type
+		//
+		public static TypeExpr ResolveParameterExpressionType (IMemberContext ec, Location location)
+		{
+			TypeSpec p_type = ec.Module.PredefinedTypes.ParameterExpression.Resolve ();
+			return new TypeExpression (p_type, location);
+		}
+
+		public void SetIndex (int index)
+		{
+			idx = index;
+		}
+
+		public void Warning_UselessOptionalParameter (Report Report)
+		{
+			Report.Warning (1066, 1, Location,
+				"The default value specified for optional parameter `{0}' will never be used",
+				Name);
+		}
+	}
+
+	//
+	// Imported or resolved parameter information
+	//
+	public class ParameterData : IParameterData
+	{
+		readonly string name;
+		readonly Parameter.Modifier modifiers;
+		readonly Expression default_value;
+
+		public ParameterData (string name, Parameter.Modifier modifiers)
+		{
+			this.name = name;
+			this.modifiers = modifiers;
+		}
+
+		public ParameterData (string name, Parameter.Modifier modifiers, Expression defaultValue)
+			: this (name, modifiers)
+		{
+			this.default_value = defaultValue;
+		}
+
+		#region IParameterData Members
+
+		public Expression DefaultValue {
+			get { return default_value; }
+		}
+
+		public bool HasExtensionMethodModifier {
+			get { return (modifiers & Parameter.Modifier.This) != 0; }
+		}
+
+		public bool HasDefaultValue {
+			get { return default_value != null; }
+		}
+
+		public Parameter.Modifier ModFlags {
+			get { return modifiers; }
+		}
+
+		public string Name {
+			get { return name; }
+		}
+
+		#endregion
+	}
+
+	public abstract class AParametersCollection
+	{
+		protected bool has_arglist;
+		protected bool has_params;
+
+		// Null object pattern
+		protected IParameterData [] parameters;
+		protected TypeSpec [] types;
+
+		public CallingConventions CallingConvention {
+			get {
+				return has_arglist ?
+					CallingConventions.VarArgs :
+					CallingConventions.Standard;
+			}
+		}
+
+		public int Count {
+			get { return parameters.Length; }
+		}
+
+		public TypeSpec ExtensionMethodType {
+			get {
+				if (Count == 0)
+					return null;
+
+				return FixedParameters [0].HasExtensionMethodModifier ?
+					types [0] : null;
+			}
+		}
+
+		public IParameterData [] FixedParameters {
+			get {
+				return parameters;
+			}
+		}
+
+		public static ParameterAttributes GetParameterAttribute (Parameter.Modifier modFlags)
+		{
+			return (modFlags & Parameter.Modifier.OUT) != 0 ?
+				ParameterAttributes.Out : ParameterAttributes.None;
+		}
+
+		// Very expensive operation
+		public MetaType[] GetMetaInfo ()
+		{
+			MetaType[] types;
+			if (has_arglist) {
+				if (Count == 1)
+					return MetaType.EmptyTypes;
+
+				types = new MetaType[Count - 1];
+			} else {
+				if (Count == 0)
+					return MetaType.EmptyTypes;
+
+				types = new MetaType[Count];
+			}
+
+			for (int i = 0; i < types.Length; ++i) {
+				types[i] = Types[i].GetMetaInfo ();
+
+				if ((FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) == 0)
+					continue;
+
+				// TODO MemberCache: Should go to MetaInfo getter
+				types [i] = types [i].MakeByRefType ();
+			}
+
+			return types;
+		}
+
+		//
+		// Returns the parameter information based on the name
+		//
+		public int GetParameterIndexByName (string name)
+		{
+			for (int idx = 0; idx < Count; ++idx) {
+				if (parameters [idx].Name == name)
+					return idx;
+			}
+
+			return -1;
+		}
+
+		public string GetSignatureForDocumentation ()
+		{
+			if (IsEmpty)
+				return string.Empty;
+
+			StringBuilder sb = new StringBuilder ("(");
+			for (int i = 0; i < Count; ++i) {
+				if (i != 0)
+					sb.Append (",");
+
+				sb.Append (types [i].GetSignatureForDocumentation ());
+
+				if ((parameters[i].ModFlags & Parameter.Modifier.RefOutMask) != 0)
+					sb.Append ("@");
+			}
+			sb.Append (")");
+
+			return sb.ToString ();
+		}
+
+		public string GetSignatureForError ()
+		{
+			return GetSignatureForError ("(", ")", Count);
+		}
+
+		public string GetSignatureForError (string start, string end, int count)
+		{
+			StringBuilder sb = new StringBuilder (start);
+			for (int i = 0; i < count; ++i) {
+				if (i != 0)
+					sb.Append (", ");
+				sb.Append (ParameterDesc (i));
+			}
+			sb.Append (end);
+			return sb.ToString ();
+		}
+
+		public bool HasArglist {
+			get { return has_arglist; }
+		}
+
+		public bool HasExtensionMethodType {
+			get {
+				if (Count == 0)
+					return false;
+
+				return FixedParameters [0].HasExtensionMethodModifier;
+			}
+		}
+
+		public bool HasParams {
+			get { return has_params; }
+		}
+
+		public bool IsEmpty {
+			get { return parameters.Length == 0; }
+		}
+
+		public AParametersCollection Inflate (TypeParameterInflator inflator)
+		{
+			TypeSpec[] inflated_types = null;
+			bool default_value = false;
+
+			for (int i = 0; i < Count; ++i) {
+				var inflated_param = inflator.Inflate (types[i]);
+				if (inflated_types == null) {
+					if (inflated_param == types[i])
+						continue;
+
+					default_value |= FixedParameters[i].HasDefaultValue;
+					inflated_types = new TypeSpec[types.Length];
+					Array.Copy (types, inflated_types, types.Length);
+				} else {
+					if (inflated_param == types[i])
+						continue;
+
+					default_value |= FixedParameters[i].HasDefaultValue;
+				}
+
+				inflated_types[i] = inflated_param;
+			}
+
+			if (inflated_types == null)
+				return this;
+
+			var clone = (AParametersCollection) MemberwiseClone ();
+			clone.types = inflated_types;
+
+			//
+			// Default expression is original expression from the parameter
+			// declaration context which can be of nested enum in generic class type.
+			// In such case we end up with expression type of G<T>.E and e.g. parameter
+			// type of G<int>.E and conversion would fail without inflate in this
+			// context.
+			//
+			if (default_value) {
+				clone.parameters = new IParameterData[Count];
+				for (int i = 0; i < Count; ++i) {
+					var fp = FixedParameters[i];
+					clone.FixedParameters[i] = fp;
+
+					if (!fp.HasDefaultValue)
+						continue;
+
+					var expr = fp.DefaultValue;
+
+					if (inflated_types[i] == expr.Type)
+						continue;
+
+					var c = expr as Constant;
+					if (c != null) {
+						//
+						// It may fail we are inflating before type validation is done
+						//
+						c = Constant.ExtractConstantFromValue (inflated_types[i], c.GetValue (), expr.Location);
+						if (c == null)
+							expr = new DefaultValueExpression (new TypeExpression (inflated_types[i], expr.Location), expr.Location);
+						else
+							expr = c;
+					} else if (expr is DefaultValueExpression)
+						expr = new DefaultValueExpression (new TypeExpression (inflated_types[i], expr.Location), expr.Location);
+
+					clone.FixedParameters[i] = new ParameterData (fp.Name, fp.ModFlags, expr);
+				}
+			}
+
+			return clone;
+		}
+
+		public string ParameterDesc (int pos)
+		{
+			if (types == null || types [pos] == null)
+				return ((Parameter)FixedParameters [pos]).GetSignatureForError ();
+
+			string type = types [pos].GetSignatureForError ();
+			if (FixedParameters [pos].HasExtensionMethodModifier)
+				return "this " + type;
+
+			var mod = FixedParameters[pos].ModFlags & Parameter.Modifier.ModifierMask;
+			if (mod == 0)
+				return type;
+
+			return Parameter.GetModifierSignature (mod) + " " + type;
+		}
+
+		public TypeSpec[] Types {
+			get { return types; }
+			set { types = value; }
+		}
+	}
+
+	//
+	// A collection of imported or resolved parameters
+	//
+	public class ParametersImported : AParametersCollection
+	{
+		public ParametersImported (IParameterData [] parameters, TypeSpec [] types, bool hasArglist, bool hasParams)
+		{
+			this.parameters = parameters;
+			this.types = types;
+			this.has_arglist = hasArglist;
+			this.has_params = hasParams;
+		}
+
+		public ParametersImported (IParameterData[] param, TypeSpec[] types, bool hasParams)
+		{
+			this.parameters = param;
+			this.types = types;
+			this.has_params = hasParams;
+		}
+	}
+
+	/// <summary>
+	///   Represents the methods parameters
+	/// </summary>
+	public class ParametersCompiled : AParametersCollection
+	{
+		public static readonly ParametersCompiled EmptyReadOnlyParameters = new ParametersCompiled ();
+		
+		// Used by C# 2.0 delegates
+		public static readonly ParametersCompiled Undefined = new ParametersCompiled ();
+
+		private ParametersCompiled ()
+		{
+			parameters = new Parameter [0];
+			types = TypeSpec.EmptyTypes;
+		}
+
+		private ParametersCompiled (IParameterData[] parameters, TypeSpec[] types)
+		{
+			this.parameters = parameters;
+		    this.types = types;
+		}
+		
+		public ParametersCompiled (params Parameter[] parameters)
+		{
+			if (parameters == null || parameters.Length == 0)
+				throw new ArgumentException ("Use EmptyReadOnlyParameters");
+
+			this.parameters = parameters;
+			int count = parameters.Length;
+
+			for (int i = 0; i < count; i++){
+				has_params |= (parameters [i].ModFlags & Parameter.Modifier.PARAMS) != 0;
+			}
+		}
+
+		public ParametersCompiled (Parameter [] parameters, bool has_arglist) :
+			this (parameters)
+		{
+			this.has_arglist = has_arglist;
+		}
+		
+		public static ParametersCompiled CreateFullyResolved (Parameter p, TypeSpec type)
+		{
+			return new ParametersCompiled (new Parameter [] { p }, new TypeSpec [] { type });
+		}
+		
+		public static ParametersCompiled CreateFullyResolved (Parameter[] parameters, TypeSpec[] types)
+		{
+			return new ParametersCompiled (parameters, types);
+		}
+
+		public static ParametersCompiled Prefix (ParametersCompiled parameters, Parameter p, TypeSpec type)
+		{
+			var ptypes = new TypeSpec [parameters.Count + 1];
+			ptypes [0] = type;
+			Array.Copy (parameters.Types, 0, ptypes, 1, parameters.Count);
+
+			var param = new Parameter [ptypes.Length];
+			param [0] = p;
+			for (int i = 0; i < parameters.Count; ++i) {
+				var pi = parameters [i];
+				param [i + 1] = pi;
+				pi.SetIndex (i + 1);
+			}
+
+			return ParametersCompiled.CreateFullyResolved (param, ptypes);
+		}
+
+		//
+		// TODO: This does not fit here, it should go to different version of AParametersCollection
+		// as the underlying type is not Parameter and some methods will fail to cast
+		//
+		public static AParametersCollection CreateFullyResolved (params TypeSpec[] types)
+		{
+			var pd = new ParameterData [types.Length];
+			for (int i = 0; i < pd.Length; ++i)
+				pd[i] = new ParameterData (null, Parameter.Modifier.NONE, null);
+
+			return new ParametersCompiled (pd, types);
+		}
+
+		public static ParametersCompiled CreateImplicitParameter (FullNamedExpression texpr, Location loc)
+		{
+			return new ParametersCompiled (
+				new[] { new Parameter (texpr, "value", Parameter.Modifier.NONE, null, loc) },
+				null);
+		}
+
+		public void CheckConstraints (IMemberContext mc)
+		{
+			foreach (Parameter p in parameters) {
+				//
+				// It's null for compiler generated types or special types like __arglist
+				//
+				if (p.TypeExpression != null)
+					ConstraintChecker.Check (mc, p.Type, p.TypeExpression.Location);
+			}
+		}
+
+		//
+		// Returns non-zero value for equal CLS parameter signatures
+		//
+		public static int IsSameClsSignature (AParametersCollection a, AParametersCollection b)
+		{
+			int res = 0;
+
+			for (int i = 0; i < a.Count; ++i) {
+				var a_type = a.Types[i];
+				var b_type = b.Types[i];
+				if (TypeSpecComparer.Override.IsEqual (a_type, b_type)) {
+					if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
+						res |= 1;
+
+					continue;
+				}
+
+				var ac_a = a_type as ArrayContainer;
+				if (ac_a == null)
+					return 0;
+
+				var ac_b = b_type as ArrayContainer;
+				if (ac_b == null)
+					return 0;
+
+				if (ac_a.Element is ArrayContainer || ac_b.Element is ArrayContainer) {
+					res |= 2;
+					continue;
+				}
+
+				if (ac_a.Rank != ac_b.Rank && TypeSpecComparer.Override.IsEqual (ac_a.Element, ac_b.Element)) {
+					res |= 1;
+					continue;
+				}
+
+				return 0;
+			}
+
+			return res;
+		}
+
+		public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter compilerParams, TypeSpec compilerTypes)
+		{
+			return MergeGenerated (ctx, userParams, checkConflicts,
+				new Parameter [] { compilerParams },
+				new TypeSpec [] { compilerTypes });
+		}
+
+		//
+		// Use this method when you merge compiler generated parameters with user parameters
+		//
+		public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter[] compilerParams, TypeSpec[] compilerTypes)
+		{
+			Parameter[] all_params = new Parameter [userParams.Count + compilerParams.Length];
+			userParams.FixedParameters.CopyTo(all_params, 0);
+
+			TypeSpec [] all_types;
+			if (userParams.types != null) {
+				all_types = new TypeSpec [all_params.Length];
+				userParams.Types.CopyTo (all_types, 0);
+			} else {
+				all_types = null;
+			}
+
+			int last_filled = userParams.Count;
+			int index = 0;
+			foreach (Parameter p in compilerParams) {
+				for (int i = 0; i < last_filled; ++i) {
+					while (p.Name == all_params [i].Name) {
+						if (checkConflicts && i < userParams.Count) {
+							ctx.Report.Error (316, userParams[i].Location,
+								"The parameter name `{0}' conflicts with a compiler generated name", p.Name);
+						}
+						p.Name = '_' + p.Name;
+					}
+				}
+				all_params [last_filled] = p;
+				if (all_types != null)
+					all_types [last_filled] = compilerTypes [index++];
+				++last_filled;
+			}
+			
+			ParametersCompiled parameters = new ParametersCompiled (all_params, all_types);
+			parameters.has_params = userParams.has_params;
+			return parameters;
+		}
+
+		//
+		// Parameters checks for members which don't have a block
+		//
+		public void CheckParameters (MemberCore member)
+		{
+			for (int i = 0; i < parameters.Length; ++i) {
+				var name = parameters[i].Name;
+				for (int ii = i + 1; ii < parameters.Length; ++ii) {
+					if (parameters[ii].Name == name)
+						this[ii].Error_DuplicateName (member.Compiler.Report);
+				}
+			}
+		}
+
+		public bool Resolve (IMemberContext ec)
+		{
+			if (types != null)
+				return true;
+			
+			types = new TypeSpec [Count];
+			
+			bool ok = true;
+			Parameter p;
+			for (int i = 0; i < FixedParameters.Length; ++i) {
+				p = this [i];
+				TypeSpec t = p.Resolve (ec, i);
+				if (t == null) {
+					ok = false;
+					continue;
+				}
+
+				types [i] = t;
+			}
+
+			return ok;
+		}
+
+		public void ResolveDefaultValues (MemberCore m)
+		{
+			ResolveContext rc = null;
+			for (int i = 0; i < parameters.Length; ++i) {
+				Parameter p = (Parameter) parameters [i];
+
+				//
+				// Try not to enter default values resolution if there are is not any default value possible
+				//
+				if (p.HasDefaultValue || p.OptAttributes != null) {
+					if (rc == null)
+						rc = new ResolveContext (m);
+
+					p.ResolveDefaultValue (rc);
+				}
+			}
+		}
+
+		// Define each type attribute (in/out/ref) and
+		// the argument names.
+		public void ApplyAttributes (IMemberContext mc, MethodBase builder)
+		{
+			if (Count == 0)
+				return;
+
+			MethodBuilder mb = builder as MethodBuilder;
+			ConstructorBuilder cb = builder as ConstructorBuilder;
+			var pa = mc.Module.PredefinedAttributes;
+
+			for (int i = 0; i < Count; i++) {
+				this [i].ApplyAttributes (mb, cb, i + 1, pa);
+			}
+		}
+
+		public void VerifyClsCompliance (IMemberContext ctx)
+		{
+			foreach (Parameter p in FixedParameters)
+				p.IsClsCompliant (ctx);
+		}
+
+		public Parameter this [int pos] {
+			get { return (Parameter) parameters [pos]; }
+		}
+
+		public Expression CreateExpressionTree (BlockContext ec, Location loc)
+		{
+			var initializers = new ArrayInitializer (Count, loc);
+			foreach (Parameter p in FixedParameters) {
+				//
+				// Each parameter expression is stored to local variable
+				// to save some memory when referenced later.
+				//
+				StatementExpression se = new StatementExpression (p.CreateExpressionTreeVariable (ec), Location.Null);
+				if (se.Resolve (ec)) {
+					ec.CurrentBlock.AddScopeStatement (new TemporaryVariableReference.Declarator (p.ExpressionTreeVariableReference ()));
+					ec.CurrentBlock.AddScopeStatement (se);
+				}
+				
+				initializers.Add (p.ExpressionTreeVariableReference ());
+			}
+
+			return new ArrayCreation (
+				Parameter.ResolveParameterExpressionType (ec, loc),
+				initializers, loc);
+		}
+
+		public ParametersCompiled Clone ()
+		{
+			ParametersCompiled p = (ParametersCompiled) MemberwiseClone ();
+
+			p.parameters = new IParameterData [parameters.Length];
+			for (int i = 0; i < Count; ++i)
+				p.parameters [i] = this [i].Clone ();
+
+			return p;
+		}
+	}
+
+	//
+	// Default parameter value expression. We need this wrapper to handle
+	// default parameter values of folded constants (e.g. indexer parameters).
+	// The expression is resolved only once but applied to two methods which
+	// both share reference to this expression and we ensure that resolving
+	// this expression always returns same instance
+	//
+	public class DefaultParameterValueExpression : CompositeExpression
+	{
+		public DefaultParameterValueExpression (Expression expr)
+			: base (expr)
+		{
+		}
+
+		public void Resolve (ResolveContext rc, Parameter p)
+		{
+			var expr = Resolve (rc);
+			if (expr == null) {
+				this.expr = ErrorExpression.Instance;
+				return;
+			}
+
+			expr = Child;
+
+			if (!(expr is Constant || expr is DefaultValueExpression || (expr is New && ((New) expr).IsDefaultStruct))) {
+				if (!(expr is ErrorExpression)) {
+					rc.Report.Error (1736, Location,
+						"The expression being assigned to optional parameter `{0}' must be a constant or default value",
+						p.Name);
+				}
+
+				return;
+			}
+
+			var parameter_type = p.Type;
+			if (type == parameter_type)
+				return;
+
+			var res = Convert.ImplicitConversionStandard (rc, expr, parameter_type, Location);
+			if (res != null) {
+				if (parameter_type.IsNullableType && res is Nullable.Wrap) {
+					Nullable.Wrap wrap = (Nullable.Wrap) res;
+					res = wrap.Child;
+					if (!(res is Constant)) {
+						rc.Report.Error (1770, Location,
+							"The expression being assigned to nullable optional parameter `{0}' must be default value",
+							p.Name);
+						return;
+					}
+				}
+
+				if (!expr.IsNull && TypeSpec.IsReferenceType (parameter_type) && parameter_type.BuiltinType != BuiltinTypeSpec.Type.String) {
+					rc.Report.Error (1763, Location,
+						"Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
+						p.Name, parameter_type.GetSignatureForError ());
+
+					return;
+				}
+
+				this.expr = res;
+				return;
+			}
+
+			rc.Report.Error (1750, Location,
+				"Optional parameter expression of type `{0}' cannot be converted to parameter type `{1}'",
+				type.GetSignatureForError (), parameter_type.GetSignatureForError ());
+
+			this.expr = ErrorExpression.Instance;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/pending.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/pending.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/pending.cs	(revision 11807)
@@ -0,0 +1,734 @@
+//
+// pending.cs: Pending method implementation
+//
+// Authors:
+//   Miguel de Icaza (miguel@gnu.org)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2008 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+
+	struct TypeAndMethods {
+		public TypeSpec          type;
+		public IList<MethodSpec> methods;
+
+		// 
+		// Whether it is optional, this is used to allow the explicit/implicit
+		// implementation when a base class already implements an interface. 
+		//
+		// For example:
+		//
+		// class X : IA { }  class Y : X, IA { IA.Explicit (); }
+		//
+		public bool          optional;
+				
+		//
+		// This flag on the method says `We found a match, but
+		// because it was private, we could not use the match
+		//
+		public MethodData [] found;
+
+		// If a method is defined here, then we always need to
+		// create a proxy for it.  This is used when implementing
+		// an interface's indexer with a different IndexerName.
+		public MethodSpec [] need_proxy;
+	}
+
+	struct ProxyMethodContext : IMemberContext
+	{
+		readonly TypeContainer container;
+
+		public ProxyMethodContext (TypeContainer container)
+		{
+			this.container = container;
+		}
+
+		public TypeSpec CurrentType {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public TypeParameters CurrentTypeParameters {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public MemberCore CurrentMemberDefinition {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public bool IsObsolete {
+			get {
+				return false;
+			}
+		}
+
+		public bool IsUnsafe {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		public bool IsStatic {
+			get {
+				return false;
+			}
+		}
+
+		public ModuleContainer Module {
+			get {
+				return container.Module;
+			}
+		}
+
+		public string GetSignatureForError ()
+		{
+			throw new NotImplementedException ();
+		}
+
+		public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public FullNamedExpression LookupNamespaceAlias (string name)
+		{
+			throw new NotImplementedException ();
+		}
+	}
+
+	public class PendingImplementation
+	{
+		/// <summary>
+		///   The container for this PendingImplementation
+		/// </summary>
+		readonly TypeDefinition container;
+		
+		/// <summary>
+		///   This is the array of TypeAndMethods that describes the pending implementations
+		///   (both interfaces and abstract methods in base class)
+		/// </summary>
+		TypeAndMethods [] pending_implementations;
+
+		PendingImplementation (TypeDefinition container, MissingInterfacesInfo[] missing_ifaces, MethodSpec[] abstract_methods, int total)
+		{
+			var type_builder = container.Definition;
+			
+			this.container = container;
+			pending_implementations = new TypeAndMethods [total];
+
+			int i = 0;
+			if (abstract_methods != null) {
+				int count = abstract_methods.Length;
+				pending_implementations [i].methods = new MethodSpec [count];
+				pending_implementations [i].need_proxy = new MethodSpec [count];
+
+				pending_implementations [i].methods = abstract_methods;
+				pending_implementations [i].found = new MethodData [count];
+				pending_implementations [i].type = type_builder;
+				++i;
+			}
+
+			foreach (MissingInterfacesInfo missing in missing_ifaces) {
+				var iface = missing.Type;
+				var mi = MemberCache.GetInterfaceMethods (iface);
+
+				int count = mi.Count;
+				pending_implementations [i].type = iface;
+				pending_implementations [i].optional = missing.Optional;
+				pending_implementations [i].methods = mi;
+				pending_implementations [i].found = new MethodData [count];
+				pending_implementations [i].need_proxy = new MethodSpec [count];
+				i++;
+			}
+		}
+
+		Report Report {
+			get {
+				return container.Module.Compiler.Report;
+			}
+		}
+
+		struct MissingInterfacesInfo {
+			public TypeSpec Type;
+			public bool Optional;
+
+			public MissingInterfacesInfo (TypeSpec t)
+			{
+				Type = t;
+				Optional = false;
+			}
+		}
+
+		static readonly MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0];
+		
+		static MissingInterfacesInfo [] GetMissingInterfaces (TypeDefinition container)
+		{
+			//
+			// Interfaces will return all interfaces that the container
+			// implements including any inherited interfaces
+			//
+			var impl = container.Definition.Interfaces;
+
+			if (impl == null || impl.Count == 0)
+				return EmptyMissingInterfacesInfo;
+
+			var ret = new MissingInterfacesInfo[impl.Count];
+
+			for (int i = 0; i < ret.Length; i++)
+				ret [i] = new MissingInterfacesInfo (impl [i]);
+
+			// we really should not get here because Object doesnt implement any
+			// interfaces. But it could implement something internal, so we have
+			// to handle that case.
+			if (container.BaseType == null)
+				return ret;
+			
+			var base_impls = container.BaseType.Interfaces;
+			if (base_impls != null) {
+				foreach (TypeSpec t in base_impls) {
+					for (int i = 0; i < ret.Length; i++) {
+						if (t == ret[i].Type) {
+							ret[i].Optional = true;
+							break;
+						}
+					}
+				}
+			}
+
+			return ret;
+		}
+		
+		//
+		// Factory method: if there are pending implementation methods, we return a PendingImplementation
+		// object, otherwise we return null.
+		//
+		// Register method implementations are either abstract methods
+		// flagged as such on the base class or interface methods
+		//
+		static public PendingImplementation GetPendingImplementations (TypeDefinition container)
+		{
+			TypeSpec b = container.BaseType;
+
+			var missing_interfaces = GetMissingInterfaces (container);
+
+			//
+			// If we are implementing an abstract class, and we are not
+			// ourselves abstract, and there are abstract methods (C# allows
+			// abstract classes that have no abstract methods), then allocate
+			// one slot.
+			//
+			// We also pre-compute the methods.
+			//
+			bool implementing_abstract = ((b != null) && b.IsAbstract && (container.ModFlags & Modifiers.ABSTRACT) == 0);
+			MethodSpec[] abstract_methods = null;
+
+			if (implementing_abstract){
+				var am = MemberCache.GetNotImplementedAbstractMethods (b);
+
+				if (am == null) {
+					implementing_abstract = false;
+				} else {
+					abstract_methods = new MethodSpec[am.Count];
+					am.CopyTo (abstract_methods, 0);
+				}
+			}
+			
+			int total = missing_interfaces.Length +  (implementing_abstract ? 1 : 0);
+			if (total == 0)
+				return null;
+
+			var pending = new PendingImplementation (container, missing_interfaces, abstract_methods, total);
+
+			//
+			// check for inherited conflicting methods
+			//
+			foreach (var p in pending.pending_implementations) {
+				//
+				// It can happen for generic interfaces only
+				//
+				if (!p.type.IsGeneric)
+					continue;
+
+				//
+				// CLR does not distinguishes between ref and out
+				//
+				for (int i = 0; i < p.methods.Count; ++i) {
+					MethodSpec compared_method = p.methods[i];
+					if (compared_method.Parameters.IsEmpty)
+						continue;
+
+					for (int ii = i + 1; ii < p.methods.Count; ++ii) {
+						MethodSpec tested_method = p.methods[ii];
+						if (compared_method.Name != tested_method.Name)
+							continue;
+
+						if (p.type != tested_method.DeclaringType)
+							continue;
+
+						if (!TypeSpecComparer.Override.IsSame (compared_method.Parameters.Types, tested_method.Parameters.Types))
+							continue;
+
+						bool exact_match = true;
+						bool ref_only_difference = false;
+						var cp = compared_method.Parameters.FixedParameters;
+						var tp = tested_method.Parameters.FixedParameters;
+
+						for (int pi = 0; pi < cp.Length; ++pi) {
+							//
+							// First check exact modifiers match
+							//
+							if ((cp[pi].ModFlags & Parameter.Modifier.RefOutMask) == (tp[pi].ModFlags & Parameter.Modifier.RefOutMask))
+								continue;
+
+							if (((cp[pi].ModFlags | tp[pi].ModFlags) & Parameter.Modifier.RefOutMask) == Parameter.Modifier.RefOutMask) {
+								ref_only_difference = true;
+								continue;
+							}
+
+							exact_match = false;
+							break;
+						}
+
+						if (!exact_match || !ref_only_difference)
+							continue;
+
+						pending.Report.SymbolRelatedToPreviousError (compared_method);
+						pending.Report.SymbolRelatedToPreviousError (tested_method);
+						pending.Report.Error (767, container.Location,
+							"Cannot implement interface `{0}' with the specified type parameters because it causes method `{1}' to differ on parameter modifiers only",
+							p.type.GetDefinition().GetSignatureForError (), compared_method.GetSignatureForError ());
+
+						break;
+					}
+				}
+			}
+
+			return pending;
+		}
+
+		public enum Operation {
+			//
+			// If you change this, review the whole InterfaceMethod routine as there
+			// are a couple of assumptions on these three states
+			//
+			Lookup, ClearOne, ClearAll
+		}
+
+		/// <summary>
+		///   Whether the specified method is an interface method implementation
+		/// </summary>
+		public MethodSpec IsInterfaceMethod (MemberName name, TypeSpec ifaceType, MethodData method, out MethodSpec ambiguousCandidate, ref bool optional)
+		{
+			return InterfaceMethod (name, ifaceType, method, Operation.Lookup, out ambiguousCandidate, ref optional);
+		}
+
+		public void ImplementMethod (MemberName name, TypeSpec ifaceType, MethodData method, bool clear_one, out MethodSpec ambiguousCandidate, ref bool optional)
+		{
+			InterfaceMethod (name, ifaceType, method, clear_one ? Operation.ClearOne : Operation.ClearAll, out ambiguousCandidate, ref optional);
+		}
+
+		/// <remarks>
+		///   If a method in Type `t' (or null to look in all interfaces
+		///   and the base abstract class) with name `Name', return type `ret_type' and
+		///   arguments `args' implements an interface, this method will
+		///   return the MethodInfo that this method implements.
+		///
+		///   If `name' is null, we operate solely on the method's signature.  This is for
+		///   instance used when implementing indexers.
+		///
+		///   The `Operation op' controls whether to lookup, clear the pending bit, or clear
+		///   all the methods with the given signature.
+		///
+		///   The `MethodInfo need_proxy' is used when we're implementing an interface's
+		///   indexer in a class.  If the new indexer's IndexerName does not match the one
+		///   that was used in the interface, then we always need to create a proxy for it.
+		///
+		/// </remarks>
+		public MethodSpec InterfaceMethod (MemberName name, TypeSpec iType, MethodData method, Operation op, out MethodSpec ambiguousCandidate, ref bool optional)
+		{
+			ambiguousCandidate = null;
+
+			if (pending_implementations == null)
+				return null;
+
+			TypeSpec ret_type = method.method.ReturnType;
+			ParametersCompiled args = method.method.ParameterInfo;
+			bool is_indexer = method.method is Indexer.SetIndexerMethod || method.method is Indexer.GetIndexerMethod;
+			MethodSpec m;
+
+			foreach (TypeAndMethods tm in pending_implementations){
+				if (!(iType == null || tm.type == iType))
+					continue;
+
+				int method_count = tm.methods.Count;
+				for (int i = 0; i < method_count; i++){
+					m = tm.methods [i];
+
+					if (m == null)
+						continue;
+
+					if (is_indexer) {
+						if (!m.IsAccessor || m.Parameters.IsEmpty)
+							continue;
+					} else {
+						if (name.Name != m.Name)
+							continue;
+
+						if (m.Arity != name.Arity)
+							continue;
+					}
+
+					if (!TypeSpecComparer.Override.IsEqual (m.Parameters, args))
+						continue;
+
+					if (!TypeSpecComparer.Override.IsEqual (m.ReturnType, ret_type)) {
+						tm.found[i] = method;
+						continue;
+					}
+
+					//
+					// `need_proxy' is not null when we're implementing an
+					// interface indexer and this is Clear(One/All) operation.
+					//
+					// If `name' is null, then we do a match solely based on the
+					// signature and not on the name (this is done in the Lookup
+					// for an interface indexer).
+					//
+					if (op != Operation.Lookup) {
+						if (m.IsAccessor != method.method.IsAccessor)
+							continue;
+
+						// If `t != null', then this is an explicitly interface
+						// implementation and we can always clear the method.
+						// `need_proxy' is not null if we're implementing an
+						// interface indexer.  In this case, we need to create
+						// a proxy if the implementation's IndexerName doesn't
+						// match the IndexerName in the interface.
+						if (m.DeclaringType.IsInterface && iType == null && name.Name != m.Name) {	// TODO: This is very expensive comparison
+							tm.need_proxy[i] = method.method.Spec;
+						} else {
+							tm.methods[i] = null;
+						}
+					} else {
+						tm.found [i] = method;
+						optional = tm.optional;
+					}
+
+					if (op == Operation.Lookup && name.ExplicitInterface != null && ambiguousCandidate == null) {
+						ambiguousCandidate = m;
+						continue;
+					}
+
+					//
+					// Lookups and ClearOne return
+					//
+					if (op != Operation.ClearAll)
+						return m;
+				}
+
+				// If a specific type was requested, we can stop now.
+				if (tm.type == iType)
+					break;
+			}
+
+			m = ambiguousCandidate;
+			ambiguousCandidate = null;
+			return m;
+		}
+
+		/// <summary>
+		///   C# allows this kind of scenarios:
+		///   interface I { void M (); }
+		///   class X { public void M (); }
+		///   class Y : X, I { }
+		///
+		///   For that case, we create an explicit implementation function
+		///   I.M in Y.
+		/// </summary>
+		void DefineProxy (TypeSpec iface, MethodSpec base_method, MethodSpec iface_method)
+		{
+			// TODO: Handle nested iface names
+			string proxy_name;
+			var ns = iface.MemberDefinition.Namespace;
+			if (string.IsNullOrEmpty (ns))
+				proxy_name = iface.MemberDefinition.Name + "." + iface_method.Name;
+			else
+				proxy_name = ns + "." + iface.MemberDefinition.Name + "." + iface_method.Name;
+
+			var param = iface_method.Parameters;
+
+			MethodBuilder proxy = container.TypeBuilder.DefineMethod (
+				proxy_name,
+				MethodAttributes.Private |
+				MethodAttributes.HideBySig |
+				MethodAttributes.NewSlot |
+				MethodAttributes.CheckAccessOnOverride |
+				MethodAttributes.Virtual | MethodAttributes.Final,
+				CallingConventions.Standard | CallingConventions.HasThis,
+				base_method.ReturnType.GetMetaInfo (), param.GetMetaInfo ());
+
+			if (iface_method.IsGeneric) {
+				var gnames = iface_method.GenericDefinition.TypeParameters.Select (l => l.Name).ToArray ();
+				proxy.DefineGenericParameters (gnames);
+			}
+
+			for (int i = 0; i < param.Count; i++) {
+				string name = param.FixedParameters [i].Name;
+				ParameterAttributes attr = ParametersCompiled.GetParameterAttribute (param.FixedParameters [i].ModFlags);
+				proxy.DefineParameter (i + 1, attr, name);
+			}
+
+			int top = param.Count;
+			var ec = new EmitContext (new ProxyMethodContext (container), proxy.GetILGenerator (), null, null);
+			ec.EmitThis ();
+			// TODO: GetAllParametersArguments
+			for (int i = 0; i < top; i++)
+				ec.EmitArgumentLoad (i);
+
+			ec.Emit (OpCodes.Call, base_method);
+			ec.Emit (OpCodes.Ret);
+
+			container.TypeBuilder.DefineMethodOverride (proxy, (MethodInfo) iface_method.GetMetaInfo ());
+		}
+		
+		/// <summary>
+		///   This function tells whether one of our base classes implements
+		///   the given method (which turns out, it is valid to have an interface
+		///   implementation in a base
+		/// </summary>
+		bool BaseImplements (TypeSpec iface_type, MethodSpec mi, out MethodSpec base_method)
+		{
+			base_method = null;
+			var base_type = container.BaseType;
+
+			//
+			// Setup filter with no return type to give better error message
+			// about mismatch at return type when the check bellow rejects them
+			//
+			var parameters = mi.Parameters;
+			MethodSpec close_match = null;
+
+			while (true) {
+				var candidates = MemberCache.FindMembers (base_type, mi.Name, false);
+				if (candidates == null) {
+					base_method = close_match;
+					return false;
+				}
+
+				MethodSpec similar_candidate = null;
+				foreach (var candidate in candidates) {
+					if (candidate.Kind != MemberKind.Method)
+						continue;
+
+					if (candidate.Arity != mi.Arity)
+						continue;
+
+					var candidate_param = ((MethodSpec) candidate).Parameters;
+					if (!TypeSpecComparer.Override.IsEqual (parameters.Types, candidate_param.Types))
+						continue;
+
+					bool modifiers_match = true;
+					for (int i = 0; i < parameters.Count; ++i) {
+						//
+						// First check exact ref/out match
+						//
+						if ((parameters.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) == (candidate_param.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
+							continue;
+
+						modifiers_match = false;
+
+						//
+						// Different in ref/out only
+						//
+						if ((parameters.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (candidate_param.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask)) {
+							if (similar_candidate == null) {
+								if (!candidate.IsPublic)
+									break;
+
+								if (!TypeSpecComparer.Override.IsEqual (mi.ReturnType, ((MethodSpec) candidate).ReturnType))
+									break;
+
+								// It's used for ref/out ambiguity overload check
+								similar_candidate = (MethodSpec) candidate;
+							}
+
+							continue;
+						}
+
+						similar_candidate = null;
+						break;
+					}
+
+					if (!modifiers_match)
+						continue;
+
+					//
+					// From this point the candidate is used for detailed error reporting
+					// because it's very close match to what we are looking for
+					//
+					var m = (MethodSpec) candidate;
+
+					if (!m.IsPublic) {
+						if (close_match == null)
+							close_match = m;
+
+						continue;
+					}
+
+					if (!TypeSpecComparer.Override.IsEqual (mi.ReturnType, m.ReturnType)) {
+						if (close_match == null)
+							close_match = m;
+
+						continue;
+					}
+						
+					base_method = m;
+
+					if (mi.IsGeneric && !Method.CheckImplementingMethodConstraints (container, m, mi)) {
+						return true;
+					}
+				}
+				
+				if (base_method != null) {
+					if (similar_candidate != null) {
+						Report.SymbolRelatedToPreviousError (similar_candidate);
+						Report.SymbolRelatedToPreviousError (mi);
+						Report.SymbolRelatedToPreviousError (container);
+						Report.Warning (1956, 1, ((MemberCore) base_method.MemberDefinition).Location,
+							"The interface method `{0}' implementation is ambiguous between following methods: `{1}' and `{2}' in type `{3}'",
+							mi.GetSignatureForError (), base_method.GetSignatureForError (), similar_candidate.GetSignatureForError (), container.GetSignatureForError ());
+					}
+
+					break;
+				}
+
+				base_type = candidates[0].DeclaringType.BaseType;
+				if (base_type == null) {
+					base_method = close_match;
+					return false;
+				}
+			}
+
+			if (!base_method.IsVirtual) {
+#if STATIC
+				var base_builder = base_method.GetMetaInfo () as MethodBuilder;
+				if (base_builder != null) {
+					//
+					// We can avoid creating a proxy if base_method can be marked 'final virtual'. This can
+					// be done for all methods from compiled assembly
+					//
+					base_builder.__SetAttributes (base_builder.Attributes | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.NewSlot);
+					return true;
+				}
+#endif
+				DefineProxy (iface_type, base_method, mi);
+			}
+
+			return true;
+		}
+
+		/// <summary>
+		///   Verifies that any pending abstract methods or interface methods
+		///   were implemented.
+		/// </summary>
+		public bool VerifyPendingMethods ()
+		{
+			int top = pending_implementations.Length;
+			bool errors = false;
+			int i;
+			
+			for (i = 0; i < top; i++){
+				TypeSpec type = pending_implementations [i].type;
+
+				bool base_implements_type = type.IsInterface &&
+					container.BaseType != null &&
+					container.BaseType.ImplementsInterface (type, false);
+
+				for (int j = 0; j < pending_implementations [i].methods.Count; ++j) {
+					var mi = pending_implementations[i].methods[j];
+					if (mi == null)
+						continue;
+
+					if (type.IsInterface){
+						var need_proxy =
+							pending_implementations [i].need_proxy [j];
+
+						if (need_proxy != null) {
+							DefineProxy (type, need_proxy, mi);
+							continue;
+						}
+
+						if (pending_implementations [i].optional)
+							continue;
+
+						MethodSpec candidate;
+						if (base_implements_type || BaseImplements (type, mi, out candidate))
+							continue;
+
+						if (candidate == null) {
+							MethodData md = pending_implementations [i].found [j];
+							if (md != null)
+								candidate = md.method.Spec;
+						}
+
+						Report.SymbolRelatedToPreviousError (mi);
+						if (candidate != null) {
+							Report.SymbolRelatedToPreviousError (candidate);
+							if (candidate.IsStatic) {
+								Report.Error (736, container.Location,
+									"`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is static",
+									container.GetSignatureForError (), mi.GetSignatureForError (), candidate.GetSignatureForError ());
+							} else if ((candidate.Modifiers & Modifiers.PUBLIC) == 0) {
+								Report.Error (737, container.Location,
+									"`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is not public",
+									container.GetSignatureForError (), mi.GetSignatureForError (), candidate.GetSignatureForError ());
+							} else {
+								Report.Error (738, container.Location,
+									"`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' return type `{3}' does not match interface member return type `{4}'",
+									container.GetSignatureForError (), mi.GetSignatureForError (), candidate.GetSignatureForError (),
+									candidate.ReturnType.GetSignatureForError (), mi.ReturnType.GetSignatureForError ());
+							}
+						} else {
+							Report.Error (535, container.Location, "`{0}' does not implement interface member `{1}'",
+								container.GetSignatureForError (), mi.GetSignatureForError ());
+						}
+					} else {
+						Report.SymbolRelatedToPreviousError (mi);
+						Report.Error (534, container.Location, "`{0}' does not implement inherited abstract member `{1}'",
+							container.GetSignatureForError (), mi.GetSignatureForError ());
+					}
+					errors = true;
+				}
+			}
+			return errors;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/property.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/property.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/property.cs	(revision 11807)
@@ -0,0 +1,1807 @@
+//
+// property.cs: Property based handlers
+//
+// Authors: Miguel de Icaza (miguel@gnu.org)
+//          Martin Baulig (martin@ximian.com)
+//          Marek Safar (marek.safar@seznam.cz)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Mono.CompilerServices.SymbolWriter;
+
+#if NET_2_1
+using XmlElement = System.Object;
+#endif
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp
+{
+	// It is used as a base class for all property based members
+	// This includes properties, indexers, and events
+	public abstract class PropertyBasedMember : InterfaceMemberBase
+	{
+		protected PropertyBasedMember (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
+			: base (parent, type, mod, allowed_mod, name, attrs)
+		{
+		}
+
+		protected void CheckReservedNameConflict (string prefix, MethodSpec accessor)
+		{
+			string name;
+			AParametersCollection parameters;
+			if (accessor != null) {
+				name = accessor.Name;
+				parameters = accessor.Parameters;
+			} else {
+				name = prefix + ShortName;
+				if (IsExplicitImpl)
+					name = MemberName.Left + "." + name;
+
+				if (this is Indexer) {
+					parameters = ((Indexer) this).ParameterInfo;
+					if (prefix[0] == 's') {
+						var data = new IParameterData[parameters.Count + 1];
+						Array.Copy (parameters.FixedParameters, data, data.Length - 1);
+						data[data.Length - 1] = new ParameterData ("value", Parameter.Modifier.NONE);
+						var types = new TypeSpec[data.Length];
+						Array.Copy (parameters.Types, types, data.Length - 1);
+						types[data.Length - 1] = member_type;
+
+						parameters = new ParametersImported (data, types, false);
+					}
+				} else {
+					if (prefix[0] == 's')
+						parameters = ParametersCompiled.CreateFullyResolved (new[] { member_type });
+					else
+						parameters = ParametersCompiled.EmptyReadOnlyParameters;
+				}
+			}
+
+			var conflict = MemberCache.FindMember (Parent.Definition,
+				new MemberFilter (name, 0, MemberKind.Method, parameters, null),
+				BindingRestriction.DeclaredOnly | BindingRestriction.NoAccessors);
+
+			if (conflict != null) {
+				Report.SymbolRelatedToPreviousError (conflict);
+				Report.Error (82, Location, "A member `{0}' is already reserved", conflict.GetSignatureForError ());
+			}
+		}
+
+		public abstract void PrepareEmit ();
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			if (!MemberType.IsCLSCompliant ()) {
+				Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
+					GetSignatureForError ());
+			}
+			return true;
+		}
+
+	}
+
+	public class PropertySpec : MemberSpec, IInterfaceMemberSpec
+	{
+		PropertyInfo info;
+		TypeSpec memberType;
+		MethodSpec set, get;
+
+		public PropertySpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, PropertyInfo info, Modifiers modifiers)
+			: base (kind, declaringType, definition, modifiers)
+		{
+			this.info = info;
+			this.memberType = memberType;
+		}
+
+		#region Properties
+
+		public MethodSpec Get {
+			get {
+				return get;
+			}
+			set {
+				get = value;
+				get.IsAccessor = true;
+			}
+		}
+
+		public MethodSpec Set { 
+			get {
+				return set;
+			}
+			set {
+				set = value;
+				set.IsAccessor = true;
+			}
+		}
+
+		public bool HasDifferentAccessibility {
+			get {
+				return HasGet && HasSet && 
+					(Get.Modifiers & Modifiers.AccessibilityMask) != (Set.Modifiers & Modifiers.AccessibilityMask);
+			}
+		}
+
+		public bool HasGet {
+			get {
+				return Get != null;
+			}
+		}
+
+		public bool HasSet {
+			get {
+				return Set != null;
+			}
+		}
+
+		public PropertyInfo MetaInfo {
+			get {
+				if ((state & StateFlags.PendingMetaInflate) != 0)
+					throw new NotSupportedException ();
+
+				return info;
+			}
+		}
+
+		public TypeSpec MemberType {
+			get {
+				return memberType;
+			}
+		}
+
+		#endregion
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var ps = (PropertySpec) base.InflateMember (inflator);
+			ps.memberType = inflator.Inflate (memberType);
+			return ps;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			return memberType.ResolveMissingDependencies (this);
+		}
+	}
+
+	//
+	// Properties and Indexers both generate PropertyBuilders, we use this to share 
+	// their common bits.
+	//
+	abstract public class PropertyBase : PropertyBasedMember {
+
+		public class GetMethod : PropertyMethod
+		{
+			static readonly string[] attribute_targets = new string [] { "method", "return" };
+
+			internal const string Prefix = "get_";
+
+			public GetMethod (PropertyBase method, Modifiers modifiers, Attributes attrs, Location loc)
+				: base (method, Prefix, modifiers, attrs, loc)
+			{
+			}
+
+			public override void Define (TypeContainer parent)
+			{
+				base.Define (parent);
+
+				Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
+
+				method_data = new MethodData (method, ModFlags, flags, this);
+
+				method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
+			}
+
+			public override TypeSpec ReturnType {
+				get {
+					return method.MemberType;
+				}
+			}
+
+			public override ParametersCompiled ParameterInfo {
+				get {
+					return ParametersCompiled.EmptyReadOnlyParameters;
+				}
+			}
+
+			public override string[] ValidAttributeTargets {
+				get {
+					return attribute_targets;
+				}
+			}
+		}
+
+		public class SetMethod : PropertyMethod {
+
+			static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
+
+			internal const string Prefix = "set_";
+
+			protected ParametersCompiled parameters;
+
+			public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
+				: base (method, Prefix, modifiers, attrs, loc)
+			{
+				this.parameters = parameters;
+			}
+
+			protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+			{
+				if (a.Target == AttributeTargets.Parameter) {
+					parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
+					return;
+				}
+
+				base.ApplyToExtraTarget (a, ctor, cdata, pa);
+			}
+
+			public override ParametersCompiled ParameterInfo {
+			    get {
+			        return parameters;
+			    }
+			}
+
+			public override void Define (TypeContainer parent)
+			{
+				parameters.Resolve (this);
+				
+				base.Define (parent);
+
+				Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
+
+				method_data = new MethodData (method, ModFlags, flags, this);
+
+				method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
+			}
+
+			public override TypeSpec ReturnType {
+				get {
+					return Parent.Compiler.BuiltinTypes.Void;
+				}
+			}
+
+			public override string[] ValidAttributeTargets {
+				get {
+					return attribute_targets;
+				}
+			}
+		}
+
+		static readonly string[] attribute_targets = new string[] { "property" };
+
+		public abstract class PropertyMethod : AbstractPropertyEventMethod
+		{
+			const Modifiers AllowedModifiers =
+				Modifiers.PUBLIC |
+				Modifiers.PROTECTED |
+				Modifiers.INTERNAL |
+				Modifiers.PRIVATE;
+		
+			protected readonly PropertyBase method;
+			protected MethodAttributes flags;
+
+			public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
+				: base (method, prefix, attrs, loc)
+			{
+				this.method = method;
+				this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
+				this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
+			}
+
+			public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+			{
+				if (a.Type == pa.MethodImpl) {
+					method.is_external_implementation = a.IsInternalCall ();
+				}
+
+				base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+			}
+
+			public override AttributeTargets AttributeTargets {
+				get {
+					return AttributeTargets.Method;
+				}
+			}
+
+			public override bool IsClsComplianceRequired ()
+			{
+				return method.IsClsComplianceRequired ();
+			}
+
+			public virtual void Define (TypeContainer parent)
+			{
+				var container = parent.PartialContainer;
+
+				//
+				// Check for custom access modifier
+				//
+				if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
+					ModFlags |= method.ModFlags;
+					flags = method.flags;
+				} else {
+					if (container.Kind == MemberKind.Interface)
+						Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
+							GetSignatureForError ());
+					else if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
+						Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
+					}
+
+					CheckModifiers (ModFlags);
+					ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
+					ModFlags |= Modifiers.PROPERTY_CUSTOM;
+					flags = ModifiersExtensions.MethodAttr (ModFlags);
+					flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
+				}
+
+				CheckAbstractAndExtern (block != null);
+				CheckProtectedModifier ();
+
+				if (block != null) {
+					if (block.IsIterator)
+						Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
+
+					if (Compiler.Settings.WriteMetadataOnly)
+						block = null;
+				}
+			}
+
+			public bool HasCustomAccessModifier {
+				get {
+					return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
+				}
+			}
+
+			public PropertyBase Property {
+				get {
+					return method;
+				}
+			}
+
+			public override ObsoleteAttribute GetAttributeObsolete ()
+			{
+				return method.GetAttributeObsolete ();
+			}
+
+			public override string GetSignatureForError()
+			{
+				return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
+			}
+
+			void CheckModifiers (Modifiers modflags)
+			{
+				if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
+					Report.Error (273, Location,
+						"The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
+						GetSignatureForError (), method.GetSignatureForError ());
+				}
+			}
+		}
+
+		PropertyMethod get, set, first;
+		PropertyBuilder PropertyBuilder;
+
+		protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
+			: base (parent, type, mod_flags, allowed_mod, name, attrs)
+		{
+		}
+
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Property;
+			}
+		}
+
+		public PropertyMethod AccessorFirst {
+			get {
+				return first;
+			}
+		}
+
+		public PropertyMethod AccessorSecond {
+			get {
+				return first == get ? set : get;
+			}
+		}
+
+		public override Variance ExpectedMemberTypeVariance {
+			get {
+				return (get != null && set != null) ?
+					Variance.None : set == null ?
+					Variance.Covariant :
+					Variance.Contravariant;
+			}
+		}
+
+		public PropertyMethod Get {
+			get {
+				return get;
+			}
+			set {
+				get = value;
+				if (first == null)
+					first = value;
+
+				Parent.AddNameToContainer (get, get.MemberName.Basename);
+			}
+		}
+
+		public PropertyMethod Set {
+			get {
+				return set;
+			}
+			set {
+				set = value;
+				if (first == null)
+					first = value;
+
+				Parent.AddNameToContainer (set, set.MemberName.Basename);
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+
+		#endregion
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.HasSecurityAttribute) {
+				a.Error_InvalidSecurityParent ();
+				return;
+			}
+
+			if (a.Type == pa.Dynamic) {
+				a.Error_MisusedDynamicAttribute ();
+				return;
+			}
+
+			PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
+		{
+			if (IsExplicitImpl) {
+				MemberFilter filter;
+				if (kind == MemberKind.Indexer)
+					filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
+				else
+					filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
+
+				var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
+
+				if (implementing == null)
+					return;
+
+				var accessor = get ? implementing.Get : implementing.Set;
+				if (accessor != null) {
+					Report.SymbolRelatedToPreviousError (accessor);
+					Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
+						GetSignatureForError (), accessor.GetSignatureForError ());
+				}
+			}
+		}
+
+		protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+		{
+			var ok = base.CheckOverrideAgainstBase (base_member);
+
+			//
+			// Check base property accessors conflict
+			//
+			var base_prop = (PropertySpec) base_member;
+			if (Get == null) {
+				if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasGet && !base_prop.Get.IsAccessible (this)) {
+					// TODO: Should be different error code but csc uses for some reason same
+					Report.SymbolRelatedToPreviousError (base_prop);
+					Report.Error (545, Location,
+						"`{0}': cannot override because `{1}' does not have accessible get accessor",
+						GetSignatureForError (), base_prop.GetSignatureForError ());
+					ok = false;
+				}
+			} else {
+				if (!base_prop.HasGet) {
+					if (ok) {
+						Report.SymbolRelatedToPreviousError (base_prop);
+						Report.Error (545, Get.Location,
+							"`{0}': cannot override because `{1}' does not have an overridable get accessor",
+							Get.GetSignatureForError (), base_prop.GetSignatureForError ());
+						ok = false;
+					}
+				} else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
+					if (!CheckAccessModifiers (Get, base_prop.Get)) {
+						Error_CannotChangeAccessModifiers (Get, base_prop.Get);
+						ok = false;
+					}
+				}
+			}
+
+			if (Set == null) {
+				if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasSet && !base_prop.Set.IsAccessible (this)) {
+					// TODO: Should be different error code but csc uses for some reason same
+					Report.SymbolRelatedToPreviousError (base_prop);
+					Report.Error (546, Location,
+						"`{0}': cannot override because `{1}' does not have accessible set accessor",
+						GetSignatureForError (), base_prop.GetSignatureForError ());
+					ok = false;
+				}
+			} else {
+				if (!base_prop.HasSet) {
+					if (ok) {
+						Report.SymbolRelatedToPreviousError (base_prop);
+						Report.Error (546, Set.Location,
+							"`{0}': cannot override because `{1}' does not have an overridable set accessor",
+							Set.GetSignatureForError (), base_prop.GetSignatureForError ());
+						ok = false;
+					}
+				} else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
+					if (!CheckAccessModifiers (Set, base_prop.Set)) {
+						Error_CannotChangeAccessModifiers (Set, base_prop.Set);
+						ok = false;
+					}
+				}
+			}
+
+			if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
+				if (!CheckAccessModifiers (this, base_prop)) {
+					Error_CannotChangeAccessModifiers (this, base_prop);
+					ok = false;
+				}
+			}
+
+			return ok;
+		}
+
+		protected override void DoMemberTypeDependentChecks ()
+		{
+			base.DoMemberTypeDependentChecks ();
+
+			IsTypePermitted ();
+
+			if (MemberType.IsStatic)
+				Error_StaticReturnType ();
+		}
+
+		protected override void DoMemberTypeIndependentChecks ()
+		{
+			base.DoMemberTypeIndependentChecks ();
+
+			//
+			// Accessors modifiers check
+			//
+			if (AccessorSecond != null) {
+				if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
+					Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
+						GetSignatureForError ());
+				}
+			} else if ((ModFlags & Modifiers.OVERRIDE) == 0 && 
+				(Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
+				(Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
+				Report.Error (276, Location, 
+					      "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
+					      GetSignatureForError ());
+			}
+		}
+
+		protected bool DefineAccessors ()
+		{
+			first.Define (Parent);
+			if (AccessorSecond != null)
+				AccessorSecond.Define (Parent);
+
+			return true;
+		}
+
+		protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
+		{
+			PropertyBuilder = Parent.TypeBuilder.DefineProperty (
+				GetFullName (MemberName), PropertyAttributes.None,
+#if !BOOTSTRAP_BASIC	// Requires trunk version mscorlib
+				IsStatic ? 0 : CallingConventions.HasThis,
+#endif
+				MemberType.GetMetaInfo (), null, null,
+				parameters.GetMetaInfo (), null, null);
+
+			PropertySpec spec;
+			if (kind == MemberKind.Indexer)
+				spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
+			else
+				spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
+
+			if (Get != null) {
+				spec.Get = Get.Spec;
+				Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
+			} else {
+				CheckMissingAccessor (kind, parameters, true);
+			}
+
+			if (Set != null) {
+				spec.Set = Set.Spec;
+				Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
+			} else {
+				CheckMissingAccessor (kind, parameters, false);
+			}
+
+			Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
+		}
+
+		public override void Emit ()
+		{
+			CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
+			CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
+
+			if (OptAttributes != null)
+				OptAttributes.Emit ();
+
+			if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
+			} else if (member_type.HasDynamicElement) {
+				Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
+			}
+
+			ConstraintChecker.Check (this, member_type, type_expr.Location);
+
+			first.Emit (Parent);
+			if (AccessorSecond != null)
+				AccessorSecond.Emit (Parent);
+
+			base.Emit ();
+		}
+
+		public override bool IsUsed {
+			get {
+				if (IsExplicitImpl)
+					return true;
+
+				return Get.IsUsed | Set.IsUsed;
+			}
+		}
+
+		public override void PrepareEmit ()
+		{
+			AccessorFirst.PrepareEmit ();
+			if (AccessorSecond != null)
+				AccessorSecond.PrepareEmit ();
+
+			if (get != null) {
+				var method = Get.Spec.GetMetaInfo () as MethodBuilder;
+				if (method != null)
+					PropertyBuilder.SetGetMethod (method);
+			}
+
+			if (set != null) {
+				var method = Set.Spec.GetMetaInfo () as MethodBuilder;
+				if (method != null)
+					PropertyBuilder.SetSetMethod (method);
+			}
+		}
+
+		protected override void SetMemberName (MemberName new_name)
+		{
+			base.SetMemberName (new_name);
+
+			if (Get != null)
+				Get.UpdateName (this);
+
+			if (Set != null)
+				Set.UpdateName (this);
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			if (get != null)
+				get.WriteDebugSymbol (file);
+
+			if (set != null)
+				set.WriteDebugSymbol (file);
+		}
+
+		//
+		//   Represents header string for documentation comment.
+		//
+		public override string DocCommentHeader {
+			get { return "P:"; }
+		}
+	}
+			
+	public class Property : PropertyBase
+	{
+		public sealed class BackingField : Field
+		{
+			readonly Property property;
+			const Modifiers DefaultModifiers = Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | Modifiers.DEBUGGER_HIDDEN;
+
+			public BackingField (Property p, bool readOnly)
+				: base (p.Parent, p.type_expr, DefaultModifiers | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
+				new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
+			{
+				this.property = p;
+				if (readOnly)
+					ModFlags |= Modifiers.READONLY;
+			}
+
+			public Property OriginalProperty {
+				get {
+					return property;
+				}
+			}
+
+			public override string GetSignatureForError ()
+			{
+				return property.GetSignatureForError ();
+			}
+		}
+
+		static readonly string[] attribute_target_auto = new string[] { "property", "field" };
+
+		Field backing_field;
+
+		public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
+				 MemberName name, Attributes attrs)
+			: base (parent, type, mod,
+				parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
+				parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
+				AllowedModifiersClass,
+				name, attrs)
+		{
+		}
+
+		public Expression Initializer { get; set; }
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Target == AttributeTargets.Field) {
+				backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		void CreateAutomaticProperty ()
+		{
+			// Create backing field
+			backing_field = new BackingField (this, Initializer != null && Set == null);
+			if (!backing_field.Define ())
+				return;
+
+			if (Initializer != null) {
+				backing_field.Initializer = Initializer;
+				Parent.RegisterFieldForInitialization (backing_field, new FieldInitializer (backing_field, Initializer, Location));
+				backing_field.ModFlags |= Modifiers.READONLY;
+			}
+
+			Parent.PartialContainer.Members.Add (backing_field);
+
+			FieldExpr fe = new FieldExpr (backing_field, Location);
+			if ((backing_field.ModFlags & Modifiers.STATIC) == 0)
+				fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
+
+			//
+			// Create get block but we careful with location to
+			// emit only single sequence point per accessor. This allow
+			// to set a breakpoint on it even with no user code
+			//
+			Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
+			Return r = new Return (fe, Get.Location);
+			Get.Block.AddStatement (r);
+			Get.ModFlags |= Modifiers.COMPILER_GENERATED;
+
+			// Create set block
+			if (Set != null) {
+				Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
+				Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
+				Set.Block.AddStatement (new StatementExpression (a, Set.Location));
+				Set.ModFlags |= Modifiers.COMPILER_GENERATED;
+			}
+		}
+		
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
+
+			bool auto = AccessorFirst.Block == null && (AccessorSecond == null || AccessorSecond.Block == null) &&
+				(ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0;
+
+			if (Initializer != null) {
+				if (!auto)
+					Report.Error (8050, Location, "`{0}': Only auto-implemented properties can have initializers",
+						GetSignatureForError ());
+
+				if (IsInterface)
+					Report.Error (8053, Location, "`{0}': Properties inside interfaces cannot have initializers",
+						GetSignatureForError ());
+
+				if (Compiler.Settings.Version < LanguageVersion.V_6)
+					Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented property initializer");
+			}
+
+			if (auto) {
+				if (Get == null) {
+					Report.Error (8052, Location, "Auto-implemented property `{0}' must have get accessor",
+						GetSignatureForError ());
+					return false;
+				}
+
+				if (Initializer == null && AccessorSecond == null) {
+					Report.Error (8051, Location, "Auto-implemented property `{0}' must have set accessor or initializer",
+						GetSignatureForError ());
+				}
+
+				if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
+					Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
+
+				CreateAutomaticProperty ();
+			}
+
+			if (!DefineAccessors ())
+				return false;
+
+			if (AccessorSecond == null) {
+				PropertyMethod pm;
+				if (AccessorFirst is GetMethod)
+					pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
+				else
+					pm = new GetMethod (this, 0, null, Location);
+
+				Parent.AddNameToContainer (pm, pm.MemberName.Basename);
+			}
+
+			if (!CheckBase ())
+				return false;
+
+			DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
+			return true;
+		}
+
+		public override void Emit ()
+		{
+			if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
+				Report.Error (842, Location,
+					"Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
+					GetSignatureForError ());
+			}
+
+			base.Emit ();
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
+					attribute_target_auto : base.ValidAttributeTargets;
+			}
+		}
+	}
+
+	/// <summary>
+	/// For case when event is declared like property (with add and remove accessors).
+	/// </summary>
+	public class EventProperty: Event {
+		public abstract class AEventPropertyAccessor : AEventAccessor
+		{
+			protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
+				: base (method, prefix, attrs, loc)
+			{
+			}
+
+			public override void Define (TypeContainer ds)
+			{
+				CheckAbstractAndExtern (block != null);
+				base.Define (ds);
+			}
+			
+			public override string GetSignatureForError ()
+			{
+				return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
+			}
+		}
+
+		public sealed class AddDelegateMethod: AEventPropertyAccessor
+		{
+			public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
+				: base (method, AddPrefix, attrs, loc)
+			{
+			}
+		}
+
+		public sealed class RemoveDelegateMethod: AEventPropertyAccessor
+		{
+			public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
+				: base (method, RemovePrefix, attrs, loc)
+			{
+			}
+		}
+
+		static readonly string[] attribute_targets = new string [] { "event" };
+
+		public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
+			: base (parent, type, mod_flags, name, attrs)
+		{
+		}
+
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+		
+		public override bool Define()
+		{
+			if (!base.Define ())
+				return false;
+
+			SetIsUsed ();
+			return true;
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return attribute_targets;
+			}
+		}
+	}
+
+	/// <summary>
+	/// Event is declared like field.
+	/// </summary>
+	public class EventField : Event
+	{
+		abstract class EventFieldAccessor : AEventAccessor
+		{
+			protected EventFieldAccessor (EventField method, string prefix)
+				: base (method, prefix, null, method.Location)
+			{
+			}
+
+			protected abstract MethodSpec GetOperation (Location loc);
+
+			public override void Emit (TypeDefinition parent)
+			{
+				if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
+					block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
+						IsCompilerGenerated = true
+					};
+					FabricateBodyStatement ();
+				}
+
+				base.Emit (parent);
+			}
+
+			void FabricateBodyStatement ()
+			{
+				//
+				// Delegate obj1 = backing_field
+				// do {
+				//   Delegate obj2 = obj1;
+				//   obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
+				// } while ((object)obj1 != (object)obj2)
+				//
+
+				var field_info = ((EventField) method).backing_field;
+				FieldExpr f_expr = new FieldExpr (field_info, Location);
+				if (!IsStatic)
+					f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
+
+				var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
+				var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
+
+				block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
+
+				var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
+					new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
+					new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
+
+				var body = new ExplicitBlock (block, Location, Location);
+				block.AddStatement (new Do (body, cond, Location, Location));
+
+				body.AddStatement (new StatementExpression (
+					new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
+
+				var args_oper = new Arguments (2);
+				args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
+				args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
+
+				var op_method = GetOperation (Location);
+
+				var args = new Arguments (3);
+				args.Add (new Argument (f_expr, Argument.AType.Ref));
+				args.Add (new Argument (new Cast (
+					new TypeExpression (field_info.MemberType, Location),
+					new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
+					Location)));
+				args.Add (new Argument (new LocalVariableReference (obj1, Location)));
+
+				var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
+				if (cas == null) {
+					if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
+						// Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
+						body.AddStatement (new Lock (
+							block.GetParameterReference (0, Location),
+							new StatementExpression (new SimpleAssign (
+								f_expr, args [1].Expr, Location), Location), Location));
+					} else {
+						Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
+					}
+				} else {
+					body.AddStatement (new StatementExpression (new SimpleAssign (
+						new LocalVariableReference (obj1, Location),
+						new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
+				}
+			}
+		}
+
+		sealed class AddDelegateMethod: EventFieldAccessor
+		{
+			public AddDelegateMethod (EventField method):
+				base (method, AddPrefix)
+			{
+			}
+
+			protected override MethodSpec GetOperation (Location loc)
+			{
+				return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
+			}
+		}
+
+		sealed class RemoveDelegateMethod: EventFieldAccessor
+		{
+			public RemoveDelegateMethod (EventField method):
+				base (method, RemovePrefix)
+			{
+			}
+
+			protected override MethodSpec GetOperation (Location loc)
+			{
+				return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
+			}
+		}
+
+
+		static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
+		static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
+
+		Expression initializer;
+		Field backing_field;
+		List<FieldDeclarator> declarators;
+
+		public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
+			: base (parent, type, mod_flags, name, attrs)
+		{
+			Add = new AddDelegateMethod (this);
+			Remove = new RemoveDelegateMethod (this);
+		}
+
+		#region Properties
+
+		public List<FieldDeclarator> Declarators {
+			get {
+				return this.declarators;
+			}
+		}
+
+		bool HasBackingField {
+			get {
+				return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
+			}
+		}
+
+		public Expression Initializer {
+			get {
+				return initializer;
+			}
+			set {
+				initializer = value;
+			}
+		}
+
+		public override string[] ValidAttributeTargets {
+			get {
+				return HasBackingField ? attribute_targets : attribute_targets_interface;
+			}
+		}
+
+		#endregion
+
+		
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public void AddDeclarator (FieldDeclarator declarator)
+		{
+			if (declarators == null)
+				declarators = new List<FieldDeclarator> (2);
+
+			declarators.Add (declarator);
+
+			Parent.AddNameToContainer (this, declarator.Name.Value);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Target == AttributeTargets.Field) {
+				backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			if (a.Target == AttributeTargets.Method) {
+				int errors = Report.Errors;
+				Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				if (errors == Report.Errors)
+					Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		public override bool Define()
+		{
+			var mod_flags_src = ModFlags;
+
+			if (!base.Define ())
+				return false;
+
+			if (declarators != null) {
+				if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
+					mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
+
+				var t = new TypeExpression (MemberType, TypeExpression.Location);
+				foreach (var d in declarators) {
+					var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
+
+					if (d.Initializer != null)
+						ef.initializer = d.Initializer;
+
+					ef.Define ();
+					Parent.PartialContainer.Members.Add (ef);
+				}
+			}
+
+			if (!HasBackingField) {
+				SetIsUsed ();
+				return true;
+			}
+
+			backing_field = new Field (Parent,
+				new TypeExpression (MemberType, Location),
+				Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
+				MemberName, null);
+
+			Parent.PartialContainer.Members.Add (backing_field);
+			backing_field.Initializer = Initializer;
+			backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
+
+			// Call define because we passed fields definition
+			backing_field.Define ();
+
+			// Set backing field for event fields
+			spec.BackingField = backing_field.Spec;
+
+			return true;
+		}
+	}
+
+	public abstract class Event : PropertyBasedMember
+	{
+		public abstract class AEventAccessor : AbstractPropertyEventMethod
+		{
+			protected readonly Event method;
+			readonly ParametersCompiled parameters;
+
+			static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
+
+			public const string AddPrefix = "add_";
+			public const string RemovePrefix = "remove_";
+
+			protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
+				: base (method, prefix, attrs, loc)
+			{
+				this.method = method;
+				this.ModFlags = method.ModFlags;
+				this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
+			}
+
+			public bool IsInterfaceImplementation {
+				get { return method_data.implementing != null; }
+			}
+
+			public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+			{
+				if (a.Type == pa.MethodImpl) {
+					method.is_external_implementation = a.IsInternalCall ();
+				}
+
+				base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+			}
+
+			protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+			{
+				if (a.Target == AttributeTargets.Parameter) {
+					parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
+					return;
+				}
+
+				base.ApplyToExtraTarget (a, ctor, cdata, pa);
+			}
+
+			public override AttributeTargets AttributeTargets {
+				get {
+					return AttributeTargets.Method;
+				}
+			}
+
+			public override bool IsClsComplianceRequired ()
+			{
+				return method.IsClsComplianceRequired ();
+			}
+
+			public virtual void Define (TypeContainer parent)
+			{
+				// Fill in already resolved event type to speed things up and
+				// avoid confusing duplicate errors
+				((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
+				parameters.Types = new TypeSpec[] { method.member_type };
+
+				method_data = new MethodData (method, method.ModFlags,
+					method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
+
+				if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
+					return;
+
+				if (Compiler.Settings.WriteMetadataOnly)
+					block = null;
+
+				Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
+				Spec.IsAccessor = true;
+			}
+
+			public override TypeSpec ReturnType {
+				get {
+					return Parent.Compiler.BuiltinTypes.Void;
+				}
+			}
+
+			public override ObsoleteAttribute GetAttributeObsolete ()
+			{
+				return method.GetAttributeObsolete ();
+			}
+
+			public MethodData MethodData {
+				get {
+					return method_data;
+				}
+			}
+
+			public override string[] ValidAttributeTargets {
+				get {
+					return attribute_targets;
+				}
+			}
+
+			public override ParametersCompiled ParameterInfo {
+				get {
+					return parameters;
+				}
+			}
+		}
+
+		AEventAccessor add, remove;
+		EventBuilder EventBuilder;
+		protected EventSpec spec;
+
+		protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
+			: base (parent, type, mod_flags,
+				parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
+				parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
+				AllowedModifiersClass,
+				name, attrs)
+		{
+		}
+
+		#region Properties
+
+		public override AttributeTargets AttributeTargets {
+			get {
+				return AttributeTargets.Event;
+			}
+		}
+
+		public AEventAccessor Add {
+			get {
+				return this.add;
+			}
+			set {
+				add = value;
+				Parent.AddNameToContainer (value, value.MemberName.Basename);
+			}
+		}
+
+		public override Variance ExpectedMemberTypeVariance {
+			get {
+				return Variance.Contravariant;
+			}
+		}
+
+		public AEventAccessor Remove {
+			get {
+				return this.remove;
+			}
+			set {
+				remove = value;
+				Parent.AddNameToContainer (value, value.MemberName.Basename);
+			}
+		}
+		#endregion
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if ((a.HasSecurityAttribute)) {
+				a.Error_InvalidSecurityParent ();
+				return;
+			}
+
+			EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
+		}
+
+		protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+		{
+			var ok = base.CheckOverrideAgainstBase (base_member);
+
+			if (!CheckAccessModifiers (this, base_member)) {
+				Error_CannotChangeAccessModifiers (this, base_member);
+				ok = false;
+			}
+
+			return ok;
+		}
+
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			if (!MemberType.IsDelegate) {
+				Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
+			}
+
+			if (!CheckBase ())
+				return false;
+
+			//
+			// Now define the accessors
+			//
+			add.Define (Parent);
+			remove.Define (Parent);
+
+			EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
+
+			spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
+
+			Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
+			Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
+			Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
+
+			return true;
+		}
+
+		public override void Emit ()
+		{
+			CheckReservedNameConflict (null, add.Spec);
+			CheckReservedNameConflict (null, remove.Spec);
+
+			if (OptAttributes != null) {
+				OptAttributes.Emit ();
+			}
+
+			ConstraintChecker.Check (this, member_type, type_expr.Location);
+
+			Add.Emit (Parent);
+			Remove.Emit (Parent);
+
+			base.Emit ();
+		}
+
+		public override void PrepareEmit ()
+		{
+			add.PrepareEmit ();
+			remove.PrepareEmit ();
+
+			EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
+			EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
+		}
+
+		public override void WriteDebugSymbol (MonoSymbolFile file)
+		{
+			add.WriteDebugSymbol (file);
+			remove.WriteDebugSymbol (file);
+		}
+
+		//
+		//   Represents header string for documentation comment.
+		//
+		public override string DocCommentHeader {
+			get { return "E:"; }
+		}
+	}
+
+	public class EventSpec : MemberSpec, IInterfaceMemberSpec
+	{
+		MethodSpec add, remove;
+		FieldSpec backing_field;
+
+		public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
+			: base (MemberKind.Event, declaringType, definition, modifiers)
+		{
+			this.AccessorAdd = add;
+			this.AccessorRemove = remove;
+			this.MemberType = eventType;
+		}
+
+		#region Properties
+
+		public MethodSpec AccessorAdd { 
+			get {
+				return add;
+			}
+			set {
+				add = value;
+			}
+		}
+
+		public MethodSpec AccessorRemove {
+			get {
+				return remove;
+			}
+			set {
+				remove = value;
+			}
+		}
+
+		public FieldSpec BackingField {
+			get {
+				return backing_field;
+			}
+			set {
+				backing_field = value;
+			}
+		}
+
+		public TypeSpec MemberType { get; private set; }
+
+		#endregion
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var es = (EventSpec) base.InflateMember (inflator);
+			es.MemberType = inflator.Inflate (MemberType);
+
+			if (backing_field != null)
+				es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
+
+			return es;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			return MemberType.ResolveMissingDependencies (this);
+		}
+	}
+ 
+	public class Indexer : PropertyBase, IParametersMember
+	{
+		public class GetIndexerMethod : GetMethod, IParametersMember
+		{
+			ParametersCompiled parameters;
+
+			public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
+				: base (property, modifiers, attrs, loc)
+			{
+				this.parameters = parameters;
+			}
+
+			public override void Define (TypeContainer parent)
+			{
+				// Disable reporting, parameters are resolved twice
+				Report.DisableReporting ();
+				try {
+					parameters.Resolve (this);
+				} finally {
+					Report.EnableReporting ();
+				}
+
+				base.Define (parent);
+			}
+
+			public override ParametersCompiled ParameterInfo {
+				get {
+					return parameters;
+				}
+			}
+
+			#region IParametersMember Members
+
+			AParametersCollection IParametersMember.Parameters {
+				get {
+					return parameters;
+				}
+			}
+
+			TypeSpec IInterfaceMemberSpec.MemberType {
+				get {
+					return ReturnType;
+				}
+			}
+
+			#endregion
+		}
+
+		public class SetIndexerMethod : SetMethod, IParametersMember
+		{
+			public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
+				: base (property, modifiers, parameters, attrs, loc)
+			{
+			}
+
+			#region IParametersMember Members
+
+			AParametersCollection IParametersMember.Parameters {
+				get {
+					return parameters;
+				}
+			}
+
+			TypeSpec IInterfaceMemberSpec.MemberType {
+				get {
+					return ReturnType;
+				}
+			}
+
+			#endregion
+		}
+
+		const Modifiers AllowedModifiers =
+			Modifiers.NEW |
+			Modifiers.PUBLIC |
+			Modifiers.PROTECTED |
+			Modifiers.INTERNAL |
+			Modifiers.PRIVATE |
+			Modifiers.VIRTUAL |
+			Modifiers.SEALED |
+			Modifiers.OVERRIDE |
+			Modifiers.UNSAFE |
+			Modifiers.EXTERN |
+			Modifiers.ABSTRACT;
+
+		const Modifiers AllowedInterfaceModifiers =
+			Modifiers.NEW;
+
+		readonly ParametersCompiled parameters;
+
+		public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
+			: base (parent, type, mod,
+				parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
+				name, attrs)
+		{
+			this.parameters = parameters;
+		}
+
+		#region Properties
+
+		AParametersCollection IParametersMember.Parameters {
+			get {
+				return parameters;
+			}
+		}
+
+		public ParametersCompiled ParameterInfo {
+			get {
+				return parameters;
+			}
+		}
+
+		#endregion
+
+		
+		public override void Accept (StructuralVisitor visitor)
+		{
+			visitor.Visit (this);
+		}
+
+		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+		{
+			if (a.Type == pa.IndexerName) {
+				// Attribute was copied to container
+				return;
+			}
+
+			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+		}
+
+		protected override bool CheckForDuplications ()
+		{
+			return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
+		}
+		
+		public override bool Define ()
+		{
+			if (!base.Define ())
+				return false;
+
+			if (!DefineParameters (parameters))
+				return false;
+
+			if (OptAttributes != null) {
+				Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
+				if (indexer_attr != null) {
+					var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
+					if (compiling != null)
+						compiling.Define ();
+
+					if (IsExplicitImpl) {
+						Report.Error (415, indexer_attr.Location,
+							"The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
+							indexer_attr.Type.GetSignatureForError ());
+					} else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+						Report.Error (609, indexer_attr.Location,
+							"Cannot set the `IndexerName' attribute on an indexer marked override");
+					} else {
+						string name = indexer_attr.GetIndexerAttributeValue ();
+
+						if (!string.IsNullOrEmpty (name)) {
+							SetMemberName (new MemberName (MemberName.Left, name, Location));
+						}
+					}
+				}
+			}
+
+			if (InterfaceType != null) {
+				string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
+				if (base_IndexerName != ShortName) {
+					SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
+				}
+			}
+
+			Parent.AddNameToContainer (this, MemberName.Basename);
+
+			flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
+			
+			if (!DefineAccessors ())
+				return false;
+
+			if (!CheckBase ())
+				return false;
+
+			DefineBuilders (MemberKind.Indexer, parameters);
+			return true;
+		}
+
+		public override bool EnableOverloadChecks (MemberCore overload)
+		{
+			if (overload is Indexer) {
+				caching_flags |= Flags.MethodOverloadsExist;
+				return true;
+			}
+
+			return base.EnableOverloadChecks (overload);
+		}
+
+		public override void Emit ()
+		{
+			parameters.CheckConstraints (this);
+
+			base.Emit ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
+			if (MemberName.ExplicitInterface != null) {
+				sb.Append (".");
+				sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
+			}
+
+			sb.Append (".this");
+			sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
+			return sb.ToString ();
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
+		}
+
+		protected override bool VerifyClsCompliance ()
+		{
+			if (!base.VerifyClsCompliance ())
+				return false;
+
+			parameters.VerifyClsCompliance (this);
+			return true;
+		}
+	}
+
+	public class IndexerSpec : PropertySpec, IParametersMember
+	{
+		AParametersCollection parameters;
+
+		public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
+			: base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
+		{
+			this.parameters = parameters;
+		}
+
+		#region Properties
+		public AParametersCollection Parameters {
+			get {
+				return parameters;
+			}
+		}
+		#endregion
+
+		public override string GetSignatureForDocumentation ()
+		{
+			return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
+		}
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var spec = (IndexerSpec) base.InflateMember (inflator);
+			spec.parameters = parameters.Inflate (inflator);
+			return spec;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			var missing = base.ResolveMissingDependencies (caller);
+
+			foreach (var pt in parameters.Types) {
+				var m = pt.GetMissingDependencies (caller);
+				if (m == null)
+					continue;
+
+				if (missing == null)
+					missing = new List<MissingTypeSpecReference> ();
+
+				missing.AddRange (m);
+			}
+
+			return missing;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/reflection.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/reflection.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/reflection.cs	(revision 11807)
@@ -0,0 +1,550 @@
+﻿//
+// reflection.cs: System.Reflection and System.Reflection.Emit specific implementations
+//
+// Author: Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2009-2010 Novell, Inc. 
+//
+//
+
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.IO;
+using System.Runtime.CompilerServices;
+using System.Reflection.Emit;
+using System.Security;
+
+namespace Mono.CSharp
+{
+#if STATIC
+	public class ReflectionImporter
+	{
+		public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
+		{
+			throw new NotSupportedException ();
+		}
+
+		public TypeSpec ImportType (Type type)
+		{
+			throw new NotSupportedException ();
+		}
+	}
+#else
+	public sealed class ReflectionImporter : MetadataImporter
+	{
+		public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
+			: base (module)
+		{
+			Initialize (builtin);
+		}
+
+		public override void AddCompiledType (TypeBuilder builder, TypeSpec spec)
+		{
+		}
+
+		protected override MemberKind DetermineKindFromBaseType (Type baseType)
+		{
+			if (baseType == typeof (ValueType))
+				return MemberKind.Struct;
+
+			if (baseType == typeof (System.Enum))
+				return MemberKind.Enum;
+
+			if (baseType == typeof (MulticastDelegate))
+				return MemberKind.Delegate;
+
+			return MemberKind.Class;
+		}
+
+		protected override bool HasVolatileModifier (Type[] modifiers)
+		{
+			foreach (var t in modifiers) {
+				if (t == typeof (IsVolatile))
+					return true;
+			}
+
+			return false;
+		}
+
+		public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
+		{
+			// It can be used more than once when importing same assembly
+			// into 2 or more global aliases
+		GetAssemblyDefinition (assembly);
+
+			//
+			// This part tries to simulate loading of top-level
+			// types only, any missing dependencies are ignores here.
+			// Full error report is reported later when the type is
+			// actually used
+			//
+			Type[] all_types;
+			try {
+				all_types = assembly.GetTypes ();
+			} catch (ReflectionTypeLoadException e) {
+				all_types = e.Types;
+			}
+
+			ImportTypes (all_types, targetNamespace, true);
+		}
+
+		public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
+		{
+			var module_definition = new ImportedModuleDefinition (module);
+			module_definition.ReadAttributes ();
+
+			Type[] all_types;
+			try {
+				all_types = module.GetTypes ();
+			} catch (ReflectionTypeLoadException e) {
+				all_types = e.Types;
+			}
+
+			ImportTypes (all_types, targetNamespace, false);
+
+			return module_definition;
+		}
+
+		void Initialize (BuiltinTypes builtin)
+		{
+			//
+			// Setup mapping for build-in types to avoid duplication of their definition
+			//
+			compiled_types.Add (typeof (object), builtin.Object);
+			compiled_types.Add (typeof (System.ValueType), builtin.ValueType);
+			compiled_types.Add (typeof (System.Attribute), builtin.Attribute);
+
+			compiled_types.Add (typeof (int), builtin.Int);
+			compiled_types.Add (typeof (long), builtin.Long);
+			compiled_types.Add (typeof (uint), builtin.UInt);
+			compiled_types.Add (typeof (ulong), builtin.ULong);
+			compiled_types.Add (typeof (byte), builtin.Byte);
+			compiled_types.Add (typeof (sbyte), builtin.SByte);
+			compiled_types.Add (typeof (short), builtin.Short);
+			compiled_types.Add (typeof (ushort), builtin.UShort);
+
+			compiled_types.Add (typeof (System.Collections.IEnumerator), builtin.IEnumerator);
+			compiled_types.Add (typeof (System.Collections.IEnumerable), builtin.IEnumerable);
+			compiled_types.Add (typeof (System.IDisposable), builtin.IDisposable);
+
+			compiled_types.Add (typeof (char), builtin.Char);
+			compiled_types.Add (typeof (string), builtin.String);
+			compiled_types.Add (typeof (float), builtin.Float);
+			compiled_types.Add (typeof (double), builtin.Double);
+			compiled_types.Add (typeof (decimal), builtin.Decimal);
+			compiled_types.Add (typeof (bool), builtin.Bool);
+			compiled_types.Add (typeof (System.IntPtr), builtin.IntPtr);
+			compiled_types.Add (typeof (System.UIntPtr), builtin.UIntPtr);
+
+			compiled_types.Add (typeof (System.MulticastDelegate), builtin.MulticastDelegate);
+			compiled_types.Add (typeof (System.Delegate), builtin.Delegate);
+			compiled_types.Add (typeof (System.Enum), builtin.Enum);
+			compiled_types.Add (typeof (System.Array), builtin.Array);
+			compiled_types.Add (typeof (void), builtin.Void);
+			compiled_types.Add (typeof (System.Type), builtin.Type);
+			compiled_types.Add (typeof (System.Exception), builtin.Exception);
+			compiled_types.Add (typeof (System.RuntimeFieldHandle), builtin.RuntimeFieldHandle);
+			compiled_types.Add (typeof (System.RuntimeTypeHandle), builtin.RuntimeTypeHandle);
+		}
+	}
+
+	[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Explicit)]
+	struct SingleConverter
+	{
+		[System.Runtime.InteropServices.FieldOffset (0)]
+		int i;
+
+#pragma warning disable 414
+		[System.Runtime.InteropServices.FieldOffset (0)]
+		float f;
+#pragma warning restore 414
+
+		public static int SingleToInt32Bits (float v)
+		{
+			SingleConverter c = new SingleConverter ();
+			c.f = v;
+			return c.i;
+		}
+	}
+
+#endif
+
+	public class AssemblyDefinitionDynamic : AssemblyDefinition
+	{
+		//
+		// In-memory only assembly container
+		//
+		public AssemblyDefinitionDynamic (ModuleContainer module, string name)
+			: base (module, name)
+		{
+		}
+
+		//
+		// Assembly container with file output
+		//
+		public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
+			: base (module, name, fileName)
+		{
+		}
+
+		public Module IncludeModule (string moduleFile)
+		{
+			return builder_extra.AddModule (moduleFile);
+		}
+
+#if !STATIC
+		public override ModuleBuilder CreateModuleBuilder ()
+		{
+			if (file_name == null)
+				return Builder.DefineDynamicModule (Name, false);
+
+			return base.CreateModuleBuilder ();
+		}
+#endif
+		//
+		// Initializes the code generator
+		//
+		public bool Create (AppDomain domain, AssemblyBuilderAccess access)
+		{
+#if STATIC || FULL_AOT_RUNTIME
+			throw new NotSupportedException ();
+#else
+			ResolveAssemblySecurityAttributes ();
+			var an = CreateAssemblyName ();
+
+			Builder = file_name == null ?
+				domain.DefineDynamicAssembly (an, access) :
+				domain.DefineDynamicAssembly (an, access, Dirname (file_name));
+
+			module.Create (this, CreateModuleBuilder ());
+			builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
+			return true;
+#endif
+		}
+
+		static string Dirname (string name)
+		{
+			int pos = name.LastIndexOf ('/');
+
+			if (pos != -1)
+				return name.Substring (0, pos);
+
+			pos = name.LastIndexOf ('\\');
+			if (pos != -1)
+				return name.Substring (0, pos);
+
+			return ".";
+		}
+
+#if !STATIC
+		protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
+		{
+			try {
+				var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
+				var set_module_only = module_only.GetSetMethod (true);
+
+				set_module_only.Invoke (Builder, new object[] { true });
+			} catch {
+				base.SaveModule (pekind, machine);
+			}
+
+			Builder.Save (file_name, pekind, machine);
+		}
+#endif
+	}
+
+	//
+	// Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
+	// compiler
+	//
+	class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
+	{
+		static MethodInfo adder_method;
+		static MethodInfo add_permission;
+		static MethodInfo add_type_forwarder;
+		static MethodInfo win32_icon_define;
+		static FieldInfo assembly_version;
+		static FieldInfo assembly_algorithm;
+		static FieldInfo assembly_culture;
+		static FieldInfo assembly_flags;
+
+		AssemblyBuilder builder;
+
+		public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
+			: base (ctx)
+		{
+			this.builder = ab;
+		}
+
+		public override Module AddModule (string module)
+		{
+			try {
+				if (adder_method == null)
+					adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
+
+				return (Module) adder_method.Invoke (builder, new object[] { module });
+			} catch {
+				return base.AddModule (module);
+			}
+		}
+
+		public override void AddPermissionRequests (PermissionSet[] permissions)
+		{
+			try {
+				if (add_permission == null)
+					add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
+
+				add_permission.Invoke (builder, permissions);
+			} catch {
+				base.AddPermissionRequests (permissions);
+			}
+		}
+
+		public override void AddTypeForwarder (TypeSpec type, Location loc)
+		{
+			try {
+				if (add_type_forwarder == null) {
+					add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
+				}
+
+				add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
+			} catch {
+				base.AddTypeForwarder (type, loc);
+			}
+		}
+
+		public override void DefineWin32IconResource (string fileName)
+		{
+			try {
+				if (win32_icon_define == null)
+					win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
+
+				win32_icon_define.Invoke (builder, new object[] { fileName });
+			} catch {
+				base.DefineWin32IconResource (fileName);
+			}
+		}
+
+		public override void SetAlgorithmId (uint value, Location loc)
+		{
+			try {
+				if (assembly_algorithm == null)
+					assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+
+				assembly_algorithm.SetValue (builder, value);
+			} catch {
+				base.SetAlgorithmId (value, loc);
+			}
+		}
+
+		public override void SetCulture (string culture, Location loc)
+		{
+			try {
+				if (assembly_culture == null)
+					assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+
+				assembly_culture.SetValue (builder, culture);
+			} catch {
+				base.SetCulture (culture, loc);
+			}
+		}
+
+		public override void SetFlags (uint flags, Location loc)
+		{
+			try {
+				if (assembly_flags == null)
+					assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+
+				assembly_flags.SetValue (builder, flags);
+			} catch {
+				base.SetFlags (flags, loc);
+			}
+		}
+
+		public override void SetVersion (Version version, Location loc)
+		{
+			try {
+				if (assembly_version == null)
+					assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
+
+				assembly_version.SetValue (builder, version.ToString (4));
+			} catch {
+				base.SetVersion (version, loc);
+			}
+		}
+	}
+
+	//
+	// Reflection based references loader
+	//
+	class DynamicLoader : AssemblyReferencesLoader<Assembly>
+	{
+		readonly ReflectionImporter importer;
+
+		public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
+			: base (compiler)
+		{
+			paths.Add (GetSystemDir ());
+
+			this.importer = importer;
+		}
+
+		public ReflectionImporter Importer {
+			get {
+				return importer;
+			}
+		}
+
+		protected override string[] GetDefaultReferences ()
+		{
+			//
+			// For now the "default config" is harcoded into the compiler
+			// we can move this outside later
+			//
+			var default_references = new List<string> (8);
+
+			default_references.Add ("System");
+			default_references.Add ("System.Xml");
+#if NET_2_1
+			default_references.Add ("System.Net");
+			default_references.Add ("System.Windows");
+			default_references.Add ("System.Windows.Browser");
+#endif
+
+			if (compiler.Settings.Version > LanguageVersion.ISO_2)
+				default_references.Add ("System.Core");
+			if (compiler.Settings.Version > LanguageVersion.V_3)
+				default_references.Add ("Microsoft.CSharp");
+
+			return default_references.ToArray ();
+		}
+
+		//
+		// Returns the directory where the system assemblies are installed
+		//
+		static string GetSystemDir ()
+		{
+			return Path.GetDirectoryName (typeof (object).Assembly.Location);
+		}
+
+		public override bool HasObjectType (Assembly assembly)
+		{
+			return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
+		}
+
+		public override Assembly LoadAssemblyFile (string assembly, bool isImplicitReference)
+		{
+			Assembly a = null;
+
+			try {
+				try {
+					char[] path_chars = { '/', '\\' };
+
+					if (assembly.IndexOfAny (path_chars) != -1) {
+						a = Assembly.LoadFrom (assembly);
+					} else {
+						string ass = assembly;
+						if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
+							ass = assembly.Substring (0, assembly.Length - 4);
+						a = Assembly.Load (ass);
+					}
+				} catch (FileNotFoundException) {
+					bool err = !isImplicitReference;
+					foreach (string dir in paths) {
+						string full_path = Path.Combine (dir, assembly);
+						if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
+							full_path += ".dll";
+
+						try {
+							a = Assembly.LoadFrom (full_path);
+							err = false;
+							break;
+						} catch (FileNotFoundException) {
+						}
+					}
+
+					if (err) {
+						Error_FileNotFound (assembly);
+						return a;
+					}
+				}
+			} catch (BadImageFormatException) {
+				Error_FileCorrupted (assembly);
+			}
+
+			return a;
+		}
+
+		Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
+		{
+			string total_log = "";
+
+			try {
+				try {
+					return assembly.IncludeModule (module);
+				} catch (FileNotFoundException) {
+					bool err = true;
+					foreach (string dir in paths) {
+						string full_path = Path.Combine (dir, module);
+						if (!module.EndsWith (".netmodule"))
+							full_path += ".netmodule";
+
+						try {
+							return assembly.IncludeModule (full_path);
+						} catch (FileNotFoundException ff) {
+							total_log += ff.FusionLog;
+						}
+					}
+					if (err) {
+						Error_FileNotFound (module);
+						return null;
+					}
+				}
+			} catch (BadImageFormatException) {
+				Error_FileCorrupted (module);
+			}
+
+			return null;
+		}
+
+		public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
+		{
+			foreach (var moduleName in compiler.Settings.Modules) {
+				var m = LoadModuleFile (assembly, moduleName);
+				if (m == null)
+					continue;
+
+				var md = importer.ImportModule (m, targetNamespace);
+				assembly.AddModule (md);
+			}
+		}
+
+		public override void LoadReferences (ModuleContainer module)
+		{
+			Assembly corlib;
+			List<Tuple<RootNamespace, Assembly>> loaded;
+			base.LoadReferencesCore (module, out corlib, out loaded);
+
+			if (corlib == null)
+				return;
+
+			importer.ImportAssembly (corlib, module.GlobalRootNamespace);
+			foreach (var entry in loaded) {
+				importer.ImportAssembly (entry.Item2, entry.Item1);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/report.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/report.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/report.cs	(revision 11807)
@@ -0,0 +1,1144 @@
+//
+// report.cs: report errors and warnings.
+//
+// Author: Miguel de Icaza (miguel@ximian.com)
+//         Marek Safar (marek.safar@gmail.com)         
+//
+// Copyright 2001 Ximian, Inc. (http://www.ximian.com)
+// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
+//
+
+using System;
+using System.IO;
+using System.Text;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace Mono.CSharp {
+
+	//
+	// Errors and warnings manager
+	//
+	public class Report
+	{
+		public const int RuntimeErrorId = 10000;
+
+		Dictionary<int, WarningRegions> warning_regions_table;
+
+		ReportPrinter printer;
+
+		int reporting_disabled;
+
+		readonly CompilerSettings settings;
+		
+		/// <summary>
+		/// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
+		/// </summary>
+		List<string> extra_information = new List<string> ();
+
+		// 
+		// IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
+		//
+		public static readonly int[] AllWarnings = new int[] {
+			28, 67, 78,
+			105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
+			219, 251, 252, 253, 278, 282,
+			402, 414, 419, 420, 429, 436, 437, 440, 458, 464, 465, 467, 469, 472, 473,
+			612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
+			728,
+			809, 824,
+			1030, 1058, 1060, 1066,
+			1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
+			1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1697, 1699,
+			1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
+			1901, 1956, 1981, 1998,
+			2002, 2023, 2029,
+			3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
+			3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
+			3021, 3022, 3023, 3024, 3026, 3027,
+			4014, 4024, 4025, 4026,
+			7035, 7080, 7081, 7082, 7095,
+			8009,
+		};
+
+		static HashSet<int> AllWarningsHashSet;
+
+		public Report (CompilerContext context, ReportPrinter printer)
+		{
+			if (context == null)
+				throw new ArgumentNullException ("settings");
+			if (printer == null)
+				throw new ArgumentNullException ("printer");
+
+			this.settings = context.Settings;
+			this.printer = printer;
+		}
+
+		public void DisableReporting ()
+		{
+			++reporting_disabled;
+		}
+
+		public void EnableReporting ()
+		{
+			--reporting_disabled;
+		}
+
+		public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
+		{
+			string version;
+			switch (compiler.Settings.Version) {
+			case LanguageVersion.ISO_1:
+				version = "1.0";
+				break;
+			case LanguageVersion.ISO_2:
+				version = "2.0";
+				break;
+			case LanguageVersion.V_3:
+				version = "3.0";
+				break;
+			case LanguageVersion.V_4:
+				version = "4.0";
+				break;
+			case LanguageVersion.V_5:
+				version = "5.0";
+				break;
+			case LanguageVersion.V_6:
+				version = "6.0";
+				break;
+			default:
+				throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
+			}
+
+			Error (1644, loc,
+				"Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
+				      feature, version);
+		}
+
+		public void FeatureIsNotSupported (Location loc, string feature)
+		{
+			Error (1644, loc,
+				"Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
+				feature);
+		}
+		        
+		public void RuntimeMissingSupport (Location loc, string feature) 
+		{
+			Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
+		}
+
+		/// <summary>
+		/// In most error cases is very useful to have information about symbol that caused the error.
+		/// Call this method before you call Report.Error when it makes sense.
+		/// </summary>
+		public void SymbolRelatedToPreviousError (Location loc, string symbol)
+		{
+			SymbolRelatedToPreviousError (loc.ToString ());
+		}
+
+		public void SymbolRelatedToPreviousError (MemberSpec ms)
+		{
+			if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
+				return;
+
+			var mc = ms.MemberDefinition as MemberCore;
+			while (ms is ElementTypeSpec) {
+				ms = ((ElementTypeSpec) ms).Element;
+				mc = ms.MemberDefinition as MemberCore;
+			}
+
+			if (mc != null) {
+				SymbolRelatedToPreviousError (mc);
+			} else {
+				if (ms.DeclaringType != null)
+					ms = ms.DeclaringType;
+
+				var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
+				if (imported_type != null) {
+					var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
+					SymbolRelatedToPreviousError (iad.Location);
+				}
+			}
+		}
+
+		public void SymbolRelatedToPreviousError (MemberCore mc)
+		{
+			SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
+		}
+
+		public void SymbolRelatedToPreviousError (string loc)
+		{
+			string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
+			if (extra_information.Contains (msg))
+				return;
+
+			extra_information.Add (msg);
+		}
+
+		public bool CheckWarningCode (int code, Location loc)
+		{
+			if (AllWarningsHashSet == null)
+				AllWarningsHashSet = new HashSet<int> (AllWarnings);
+
+			if (AllWarningsHashSet.Contains (code))
+				return true;
+
+			Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
+			return false;
+		}
+
+		public void ExtraInformation (Location loc, string msg)
+		{
+			extra_information.Add (String.Format ("{0} {1}", loc, msg));
+		}
+
+		public WarningRegions RegisterWarningRegion (Location location)
+		{
+			WarningRegions regions;
+			if (warning_regions_table == null) {
+				regions = null;
+				warning_regions_table = new Dictionary<int, WarningRegions> ();
+			} else {
+				warning_regions_table.TryGetValue (location.File, out regions);
+			}
+
+			if (regions == null) {
+				regions = new WarningRegions ();
+				warning_regions_table.Add (location.File, regions);
+			}
+
+			return regions;
+		}
+
+		public void Warning (int code, int level, Location loc, string message)
+		{
+			if (reporting_disabled > 0)
+				return;
+
+			if (!settings.IsWarningEnabled (code, level))
+				return;
+
+			if (warning_regions_table != null && !loc.IsNull) {
+				WarningRegions regions;
+				if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
+					return;
+			}
+
+			AbstractMessage msg;
+			if (settings.IsWarningAsError (code)) {
+				message = "Warning as Error: " + message;
+				msg = new ErrorMessage (code, loc, message, extra_information);
+			} else {
+				msg = new WarningMessage (code, loc, message, extra_information);
+			}
+
+			extra_information.Clear ();
+			printer.Print (msg, settings.ShowFullPaths);
+		}
+
+		public void Warning (int code, int level, Location loc, string format, string arg)
+		{
+			Warning (code, level, loc, String.Format (format, arg));
+		}
+
+		public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
+		{
+			Warning (code, level, loc, String.Format (format, arg1, arg2));
+		}
+
+		public void Warning (int code, int level, Location loc, string format, params object[] args)
+		{
+			Warning (code, level, loc, String.Format (format, args));
+		}
+
+		public void Warning (int code, int level, string message)
+		{
+			Warning (code, level, Location.Null, message);
+		}
+
+		public void Warning (int code, int level, string format, string arg)
+		{
+			Warning (code, level, Location.Null, format, arg);
+		}
+
+		public void Warning (int code, int level, string format, string arg1, string arg2)
+		{
+			Warning (code, level, Location.Null, format, arg1, arg2);
+		}
+
+		public void Warning (int code, int level, string format, params string[] args)
+		{
+			Warning (code, level, Location.Null, String.Format (format, args));
+		}
+
+		//
+		// Warnings encountered so far
+		//
+		public int Warnings {
+			get { return printer.WarningsCount; }
+		}
+
+		public void Error (int code, Location loc, string error)
+		{
+			if (reporting_disabled > 0)
+				return;
+
+			ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
+			extra_information.Clear ();
+
+			printer.Print (msg, settings.ShowFullPaths);
+
+			if (settings.Stacktrace)
+				Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
+
+			if (printer.ErrorsCount == settings.FatalCounter)
+				throw new FatalException (msg.Text);
+		}
+
+		public void Error (int code, Location loc, string format, string arg)
+		{
+			Error (code, loc, String.Format (format, arg));
+		}
+
+		public void Error (int code, Location loc, string format, string arg1, string arg2)
+		{
+			Error (code, loc, String.Format (format, arg1, arg2));
+		}
+
+		public void Error (int code, Location loc, string format, params string[] args)
+		{
+			Error (code, loc, String.Format (format, args));
+		}
+
+		public void Error (int code, string error)
+		{
+			Error (code, Location.Null, error);
+		}
+
+		public void Error (int code, string format, string arg)
+		{
+			Error (code, Location.Null, format, arg);
+		}
+
+		public void Error (int code, string format, string arg1, string arg2)
+		{
+			Error (code, Location.Null, format, arg1, arg2);
+		}
+
+		public void Error (int code, string format, params string[] args)
+		{
+			Error (code, Location.Null, String.Format (format, args));
+		}
+
+		//
+		// Errors encountered so far
+		//
+		public int Errors {
+			get { return printer.ErrorsCount; }
+		}
+
+		public bool IsDisabled {
+			get {
+				return reporting_disabled > 0;
+			}
+		}
+
+		public ReportPrinter Printer {
+			get { return printer; }
+		}
+
+		public ReportPrinter SetPrinter (ReportPrinter printer)
+		{
+			ReportPrinter old = this.printer;
+			this.printer = printer;
+			return old;
+		}
+
+		[Conditional ("MCS_DEBUG")]
+		static public void Debug (string message, params object[] args)
+		{
+			Debug (4, message, args);
+		}
+			
+		[Conditional ("MCS_DEBUG")]
+		static public void Debug (int category, string message, params object[] args)
+		{
+//			if ((category & DebugFlags) == 0)
+//				return;
+
+			StringBuilder sb = new StringBuilder (message);
+
+			if ((args != null) && (args.Length > 0)) {
+				sb.Append (": ");
+
+				bool first = true;
+				foreach (object arg in args) {
+					if (first)
+						first = false;
+					else
+						sb.Append (", ");
+					if (arg == null)
+						sb.Append ("null");
+//					else if (arg is ICollection)
+//						sb.Append (PrintCollection ((ICollection) arg));
+					else
+						sb.Append (arg);
+				}
+			}
+
+			Console.WriteLine (sb.ToString ());
+		}
+/*
+		static public string PrintCollection (ICollection collection)
+		{
+			StringBuilder sb = new StringBuilder ();
+
+			sb.Append (collection.GetType ());
+			sb.Append ("(");
+
+			bool first = true;
+			foreach (object o in collection) {
+				if (first)
+					first = false;
+				else
+					sb.Append (", ");
+				sb.Append (o);
+			}
+
+			sb.Append (")");
+			return sb.ToString ();
+		}
+*/
+		static string FriendlyStackTrace (StackTrace t)
+		{
+			StringBuilder sb = new StringBuilder ();
+
+			bool foundUserCode = false;
+
+			for (int i = 0; i < t.FrameCount; i++) {
+				StackFrame f = t.GetFrame (i);
+				var mb = f.GetMethod ();
+
+				if (!foundUserCode && mb.ReflectedType == typeof (Report))
+					continue;
+
+				foundUserCode = true;
+
+				sb.Append ("\tin ");
+
+				if (f.GetFileLineNumber () > 0)
+					sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
+
+				sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
+
+				bool first = true;
+				foreach (var pi in mb.GetParameters ()) {
+					if (!first)
+						sb.Append (", ");
+					first = false;
+
+					sb.Append (pi.ParameterType.FullName);
+				}
+				sb.Append (")\n");
+			}
+
+			return sb.ToString ();
+		}
+	}
+
+	public abstract class AbstractMessage
+	{
+		readonly string[] extra_info;
+		protected readonly int code;
+		protected readonly Location location;
+		readonly string message;
+
+		protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
+		{
+			this.code = code;
+			if (code < 0)
+				this.code = 8000 - code;
+
+			this.location = loc;
+			this.message = msg;
+			if (extraInfo.Count != 0) {
+				this.extra_info = extraInfo.ToArray ();
+			}
+		}
+
+		protected AbstractMessage (AbstractMessage aMsg)
+		{
+			this.code = aMsg.code;
+			this.location = aMsg.location;
+			this.message = aMsg.message;
+			this.extra_info = aMsg.extra_info;
+		}
+
+		public int Code {
+			get { return code; }
+		}
+
+		public override bool Equals (object obj)
+		{
+			AbstractMessage msg = obj as AbstractMessage;
+			if (msg == null)
+				return false;
+
+			return code == msg.code && location.Equals (msg.location) && message == msg.message;
+		}
+
+		public override int GetHashCode ()
+		{
+			return code.GetHashCode ();
+		}
+
+		public abstract bool IsWarning { get; }
+
+		public Location Location {
+			get { return location; }
+		}
+
+		public abstract string MessageType { get; }
+
+		public string[] RelatedSymbols {
+			get { return extra_info; }
+		}
+
+		public string Text {
+			get { return message; }
+		}
+	}
+
+	sealed class WarningMessage : AbstractMessage
+	{
+		public WarningMessage (int code, Location loc, string message, List<string> extra_info)
+			: base (code, loc, message, extra_info)
+		{
+		}
+
+		public override bool IsWarning {
+			get { return true; }
+		}
+
+		public override string MessageType {
+			get {
+				return "warning";
+			}
+		}
+	}
+
+	sealed class ErrorMessage : AbstractMessage
+	{
+		public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
+			: base (code, loc, message, extraInfo)
+		{
+		}
+
+		public ErrorMessage (AbstractMessage aMsg)
+			: base (aMsg)
+		{
+		}
+
+		public override bool IsWarning {
+			get { return false; }
+		}
+
+		public override string MessageType {
+			get {
+				return "error";
+			}
+		}
+	}
+
+	//
+	// Generic base for any message writer
+	//
+	public abstract class ReportPrinter
+	{
+		protected HashSet<ITypeDefinition> reported_missing_definitions;
+
+		#region Properties
+
+		public int ErrorsCount { get; protected set; }
+		
+		public int WarningsCount { get; private set; }
+	
+		//
+		// When (symbols related to previous ...) can be used
+		//
+		public virtual bool HasRelatedSymbolSupport {
+			get { return true; }
+		}
+
+		#endregion
+
+
+		protected virtual string FormatText (string txt)
+		{
+			return txt;
+		}
+
+		public virtual void Print (AbstractMessage msg, bool showFullPath)
+		{
+			if (msg.IsWarning) {
+				++WarningsCount;
+			} else {
+				++ErrorsCount;
+			}
+		}
+
+		protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
+		{
+			StringBuilder txt = new StringBuilder ();
+			if (!msg.Location.IsNull) {
+				if (showFullPath)
+					txt.Append (msg.Location.ToStringFullName ());
+				else
+					txt.Append (msg.Location.ToString ());
+
+				txt.Append (" ");
+			}
+
+			txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
+
+			if (!msg.IsWarning)
+				output.WriteLine (FormatText (txt.ToString ()));
+			else
+				output.WriteLine (txt.ToString ());
+
+			if (msg.RelatedSymbols != null) {
+				foreach (string s in msg.RelatedSymbols)
+					output.WriteLine (s + msg.MessageType + ")");
+			}
+		}
+
+		//
+		// Tracks reported missing types. It needs to be session specific 
+		// because we can run in probing mode
+		//
+		public bool MissingTypeReported (ITypeDefinition typeDefinition)
+		{
+			if (reported_missing_definitions == null)
+				reported_missing_definitions = new HashSet<ITypeDefinition> ();
+
+			if (reported_missing_definitions.Contains (typeDefinition))
+				return true;
+
+			reported_missing_definitions.Add (typeDefinition);
+			return false;
+		}
+
+		public void Reset ()
+		{
+			// HACK: Temporary hack for broken repl flow
+			ErrorsCount = WarningsCount = 0;
+		}
+	}
+
+	sealed class NullReportPrinter : ReportPrinter
+	{
+	}
+
+	//
+	// Default message recorder, it uses two types of message groups.
+	// Common messages: messages reported in all sessions.
+	// Merged messages: union of all messages in all sessions. 
+	//
+	// Used by the Lambda expressions to compile the code with various
+	// parameter values, or by attribute resolver
+	//
+	class SessionReportPrinter : ReportPrinter
+	{
+		List<AbstractMessage> session_messages;
+		//
+		// A collection of exactly same messages reported in all sessions
+		//
+		List<AbstractMessage> common_messages;
+
+		//
+		// A collection of unique messages reported in all sessions
+		//
+		List<AbstractMessage> merged_messages;
+
+		bool showFullPaths;
+
+		public void ClearSession ()
+		{
+			session_messages = null;
+		}
+
+		public override void Print (AbstractMessage msg, bool showFullPath)
+		{
+			//
+			// This line is useful when debugging recorded messages
+			//
+			// Console.WriteLine ("RECORDING: {0}", msg.Text);
+
+			if (session_messages == null)
+				session_messages = new List<AbstractMessage> ();
+
+			session_messages.Add (msg);
+
+			this.showFullPaths = showFullPath;
+			base.Print (msg, showFullPath);
+		}
+
+		public void EndSession ()
+		{
+			if (session_messages == null)
+				return;
+
+			//
+			// Handles the first session
+			//
+			if (common_messages == null) {
+				common_messages = new List<AbstractMessage> (session_messages);
+				merged_messages = session_messages;
+				session_messages = null;
+				return;
+			}
+
+			//
+			// Store common messages if any
+			//
+			for (int i = 0; i < common_messages.Count; ++i) {
+				AbstractMessage cmsg = common_messages[i];
+				bool common_msg_found = false;
+				foreach (AbstractMessage msg in session_messages) {
+					if (cmsg.Equals (msg)) {
+						common_msg_found = true;
+						break;
+					}
+				}
+
+				if (!common_msg_found)
+					common_messages.RemoveAt (i);
+			}
+
+			//
+			// Merge session and previous messages
+			//
+			for (int i = 0; i < session_messages.Count; ++i) {
+				AbstractMessage msg = session_messages[i];
+				bool msg_found = false;
+				for (int ii = 0; ii < merged_messages.Count; ++ii) {
+					if (msg.Equals (merged_messages[ii])) {
+						msg_found = true;
+						break;
+					}
+				}
+
+				if (!msg_found)
+					merged_messages.Add (msg);
+			}
+		}
+
+		public bool IsEmpty {
+			get {
+				return merged_messages == null && common_messages == null;
+			}
+		}
+
+		//
+		// Prints collected messages, common messages have a priority
+		//
+		public bool Merge (ReportPrinter dest)
+		{
+			var messages_to_print = merged_messages;
+			if (common_messages != null && common_messages.Count > 0) {
+				messages_to_print = common_messages;
+			}
+
+			if (messages_to_print == null)
+				return false;
+
+			bool error_msg = false;
+			foreach (AbstractMessage msg in messages_to_print) {
+				dest.Print (msg, showFullPaths);
+				error_msg |= !msg.IsWarning;
+			}
+
+			if (reported_missing_definitions != null) {
+				foreach (var missing in reported_missing_definitions)
+					dest.MissingTypeReported (missing);
+			}
+
+			return error_msg;
+		}
+	}
+
+	public class StreamReportPrinter : ReportPrinter
+	{
+		readonly TextWriter writer;
+
+		public StreamReportPrinter (TextWriter writer)
+		{
+			this.writer = writer;
+		}
+
+		public override void Print (AbstractMessage msg, bool showFullPath)
+		{
+			Print (msg, writer, showFullPath);
+			base.Print (msg, showFullPath);
+		}
+	}
+
+	public class ConsoleReportPrinter : StreamReportPrinter
+	{
+		static readonly string prefix, postfix;
+
+		static ConsoleReportPrinter ()
+		{
+			string term = Environment.GetEnvironmentVariable ("TERM");
+			bool xterm_colors = false;
+			
+			switch (term){
+			case "xterm":
+			case "rxvt":
+			case "rxvt-unicode": 
+				if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
+					xterm_colors = true;
+				}
+				break;
+
+			case "xterm-color":
+			case "xterm-256color":
+				xterm_colors = true;
+				break;
+			}
+			if (!xterm_colors)
+				return;
+
+			if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
+				return;
+			
+			string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
+			if (config == null){
+				config = "errors=red";
+				//config = "brightwhite,red";
+			}
+
+			if (config == "disable")
+				return;
+
+			if (!config.StartsWith ("errors="))
+				return;
+
+			config = config.Substring (7);
+			
+			int p = config.IndexOf (",");
+			if (p == -1)
+				prefix = GetForeground (config);
+			else
+				prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
+			postfix = "\x001b[0m";
+		}
+
+		public ConsoleReportPrinter ()
+			: base (Console.Error)
+		{
+		}
+
+		public ConsoleReportPrinter (TextWriter writer)
+			: base (writer)
+		{
+		}
+
+		static int NameToCode (string s)
+		{
+			switch (s) {
+			case "black":
+				return 0;
+			case "red":
+				return 1;
+			case "green":
+				return 2;
+			case "yellow":
+				return 3;
+			case "blue":
+				return 4;
+			case "magenta":
+				return 5;
+			case "cyan":
+				return 6;
+			case "grey":
+			case "white":
+				return 7;
+			}
+			return 7;
+		}
+
+		//
+		// maps a color name to its xterm color code
+		//
+		static string GetForeground (string s)
+		{
+			string highcode;
+
+			if (s.StartsWith ("bright")) {
+				highcode = "1;";
+				s = s.Substring (6);
+			} else
+				highcode = "";
+
+			return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
+		}
+
+		static string GetBackground (string s)
+		{
+			return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
+		}
+
+		protected override string FormatText (string txt)
+		{
+			if (prefix != null)
+				return prefix + txt + postfix;
+
+			return txt;
+		}
+	}
+
+	class TimeReporter
+	{
+		public enum TimerType
+		{
+			ParseTotal,
+			AssemblyBuilderSetup,
+			CreateTypeTotal,
+			ReferencesLoading,
+			ReferencesImporting,
+			PredefinedTypesInit,
+			ModuleDefinitionTotal,
+			EmitTotal,
+			CloseTypes,
+			Resouces,
+			OutputSave,
+			DebugSave,
+		}
+
+		readonly Stopwatch[] timers;
+		Stopwatch total;
+
+		public TimeReporter (bool enabled)
+		{
+			if (!enabled)
+				return;
+
+			timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
+		}
+
+		public void Start (TimerType type)
+		{
+			if (timers != null) {
+				var sw = new Stopwatch ();
+				timers[(int) type] = sw;
+				sw.Start ();
+			}
+		}
+
+		public void StartTotal ()
+		{
+			total = new Stopwatch ();
+			total.Start ();
+		}
+
+		public void Stop (TimerType type)
+		{
+			if (timers != null) {
+				timers[(int) type].Stop ();
+			}
+		}
+
+		public void StopTotal ()
+		{
+			total.Stop ();
+		}
+
+		public void ShowStats ()
+		{
+			if (timers == null)
+				return;
+
+			Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> {
+				{ TimerType.ParseTotal, "Parsing source files" },
+				{ TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
+				{ TimerType.CreateTypeTotal, "Compiled types created" },
+				{ TimerType.ReferencesLoading, "Referenced assemblies loading" },
+				{ TimerType.ReferencesImporting, "Referenced assemblies importing" },
+				{ TimerType.PredefinedTypesInit, "Predefined types initialization" },
+				{ TimerType.ModuleDefinitionTotal, "Module definition" },
+				{ TimerType.EmitTotal, "Resolving and emitting members blocks" },
+				{ TimerType.CloseTypes, "Module types closed" },
+				{ TimerType.Resouces, "Embedding resources" },
+				{ TimerType.OutputSave, "Writing output file" },
+				{ TimerType.DebugSave, "Writing debug symbols file" },
+			};
+
+			int counter = 0;
+			double percentage = (double) total.ElapsedMilliseconds / 100;
+			long subtotal = total.ElapsedMilliseconds;
+			foreach (var timer in timers) {
+				string msg = timer_names[(TimerType) counter++];
+				var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
+				Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
+				subtotal -= ms;
+			}
+
+			Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
+			Console.WriteLine ();
+			Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
+		}
+	}
+
+	public class InternalErrorException : Exception {
+		public InternalErrorException (MemberCore mc, Exception e)
+			: base (mc.Location + " " + mc.GetSignatureForError (), e)
+		{
+		}
+
+		public InternalErrorException ()
+			: base ("Internal error")
+		{
+		}
+
+		public InternalErrorException (string message)
+			: base (message)
+		{
+		}
+
+		public InternalErrorException (string message, params object[] args)
+			: base (String.Format (message, args))
+		{
+		}
+
+		public InternalErrorException (Exception exception, string message, params object[] args)
+			: base (String.Format (message, args), exception)
+		{
+		}
+		
+		public InternalErrorException (Exception e, Location loc)
+			: base (loc.ToString (), e)
+		{
+		}
+	}
+
+	class FatalException : Exception
+	{
+		public FatalException (string message)
+			: base (message)
+		{
+		}
+	}
+
+	/// <summary>
+	/// Handles #pragma warning
+	/// </summary>
+	public class WarningRegions {
+
+		abstract class PragmaCmd
+		{
+			public int Line;
+
+			protected PragmaCmd (int line)
+			{
+				Line = line;
+			}
+
+			public abstract bool IsEnabled (int code, bool previous);
+		}
+		
+		class Disable : PragmaCmd
+		{
+			int code;
+			public Disable (int line, int code)
+				: base (line)
+			{
+				this.code = code;
+			}
+
+			public override bool IsEnabled (int code, bool previous)
+			{
+				return this.code != code && previous;
+			}
+		}
+
+		class DisableAll : PragmaCmd
+		{
+			public DisableAll (int line)
+				: base (line) {}
+
+			public override bool IsEnabled(int code, bool previous)
+			{
+				return false;
+			}
+		}
+
+		class Enable : PragmaCmd
+		{
+			int code;
+			public Enable (int line, int code)
+				: base (line)
+			{
+				this.code = code;
+			}
+
+			public override bool IsEnabled(int code, bool previous)
+			{
+				return this.code == code || previous;
+			}
+		}
+
+		class EnableAll : PragmaCmd
+		{
+			public EnableAll (int line)
+				: base (line) {}
+
+			public override bool IsEnabled(int code, bool previous)
+			{
+				return true;
+			}
+		}
+
+
+		List<PragmaCmd> regions = new List<PragmaCmd> ();
+
+		public void WarningDisable (int line)
+		{
+			regions.Add (new DisableAll (line));
+		}
+
+		public void WarningDisable (Location location, int code, Report Report)
+		{
+			if (Report.CheckWarningCode (code, location))
+				regions.Add (new Disable (location.Row, code));
+		}
+
+		public void WarningEnable (int line)
+		{
+			regions.Add (new EnableAll (line));
+		}
+
+		public void WarningEnable (Location location, int code, CompilerContext context)
+		{
+			if (!context.Report.CheckWarningCode (code, location))
+				return;
+
+			if (context.Settings.IsWarningDisabledGlobally (code))
+				context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
+
+			regions.Add (new Enable (location.Row, code));
+		}
+
+		public bool IsWarningEnabled (int code, int src_line)
+		{
+			bool result = true;
+			foreach (PragmaCmd pragma in regions) {
+				if (src_line < pragma.Line)
+					break;
+
+				result = pragma.IsEnabled (code, result);
+			}
+			return result;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/settings.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/settings.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/settings.cs	(revision 11807)
@@ -0,0 +1,1601 @@
+//
+// settings.cs: All compiler settings
+//
+// Author: Miguel de Icaza (miguel@ximian.com)
+//            Ravi Pratap  (ravi@ximian.com)
+//            Marek Safar  (marek.safar@gmail.com)
+//
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2008 Novell, Inc
+// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
+//
+
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Globalization;
+using System;
+
+namespace Mono.CSharp {
+
+	public enum LanguageVersion
+	{
+		ISO_1 = 1,
+		ISO_2 = 2,
+		V_3 = 3,
+		V_4 = 4,
+		V_5 = 5,
+		V_6 = 6,
+		Experimental = 100,
+
+		Default = LanguageVersion.V_6,
+	}
+
+	public enum RuntimeVersion
+	{
+		v1,
+		v2,
+		v4
+	}
+
+	public enum Target
+	{
+		Library, Exe, Module, WinExe
+	}
+
+	public enum Platform
+	{
+		AnyCPU,
+		AnyCPU32Preferred,
+		Arm,
+		X86,
+		X64,
+		IA64
+	}
+
+	public class CompilerSettings
+	{
+		public Target Target;
+		public Platform Platform;
+		public string TargetExt;
+		public bool VerifyClsCompliance;
+		public bool Optimize;
+		public LanguageVersion Version;
+		public bool EnhancedWarnings;
+		public bool LoadDefaultReferences;
+		public string SdkVersion;
+
+		public string StrongNameKeyFile;
+		public string StrongNameKeyContainer;
+		public bool StrongNameDelaySign;
+
+		public int TabSize;
+
+		public bool WarningsAreErrors;
+		public int WarningLevel;
+
+		//
+		// Assemblies references to be loaded
+		//
+		public List<string> AssemblyReferences;
+
+		// 
+		// External aliases for assemblies
+		//
+		public List<Tuple<string, string>> AssemblyReferencesAliases;
+
+		//
+		// Modules to be embedded
+		//
+		public List<string> Modules;
+
+		//
+		// Lookup paths for referenced assemblies
+		//
+		public List<string> ReferencesLookupPaths;
+
+		//
+		// Encoding.
+		//
+		public Encoding Encoding;
+
+		//
+		// If set, enable XML documentation generation
+		//
+		public string DocumentationFile;
+
+		public string MainClass;
+
+		//
+		// Output file
+		//
+		public string OutputFile;
+
+		// 
+		// The default compiler checked state
+		//
+		public bool Checked;
+
+		//
+		// If true, the compiler is operating in statement mode,
+		// this currently turns local variable declaration into
+		// static variables of a class
+		//
+		public bool StatementMode;	// TODO: SUPER UGLY
+		
+		//
+		// Whether to allow Unsafe code
+		//
+		public bool Unsafe;
+
+		public string Win32ResourceFile;
+		public string Win32IconFile;
+
+		//
+		// A list of resource files for embedding
+		//
+		public List<AssemblyResource> Resources;
+
+		public bool GenerateDebugInfo;
+
+		#region Compiler debug flags only
+		public bool ParseOnly, TokenizeOnly, Timestamps;
+		public int DebugFlags;
+		public int VerboseParserFlag;
+		public int FatalCounter;
+		public bool Stacktrace;
+		public bool BreakOnInternalError;
+		#endregion
+
+		public bool ShowFullPaths;
+
+		//
+		// Whether we are being linked against the standard libraries.
+		// This is only used to tell whether `System.Object' should
+		// have a base class or not.
+		//
+		public bool StdLib;
+
+		public RuntimeVersion StdLibRuntimeVersion;
+
+		public string RuntimeMetadataVersion;
+
+		public bool WriteMetadataOnly;
+
+		readonly List<string> conditional_symbols;
+
+		readonly List<SourceFile> source_files;
+
+		List<int> warnings_as_error;
+		List<int> warnings_only;
+		HashSet<int> warning_ignore_table;
+
+		public CompilerSettings ()
+		{
+			StdLib = true;
+			Target = Target.Exe;
+			TargetExt = ".exe";
+			Platform = Platform.AnyCPU;
+			Version = LanguageVersion.Default;
+			VerifyClsCompliance = true;
+			Encoding = Encoding.UTF8;
+			LoadDefaultReferences = true;
+			StdLibRuntimeVersion = RuntimeVersion.v4;
+			WarningLevel = 4;
+
+			// Default to 1 or mdb files would be platform speficic
+			TabSize = 1;
+
+			AssemblyReferences = new List<string> ();
+			AssemblyReferencesAliases = new List<Tuple<string, string>> ();
+			Modules = new List<string> ();
+			ReferencesLookupPaths = new List<string> ();
+
+			conditional_symbols = new List<string> ();
+			//
+			// Add default mcs define
+			//
+			conditional_symbols.Add ("__MonoCS__");
+
+			source_files = new List<SourceFile> ();
+		}
+
+		#region Properties
+
+		public SourceFile FirstSourceFile {
+			get {
+				return source_files.Count > 0 ? source_files [0] : null;
+			}
+		}
+
+		public bool HasKeyFileOrContainer {
+			get {
+				return StrongNameKeyFile != null || StrongNameKeyContainer != null;
+			}
+		}
+
+		public bool NeedsEntryPoint {
+			get {
+				return Target == Target.Exe || Target == Target.WinExe;
+			}
+		}
+
+		public List<SourceFile> SourceFiles {
+			get {
+				return source_files;
+			}
+		}
+
+		#endregion
+
+		public void AddConditionalSymbol (string symbol)
+		{
+			if (!conditional_symbols.Contains (symbol))
+				conditional_symbols.Add (symbol);
+		}
+
+		public void AddWarningAsError (int id)
+		{
+			if (warnings_as_error == null)
+				warnings_as_error = new List<int> ();
+
+			warnings_as_error.Add (id);
+		}
+
+		public void AddWarningOnly (int id)
+		{
+			if (warnings_only == null)
+				warnings_only = new List<int> ();
+
+			warnings_only.Add (id);
+		}
+
+		public bool IsConditionalSymbolDefined (string symbol)
+		{
+			return conditional_symbols.Contains (symbol);
+		}
+
+		public bool IsWarningAsError (int code)
+		{
+			bool is_error = WarningsAreErrors;
+
+			// Check specific list
+			if (warnings_as_error != null)
+				is_error |= warnings_as_error.Contains (code);
+
+			// Ignore excluded warnings
+			if (warnings_only != null && warnings_only.Contains (code))
+				is_error = false;
+
+			return is_error;
+		}
+
+		public bool IsWarningEnabled (int code, int level)
+		{
+			if (WarningLevel < level)
+				return false;
+
+			return !IsWarningDisabledGlobally (code);
+		}
+
+		public bool IsWarningDisabledGlobally (int code)
+		{
+			return warning_ignore_table != null && warning_ignore_table.Contains (code);
+		}
+
+		public void SetIgnoreWarning (int code)
+		{
+			if (warning_ignore_table == null)
+				warning_ignore_table = new HashSet<int> ();
+
+			warning_ignore_table.Add (code);
+		}
+	}
+
+	public class CommandLineParser
+	{
+		enum ParseResult
+		{
+			Success,
+			Error,
+			Stop,
+			UnknownOption
+		}
+
+		static readonly char[] argument_value_separator = { ';', ',' };
+		static readonly char[] numeric_value_separator = { ';', ',', ' ' };
+
+		readonly TextWriter output;
+		readonly Report report;
+		bool stop_argument;
+
+		Dictionary<string, int> source_file_index;
+
+		public event Func<string[], int, int> UnknownOptionHandler;
+
+		CompilerSettings parser_settings;
+
+		public CommandLineParser (TextWriter errorOutput)
+			: this (errorOutput, Console.Out)
+		{
+		}
+
+		public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput)
+		{
+			var rp = new StreamReportPrinter (errorOutput);
+
+			parser_settings = new CompilerSettings ();
+			report = new Report (new CompilerContext (parser_settings, rp), rp);
+			this.output = messagesOutput;
+		}
+
+		public bool HasBeenStopped {
+			get {
+				return stop_argument;
+			}
+		}
+
+		void About ()
+		{
+			output.WriteLine (
+				"The Mono C# compiler is Copyright 2001-2011, Novell, Inc.\n\n" +
+				"The compiler source code is released under the terms of the \n" +
+				"MIT X11 or GNU GPL licenses\n\n" +
+
+				"For more information on Mono, visit the project Web site\n" +
+				"   http://www.mono-project.com\n\n" +
+
+				"The compiler was written by Miguel de Icaza, Ravi Pratap, Martin Baulig, Marek Safar, Raja R Harinath, Atushi Enomoto");
+		}
+
+		public CompilerSettings ParseArguments (string[] args)
+		{
+			CompilerSettings settings = new CompilerSettings ();
+			if (!ParseArguments (settings, args))
+				return null;
+
+			return settings;
+		}
+
+		public bool ParseArguments (CompilerSettings settings, string[] args)
+		{
+			if (settings == null)
+				throw new ArgumentNullException ("settings");
+
+			List<string> response_file_list = null;
+			bool parsing_options = true;
+			stop_argument = false;
+			source_file_index = new Dictionary<string, int> ();
+
+			for (int i = 0; i < args.Length; i++) {
+				string arg = args[i];
+				if (arg.Length == 0)
+					continue;
+
+				if (arg[0] == '@') {
+					string[] extra_args;
+					string response_file = arg.Substring (1);
+
+					if (response_file_list == null)
+						response_file_list = new List<string> ();
+
+					if (response_file_list.Contains (response_file)) {
+						report.Error (1515, "Response file `{0}' specified multiple times", response_file);
+						return false;
+					}
+
+					response_file_list.Add (response_file);
+
+					extra_args = LoadArgs (response_file);
+					if (extra_args == null) {
+						report.Error (2011, "Unable to open response file: " + response_file);
+						return false;
+					}
+
+					args = AddArgs (args, extra_args);
+					continue;
+				}
+
+				if (parsing_options) {
+					if (arg == "--") {
+						parsing_options = false;
+						continue;
+					}
+
+					bool dash_opt = arg[0] == '-';
+					bool slash_opt = arg[0] == '/';
+					if (dash_opt) {
+						switch (ParseOptionUnix (arg, ref args, ref i, settings)) {
+						case ParseResult.Error:
+						case ParseResult.Success:
+							continue;
+						case ParseResult.Stop:
+							stop_argument = true;
+							return true;
+						case ParseResult.UnknownOption:
+							if (UnknownOptionHandler != null) {
+								var ret = UnknownOptionHandler (args, i);
+								if (ret != -1) {
+									i = ret;
+									continue;
+								}
+							}
+							break;
+						}
+					}
+
+					if (dash_opt || slash_opt) {
+						// Try a -CSCOPTION
+						string csc_opt = dash_opt ? "/" + arg.Substring (1) : arg;
+						switch (ParseOption (csc_opt, ref args, settings)) {
+						case ParseResult.Error:
+						case ParseResult.Success:
+							continue;
+						case ParseResult.UnknownOption:
+							// Need to skip `/home/test.cs' however /test.cs is considered as error
+							if ((slash_opt && arg.Length > 3 && arg.IndexOf ('/', 2) > 0))
+								break;
+
+							if (UnknownOptionHandler != null) {
+								var ret = UnknownOptionHandler (args, i);
+								if (ret != -1) {
+									i = ret;
+									continue;
+								}
+							}
+
+							Error_WrongOption (arg);
+							return false;
+
+						case ParseResult.Stop:
+							stop_argument = true;
+							return true;
+						}
+					}
+				}
+
+				ProcessSourceFiles (arg, false, settings.SourceFiles);
+			}
+
+			return report.Errors == 0;
+		}
+
+		void ProcessSourceFiles (string spec, bool recurse, List<SourceFile> sourceFiles)
+		{
+			string path, pattern;
+
+			SplitPathAndPattern (spec, out path, out pattern);
+			if (pattern.IndexOf ('*') == -1) {
+				AddSourceFile (spec, sourceFiles);
+				return;
+			}
+
+			string[] files;
+			try {
+				files = Directory.GetFiles (path, pattern);
+			} catch (System.IO.DirectoryNotFoundException) {
+				report.Error (2001, "Source file `" + spec + "' could not be found");
+				return;
+			} catch (System.IO.IOException) {
+				report.Error (2001, "Source file `" + spec + "' could not be found");
+				return;
+			}
+			foreach (string f in files) {
+				AddSourceFile (f, sourceFiles);
+			}
+
+			if (!recurse)
+				return;
+
+			string[] dirs = null;
+
+			try {
+				dirs = Directory.GetDirectories (path);
+			} catch {
+			}
+
+			foreach (string d in dirs) {
+
+				// Don't include path in this string, as each
+				// directory entry already does
+				ProcessSourceFiles (d + "/" + pattern, true, sourceFiles);
+			}
+		}
+
+		static string[] AddArgs (string[] args, string[] extra_args)
+		{
+			string[] new_args;
+			new_args = new string[extra_args.Length + args.Length];
+
+			// if args contains '--' we have to take that into account
+			// split args into first half and second half based on '--'
+			// and add the extra_args before --
+			int split_position = Array.IndexOf (args, "--");
+			if (split_position != -1) {
+				Array.Copy (args, new_args, split_position);
+				extra_args.CopyTo (new_args, split_position);
+				Array.Copy (args, split_position, new_args, split_position + extra_args.Length, args.Length - split_position);
+			} else {
+				args.CopyTo (new_args, 0);
+				extra_args.CopyTo (new_args, args.Length);
+			}
+
+			return new_args;
+		}
+
+		void AddAssemblyReference (string alias, string assembly, CompilerSettings settings)
+		{
+			if (assembly.Length == 0) {
+				report.Error (1680, "Invalid reference alias `{0}='. Missing filename", alias);
+				return;
+			}
+
+			if (!IsExternAliasValid (alias)) {
+				report.Error (1679, "Invalid extern alias for -reference. Alias `{0}' is not a valid identifier", alias);
+				return;
+			}
+
+			settings.AssemblyReferencesAliases.Add (Tuple.Create (alias, assembly));
+		}
+
+		void AddResource (AssemblyResource res, CompilerSettings settings)
+		{
+			if (settings.Resources == null) {
+				settings.Resources = new List<AssemblyResource> ();
+				settings.Resources.Add (res);
+				return;
+			}
+
+			if (settings.Resources.Contains (res)) {
+				report.Error (1508, "The resource identifier `{0}' has already been used in this assembly", res.Name);
+				return;
+			}
+
+			settings.Resources.Add (res);
+		}
+
+		void AddSourceFile (string fileName, List<SourceFile> sourceFiles)
+		{
+			string path = Path.GetFullPath (fileName);
+
+			int index;
+			if (source_file_index.TryGetValue (path, out index)) {
+				string other_name = sourceFiles[index - 1].Name;
+				if (fileName.Equals (other_name))
+					report.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
+				else
+					report.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", fileName, other_name, path);
+
+				return;
+			}
+
+			var unit = new SourceFile (fileName, path, sourceFiles.Count + 1);
+			sourceFiles.Add (unit);
+			source_file_index.Add (path, unit.Index);
+		}
+
+		public bool ProcessWarningsList (string text, Action<int> action)
+		{
+			bool valid = true;
+			foreach (string wid in text.Split (numeric_value_separator, StringSplitOptions.RemoveEmptyEntries)) {
+				int id;
+				if (!int.TryParse (wid, NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, out id)) {
+					report.Error (1904, "`{0}' is not a valid warning number", wid);
+					valid = false;
+					continue;
+				}
+
+				if (report.CheckWarningCode (id, Location.Null))
+					action (id);
+			}
+
+			return valid;
+		}
+
+		void Error_RequiresArgument (string option)
+		{
+			report.Error (2006, "Missing argument for `{0}' option", option);
+		}
+
+		void Error_RequiresFileName (string option)
+		{
+			report.Error (2005, "Missing file specification for `{0}' option", option);
+		}
+
+		void Error_WrongOption (string option)
+		{
+			report.Error (2007, "Unrecognized command-line option: `{0}'", option);
+		}
+
+		static bool IsExternAliasValid (string identifier)
+		{
+			return Tokenizer.IsValidIdentifier (identifier);
+		}
+
+		static string[] LoadArgs (string file)
+		{
+			StreamReader f;
+			var args = new List<string> ();
+			string line;
+			try {
+				f = new StreamReader (file);
+			} catch {
+				return null;
+			}
+
+			StringBuilder sb = new StringBuilder ();
+
+			while ((line = f.ReadLine ()) != null) {
+				int t = line.Length;
+
+				for (int i = 0; i < t; i++) {
+					char c = line[i];
+
+					if (c == '"' || c == '\'') {
+						char end = c;
+
+						for (i++; i < t; i++) {
+							c = line[i];
+
+							if (c == end)
+								break;
+							sb.Append (c);
+						}
+					} else if (c == ' ') {
+						if (sb.Length > 0) {
+							args.Add (sb.ToString ());
+							sb.Length = 0;
+						}
+					} else
+						sb.Append (c);
+				}
+				if (sb.Length > 0) {
+					args.Add (sb.ToString ());
+					sb.Length = 0;
+				}
+			}
+
+			return args.ToArray ();
+		}
+
+		void OtherFlags ()
+		{
+			output.WriteLine (
+				"Other flags in the compiler\n" +
+				"   --fatal[=COUNT]    Makes error after COUNT fatal\n" +
+				"   --lint             Enhanced warnings\n" +
+				"   --metadata-only    Produced assembly will contain metadata only\n" +
+				"   --parse            Only parses the source file\n" +
+				"   --runtime:VERSION  Sets mscorlib.dll metadata version: v1, v2, v4\n" +
+				"   --stacktrace       Shows stack trace at error location\n" +
+				"   --timestamp        Displays time stamps of various compiler events\n" +
+				"   -v                 Verbose parsing (for debugging the parser)\n" +
+				"   --mcs-debug X      Sets MCS debugging level to X\n" +
+				"   --break-on-ice     Breaks compilation on internal compiler error");
+		}
+
+		//
+		// This parses the -arg and /arg options to the compiler, even if the strings
+		// in the following text use "/arg" on the strings.
+		//
+		ParseResult ParseOption (string option, ref string[] args, CompilerSettings settings)
+		{
+			int idx = option.IndexOf (':');
+			string arg, value;
+
+			if (idx == -1) {
+				arg = option;
+				value = "";
+			} else {
+				arg = option.Substring (0, idx);
+
+				value = option.Substring (idx + 1);
+			}
+
+			switch (arg.ToLowerInvariant ()) {
+			case "/nologo":
+				return ParseResult.Success;
+
+			case "/t":
+			case "/target":
+				switch (value) {
+				case "exe":
+					settings.Target = Target.Exe;
+					break;
+
+				case "winexe":
+					settings.Target = Target.WinExe;
+					break;
+
+				case "library":
+					settings.Target = Target.Library;
+					settings.TargetExt = ".dll";
+					break;
+
+				case "module":
+					settings.Target = Target.Module;
+					settings.TargetExt = ".netmodule";
+					break;
+
+				default:
+					report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
+					return ParseResult.Error;
+				}
+				return ParseResult.Success;
+
+			case "/out":
+				if (value.Length == 0) {
+					Error_RequiresFileName (option);
+					return ParseResult.Error;
+				}
+				settings.OutputFile = value;
+				return ParseResult.Success;
+
+			case "/o":
+			case "/o+":
+			case "/optimize":
+			case "/optimize+":
+				settings.Optimize = true;
+				return ParseResult.Success;
+
+			case "/o-":
+			case "/optimize-":
+				settings.Optimize = false;
+				return ParseResult.Success;
+
+			// TODO: Not supported by csc 3.5+
+			case "/incremental":
+			case "/incremental+":
+			case "/incremental-":
+				// nothing.
+				return ParseResult.Success;
+
+			case "/d":
+			case "/define": {
+					if (value.Length == 0) {
+						Error_RequiresArgument (option);
+						return ParseResult.Error;
+					}
+
+					foreach (string d in value.Split (argument_value_separator)) {
+						string conditional = d.Trim ();
+						if (!Tokenizer.IsValidIdentifier (conditional)) {
+							report.Warning (2029, 1, "Invalid conditional define symbol `{0}'", conditional);
+							continue;
+						}
+
+						settings.AddConditionalSymbol (conditional);
+					}
+					return ParseResult.Success;
+				}
+
+			case "/bugreport":
+				//
+				// We should collect data, runtime, etc and store in the file specified
+				//
+				output.WriteLine ("To file bug reports, please visit: http://www.mono-project.com/Bugs");
+				return ParseResult.Success;
+
+			case "/pkg": {
+					string packages;
+
+					if (value.Length == 0) {
+						Error_RequiresArgument (option);
+						return ParseResult.Error;
+					}
+					packages = String.Join (" ", value.Split (new Char[] { ';', ',', '\n', '\r' }));
+					string pkgout = Driver.GetPackageFlags (packages, report);
+
+					if (pkgout == null)
+						return ParseResult.Error;
+
+					string[] xargs = pkgout.Trim (new Char[] { ' ', '\n', '\r', '\t' }).Split (new Char[] { ' ', '\t' });
+					args = AddArgs (args, xargs);
+					return ParseResult.Success;
+				}
+
+			case "/linkres":
+			case "/linkresource":
+			case "/res":
+			case "/resource":
+				AssemblyResource res = null;
+				string[] s = value.Split (argument_value_separator, StringSplitOptions.RemoveEmptyEntries);
+				switch (s.Length) {
+				case 1:
+					if (s[0].Length == 0)
+						goto default;
+					res = new AssemblyResource (s[0], Path.GetFileName (s[0]));
+					break;
+				case 2:
+					res = new AssemblyResource (s[0], s[1]);
+					break;
+				case 3:
+					if (s[2] != "public" && s[2] != "private") {
+						report.Error (1906, "Invalid resource visibility option `{0}'. Use either `public' or `private' instead", s[2]);
+						return ParseResult.Error;
+					}
+					res = new AssemblyResource (s[0], s[1], s[2] == "private");
+					break;
+				default:
+					report.Error (-2005, "Wrong number of arguments for option `{0}'", option);
+					return ParseResult.Error;
+				}
+
+				if (res != null) {
+					res.IsEmbeded = arg[1] == 'r' || arg[1] == 'R';
+					AddResource (res, settings);
+				}
+
+				return ParseResult.Success;
+
+			case "/recurse":
+				if (value.Length == 0) {
+					Error_RequiresFileName (option);
+					return ParseResult.Error;
+				}
+				ProcessSourceFiles (value, true, settings.SourceFiles);
+				return ParseResult.Success;
+
+			case "/r":
+			case "/reference": {
+					if (value.Length == 0) {
+						Error_RequiresFileName (option);
+						return ParseResult.Error;
+					}
+
+					string[] refs = value.Split (argument_value_separator);
+					foreach (string r in refs) {
+						if (r.Length == 0)
+							continue;
+
+						string val = r;
+						int index = val.IndexOf ('=');
+						if (index > -1) {
+							string alias = r.Substring (0, index);
+							string assembly = r.Substring (index + 1);
+							AddAssemblyReference (alias, assembly, settings);
+							if (refs.Length != 1) {
+								report.Error (2034, "Cannot specify multiple aliases using single /reference option");
+								return ParseResult.Error;
+							}
+						} else {
+							settings.AssemblyReferences.Add (val);
+						}
+					}
+					return ParseResult.Success;
+				}
+			case "/addmodule": {
+					if (value.Length == 0) {
+						Error_RequiresFileName (option);
+						return ParseResult.Error;
+					}
+
+					string[] refs = value.Split (argument_value_separator);
+					foreach (string r in refs) {
+						settings.Modules.Add (r);
+					}
+					return ParseResult.Success;
+				}
+			case "/win32res": {
+					if (value.Length == 0) {
+						Error_RequiresFileName (option);
+						return ParseResult.Error;
+					}
+
+					if (settings.Win32IconFile != null)
+						report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
+
+					settings.Win32ResourceFile = value;
+					return ParseResult.Success;
+				}
+			case "/win32icon": {
+					if (value.Length == 0) {
+						Error_RequiresFileName (option);
+						return ParseResult.Error;
+					}
+
+					if (settings.Win32ResourceFile != null)
+						report.Error (1565, "Cannot specify the `win32res' and the `win32ico' compiler option at the same time");
+
+					settings.Win32IconFile = value;
+					return ParseResult.Success;
+				}
+			case "/doc": {
+					if (value.Length == 0) {
+						Error_RequiresFileName (option);
+						return ParseResult.Error;
+					}
+
+					settings.DocumentationFile = value;
+					return ParseResult.Success;
+				}
+			case "/lib": {
+					string[] libdirs;
+
+					if (value.Length == 0) {
+						return ParseResult.Error;
+					}
+
+					libdirs = value.Split (argument_value_separator);
+					foreach (string dir in libdirs)
+						settings.ReferencesLookupPaths.Add (dir);
+					return ParseResult.Success;
+				}
+
+			case "/debug-":
+				settings.GenerateDebugInfo = false;
+				return ParseResult.Success;
+
+			case "/debug":
+				if (value.Equals ("full", StringComparison.OrdinalIgnoreCase) || value.Equals ("pdbonly", StringComparison.OrdinalIgnoreCase) || idx < 0) {
+					settings.GenerateDebugInfo = true;
+					return ParseResult.Success;
+				}
+
+				if (value.Length > 0) {
+					report.Error (1902, "Invalid debug option `{0}'. Valid options are `full' or `pdbonly'", value);
+				} else {
+					Error_RequiresArgument (option);
+				}
+
+				return ParseResult.Error;
+
+			case "/debug+":
+				settings.GenerateDebugInfo = true;
+				return ParseResult.Success;
+
+			case "/checked":
+			case "/checked+":
+				settings.Checked = true;
+				return ParseResult.Success;
+
+			case "/checked-":
+				settings.Checked = false;
+				return ParseResult.Success;
+
+			case "/clscheck":
+			case "/clscheck+":
+				settings.VerifyClsCompliance = true;
+				return ParseResult.Success;
+
+			case "/clscheck-":
+				settings.VerifyClsCompliance = false;
+				return ParseResult.Success;
+
+			case "/unsafe":
+			case "/unsafe+":
+				settings.Unsafe = true;
+				return ParseResult.Success;
+
+			case "/unsafe-":
+				settings.Unsafe = false;
+				return ParseResult.Success;
+
+			case "/warnaserror":
+			case "/warnaserror+":
+				if (value.Length == 0) {
+					settings.WarningsAreErrors = true;
+					parser_settings.WarningsAreErrors = true;
+				} else {
+					if (!ProcessWarningsList (value, settings.AddWarningAsError))
+						return ParseResult.Error;
+				}
+				return ParseResult.Success;
+
+			case "/warnaserror-":
+				if (value.Length == 0) {
+					settings.WarningsAreErrors = false;
+				} else {
+					if (!ProcessWarningsList (value, settings.AddWarningOnly))
+						return ParseResult.Error;
+				}
+				return ParseResult.Success;
+
+			case "/warn":
+			case "/w":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				SetWarningLevel (value, settings);
+				return ParseResult.Success;
+
+			case "/nowarn":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				if (!ProcessWarningsList (value, settings.SetIgnoreWarning))
+					return ParseResult.Error;
+
+				return ParseResult.Success;
+
+			case "/noconfig":
+				settings.LoadDefaultReferences = false;
+				return ParseResult.Success;
+
+			case "/platform":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				switch (value.ToLowerInvariant ()) {
+				case "arm":
+					settings.Platform = Platform.Arm;
+					break;
+				case "anycpu":
+					settings.Platform = Platform.AnyCPU;
+					break;
+				case "x86":
+					settings.Platform = Platform.X86;
+					break;
+				case "x64":
+					settings.Platform = Platform.X64;
+					break;
+				case "itanium":
+					settings.Platform = Platform.IA64;
+					break;
+				case "anycpu32bitpreferred":
+					settings.Platform = Platform.AnyCPU32Preferred;
+					break;
+				default:
+					report.Error (1672, "Invalid -platform option `{0}'. Valid options are `anycpu', `anycpu32bitpreferred', `arm', `x86', `x64' or `itanium'",
+						value);
+					return ParseResult.Error;
+				}
+
+				return ParseResult.Success;
+
+			case "/sdk":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				settings.SdkVersion = value;
+				return ParseResult.Success;
+
+			// We just ignore this.
+			case "/errorreport":
+			case "/filealign":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				return ParseResult.Success;
+
+			case "/helpinternal":
+				OtherFlags ();
+				return ParseResult.Stop;
+
+			case "/help":
+			case "/?":
+				Usage ();
+				return ParseResult.Stop;
+
+			case "/main":
+			case "/m":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+				settings.MainClass = value;
+				return ParseResult.Success;
+
+			case "/nostdlib":
+			case "/nostdlib+":
+				settings.StdLib = false;
+				return ParseResult.Success;
+
+			case "/nostdlib-":
+				settings.StdLib = true;
+				return ParseResult.Success;
+
+			case "/fullpaths":
+				settings.ShowFullPaths = true;
+				return ParseResult.Success;
+
+			case "/keyfile":
+				if (value.Length == 0) {
+					Error_RequiresFileName (option);
+					return ParseResult.Error;
+				}
+
+				settings.StrongNameKeyFile = value;
+				return ParseResult.Success;
+
+			case "/keycontainer":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				settings.StrongNameKeyContainer = value;
+				return ParseResult.Success;
+
+			case "/delaysign+":
+			case "/delaysign":
+				settings.StrongNameDelaySign = true;
+				return ParseResult.Success;
+
+			case "/delaysign-":
+				settings.StrongNameDelaySign = false;
+				return ParseResult.Success;
+
+			case "/langversion":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				switch (value.ToLowerInvariant ()) {
+				case "iso-1":
+				case "1":
+					settings.Version = LanguageVersion.ISO_1;
+					return ParseResult.Success;
+				case "default":
+					settings.Version = LanguageVersion.Default;
+					return ParseResult.Success;
+				case "2":
+				case "iso-2":
+					settings.Version = LanguageVersion.ISO_2;
+					return ParseResult.Success;
+				case "3":
+					settings.Version = LanguageVersion.V_3;
+					return ParseResult.Success;
+				case "4":
+					settings.Version = LanguageVersion.V_4;
+					return ParseResult.Success;
+				case "5":
+					settings.Version = LanguageVersion.V_5;
+					return ParseResult.Success;
+				case "6":
+					settings.Version = LanguageVersion.V_6;
+					return ParseResult.Success;
+				case "experimental":
+					settings.Version = LanguageVersion.Experimental;
+					return ParseResult.Success;
+				case "future":
+					report.Warning (8000, 1, "Language version `future' is no longer supported");
+					goto case "6";
+				}
+
+				report.Error (1617, "Invalid -langversion option `{0}'. It must be `ISO-1', `ISO-2', Default or value in range 1 to 6", value);
+				return ParseResult.Error;
+
+			case "/codepage":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				switch (value) {
+				case "utf8":
+					settings.Encoding = Encoding.UTF8;
+					break;
+				case "reset":
+					settings.Encoding = Encoding.Default;
+					break;
+				default:
+					try {
+						settings.Encoding = Encoding.GetEncoding (int.Parse (value));
+					} catch {
+						report.Error (2016, "Code page `{0}' is invalid or not installed", value);
+					}
+					return ParseResult.Error;
+				}
+				return ParseResult.Success;
+
+			case "runtimemetadataversion":
+				if (value.Length == 0) {
+					Error_RequiresArgument (option);
+					return ParseResult.Error;
+				}
+
+				settings.RuntimeMetadataVersion = value;
+				return ParseResult.Success;
+
+			default:
+				return ParseResult.UnknownOption;
+			}
+		}
+
+		//
+		// Currently handles the Unix-like command line options, but will be
+		// deprecated in favor of the CSCParseOption, which will also handle the
+		// options that start with a dash in the future.
+		//
+		ParseResult ParseOptionUnix (string arg, ref string[] args, ref int i, CompilerSettings settings)
+		{
+			switch (arg){
+			case "-v":
+				settings.VerboseParserFlag++;
+				return ParseResult.Success;
+
+			case "--version":
+				Version ();
+				return ParseResult.Stop;
+				
+			case "--parse":
+				settings.ParseOnly = true;
+				return ParseResult.Success;
+				
+			case "--main": case "-m":
+				report.Warning (-29, 1, "Compatibility: Use -main:CLASS instead of --main CLASS or -m CLASS");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				settings.MainClass = args[++i];
+				return ParseResult.Success;
+				
+			case "--unsafe":
+				report.Warning (-29, 1, "Compatibility: Use -unsafe instead of --unsafe");
+				settings.Unsafe = true;
+				return ParseResult.Success;
+				
+			case "/?": case "/h": case "/help":
+			case "--help":
+				Usage ();
+				return ParseResult.Stop;
+
+			case "--define":
+				report.Warning (-29, 1, "Compatibility: Use -d:SYMBOL instead of --define SYMBOL");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+
+				settings.AddConditionalSymbol (args [++i]);
+				return ParseResult.Success;
+
+			case "--tokenize":
+				settings.TokenizeOnly = true;
+				return ParseResult.Success;
+				
+			case "-o": 
+			case "--output":
+				report.Warning (-29, 1, "Compatibility: Use -out:FILE instead of --output FILE or -o FILE");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				settings.OutputFile = args[++i];
+				return ParseResult.Success;
+
+			case "--checked":
+				report.Warning (-29, 1, "Compatibility: Use -checked instead of --checked");
+				settings.Checked = true;
+				return ParseResult.Success;
+				
+			case "--stacktrace":
+				settings.Stacktrace = true;
+				return ParseResult.Success;
+				
+			case "--linkresource":
+			case "--linkres":
+				report.Warning (-29, 1, "Compatibility: Use -linkres:VALUE instead of --linkres VALUE");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+
+				AddResource (new AssemblyResource (args[++i], args[i]), settings);
+				return ParseResult.Success;
+				
+			case "--resource":
+			case "--res":
+				report.Warning (-29, 1, "Compatibility: Use -res:VALUE instead of --res VALUE");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+
+				AddResource (new AssemblyResource (args[++i], args[i], true), settings);
+				return ParseResult.Success;
+				
+			case "--target":
+				report.Warning (-29, 1, "Compatibility: Use -target:KIND instead of --target KIND");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				
+				string type = args [++i];
+				switch (type){
+				case "library":
+					settings.Target = Target.Library;
+					settings.TargetExt = ".dll";
+					break;
+					
+				case "exe":
+					settings.Target = Target.Exe;
+					break;
+					
+				case "winexe":
+					settings.Target = Target.WinExe;
+					break;
+					
+				case "module":
+					settings.Target = Target.Module;
+					settings.TargetExt = ".dll";
+					break;
+				default:
+					report.Error (2019, "Invalid target type for -target. Valid options are `exe', `winexe', `library' or `module'");
+					break;
+				}
+				return ParseResult.Success;
+				
+			case "-r":
+				report.Warning (-29, 1, "Compatibility: Use -r:LIBRARY instead of -r library");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				
+				string val = args [++i];
+				int idx = val.IndexOf ('=');
+				if (idx > -1) {
+					string alias = val.Substring (0, idx);
+					string assembly = val.Substring (idx + 1);
+					AddAssemblyReference (alias, assembly, settings);
+					return ParseResult.Success;
+				}
+
+				settings.AssemblyReferences.Add (val);
+				return ParseResult.Success;
+				
+			case "-L":
+				report.Warning (-29, 1, "Compatibility: Use -lib:ARG instead of --L arg");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				settings.ReferencesLookupPaths.Add (args [++i]);
+				return ParseResult.Success;
+
+			case "--lint":
+				settings.EnhancedWarnings = true;
+				return ParseResult.Success;
+				
+			case "--nostdlib":
+				report.Warning (-29, 1, "Compatibility: Use -nostdlib instead of --nostdlib");
+				settings.StdLib = false;
+				return ParseResult.Success;
+				
+			case "--nowarn":
+				report.Warning (-29, 1, "Compatibility: Use -nowarn instead of --nowarn");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				int warn = 0;
+				
+				try {
+					warn = int.Parse (args [++i]);
+				} catch {
+					Usage ();
+					Environment.Exit (1);
+				}
+				settings.SetIgnoreWarning (warn);
+				return ParseResult.Success;
+
+			case "--wlevel":
+				report.Warning (-29, 1, "Compatibility: Use -warn:LEVEL instead of --wlevel LEVEL");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+
+				SetWarningLevel (args [++i], settings);
+				return ParseResult.Success;
+
+			case "--mcs-debug":
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+
+				try {
+					settings.DebugFlags = int.Parse (args [++i]);
+				} catch {
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+
+				return ParseResult.Success;
+				
+			case "--about":
+				About ();
+				return ParseResult.Stop;
+				
+			case "--recurse":
+				report.Warning (-29, 1, "Compatibility: Use -recurse:PATTERN option instead --recurse PATTERN");
+				if ((i + 1) >= args.Length){
+					Error_RequiresArgument (arg);
+					return ParseResult.Error;
+				}
+				ProcessSourceFiles (args [++i], true, settings.SourceFiles);
+				return ParseResult.Success;
+				
+			case "--timestamp":
+				settings.Timestamps = true;
+				return ParseResult.Success;
+
+			case "--debug": case "-g":
+				report.Warning (-29, 1, "Compatibility: Use -debug option instead of -g or --debug");
+				settings.GenerateDebugInfo = true;
+				return ParseResult.Success;
+				
+			case "--noconfig":
+				report.Warning (-29, 1, "Compatibility: Use -noconfig option instead of --noconfig");
+				settings.LoadDefaultReferences = false;
+				return ParseResult.Success;
+
+			case "--metadata-only":
+				settings.WriteMetadataOnly = true;
+				return ParseResult.Success;
+
+			case "--break-on-ice":
+				settings.BreakOnInternalError = true;
+				return ParseResult.Success;
+
+			default:
+				if (arg.StartsWith ("--fatal", StringComparison.Ordinal)){
+					int fatal = 1;
+					if (arg.StartsWith ("--fatal=", StringComparison.Ordinal))
+						int.TryParse (arg.Substring (8), out fatal);
+
+					settings.FatalCounter = fatal;
+					return ParseResult.Success;
+				}
+				if (arg.StartsWith ("--runtime:", StringComparison.Ordinal)) {
+					string version = arg.Substring (10);
+
+					switch (version) {
+					case "v1":
+					case "V1":
+						settings.StdLibRuntimeVersion = RuntimeVersion.v1;
+						break;
+					case "v2":
+					case "V2":
+						settings.StdLibRuntimeVersion = RuntimeVersion.v2;
+						break;
+					case "v4":
+					case "V4":
+						settings.StdLibRuntimeVersion = RuntimeVersion.v4;
+						break;
+					}
+					return ParseResult.Success;
+				}
+
+				return ParseResult.UnknownOption;
+			}
+		}
+
+		void SetWarningLevel (string s, CompilerSettings settings)
+		{
+			int level = -1;
+
+			try {
+				level = int.Parse (s);
+			} catch {
+			}
+			if (level < 0 || level > 4) {
+				report.Error (1900, "Warning level must be in the range 0-4");
+				return;
+			}
+			settings.WarningLevel = level;
+		}
+
+		//
+		// Given a path specification, splits the path from the file/pattern
+		//
+		static void SplitPathAndPattern (string spec, out string path, out string pattern)
+		{
+			int p = spec.LastIndexOf ('/');
+			if (p != -1) {
+				//
+				// Windows does not like /file.cs, switch that to:
+				// "\", "file.cs"
+				//
+				if (p == 0) {
+					path = "\\";
+					pattern = spec.Substring (1);
+				} else {
+					path = spec.Substring (0, p);
+					pattern = spec.Substring (p + 1);
+				}
+				return;
+			}
+
+			p = spec.LastIndexOf ('\\');
+			if (p != -1) {
+				path = spec.Substring (0, p);
+				pattern = spec.Substring (p + 1);
+				return;
+			}
+
+			path = ".";
+			pattern = spec;
+		}
+
+		void Usage ()
+		{
+			output.WriteLine (
+				"Mono C# compiler, Copyright 2001-2011 Novell, Inc., Copyright 2011-2012 Xamarin, Inc\n" +
+				"mcs [options] source-files\n" +
+				"   --about              About the Mono C# compiler\n" +
+				"   -addmodule:M1[,Mn]   Adds the module to the generated assembly\n" +
+				"   -checked[+|-]        Sets default aritmetic overflow context\n" +
+				"   -clscheck[+|-]       Disables CLS Compliance verifications\n" +
+				"   -codepage:ID         Sets code page to the one in ID (number, utf8, reset)\n" +
+				"   -define:S1[;S2]      Defines one or more conditional symbols (short: -d)\n" +
+				"   -debug[+|-], -g      Generate debugging information\n" +
+				"   -delaysign[+|-]      Only insert the public key into the assembly (no signing)\n" +
+				"   -doc:FILE            Process documentation comments to XML file\n" +
+				"   -fullpaths           Any issued error or warning uses absolute file path\n" +
+				"   -help                Lists all compiler options (short: -?)\n" +
+				"   -keycontainer:NAME   The key pair container used to sign the output assembly\n" +
+				"   -keyfile:FILE        The key file used to strongname the ouput assembly\n" +
+				"   -langversion:TEXT    Specifies language version: ISO-1, ISO-2, 3, 4, 5, Default or Future\n" +
+				"   -lib:PATH1[,PATHn]   Specifies the location of referenced assemblies\n" +
+				"   -main:CLASS          Specifies the class with the Main method (short: -m)\n" +
+				"   -noconfig            Disables implicitly referenced assemblies\n" +
+				"   -nostdlib[+|-]       Does not reference mscorlib.dll library\n" +
+				"   -nowarn:W1[,Wn]      Suppress one or more compiler warnings\n" +
+				"   -optimize[+|-]       Enables advanced compiler optimizations (short: -o)\n" +
+				"   -out:FILE            Specifies output assembly name\n" +
+				"   -pkg:P1[,Pn]         References packages P1..Pn\n" +
+				"   -platform:ARCH       Specifies the target platform of the output assembly\n" +
+				"                        ARCH can be one of: anycpu, anycpu32bitpreferred, arm,\n" +
+				"                        x86, x64 or itanium. The default is anycpu.\n" +
+				"   -recurse:SPEC        Recursively compiles files according to SPEC pattern\n" +
+				"   -reference:A1[,An]   Imports metadata from the specified assembly (short: -r)\n" +
+				"   -reference:ALIAS=A   Imports metadata using specified extern alias (short: -r)\n" +
+				"   -sdk:VERSION         Specifies SDK version of referenced assemblies\n" +
+				"                        VERSION can be one of: 2, 4, 4.5 (default) or a custom value\n" +
+				"   -target:KIND         Specifies the format of the output assembly (short: -t)\n" +
+				"                        KIND can be one of: exe, winexe, library, module\n" +
+				"   -unsafe[+|-]         Allows to compile code which uses unsafe keyword\n" +
+				"   -warnaserror[+|-]    Treats all warnings as errors\n" +
+				"   -warnaserror[+|-]:W1[,Wn] Treats one or more compiler warnings as errors\n" +
+				"   -warn:0-4            Sets warning level, the default is 4 (short -w:)\n" +
+				"   -helpinternal        Shows internal and advanced compiler options\n" +
+				"\n" +
+				"Resources:\n" +
+				"   -linkresource:FILE[,ID] Links FILE as a resource (short: -linkres)\n" +
+				"   -resource:FILE[,ID]     Embed FILE as a resource (short: -res)\n" +
+				"   -win32res:FILE          Specifies Win32 resource file (.res)\n" +
+				"   -win32icon:FILE         Use this icon for the output\n" +
+								"   @file                   Read response file for more options\n\n" +
+				"Options can be of the form -option or /option");
+		}
+
+		void Version ()
+		{
+			string version = System.Reflection.MethodBase.GetCurrentMethod ().DeclaringType.Assembly.GetName ().Version.ToString ();
+			output.WriteLine ("Mono C# compiler version {0}", version);
+		}
+	}
+
+	public class RootContext
+	{
+		//
+		// Contains the parsed tree
+		//
+		static ModuleContainer root;
+
+		static public ModuleContainer ToplevelTypes {
+			get { return root; }
+			set { root = value; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/statement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/statement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/statement.cs	(revision 11807)
@@ -0,0 +1,8074 @@
+//
+// statement.cs: Statement representation for the IL tree.
+//
+// Authors:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Martin Baulig (martin@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001, 2002, 2003 Ximian, Inc.
+// Copyright 2003, 2004 Novell, Inc.
+// Copyright 2011 Xamarin Inc.
+//
+
+using System;
+using System.Collections.Generic;
+
+#if STATIC
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection.Emit;
+#endif
+
+namespace Mono.CSharp {
+	
+	public abstract class Statement {
+		public Location loc;
+		protected bool reachable;
+
+		public bool IsUnreachable {
+			get {
+				return !reachable;
+			}
+		}
+		
+		/// <summary>
+		///   Resolves the statement, true means that all sub-statements
+		///   did resolve ok.
+		///  </summary>
+		public virtual bool Resolve (BlockContext bc)
+		{
+			return true;
+		}
+
+		/// <summary>
+		///   Return value indicates whether all code paths emitted return.
+		/// </summary>
+		protected abstract void DoEmit (EmitContext ec);
+
+		public virtual void Emit (EmitContext ec)
+		{
+			ec.Mark (loc);
+			DoEmit (ec);
+
+			if (ec.StatementEpilogue != null) {
+				ec.EmitEpilogue ();
+			}
+		}
+
+		//
+		// This routine must be overrided in derived classes and make copies
+		// of all the data that might be modified if resolved
+		// 
+		protected abstract void CloneTo (CloneContext clonectx, Statement target);
+
+		public Statement Clone (CloneContext clonectx)
+		{
+			Statement s = (Statement) this.MemberwiseClone ();
+			CloneTo (clonectx, s);
+			return s;
+		}
+
+		public virtual Expression CreateExpressionTree (ResolveContext ec)
+		{
+			ec.Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
+			return null;
+		}
+		
+		public virtual object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		//
+		// Return value indicates whether statement has unreachable end
+		//
+		protected abstract bool DoFlowAnalysis (FlowAnalysisContext fc);
+
+		public bool FlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (reachable) {
+				fc.UnreachableReported = false;
+				var res = DoFlowAnalysis (fc);
+				return res;
+			}
+
+			//
+			// Special handling cases
+			//
+			if (this is Block) {
+				return DoFlowAnalysis (fc);
+			}
+
+			if (this is EmptyStatement || loc.IsNull)
+				return true;
+
+			if (fc.UnreachableReported)
+				return true;
+
+			fc.Report.Warning (162, 2, loc, "Unreachable code detected");
+			fc.UnreachableReported = true;
+			return true;
+		}
+
+		public virtual Reachability MarkReachable (Reachability rc)
+		{
+			if (!rc.IsUnreachable)
+				reachable = true;
+
+			return rc;
+		}
+
+		protected void CheckExitBoundaries (BlockContext bc, Block scope)
+		{
+			if (bc.CurrentBlock.ParametersBlock.Original != scope.ParametersBlock.Original) {
+				bc.Report.Error (1632, loc, "Control cannot leave the body of an anonymous method");
+				return;
+			}
+
+			for (var b = bc.CurrentBlock; b != null && b != scope; b = b.Parent) {
+				if (b.IsFinallyBlock) {
+					Error_FinallyClauseExit (bc);
+					break;
+				}
+			}
+		}
+
+		protected void Error_FinallyClauseExit (BlockContext bc)
+		{
+			bc.Report.Error (157, loc, "Control cannot leave the body of a finally clause");
+		}
+	}
+
+	public sealed class EmptyStatement : Statement
+	{
+		public EmptyStatement (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			return true;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			throw new NotSupportedException ();
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return false;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			// nothing needed.
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class If : Statement {
+		Expression expr;
+		public Statement TrueStatement;
+		public Statement FalseStatement;
+
+		bool true_returns, false_returns;
+
+		public If (Expression bool_expr, Statement true_statement, Location l)
+			: this (bool_expr, true_statement, null, l)
+		{
+		}
+
+		public If (Expression bool_expr,
+			   Statement true_statement,
+			   Statement false_statement,
+			   Location l)
+		{
+			this.expr = bool_expr;
+			TrueStatement = true_statement;
+			FalseStatement = false_statement;
+			loc = l;
+		}
+
+		public Expression Expr {
+			get {
+				return this.expr;
+			}
+		}
+		
+		public override bool Resolve (BlockContext ec)
+		{
+			expr = expr.Resolve (ec);
+
+			var ok = TrueStatement.Resolve (ec);
+
+			if (FalseStatement != null) {
+				ok &= FalseStatement.Resolve (ec);
+			}
+
+			return ok;
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			Label false_target = ec.DefineLabel ();
+			Label end;
+
+			//
+			// If we're a boolean constant, Resolve() already
+			// eliminated dead code for us.
+			//
+			Constant c = expr as Constant;
+			if (c != null){
+				c.EmitSideEffect (ec);
+
+				if (!c.IsDefaultValue)
+					TrueStatement.Emit (ec);
+				else if (FalseStatement != null)
+					FalseStatement.Emit (ec);
+
+				return;
+			}			
+			
+			expr.EmitBranchable (ec, false_target, false);
+			
+			TrueStatement.Emit (ec);
+
+			if (FalseStatement != null){
+				bool branch_emitted = false;
+				
+				end = ec.DefineLabel ();
+				if (!true_returns){
+					ec.Emit (OpCodes.Br, end);
+					branch_emitted = true;
+				}
+
+				ec.MarkLabel (false_target);
+				FalseStatement.Emit (ec);
+
+				if (branch_emitted)
+					ec.MarkLabel (end);
+			} else {
+				ec.MarkLabel (false_target);
+			}
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysisConditional (fc);
+
+			var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
+
+			fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
+
+			var res = TrueStatement.FlowAnalysis (fc);
+
+			if (FalseStatement == null) {
+				var c = expr as Constant;
+				if (c != null && !c.IsDefaultValue)
+					return true_returns;
+
+				if (true_returns)
+					fc.DefiniteAssignment = da_false;
+				else
+					fc.DefiniteAssignment &= da_false;
+ 
+				return false;
+			}
+
+			if (true_returns) {
+				fc.DefiniteAssignment = da_false;
+				return FalseStatement.FlowAnalysis (fc);
+			}
+
+			var da_true = fc.DefiniteAssignment;
+
+			fc.DefiniteAssignment = da_false;
+			res &= FalseStatement.FlowAnalysis (fc);
+
+			if (!TrueStatement.IsUnreachable) {
+				if (false_returns || FalseStatement.IsUnreachable)
+					fc.DefiniteAssignment = da_true;
+				else
+					fc.DefiniteAssignment &= da_true;
+			}
+
+			return res;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (rc.IsUnreachable)
+				return rc;
+
+			base.MarkReachable (rc);
+
+			var c = expr as Constant;
+			if (c != null) {
+				bool take = !c.IsDefaultValue;
+				if (take) {
+					rc = TrueStatement.MarkReachable (rc);
+				} else {
+					if (FalseStatement != null)
+						rc = FalseStatement.MarkReachable (rc);
+				}
+
+				return rc;
+			}
+
+			var true_rc = TrueStatement.MarkReachable (rc);
+			true_returns = true_rc.IsUnreachable;
+	
+			if (FalseStatement == null)
+				return rc;
+
+			var false_rc = FalseStatement.MarkReachable (rc);
+			false_returns = false_rc.IsUnreachable;
+
+			return true_rc & false_rc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			If target = (If) t;
+
+			target.expr = expr.Clone (clonectx);
+			target.TrueStatement = TrueStatement.Clone (clonectx);
+			if (FalseStatement != null)
+				target.FalseStatement = FalseStatement.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Do : LoopStatement
+	{
+		public Expression expr;
+		bool iterator_reachable, end_reachable;
+
+		public Do (Statement statement, BooleanExpression bool_expr, Location doLocation, Location whileLocation)
+			: base (statement)
+		{
+			expr = bool_expr;
+			loc = doLocation;
+			WhileLocation = whileLocation;
+		}
+
+		public Location WhileLocation {
+			get; private set;
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			var ok = base.Resolve (bc);
+
+			expr = expr.Resolve (bc);
+
+			return ok;
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			Label loop = ec.DefineLabel ();
+			Label old_begin = ec.LoopBegin;
+			Label old_end = ec.LoopEnd;
+			
+			ec.LoopBegin = ec.DefineLabel ();
+			ec.LoopEnd = ec.DefineLabel ();
+				
+			ec.MarkLabel (loop);
+			Statement.Emit (ec);
+			ec.MarkLabel (ec.LoopBegin);
+
+			// Mark start of while condition
+			ec.Mark (WhileLocation);
+
+			//
+			// Dead code elimination
+			//
+			if (expr is Constant) {
+				bool res = !((Constant) expr).IsDefaultValue;
+
+				expr.EmitSideEffect (ec);
+				if (res)
+					ec.Emit (OpCodes.Br, loop);
+			} else {
+				expr.EmitBranchable (ec, loop, true);
+			}
+			
+			ec.MarkLabel (ec.LoopEnd);
+
+			ec.LoopBegin = old_begin;
+			ec.LoopEnd = old_end;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			var res = Statement.FlowAnalysis (fc);
+
+			expr.FlowAnalysisConditional (fc);
+
+			fc.DefiniteAssignment = fc.DefiniteAssignmentOnFalse;
+
+			if (res && !iterator_reachable)
+				return !end_reachable;
+
+			if (!end_reachable) {
+				var c = expr as Constant;
+				if (c != null && !c.IsDefaultValue)
+					return true;
+			}
+
+			return false;
+		}
+		
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			
+			var body_rc = Statement.MarkReachable (rc);
+
+			if (body_rc.IsUnreachable && !iterator_reachable) {
+				expr = new UnreachableExpression (expr);
+				return end_reachable ? rc : Reachability.CreateUnreachable ();
+			}
+
+			if (!end_reachable) {
+				var c = expr as Constant;
+				if (c != null && !c.IsDefaultValue)
+					return Reachability.CreateUnreachable ();
+			}
+
+			return rc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Do target = (Do) t;
+
+			target.Statement = Statement.Clone (clonectx);
+			target.expr = expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		public override void SetEndReachable ()
+		{
+			end_reachable = true;
+		}
+
+		public override void SetIteratorReachable ()
+		{
+			iterator_reachable = true;
+		}
+	}
+
+	public class While : LoopStatement
+	{
+		public Expression expr;
+		bool empty, infinite, end_reachable;
+		List<DefiniteAssignmentBitSet> end_reachable_das;
+
+		public While (BooleanExpression bool_expr, Statement statement, Location l)
+			: base (statement)
+		{
+			this.expr = bool_expr;
+			loc = l;
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			bool ok = true;
+
+			expr = expr.Resolve (bc);
+			if (expr == null)
+				ok = false;
+
+			var c = expr as Constant;
+			if (c != null) {
+				empty = c.IsDefaultValue;
+				infinite = !empty;
+			}
+
+			ok &= base.Resolve (bc);
+			return ok;
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (empty) {
+				expr.EmitSideEffect (ec);
+				return;
+			}
+
+			Label old_begin = ec.LoopBegin;
+			Label old_end = ec.LoopEnd;
+			
+			ec.LoopBegin = ec.DefineLabel ();
+			ec.LoopEnd = ec.DefineLabel ();
+
+			//
+			// Inform whether we are infinite or not
+			//
+			if (expr is Constant) {
+				// expr is 'true', since the 'empty' case above handles the 'false' case
+				ec.MarkLabel (ec.LoopBegin);
+
+				if (ec.EmitAccurateDebugInfo)
+					ec.Emit (OpCodes.Nop);
+
+				expr.EmitSideEffect (ec);
+				Statement.Emit (ec);
+				ec.Emit (OpCodes.Br, ec.LoopBegin);
+					
+				//
+				// Inform that we are infinite (ie, `we return'), only
+				// if we do not `break' inside the code.
+				//
+				ec.MarkLabel (ec.LoopEnd);
+			} else {
+				Label while_loop = ec.DefineLabel ();
+
+				ec.Emit (OpCodes.Br, ec.LoopBegin);
+				ec.MarkLabel (while_loop);
+
+				Statement.Emit (ec);
+			
+				ec.MarkLabel (ec.LoopBegin);
+
+				ec.Mark (loc);
+				expr.EmitBranchable (ec, while_loop, true);
+				
+				ec.MarkLabel (ec.LoopEnd);
+			}	
+
+			ec.LoopBegin = old_begin;
+			ec.LoopEnd = old_end;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysisConditional (fc);
+
+			fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
+			var da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
+
+			Statement.FlowAnalysis (fc);
+
+			//
+			// Special case infinite while with breaks
+			//
+			if (end_reachable_das != null) {
+				da_false = DefiniteAssignmentBitSet.And (end_reachable_das);
+				end_reachable_das = null;
+			}
+
+			fc.DefiniteAssignment = da_false;
+
+			if (infinite && !end_reachable)
+				return true;
+
+			return false;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (rc.IsUnreachable)
+				return rc;
+
+			base.MarkReachable (rc);
+
+			//
+			// Special case unreachable while body
+			//
+			if (empty) {
+				Statement.MarkReachable (Reachability.CreateUnreachable ());
+				return rc;
+			}
+
+			Statement.MarkReachable (rc);
+
+			//
+			// When infinite while end is unreachable via break anything what follows is unreachable too
+			//
+			if (infinite && !end_reachable)
+				return Reachability.CreateUnreachable ();
+
+			return rc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			While target = (While) t;
+
+			target.expr = expr.Clone (clonectx);
+			target.Statement = Statement.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
+		{
+			if (!infinite)
+				return;
+
+			if (end_reachable_das == null)
+				end_reachable_das = new List<DefiniteAssignmentBitSet> ();
+
+			end_reachable_das.Add (fc.DefiniteAssignment);
+		}
+
+		public override void SetEndReachable ()
+		{
+			end_reachable = true;
+		}
+	}
+
+	public class For : LoopStatement
+	{
+		bool infinite, empty, iterator_reachable, end_reachable;
+		List<DefiniteAssignmentBitSet> end_reachable_das;
+		
+		public For (Location l)
+			: base (null)
+		{
+			loc = l;
+		}
+
+		public Statement Initializer {
+			get; set;
+		}
+
+		public Expression Condition {
+			get; set;
+		}
+
+		public Statement Iterator {
+			get; set;
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			Initializer.Resolve (bc);
+
+			if (Condition != null) {
+				Condition = Condition.Resolve (bc);
+				var condition_constant = Condition as Constant;
+				if (condition_constant != null) {
+					if (condition_constant.IsDefaultValue) {
+						empty = true;
+					} else {
+						infinite = true;
+					}
+				}
+			} else {
+				infinite = true;
+			}
+
+			return base.Resolve (bc) && Iterator.Resolve (bc);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			Initializer.FlowAnalysis (fc);
+
+			DefiniteAssignmentBitSet da_false;
+			if (Condition != null) {
+				Condition.FlowAnalysisConditional (fc);
+				fc.DefiniteAssignment = fc.DefiniteAssignmentOnTrue;
+				da_false = new DefiniteAssignmentBitSet (fc.DefiniteAssignmentOnFalse);
+			} else {
+				da_false = fc.BranchDefiniteAssignment ();
+			}
+
+			Statement.FlowAnalysis (fc);
+
+			Iterator.FlowAnalysis (fc);
+
+			//
+			// Special case infinite for with breaks
+			//
+			if (end_reachable_das != null) {
+				da_false = DefiniteAssignmentBitSet.And (end_reachable_das);
+				end_reachable_das = null;
+			}
+
+			fc.DefiniteAssignment = da_false;
+
+			if (infinite && !end_reachable)
+				return true;
+
+			return false;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			Initializer.MarkReachable (rc);
+
+			var body_rc = Statement.MarkReachable (rc);
+			if (!body_rc.IsUnreachable || iterator_reachable) {
+				Iterator.MarkReachable (rc);
+			}
+
+			//
+			// When infinite for end is unreachable via break anything what follows is unreachable too
+			//
+			if (infinite && !end_reachable) {
+				return Reachability.CreateUnreachable ();
+			}
+
+			return rc;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (Initializer != null)
+				Initializer.Emit (ec);
+
+			if (empty) {
+				Condition.EmitSideEffect (ec);
+				return;
+			}
+
+			Label old_begin = ec.LoopBegin;
+			Label old_end = ec.LoopEnd;
+			Label loop = ec.DefineLabel ();
+			Label test = ec.DefineLabel ();
+
+			ec.LoopBegin = ec.DefineLabel ();
+			ec.LoopEnd = ec.DefineLabel ();
+
+			ec.Emit (OpCodes.Br, test);
+			ec.MarkLabel (loop);
+			Statement.Emit (ec);
+
+			ec.MarkLabel (ec.LoopBegin);
+			Iterator.Emit (ec);
+
+			ec.MarkLabel (test);
+			//
+			// If test is null, there is no test, and we are just
+			// an infinite loop
+			//
+			if (Condition != null) {
+				ec.Mark (Condition.Location);
+
+				//
+				// The Resolve code already catches the case for
+				// Test == Constant (false) so we know that
+				// this is true
+				//
+				if (Condition is Constant) {
+					Condition.EmitSideEffect (ec);
+					ec.Emit (OpCodes.Br, loop);
+				} else {
+					Condition.EmitBranchable (ec, loop, true);
+				}
+				
+			} else
+				ec.Emit (OpCodes.Br, loop);
+			ec.MarkLabel (ec.LoopEnd);
+
+			ec.LoopBegin = old_begin;
+			ec.LoopEnd = old_end;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			For target = (For) t;
+
+			if (Initializer != null)
+				target.Initializer = Initializer.Clone (clonectx);
+			if (Condition != null)
+				target.Condition = Condition.Clone (clonectx);
+			if (Iterator != null)
+				target.Iterator = Iterator.Clone (clonectx);
+			target.Statement = Statement.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
+		{
+			if (!infinite)
+				return;
+
+			if (end_reachable_das == null)
+				end_reachable_das = new List<DefiniteAssignmentBitSet> ();
+
+			end_reachable_das.Add (fc.DefiniteAssignment);
+		}
+
+		public override void SetEndReachable ()
+		{
+			end_reachable = true;
+		}
+
+		public override void SetIteratorReachable ()
+		{
+			iterator_reachable = true;
+		}
+	}
+
+	public abstract class LoopStatement : Statement
+	{
+		protected LoopStatement (Statement statement)
+		{
+			Statement = statement;
+		}
+
+		public Statement Statement { get; set; }
+
+		public override bool Resolve (BlockContext bc)
+		{
+			var prev_loop = bc.EnclosingLoop;
+			var prev_los = bc.EnclosingLoopOrSwitch;
+			bc.EnclosingLoopOrSwitch = bc.EnclosingLoop = this;
+			var ok = Statement.Resolve (bc);
+			bc.EnclosingLoopOrSwitch = prev_los;
+			bc.EnclosingLoop = prev_loop;
+
+			return ok;
+		}
+
+		//
+		// Needed by possibly infinite loops statements (for, while) and switch statment
+		//
+		public virtual void AddEndDefiniteAssignment (FlowAnalysisContext fc)
+		{
+		}
+
+		public virtual void SetEndReachable ()
+		{
+		}
+
+		public virtual void SetIteratorReachable ()
+		{
+		}
+	}
+	
+	public class StatementExpression : Statement
+	{
+		ExpressionStatement expr;
+		
+		public StatementExpression (ExpressionStatement expr)
+		{
+			this.expr = expr;
+			loc = expr.StartLocation;
+		}
+
+		public StatementExpression (ExpressionStatement expr, Location loc)
+		{
+			this.expr = expr;
+			this.loc = loc;
+		}
+
+		public ExpressionStatement Expr {
+			get {
+ 				return this.expr;
+			}
+		}
+		
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			StatementExpression target = (StatementExpression) t;
+			target.expr = (ExpressionStatement) expr.Clone (clonectx);
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			expr.EmitStatement (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+			return false;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			expr.MarkReachable (rc);
+			return rc;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			expr = expr.ResolveStatement (ec);
+			return expr != null;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class StatementErrorExpression : Statement
+	{
+		Expression expr;
+
+		public StatementErrorExpression (Expression expr)
+		{
+			this.expr = expr;
+			this.loc = expr.StartLocation;
+		}
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			expr.Error_InvalidExpressionStatement (bc);
+			return true;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			throw new NotSupportedException ();
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return false;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			var t = (StatementErrorExpression) target;
+
+			t.expr = expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// Simple version of statement list not requiring a block
+	//
+	public class StatementList : Statement
+	{
+		List<Statement> statements;
+
+		public StatementList (Statement first, Statement second)
+		{
+			statements = new List<Statement> { first, second };
+		}
+
+		#region Properties
+		public IList<Statement> Statements {
+			get {
+				return statements;
+			}
+		}
+		#endregion
+
+		public void Add (Statement statement)
+		{
+			statements.Add (statement);
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			foreach (var s in statements)
+				s.Resolve (ec);
+
+			return true;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			foreach (var s in statements)
+				s.Emit (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			foreach (var s in statements)
+				s.FlowAnalysis (fc);
+
+			return false;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			Reachability res = rc;
+			foreach (var s in statements)
+				res = s.MarkReachable (rc);
+
+			return res;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			StatementList t = (StatementList) target;
+
+			t.statements = new List<Statement> (statements.Count);
+			foreach (Statement s in statements)
+				t.statements.Add (s.Clone (clonectx));
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// For statements which require special handling when inside try or catch block
+	//
+	public abstract class ExitStatement : Statement
+	{
+		protected bool unwind_protect;
+
+		protected abstract bool DoResolve (BlockContext bc);
+		protected abstract bool IsLocalExit { get; }
+
+		public override bool Resolve (BlockContext bc)
+		{
+			var res = DoResolve (bc);
+
+			if (!IsLocalExit) {
+				//
+				// We are inside finally scope but is it the scope we are exiting
+				//
+				if (bc.HasSet (ResolveContext.Options.FinallyScope)) {
+
+					for (var b = bc.CurrentBlock; b != null; b = b.Parent) {
+						if (b.IsFinallyBlock) {
+							Error_FinallyClauseExit (bc);
+							break;
+						}
+
+						if (b is ParametersBlock)
+							break;
+					}
+				}
+			}
+
+			unwind_protect = bc.HasAny (ResolveContext.Options.TryScope | ResolveContext.Options.CatchScope);
+			return res;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (IsLocalExit)
+				return true;
+
+			if (fc.TryFinally != null) {
+			    fc.TryFinally.RegisterForControlExitCheck (new DefiniteAssignmentBitSet (fc.DefiniteAssignment));
+			} else {
+			    fc.ParametersBlock.CheckControlExit (fc);
+			}
+
+			return true;
+		}
+	}
+
+	/// <summary>
+	///   Implements the return statement
+	/// </summary>
+	public class Return : ExitStatement
+	{
+		Expression expr;
+
+		public Return (Expression expr, Location l)
+		{
+			this.expr = expr;
+			loc = l;
+		}
+
+		#region Properties
+
+		public Expression Expr {
+			get {
+				return expr;
+			}
+			protected set {
+				expr = value;
+			}
+		}
+
+		protected override bool IsLocalExit {
+			get {
+				return false;
+			}
+		}
+
+		#endregion
+
+		protected override bool DoResolve (BlockContext ec)
+		{
+			var block_return_type = ec.ReturnType;
+
+			if (expr == null) {
+				if (block_return_type.Kind == MemberKind.Void)
+					return true;
+
+				//
+				// Return must not be followed by an expression when
+				// the method return type is Task
+				//
+				if (ec.CurrentAnonymousMethod is AsyncInitializer) {
+					var storey = (AsyncTaskStorey) ec.CurrentAnonymousMethod.Storey;
+					if (storey.ReturnType == ec.Module.PredefinedTypes.Task.TypeSpec) {
+						//
+						// Extra trick not to emit ret/leave inside awaiter body
+						//
+						expr = EmptyExpression.Null;
+						return true;
+					}
+
+					if (storey.ReturnType.IsGenericTask)
+						block_return_type = storey.ReturnType.TypeArguments[0];
+				}
+
+				if (ec.CurrentIterator != null) {
+					Error_ReturnFromIterator (ec);
+				} else if (block_return_type != InternalType.ErrorType) {
+					ec.Report.Error (126, loc,
+						"An object of a type convertible to `{0}' is required for the return statement",
+						block_return_type.GetSignatureForError ());
+				}
+
+				return false;
+			}
+
+			expr = expr.Resolve (ec);
+
+			AnonymousExpression am = ec.CurrentAnonymousMethod;
+			if (am == null) {
+				if (block_return_type.Kind == MemberKind.Void) {
+					ec.Report.Error (127, loc,
+						"`{0}': A return keyword must not be followed by any expression when method returns void",
+						ec.GetSignatureForError ());
+
+					return false;
+				}
+			} else {
+				if (am.IsIterator) {
+					Error_ReturnFromIterator (ec);
+					return false;
+				}
+
+				var async_block = am as AsyncInitializer;
+				if (async_block != null) {
+					if (expr != null) {
+						var storey = (AsyncTaskStorey) am.Storey;
+						var async_type = storey.ReturnType;
+
+						if (async_type == null && async_block.ReturnTypeInference != null) {
+							if (expr.Type.Kind == MemberKind.Void && !(this is ContextualReturn))
+								ec.Report.Error (4029, loc, "Cannot return an expression of type `void'");
+							else
+								async_block.ReturnTypeInference.AddCommonTypeBoundAsync (expr.Type);
+							return true;
+						}
+
+						if (async_type.Kind == MemberKind.Void) {
+							ec.Report.Error (8030, loc,
+								"Anonymous function or lambda expression converted to a void returning delegate cannot return a value");
+							return false;
+						}
+
+						if (!async_type.IsGenericTask) {
+							if (this is ContextualReturn)
+								return true;
+
+							if (async_block.DelegateType != null) {
+								ec.Report.Error (8031, loc,
+									"Async lambda expression or anonymous method converted to a `Task' cannot return a value. Consider returning `Task<T>'");
+							} else {
+								ec.Report.Error (1997, loc,
+									"`{0}': A return keyword must not be followed by an expression when async method returns `Task'. Consider using `Task<T>' return type",
+									ec.GetSignatureForError ());
+							}
+							return false;
+						}
+
+						//
+						// The return type is actually Task<T> type argument
+						//
+						if (expr.Type == async_type) {
+							ec.Report.Error (4016, loc,
+								"`{0}': The return expression type of async method must be `{1}' rather than `Task<{1}>'",
+								ec.GetSignatureForError (), async_type.TypeArguments[0].GetSignatureForError ());
+						} else {
+							block_return_type = async_type.TypeArguments[0];
+						}
+					}
+				} else {
+					if (block_return_type.Kind == MemberKind.Void) {
+						ec.Report.Error (8030, loc,
+							"Anonymous function or lambda expression converted to a void returning delegate cannot return a value");
+						return false;
+					}
+
+					var l = am as AnonymousMethodBody;
+					if (l != null && expr != null) {
+						if (l.ReturnTypeInference != null) {
+							l.ReturnTypeInference.AddCommonTypeBound (expr.Type);
+							return true;
+						}
+
+						//
+						// Try to optimize simple lambda. Only when optimizations are enabled not to cause
+						// unexpected debugging experience
+						//
+						if (this is ContextualReturn && !ec.IsInProbingMode && ec.Module.Compiler.Settings.Optimize) {
+							l.DirectMethodGroupConversion = expr.CanReduceLambda (l);
+						}
+					}
+				}
+			}
+
+			if (expr == null)
+				return false;
+
+			if (expr.Type != block_return_type && expr.Type != InternalType.ErrorType) {
+				expr = Convert.ImplicitConversionRequired (ec, expr, block_return_type, loc);
+
+				if (expr == null) {
+					if (am != null && block_return_type == ec.ReturnType) {
+						ec.Report.Error (1662, loc,
+							"Cannot convert `{0}' to delegate type `{1}' because some of the return types in the block are not implicitly convertible to the delegate return type",
+							am.ContainerType, am.GetSignatureForError ());
+					}
+					return false;
+				}
+			}
+
+			return true;			
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (expr != null) {
+
+				var async_body = ec.CurrentAnonymousMethod as AsyncInitializer;
+				if (async_body != null) {
+					var storey = (AsyncTaskStorey)async_body.Storey;
+					Label exit_label = async_body.BodyEnd;
+
+					//
+					// It's null for await without async
+					//
+					if (storey.HoistedReturnValue != null) {
+						//
+						// Special case hoisted return value (happens in try/finally scenario)
+						//
+						if (ec.TryFinallyUnwind != null) {
+							if (storey.HoistedReturnValue is VariableReference) {
+								storey.HoistedReturnValue = ec.GetTemporaryField (storey.HoistedReturnValue.Type);
+							}
+
+							exit_label = TryFinally.EmitRedirectedReturn (ec, async_body);
+						}
+
+						var async_return = (IAssignMethod)storey.HoistedReturnValue;
+						async_return.EmitAssign (ec, expr, false, false);
+						ec.EmitEpilogue ();
+					} else {
+						expr.Emit (ec);
+
+						if (ec.TryFinallyUnwind != null)
+							exit_label = TryFinally.EmitRedirectedReturn (ec, async_body);
+					}
+
+					ec.Emit (OpCodes.Leave, exit_label);
+					return;
+				}
+
+				expr.Emit (ec);
+				ec.EmitEpilogue ();
+
+				if (unwind_protect || ec.EmitAccurateDebugInfo)
+					ec.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
+			}
+
+			if (unwind_protect) {
+				ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ());
+			} else if (ec.EmitAccurateDebugInfo) {
+				ec.Emit (OpCodes.Br, ec.CreateReturnLabel ());
+			} else {
+				ec.Emit (OpCodes.Ret);
+			}
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (expr != null)
+				expr.FlowAnalysis (fc);
+
+			base.DoFlowAnalysis (fc);
+			return true;
+		}
+
+		void Error_ReturnFromIterator (ResolveContext rc)
+		{
+			rc.Report.Error (1622, loc,
+				"Cannot return a value from iterators. Use the yield return statement to return a value, or yield break to end the iteration");
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Reachability.CreateUnreachable ();
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Return target = (Return) t;
+			// It's null for simple return;
+			if (expr != null)
+				target.expr = expr.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Goto : ExitStatement
+	{
+		string target;
+		LabeledStatement label;
+		TryFinally try_finally;
+
+		public Goto (string label, Location l)
+		{
+			loc = l;
+			target = label;
+		}
+
+		public string Target {
+			get { return target; }
+		}
+
+		protected override bool IsLocalExit {
+			get {
+				return true;
+			}
+		}
+
+		protected override bool DoResolve (BlockContext bc)
+		{
+			label = bc.CurrentBlock.LookupLabel (target);
+			if (label == null) {
+				Error_UnknownLabel (bc, target, loc);
+				return false;
+			}
+
+			try_finally = bc.CurrentTryBlock as TryFinally;
+
+			CheckExitBoundaries (bc, label.Block);
+
+			return true;
+		}
+
+		public static void Error_UnknownLabel (BlockContext bc, string label, Location loc)
+		{
+			bc.Report.Error (159, loc, "The label `{0}:' could not be found within the scope of the goto statement",
+				label);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (fc.LabelStack == null) {
+				fc.LabelStack = new List<LabeledStatement> ();
+			} else if (fc.LabelStack.Contains (label)) {
+				return true;
+			}
+
+			fc.LabelStack.Add (label);
+			label.Block.ScanGotoJump (label, fc);
+			fc.LabelStack.Remove (label);
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (rc.IsUnreachable)
+				return rc;
+
+			base.MarkReachable (rc);
+
+			if (try_finally != null) {
+				if (try_finally.FinallyBlock.HasReachableClosingBrace) {
+					label.AddGotoReference (rc, false);
+				} else {
+					label.AddGotoReference (rc, true);
+				}
+			} else {
+				label.AddGotoReference (rc, false);
+			}
+
+			return Reachability.CreateUnreachable ();
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			// Nothing to clone
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (label == null)
+				throw new InternalErrorException ("goto emitted before target resolved");
+
+			Label l = label.LabelTarget (ec);
+
+			if (ec.TryFinallyUnwind != null && IsLeavingFinally (label.Block)) {
+				var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
+				l = TryFinally.EmitRedirectedJump (ec, async_body, l, label.Block);
+			}
+
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
+		}
+
+		bool IsLeavingFinally (Block labelBlock)
+		{
+			var b = try_finally.Statement as Block;
+			while (b != null) {
+				if (b == labelBlock)
+					return true;
+
+				b = b.Parent;
+			}
+
+			return false;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class LabeledStatement : Statement {
+		string name;
+		bool defined;
+		bool referenced;
+		bool finalTarget;
+		Label label;
+		Block block;
+		
+		public LabeledStatement (string name, Block block, Location l)
+		{
+			this.name = name;
+			this.block = block;
+			this.loc = l;
+		}
+
+		public Label LabelTarget (EmitContext ec)
+		{
+			if (defined)
+				return label;
+
+			label = ec.DefineLabel ();
+			defined = true;
+			return label;
+		}
+
+		public Block Block {
+			get {
+				return block;
+			}
+		}
+
+		public string Name {
+			get { return name; }
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			var t = (LabeledStatement) target;
+
+			t.block = clonectx.RemapBlockCopy (block);
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			return true;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			LabelTarget (ec);
+			ec.MarkLabel (label);
+
+			if (finalTarget)
+				ec.Emit (OpCodes.Br_S, label);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (!referenced) {
+				fc.Report.Warning (164, 2, loc, "This label has not been referenced");
+			}
+
+			return false;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			if (referenced)
+				rc = new Reachability ();
+
+			return rc;
+		}
+
+		public void AddGotoReference (Reachability rc, bool finalTarget)
+		{
+			if (referenced)
+				return;
+
+			referenced = true;
+			MarkReachable (rc);
+
+			//
+			// Label is final target when goto jumps out of try block with
+			// finally clause. In that case we need leave with target but in C#
+			// terms the label is unreachable. Using finalTarget we emit
+			// explicit label not just marker
+			//
+			if (finalTarget) {
+				this.finalTarget = true;
+				return;
+			}
+
+			block.ScanGotoJump (this);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+	
+
+	/// <summary>
+	///   `goto default' statement
+	/// </summary>
+	public class GotoDefault : SwitchGoto
+	{		
+		public GotoDefault (Location l)
+			: base (l)
+		{
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			if (bc.Switch == null) {
+				Error_GotoCaseRequiresSwitchBlock (bc);
+				return false;
+			}
+
+			bc.Switch.RegisterGotoCase (null, null);
+			base.Resolve (bc);
+
+			return true;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.Switch.DefaultLabel.GetILLabel (ec));
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (!rc.IsUnreachable) {
+				var label = switch_statement.DefaultLabel;
+				if (label.IsUnreachable) {
+					label.MarkReachable (rc);
+					switch_statement.Block.ScanGotoJump (label);
+				}
+			}
+
+			return base.MarkReachable (rc);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   `goto case' statement
+	/// </summary>
+	public class GotoCase : SwitchGoto
+	{
+		Expression expr;
+		
+		public GotoCase (Expression e, Location l)
+			: base (l)
+		{
+			expr = e;
+		}
+
+		public Expression Expr {
+			get {
+ 				return expr;
+			}
+		}
+
+		public SwitchLabel Label { get; set; }
+
+		public override bool Resolve (BlockContext ec)
+		{
+			if (ec.Switch == null) {
+				Error_GotoCaseRequiresSwitchBlock (ec);
+				return false;
+			}
+
+			Constant c = expr.ResolveLabelConstant (ec);
+			if (c == null) {
+				return false;
+			}
+
+			Constant res;
+			if (ec.Switch.IsNullable && c is NullLiteral) {
+				res = c;
+			} else {
+				TypeSpec type = ec.Switch.SwitchType;
+				res = c.Reduce (ec, type);
+				if (res == null) {
+					c.Error_ValueCannotBeConverted (ec, type, true);
+					return false;
+				}
+
+				if (!Convert.ImplicitStandardConversionExists (c, type))
+					ec.Report.Warning (469, 2, loc,
+						"The `goto case' value is not implicitly convertible to type `{0}'",
+						type.GetSignatureForError ());
+
+			}
+
+			ec.Switch.RegisterGotoCase (this, res);
+			base.Resolve (ec);
+			expr = res;
+
+			return true;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, Label.GetILLabel (ec));
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			GotoCase target = (GotoCase) t;
+
+			target.expr = expr.Clone (clonectx);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (!rc.IsUnreachable) {
+				var label = switch_statement.FindLabel ((Constant) expr);
+				if (label.IsUnreachable) {
+					label.MarkReachable (rc);
+					switch_statement.Block.ScanGotoJump (label);
+				}
+			}
+
+			return base.MarkReachable (rc);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public abstract class SwitchGoto : Statement
+	{
+		protected bool unwind_protect;
+		protected Switch switch_statement;
+
+		protected SwitchGoto (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			// Nothing to clone
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			CheckExitBoundaries (bc, bc.Switch.Block);
+
+			unwind_protect = bc.HasAny (ResolveContext.Options.TryScope | ResolveContext.Options.CatchScope);
+			switch_statement = bc.Switch;
+
+			return true;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Reachability.CreateUnreachable ();
+		}
+
+		protected void Error_GotoCaseRequiresSwitchBlock (BlockContext bc)
+		{
+			bc.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
+		}
+	}
+	
+	public class Throw : Statement {
+		Expression expr;
+		
+		public Throw (Expression expr, Location l)
+		{
+			this.expr = expr;
+			loc = l;
+		}
+
+		public Expression Expr {
+			get {
+ 				return this.expr;
+			}
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			if (expr == null) {
+				if (!ec.HasSet (ResolveContext.Options.CatchScope)) {
+					ec.Report.Error (156, loc, "A throw statement with no arguments is not allowed outside of a catch clause");
+				} else if (ec.HasSet (ResolveContext.Options.FinallyScope)) {
+					for (var b = ec.CurrentBlock; b != null && !b.IsCatchBlock; b = b.Parent) {
+						if (b.IsFinallyBlock) {
+							ec.Report.Error (724, loc,
+								"A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
+							break;
+						}
+					}
+				}
+
+				return true;
+			}
+
+			expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
+
+			if (expr == null)
+				return false;
+
+			var et = ec.BuiltinTypes.Exception;
+			if (Convert.ImplicitConversionExists (ec, expr, et))
+				expr = Convert.ImplicitConversion (ec, expr, et, loc);
+			else
+				ec.Report.Error (155, expr.Location, "The type caught or thrown must be derived from System.Exception");
+
+			return true;
+		}
+			
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (expr == null) {
+				var atv = ec.AsyncThrowVariable;
+				if (atv != null) {
+					if (atv.HoistedVariant != null) {
+						atv.HoistedVariant.Emit (ec);
+					} else {
+						atv.Emit (ec);
+					}
+
+					ec.Emit (OpCodes.Throw);
+				} else {
+					ec.Emit (OpCodes.Rethrow);
+				}
+			} else {
+				expr.Emit (ec);
+
+				ec.Emit (OpCodes.Throw);
+			}
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (expr != null)
+				expr.FlowAnalysis (fc);
+
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Reachability.CreateUnreachable ();
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Throw target = (Throw) t;
+
+			if (expr != null)
+				target.expr = expr.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Break : LocalExitStatement
+	{		
+		public Break (Location l)
+			: base (l)
+		{
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			var l = ec.LoopEnd;
+
+			if (ec.TryFinallyUnwind != null) {
+				var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
+				l = TryFinally.EmitRedirectedJump (ec, async_body, l, enclosing_loop.Statement as Block);
+			}
+
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			enclosing_loop.AddEndDefiniteAssignment (fc);
+			return true;
+		}
+
+		protected override bool DoResolve (BlockContext bc)
+		{
+			enclosing_loop = bc.EnclosingLoopOrSwitch;
+			return base.DoResolve (bc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			if (!rc.IsUnreachable)
+				enclosing_loop.SetEndReachable ();
+
+			return Reachability.CreateUnreachable ();
+		}
+	}
+
+	public class Continue : LocalExitStatement
+	{		
+		public Continue (Location l)
+			: base (l)
+		{
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			var l = ec.LoopBegin;
+
+			if (ec.TryFinallyUnwind != null) {
+				var async_body = (AsyncInitializer) ec.CurrentAnonymousMethod;
+				l = TryFinally.EmitRedirectedJump (ec, async_body, l, enclosing_loop.Statement as Block);
+			}
+
+			ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
+		}
+
+		protected override bool DoResolve (BlockContext bc)
+		{
+			enclosing_loop = bc.EnclosingLoop;
+			return base.DoResolve (bc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			if (!rc.IsUnreachable)
+				enclosing_loop.SetIteratorReachable ();
+
+			return Reachability.CreateUnreachable ();
+		}
+	}
+
+	public abstract class LocalExitStatement : ExitStatement
+	{
+		protected LoopStatement enclosing_loop;
+
+		protected LocalExitStatement (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		protected override bool IsLocalExit {
+			get {
+				return true;
+			}
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			// nothing needed.
+		}
+
+		protected override bool DoResolve (BlockContext bc)
+		{
+			if (enclosing_loop == null) {
+				bc.Report.Error (139, loc, "No enclosing loop out of which to break or continue");
+				return false;
+			}
+
+			var block = enclosing_loop.Statement as Block;
+
+			// Don't need to do extra checks for simple statements loops
+			if (block != null) {
+				CheckExitBoundaries (bc, block);
+			}
+
+			return true;
+		}
+	}
+
+	public interface ILocalVariable
+	{
+		void Emit (EmitContext ec);
+		void EmitAssign (EmitContext ec);
+		void EmitAddressOf (EmitContext ec);
+	}
+
+	public interface INamedBlockVariable
+	{
+		Block Block { get; }
+		Expression CreateReferenceExpression (ResolveContext rc, Location loc);
+		bool IsDeclared { get; }
+		bool IsParameter { get; }
+		Location Location { get; }
+	}
+
+	public class BlockVariableDeclarator
+	{
+		LocalVariable li;
+		Expression initializer;
+
+		public BlockVariableDeclarator (LocalVariable li, Expression initializer)
+		{
+			if (li.Type != null)
+				throw new ArgumentException ("Expected null variable type");
+
+			this.li = li;
+			this.initializer = initializer;
+		}
+
+		#region Properties
+
+		public LocalVariable Variable {
+			get {
+				return li;
+			}
+		}
+
+		public Expression Initializer {
+			get {
+				return initializer;
+			}
+			set {
+				initializer = value;
+			}
+		}
+
+		#endregion
+
+		public virtual BlockVariableDeclarator Clone (CloneContext cloneCtx)
+		{
+			var t = (BlockVariableDeclarator) MemberwiseClone ();
+			if (initializer != null)
+				t.initializer = initializer.Clone (cloneCtx);
+
+			return t;
+		}
+	}
+
+	public class BlockVariable : Statement
+	{
+		Expression initializer;
+		protected FullNamedExpression type_expr;
+		protected LocalVariable li;
+		protected List<BlockVariableDeclarator> declarators;
+		TypeSpec type;
+
+		public BlockVariable (FullNamedExpression type, LocalVariable li)
+		{
+			this.type_expr = type;
+			this.li = li;
+			this.loc = type_expr.Location;
+		}
+
+		protected BlockVariable (LocalVariable li)
+		{
+			this.li = li;
+		}
+
+		#region Properties
+
+		public List<BlockVariableDeclarator> Declarators {
+			get {
+				return declarators;
+			}
+		}
+
+		public Expression Initializer {
+			get {
+				return initializer;
+			}
+			set {
+				initializer = value;
+			}
+		}
+
+		public FullNamedExpression TypeExpression {
+			get {
+				return type_expr;
+			}
+		}
+
+		public LocalVariable Variable {
+			get {
+				return li;
+			}
+		}
+
+		#endregion
+
+		public void AddDeclarator (BlockVariableDeclarator decl)
+		{
+			if (declarators == null)
+				declarators = new List<BlockVariableDeclarator> ();
+
+			declarators.Add (decl);
+		}
+
+		static void CreateEvaluatorVariable (BlockContext bc, LocalVariable li)
+		{
+			if (bc.Report.Errors != 0)
+				return;
+
+			var container = bc.CurrentMemberDefinition.Parent.PartialContainer;
+
+			Field f = new Field (container, new TypeExpression (li.Type, li.Location), Modifiers.PUBLIC | Modifiers.STATIC,
+				new MemberName (li.Name, li.Location), null);
+
+			container.AddField (f);
+			f.Define ();
+
+			li.HoistedVariant = new HoistedEvaluatorVariable (f);
+			li.SetIsUsed ();
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			return Resolve (bc, true);
+		}
+
+		public bool Resolve (BlockContext bc, bool resolveDeclaratorInitializers)
+		{
+			if (type == null && !li.IsCompilerGenerated) {
+				var vexpr = type_expr as VarExpr;
+
+				//
+				// C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
+				// same name exists or as a keyword when no type was found
+				//
+				if (vexpr != null && !vexpr.IsPossibleTypeOrNamespace (bc)) {
+					if (bc.Module.Compiler.Settings.Version < LanguageVersion.V_3)
+						bc.Report.FeatureIsNotAvailable (bc.Module.Compiler, loc, "implicitly typed local variable");
+
+					if (li.IsFixed) {
+						bc.Report.Error (821, loc, "A fixed statement cannot use an implicitly typed local variable");
+						return false;
+					}
+
+					if (li.IsConstant) {
+						bc.Report.Error (822, loc, "An implicitly typed local variable cannot be a constant");
+						return false;
+					}
+
+					if (Initializer == null) {
+						bc.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
+						return false;
+					}
+
+					if (declarators != null) {
+						bc.Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
+						declarators = null;
+					}
+
+					Initializer = Initializer.Resolve (bc);
+					if (Initializer != null) {
+						((VarExpr) type_expr).InferType (bc, Initializer);
+						type = type_expr.Type;
+					} else {
+						// Set error type to indicate the var was placed correctly but could
+						// not be infered
+						//
+						// var a = missing ();
+						//
+						type = InternalType.ErrorType;
+					}
+				}
+
+				if (type == null) {
+					type = type_expr.ResolveAsType (bc);
+					if (type == null)
+						return false;
+
+					if (li.IsConstant && !type.IsConstantCompatible) {
+						Const.Error_InvalidConstantType (type, loc, bc.Report);
+					}
+				}
+
+				if (type.IsStatic)
+					FieldBase.Error_VariableOfStaticClass (loc, li.Name, type, bc.Report);
+
+				li.Type = type;
+			}
+
+			bool eval_global = bc.Module.Compiler.Settings.StatementMode && bc.CurrentBlock is ToplevelBlock;
+			if (eval_global) {
+				CreateEvaluatorVariable (bc, li);
+			} else if (type != InternalType.ErrorType) {
+				li.PrepareAssignmentAnalysis (bc);
+			}
+
+			if (initializer != null) {
+				initializer = ResolveInitializer (bc, li, initializer);
+				// li.Variable.DefinitelyAssigned 
+			}
+
+			if (declarators != null) {
+				foreach (var d in declarators) {
+					d.Variable.Type = li.Type;
+					if (eval_global) {
+						CreateEvaluatorVariable (bc, d.Variable);
+					} else if (type != InternalType.ErrorType) {
+						d.Variable.PrepareAssignmentAnalysis (bc);
+					}
+
+					if (d.Initializer != null && resolveDeclaratorInitializers) {
+						d.Initializer = ResolveInitializer (bc, d.Variable, d.Initializer);
+						// d.Variable.DefinitelyAssigned 
+					} 
+				}
+			}
+
+			return true;
+		}
+
+		protected virtual Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
+		{
+			var a = new SimpleAssign (li.CreateReferenceExpression (bc, li.Location), initializer, li.Location);
+			return a.ResolveStatement (bc);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			li.CreateBuilder (ec);
+
+			if (Initializer != null && !IsUnreachable)
+				((ExpressionStatement) Initializer).EmitStatement (ec);
+
+			if (declarators != null) {
+				foreach (var d in declarators) {
+					d.Variable.CreateBuilder (ec);
+					if (d.Initializer != null && !IsUnreachable) {
+						ec.Mark (d.Variable.Location);
+						((ExpressionStatement) d.Initializer).EmitStatement (ec);
+					}
+				}
+			}
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (Initializer != null)
+				Initializer.FlowAnalysis (fc);
+
+			if (declarators != null) {
+				foreach (var d in declarators) {
+					if (d.Initializer != null)
+						d.Initializer.FlowAnalysis (fc);
+				}
+			}
+
+			return false;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			var init = initializer as ExpressionStatement;
+			if (init != null)
+				init.MarkReachable (rc);
+
+			return base.MarkReachable (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			BlockVariable t = (BlockVariable) target;
+
+			if (type_expr != null)
+				t.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
+
+			if (initializer != null)
+				t.initializer = initializer.Clone (clonectx);
+
+			if (declarators != null) {
+				t.declarators = null;
+				foreach (var d in declarators)
+					t.AddDeclarator (d.Clone (clonectx));
+			}
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class BlockConstant : BlockVariable
+	{
+		public BlockConstant (FullNamedExpression type, LocalVariable li)
+			: base (type, li)
+		{
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			// Nothing to emit, not even sequence point
+		}
+
+		protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
+		{
+			initializer = initializer.Resolve (bc);
+			if (initializer == null)
+				return null;
+
+			var c = initializer as Constant;
+			if (c == null) {
+				initializer.Error_ExpressionMustBeConstant (bc, initializer.Location, li.Name);
+				return null;
+			}
+
+			c = c.ConvertImplicitly (li.Type);
+			if (c == null) {
+				if (TypeSpec.IsReferenceType (li.Type))
+					initializer.Error_ConstantCanBeInitializedWithNullOnly (bc, li.Type, initializer.Location, li.Name);
+				else
+					initializer.Error_ValueCannotBeConverted (bc, li.Type, false);
+
+				return null;
+			}
+
+			li.ConstantValue = c;
+			return initializer;
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	//
+	// The information about a user-perceived local variable
+	//
+	public sealed class LocalVariable : INamedBlockVariable, ILocalVariable
+	{
+		[Flags]
+		public enum Flags
+		{
+			Used = 1,
+			IsThis = 1 << 1,
+			AddressTaken = 1 << 2,
+			CompilerGenerated = 1 << 3,
+			Constant = 1 << 4,
+			ForeachVariable = 1 << 5,
+			FixedVariable = 1 << 6,
+			UsingVariable = 1 << 7,
+			IsLocked = 1 << 8,
+
+			ReadonlyMask = ForeachVariable | FixedVariable | UsingVariable
+		}
+
+		TypeSpec type;
+		readonly string name;
+		readonly Location loc;
+		readonly Block block;
+		Flags flags;
+		Constant const_value;
+
+		public VariableInfo VariableInfo;
+		HoistedVariable hoisted_variant;
+
+		LocalBuilder builder;
+
+		public LocalVariable (Block block, string name, Location loc)
+		{
+			this.block = block;
+			this.name = name;
+			this.loc = loc;
+		}
+
+		public LocalVariable (Block block, string name, Flags flags, Location loc)
+			: this (block, name, loc)
+		{
+			this.flags = flags;
+		}
+
+		//
+		// Used by variable declarators
+		//
+		public LocalVariable (LocalVariable li, string name, Location loc)
+			: this (li.block, name, li.flags, loc)
+		{
+		}
+
+		#region Properties
+
+		public bool AddressTaken {
+			get {
+				return (flags & Flags.AddressTaken) != 0;
+			}
+		}
+
+		public Block Block {
+			get {
+				return block;
+			}
+		}
+
+		public Constant ConstantValue {
+			get {
+				return const_value;
+			}
+			set {
+				const_value = value;
+			}
+		}
+
+		//
+		// Hoisted local variable variant
+		//
+		public HoistedVariable HoistedVariant {
+			get {
+				return hoisted_variant;
+			}
+			set {
+				hoisted_variant = value;
+			}
+		}
+
+		public bool IsDeclared {
+			get {
+				return type != null;
+			}
+		}
+
+		public bool IsCompilerGenerated {
+			get {
+				return (flags & Flags.CompilerGenerated) != 0;
+			}
+		}
+
+		public bool IsConstant {
+			get {
+				return (flags & Flags.Constant) != 0;
+			}
+		}
+
+		public bool IsLocked {
+			get {
+				return (flags & Flags.IsLocked) != 0;
+			}
+			set {
+				flags = value ? flags | Flags.IsLocked : flags & ~Flags.IsLocked;
+			}
+		}
+
+		public bool IsThis {
+			get {
+				return (flags & Flags.IsThis) != 0;
+			}
+		}
+
+		public bool IsFixed {
+			get {
+				return (flags & Flags.FixedVariable) != 0;
+			}
+		}
+
+		bool INamedBlockVariable.IsParameter {
+			get {
+				return false;
+			}
+		}
+
+		public bool IsReadonly {
+			get {
+				return (flags & Flags.ReadonlyMask) != 0;
+			}
+		}
+
+		public Location Location {
+			get {
+				return loc;
+			}
+		}
+
+		public string Name {
+			get {
+				return name;
+			}
+		}
+
+		public TypeSpec Type {
+		    get {
+				return type;
+			}
+		    set {
+				type = value;
+			}
+		}
+
+		#endregion
+
+		public void CreateBuilder (EmitContext ec)
+		{
+			if ((flags & Flags.Used) == 0) {
+				if (VariableInfo == null) {
+					// Missing flow analysis or wrong variable flags
+					throw new InternalErrorException ("VariableInfo is null and the variable `{0}' is not used", name);
+				}
+
+				if (VariableInfo.IsEverAssigned)
+					ec.Report.Warning (219, 3, Location, "The variable `{0}' is assigned but its value is never used", Name);
+				else
+					ec.Report.Warning (168, 3, Location, "The variable `{0}' is declared but never used", Name);
+			}
+
+			if (HoistedVariant != null)
+				return;
+
+			if (builder != null) {
+				if ((flags & Flags.CompilerGenerated) != 0)
+					return;
+
+				// To avoid Used warning duplicates
+				throw new InternalErrorException ("Already created variable `{0}'", name);
+			}
+
+			//
+			// All fixed variabled are pinned, a slot has to be alocated
+			//
+			builder = ec.DeclareLocal (Type, IsFixed);
+			if (!ec.HasSet (BuilderContext.Options.OmitDebugInfo) && (flags & Flags.CompilerGenerated) == 0)
+				ec.DefineLocalVariable (name, builder);
+		}
+
+		public static LocalVariable CreateCompilerGenerated (TypeSpec type, Block block, Location loc)
+		{
+			LocalVariable li = new LocalVariable (block, GetCompilerGeneratedName (block), Flags.CompilerGenerated | Flags.Used, loc);
+			li.Type = type;
+			return li;
+		}
+
+		public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
+		{
+			if (IsConstant && const_value != null)
+				return Constant.CreateConstantFromValue (Type, const_value.GetValue (), loc);
+
+			return new LocalVariableReference (this, loc);
+		}
+
+		public void Emit (EmitContext ec)
+		{
+			// TODO: Need something better for temporary variables
+			if ((flags & Flags.CompilerGenerated) != 0)
+				CreateBuilder (ec);
+
+			ec.Emit (OpCodes.Ldloc, builder);
+		}
+
+		public void EmitAssign (EmitContext ec)
+		{
+			// TODO: Need something better for temporary variables
+			if ((flags & Flags.CompilerGenerated) != 0)
+				CreateBuilder (ec);
+
+			ec.Emit (OpCodes.Stloc, builder);
+		}
+
+		public void EmitAddressOf (EmitContext ec)
+		{
+			// TODO: Need something better for temporary variables
+			if ((flags & Flags.CompilerGenerated) != 0)
+				CreateBuilder (ec);
+
+			ec.Emit (OpCodes.Ldloca, builder);
+		}
+
+		public static string GetCompilerGeneratedName (Block block)
+		{
+			// HACK: Debugger depends on the name semantics
+			return "$locvar" + block.ParametersBlock.TemporaryLocalsCount++.ToString ("X");
+		}
+
+		public string GetReadOnlyContext ()
+		{
+			switch (flags & Flags.ReadonlyMask) {
+			case Flags.FixedVariable:
+				return "fixed variable";
+			case Flags.ForeachVariable:
+				return "foreach iteration variable";
+			case Flags.UsingVariable:
+				return "using variable";
+			}
+
+			throw new InternalErrorException ("Variable is not readonly");
+		}
+
+		public bool IsThisAssigned (FlowAnalysisContext fc, Block block)
+		{
+			if (VariableInfo == null)
+				throw new Exception ();
+
+			if (IsAssigned (fc))
+				return true;
+
+			return VariableInfo.IsFullyInitialized (fc, block.StartLocation);
+		}
+
+		public bool IsAssigned (FlowAnalysisContext fc)
+		{
+			return fc.IsDefinitelyAssigned (VariableInfo);
+		}
+
+		public void PrepareAssignmentAnalysis (BlockContext bc)
+		{
+			//
+			// No need to run assignment analysis for these guys
+			//
+			if ((flags & (Flags.Constant | Flags.ReadonlyMask | Flags.CompilerGenerated)) != 0)
+				return;
+
+			VariableInfo = VariableInfo.Create (bc, this);
+		}
+
+		//
+		// Mark the variables as referenced in the user code
+		//
+		public void SetIsUsed ()
+		{
+			flags |= Flags.Used;
+		}
+
+		public void SetHasAddressTaken ()
+		{
+			flags |= (Flags.AddressTaken | Flags.Used);
+		}
+
+		public override string ToString ()
+		{
+			return string.Format ("LocalInfo ({0},{1},{2},{3})", name, type, VariableInfo, Location);
+		}
+	}
+
+	/// <summary>
+	///   Block represents a C# block.
+	/// </summary>
+	///
+	/// <remarks>
+	///   This class is used in a number of places: either to represent
+	///   explicit blocks that the programmer places or implicit blocks.
+	///
+	///   Implicit blocks are used as labels or to introduce variable
+	///   declarations.
+	///
+	///   Top-level blocks derive from Block, and they are called ToplevelBlock
+	///   they contain extra information that is not necessary on normal blocks.
+	/// </remarks>
+	public class Block : Statement {
+		[Flags]
+		public enum Flags
+		{
+			Unchecked = 1,
+			ReachableEnd = 8,
+			Unsafe = 16,
+			HasCapturedVariable = 64,
+			HasCapturedThis = 1 << 7,
+			IsExpressionTree = 1 << 8,
+			CompilerGenerated = 1 << 9,
+			HasAsyncModifier = 1 << 10,
+			Resolved = 1 << 11,
+			YieldBlock = 1 << 12,
+			AwaitBlock = 1 << 13,
+			FinallyBlock = 1 << 14,
+			CatchBlock = 1 << 15,
+			Iterator = 1 << 20,
+			NoFlowAnalysis = 1 << 21,
+			InitializationEmitted = 1 << 22
+		}
+
+		public Block Parent;
+		public Location StartLocation;
+		public Location EndLocation;
+
+		public ExplicitBlock Explicit;
+		public ParametersBlock ParametersBlock;
+
+		protected Flags flags;
+
+		//
+		// The statements in this block
+		//
+		protected List<Statement> statements;
+
+		protected List<Statement> scope_initializers;
+
+		int? resolving_init_idx;
+
+		Block original;
+
+#if DEBUG
+		static int id;
+		public int ID = id++;
+
+		static int clone_id_counter;
+		int clone_id;
+#endif
+
+//		int assignable_slots;
+
+		public Block (Block parent, Location start, Location end)
+			: this (parent, 0, start, end)
+		{
+		}
+
+		public Block (Block parent, Flags flags, Location start, Location end)
+		{
+			if (parent != null) {
+				// the appropriate constructors will fixup these fields
+				ParametersBlock = parent.ParametersBlock;
+				Explicit = parent.Explicit;
+			}
+			
+			this.Parent = parent;
+			this.flags = flags;
+			this.StartLocation = start;
+			this.EndLocation = end;
+			this.loc = start;
+			statements = new List<Statement> (4);
+
+			this.original = this;
+		}
+
+		#region Properties
+
+		public Block Original {
+			get {
+				return original;
+			}
+			protected set {
+				original = value;
+			}
+		}
+
+		public bool IsCompilerGenerated {
+			get { return (flags & Flags.CompilerGenerated) != 0; }
+			set { flags = value ? flags | Flags.CompilerGenerated : flags & ~Flags.CompilerGenerated; }
+		}
+
+
+		public bool IsCatchBlock {
+			get {
+				return (flags & Flags.CatchBlock) != 0;
+			}
+		}
+
+		public bool IsFinallyBlock {
+			get {
+				return (flags & Flags.FinallyBlock) != 0;
+			}
+		}
+
+		public bool Unchecked {
+			get { return (flags & Flags.Unchecked) != 0; }
+			set { flags = value ? flags | Flags.Unchecked : flags & ~Flags.Unchecked; }
+		}
+
+		public bool Unsafe {
+			get { return (flags & Flags.Unsafe) != 0; }
+			set { flags |= Flags.Unsafe; }
+		}
+
+		public List<Statement> Statements {
+			get { return statements; }
+		}
+
+		#endregion
+
+		public void SetEndLocation (Location loc)
+		{
+			EndLocation = loc;
+		}
+
+		public void AddLabel (LabeledStatement target)
+		{
+			ParametersBlock.TopBlock.AddLabel (target.Name, target);
+		}
+
+		public void AddLocalName (LocalVariable li)
+		{
+			AddLocalName (li.Name, li);
+		}
+
+		public void AddLocalName (string name, INamedBlockVariable li)
+		{
+			ParametersBlock.TopBlock.AddLocalName (name, li, false);
+		}
+
+		public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
+		{
+			if (reason == null) {
+				Error_AlreadyDeclared (name, variable);
+				return;
+			}
+
+			ParametersBlock.TopBlock.Report.Error (136, variable.Location,
+				"A local variable named `{0}' cannot be declared in this scope because it would give a different meaning " +
+				"to `{0}', which is already used in a `{1}' scope to denote something else",
+				name, reason);
+		}
+
+		public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable)
+		{
+			var pi = variable as ParametersBlock.ParameterInfo;
+			if (pi != null) {
+				pi.Parameter.Error_DuplicateName (ParametersBlock.TopBlock.Report);
+			} else {
+				ParametersBlock.TopBlock.Report.Error (128, variable.Location,
+					"A local variable named `{0}' is already defined in this scope", name);
+			}
+		}
+					
+		public virtual void Error_AlreadyDeclaredTypeParameter (string name, Location loc)
+		{
+			ParametersBlock.TopBlock.Report.Error (412, loc,
+				"The type parameter name `{0}' is the same as local variable or parameter name",
+				name);
+		}
+
+		//
+		// It should be used by expressions which require to
+		// register a statement during resolve process.
+		//
+		public void AddScopeStatement (Statement s)
+		{
+			if (scope_initializers == null)
+				scope_initializers = new List<Statement> ();
+
+			//
+			// Simple recursive helper, when resolve scope initializer another
+			// new scope initializer can be added, this ensures it's initialized
+			// before existing one. For now this can happen with expression trees
+			// in base ctor initializer only
+			//
+			if (resolving_init_idx.HasValue) {
+				scope_initializers.Insert (resolving_init_idx.Value, s);
+				++resolving_init_idx;
+			} else {
+				scope_initializers.Add (s);
+			}
+		}
+
+		public void InsertStatement (int index, Statement s)
+		{
+			statements.Insert (index, s);
+		}
+		
+		public void AddStatement (Statement s)
+		{
+			statements.Add (s);
+		}
+
+		public LabeledStatement LookupLabel (string name)
+		{
+			return ParametersBlock.GetLabel (name, this);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (rc.IsUnreachable)
+				return rc;
+
+			MarkReachableScope (rc);
+
+			foreach (var s in statements) {
+				rc = s.MarkReachable (rc);
+				if (rc.IsUnreachable) {
+					if ((flags & Flags.ReachableEnd) != 0)
+						return new Reachability ();
+
+					return rc;
+				}
+			}
+
+			flags |= Flags.ReachableEnd;
+
+			return rc;
+		}
+
+		public void MarkReachableScope (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			if (scope_initializers != null) {
+				foreach (var si in scope_initializers)
+					si.MarkReachable (rc);
+			}
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			if ((flags & Flags.Resolved) != 0)
+				return true;
+
+			Block prev_block = bc.CurrentBlock;
+			bc.CurrentBlock = this;
+
+			//
+			// Compiler generated scope statements
+			//
+			if (scope_initializers != null) {
+				for (resolving_init_idx = 0; resolving_init_idx < scope_initializers.Count; ++resolving_init_idx) {
+					scope_initializers[resolving_init_idx.Value].Resolve (bc);
+				}
+
+				resolving_init_idx = null;
+			}
+
+			bool ok = true;
+			int statement_count = statements.Count;
+			for (int ix = 0; ix < statement_count; ix++){
+				Statement s = statements [ix];
+
+				if (!s.Resolve (bc)) {
+					ok = false;
+					if (!bc.IsInProbingMode)
+						statements [ix] = new EmptyStatement (s.loc);
+
+					continue;
+				}
+			}
+
+			bc.CurrentBlock = prev_block;
+
+			flags |= Flags.Resolved;
+			return ok;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			for (int ix = 0; ix < statements.Count; ix++){
+				statements [ix].Emit (ec);
+			}
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (scope_initializers != null)
+				EmitScopeInitializers (ec);
+
+			DoEmit (ec);
+		}
+
+		protected void EmitScopeInitializers (EmitContext ec)
+		{
+			foreach (Statement s in scope_initializers)
+				s.Emit (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (scope_initializers != null) {
+				foreach (var si in scope_initializers)
+					si.FlowAnalysis (fc);
+			}
+
+			return DoFlowAnalysis (fc, 0);	
+		}
+
+		bool DoFlowAnalysis (FlowAnalysisContext fc, int startIndex)
+		{
+			bool end_unreachable = !reachable;
+			for (; startIndex < statements.Count; ++startIndex) {
+				var s = statements[startIndex];
+
+				end_unreachable = s.FlowAnalysis (fc);
+				if (s.IsUnreachable) {
+					statements [startIndex] = RewriteUnreachableStatement (s);
+					continue;
+				}
+
+				//
+				// Statement end reachability is needed mostly due to goto support. Consider
+				//
+				// if (cond) {
+				//    goto X;
+				// } else {
+				//    goto Y;
+				// }
+				// X:
+				//
+				// X label is reachable only via goto not as another statement after if. We need
+				// this for flow-analysis only to carry variable info correctly.
+				//
+				if (end_unreachable) {
+					for (++startIndex; startIndex < statements.Count; ++startIndex) {
+						s = statements[startIndex];
+						if (s is SwitchLabel) {
+							s.FlowAnalysis (fc);
+							break;
+						}
+
+						if (s.IsUnreachable) {
+							s.FlowAnalysis (fc);
+							statements [startIndex] = RewriteUnreachableStatement (s);
+						}
+					}
+				}
+			}
+
+			//
+			// The condition should be true unless there is forward jumping goto
+			// 
+			// if (this is ExplicitBlock && end_unreachable != Explicit.HasReachableClosingBrace)
+			//	Debug.Fail ();
+
+			return !Explicit.HasReachableClosingBrace;
+		}
+
+		static Statement RewriteUnreachableStatement (Statement s)
+		{
+			// LAMESPEC: It's not clear whether declararion statement should be part of reachability
+			// analysis. Even csc report unreachable warning for it but it's actually used hence
+			// we try to emulate this behaviour
+			//
+			// Consider:
+			// 	goto L;
+			//	int v;
+			// L:
+			//	v = 1;
+
+			if (s is BlockVariable)
+				return s;
+
+			return new EmptyStatement (s.loc);
+		}
+
+		public void ScanGotoJump (Statement label)
+		{
+			int i;
+			for (i = 0; i < statements.Count; ++i) {
+				if (statements[i] == label)
+					break;
+			}
+
+			var rc = new Reachability ();
+			for (++i; i < statements.Count; ++i) {
+				var s = statements[i];
+				rc = s.MarkReachable (rc);
+				if (rc.IsUnreachable)
+					return;
+			}
+
+			flags |= Flags.ReachableEnd;
+		}
+
+		public void ScanGotoJump (Statement label, FlowAnalysisContext fc)
+		{
+			int i;
+			for (i = 0; i < statements.Count; ++i) {
+				if (statements[i] == label)
+					break;
+			}
+
+			DoFlowAnalysis (fc, ++i);
+		}
+
+#if DEBUG
+		public override string ToString ()
+		{
+			return String.Format ("{0}: ID={1} Clone={2} Location={3}", GetType (), ID, clone_id != 0, StartLocation);
+		}
+#endif
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Block target = (Block) t;
+#if DEBUG
+			target.clone_id = ++clone_id_counter;
+#endif
+
+			clonectx.AddBlockMap (this, target);
+			if (original != this)
+				clonectx.AddBlockMap (original, target);
+
+			target.ParametersBlock = (ParametersBlock) (ParametersBlock == this ? target : clonectx.RemapBlockCopy (ParametersBlock));
+			target.Explicit = (ExplicitBlock) (Explicit == this ? target : clonectx.LookupBlock (Explicit));
+
+			if (Parent != null)
+				target.Parent = clonectx.RemapBlockCopy (Parent);
+
+			target.statements = new List<Statement> (statements.Count);
+			foreach (Statement s in statements)
+				target.statements.Add (s.Clone (clonectx));
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class ExplicitBlock : Block
+	{
+		protected AnonymousMethodStorey am_storey;
+
+		public ExplicitBlock (Block parent, Location start, Location end)
+			: this (parent, (Flags) 0, start, end)
+		{
+		}
+
+		public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
+			: base (parent, flags, start, end)
+		{
+			this.Explicit = this;
+		}
+
+		#region Properties
+
+		public AnonymousMethodStorey AnonymousMethodStorey {
+			get {
+				return am_storey;
+			}
+		}
+
+		public bool HasAwait {
+			get {
+				return (flags & Flags.AwaitBlock) != 0;
+			}
+		}
+
+		public bool HasCapturedThis {
+			set {
+				flags = value ? flags | Flags.HasCapturedThis : flags & ~Flags.HasCapturedThis;
+			}
+			get {
+				return (flags & Flags.HasCapturedThis) != 0;
+			}
+		}
+
+		//
+		// Used to indicate that the block has reference to parent
+		// block and cannot be made static when defining anonymous method
+		//
+		public bool HasCapturedVariable {
+			set {
+				flags = value ? flags | Flags.HasCapturedVariable : flags & ~Flags.HasCapturedVariable;
+			}
+			get {
+				return (flags & Flags.HasCapturedVariable) != 0;
+			}
+		}
+
+		public bool HasReachableClosingBrace {
+		    get {
+		        return (flags & Flags.ReachableEnd) != 0;
+		    }
+			set {
+				flags = value ? flags | Flags.ReachableEnd : flags & ~Flags.ReachableEnd;
+			}
+		}
+
+		public bool HasYield {
+			get {
+				return (flags & Flags.YieldBlock) != 0;
+			}
+		}
+
+		#endregion
+
+		//
+		// Creates anonymous method storey in current block
+		//
+		public AnonymousMethodStorey CreateAnonymousMethodStorey (ResolveContext ec)
+		{
+			//
+			// Return same story for iterator and async blocks unless we are
+			// in nested anonymous method
+			//
+			if (ec.CurrentAnonymousMethod is StateMachineInitializer && ParametersBlock.Original == ec.CurrentAnonymousMethod.Block.Original)
+				return ec.CurrentAnonymousMethod.Storey;
+
+			if (am_storey == null) {
+				MemberBase mc = ec.MemberContext as MemberBase;
+
+				//
+				// Creates anonymous method storey for this block
+				//
+				am_storey = new AnonymousMethodStorey (this, ec.CurrentMemberDefinition.Parent.PartialContainer, mc, ec.CurrentTypeParameters, "AnonStorey", MemberKind.Class);
+			}
+
+			return am_storey;
+		}
+
+		public void EmitScopeInitialization (EmitContext ec)
+		{
+			if ((flags & Flags.InitializationEmitted) != 0)
+				return;
+
+			if (am_storey != null) {
+				DefineStoreyContainer (ec, am_storey);
+				am_storey.EmitStoreyInstantiation (ec, this);
+			}
+
+			if (scope_initializers != null)
+				EmitScopeInitializers (ec);
+
+			flags |= Flags.InitializationEmitted;
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			EmitScopeInitialization (ec);
+
+			if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated && ec.Mark (StartLocation)) {
+				ec.Emit (OpCodes.Nop);
+			}
+
+			if (Parent != null)
+				ec.BeginScope ();
+
+			DoEmit (ec);
+
+			if (Parent != null)
+				ec.EndScope ();
+
+			if (ec.EmitAccurateDebugInfo && HasReachableClosingBrace && !(this is ParametersBlock) &&
+				!IsCompilerGenerated && ec.Mark (EndLocation)) {
+				ec.Emit (OpCodes.Nop);
+			}
+		}
+
+		protected void DefineStoreyContainer (EmitContext ec, AnonymousMethodStorey storey)
+		{
+			if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null) {
+				storey.SetNestedStoryParent (ec.CurrentAnonymousMethod.Storey);
+				storey.Mutator = ec.CurrentAnonymousMethod.Storey.Mutator;
+			}
+
+			//
+			// Creates anonymous method storey
+			//
+			storey.CreateContainer ();
+			storey.DefineContainer ();
+
+			if (Original.Explicit.HasCapturedThis && Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock != null) {
+
+				//
+				// Only first storey in path will hold this reference. All children blocks will
+				// reference it indirectly using $ref field
+				//
+				for (Block b = Original.Explicit; b != null; b = b.Parent) {
+					if (b.Parent != null) {
+						var s = b.Parent.Explicit.AnonymousMethodStorey;
+						if (s != null) {
+							storey.HoistedThis = s.HoistedThis;
+							break;
+						}
+					}
+
+					if (b.Explicit == b.Explicit.ParametersBlock && b.Explicit.ParametersBlock.StateMachine != null) {
+						if (storey.HoistedThis == null)
+							storey.HoistedThis = b.Explicit.ParametersBlock.StateMachine.HoistedThis;
+
+						if (storey.HoistedThis != null)
+							break;
+					}
+				}
+				
+				//
+				// We are the first storey on path and 'this' has to be hoisted
+				//
+				if (storey.HoistedThis == null) {
+					foreach (ExplicitBlock ref_block in Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock) {
+						//
+						// ThisReferencesFromChildrenBlock holds all reference even if they
+						// are not on this path. It saves some memory otherwise it'd have to
+						// be in every explicit block. We run this check to see if the reference
+						// is valid for this storey
+						//
+						Block block_on_path = ref_block;
+						for (; block_on_path != null && block_on_path != Original; block_on_path = block_on_path.Parent);
+
+						if (block_on_path == null)
+							continue;
+
+						if (storey.HoistedThis == null) {
+							storey.AddCapturedThisField (ec, null);
+						}
+
+						for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
+							ParametersBlock pb;
+							AnonymousMethodStorey b_storey = b.AnonymousMethodStorey;
+
+							if (b_storey != null) {
+								//
+								// Don't add storey cross reference for `this' when the storey ends up not
+								// beeing attached to any parent
+								//
+								if (b.ParametersBlock.StateMachine == null) {
+									AnonymousMethodStorey s = null;
+									for (Block ab = b.AnonymousMethodStorey.OriginalSourceBlock.Parent; ab != null; ab = ab.Parent) {
+										s = ab.Explicit.AnonymousMethodStorey;
+										if (s != null)
+											break;
+									}
+
+									// Needs to be in sync with AnonymousMethodBody::DoCreateMethodHost
+									if (s == null) {
+										var parent = storey == null || storey.Kind == MemberKind.Struct ? null : storey;
+										b.AnonymousMethodStorey.AddCapturedThisField (ec, parent);
+										break;
+									}
+
+								}
+
+								//
+								// Stop propagation inside same top block
+								//
+								if (b.ParametersBlock == ParametersBlock.Original) {
+									b_storey.AddParentStoreyReference (ec, storey);
+//									b_storey.HoistedThis = storey.HoistedThis;
+									break;
+								}
+
+								b = pb = b.ParametersBlock;
+							} else {
+								pb = b as ParametersBlock;
+							}
+
+							if (pb != null && pb.StateMachine != null) {
+								if (pb.StateMachine == storey)
+									break;
+
+								//
+								// If we are state machine with no parent. We can hook into parent without additional
+ 								// reference and capture this directly
+								//
+								ExplicitBlock parent_storey_block = pb;
+								while (parent_storey_block.Parent != null) {
+									parent_storey_block = parent_storey_block.Parent.Explicit;
+									if (parent_storey_block.AnonymousMethodStorey != null) {
+										break;
+									}
+								}
+
+								if (parent_storey_block.AnonymousMethodStorey == null) {
+									pb.StateMachine.AddCapturedThisField (ec, null);
+									b.HasCapturedThis = true;
+									continue;
+								}
+
+								pb.StateMachine.AddParentStoreyReference (ec, storey);
+							}
+
+							//
+							// Add parent storey reference only when this is not captured directly
+							//
+							if (b_storey != null) {
+								b_storey.AddParentStoreyReference (ec, storey);
+								b_storey.HoistedThis = storey.HoistedThis;
+							}
+						}
+					}
+				}
+			}
+
+			var ref_blocks = storey.ReferencesFromChildrenBlock;
+			if (ref_blocks != null) {
+				foreach (ExplicitBlock ref_block in ref_blocks) {
+					for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
+						if (b.AnonymousMethodStorey != null) {
+							b.AnonymousMethodStorey.AddParentStoreyReference (ec, storey);
+
+							//
+							// Stop propagation inside same top block
+							//
+							if (b.ParametersBlock == ParametersBlock.Original)
+								break;
+
+							b = b.ParametersBlock;
+						}
+
+						var pb = b as ParametersBlock;
+						if (pb != null && pb.StateMachine != null) {
+							if (pb.StateMachine == storey)
+								break;
+
+							pb.StateMachine.AddParentStoreyReference (ec, storey);
+						}
+
+						b.HasCapturedVariable = true;
+					}
+				}
+			}
+
+			storey.Define ();
+			storey.PrepareEmit ();
+			storey.Parent.PartialContainer.AddCompilerGeneratedClass (storey);
+		}
+
+		public void RegisterAsyncAwait ()
+		{
+			var block = this;
+			while ((block.flags & Flags.AwaitBlock) == 0) {
+				block.flags |= Flags.AwaitBlock;
+
+				if (block is ParametersBlock)
+					return;
+
+				block = block.Parent.Explicit;
+			}
+		}
+
+		public void RegisterIteratorYield ()
+		{
+			ParametersBlock.TopBlock.IsIterator = true;
+
+			var block = this;
+			while ((block.flags & Flags.YieldBlock) == 0) {
+				block.flags |= Flags.YieldBlock;
+
+				if (block.Parent == null)
+					return;
+
+				block = block.Parent.Explicit;
+			}
+		}
+
+		public void SetCatchBlock ()
+		{
+			flags |= Flags.CatchBlock;
+		}
+
+		public void SetFinallyBlock ()
+		{
+			flags |= Flags.FinallyBlock;
+		}
+
+		public void WrapIntoDestructor (TryFinally tf, ExplicitBlock tryBlock)
+		{
+			tryBlock.statements = statements;
+			statements = new List<Statement> (1);
+			statements.Add (tf);
+		}
+	}
+
+	//
+	// ParametersBlock was introduced to support anonymous methods
+	// and lambda expressions
+	// 
+	public class ParametersBlock : ExplicitBlock
+	{
+		public class ParameterInfo : INamedBlockVariable
+		{
+			readonly ParametersBlock block;
+			readonly int index;
+			public VariableInfo VariableInfo;
+			bool is_locked;
+
+			public ParameterInfo (ParametersBlock block, int index)
+			{
+				this.block = block;
+				this.index = index;
+			}
+
+			#region Properties
+
+			public ParametersBlock Block {
+				get {
+					return block;
+				}
+			}
+
+			Block INamedBlockVariable.Block {
+				get {
+					return block;
+				}
+			}
+
+			public bool IsDeclared {
+				get {
+					return true;
+				}
+			}
+
+			public bool IsParameter {
+				get {
+					return true;
+				}
+			}
+
+			public bool IsLocked {
+				get {
+					return is_locked;
+				}
+				set {
+					is_locked = value;
+				}
+			}
+
+			public Location Location {
+				get {
+					return Parameter.Location;
+				}
+			}
+
+			public Parameter Parameter {
+				get {
+					return block.Parameters [index];
+				}
+			}
+
+			public TypeSpec ParameterType {
+				get {
+					return Parameter.Type;
+				}
+			}
+
+			#endregion
+
+			public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
+			{
+				return new ParameterReference (this, loc);
+			}
+		}
+
+		// 
+		// Block is converted into an expression
+		//
+		sealed class BlockScopeExpression : Expression
+		{
+			Expression child;
+			readonly ParametersBlock block;
+
+			public BlockScopeExpression (Expression child, ParametersBlock block)
+			{
+				this.child = child;
+				this.block = block;
+			}
+
+			public override bool ContainsEmitWithAwait ()
+			{
+				return child.ContainsEmitWithAwait ();
+			}
+
+			public override Expression CreateExpressionTree (ResolveContext ec)
+			{
+				throw new NotSupportedException ();
+			}
+
+			protected override Expression DoResolve (ResolveContext ec)
+			{
+				if (child == null)
+					return null;
+
+				child = child.Resolve (ec);
+				if (child == null)
+					return null;
+
+				eclass = child.eclass;
+				type = child.Type;
+				return this;
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				block.EmitScopeInitializers (ec);
+				child.Emit (ec);
+			}
+		}
+
+		protected ParametersCompiled parameters;
+		protected ParameterInfo[] parameter_info;
+		protected bool resolved;
+		protected ToplevelBlock top_block;
+		protected StateMachine state_machine;
+		protected Dictionary<string, object> labels;
+
+		public ParametersBlock (Block parent, ParametersCompiled parameters, Location start, Flags flags = 0)
+			: base (parent, 0, start, start)
+		{
+			if (parameters == null)
+				throw new ArgumentNullException ("parameters");
+
+			this.parameters = parameters;
+			ParametersBlock = this;
+
+			this.flags |= flags | (parent.ParametersBlock.flags & (Flags.YieldBlock | Flags.AwaitBlock));
+
+			this.top_block = parent.ParametersBlock.top_block;
+			ProcessParameters ();
+		}
+
+		protected ParametersBlock (ParametersCompiled parameters, Location start)
+			: base (null, 0, start, start)
+		{
+			if (parameters == null)
+				throw new ArgumentNullException ("parameters");
+
+			this.parameters = parameters;
+			ParametersBlock = this;
+		}
+
+		//
+		// It's supposed to be used by method body implementation of anonymous methods
+		//
+		protected ParametersBlock (ParametersBlock source, ParametersCompiled parameters)
+			: base (null, 0, source.StartLocation, source.EndLocation)
+		{
+			this.parameters = parameters;
+			this.statements = source.statements;
+			this.scope_initializers = source.scope_initializers;
+
+			this.resolved = true;
+			this.reachable = source.reachable;
+			this.am_storey = source.am_storey;
+			this.state_machine = source.state_machine;
+			this.flags = source.flags & Flags.ReachableEnd;
+
+			ParametersBlock = this;
+
+			//
+			// Overwrite original for comparison purposes when linking cross references
+			// between anonymous methods
+			//
+			Original = source.Original;
+		}
+
+		#region Properties
+
+		public bool IsAsync {
+			get {
+				return (flags & Flags.HasAsyncModifier) != 0;
+			}
+			set {
+				flags = value ? flags | Flags.HasAsyncModifier : flags & ~Flags.HasAsyncModifier;
+			}
+		}
+
+		//
+		// Block has been converted to expression tree
+		//
+		public bool IsExpressionTree {
+			get {
+				return (flags & Flags.IsExpressionTree) != 0;
+			}
+		}
+
+		//
+		// The parameters for the block.
+		//
+		public ParametersCompiled Parameters {
+			get {
+				return parameters;
+			}
+		}
+
+		public StateMachine StateMachine {
+			get {
+				return state_machine;
+			}
+		}
+
+		public ToplevelBlock TopBlock {
+			get {
+				return top_block;
+			}
+			set {
+				top_block = value;
+			}
+		}
+
+		public bool Resolved {
+			get {
+				return (flags & Flags.Resolved) != 0;
+			}
+		}
+
+		public int TemporaryLocalsCount { get; set; }
+
+		#endregion
+
+		//
+		// Checks whether all `out' parameters have been assigned.
+		//
+		public void CheckControlExit (FlowAnalysisContext fc)
+		{
+			CheckControlExit (fc, fc.DefiniteAssignment);
+		}
+
+		public virtual void CheckControlExit (FlowAnalysisContext fc, DefiniteAssignmentBitSet dat)
+		{
+			if (parameter_info == null)
+				return;
+
+			foreach (var p in parameter_info) {
+				if (p.VariableInfo == null)
+					continue;
+
+				if (p.VariableInfo.IsAssigned (dat))
+					continue;
+
+				fc.Report.Error (177, p.Location,
+					"The out parameter `{0}' must be assigned to before control leaves the current method",
+					p.Parameter.Name);
+			}					
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			base.CloneTo (clonectx, t);
+
+			var target = (ParametersBlock) t;
+
+			//
+			// Clone label statements as well as they contain block reference
+			//
+			var pb = this;
+			while (true) {
+				if (pb.labels != null) {
+					target.labels = new Dictionary<string, object> ();
+
+					foreach (var entry in pb.labels) {
+						var list = entry.Value as List<LabeledStatement>;
+
+						if (list != null) {
+							var list_clone = new List<LabeledStatement> ();
+							foreach (var lentry in list) {
+								list_clone.Add (RemapLabeledStatement (lentry, lentry.Block, clonectx.RemapBlockCopy (lentry.Block)));
+							}
+
+							target.labels.Add (entry.Key, list_clone);
+						} else {
+							var labeled = (LabeledStatement) entry.Value;
+							target.labels.Add (entry.Key, RemapLabeledStatement (labeled, labeled.Block, clonectx.RemapBlockCopy (labeled.Block)));
+						}
+					}
+
+					break;
+				}
+
+				if (pb.Parent == null)
+					break;
+
+				pb = pb.Parent.ParametersBlock;
+			}
+		}
+
+		public override Expression CreateExpressionTree (ResolveContext ec)
+		{
+			if (statements.Count == 1) {
+				Expression expr = statements[0].CreateExpressionTree (ec);
+				if (scope_initializers != null)
+					expr = new BlockScopeExpression (expr, this);
+
+				return expr;
+			}
+
+			return base.CreateExpressionTree (ec);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (state_machine != null && state_machine.OriginalSourceBlock != this) {
+				DefineStoreyContainer (ec, state_machine);
+				state_machine.EmitStoreyInstantiation (ec, this);
+			}
+
+			base.Emit (ec);
+		}
+
+		public void EmitEmbedded (EmitContext ec)
+		{
+			if (state_machine != null && state_machine.OriginalSourceBlock != this) {
+				DefineStoreyContainer (ec, state_machine);
+				state_machine.EmitStoreyInstantiation (ec, this);
+			}
+
+			base.Emit (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			var res = base.DoFlowAnalysis (fc);
+
+			if (HasReachableClosingBrace)
+				CheckControlExit (fc);
+
+			return res;
+		}
+
+		public LabeledStatement GetLabel (string name, Block block)
+		{
+			//
+			// Cloned parameters blocks can have their own cloned version of top-level labels
+			//
+			if (labels == null) {
+				if (Parent != null)
+					return Parent.ParametersBlock.GetLabel (name, block);
+
+				return null;
+			}
+
+			object value;
+			if (!labels.TryGetValue (name, out value)) {
+				return null;
+			}
+
+			var label = value as LabeledStatement;
+			Block b = block;
+			if (label != null) {
+				if (IsLabelVisible (label, b))
+					return label;
+
+			} else {
+				List<LabeledStatement> list = (List<LabeledStatement>) value;
+				for (int i = 0; i < list.Count; ++i) {
+					label = list[i];
+					if (IsLabelVisible (label, b))
+						return label;
+				}
+			}
+
+			return null;
+		}
+
+		static bool IsLabelVisible (LabeledStatement label, Block b)
+		{
+			do {
+				if (label.Block == b)
+					return true;
+				b = b.Parent;
+			} while (b != null);
+
+			return false;
+		}
+
+		public ParameterInfo GetParameterInfo (Parameter p)
+		{
+			for (int i = 0; i < parameters.Count; ++i) {
+				if (parameters[i] == p)
+					return parameter_info[i];
+			}
+
+			throw new ArgumentException ("Invalid parameter");
+		}
+
+		public ParameterReference GetParameterReference (int index, Location loc)
+		{
+			return new ParameterReference (parameter_info[index], loc);
+		}
+
+		public Statement PerformClone ()
+		{
+			CloneContext clonectx = new CloneContext ();
+			return Clone (clonectx);
+		}
+
+		protected void ProcessParameters ()
+		{
+			if (parameters.Count == 0)
+				return;
+
+			parameter_info = new ParameterInfo[parameters.Count];
+			for (int i = 0; i < parameter_info.Length; ++i) {
+				var p = parameters.FixedParameters[i];
+				if (p == null)
+					continue;
+
+				// TODO: Should use Parameter only and more block there
+				parameter_info[i] = new ParameterInfo (this, i);
+				if (p.Name != null)
+					AddLocalName (p.Name, parameter_info[i]);
+			}
+		}
+
+		static LabeledStatement RemapLabeledStatement (LabeledStatement stmt, Block src, Block dst)
+		{
+			var src_stmts = src.Statements;
+			for (int i = 0; i < src_stmts.Count; ++i) {
+				if (src_stmts[i] == stmt)
+					return (LabeledStatement) dst.Statements[i];
+			}
+
+			throw new InternalErrorException ("Should never be reached");
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			// TODO: if ((flags & Flags.Resolved) != 0)
+
+			if (resolved)
+				return true;
+
+			resolved = true;
+
+			if (bc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
+				flags |= Flags.IsExpressionTree;
+
+			try {
+				PrepareAssignmentAnalysis (bc);
+
+				if (!base.Resolve (bc))
+					return false;
+
+			} catch (Exception e) {
+				if (e is CompletionResult || bc.Report.IsDisabled || e is FatalException || bc.Report.Printer is NullReportPrinter || bc.Module.Compiler.Settings.BreakOnInternalError)
+					throw;
+
+				if (bc.CurrentBlock != null) {
+					bc.Report.Error (584, bc.CurrentBlock.StartLocation, "Internal compiler error: {0}", e.Message);
+				} else {
+					bc.Report.Error (587, "Internal compiler error: {0}", e.Message);
+				}
+			}
+
+			//
+			// If an asynchronous body of F is either an expression classified as nothing, or a 
+			// statement block where no return statements have expressions, the inferred return type is Task
+			//
+			if (IsAsync) {
+				var am = bc.CurrentAnonymousMethod as AnonymousMethodBody;
+				if (am != null && am.ReturnTypeInference != null && !am.ReturnTypeInference.HasBounds (0)) {
+					am.ReturnTypeInference = null;
+					am.ReturnType = bc.Module.PredefinedTypes.Task.TypeSpec;
+					return true;
+				}
+			}
+
+			return true;
+		}
+
+		void PrepareAssignmentAnalysis (BlockContext bc)
+		{
+			for (int i = 0; i < parameters.Count; ++i) {
+				var par = parameters.FixedParameters[i];
+
+				if ((par.ModFlags & Parameter.Modifier.OUT) == 0)
+					continue;
+
+				parameter_info [i].VariableInfo = VariableInfo.Create (bc, (Parameter) par);
+			}
+		}
+
+		public ToplevelBlock ConvertToIterator (IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
+		{
+			var iterator = new Iterator (this, method, host, iterator_type, is_enumerable);
+			var stateMachine = new IteratorStorey (iterator);
+
+			state_machine = stateMachine;
+			iterator.SetStateMachine (stateMachine);
+
+			var tlb = new ToplevelBlock (host.Compiler, Parameters, Location.Null, Flags.CompilerGenerated);
+			tlb.Original = this;
+			tlb.state_machine = stateMachine;
+			tlb.AddStatement (new Return (iterator, iterator.Location));
+			return tlb;
+		}
+
+		public ParametersBlock ConvertToAsyncTask (IMemberContext context, TypeDefinition host, ParametersCompiled parameters, TypeSpec returnType, TypeSpec delegateType, Location loc)
+		{
+			for (int i = 0; i < parameters.Count; i++) {
+				Parameter p = parameters[i];
+				Parameter.Modifier mod = p.ModFlags;
+				if ((mod & Parameter.Modifier.RefOutMask) != 0) {
+					host.Compiler.Report.Error (1988, p.Location,
+						"Async methods cannot have ref or out parameters");
+					return this;
+				}
+
+				if (p is ArglistParameter) {
+					host.Compiler.Report.Error (4006, p.Location,
+						"__arglist is not allowed in parameter list of async methods");
+					return this;
+				}
+
+				if (parameters.Types[i].IsPointer) {
+					host.Compiler.Report.Error (4005, p.Location,
+						"Async methods cannot have unsafe parameters");
+					return this;
+				}
+			}
+
+			if (!HasAwait) {
+				host.Compiler.Report.Warning (1998, 1, loc,
+					"Async block lacks `await' operator and will run synchronously");
+			}
+
+			var block_type = host.Module.Compiler.BuiltinTypes.Void;
+			var initializer = new AsyncInitializer (this, host, block_type);
+			initializer.Type = block_type;
+			initializer.DelegateType = delegateType;
+
+			var stateMachine = new AsyncTaskStorey (this, context, initializer, returnType);
+
+			state_machine = stateMachine;
+			initializer.SetStateMachine (stateMachine);
+
+			const Flags flags = Flags.CompilerGenerated;
+
+			var b = this is ToplevelBlock ?
+				new ToplevelBlock (host.Compiler, Parameters, Location.Null, flags) :
+				new ParametersBlock (Parent, parameters, Location.Null, flags | Flags.HasAsyncModifier);
+
+			b.Original = this;
+			b.state_machine = stateMachine;
+			b.AddStatement (new AsyncInitializerStatement (initializer));
+			return b;
+		}
+	}
+
+	//
+	//
+	//
+	public class ToplevelBlock : ParametersBlock
+	{
+		LocalVariable this_variable;
+		CompilerContext compiler;
+		Dictionary<string, object> names;
+
+		List<ExplicitBlock> this_references;
+
+		public ToplevelBlock (CompilerContext ctx, Location loc)
+			: this (ctx, ParametersCompiled.EmptyReadOnlyParameters, loc)
+		{
+		}
+
+		public ToplevelBlock (CompilerContext ctx, ParametersCompiled parameters, Location start, Flags flags = 0)
+			: base (parameters, start)
+		{
+			this.compiler = ctx;
+			this.flags = flags;
+			top_block = this;
+
+			ProcessParameters ();
+		}
+
+		//
+		// Recreates a top level block from parameters block. Used for
+		// compiler generated methods where the original block comes from
+		// explicit child block. This works for already resolved blocks
+		// only to ensure we resolve them in the correct flow order
+		//
+		public ToplevelBlock (ParametersBlock source, ParametersCompiled parameters)
+			: base (source, parameters)
+		{
+			this.compiler = source.TopBlock.compiler;
+			top_block = this;
+		}
+
+		public bool IsIterator {
+			get {
+				return (flags & Flags.Iterator) != 0;
+			}
+			set {
+				flags = value ? flags | Flags.Iterator : flags & ~Flags.Iterator;
+			}
+		}
+
+		public Report Report {
+			get {
+				return compiler.Report;
+			}
+		}
+
+		//
+		// Used by anonymous blocks to track references of `this' variable
+		//
+		public List<ExplicitBlock> ThisReferencesFromChildrenBlock {
+			get {
+				return this_references;
+			}
+		}
+
+		//
+		// Returns the "this" instance variable of this block.
+		// See AddThisVariable() for more information.
+		//
+		public LocalVariable ThisVariable {
+			get {
+				return this_variable;
+			}
+		}
+
+		public void AddLocalName (string name, INamedBlockVariable li, bool ignoreChildrenBlocks)
+		{
+			if (names == null)
+				names = new Dictionary<string, object> ();
+
+			object value;
+			if (!names.TryGetValue (name, out value)) {
+				names.Add (name, li);
+				return;
+			}
+
+			INamedBlockVariable existing = value as INamedBlockVariable;
+			List<INamedBlockVariable> existing_list;
+			if (existing != null) {
+				existing_list = new List<INamedBlockVariable> ();
+				existing_list.Add (existing);
+				names[name] = existing_list;
+			} else {
+				existing_list = (List<INamedBlockVariable>) value;
+			}
+
+			//
+			// A collision checking between local names
+			//
+			var variable_block = li.Block.Explicit;
+			for (int i = 0; i < existing_list.Count; ++i) {
+				existing = existing_list[i];
+				Block b = existing.Block.Explicit;
+
+				// Collision at same level
+				if (variable_block == b) {
+					li.Block.Error_AlreadyDeclared (name, li);
+					break;
+				}
+
+				// Collision with parent
+				Block parent = variable_block;
+				while ((parent = parent.Parent) != null) {
+					if (parent == b) {
+						li.Block.Error_AlreadyDeclared (name, li, "parent or current");
+						i = existing_list.Count;
+						break;
+					}
+				}
+
+				if (!ignoreChildrenBlocks && variable_block.Parent != b.Parent) {
+					// Collision with children
+					while ((b = b.Parent) != null) {
+						if (variable_block == b) {
+							li.Block.Error_AlreadyDeclared (name, li, "child");
+							i = existing_list.Count;
+							break;
+						}
+					}
+				}
+			}
+
+			existing_list.Add (li);
+		}
+
+		public void AddLabel (string name, LabeledStatement label)
+		{
+			if (labels == null)
+				labels = new Dictionary<string, object> ();
+
+			object value;
+			if (!labels.TryGetValue (name, out value)) {
+				labels.Add (name, label);
+				return;
+			}
+
+			LabeledStatement existing = value as LabeledStatement;
+			List<LabeledStatement> existing_list;
+			if (existing != null) {
+				existing_list = new List<LabeledStatement> ();
+				existing_list.Add (existing);
+				labels[name] = existing_list;
+			} else {
+				existing_list = (List<LabeledStatement>) value;
+			}
+
+			//
+			// A collision checking between labels
+			//
+			for (int i = 0; i < existing_list.Count; ++i) {
+				existing = existing_list[i];
+				Block b = existing.Block;
+
+				// Collision at same level
+				if (label.Block == b) {
+					Report.SymbolRelatedToPreviousError (existing.loc, name);
+					Report.Error (140, label.loc, "The label `{0}' is a duplicate", name);
+					break;
+				}
+
+				// Collision with parent
+				b = label.Block;
+				while ((b = b.Parent) != null) {
+					if (existing.Block == b) {
+						Report.Error (158, label.loc,
+							"The label `{0}' shadows another label by the same name in a contained scope", name);
+						i = existing_list.Count;
+						break;
+					}
+				}
+
+				// Collision with with children
+				b = existing.Block;
+				while ((b = b.Parent) != null) {
+					if (label.Block == b) {
+						Report.Error (158, label.loc,
+							"The label `{0}' shadows another label by the same name in a contained scope", name);
+						i = existing_list.Count;
+						break;
+					}
+				}
+			}
+
+			existing_list.Add (label);
+		}
+
+		public void AddThisReferenceFromChildrenBlock (ExplicitBlock block)
+		{
+			if (this_references == null)
+				this_references = new List<ExplicitBlock> ();
+
+			if (!this_references.Contains (block))
+				this_references.Add (block);
+		}
+
+		public void RemoveThisReferenceFromChildrenBlock (ExplicitBlock block)
+		{
+			this_references.Remove (block);
+		}
+
+		//
+		// Creates an arguments set from all parameters, useful for method proxy calls
+		//
+		public Arguments GetAllParametersArguments ()
+		{
+			int count = parameters.Count;
+			Arguments args = new Arguments (count);
+			for (int i = 0; i < count; ++i) {
+				var pi = parameter_info[i];
+				var arg_expr = GetParameterReference (i, pi.Location);
+
+				Argument.AType atype_modifier;
+				switch (pi.Parameter.ParameterModifier & Parameter.Modifier.RefOutMask) {
+				case Parameter.Modifier.REF:
+					atype_modifier = Argument.AType.Ref;
+					break;
+				case Parameter.Modifier.OUT:
+					atype_modifier = Argument.AType.Out;
+					break;
+				default:
+					atype_modifier = 0;
+					break;
+				}
+
+				args.Add (new Argument (arg_expr, atype_modifier));
+			}
+
+			return args;
+		}
+
+		//
+		// Lookup inside a block, the returned value can represent 3 states
+		//
+		// true+variable: A local name was found and it's valid
+		// false+variable: A local name was found in a child block only
+		// false+null: No local name was found
+		//
+		public bool GetLocalName (string name, Block block, ref INamedBlockVariable variable)
+		{
+			if (names == null)
+				return false;
+
+			object value;
+			if (!names.TryGetValue (name, out value))
+				return false;
+
+			variable = value as INamedBlockVariable;
+			Block b = block;
+			if (variable != null) {
+				do {
+					if (variable.Block == b.Original)
+						return true;
+
+					b = b.Parent;
+				} while (b != null);
+
+				b = variable.Block;
+				do {
+					if (block == b)
+						return false;
+
+					b = b.Parent;
+				} while (b != null);
+			} else {
+				List<INamedBlockVariable> list = (List<INamedBlockVariable>) value;
+				for (int i = 0; i < list.Count; ++i) {
+					variable = list[i];
+					do {
+						if (variable.Block == b.Original)
+							return true;
+
+						b = b.Parent;
+					} while (b != null);
+
+					b = variable.Block;
+					do {
+						if (block == b)
+							return false;
+
+						b = b.Parent;
+					} while (b != null);
+
+					b = block;
+				}
+			}
+
+			variable = null;
+			return false;
+		}
+
+		public void IncludeBlock (ParametersBlock pb, ToplevelBlock block)
+		{
+			if (block.names != null) {
+				foreach (var n in block.names) {
+					var variable = n.Value as INamedBlockVariable;
+					if (variable != null) {
+						if (variable.Block.ParametersBlock == pb)
+							AddLocalName (n.Key, variable, false);
+						continue;
+					}
+
+					foreach (var v in (List<INamedBlockVariable>) n.Value)
+						if (v.Block.ParametersBlock == pb)
+							AddLocalName (n.Key, v, false);
+				}
+			}
+		}
+
+		// <summary>
+		//   This is used by non-static `struct' constructors which do not have an
+		//   initializer - in this case, the constructor must initialize all of the
+		//   struct's fields.  To do this, we add a "this" variable and use the flow
+		//   analysis code to ensure that it's been fully initialized before control
+		//   leaves the constructor.
+		// </summary>
+		public void AddThisVariable (BlockContext bc)
+		{
+			if (this_variable != null)
+				throw new InternalErrorException (StartLocation.ToString ());
+
+			this_variable = new LocalVariable (this, "this", LocalVariable.Flags.IsThis | LocalVariable.Flags.Used, StartLocation);
+			this_variable.Type = bc.CurrentType;
+			this_variable.PrepareAssignmentAnalysis (bc);
+		}
+
+		public override void CheckControlExit (FlowAnalysisContext fc, DefiniteAssignmentBitSet dat)
+		{
+			//
+			// If we're a non-static struct constructor which doesn't have an
+			// initializer, then we must initialize all of the struct's fields.
+			//
+			if (this_variable != null)
+				this_variable.IsThisAssigned (fc, this);
+
+			base.CheckControlExit (fc, dat);
+		}
+
+		public override void Emit (EmitContext ec)
+		{
+			if (Report.Errors > 0)
+				return;
+
+			try {
+			if (IsCompilerGenerated) {
+				using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+					base.Emit (ec);
+				}
+			} else {
+				base.Emit (ec);
+			}
+
+			//
+			// If `HasReturnLabel' is set, then we already emitted a
+			// jump to the end of the method, so we must emit a `ret'
+			// there.
+			//
+			// Unfortunately, System.Reflection.Emit automatically emits
+			// a leave to the end of a finally block.  This is a problem
+			// if no code is following the try/finally block since we may
+			// jump to a point after the end of the method.
+			// As a workaround, we're always creating a return label in
+			// this case.
+			//
+			if (ec.HasReturnLabel || HasReachableClosingBrace) {
+				if (ec.HasReturnLabel)
+					ec.MarkLabel (ec.ReturnLabel);
+
+				if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated)
+					ec.Mark (EndLocation);
+
+				if (ec.ReturnType.Kind != MemberKind.Void)
+					ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
+
+				ec.Emit (OpCodes.Ret);
+			}
+
+			} catch (Exception e) {
+				throw new InternalErrorException (e, StartLocation);
+			}
+		}
+
+		public bool Resolve (BlockContext bc, IMethodData md)
+		{
+			if (resolved)
+				return true;
+
+			var errors = bc.Report.Errors;
+
+			base.Resolve (bc);
+
+			if (bc.Report.Errors > errors)
+				return false;
+
+			MarkReachable (new Reachability ());
+
+			if (HasReachableClosingBrace && bc.ReturnType.Kind != MemberKind.Void) {
+				// TODO: var md = bc.CurrentMemberDefinition;
+				bc.Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
+			}
+
+			if ((flags & Flags.NoFlowAnalysis) != 0)
+				return true;
+
+			var fc = new FlowAnalysisContext (bc.Module.Compiler, this, bc.AssignmentInfoOffset);
+			try {
+				FlowAnalysis (fc);
+			} catch (Exception e) {
+				throw new InternalErrorException (e, StartLocation);
+			}
+
+			return true;
+		}
+	}
+	
+	public class SwitchLabel : Statement
+	{
+		Constant converted;
+		Expression label;
+
+		Label? il_label;
+
+		//
+		// if expr == null, then it is the default case.
+		//
+		public SwitchLabel (Expression expr, Location l)
+		{
+			label = expr;
+			loc = l;
+		}
+
+		public bool IsDefault {
+			get {
+				return label == null;
+			}
+		}
+
+		public Expression Label {
+			get {
+				return label;
+			}
+		}
+
+		public Location Location {
+			get {
+				return loc;
+			}
+		}
+
+		public Constant Converted {
+			get {
+				return converted;
+			}
+			set {
+				converted = value; 
+			}
+		}
+
+		public bool SectionStart { get; set; }
+
+		public Label GetILLabel (EmitContext ec)
+		{
+			if (il_label == null){
+				il_label = ec.DefineLabel ();
+			}
+
+			return il_label.Value;
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			ec.MarkLabel (GetILLabel (ec));
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (!SectionStart)
+				return false;
+
+			fc.DefiniteAssignment = new DefiniteAssignmentBitSet (fc.SwitchInitialDefinitiveAssignment);
+			return false;
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			if (ResolveAndReduce (bc))
+				bc.Switch.RegisterLabel (bc, this);
+
+			return true;
+		}
+
+		//
+		// Resolves the expression, reduces it to a literal if possible
+		// and then converts it to the requested type.
+		//
+		bool ResolveAndReduce (BlockContext rc)
+		{
+			if (IsDefault)
+				return true;
+
+			var c = label.ResolveLabelConstant (rc);
+			if (c == null)
+				return false;
+
+			if (rc.Switch.IsNullable && c is NullLiteral) {
+				converted = c;
+				return true;
+			}
+
+			converted = c.ImplicitConversionRequired (rc, rc.Switch.SwitchType);
+			return converted != null;
+		}
+
+		public void Error_AlreadyOccurs (ResolveContext ec, SwitchLabel collision_with)
+		{
+			ec.Report.SymbolRelatedToPreviousError (collision_with.loc, null);
+			ec.Report.Error (152, loc, "The label `{0}' already occurs in this switch statement", GetSignatureForError ());
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement target)
+		{
+			var t = (SwitchLabel) target;
+			if (label != null)
+				t.label = label.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		public string GetSignatureForError ()
+		{
+			string label;
+			if (converted == null)
+				label = "default";
+			else
+				label = converted.GetValueAsLiteral ();
+
+			return string.Format ("case {0}:", label);
+		}
+	}
+
+	public class Switch : LoopStatement
+	{
+		// structure used to hold blocks of keys while calculating table switch
+		sealed class LabelsRange : IComparable<LabelsRange>
+		{
+			public readonly long min;
+			public long max;
+			public readonly List<long> label_values;
+
+			public LabelsRange (long value)
+			{
+				min = max = value;
+				label_values = new List<long> ();
+				label_values.Add (value);
+			}
+
+			public LabelsRange (long min, long max, ICollection<long> values)
+			{
+				this.min = min;
+				this.max = max;
+				this.label_values = new List<long> (values);
+			}
+
+			public long Range {
+				get {
+					return max - min + 1;
+				}
+			}
+
+			public bool AddValue (long value)
+			{
+				var gap = value - min + 1;
+				// Ensure the range has > 50% occupancy
+				if (gap > 2 * (label_values.Count + 1) || gap <= 0)
+					return false;
+
+				max = value;
+				label_values.Add (value);
+				return true;
+			}
+
+			public int CompareTo (LabelsRange other)
+			{
+				int nLength = label_values.Count;
+				int nLengthOther = other.label_values.Count;
+				if (nLengthOther == nLength)
+					return (int) (other.min - min);
+
+				return nLength - nLengthOther;
+			}
+		}
+
+		sealed class DispatchStatement : Statement
+		{
+			readonly Switch body;
+
+			public DispatchStatement (Switch body)
+			{
+				this.body = body;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+				throw new NotImplementedException ();
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				return false;
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				body.EmitDispatch (ec);
+			}
+		}
+
+		class MissingBreak : Statement
+		{
+			readonly SwitchLabel label;
+
+			public MissingBreak (SwitchLabel sl)
+			{
+				this.label = sl;
+				this.loc = sl.loc;
+			}
+
+			public bool FallOut { get; set; }
+
+			protected override void DoEmit (EmitContext ec)
+			{
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				if (FallOut) {
+					fc.Report.Error (8070, loc, "Control cannot fall out of switch statement through final case label `{0}'",
+						label.GetSignatureForError ());
+				} else {
+					fc.Report.Error (163, loc, "Control cannot fall through from one case label `{0}' to another",
+						label.GetSignatureForError ());
+				}
+				return true;
+			}
+		}
+
+		public Expression Expr;
+
+		//
+		// Mapping of all labels to their SwitchLabels
+		//
+		Dictionary<long, SwitchLabel> labels;
+		Dictionary<string, SwitchLabel> string_labels;
+		List<SwitchLabel> case_labels;
+
+		List<Tuple<GotoCase, Constant>> goto_cases;
+		List<DefiniteAssignmentBitSet> end_reachable_das;
+
+		/// <summary>
+		///   The governing switch type
+		/// </summary>
+		public TypeSpec SwitchType;
+
+		Expression new_expr;
+
+		SwitchLabel case_null;
+		SwitchLabel case_default;
+
+		Label defaultLabel, nullLabel;
+		VariableReference value;
+		ExpressionStatement string_dictionary;
+		FieldExpr switch_cache_field;
+		ExplicitBlock block;
+		bool end_reachable;
+
+		//
+		// Nullable Types support
+		//
+		Nullable.Unwrap unwrap;
+
+		public Switch (Expression e, ExplicitBlock block, Location l)
+			: base (block)
+		{
+			Expr = e;
+			this.block = block;
+			loc = l;
+		}
+
+		public SwitchLabel ActiveLabel { get; set; }
+
+		public ExplicitBlock Block {
+			get {
+				return block;
+			}
+		}
+
+		public SwitchLabel DefaultLabel {
+			get {
+				return case_default;
+			}
+		}
+
+		public bool IsNullable {
+			get {
+				return unwrap != null;
+			}
+		}
+
+		public List<SwitchLabel> RegisteredLabels {
+			get {
+				return case_labels;
+			}
+		}
+
+		//
+		// Determines the governing type for a switch.  The returned
+		// expression might be the expression from the switch, or an
+		// expression that includes any potential conversions to
+		//
+		static Expression SwitchGoverningType (ResolveContext rc, Expression expr, bool unwrapExpr)
+		{
+			switch (expr.Type.BuiltinType) {
+			case BuiltinTypeSpec.Type.Byte:
+			case BuiltinTypeSpec.Type.SByte:
+			case BuiltinTypeSpec.Type.UShort:
+			case BuiltinTypeSpec.Type.Short:
+			case BuiltinTypeSpec.Type.UInt:
+			case BuiltinTypeSpec.Type.Int:
+			case BuiltinTypeSpec.Type.ULong:
+			case BuiltinTypeSpec.Type.Long:
+			case BuiltinTypeSpec.Type.Char:
+			case BuiltinTypeSpec.Type.String:
+			case BuiltinTypeSpec.Type.Bool:
+				return expr;
+			}
+
+			if (expr.Type.IsEnum)
+				return expr;
+
+			//
+			// Try to find a *user* defined implicit conversion.
+			//
+			// If there is no implicit conversion, or if there are multiple
+			// conversions, we have to report an error
+			//
+			Expression converted = null;
+			foreach (TypeSpec tt in rc.Module.PredefinedTypes.SwitchUserTypes) {
+
+				if (!unwrapExpr && tt.IsNullableType && expr.Type.IsNullableType)
+					break;
+
+				var restr = Convert.UserConversionRestriction.ImplicitOnly |
+					Convert.UserConversionRestriction.ProbingOnly;
+
+				if (unwrapExpr)
+					restr |= Convert.UserConversionRestriction.NullableSourceOnly;
+
+				var e = Convert.UserDefinedConversion (rc, expr, tt, restr, Location.Null);
+				if (e == null)
+					continue;
+
+				//
+				// Ignore over-worked ImplicitUserConversions that do
+				// an implicit conversion in addition to the user conversion.
+				// 
+				var uc = e as UserCast;
+				if (uc == null)
+					continue;
+
+				if (converted != null){
+//					rc.Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
+					return null;
+				}
+
+				converted = e;
+			}
+			return converted;
+		}
+
+		public static TypeSpec[] CreateSwitchUserTypes (ModuleContainer module, TypeSpec nullable)
+		{
+			var types = module.Compiler.BuiltinTypes;
+
+			// LAMESPEC: For some reason it does not contain bool which looks like csc bug
+			TypeSpec[] stypes = new[] {
+				types.SByte,
+				types.Byte,
+				types.Short,
+				types.UShort,
+				types.Int,
+				types.UInt,
+				types.Long,
+				types.ULong,
+				types.Char,
+				types.String
+			};
+
+			if (nullable != null) {
+
+				Array.Resize (ref stypes, stypes.Length + 9);
+
+				for (int i = 0; i < 9; ++i) {
+					stypes [10 + i] = nullable.MakeGenericType (module, new [] { stypes [i] });
+				}
+			}
+
+			return stypes;
+		}
+
+		public void RegisterLabel (BlockContext rc, SwitchLabel sl)
+		{
+			case_labels.Add (sl);
+
+			if (sl.IsDefault) {
+				if (case_default != null) {
+					sl.Error_AlreadyOccurs (rc, case_default);
+				} else {
+					case_default = sl;
+				}
+
+				return;
+			}
+
+			try {
+				if (string_labels != null) {
+					string string_value = sl.Converted.GetValue () as string;
+					if (string_value == null)
+						case_null = sl;
+					else
+						string_labels.Add (string_value, sl);
+				} else {
+					if (sl.Converted is NullLiteral) {
+						case_null = sl;
+					} else {
+						labels.Add (sl.Converted.GetValueAsLong (), sl);
+					}
+				}
+			} catch (ArgumentException) {
+				if (string_labels != null)
+					sl.Error_AlreadyOccurs (rc, string_labels[(string) sl.Converted.GetValue ()]);
+				else
+					sl.Error_AlreadyOccurs (rc, labels[sl.Converted.GetValueAsLong ()]);
+			}
+		}
+		
+		//
+		// This method emits code for a lookup-based switch statement (non-string)
+		// Basically it groups the cases into blocks that are at least half full,
+		// and then spits out individual lookup opcodes for each block.
+		// It emits the longest blocks first, and short blocks are just
+		// handled with direct compares.
+		//
+		void EmitTableSwitch (EmitContext ec, Expression val)
+		{
+			if (labels != null && labels.Count > 0) {
+				List<LabelsRange> ranges;
+				if (string_labels != null) {
+					// We have done all hard work for string already
+					// setup single range only
+					ranges = new List<LabelsRange> (1);
+					ranges.Add (new LabelsRange (0, labels.Count - 1, labels.Keys));
+				} else {
+					var element_keys = new long[labels.Count];
+					labels.Keys.CopyTo (element_keys, 0);
+					Array.Sort (element_keys);
+
+					//
+					// Build possible ranges of switch labes to reduce number
+					// of comparisons
+					//
+					ranges = new List<LabelsRange> (element_keys.Length);
+					var range = new LabelsRange (element_keys[0]);
+					ranges.Add (range);
+					for (int i = 1; i < element_keys.Length; ++i) {
+						var l = element_keys[i];
+						if (range.AddValue (l))
+							continue;
+
+						range = new LabelsRange (l);
+						ranges.Add (range);
+					}
+
+					// sort the blocks so we can tackle the largest ones first
+					ranges.Sort ();
+				}
+
+				Label lbl_default = defaultLabel;
+				TypeSpec compare_type = SwitchType.IsEnum ? EnumSpec.GetUnderlyingType (SwitchType) : SwitchType;
+
+				for (int range_index = ranges.Count - 1; range_index >= 0; --range_index) {
+					LabelsRange kb = ranges[range_index];
+					lbl_default = (range_index == 0) ? defaultLabel : ec.DefineLabel ();
+
+					// Optimize small ranges using simple equality check
+					if (kb.Range <= 2) {
+						foreach (var key in kb.label_values) {
+							SwitchLabel sl = labels[key];
+							if (sl == case_default || sl == case_null)
+								continue;
+
+							if (sl.Converted.IsZeroInteger) {
+								val.EmitBranchable (ec, sl.GetILLabel (ec), false);
+							} else {
+								val.Emit (ec);
+								sl.Converted.Emit (ec);
+								ec.Emit (OpCodes.Beq, sl.GetILLabel (ec));
+							}
+						}
+					} else {
+						// TODO: if all the keys in the block are the same and there are
+						//       no gaps/defaults then just use a range-check.
+						if (compare_type.BuiltinType == BuiltinTypeSpec.Type.Long || compare_type.BuiltinType == BuiltinTypeSpec.Type.ULong) {
+							// TODO: optimize constant/I4 cases
+
+							// check block range (could be > 2^31)
+							val.Emit (ec);
+							ec.EmitLong (kb.min);
+							ec.Emit (OpCodes.Blt, lbl_default);
+
+							val.Emit (ec);
+							ec.EmitLong (kb.max);
+							ec.Emit (OpCodes.Bgt, lbl_default);
+
+							// normalize range
+							val.Emit (ec);
+							if (kb.min != 0) {
+								ec.EmitLong (kb.min);
+								ec.Emit (OpCodes.Sub);
+							}
+
+							ec.Emit (OpCodes.Conv_I4);	// assumes < 2^31 labels!
+						} else {
+							// normalize range
+							val.Emit (ec);
+							int first = (int) kb.min;
+							if (first > 0) {
+								ec.EmitInt (first);
+								ec.Emit (OpCodes.Sub);
+							} else if (first < 0) {
+								ec.EmitInt (-first);
+								ec.Emit (OpCodes.Add);
+							}
+						}
+
+						// first, build the list of labels for the switch
+						int iKey = 0;
+						long cJumps = kb.Range;
+						Label[] switch_labels = new Label[cJumps];
+						for (int iJump = 0; iJump < cJumps; iJump++) {
+							var key = kb.label_values[iKey];
+							if (key == kb.min + iJump) {
+								switch_labels[iJump] = labels[key].GetILLabel (ec);
+								iKey++;
+							} else {
+								switch_labels[iJump] = lbl_default;
+							}
+						}
+
+						// emit the switch opcode
+						ec.Emit (OpCodes.Switch, switch_labels);
+					}
+
+					// mark the default for this block
+					if (range_index != 0)
+						ec.MarkLabel (lbl_default);
+				}
+
+				// the last default just goes to the end
+				if (ranges.Count > 0)
+					ec.Emit (OpCodes.Br, lbl_default);
+			}
+		}
+		
+		public SwitchLabel FindLabel (Constant value)
+		{
+			SwitchLabel sl = null;
+
+			if (string_labels != null) {
+				string s = value.GetValue () as string;
+				if (s == null) {
+					if (case_null != null)
+						sl = case_null;
+					else if (case_default != null)
+						sl = case_default;
+				} else {
+					string_labels.TryGetValue (s, out sl);
+				}
+			} else {
+				if (value is NullLiteral) {
+					sl = case_null;
+				} else {
+					labels.TryGetValue (value.GetValueAsLong (), out sl);
+				}
+			}
+
+			return sl;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			Expr.FlowAnalysis (fc);
+
+			var prev_switch = fc.SwitchInitialDefinitiveAssignment;
+			var InitialDefinitiveAssignment = fc.DefiniteAssignment;
+			fc.SwitchInitialDefinitiveAssignment = InitialDefinitiveAssignment;
+
+			block.FlowAnalysis (fc);
+
+			fc.SwitchInitialDefinitiveAssignment = prev_switch;
+
+			if (end_reachable_das != null) {
+				var sections_das = DefiniteAssignmentBitSet.And (end_reachable_das);
+				InitialDefinitiveAssignment |= sections_das;
+				end_reachable_das = null;
+			}
+
+			fc.DefiniteAssignment = InitialDefinitiveAssignment;
+
+			return case_default != null && !end_reachable;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			Expr = Expr.Resolve (ec);
+			if (Expr == null)
+				return false;
+
+			//
+			// LAMESPEC: User conversion from non-nullable governing type has a priority
+			//
+			new_expr = SwitchGoverningType (ec, Expr, false);
+
+			if (new_expr == null) {
+				if (Expr.Type.IsNullableType) {
+					unwrap = Nullable.Unwrap.Create (Expr, false);
+					if (unwrap == null)
+						return false;
+
+					//
+					// Unwrap + user conversion using non-nullable type is not allowed but user operator
+					// involving nullable Expr and nullable governing type is
+					//
+					new_expr = SwitchGoverningType (ec, unwrap, true);
+				}
+			}
+
+			if (new_expr == null) {
+				if (Expr.Type != InternalType.ErrorType) {
+					ec.Report.Error (151, loc,
+						"A switch expression of type `{0}' cannot be converted to an integral type, bool, char, string, enum or nullable type",
+						Expr.Type.GetSignatureForError ());
+				}
+
+				return false;
+			}
+
+			SwitchType = new_expr.Type;
+			if (SwitchType.IsNullableType) {
+				new_expr = unwrap = Nullable.Unwrap.Create (new_expr, true);
+				SwitchType = Nullable.NullableInfo.GetUnderlyingType (SwitchType);
+			}
+
+			if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.Bool && ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
+				ec.Report.FeatureIsNotAvailable (ec.Module.Compiler, loc, "switch expression of boolean type");
+				return false;
+			}
+
+			if (block.Statements.Count == 0)
+				return true;
+
+			if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
+				string_labels = new Dictionary<string, SwitchLabel> ();
+			} else {
+				labels = new Dictionary<long, SwitchLabel> ();
+			}
+
+			case_labels = new List<SwitchLabel> ();
+
+			var constant = new_expr as Constant;
+
+			//
+			// Don't need extra variable for constant switch or switch with
+			// only default case
+			//
+			if (constant == null) {
+				//
+				// Store switch expression for comparison purposes
+				//
+				value = new_expr as VariableReference;
+				if (value == null && !HasOnlyDefaultSection ()) {
+					var current_block = ec.CurrentBlock;
+					ec.CurrentBlock = Block;
+					// Create temporary variable inside switch scope
+					value = TemporaryVariableReference.Create (SwitchType, ec.CurrentBlock, loc);
+					value.Resolve (ec);
+					ec.CurrentBlock = current_block;
+				}
+			}
+
+			Switch old_switch = ec.Switch;
+			ec.Switch = this;
+			var parent_los = ec.EnclosingLoopOrSwitch;
+			ec.EnclosingLoopOrSwitch = this;
+
+			var ok = Statement.Resolve (ec);
+
+			ec.EnclosingLoopOrSwitch = parent_los;
+			ec.Switch = old_switch;
+
+			//
+			// Check if all goto cases are valid. Needs to be done after switch
+			// is resolved because goto can jump forward in the scope.
+			//
+			if (goto_cases != null) {
+				foreach (var gc in goto_cases) {
+					if (gc.Item1 == null) {
+						if (DefaultLabel == null) {
+							Goto.Error_UnknownLabel (ec, "default", loc);
+						}
+
+						continue;
+					}
+
+					var sl = FindLabel (gc.Item2);
+					if (sl == null) {
+						Goto.Error_UnknownLabel (ec, "case " + gc.Item2.GetValueAsLiteral (), loc);
+					} else {
+						gc.Item1.Label = sl;
+					}
+				}
+			}
+
+			if (!ok)
+				return false;
+
+			if (constant == null && SwitchType.BuiltinType == BuiltinTypeSpec.Type.String && string_labels.Count > 6) {
+				ResolveStringSwitchMap (ec);
+			}
+
+			//
+			// Anonymous storey initialization has to happen before
+			// any generated switch dispatch
+			//
+			block.InsertStatement (0, new DispatchStatement (this));
+
+			return true;
+		}
+
+		bool HasOnlyDefaultSection ()
+		{
+			for (int i = 0; i < block.Statements.Count; ++i) {
+				var s = block.Statements[i] as SwitchLabel;
+
+				if (s == null || s.IsDefault)
+					continue;
+
+				return false;
+			}
+
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (rc.IsUnreachable)
+				return rc;
+
+			base.MarkReachable (rc);
+
+			block.MarkReachableScope (rc);
+
+			if (block.Statements.Count == 0)
+				return rc;
+
+			SwitchLabel constant_label = null;
+			var constant = new_expr as Constant;
+
+			if (constant != null) {
+				constant_label = FindLabel (constant) ?? case_default;
+				if (constant_label == null) {
+					block.Statements.RemoveAt (0);
+					return rc;
+				}
+			}
+
+			var section_rc = new Reachability ();
+			SwitchLabel prev_label = null;
+
+			for (int i = 0; i < block.Statements.Count; ++i) {
+				var s = block.Statements[i];
+				var sl = s as SwitchLabel;
+
+				if (sl != null && sl.SectionStart) {
+					//
+					// Section is marked already via goto case
+					//
+					if (!sl.IsUnreachable) {
+						section_rc = new Reachability ();
+						continue;
+					}
+
+					if (constant_label != null && constant_label != sl)
+						section_rc = Reachability.CreateUnreachable ();
+					else if (section_rc.IsUnreachable) {
+						section_rc = new Reachability ();
+					} else {
+						if (prev_label != null) {
+							sl.SectionStart = false;
+							s = new MissingBreak (prev_label);
+							s.MarkReachable (rc);
+							block.Statements.Insert (i - 1, s);
+							++i;
+						}
+					}
+
+					prev_label = sl;
+				}
+
+				section_rc = s.MarkReachable (section_rc);
+			}
+
+			if (!section_rc.IsUnreachable && prev_label != null) {
+				prev_label.SectionStart = false;
+				var s = new MissingBreak (prev_label) {
+					FallOut = true
+				};
+
+				s.MarkReachable (rc);
+				block.Statements.Add (s);
+			}
+
+			//
+			// Reachability can affect parent only when all possible paths are handled but
+			// we still need to run reachability check on switch body to check for fall-through
+			//
+			if (case_default == null && constant_label == null)
+				return rc;
+
+			//
+			// We have at least one local exit from the switch
+			//
+			if (end_reachable)
+				return rc;
+
+			return Reachability.CreateUnreachable ();
+		}
+
+		public void RegisterGotoCase (GotoCase gotoCase, Constant value)
+		{
+			if (goto_cases == null)
+				goto_cases = new List<Tuple<GotoCase, Constant>> ();
+
+			goto_cases.Add (Tuple.Create (gotoCase, value));
+		}
+
+		//
+		// Converts string switch into string hashtable
+		//
+		void ResolveStringSwitchMap (ResolveContext ec)
+		{
+			FullNamedExpression string_dictionary_type;
+			if (ec.Module.PredefinedTypes.Dictionary.Define ()) {
+				string_dictionary_type = new TypeExpression (
+					ec.Module.PredefinedTypes.Dictionary.TypeSpec.MakeGenericType (ec,
+						new [] { ec.BuiltinTypes.String, ec.BuiltinTypes.Int }),
+					loc);
+			} else if (ec.Module.PredefinedTypes.Hashtable.Define ()) {
+				string_dictionary_type = new TypeExpression (ec.Module.PredefinedTypes.Hashtable.TypeSpec, loc);
+			} else {
+				ec.Module.PredefinedTypes.Dictionary.Resolve ();
+				return;
+			}
+
+			var ctype = ec.CurrentMemberDefinition.Parent.PartialContainer;
+			Field field = new Field (ctype, string_dictionary_type,
+				Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
+				new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "switch$map", ec.Module.CounterSwitchTypes++), loc), null);
+			if (!field.Define ())
+				return;
+			ctype.AddField (field);
+
+			var init = new List<Expression> ();
+			int counter = -1;
+			labels = new Dictionary<long, SwitchLabel> (string_labels.Count);
+			string value = null;
+
+			foreach (SwitchLabel sl in case_labels) {
+
+				if (sl.SectionStart)
+					labels.Add (++counter, sl);
+
+				if (sl == case_default || sl == case_null)
+					continue;
+
+				value = (string) sl.Converted.GetValue ();
+				var init_args = new List<Expression> (2);
+				init_args.Add (new StringLiteral (ec.BuiltinTypes, value, sl.Location));
+
+				sl.Converted = new IntConstant (ec.BuiltinTypes, counter, loc);
+				init_args.Add (sl.Converted);
+
+				init.Add (new CollectionElementInitializer (init_args, loc));
+			}
+	
+			Arguments args = new Arguments (1);
+			args.Add (new Argument (new IntConstant (ec.BuiltinTypes, init.Count, loc)));
+			Expression initializer = new NewInitialize (string_dictionary_type, args,
+				new CollectionOrObjectInitializers (init, loc), loc);
+
+			switch_cache_field = new FieldExpr (field, loc);
+			string_dictionary = new SimpleAssign (switch_cache_field, initializer.Resolve (ec));
+		}
+
+		void DoEmitStringSwitch (EmitContext ec)
+		{
+			Label l_initialized = ec.DefineLabel ();
+
+			//
+			// Skip initialization when value is null
+			//
+			value.EmitBranchable (ec, nullLabel, false);
+
+			//
+			// Check if string dictionary is initialized and initialize
+			//
+			switch_cache_field.EmitBranchable (ec, l_initialized, true);
+			using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
+				string_dictionary.EmitStatement (ec);
+			}
+			ec.MarkLabel (l_initialized);
+
+			LocalTemporary string_switch_variable = new LocalTemporary (ec.BuiltinTypes.Int);
+
+			ResolveContext rc = new ResolveContext (ec.MemberContext);
+
+			if (switch_cache_field.Type.IsGeneric) {
+				Arguments get_value_args = new Arguments (2);
+				get_value_args.Add (new Argument (value));
+				get_value_args.Add (new Argument (string_switch_variable, Argument.AType.Out));
+				Expression get_item = new Invocation (new MemberAccess (switch_cache_field, "TryGetValue", loc), get_value_args).Resolve (rc);
+				if (get_item == null)
+					return;
+
+				//
+				// A value was not found, go to default case
+				//
+				get_item.EmitBranchable (ec, defaultLabel, false);
+			} else {
+				Arguments get_value_args = new Arguments (1);
+				get_value_args.Add (new Argument (value));
+
+				Expression get_item = new ElementAccess (switch_cache_field, get_value_args, loc).Resolve (rc);
+				if (get_item == null)
+					return;
+
+				LocalTemporary get_item_object = new LocalTemporary (ec.BuiltinTypes.Object);
+				get_item_object.EmitAssign (ec, get_item, true, false);
+				ec.Emit (OpCodes.Brfalse, defaultLabel);
+
+				ExpressionStatement get_item_int = (ExpressionStatement) new SimpleAssign (string_switch_variable,
+					new Cast (new TypeExpression (ec.BuiltinTypes.Int, loc), get_item_object, loc)).Resolve (rc);
+
+				get_item_int.EmitStatement (ec);
+				get_item_object.Release (ec);
+			}
+
+			EmitTableSwitch (ec, string_switch_variable);
+			string_switch_variable.Release (ec);
+		}
+
+		//
+		// Emits switch using simple if/else comparison for small label count (4 + optional default)
+		//
+		void EmitShortSwitch (EmitContext ec)
+		{
+			MethodSpec equal_method = null;
+			if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
+				equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (loc);
+			}
+
+			if (equal_method != null) {
+				value.EmitBranchable (ec, nullLabel, false);
+			}
+
+			for (int i = 0; i < case_labels.Count; ++i) {
+				var label = case_labels [i];
+				if (label == case_default || label == case_null)
+					continue;
+
+				var constant = label.Converted;
+
+				if (equal_method != null) {
+					value.Emit (ec);
+					constant.Emit (ec);
+
+					var call = new CallEmitter ();
+					call.EmitPredefined (ec, equal_method, new Arguments (0));
+					ec.Emit (OpCodes.Brtrue, label.GetILLabel (ec));
+					continue;
+				}
+
+				if (constant.IsZeroInteger && constant.Type.BuiltinType != BuiltinTypeSpec.Type.Long && constant.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
+					value.EmitBranchable (ec, label.GetILLabel (ec), false);
+					continue;
+				}
+
+				value.Emit (ec);
+				constant.Emit (ec);
+				ec.Emit (OpCodes.Beq, label.GetILLabel (ec));
+			}
+
+			ec.Emit (OpCodes.Br, defaultLabel);
+		}
+
+		void EmitDispatch (EmitContext ec)
+		{
+			if (value == null) {
+				//
+				// Constant switch, we've already done the work if there is only 1 label
+				// referenced
+				//
+				int reachable = 0;
+				foreach (var sl in case_labels) {
+					if (sl.IsUnreachable)
+						continue;
+
+					if (reachable++ > 0) {
+						var constant = (Constant) new_expr;
+						var constant_label = FindLabel (constant) ?? case_default;
+
+						ec.Emit (OpCodes.Br, constant_label.GetILLabel (ec));
+						break;
+					}
+				}
+
+				return;
+			}
+
+			if (string_dictionary != null) {
+				DoEmitStringSwitch (ec);
+			} else if (case_labels.Count < 4 || string_labels != null) {
+				EmitShortSwitch (ec);
+			} else {
+				EmitTableSwitch (ec, value);
+			}
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			//
+			// Setup the codegen context
+			//
+			Label old_end = ec.LoopEnd;
+			Switch old_switch = ec.Switch;
+
+			ec.LoopEnd = ec.DefineLabel ();
+			ec.Switch = this;
+
+			defaultLabel = case_default == null ? ec.LoopEnd : case_default.GetILLabel (ec);
+			nullLabel = case_null == null ? defaultLabel : case_null.GetILLabel (ec);
+
+			if (value != null) {
+				ec.Mark (loc);
+				if (IsNullable) {
+					unwrap.EmitCheck (ec);
+					ec.Emit (OpCodes.Brfalse, nullLabel);
+					value.EmitAssign (ec, new_expr, false, false);
+				} else if (new_expr != value) {
+					value.EmitAssign (ec, new_expr, false, false);
+				}
+
+
+				//
+				// Next statement is compiler generated we don't need extra
+				// nop when we can use the statement for sequence point
+				//
+				ec.Mark (block.StartLocation);
+				block.IsCompilerGenerated = true;
+			} else {
+				new_expr.EmitSideEffect (ec);
+			}
+
+			block.Emit (ec);
+
+			// Restore context state. 
+			ec.MarkLabel (ec.LoopEnd);
+
+			//
+			// Restore the previous context
+			//
+			ec.LoopEnd = old_end;
+			ec.Switch = old_switch;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Switch target = (Switch) t;
+
+			target.Expr = Expr.Clone (clonectx);
+			target.Statement = target.block = (ExplicitBlock) block.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+		public override void AddEndDefiniteAssignment (FlowAnalysisContext fc)
+		{
+			if (case_default == null && !(new_expr is Constant))
+				return;
+
+			if (end_reachable_das == null)
+				end_reachable_das = new List<DefiniteAssignmentBitSet> ();
+
+			end_reachable_das.Add (fc.DefiniteAssignment);
+		}
+
+		public override void SetEndReachable ()
+		{
+			end_reachable = true;
+		}
+	}
+
+	// A place where execution can restart in a state machine
+	public abstract class ResumableStatement : Statement
+	{
+		bool prepared;
+		protected Label resume_point;
+
+		public Label PrepareForEmit (EmitContext ec)
+		{
+			if (!prepared) {
+				prepared = true;
+				resume_point = ec.DefineLabel ();
+			}
+			return resume_point;
+		}
+
+		public virtual Label PrepareForDispose (EmitContext ec, Label end)
+		{
+			return end;
+		}
+
+		public virtual void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
+		{
+		}
+	}
+
+	public abstract class TryFinallyBlock : ExceptionStatement
+	{
+		protected Statement stmt;
+		Label dispose_try_block;
+		bool prepared_for_dispose, emitted_dispose;
+		Method finally_host;
+
+		protected TryFinallyBlock (Statement stmt, Location loc)
+			: base (loc)
+		{
+			this.stmt = stmt;
+		}
+
+		#region Properties
+
+		public Statement Statement {
+			get {
+				return stmt;
+			}
+		}
+
+		#endregion
+
+		protected abstract void EmitTryBody (EmitContext ec);
+		public abstract void EmitFinallyBody (EmitContext ec);
+
+		public override Label PrepareForDispose (EmitContext ec, Label end)
+		{
+			if (!prepared_for_dispose) {
+				prepared_for_dispose = true;
+				dispose_try_block = ec.DefineLabel ();
+			}
+			return dispose_try_block;
+		}
+
+		protected sealed override void DoEmit (EmitContext ec)
+		{
+			EmitTryBodyPrepare (ec);
+			EmitTryBody (ec);
+
+			bool beginFinally = EmitBeginFinallyBlock (ec);
+
+			Label start_finally = ec.DefineLabel ();
+			if (resume_points != null && beginFinally) {
+				var state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
+
+				ec.Emit (OpCodes.Ldloc, state_machine.SkipFinally);
+				ec.Emit (OpCodes.Brfalse_S, start_finally);
+				ec.Emit (OpCodes.Endfinally);
+			}
+
+			ec.MarkLabel (start_finally);
+
+			if (finally_host != null) {
+				finally_host.Define ();
+				finally_host.PrepareEmit ();
+				finally_host.Emit ();
+
+				// Now it's safe to add, to close it properly and emit sequence points
+				finally_host.Parent.AddMember (finally_host);
+
+				var ce = new CallEmitter ();
+				ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
+				ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0), true);
+			} else {
+				EmitFinallyBody (ec);
+			}
+
+			if (beginFinally)
+				ec.EndExceptionBlock ();
+		}
+
+		public override void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
+		{
+			if (emitted_dispose)
+				return;
+
+			emitted_dispose = true;
+
+			Label end_of_try = ec.DefineLabel ();
+
+			// Ensure that the only way we can get into this code is through a dispatcher
+			if (have_dispatcher)
+				ec.Emit (OpCodes.Br, end);
+
+			ec.BeginExceptionBlock ();
+
+			ec.MarkLabel (dispose_try_block);
+
+			Label[] labels = null;
+			for (int i = 0; i < resume_points.Count; ++i) {
+				ResumableStatement s = resume_points[i];
+				Label ret = s.PrepareForDispose (ec, end_of_try);
+				if (ret.Equals (end_of_try) && labels == null)
+					continue;
+				if (labels == null) {
+					labels = new Label[resume_points.Count];
+					for (int j = 0; j < i; ++j)
+						labels[j] = end_of_try;
+				}
+				labels[i] = ret;
+			}
+
+			if (labels != null) {
+				int j;
+				for (j = 1; j < labels.Length; ++j)
+					if (!labels[0].Equals (labels[j]))
+						break;
+				bool emit_dispatcher = j < labels.Length;
+
+				if (emit_dispatcher) {
+					ec.Emit (OpCodes.Ldloc, pc);
+					ec.EmitInt (first_resume_pc);
+					ec.Emit (OpCodes.Sub);
+					ec.Emit (OpCodes.Switch, labels);
+				}
+
+				foreach (ResumableStatement s in resume_points)
+					s.EmitForDispose (ec, pc, end_of_try, emit_dispatcher);
+			}
+
+			ec.MarkLabel (end_of_try);
+
+			ec.BeginFinallyBlock ();
+
+			if (finally_host != null) {
+				var ce = new CallEmitter ();
+				ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
+				ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0), true);
+			} else {
+				EmitFinallyBody (ec);
+			}
+
+			ec.EndExceptionBlock ();
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			var res = stmt.FlowAnalysis (fc);
+			parent = null;
+			return res;
+		}
+
+		protected virtual bool EmitBeginFinallyBlock (EmitContext ec)
+		{
+			ec.BeginFinallyBlock ();
+			return true;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Statement.MarkReachable (rc);
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			bool ok;
+
+			parent = bc.CurrentTryBlock;
+			bc.CurrentTryBlock = this;
+
+			using (bc.Set (ResolveContext.Options.TryScope)) {
+				ok = stmt.Resolve (bc);
+			}
+
+			bc.CurrentTryBlock = parent;
+
+			//
+			// Finally block inside iterator is called from MoveNext and
+			// Dispose methods that means we need to lift the block into
+			// newly created host method to emit the body only once. The
+			// original block then simply calls the newly generated method.
+			//
+			if (bc.CurrentIterator != null && !bc.IsInProbingMode) {
+				var b = stmt as Block;
+				if (b != null && b.Explicit.HasYield) {
+					finally_host = bc.CurrentIterator.CreateFinallyHost (this);
+				}
+			}
+
+			return base.Resolve (bc) && ok;
+		}
+	}
+
+	//
+	// Base class for blocks using exception handling
+	//
+	public abstract class ExceptionStatement : ResumableStatement
+	{
+		protected List<ResumableStatement> resume_points;
+		protected int first_resume_pc;
+		protected ExceptionStatement parent;
+
+		protected ExceptionStatement (Location loc)
+		{
+			this.loc = loc;
+		}
+
+		protected virtual void EmitTryBodyPrepare (EmitContext ec)
+		{
+			StateMachineInitializer state_machine = null;
+			if (resume_points != null) {
+				state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
+
+				ec.EmitInt ((int) IteratorStorey.State.Running);
+				ec.Emit (OpCodes.Stloc, state_machine.CurrentPC);
+			}
+
+			ec.BeginExceptionBlock ();
+
+			if (resume_points != null) {
+				ec.MarkLabel (resume_point);
+
+				// For normal control flow, we want to fall-through the Switch
+				// So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
+				ec.Emit (OpCodes.Ldloc, state_machine.CurrentPC);
+				ec.EmitInt (first_resume_pc);
+				ec.Emit (OpCodes.Sub);
+
+				Label[] labels = new Label[resume_points.Count];
+				for (int i = 0; i < resume_points.Count; ++i)
+					labels[i] = resume_points[i].PrepareForEmit (ec);
+				ec.Emit (OpCodes.Switch, labels);
+			}
+		}
+
+		public virtual int AddResumePoint (ResumableStatement stmt, int pc, StateMachineInitializer stateMachine)
+		{
+			if (parent != null) {
+				// TODO: MOVE to virtual TryCatch
+				var tc = this as TryCatch;
+				var s = tc != null && tc.IsTryCatchFinally ? stmt : this;
+
+				pc = parent.AddResumePoint (s, pc, stateMachine);
+			} else {
+				pc = stateMachine.AddResumePoint (this);
+			}
+
+			if (resume_points == null) {
+				resume_points = new List<ResumableStatement> ();
+				first_resume_pc = pc;
+			}
+
+			if (pc != first_resume_pc + resume_points.Count)
+				throw new InternalErrorException ("missed an intervening AddResumePoint?");
+
+			resume_points.Add (stmt);
+			return pc;
+		}
+	}
+
+	public class Lock : TryFinallyBlock
+	{
+		Expression expr;
+		TemporaryVariableReference expr_copy;
+		TemporaryVariableReference lock_taken;
+			
+		public Lock (Expression expr, Statement stmt, Location loc)
+			: base (stmt, loc)
+		{
+			this.expr = expr;
+		}
+
+		public Expression Expr {
+			get {
+ 				return this.expr;
+			}
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+			return base.DoFlowAnalysis (fc);
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			expr = expr.Resolve (ec);
+			if (expr == null)
+				return false;
+
+			if (!TypeSpec.IsReferenceType (expr.Type)) {
+				ec.Report.Error (185, loc,
+					"`{0}' is not a reference type as required by the lock statement",
+					expr.Type.GetSignatureForError ());
+			}
+
+			if (expr.Type.IsGenericParameter) {
+				expr = Convert.ImplicitTypeParameterConversion (expr, (TypeParameterSpec)expr.Type, ec.BuiltinTypes.Object);
+			}
+
+			VariableReference lv = expr as VariableReference;
+			bool locked;
+			if (lv != null) {
+				locked = lv.IsLockedByStatement;
+				lv.IsLockedByStatement = true;
+			} else {
+				lv = null;
+				locked = false;
+			}
+
+			//
+			// Have to keep original lock value around to unlock same location
+			// in the case of original value has changed or is null
+			//
+			expr_copy = TemporaryVariableReference.Create (ec.BuiltinTypes.Object, ec.CurrentBlock, loc);
+			expr_copy.Resolve (ec);
+
+			//
+			// Ensure Monitor methods are available
+			//
+			if (ResolvePredefinedMethods (ec) > 1) {
+				lock_taken = TemporaryVariableReference.Create (ec.BuiltinTypes.Bool, ec.CurrentBlock, loc);
+				lock_taken.Resolve (ec);
+			}
+
+			using (ec.Set (ResolveContext.Options.LockScope)) {
+				base.Resolve (ec);
+			}
+
+			if (lv != null) {
+				lv.IsLockedByStatement = locked;
+			}
+
+			return true;
+		}
+		
+		protected override void EmitTryBodyPrepare (EmitContext ec)
+		{
+			expr_copy.EmitAssign (ec, expr);
+
+			if (lock_taken != null) {
+				//
+				// Initialize ref variable
+				//
+				lock_taken.EmitAssign (ec, new BoolLiteral (ec.BuiltinTypes, false, loc));
+			} else {
+				//
+				// Monitor.Enter (expr_copy)
+				//
+				expr_copy.Emit (ec);
+				ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter.Get ());
+			}
+
+			base.EmitTryBodyPrepare (ec);
+		}
+
+		protected override void EmitTryBody (EmitContext ec)
+		{
+			//
+			// Monitor.Enter (expr_copy, ref lock_taken)
+			//
+			if (lock_taken != null) {
+				expr_copy.Emit (ec);
+				lock_taken.LocalInfo.CreateBuilder (ec);
+				lock_taken.AddressOf (ec, AddressOp.Load);
+				ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter_v4.Get ());
+			}
+
+			Statement.Emit (ec);
+		}
+
+		public override void EmitFinallyBody (EmitContext ec)
+		{
+			//
+			// if (lock_taken) Monitor.Exit (expr_copy)
+			//
+			Label skip = ec.DefineLabel ();
+
+			if (lock_taken != null) {
+				lock_taken.Emit (ec);
+				ec.Emit (OpCodes.Brfalse_S, skip);
+			}
+
+			expr_copy.Emit (ec);
+			var m = ec.Module.PredefinedMembers.MonitorExit.Resolve (loc);
+			if (m != null)
+				ec.Emit (OpCodes.Call, m);
+
+			ec.MarkLabel (skip);
+		}
+
+		int ResolvePredefinedMethods (ResolveContext rc)
+		{
+			// Try 4.0 Monitor.Enter (object, ref bool) overload first
+			var m = rc.Module.PredefinedMembers.MonitorEnter_v4.Get ();
+			if (m != null)
+				return 4;
+
+			m = rc.Module.PredefinedMembers.MonitorEnter.Get ();
+			if (m != null)
+				return 1;
+
+			rc.Module.PredefinedMembers.MonitorEnter_v4.Resolve (loc);
+			return 0;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Lock target = (Lock) t;
+
+			target.expr = expr.Clone (clonectx);
+			target.stmt = Statement.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+
+	}
+
+	public class Unchecked : Statement {
+		public Block Block;
+		
+		public Unchecked (Block b, Location loc)
+		{
+			Block = b;
+			b.Unchecked = true;
+			this.loc = loc;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
+				return Block.Resolve (ec);
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			using (ec.With (EmitContext.Options.CheckedScope, false))
+				Block.Emit (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return Block.FlowAnalysis (fc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Block.MarkReachable (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Unchecked target = (Unchecked) t;
+
+			target.Block = clonectx.LookupBlock (Block);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Checked : Statement {
+		public Block Block;
+		
+		public Checked (Block b, Location loc)
+		{
+			Block = b;
+			b.Unchecked = false;
+			this.loc = loc;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
+				return Block.Resolve (ec);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			using (ec.With (EmitContext.Options.CheckedScope, true))
+				Block.Emit (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return Block.FlowAnalysis (fc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Block.MarkReachable (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Checked target = (Checked) t;
+
+			target.Block = clonectx.LookupBlock (Block);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Unsafe : Statement {
+		public Block Block;
+
+		public Unsafe (Block b, Location loc)
+		{
+			Block = b;
+			Block.Unsafe = true;
+			this.loc = loc;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			if (ec.CurrentIterator != null)
+				ec.Report.Error (1629, loc, "Unsafe code may not appear in iterators");
+
+			using (ec.Set (ResolveContext.Options.UnsafeScope))
+				return Block.Resolve (ec);
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			Block.Emit (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			return Block.FlowAnalysis (fc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+			return Block.MarkReachable (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Unsafe target = (Unsafe) t;
+
+			target.Block = clonectx.LookupBlock (Block);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	// 
+	// Fixed statement
+	//
+	public class Fixed : Statement
+	{
+		abstract class Emitter : ShimExpression
+		{
+			protected LocalVariable vi;
+
+			protected Emitter (Expression expr, LocalVariable li)
+				: base (expr)
+			{
+				vi = li;
+			}
+
+			public abstract void EmitExit (EmitContext ec);
+
+			public override void FlowAnalysis (FlowAnalysisContext fc)
+			{
+				expr.FlowAnalysis (fc);
+			}
+		}
+
+		class ExpressionEmitter : Emitter {
+			public ExpressionEmitter (Expression converted, LocalVariable li) :
+				base (converted, li)
+			{
+			}
+
+			protected override Expression DoResolve (ResolveContext rc)
+			{
+				throw new NotImplementedException ();
+			}
+
+			public override void Emit (EmitContext ec) {
+				//
+				// Store pointer in pinned location
+				//
+				expr.Emit (ec);
+				vi.EmitAssign (ec);
+			}
+
+			public override void EmitExit (EmitContext ec)
+			{
+				ec.EmitInt (0);
+				ec.Emit (OpCodes.Conv_U);
+				vi.EmitAssign (ec);
+			}
+		}
+
+		class StringEmitter : Emitter
+		{
+			LocalVariable pinned_string;
+
+			public StringEmitter (Expression expr, LocalVariable li)
+				: base (expr, li)
+			{
+			}
+
+			protected override Expression DoResolve (ResolveContext rc)
+			{
+				pinned_string = new LocalVariable (vi.Block, "$pinned",
+					LocalVariable.Flags.FixedVariable | LocalVariable.Flags.CompilerGenerated | LocalVariable.Flags.Used,
+					vi.Location);
+				pinned_string.Type = rc.BuiltinTypes.String;
+
+				eclass = ExprClass.Variable;
+				type = rc.BuiltinTypes.Int;
+				return this;
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				pinned_string.CreateBuilder (ec);
+
+				expr.Emit (ec);
+				pinned_string.EmitAssign (ec);
+
+				// TODO: Should use Binary::Add
+				pinned_string.Emit (ec);
+				ec.Emit (OpCodes.Conv_I);
+
+				var m = ec.Module.PredefinedMembers.RuntimeHelpersOffsetToStringData.Resolve (loc);
+				if (m == null)
+					return;
+
+				PropertyExpr pe = new PropertyExpr (m, pinned_string.Location);
+				//pe.InstanceExpression = pinned_string;
+				pe.Resolve (new ResolveContext (ec.MemberContext)).Emit (ec);
+
+				ec.Emit (OpCodes.Add);
+				vi.EmitAssign (ec);
+			}
+
+			public override void EmitExit (EmitContext ec)
+			{
+				ec.EmitNull ();
+				pinned_string.EmitAssign (ec);
+			}
+		}
+
+		public class VariableDeclaration : BlockVariable
+		{
+			public VariableDeclaration (FullNamedExpression type, LocalVariable li)
+				: base (type, li)
+			{
+			}
+
+			protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
+			{
+				if (!Variable.Type.IsPointer && li == Variable) {
+					bc.Report.Error (209, TypeExpression.Location,
+						"The type of locals declared in a fixed statement must be a pointer type");
+					return null;
+				}
+
+				//
+				// The rules for the possible declarators are pretty wise,
+				// but the production on the grammar is more concise.
+				//
+				// So we have to enforce these rules here.
+				//
+				// We do not resolve before doing the case 1 test,
+				// because the grammar is explicit in that the token &
+				// is present, so we need to test for this particular case.
+				//
+
+				if (initializer is Cast) {
+					bc.Report.Error (254, initializer.Location, "The right hand side of a fixed statement assignment may not be a cast expression");
+					return null;
+				}
+
+				initializer = initializer.Resolve (bc);
+
+				if (initializer == null)
+					return null;
+
+				//
+				// Case 1: Array
+				//
+				if (initializer.Type.IsArray) {
+					TypeSpec array_type = TypeManager.GetElementType (initializer.Type);
+
+					//
+					// Provided that array_type is unmanaged,
+					//
+					if (!TypeManager.VerifyUnmanaged (bc.Module, array_type, loc))
+						return null;
+
+					//
+					// and T* is implicitly convertible to the
+					// pointer type given in the fixed statement.
+					//
+					ArrayPtr array_ptr = new ArrayPtr (initializer, array_type, loc);
+
+					Expression converted = Convert.ImplicitConversionRequired (bc, array_ptr.Resolve (bc), li.Type, loc);
+					if (converted == null)
+						return null;
+
+					//
+					// fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
+					//
+					converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
+						new Binary (Binary.Operator.Equality, initializer, new NullLiteral (loc)),
+						new Binary (Binary.Operator.Equality, new MemberAccess (initializer, "Length"), new IntConstant (bc.BuiltinTypes, 0, loc)))),
+							new NullLiteral (loc),
+							converted, loc);
+
+					converted = converted.Resolve (bc);
+
+					return new ExpressionEmitter (converted, li);
+				}
+
+				//
+				// Case 2: string
+				//
+				if (initializer.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
+					return new StringEmitter (initializer, li).Resolve (bc);
+				}
+
+				// Case 3: fixed buffer
+				if (initializer is FixedBufferPtr) {
+					return new ExpressionEmitter (initializer, li);
+				}
+
+				//
+				// Case 4: & object.
+				//
+				bool already_fixed = true;
+				Unary u = initializer as Unary;
+				if (u != null && u.Oper == Unary.Operator.AddressOf) {
+					IVariableReference vr = u.Expr as IVariableReference;
+					if (vr == null || !vr.IsFixed) {
+						already_fixed = false;
+					}
+				}
+
+				if (already_fixed) {
+					bc.Report.Error (213, loc, "You cannot use the fixed statement to take the address of an already fixed expression");
+				}
+
+				initializer = Convert.ImplicitConversionRequired (bc, initializer, li.Type, loc);
+				return new ExpressionEmitter (initializer, li);
+			}
+		}
+
+
+		VariableDeclaration decl;
+		Statement statement;
+		bool has_ret;
+
+		public Fixed (VariableDeclaration decl, Statement stmt, Location l)
+		{
+			this.decl = decl;
+			statement = stmt;
+			loc = l;
+		}
+
+		#region Properties
+
+		public Statement Statement {
+			get {
+				return statement;
+			}
+		}
+
+		public BlockVariable Variables {
+			get {
+				return decl;
+			}
+		}
+
+		#endregion
+
+		public override bool Resolve (BlockContext bc)
+		{
+			using (bc.Set (ResolveContext.Options.FixedInitializerScope)) {
+				if (!decl.Resolve (bc))
+					return false;
+			}
+
+			return statement.Resolve (bc);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			decl.FlowAnalysis (fc);
+			return statement.FlowAnalysis (fc);
+		}
+		
+		protected override void DoEmit (EmitContext ec)
+		{
+			decl.Variable.CreateBuilder (ec);
+			decl.Initializer.Emit (ec);
+			if (decl.Declarators != null) {
+				foreach (var d in decl.Declarators) {
+					d.Variable.CreateBuilder (ec);
+					d.Initializer.Emit (ec);
+				}
+			}
+
+			statement.Emit (ec);
+
+			if (has_ret)
+				return;
+
+			//
+			// Clear the pinned variable
+			//
+			((Emitter) decl.Initializer).EmitExit (ec);
+			if (decl.Declarators != null) {
+				foreach (var d in decl.Declarators) {
+					((Emitter)d.Initializer).EmitExit (ec);
+				}
+			}
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			decl.MarkReachable (rc);
+
+			rc = statement.MarkReachable (rc);
+
+			// TODO: What if there is local exit?
+			has_ret = rc.IsUnreachable;
+			return rc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Fixed target = (Fixed) t;
+
+			target.decl = (VariableDeclaration) decl.Clone (clonectx);
+			target.statement = statement.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Catch : Statement
+	{
+		class FilterStatement : Statement
+		{
+			readonly Catch ctch;
+
+			public FilterStatement (Catch ctch)
+			{
+				this.ctch = ctch;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				if (ctch.li != null) {
+					if (ctch.hoisted_temp != null)
+						ctch.hoisted_temp.Emit (ec);
+					else
+						ctch.li.Emit (ec);
+
+					if (!ctch.IsGeneral && ctch.type.Kind == MemberKind.TypeParameter)
+						ec.Emit (OpCodes.Box, ctch.type);
+				}
+
+				var expr_start = ec.DefineLabel ();
+				var end = ec.DefineLabel ();
+
+				ec.Emit (OpCodes.Brtrue_S, expr_start);
+				ec.EmitInt (0);
+				ec.Emit (OpCodes.Br, end);
+				ec.MarkLabel (expr_start);
+
+				ctch.Filter.Emit (ec);
+
+				ec.MarkLabel (end);
+				ec.Emit (OpCodes.Endfilter);
+				ec.BeginFilterHandler ();
+				ec.Emit (OpCodes.Pop);
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				ctch.Filter.FlowAnalysis (fc);
+				return true;
+			}
+
+			public override bool Resolve (BlockContext bc)
+			{
+				ctch.Filter = ctch.Filter.Resolve (bc);
+
+				if (ctch.Filter != null) {
+					if (ctch.Filter.ContainsEmitWithAwait ()) {
+						bc.Report.Error (7094, ctch.Filter.Location, "The `await' operator cannot be used in the filter expression of a catch clause");
+					}
+
+					var c = ctch.Filter as Constant;
+					if (c != null && !c.IsDefaultValue) {
+						bc.Report.Warning (7095, 1, ctch.Filter.Location, "Exception filter expression is a constant");
+					}
+				}
+
+				return true;
+			}
+		}
+
+		ExplicitBlock block;
+		LocalVariable li;
+		FullNamedExpression type_expr;
+		CompilerAssign assign;
+		TypeSpec type;
+		LocalTemporary hoisted_temp;
+
+		public Catch (ExplicitBlock block, Location loc)
+		{
+			this.block = block;
+			this.loc = loc;
+		}
+
+		#region Properties
+
+		public ExplicitBlock Block {
+			get {
+				return block;
+			}
+		}
+
+		public TypeSpec CatchType {
+			get {
+				return type;
+			}
+		}
+
+		public Expression Filter {
+			get; set;
+		}
+
+		public bool IsGeneral {
+			get {
+				return type_expr == null;
+			}
+		}
+
+		public FullNamedExpression TypeExpression {
+			get {
+				return type_expr;
+			}
+			set {
+				type_expr = value;
+			}
+		}
+
+		public LocalVariable Variable {
+			get {
+				return li;
+			}
+			set {
+				li = value;
+			}
+		}
+
+		#endregion
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			if (Filter != null) {
+				ec.BeginExceptionFilterBlock ();
+				ec.Emit (OpCodes.Isinst, IsGeneral ? ec.BuiltinTypes.Object : CatchType);
+
+				if (li != null)
+					EmitCatchVariableStore (ec);
+
+				if (Block.HasAwait) {
+					Block.EmitScopeInitialization (ec);
+				} else {
+					Block.Emit (ec);
+				}
+
+				return;
+			}
+
+			if (IsGeneral)
+				ec.BeginCatchBlock (ec.BuiltinTypes.Object);
+			else
+				ec.BeginCatchBlock (CatchType);
+
+			if (li != null) {
+				EmitCatchVariableStore (ec);
+			} else {
+				ec.Emit (OpCodes.Pop);
+			}
+
+			if (!Block.HasAwait)
+				Block.Emit (ec);
+		}
+
+		void EmitCatchVariableStore (EmitContext ec)
+		{
+			li.CreateBuilder (ec);
+
+			//
+			// Special case hoisted catch variable, we have to use a temporary variable
+			// to pass via anonymous storey initialization with the value still on top
+			// of the stack
+			//
+			if (li.HoistedVariant != null) {
+				hoisted_temp = new LocalTemporary (li.Type);
+				hoisted_temp.Store (ec);
+
+				// switch to assignment from temporary variable and not from top of the stack
+				assign.UpdateSource (hoisted_temp);
+			}
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			using (bc.Set (ResolveContext.Options.CatchScope)) {
+				if (type_expr == null) {
+					if (CreateExceptionVariable (bc.Module.Compiler.BuiltinTypes.Object)) {
+						Expression source = new EmptyExpression (li.Type);
+						assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
+						Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
+					}
+				} else {
+					type = type_expr.ResolveAsType (bc);
+					if (type == null)
+						return false;
+
+					if (li == null)
+						CreateExceptionVariable (type);
+
+					if (type.BuiltinType != BuiltinTypeSpec.Type.Exception && !TypeSpec.IsBaseClass (type, bc.BuiltinTypes.Exception, false)) {
+						bc.Report.Error (155, loc, "The type caught or thrown must be derived from System.Exception");
+					} else if (li != null) {
+						li.Type = type;
+						li.PrepareAssignmentAnalysis (bc);
+
+						// source variable is at the top of the stack
+						Expression source = new EmptyExpression (li.Type);
+						if (li.Type.IsGenericParameter)
+							source = new UnboxCast (source, li.Type);
+
+						//
+						// Uses Location.Null to hide from symbol file
+						//
+						assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
+						Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
+					}
+				}
+
+				if (Filter != null) {
+					Block.AddScopeStatement (new FilterStatement (this));
+				}
+
+				Block.SetCatchBlock ();
+				return Block.Resolve (bc);
+			}
+		}
+
+		bool CreateExceptionVariable (TypeSpec type)
+		{
+			if (!Block.HasAwait)
+				return false;
+
+			// TODO: Scan the block for rethrow expression
+			//if (!Block.HasRethrow)
+			//	return;
+
+			li = LocalVariable.CreateCompilerGenerated (type, block, Location.Null);
+			return true;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			if (li != null && !li.IsCompilerGenerated) {
+				fc.SetVariableAssigned (li.VariableInfo, true);
+			}
+
+			return block.FlowAnalysis (fc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			var c = Filter as Constant;
+			if (c != null && c.IsDefaultValue)
+				return Reachability.CreateUnreachable ();
+
+			return block.MarkReachable (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Catch target = (Catch) t;
+
+			if (type_expr != null)
+				target.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
+
+			if (Filter != null)
+				target.Filter = Filter.Clone (clonectx);
+
+			target.block = (ExplicitBlock) clonectx.LookupBlock (block);
+		}
+	}
+
+	public class TryFinally : TryFinallyBlock
+	{
+		ExplicitBlock fini;
+		List<DefiniteAssignmentBitSet> try_exit_dat;
+		List<Label> redirected_jumps;
+		Label? start_fin_label;
+
+		public Statement Stmt {
+			get { return this.stmt; }
+		}
+
+		public ExplicitBlock Fini {
+			get { return this.fini; }
+		}
+
+		public TryFinally (Statement stmt, ExplicitBlock fini, Location loc)
+			 : base (stmt, loc)
+		{
+			this.fini = fini;
+		}
+
+		public ExplicitBlock FinallyBlock {
+			get {
+ 				return fini;
+			}
+		}
+
+		public void RegisterForControlExitCheck (DefiniteAssignmentBitSet vector)
+		{
+			if (try_exit_dat == null)
+				try_exit_dat = new List<DefiniteAssignmentBitSet> ();
+
+			try_exit_dat.Add (vector);
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			bool ok = base.Resolve (bc);
+
+			fini.SetFinallyBlock ();
+			using (bc.Set (ResolveContext.Options.FinallyScope)) {
+				ok &= fini.Resolve (bc);
+			}
+
+			return ok;
+		}
+
+		protected override void EmitTryBody (EmitContext ec)
+		{
+			if (fini.HasAwait) {
+				if (ec.TryFinallyUnwind == null)
+					ec.TryFinallyUnwind = new List<TryFinally> ();
+
+				ec.TryFinallyUnwind.Add (this);
+				stmt.Emit (ec);
+				ec.TryFinallyUnwind.Remove (this);
+
+				if (start_fin_label != null)
+					ec.MarkLabel (start_fin_label.Value);
+
+				return;
+			}
+
+			stmt.Emit (ec);
+		}
+
+		protected override bool EmitBeginFinallyBlock (EmitContext ec)
+		{
+			if (fini.HasAwait)
+				return false;
+
+			return base.EmitBeginFinallyBlock (ec);
+		}
+
+		public override void EmitFinallyBody (EmitContext ec)
+		{
+			if (!fini.HasAwait) {
+				fini.Emit (ec);
+				return;
+			}
+
+			//
+			// Emits catch block like
+			//
+			// catch (object temp) {
+			//	this.exception_field = temp;
+			// }
+			//
+			var type = ec.BuiltinTypes.Object;
+			ec.BeginCatchBlock (type);
+
+			var temp = ec.GetTemporaryLocal (type);
+			ec.Emit (OpCodes.Stloc, temp);
+
+			var exception_field = ec.GetTemporaryField (type);
+			ec.EmitThis ();
+			ec.Emit (OpCodes.Ldloc, temp);
+			exception_field.EmitAssignFromStack (ec);
+
+			ec.EndExceptionBlock ();
+
+			ec.FreeTemporaryLocal (temp, type);
+
+			fini.Emit (ec);
+
+			//
+			// Emits exception rethrow
+			//
+			// if (this.exception_field != null)
+			//	throw this.exception_field;
+			//
+			exception_field.Emit (ec);
+			var skip_throw = ec.DefineLabel ();
+			ec.Emit (OpCodes.Brfalse_S, skip_throw);
+			exception_field.Emit (ec);
+			ec.Emit (OpCodes.Throw);
+			ec.MarkLabel (skip_throw);
+
+			exception_field.IsAvailableForReuse = true;
+
+			EmitUnwindFinallyTable (ec);
+		}
+
+		bool IsParentBlock (Block block)
+		{
+			for (Block b = fini; b != null; b = b.Parent) {
+				if (b == block)
+					return true;
+			}
+
+			return false;
+		}
+
+		public static Label EmitRedirectedJump (EmitContext ec, AsyncInitializer initializer, Label label, Block labelBlock)
+		{
+			int idx;
+			if (labelBlock != null) {
+				for (idx = ec.TryFinallyUnwind.Count; idx != 0; --idx) {
+					var fin = ec.TryFinallyUnwind [idx - 1];
+					if (!fin.IsParentBlock (labelBlock))
+						break;
+				}
+			} else {
+				idx = 0;
+			}
+
+			bool set_return_state = true;
+
+			for (; idx < ec.TryFinallyUnwind.Count; ++idx) {
+				var fin = ec.TryFinallyUnwind [idx];
+				if (labelBlock != null && !fin.IsParentBlock (labelBlock))
+					break;
+
+				fin.EmitRedirectedExit (ec, label, initializer, set_return_state);
+				set_return_state = false;
+
+				if (fin.start_fin_label == null) {
+					fin.start_fin_label = ec.DefineLabel ();
+				}
+
+				label = fin.start_fin_label.Value;
+			}
+
+			return label;
+		}
+
+		public static Label EmitRedirectedReturn (EmitContext ec, AsyncInitializer initializer)
+		{
+			return EmitRedirectedJump (ec, initializer, initializer.BodyEnd, null);
+		}
+
+		void EmitRedirectedExit (EmitContext ec, Label label, AsyncInitializer initializer, bool setReturnState)
+		{
+			if (redirected_jumps == null) {
+				redirected_jumps = new List<Label> ();
+
+				// Add fallthrough label
+				redirected_jumps.Add (ec.DefineLabel ());
+
+				if (setReturnState)
+					initializer.HoistedReturnState = ec.GetTemporaryField (ec.Module.Compiler.BuiltinTypes.Int, true);
+			}
+
+			int index = redirected_jumps.IndexOf (label);
+			if (index < 0) {
+				redirected_jumps.Add (label);
+				index = redirected_jumps.Count - 1;
+			}
+
+			//
+			// Indicates we have captured exit jump
+			//
+			if (setReturnState) {
+				var value = new IntConstant (initializer.HoistedReturnState.Type, index, Location.Null);
+				initializer.HoistedReturnState.EmitAssign (ec, value, false, false);
+			}
+		}
+
+		//
+		// Emits state table of jumps outside of try block and reload of return
+		// value when try block returns value
+		//
+		void EmitUnwindFinallyTable (EmitContext ec)
+		{
+			if (redirected_jumps == null)
+				return;
+
+			var initializer = (AsyncInitializer)ec.CurrentAnonymousMethod;
+			initializer.HoistedReturnState.EmitLoad (ec);
+			ec.Emit (OpCodes.Switch, redirected_jumps.ToArray ());
+
+			// Mark fallthrough label
+			ec.MarkLabel (redirected_jumps [0]);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			var da = fc.BranchDefiniteAssignment ();
+
+			var tf = fc.TryFinally;
+			fc.TryFinally = this;
+
+			var res_stmt = Statement.FlowAnalysis (fc);
+
+			fc.TryFinally = tf;
+
+			var try_da = fc.DefiniteAssignment;
+			fc.DefiniteAssignment = da;
+
+			var res_fin = fini.FlowAnalysis (fc);
+
+			if (try_exit_dat != null) {
+				//
+				// try block has global exit but we need to run definite assignment check
+				// for parameter block out parameter after finally block because it's always
+				// executed before exit
+				//
+				foreach (var try_da_part in try_exit_dat)
+					fc.ParametersBlock.CheckControlExit (fc, fc.DefiniteAssignment | try_da_part);
+
+				try_exit_dat = null;
+			}
+
+			fc.DefiniteAssignment |= try_da;
+			return res_stmt | res_fin;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			//
+			// Mark finally block first for any exit statement in try block
+			// to know whether the code which follows finally is reachable
+			//
+			return fini.MarkReachable (rc) | base.MarkReachable (rc);
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			TryFinally target = (TryFinally) t;
+
+			target.stmt = stmt.Clone (clonectx);
+			if (fini != null)
+				target.fini = (ExplicitBlock) clonectx.LookupBlock (fini);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class TryCatch : ExceptionStatement
+	{
+		public Block Block;
+		List<Catch> clauses;
+		readonly bool inside_try_finally;
+		List<Catch> catch_sm;
+
+		public TryCatch (Block block, List<Catch> catch_clauses, Location l, bool inside_try_finally)
+			: base (l)
+		{
+			this.Block = block;
+			this.clauses = catch_clauses;
+			this.inside_try_finally = inside_try_finally;
+		}
+
+		public List<Catch> Clauses {
+			get {
+				return clauses;
+			}
+		}
+
+		public bool IsTryCatchFinally {
+			get {
+				return inside_try_finally;
+			}
+		}
+
+		public override bool Resolve (BlockContext bc)
+		{
+			bool ok;
+
+			using (bc.Set (ResolveContext.Options.TryScope)) {
+				parent = bc.CurrentTryBlock;
+
+				if (IsTryCatchFinally) {
+					ok = Block.Resolve (bc);
+				} else {
+					using (bc.Set (ResolveContext.Options.TryWithCatchScope)) {
+						bc.CurrentTryBlock = this;
+						ok = Block.Resolve (bc);
+						bc.CurrentTryBlock = parent;
+					}
+				}
+			}
+
+			for (int i = 0; i < clauses.Count; ++i) {
+				var c = clauses[i];
+
+				ok &= c.Resolve (bc);
+
+				if (c.Block.HasAwait) {
+					if (catch_sm == null)
+						catch_sm = new List<Catch> ();
+
+					catch_sm.Add (c);
+				}
+
+				if (c.Filter != null)
+					continue;
+
+				TypeSpec resolved_type = c.CatchType;
+				if (resolved_type == null)
+					continue;
+
+				for (int ii = 0; ii < clauses.Count; ++ii) {
+					if (ii == i)
+						continue;
+
+					if (clauses[ii].Filter != null)
+						continue;
+
+					if (clauses[ii].IsGeneral) {
+						if (resolved_type.BuiltinType != BuiltinTypeSpec.Type.Exception)
+							continue;
+
+						if (!bc.Module.DeclaringAssembly.WrapNonExceptionThrows)
+							continue;
+
+						if (!bc.Module.PredefinedAttributes.RuntimeCompatibility.IsDefined)
+							continue;
+
+						bc.Report.Warning (1058, 1, c.loc,
+							"A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
+
+						continue;
+					}
+
+					if (ii >= i)
+						continue;
+
+					var ct = clauses[ii].CatchType;
+					if (ct == null)
+						continue;
+
+					if (resolved_type == ct || TypeSpec.IsBaseClass (resolved_type, ct, true)) {
+						bc.Report.Error (160, c.loc,
+							"A previous catch clause already catches all exceptions of this or a super type `{0}'",
+							ct.GetSignatureForError ());
+						ok = false;
+					}
+				}
+			}
+
+			return base.Resolve (bc) && ok;
+		}
+
+		protected sealed override void DoEmit (EmitContext ec)
+		{
+			if (!inside_try_finally)
+				EmitTryBodyPrepare (ec);
+
+			Block.Emit (ec);
+
+			LocalBuilder state_variable = null;
+			foreach (Catch c in clauses) {
+				c.Emit (ec);
+
+				if (catch_sm != null) {
+					if (state_variable == null) {
+						//
+						// Cannot reuse temp variable because non-catch path assumes the value is 0
+						// which may not be true for reused local variable
+						//
+						state_variable = ec.DeclareLocal (ec.Module.Compiler.BuiltinTypes.Int, false);
+					}
+
+					var index = catch_sm.IndexOf (c);
+					if (index < 0)
+						continue;
+
+					ec.EmitInt (index + 1);
+					ec.Emit (OpCodes.Stloc, state_variable);
+				}
+			}
+
+			if (!inside_try_finally)
+				ec.EndExceptionBlock ();
+
+			if (state_variable != null) {
+				ec.Emit (OpCodes.Ldloc, state_variable);
+
+				var labels = new Label [catch_sm.Count + 1];
+				for (int i = 0; i < labels.Length; ++i) {
+					labels [i] = ec.DefineLabel ();
+				}
+
+				var end = ec.DefineLabel ();
+				ec.Emit (OpCodes.Switch, labels);
+
+				// 0 value is default label
+				ec.MarkLabel (labels [0]);
+				ec.Emit (OpCodes.Br, end);
+
+				var atv = ec.AsyncThrowVariable;
+				Catch c = null;
+				for (int i = 0; i < catch_sm.Count; ++i) {
+					if (c != null && c.Block.HasReachableClosingBrace)
+						ec.Emit (OpCodes.Br, end);
+
+					ec.MarkLabel (labels [i + 1]);
+					c = catch_sm [i];
+					ec.AsyncThrowVariable = c.Variable;
+					c.Block.Emit (ec);
+				}
+				ec.AsyncThrowVariable = atv;
+
+				ec.MarkLabel (end);
+			}
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			var start_fc = fc.BranchDefiniteAssignment ();
+			var res = Block.FlowAnalysis (fc);
+
+			DefiniteAssignmentBitSet try_fc = res ? null : fc.DefiniteAssignment;
+
+			foreach (var c in clauses) {
+				fc.DefiniteAssignment = new DefiniteAssignmentBitSet (start_fc);
+				if (!c.FlowAnalysis (fc)) {
+					if (try_fc == null)
+						try_fc = fc.DefiniteAssignment;
+					else
+						try_fc &= fc.DefiniteAssignment;
+
+					res = false;
+				}
+			}
+
+			fc.DefiniteAssignment = try_fc ?? start_fc;
+			parent = null;
+			return res;
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			if (rc.IsUnreachable)
+				return rc;
+
+			base.MarkReachable (rc);
+
+			var tc_rc = Block.MarkReachable (rc);
+
+			foreach (var c in clauses)
+				tc_rc &= c.MarkReachable (rc);
+
+			return tc_rc;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			TryCatch target = (TryCatch) t;
+
+			target.Block = clonectx.LookupBlock (Block);
+			if (clauses != null){
+				target.clauses = new List<Catch> ();
+				foreach (Catch c in clauses)
+					target.clauses.Add ((Catch) c.Clone (clonectx));
+			}
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	public class Using : TryFinallyBlock
+	{
+		public class VariableDeclaration : BlockVariable
+		{
+			Statement dispose_call;
+
+			public VariableDeclaration (FullNamedExpression type, LocalVariable li)
+				: base (type, li)
+			{
+			}
+
+			public VariableDeclaration (LocalVariable li, Location loc)
+				: base (li)
+			{
+				reachable = true;
+				this.loc = loc;
+			}
+
+			public VariableDeclaration (Expression expr)
+				: base (null)
+			{
+				loc = expr.Location;
+				Initializer = expr;
+			}
+
+			#region Properties
+
+			public bool IsNested { get; private set; }
+
+			#endregion
+
+			public void EmitDispose (EmitContext ec)
+			{
+				dispose_call.Emit (ec);
+			}
+
+			public override bool Resolve (BlockContext bc)
+			{
+				if (IsNested)
+					return true;
+
+				return base.Resolve (bc, false);
+			}
+
+			public Expression ResolveExpression (BlockContext bc)
+			{
+				var e = Initializer.Resolve (bc);
+				if (e == null)
+					return null;
+
+				li = LocalVariable.CreateCompilerGenerated (e.Type, bc.CurrentBlock, loc);
+				Initializer = ResolveInitializer (bc, Variable, e);
+				return e;
+			}
+
+			protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
+			{
+				if (li.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
+					initializer = initializer.Resolve (bc);
+					if (initializer == null)
+						return null;
+
+					// Once there is dynamic used defer conversion to runtime even if we know it will never succeed
+					Arguments args = new Arguments (1);
+					args.Add (new Argument (initializer));
+					initializer = new DynamicConversion (bc.BuiltinTypes.IDisposable, 0, args, initializer.Location).Resolve (bc);
+					if (initializer == null)
+						return null;
+
+					var var = LocalVariable.CreateCompilerGenerated (initializer.Type, bc.CurrentBlock, loc);
+					dispose_call = CreateDisposeCall (bc, var);
+					dispose_call.Resolve (bc);
+
+					return base.ResolveInitializer (bc, li, new SimpleAssign (var.CreateReferenceExpression (bc, loc), initializer, loc));
+				}
+
+				if (li == Variable) {
+					CheckIDiposableConversion (bc, li, initializer);
+					dispose_call = CreateDisposeCall (bc, li);
+					dispose_call.Resolve (bc);
+				}
+
+				return base.ResolveInitializer (bc, li, initializer);
+			}
+
+			protected virtual void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
+			{
+				var type = li.Type;
+
+				if (type.BuiltinType != BuiltinTypeSpec.Type.IDisposable && !CanConvertToIDisposable (bc, type)) {
+					if (type.IsNullableType) {
+						// it's handled in CreateDisposeCall
+						return;
+					}
+
+					if (type != InternalType.ErrorType) {
+						bc.Report.SymbolRelatedToPreviousError (type);
+						var loc = type_expr == null ? initializer.Location : type_expr.Location;
+						bc.Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
+							type.GetSignatureForError ());
+					}
+
+					return;
+				}
+			}
+
+			static bool CanConvertToIDisposable (BlockContext bc, TypeSpec type)
+			{
+				var target = bc.BuiltinTypes.IDisposable;
+				var tp = type as TypeParameterSpec;
+				if (tp != null)
+					return Convert.ImplicitTypeParameterConversion (null, tp, target) != null;
+
+				return type.ImplementsInterface (target, false);
+			}
+
+			protected virtual Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
+			{
+				var lvr = lv.CreateReferenceExpression (bc, lv.Location);
+				var type = lv.Type;
+				var loc = lv.Location;
+
+				var idt = bc.BuiltinTypes.IDisposable;
+				var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
+
+				var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
+				dispose_mg.InstanceExpression = type.IsNullableType ?
+					new Cast (new TypeExpression (idt, loc), lvr, loc).Resolve (bc) :
+					lvr;
+
+				//
+				// Hide it from symbol file via null location
+				//
+				Statement dispose = new StatementExpression (new Invocation (dispose_mg, null), Location.Null);
+
+				// Add conditional call when disposing possible null variable
+				if (!TypeSpec.IsValueType (type) || type.IsNullableType)
+					dispose = new If (new Binary (Binary.Operator.Inequality, lvr, new NullLiteral (loc)), dispose, dispose.loc);
+
+				return dispose;
+			}
+
+			public void ResolveDeclaratorInitializer (BlockContext bc)
+			{
+				Initializer = base.ResolveInitializer (bc, Variable, Initializer);
+			}
+
+			public Statement RewriteUsingDeclarators (BlockContext bc, Statement stmt)
+			{
+				for (int i = declarators.Count - 1; i >= 0; --i) {
+					var d = declarators [i];
+					var vd = new VariableDeclaration (d.Variable, d.Variable.Location);
+					vd.Initializer = d.Initializer;
+					vd.IsNested = true;
+					vd.dispose_call = CreateDisposeCall (bc, d.Variable);
+					vd.dispose_call.Resolve (bc);
+
+					stmt = new Using (vd, stmt, d.Variable.Location);
+				}
+
+				declarators = null;
+				return stmt;
+			}	
+
+			public override object Accept (StructuralVisitor visitor)
+			{
+				return visitor.Visit (this);
+			}	
+		}
+
+		VariableDeclaration decl;
+
+		public Using (VariableDeclaration decl, Statement stmt, Location loc)
+			: base (stmt, loc)
+		{
+			this.decl = decl;
+		}
+
+		public Using (Expression expr, Statement stmt, Location loc)
+			: base (stmt, loc)
+		{
+			this.decl = new VariableDeclaration (expr);
+		}
+
+		#region Properties
+
+		public Expression Expr {
+			get {
+				return decl.Variable == null ? decl.Initializer : null;
+			}
+		}
+
+		public BlockVariable Variables {
+			get {
+				return decl;
+			}
+		}
+
+		#endregion
+
+		public override void Emit (EmitContext ec)
+		{
+			//
+			// Don't emit sequence point it will be set on variable declaration
+			//
+			DoEmit (ec);
+		}
+
+		protected override void EmitTryBodyPrepare (EmitContext ec)
+		{
+			decl.Emit (ec);
+			base.EmitTryBodyPrepare (ec);
+		}
+
+		protected override void EmitTryBody (EmitContext ec)
+		{
+			stmt.Emit (ec);
+		}
+
+		public override void EmitFinallyBody (EmitContext ec)
+		{
+			decl.EmitDispose (ec);
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			decl.FlowAnalysis (fc);
+			return stmt.FlowAnalysis (fc);
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			decl.MarkReachable (rc);
+			return base.MarkReachable (rc);
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			VariableReference vr;
+			bool vr_locked = false;
+
+			using (ec.Set (ResolveContext.Options.UsingInitializerScope)) {
+				if (decl.Variable == null) {
+					vr = decl.ResolveExpression (ec) as VariableReference;
+					if (vr != null) {
+						vr_locked = vr.IsLockedByStatement;
+						vr.IsLockedByStatement = true;
+					}
+				} else {
+					if (decl.IsNested) {
+						decl.ResolveDeclaratorInitializer (ec);
+					} else {
+						if (!decl.Resolve (ec))
+							return false;
+
+						if (decl.Declarators != null) {
+							stmt = decl.RewriteUsingDeclarators (ec, stmt);
+						}
+					}
+
+					vr = null;
+				}
+			}
+
+			var ok = base.Resolve (ec);
+
+			if (vr != null)
+				vr.IsLockedByStatement = vr_locked;
+
+			return ok;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Using target = (Using) t;
+
+			target.decl = (VariableDeclaration) decl.Clone (clonectx);
+			target.stmt = stmt.Clone (clonectx);
+		}
+
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+
+	/// <summary>
+	///   Implementation of the foreach C# statement
+	/// </summary>
+	public class Foreach : LoopStatement
+	{
+		abstract class IteratorStatement : Statement
+		{
+			protected readonly Foreach for_each;
+
+			protected IteratorStatement (Foreach @foreach)
+			{
+				this.for_each = @foreach;
+				this.loc = @foreach.expr.Location;
+			}
+
+			protected override void CloneTo (CloneContext clonectx, Statement target)
+			{
+				throw new NotImplementedException ();
+			}
+
+			public override void Emit (EmitContext ec)
+			{
+				if (ec.EmitAccurateDebugInfo) {
+					ec.Emit (OpCodes.Nop);
+				}
+
+				base.Emit (ec);
+			}
+
+			protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+			{
+				throw new NotImplementedException ();
+			}
+		}
+
+		sealed class ArrayForeach : IteratorStatement
+		{
+			TemporaryVariableReference[] lengths;
+			Expression [] length_exprs;
+			StatementExpression[] counter;
+			TemporaryVariableReference[] variables;
+
+			TemporaryVariableReference copy;
+
+			public ArrayForeach (Foreach @foreach, int rank)
+				: base (@foreach)
+			{
+				counter = new StatementExpression[rank];
+				variables = new TemporaryVariableReference[rank];
+				length_exprs = new Expression [rank];
+
+				//
+				// Only use temporary length variables when dealing with
+				// multi-dimensional arrays
+				//
+				if (rank > 1)
+					lengths = new TemporaryVariableReference [rank];
+			}
+
+			public override bool Resolve (BlockContext ec)
+			{
+				Block variables_block = for_each.variable.Block;
+				copy = TemporaryVariableReference.Create (for_each.expr.Type, variables_block, loc);
+				copy.Resolve (ec);
+
+				int rank = length_exprs.Length;
+				Arguments list = new Arguments (rank);
+				for (int i = 0; i < rank; i++) {
+					var v = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
+					variables[i] = v;
+					counter[i] = new StatementExpression (new UnaryMutator (UnaryMutator.Mode.PostIncrement, v, Location.Null));
+					counter[i].Resolve (ec);
+
+					if (rank == 1) {
+						length_exprs [i] = new MemberAccess (copy, "Length").Resolve (ec);
+					} else {
+						lengths[i] = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
+						lengths[i].Resolve (ec);
+
+						Arguments args = new Arguments (1);
+						args.Add (new Argument (new IntConstant (ec.BuiltinTypes, i, loc)));
+						length_exprs [i] = new Invocation (new MemberAccess (copy, "GetLength"), args).Resolve (ec);
+					}
+
+					list.Add (new Argument (v));
+				}
+
+				var access = new ElementAccess (copy, list, loc).Resolve (ec);
+				if (access == null)
+					return false;
+
+				TypeSpec var_type;
+				if (for_each.type is VarExpr) {
+					// Infer implicitly typed local variable from foreach array type
+					var_type = access.Type;
+				} else {
+					var_type = for_each.type.ResolveAsType (ec);
+
+					if (var_type == null)
+						return false;
+
+					access = Convert.ExplicitConversion (ec, access, var_type, loc);
+					if (access == null)
+						return false;
+				}
+
+				for_each.variable.Type = var_type;
+
+				var variable_ref = new LocalVariableReference (for_each.variable, loc).Resolve (ec);
+				if (variable_ref == null)
+					return false;
+
+				for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, access, Location.Null), for_each.type.Location));
+
+				return for_each.body.Resolve (ec);
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				copy.EmitAssign (ec, for_each.expr);
+
+				int rank = length_exprs.Length;
+				Label[] test = new Label [rank];
+				Label[] loop = new Label [rank];
+
+				for (int i = 0; i < rank; i++) {
+					test [i] = ec.DefineLabel ();
+					loop [i] = ec.DefineLabel ();
+
+					if (lengths != null)
+						lengths [i].EmitAssign (ec, length_exprs [i]);
+				}
+
+				IntConstant zero = new IntConstant (ec.BuiltinTypes, 0, loc);
+				for (int i = 0; i < rank; i++) {
+					variables [i].EmitAssign (ec, zero);
+
+					ec.Emit (OpCodes.Br, test [i]);
+					ec.MarkLabel (loop [i]);
+				}
+
+				for_each.body.Emit (ec);
+
+				ec.MarkLabel (ec.LoopBegin);
+				ec.Mark (for_each.expr.Location);
+
+				for (int i = rank - 1; i >= 0; i--){
+					counter [i].Emit (ec);
+
+					ec.MarkLabel (test [i]);
+					variables [i].Emit (ec);
+
+					if (lengths != null)
+						lengths [i].Emit (ec);
+					else
+						length_exprs [i].Emit (ec);
+
+					ec.Emit (OpCodes.Blt, loop [i]);
+				}
+
+				ec.MarkLabel (ec.LoopEnd);
+			}
+		}
+
+		sealed class CollectionForeach : IteratorStatement, OverloadResolver.IErrorHandler
+		{
+			class RuntimeDispose : Using.VariableDeclaration
+			{
+				public RuntimeDispose (LocalVariable lv, Location loc)
+					: base (lv, loc)
+				{
+					reachable = true;
+				}
+
+				protected override void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
+				{
+					// Defered to runtime check
+				}
+
+				protected override Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
+				{
+					var idt = bc.BuiltinTypes.IDisposable;
+
+					//
+					// Fabricates code like
+					//
+					// if ((temp = vr as IDisposable) != null) temp.Dispose ();
+					//
+
+					var dispose_variable = LocalVariable.CreateCompilerGenerated (idt, bc.CurrentBlock, loc);
+
+					var idisaposable_test = new Binary (Binary.Operator.Inequality, new CompilerAssign (
+						dispose_variable.CreateReferenceExpression (bc, loc),
+						new As (lv.CreateReferenceExpression (bc, loc), new TypeExpression (dispose_variable.Type, loc), loc),
+						loc), new NullLiteral (loc));
+
+					var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
+
+					var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
+					dispose_mg.InstanceExpression = dispose_variable.CreateReferenceExpression (bc, loc);
+
+					Statement dispose = new StatementExpression (new Invocation (dispose_mg, null));
+					return new If (idisaposable_test, dispose, loc);
+				}
+			}
+
+			LocalVariable variable;
+			Expression expr;
+			Statement statement;
+			ExpressionStatement init;
+			TemporaryVariableReference enumerator_variable;
+			bool ambiguous_getenumerator_name;
+
+			public CollectionForeach (Foreach @foreach, LocalVariable var, Expression expr)
+				: base (@foreach)
+			{
+				this.variable = var;
+				this.expr = expr;
+			}
+
+			void Error_WrongEnumerator (ResolveContext rc, MethodSpec enumerator)
+			{
+				rc.Report.SymbolRelatedToPreviousError (enumerator);
+				rc.Report.Error (202, loc,
+					"foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
+						enumerator.ReturnType.GetSignatureForError (), enumerator.GetSignatureForError ());
+			}
+
+			MethodGroupExpr ResolveGetEnumerator (ResolveContext rc)
+			{
+				//
+				// Option 1: Try to match by name GetEnumerator first
+				//
+				var mexpr = Expression.MemberLookup (rc, false, expr.Type,
+					"GetEnumerator", 0, Expression.MemberLookupRestrictions.ExactArity, loc);		// TODO: What if CS0229 ?
+
+				var mg = mexpr as MethodGroupExpr;
+				if (mg != null) {
+					mg.InstanceExpression = expr;
+					Arguments args = new Arguments (0);
+					mg = mg.OverloadResolve (rc, ref args, this, OverloadResolver.Restrictions.ProbingOnly | OverloadResolver.Restrictions.GetEnumeratorLookup);
+
+					// For ambiguous GetEnumerator name warning CS0278 was reported, but Option 2 could still apply
+					if (ambiguous_getenumerator_name)
+						mg = null;
+
+					if (mg != null && !mg.BestCandidate.IsStatic && mg.BestCandidate.IsPublic) {
+						return mg;
+					}
+				}
+
+				//
+				// Option 2: Try to match using IEnumerable interfaces with preference of generic version
+				//
+				var t = expr.Type;
+				PredefinedMember<MethodSpec> iface_candidate = null;
+				var ptypes = rc.Module.PredefinedTypes;
+				var gen_ienumerable = ptypes.IEnumerableGeneric;
+				if (!gen_ienumerable.Define ())
+					gen_ienumerable = null;
+
+				var ifaces = t.Interfaces;
+				if (ifaces != null) {
+					foreach (var iface in ifaces) {
+						if (gen_ienumerable != null && iface.MemberDefinition == gen_ienumerable.TypeSpec.MemberDefinition) {
+							if (iface_candidate != null && iface_candidate != rc.Module.PredefinedMembers.IEnumerableGetEnumerator) {
+								rc.Report.SymbolRelatedToPreviousError (expr.Type);
+								rc.Report.Error (1640, loc,
+									"foreach statement cannot operate on variables of type `{0}' because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
+									expr.Type.GetSignatureForError (), gen_ienumerable.TypeSpec.GetSignatureForError ());
+
+								return null;
+							}
+
+							// TODO: Cache this somehow
+							iface_candidate = new PredefinedMember<MethodSpec> (rc.Module, iface,
+								MemberFilter.Method ("GetEnumerator", 0, ParametersCompiled.EmptyReadOnlyParameters, null));
+
+							continue;
+						}
+
+						if (iface.BuiltinType == BuiltinTypeSpec.Type.IEnumerable && iface_candidate == null) {
+							iface_candidate = rc.Module.PredefinedMembers.IEnumerableGetEnumerator;
+						}
+					}
+				}
+
+				if (iface_candidate == null) {
+					if (expr.Type != InternalType.ErrorType) {
+						rc.Report.Error (1579, loc,
+							"foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `{1}' or is inaccessible",
+							expr.Type.GetSignatureForError (), "GetEnumerator");
+					}
+
+					return null;
+				}
+
+				var method = iface_candidate.Resolve (loc);
+				if (method == null)
+					return null;
+
+				mg = MethodGroupExpr.CreatePredefined (method, expr.Type, loc);
+				mg.InstanceExpression = expr;
+				return mg;
+			}
+
+			MethodGroupExpr ResolveMoveNext (ResolveContext rc, MethodSpec enumerator)
+			{
+				var ms = MemberCache.FindMember (enumerator.ReturnType,
+					MemberFilter.Method ("MoveNext", 0, ParametersCompiled.EmptyReadOnlyParameters, rc.BuiltinTypes.Bool),
+					BindingRestriction.InstanceOnly) as MethodSpec;
+
+				if (ms == null || !ms.IsPublic) {
+					Error_WrongEnumerator (rc, enumerator);
+					return null;
+				}
+
+				return MethodGroupExpr.CreatePredefined (ms, enumerator.ReturnType, expr.Location);
+			}
+
+			PropertySpec ResolveCurrent (ResolveContext rc, MethodSpec enumerator)
+			{
+				var ps = MemberCache.FindMember (enumerator.ReturnType,
+					MemberFilter.Property ("Current", null),
+					BindingRestriction.InstanceOnly) as PropertySpec;
+
+				if (ps == null || !ps.IsPublic) {
+					Error_WrongEnumerator (rc, enumerator);
+					return null;
+				}
+
+				return ps;
+			}
+
+			public override bool Resolve (BlockContext ec)
+			{
+				bool is_dynamic = expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+
+				if (is_dynamic) {
+					expr = Convert.ImplicitConversionRequired (ec, expr, ec.BuiltinTypes.IEnumerable, loc);
+				} else if (expr.Type.IsNullableType) {
+					expr = new Nullable.UnwrapCall (expr).Resolve (ec);
+				}
+
+				var get_enumerator_mg = ResolveGetEnumerator (ec);
+				if (get_enumerator_mg == null) {
+					return false;
+				}
+
+				var get_enumerator = get_enumerator_mg.BestCandidate;
+				enumerator_variable = TemporaryVariableReference.Create (get_enumerator.ReturnType, variable.Block, loc);
+				enumerator_variable.Resolve (ec);
+
+				// Prepare bool MoveNext ()
+				var move_next_mg = ResolveMoveNext (ec, get_enumerator);
+				if (move_next_mg == null) {
+					return false;
+				}
+
+				move_next_mg.InstanceExpression = enumerator_variable;
+
+				// Prepare ~T~ Current { get; }
+				var current_prop = ResolveCurrent (ec, get_enumerator);
+				if (current_prop == null) {
+					return false;
+				}
+
+				var current_pe = new PropertyExpr (current_prop, loc) { InstanceExpression = enumerator_variable }.Resolve (ec);
+				if (current_pe == null)
+					return false;
+
+				VarExpr ve = for_each.type as VarExpr;
+
+				if (ve != null) {
+					if (is_dynamic) {
+						// Source type is dynamic, set element type to dynamic too
+						variable.Type = ec.BuiltinTypes.Dynamic;
+					} else {
+						// Infer implicitly typed local variable from foreach enumerable type
+						variable.Type = current_pe.Type;
+					}
+				} else {
+					if (is_dynamic) {
+						// Explicit cast of dynamic collection elements has to be done at runtime
+						current_pe = EmptyCast.Create (current_pe, ec.BuiltinTypes.Dynamic);
+					}
+
+					variable.Type = for_each.type.ResolveAsType (ec);
+
+					if (variable.Type == null)
+						return false;
+
+					current_pe = Convert.ExplicitConversion (ec, current_pe, variable.Type, loc);
+					if (current_pe == null)
+						return false;
+				}
+
+				var variable_ref = new LocalVariableReference (variable, loc).Resolve (ec);
+				if (variable_ref == null)
+					return false;
+
+				for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, current_pe, Location.Null), for_each.type.Location));
+
+				var init = new Invocation.Predefined (get_enumerator_mg, null);
+
+				statement = new While (new BooleanExpression (new Invocation (move_next_mg, null)),
+					 for_each.body, Location.Null);
+
+				var enum_type = enumerator_variable.Type;
+
+				//
+				// Add Dispose method call when enumerator can be IDisposable
+				//
+				if (!enum_type.ImplementsInterface (ec.BuiltinTypes.IDisposable, false)) {
+					if (!enum_type.IsSealed && !TypeSpec.IsValueType (enum_type)) {
+						//
+						// Runtime Dispose check
+						//
+						var vd = new RuntimeDispose (enumerator_variable.LocalInfo, Location.Null);
+						vd.Initializer = init;
+						statement = new Using (vd, statement, Location.Null);
+					} else {
+						//
+						// No Dispose call needed
+						//
+						this.init = new SimpleAssign (enumerator_variable, init, Location.Null);
+						this.init.Resolve (ec);
+					}
+				} else {
+					//
+					// Static Dispose check
+					//
+					var vd = new Using.VariableDeclaration (enumerator_variable.LocalInfo, Location.Null);
+					vd.Initializer = init;
+					statement = new Using (vd, statement, Location.Null);
+				}
+
+				return statement.Resolve (ec);
+			}
+
+			protected override void DoEmit (EmitContext ec)
+			{
+				enumerator_variable.LocalInfo.CreateBuilder (ec);
+
+				if (init != null)
+					init.EmitStatement (ec);
+
+				statement.Emit (ec);
+			}
+
+			#region IErrorHandler Members
+
+			bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
+			{
+				ec.Report.SymbolRelatedToPreviousError (best);
+				ec.Report.Warning (278, 2, expr.Location,
+					"`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
+					expr.Type.GetSignatureForError (), "enumerable",
+					best.GetSignatureForError (), ambiguous.GetSignatureForError ());
+
+				ambiguous_getenumerator_name = true;
+				return true;
+			}
+
+			bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
+			{
+				return false;
+			}
+
+			bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
+			{
+				return false;
+			}
+
+			bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
+			{
+				return false;
+			}
+
+			#endregion
+		}
+
+		Expression type;
+		LocalVariable variable;
+		Expression expr;
+		Block body;
+
+		public Foreach (Expression type, LocalVariable var, Expression expr, Statement stmt, Block body, Location l)
+			: base (stmt)
+		{
+			this.type = type;
+			this.variable = var;
+			this.expr = expr;
+			this.body = body;
+			loc = l;
+		}
+
+		public Expression Expr {
+			get { return expr; }
+		}
+
+		public Expression TypeExpression {
+			get { return type; }
+		}
+
+		public LocalVariable Variable {
+			get { return variable; }
+		}
+
+		public override Reachability MarkReachable (Reachability rc)
+		{
+			base.MarkReachable (rc);
+
+			body.MarkReachable (rc);
+
+			return rc;
+		}
+
+		public override bool Resolve (BlockContext ec)
+		{
+			expr = expr.Resolve (ec);
+			if (expr == null)
+				return false;
+
+			if (expr.IsNull) {
+				ec.Report.Error (186, loc, "Use of null is not valid in this context");
+				return false;
+			}
+
+			body.AddStatement (Statement);
+
+			if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
+				Statement = new ArrayForeach (this, 1);
+			} else if (expr.Type is ArrayContainer) {
+				Statement = new ArrayForeach (this, ((ArrayContainer) expr.Type).Rank);
+			} else {
+				if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
+					ec.Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
+						expr.ExprClassName);
+					return false;
+				}
+
+				Statement = new CollectionForeach (this, variable, expr);
+			}
+
+			return base.Resolve (ec);
+		}
+
+		protected override void DoEmit (EmitContext ec)
+		{
+			Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
+			ec.LoopBegin = ec.DefineLabel ();
+			ec.LoopEnd = ec.DefineLabel ();
+
+			if (!(Statement is Block))
+				ec.BeginCompilerScope ();
+
+			variable.CreateBuilder (ec);
+
+			Statement.Emit (ec);
+
+			if (!(Statement is Block))
+				ec.EndScope ();
+
+			ec.LoopBegin = old_begin;
+			ec.LoopEnd = old_end;
+		}
+
+		protected override bool DoFlowAnalysis (FlowAnalysisContext fc)
+		{
+			expr.FlowAnalysis (fc);
+
+			var da = fc.BranchDefiniteAssignment ();
+			body.FlowAnalysis (fc);
+			fc.DefiniteAssignment = da;
+			return false;
+		}
+
+		protected override void CloneTo (CloneContext clonectx, Statement t)
+		{
+			Foreach target = (Foreach) t;
+
+			target.type = type.Clone (clonectx);
+			target.expr = expr.Clone (clonectx);
+			target.body = (Block) body.Clone (clonectx);
+			target.Statement = Statement.Clone (clonectx);
+		}
+		
+		public override object Accept (StructuralVisitor visitor)
+		{
+			return visitor.Visit (this);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/support.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/support.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/support.cs	(revision 11807)
@@ -0,0 +1,364 @@
+//
+// support.cs: Support routines to work around the fact that System.Reflection.Emit
+// can not introspect types that are being constructed
+//
+// Author:
+//   Miguel de Icaza (miguel@ximian.com)
+//   Marek Safar (marek.safar@gmail.com)
+//
+// Copyright 2001 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2009 Novell, Inc
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Linq;
+using System.IO;
+using System.Text;
+using System.Collections.Generic;
+
+namespace Mono.CSharp {
+
+	sealed class ReferenceEquality<T> : IEqualityComparer<T> where T : class
+	{
+		public static readonly IEqualityComparer<T> Default = new ReferenceEquality<T> ();
+
+		private ReferenceEquality ()
+		{
+		}
+
+		public bool Equals (T x, T y)
+		{
+			return ReferenceEquals (x, y);
+		}
+
+		public int GetHashCode (T obj)
+		{
+			return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode (obj);
+		}
+	}
+#if !NET_4_0 && !MOBILE_DYNAMIC
+	public class Tuple<T1, T2> : IEquatable<Tuple<T1, T2>>
+	{
+		public Tuple (T1 item1, T2 item2)
+		{
+			Item1 = item1;
+			Item2 = item2;
+		}
+
+		public T1 Item1 { get; private set; }
+		public T2 Item2 { get; private set; }
+
+		public override int GetHashCode ()
+		{
+			return ((object)Item1 ?? 0) .GetHashCode () ^ ((object)Item2 ?? 0).GetHashCode ();
+		}
+
+		#region IEquatable<Tuple<T1,T2>> Members
+
+		public bool Equals (Tuple<T1, T2> other)
+		{
+			return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) &&
+				EqualityComparer<T2>.Default.Equals (Item2, other.Item2);
+		}
+
+		#endregion
+	}
+
+	public class Tuple<T1, T2, T3> : IEquatable<Tuple<T1, T2, T3>>
+	{
+		public Tuple (T1 item1, T2 item2, T3 item3)
+		{
+			Item1 = item1;
+			Item2 = item2;
+			Item3 = item3;
+		}
+
+		public T1 Item1 { get; private set; }
+		public T2 Item2 { get; private set; }
+		public T3 Item3 { get; private set; }
+
+		public override int GetHashCode ()
+		{
+			return Item1.GetHashCode () ^ Item2.GetHashCode () ^ Item3.GetHashCode ();
+		}
+
+		#region IEquatable<Tuple<T1,T2>> Members
+
+		public bool Equals (Tuple<T1, T2, T3> other)
+		{
+			return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) &&
+				EqualityComparer<T2>.Default.Equals (Item2, other.Item2) &&
+				EqualityComparer<T3>.Default.Equals (Item3, other.Item3);
+		}
+
+		#endregion
+	}
+
+	static class Tuple
+	{
+		public static Tuple<T1, T2> Create<T1, T2> (T1 item1, T2 item2)
+		{
+			return new Tuple<T1, T2> (item1, item2);
+		}
+
+		public static Tuple<T1, T2, T3> Create<T1, T2, T3> (T1 item1, T2 item2, T3 item3)
+		{
+			return new Tuple<T1, T2, T3> (item1, item2, item3);
+		}
+	}
+#endif
+
+	static class ArrayComparer
+	{
+		public static bool IsEqual<T> (T[] array1, T[] array2)
+		{
+			if (array1 == null || array2 == null)
+				return array1 == array2;
+
+			var eq = EqualityComparer<T>.Default;
+
+			for (int i = 0; i < array1.Length; ++i) {
+				if (!eq.Equals (array1[i], array2[i])) {
+					return false;
+				}
+			}
+
+			return true;
+		}
+	}
+#if !FULL_AST
+	/// <summary>
+	///   This is an arbitrarily seekable StreamReader wrapper.
+	///
+	///   It uses a self-tuning buffer to cache the seekable data,
+	///   but if the seek is too far, it may read the underly
+	///   stream all over from the beginning.
+	/// </summary>
+	public class SeekableStreamReader : IDisposable
+	{
+		public const int DefaultReadAheadSize =
+			4096 / 2;
+
+		StreamReader reader;
+		Stream stream;
+
+		char[] buffer;
+		int read_ahead_length;	// the length of read buffer
+		int buffer_start;       // in chars
+		int char_count;         // count of filled characters in buffer[]
+		int pos;                // index into buffer[]
+
+		public SeekableStreamReader (Stream stream, Encoding encoding, char[] sharedBuffer = null)
+		{
+			this.stream = stream;
+			this.buffer = sharedBuffer;
+
+			InitializeStream (DefaultReadAheadSize);
+			reader = new StreamReader (stream, encoding, true);
+		}
+
+		public void Dispose ()
+		{
+			// Needed to release stream reader buffers
+			reader.Dispose ();
+		}
+
+		void InitializeStream (int read_length_inc)
+		{
+			read_ahead_length += read_length_inc;
+
+			int required_buffer_size = read_ahead_length * 2;
+
+			if (buffer == null || buffer.Length < required_buffer_size)
+				buffer = new char [required_buffer_size];
+
+			stream.Position = 0;
+			buffer_start = char_count = pos = 0;
+		}
+
+		/// <remarks>
+		///   This value corresponds to the current position in a stream of characters.
+		///   The StreamReader hides its manipulation of the underlying byte stream and all
+		///   character set/decoding issues.  Thus, we cannot use this position to guess at
+		///   the corresponding position in the underlying byte stream even though there is
+		///   a correlation between them.
+		/// </remarks>
+		public int Position {
+			get {
+				return buffer_start + pos;
+			}
+
+			set {
+				//
+				// If the lookahead was too small, re-read from the beginning. Increase the buffer size while we're at it
+				// This should never happen until we are parsing some weird source code
+				//
+				if (value < buffer_start) {
+					InitializeStream (read_ahead_length);
+
+					//
+					// Discard buffer data after underlying stream changed position
+					// Cannot use handy reader.DiscardBufferedData () because it for
+					// some strange reason resets encoding as well
+					//
+					reader = new StreamReader (stream, reader.CurrentEncoding, true);
+				}
+
+				while (value > buffer_start + char_count) {
+					pos = char_count;
+					if (!ReadBuffer ())
+						throw new InternalErrorException ("Seek beyond end of file: " + (buffer_start + char_count - value));
+				}
+
+				pos = value - buffer_start;
+			}
+		}
+
+		bool ReadBuffer ()
+		{
+			int slack = buffer.Length - char_count;
+
+			//
+			// read_ahead_length is only half of the buffer to deal with
+			// reads ahead and moves back without re-reading whole buffer
+			//
+			if (slack <= read_ahead_length) {
+				//
+				// shift the buffer to make room for read_ahead_length number of characters
+				//
+				int shift = read_ahead_length - slack;
+				Array.Copy (buffer, shift, buffer, 0, char_count - shift);
+
+				// Update all counters
+				pos -= shift;
+				char_count -= shift;
+				buffer_start += shift;
+				slack += shift;
+			}
+
+			char_count += reader.Read (buffer, char_count, slack);
+
+			return pos < char_count;
+		}
+		
+		public char GetChar (int position)
+		{
+			if (buffer_start <= position && position < buffer.Length)
+				return buffer[position];
+			return '\0';
+		}
+		
+		public char[] ReadChars (int fromPosition, int toPosition)
+		{
+			char[] chars = new char[toPosition - fromPosition];
+			if (buffer_start <= fromPosition && toPosition <= buffer_start + buffer.Length) {
+				Array.Copy (buffer, fromPosition - buffer_start, chars, 0, chars.Length);
+			} else {
+				throw new NotImplementedException ();
+			}
+
+			return chars;
+		}
+
+		public int Peek ()
+		{
+			if ((pos >= char_count) && !ReadBuffer ())
+				return -1;
+
+			return buffer [pos];
+		}
+
+		public int Read ()
+		{
+			if ((pos >= char_count) && !ReadBuffer ())
+				return -1;
+
+			return buffer [pos++];
+		}
+	}
+#endif
+
+	public class UnixUtils {
+		[System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
+		extern static int _isatty (int fd);
+			
+		public static bool isatty (int fd)
+		{
+			try {
+				return _isatty (fd) == 1;
+			} catch {
+				return false;
+			}
+		}
+	}
+
+	/// <summary>
+	///   An exception used to terminate the compiler resolution phase and provide completions
+	/// </summary>
+	/// <remarks>
+	///   This is thrown when we want to return the completions or
+	///   terminate the completion process by AST nodes used in
+	///   the completion process.
+	/// </remarks>
+	public class CompletionResult : Exception {
+		string [] result;
+		string base_text;
+		
+		public CompletionResult (string base_text, string [] res)
+		{
+			if (base_text == null)
+				throw new ArgumentNullException ("base_text");
+			this.base_text = base_text;
+
+			result = res;
+			Array.Sort (result);
+		}
+
+		public string [] Result {
+			get {
+				return result;
+			}
+		}
+
+		public string BaseText {
+			get {
+				return base_text;
+			}
+		}
+	}
+
+	struct TypeNameParser
+	{
+		internal static string Escape(string name)
+		{
+			if (name == null) {
+				return null;
+			}
+			StringBuilder sb = null;
+			for (int pos = 0; pos < name.Length; pos++) {
+				char c = name[pos];
+				switch (c) {
+					case '\\':
+					case '+':
+					case ',':
+					case '[':
+					case ']':
+					case '*':
+					case '&':
+						if (sb == null) {
+							sb = new StringBuilder(name, 0, pos, name.Length + 3);
+						}
+						sb.Append("\\").Append(c);
+						break;
+					default:
+						if (sb != null) {
+							sb.Append(c);
+						}
+						break;
+				}
+			}
+			return sb != null ? sb.ToString() : name;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/symbolwriter.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/symbolwriter.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/symbolwriter.cs	(revision 11807)
@@ -0,0 +1,234 @@
+//
+// symbolwriter.cs: The debug symbol writer
+//
+// Authors: Martin Baulig (martin@ximian.com)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2004-2010 Novell, Inc
+//
+
+using System;
+
+#if STATIC
+using IKVM.Reflection;
+using IKVM.Reflection.Emit;
+#else
+using System.Reflection;
+using System.Reflection.Emit;
+#endif
+
+using Mono.CompilerServices.SymbolWriter;
+
+namespace Mono.CSharp
+{
+	static class SymbolWriter
+	{
+#if !NET_4_0 && !STATIC
+		delegate int GetILOffsetFunc (ILGenerator ig);
+		static GetILOffsetFunc get_il_offset_func;
+
+		delegate Guid GetGuidFunc (ModuleBuilder mb);
+		static GetGuidFunc get_guid_func;
+
+		static void Initialize ()
+		{
+			var mi = typeof (ILGenerator).GetMethod (
+				"Mono_GetCurrentOffset",
+				BindingFlags.Static | BindingFlags.NonPublic);
+			if (mi == null)
+				throw new MissingMethodException ("Mono_GetCurrentOffset");
+
+			get_il_offset_func = (GetILOffsetFunc) System.Delegate.CreateDelegate (
+				typeof (GetILOffsetFunc), mi);
+
+			mi = typeof (ModuleBuilder).GetMethod (
+				"Mono_GetGuid",
+				BindingFlags.Static | BindingFlags.NonPublic);
+			if (mi == null)
+				throw new MissingMethodException ("Mono_GetGuid");
+
+			get_guid_func = (GetGuidFunc) System.Delegate.CreateDelegate (
+				typeof (GetGuidFunc), mi);
+		}
+#endif
+
+		static int GetILOffset (ILGenerator ig)
+		{
+#if NET_4_0 || STATIC
+			return ig.ILOffset;
+#else
+			if (get_il_offset_func == null)
+				Initialize ();
+
+			return get_il_offset_func (ig);
+#endif
+		}
+
+		public static Guid GetGuid (ModuleBuilder module)
+		{
+#if NET_4_0 || STATIC
+			return module.ModuleVersionId;
+#else
+			if (get_guid_func == null)
+				Initialize ();
+
+			return get_guid_func (module);
+#endif
+		}
+
+		public static bool HasSymbolWriter {
+			get { return symwriter != null; }
+		}
+
+		public static MonoSymbolWriter symwriter;
+
+		public static void DefineLocalVariable (string name, LocalBuilder builder)
+		{
+			if (symwriter != null) {
+				symwriter.DefineLocalVariable (builder.LocalIndex, name);
+			}
+		}
+
+		public static SourceMethodBuilder OpenMethod (ICompileUnit file, IMethodDef method)
+		{
+			if (symwriter != null)
+				return symwriter.OpenMethod (file, -1 /* Not used */, method);
+			else
+				return null;
+		}
+
+		public static void CloseMethod ()
+		{
+			if (symwriter != null)
+				symwriter.CloseMethod ();
+		}
+
+		public static int OpenScope (ILGenerator ig)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ig);
+				return symwriter.OpenScope (offset);
+			} else {
+				return -1;
+			}
+		}
+
+		public static void CloseScope (ILGenerator ig)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ig);
+				symwriter.CloseScope (offset);
+			}
+		}
+
+		public static void DefineAnonymousScope (int id)
+		{
+			if (symwriter != null)
+				symwriter.DefineAnonymousScope (id);
+		}
+
+		public static void DefineScopeVariable (int scope, LocalBuilder builder)
+		{
+			if (symwriter != null) {
+				symwriter.DefineScopeVariable (scope, builder.LocalIndex);
+			}
+		}
+
+		public static void DefineScopeVariable (int scope)
+		{
+			if (symwriter != null)
+				symwriter.DefineScopeVariable (scope, -1);
+		}
+
+		public static void DefineCapturedLocal (int scope_id, string name,
+							string captured_name)
+		{
+			if (symwriter != null)
+				symwriter.DefineCapturedLocal (scope_id, name, captured_name);
+		}
+
+		public static void DefineCapturedParameter (int scope_id, string name,
+							    string captured_name)
+		{
+			if (symwriter != null)
+				symwriter.DefineCapturedParameter (scope_id, name, captured_name);
+		}
+
+		public static void DefineCapturedThis (int scope_id, string captured_name)
+		{
+			if (symwriter != null)
+				symwriter.DefineCapturedThis (scope_id, captured_name);
+		}
+
+		public static void DefineCapturedScope (int scope_id, int id, string captured_name)
+		{
+			if (symwriter != null)
+				symwriter.DefineCapturedScope (scope_id, id, captured_name);
+		}
+
+		public static void OpenCompilerGeneratedBlock (EmitContext ec)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ec.ig);
+				symwriter.OpenCompilerGeneratedBlock (offset);
+			}
+		}
+
+		public static void CloseCompilerGeneratedBlock (EmitContext ec)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ec.ig);
+				symwriter.CloseCompilerGeneratedBlock (offset);
+			}
+		}
+
+		public static void StartIteratorBody (EmitContext ec)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ec.ig);
+				symwriter.StartIteratorBody (offset);
+			}
+		}
+
+		public static void EndIteratorBody (EmitContext ec)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ec.ig);
+				symwriter.EndIteratorBody (offset);
+			}
+		}
+
+		public static void StartIteratorDispatcher (EmitContext ec)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ec.ig);
+				symwriter.StartIteratorDispatcher (offset);
+			}
+		}
+
+		public static void EndIteratorDispatcher (EmitContext ec)
+		{
+			if (symwriter != null) {
+				int offset = GetILOffset (ec.ig);
+				symwriter.EndIteratorDispatcher (offset);
+			}
+		}
+
+		public static void MarkSequencePoint (ILGenerator ig, Location loc)
+		{
+			if (symwriter != null) {
+				SourceFileEntry file = loc.SourceFile.SourceFileEntry;
+				int offset = GetILOffset (ig);
+				symwriter.MarkSequencePoint (offset, file, loc.Row, loc.Column, false);
+			}
+		}
+
+		public static void Reset ()
+		{
+			symwriter = null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/typemanager.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/typemanager.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/typemanager.cs	(revision 11807)
@@ -0,0 +1,1143 @@
+//
+// typemanager.cs: C# type manager
+//
+// Author: Miguel de Icaza (miguel@gnu.org)
+//         Ravi Pratap     (ravi@ximian.com)
+//         Marek Safar     (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+// Copyright 2003-2011 Novell, Inc.
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Globalization;
+using System.Collections.Generic;
+using System.Text;
+using System.IO;
+
+namespace Mono.CSharp
+{
+	//
+	// All compiler built-in types (they have to exist otherwise the compiler will not work)
+	//
+	public class BuiltinTypes
+	{
+		public readonly BuiltinTypeSpec Object;
+		public readonly BuiltinTypeSpec ValueType;
+		public readonly BuiltinTypeSpec Attribute;
+
+		public readonly BuiltinTypeSpec Int;
+		public readonly BuiltinTypeSpec UInt;
+		public readonly BuiltinTypeSpec Long;
+		public readonly BuiltinTypeSpec ULong;
+		public readonly BuiltinTypeSpec Float;
+		public readonly BuiltinTypeSpec Double;
+		public readonly BuiltinTypeSpec Char;
+		public readonly BuiltinTypeSpec Short;
+		public readonly BuiltinTypeSpec Decimal;
+		public readonly BuiltinTypeSpec Bool;
+		public readonly BuiltinTypeSpec SByte;
+		public readonly BuiltinTypeSpec Byte;
+		public readonly BuiltinTypeSpec UShort;
+		public readonly BuiltinTypeSpec String;
+
+		public readonly BuiltinTypeSpec Enum;
+		public readonly BuiltinTypeSpec Delegate;
+		public readonly BuiltinTypeSpec MulticastDelegate;
+		public readonly BuiltinTypeSpec Void;
+		public readonly BuiltinTypeSpec Array;
+		public readonly BuiltinTypeSpec Type;
+		public readonly BuiltinTypeSpec IEnumerator;
+		public readonly BuiltinTypeSpec IEnumerable;
+		public readonly BuiltinTypeSpec IDisposable;
+		public readonly BuiltinTypeSpec IntPtr;
+		public readonly BuiltinTypeSpec UIntPtr;
+		public readonly BuiltinTypeSpec RuntimeFieldHandle;
+		public readonly BuiltinTypeSpec RuntimeTypeHandle;
+		public readonly BuiltinTypeSpec Exception;
+
+		//
+		// These are internal buil-in types which depend on other
+		// build-in type (mostly object)
+		//
+		public readonly BuiltinTypeSpec Dynamic;
+
+		// Predefined operators tables
+		public readonly Binary.PredefinedOperator[] OperatorsBinaryStandard;
+		public readonly Binary.PredefinedOperator[] OperatorsBinaryEquality;
+		public readonly Binary.PredefinedOperator[] OperatorsBinaryUnsafe;
+		public readonly TypeSpec[][] OperatorsUnary;
+		public readonly TypeSpec[] OperatorsUnaryMutator;
+
+		public readonly TypeSpec[] BinaryPromotionsTypes;
+
+		readonly BuiltinTypeSpec[] types;
+
+		public BuiltinTypes ()
+		{
+			Object = new BuiltinTypeSpec (MemberKind.Class, "System", "Object", BuiltinTypeSpec.Type.Object);
+			ValueType = new BuiltinTypeSpec (MemberKind.Class, "System", "ValueType", BuiltinTypeSpec.Type.ValueType);
+			Attribute = new BuiltinTypeSpec (MemberKind.Class, "System", "Attribute", BuiltinTypeSpec.Type.Attribute);
+
+			Int = new BuiltinTypeSpec (MemberKind.Struct, "System", "Int32", BuiltinTypeSpec.Type.Int);
+			Long = new BuiltinTypeSpec (MemberKind.Struct, "System", "Int64", BuiltinTypeSpec.Type.Long);
+			UInt = new BuiltinTypeSpec (MemberKind.Struct, "System", "UInt32", BuiltinTypeSpec.Type.UInt);
+			ULong = new BuiltinTypeSpec (MemberKind.Struct, "System", "UInt64", BuiltinTypeSpec.Type.ULong);
+			Byte = new BuiltinTypeSpec (MemberKind.Struct, "System", "Byte", BuiltinTypeSpec.Type.Byte);
+			SByte = new BuiltinTypeSpec (MemberKind.Struct, "System", "SByte", BuiltinTypeSpec.Type.SByte);
+			Short = new BuiltinTypeSpec (MemberKind.Struct, "System", "Int16", BuiltinTypeSpec.Type.Short);
+			UShort = new BuiltinTypeSpec (MemberKind.Struct, "System", "UInt16", BuiltinTypeSpec.Type.UShort);
+
+			IEnumerator = new BuiltinTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerator", BuiltinTypeSpec.Type.IEnumerator);
+			IEnumerable = new BuiltinTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerable", BuiltinTypeSpec.Type.IEnumerable);
+			IDisposable = new BuiltinTypeSpec (MemberKind.Interface, "System", "IDisposable", BuiltinTypeSpec.Type.IDisposable);
+
+			Char = new BuiltinTypeSpec (MemberKind.Struct, "System", "Char", BuiltinTypeSpec.Type.Char);
+			String = new BuiltinTypeSpec (MemberKind.Class, "System", "String", BuiltinTypeSpec.Type.String);
+			Float = new BuiltinTypeSpec (MemberKind.Struct, "System", "Single", BuiltinTypeSpec.Type.Float);
+			Double = new BuiltinTypeSpec (MemberKind.Struct, "System", "Double", BuiltinTypeSpec.Type.Double);
+			Decimal = new BuiltinTypeSpec (MemberKind.Struct, "System", "Decimal", BuiltinTypeSpec.Type.Decimal);
+			Bool = new BuiltinTypeSpec (MemberKind.Struct, "System", "Boolean", BuiltinTypeSpec.Type.Bool);
+			IntPtr = new BuiltinTypeSpec (MemberKind.Struct, "System", "IntPtr", BuiltinTypeSpec.Type.IntPtr);
+			UIntPtr = new BuiltinTypeSpec (MemberKind.Struct, "System", "UIntPtr", BuiltinTypeSpec.Type.UIntPtr);
+
+			MulticastDelegate = new BuiltinTypeSpec (MemberKind.Class, "System", "MulticastDelegate", BuiltinTypeSpec.Type.MulticastDelegate);
+			Delegate = new BuiltinTypeSpec (MemberKind.Class, "System", "Delegate", BuiltinTypeSpec.Type.Delegate);
+			Enum = new BuiltinTypeSpec (MemberKind.Class, "System", "Enum", BuiltinTypeSpec.Type.Enum);
+			Array = new BuiltinTypeSpec (MemberKind.Class, "System", "Array", BuiltinTypeSpec.Type.Array);
+			Void = new BuiltinTypeSpec (MemberKind.Void, "System", "Void", BuiltinTypeSpec.Type.Other);
+			Type = new BuiltinTypeSpec (MemberKind.Class, "System", "Type", BuiltinTypeSpec.Type.Type);
+			Exception = new BuiltinTypeSpec (MemberKind.Class, "System", "Exception", BuiltinTypeSpec.Type.Exception);
+			RuntimeFieldHandle = new BuiltinTypeSpec (MemberKind.Struct, "System", "RuntimeFieldHandle", BuiltinTypeSpec.Type.Other);
+			RuntimeTypeHandle = new BuiltinTypeSpec (MemberKind.Struct, "System", "RuntimeTypeHandle", BuiltinTypeSpec.Type.Other);
+
+			// TODO: Maybe I should promote it to different kind for faster compares
+			Dynamic = new BuiltinTypeSpec ("dynamic", BuiltinTypeSpec.Type.Dynamic);
+
+			OperatorsBinaryStandard = Binary.CreateStandardOperatorsTable (this);
+			OperatorsBinaryEquality = Binary.CreateEqualityOperatorsTable (this);
+			OperatorsBinaryUnsafe = Binary.CreatePointerOperatorsTable (this);
+			OperatorsUnary = Unary.CreatePredefinedOperatorsTable (this);
+			OperatorsUnaryMutator = UnaryMutator.CreatePredefinedOperatorsTable (this);
+
+			BinaryPromotionsTypes = ConstantFold.CreateBinaryPromotionsTypes (this);
+
+			types = new BuiltinTypeSpec[] {
+				Object, ValueType, Attribute,
+				Int, UInt, Long, ULong, Float, Double, Char, Short, Decimal, Bool, SByte, Byte, UShort, String,
+				Enum, Delegate, MulticastDelegate, Void, Array, Type, IEnumerator, IEnumerable, IDisposable,
+				IntPtr, UIntPtr, RuntimeFieldHandle, RuntimeTypeHandle, Exception };
+		}
+
+		public BuiltinTypeSpec[] AllTypes {
+			get {
+				return types;
+			}
+		}
+
+		public bool CheckDefinitions (ModuleContainer module)
+		{
+			var ctx = module.Compiler;
+			foreach (var p in types) {
+				var found = PredefinedType.Resolve (module, p.Kind, p.Namespace, p.Name, p.Arity, true, true);
+				if (found == null || found == p)
+					continue;
+
+				var tc = found.MemberDefinition as TypeDefinition;
+				if (tc != null) {
+					var ns = module.GlobalRootNamespace.GetNamespace (p.Namespace, false);
+					ns.SetBuiltinType (p);
+
+					tc.SetPredefinedSpec (p);
+					p.SetDefinition (found);
+				}
+			}
+
+			if (ctx.Report.Errors != 0)
+				return false;
+
+			// Set internal build-in types
+			Dynamic.SetDefinition (Object);
+
+			return true;
+		}
+	}
+
+	//
+	// Compiler predefined types. Usually used for compiler generated
+	// code or for comparison against well known framework type. They
+	// may not exist as they are optional
+	//
+	class PredefinedTypes
+	{
+		public readonly PredefinedType ArgIterator;
+		public readonly PredefinedType TypedReference;
+		public readonly PredefinedType MarshalByRefObject;
+		public readonly PredefinedType RuntimeHelpers;
+		public readonly PredefinedType IAsyncResult;
+		public readonly PredefinedType AsyncCallback;
+		public readonly PredefinedType RuntimeArgumentHandle;
+		public readonly PredefinedType CharSet;
+		public readonly PredefinedType IsVolatile;
+		public readonly PredefinedType IEnumeratorGeneric;
+		public readonly PredefinedType IListGeneric;
+		public readonly PredefinedType IReadOnlyListGeneric;
+		public readonly PredefinedType ICollectionGeneric;
+		public readonly PredefinedType IReadOnlyCollectionGeneric;
+		public readonly PredefinedType IEnumerableGeneric;
+		public readonly PredefinedType Nullable;
+		public readonly PredefinedType Activator;
+		public readonly PredefinedType Interlocked;
+		public readonly PredefinedType Monitor;
+		public readonly PredefinedType NotSupportedException;
+		public readonly PredefinedType RuntimeFieldHandle;
+		public readonly PredefinedType RuntimeMethodHandle;
+		public readonly PredefinedType SecurityAction;
+		public readonly PredefinedType Dictionary;
+		public readonly PredefinedType Hashtable;
+		public readonly TypeSpec[] SwitchUserTypes;
+
+		//
+		// C# 3.0
+		//
+		public readonly PredefinedType Expression;
+		public readonly PredefinedType ExpressionGeneric;
+		public readonly PredefinedType ParameterExpression;
+		public readonly PredefinedType FieldInfo;
+		public readonly PredefinedType MethodBase;
+		public readonly PredefinedType MethodInfo;
+		public readonly PredefinedType ConstructorInfo;
+		public readonly PredefinedType MemberBinding;
+
+		//
+		// C# 4.0
+		//
+		public readonly PredefinedType Binder;
+		public readonly PredefinedType CallSite;
+		public readonly PredefinedType CallSiteGeneric;
+		public readonly PredefinedType BinderFlags;
+
+		//
+		// C# 5.0
+		//
+		public readonly PredefinedType AsyncVoidMethodBuilder;
+		public readonly PredefinedType AsyncTaskMethodBuilder;
+		public readonly PredefinedType AsyncTaskMethodBuilderGeneric;
+		public readonly PredefinedType Action;
+		public readonly PredefinedType Task;
+		public readonly PredefinedType TaskGeneric;
+		public readonly PredefinedType IAsyncStateMachine;
+		public readonly PredefinedType INotifyCompletion;
+		public readonly PredefinedType ICriticalNotifyCompletion;
+
+		public PredefinedTypes (ModuleContainer module)
+		{
+			TypedReference = new PredefinedType (module, MemberKind.Struct, "System", "TypedReference");
+			ArgIterator = new PredefinedType (module, MemberKind.Struct, "System", "ArgIterator");
+
+			MarshalByRefObject = new PredefinedType (module, MemberKind.Class, "System", "MarshalByRefObject");
+			RuntimeHelpers = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "RuntimeHelpers");
+			IAsyncResult = new PredefinedType (module, MemberKind.Interface, "System", "IAsyncResult");
+			AsyncCallback = new PredefinedType (module, MemberKind.Delegate, "System", "AsyncCallback");
+			RuntimeArgumentHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeArgumentHandle");
+			CharSet = new PredefinedType (module, MemberKind.Enum, "System.Runtime.InteropServices", "CharSet");
+			IsVolatile = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "IsVolatile");
+			IEnumeratorGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IEnumerator", 1);
+			IListGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IList", 1);
+			IReadOnlyListGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IReadOnlyList", 1);
+			ICollectionGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "ICollection", 1);
+			IReadOnlyCollectionGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IReadOnlyCollection", 1);
+			IEnumerableGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IEnumerable", 1);
+			Nullable = new PredefinedType (module, MemberKind.Struct, "System", "Nullable", 1);
+			Activator = new PredefinedType (module, MemberKind.Class, "System", "Activator");
+			Interlocked = new PredefinedType (module, MemberKind.Class, "System.Threading", "Interlocked");
+			Monitor = new PredefinedType (module, MemberKind.Class, "System.Threading", "Monitor");
+			NotSupportedException = new PredefinedType (module, MemberKind.Class, "System", "NotSupportedException");
+			RuntimeFieldHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeFieldHandle");
+			RuntimeMethodHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeMethodHandle");
+			SecurityAction = new PredefinedType (module, MemberKind.Enum, "System.Security.Permissions", "SecurityAction");
+			Dictionary = new PredefinedType (module, MemberKind.Class, "System.Collections.Generic", "Dictionary", 2);
+			Hashtable = new PredefinedType (module, MemberKind.Class, "System.Collections", "Hashtable");
+
+			Expression = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "Expression");
+			ExpressionGeneric = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "Expression", 1);
+			MemberBinding = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "MemberBinding");
+			ParameterExpression = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "ParameterExpression");
+			FieldInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "FieldInfo");
+			MethodBase = new PredefinedType (module, MemberKind.Class, "System.Reflection", "MethodBase");
+			MethodInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "MethodInfo");
+			ConstructorInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "ConstructorInfo");
+
+			CallSite = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "CallSite");
+			CallSiteGeneric = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "CallSite", 1);
+			Binder = new PredefinedType (module, MemberKind.Class, "Microsoft.CSharp.RuntimeBinder", "Binder");
+			BinderFlags = new PredefinedType (module, MemberKind.Enum, "Microsoft.CSharp.RuntimeBinder", "CSharpBinderFlags");
+
+			Action = new PredefinedType (module, MemberKind.Delegate, "System", "Action");
+			AsyncVoidMethodBuilder = new PredefinedType (module, MemberKind.Struct, "System.Runtime.CompilerServices", "AsyncVoidMethodBuilder");
+			AsyncTaskMethodBuilder = new PredefinedType (module, MemberKind.Struct, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
+			AsyncTaskMethodBuilderGeneric = new PredefinedType (module, MemberKind.Struct, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder", 1);
+			Task = new PredefinedType (module, MemberKind.Class, "System.Threading.Tasks", "Task");
+			TaskGeneric = new PredefinedType (module, MemberKind.Class, "System.Threading.Tasks", "Task", 1);
+			IAsyncStateMachine = new PredefinedType (module, MemberKind.Interface, "System.Runtime.CompilerServices", "IAsyncStateMachine");
+			INotifyCompletion = new PredefinedType (module, MemberKind.Interface, "System.Runtime.CompilerServices", "INotifyCompletion");
+			ICriticalNotifyCompletion = new PredefinedType (module, MemberKind.Interface, "System.Runtime.CompilerServices", "ICriticalNotifyCompletion");
+
+			//
+			// Define types which are used for comparison. It does not matter
+			// if they don't exist as no error report is needed
+			//
+			if (TypedReference.Define ())
+				TypedReference.TypeSpec.IsSpecialRuntimeType = true;
+
+			if (ArgIterator.Define ())
+				ArgIterator.TypeSpec.IsSpecialRuntimeType = true;
+
+			if (IEnumerableGeneric.Define ())
+				IEnumerableGeneric.TypeSpec.IsArrayGenericInterface = true;
+
+			if (IListGeneric.Define ())
+				IListGeneric.TypeSpec.IsArrayGenericInterface = true;
+
+			if (IReadOnlyListGeneric.Define ())
+				IReadOnlyListGeneric.TypeSpec.IsArrayGenericInterface = true;
+
+			if (ICollectionGeneric.Define ())
+				ICollectionGeneric.TypeSpec.IsArrayGenericInterface = true;
+
+			if (IReadOnlyCollectionGeneric.Define ())
+				IReadOnlyCollectionGeneric.TypeSpec.IsArrayGenericInterface = true;
+
+			if (Nullable.Define ())
+				Nullable.TypeSpec.IsNullableType = true;
+
+			if (ExpressionGeneric.Define ())
+				ExpressionGeneric.TypeSpec.IsExpressionTreeType = true;
+
+			Task.Define ();
+			if (TaskGeneric.Define ())
+				TaskGeneric.TypeSpec.IsGenericTask = true;
+
+			SwitchUserTypes = Switch.CreateSwitchUserTypes (module, Nullable.TypeSpec);
+		}
+	}
+
+	class PredefinedMembers
+	{
+		public readonly PredefinedMember<MethodSpec> ActivatorCreateInstance;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderCreate;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderStart;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderSetResult;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderSetException;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderSetStateMachine;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderOnCompleted;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderOnCompletedUnsafe;
+		public readonly PredefinedMember<PropertySpec> AsyncTaskMethodBuilderTask;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericCreate;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericStart;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericSetResult;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericSetException;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericSetStateMachine;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericOnCompleted;
+		public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericOnCompletedUnsafe;
+		public readonly PredefinedMember<PropertySpec> AsyncTaskMethodBuilderGenericTask;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderCreate;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderStart;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetException;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetResult;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetStateMachine;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompleted;
+		public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompletedUnsafe;
+		public readonly PredefinedMember<MethodSpec> AsyncStateMachineAttributeCtor;
+		public readonly PredefinedMember<MethodSpec> DebuggerBrowsableAttributeCtor;
+		public readonly PredefinedMember<MethodSpec> DecimalCtor;
+		public readonly PredefinedMember<MethodSpec> DecimalCtorInt;
+		public readonly PredefinedMember<MethodSpec> DecimalCtorLong;
+		public readonly PredefinedMember<MethodSpec> DecimalConstantAttributeCtor;
+		public readonly PredefinedMember<MethodSpec> DefaultMemberAttributeCtor;
+		public readonly PredefinedMember<MethodSpec> DelegateCombine;
+		public readonly PredefinedMember<MethodSpec> DelegateEqual;
+		public readonly PredefinedMember<MethodSpec> DelegateInequal;
+		public readonly PredefinedMember<MethodSpec> DelegateRemove;
+		public readonly PredefinedMember<MethodSpec> DynamicAttributeCtor;
+		public readonly PredefinedMember<MethodSpec> FieldInfoGetFieldFromHandle;
+		public readonly PredefinedMember<MethodSpec> FieldInfoGetFieldFromHandle2;
+		public readonly PredefinedMember<MethodSpec> IDisposableDispose;
+		public readonly PredefinedMember<MethodSpec> IEnumerableGetEnumerator;
+		public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange;
+		public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange_T;
+		public readonly PredefinedMember<MethodSpec> FixedBufferAttributeCtor;
+		public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle;
+		public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle2;
+		public readonly PredefinedMember<MethodSpec> MonitorEnter;
+		public readonly PredefinedMember<MethodSpec> MonitorEnter_v4;
+		public readonly PredefinedMember<MethodSpec> MonitorExit;
+		public readonly PredefinedMember<PropertySpec> RuntimeCompatibilityWrapNonExceptionThrows;
+		public readonly PredefinedMember<MethodSpec> RuntimeHelpersInitializeArray;
+		public readonly PredefinedMember<PropertySpec> RuntimeHelpersOffsetToStringData;
+		public readonly PredefinedMember<ConstSpec> SecurityActionRequestMinimum;
+		public readonly PredefinedMember<FieldSpec> StringEmpty;
+		public readonly PredefinedMember<MethodSpec> StringEqual;
+		public readonly PredefinedMember<MethodSpec> StringInequal;
+		public readonly PredefinedMember<MethodSpec> StructLayoutAttributeCtor;
+		public readonly PredefinedMember<FieldSpec> StructLayoutCharSet;
+		public readonly PredefinedMember<FieldSpec> StructLayoutSize;
+		public readonly PredefinedMember<MethodSpec> TypeGetTypeFromHandle;
+
+		public PredefinedMembers (ModuleContainer module)
+		{
+			var types = module.PredefinedTypes;
+			var atypes = module.PredefinedAttributes;
+			var btypes = module.Compiler.BuiltinTypes;
+
+			var tp = new TypeParameter (0, new MemberName ("T"), null, null, Variance.None);
+
+			ActivatorCreateInstance = new PredefinedMember<MethodSpec> (module, types.Activator,
+				MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null));
+
+			AsyncTaskMethodBuilderCreate = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Method ("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, types.AsyncTaskMethodBuilder.TypeSpec));
+
+			AsyncTaskMethodBuilderSetResult = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Method ("SetResult", 0, ParametersCompiled.EmptyReadOnlyParameters, btypes.Void));
+
+			AsyncTaskMethodBuilderSetStateMachine = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				"SetStateMachine", MemberKind.Method, () => new[] {
+						types.IAsyncStateMachine.TypeSpec
+				}, btypes.Void);
+
+			AsyncTaskMethodBuilderSetException = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Method ("SetException", 0,
+				ParametersCompiled.CreateFullyResolved (btypes.Exception), btypes.Void));
+
+			AsyncTaskMethodBuilderOnCompleted = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Method ("AwaitOnCompleted", 2,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.REF)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null)
+							}, false),
+					btypes.Void));
+
+			AsyncTaskMethodBuilderOnCompletedUnsafe = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Method ("AwaitUnsafeOnCompleted", 2,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.REF)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null)
+							}, false),
+					btypes.Void));
+
+			AsyncTaskMethodBuilderStart = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Method ("Start", 1,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+							}, false),
+					btypes.Void));
+
+			AsyncTaskMethodBuilderTask = new PredefinedMember<PropertySpec> (module, types.AsyncTaskMethodBuilder,
+				MemberFilter.Property ("Task", null));
+
+			AsyncTaskMethodBuilderGenericCreate = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				MemberFilter.Method ("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, types.AsyncVoidMethodBuilder.TypeSpec));
+
+			AsyncTaskMethodBuilderGenericSetResult = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				"SetResult", MemberKind.Method, () => new TypeSpec[] {
+						types.AsyncTaskMethodBuilderGeneric.TypeSpec.MemberDefinition.TypeParameters[0]
+				}, btypes.Void);
+
+			AsyncTaskMethodBuilderGenericSetStateMachine = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				"SetStateMachine", MemberKind.Method, () => new[] {
+						types.IAsyncStateMachine.TypeSpec
+				}, btypes.Void);
+
+			AsyncTaskMethodBuilderGenericSetException = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				MemberFilter.Method ("SetException", 0,
+				ParametersCompiled.CreateFullyResolved (btypes.Exception), btypes.Void));
+
+			AsyncTaskMethodBuilderGenericOnCompleted = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				MemberFilter.Method ("AwaitOnCompleted", 2,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.REF)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null)
+							}, false),
+					btypes.Void));
+
+			AsyncTaskMethodBuilderGenericOnCompletedUnsafe = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				MemberFilter.Method ("AwaitUnsafeOnCompleted", 2,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.REF)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null)
+							}, false),
+					btypes.Void));
+
+			AsyncTaskMethodBuilderGenericStart = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				MemberFilter.Method ("Start", 1,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+							}, false),
+					btypes.Void));
+
+			AsyncTaskMethodBuilderGenericTask = new PredefinedMember<PropertySpec> (module, types.AsyncTaskMethodBuilderGeneric,
+				MemberFilter.Property ("Task", null));
+
+			AsyncVoidMethodBuilderCreate = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				MemberFilter.Method ("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, types.AsyncVoidMethodBuilder.TypeSpec));
+
+			AsyncVoidMethodBuilderSetException = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				MemberFilter.Method ("SetException", 0, null, btypes.Void));
+
+			AsyncVoidMethodBuilderSetResult = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				MemberFilter.Method ("SetResult", 0, ParametersCompiled.EmptyReadOnlyParameters, btypes.Void));
+
+			AsyncVoidMethodBuilderSetStateMachine = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				"SetStateMachine", MemberKind.Method, () => new[] {
+						types.IAsyncStateMachine.TypeSpec
+				}, btypes.Void);
+
+			AsyncVoidMethodBuilderOnCompleted = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				MemberFilter.Method ("AwaitOnCompleted", 2,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.REF)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null)
+							}, false),
+					btypes.Void));
+
+			AsyncVoidMethodBuilderOnCompletedUnsafe = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				MemberFilter.Method ("AwaitUnsafeOnCompleted", 2,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.REF)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null)
+							}, false),
+					btypes.Void));
+
+			AsyncVoidMethodBuilderStart = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder,
+				MemberFilter.Method ("Start", 1,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+							}, false),
+					btypes.Void));
+
+			AsyncStateMachineAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.AsyncStateMachine,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (
+					btypes.Type)));
+
+			DebuggerBrowsableAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DebuggerBrowsable,
+				MemberFilter.Constructor (null));
+
+			DecimalCtor = new PredefinedMember<MethodSpec> (module, btypes.Decimal,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (
+					btypes.Int, btypes.Int, btypes.Int, btypes.Bool, btypes.Byte)));
+
+			DecimalCtorInt = new PredefinedMember<MethodSpec> (module, btypes.Decimal,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Int)));
+
+			DecimalCtorLong = new PredefinedMember<MethodSpec> (module, btypes.Decimal,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Long)));
+
+			DecimalConstantAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DecimalConstant,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (
+					btypes.Byte, btypes.Byte, btypes.UInt, btypes.UInt, btypes.UInt)));
+
+			DefaultMemberAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DefaultMember,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.String)));
+
+			DelegateCombine = new PredefinedMember<MethodSpec> (module, btypes.Delegate, "Combine", btypes.Delegate, btypes.Delegate);
+			DelegateRemove = new PredefinedMember<MethodSpec> (module, btypes.Delegate, "Remove", btypes.Delegate, btypes.Delegate);
+
+			DelegateEqual = new PredefinedMember<MethodSpec> (module, btypes.Delegate,
+				new MemberFilter (Operator.GetMetadataName (Operator.OpType.Equality), 0, MemberKind.Operator, null, btypes.Bool));
+
+			DelegateInequal = new PredefinedMember<MethodSpec> (module, btypes.Delegate,
+				new MemberFilter (Operator.GetMetadataName (Operator.OpType.Inequality), 0, MemberKind.Operator, null, btypes.Bool));
+
+			DynamicAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.Dynamic,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (
+					ArrayContainer.MakeType (module, btypes.Bool))));
+
+			FieldInfoGetFieldFromHandle = new PredefinedMember<MethodSpec> (module, types.FieldInfo,
+				"GetFieldFromHandle", MemberKind.Method, types.RuntimeFieldHandle);
+
+			FieldInfoGetFieldFromHandle2 = new PredefinedMember<MethodSpec> (module, types.FieldInfo,
+				"GetFieldFromHandle", MemberKind.Method, types.RuntimeFieldHandle, new PredefinedType (btypes.RuntimeTypeHandle));
+
+			FixedBufferAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.FixedBuffer,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Type, btypes.Int)));
+
+			IDisposableDispose = new PredefinedMember<MethodSpec> (module, btypes.IDisposable, "Dispose", TypeSpec.EmptyTypes);
+
+			IEnumerableGetEnumerator = new PredefinedMember<MethodSpec> (module, btypes.IEnumerable,
+				"GetEnumerator", TypeSpec.EmptyTypes);
+
+			InterlockedCompareExchange = new PredefinedMember<MethodSpec> (module, types.Interlocked,
+				MemberFilter.Method ("CompareExchange", 0,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.NONE),
+								new ParameterData (null, Parameter.Modifier.NONE)
+							},
+						new[] {
+								btypes.Int, btypes.Int, btypes.Int
+							},
+						false),
+				btypes.Int));
+
+			InterlockedCompareExchange_T = new PredefinedMember<MethodSpec> (module, types.Interlocked,
+				MemberFilter.Method ("CompareExchange", 1,
+					new ParametersImported (
+						new[] {
+								new ParameterData (null, Parameter.Modifier.REF),
+								new ParameterData (null, Parameter.Modifier.NONE),
+								new ParameterData (null, Parameter.Modifier.NONE)
+							},
+						new[] {
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+								new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null),
+							}, false),
+					null));
+
+			MethodInfoGetMethodFromHandle = new PredefinedMember<MethodSpec> (module, types.MethodBase,
+				"GetMethodFromHandle", MemberKind.Method, types.RuntimeMethodHandle);
+
+			MethodInfoGetMethodFromHandle2 = new PredefinedMember<MethodSpec> (module, types.MethodBase,
+				"GetMethodFromHandle", MemberKind.Method, types.RuntimeMethodHandle, new PredefinedType (btypes.RuntimeTypeHandle));
+
+			MonitorEnter = new PredefinedMember<MethodSpec> (module, types.Monitor, "Enter", btypes.Object);
+
+			MonitorEnter_v4 = new PredefinedMember<MethodSpec> (module, types.Monitor,
+				MemberFilter.Method ("Enter", 0,
+					new ParametersImported (new[] {
+							new ParameterData (null, Parameter.Modifier.NONE),
+							new ParameterData (null, Parameter.Modifier.REF)
+						},
+					new[] {
+							btypes.Object, btypes.Bool
+						}, false), null));
+
+			MonitorExit = new PredefinedMember<MethodSpec> (module, types.Monitor, "Exit", btypes.Object);
+
+			RuntimeCompatibilityWrapNonExceptionThrows = new PredefinedMember<PropertySpec> (module, atypes.RuntimeCompatibility,
+				MemberFilter.Property ("WrapNonExceptionThrows", btypes.Bool));
+
+			RuntimeHelpersInitializeArray = new PredefinedMember<MethodSpec> (module, types.RuntimeHelpers,
+				"InitializeArray", btypes.Array, btypes.RuntimeFieldHandle);
+
+			RuntimeHelpersOffsetToStringData = new PredefinedMember<PropertySpec> (module, types.RuntimeHelpers,
+				MemberFilter.Property ("OffsetToStringData", btypes.Int));
+
+			SecurityActionRequestMinimum = new PredefinedMember<ConstSpec> (module, types.SecurityAction, "RequestMinimum",
+				MemberKind.Field, types.SecurityAction);
+
+			StringEmpty = new PredefinedMember<FieldSpec> (module, btypes.String, MemberFilter.Field ("Empty", btypes.String));
+
+			StringEqual = new PredefinedMember<MethodSpec> (module, btypes.String,
+				new MemberFilter (Operator.GetMetadataName (Operator.OpType.Equality), 0, MemberKind.Operator, null, btypes.Bool));
+
+			StringInequal = new PredefinedMember<MethodSpec> (module, btypes.String,
+				new MemberFilter (Operator.GetMetadataName (Operator.OpType.Inequality), 0, MemberKind.Operator, null, btypes.Bool));
+
+			StructLayoutAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.StructLayout,
+				MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Short)));
+
+			StructLayoutCharSet = new PredefinedMember<FieldSpec> (module, atypes.StructLayout, "CharSet",
+				MemberKind.Field, types.CharSet);
+
+			StructLayoutSize = new PredefinedMember<FieldSpec> (module, atypes.StructLayout,
+				MemberFilter.Field ("Size", btypes.Int));
+
+			TypeGetTypeFromHandle = new PredefinedMember<MethodSpec> (module, btypes.Type, "GetTypeFromHandle", btypes.RuntimeTypeHandle);
+		}
+	}
+
+	public class PredefinedType
+	{
+		readonly string name;
+		readonly string ns;
+		readonly int arity;
+		readonly MemberKind kind;
+		protected readonly ModuleContainer module;
+		protected TypeSpec type;
+		bool defined;
+
+		public PredefinedType (ModuleContainer module, MemberKind kind, string ns, string name, int arity)
+			: this (module, kind, ns, name)
+		{
+			this.arity = arity;
+		}
+
+		public PredefinedType (ModuleContainer module, MemberKind kind, string ns, string name)
+		{
+			this.module = module;
+			this.kind = kind;
+			this.name = name;
+			this.ns = ns;
+		}
+
+		public PredefinedType (BuiltinTypeSpec type)
+		{
+			this.kind = type.Kind;
+			this.name = type.Name;
+			this.ns = type.Namespace;
+			this.type = type;
+		}
+
+		#region Properties
+
+		public int Arity {
+			get {
+				return arity;
+			}
+		}
+
+		public bool IsDefined {
+			get {
+				return type != null;
+			}
+		}
+
+		public string Name {
+			get {
+				return name;
+			}
+		}
+
+		public string Namespace {
+			get {
+				return ns;
+			}
+		}
+
+		public TypeSpec TypeSpec {
+			get {
+				return type;
+			}
+		}
+
+		#endregion
+
+		public bool Define ()
+		{
+			if (type != null)
+				return true;
+
+			if (!defined) {
+				defined = true;
+				type = Resolve (module, kind, ns, name, arity, false, false);
+			}
+
+			return type != null;
+		}
+
+		public string GetSignatureForError ()
+		{
+			return ns + "." + name;
+		}
+
+		public static TypeSpec Resolve (ModuleContainer module, MemberKind kind, string ns, string name, int arity, bool required, bool reportErrors)
+		{
+			//
+			// Cannot call it with true because it could create non-existent namespaces for
+			// predefined types. It's set to true only for build-in types which all must
+			// exist therefore it does not matter, for predefined types we don't want to create
+			// fake namespaces when type is optional and does not exist (e.g. System.Linq).
+			//
+			Namespace type_ns = module.GlobalRootNamespace.GetNamespace (ns, required);
+
+			IList<TypeSpec> found = null;
+			if (type_ns != null)
+				found = type_ns.GetAllTypes (name);
+
+			if (found == null) {
+				if (reportErrors)
+					module.Compiler.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported", ns, name);
+
+				return null;
+			}
+
+			TypeSpec best_match = null;
+			foreach (var candidate in found) {
+				if (candidate.Kind != kind) {
+					if (candidate.Kind == MemberKind.Struct && kind == MemberKind.Void && candidate.MemberDefinition is TypeContainer) {
+						// Void is declared as struct but we keep it internally as
+						// special kind, the swap will be done by caller
+					} else {
+						continue;
+					}
+				}
+
+				if (candidate.Arity != arity)
+					continue;
+
+				if ((candidate.Modifiers & Modifiers.INTERNAL) != 0 && !candidate.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly))
+					continue;
+
+				if (best_match == null) {
+					best_match = candidate;
+					continue;
+				}
+
+				var other_match = best_match;
+				if (!best_match.MemberDefinition.IsImported &&
+					module.Compiler.BuiltinTypes.Object.MemberDefinition.DeclaringAssembly == candidate.MemberDefinition.DeclaringAssembly) {
+					best_match = candidate;
+				}
+
+				string location;
+				if (best_match.MemberDefinition is MemberCore) {
+					location = ((MemberCore) best_match.MemberDefinition).Location.Name;
+				} else {
+					var assembly = (ImportedAssemblyDefinition) best_match.MemberDefinition.DeclaringAssembly;
+					location = Path.GetFileName (assembly.Location);
+				}
+
+				module.Compiler.Report.SymbolRelatedToPreviousError (other_match);
+				module.Compiler.Report.SymbolRelatedToPreviousError (candidate);
+
+				module.Compiler.Report.Warning (1685, 1,
+					"The predefined type `{0}.{1}' is defined multiple times. Using definition from `{2}'",
+					ns, name, location);
+
+				break;
+			}
+
+			if (best_match == null && reportErrors) {
+				var found_member = found[0];
+
+				if (found_member.Kind == MemberKind.MissingType) {
+					// CSC: should be different error number
+					module.Compiler.Report.Error (518, "The predefined type `{0}.{1}' is defined in an assembly that is not referenced.", ns, name);
+				} else {
+					Location loc;
+					if (found_member.MemberDefinition is MemberCore) {
+						loc = ((MemberCore) found_member.MemberDefinition).Location;
+					} else {
+						loc = Location.Null;
+						module.Compiler.Report.SymbolRelatedToPreviousError (found_member);
+					}
+
+					module.Compiler.Report.Error (520, loc, "The predefined type `{0}.{1}' is not declared correctly", ns, name);
+				}
+			}
+
+			return best_match;
+		}
+
+		public TypeSpec Resolve ()
+		{
+			if (type == null)
+				type = Resolve (module, kind, ns, name, arity, false, true);
+
+			return type;
+		}
+	}
+
+	public class PredefinedMember<T> where T : MemberSpec
+	{
+		readonly ModuleContainer module;
+		T member;
+		TypeSpec declaring_type;
+		readonly PredefinedType declaring_type_predefined;
+		MemberFilter filter;
+		readonly Func<TypeSpec[]> filter_builder;
+
+		public PredefinedMember (ModuleContainer module, PredefinedType type, MemberFilter filter)
+		{
+			this.module = module;
+			this.declaring_type_predefined = type;
+			this.filter = filter;
+		}
+
+		public PredefinedMember (ModuleContainer module, TypeSpec type, MemberFilter filter)
+		{
+			this.module = module;
+			this.declaring_type = type;
+			this.filter = filter;
+		}
+
+		public PredefinedMember (ModuleContainer module, PredefinedType type, string name, params TypeSpec[] types)
+			: this (module, type, MemberFilter.Method (name, 0, ParametersCompiled.CreateFullyResolved (types), null))
+		{
+		}
+
+		public PredefinedMember (ModuleContainer module, PredefinedType type, string name, MemberKind kind, params PredefinedType[] types)
+			: this (module, type, new MemberFilter (name, 0, kind, null, null))
+		{
+			filter_builder = () => {
+				var ptypes = new TypeSpec[types.Length];
+				for (int i = 0; i < ptypes.Length; ++i) {
+					var p = types[i];
+					if (!p.Define ())
+						return null;
+
+					ptypes[i] = p.TypeSpec;
+				}
+
+				return ptypes;
+			};
+		}
+
+		public PredefinedMember (ModuleContainer module, PredefinedType type, string name, MemberKind kind, Func<TypeSpec[]> typesBuilder, TypeSpec returnType)
+			: this (module, type, new MemberFilter (name, 0, kind, null, returnType))
+		{
+			filter_builder = typesBuilder;
+		}
+
+		public PredefinedMember (ModuleContainer module, BuiltinTypeSpec type, string name, params TypeSpec[] types)
+			: this (module, type, MemberFilter.Method (name, 0, ParametersCompiled.CreateFullyResolved (types), null))
+		{
+		}
+
+		public T Get ()
+		{
+			if (member != null)
+				return member;
+
+			if (declaring_type == null) {
+				if (!declaring_type_predefined.Define ())
+					return null;
+
+				declaring_type = declaring_type_predefined.TypeSpec;
+			}
+
+			if (filter_builder != null) {
+				var types = filter_builder ();
+
+				if (filter.Kind == MemberKind.Field)
+					filter = new MemberFilter (filter.Name, filter.Arity, filter.Kind, null, types [0]);
+				else
+					filter = new MemberFilter (filter.Name, filter.Arity, filter.Kind,
+						ParametersCompiled.CreateFullyResolved (types), filter.MemberType);
+			}
+
+			member = MemberCache.FindMember (declaring_type, filter, BindingRestriction.DeclaredOnly) as T;
+			if (member == null)
+				return null;
+
+			if (!member.IsAccessible (module))
+				return null;
+
+			return member;
+		}
+
+		public T Resolve (Location loc)
+		{
+			if (member != null)
+				return member;
+
+			if (Get () != null)
+				return member;
+
+			if (declaring_type == null) {
+				if (declaring_type_predefined.Resolve () == null)
+					return null;
+			}
+
+			if (filter_builder != null) {
+				filter = new MemberFilter (filter.Name, filter.Arity, filter.Kind,
+					ParametersCompiled.CreateFullyResolved (filter_builder ()), filter.MemberType);
+			}
+
+			string method_args = null;
+			if (filter.Parameters != null)
+				method_args = filter.Parameters.GetSignatureForError ();
+
+			module.Compiler.Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
+				declaring_type.GetSignatureForError (), filter.Name, method_args);
+
+			return null;
+		}
+	}
+
+	public class AwaiterDefinition
+	{
+		public PropertySpec IsCompleted { get; set; }
+		public MethodSpec GetResult { get; set; }
+		public bool INotifyCompletion { get; set; }
+
+		public bool IsValidPattern {
+			get {
+				return IsCompleted != null && GetResult != null && IsCompleted.HasGet;
+			}
+		}
+	}
+
+	partial class TypeManager {
+
+	static public string CSharpName(IList<TypeSpec> types)
+	{
+		if (types.Count == 0)
+			return string.Empty;
+
+		StringBuilder sb = new StringBuilder ();
+		for (int i = 0; i < types.Count; ++i) {
+			if (i > 0)
+				sb.Append (",");
+
+			sb.Append (types [i].GetSignatureForError ());
+		}
+		return sb.ToString ();
+	}
+
+	static public string GetFullNameSignature (MemberSpec mi)
+	{
+		return mi.GetSignatureForError ();
+	}
+
+	static public string CSharpSignature (MemberSpec mb)
+	{
+		return mb.GetSignatureForError ();
+	}
+		
+	public static bool IsFamilyAccessible (TypeSpec type, TypeSpec parent)
+	{
+//		TypeParameter tparam = LookupTypeParameter (type);
+//		TypeParameter pparam = LookupTypeParameter (parent);
+
+		if (type.Kind == MemberKind.TypeParameter && parent.Kind == MemberKind.TypeParameter) { // (tparam != null) && (pparam != null)) {
+			if (type == parent)
+				return true;
+
+			throw new NotImplementedException ("net");
+//			return tparam.IsSubclassOf (parent);
+		}
+
+		do {
+			if (IsInstantiationOfSameGenericType (type, parent))
+				return true;
+
+			type = type.BaseType;
+		} while (type != null);
+
+		return false;
+	}
+
+	//
+	// Checks whether `type' is a nested child of `parent'.
+	//
+	public static bool IsNestedChildOf (TypeSpec type, ITypeDefinition parent)
+	{
+		if (type == null)
+			return false;
+
+		if (type.MemberDefinition == parent)
+			return false;
+
+		type = type.DeclaringType;
+		while (type != null) {
+			if (type.MemberDefinition == parent)
+				return true;
+
+			type = type.DeclaringType;
+		}
+
+		return false;
+	}
+
+	public static TypeSpec GetElementType (TypeSpec t)
+	{
+		return ((ElementTypeSpec)t).Element;
+	}
+
+	/// <summary>
+	/// This method is not implemented by MS runtime for dynamic types
+	/// </summary>
+	public static bool HasElementType (TypeSpec t)
+	{
+		return t is ElementTypeSpec;
+	}
+
+	/// <summary>
+	///   Utility function that can be used to probe whether a type
+	///   is managed or not.  
+	/// </summary>
+	public static bool VerifyUnmanaged (ModuleContainer rc, TypeSpec t, Location loc)
+	{
+		if (t.IsUnmanaged)
+			return true;
+
+		while (t.IsPointer)
+			t = ((ElementTypeSpec) t).Element;
+
+		rc.Compiler.Report.SymbolRelatedToPreviousError (t);
+		rc.Compiler.Report.Error (208, loc,
+			"Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
+			t.GetSignatureForError ());
+
+		return false;	
+	}
+#region Generics
+	// This method always return false for non-generic compiler,
+	// while Type.IsGenericParameter is returned if it is supported.
+	public static bool IsGenericParameter (TypeSpec type)
+	{
+		return type.IsGenericParameter;
+	}
+
+	public static bool IsGenericType (TypeSpec type)
+	{
+		return type.IsGeneric;
+	}
+
+	public static TypeSpec[] GetTypeArguments (TypeSpec t)
+	{
+		// TODO: return empty array !!
+		return t.TypeArguments;
+	}
+
+	/// <summary>
+	///   Check whether `type' and `parent' are both instantiations of the same
+	///   generic type.  Note that we do not check the type parameters here.
+	/// </summary>
+	public static bool IsInstantiationOfSameGenericType (TypeSpec type, TypeSpec parent)
+	{
+		return type == parent || type.MemberDefinition == parent.MemberDefinition;
+	}
+#endregion
+}
+
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/typespec.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/typespec.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/typespec.cs	(revision 11807)
@@ -0,0 +1,2021 @@
+﻿//
+// typespec.cs: Type specification
+//
+// Authors: Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright 2010 Novell, Inc
+// Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
+//
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Linq;
+
+#if STATIC
+using MetaType = IKVM.Reflection.Type;
+using IKVM.Reflection;
+#else
+using MetaType = System.Type;
+using System.Reflection;
+#endif
+
+namespace Mono.CSharp
+{
+	//
+	// Inflated or non-inflated representation of any type. 
+	//
+	public class TypeSpec : MemberSpec
+	{
+		protected MetaType info;
+		protected MemberCache cache;
+		protected IList<TypeSpec> ifaces;
+		TypeSpec base_type;
+
+		Dictionary<TypeSpec[], InflatedTypeSpec> inflated_instances;
+
+		public static readonly TypeSpec[] EmptyTypes = new TypeSpec[0];
+
+#if !STATIC
+		// Reflection Emit hacking
+		static readonly Type TypeBuilder;
+		static readonly Type GenericTypeBuilder;
+
+		static TypeSpec ()
+		{
+			var assembly = typeof (object).Assembly;
+			TypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilder");
+			GenericTypeBuilder = assembly.GetType ("System.Reflection.MonoGenericClass");
+			if (GenericTypeBuilder == null)
+				GenericTypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilderInstantiation");
+		}
+#endif
+
+		public TypeSpec (MemberKind kind, TypeSpec declaringType, ITypeDefinition definition, MetaType info, Modifiers modifiers)
+			: base (kind, declaringType, definition, modifiers)
+		{
+			this.declaringType = declaringType;
+			this.info = info;
+
+			if (definition != null && definition.TypeParametersCount > 0)
+				state |= StateFlags.IsGeneric;
+		}
+
+		#region Properties
+
+		public override int Arity {
+			get {
+				return MemberDefinition.TypeParametersCount;
+			}
+		}
+
+		public virtual TypeSpec BaseType {
+			get {
+				return base_type;
+			}
+			set {
+				base_type = value;
+			}
+		}
+
+		public virtual BuiltinTypeSpec.Type BuiltinType {
+			get {
+				return BuiltinTypeSpec.Type.None;
+			}
+		}
+
+		public bool HasDynamicElement {
+			get {
+				return (state & StateFlags.HasDynamicElement) != 0;
+			}
+		}
+
+		//
+		// Returns a list of all interfaces including
+		// interfaces from base type or base interfaces
+		//
+		public virtual IList<TypeSpec> Interfaces {
+			get {
+				if ((state & StateFlags.InterfacesImported) == 0) {
+					state |= StateFlags.InterfacesImported;
+
+					//
+					// Delay interfaces expansion to save memory and once all
+					// base types has been imported to avoid problems where
+					// interface references type before its base was imported
+					//
+					var imported = MemberDefinition as ImportedTypeDefinition;
+					if (imported != null && Kind != MemberKind.MissingType)
+						imported.DefineInterfaces (this);
+
+				}
+
+				return ifaces;
+			}
+			set {
+				ifaces = value;
+			}
+		}
+
+		public bool IsArray {
+			get {
+				return Kind == MemberKind.ArrayType;
+			}
+		}
+
+		public bool IsAttribute {
+			get {
+				if (!IsClass)
+					return false;
+
+				var type = this;
+				do {
+					if (type.BuiltinType == BuiltinTypeSpec.Type.Attribute)
+						return true;
+
+					if (type.IsGeneric)
+						return false;
+					
+					type = type.base_type;
+				} while (type != null);
+
+				return false;
+			}
+		}
+
+		public bool IsInterface {
+			get {
+				return Kind == MemberKind.Interface;
+			}
+		}
+
+		public bool IsClass {
+			get {
+				return Kind == MemberKind.Class;
+			}
+		}
+
+		public bool IsConstantCompatible {
+			get {
+				if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate | MemberKind.ArrayType)) != 0)
+					return true;
+
+				switch (BuiltinType) {
+				case BuiltinTypeSpec.Type.Int:
+				case BuiltinTypeSpec.Type.UInt:
+				case BuiltinTypeSpec.Type.Long:
+				case BuiltinTypeSpec.Type.ULong:
+				case BuiltinTypeSpec.Type.Float:
+				case BuiltinTypeSpec.Type.Double:
+				case BuiltinTypeSpec.Type.Char:
+				case BuiltinTypeSpec.Type.Short:
+				case BuiltinTypeSpec.Type.Decimal:
+				case BuiltinTypeSpec.Type.Bool:
+				case BuiltinTypeSpec.Type.SByte:
+				case BuiltinTypeSpec.Type.Byte:
+				case BuiltinTypeSpec.Type.UShort:
+				case BuiltinTypeSpec.Type.Dynamic:
+					return true;
+				}
+
+				return false;
+			}
+		}
+
+		public bool IsDelegate {
+			get {
+				return Kind == MemberKind.Delegate;
+			}
+		}
+
+		//
+		// Returns true for instances of Expression<T>
+		//
+		public virtual bool IsExpressionTreeType {
+			get {
+				return false;
+			}
+			set {
+				state = value ? state | StateFlags.InflatedExpressionType : state & ~StateFlags.InflatedExpressionType;
+			}
+		}
+
+		public bool IsEnum {
+			get {
+				return Kind == MemberKind.Enum;
+			}
+		}
+
+		//
+		// Returns true for instances of IList<T>, IEnumerable<T>, ICollection<T>
+		//
+		public virtual bool IsArrayGenericInterface {
+			get {
+				return false;
+			}
+			set {
+				state = value ? state | StateFlags.GenericIterateInterface : state & ~StateFlags.GenericIterateInterface;
+			}
+		}
+
+		//
+		// Returns true for instances of System.Threading.Tasks.Task<T>
+		//
+		public virtual bool IsGenericTask {
+			get {
+				return false;
+			}
+			set {
+				state = value ? state | StateFlags.GenericTask : state & ~StateFlags.GenericTask;
+			}
+		}
+
+		// TODO: Should probably do
+		// IsGenericType -- recursive
+		// HasTypeParameter -- non-recursive
+		public bool IsGenericOrParentIsGeneric {
+			get {
+				var ts = this;
+				do {
+					if (ts.IsGeneric)
+						return true;
+					ts = ts.declaringType;
+				} while (ts != null);
+
+				return false;
+			}
+		}
+
+		public bool IsGenericParameter {
+			get {
+				return Kind == MemberKind.TypeParameter;
+			}
+		}
+
+		//
+		// Returns true for instances of Nullable<T>
+		//
+		public virtual bool IsNullableType {
+			get {
+				return false;
+			}
+			set {
+				state = value ? state | StateFlags.InflatedNullableType : state & ~StateFlags.InflatedNullableType;
+			}
+		}
+
+		public bool IsNested {
+			get { return declaringType != null && Kind != MemberKind.TypeParameter; }
+		}
+
+		public bool IsPointer {
+			get {
+				return Kind == MemberKind.PointerType;
+			}
+		}
+
+		public bool IsSealed {
+			get { return (Modifiers & Modifiers.SEALED) != 0; }
+		}
+
+		public bool IsSpecialRuntimeType {
+			get {
+				return (state & StateFlags.SpecialRuntimeType) != 0;
+			}
+			set {
+				state = value ? state | StateFlags.SpecialRuntimeType : state & ~StateFlags.SpecialRuntimeType;
+			}
+		}
+
+		public bool IsStruct {
+			get { 
+				return Kind == MemberKind.Struct;
+			}
+		}
+
+		public bool IsStructOrEnum {
+			get {
+				return (Kind & (MemberKind.Struct | MemberKind.Enum)) != 0;
+			}
+		}
+
+		public bool IsTypeBuilder {
+			get {
+#if STATIC
+				return true;
+#else
+				var meta = GetMetaInfo().GetType ();
+				return meta == TypeBuilder || meta == GenericTypeBuilder;
+#endif
+			}
+		}
+
+		//
+		// Whether a type is unmanaged. This is used by the unsafe code
+		//
+		public bool IsUnmanaged {
+			get {
+				if (IsPointer)
+					return ((ElementTypeSpec) this).Element.IsUnmanaged;
+
+				var ds = MemberDefinition as TypeDefinition;
+				if (ds != null)
+					return ds.IsUnmanagedType ();
+
+				if (Kind == MemberKind.Void)
+					return true;
+
+				if (Kind == MemberKind.TypeParameter)
+					return false;
+
+				if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
+					return false;
+
+				return IsValueType (this);
+			}
+		}
+
+		//
+		// A cache of all type members (including nested types)
+		//
+		public MemberCache MemberCache {
+			get {
+				if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
+					InitializeMemberCache (false);
+
+				return cache;
+			}
+			set {
+				if (cache != null)
+					throw new InternalErrorException ("Membercache reset");
+
+				cache = value;
+			}
+		}
+
+		public MemberCache MemberCacheTypes {
+			get {
+				if (cache == null)
+					InitializeMemberCache (true);
+
+				return cache;
+			}
+		}	
+
+		public new ITypeDefinition MemberDefinition {
+			get {
+				return (ITypeDefinition) definition;
+			}
+		}
+
+		// TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
+		// remove the property, YES IT WOULD !!!
+		public virtual TypeSpec[] TypeArguments {
+			get { return TypeSpec.EmptyTypes; }
+		}
+
+		#endregion
+
+		public virtual bool AddInterface (TypeSpec iface)
+		{
+			if ((state & StateFlags.InterfacesExpanded) != 0)
+				throw new InternalErrorException ("Modifying expanded interface list");
+
+			if (ifaces == null) {
+				ifaces = new List<TypeSpec> { iface };
+				return true;
+			}
+
+			if (!ifaces.Contains (iface)) {
+				ifaces.Add (iface);
+				return true;
+			}
+
+			return false;
+		}
+
+		//
+		// Special version used during type definition
+		//
+		public bool AddInterfaceDefined (TypeSpec iface)
+		{
+			if (!AddInterface (iface))
+				return false;
+
+			//
+			// We can get into a situation where a type is inflated before
+			// its interfaces are resoved. Consider this situation
+			//
+			// class A<T> : X<A<int>>, IFoo {}
+			//
+			// When resolving base class of X`1 we inflate context type A`1
+			// All this happens before we even hit IFoo resolve. Without
+			// additional expansion any inside usage of A<T> would miss IFoo
+			// interface because it comes from early inflated A`1 definition.
+			//
+			if (inflated_instances != null) {
+				//
+				// Inflate only existing instances not any new instances added
+				// during AddInterface
+				//
+				var inflated_existing = inflated_instances.Values.ToArray ();
+				foreach (var inflated in inflated_existing) {
+					inflated.AddInterface (iface);
+				}
+			}
+
+			return true;
+		}
+
+		//
+		// Returns all type arguments, usefull for nested types
+		//
+		public static TypeSpec[] GetAllTypeArguments (TypeSpec type)
+		{
+			IList<TypeSpec> targs = TypeSpec.EmptyTypes;
+
+			do {
+				if (type.Arity > 0) {
+					if (targs.Count == 0) {
+						targs = type.TypeArguments;
+					} else {
+						var list = targs as List<TypeSpec> ?? new List<TypeSpec> (targs);
+						list.AddRange (type.TypeArguments);
+						targs = list;
+					}
+				}
+
+				type = type.declaringType;
+			} while (type != null);
+
+			return targs as TypeSpec[] ?? ((List<TypeSpec>) targs).ToArray ();
+		}
+
+		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+		{
+			if (Kind != MemberKind.Class)
+				throw new InternalErrorException ();
+
+			if (!pa.IsDefined)
+				return Attribute.DefaultUsageAttribute;
+
+			AttributeUsageAttribute aua = null;
+			var type = this;
+			while (type != null) {
+				aua = type.MemberDefinition.GetAttributeUsage (pa);
+				if (aua != null)
+					break;
+
+				type = type.BaseType;
+			}
+
+			return aua;
+		}
+
+		//
+		// Return metadata information used during emit to describe the type
+		//
+		public virtual MetaType GetMetaInfo ()
+		{
+			return info;
+		}
+
+		public virtual TypeSpec GetDefinition ()
+		{
+			return this;
+		}
+
+		//
+		// Text representation of type used by documentation writer
+		//
+		public override string GetSignatureForDocumentation ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			if (IsNested) {
+				sb.Append (DeclaringType.GetSignatureForDocumentation ());
+			} else {
+				sb.Append (MemberDefinition.Namespace);
+			}
+
+			if (sb.Length != 0)
+				sb.Append (".");
+
+			sb.Append (Name);
+			if (Arity > 0) {
+				if (this is InflatedTypeSpec) {
+				    sb.Append ("{");
+				    for (int i = 0; i < Arity; ++i) {
+				        if (i > 0)
+				            sb.Append (",");
+
+				        sb.Append (TypeArguments[i].GetSignatureForDocumentation ());
+				    }
+				    sb.Append ("}");
+				} else {
+					sb.Append ("`");
+					sb.Append (Arity.ToString ());
+				}
+			}
+
+			return sb.ToString ();
+		}
+
+		public string GetExplicitNameSignatureForDocumentation ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			if (IsNested) {
+				sb.Append (DeclaringType.GetExplicitNameSignatureForDocumentation ());
+			} else if (MemberDefinition.Namespace != null) {
+				sb.Append (MemberDefinition.Namespace.Replace ('.', '#'));
+			}
+
+			if (sb.Length != 0)
+				sb.Append ("#");
+
+			sb.Append (Name);
+			if (Arity > 0) {
+				sb.Append ("{");
+				for (int i = 0; i < Arity; ++i) {
+					if (i > 0)
+						sb.Append (",");
+
+					sb.Append (TypeArguments[i].GetExplicitNameSignatureForDocumentation ());
+				}
+				sb.Append ("}");
+			}
+
+			return sb.ToString ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			string s;
+
+			if (IsNested) {
+				s = DeclaringType.GetSignatureForError ();
+			} else if (MemberDefinition is AnonymousTypeClass) {
+				return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
+			} else {
+				s = MemberDefinition.Namespace;
+			}
+
+			if (!string.IsNullOrEmpty (s))
+				s += ".";
+
+			return s + Name + GetTypeNameSignature ();
+		}
+
+		public string GetSignatureForErrorIncludingAssemblyName ()
+		{
+			return string.Format ("{0} [{1}]", GetSignatureForError (), MemberDefinition.DeclaringAssembly.FullName);
+		}
+
+		protected virtual string GetTypeNameSignature ()
+		{
+			if (!IsGeneric)
+				return null;
+
+			return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
+		}
+
+		public bool ImplementsInterface (TypeSpec iface, bool variantly)
+		{
+			var ifaces = Interfaces;
+			if (ifaces != null) {
+				for (int i = 0; i < ifaces.Count; ++i) {
+					if (TypeSpecComparer.IsEqual (ifaces[i], iface))
+						return true;
+
+					if (variantly && TypeSpecComparer.Variant.IsEqual (ifaces[i], iface))
+						return true;
+				}
+			}
+
+			return false;
+		}
+
+		protected virtual void InitializeMemberCache (bool onlyTypes)
+		{
+			try {
+				MemberDefinition.LoadMembers (this, onlyTypes, ref cache);
+			} catch (Exception e) {
+				throw new InternalErrorException (e, "Unexpected error when loading type `{0}'", GetSignatureForError ());
+			}
+
+			if (onlyTypes)
+				state |= StateFlags.PendingMemberCacheMembers;
+			else
+				state &= ~StateFlags.PendingMemberCacheMembers;
+		}
+
+		//
+		// Is @baseClass base implementation of @type. With enabled @dynamicIsEqual the slower
+		// comparison is used to hide differences between `object' and `dynamic' for generic
+		// types. Should not be used for comparisons where G<object> != G<dynamic>
+		//
+		public static bool IsBaseClass (TypeSpec type, TypeSpec baseClass, bool dynamicIsObject)
+		{
+			if (dynamicIsObject && baseClass.IsGeneric) {
+				//
+				// Returns true for a hierarchies like this when passing baseClass of A<dynamic>
+				//
+				// class B : A<object> {}
+				//
+				type = type.BaseType;
+				while (type != null) {
+					if (TypeSpecComparer.IsEqual (type, baseClass))
+						return true;
+
+					type = type.BaseType;
+				}
+
+				return false;
+			}
+
+			while (type != null) {
+				type = type.BaseType;
+				if (type == baseClass)
+					return true;
+			}
+
+			return false;
+		}
+
+		public static bool IsReferenceType (TypeSpec t)
+		{
+			switch (t.Kind) {
+			case MemberKind.TypeParameter:
+				return ((TypeParameterSpec) t).IsReferenceType;
+			case MemberKind.Struct:
+			case MemberKind.Enum:
+			case MemberKind.Void:
+			case MemberKind.PointerType:
+				return false;
+			case MemberKind.InternalCompilerType:
+				//
+				// Null is considered to be a reference type
+				//			
+				return t == InternalType.NullLiteral || t.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+			default:
+				return true;
+			}
+		}
+
+		public static bool IsNonNullableValueType (TypeSpec t)
+		{
+			switch (t.Kind) {
+			case MemberKind.TypeParameter:
+				return ((TypeParameterSpec) t).IsValueType;
+			case MemberKind.Struct:
+				return !t.IsNullableType;
+			case MemberKind.Enum:
+				return true;
+			default:
+				return false;
+			}
+		}
+
+		public static bool IsValueType (TypeSpec t)
+		{
+			switch (t.Kind) {
+			case MemberKind.TypeParameter:
+				return ((TypeParameterSpec) t).IsValueType;
+			case MemberKind.Struct:
+			case MemberKind.Enum:
+				return true;
+			default:
+				return false;
+			}
+		}
+
+		public override MemberSpec InflateMember (TypeParameterInflator inflator)
+		{
+			var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
+
+			//
+			// When inflating nested type from inside the type instance will be same
+			// because type parameters are same for all nested types
+			//
+			if (DeclaringType == inflator.TypeInstance) {
+				return MakeGenericType (inflator.Context, targs);
+			}
+
+			return new InflatedTypeSpec (inflator.Context, this, inflator.TypeInstance, targs);
+		}
+
+		//
+		// Inflates current type using specific type arguments
+		//
+		public InflatedTypeSpec MakeGenericType (IModuleContext context, TypeSpec[] targs)
+		{
+			if (targs.Length == 0 && !IsNested)
+				throw new ArgumentException ("Empty type arguments for type " + GetSignatureForError ());
+
+			InflatedTypeSpec instance;
+
+			if (inflated_instances == null) {
+				inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
+
+				if (IsNested) {
+					instance = this as InflatedTypeSpec;
+					if (instance != null) {
+						//
+						// Nested types could be inflated on already inflated instances
+						// Caching this type ensured we are using same instance for
+						// inside/outside inflation using local type parameters
+						//
+						inflated_instances.Add (TypeArguments, instance);
+					}
+				}
+			}
+
+			if (!inflated_instances.TryGetValue (targs, out instance)) {
+				if (GetDefinition () != this && !IsNested)
+					throw new InternalErrorException ("`{0}' must be type definition or nested non-inflated type to MakeGenericType",
+						GetSignatureForError ());
+
+				instance = new InflatedTypeSpec (context, this, declaringType, targs);
+				inflated_instances.Add (targs, instance);
+			}
+
+			return instance;
+		}
+
+		public virtual TypeSpec Mutate (TypeParameterMutator mutator)
+		{
+			return this;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			List<MissingTypeSpecReference> missing = null;
+
+			if (Kind == MemberKind.MissingType) {
+				missing = new List<MissingTypeSpecReference> ();
+				missing.Add (new MissingTypeSpecReference (this, caller));
+				return missing;
+			}
+
+			foreach (var targ in TypeArguments) {
+				if (targ.Kind == MemberKind.MissingType) {
+					if (missing == null)
+						missing = new List<MissingTypeSpecReference> ();
+
+					missing.Add (new MissingTypeSpecReference (targ, caller));
+				}
+			}
+
+			if (Interfaces != null) {
+				foreach (var iface in Interfaces) {
+					if (iface.Kind == MemberKind.MissingType) {
+						if (missing == null)
+							missing = new List<MissingTypeSpecReference> ();
+
+						missing.Add (new MissingTypeSpecReference (iface, caller));
+					}
+				}
+			}
+
+			if (MemberDefinition.TypeParametersCount > 0) {
+				foreach (var tp in MemberDefinition.TypeParameters) {
+					var tp_missing = tp.GetMissingDependencies (this);
+					if (tp_missing != null) {
+						if (missing == null)
+							missing = new List<MissingTypeSpecReference> ();
+
+						missing.AddRange (tp_missing);
+					}
+				}
+			}
+
+			if (missing != null || BaseType == null)
+				return missing;
+
+			return BaseType.ResolveMissingDependencies (this);
+		}
+
+		public void SetMetaInfo (MetaType info)
+		{
+			if (this.info != null)
+				throw new InternalErrorException ("MetaInfo reset");
+
+			this.info = info;
+		}
+
+		public void SetExtensionMethodContainer ()
+		{
+			modifiers |= Modifiers.METHOD_EXTENSION;
+		}
+
+		public void UpdateInflatedInstancesBaseType ()
+		{
+			//
+			// When nested class has a partial part the situation where parent type
+			// is inflated before its base type is defined can occur. In such case
+			// all inflated (should be only 1) instansted need to be updated
+			//
+			// partial class A<T> {
+			//   partial class B : A<int> { }
+			// }
+			//
+			// partial class A<T> : X {}
+			//
+			if (inflated_instances == null)
+				return;
+
+			foreach (var inflated in inflated_instances) {
+				//
+				// Don't need to inflate possible generic type because for now the method
+				// is always used from within the nested type
+				//
+				inflated.Value.BaseType = base_type;
+			}
+		}
+	}
+
+	//
+	// Special version used for types which must exist in corlib or
+	// the compiler cannot work
+	//
+	public sealed class BuiltinTypeSpec : TypeSpec
+	{
+		public enum Type
+		{
+			None = 0,
+
+			// Ordered carefully for fast compares
+			FirstPrimitive = 1,
+			Bool = 1,
+			Byte = 2,
+			SByte = 3,
+			Char = 4,
+			Short = 5,
+			UShort = 6,
+			Int = 7,
+			UInt = 8,
+			Long = 9,
+			ULong = 10,
+			Float = 11,
+			Double = 12,
+			LastPrimitive = 12,
+			Decimal = 13,
+
+			IntPtr = 14,
+			UIntPtr = 15,
+
+			Object = 16,
+			Dynamic = 17,
+			String = 18,
+			Type = 19,
+
+			ValueType = 20,
+			Enum = 21,
+			Delegate = 22,
+			MulticastDelegate = 23,
+			Array = 24,
+
+			IEnumerator,
+			IEnumerable,
+			IDisposable,
+			Exception,
+			Attribute,
+			Other,
+		}
+
+		readonly Type type;
+		readonly string ns;
+		readonly string name;
+
+		public BuiltinTypeSpec (MemberKind kind, string ns, string name, Type builtinKind)
+			: base (kind, null, null, null, Modifiers.PUBLIC)
+		{
+			this.type = builtinKind;
+			this.ns = ns;
+			this.name = name;
+		}
+
+		public BuiltinTypeSpec (string name, Type builtinKind)
+			: this (MemberKind.InternalCompilerType, "", name, builtinKind)
+		{
+			// Make all internal types CLS-compliant, non-obsolete, compact
+			state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
+		}
+
+		#region Properties
+
+		public override int Arity {
+			get {
+				return 0;
+			}
+		}
+
+		public override BuiltinTypeSpec.Type BuiltinType {
+			get {
+				return type;
+			}
+		}
+
+		public string FullName {
+			get {
+				return ns + '.' + name;
+			}
+		}
+
+		public override string Name {
+			get {
+				return name;
+			}
+		}
+
+		public string Namespace {
+			get {
+				return ns;
+			}
+		}
+
+		#endregion
+
+		public static bool IsPrimitiveType (TypeSpec type)
+		{
+			return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.LastPrimitive;
+		}
+
+		public static bool IsPrimitiveTypeOrDecimal (TypeSpec type)
+		{
+			return type.BuiltinType >= Type.FirstPrimitive && type.BuiltinType <= Type.Decimal;
+		}
+
+		public override string GetSignatureForError ()
+		{
+			switch (Name) {
+			case "Int32": return "int";
+			case "Int64": return "long";
+			case "String": return "string";
+			case "Boolean": return "bool";
+			case "Void": return "void";
+			case "Object": return "object";
+			case "UInt32": return "uint";
+			case "Int16": return "short";
+			case "UInt16": return "ushort";
+			case "UInt64": return "ulong";
+			case "Single": return "float";
+			case "Double": return "double";
+			case "Decimal": return "decimal";
+			case "Char": return "char";
+			case "Byte": return "byte";
+			case "SByte": return "sbyte";
+			}
+
+			if (ns.Length == 0)
+				return name;
+
+			return FullName;
+		}
+
+		//
+		// Returns the size of type if known, otherwise, 0
+		//
+		public static int GetSize (TypeSpec type)
+		{
+			switch (type.BuiltinType) {
+			case Type.Int:
+			case Type.UInt:
+			case Type.Float:
+				return 4;
+			case Type.Long:
+			case Type.ULong:
+			case Type.Double:
+				return 8;
+			case Type.Byte:
+			case Type.SByte:
+			case Type.Bool:
+				return 1;
+			case Type.Short:
+			case Type.Char:
+			case Type.UShort:
+				return 2;
+			case Type.Decimal:
+				return 16;
+			default:
+				return 0;
+			}
+		}
+
+		public void SetDefinition (ITypeDefinition td, MetaType type, Modifiers mod)
+		{
+			this.definition = td;
+			this.info = type;
+			this.modifiers |= (mod & ~Modifiers.AccessibilityMask);
+		}
+
+		public void SetDefinition (TypeSpec ts)
+		{
+			this.definition = ts.MemberDefinition;
+			this.info = ts.GetMetaInfo ();
+			this.BaseType = ts.BaseType;
+			this.Interfaces = ts.Interfaces;
+			this.modifiers = ts.Modifiers;
+		}
+	}
+
+	//
+	// Various type comparers used by compiler
+	//
+	static class TypeSpecComparer
+	{
+		//
+		// Does strict reference comparion only
+		//
+		public static readonly DefaultImpl Default = new DefaultImpl ();
+
+		public class DefaultImpl : IEqualityComparer<TypeSpec[]>
+		{
+			#region IEqualityComparer<TypeSpec[]> Members
+
+			bool IEqualityComparer<TypeSpec[]>.Equals (TypeSpec[] x, TypeSpec[] y)
+			{
+				if (x == y)
+					return true;
+
+				if (x.Length != y.Length)
+					return false;
+
+				for (int i = 0; i < x.Length; ++i)
+					if (x[i] != y[i])
+						return false;
+
+				return true;
+			}
+
+			int IEqualityComparer<TypeSpec[]>.GetHashCode (TypeSpec[] obj)
+			{
+				int hash = 0;
+				for (int i = 0; i < obj.Length; ++i)
+					hash = (hash << 5) - hash + obj[i].GetHashCode ();
+
+				return hash;
+			}
+
+			#endregion
+		}
+
+		//
+		// When comparing type signature of overrides or overloads
+		// this version tolerates different MVARs at same position
+		//
+		public static class Override
+		{
+			public static bool IsEqual (TypeSpec a, TypeSpec b)
+			{
+				if (a == b)
+					return true;
+
+				//
+				// Consider the following example:
+				//
+				//     public abstract class A
+				//     {
+				//        public abstract T Foo<T>();
+				//     }
+				//
+				//     public class B : A
+				//     {
+				//        public override U Foo<T>() { return default (U); }
+				//     }
+				//
+				// Here, `T' and `U' are method type parameters from different methods
+				// (A.Foo and B.Foo), so both `==' and Equals() will fail.
+				//
+				// However, since we're determining whether B.Foo() overrides A.Foo(),
+				// we need to do a signature based comparision and consider them equal.
+				//
+
+				var tp_a = a as TypeParameterSpec;
+				if (tp_a != null) {
+					var tp_b = b as TypeParameterSpec;
+					return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
+				}
+
+				var ac_a = a as ArrayContainer;
+				if (ac_a != null) {
+					var ac_b = b as ArrayContainer;
+					return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
+				}
+
+				if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
+
+				if (a.MemberDefinition != b.MemberDefinition)
+					return false;
+
+				do {
+					for (int i = 0; i < a.TypeArguments.Length; ++i) {
+						if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
+							return false;
+					}
+
+					a = a.DeclaringType;
+					b = b.DeclaringType;
+				} while (a != null);
+
+				return true;
+			}
+
+			public static bool IsEqual (TypeSpec[] a, TypeSpec[] b)
+			{
+				if (a == b)
+					return true;
+
+				if (a.Length != b.Length)
+					return false;
+
+				for (int i = 0; i < a.Length; ++i) {
+					if (!IsEqual (a[i], b[i]))
+						return false;
+				}
+
+				return true;
+			}
+
+
+			//
+			// Compares unordered arrays
+			//
+			public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
+			{
+				if (a == b)
+					return true;
+
+				if (a == null || b == null || a.Length != b.Length)
+					return false;
+
+				for (int ai = 0; ai < a.Length; ++ai) {
+					bool found = false;
+					for (int bi = 0; bi < b.Length; ++bi) {
+						if (IsEqual (a[ai], b[bi])) {
+							found = true;
+							break;
+						}
+					}
+
+					if (!found)
+						return false;
+				}
+
+				return true;
+			}
+
+			public static bool IsEqual (AParametersCollection a, AParametersCollection b)
+			{
+				if (a == b)
+					return true;
+
+				if (a.Count != b.Count)
+					return false;
+
+				for (int i = 0; i < a.Count; ++i) {
+					if (!IsEqual (a.Types[i], b.Types[i]))
+						return false;
+
+					if ((a.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask) != (b.FixedParameters[i].ModFlags & Parameter.Modifier.RefOutMask))
+						return false;
+				}
+
+				return true;
+			}
+		}
+
+		//
+		// Type variance equality comparison
+		//
+		public static class Variant
+		{
+			public static bool IsEqual (TypeSpec type1, TypeSpec type2)
+			{
+				if (!type1.IsGeneric || !type2.IsGeneric)
+					return false;
+
+				var target_type_def = type2.MemberDefinition;
+				if (type1.MemberDefinition != target_type_def)
+					return false;
+
+				var t1_targs = type1.TypeArguments;
+				var t2_targs = type2.TypeArguments;
+				var targs_definition = target_type_def.TypeParameters;
+
+				if (!type1.IsInterface && !type1.IsDelegate) {
+					return false;
+				}
+
+				for (int i = 0; i < targs_definition.Length; ++i) {
+					if (TypeSpecComparer.IsEqual (t1_targs[i], t2_targs[i]))
+						continue;
+
+					Variance v = targs_definition[i].Variance;
+					if (v == Variance.None) {
+						return false;
+					}
+
+					if (v == Variance.Covariant) {
+						if (!Convert.ImplicitReferenceConversionExists (t1_targs[i], t2_targs[i]))
+							return false;
+					} else if (!Convert.ImplicitReferenceConversionExists (t2_targs[i], t1_targs[i])) {
+						return false;
+					}
+				}
+
+				return true;
+			}
+		}
+
+		//
+		// Checks whether two generic instances may become equal for some
+		// particular instantiation (26.3.1).
+		//
+		public static class Unify
+		{
+			//
+			// Either @a or @b must be generic type
+			//
+			public static bool IsEqual (TypeSpec a, TypeSpec b)
+			{
+				if (a.MemberDefinition != b.MemberDefinition) {
+					var base_ifaces = a.Interfaces;
+					if (base_ifaces != null) {
+						foreach (var base_iface in base_ifaces) {
+							if (base_iface.Arity > 0 && IsEqual (base_iface, b))
+								return true;
+						}
+					}
+
+					return false;
+				}
+
+				var ta = a.TypeArguments;
+				var tb = b.TypeArguments;
+				for (int i = 0; i < ta.Length; i++) {
+					if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
+						return false;
+				}
+
+				if (a.IsNested && b.IsNested)
+					return IsEqual (a.DeclaringType, b.DeclaringType);
+
+				return true;
+			}
+
+			static bool ContainsTypeParameter (TypeSpec tparam, TypeSpec type)
+			{
+				TypeSpec[] targs = type.TypeArguments;
+				for (int i = 0; i < targs.Length; i++) {
+					if (tparam == targs[i])
+						return true;
+
+					if (ContainsTypeParameter (tparam, targs[i]))
+						return true;
+				}
+
+				return false;
+			}
+
+			/// <summary>
+			///   Check whether `a' and `b' may become equal generic types.
+			///   The algorithm to do that is a little bit complicated.
+			/// </summary>
+			static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
+			{
+				if (a.IsGenericParameter) {
+					//
+					// If a is an array of a's type, they may never
+					// become equal.
+					//
+					if (b.IsArray)
+						return false;
+
+					//
+					// If b is a generic parameter or an actual type,
+					// they may become equal:
+					//
+					//    class X<T,U> : I<T>, I<U>
+					//    class X<T> : I<T>, I<float>
+					// 
+					if (b.IsGenericParameter)
+						return a != b && a.DeclaringType == b.DeclaringType;
+
+					//
+					// We're now comparing a type parameter with a
+					// generic instance.  They may become equal unless
+					// the type parameter appears anywhere in the
+					// generic instance:
+					//
+					//    class X<T,U> : I<T>, I<X<U>>
+					//        -> error because you could instanciate it as
+					//           X<X<int>,int>
+					//
+					//    class X<T> : I<T>, I<X<T>> -> ok
+					//
+
+					return !ContainsTypeParameter (a, b);
+				}
+
+				if (b.IsGenericParameter)
+					return MayBecomeEqualGenericTypes (b, a);
+
+				//
+				// At this point, neither a nor b are a type parameter.
+				//
+				// If one of them is a generic instance, compare them (if the
+				// other one is not a generic instance, they can never
+				// become equal).
+				//
+				if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
+					return IsEqual (a, b);
+
+				//
+				// If both of them are arrays.
+				//
+				var a_ac = a as ArrayContainer;
+				if (a_ac != null) {
+					var b_ac = b as ArrayContainer;
+					if (b_ac == null || a_ac.Rank != b_ac.Rank)
+						return false;
+
+					return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
+				}
+
+				//
+				// Ok, two ordinary types.
+				//
+				return false;
+			}
+		}
+
+		public static bool Equals (TypeSpec[] x, TypeSpec[] y)
+		{
+			if (x == y)
+				return true;
+
+			if (x.Length != y.Length)
+				return false;
+
+			for (int i = 0; i < x.Length; ++i)
+				if (!IsEqual (x[i], y[i]))
+					return false;
+
+			return true;
+		}
+
+		//
+		// Identity type conversion
+		//
+		// Default reference comparison, it has to be used when comparing
+		// two possible dynamic/internal types
+		//
+		public static bool IsEqual (TypeSpec a, TypeSpec b)
+		{
+			if (a == b) {
+				// This also rejects dynamic == dynamic
+				return a.Kind != MemberKind.InternalCompilerType || a.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
+			}
+
+			if (a == null || b == null)
+				return false;
+
+			if (a.IsArray) {
+				var a_a = (ArrayContainer) a;
+				var b_a = b as ArrayContainer;
+				if (b_a == null)
+					return false;
+
+				return a_a.Rank == b_a.Rank && IsEqual (a_a.Element, b_a.Element);
+			}
+
+			if (!a.IsGeneric || !b.IsGeneric) {
+				//
+				// object and dynamic are considered equivalent there is an identity conversion
+				// between object and dynamic, and between constructed types that are the same
+				// when replacing all occurences of dynamic with object.
+				//
+				if (a.BuiltinType == BuiltinTypeSpec.Type.Dynamic || b.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+					return b.BuiltinType == BuiltinTypeSpec.Type.Object || a.BuiltinType == BuiltinTypeSpec.Type.Object;
+
+				return false;
+			}
+
+			if (a.MemberDefinition != b.MemberDefinition)
+				return false;
+
+			do {
+				if (!Equals (a.TypeArguments, b.TypeArguments))
+					return false;
+
+				a = a.DeclaringType;
+				b = b.DeclaringType;
+			} while (a != null);
+
+			return true;
+		}
+	}
+
+	public interface ITypeDefinition : IMemberDefinition
+	{
+		IAssemblyDefinition DeclaringAssembly { get; }
+		string Namespace { get; }
+		bool IsPartial { get; }
+		bool IsComImport { get; }
+		bool IsTypeForwarder { get; }
+		bool IsCyclicTypeForwarder { get; }
+		int TypeParametersCount { get; }
+		TypeParameterSpec[] TypeParameters { get; }
+
+		TypeSpec GetAttributeCoClass ();
+		string GetAttributeDefaultMember ();
+		AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
+		bool IsInternalAsPublic (IAssemblyDefinition assembly);
+		void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache);
+	}
+
+	class InternalType : TypeSpec, ITypeDefinition
+	{
+		public static readonly InternalType AnonymousMethod = new InternalType ("anonymous method");
+		public static readonly InternalType Arglist = new InternalType ("__arglist");
+		public static readonly InternalType MethodGroup = new InternalType ("method group");
+		public static readonly InternalType NullLiteral = new InternalType ("null");
+		public static readonly InternalType FakeInternalType = new InternalType ("<fake$type>");
+		public static readonly InternalType Namespace = new InternalType ("<namespace>");
+		public static readonly InternalType ErrorType = new InternalType ("<error>");
+
+		readonly string name;
+
+		InternalType (string name)
+			: base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
+		{
+			this.name = name;
+			this.definition = this;
+			cache = MemberCache.Empty;
+
+			// Make all internal types CLS-compliant, non-obsolete
+			state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected | StateFlags.MissingDependency_Undetected)) | StateFlags.CLSCompliant;
+		}
+
+		#region Properties
+
+		public override int Arity {
+			get {
+				return 0;
+			}
+		}
+
+		IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
+			get {
+				throw new NotImplementedException ();
+			}
+		}
+
+		bool ITypeDefinition.IsComImport {
+			get {
+				return false;
+			}
+		}
+
+		bool IMemberDefinition.IsImported {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsPartial {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsCyclicTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		public override string Name {
+			get {
+				return name;
+			}
+		}
+
+		string ITypeDefinition.Namespace {
+			get {
+				return null;
+			}
+		}
+
+		int ITypeDefinition.TypeParametersCount {
+			get {
+				return 0;
+			}
+		}
+
+		TypeParameterSpec[] ITypeDefinition.TypeParameters {
+			get {
+				return null;
+			}
+		}
+
+		#endregion
+
+		public override string GetSignatureForError ()
+		{
+			return name;
+		}
+
+		#region ITypeDefinition Members
+
+		TypeSpec ITypeDefinition.GetAttributeCoClass ()
+		{
+			return null;
+		}
+
+		string ITypeDefinition.GetAttributeDefaultMember ()
+		{
+			return null;
+		}
+
+		AttributeUsageAttribute ITypeDefinition.GetAttributeUsage (PredefinedAttribute pa)
+		{
+			return null;
+		}
+
+		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
+		{
+			throw new NotImplementedException ();
+		}
+
+		void ITypeDefinition.LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+		{
+			throw new NotImplementedException ();
+		}
+
+		string[] IMemberDefinition.ConditionalConditions ()
+		{
+			return null;
+		}
+
+		ObsoleteAttribute IMemberDefinition.GetAttributeObsolete ()
+		{
+			return null;
+		}
+
+		bool? IMemberDefinition.CLSAttributeValue {
+			get {
+				return null;
+			}
+		}
+
+		void IMemberDefinition.SetIsAssigned ()
+		{
+		}
+
+		void IMemberDefinition.SetIsUsed ()
+		{
+		}
+
+		#endregion
+	}
+
+	//
+	// Common base class for composite types
+	//
+	public abstract class ElementTypeSpec : TypeSpec, ITypeDefinition
+	{
+		protected ElementTypeSpec (MemberKind kind, TypeSpec element, MetaType info)
+			: base (kind, element.DeclaringType, null, info, element.Modifiers)
+		{
+			this.Element = element;
+
+			state &= ~SharedStateFlags;
+			state |= (element.state & SharedStateFlags);
+
+			if (element.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
+				state |= StateFlags.HasDynamicElement;
+
+			// Has to use its own type definition instead of just element definition to
+			// correctly identify itself for cases like x.MemberDefininition == predefined.MemberDefinition
+			this.definition = this;
+
+			cache = MemberCache.Empty;
+		}
+
+		#region Properties
+
+		public TypeSpec Element { get; private set; }
+
+		bool ITypeDefinition.IsComImport {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsPartial {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		bool ITypeDefinition.IsCyclicTypeForwarder {
+			get {
+				return false;
+			}
+		}
+
+		public override string Name {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		#endregion
+
+		public override ObsoleteAttribute GetAttributeObsolete ()
+		{
+			return Element.GetAttributeObsolete ();
+		}
+
+		protected virtual string GetPostfixSignature ()
+		{
+			return null;
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			return Element.GetSignatureForDocumentation () + GetPostfixSignature ();
+		}
+
+		public override string GetSignatureForError ()
+		{
+			return Element.GetSignatureForError () + GetPostfixSignature ();
+		}
+
+		public override TypeSpec Mutate (TypeParameterMutator mutator)
+		{
+			var me = Element.Mutate (mutator);
+			if (me == Element)
+				return this;
+
+			var mutated = (ElementTypeSpec) MemberwiseClone ();
+			mutated.Element = me;
+			mutated.info = null;
+			return mutated;
+		}
+
+		#region ITypeDefinition Members
+
+		IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
+			get {
+				return Element.MemberDefinition.DeclaringAssembly;
+			}
+		}
+
+		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
+		{
+			return Element.MemberDefinition.IsInternalAsPublic (assembly);
+		}
+
+		public string Namespace {
+			get { throw new NotImplementedException (); }
+		}
+
+		public int TypeParametersCount {
+			get {
+				return 0;
+			}
+		}
+
+		public TypeParameterSpec[] TypeParameters {
+			get {
+				throw new NotSupportedException ();
+			}
+		}
+
+		public TypeSpec GetAttributeCoClass ()
+		{
+			return Element.MemberDefinition.GetAttributeCoClass ();
+		}
+
+		public string GetAttributeDefaultMember ()
+		{
+			return Element.MemberDefinition.GetAttributeDefaultMember ();
+		}
+
+		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
+		{
+			Element.MemberDefinition.LoadMembers (declaringType, onlyTypes, ref cache);
+		}
+
+		public bool IsImported {
+			get {
+				return Element.MemberDefinition.IsImported;
+			}
+		}
+
+		public string[] ConditionalConditions ()
+		{
+			return Element.MemberDefinition.ConditionalConditions ();
+		}
+
+		bool? IMemberDefinition.CLSAttributeValue {
+			get {
+				return Element.MemberDefinition.CLSAttributeValue;
+			}
+		}
+
+		public void SetIsAssigned ()
+		{
+			Element.MemberDefinition.SetIsAssigned ();
+		}
+
+		public void SetIsUsed ()
+		{
+			Element.MemberDefinition.SetIsUsed ();
+		}
+
+		#endregion
+	}
+
+	public class ArrayContainer : ElementTypeSpec
+	{
+		public struct TypeRankPair : IEquatable<TypeRankPair>
+		{
+			TypeSpec ts;
+			int rank;
+
+			public TypeRankPair (TypeSpec ts, int rank)
+			{
+				this.ts = ts;
+				this.rank = rank;
+			}
+
+			public override int GetHashCode ()
+			{
+				return ts.GetHashCode () ^ rank.GetHashCode ();
+			}
+
+			#region IEquatable<Tuple<T1,T2>> Members
+
+			public bool Equals (TypeRankPair other)
+			{
+				return other.ts == ts && other.rank == rank;
+			}
+
+			#endregion
+		}
+
+		readonly int rank;
+		readonly ModuleContainer module;
+
+		private ArrayContainer (ModuleContainer module, TypeSpec element, int rank)
+			: base (MemberKind.ArrayType, element, null)
+		{
+			this.module = module;
+			this.rank = rank;
+		}
+
+		public int Rank {
+			get {
+				return rank;
+			}
+		}
+
+		public MethodInfo GetConstructor ()
+		{
+			var mb = module.Builder;
+
+			var arg_types = new MetaType[rank];
+			for (int i = 0; i < rank; i++)
+				arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
+
+			var ctor = mb.GetArrayMethod (
+				GetMetaInfo (), Constructor.ConstructorName,
+				CallingConventions.HasThis,
+				null, arg_types);
+
+			return ctor;
+		}
+
+		public MethodInfo GetAddressMethod ()
+		{
+			var mb = module.Builder;
+
+			var arg_types = new MetaType[rank];
+			for (int i = 0; i < rank; i++)
+				arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
+
+			var address = mb.GetArrayMethod (
+				GetMetaInfo (), "Address",
+				CallingConventions.HasThis | CallingConventions.Standard,
+				ReferenceContainer.MakeType (module, Element).GetMetaInfo (), arg_types);
+
+			return address;
+		}
+
+		public MethodInfo GetGetMethod ()
+		{
+			var mb = module.Builder;
+
+			var arg_types = new MetaType[rank];
+			for (int i = 0; i < rank; i++)
+				arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
+
+			var get = mb.GetArrayMethod (
+				GetMetaInfo (), "Get",
+				CallingConventions.HasThis | CallingConventions.Standard,
+				Element.GetMetaInfo (), arg_types);
+
+			return get;
+		}
+
+		public MethodInfo GetSetMethod ()
+		{
+			var mb = module.Builder;
+
+			var arg_types = new MetaType[rank + 1];
+			for (int i = 0; i < rank; i++)
+				arg_types[i] = module.Compiler.BuiltinTypes.Int.GetMetaInfo ();
+
+			arg_types[rank] = Element.GetMetaInfo ();
+
+			var set = mb.GetArrayMethod (
+				GetMetaInfo (), "Set",
+				CallingConventions.HasThis | CallingConventions.Standard,
+				module.Compiler.BuiltinTypes.Void.GetMetaInfo (), arg_types);
+
+			return set;
+		}
+
+		public override MetaType GetMetaInfo ()
+		{
+			if (info == null) {
+				if (rank == 1)
+					info = Element.GetMetaInfo ().MakeArrayType ();
+				else
+					info = Element.GetMetaInfo ().MakeArrayType (rank);
+			}
+
+			return info;
+		}
+
+		protected override string GetPostfixSignature()
+		{
+			return GetPostfixSignature (rank);
+		}
+
+		public static string GetPostfixSignature (int rank)
+		{
+			StringBuilder sb = new StringBuilder ();
+			sb.Append ("[");
+			for (int i = 1; i < rank; i++) {
+				sb.Append (",");
+			}
+			sb.Append ("]");
+
+			return sb.ToString ();
+		}
+
+		public override string GetSignatureForDocumentation ()
+		{
+			StringBuilder sb = new StringBuilder ();
+			GetElementSignatureForDocumentation (sb);
+			return sb.ToString ();
+		}
+
+		void GetElementSignatureForDocumentation (StringBuilder sb)
+		{
+			var ac = Element as ArrayContainer;
+			if (ac == null)
+				sb.Append (Element.GetSignatureForDocumentation ());
+			else
+				ac.GetElementSignatureForDocumentation (sb);
+
+			sb.Append ("[");
+			for (int i = 1; i < rank; i++) {
+				if (i == 1)
+					sb.Append ("0:");
+
+				sb.Append (",0:");
+			}
+			sb.Append ("]");
+		}
+
+		public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element)
+		{
+			return MakeType (module, element, 1);
+		}
+
+		public static ArrayContainer MakeType (ModuleContainer module, TypeSpec element, int rank)
+		{
+			ArrayContainer ac;
+			var key = new TypeRankPair (element, rank);
+			if (!module.ArrayTypesCache.TryGetValue (key, out ac)) {
+				ac = new ArrayContainer (module, element, rank);
+				ac.BaseType = module.Compiler.BuiltinTypes.Array;
+				ac.Interfaces = ac.BaseType.Interfaces;
+
+				module.ArrayTypesCache.Add (key, ac);
+			}
+
+			return ac;
+		}
+
+		public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
+		{
+			return Element.ResolveMissingDependencies (caller);
+		}
+	}
+
+	class ReferenceContainer : ElementTypeSpec
+	{
+		private ReferenceContainer (TypeSpec element)
+			: base (MemberKind.Class, element, null)	// TODO: Kind.Class is most likely wrong
+		{
+		}
+
+		public override MetaType GetMetaInfo ()
+		{
+			if (info == null) {
+				info = Element.GetMetaInfo ().MakeByRefType ();
+			}
+
+			return info;
+		}
+
+		public static ReferenceContainer MakeType (ModuleContainer module, TypeSpec element)
+		{
+			ReferenceContainer pc;
+			if (!module.ReferenceTypesCache.TryGetValue (element, out pc)) {
+				pc = new ReferenceContainer (element);
+				module.ReferenceTypesCache.Add (element, pc);
+			}
+
+			return pc;
+		}
+	}
+
+	class PointerContainer : ElementTypeSpec
+	{
+		private PointerContainer (TypeSpec element)
+			: base (MemberKind.PointerType, element, null)
+		{
+			// It's never CLS-Compliant
+			state &= ~StateFlags.CLSCompliant_Undetected;
+		}
+
+		public override MetaType GetMetaInfo ()
+		{
+			if (info == null) {
+				info = Element.GetMetaInfo ().MakePointerType ();
+			}
+
+			return info;
+		}
+
+		protected override string GetPostfixSignature()
+		{
+ 			return "*";
+		}
+
+		public static PointerContainer MakeType (ModuleContainer module, TypeSpec element)
+		{
+			PointerContainer pc;
+			if (!module.PointerTypesCache.TryGetValue (element, out pc)) {
+				pc = new PointerContainer (element);
+				module.PointerTypesCache.Add (element, pc);
+			}
+
+			return pc;
+		}
+	}
+
+	public class MissingTypeSpecReference
+	{
+		public MissingTypeSpecReference (TypeSpec type, MemberSpec caller)
+		{
+			Type = type;
+			Caller = caller;
+		}
+
+		public TypeSpec Type { get; private set; }
+		public MemberSpec Caller { get; private set; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/visit.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/visit.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/visit.cs	(revision 11807)
@@ -0,0 +1,618 @@
+//
+// visit.cs: Visitors for parsed dom
+//
+// Authors: Mike Krüger (mkrueger@novell.com)
+//          Marek Safar (marek.safar@gmail.com)
+//
+// Dual licensed under the terms of the MIT X11 or GNU GPL
+//
+// Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+// Copyright 2011 Xamarin Inc
+//
+
+using System;
+using System.Diagnostics;
+
+namespace Mono.CSharp
+{
+	public abstract class StructuralVisitor
+	{
+		public virtual void Visit (MemberCore member)
+		{
+			Debug.Fail ("unknown member type: " + member.GetType ());
+		}
+
+		public virtual void Visit (ModuleContainer mc)
+		{
+			foreach (var container in mc.Containers) {
+				container.Accept (this);
+			}
+		}
+
+		void VisitTypeDefinition (TypeDefinition tc)
+		{
+			foreach (var member in tc.Members) {
+				member.Accept (this);
+			}
+		}
+
+		public virtual void Visit (NamespaceContainer ns)
+		{
+		}
+
+		public virtual void Visit (UsingNamespace un)
+		{
+		}
+
+		public virtual void Visit (UsingAliasNamespace uan)
+		{
+		}
+		
+		public virtual void Visit (UsingExternAlias uea)
+		{
+		}
+
+		public virtual void Visit (CompilationSourceFile csf)
+		{
+		}
+
+		public virtual void Visit (Class c)
+		{
+			VisitTypeDefinition (c);
+		}
+
+		public virtual void Visit (Struct s)
+		{
+			VisitTypeDefinition (s);
+		}
+
+
+		public virtual void Visit (Interface i)
+		{
+			VisitTypeDefinition (i);
+		}
+
+		public virtual void Visit (Delegate d)
+		{
+		}
+
+		public virtual void Visit (Enum e)
+		{
+			VisitTypeDefinition (e);
+		}
+
+		public virtual void Visit (FixedField f)
+		{
+		}
+
+		public virtual void Visit (Const c)
+		{
+		}
+
+		public virtual void Visit (Field f)
+		{
+		}
+
+		public virtual void Visit (Operator o)
+		{
+		}
+
+		public virtual void Visit (Indexer i)
+		{
+		}
+
+		public virtual void Visit (Method m)
+		{
+		}
+
+		public virtual void Visit (Property p)
+		{
+		}
+
+		public virtual void Visit (Constructor c)
+		{
+		}
+
+		public virtual void Visit (Destructor d)
+		{
+		}
+
+		public virtual void Visit (EventField e)
+		{
+		}
+		public virtual void Visit (EventProperty ep)
+		{
+		}
+
+		public virtual void Visit (EnumMember em)
+		{
+		}
+		
+		public virtual object Visit (Statement stmt)
+		{
+			Debug.Fail ("unknown statement:" + stmt);
+			return null;
+		}
+		
+		public virtual object Visit (BlockVariable blockVariableDeclaration)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (BlockConstant blockConstantDeclaration)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (EmptyStatement emptyStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (EmptyExpressionStatement emptyExpressionStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (EmptyExpression emptyExpression)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (ErrorExpression errorExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (If ifStatement)
+		{
+			return null;
+		}
+
+
+		public virtual object Visit (Do doStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (While whileStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (For forStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (StatementExpression statementExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (StatementErrorExpression errorStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Return returnStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Goto gotoStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (LabeledStatement labeledStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (SwitchLabel switchLabel)
+		{
+			return null;
+		}
+
+		public virtual object Visit (GotoDefault gotoDefault)
+		{
+			return null;
+		}
+
+		public virtual object Visit (GotoCase gotoCase)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Throw throwStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Break breakStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Continue continueStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Block blockStatement)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (Switch switchStatement)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (StatementList statementList)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (Lock lockStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Unchecked uncheckedStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Checked checkedStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Unsafe unsafeStatement)
+		{
+			return null;
+		}
+
+
+		public virtual object Visit (Fixed fixedStatement)
+		{
+			return null;
+		}
+
+
+		public virtual object Visit (TryFinally tryFinallyStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (TryCatch tryCatchStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Using usingStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Foreach foreachStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Yield yieldStatement)
+		{
+			return null;
+		}
+
+		public virtual object Visit (YieldBreak yieldBreakStatement)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (InvalidStatementExpression invalidStatementExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Expression expression)
+		{
+			Debug.Fail ("Visit unknown expression:" + expression);
+			return null;
+		}
+
+		public virtual object Visit (MemberAccess memberAccess)
+		{
+			return null;
+		}
+
+		public virtual object Visit (QualifiedAliasMember qualifiedAliasMember)
+		{
+			return null;
+		}
+
+		public virtual object Visit (LocalVariableReference localVariableReference)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Constant constant)
+		{
+			return null;
+		}
+
+		public virtual object Visit (BooleanExpression booleanExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (SimpleName simpleName)
+		{
+			return null;
+		}
+
+		public virtual object Visit (ParenthesizedExpression parenthesizedExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Unary unaryExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (UnaryMutator unaryMutatorExpression)
+		{
+			return null;
+		}
+
+		// *expr
+		public virtual object Visit (Indirection indirectionExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Is isExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (As asExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Cast castExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (ComposedCast composedCast)
+		{
+			return null;
+		}
+
+		public virtual object Visit (DefaultValueExpression defaultValueExpression)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (DefaultParameterValueExpression defaultParameterValueExpression)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (Binary binaryExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Nullable.NullCoalescingOperator nullCoalescingOperator)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Conditional conditionalExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Invocation invocationExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (New newExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (NewAnonymousType newAnonymousType)
+		{
+			return null;
+		}
+
+		public virtual object Visit (NewInitialize newInitializeExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (ArrayCreation arrayCreationExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (This thisExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (ArglistAccess argListAccessExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Arglist argListExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (TypeOf typeOfExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (SizeOf sizeOfExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (CheckedExpr checkedExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (UnCheckedExpr uncheckedExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (ElementAccess elementAccessExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (BaseThis baseAccessExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (StackAlloc stackAllocExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (SimpleAssign simpleAssign)
+		{
+			return null;
+		}
+
+		public virtual object Visit (CompoundAssign compoundAssign)
+		{
+			return null;
+		}
+
+		public virtual object Visit (TypeExpression typeExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (AnonymousMethodExpression anonymousMethodExpression)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (LambdaExpression lambdaExpression)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (ConstInitializer constInitializer)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (ArrayInitializer arrayInitializer)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (Linq.QueryExpression queryExpression)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.QueryStartClause queryExpression)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (Linq.SelectMany selectMany)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.Select select)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.GroupBy groupBy)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.Let let)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.Where where)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.Join join)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.GroupJoin groupJoin)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.OrderByAscending orderByAscending)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.OrderByDescending orderByDescending)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Linq.ThenByAscending thenByAscending)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (Linq.ThenByDescending thenByDescending)
+		{
+			return null;
+		}
+		
+		// undocumented expressions
+		public virtual object Visit (RefValueExpr refValueExpr)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (RefTypeExpr refTypeExpr)
+		{
+			return null;
+		}
+		
+		public virtual object Visit (MakeRefExpr makeRefExpr)
+		{
+			return null;
+		}
+
+		public virtual object Visit (Await awaitExpr)
+		{
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/PatternMatching/AnyType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/PatternMatching/AnyType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/PatternMatching/AnyType.cs	(revision 11807)
@@ -0,0 +1,37 @@
+//
+// AnyType.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp;
+
+namespace ICSharpCode.NRefactory.PatternMatching
+{
+
+
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,35 @@
+﻿using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ICSharpCode.NRefactory.CSharp")]
+[assembly: AssemblyDescription("C# parser and semantic analysis")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("ICSharpCode")]
+[assembly: AssemblyProduct("SharpDevelop/MonoDevelop")]
+[assembly: AssemblyCopyright("Copyright 2010-2014 AlphaSierraPapa and Xamarin Inc.")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("ec817c21-8977-45f7-bc62-ca478f5630d5")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.0.0.0")]
+[assembly: AssemblyFileVersion("5.5.0")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/QueryExpressionExpander.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/QueryExpressionExpander.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/QueryExpressionExpander.cs	(revision 11807)
@@ -0,0 +1,430 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.PatternMatching;
+
+namespace ICSharpCode.NRefactory.CSharp {
+	public class QueryExpressionExpansionResult {
+		public AstNode AstNode { get; private set; }
+
+		/// <summary>
+		/// Maps original range variables to some node in the new tree that represents them.
+		/// </summary>
+		public IDictionary<Identifier, AstNode> RangeVariables { get; private set; }
+
+		/// <summary>
+		/// Maps clauses to method calls. The keys will always be either a <see cref="QueryClause"/> or a <see cref="QueryOrdering"/>
+		/// </summary>
+		public IDictionary<AstNode, Expression> Expressions { get; private set; }
+
+		public QueryExpressionExpansionResult(AstNode astNode, IDictionary<Identifier, AstNode> rangeVariables, IDictionary<AstNode, Expression> expressions) {
+			AstNode = astNode;
+			RangeVariables = rangeVariables;
+			Expressions = expressions;
+		}
+	}
+
+	public class QueryExpressionExpander {
+		class Visitor : DepthFirstAstVisitor<AstNode> {
+			internal IEnumerator<string> TransparentIdentifierNamePicker;
+
+			protected override AstNode VisitChildren(AstNode node) {
+				List<AstNode> newChildren = null;
+				
+				int i = 0;
+				foreach (var child in node.Children) {
+					var newChild = child.AcceptVisitor(this);
+					if (newChild != null) {
+						newChildren = newChildren ?? Enumerable.Repeat((AstNode)null, i).ToList();
+						newChildren.Add(newChild);
+					}
+					else if (newChildren != null) {
+						newChildren.Add(null);
+					}
+					i++;
+				}
+
+				if (newChildren == null)
+					return null;
+
+				var result = node.Clone();
+
+				i = 0;
+				foreach (var children in result.Children) {
+					if (newChildren[i] != null)
+						children.ReplaceWith(newChildren[i]);
+					i++;
+				}
+
+				return result;
+			}
+
+			Expression MakeNestedMemberAccess(Expression target, IEnumerable<string> members) {
+				return members.Aggregate(target, (current, m) => current.Member(m));
+			}
+
+			Expression VisitNested(Expression node, ParameterDeclaration transparentParameter) {
+				var oldRangeVariableSubstitutions = activeRangeVariableSubstitutions;
+				try {
+					if (transparentParameter != null && currentTransparentType.Count > 1) {
+						activeRangeVariableSubstitutions = new Dictionary<string, Expression>(activeRangeVariableSubstitutions);
+						foreach (var t in currentTransparentType)
+							activeRangeVariableSubstitutions[t.Item1.Name] = MakeNestedMemberAccess(new IdentifierExpression(transparentParameter.Name), t.Item2);
+					}
+					var result = node.AcceptVisitor(this);
+					return (Expression)(result ?? node.Clone());
+				}
+				finally {
+					activeRangeVariableSubstitutions = oldRangeVariableSubstitutions;
+				}
+			}
+
+			QueryClause GetNextQueryClause(QueryClause clause) {
+				for (AstNode node = clause.NextSibling; node != null; node = node.NextSibling) {
+					if (node.Role == QueryExpression.ClauseRole)
+						return (QueryClause)node;
+				}
+				return null;
+			}
+
+			public IDictionary<Identifier, AstNode> rangeVariables = new Dictionary<Identifier, AstNode>();
+			public IDictionary<AstNode, Expression> expressions = new Dictionary<AstNode, Expression>();
+
+			Dictionary<string, Expression> activeRangeVariableSubstitutions = new Dictionary<string, Expression>();
+			List<Tuple<Identifier, List<string>>> currentTransparentType = new List<Tuple<Identifier, List<string>>>();
+			Expression currentResult;
+			bool eatSelect;
+
+			void MapExpression(AstNode orig, Expression newExpr) {
+				Debug.Assert(orig is QueryClause || orig is QueryOrdering);
+				expressions[orig] = newExpr;
+			}
+
+			internal static IEnumerable<string> FallbackTransparentIdentifierNamePicker()
+			{
+				const string TransparentParameterNameTemplate = "x{0}";
+				int currentTransparentParameter = 0;
+				for (;;) {
+					yield return string.Format(CultureInfo.InvariantCulture, TransparentParameterNameTemplate, currentTransparentParameter++);
+				}
+			}
+
+			ParameterDeclaration CreateParameterForCurrentRangeVariable() {
+				var param = new ParameterDeclaration();
+
+				if (currentTransparentType.Count == 1) {
+					var clonedRangeVariable = (Identifier)currentTransparentType[0].Item1.Clone();
+					if (!rangeVariables.ContainsKey(currentTransparentType[0].Item1))
+						rangeVariables[currentTransparentType[0].Item1] = param;
+					param.AddChild(clonedRangeVariable, Roles.Identifier);
+				}
+				else {
+					if (!TransparentIdentifierNamePicker.MoveNext()) {
+						TransparentIdentifierNamePicker = FallbackTransparentIdentifierNamePicker().GetEnumerator();
+						TransparentIdentifierNamePicker.MoveNext();
+					}
+					string name = TransparentIdentifierNamePicker.Current;
+					param.AddChild(Identifier.Create(name), Roles.Identifier);
+				}
+				return param;
+			}
+
+			LambdaExpression CreateLambda(IList<ParameterDeclaration> parameters, Expression body) {
+				var result = new LambdaExpression();
+				if (parameters.Count > 1)
+					result.AddChild(new CSharpTokenNode(TextLocation.Empty, Roles.LPar), Roles.LPar);
+				result.AddChild(parameters[0], Roles.Parameter);
+				for (int i = 1; i < parameters.Count; i++) {
+					result.AddChild(new CSharpTokenNode(TextLocation.Empty, Roles.Comma), Roles.Comma);
+					result.AddChild(parameters[i], Roles.Parameter);
+				}
+				if (parameters.Count > 1)
+					result.AddChild(new CSharpTokenNode(TextLocation.Empty, Roles.RPar), Roles.RPar);
+				result.AddChild(body, LambdaExpression.BodyRole);
+
+				return result;
+			}
+
+			ParameterDeclaration CreateParameter(Identifier identifier) {
+				var result = new ParameterDeclaration();
+				result.AddChild(identifier, Roles.Identifier);
+				return result;
+			}
+
+			Expression AddMemberToCurrentTransparentType(ParameterDeclaration param, Identifier name, Expression value, bool namedExpression) {
+				Expression newAssignment = VisitNested(value, param);
+				if (namedExpression) {
+					newAssignment = new NamedExpression(name.Name, VisitNested(value, param));
+					if (!rangeVariables.ContainsKey(name) )
+						rangeVariables[name] = ((NamedExpression)newAssignment).NameToken;
+				}
+
+				foreach (var t in currentTransparentType)
+					t.Item2.Insert(0, param.Name);
+
+				currentTransparentType.Add(Tuple.Create(name, new List<string> { name.Name }));
+				return new AnonymousTypeCreateExpression(new[] { new IdentifierExpression(param.Name), newAssignment });
+			}
+
+			void AddFirstMemberToCurrentTransparentType(Identifier identifier) {
+				Debug.Assert(currentTransparentType.Count == 0);
+				currentTransparentType.Add(Tuple.Create(identifier, new List<string>()));
+			}
+
+			public override AstNode VisitQueryExpression(QueryExpression queryExpression) {
+				var oldTransparentType = currentTransparentType;
+				var oldResult = currentResult;
+				var oldEatSelect = eatSelect;
+				try {
+					currentTransparentType = new List<Tuple<Identifier, List<string>>>();
+					currentResult = null;
+					eatSelect = false;
+
+					foreach (var clause in queryExpression.Clauses) {
+						var result = (Expression)clause.AcceptVisitor(this);
+						MapExpression(clause, result ?? currentResult);
+						currentResult = result;
+					}
+
+					return currentResult; 
+				}
+				finally {
+					currentTransparentType = oldTransparentType;
+					currentResult = oldResult;
+					eatSelect = oldEatSelect;
+				}
+			}
+
+			public override AstNode VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause) {
+				var prev = VisitNested(queryContinuationClause.PrecedingQuery, null);
+				AddFirstMemberToCurrentTransparentType(queryContinuationClause.IdentifierToken);
+				return prev;
+			}
+
+			static bool NeedsToBeParenthesized(Expression expr)
+			{
+				UnaryOperatorExpression unary = expr as UnaryOperatorExpression;
+				if (unary != null) {
+					if (unary.Operator == UnaryOperatorType.PostIncrement || unary.Operator == UnaryOperatorType.PostDecrement) {
+						return false;
+					}
+					return true;
+				}
+			
+				if (expr is BinaryOperatorExpression || expr is ConditionalExpression || expr is AssignmentExpression) {
+					return true;
+				}
+
+				return false;
+			}
+
+			static Expression ParenthesizeIfNeeded(Expression expr)
+			{
+				return NeedsToBeParenthesized(expr) ? new ParenthesizedExpression(expr.Clone()) : expr;
+			}
+
+			public override AstNode VisitQueryFromClause(QueryFromClause queryFromClause) {
+				if (currentResult == null) {
+					AddFirstMemberToCurrentTransparentType(queryFromClause.IdentifierToken);
+					if (queryFromClause.Type.IsNull) {
+						return VisitNested(ParenthesizeIfNeeded(queryFromClause.Expression), null);
+					}
+					else {
+						return VisitNested(ParenthesizeIfNeeded(queryFromClause.Expression), null).Invoke("Cast", new[] { queryFromClause.Type.Clone() }, new Expression[0]);
+					}
+				}
+				else {
+					var innerSelectorParam = CreateParameterForCurrentRangeVariable();
+					var lambdaContent = VisitNested(queryFromClause.Expression, innerSelectorParam);
+					if (!queryFromClause.Type.IsNull) {
+						lambdaContent = lambdaContent.Invoke("Cast", new[] { queryFromClause.Type.Clone() }, new Expression[0]);
+					}
+					var innerSelector = CreateLambda(new[] { innerSelectorParam }, lambdaContent);
+
+					var clonedIdentifier = (Identifier)queryFromClause.IdentifierToken.Clone();
+
+					var resultParam = CreateParameterForCurrentRangeVariable();
+					Expression body;
+					// Second from clause - SelectMany
+					var select = GetNextQueryClause(queryFromClause) as QuerySelectClause;
+					if (select != null) {
+						body = VisitNested(select.Expression, resultParam);
+						eatSelect = true;
+					}
+					else {
+						body = AddMemberToCurrentTransparentType(resultParam, queryFromClause.IdentifierToken, new IdentifierExpression(queryFromClause.Identifier), false);
+					}
+
+					var resultSelectorParam2 = CreateParameter(clonedIdentifier);
+					var resultSelector = CreateLambda(new[] { resultParam, resultSelectorParam2 }, body);
+					rangeVariables[queryFromClause.IdentifierToken] = resultSelectorParam2;
+
+					return currentResult.Invoke("SelectMany", innerSelector, resultSelector);
+				}
+			}
+
+			public override AstNode VisitQueryLetClause(QueryLetClause queryLetClause) {
+				var param = CreateParameterForCurrentRangeVariable();
+				var body = AddMemberToCurrentTransparentType(param, queryLetClause.IdentifierToken, queryLetClause.Expression, true);
+				var lambda = CreateLambda(new[] { param }, body);
+
+				return currentResult.Invoke("Select", lambda);
+			}
+
+			public override AstNode VisitQueryWhereClause(QueryWhereClause queryWhereClause) {
+				var param = CreateParameterForCurrentRangeVariable();
+				return currentResult.Invoke("Where", CreateLambda(new[] { param }, VisitNested(queryWhereClause.Condition, param)));
+			}
+
+			public override AstNode VisitQueryJoinClause(QueryJoinClause queryJoinClause) {
+				Expression resultSelectorBody = null;
+				var inExpression = VisitNested(queryJoinClause.InExpression, null);
+				if (!queryJoinClause.Type.IsNull) {
+					inExpression = inExpression.Invoke("Cast", new[] { queryJoinClause.Type.Clone() }, EmptyList<Expression>.Instance);
+				}
+				var key1SelectorFirstParam = CreateParameterForCurrentRangeVariable();
+				var key1Selector = CreateLambda(new[] { key1SelectorFirstParam }, VisitNested(queryJoinClause.OnExpression, key1SelectorFirstParam));
+				var key2Param = CreateParameter(Identifier.Create(queryJoinClause.JoinIdentifier));
+				var key2Selector = CreateLambda(new[] { key2Param }, VisitNested(queryJoinClause.EqualsExpression, null));
+
+				var resultSelectorFirstParam = CreateParameterForCurrentRangeVariable();
+
+				var select = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
+				if (select != null) {
+					resultSelectorBody = VisitNested(select.Expression, resultSelectorFirstParam);
+					eatSelect = true;
+				}
+
+				if (queryJoinClause.IntoKeyword.IsNull) {
+					// Normal join
+					if (resultSelectorBody == null)
+						resultSelectorBody = AddMemberToCurrentTransparentType(resultSelectorFirstParam, queryJoinClause.JoinIdentifierToken, new IdentifierExpression(queryJoinClause.JoinIdentifier), false);
+
+					var resultSelector = CreateLambda(new[] { resultSelectorFirstParam, CreateParameter(Identifier.Create(queryJoinClause.JoinIdentifier)) }, resultSelectorBody);
+					rangeVariables[queryJoinClause.JoinIdentifierToken] = key2Param;
+					return currentResult.Invoke("Join", inExpression, key1Selector, key2Selector, resultSelector);
+				}
+				else {
+					// Group join
+					if (resultSelectorBody == null)
+						resultSelectorBody = AddMemberToCurrentTransparentType(resultSelectorFirstParam, queryJoinClause.IntoIdentifierToken, new IdentifierExpression(queryJoinClause.IntoIdentifier), false);
+
+					var intoParam = CreateParameter(Identifier.Create(queryJoinClause.IntoIdentifier));
+					var resultSelector = CreateLambda(new[] { resultSelectorFirstParam, intoParam }, resultSelectorBody);
+					rangeVariables[queryJoinClause.IntoIdentifierToken] = intoParam;
+
+					return currentResult.Invoke("GroupJoin", inExpression, key1Selector, key2Selector, resultSelector);
+				}
+			}
+
+			public override AstNode VisitQueryOrderClause(QueryOrderClause queryOrderClause) {
+				var current = currentResult;
+				bool first = true;
+				foreach (var o in queryOrderClause.Orderings) {
+					string methodName = first ? (o.Direction == QueryOrderingDirection.Descending ? "OrderByDescending" : "OrderBy")
+					                          : (o.Direction == QueryOrderingDirection.Descending ? "ThenByDescending" : "ThenBy");
+
+					var param = CreateParameterForCurrentRangeVariable();
+					current = current.Invoke(methodName, CreateLambda(new[] { param }, VisitNested(o.Expression, param)));
+					MapExpression(o, current);
+					first = false;
+				}
+				return current;
+			}
+
+			bool IsSingleRangeVariable(Expression expr) {
+				if (currentTransparentType.Count > 1)
+					return false;
+				var unpacked = ParenthesizedExpression.UnpackParenthesizedExpression(expr);
+				return unpacked is IdentifierExpression && ((IdentifierExpression)unpacked).Identifier == currentTransparentType[0].Item1.Name;
+			}
+
+			public override AstNode VisitQuerySelectClause(QuerySelectClause querySelectClause) {
+				if (eatSelect) {
+					eatSelect = false;
+					return currentResult;
+				}
+				else if (((QueryExpression)querySelectClause.Parent).Clauses.Count > 2 && IsSingleRangeVariable(querySelectClause.Expression)) {
+					// A simple query that ends with a trivial select should be removed.
+					return currentResult;
+				}
+
+				var param = CreateParameterForCurrentRangeVariable();
+				var lambda = CreateLambda(new[] { param }, VisitNested(querySelectClause.Expression, param));
+				return currentResult.Invoke("Select", lambda);
+			}
+
+			public override AstNode VisitQueryGroupClause(QueryGroupClause queryGroupClause) {
+				var param = CreateParameterForCurrentRangeVariable();
+				var keyLambda = CreateLambda(new[] { param }, VisitNested(queryGroupClause.Key, param));
+
+				if (IsSingleRangeVariable(queryGroupClause.Projection)) {
+					// We are grouping by the single active range variable, so we can use the single argument form of GroupBy
+					return currentResult.Invoke("GroupBy", keyLambda);
+				}
+				else {
+					var projectionParam = CreateParameterForCurrentRangeVariable();
+					var projectionLambda = CreateLambda(new[] { projectionParam }, VisitNested(queryGroupClause.Projection, projectionParam));
+					return currentResult.Invoke("GroupBy", keyLambda, projectionLambda);
+				}
+			}
+
+			public override AstNode VisitIdentifierExpression(IdentifierExpression identifierExpression) {
+				Expression subst;
+				activeRangeVariableSubstitutions.TryGetValue(identifierExpression.Identifier, out subst);
+				return subst != null ? subst.Clone() : null;
+			}
+		}
+
+		/// <summary>
+		/// Expands all occurances of query patterns in the specified node. Returns a clone of the node with all query patterns expanded, or null if there was no query pattern to expand.
+		/// </summary>
+		/// <param name="node"></param>
+		/// <param name="transparentIdentifierNamePicker">A sequence of names to use for transparent identifiers. Once the sequence is over, a fallback name generator is used</param> 
+		/// <returns></returns>
+		public QueryExpressionExpansionResult ExpandQueryExpressions(AstNode node, IEnumerable<string> transparentIdentifierNamePicker) {
+			var visitor = new Visitor();
+			visitor.TransparentIdentifierNamePicker = transparentIdentifierNamePicker.GetEnumerator();
+			var astNode = node.AcceptVisitor(visitor);
+			if (astNode != null) {
+				astNode.Freeze();
+				return new QueryExpressionExpansionResult(astNode, visitor.rangeVariables, visitor.expressions);
+			}
+			else {
+				return null;
+			}
+		}
+
+		
+		/// <summary>
+		/// Expands all occurances of query patterns in the specified node. Returns a clone of the node with all query patterns expanded, or null if there was no query pattern to expand.
+		/// </summary>
+		/// <param name="node"></param>
+		/// <returns></returns>
+		public QueryExpressionExpansionResult ExpandQueryExpressions(AstNode node)
+		{
+			return ExpandQueryExpressions(node, Enumerable.Empty<string>());
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/BaseRefactoringContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/BaseRefactoringContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/BaseRefactoringContext.cs	(revision 11807)
@@ -0,0 +1,319 @@
+﻿// 
+// BaseRefactoringContext.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin <http://xamarin.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Editor;
+using System.ComponentModel.Design;
+using ICSharpCode.NRefactory.CSharp.Analysis;
+using ICSharpCode.NRefactory.Utils;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Analysis;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	public abstract class BaseRefactoringContext : IServiceProvider
+	{
+		readonly CSharpAstResolver resolver;
+		readonly CancellationToken cancellationToken;
+		
+		public virtual bool Supports(Version version)
+		{
+			return true;
+		}
+
+		/// <summary>
+		/// Gets the default namespace which should be defined in this file.
+		/// </summary>
+		public abstract string DefaultNamespace {
+			get;
+		}
+
+		/// <summary>
+		/// Gets a value indicating if 'var' keyword should be used or explicit types.
+		/// </summary>
+		public virtual bool UseExplicitTypes {
+			get;
+			set;
+		}
+		
+		public CancellationToken CancellationToken {
+			get { return cancellationToken; }
+		}
+		
+		public virtual AstNode RootNode {
+			get {
+				return resolver.RootNode;
+			}
+		}
+
+		public CSharpAstResolver Resolver {
+			get {
+				return resolver;
+			}
+		}
+
+		public virtual CSharpUnresolvedFile UnresolvedFile {
+			get {
+				return resolver.UnresolvedFile;
+			}
+		}
+
+		public ICompilation Compilation {
+			get { return resolver.Compilation; }
+		}
+
+		/// <summary>
+		/// Gets the type graph for the current compilation.
+		/// </summary>
+		public virtual TypeGraph TypeGraph {
+			get { return new TypeGraph(Compilation.Assemblies); }
+		}
+		
+		public BaseRefactoringContext (ICSharpCode.NRefactory.CSharp.Resolver.CSharpAstResolver resolver, System.Threading.CancellationToken cancellationToken)
+		{
+			this.resolver = resolver;
+			this.cancellationToken = cancellationToken;
+			this.referenceFinder = new LocalReferenceFinder(resolver);
+		}
+
+
+		#region Resolving
+		public ResolveResult Resolve (AstNode node)
+		{
+			return resolver.Resolve (node, cancellationToken);
+		}
+		
+		public CSharpResolver GetResolverStateBefore(AstNode node)
+		{
+			return resolver.GetResolverStateBefore (node, cancellationToken);
+		}
+		
+		public CSharpResolver GetResolverStateAfter(AstNode node)
+		{
+			return resolver.GetResolverStateAfter (node, cancellationToken);
+		}
+
+		public IType ResolveType (AstType type)
+		{
+			return resolver.Resolve (type, cancellationToken).Type;
+		}
+		
+		public IType GetExpectedType (Expression expression)
+		{
+			return resolver.GetExpectedType(expression, cancellationToken);
+		}
+		
+		public Conversion GetConversion (Expression expression)
+		{
+			return resolver.GetConversion(expression, cancellationToken);
+		}
+		
+		public TypeSystemAstBuilder CreateTypeSystemAstBuilder(AstNode node)
+		{
+			var csResolver = resolver.GetResolverStateBefore(node);
+			return new TypeSystemAstBuilder(csResolver);
+		}
+		#endregion
+
+		#region Code Analyzation
+		/// <summary>
+		/// Creates a new definite assignment analysis object with a given root statement.
+		/// </summary>
+		/// <returns>
+		/// The definite assignment analysis object.
+		/// </returns>
+		/// <param name='root'>
+		/// The root statement.
+		/// </param>
+		public DefiniteAssignmentAnalysis CreateDefiniteAssignmentAnalysis (Statement root)
+		{
+			return new DefiniteAssignmentAnalysis (root, resolver, CancellationToken);
+		}
+
+		/// <summary>
+		/// Creates a new reachability analysis object with a given statement.
+		/// </summary>
+		/// <param name="statement">
+		/// The statement to start the analysis.
+		/// </param>
+		/// <param name="recursiveDetectorVisitor">
+		/// TODO.
+		/// </param>
+		/// <returns>
+		/// The reachability analysis object.
+		/// </returns>
+		public ReachabilityAnalysis CreateReachabilityAnalysis (Statement statement, ReachabilityAnalysis.RecursiveDetectorVisitor recursiveDetectorVisitor = null)
+		{
+			return ReachabilityAnalysis.Create (statement, resolver, recursiveDetectorVisitor, CancellationToken);
+		}
+
+		/// <summary>
+		/// Parses a composite format string.
+		/// </summary>
+		/// <returns>
+		/// The format string parsing result.
+		/// </returns>
+		public virtual FormatStringParseResult ParseFormatString(string source)
+		{
+			return new CompositeFormatStringParser().Parse(source);
+		}
+
+		LocalReferenceFinder referenceFinder;
+
+		public IList<ReferenceResult> FindReferences(AstNode rootNode, IVariable variable)
+		{
+			return referenceFinder.FindReferences(rootNode, variable);
+		}
+
+		#endregion
+
+
+		#region Naming
+		public virtual string GetNameProposal (string name, TextLocation loc, bool camelCase = true)
+		{
+			string baseName = (camelCase ? char.ToLower (name [0]) : char.ToUpper (name [0])) + name.Substring (1);
+
+			var type = RootNode.GetNodeAt<TypeDeclaration>(loc);
+			if (type == null)
+				return baseName;
+
+			int number = -1;
+			string proposedName;
+			do {
+				proposedName = AppendNumberToName (baseName, number++);
+			} while (type.Members.Select (m => m.GetChildByRole (Roles.Identifier)).Any (n => n.Name == proposedName));
+			return proposedName;
+		}
+		
+		public virtual string GetLocalNameProposal (string name, TextLocation loc, bool camelCase = true)
+		{
+			string baseName = (camelCase ? char.ToLower (name [0]) : char.ToUpper (name [0])) + name.Substring (1);
+			var node = RootNode.GetNodeAt(loc);
+			if (node == null)
+				return baseName;
+			
+			var context = GetResolverStateBefore (node);
+			int number = -1;
+			string proposedName;
+			do {
+				proposedName = AppendNumberToName (baseName, number++);
+			} while (!(context.ResolveSimpleName (proposedName, EmptyList<IType>.Instance) is UnknownIdentifierResolveResult));
+			return proposedName;
+		}
+
+		static string AppendNumberToName (string baseName, int number)
+		{
+			return baseName + (number > 0 ? (number + 1).ToString () : "");
+		}
+		#endregion
+
+		#region Text stuff
+		public virtual TextEditorOptions TextEditorOptions {
+			get {
+				return TextEditorOptions.Default;
+			}
+		}
+
+		public virtual bool IsSomethingSelected {
+			get {
+				return SelectionStart != TextLocation.Empty;
+			}
+		}
+
+		public virtual string SelectedText {
+			get { return string.Empty; }
+		}
+
+		public virtual TextLocation SelectionStart {
+			get {
+				return TextLocation.Empty;
+			}
+		}
+
+		public virtual TextLocation SelectionEnd {
+			get {
+				return TextLocation.Empty;
+			}
+		}
+
+		public abstract int GetOffset (TextLocation location);
+
+		public abstract IDocumentLine GetLineByOffset (int offset);
+
+		public int GetOffset (int line, int col)
+		{
+			return GetOffset (new TextLocation (line, col));
+		}
+
+		public abstract TextLocation GetLocation (int offset);
+
+		public abstract string GetText (int offset, int length);
+
+		public abstract string GetText (ISegment segment);
+		#endregion
+
+
+		/// <summary>
+		/// Translates the english input string to the context language.
+		/// </summary>
+		/// <returns>
+		/// The translated string.
+		/// </returns>
+		public virtual string TranslateString(string str)
+		{
+			return str;
+		}
+
+		#region IServiceProvider implementation
+		IServiceContainer services = new ServiceContainer();
+		
+		/// <summary>
+		/// Gets a service container used to associate services with this context.
+		/// </summary>
+		public IServiceContainer Services {
+			get { return services; }
+			protected set { services = value; }
+		}
+		
+		/// <summary>
+		/// Retrieves a service from the refactoring context.
+		/// If the service is not found in the <see cref="Services"/> container.
+		/// </summary>
+		public object GetService(Type serviceType)
+		{
+			return services.GetService(serviceType);
+		}
+		#endregion
+	}
+	
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeAction.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeAction.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeAction.cs	(revision 11807)
@@ -0,0 +1,197 @@
+// 
+// CodeAction.cs
+//  
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Refactoring;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// A code action provides a code transformation with a description.
+	/// </summary>
+	public class CodeAction
+	{
+		/// <summary>
+		/// Gets the description.
+		/// </summary>
+		public string Description {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// Gets the code transformation.
+		/// </summary>
+		public Action<Script> Run {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// Gets the action start location.
+		/// </summary>
+		public TextLocation Start {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// Gets the action end location.
+		/// </summary>
+		public TextLocation End {
+			get;
+			private set;
+		}
+		
+		/// <summary>
+		/// This property is used to identify which actions are "siblings", ie which actions
+		/// are the same kind of fix. This is used to group issues when batch fixing them.
+		/// </summary>
+		/// <remarks>
+		/// Although the type is <see cref="object"/>, there is a restriction: The instance
+		/// used must behave well as a key (for instance in a hash table). Additionaly, this
+		/// value must be independent of the specific <see cref="CodeIssueProvider"/> instance
+		/// which created it. In other words two different instances of the same issue provider
+		/// implementation should use the same sibling keys for the same kinds of issues.
+		/// </remarks>
+		/// <value>The non-null sibling key if this type of action is batchable, null otherwise.</value>
+		public object SiblingKey {
+			get;
+			private set;
+		}
+
+		Severity severity = Severity.Suggestion;
+
+		/// <summary>
+		/// Gets or sets the severity of the code action. 
+		/// Actions are sorted according to their Severity.
+		/// </summary>
+		/// <value>The severity.</value>
+		public Severity Severity {
+			get {
+				return severity;
+			}
+			set {
+				severity = value;
+			}
+		}
+
+		const string defaultSiblingKey = "default";
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction"/> class,
+		/// using a non-null default value for <see cref="SiblingKey"/>.
+		/// </summary>
+		/// <param name='description'>
+		/// The description.
+		/// </param>
+		/// <param name='action'>
+		/// The code transformation.
+		/// </param>
+		/// <param name='astNode'>
+		/// A node that specifies the start/end positions for the code action.
+		/// </param>
+		public CodeAction (string description, Action<Script> action, AstNode astNode)
+			: this (description, action, astNode, defaultSiblingKey)
+		{
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction"/> class.
+		/// </summary>
+		/// <param name='description'>
+		/// The description.
+		/// </param>
+		/// <param name='action'>
+		/// The code transformation.
+		/// </param>
+		/// <param name='astNode'>
+		/// A node that specifies the start/end positions for the code action.
+		/// </param>
+		/// <param name="siblingKey>
+		/// The key used to associate this action with other actions that should be fixed together in batch mode.
+		/// </param>
+		public CodeAction (string description, Action<Script> action, AstNode astNode, object siblingKey)
+		{
+			if (action == null)
+				throw new ArgumentNullException ("action");
+			if (description == null)
+				throw new ArgumentNullException ("description");
+			if (astNode == null)
+				throw new ArgumentNullException("astNode");
+			Description = description;
+			Run = action;
+			Start = astNode.StartLocation;
+			End = astNode.EndLocation;
+			SiblingKey = siblingKey;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction"/> class,
+		/// using a non-null default value for <see cref="SiblingKey"/>.
+		/// </summary>
+		/// <param name='description'>
+		/// The description.
+		/// </param>
+		/// <param name='action'>
+		/// The code transformation.
+		/// </param>
+		/// <param name='start'>Start position for the code action.</param>
+		/// <param name='end'>End position for the code action.</param>
+		public CodeAction (string description, Action<Script> action, TextLocation start, TextLocation end)
+			: this (description, action, start, end, defaultSiblingKey)
+		{
+			SiblingKey = defaultSiblingKey;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction"/> class.
+		/// </summary>
+		/// <param name='description'>
+		/// The description.
+		/// </param>
+		/// <param name='action'>
+		/// The code transformation.
+		/// </param>
+		/// <param name='start'>Start position for the code action.</param>
+		/// <param name='end'>End position for the code action.</param>
+		/// <param name="siblingKey>
+		/// The key used to associate this action with other actions that should be fixed together in batch mode.
+		/// </param>
+		public CodeAction (string description, Action<Script> action, TextLocation start, TextLocation end, object siblingKey)
+		{
+			if (action == null)
+				throw new ArgumentNullException ("action");
+			if (description == null)
+				throw new ArgumentNullException ("description");
+			Description = description;
+			Run = action;
+			this.Start = start;
+			this.End = end;
+			SiblingKey = siblingKey;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeActionProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeActionProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeActionProvider.cs	(revision 11807)
@@ -0,0 +1,37 @@
+﻿// 
+// ContextAction.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Threading;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	public abstract class CodeActionProvider
+	{
+		public abstract IEnumerable<CodeAction> GetActions (RefactoringContext context);
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeActions/RemoveFieldRefactoryActionRefactoringAction.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeActions/RemoveFieldRefactoryActionRefactoringAction.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeActions/RemoveFieldRefactoryActionRefactoringAction.cs	(revision 11807)
@@ -0,0 +1,110 @@
+//
+// RemoveField.cs
+//
+// Author:
+//       Ciprian Khlud <ciprian.mustiata@yahoo.com>
+//
+// Copyright (c) 2013 Ciprian Khlud
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+//	[ContextAction("Removes a field from a class", Description = "It removes also the empty assingments and the usages")]
+	public class RemoveFieldRefactoryAction : ICodeActionProvider
+	{
+		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
+		{
+			var fieldDeclaration = GetFieldDeclaration(context);
+            if(fieldDeclaration==null)
+			    yield break;
+
+			
+			yield return new CodeAction(string.Format(context.TranslateString("Remove field '{0}'"), fieldDeclaration.Name)
+			                            , script => GenerateNewScript(
+                script, fieldDeclaration, context), fieldDeclaration);
+		}
+		
+		
+		void GenerateNewScript(Script script, FieldDeclaration fieldDeclaration, RefactoringContext context)
+        {
+            var firstOrNullObject = fieldDeclaration.Variables.FirstOrNullObject();
+		    if(firstOrNullObject==null)
+                return;
+			var matchedNodes = ComputeMatchNodes(context, firstOrNullObject);
+
+		    foreach (var matchNode in matchedNodes)
+            {
+                var parent = matchNode.Parent;
+                if (matchNode is VariableInitializer)
+                {
+                    script.Remove(parent);
+                }
+                else
+                if (matchNode is IdentifierExpression)
+                {
+                    if(parent is AssignmentExpression)
+                    {
+                        script.Remove(parent.Parent);
+                    }
+                    else
+                    {
+                        var clone = (IdentifierExpression)matchNode.Clone();
+                        clone.Identifier = "TODO";
+                        script.Replace(matchNode, clone);
+                    }
+                }
+            }
+        }
+
+	    private static List<AstNode> ComputeMatchNodes(RefactoringContext context, VariableInitializer firstOrNullObject)
+	    {
+	        var referenceFinder = new FindReferences();
+	        var matchedNodes = new List<AstNode>();
+
+	        var resolveResult = context.Resolver.Resolve(firstOrNullObject);
+	        var member = resolveResult as MemberResolveResult;
+            if (member == null)//not a member is unexpected case, so is better to return no match than to break the code
+                return matchedNodes;
+
+	        FoundReferenceCallback callback = (matchNode, result) => matchedNodes.Add(matchNode);
+
+	        var searchScopes = referenceFinder.GetSearchScopes(member.Member);
+	        referenceFinder.FindReferencesInFile(searchScopes,
+	                                             context.UnresolvedFile,
+	                                             context.RootNode as SyntaxTree,
+	                                             context.Compilation, callback,
+	                                             context.CancellationToken);
+	        return matchedNodes;
+	    }
+
+	    FieldDeclaration GetFieldDeclaration(RefactoringContext context)
+		{
+			var result = context.GetNode<FieldDeclaration>();
+
+			return result;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeGenerationService.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeGenerationService.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeGenerationService.cs	(revision 11807)
@@ -0,0 +1,64 @@
+//
+// CodeGenerationService.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public abstract class CodeGenerationService
+	{
+		public abstract EntityDeclaration GenerateMemberImplementation(RefactoringContext context, IMember member, bool explicitImplementation);
+	}
+
+	public class DefaultCodeGenerationService : CodeGenerationService
+	{
+		public override EntityDeclaration GenerateMemberImplementation(RefactoringContext context, IMember member, bool explicitImplementation)
+		{
+			var builder = context.CreateTypeSystemAstBuilder();
+			builder.GenerateBody = true;
+			builder.ShowModifiers = false;
+			builder.ShowAccessibility = true;
+			builder.ShowConstantValues = !explicitImplementation;
+			builder.ShowTypeParameterConstraints = !explicitImplementation;
+			builder.UseCustomEvents = explicitImplementation;
+			var decl = builder.ConvertEntity(member);
+			if (explicitImplementation) {
+				decl.Modifiers = Modifiers.None;
+				decl.AddChild(builder.ConvertType(member.DeclaringType), EntityDeclaration.PrivateImplementationTypeRole);
+			} else if (member.DeclaringType.Kind == TypeKind.Interface) {
+				decl.Modifiers |= Modifiers.Public;
+			} else {
+				// Remove 'internal' modifier from 'protected internal' members if the override is in a different assembly than the member
+				if (!member.ParentAssembly.InternalsVisibleTo(context.Compilation.MainAssembly)) {
+					decl.Modifiers &= ~Modifiers.Internal;
+				}
+			}
+			return decl;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeIssue.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeIssue.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeIssue.cs	(revision 11807)
@@ -0,0 +1,181 @@
+﻿// 
+// InspectionIssue.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin <http://xamarin.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Refactoring;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// A code issue marks a region of text with an issue and can provide solution actions for this issue.
+	/// </summary>
+	public class CodeIssue
+	{
+		/// <summary>
+		/// Gets the description of the issue.
+		/// </summary>
+		public string Description {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// Gets the issue start location.
+		/// </summary>
+		public TextLocation Start {
+			get;
+			private set;
+		}
+		
+		/// <summary>
+		/// Gets the issue end location.
+		/// </summary>
+		public TextLocation End {
+			get;
+			private set;
+		}
+
+		/// <summary>
+		/// Gets a list of potential solutions for the issue.
+		/// </summary>
+		public IList<CodeAction> Actions {
+			get;
+			private set;
+		}
+
+		List<Type> actionProvider = new List<Type>();
+		public List<Type> ActionProvider {
+			get {
+				return actionProvider;
+			}
+			set {
+				actionProvider = value;
+			}
+		}
+
+		/// <summary>
+		/// Gets or sets the Issue marker which should be used to mark this issue in the editor.
+		/// It's up to the editor implementation if and how this info is used.
+		/// </summary>
+		public IssueMarker IssueMarker {
+			get;
+			set;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(TextLocation start, TextLocation end, string issueDescription)
+		{
+			if (issueDescription == null)
+				throw new ArgumentNullException("issueDescription");
+			Description = issueDescription;
+			Start = start;
+			End = end;
+			Actions = EmptyList<CodeAction>.Instance;
+			IssueMarker = IssueMarker.WavedLine;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(TextLocation start, TextLocation end, string issueDescription, IEnumerable<CodeAction> actions) : this(start, end, issueDescription)
+		{
+			if (actions != null)
+				Actions = actions.ToArray();
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(TextLocation start, TextLocation end, string issueDescription, params CodeAction[] actions) : this(start, end, issueDescription)
+		{
+			if (actions != null)
+				Actions = actions;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(TextLocation start, TextLocation end, string issueDescription, string actionDescription, Action<Script> fix) : this(start, end, issueDescription)
+		{
+			if (actionDescription == null)
+				throw new ArgumentNullException("actionDescription");
+			if (fix == null)
+				throw new ArgumentNullException("fix");
+			this.Actions = new [] { new CodeAction(actionDescription, fix, start, end) };
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(AstNode node, string issueDescription)
+		{
+			if (node == null)
+				throw new ArgumentNullException("node");
+			if (issueDescription == null)
+				throw new ArgumentNullException("issueDescription");
+			Description = issueDescription;
+			Start = node.StartLocation;
+			End = node.EndLocation;
+			Actions = EmptyList<CodeAction>.Instance;
+			IssueMarker = IssueMarker.WavedLine;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(AstNode node, string issueDescription, IEnumerable<CodeAction> actions) : this(node, issueDescription)
+		{
+			if (actions != null)
+				Actions = actions.ToArray();
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(AstNode node, string issueDescription, params CodeAction[] actions) : this(node, issueDescription)
+		{
+			if (actions != null)
+				Actions = actions;
+		}
+
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue"/> class.
+		/// </summary>
+		public CodeIssue(AstNode node, string issueDescription, string actionDescription, Action<Script> fix) : this(node, issueDescription)
+		{
+			if (actionDescription == null)
+				throw new ArgumentNullException("actionDescription");
+			if (fix == null)
+				throw new ArgumentNullException("fix");
+			this.Actions = new [] { new CodeAction(actionDescription, fix, node) };
+		}
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeIssueProvider.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeIssueProvider.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CodeIssueProvider.cs	(revision 11807)
@@ -0,0 +1,76 @@
+﻿// 
+// IInspector.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin <http://xamarin.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// The code issue provider gets a list of all code issues in a syntax tree.
+	/// </summary>
+	public abstract class CodeIssueProvider
+	{
+		SubIssueAttribute[] subIssueAttributes;
+
+		public bool HasSubIssues {
+			get {
+				Initialize ();
+				return subIssueAttributes.Length > 0;
+			}
+		}
+
+		public IEnumerable<SubIssueAttribute> SubIssues {
+			get {
+				Initialize ();
+				return subIssueAttributes;
+			}
+		}
+
+		static readonly SubIssueAttribute[] emptyAttributes = new SubIssueAttribute[0];
+		void Initialize()
+		{
+			if (subIssueAttributes != null)
+				return;
+			subIssueAttributes = GetType().GetCustomAttributes(typeof(SubIssueAttribute), false).OfType<SubIssueAttribute>().ToArray() ?? emptyAttributes;
+		}
+
+		/// <summary>
+		/// Gets all code issues inside a syntax tree.
+		/// </summary>
+		/// <param name='context'>
+		/// The refactoring context of the issues to get.
+		/// </param>
+		/// <param name='subIssue'>
+		/// The name of the sub issue to run.
+		/// </param>
+		public virtual IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context, string subIssue = null)
+		{
+			return GetIssues(context);
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CommonSubIssues.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CommonSubIssues.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/CommonSubIssues.cs	(revision 11807)
@@ -0,0 +1,37 @@
+//
+// ConvertToStaticMethodIssue.cs
+//
+// Author:
+//       Ciprian Khlud <ciprian.mustiata@yahoo.com>
+//
+// Copyright (c) 2013 Ciprian Khlud
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	public class CommonSubIssues
+	{
+		public const string PrivateMember    = "Private accessibility";
+		public const string NonPrivateMember = "Non-private accessibility";
+
+	}
+
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/ContextActionAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/ContextActionAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/ContextActionAttribute.cs	(revision 11807)
@@ -0,0 +1,43 @@
+﻿// 
+// ProviderDescriptionAttribute.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public class ContextActionAttribute : System.Attribute
+	{
+		public string Title { get; private set;}
+		public string Description { get; set; }
+		public string Category { get; set; }
+
+		public ContextActionAttribute (string title)
+		{
+			Title = title;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/DocumentScript.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/DocumentScript.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/DocumentScript.cs	(revision 11807)
@@ -0,0 +1,179 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Diagnostics;
+using ICSharpCode.NRefactory.Editor;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// Script implementation based on IDocument.
+	/// </summary>
+	public class DocumentScript : Script
+	{
+		readonly IDocument currentDocument;
+		
+		public IDocument CurrentDocument {
+			get { return currentDocument; }
+		}
+		readonly IDocument originalDocument;
+		
+		public IDocument OriginalDocument {
+			get { return originalDocument; }
+		}
+		readonly IDisposable undoGroup;
+		
+		
+		public DocumentScript(IDocument document, CSharpFormattingOptions formattingOptions, TextEditorOptions options) : base(formattingOptions, options)
+		{
+			this.originalDocument = document.CreateDocumentSnapshot();
+			this.currentDocument = document;
+			Debug.Assert(currentDocument.Version.CompareAge(originalDocument.Version) == 0);
+			this.undoGroup = document.OpenUndoGroup();
+		}
+		
+		public override void Dispose()
+		{
+			// Since base.Dispose() reformats some nodes; we need to include it in the undo group
+			base.Dispose();
+			if (undoGroup != null)
+				undoGroup.Dispose();
+		}
+		
+		public override void Remove(AstNode node, bool removeEmptyLine = true)
+		{
+			var segment = GetSegment (node);
+			int startOffset = segment.Offset;
+			int endOffset = segment.EndOffset;
+			var startLine = currentDocument.GetLineByOffset (startOffset);
+			var endLine = currentDocument.GetLineByOffset (endOffset);
+			
+			if (startLine != null && endLine != null) {
+				bool removeStart = string.IsNullOrWhiteSpace (currentDocument.GetText (startLine.Offset, startOffset - startLine.Offset));
+				if (removeStart)
+					startOffset = startLine.Offset;
+				bool removeEnd = string.IsNullOrWhiteSpace (currentDocument.GetText (endOffset, endLine.EndOffset - endOffset));
+				if (removeEnd)
+					endOffset = endLine.EndOffset;
+				
+				// Remove delimiter if the whole line get's removed.
+				if (removeStart && removeEnd)
+					endOffset += endLine.DelimiterLength;
+			}
+			
+			Replace (startOffset, endOffset - startOffset, string.Empty);
+		}
+		
+		public override void Replace(int offset, int length, string newText)
+		{
+			currentDocument.Replace(offset, length, newText);
+		}
+		
+		public override int GetCurrentOffset(TextLocation originalDocumentLocation)
+		{
+			int offset = originalDocument.GetOffset(originalDocumentLocation);
+			return GetCurrentOffset(offset);
+		}
+		
+		public override int GetCurrentOffset(int originalDocumentOffset)
+		{
+			return originalDocument.Version.MoveOffsetTo(currentDocument.Version, originalDocumentOffset);
+		}
+		
+		public override void FormatText(IEnumerable<AstNode> nodes)
+		{
+			var syntaxTree = SyntaxTree.Parse(currentDocument, "dummy.cs");
+			var formatter = new CSharpFormatter(FormattingOptions, Options);
+			var segments = new List<ISegment>();
+			foreach (var node in nodes.OrderByDescending (n => n.StartLocation)) {
+				var segment = GetSegment(node);
+				
+				formatter.AddFormattingRegion (new ICSharpCode.NRefactory.TypeSystem.DomRegion (
+					currentDocument.GetLocation (segment.Offset), 
+					currentDocument.GetLocation (segment.EndOffset)
+					));
+				segments.Add(segment);
+			}
+			if (segments.Count == 0)
+				return;
+			var changes = formatter.AnalyzeFormatting (currentDocument, syntaxTree);
+			foreach (var segment in segments) {
+				changes.ApplyChanges(segment.Offset, segment.Length - 1);
+			}
+		}
+		
+		protected override int GetIndentLevelAt(int offset)
+		{
+			var line = currentDocument.GetLineByOffset(offset);
+			int spaces = 0;
+			int indentationLevel = 0;
+			for (int i = line.Offset; i < currentDocument.TextLength; i++) {
+				char c = currentDocument.GetCharAt(i);
+				if (c == '\t') {
+					spaces = 0;
+					indentationLevel++;
+				} else if (c == ' ') {
+					spaces++;
+					if (spaces == 4) {
+						spaces = 0;
+						indentationLevel++;
+					}
+				} else {
+					break;
+				}
+			}
+			return indentationLevel;
+		}
+		
+		protected override ISegment CreateTrackedSegment(int offset, int length)
+		{
+			return new TrackedSegment(this, offset, offset + length);
+		}
+		
+		sealed class TrackedSegment : ISegment
+		{
+			readonly DocumentScript script;
+			readonly ITextSourceVersion originalVersion;
+			readonly int originalStart;
+			readonly int originalEnd;
+			
+			public TrackedSegment(DocumentScript script, int originalStart, int originalEnd)
+			{
+				this.script = script;
+				this.originalVersion = script.currentDocument.Version;
+				this.originalStart = originalStart;
+				this.originalEnd = originalEnd;
+			}
+			
+			public int Offset {
+				get { return originalVersion.MoveOffsetTo(script.currentDocument.Version, originalStart); }
+			}
+			
+			public int Length {
+				get { return this.EndOffset - this.Offset; }
+			}
+			
+			public int EndOffset {
+				get { return originalVersion.MoveOffsetTo(script.currentDocument.Version, originalEnd); }
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/FormatStringHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/FormatStringHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/FormatStringHelper.cs	(revision 11807)
@@ -0,0 +1,86 @@
+//
+// FormatStringHelper.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	static class FormatStringHelper
+	{
+		static readonly string[] parameterNames = { "format", "frmt", "fmt" };
+		
+		public static bool TryGetFormattingParameters(CSharpInvocationResolveResult invocationResolveResult, InvocationExpression invocationExpression,
+		                                     		  out Expression formatArgument, out IList<Expression> arguments,
+		                                              Func<IParameter, Expression, bool> argumentFilter)
+		{
+			if (argumentFilter == null)
+				argumentFilter = (p, e) => true;
+
+			formatArgument = null;
+			arguments = new List<Expression>();
+
+			// Serach for method of type: void Name(string format, params object[] args);
+			if (invocationResolveResult.Member.SymbolKind == SymbolKind.Method) {
+				var methods = invocationResolveResult.Member.DeclaringType.GetMethods(m => m.Name == invocationResolveResult.Member.Name).ToList();
+				if (!methods.Any(m => m.Parameters.Count == 2 && 
+					m.Parameters[0].Type.IsKnownType(KnownTypeCode.String) && parameterNames.Contains(m.Parameters[0].Name) && 
+					m.Parameters[1].IsParams))
+					return false;
+			}
+
+			var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap();
+			var resolvedParameters = invocationResolveResult.Member.Parameters;
+			var allArguments = invocationExpression.Arguments.ToArray();
+			for (int i = 0; i < allArguments.Length; i++) {
+				var parameterIndex = argumentToParameterMap[i];
+				if (parameterIndex < 0 || parameterIndex >= resolvedParameters.Count) {
+					// No valid mapping for this argument, skip it
+					continue;
+				}
+				var parameter = resolvedParameters[parameterIndex];
+				var argument = allArguments[i];
+				if (i == 0 && parameter.Type.IsKnownType(KnownTypeCode.String) && parameterNames.Contains(parameter.Name)) {
+					formatArgument = argument;
+				} else if (formatArgument != null && parameter.IsParams && !invocationResolveResult.IsExpandedForm) {
+					var ace = argument as ArrayCreateExpression;
+					if (ace == null || ace.Initializer.IsNull)
+						return false;
+					foreach (var element in ace.Initializer.Elements) {
+						if (argumentFilter(parameter, element))
+							arguments.Add(argument);
+					}
+				} else if (formatArgument != null && argumentFilter(parameter, argument)) {
+					arguments.Add(argument);
+				}
+			}
+			return formatArgument != null;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/IssueAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/IssueAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/IssueAttribute.cs	(revision 11807)
@@ -0,0 +1,91 @@
+﻿// 
+// IssueAttribute.cs
+//  
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Refactoring;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public class IssueDescriptionAttribute : System.Attribute
+	{
+		public string Title { get; private set;}
+		public string Description { get; set; }
+		public string Category { get; set; }
+
+		public string AnalysisDisableKeyword { get; set; }
+		public string SuppressMessageCategory { get; set; }
+		public string SuppressMessageCheckId { get; set; }
+		public int PragmaWarning { get; set; }
+		public bool IsEnabledByDefault { get; set; }
+		public bool SupportsAutoFix { get; set; }
+
+		public Severity Severity { get; set; }
+
+		public IssueDescriptionAttribute (string title)
+		{
+			Title = title;
+			Severity = Severity.Suggestion;
+			IsEnabledByDefault = true;
+		}
+	}
+
+	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
+	public class SubIssueAttribute : System.Attribute
+	{
+		public string Title { get; private set;}
+		public string Description { get; set; }
+
+		public bool? IsEnabledByDefault { get; set; }
+		public Severity? Severity { get; set; }
+
+		public SubIssueAttribute (string title)
+		{
+			Title = title;
+		}
+
+		public SubIssueAttribute (string title, Severity severity)
+		{
+			Title = title;
+			this.Severity = severity;
+		}
+
+		public SubIssueAttribute (string title, bool isEnabledByDefault)
+		{
+			Title = title;
+			this.IsEnabledByDefault = isEnabledByDefault;
+		}
+
+		public SubIssueAttribute (string title, Severity severity, bool isEnabledByDefault)
+		{
+			Title = title;
+			this.Severity = severity;
+			this.IsEnabledByDefault = isEnabledByDefault;
+		}
+
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/LambdaHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/LambdaHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/LambdaHelper.cs	(revision 11807)
@@ -0,0 +1,51 @@
+﻿// 
+// LambdaHelper.cs
+// 
+// Author:
+//      Mansheng Yang <lightyang0@gmail.com>
+// 
+// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	public class LambdaHelper
+	{
+		public static IType GetLambdaReturnType(RefactoringContext context, LambdaExpression lambda)
+		{
+			LambdaResolveResult rr = context.Resolve(lambda) as LambdaResolveResult;
+			if (rr == null)
+				return SpecialType.UnknownType;
+			if (rr.IsAsync) {
+				// Unpack Task<T>
+				if (rr.ReturnType.IsKnownType(KnownTypeCode.Task))
+					return context.Compilation.FindType(KnownTypeCode.Void);
+				else if (rr.ReturnType.IsKnownType(KnownTypeCode.TaskOfT) && rr.ReturnType.IsParameterized)
+					return rr.ReturnType.TypeArguments[0];
+			}
+			return rr.ReturnType;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/LocalReferenceFinder.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/LocalReferenceFinder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/LocalReferenceFinder.cs	(revision 11807)
@@ -0,0 +1,159 @@
+//
+// LocalReferenceFinder.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+using System.Diagnostics;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+
+	/// <summary>
+	/// Finds references to <see cref="IVariable">IVariables</see>.
+	/// </summary>
+	/// <remarks>
+	/// This class is more efficient than <see cref="FindReferences"/>
+	/// if there is already a resolved tree or if multiple searches needs
+	/// to be performed.
+	/// </remarks>		
+	public class LocalReferenceFinder
+	{
+		LocalReferenceLocator locator;
+
+		MultiDictionary<IVariable, ReferenceResult> references = new MultiDictionary<IVariable, ReferenceResult>();
+		
+		HashSet<AstNode> visitedRoots = new HashSet<AstNode>();
+		
+		public LocalReferenceFinder(CSharpAstResolver resolver)
+		{
+			locator = new LocalReferenceLocator(resolver, this);
+		}
+
+		public LocalReferenceFinder(BaseRefactoringContext context) : this(context.Resolver)
+		{
+		}
+
+		void VisitIfNeccessary(AstNode rootNode)
+		{
+			// If any of the parent nodes are recorded as visited,
+			// we don't need to traverse rootNode this time.
+			var tmpRoot = rootNode;
+			while(tmpRoot != null){
+				if (visitedRoots.Contains(tmpRoot))
+					return;
+				tmpRoot = tmpRoot.Parent;
+			}
+
+			locator.ProccessRoot (rootNode);
+		}
+
+		/// <summary>
+		/// Finds the references to <paramref name="variable"/>.
+		/// </summary>
+		/// <param name='rootNode'>
+		/// Root node for the search.
+		/// </param>
+		/// <param name='variable'>
+		/// The variable to find references for.
+		/// </param>
+		/// <remarks>
+		/// When a single <see cref="LocalReferenceFinder"/> is reused for multiple
+		/// searches, which references outside of <paramref name="rootNode"/> are
+		/// or are not reported is undefined.
+		/// </remarks>
+		public IList<ReferenceResult> FindReferences(AstNode rootNode, IVariable variable)
+		{
+			lock (locator) {
+				VisitIfNeccessary(rootNode);
+				var lookup = (ILookup<IVariable, ReferenceResult>)references;
+				if (!lookup.Contains(variable))
+					return new List<ReferenceResult>();
+				// Clone the list for thread safety
+				return references[variable].ToList();
+			}
+		}
+
+		class LocalReferenceLocator : DepthFirstAstVisitor
+		{
+			CSharpAstResolver resolver;
+
+			LocalReferenceFinder referenceFinder;
+
+			public LocalReferenceLocator(CSharpAstResolver resolver, LocalReferenceFinder referenceFinder)
+			{
+				this.resolver = resolver;
+				this.referenceFinder = referenceFinder;
+			}
+
+			IList<IVariable> processedVariables = new List<IVariable>();
+
+			public void ProccessRoot (AstNode rootNode)
+			{
+				rootNode.AcceptVisitor(this);
+				referenceFinder.visitedRoots.Add(rootNode);
+			}
+
+			public override void VisitCSharpTokenNode(CSharpTokenNode token)
+			{
+				// Nothing
+			}
+
+			protected override void VisitChildren(AstNode node)
+			{
+				if (referenceFinder.visitedRoots.Contains(node))
+					return;
+				var localResolveResult = resolver.Resolve(node) as LocalResolveResult;
+				if (localResolveResult != null && !processedVariables.Contains(localResolveResult.Variable)) {
+					referenceFinder.references.Add(localResolveResult.Variable, new ReferenceResult(node, localResolveResult));
+
+					processedVariables.Add(localResolveResult.Variable);
+					base.VisitChildren(node);
+					Debug.Assert(processedVariables.Contains(localResolveResult.Variable), "Variable should still be in the list of processed variables.");
+					processedVariables.Remove(localResolveResult.Variable);
+				} else {
+					base.VisitChildren(node);
+				}
+			}
+		}
+	}
+
+	public class ReferenceResult
+	{
+		public ReferenceResult (AstNode node, LocalResolveResult resolveResult)
+		{
+			Node = node;
+			ResolveResult = resolveResult;
+		}
+
+		public AstNode Node { get; private set; }
+
+		public LocalResolveResult ResolveResult { get; private set; }
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/NamingHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/NamingHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/NamingHelper.cs	(revision 11807)
@@ -0,0 +1,242 @@
+//
+// NamingHelper.cs
+//
+// Author:
+//       Simon Lindgren <simon.n.lindgren@gmail.com>
+//
+// Copyright (c) 2012 Simon Lindgren
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Text;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	public class NamingHelper
+	{
+		ISet<string> usedVariableNames;
+		RefactoringContext context;
+
+		public NamingHelper(RefactoringContext context)
+		{
+			this.context = context;
+			if (usedVariableNames == null) {
+				var visitor = new VariableFinderVisitor();
+				var astNode = context.GetNode<Statement>();
+				astNode.AcceptVisitor(visitor);
+				usedVariableNames = visitor.VariableNames;
+			}
+		}
+
+		public static IEnumerable<string> GenerateNameProposals(AstType type)
+		{
+			if (type is PrimitiveType) {
+				var pt = (PrimitiveType)type;
+				switch (pt.Keyword) {
+					case "object":
+						yield return "o";
+						yield return "obj";
+						break;
+					case "bool":
+						yield return "b";
+						yield return "pred";
+						break;
+					case "double":
+					case "float":
+					case "decimal":
+						yield return "d";
+						yield return "f";
+						yield return "m";
+						break;
+					case "char":
+						yield return "c";
+						break;
+					default:
+						yield return "i";
+						yield return "j";
+						yield return "k";
+						break;
+				}
+				yield break;
+			}
+			string name;
+			if (type is SimpleType) {
+				name = ((SimpleType)type).Identifier;
+			} else if (type is MemberType) {
+				name = ((MemberType)type).MemberName;
+			} else {
+				yield break;
+			}
+
+			var names = WordParser.BreakWords(name);
+			if (names.Count > 0) {
+				names [0] = Char.ToLower(names [0] [0]) + names [0].Substring(1);
+			}
+			yield return string.Join("", names);
+		}
+
+		/// <summary>
+		/// Generates a variable name for a variable of the specified type.
+		/// </summary>
+		/// <returns>
+		/// The variable name.
+		/// </returns>
+		/// <param name='type'>
+		/// The type of the variable.
+		/// </param>
+		/// <param name='baseName'>
+		/// Suggested base name.
+		/// </param>
+		public string GenerateVariableName(AstType type, string baseName = null)
+		{
+			if (baseName == null) {
+				foreach (var name in NamingHelper.GenerateNameProposals(type)) {
+					baseName = baseName ?? name;
+					if (NameIsUnused(name)) {
+						usedVariableNames.Add(name);
+						return name;
+					}
+				}
+			} else if (NameIsUnused(baseName)) {
+				return baseName;
+			}
+
+			// If we get here, all of the standard suggestions are already used.
+			// This will at least be the second variable named based on firstSuggestion, so start at 2
+			int counter = 2;
+			string proposedName;
+			do {
+				proposedName = baseName + counter++;
+			} while (!NameIsUnused(proposedName));
+			usedVariableNames.Add(proposedName);
+			return proposedName;
+		}
+
+		bool NameIsUnused(string name)
+		{
+			return !usedVariableNames.Contains(name) && LookupVariable(name) == null;
+		}
+
+		/// <summary>
+		/// Generates a variable name for a variable of the specified type.
+		/// </summary>
+		/// <returns>
+		/// The variable name.
+		/// </returns>
+		/// <param name='type'>
+		/// The type of the variable.
+		/// </param>
+		/// <param name='baseName'>
+		/// Suggested base name.
+		/// </param>
+		public string GenerateVariableName(IType type, string baseName = null)
+		{
+			AstType astType = ToAstType(type);
+			return GenerateVariableName(astType, baseName);
+		}
+
+		AstType ToAstType(IType type)
+		{
+			switch (type.FullName) {
+				case "System.Object":
+					return new PrimitiveType("object");
+				case "System.String":
+					return new PrimitiveType("string");
+				case "System.Boolean":
+					return new PrimitiveType("bool");
+				case "System.Char":
+					return new PrimitiveType("char");
+				case "System.SByte":
+					return new PrimitiveType("sbyte");
+				case "System.Byte":
+					return new PrimitiveType("byte");
+				case "System.Int16":
+					return new PrimitiveType("short");
+				case "System.UInt16":
+					return new PrimitiveType("ushort");
+				case "System.Int32":
+					return new PrimitiveType("int");
+				case "System.UInt32":
+					return new PrimitiveType("uint");
+				case "System.Int64":
+					return new PrimitiveType("long");
+				case "System.UInt64":
+					return new PrimitiveType("ulong");
+				case "System.Single":
+					return new PrimitiveType("float");
+				case "System.Double":
+					return new PrimitiveType("double");
+				case "System.Decimal":
+					return new PrimitiveType("decimal");
+				default:
+					return new SimpleType(type.Name);
+			}
+		}
+
+		IVariable LookupVariable(string name)
+		{
+			var blockStatement = context.GetNode<BlockStatement>();
+			var resolverState = context.GetResolverStateAfter(blockStatement.RBraceToken.PrevSibling);
+			var simpleNameRR = resolverState.ResolveSimpleName(name, new List<IType>()) as LocalResolveResult;
+			if (simpleNameRR == null)
+				return null;
+			return simpleNameRR.Variable;
+		}
+
+		class VariableFinderVisitor : DepthFirstAstVisitor
+		{
+
+			public ISet<string> VariableNames = new HashSet<string>();
+
+			public override void VisitVariableInitializer(VariableInitializer variableInitializer)
+			{
+				ProcessName(variableInitializer.Name);
+				base.VisitVariableInitializer(variableInitializer);
+			}
+
+			public override void VisitQueryLetClause(QueryLetClause queryLetClause)
+			{
+				ProcessName(queryLetClause.Identifier);
+				base.VisitQueryLetClause(queryLetClause);
+			}
+
+			public override void VisitQueryFromClause(QueryFromClause queryFromClause)
+			{
+				ProcessName(queryFromClause.Identifier);
+				base.VisitQueryFromClause(queryFromClause);
+			}
+
+			public override void VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+			{
+				ProcessName(queryContinuationClause.Identifier);
+				base.VisitQueryContinuationClause(queryContinuationClause);
+			}
+
+			void ProcessName(string name)
+			{
+				if (!VariableNames.Contains(name))
+					VariableNames.Add(name);
+			}
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/PatternHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/PatternHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/PatternHelper.cs	(revision 11807)
@@ -0,0 +1,172 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.PatternMatching;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// Helper class for constructing pattern ASTs.
+	/// </summary>
+	public class PatternHelper
+	{
+		/// <summary>
+		/// Produces a choice pattern for <c>expr1 op expr2</c> or <c>expr2 op expr1</c>.
+		/// </summary>
+		public static Expression CommutativeOperator(Expression expr1, BinaryOperatorType op, Expression expr2)
+		{
+			return new Choice {
+				new BinaryOperatorExpression(expr1, op, expr2),
+				new BinaryOperatorExpression(expr2.Clone(), op, expr1.Clone())
+			};
+		}
+
+		public static Expression CommutativeOperatorWithOptionalParentheses(Expression expr1, BinaryOperatorType op, Expression expr2)
+		{
+			return OptionalParentheses(CommutativeOperator(OptionalParentheses(expr1), op, OptionalParentheses(expr2)));
+		}
+		
+		/// <summary>
+		/// Optionally allows parentheses around the given expression.
+		/// </summary>
+		public static Expression OptionalParentheses(Expression expr)
+		{
+			return new OptionalParenthesesPattern(expr);
+		}
+		
+		sealed class OptionalParenthesesPattern : Pattern
+		{
+			readonly INode child;
+			
+			public OptionalParenthesesPattern(INode child)
+			{
+				this.child = child;
+			}
+			
+			public override bool DoMatch(INode other, Match match)
+			{
+				INode unpacked = ParenthesizedExpression.UnpackParenthesizedExpression(other as Expression);
+				return child.DoMatch(unpacked, match);
+			}
+		}
+
+		/// <summary>
+		/// Optionally allow a block around the given statement;
+		/// </summary>
+		/// <returns>The statement.</returns>
+		public static Statement EmbeddedStatement(Statement statement)
+		{
+			return new OptionalBlockPattern(statement);
+		}
+
+		sealed class OptionalBlockPattern : Pattern
+		{
+			readonly INode child;
+
+			public OptionalBlockPattern(INode child)
+			{
+				this.child = child;
+			}
+
+			public override bool DoMatch(INode other, Match match)
+			{
+				INode unpacked = UnpackBlockStatement(other as Statement);
+				return child.DoMatch(unpacked, match);
+			}
+
+			
+			/// <summary>
+			/// Unpacks the given expression if it is a ParenthesizedExpression, CheckedExpression or UncheckedExpression.
+			/// </summary>
+			public static Statement UnpackBlockStatement(Statement stmt)
+			{
+				while (stmt is BlockStatement) {
+					stmt = stmt.GetChildByRole(BlockStatement.StatementRole);
+					if (stmt.GetNextSibling(s => s.Role == BlockStatement.StatementRole) != null)
+						return null;
+				}
+				return stmt;
+			}
+		}
+
+	
+		/// <summary>
+		/// Allows to give parameter declaration group names.
+		/// </summary>
+		public static ParameterDeclaration NamedParameter(string groupName)
+		{
+			return new NamedParameterDeclaration (groupName);
+		}
+
+		/// <summary>
+		/// Allows to give parameter declaration group names.
+		/// </summary>
+		public static ParameterDeclaration NamedParameter(string groupName, AstType type, string name, ParameterModifier modifier = ParameterModifier.None)
+		{
+			return new NamedParameterDeclaration (groupName, type, name, modifier);
+		}
+
+		sealed class NamedParameterDeclaration : ParameterDeclaration
+		{
+			readonly string groupName;
+			public string GroupName {
+				get { return groupName; }
+			}
+
+			public NamedParameterDeclaration(string groupName = null)
+			{
+				this.groupName = groupName;
+			}
+
+			public NamedParameterDeclaration(string groupName, AstType type, string name, ParameterModifier modifier = ParameterModifier.None) : base (type, name, modifier)
+			{
+				this.groupName = groupName;
+			}
+
+			protected internal override bool DoMatch(AstNode other, Match match)
+			{
+				match.Add(this.groupName, other);
+				return base.DoMatch(other, match);
+			}
+		}
+
+		/// <summary>
+		/// Matches any type
+		/// </summary>
+		public static AstType AnyType (bool doesMatchNullTypes = false)
+		{
+			if (doesMatchNullTypes)
+				return new OptionalNode(new AnyNode());
+			else
+				return new AnyNode();
+		}
+
+		/// <summary>
+		/// Matches any type
+		/// </summary>
+		public static AstType AnyType (string groupName, bool doesMatchNullTypes = false)
+		{
+			if (doesMatchNullTypes)
+				return new OptionalNode(new AnyNode(groupName));
+			else
+				return new AnyNode(groupName);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/RefactoringAstHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/RefactoringAstHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/RefactoringAstHelper.cs	(revision 11807)
@@ -0,0 +1,49 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// Helper methods for constructing ASTs for refactoring.
+	/// These helpers work with frozen ASTs, i.e. they clone input nodes.
+	/// </summary>
+	public class RefactoringAstHelper
+	{
+		/// <summary>
+		/// Removes the target from a member reference while preserving the identifier and type arguments.
+		/// </summary>
+		public static IdentifierExpression RemoveTarget(MemberReferenceExpression mre)
+		{
+			IdentifierExpression ident = new IdentifierExpression(mre.MemberName);
+			ident.TypeArguments.AddRange(mre.TypeArguments.Select(t => t.Clone()));
+			return ident;
+		}
+		
+		/// <summary>
+		/// Removes the target from a member reference while preserving the identifier and type arguments.
+		/// </summary>
+		public static SimpleType RemoveTarget(MemberType memberType)
+		{
+			return new SimpleType(memberType.MemberName, memberType.TypeArguments.Select(t => t.Clone()));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/RefactoringContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/RefactoringContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/RefactoringContext.cs	(revision 11807)
@@ -0,0 +1,108 @@
+﻿// 
+// RefactoringContext.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Editor;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	public abstract class RefactoringContext : BaseRefactoringContext
+	{
+		public RefactoringContext(CSharpAstResolver resolver, CancellationToken cancellationToken) : base (resolver, cancellationToken)
+		{
+
+		}
+
+		public abstract TextLocation Location { get; }
+		
+		public TypeSystemAstBuilder CreateTypeSystemAstBuilder()
+		{
+			var astNode = GetNode() ?? RootNode.GetNodeAt(Location) ?? RootNode;
+			var csResolver = Resolver.GetResolverStateBefore(astNode);
+			return new TypeSystemAstBuilder(csResolver);
+		}
+		
+		public virtual AstType CreateShortType (IType fullType)
+		{
+			var builder = CreateTypeSystemAstBuilder();
+			return builder.ConvertType(fullType);
+		}
+		
+		public virtual AstType CreateShortType(string ns, string name, int typeParameterCount = 0)
+		{
+			var builder = CreateTypeSystemAstBuilder();
+			return builder.ConvertType(new TopLevelTypeName(ns, name, typeParameterCount));
+		}
+
+		public virtual IEnumerable<AstNode> GetSelectedNodes()
+		{
+			if (!IsSomethingSelected) {
+				return Enumerable.Empty<AstNode> ();
+			}
+			
+			return RootNode.GetNodesBetween(SelectionStart, SelectionEnd);
+		}
+
+		public AstNode GetNode ()
+		{
+			return RootNode.GetNodeAt (Location);
+		}
+		
+		public AstNode GetNode (Predicate<AstNode> pred)
+		{
+			return RootNode.GetNodeAt (Location, pred);
+		}
+		
+		public T GetNode<T> () where T : AstNode
+		{
+			return RootNode.GetNodeAt<T> (Location);
+		}
+		
+		public CSharpTypeResolveContext GetTypeResolveContext()
+		{
+			if (UnresolvedFile != null)
+				return UnresolvedFile.GetTypeResolveContext(Compilation, Location);
+			else
+				return null;
+		}
+
+		#region Naming
+		public virtual string GetNameProposal (string name, bool camelCase = true)
+		{
+			return GetNameProposal(name, Location, camelCase);
+		}
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/Script.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/Script.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/Script.cs	(revision 11807)
@@ -0,0 +1,651 @@
+﻿// 
+// Script.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@novell.com>
+// 
+// Copyright (c) 2011 Mike Krüger <mkrueger@novell.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Threading.Tasks;
+using System.Linq;
+using System.Text;
+using Mono.CSharp;
+using ITypeDefinition = ICSharpCode.NRefactory.TypeSystem.ITypeDefinition;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// Class for creating change scripts.
+	/// 'Original document' = document without the change script applied.
+	/// 'Current document' = document with the change script (as far as it is already created) applies.
+	/// </summary>
+	public abstract class Script : IDisposable
+	{
+		internal struct Segment : ISegment
+		{
+			readonly int offset;
+			readonly int length;
+			
+			public int Offset {
+				get { return offset; }
+			}
+			
+			public int Length {
+				get { return length; }
+			}
+			
+			public int EndOffset {
+				get { return Offset + Length; }
+			}
+			
+			public Segment (int offset, int length)
+			{
+				this.offset = offset;
+				this.length = length;
+			}
+			
+			public override string ToString ()
+			{
+				return string.Format ("[Script.Segment: Offset={0}, Length={1}, EndOffset={2}]", Offset, Length, EndOffset);
+			}
+		}
+		
+		readonly CSharpFormattingOptions formattingOptions;
+		readonly TextEditorOptions options;
+		readonly Dictionary<AstNode, ISegment> segmentsForInsertedNodes = new Dictionary<AstNode, ISegment>();
+		
+		protected Script(CSharpFormattingOptions formattingOptions, TextEditorOptions options)
+		{
+			if (formattingOptions == null)
+				throw new ArgumentNullException("formattingOptions");
+			if (options == null)
+				throw new ArgumentNullException("options");
+			this.formattingOptions = formattingOptions;
+			this.options = options;
+		}
+		
+		/// <summary>
+		/// Given an offset in the original document (at the start of script execution),
+		/// returns the offset in the current document.
+		/// </summary>
+		public abstract int GetCurrentOffset(int originalDocumentOffset);
+		
+		/// <summary>
+		/// Given an offset in the original document (at the start of script execution),
+		/// returns the offset in the current document.
+		/// </summary>
+		public abstract int GetCurrentOffset(TextLocation originalDocumentLocation);
+		
+		/// <summary>
+		/// Creates a tracked segment for the specified (offset,length)-segment.
+		/// Offset is interpreted to be an offset in the current document.
+		/// </summary>
+		/// <returns>
+		/// A segment that initially has the specified values, and updates
+		/// on every <see cref="Replace(int,int,string)"/> call.
+		/// </returns>
+		protected abstract ISegment CreateTrackedSegment(int offset, int length);
+
+		/// <summary>
+		/// Gets the current text segment of the specified AstNode.
+		/// </summary>
+		/// <param name="node">The node to get the segment for.</param>
+		public ISegment GetSegment(AstNode node)
+		{
+			ISegment segment;
+			if (segmentsForInsertedNodes.TryGetValue(node, out segment))
+				return segment;
+			if (node.StartLocation.IsEmpty || node.EndLocation.IsEmpty) {
+				throw new InvalidOperationException("Trying to get the position of a node that is not part of the original document and was not inserted");
+			}
+			int startOffset = GetCurrentOffset(node.StartLocation);
+			int endOffset = GetCurrentOffset(node.EndLocation);
+			return new Segment(startOffset, endOffset - startOffset);
+		}
+		
+		/// <summary>
+		/// Replaces text.
+		/// </summary>
+		/// <param name="offset">The starting offset of the text to be replaced.</param>
+		/// <param name="length">The length of the text to be replaced.</param>
+		/// <param name="newText">The new text.</param>
+		public abstract void Replace (int offset, int length, string newText);
+		
+		public void InsertText(int offset, string newText)
+		{
+			Replace(offset, 0, newText);
+		}
+		
+		public void RemoveText(int offset, int length)
+		{
+			Replace(offset, length, "");
+		}
+		
+		public CSharpFormattingOptions FormattingOptions {
+			get { return formattingOptions; }
+		}
+		
+		public TextEditorOptions Options {
+			get { return options; }
+		}
+		
+		public void InsertBefore(AstNode node, AstNode newNode)
+		{
+			var startOffset = GetCurrentOffset(new TextLocation(node.StartLocation.Line, 1));
+			var output = OutputNode (GetIndentLevelAt (startOffset), newNode);
+			string text = output.Text;
+			if (!(newNode is Expression || newNode is AstType))
+				text += Options.EolMarker;
+			InsertText(startOffset, text);
+			output.RegisterTrackedSegments(this, startOffset);
+			CorrectFormatting (node, newNode);
+		}
+
+		public void InsertAfter(AstNode node, AstNode newNode)
+		{
+            var indentLevel = IndentLevelFor(node);
+            var output = OutputNode(indentLevel, newNode);
+            string text =  PrefixFor(node, newNode) + output.Text;
+
+            var insertOffset = GetCurrentOffset(node.EndLocation);
+            InsertText(insertOffset, text);
+            output.RegisterTrackedSegments(this, insertOffset);
+            CorrectFormatting (node, newNode);
+		}
+
+	    private int IndentLevelFor(AstNode node)
+	    {
+            if (!DoesInsertingAfterRequireNewline(node))
+	            return 0;
+	        
+            return GetIndentLevelAt(GetCurrentOffset(new TextLocation(node.StartLocation.Line, 1)));
+	    }
+
+	    bool DoesInsertingAfterRequireNewline(AstNode node)
+	    {
+            if (node is Expression)
+                return false;
+
+            if (node is AstType)
+                return false;
+
+	        if (node is ParameterDeclaration)
+	            return false;
+
+	        var token = node as CSharpTokenNode;
+	        if (token != null && token.Role == Roles.LPar)
+	            return false;
+	        
+	        return true;
+	    }
+
+	    private string PrefixFor(AstNode node, AstNode newNode)
+	    {
+	        if (DoesInsertingAfterRequireNewline(node))
+	            return Options.EolMarker;
+
+	        if (newNode is ParameterDeclaration && node is ParameterDeclaration)
+	            //todo: worry about adding characters to the document without matching AstNode's. 
+	            return ", ";
+
+	        return String.Empty;
+	    }
+
+	    public void AddTo(BlockStatement bodyStatement, AstNode newNode)
+		{
+			var startOffset = GetCurrentOffset(bodyStatement.LBraceToken.EndLocation);
+			var output = OutputNode(1 + GetIndentLevelAt(startOffset), newNode, true);
+			InsertText(startOffset, output.Text);
+			output.RegisterTrackedSegments(this, startOffset);
+			CorrectFormatting (null, newNode);
+		}
+	
+		public void AddTo(TypeDeclaration typeDecl, EntityDeclaration entityDecl)
+		{
+			var startOffset = GetCurrentOffset(typeDecl.LBraceToken.EndLocation);
+			var output = OutputNode(1 + GetIndentLevelAt(startOffset), entityDecl, true);
+			InsertText(startOffset, output.Text);
+			output.RegisterTrackedSegments(this, startOffset);
+			CorrectFormatting (null, entityDecl);
+		}
+		
+		/// <summary>
+		/// Changes the modifier of a given entity declaration.
+		/// </summary>
+		/// <param name="entity">The entity.</param>
+		/// <param name="modifiers">The new modifiers.</param>
+		public void ChangeModifier(EntityDeclaration entity, Modifiers modifiers)
+		{
+			var dummyEntity = new MethodDeclaration ();
+			dummyEntity.Modifiers = modifiers;
+
+			int offset;
+			int endOffset;
+
+			if (entity.ModifierTokens.Any ()) {
+				offset = GetCurrentOffset(entity.ModifierTokens.First ().StartLocation);
+				endOffset = GetCurrentOffset(entity.ModifierTokens.Last ().GetNextSibling (s => s.Role != Roles.NewLine && s.Role != Roles.Whitespace).StartLocation);
+			} else {
+				var child = entity.FirstChild;
+				while (child.NodeType == NodeType.Whitespace ||
+				       child.Role == EntityDeclaration.AttributeRole ||
+				       child.Role == Roles.NewLine) {
+					child = child.NextSibling;
+				}
+				offset = endOffset = GetCurrentOffset(child.StartLocation);
+			}
+
+			var sb = new StringBuilder();
+			foreach (var modifier in dummyEntity.ModifierTokens) {
+				sb.Append(modifier.ToString());
+				sb.Append(' ');
+			}
+
+			Replace(offset, endOffset - offset, sb.ToString());
+		}
+
+		public void ChangeModifier(ParameterDeclaration param, ParameterModifier modifier)
+		{
+			var child = param.FirstChild;
+			Func<AstNode, bool> pred = s => s.Role == ParameterDeclaration.RefModifierRole || s.Role == ParameterDeclaration.OutModifierRole || s.Role == ParameterDeclaration.ParamsModifierRole || s.Role == ParameterDeclaration.ThisModifierRole;
+			if (!pred(child))
+				child = child.GetNextSibling(pred); 
+
+			int offset;
+			int endOffset;
+
+			if (child != null) {
+				offset = GetCurrentOffset(child.StartLocation);
+				endOffset = GetCurrentOffset(child.GetNextSibling (s => s.Role != Roles.NewLine && s.Role != Roles.Whitespace).StartLocation);
+			} else {
+				offset = endOffset = GetCurrentOffset(param.Type.StartLocation);
+			}
+			string modString;
+			switch (modifier) {
+				case ParameterModifier.None:
+					modString = "";
+					break;
+				case ParameterModifier.Ref:
+					modString = "ref ";
+					break;
+				case ParameterModifier.Out:
+					modString = "out ";
+					break;
+				case ParameterModifier.Params:
+					modString = "params ";
+					break;
+				case ParameterModifier.This:
+					modString = "this ";
+					break;
+				default:
+					throw new ArgumentOutOfRangeException();
+			}
+			Replace(offset, endOffset - offset, modString);
+		}
+
+		/// <summary>
+		/// Changes the base types of a type declaration.
+		/// </summary>
+		/// <param name="type">The type declaration to modify.</param>
+		/// <param name="baseTypes">The new base types.</param>
+		public void ChangeBaseTypes(TypeDeclaration type, IEnumerable<AstType> baseTypes)
+		{
+			var dummyType = new TypeDeclaration();
+			dummyType.BaseTypes.AddRange(baseTypes);
+
+			int offset;
+			int endOffset;
+			var sb = new StringBuilder();
+
+			if (type.BaseTypes.Any ()) {
+				offset = GetCurrentOffset(type.ColonToken.StartLocation);
+				endOffset = GetCurrentOffset(type.BaseTypes.Last ().EndLocation);
+			} else {
+				sb.Append(' ');
+				if (type.TypeParameters.Any()) {
+					offset = endOffset = GetCurrentOffset(type.RChevronToken.EndLocation);
+				} else {
+					offset = endOffset = GetCurrentOffset(type.NameToken.EndLocation);
+				}
+			}
+
+			if (dummyType.BaseTypes.Any()) {
+				sb.Append(": ");
+				sb.Append(string.Join(", ", dummyType.BaseTypes));
+			}
+
+			Replace(offset, endOffset - offset, sb.ToString());
+			FormatText(type);
+		}
+
+
+		/// <summary>
+		/// Adds an attribute section to a given entity.
+		/// </summary>
+		/// <param name="entity">The entity to add the attribute to.</param>
+		/// <param name="attr">The attribute to add.</param>
+		public void AddAttribute(EntityDeclaration entity, AttributeSection attr)
+		{
+			var node = entity.FirstChild;
+			while (node.NodeType == NodeType.Whitespace || node.Role == Roles.Attribute) {
+				node = node.NextSibling;
+			}
+			InsertBefore(node, attr);
+		}
+
+		public virtual Task Link (params AstNode[] nodes)
+		{
+			// Default implementation: do nothing
+			// Derived classes are supposed to enter the text editor's linked state.
+			
+			// Immediately signal the task as completed:
+			var tcs = new TaskCompletionSource<object>();
+			tcs.SetResult(null);
+			return tcs.Task;
+		}
+
+		public virtual Task Link (IEnumerable<AstNode> nodes)
+		{
+			return Link(nodes.ToArray());
+		}
+		
+		public void Replace (AstNode node, AstNode replaceWith)
+		{
+			var segment = GetSegment (node);
+			int startOffset = segment.Offset;
+			int level = 0;
+			if (!(replaceWith is Expression) && !(replaceWith is AstType))
+				level = GetIndentLevelAt (startOffset);
+			NodeOutput output = OutputNode (level, replaceWith);
+			output.TrimStart ();
+			Replace (startOffset, segment.Length, output.Text);
+			output.RegisterTrackedSegments(this, startOffset);
+			CorrectFormatting (node, node);
+		}
+
+		List<AstNode> nodesToFormat = new List<AstNode> ();
+
+		void CorrectFormatting(AstNode node, AstNode newNode)
+		{
+			if (node is Identifier || node is IdentifierExpression || node is CSharpTokenNode || node is AstType)
+				return;
+			if (node == null || node.Parent is BlockStatement) {
+				nodesToFormat.Add (newNode); 
+			} else {
+				nodesToFormat.Add ((node.Parent != null && (node.Parent is Statement || node.Parent is Expression || node.Parent is VariableInitializer)) ? node.Parent : newNode); 
+			}
+		}
+		
+		public abstract void Remove (AstNode node, bool removeEmptyLine = true);
+
+		/// <summary>
+		/// Safely removes an attribue from it's section (removes empty sections).
+		/// </summary>
+		/// <param name="attr">The attribute to be removed.</param>
+		public void RemoveAttribute(Attribute attr)
+		{
+			AttributeSection section = (AttributeSection)attr.Parent;
+			if (section.Attributes.Count == 1) {
+				Remove(section);
+				return;
+			}
+
+			var newSection = (AttributeSection)section.Clone();
+			int i = 0;
+			foreach (var a in section.Attributes) {
+				if (a == attr)
+					break;
+				i++;
+			}
+			newSection.Attributes.Remove (newSection.Attributes.ElementAt (i));
+			Replace(section, newSection);
+		}
+		
+		public abstract void FormatText (IEnumerable<AstNode> nodes);
+
+		public void FormatText (params AstNode[] nodes)
+		{
+			FormatText ((IEnumerable<AstNode>)nodes);
+		}
+
+		public virtual void Select (AstNode node)
+		{
+			// default implementation: do nothing
+			// Derived classes are supposed to set the text editor's selection
+		}
+
+		public virtual void Select (TextLocation start, TextLocation end)
+		{
+			// default implementation: do nothing
+			// Derived classes are supposed to set the text editor's selection
+		}
+
+		public virtual void Select (int startOffset, int endOffset)
+		{
+			// default implementation: do nothing
+			// Derived classes are supposed to set the text editor's selection
+		}
+
+		
+		public enum InsertPosition
+		{
+			Start,
+			Before,
+			After,
+			End
+		}
+		
+		public virtual Task<Script> InsertWithCursor(string operation, InsertPosition defaultPosition, IList<AstNode> nodes)
+		{
+			throw new NotImplementedException();
+		}
+		
+		public virtual Task<Script> InsertWithCursor(string operation, ITypeDefinition parentType, Func<Script, RefactoringContext, IList<AstNode>> nodeCallback)
+		{
+			throw new NotImplementedException();
+		}
+		
+		public Task<Script> InsertWithCursor(string operation, InsertPosition defaultPosition, params AstNode[] nodes)
+		{
+			return InsertWithCursor(operation, defaultPosition, (IList<AstNode>)nodes);
+		}
+
+		public Task<Script> InsertWithCursor(string operation, ITypeDefinition parentType, Func<Script, RefactoringContext, AstNode> nodeCallback)
+		{
+			return InsertWithCursor(operation, parentType, (Func<Script, RefactoringContext, IList<AstNode>>)delegate (Script s, RefactoringContext ctx) {
+				return new AstNode[] { nodeCallback(s, ctx) };
+			});
+		}
+		
+		protected virtual int GetIndentLevelAt (int offset)
+		{
+			return 0;
+		}
+		
+		sealed class SegmentTrackingTokenWriter : TextWriterTokenWriter
+		{
+			internal List<KeyValuePair<AstNode, Segment>> NewSegments = new List<KeyValuePair<AstNode, Segment>>();
+			readonly Stack<int> startOffsets = new Stack<int>();
+			readonly StringWriter stringWriter;
+			
+			public SegmentTrackingTokenWriter(StringWriter stringWriter)
+				: base(stringWriter)
+			{
+				this.stringWriter = stringWriter;
+			}
+			
+			public override void WriteIdentifier (Identifier identifier)
+			{
+				int startOffset = stringWriter.GetStringBuilder ().Length;
+				int endOffset = startOffset + (identifier.Name ?? "").Length + (identifier.IsVerbatim ? 1 : 0);
+				NewSegments.Add(new KeyValuePair<AstNode, Segment>(identifier, new Segment(startOffset, endOffset - startOffset)));
+				base.WriteIdentifier (identifier);
+			}
+			
+			public override void StartNode (AstNode node)
+			{
+				base.StartNode (node);
+				startOffsets.Push(stringWriter.GetStringBuilder ().Length);
+			}
+			
+			public override void EndNode (AstNode node)
+			{
+				int startOffset = startOffsets.Pop();
+				int endOffset = stringWriter.GetStringBuilder ().Length;
+				NewSegments.Add(new KeyValuePair<AstNode, Segment>(node, new Segment(startOffset, endOffset - startOffset)));
+				base.EndNode (node);
+			}
+		}
+		
+		protected NodeOutput OutputNode(int indentLevel, AstNode node, bool startWithNewLine = false)
+		{
+			var stringWriter = new StringWriter ();
+			var formatter = new SegmentTrackingTokenWriter(stringWriter);
+			formatter.Indentation = indentLevel;
+			formatter.IndentationString = Options.TabsToSpaces ? new string (' ', Options.IndentSize) : "\t";
+			stringWriter.NewLine = Options.EolMarker;
+			if (startWithNewLine)
+				formatter.NewLine ();
+			var visitor = new CSharpOutputVisitor (formatter, formattingOptions);
+			node.AcceptVisitor (visitor);
+			string text = stringWriter.ToString().TrimEnd();
+			return new NodeOutput(text, formatter.NewSegments);
+		}
+		
+		protected class NodeOutput
+		{
+			string text;
+			readonly List<KeyValuePair<AstNode, Segment>> newSegments;
+			int trimmedLength;
+			
+			internal NodeOutput(string text, List<KeyValuePair<AstNode, Segment>> newSegments)
+			{
+				this.text = text;
+				this.newSegments = newSegments;
+			}
+			
+			public string Text {
+				get { return text; }
+			}
+			
+			public void TrimStart()
+			{
+				for (int i = 0; i < text.Length; i++) {
+					char ch = text [i];
+					if (ch != ' ' && ch != '\t') {
+						if (i > 0) {
+							text = text.Substring (i);
+							trimmedLength = i;
+						}
+						break;
+					}
+				}
+			}
+			
+			public void RegisterTrackedSegments(Script script, int insertionOffset)
+			{
+				foreach (var pair in newSegments) {
+					int offset = insertionOffset + pair.Value.Offset - trimmedLength;
+					ISegment trackedSegment = script.CreateTrackedSegment(offset, pair.Value.Length);
+					script.segmentsForInsertedNodes.Add(pair.Key, trackedSegment);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Renames the specified symbol.
+		/// </summary>
+		/// <param name='symbol'>
+		/// The symbol to rename
+		/// </param>
+		/// <param name='name'>
+		/// The new name, if null the user is prompted for a new name.
+		/// </param>
+		public virtual void Rename(ISymbol symbol, string name = null)
+		{
+		}
+		
+		public virtual void DoGlobalOperationOn(IEnumerable<IEntity> entities, Action<RefactoringContext, Script, IEnumerable<AstNode>> callback, string operationDescription = null)
+		{
+		}
+
+		public virtual void Dispose()
+		{
+			FormatText (nodesToFormat);
+		}
+		
+		public enum NewTypeContext {
+			/// <summary>
+			/// The class should be placed in a new file to the current namespace.
+			/// </summary>
+			CurrentNamespace,
+			
+			/// <summary>
+			/// The class should be placed in the unit tests. (not implemented atm.)
+			/// </summary>
+			UnitTests
+		}
+		
+		/// <summary>
+		/// Creates a new file containing the type, namespace and correct usings.
+		/// (Note: Should take care of IDE specific things, file headers, add to project, correct name).
+		/// </summary>
+		/// <param name='newType'>
+		/// New type to be created.
+		/// </param>
+		/// <param name='context'>
+		/// The Context in which the new type should be created.
+		/// </param>
+		public virtual void CreateNewType(AstNode newType, NewTypeContext context = NewTypeContext.CurrentNamespace)
+		{
+		}
+	}
+
+	public static class ExtMethods
+	{
+		public static void ContinueScript (this Task task, Action act)
+		{
+			if (task.IsCompleted) {
+				act();
+			} else {
+				task.ContinueWith(delegate {
+					act();
+				}, TaskScheduler.FromCurrentSynchronizationContext());
+			}
+		}
+
+		public static void ContinueScript (this Task<Script> task, Action<Script> act)
+		{
+			if (task.IsCompleted) {
+				act(task.Result);
+			} else {
+				task.ContinueWith(delegate {
+					act(task.Result);
+				}, TaskScheduler.FromCurrentSynchronizationContext());
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/TypeGuessing.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/TypeGuessing.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/TypeGuessing.cs	(revision 11807)
@@ -0,0 +1,349 @@
+//
+// TypeGuessing.cs
+//
+// Author:
+//       Mike KrÃŒger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.Semantics;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public static class TypeGuessing
+	{
+		static int GetArgumentIndex(IEnumerable<Expression> arguments, AstNode parameter)
+		{
+			int argumentNumber = 0;
+			foreach (var arg in arguments) {
+				if (arg == parameter) {
+					return argumentNumber;
+				}
+				argumentNumber++;
+			}
+			return -1;
+		}
+
+		static IEnumerable<IType> GetAllValidTypesFromInvocation(CSharpAstResolver resolver, InvocationExpression invoke, AstNode parameter)
+		{
+			int index = GetArgumentIndex(invoke.Arguments, parameter);
+			if (index < 0)
+				yield break;
+
+			var targetResult = resolver.Resolve(invoke.Target) as MethodGroupResolveResult;
+			if (targetResult != null) {
+				foreach (var method in targetResult.Methods) {
+					if (index < method.Parameters.Count) {
+						if (method.Parameters [index].IsParams) {
+							var arrayType = method.Parameters [index].Type as ArrayType;
+							if (arrayType != null)
+								yield return arrayType.ElementType;
+						}
+
+						yield return method.Parameters [index].Type;
+					}
+				}
+				foreach (var extMethods in targetResult.GetExtensionMethods ()) {
+					foreach (var extMethod in extMethods) {
+						IType[] inferredTypes;
+						var m = extMethod;
+						if (CSharpResolver.IsEligibleExtensionMethod(targetResult.TargetType, extMethod, true, out inferredTypes)) {
+							if (inferredTypes != null)
+								m = extMethod.Specialize(new TypeParameterSubstitution(null, inferredTypes));
+						}
+
+						int correctedIndex = index + 1;
+						if (correctedIndex < m.Parameters.Count) {
+							if (m.Parameters [correctedIndex].IsParams) {
+								var arrayType = m.Parameters [correctedIndex].Type as ArrayType;
+								if (arrayType != null)
+									yield return arrayType.ElementType;
+							}
+							yield return m.Parameters [correctedIndex].Type;
+						}
+					}
+				}
+			}
+		}
+
+		static IEnumerable<IType> GetAllValidTypesFromObjectCreation(CSharpAstResolver resolver, ObjectCreateExpression invoke, AstNode parameter)
+		{
+			int index = GetArgumentIndex(invoke.Arguments, parameter);
+			if (index < 0)
+				yield break;
+
+			var targetResult = resolver.Resolve(invoke.Type);
+			if (targetResult is TypeResolveResult) {
+				var type = ((TypeResolveResult)targetResult).Type;
+				if (type.Kind == TypeKind.Delegate && index == 0) {
+					yield return type;
+					yield break;
+				}
+				foreach (var constructor in type.GetConstructors ()) {
+					if (index < constructor.Parameters.Count)
+						yield return constructor.Parameters [index].Type;
+				}
+			}
+		}
+
+		public static IType GetElementType(CSharpAstResolver resolver, IType type)
+		{
+			// TODO: A better get element type method.
+			if (type.Kind == TypeKind.Array || type.Kind == TypeKind.Dynamic) {
+				if (type.Kind == TypeKind.Array)
+					return ((ArrayType)type).ElementType;
+				return resolver.Compilation.FindType(KnownTypeCode.Object);
+			}
+
+
+			foreach (var method in type.GetMethods (m => m.Name == "GetEnumerator")) {
+				IType returnType = null;
+				foreach (var prop in method.ReturnType.GetProperties(p => p.Name == "Current")) {
+					if (returnType != null && prop.ReturnType.IsKnownType (KnownTypeCode.Object))
+						continue;
+					returnType = prop.ReturnType;
+				}
+				if (returnType != null)
+					return returnType;
+			}
+
+			return resolver.Compilation.FindType(KnownTypeCode.Object);
+		}
+
+		static IEnumerable<IType> GuessFromConstructorInitializer(CSharpAstResolver resolver, AstNode expr)
+		{
+			var init = expr.Parent as ConstructorInitializer;
+			var rr = resolver.Resolve(expr.Parent);
+			int index = GetArgumentIndex(init.Arguments, expr);
+			if (index >= 0) {
+				foreach (var constructor in rr.Type.GetConstructors()) {
+					if (index < constructor.Parameters.Count) {
+						yield return constructor.Parameters[index].Type;
+					}
+				}
+			}
+		}
+
+		public static IEnumerable<IType> GetValidTypes(CSharpAstResolver resolver, AstNode expr)
+		{
+			if (expr.Role == Roles.Condition) {
+				return new [] { resolver.Compilation.FindType (KnownTypeCode.Boolean) };
+			}
+
+			var mref = expr as MemberReferenceExpression;
+			if (mref != null) {
+				// case: guess enum when trying to access not existent enum member
+				var rr = resolver.Resolve(mref.Target);
+				if (!rr.IsError && rr.Type.Kind == TypeKind.Enum)
+					return new [] { rr.Type };
+			}
+
+			if (expr.Parent is ParenthesizedExpression || expr.Parent is NamedArgumentExpression) {
+				return GetValidTypes(resolver, expr.Parent);
+			}
+			if (expr.Parent is DirectionExpression) {
+				var parent = expr.Parent.Parent;
+				if (parent is InvocationExpression) {
+					var invoke = (InvocationExpression)parent;
+					return GetAllValidTypesFromInvocation(resolver, invoke, expr.Parent);
+				}
+			}
+
+			if (expr.Parent is ArrayInitializerExpression) {
+				if (expr is NamedExpression)
+					return new [] { resolver.Resolve(((NamedExpression)expr).Expression).Type };
+
+				var aex = expr.Parent as ArrayInitializerExpression;
+				if (aex.IsSingleElement)
+					aex = aex.Parent as ArrayInitializerExpression;
+				var type = GetElementType(resolver, resolver.Resolve(aex.Parent).Type);
+				if (type.Kind != TypeKind.Unknown)
+					return new [] { type };
+			}
+
+			if (expr.Parent is ObjectCreateExpression) {
+				var invoke = (ObjectCreateExpression)expr.Parent;
+				return GetAllValidTypesFromObjectCreation(resolver, invoke, expr);
+			}
+
+			if (expr.Parent is ArrayCreateExpression) {
+				var ace = (ArrayCreateExpression)expr.Parent;
+				if (!ace.Type.IsNull) {
+					return new [] { resolver.Resolve(ace.Type).Type };
+				}
+			}
+
+			if (expr.Parent is InvocationExpression) {
+				var parent = expr.Parent;
+				if (parent is InvocationExpression) {
+					var invoke = (InvocationExpression)parent;
+					return GetAllValidTypesFromInvocation(resolver, invoke, expr);
+				}
+			}
+
+			if (expr.Parent is VariableInitializer) {
+				var initializer = (VariableInitializer)expr.Parent;
+				var field = initializer.GetParent<FieldDeclaration>();
+				if (field != null) {
+					var rr = resolver.Resolve(field.ReturnType);
+					if (!rr.IsError)
+						return new [] { rr.Type };
+				}
+				var varStmt = initializer.GetParent<VariableDeclarationStatement>();
+				if (varStmt != null) {
+					var rr = resolver.Resolve(varStmt.Type);
+					if (!rr.IsError)
+						return new [] { rr.Type };
+				}
+				return new [] { resolver.Resolve(initializer).Type };
+			}
+
+			if (expr.Parent is CastExpression) {
+				var cast = (CastExpression)expr.Parent;
+				return new [] { resolver.Resolve(cast.Type).Type };
+			}
+
+			if (expr.Parent is AsExpression) {
+				var cast = (AsExpression)expr.Parent;
+				return new [] { resolver.Resolve(cast.Type).Type };
+			}
+
+			if (expr.Parent is AssignmentExpression) {
+				var assign = (AssignmentExpression)expr.Parent;
+				var other = assign.Left == expr ? assign.Right : assign.Left;
+				return new [] { resolver.Resolve(other).Type };
+			}
+
+			if (expr.Parent is BinaryOperatorExpression) {
+				var assign = (BinaryOperatorExpression)expr.Parent;
+				var other = assign.Left == expr ? assign.Right : assign.Left;
+				return new [] { resolver.Resolve(other).Type };
+			}
+
+			if (expr.Parent is ReturnStatement) {
+				var parent = expr.Ancestors.FirstOrDefault(n => n is EntityDeclaration || n is AnonymousMethodExpression|| n is LambdaExpression);
+				if (parent != null) {
+					var rr = resolver.Resolve(parent);
+					if (!rr.IsError)
+						return new [] { rr.Type };
+				}
+				var e = parent as EntityDeclaration;
+				if (e != null) {
+					var rt = resolver.Resolve(e.ReturnType);
+					if (!rt.IsError)
+						return new [] { rt.Type };
+				}
+			}
+
+			if (expr.Parent is YieldReturnStatement) {
+				ParameterizedType pt = null;
+				var parent = expr.Ancestors.FirstOrDefault(n => n is EntityDeclaration || n is AnonymousMethodExpression|| n is LambdaExpression);
+				if (parent != null) {
+					var rr = resolver.Resolve(parent);
+					if (!rr.IsError)
+						pt = rr.Type as ParameterizedType;
+				}
+				var e = parent as EntityDeclaration;
+				if (e != null) {
+					var rt = resolver.Resolve(e.ReturnType);
+					if (!rt.IsError)
+						pt = rt.Type as ParameterizedType;
+				}
+				if (pt != null) {
+					if (pt.FullName == "System.Collections.Generic.IEnumerable") {
+						return new [] { pt.TypeArguments.First() };
+					}
+				}
+			}
+
+			if (expr.Parent is UnaryOperatorExpression) {
+				var uop = (UnaryOperatorExpression)expr.Parent;
+				switch (uop.Operator) {
+					case UnaryOperatorType.Not:
+						return new [] { resolver.Compilation.FindType(KnownTypeCode.Boolean) };
+						case UnaryOperatorType.Minus:
+						case UnaryOperatorType.Plus:
+						case UnaryOperatorType.Increment:
+						case UnaryOperatorType.Decrement:
+						case UnaryOperatorType.PostIncrement:
+						case UnaryOperatorType.PostDecrement:
+						return new [] { resolver.Compilation.FindType(KnownTypeCode.Int32) };
+				}
+			}
+
+			if (expr.Parent is ConstructorInitializer)
+				return GuessFromConstructorInitializer(resolver, expr);
+
+			if (expr.Parent is NamedExpression) {
+				var rr = resolver.Resolve(expr.Parent);
+				if (!rr.IsError) {
+					return new [] { rr.Type };
+				}
+			}
+
+			return Enumerable.Empty<IType>();
+		}
+		static readonly IType[] emptyTypes = new IType[0];
+		public static AstType GuessAstType(RefactoringContext context, AstNode expr)
+		{
+			var type = GetValidTypes(context.Resolver, expr).ToArray();
+			var typeInference = new TypeInference(context.Compilation);
+			typeInference.Algorithm = TypeInferenceAlgorithm.Improved;
+			var inferedType = typeInference.FindTypeInBounds(type, emptyTypes);
+			if (inferedType.Kind == TypeKind.Unknown)
+				return new PrimitiveType("object");
+			return context.CreateShortType(inferedType);
+		}
+
+		public static IType GuessType(BaseRefactoringContext context, AstNode expr)
+		{
+			if (expr is SimpleType && expr.Role == Roles.TypeArgument) {
+				if (expr.Parent is MemberReferenceExpression || expr.Parent is IdentifierExpression) {
+					var rr = context.Resolve (expr.Parent);
+					var argumentNumber = expr.Parent.GetChildrenByRole (Roles.TypeArgument).TakeWhile (c => c != expr).Count ();
+
+					var mgrr = rr as MethodGroupResolveResult;
+					if (mgrr != null && mgrr.Methods.Any () && mgrr.Methods.First ().TypeArguments.Count > argumentNumber)
+						return mgrr.Methods.First ().TypeParameters[argumentNumber]; 
+				} else if (expr.Parent is MemberType || expr.Parent is SimpleType) {
+					var rr = context.Resolve (expr.Parent);
+					var argumentNumber = expr.Parent.GetChildrenByRole (Roles.TypeArgument).TakeWhile (c => c != expr).Count ();
+					var mgrr = rr as TypeResolveResult;
+					if (mgrr != null &&  mgrr.Type.TypeParameterCount > argumentNumber) {
+						return mgrr.Type.GetDefinition ().TypeParameters[argumentNumber]; 
+					}
+				}
+			}
+
+			var type = GetValidTypes(context.Resolver, expr).ToArray();
+			var typeInference = new TypeInference(context.Compilation);
+			typeInference.Algorithm = TypeInferenceAlgorithm.Improved;
+			var inferedType = typeInference.FindTypeInBounds(type, emptyTypes);
+			return inferedType;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/TypeSystemAstBuilder.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/TypeSystemAstBuilder.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/TypeSystemAstBuilder.cs	(revision 11807)
@@ -0,0 +1,981 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// Converts from type system to the C# AST.
+	/// </summary>
+	public class TypeSystemAstBuilder
+	{
+		readonly CSharpResolver resolver;
+		
+		#region Constructor
+		/// <summary>
+		/// Creates a new TypeSystemAstBuilder.
+		/// </summary>
+		/// <param name="resolver">
+		/// A resolver initialized for the position where the type will be inserted.
+		/// </param>
+		public TypeSystemAstBuilder(CSharpResolver resolver)
+		{
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			this.resolver = resolver;
+			InitProperties();
+		}
+		
+		/// <summary>
+		/// Creates a new TypeSystemAstBuilder.
+		/// </summary>
+		public TypeSystemAstBuilder()
+		{
+			InitProperties();
+		}
+		#endregion
+		
+		#region Properties
+		void InitProperties()
+		{
+			this.ShowAccessibility = true;
+			this.ShowModifiers = true;
+			this.ShowBaseTypes = true;
+			this.ShowTypeParameters = true;
+			this.ShowTypeParameterConstraints = true;
+			this.ShowParameterNames = true;
+			this.ShowConstantValues = true;
+			this.UseAliases = true;
+		}
+		
+		/// <summary>
+		/// Specifies whether the ast builder should add annotations to type references.
+		/// The default value is <c>false</c>.
+		/// </summary>
+		public bool AddAnnotations { get; set; }
+		
+		/// <summary>
+		/// Controls the accessibility modifiers are shown.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowAccessibility { get; set; }
+		
+		/// <summary>
+		/// Controls the non-accessibility modifiers are shown.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowModifiers { get; set; }
+		
+		/// <summary>
+		/// Controls whether base type references are shown.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowBaseTypes { get; set; }
+		
+		/// <summary>
+		/// Controls whether type parameter declarations are shown.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowTypeParameters { get; set; }
+		
+		/// <summary>
+		/// Controls whether constraints on type parameter declarations are shown.
+		/// Has no effect if ShowTypeParameters is false.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowTypeParameterConstraints { get; set; }
+		
+		/// <summary>
+		/// Controls whether the names of parameters are shown.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowParameterNames { get; set; }
+		
+		/// <summary>
+		/// Controls whether to show default values of optional parameters, and the values of constant fields.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool ShowConstantValues { get; set; }
+		
+		/// <summary>
+		/// Controls whether to use fully-qualified type names or short type names.
+		/// The default value is <c>false</c>.
+		/// </summary>
+		public bool AlwaysUseShortTypeNames { get; set; }
+		
+		/// <summary>
+		/// Controls whether to generate a body that throws a <c>System.NotImplementedException</c>.
+		/// The default value is <c>false</c>.
+		/// </summary>
+		public bool GenerateBody { get; set; }
+		
+		/// <summary>
+		/// Controls whether to generate custom events.
+		/// The default value is <c>false</c>.
+		/// </summary>
+		public bool UseCustomEvents { get; set; }
+
+		/// <summary>
+		/// Controls if unbound type argument names are inserted in the ast or not.
+		/// The default value is <c>false</c>.
+		/// </summary>
+		public bool ConvertUnboundTypeArguments { get; set;}
+
+		/// <summary>
+		/// Controls if aliases should be used inside the type name or not.
+		/// The default value is <c>true</c>.
+		/// </summary>
+		public bool UseAliases { get; set;}
+		#endregion
+		
+		#region Convert Type
+		public AstType ConvertType(IType type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			AstType astType = ConvertTypeHelper(type);
+			if (AddAnnotations)
+				astType.AddAnnotation(type);
+			return astType;
+		}
+		
+		public AstType ConvertType(FullTypeName fullTypeName)
+		{
+			if (resolver != null) {
+				foreach (var asm in resolver.Compilation.Assemblies) {
+					var def = asm.GetTypeDefinition(fullTypeName);
+					if (def != null) {
+						return ConvertType(def);
+					}
+				}
+			}
+			TopLevelTypeName top = fullTypeName.TopLevelTypeName;
+			AstType type;
+			if (string.IsNullOrEmpty(top.Namespace)) {
+				type = new SimpleType(top.Name);
+			} else {
+				type = new SimpleType(top.Namespace).MemberType(top.Name);
+			}
+			for (int i = 0; i < fullTypeName.NestingLevel; i++) {
+				type = type.MemberType(fullTypeName.GetNestedTypeName(i));
+			}
+			return type;
+		}
+		
+		AstType ConvertTypeHelper(IType type)
+		{
+			TypeWithElementType typeWithElementType = type as TypeWithElementType;
+			if (typeWithElementType != null) {
+				if (typeWithElementType is PointerType) {
+					return ConvertType(typeWithElementType.ElementType).MakePointerType();
+				} else if (typeWithElementType is ArrayType) {
+					return ConvertType(typeWithElementType.ElementType).MakeArrayType(((ArrayType)type).Dimensions);
+				} else {
+					// e.g. ByReferenceType; not supported as type in C#
+					return ConvertType(typeWithElementType.ElementType);
+				}
+			}
+			ParameterizedType pt = type as ParameterizedType;
+			if (pt != null) {
+				if (pt.Name == "Nullable" && pt.Namespace == "System" && pt.TypeParameterCount == 1) {
+					return ConvertType(pt.TypeArguments[0]).MakeNullableType();
+				}
+				return ConvertTypeHelper(pt.GetDefinition(), pt.TypeArguments);
+			}
+			ITypeDefinition typeDef = type as ITypeDefinition;
+			if (typeDef != null) {
+				if (typeDef.TypeParameterCount > 0) {
+					// Unbound type
+					IType[] typeArguments = new IType[typeDef.TypeParameterCount];
+					for (int i = 0; i < typeArguments.Length; i++) {
+						typeArguments[i] = SpecialType.UnboundTypeArgument;
+					}
+					return ConvertTypeHelper(typeDef, typeArguments);
+				} else {
+					return ConvertTypeHelper(typeDef, EmptyList<IType>.Instance);
+				}
+			}
+			return new SimpleType(type.Name);
+		}
+		
+		AstType ConvertTypeHelper(ITypeDefinition typeDef, IList<IType> typeArguments)
+		{
+			Debug.Assert(typeArguments.Count >= typeDef.TypeParameterCount);
+			
+			string keyword = KnownTypeReference.GetCSharpNameByTypeCode(typeDef.KnownTypeCode);
+			if (keyword != null)
+				return new PrimitiveType(keyword);
+			
+			// The number of type parameters belonging to outer classes
+			int outerTypeParameterCount;
+			if (typeDef.DeclaringType != null)
+				outerTypeParameterCount = typeDef.DeclaringType.TypeParameterCount;
+			else
+				outerTypeParameterCount = 0;
+			
+			if (resolver != null) {
+				// Look if there's an alias to the target type
+				if (UseAliases) {
+					for (ResolvedUsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) {
+						foreach (var pair in usingScope.UsingAliases) {
+							if (pair.Value is TypeResolveResult) {
+								if (TypeMatches(pair.Value.Type, typeDef, typeArguments))
+									return new SimpleType(pair.Key);
+							}
+						}
+					}
+				}
+				
+				IList<IType> localTypeArguments;
+				if (typeDef.TypeParameterCount > outerTypeParameterCount) {
+					localTypeArguments = new IType[typeDef.TypeParameterCount - outerTypeParameterCount];
+					for (int i = 0; i < localTypeArguments.Count; i++) {
+						localTypeArguments[i] = typeArguments[outerTypeParameterCount + i];
+					}
+				} else {
+					localTypeArguments = EmptyList<IType>.Instance;
+				}
+				ResolveResult rr = resolver.ResolveSimpleName(typeDef.Name, localTypeArguments);
+				TypeResolveResult trr = rr as TypeResolveResult;
+				if (trr != null || (localTypeArguments.Count == 0 && resolver.IsVariableReferenceWithSameType(rr, typeDef.Name, out trr))) {
+					if (!trr.IsError && TypeMatches(trr.Type, typeDef, typeArguments)) {
+						// We can use the short type name
+						SimpleType shortResult = new SimpleType(typeDef.Name);
+						AddTypeArguments(shortResult, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
+						return shortResult;
+					}
+				}
+			}
+			
+			if (AlwaysUseShortTypeNames) {
+				var shortResult = new SimpleType(typeDef.Name);
+				AddTypeArguments(shortResult, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
+				return shortResult;
+			}
+			MemberType result = new MemberType();
+			if (typeDef.DeclaringTypeDefinition != null) {
+				// Handle nested types
+				result.Target = ConvertTypeHelper(typeDef.DeclaringTypeDefinition, typeArguments);
+			} else {
+				// Handle top-level types
+				if (string.IsNullOrEmpty(typeDef.Namespace)) {
+					result.Target = new SimpleType("global");
+					result.IsDoubleColon = true;
+				} else {
+					result.Target = ConvertNamespace(typeDef.Namespace);
+				}
+			}
+			result.MemberName = typeDef.Name;
+			AddTypeArguments(result, typeDef, typeArguments, outerTypeParameterCount, typeDef.TypeParameterCount);
+			return result;
+		}
+		
+		/// <summary>
+		/// Gets whether 'type' is the same as 'typeDef' parameterized with the given type arguments.
+		/// </summary>
+		bool TypeMatches(IType type, ITypeDefinition typeDef, IList<IType> typeArguments)
+		{
+			if (typeDef.TypeParameterCount == 0) {
+				return typeDef.Equals(type);
+			} else {
+				if (!typeDef.Equals(type.GetDefinition()))
+					return false;
+				ParameterizedType pt = type as ParameterizedType;
+				if (pt == null) {
+					return typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument);
+				}
+				var ta = pt.TypeArguments;
+				for (int i = 0; i < ta.Count; i++) {
+					if (!ta[i].Equals(typeArguments[i]))
+						return false;
+				}
+				return true;
+			}
+		}
+		
+		/// <summary>
+		/// Adds type arguments to the result type.
+		/// </summary>
+		/// <param name="result">The result AST node (a SimpleType or MemberType)</param>
+		/// <param name="typeDef">The type definition that owns the type parameters</param>
+		/// <param name="typeArguments">The list of type arguments</param>
+		/// <param name="startIndex">Index of first type argument to add</param>
+		/// <param name="endIndex">Index after last type argument to add</param>
+		void AddTypeArguments(AstType result, ITypeDefinition typeDef, IList<IType> typeArguments, int startIndex, int endIndex)
+		{
+			Debug.Assert(endIndex <= typeDef.TypeParameterCount);
+			for (int i = startIndex; i < endIndex; i++) {
+				if (ConvertUnboundTypeArguments && typeArguments[i].Kind == TypeKind.UnboundTypeArgument) {
+					result.AddChild(new SimpleType(typeDef.TypeParameters[i].Name), Roles.TypeArgument);
+				} else {
+					result.AddChild(ConvertType(typeArguments[i]), Roles.TypeArgument);
+				}
+			}
+		}
+		
+		public AstType ConvertNamespace(string namespaceName)
+		{
+			if (resolver != null) {
+				// Look if there's an alias to the target namespace
+				if (UseAliases) {
+					for (ResolvedUsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) {
+						foreach (var pair in usingScope.UsingAliases) {
+							NamespaceResolveResult nrr = pair.Value as NamespaceResolveResult;
+							if (nrr != null && nrr.NamespaceName == namespaceName)
+								return new SimpleType(pair.Key);
+						}
+					}
+				}
+			}
+			
+			int pos = namespaceName.LastIndexOf('.');
+			if (pos < 0) {
+				if (IsValidNamespace(namespaceName)) {
+					return new SimpleType(namespaceName);
+				} else {
+					return new MemberType {
+						Target = new SimpleType("global"),
+						IsDoubleColon = true,
+						MemberName = namespaceName
+					};
+				}
+			} else {
+				string parentNamespace = namespaceName.Substring(0, pos);
+				string localNamespace = namespaceName.Substring(pos + 1);
+				return new MemberType {
+					Target = ConvertNamespace(parentNamespace),
+					MemberName = localNamespace
+				};
+			}
+		}
+		
+		bool IsValidNamespace(string firstNamespacePart)
+		{
+			if (resolver == null)
+				return true; // just assume namespaces are valid if we don't have a resolver
+			NamespaceResolveResult nrr = resolver.ResolveSimpleName(firstNamespacePart, EmptyList<IType>.Instance) as NamespaceResolveResult;
+			return nrr != null && !nrr.IsError && nrr.NamespaceName == firstNamespacePart;
+		}
+		#endregion
+		
+		#region Convert Attribute
+		public Attribute ConvertAttribute(IAttribute attribute)
+		{
+			Attribute attr = new Attribute();
+			attr.Type = ConvertType(attribute.AttributeType);
+			SimpleType st = attr.Type as SimpleType;
+			MemberType mt = attr.Type as MemberType;
+			if (st != null && st.Identifier.EndsWith("Attribute", StringComparison.Ordinal)) {
+				st.Identifier = st.Identifier.Substring(0, st.Identifier.Length - 9);
+			} else if (mt != null && mt.MemberName.EndsWith("Attribute", StringComparison.Ordinal)) {
+				mt.MemberName = mt.MemberName.Substring(0, mt.MemberName.Length - 9);
+			}
+			foreach (ResolveResult arg in attribute.PositionalArguments) {
+				attr.Arguments.Add(ConvertConstantValue(arg));
+			}
+			foreach (var pair in attribute.NamedArguments) {
+				attr.Arguments.Add(new NamedExpression(pair.Key.Name, ConvertConstantValue(pair.Value)));
+			}
+			return attr;
+		}
+		#endregion
+		
+		#region Convert Constant Value
+		public Expression ConvertConstantValue(ResolveResult rr)
+		{
+			if (rr == null)
+				throw new ArgumentNullException("rr");
+			if (rr is ConversionResolveResult) {
+				// unpack ConversionResolveResult if necessary
+				// (e.g. a boxing conversion or string->object reference conversion)
+				rr = ((ConversionResolveResult)rr).Input;
+			}
+			
+			if (rr is TypeOfResolveResult) {
+				return new TypeOfExpression(ConvertType(rr.Type));
+			} else if (rr is ArrayCreateResolveResult) {
+				ArrayCreateResolveResult acrr = (ArrayCreateResolveResult)rr;
+				ArrayCreateExpression ace = new ArrayCreateExpression();
+				ace.Type = ConvertType(acrr.Type);
+				ComposedType composedType = ace.Type as ComposedType;
+				if (composedType != null) {
+					composedType.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers);
+					if (!composedType.HasNullableSpecifier && composedType.PointerRank == 0)
+						ace.Type = composedType.BaseType;
+				}
+				
+				if (acrr.SizeArguments != null && acrr.InitializerElements == null) {
+					ace.AdditionalArraySpecifiers.FirstOrNullObject().Remove();
+					ace.Arguments.AddRange(acrr.SizeArguments.Select(ConvertConstantValue));
+				}
+				if (acrr.InitializerElements != null) {
+					ArrayInitializerExpression initializer = new ArrayInitializerExpression();
+					initializer.Elements.AddRange(acrr.InitializerElements.Select(ConvertConstantValue));
+					ace.Initializer = initializer;
+				}
+				return ace;
+			} else if (rr.IsCompileTimeConstant) {
+				return ConvertConstantValue(rr.Type, rr.ConstantValue);
+			} else {
+				return new ErrorExpression();
+			}
+		}
+		
+		public Expression ConvertConstantValue(IType type, object constantValue)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			if (constantValue == null) {
+				if (type.IsReferenceType == true)
+					return new NullReferenceExpression();
+				else
+					return new DefaultValueExpression(ConvertType(type));
+			} else if (type.Kind == TypeKind.Enum) {
+				return ConvertEnumValue(type, (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, constantValue, false));
+			} else {
+				return new PrimitiveExpression(constantValue);
+			}
+		}
+		
+		bool IsFlagsEnum(ITypeDefinition type)
+		{
+			IType flagsAttributeType = type.Compilation.FindType(typeof(System.FlagsAttribute));
+			return type.GetAttribute(flagsAttributeType) != null;
+		}
+		
+		Expression ConvertEnumValue(IType type, long val)
+		{
+			ITypeDefinition enumDefinition = type.GetDefinition();
+			TypeCode enumBaseTypeCode = ReflectionHelper.GetTypeCode(enumDefinition.EnumUnderlyingType);
+			foreach (IField field in enumDefinition.Fields) {
+				if (field.IsConst && object.Equals(CSharpPrimitiveCast.Cast(TypeCode.Int64, field.ConstantValue, false), val))
+					return ConvertType(type).Member(field.Name);
+			}
+			if (IsFlagsEnum(enumDefinition)) {
+				long enumValue = val;
+				Expression expr = null;
+				long negatedEnumValue = ~val;
+				// limit negatedEnumValue to the appropriate range
+				switch (enumBaseTypeCode) {
+					case TypeCode.Byte:
+					case TypeCode.SByte:
+						negatedEnumValue &= byte.MaxValue;
+						break;
+					case TypeCode.Int16:
+					case TypeCode.UInt16:
+						negatedEnumValue &= ushort.MaxValue;
+						break;
+					case TypeCode.Int32:
+					case TypeCode.UInt32:
+						negatedEnumValue &= uint.MaxValue;
+						break;
+				}
+				Expression negatedExpr = null;
+				foreach (IField field in enumDefinition.Fields.Where(fld => fld.IsConst)) {
+					long fieldValue = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, field.ConstantValue, false);
+					if (fieldValue == 0)
+						continue;	// skip None enum value
+
+					if ((fieldValue & enumValue) == fieldValue) {
+						var fieldExpression = ConvertType(type).Member(field.Name);
+						if (expr == null)
+							expr = fieldExpression;
+						else
+							expr = new BinaryOperatorExpression(expr, BinaryOperatorType.BitwiseOr, fieldExpression);
+
+						enumValue &= ~fieldValue;
+					}
+					if ((fieldValue & negatedEnumValue) == fieldValue) {
+						var fieldExpression = ConvertType(type).Member(field.Name);
+						if (negatedExpr == null)
+							negatedExpr = fieldExpression;
+						else
+							negatedExpr = new BinaryOperatorExpression(negatedExpr, BinaryOperatorType.BitwiseOr, fieldExpression);
+
+						negatedEnumValue &= ~fieldValue;
+					}
+				}
+				if (enumValue == 0 && expr != null) {
+					if (!(negatedEnumValue == 0 && negatedExpr != null && negatedExpr.Descendants.Count() < expr.Descendants.Count())) {
+						return expr;
+					}
+				}
+				if (negatedEnumValue == 0 && negatedExpr != null) {
+					return new UnaryOperatorExpression(UnaryOperatorType.BitNot, negatedExpr);
+				}
+			}
+			return new PrimitiveExpression(CSharpPrimitiveCast.Cast(enumBaseTypeCode, val, false)).CastTo(ConvertType(type));
+		}
+		
+		#endregion
+		
+		#region Convert Parameter
+		public ParameterDeclaration ConvertParameter(IParameter parameter)
+		{
+			if (parameter == null)
+				throw new ArgumentNullException("parameter");
+			ParameterDeclaration decl = new ParameterDeclaration();
+			if (parameter.IsRef) {
+				decl.ParameterModifier = ParameterModifier.Ref;
+			} else if (parameter.IsOut) {
+				decl.ParameterModifier = ParameterModifier.Out;
+			} else if (parameter.IsParams) {
+				decl.ParameterModifier = ParameterModifier.Params;
+			}
+			decl.Type = ConvertType(parameter.Type);
+			if (this.ShowParameterNames) {
+				decl.Name = parameter.Name;
+			}
+			if (parameter.IsOptional && this.ShowConstantValues) {
+				decl.DefaultExpression = ConvertConstantValue(parameter.Type, parameter.ConstantValue);
+			}
+			return decl;
+		}
+		#endregion
+		
+		#region Convert Entity
+		public AstNode ConvertSymbol(ISymbol symbol)
+		{
+			if (symbol == null)
+				throw new ArgumentNullException("symbol");
+			switch (symbol.SymbolKind) {
+				case SymbolKind.Namespace:
+					return ConvertNamespaceDeclaration((INamespace)symbol);
+				case SymbolKind.Variable:
+					return ConvertVariable((IVariable)symbol);
+				case SymbolKind.Parameter:
+					return ConvertParameter((IParameter)symbol);
+				case SymbolKind.TypeParameter:
+					return ConvertTypeParameter((ITypeParameter)symbol);
+				default:
+					IEntity entity = symbol as IEntity;
+					if (entity != null)
+						return ConvertEntity(entity);
+					throw new ArgumentException("Invalid value for SymbolKind: " + symbol.SymbolKind);
+			}
+		}
+		
+		public EntityDeclaration ConvertEntity(IEntity entity)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			switch (entity.SymbolKind) {
+				case SymbolKind.TypeDefinition:
+					return ConvertTypeDefinition((ITypeDefinition)entity);
+				case SymbolKind.Field:
+					return ConvertField((IField)entity);
+				case SymbolKind.Property:
+					return ConvertProperty((IProperty)entity);
+				case SymbolKind.Indexer:
+					return ConvertIndexer((IProperty)entity);
+				case SymbolKind.Event:
+					return ConvertEvent((IEvent)entity);
+				case SymbolKind.Method:
+					return ConvertMethod((IMethod)entity);
+				case SymbolKind.Operator:
+					return ConvertOperator((IMethod)entity);
+				case SymbolKind.Constructor:
+					return ConvertConstructor((IMethod)entity);
+				case SymbolKind.Destructor:
+					return ConvertDestructor((IMethod)entity);
+				case SymbolKind.Accessor:
+					IMethod accessor = (IMethod)entity;
+					return ConvertAccessor(accessor, accessor.AccessorOwner != null ? accessor.AccessorOwner.Accessibility : Accessibility.None);
+				default:
+					throw new ArgumentException("Invalid value for SymbolKind: " + entity.SymbolKind);
+			}
+		}
+		
+		EntityDeclaration ConvertTypeDefinition(ITypeDefinition typeDefinition)
+		{
+			Modifiers modifiers = Modifiers.None;
+			if (this.ShowAccessibility) {
+				modifiers |= ModifierFromAccessibility(typeDefinition.Accessibility);
+			}
+			if (this.ShowModifiers) {
+				if (typeDefinition.IsStatic) {
+					modifiers |= Modifiers.Static;
+				} else if (typeDefinition.IsAbstract) {
+					modifiers |= Modifiers.Abstract;
+				} else if (typeDefinition.IsSealed) {
+					modifiers |= Modifiers.Sealed;
+				}
+				if (typeDefinition.IsShadowing) {
+					modifiers |= Modifiers.New;
+				}
+			}
+			
+			ClassType classType;
+			switch (typeDefinition.Kind) {
+				case TypeKind.Struct:
+					classType = ClassType.Struct;
+					modifiers &= ~Modifiers.Sealed;
+					break;
+				case TypeKind.Enum:
+					classType = ClassType.Enum;
+					modifiers &= ~Modifiers.Sealed;
+					break;
+				case TypeKind.Interface:
+					classType = ClassType.Interface;
+					modifiers &= ~Modifiers.Abstract;
+					break;
+				case TypeKind.Delegate:
+					IMethod invoke = typeDefinition.GetDelegateInvokeMethod();
+					if (invoke != null) {
+						return ConvertDelegate(invoke, modifiers);
+					} else {
+						goto default;
+					}
+				default:
+					classType = ClassType.Class;
+					break;
+			}
+			
+			var decl = new TypeDeclaration();
+			decl.ClassType = classType;
+			decl.Modifiers = modifiers;
+			decl.Name = typeDefinition.Name;
+			
+			int outerTypeParameterCount = (typeDefinition.DeclaringTypeDefinition == null) ? 0 : typeDefinition.DeclaringTypeDefinition.TypeParameterCount;
+			
+			if (this.ShowTypeParameters) {
+				foreach (ITypeParameter tp in typeDefinition.TypeParameters.Skip(outerTypeParameterCount)) {
+					decl.TypeParameters.Add(ConvertTypeParameter(tp));
+				}
+			}
+			
+			if (this.ShowBaseTypes) {
+				foreach (IType baseType in typeDefinition.DirectBaseTypes) {
+					decl.BaseTypes.Add(ConvertType(baseType));
+				}
+			}
+			
+			if (this.ShowTypeParameters && this.ShowTypeParameterConstraints) {
+				foreach (ITypeParameter tp in typeDefinition.TypeParameters) {
+					var constraint = ConvertTypeParameterConstraint(tp);
+					if (constraint != null)
+						decl.Constraints.Add(constraint);
+				}
+			}
+			return decl;
+		}
+		
+		DelegateDeclaration ConvertDelegate(IMethod invokeMethod, Modifiers modifiers)
+		{
+			ITypeDefinition d = invokeMethod.DeclaringTypeDefinition;
+			
+			DelegateDeclaration decl = new DelegateDeclaration();
+			decl.Modifiers = modifiers & ~Modifiers.Sealed;
+			decl.ReturnType = ConvertType(invokeMethod.ReturnType);
+			decl.Name = d.Name;
+			
+			if (this.ShowTypeParameters) {
+				foreach (ITypeParameter tp in d.TypeParameters) {
+					decl.TypeParameters.Add(ConvertTypeParameter(tp));
+				}
+			}
+			
+			foreach (IParameter p in invokeMethod.Parameters) {
+				decl.Parameters.Add(ConvertParameter(p));
+			}
+			
+			if (this.ShowTypeParameters && this.ShowTypeParameterConstraints) {
+				foreach (ITypeParameter tp in d.TypeParameters) {
+					var constraint = ConvertTypeParameterConstraint(tp);
+					if (constraint != null)
+						decl.Constraints.Add(constraint);
+				}
+			}
+			return decl;
+		}
+		
+		FieldDeclaration ConvertField(IField field)
+		{
+			FieldDeclaration decl = new FieldDeclaration();
+			if (ShowModifiers) {
+				Modifiers m = GetMemberModifiers(field);
+				if (field.IsConst) {
+					m &= ~Modifiers.Static;
+					m |= Modifiers.Const;
+				} else if (field.IsReadOnly) {
+					m |= Modifiers.Readonly;
+				} else if (field.IsVolatile) {
+					m |= Modifiers.Volatile;
+				}
+				decl.Modifiers = m;
+			}
+			decl.ReturnType = ConvertType(field.ReturnType);
+			Expression initializer = null;
+			if (field.IsConst && this.ShowConstantValues)
+				initializer = ConvertConstantValue(field.Type, field.ConstantValue);
+			decl.Variables.Add(new VariableInitializer(field.Name, initializer));
+			return decl;
+		}
+		
+		BlockStatement GenerateBodyBlock()
+		{
+			if (GenerateBody) {
+				return new BlockStatement {
+					new ThrowStatement(new ObjectCreateExpression(ConvertType(new TopLevelTypeName("System", "NotImplementedException", 0))))
+				};
+			} else {
+				return BlockStatement.Null;
+			}
+		}
+		
+		Accessor ConvertAccessor(IMethod accessor, Accessibility ownerAccessibility)
+		{
+			if (accessor == null)
+				return Accessor.Null;
+			Accessor decl = new Accessor();
+			if (this.ShowAccessibility && accessor.Accessibility != ownerAccessibility)
+				decl.Modifiers = ModifierFromAccessibility(accessor.Accessibility);
+			decl.Body = GenerateBodyBlock();
+			return decl;
+		}
+		
+		PropertyDeclaration ConvertProperty(IProperty property)
+		{
+			PropertyDeclaration decl = new PropertyDeclaration();
+			decl.Modifiers = GetMemberModifiers(property);
+			decl.ReturnType = ConvertType(property.ReturnType);
+			decl.Name = property.Name;
+			decl.Getter = ConvertAccessor(property.Getter, property.Accessibility);
+			decl.Setter = ConvertAccessor(property.Setter, property.Accessibility);
+			return decl;
+		}
+		
+		IndexerDeclaration ConvertIndexer(IProperty indexer)
+		{
+			IndexerDeclaration decl = new IndexerDeclaration();
+			decl.Modifiers = GetMemberModifiers(indexer);
+			decl.ReturnType = ConvertType(indexer.ReturnType);
+			foreach (IParameter p in indexer.Parameters) {
+				decl.Parameters.Add(ConvertParameter(p));
+			}
+			decl.Getter = ConvertAccessor(indexer.Getter, indexer.Accessibility);
+			decl.Setter = ConvertAccessor(indexer.Setter, indexer.Accessibility);
+			return decl;
+		}
+		
+		EntityDeclaration ConvertEvent(IEvent ev)
+		{
+			if (this.UseCustomEvents) {
+				CustomEventDeclaration decl = new CustomEventDeclaration();
+				decl.Modifiers = GetMemberModifiers(ev);
+				decl.ReturnType = ConvertType(ev.ReturnType);
+				decl.Name = ev.Name;
+				decl.AddAccessor    = ConvertAccessor(ev.AddAccessor, ev.Accessibility);
+				decl.RemoveAccessor = ConvertAccessor(ev.RemoveAccessor, ev.Accessibility);
+				return decl;
+			} else {
+				EventDeclaration decl = new EventDeclaration();
+				decl.Modifiers = GetMemberModifiers(ev);
+				decl.ReturnType = ConvertType(ev.ReturnType);
+				decl.Variables.Add(new VariableInitializer(ev.Name));
+				return decl;
+			}
+		}
+		
+		MethodDeclaration ConvertMethod(IMethod method)
+		{
+			MethodDeclaration decl = new MethodDeclaration();
+			decl.Modifiers = GetMemberModifiers(method);
+			if (method.IsAsync && ShowModifiers)
+				decl.Modifiers |= Modifiers.Async;
+			decl.ReturnType = ConvertType(method.ReturnType);
+			decl.Name = method.Name;
+			
+			if (this.ShowTypeParameters) {
+				foreach (ITypeParameter tp in method.TypeParameters) {
+					decl.TypeParameters.Add(ConvertTypeParameter(tp));
+				}
+			}
+			
+			foreach (IParameter p in method.Parameters) {
+				decl.Parameters.Add(ConvertParameter(p));
+			}
+			if (method.IsExtensionMethod && method.ReducedFrom == null && decl.Parameters.Any() && decl.Parameters.First().ParameterModifier == ParameterModifier.None)
+				decl.Parameters.First().ParameterModifier = ParameterModifier.This;
+			
+			if (this.ShowTypeParameters && this.ShowTypeParameterConstraints && !method.IsOverride && !method.IsExplicitInterfaceImplementation) {
+				foreach (ITypeParameter tp in method.TypeParameters) {
+					var constraint = ConvertTypeParameterConstraint(tp);
+					if (constraint != null)
+						decl.Constraints.Add(constraint);
+				}
+			}
+			decl.Body = GenerateBodyBlock();
+			return decl;
+		}
+		
+		EntityDeclaration ConvertOperator(IMethod op)
+		{
+			OperatorType? opType = OperatorDeclaration.GetOperatorType(op.Name);
+			if (opType == null)
+				return ConvertMethod(op);
+			
+			OperatorDeclaration decl = new OperatorDeclaration();
+			decl.Modifiers = GetMemberModifiers(op);
+			decl.OperatorType = opType.Value;
+			decl.ReturnType = ConvertType(op.ReturnType);
+			foreach (IParameter p in op.Parameters) {
+				decl.Parameters.Add(ConvertParameter(p));
+			}
+			decl.Body = GenerateBodyBlock();
+			return decl;
+		}
+		
+		ConstructorDeclaration ConvertConstructor(IMethod ctor)
+		{
+			ConstructorDeclaration decl = new ConstructorDeclaration();
+			decl.Modifiers = GetMemberModifiers(ctor);
+			if (ctor.DeclaringTypeDefinition != null)
+				decl.Name = ctor.DeclaringTypeDefinition.Name;
+			foreach (IParameter p in ctor.Parameters) {
+				decl.Parameters.Add(ConvertParameter(p));
+			}
+			decl.Body = GenerateBodyBlock();
+			return decl;
+		}
+		
+		DestructorDeclaration ConvertDestructor(IMethod dtor)
+		{
+			DestructorDeclaration decl = new DestructorDeclaration();
+			if (dtor.DeclaringTypeDefinition != null)
+				decl.Name = dtor.DeclaringTypeDefinition.Name;
+			decl.Body = GenerateBodyBlock();
+			return decl;
+		}
+		#endregion
+		
+		#region Convert Modifiers
+		public static Modifiers ModifierFromAccessibility(Accessibility accessibility)
+		{
+			switch (accessibility) {
+				case Accessibility.Private:
+					return Modifiers.Private;
+				case Accessibility.Public:
+					return Modifiers.Public;
+				case Accessibility.Protected:
+					return Modifiers.Protected;
+				case Accessibility.Internal:
+					return Modifiers.Internal;
+				case Accessibility.ProtectedOrInternal:
+				case Accessibility.ProtectedAndInternal:
+					return Modifiers.Protected | Modifiers.Internal;
+				default:
+					return Modifiers.None;
+			}
+		}
+		
+		Modifiers GetMemberModifiers(IMember member)
+		{
+			bool isInterfaceMember = member.DeclaringType.Kind == TypeKind.Interface;
+			Modifiers m = Modifiers.None;
+			if (this.ShowAccessibility && !isInterfaceMember) {
+				m |= ModifierFromAccessibility(member.Accessibility);
+			}
+			if (this.ShowModifiers) {
+				if (member.IsStatic) {
+					m |= Modifiers.Static;
+				} else {
+					if (member.IsAbstract && !isInterfaceMember)
+						m |= Modifiers.Abstract;
+					if (member.IsOverride)
+						m |= Modifiers.Override;
+					if (member.IsVirtual && !member.IsAbstract && !member.IsOverride)
+						m |= Modifiers.Virtual;
+					if (member.IsSealed)
+						m |= Modifiers.Sealed;
+				}
+				if (member.IsShadowing)
+					m |= Modifiers.New;
+			}
+			return m;
+		}
+		#endregion
+		
+		#region Convert Type Parameter
+		TypeParameterDeclaration ConvertTypeParameter(ITypeParameter tp)
+		{
+			TypeParameterDeclaration decl = new TypeParameterDeclaration();
+			decl.Variance = tp.Variance;
+			decl.Name = tp.Name;
+			return decl;
+		}
+		
+		Constraint ConvertTypeParameterConstraint(ITypeParameter tp)
+		{
+			if (!tp.HasDefaultConstructorConstraint && !tp.HasReferenceTypeConstraint && !tp.HasValueTypeConstraint && tp.DirectBaseTypes.All(IsObjectOrValueType)) {
+				return null;
+			}
+			Constraint c = new Constraint();
+			c.TypeParameter = new SimpleType (tp.Name);
+			if (tp.HasReferenceTypeConstraint) {
+				c.BaseTypes.Add(new PrimitiveType("class"));
+			} else if (tp.HasValueTypeConstraint) {
+				c.BaseTypes.Add(new PrimitiveType("struct"));
+			}
+			foreach (IType t in tp.DirectBaseTypes) {
+				if (!IsObjectOrValueType(t))
+					c.BaseTypes.Add(ConvertType(t));
+			}
+			if (tp.HasDefaultConstructorConstraint) {
+				c.BaseTypes.Add(new PrimitiveType("new"));
+			}
+			return c;
+		}
+		
+		static bool IsObjectOrValueType(IType type)
+		{
+			ITypeDefinition d = type.GetDefinition();
+			return d != null && (d.KnownTypeCode == KnownTypeCode.Object || d.KnownTypeCode == KnownTypeCode.ValueType);
+		}
+		#endregion
+		
+		#region Convert Variable
+		public VariableDeclarationStatement ConvertVariable(IVariable v)
+		{
+			VariableDeclarationStatement decl = new VariableDeclarationStatement();
+			decl.Modifiers = v.IsConst ? Modifiers.Const : Modifiers.None;
+			decl.Type = ConvertType(v.Type);
+			Expression initializer = null;
+			if (v.IsConst)
+				initializer = ConvertConstantValue(v.Type, v.ConstantValue);
+			decl.Variables.Add(new VariableInitializer(v.Name, initializer));
+			return decl;
+		}
+		#endregion
+		
+		NamespaceDeclaration ConvertNamespaceDeclaration(INamespace ns)
+		{
+			return new NamespaceDeclaration(ns.FullName);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/UsingHelper.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/UsingHelper.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/UsingHelper.cs	(revision 11807)
@@ -0,0 +1,201 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	/// <summary>
+	/// Helper methods for managing using declarations.
+	/// </summary>
+	public class UsingHelper
+	{
+		/// <summary>
+		/// Inserts 'using ns;' in the current scope, and then removes all explicit
+		/// usages of ns that were made redundant by the new using.
+		/// </summary>
+		public static void InsertUsingAndRemoveRedundantNamespaceUsage(RefactoringContext context, Script script, string ns)
+		{
+			InsertUsing(context, script, new UsingDeclaration(ns));
+			// TODO: remove the usages that were made redundant
+		}
+		
+		/// <summary>
+		/// Inserts 'newUsing' in the current scope.
+		/// This method will try to insert new usings in the correct position (depending on
+		/// where the existing usings are; and maintaining the sort order).
+		/// </summary>
+		public static void InsertUsing(RefactoringContext context, Script script, AstNode newUsing)
+		{
+			UsingInfo newUsingInfo = new UsingInfo(newUsing, context);
+			AstNode enclosingNamespace = context.GetNode<NamespaceDeclaration>() ?? context.RootNode;
+			// Find nearest enclosing parent that has usings:
+			AstNode usingParent = enclosingNamespace;
+			while (usingParent != null && !usingParent.Children.OfType<UsingDeclaration>().Any())
+				usingParent = usingParent.Parent;
+			if (usingParent == null) {
+				// No existing usings at all -> use the default location
+				if (script.FormattingOptions.UsingPlacement == UsingPlacement.TopOfFile) {
+					usingParent = context.RootNode;
+				} else {
+					usingParent = enclosingNamespace;
+				}
+			}
+			// Find the main block of using declarations in the chosen scope:
+			AstNode blockStart = usingParent.Children.FirstOrDefault(IsUsingDeclaration);
+			AstNode insertionPoint;
+			bool insertAfter = false;
+			if (blockStart == null) {
+				// no using declarations in the file
+				Debug.Assert(SyntaxTree.MemberRole == NamespaceDeclaration.MemberRole);
+				insertionPoint = usingParent.GetChildrenByRole(SyntaxTree.MemberRole).SkipWhile(CanAppearBeforeUsings).FirstOrDefault();
+			} else {
+				insertionPoint = blockStart;
+				while (IsUsingFollowing (ref insertionPoint) && newUsingInfo.CompareTo(new UsingInfo(insertionPoint, context)) > 0)
+					insertionPoint = insertionPoint.NextSibling;
+				if (!IsUsingDeclaration(insertionPoint)) {
+					// Insert after last using instead of before next node
+					// This affects where empty lines get placed.
+					insertionPoint = insertionPoint.PrevSibling;
+					insertAfter = true;
+				}
+			}
+			if (insertionPoint != null) {
+				if (insertAfter)
+					script.InsertAfter(insertionPoint, newUsing);
+				else
+					script.InsertBefore(insertionPoint, newUsing);
+			}
+		}
+
+		static bool IsUsingFollowing(ref AstNode insertionPoint)
+		{
+			var node = insertionPoint;
+			while (node != null && node.Role == Roles.NewLine)
+				node = node.NextSibling;
+			if (IsUsingDeclaration(node)) {
+				insertionPoint = node;
+				return true;
+			}
+			return false;
+		}
+		
+		static bool IsUsingDeclaration(AstNode node)
+		{
+			return node is UsingDeclaration || node is UsingAliasDeclaration;
+		}
+		
+		static bool CanAppearBeforeUsings(AstNode node)
+		{
+			if (node is ExternAliasDeclaration)
+				return true;
+			if (node is PreProcessorDirective)
+				return true;
+			if (node is NewLineNode)
+				return true;
+			Comment c = node as Comment;
+			if (c != null)
+				return !c.IsDocumentation;
+			return false;
+		}
+		
+		/// <summary>
+		/// Sorts the specified usings.
+		/// </summary>
+		public static IEnumerable<AstNode> SortUsingBlock(IEnumerable<AstNode> nodes, BaseRefactoringContext context)
+		{
+			var infos = nodes.Select(_ => new UsingInfo(_, context));
+			var orderedInfos = infos.OrderBy(_ => _);
+			var orderedNodes = orderedInfos.Select(_ => _.Node);
+
+			return orderedNodes;
+		}
+
+
+		private sealed class UsingInfo : IComparable<UsingInfo>
+		{
+			public AstNode Node;
+
+			public string Alias;
+			public string Name;
+
+			public bool IsAlias;
+			public bool HasTypesFromOtherAssemblies;
+			public bool IsSystem;
+
+			public UsingInfo(AstNode node, BaseRefactoringContext context)
+			{
+				var importAndAlias = GetImportAndAlias(node);
+
+				Node = node;
+
+				Alias = importAndAlias.Item2;
+				Name = importAndAlias.Item1.ToString();
+
+				IsAlias = Alias != null;
+
+				ResolveResult rr;
+				if (node.Ancestors.Contains(context.RootNode)) {
+					rr = context.Resolve(importAndAlias.Item1);
+				} else {
+					// It's possible that we're looking at a new using that
+					// isn't part of the AST.
+					var resolver = new CSharpAstResolver(new CSharpResolver(context.Compilation), node);
+					rr = resolver.Resolve(importAndAlias.Item1);
+				}
+				
+				var nrr = rr as NamespaceResolveResult;
+				HasTypesFromOtherAssemblies = nrr != null && nrr.Namespace.ContributingAssemblies.Any(a => !a.IsMainAssembly);
+
+				IsSystem = HasTypesFromOtherAssemblies && (Name == "System" || Name.StartsWith("System.", StringComparison.Ordinal));
+			}
+
+			private static Tuple<AstType, string> GetImportAndAlias(AstNode node)
+			{
+				var plainUsing = node as UsingDeclaration;
+				if (plainUsing != null)
+					return Tuple.Create(plainUsing.Import, (string)null);
+				
+				var aliasUsing = node as UsingAliasDeclaration;
+				if (aliasUsing != null)
+					return Tuple.Create(aliasUsing.Import, aliasUsing.Alias);
+
+				throw new InvalidOperationException(string.Format("Invalid using node: {0}", node));
+			}
+
+			public int CompareTo(UsingInfo y)
+			{
+				UsingInfo x = this;
+				if (x.IsAlias != y.IsAlias)
+					return x.IsAlias ? 1 : -1;
+				if (x.IsAlias)
+					return StringComparer.OrdinalIgnoreCase.Compare(x.Alias, y.Alias);
+//				if (x.HasTypesFromOtherAssemblies != y.HasTypesFromOtherAssemblies)
+//					return x.HasTypesFromOtherAssemblies ? -1 : 1;
+				if (x.IsSystem != y.IsSystem)
+					return x.IsSystem ? -1 : 1;
+				return StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/VariableReferenceGraph.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/VariableReferenceGraph.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/VariableReferenceGraph.cs	(revision 11807)
@@ -0,0 +1,575 @@
+﻿// 
+// VariableReferenceGraph.cs
+// 
+// Author:
+//      Mansheng Yang <lightyang0@gmail.com>
+// 
+// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com>
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Analysis;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using System.Threading;
+
+namespace ICSharpCode.NRefactory.CSharp.Refactoring
+{
+	class VariableReferenceNode
+	{
+		public IList<AstNode> References {
+			get;
+			private set;
+		}
+
+		public IList<VariableReferenceNode> NextNodes {
+			get;
+			private set;
+		}
+
+		public IList<VariableReferenceNode> PreviousNodes {
+			get;
+			private set;
+		}
+
+		public VariableReferenceNode ()
+		{
+			References = new List<AstNode> ();
+			NextNodes = new List<VariableReferenceNode> ();
+			PreviousNodes = new List<VariableReferenceNode> ();
+		}
+
+		public void AddNextNode (VariableReferenceNode node)
+		{
+			if (node == null)
+				return;
+			NextNodes.Add (node);
+			node.PreviousNodes.Add (this);
+		}
+	}
+
+	class VariableReferenceGraphBuilder
+	{
+		ControlFlowGraphBuilder cfgBuilder = new ControlFlowGraphBuilder ();
+		CfgVariableReferenceNodeBuilder cfgVrNodeBuilder;
+		BaseRefactoringContext ctx;
+
+		public VariableReferenceGraphBuilder(BaseRefactoringContext ctx)
+		{
+			this.ctx = ctx;
+			cfgVrNodeBuilder = new CfgVariableReferenceNodeBuilder (this);
+		}
+
+		public VariableReferenceNode Build (ISet<AstNode> references, CSharpAstResolver resolver,
+			Expression expression)
+		{
+			return ExpressionNodeCreationVisitor.CreateNode (references, resolver, new [] { expression });
+		}
+
+		public VariableReferenceNode Build (Statement statement, ISet<AstNode> references,
+			ISet<Statement> refStatements, BaseRefactoringContext context)
+		{
+			var cfg = cfgBuilder.BuildControlFlowGraph (statement, context.Resolver, context.CancellationToken);
+			if (cfg.Count == 0)
+				return new VariableReferenceNode ();
+			return cfgVrNodeBuilder.Build (cfg [0], references, refStatements, context.Resolver);
+		}
+
+		public VariableReferenceNode Build (Statement statement, ISet<AstNode> references,
+		                                           ISet<Statement> refStatements, CSharpAstResolver resolver, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			var cfg = cfgBuilder.BuildControlFlowGraph (statement, resolver, cancellationToken);
+			if (cfg.Count == 0)
+				return new VariableReferenceNode();
+			return cfgVrNodeBuilder.Build (cfg [0], references, refStatements, resolver);
+		}
+
+		class GetExpressionsVisitor : DepthFirstAstVisitor<IEnumerable<Expression>>
+		{
+
+			public override IEnumerable<Expression> VisitIfElseStatement (IfElseStatement ifElseStatement)
+			{
+				yield return ifElseStatement.Condition;
+			}
+
+			public override IEnumerable<Expression> VisitSwitchStatement (SwitchStatement switchStatement)
+			{
+				yield return switchStatement.Expression;
+			}
+
+			public override IEnumerable<Expression> VisitForStatement (ForStatement forStatement)
+			{
+				yield return forStatement.Condition;
+			}
+
+			public override IEnumerable<Expression> VisitDoWhileStatement (DoWhileStatement doWhileStatement)
+			{
+				yield return doWhileStatement.Condition;
+			}
+
+			public override IEnumerable<Expression> VisitWhileStatement (WhileStatement whileStatement)
+			{
+				yield return whileStatement.Condition;
+			}
+
+			public override IEnumerable<Expression> VisitForeachStatement (ForeachStatement foreachStatement)
+			{
+				yield return foreachStatement.InExpression;
+			}
+
+			public override IEnumerable<Expression> VisitExpressionStatement (ExpressionStatement expressionStatement)
+			{
+				yield return expressionStatement.Expression;
+			}
+
+			public override IEnumerable<Expression> VisitLockStatement (LockStatement lockStatement)
+			{
+				yield return lockStatement.Expression;
+			}
+
+			public override IEnumerable<Expression> VisitReturnStatement (ReturnStatement returnStatement)
+			{
+				yield return returnStatement.Expression;
+			}
+
+			public override IEnumerable<Expression> VisitThrowStatement (ThrowStatement throwStatement)
+			{
+				yield return throwStatement.Expression;
+			}
+
+			public override IEnumerable<Expression> VisitUsingStatement (UsingStatement usingStatement)
+			{
+				var expr = usingStatement.ResourceAcquisition as Expression;
+				if (expr != null)
+					return new [] { expr };
+
+				return usingStatement.ResourceAcquisition.AcceptVisitor (this);
+			}
+
+			public override IEnumerable<Expression> VisitVariableDeclarationStatement (
+				VariableDeclarationStatement variableDeclarationStatement)
+			{
+				return variableDeclarationStatement.Variables.Select (v => v.Initializer);
+			}
+
+			public override IEnumerable<Expression> VisitYieldReturnStatement (YieldReturnStatement yieldReturnStatement)
+			{
+				yield return yieldReturnStatement.Expression;
+			}
+
+			public override IEnumerable<Expression> VisitBlockStatement(BlockStatement blockStatement)
+			{
+				yield break;
+			}
+		}
+
+		class CfgVariableReferenceNodeBuilder
+		{
+			readonly VariableReferenceGraphBuilder variableReferenceGraphBuilder;
+			GetExpressionsVisitor getExpr = new GetExpressionsVisitor ();
+
+			ISet<AstNode> references;
+			ISet<Statement> refStatements;
+			CSharpAstResolver resolver;
+			Dictionary<ControlFlowNode, VariableReferenceNode> nodeDict;
+
+			public CfgVariableReferenceNodeBuilder(VariableReferenceGraphBuilder variableReferenceGraphBuilder)
+			{
+				this.variableReferenceGraphBuilder = variableReferenceGraphBuilder;
+			}
+
+			public VariableReferenceNode Build (ControlFlowNode startNode, ISet<AstNode> references,
+				ISet<Statement> refStatements, CSharpAstResolver resolver)
+			{
+				this.references = references;
+				this.refStatements = refStatements;
+				this.resolver = resolver;
+				nodeDict = new Dictionary<ControlFlowNode, VariableReferenceNode> ();
+				return AddNode (startNode);
+			}
+
+			static bool IsValidControlFlowNode (ControlFlowNode node)
+			{
+				if (node.NextStatement == null)
+					return false;
+				if (node.Type == ControlFlowNodeType.LoopCondition) {
+					if (node.NextStatement is ForeachStatement)
+						return false;
+				} else {
+					if (node.NextStatement is WhileStatement || node.NextStatement is DoWhileStatement ||
+						node.NextStatement is ForStatement)
+						return false;
+				}
+				return true;
+			}
+
+			VariableReferenceNode GetStatementEndNode (VariableReferenceNode currentNode, Statement statement)
+			{
+				var expressions = statement.AcceptVisitor (getExpr);
+				VariableReferenceNode endNode;
+				ExpressionNodeCreationVisitor.CreateNode (references, resolver, expressions, currentNode, out endNode);
+				return endNode;
+			}
+
+			VariableReferenceNode AddNode (ControlFlowNode startNode)
+			{
+				var node = new VariableReferenceNode ();
+				var cfNode = startNode;
+				while (true) {
+					if (variableReferenceGraphBuilder.ctx.CancellationToken.IsCancellationRequested)
+						return null;
+					if (nodeDict.ContainsKey (cfNode)) {
+						node.AddNextNode (nodeDict [cfNode]);
+						break;
+					}
+					// create a new node for fork point
+					if (cfNode.Incoming.Count > 1 || cfNode.Outgoing.Count > 1) {
+						nodeDict [cfNode] = node;
+
+						var forkNode = new VariableReferenceNode ();
+						node.AddNextNode (forkNode);
+						node = forkNode;
+					}
+					nodeDict [cfNode] = node;
+
+					if (IsValidControlFlowNode (cfNode) && refStatements.Contains (cfNode.NextStatement)) {
+						node = GetStatementEndNode (node, cfNode.NextStatement);
+					}
+
+					if (cfNode.Outgoing.Count == 1) {
+						cfNode = cfNode.Outgoing [0].To;
+					} else {
+						foreach (var e in cfNode.Outgoing) {
+							node.AddNextNode (AddNode (e.To));
+						}
+						break;
+					}
+				}
+				VariableReferenceNode result;
+				if (!nodeDict.TryGetValue (startNode, out result))
+					return new VariableReferenceNode ();
+				return result;
+			}
+		}
+
+		class ExpressionNodeCreationVisitor : DepthFirstAstVisitor
+		{
+			VariableReferenceNode startNode;
+			VariableReferenceNode endNode;
+			ISet<AstNode> references;
+			CSharpAstResolver resolver;
+
+			ExpressionNodeCreationVisitor (ISet<AstNode> references, CSharpAstResolver resolver,
+				VariableReferenceNode startNode)
+			{
+				this.references = references;
+				this.resolver = resolver;
+				this.startNode = this.endNode = startNode ?? new VariableReferenceNode ();
+			}
+
+			public static VariableReferenceNode CreateNode (ISet<AstNode> references, CSharpAstResolver resolver,
+				params Expression [] expressions)
+			{
+				VariableReferenceNode endNode;
+				return CreateNode (references, resolver, expressions, null, out endNode);
+			}
+
+			public static VariableReferenceNode CreateNode (ISet<AstNode> references, CSharpAstResolver resolver,
+				IEnumerable<Expression> expressions, VariableReferenceNode startNode, out VariableReferenceNode endNode)
+			{
+				startNode = startNode ?? new VariableReferenceNode ();
+				endNode = startNode;
+				if (expressions != null) {
+					foreach (var expr in expressions) {
+						var visitor = CreateVisitor(references, resolver, expr, endNode);
+						endNode = visitor.endNode;
+					}
+				}
+				return startNode;
+			}
+
+			static ExpressionNodeCreationVisitor CreateVisitor (ISet<AstNode> references, CSharpAstResolver resolver,
+				Expression rootExpr, VariableReferenceNode startNode = null, VariableReferenceNode nextNode = null)
+			{
+				var visitor = new ExpressionNodeCreationVisitor (references, resolver, startNode);
+				rootExpr.AcceptVisitor (visitor);
+				if (nextNode != null)
+					visitor.endNode.AddNextNode (nextNode);
+				return visitor;
+			}
+
+			static VariableReferenceNode CreateNode (ISet<AstNode> references, CSharpAstResolver resolver, 
+				Expression rootExpr, VariableReferenceNode startNode = null, VariableReferenceNode nextNode = null)
+			{
+				return CreateVisitor (references, resolver, rootExpr, startNode, nextNode).startNode;
+			}
+
+			#region Skipped Expressions
+			public override void VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression)
+			{
+			}
+
+			public override void VisitLambdaExpression (LambdaExpression lambdaExpression)
+			{
+			}
+
+			public override void VisitBaseReferenceExpression (BaseReferenceExpression baseReferenceExpression)
+			{
+			}
+
+			public override void VisitNullReferenceExpression (NullReferenceExpression nullReferenceExpression)
+			{
+			}
+
+			public override void VisitPrimitiveExpression (PrimitiveExpression primitiveExpression)
+			{
+			}
+
+			public override void VisitSizeOfExpression (SizeOfExpression sizeOfExpression)
+			{
+			}
+
+			public override void VisitThisReferenceExpression (ThisReferenceExpression thisReferenceExpression)
+			{
+			}
+
+			public override void VisitTypeOfExpression (TypeOfExpression typeOfExpression)
+			{
+			}
+
+			public override void VisitTypeReferenceExpression (TypeReferenceExpression typeReferenceExpression)
+			{
+			}
+
+			public override void VisitUndocumentedExpression (UndocumentedExpression undocumentedExpression)
+			{
+			}
+
+			public override void VisitDefaultValueExpression (DefaultValueExpression defaultValueExpression)
+			{
+			}
+
+			#endregion
+
+			public override void VisitAssignmentExpression (AssignmentExpression assignmentExpression)
+			{
+				assignmentExpression.Right.AcceptVisitor (this);
+				assignmentExpression.Left.AcceptVisitor (this);
+			}
+
+			public override void VisitBinaryOperatorExpression (BinaryOperatorExpression binaryOperatorExpression)
+			{
+				binaryOperatorExpression.Left.AcceptVisitor (this);
+				binaryOperatorExpression.Right.AcceptVisitor (this);
+			}
+
+			public override void VisitCastExpression (CastExpression castExpression)
+			{
+				castExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitCheckedExpression (CheckedExpression checkedExpression)
+			{
+				checkedExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitConditionalExpression (ConditionalExpression conditionalExpression)
+			{
+				conditionalExpression.Condition.AcceptVisitor (this);
+				var resolveResult = resolver.Resolve (conditionalExpression.Condition);
+				if (resolveResult.ConstantValue is bool) {
+					if ((bool) resolveResult.ConstantValue)
+						conditionalExpression.TrueExpression.AcceptVisitor (this);
+					else
+						conditionalExpression.FalseExpression.AcceptVisitor (this);
+					return;
+				}
+				var nextEndNode = new VariableReferenceNode ();
+				var trueNode = CreateNode (references, resolver, conditionalExpression.TrueExpression, null, 
+					nextEndNode);
+				var falseNode = CreateNode (references, resolver, conditionalExpression.FalseExpression, null, 
+					nextEndNode);
+				endNode.AddNextNode (trueNode);
+				endNode.AddNextNode (falseNode);
+				endNode = nextEndNode;
+			}
+
+			public override void VisitIdentifierExpression (IdentifierExpression identifierExpression)
+			{
+				if (references.Contains (identifierExpression))
+					endNode.References.Add (identifierExpression);
+			}
+
+			public override void VisitIndexerExpression (IndexerExpression indexerExpression)
+			{
+				indexerExpression.Target.AcceptVisitor (this);
+				foreach (var arg in indexerExpression.Arguments)
+					arg.AcceptVisitor (this);
+			}
+
+			public override void VisitInvocationExpression (InvocationExpression invocationExpression)
+			{
+				invocationExpression.Target.AcceptVisitor (this);
+				var outArguments = new List<Expression> ();
+				foreach (var arg in invocationExpression.Arguments) {
+					var directionExpr = arg as DirectionExpression;
+					if (directionExpr != null && directionExpr.FieldDirection == FieldDirection.Out) {
+						outArguments.Add (directionExpr);
+						continue;
+					}
+					arg.AcceptVisitor (this);
+				}
+				foreach (var arg in outArguments)
+					arg.AcceptVisitor (this);
+			}
+
+			public override void VisitDirectionExpression (DirectionExpression directionExpression)
+			{
+				directionExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression)
+			{
+				memberReferenceExpression.Target.AcceptVisitor (this);
+			}
+
+			public override void VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression)
+			{
+				foreach (var arg in objectCreateExpression.Arguments)
+					arg.AcceptVisitor (this);
+				objectCreateExpression.Initializer.AcceptVisitor (this);
+			}
+
+			public override void VisitAnonymousTypeCreateExpression (
+				AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+			{
+				foreach (var init in anonymousTypeCreateExpression.Initializers)
+					init.AcceptVisitor (this);
+			}
+
+			public override void VisitArrayCreateExpression (ArrayCreateExpression arrayCreateExpression)
+			{
+				foreach (var arg in arrayCreateExpression.Arguments)
+					arg.AcceptVisitor (this);
+				arrayCreateExpression.Initializer.AcceptVisitor (this);
+			}
+
+			public override void VisitParenthesizedExpression (ParenthesizedExpression parenthesizedExpression)
+			{
+				parenthesizedExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitPointerReferenceExpression (PointerReferenceExpression pointerReferenceExpression)
+			{
+				pointerReferenceExpression.Target.AcceptVisitor (this);
+			}
+
+			public override void VisitStackAllocExpression (StackAllocExpression stackAllocExpression)
+			{
+				stackAllocExpression.CountExpression.AcceptVisitor (this);
+			}
+
+			public override void VisitUnaryOperatorExpression (UnaryOperatorExpression unaryOperatorExpression)
+			{
+				unaryOperatorExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitUncheckedExpression (UncheckedExpression uncheckedExpression)
+			{
+				uncheckedExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitAsExpression (AsExpression asExpression)
+			{
+				asExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitIsExpression (IsExpression isExpression)
+			{
+				isExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitArrayInitializerExpression (ArrayInitializerExpression arrayInitializerExpression)
+			{
+				foreach (var element in arrayInitializerExpression.Elements)
+					element.AcceptVisitor (this);
+			}
+
+			public override void VisitNamedArgumentExpression (NamedArgumentExpression namedArgumentExpression)
+			{
+				namedArgumentExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitNamedExpression (NamedExpression namedExpression)
+			{
+				namedExpression.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitQueryExpression (QueryExpression queryExpression)
+			{
+				foreach (var clause in queryExpression.Clauses)
+					clause.AcceptVisitor (this);
+			}
+
+			#region Query Clauses
+
+			public override void VisitQueryContinuationClause (QueryContinuationClause queryContinuationClause)
+			{
+				queryContinuationClause.PrecedingQuery.AcceptVisitor (this);
+			}
+
+			public override void VisitQueryFromClause (QueryFromClause queryFromClause)
+			{
+				queryFromClause.Expression.AcceptVisitor (this);
+			}
+
+			public override void VisitQueryJoinClause (QueryJoinClause queryJoinClause)
+			{
+				queryJoinClause.InExpression.AcceptVisitor (this);
+			}
+
+			public override void VisitQueryLetClause (QueryLetClause queryLetClause)
+			{
+			}
+
+			public override void VisitQueryWhereClause (QueryWhereClause queryWhereClause)
+			{
+			}
+
+			public override void VisitQueryOrderClause (QueryOrderClause queryOrderClause)
+			{
+			}
+
+			public override void VisitQueryOrdering (QueryOrdering queryOrdering)
+			{
+			}
+
+			public override void VisitQuerySelectClause (QuerySelectClause querySelectClause)
+			{
+			}
+
+			public override void VisitQueryGroupClause (QueryGroupClause queryGroupClause)
+			{
+			}
+
+			#endregion
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/WordParser.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/WordParser.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Refactoring/WordParser.cs	(revision 11807)
@@ -0,0 +1,70 @@
+// 
+// WordParser.cs
+//  
+// Author:
+//       Michael Hutchinson <mhutch@xamarin.com>
+// 
+// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	public static class WordParser
+	{
+		public static List<string> BreakWords (string identifier)
+		{
+			var words = new List<string> ();
+			int wordStart = 0;
+			bool lastWasLower = false, lastWasUpper = false;
+			for (int i = 0; i < identifier.Length; i++) {
+				char c = identifier[i];
+				var category = char.GetUnicodeCategory (c);
+				if (category == System.Globalization.UnicodeCategory.LowercaseLetter) {
+					if (lastWasUpper && (i - wordStart) > 2) {
+						words.Add (identifier.Substring (wordStart, i - wordStart - 1));
+						wordStart = i - 1;
+					}
+					lastWasLower = true;
+					lastWasUpper = false;
+				} else if (category == System.Globalization.UnicodeCategory.UppercaseLetter) {
+					if (lastWasLower) {
+						words.Add (identifier.Substring (wordStart, i - wordStart));
+						wordStart = i;
+					}
+					lastWasLower = false;
+					lastWasUpper = true;
+				} else {
+					if (c == '_') {
+						if ((i - wordStart) > 0)
+							words.Add(identifier.Substring(wordStart, i - wordStart));
+						wordStart = i + 1;
+						lastWasLower = lastWasUpper = false;
+					}
+				}
+			}
+			if (wordStart < identifier.Length)
+				words.Add (identifier.Substring (wordStart));
+			return words;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AliasNamespaceResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AliasNamespaceResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AliasNamespaceResolveResult.cs	(revision 11807)
@@ -0,0 +1,52 @@
+﻿//
+// AliasResolveResult.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.Semantics;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents a namespace resolve result that's resolved using an alias.
+	/// </summary>
+	public class AliasNamespaceResolveResult : NamespaceResolveResult
+	{
+		/// <summary>
+		/// The alias used.
+		/// </summary>
+		public string Alias {
+			get;
+			private set;
+		}
+		
+		public AliasNamespaceResolveResult(string alias, NamespaceResolveResult underlyingResult) : base (underlyingResult.Namespace)
+		{
+			this.Alias = alias;
+		}
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AliasTypeResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AliasTypeResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AliasTypeResolveResult.cs	(revision 11807)
@@ -0,0 +1,52 @@
+﻿//
+// AliasTypeResolveResult.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Semantics;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents a type resolve result that's resolved using an alias.
+	/// </summary>
+	public class AliasTypeResolveResult : TypeResolveResult
+	{
+		/// <summary>
+		/// The alias used.
+		/// </summary>
+		public string Alias {
+			get;
+			private set;
+		}
+		
+		public AliasTypeResolveResult(string alias, TypeResolveResult underlyingResult) : base (underlyingResult.Type)
+		{
+			this.Alias = alias;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AwaitResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AwaitResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/AwaitResolveResult.cs	(revision 11807)
@@ -0,0 +1,81 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Linq.Expressions;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents the result of an await expression.
+	/// </summary>
+	public class AwaitResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// The method representing the GetAwaiter() call. Can be an <see cref="InvocationResolveResult"/> or a <see cref="DynamicInvocationResolveResult"/>.
+		/// </summary>
+		public readonly ResolveResult GetAwaiterInvocation;
+
+		/// <summary>
+		/// Awaiter type. Will not be null (but can be UnknownType).
+		/// </summary>
+		public readonly IType AwaiterType;
+
+		/// <summary>
+		/// Property representing the IsCompleted property on the awaiter type. Can be null if the awaiter type or the property was not found, or when awaiting a dynamic expression.
+		/// </summary>
+		public readonly IProperty IsCompletedProperty;
+
+		/// <summary>
+		/// Method representing the OnCompleted method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression.
+		/// This can also refer to an UnsafeOnCompleted method, if the awaiter type implements <c>System.Runtime.CompilerServices.ICriticalNotifyCompletion</c>.
+		/// </summary>
+		public readonly IMethod OnCompletedMethod;
+		
+		/// <summary>
+		/// Method representing the GetResult method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression.
+		/// </summary>
+		public readonly IMethod GetResultMethod;
+
+		public AwaitResolveResult(IType resultType, ResolveResult getAwaiterInvocation, IType awaiterType, IProperty isCompletedProperty, IMethod onCompletedMethod, IMethod getResultMethod)
+			: base(resultType)
+		{
+			if (awaiterType == null)
+				throw new ArgumentNullException("awaiterType");
+			if (getAwaiterInvocation == null)
+				throw new ArgumentNullException("getAwaiterInvocation");
+			this.GetAwaiterInvocation = getAwaiterInvocation;
+			this.AwaiterType = awaiterType;
+			this.IsCompletedProperty = isCompletedProperty;
+			this.OnCompletedMethod = onCompletedMethod;
+			this.GetResultMethod = getResultMethod;
+		}
+		
+		public override bool IsError {
+			get { return this.GetAwaiterInvocation.IsError || (AwaiterType.Kind != TypeKind.Dynamic && (this.IsCompletedProperty == null || this.OnCompletedMethod == null || this.GetResultMethod == null)); }
+		}
+
+		public override IEnumerable<ResolveResult> GetChildResults() {
+			return new[] { GetAwaiterInvocation };
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpAstResolver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpAstResolver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpAstResolver.cs	(revision 11807)
@@ -0,0 +1,281 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Resolves C# AST nodes.
+	/// </summary>
+	/// <remarks>This class is thread-safe.</remarks>
+	public class CSharpAstResolver
+	{
+		readonly CSharpResolver initialResolverState;
+		readonly AstNode rootNode;
+		readonly CSharpUnresolvedFile unresolvedFile;
+		readonly ResolveVisitor resolveVisitor;
+		bool resolverInitialized;
+		
+		/// <summary>
+		/// Creates a new C# AST resolver.
+		/// Use this overload if you are resolving within a complete C# file.
+		/// </summary>
+		/// <param name="compilation">The current compilation.</param>
+		/// <param name="syntaxTree">The syntax tree to be resolved.</param>
+		/// <param name="unresolvedFile">
+		/// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
+		/// <para>
+		/// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
+		/// </para>
+		/// <para>
+		/// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
+		/// member declarations in the AST with members in the type system.
+		/// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
+		/// member's signature in the AST with the signature in the type system.
+		/// </para>
+		/// </param>
+		public CSharpAstResolver(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile = null)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (syntaxTree == null)
+				throw new ArgumentNullException("syntaxTree");
+			this.initialResolverState = new CSharpResolver(compilation);
+			this.rootNode = syntaxTree;
+			this.unresolvedFile = unresolvedFile;
+			this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
+		}
+		
+		/// <summary>
+		/// Creates a new C# AST resolver.
+		/// Use this overload if you are resolving code snippets (not necessarily complete files).
+		/// </summary>
+		/// <param name="resolver">The resolver state at the root node (to be more precise: just outside the root node).</param>
+		/// <param name="rootNode">The root node of the tree to be resolved.</param>
+		/// <param name="unresolvedFile">
+		/// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
+		/// <para>
+		/// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
+		/// </para>
+		/// <para>
+		/// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
+		/// member declarations in the AST with members in the type system.
+		/// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
+		/// member's signature in the AST with the signature in the type system.
+		/// </para>
+		/// </param>
+		public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpUnresolvedFile unresolvedFile = null)
+		{
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			if (rootNode == null)
+				throw new ArgumentNullException("rootNode");
+			this.initialResolverState = resolver;
+			this.rootNode = rootNode;
+			this.unresolvedFile = unresolvedFile;
+			this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
+		}
+		
+		/// <summary>
+		/// Gets the type resolve context for the root resolver.
+		/// </summary>
+		public CSharpTypeResolveContext TypeResolveContext {
+			get { return initialResolverState.CurrentTypeResolveContext; }
+		}
+		
+		/// <summary>
+		/// Gets the compilation for this resolver.
+		/// </summary>
+		public ICompilation Compilation {
+			get { return initialResolverState.Compilation; }
+		}
+		
+		/// <summary>
+		/// Gets the root node for which this CSharpAstResolver was created.
+		/// </summary>
+		public AstNode RootNode {
+			get { return rootNode; }
+		}
+		
+		/// <summary>
+		/// Gets the unresolved file used by this CSharpAstResolver.
+		/// Can return null.
+		/// </summary>
+		public CSharpUnresolvedFile UnresolvedFile {
+			get { return unresolvedFile; }
+		}
+		
+		/// <summary>
+		/// Applies a resolver navigator. This will resolve the nodes requested by the navigator, and will inform the
+		/// navigator of the results.
+		/// This method must be called as the first operation on the CSharpAstResolver, it is invalid to apply a navigator
+		/// after a portion of the file was already resolved.
+		/// </summary>
+		public void ApplyNavigator(IResolveVisitorNavigator navigator, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (navigator == null)
+				throw new ArgumentNullException("navigator");
+			
+			lock (resolveVisitor) {
+				if (resolverInitialized)
+					throw new InvalidOperationException("Applying a navigator is only valid as the first operation on the CSharpAstResolver.");
+				
+				resolverInitialized = true;
+				resolveVisitor.cancellationToken = cancellationToken;
+				resolveVisitor.SetNavigator(navigator);
+				try {
+					resolveVisitor.Scan(rootNode);
+				} finally {
+					resolveVisitor.SetNavigator(null);
+					resolveVisitor.cancellationToken = CancellationToken.None;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Resolves the specified node.
+		/// </summary>
+		public ResolveResult Resolve(AstNode node, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (node == null || node.IsNull || IsUnresolvableNode(node))
+				return ErrorResolveResult.UnknownError;
+			lock (resolveVisitor) {
+				InitResolver();
+				resolveVisitor.cancellationToken = cancellationToken;
+				try {
+					ResolveResult rr = resolveVisitor.GetResolveResult(node);
+					if (rr == null)
+						Debug.Fail (node.GetType () + " resolved to null.", node.StartLocation + ":'" + node.ToString () + "'");
+					return rr;
+				} finally {
+					resolveVisitor.cancellationToken = CancellationToken.None;
+				}
+			}
+		}
+		
+		void InitResolver()
+		{
+			if (!resolverInitialized) {
+				resolverInitialized = true;
+				resolveVisitor.Scan(rootNode);
+			}
+		}
+		
+		/// <summary>
+		/// Gets the resolver state immediately before the specified node.
+		/// That is, if the node is a variable declaration, the returned state will not contain the newly declared variable.
+		/// </summary>
+		public CSharpResolver GetResolverStateBefore(AstNode node, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (node == null || node.IsNull)
+				throw new ArgumentNullException("node");
+			lock (resolveVisitor) {
+				InitResolver();
+				resolveVisitor.cancellationToken = cancellationToken;
+				try {
+					CSharpResolver resolver = resolveVisitor.GetResolverStateBefore(node);
+					Debug.Assert(resolver != null);
+					return resolver;
+				} finally {
+					resolveVisitor.cancellationToken = CancellationToken.None;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the resolver state immediately after the specified node.
+		/// That is, if the node is a variable declaration, the returned state will include the newly declared variable.
+		/// </summary>
+		public CSharpResolver GetResolverStateAfter(AstNode node, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (node == null || node.IsNull)
+				throw new ArgumentNullException("node");
+			while (node != null && IsUnresolvableNode(node))
+				node = node.Parent;
+			if (node == null)
+				return initialResolverState;
+			lock (resolveVisitor) {
+				InitResolver();
+				resolveVisitor.cancellationToken = cancellationToken;
+				try {
+					CSharpResolver resolver = resolveVisitor.GetResolverStateAfter(node);
+					Debug.Assert(resolver != null);
+					return resolver;
+				} finally {
+					resolveVisitor.cancellationToken = CancellationToken.None;
+				}
+			}
+		}
+		
+		ResolveVisitor.ConversionWithTargetType GetConversionWithTargetType(Expression expr, CancellationToken cancellationToken)
+		{
+			if (expr == null || expr.IsNull)
+				return new ResolveVisitor.ConversionWithTargetType(Conversion.None, SpecialType.UnknownType);
+			lock (resolveVisitor) {
+				InitResolver();
+				resolveVisitor.cancellationToken = cancellationToken;
+				try {
+					return resolveVisitor.GetConversionWithTargetType(expr);
+				} finally {
+					resolveVisitor.cancellationToken = CancellationToken.None;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets the expected type for the specified node. This is the type that a node is being converted to.
+		/// </summary>
+		public IType GetExpectedType(Expression expr, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			return GetConversionWithTargetType(expr, cancellationToken).TargetType;
+		}
+		
+		/// <summary>
+		/// Gets the conversion that is being applied to the specified expression.
+		/// </summary>
+		public Conversion GetConversion(Expression expr, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			return GetConversionWithTargetType(expr, cancellationToken).Conversion;
+		}
+		
+		/// <summary>
+		/// Gets whether the specified node is unresolvable.
+		/// </summary>
+		public static bool IsUnresolvableNode(AstNode node)
+		{
+			if (node == null)
+				throw new ArgumentNullException("node");
+			if (node.NodeType == NodeType.Token) {
+				// Most tokens cannot be resolved, but there are a couple of special cases:
+				if (node.Parent is QueryClause && node is Identifier) {
+					return false;
+				} else if (node.Role == Roles.Identifier) {
+					return !(node.Parent is ForeachStatement || node.Parent is CatchClause);
+				}
+				return true;
+			}
+			return (node.NodeType == NodeType.Whitespace || node is ArraySpecifier);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpConversions.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpConversions.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpConversions.cs	(revision 11807)
@@ -0,0 +1,1248 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Contains logic that determines whether an implicit conversion exists between two types.
+	/// </summary>
+	/// <remarks>
+	/// This class is thread-safe.
+	/// </remarks>
+	public sealed class CSharpConversions
+	{
+		readonly ConcurrentDictionary<TypePair, Conversion> implicitConversionCache = new ConcurrentDictionary<TypePair, Conversion>();
+		readonly ICompilation compilation;
+		readonly IType objectType;
+		
+		public CSharpConversions(ICompilation compilation)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			this.compilation = compilation;
+			this.objectType = compilation.FindType(KnownTypeCode.Object);
+			this.dynamicErasure = new DynamicErasure(this);
+		}
+		
+		/// <summary>
+		/// Gets the Conversions instance for the specified <see cref="ICompilation"/>.
+		/// This will make use of the context's cache manager to reuse the Conversions instance.
+		/// </summary>
+		public static CSharpConversions Get(ICompilation compilation)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			CacheManager cache = compilation.CacheManager;
+			CSharpConversions operators = (CSharpConversions)cache.GetShared(typeof(CSharpConversions));
+			if (operators == null) {
+				operators = (CSharpConversions)cache.GetOrAddShared(typeof(CSharpConversions), new CSharpConversions(compilation));
+			}
+			return operators;
+		}
+		
+		#region TypePair (for caching)
+		struct TypePair : IEquatable<TypePair>
+		{
+			public readonly IType FromType;
+			public readonly IType ToType;
+			
+			public TypePair(IType fromType, IType toType)
+			{
+				Debug.Assert(fromType != null && toType != null);
+				this.FromType = fromType;
+				this.ToType = toType;
+			}
+			
+			public override bool Equals(object obj)
+			{
+				return (obj is TypePair) && Equals((TypePair)obj);
+			}
+			
+			public bool Equals(TypePair other)
+			{
+				return object.Equals(this.FromType, other.FromType) && object.Equals(this.ToType, other.ToType);
+			}
+			
+			public override int GetHashCode()
+			{
+				unchecked {
+					return 1000000007 * FromType.GetHashCode() + 1000000009 * ToType.GetHashCode();
+				}
+			}
+		}
+		#endregion
+		
+		#region ImplicitConversion
+		private Conversion ImplicitConversion(ResolveResult resolveResult, IType toType, bool allowUserDefined)
+		{
+			Conversion c;
+			if (resolveResult.IsCompileTimeConstant) {
+				c = ImplicitEnumerationConversion(resolveResult, toType);
+				if (c.IsValid) return c;
+				if (ImplicitConstantExpressionConversion(resolveResult, toType))
+					return Conversion.ImplicitConstantExpressionConversion;
+				c = StandardImplicitConversion(resolveResult.Type, toType);
+				if (c != Conversion.None) return c;
+				if (allowUserDefined) {
+					c = UserDefinedImplicitConversion(resolveResult, resolveResult.Type, toType);
+					if (c != Conversion.None) return c;
+				}
+			} else {
+				c = ImplicitConversion(resolveResult.Type, toType, allowUserDefined);
+				if (c != Conversion.None) return c;
+			}
+			if (resolveResult.Type.Kind == TypeKind.Dynamic)
+				return Conversion.ImplicitDynamicConversion;
+			c = AnonymousFunctionConversion(resolveResult, toType);
+			if (c != Conversion.None) return c;
+			c = MethodGroupConversion(resolveResult, toType);
+			return c;
+		}
+		
+		private Conversion ImplicitConversion(IType fromType, IType toType, bool allowUserDefined)
+		{
+			// C# 4.0 spec: §6.1
+			var c = StandardImplicitConversion(fromType, toType);
+			if (c == Conversion.None && allowUserDefined) {
+				c = UserDefinedImplicitConversion(null, fromType, toType);
+			}
+			return c;
+		}
+
+		public Conversion ImplicitConversion(ResolveResult resolveResult, IType toType)
+		{
+			if (resolveResult == null)
+				throw new ArgumentNullException("resolveResult");
+			return ImplicitConversion(resolveResult, toType, allowUserDefined: true);
+		}
+
+		public Conversion ImplicitConversion(IType fromType, IType toType)
+		{
+			if (fromType == null)
+				throw new ArgumentNullException("fromType");
+			if (toType == null)
+				throw new ArgumentNullException("toType");
+			
+			TypePair pair = new TypePair(fromType, toType);
+			Conversion c;
+			if (implicitConversionCache.TryGetValue(pair, out c))
+				return c;
+
+			c = ImplicitConversion(fromType, toType, allowUserDefined: true);
+
+			implicitConversionCache[pair] = c;
+			return c;
+		}
+		
+		public Conversion StandardImplicitConversion(IType fromType, IType toType)
+		{
+			if (fromType == null)
+				throw new ArgumentNullException("fromType");
+			if (toType == null)
+				throw new ArgumentNullException("toType");
+			// C# 4.0 spec: §6.3.1
+			if (IdentityConversion(fromType, toType))
+				return Conversion.IdentityConversion;
+			if (ImplicitNumericConversion(fromType, toType))
+				return Conversion.ImplicitNumericConversion;
+			Conversion c = ImplicitNullableConversion(fromType, toType);
+			if (c != Conversion.None)
+				return c;
+			if (NullLiteralConversion(fromType, toType))
+				return Conversion.NullLiteralConversion;
+			if (ImplicitReferenceConversion(fromType, toType, 0))
+				return Conversion.ImplicitReferenceConversion;
+			if (IsBoxingConversion(fromType, toType))
+				return Conversion.BoxingConversion;
+			if (ImplicitTypeParameterConversion(fromType, toType)) {
+				// Implicit type parameter conversions that aren't also
+				// reference conversions are considered to be boxing conversions
+				return Conversion.BoxingConversion;
+			}
+			if (ImplicitPointerConversion(fromType, toType))
+				return Conversion.ImplicitPointerConversion;
+			return Conversion.None;
+		}
+		
+		/// <summary>
+		/// Gets whether the type 'fromType' is convertible to 'toType'
+		/// using one of the conversions allowed when satisying constraints (§4.4.4)
+		/// </summary>
+		public bool IsConstraintConvertible(IType fromType, IType toType)
+		{
+			if (fromType == null)
+				throw new ArgumentNullException("fromType");
+			if (toType == null)
+				throw new ArgumentNullException("toType");
+			
+			if (IdentityConversion(fromType, toType))
+				return true;
+			if (ImplicitReferenceConversion(fromType, toType, 0))
+				return true;
+			if (NullableType.IsNullable(fromType)) {
+				// An 'object' constraint still allows nullable value types
+				// (object constraints don't exist in C#, but are inserted by DefaultResolvedTypeParameter.DirectBaseTypes)
+				if (toType.IsKnownType(KnownTypeCode.Object))
+					return true;
+			} else {
+				if (IsBoxingConversion(fromType, toType))
+					return true;
+			}
+			if (ImplicitTypeParameterConversion(fromType, toType))
+				return true;
+			return false;
+		}
+		#endregion
+		
+		#region ExplicitConversion
+		public Conversion ExplicitConversion(ResolveResult resolveResult, IType toType)
+		{
+			if (resolveResult == null)
+				throw new ArgumentNullException("resolveResult");
+			if (toType == null)
+				throw new ArgumentNullException("toType");
+			
+			if (resolveResult.Type.Kind == TypeKind.Dynamic)
+				return Conversion.ExplicitDynamicConversion;
+			Conversion c = ImplicitConversion(resolveResult, toType, allowUserDefined: false);
+			if (c != Conversion.None)
+				return c;
+			c = ExplicitConversionImpl(resolveResult.Type, toType);
+			if (c != Conversion.None)
+				return c;
+			return UserDefinedExplicitConversion(resolveResult, resolveResult.Type, toType);
+		}
+		
+		public Conversion ExplicitConversion(IType fromType, IType toType)
+		{
+			if (fromType == null)
+				throw new ArgumentNullException("fromType");
+			if (toType == null)
+				throw new ArgumentNullException("toType");
+			
+			Conversion c = ImplicitConversion(fromType, toType, allowUserDefined: false);
+			if (c != Conversion.None)
+				return c;
+			c = ExplicitConversionImpl(fromType, toType);
+			if (c != Conversion.None)
+				return c;
+			return UserDefinedExplicitConversion(null, fromType, toType);
+		}
+		
+		Conversion ExplicitConversionImpl(IType fromType, IType toType)
+		{
+			// This method is called after we already checked for implicit conversions,
+			// so any remaining conversions must be explicit.
+			if (AnyNumericConversion(fromType, toType))
+				return Conversion.ExplicitNumericConversion;
+			if (ExplicitEnumerationConversion(fromType, toType))
+				return Conversion.EnumerationConversion(false, false);
+			Conversion c = ExplicitNullableConversion(fromType, toType);
+			if (c != Conversion.None)
+				return c;
+			if (ExplicitReferenceConversion(fromType, toType))
+				return Conversion.ExplicitReferenceConversion;
+			if (UnboxingConversion(fromType, toType))
+				return Conversion.UnboxingConversion;
+			c = ExplicitTypeParameterConversion(fromType, toType);
+			if (c != Conversion.None)
+				return c;
+			if (ExplicitPointerConversion(fromType, toType))
+				return Conversion.ExplicitPointerConversion;
+			return Conversion.None;
+		}
+		#endregion
+		
+		#region Identity Conversion
+		/// <summary>
+		/// Gets whether there is an identity conversion from <paramref name="fromType"/> to <paramref name="toType"/>
+		/// </summary>
+		public bool IdentityConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.1
+			return fromType.AcceptVisitor(dynamicErasure).Equals(toType.AcceptVisitor(dynamicErasure));
+		}
+		
+		readonly DynamicErasure dynamicErasure;
+		
+		sealed class DynamicErasure : TypeVisitor
+		{
+			readonly IType objectType;
+			
+			public DynamicErasure(CSharpConversions conversions)
+			{
+				this.objectType = conversions.objectType;
+			}
+			
+			public override IType VisitOtherType(IType type)
+			{
+				if (type.Kind == TypeKind.Dynamic)
+					return objectType;
+				else
+					return base.VisitOtherType(type);
+			}
+		}
+		#endregion
+		
+		#region Numeric Conversions
+		static readonly bool[,] implicitNumericConversionLookup = {
+			//       to:   short  ushort  int   uint   long   ulong
+			// from:
+			/* char   */ { false, true , true , true , true , true  },
+			/* sbyte  */ { true , false, true , false, true , false },
+			/* byte   */ { true , true , true , true , true , true  },
+			/* short  */ { false, false, true , false, true , false },
+			/* ushort */ { false, false, true , true , true , true  },
+			/* int    */ { false, false, false, false, true , false },
+			/* uint   */ { false, false, false, false, true , true  },
+		};
+		
+		bool ImplicitNumericConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.2
+			
+			TypeCode from = ReflectionHelper.GetTypeCode(fromType);
+			TypeCode to = ReflectionHelper.GetTypeCode(toType);
+			if (to >= TypeCode.Single && to <= TypeCode.Decimal) {
+				// Conversions to float/double/decimal exist from all integral types,
+				// and there's a conversion from float to double.
+				return from >= TypeCode.Char && from <= TypeCode.UInt64
+					|| from == TypeCode.Single && to == TypeCode.Double;
+			} else {
+				// Conversions to integral types: look at the table
+				return from >= TypeCode.Char && from <= TypeCode.UInt32
+					&& to >= TypeCode.Int16 && to <= TypeCode.UInt64
+					&& implicitNumericConversionLookup[from - TypeCode.Char, to - TypeCode.Int16];
+			}
+		}
+		
+		bool IsNumericType(IType type)
+		{
+			TypeCode c = ReflectionHelper.GetTypeCode(type);
+			return c >= TypeCode.Char && c <= TypeCode.Decimal;
+		}
+		
+		bool AnyNumericConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.2 + §6.2.1
+			return IsNumericType(fromType) && IsNumericType(toType);
+		}
+		#endregion
+		
+		#region Enumeration Conversions
+		Conversion ImplicitEnumerationConversion(ResolveResult rr, IType toType)
+		{
+			// C# 4.0 spec: §6.1.3
+			Debug.Assert(rr.IsCompileTimeConstant);
+			TypeCode constantType = ReflectionHelper.GetTypeCode(rr.Type);
+			if (constantType >= TypeCode.SByte && constantType <= TypeCode.Decimal && Convert.ToDouble(rr.ConstantValue) == 0) {
+				if (NullableType.GetUnderlyingType(toType).Kind == TypeKind.Enum) {
+					return Conversion.EnumerationConversion(true, NullableType.IsNullable(toType));
+				}
+			}
+			return Conversion.None;
+		}
+		
+		bool ExplicitEnumerationConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.2.2
+			if (fromType.Kind == TypeKind.Enum) {
+				return toType.Kind == TypeKind.Enum || IsNumericType(toType);
+			} else if (IsNumericType(fromType)) {
+				return toType.Kind == TypeKind.Enum;
+			}
+			return false;
+		}
+		#endregion
+		
+		#region Nullable Conversions
+		Conversion ImplicitNullableConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.4
+			if (NullableType.IsNullable(toType)) {
+				IType t = NullableType.GetUnderlyingType(toType);
+				IType s = NullableType.GetUnderlyingType(fromType); // might or might not be nullable
+				if (IdentityConversion(s, t))
+					return Conversion.ImplicitNullableConversion;
+				if (ImplicitNumericConversion(s, t))
+					return Conversion.ImplicitLiftedNumericConversion;
+			}
+			return Conversion.None;
+		}
+		
+		Conversion ExplicitNullableConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.4
+			if (NullableType.IsNullable(toType) || NullableType.IsNullable(fromType)) {
+				IType t = NullableType.GetUnderlyingType(toType);
+				IType s = NullableType.GetUnderlyingType(fromType);
+				if (IdentityConversion(s, t))
+					return Conversion.ExplicitNullableConversion;
+				if (AnyNumericConversion(s, t))
+					return Conversion.ExplicitLiftedNumericConversion;
+				if (ExplicitEnumerationConversion(s, t))
+					return Conversion.EnumerationConversion(false, true);
+			}
+			return Conversion.None;
+		}
+		#endregion
+		
+		#region Null Literal Conversion
+		bool NullLiteralConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.5
+			if (fromType.Kind == TypeKind.Null) {
+				return NullableType.IsNullable(toType) || toType.IsReferenceType == true;
+			} else {
+				return false;
+			}
+		}
+		#endregion
+		
+		#region Implicit Reference Conversion
+		public bool IsImplicitReferenceConversion(IType fromType, IType toType)
+		{
+			return ImplicitReferenceConversion(fromType, toType, 0);
+		}
+		
+		bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckNestingDepth)
+		{
+			// C# 4.0 spec: §6.1.6
+			
+			// reference conversions are possible:
+			// - if both types are known to be reference types
+			// - if both types are type parameters and fromType has a class constraint
+			//     (ImplicitTypeParameterConversionWithClassConstraintOnlyOnT)
+			if (!(fromType.IsReferenceType == true && toType.IsReferenceType != false))
+				return false;
+			
+			ArrayType fromArray = fromType as ArrayType;
+			if (fromArray != null) {
+				ArrayType toArray = toType as ArrayType;
+				if (toArray != null) {
+					// array covariance (the broken kind)
+					return fromArray.Dimensions == toArray.Dimensions
+						&& ImplicitReferenceConversion(fromArray.ElementType, toArray.ElementType, subtypeCheckNestingDepth);
+				}
+				// conversion from single-dimensional array S[] to IList<T>:
+				IType toTypeArgument = UnpackGenericArrayInterface(toType);
+				if (fromArray.Dimensions == 1 && toTypeArgument != null) {
+					// array covariance plays a part here as well (string[] is IList<object>)
+					return IdentityConversion(fromArray.ElementType, toTypeArgument)
+						|| ImplicitReferenceConversion(fromArray.ElementType, toTypeArgument, subtypeCheckNestingDepth);
+				}
+				// conversion from any array to System.Array and the interfaces it implements:
+				IType systemArray = compilation.FindType(KnownTypeCode.Array);
+				return ImplicitReferenceConversion(systemArray, toType, subtypeCheckNestingDepth);
+			}
+			
+			// now comes the hard part: traverse the inheritance chain and figure out generics+variance
+			return IsSubtypeOf(fromType, toType, subtypeCheckNestingDepth);
+		}
+		
+		/// <summary>
+		/// For IList{T}, ICollection{T}, IEnumerable{T} and IReadOnlyList{T}, returns T.
+		/// Otherwise, returns null.
+		/// </summary>
+		IType UnpackGenericArrayInterface(IType interfaceType)
+		{
+			ParameterizedType pt = interfaceType as ParameterizedType;
+			if (pt != null) {
+				KnownTypeCode tc = pt.GetDefinition().KnownTypeCode;
+				if (tc == KnownTypeCode.IListOfT || tc == KnownTypeCode.ICollectionOfT || tc == KnownTypeCode.IEnumerableOfT || tc == KnownTypeCode.IReadOnlyListOfT) {
+					return pt.GetTypeArgument(0);
+				}
+			}
+			return null;
+		}
+		
+		// Determines whether s is a subtype of t.
+		// Helper method used for ImplicitReferenceConversion, BoxingConversion and ImplicitTypeParameterConversion
+		
+		bool IsSubtypeOf(IType s, IType t, int subtypeCheckNestingDepth)
+		{
+			// conversion to dynamic + object are always possible
+			if (t.Kind == TypeKind.Dynamic || t.Equals(objectType))
+				return true;
+			if (subtypeCheckNestingDepth > 10) {
+				// Subtyping in C# is undecidable
+				// (see "On Decidability of Nominal Subtyping with Variance" by Andrew J. Kennedy and Benjamin C. Pierce),
+				// so we'll prevent infinite recursions by putting a limit on the nesting depth of variance conversions.
+				
+				// No real C# code should use generics nested more than 10 levels deep, and even if they do, most of
+				// those nestings should not involve variance.
+				return false;
+			}
+			// let GetAllBaseTypes do the work for us
+			foreach (IType baseType in s.GetAllBaseTypes()) {
+				if (IdentityOrVarianceConversion(baseType, t, subtypeCheckNestingDepth + 1))
+					return true;
+			}
+			return false;
+		}
+		
+		bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth)
+		{
+			ITypeDefinition def = s.GetDefinition();
+			if (def != null) {
+				if (!def.Equals(t.GetDefinition()))
+					return false;
+				ParameterizedType ps = s as ParameterizedType;
+				ParameterizedType pt = t as ParameterizedType;
+				if (ps != null && pt != null) {
+					// C# 4.0 spec: §13.1.3.2 Variance Conversion
+					for (int i = 0; i < def.TypeParameters.Count; i++) {
+						IType si = ps.GetTypeArgument(i);
+						IType ti = pt.GetTypeArgument(i);
+						if (IdentityConversion(si, ti))
+							continue;
+						ITypeParameter xi = def.TypeParameters[i];
+						switch (xi.Variance) {
+							case VarianceModifier.Covariant:
+								if (!ImplicitReferenceConversion(si, ti, subtypeCheckNestingDepth))
+									return false;
+								break;
+							case VarianceModifier.Contravariant:
+								if (!ImplicitReferenceConversion(ti, si, subtypeCheckNestingDepth))
+									return false;
+								break;
+							default:
+								return false;
+						}
+					}
+				} else if (ps != null || pt != null) {
+					return false; // only of of them is parameterized, or counts don't match? -> not valid conversion
+				}
+				return true;
+			} else {
+				// not type definitions? we still need to check for equal types (e.g. s and t might be type parameters)
+				return s.Equals(t);
+			}
+		}
+		#endregion
+		
+		#region Explicit Reference Conversion
+		bool ExplicitReferenceConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.2.4
+			
+			// test that the types are reference types:
+			if (toType.IsReferenceType != true)
+				return false;
+			if (fromType.IsReferenceType != true) {
+				// special case:
+				// converting from F to T is a reference conversion where T : class, F
+				// (because F actually must be a reference type as well, even though C# doesn't treat it as one)
+				if (fromType.Kind == TypeKind.TypeParameter)
+					return IsSubtypeOf(toType, fromType, 0);
+				return false;
+			}
+			
+			if (toType.Kind == TypeKind.Array) {
+				ArrayType toArray = (ArrayType)toType;
+				if (fromType.Kind == TypeKind.Array) {
+					// Array covariance
+					ArrayType fromArray = (ArrayType)fromType;
+					if (fromArray.Dimensions != toArray.Dimensions)
+						return false;
+					return ExplicitReferenceConversion(fromArray.ElementType, toArray.ElementType);
+				}
+				IType fromTypeArgument = UnpackGenericArrayInterface(fromType);
+				if (fromTypeArgument != null && toArray.Dimensions == 1) {
+					return ExplicitReferenceConversion(fromTypeArgument, toArray.ElementType)
+						|| IdentityConversion(fromTypeArgument, toArray.ElementType);
+				}
+				// Otherwise treat the array like a sealed class - require implicit conversion in the opposite direction
+				return IsImplicitReferenceConversion(toType, fromType);
+			} else if (fromType.Kind == TypeKind.Array) {
+				ArrayType fromArray = (ArrayType)fromType;
+				IType toTypeArgument = UnpackGenericArrayInterface(toType);
+				if (toTypeArgument != null && fromArray.Dimensions == 1) {
+					return ExplicitReferenceConversion(fromArray.ElementType, toTypeArgument);
+				}
+				// Otherwise treat the array like a sealed class
+				return IsImplicitReferenceConversion(fromType, toType);
+			} else if (fromType.Kind == TypeKind.Delegate && toType.Kind == TypeKind.Delegate) {
+				ITypeDefinition def = fromType.GetDefinition();
+				if (def == null || !def.Equals(toType.GetDefinition()))
+					return false;
+				ParameterizedType ps = fromType as ParameterizedType;
+				ParameterizedType pt = toType as ParameterizedType;
+				if (ps == null || pt == null) {
+					// non-generic delegate - return true for the identity conversion
+					return ps == null && pt == null;
+				}
+				for (int i = 0; i < def.TypeParameters.Count; i++) {
+					IType si = ps.GetTypeArgument(i);
+					IType ti = pt.GetTypeArgument(i);
+					if (IdentityConversion(si, ti))
+						continue;
+					ITypeParameter xi = def.TypeParameters[i];
+					switch (xi.Variance) {
+						case VarianceModifier.Covariant:
+							if (!ExplicitReferenceConversion(si, ti))
+								return false;
+							break;
+						case VarianceModifier.Contravariant:
+							if (!(si.IsReferenceType == true && ti.IsReferenceType == true))
+								return false;
+							break;
+						default:
+							return false;
+					}
+				}
+				return true;
+			} else if (IsSealedReferenceType(fromType)) {
+				// If the source type is sealed, explicit conversions can't do anything more than implicit ones
+				return IsImplicitReferenceConversion(fromType, toType);
+			} else if (IsSealedReferenceType(toType)) {
+				// The the target type is sealed, there must be an implicit conversion in the opposite direction
+				return IsImplicitReferenceConversion(toType, fromType);
+			} else {
+				if (fromType.Kind == TypeKind.Interface || toType.Kind == TypeKind.Interface)
+					return true;
+				else
+					return IsImplicitReferenceConversion(toType, fromType)
+						|| IsImplicitReferenceConversion(fromType, toType);
+			}
+		}
+		
+		bool IsSealedReferenceType(IType type)
+		{
+			TypeKind kind = type.Kind;
+			return kind == TypeKind.Class && type.GetDefinition().IsSealed
+				|| kind == TypeKind.Delegate || kind == TypeKind.Anonymous;
+		}
+		#endregion
+		
+		#region Boxing Conversions
+		public bool IsBoxingConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.1.7
+			fromType = NullableType.GetUnderlyingType(fromType);
+			if (fromType.IsReferenceType == false && toType.IsReferenceType == true)
+				return IsSubtypeOf(fromType, toType, 0);
+			else
+				return false;
+		}
+		
+		bool UnboxingConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §6.2.5
+			toType = NullableType.GetUnderlyingType(toType);
+			if (fromType.IsReferenceType == true && toType.IsReferenceType == false)
+				return IsSubtypeOf(toType, fromType, 0);
+			else
+				return false;
+		}
+		#endregion
+		
+		#region Implicit Constant-Expression Conversion
+		bool ImplicitConstantExpressionConversion(ResolveResult rr, IType toType)
+		{
+			if (rr == null || !rr.IsCompileTimeConstant)
+				return false;
+			// C# 4.0 spec: §6.1.9
+			TypeCode fromTypeCode = ReflectionHelper.GetTypeCode(rr.Type);
+			TypeCode toTypeCode = ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(toType));
+			if (fromTypeCode == TypeCode.Int64) {
+				long val = (long)rr.ConstantValue;
+				return val >= 0 && toTypeCode == TypeCode.UInt64;
+			} else if (fromTypeCode == TypeCode.Int32) {
+				object cv = rr.ConstantValue;
+				if (cv == null)
+					return false;
+				int val = (int)cv;
+				switch (toTypeCode) {
+					case TypeCode.SByte:
+						return val >= SByte.MinValue && val <= SByte.MaxValue;
+					case TypeCode.Byte:
+						return val >= Byte.MinValue && val <= Byte.MaxValue;
+					case TypeCode.Int16:
+						return val >= Int16.MinValue && val <= Int16.MaxValue;
+					case TypeCode.UInt16:
+						return val >= UInt16.MinValue && val <= UInt16.MaxValue;
+					case TypeCode.UInt32:
+						return val >= 0;
+					case TypeCode.UInt64:
+						return val >= 0;
+				}
+			}
+			return false;
+		}
+		#endregion
+		
+		#region Conversions involving type parameters
+		/// <summary>
+		/// Implicit conversions involving type parameters.
+		/// </summary>
+		bool ImplicitTypeParameterConversion(IType fromType, IType toType)
+		{
+			if (fromType.Kind != TypeKind.TypeParameter)
+				return false; // not a type parameter
+			if (fromType.IsReferenceType == true)
+				return false; // already handled by ImplicitReferenceConversion
+			return IsSubtypeOf(fromType, toType, 0);
+		}
+		
+		Conversion ExplicitTypeParameterConversion(IType fromType, IType toType)
+		{
+			if (toType.Kind == TypeKind.TypeParameter) {
+				// Explicit type parameter conversions that aren't also
+				// reference conversions are considered to be unboxing conversions
+				if (fromType.Kind == TypeKind.Interface || IsSubtypeOf(toType, fromType, 0))
+					return Conversion.UnboxingConversion;
+			} else {
+				if (fromType.Kind == TypeKind.TypeParameter && toType.Kind == TypeKind.Interface)
+					return Conversion.BoxingConversion;
+			}
+			return Conversion.None;
+		}
+		#endregion
+		
+		#region Pointer Conversions
+		bool ImplicitPointerConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §18.4 Pointer conversions
+			if (fromType is PointerType && toType is PointerType && toType.ReflectionName == "System.Void*")
+				return true;
+			if (fromType.Kind == TypeKind.Null && toType is PointerType)
+				return true;
+			return false;
+		}
+		
+		bool ExplicitPointerConversion(IType fromType, IType toType)
+		{
+			// C# 4.0 spec: §18.4 Pointer conversions
+			if (fromType.Kind == TypeKind.Pointer) {
+				return toType.Kind == TypeKind.Pointer || IsIntegerType(toType);
+			} else {
+				return toType.Kind == TypeKind.Pointer && IsIntegerType(fromType);
+			}
+		}
+		
+		bool IsIntegerType(IType type)
+		{
+			TypeCode c = ReflectionHelper.GetTypeCode(type);
+			return c >= TypeCode.SByte && c <= TypeCode.UInt64;
+		}
+		#endregion
+		
+		#region User-Defined Conversions
+		/// <summary>
+		/// Gets whether type A is encompassed by type B.
+		/// </summary>
+		bool IsEncompassedBy(IType a, IType b)
+		{
+			return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface && StandardImplicitConversion(a, b).IsValid;
+		}
+		
+		bool IsEncompassingOrEncompassedBy(IType a, IType b)
+		{
+			return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface
+				&& (StandardImplicitConversion(a, b).IsValid || StandardImplicitConversion(b, a).IsValid);
+		}
+
+		IType FindMostEncompassedType(IEnumerable<IType> candidates)
+		{
+			IType best = null;
+			foreach (var current in candidates) {
+				if (best == null || IsEncompassedBy(current, best))
+					best = current;
+				else if (!IsEncompassedBy(best, current))
+					return null;	// Ambiguous
+			}
+			return best;
+		}
+
+		IType FindMostEncompassingType(IEnumerable<IType> candidates)
+		{
+			IType best = null;
+			foreach (var current in candidates) {
+				if (best == null || IsEncompassedBy(best, current))
+					best = current;
+				else if (!IsEncompassedBy(current, best))
+					return null;	// Ambiguous
+			}
+			return best;
+		}
+
+		Conversion SelectOperator(IType mostSpecificSource, IType mostSpecificTarget, IList<OperatorInfo> operators, bool isImplicit, IType source, IType target)
+		{
+			var selected = operators.Where(op => op.SourceType.Equals(mostSpecificSource) && op.TargetType.Equals(mostSpecificTarget)).ToList();
+			if (selected.Count == 0)
+				return Conversion.None;
+
+			if (selected.Count == 1)
+				return Conversion.UserDefinedConversion(selected[0].Method, isLifted: selected[0].IsLifted, isImplicit: isImplicit, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
+
+			int nNonLifted = selected.Count(s => !s.IsLifted);
+			if (nNonLifted == 1) {
+				var op = selected.First(s => !s.IsLifted);
+				return Conversion.UserDefinedConversion(op.Method, isLifted: op.IsLifted, isImplicit: isImplicit, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
+			}
+			
+			return Conversion.UserDefinedConversion(selected[0].Method, isLifted: selected[0].IsLifted, isImplicit: isImplicit, isAmbiguous: true, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
+		}
+
+		Conversion UserDefinedImplicitConversion(ResolveResult fromResult, IType fromType, IType toType)
+		{
+			// C# 4.0 spec §6.4.4 User-defined implicit conversions
+			var operators = GetApplicableConversionOperators(fromResult, fromType, toType, false);
+
+			if (operators.Count > 0) {
+				var mostSpecificSource = operators.Any(op => op.SourceType.Equals(fromType)) ? fromType : FindMostEncompassedType(operators.Select(op => op.SourceType));
+				if (mostSpecificSource == null)
+					return Conversion.UserDefinedConversion(operators[0].Method, isImplicit: true, isLifted: operators[0].IsLifted, isAmbiguous: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
+				var mostSpecificTarget = operators.Any(op => op.TargetType.Equals(toType)) ? toType : FindMostEncompassingType(operators.Select(op => op.TargetType));
+				if (mostSpecificTarget == null) {
+					if (NullableType.IsNullable(toType))
+						return UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
+					else
+						return Conversion.UserDefinedConversion(operators[0].Method, isImplicit: true, isLifted: operators[0].IsLifted, isAmbiguous: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
+				}
+
+				var selected = SelectOperator(mostSpecificSource, mostSpecificTarget, operators, true, fromType, toType);
+				if (selected != Conversion.None) {
+					if (selected.IsLifted && NullableType.IsNullable(toType)) {
+						// Prefer A -> B -> B? over A -> A? -> B?
+						var other = UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
+						if (other != Conversion.None)
+							return other;
+					}
+					return selected;
+				}
+				else if (NullableType.IsNullable(toType))
+					return UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
+				else
+					return Conversion.None;
+			}
+			else {
+				return Conversion.None;
+			}
+		}
+		
+		Conversion UserDefinedExplicitConversion(ResolveResult fromResult, IType fromType, IType toType)
+		{
+			// C# 4.0 spec §6.4.5 User-defined implicit conversions
+			var operators = GetApplicableConversionOperators(fromResult, fromType, toType, true);
+			if (operators.Count > 0) {
+				IType mostSpecificSource;
+				if (operators.Any(op => op.SourceType.Equals(fromType))) {
+					mostSpecificSource = fromType;
+				} else {
+					var operatorsWithSourceEncompassingFromType = operators.Where(op => IsEncompassedBy(fromType, op.SourceType) || ImplicitConstantExpressionConversion(fromResult, NullableType.GetUnderlyingType(op.SourceType))).ToList();
+					if (operatorsWithSourceEncompassingFromType.Any())
+						mostSpecificSource = FindMostEncompassedType(operatorsWithSourceEncompassingFromType.Select(op => op.SourceType));
+					else
+						mostSpecificSource = FindMostEncompassingType(operators.Select(op => op.SourceType));
+				}
+				if (mostSpecificSource == null)
+					return Conversion.UserDefinedConversion(operators[0].Method, isImplicit: false, isLifted: operators[0].IsLifted, isAmbiguous: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
+
+				IType mostSpecificTarget;
+				if (operators.Any(op => op.TargetType.Equals(toType)))
+					mostSpecificTarget = toType;
+				else if (operators.Any(op => IsEncompassedBy(op.TargetType, toType)))
+					mostSpecificTarget = FindMostEncompassingType(operators.Where(op => IsEncompassedBy(op.TargetType, toType)).Select(op => op.TargetType));
+				else
+					mostSpecificTarget = FindMostEncompassedType(operators.Select(op => op.TargetType));
+				if (mostSpecificTarget == null) {
+					if (NullableType.IsNullable(toType))
+						return UserDefinedExplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
+					else
+						return Conversion.UserDefinedConversion(operators[0].Method, isImplicit: false, isLifted: operators[0].IsLifted, isAmbiguous: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
+				}
+
+				var selected = SelectOperator(mostSpecificSource, mostSpecificTarget, operators, false, fromType, toType);
+				if (selected != Conversion.None) {
+					if (selected.IsLifted && NullableType.IsNullable(toType)) {
+						// Prefer A -> B -> B? over A -> A? -> B?
+						var other = UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
+						if (other != Conversion.None)
+							return other;
+					}
+					return selected;
+				}
+				else if (NullableType.IsNullable(toType))
+					return UserDefinedExplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
+				else if (NullableType.IsNullable(fromType))
+					return UserDefinedExplicitConversion(null, NullableType.GetUnderlyingType(fromType), toType);	// A? -> A -> B
+				else
+					return Conversion.None;
+			}
+			else {
+				return Conversion.None;
+			}
+		}
+		
+		class OperatorInfo
+		{
+			public readonly IMethod Method;
+			public readonly IType SourceType;
+			public readonly IType TargetType;
+			public readonly bool IsLifted;
+			
+			public OperatorInfo(IMethod method, IType sourceType, IType targetType, bool isLifted)
+			{
+				this.Method = method;
+				this.SourceType = sourceType;
+				this.TargetType = targetType;
+				this.IsLifted = isLifted;
+			}
+		}
+		
+		List<OperatorInfo> GetApplicableConversionOperators(ResolveResult fromResult, IType fromType, IType toType, bool isExplicit)
+		{
+			// Find the candidate operators:
+			Predicate<IUnresolvedMethod> opFilter;
+			if (isExplicit)
+				opFilter = m => m.IsStatic && m.IsOperator && (m.Name == "op_Explicit" || m.Name == "op_Implicit") && m.Parameters.Count == 1;
+			else
+				opFilter = m => m.IsStatic && m.IsOperator && m.Name == "op_Implicit" && m.Parameters.Count == 1;
+			
+			var operators = NullableType.GetUnderlyingType(fromType).GetMethods(opFilter)
+				.Concat(NullableType.GetUnderlyingType(toType).GetMethods(opFilter)).Distinct();
+			// Determine whether one of them is applicable:
+			List<OperatorInfo> result = new List<OperatorInfo>();
+			foreach (IMethod op in operators) {
+				IType sourceType = op.Parameters[0].Type;
+				IType targetType = op.ReturnType;
+				// Try if the operator is applicable:
+				bool isApplicable;
+				if (isExplicit) {
+					isApplicable = (IsEncompassingOrEncompassedBy(fromType, sourceType) || ImplicitConstantExpressionConversion(fromResult, sourceType))
+						&& IsEncompassingOrEncompassedBy(targetType, toType);
+				} else {
+					isApplicable = (IsEncompassedBy(fromType, sourceType) || ImplicitConstantExpressionConversion(fromResult, sourceType))
+						&& IsEncompassedBy(targetType, toType);
+				}
+				// Try if the operator is applicable in lifted form:
+				if (isApplicable) {
+					result.Add(new OperatorInfo(op, sourceType, targetType, false));
+				}
+				if (NullableType.IsNonNullableValueType(sourceType)) {
+					// An operator can be applicable in both lifted and non-lifted form in case of explicit conversions
+					IType liftedSourceType = NullableType.Create(compilation, sourceType);
+					IType liftedTargetType = NullableType.IsNonNullableValueType(targetType) ? NullableType.Create(compilation, targetType) : targetType;
+					if (isExplicit) {
+						isApplicable = IsEncompassingOrEncompassedBy(fromType, liftedSourceType)
+							&& IsEncompassingOrEncompassedBy(liftedTargetType, toType);
+					} else {
+						isApplicable = IsEncompassedBy(fromType, liftedSourceType) && IsEncompassedBy(liftedTargetType, toType);
+					}
+
+					if (isApplicable) {
+						result.Add(new OperatorInfo(op, liftedSourceType, liftedTargetType, true));
+					}
+				}
+			}
+			return result;
+		}
+		#endregion
+		
+		#region AnonymousFunctionConversion
+		Conversion AnonymousFunctionConversion(ResolveResult resolveResult, IType toType)
+		{
+			// C# 5.0 spec §6.5 Anonymous function conversions
+			LambdaResolveResult f = resolveResult as LambdaResolveResult;
+			if (f == null)
+				return Conversion.None;
+			if (!f.IsAnonymousMethod) {
+				// It's a lambda, so conversions to expression trees exist
+				// (even if the conversion leads to a compile-time error, e.g. for statement lambdas)
+				toType = UnpackExpressionTreeType(toType);
+			}
+			IMethod d = toType.GetDelegateInvokeMethod();
+			if (d == null)
+				return Conversion.None;
+			
+			IType[] dParamTypes = new IType[d.Parameters.Count];
+			for (int i = 0; i < dParamTypes.Length; i++) {
+				dParamTypes[i] = d.Parameters[i].Type;
+			}
+			IType dReturnType = d.ReturnType;
+			
+			if (f.HasParameterList) {
+				// If F contains an anonymous-function-signature, then D and F have the same number of parameters.
+				if (d.Parameters.Count != f.Parameters.Count)
+					return Conversion.None;
+				
+				if (f.IsImplicitlyTyped) {
+					// If F has an implicitly typed parameter list, D has no ref or out parameters.
+					foreach (IParameter p in d.Parameters) {
+						if (p.IsOut || p.IsRef)
+							return Conversion.None;
+					}
+				} else {
+					// If F has an explicitly typed parameter list, each parameter in D has the same type
+					// and modifiers as the corresponding parameter in F.
+					for (int i = 0; i < f.Parameters.Count; i++) {
+						IParameter pD = d.Parameters[i];
+						IParameter pF = f.Parameters[i];
+						if (pD.IsRef != pF.IsRef || pD.IsOut != pF.IsOut)
+							return Conversion.None;
+						if (!IdentityConversion(dParamTypes[i], pF.Type))
+							return Conversion.None;
+					}
+				}
+			} else {
+				// If F does not contain an anonymous-function-signature, then D may have zero or more parameters of any
+				// type, as long as no parameter of D has the out parameter modifier.
+				foreach (IParameter p in d.Parameters) {
+					if (p.IsOut)
+						return Conversion.None;
+				}
+			}
+			
+			return f.IsValid(dParamTypes, dReturnType, this);
+		}
+
+		static IType UnpackExpressionTreeType(IType type)
+		{
+			ParameterizedType pt = type as ParameterizedType;
+			if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Expression" && pt.Namespace == "System.Linq.Expressions") {
+				return pt.GetTypeArgument(0);
+			} else {
+				return type;
+			}
+		}
+		#endregion
+		
+		#region MethodGroupConversion
+		Conversion MethodGroupConversion(ResolveResult resolveResult, IType toType)
+		{
+			// C# 4.0 spec §6.6 Method group conversions
+			MethodGroupResolveResult rr = resolveResult as MethodGroupResolveResult;
+			if (rr == null)
+				return Conversion.None;
+			IMethod invoke = toType.GetDelegateInvokeMethod();
+			if (invoke == null)
+				return Conversion.None;
+			
+			ResolveResult[] args = new ResolveResult[invoke.Parameters.Count];
+			for (int i = 0; i < args.Length; i++) {
+				IParameter param = invoke.Parameters[i];
+				IType parameterType = param.Type;
+				if ((param.IsRef || param.IsOut) && parameterType.Kind == TypeKind.ByReference) {
+					parameterType = ((ByReferenceType)parameterType).ElementType;
+					args[i] = new ByReferenceResolveResult(parameterType, param.IsOut);
+				} else {
+					args[i] = new ResolveResult(parameterType);
+				}
+			}
+			var or = rr.PerformOverloadResolution(compilation, args, allowExpandingParams: false, allowOptionalParameters: false, conversions: this);
+			if (or.FoundApplicableCandidate) {
+				IMethod method = (IMethod)or.GetBestCandidateWithSubstitutedTypeArguments();
+				var thisRR = rr.TargetResult as ThisResolveResult;
+				bool isVirtual = method.IsOverridable && !(thisRR != null && thisRR.CausesNonVirtualInvocation);
+				bool isValid = !or.IsAmbiguous && IsDelegateCompatible(method, invoke, or.IsExtensionMethodInvocation);
+				bool delegateCapturesFirstArgument = or.IsExtensionMethodInvocation || !method.IsStatic;
+				if (isValid)
+					return Conversion.MethodGroupConversion(method, isVirtual, delegateCapturesFirstArgument);
+				else
+					return Conversion.InvalidMethodGroupConversion(method, isVirtual, delegateCapturesFirstArgument);
+			} else {
+				return Conversion.None;
+			}
+		}
+		
+		/// <summary>
+		/// Gets whether a <paramref name="method"/> is compatible with a delegate type.
+		/// §15.2 Delegate compatibility
+		/// </summary>
+		/// <param name="method">The method to test for compatibility</param>
+		/// <param name="delegateType">The delegate type</param>
+		public bool IsDelegateCompatible(IMethod method, IType delegateType)
+		{
+			if (method == null)
+				throw new ArgumentNullException("method");
+			if (delegateType == null)
+				throw new ArgumentNullException("delegateType");
+			IMethod invoke = delegateType.GetDelegateInvokeMethod();
+			if (invoke == null)
+				return false;
+			return IsDelegateCompatible(method, invoke, false);
+		}
+		
+		/// <summary>
+		/// Gets whether a method <paramref name="m"/> is compatible with a delegate type.
+		/// §15.2 Delegate compatibility
+		/// </summary>
+		/// <param name="m">The method to test for compatibility</param>
+		/// <param name="invoke">The invoke method of the delegate</param>
+		/// <param name="isExtensionMethodInvocation">Gets whether m is accessed using extension method syntax.
+		/// If this parameter is true, the first parameter of <paramref name="m"/> will be ignored.</param>
+		bool IsDelegateCompatible(IMethod m, IMethod invoke, bool isExtensionMethodInvocation)
+		{
+			if (m == null)
+				throw new ArgumentNullException("m");
+			if (invoke == null)
+				throw new ArgumentNullException("invoke");
+			int firstParameterInM = isExtensionMethodInvocation ? 1 : 0;
+			if (m.Parameters.Count - firstParameterInM != invoke.Parameters.Count)
+				return false;
+			for (int i = 0; i < invoke.Parameters.Count; i++) {
+				var pm = m.Parameters[firstParameterInM + i];
+				var pd = invoke.Parameters[i];
+				// ret/out must match
+				if (pm.IsRef != pd.IsRef || pm.IsOut != pd.IsOut)
+					return false;
+				if (pm.IsRef || pm.IsOut) {
+					// ref/out parameters must have same types
+					if (!pm.Type.Equals(pd.Type))
+						return false;
+				} else {
+					// non-ref/out parameters must have an identity or reference conversion from pd to pm
+					if (!IdentityConversion(pd.Type, pm.Type) && !IsImplicitReferenceConversion(pd.Type, pm.Type))
+						return false;
+				}
+			}
+			// check return type compatibility
+			return IdentityConversion(m.ReturnType, invoke.ReturnType)
+				|| IsImplicitReferenceConversion(m.ReturnType, invoke.ReturnType);
+		}
+		#endregion
+		
+		#region BetterConversion
+		/// <summary>
+		/// Gets the better conversion (C# 4.0 spec, §7.5.3.3)
+		/// </summary>
+		/// <returns>0 = neither is better; 1 = t1 is better; 2 = t2 is better</returns>
+		public int BetterConversion(ResolveResult resolveResult, IType t1, IType t2)
+		{
+			LambdaResolveResult lambda = resolveResult as LambdaResolveResult;
+			if (lambda != null) {
+				if (!lambda.IsAnonymousMethod) {
+					t1 = UnpackExpressionTreeType(t1);
+					t2 = UnpackExpressionTreeType(t2);
+				}
+				IMethod m1 = t1.GetDelegateInvokeMethod();
+				IMethod m2 = t2.GetDelegateInvokeMethod();
+				if (m1 == null || m2 == null)
+					return 0;
+				if (m1.Parameters.Count != m2.Parameters.Count)
+					return 0;
+				IType[] parameterTypes = new IType[m1.Parameters.Count];
+				for (int i = 0; i < parameterTypes.Length; i++) {
+					parameterTypes[i] = m1.Parameters[i].Type;
+					if (!parameterTypes[i].Equals(m2.Parameters[i].Type))
+						return 0;
+				}
+				if (lambda.HasParameterList && parameterTypes.Length != lambda.Parameters.Count)
+					return 0;
+				
+				IType ret1 = m1.ReturnType;
+				IType ret2 = m2.ReturnType;
+				if (ret1.Kind == TypeKind.Void && ret2.Kind != TypeKind.Void)
+					return 2;
+				if (ret1.Kind != TypeKind.Void && ret2.Kind == TypeKind.Void)
+					return 1;
+				
+				IType inferredRet = lambda.GetInferredReturnType(parameterTypes);
+				int r = BetterConversion(inferredRet, ret1, ret2);
+				if (r == 0 && lambda.IsAsync) {
+					ret1 = UnpackTask(ret1);
+					ret2 = UnpackTask(ret2);
+					inferredRet = UnpackTask(inferredRet);
+					if (ret1 != null && ret2 != null && inferredRet != null)
+						r = BetterConversion(inferredRet, ret1, ret2);
+				}
+				return r;
+			} else {
+				return BetterConversion(resolveResult.Type, t1, t2);
+			}
+		}
+		
+		/// <summary>
+		/// Unpacks the generic Task[T]. Returns null if the input is not Task[T].
+		/// </summary>
+		static IType UnpackTask(IType type)
+		{
+			ParameterizedType pt = type as ParameterizedType;
+			if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Task" && pt.Namespace == "System.Threading.Tasks") {
+				return pt.GetTypeArgument(0);
+			}
+			return null;
+		}
+		
+		/// <summary>
+		/// Gets the better conversion (C# 4.0 spec, §7.5.3.4)
+		/// </summary>
+		/// <returns>0 = neither is better; 1 = t1 is better; 2 = t2 is better</returns>
+		public int BetterConversion(IType s, IType t1, IType t2)
+		{
+			bool ident1 = IdentityConversion(s, t1);
+			bool ident2 = IdentityConversion(s, t2);
+			if (ident1 && !ident2)
+				return 1;
+			if (ident2 && !ident1)
+				return 2;
+			return BetterConversionTarget(t1, t2);
+		}
+		
+		/// <summary>
+		/// Gets the better conversion target (C# 4.0 spec, §7.5.3.5)
+		/// </summary>
+		/// <returns>0 = neither is better; 1 = t1 is better; 2 = t2 is better</returns>
+		int BetterConversionTarget(IType t1, IType t2)
+		{
+			bool t1To2 = ImplicitConversion(t1, t2).IsValid;
+			bool t2To1 = ImplicitConversion(t2, t1).IsValid;
+			if (t1To2 && !t2To1)
+				return 1;
+			if (t2To1 && !t1To2)
+				return 2;
+			TypeCode t1Code = ReflectionHelper.GetTypeCode(t1);
+			TypeCode t2Code = ReflectionHelper.GetTypeCode(t2);
+			if (IsBetterIntegralType(t1Code, t2Code))
+				return 1;
+			if (IsBetterIntegralType(t2Code, t1Code))
+				return 2;
+			return 0;
+		}
+		
+		bool IsBetterIntegralType(TypeCode t1, TypeCode t2)
+		{
+			// signed types are better than unsigned types
+			switch (t1) {
+				case TypeCode.SByte:
+					return t2 == TypeCode.Byte || t2 == TypeCode.UInt16 || t2 == TypeCode.UInt32 || t2 == TypeCode.UInt64;
+				case TypeCode.Int16:
+					return t2 == TypeCode.UInt16 || t2 == TypeCode.UInt32 || t2 == TypeCode.UInt64;
+				case TypeCode.Int32:
+					return t2 == TypeCode.UInt32 || t2 == TypeCode.UInt64;
+				case TypeCode.Int64:
+					return t2 == TypeCode.UInt64;
+				default:
+					return false;
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpInvocationResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpInvocationResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpInvocationResolveResult.cs	(revision 11807)
@@ -0,0 +1,145 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents the result of a method, constructor or indexer invocation.
+	/// Provides additional C#-specific information for InvocationResolveResult.
+	/// </summary>
+	public class CSharpInvocationResolveResult : InvocationResolveResult
+	{
+		public readonly OverloadResolutionErrors OverloadResolutionErrors;
+		
+		/// <summary>
+		/// Gets whether this invocation is calling an extension method using extension method syntax.
+		/// </summary>
+		public readonly bool IsExtensionMethodInvocation;
+		
+		/// <summary>
+		/// Gets whether this invocation is calling a delegate (without explicitly calling ".Invoke()").
+		/// </summary>
+		public readonly bool IsDelegateInvocation;
+		
+		/// <summary>
+		/// Gets whether a params-Array is being used in its expanded form.
+		/// </summary>
+		public readonly bool IsExpandedForm;
+		
+		readonly IList<int> argumentToParameterMap;
+
+		/// <summary>
+		/// If IsExtensionMethodInvocation is true this property holds the reduced method.
+		/// </summary>
+		IMethod reducedMethod;
+		public IMethod ReducedMethod {
+			get {
+				if (!IsExtensionMethodInvocation)
+					return null;
+				if (reducedMethod == null && Member is IMethod)
+					reducedMethod = new ReducedExtensionMethod ((IMethod)Member);
+				return reducedMethod;
+			}
+		}
+		
+		public CSharpInvocationResolveResult(
+			ResolveResult targetResult, IParameterizedMember member,
+			IList<ResolveResult> arguments,
+			OverloadResolutionErrors overloadResolutionErrors = OverloadResolutionErrors.None,
+			bool isExtensionMethodInvocation = false,
+			bool isExpandedForm = false,
+			bool isDelegateInvocation = false,
+			IList<int> argumentToParameterMap = null,
+			IList<ResolveResult> initializerStatements = null,
+			IType returnTypeOverride = null
+		)
+			: base(targetResult, member, arguments, initializerStatements, returnTypeOverride)
+		{
+			this.OverloadResolutionErrors = overloadResolutionErrors;
+			this.IsExtensionMethodInvocation = isExtensionMethodInvocation;
+			this.IsExpandedForm = isExpandedForm;
+			this.IsDelegateInvocation = isDelegateInvocation;
+			this.argumentToParameterMap = argumentToParameterMap;
+		}
+		
+		public override bool IsError {
+			get { return this.OverloadResolutionErrors != OverloadResolutionErrors.None; }
+		}
+		
+		/// <summary>
+		/// Gets an array that maps argument indices to parameter indices.
+		/// For arguments that could not be mapped to any parameter, the value will be -1.
+		/// 
+		/// parameterIndex = ArgumentToParameterMap[argumentIndex]
+		/// </summary>
+		public IList<int> GetArgumentToParameterMap()
+		{
+			return argumentToParameterMap;
+		}
+		
+		public override IList<ResolveResult> GetArgumentsForCall()
+		{
+			ResolveResult[] results = new ResolveResult[Member.Parameters.Count];
+			List<ResolveResult> paramsArguments = IsExpandedForm ? new List<ResolveResult>() : null;
+			// map arguments to parameters:
+			for (int i = 0; i < Arguments.Count; i++) {
+				int mappedTo;
+				if (argumentToParameterMap != null)
+					mappedTo = argumentToParameterMap[i];
+				else
+					mappedTo = IsExpandedForm ? Math.Min(i, results.Length - 1) : i;
+				
+				if (mappedTo >= 0 && mappedTo < results.Length) {
+					if (IsExpandedForm && mappedTo == results.Length - 1) {
+						paramsArguments.Add(Arguments[i]);
+					} else {
+						var narr = Arguments[i] as NamedArgumentResolveResult;
+						if (narr != null)
+							results[mappedTo] = narr.Argument;
+						else
+							results[mappedTo] = Arguments[i];
+					}
+				}
+			}
+			if (IsExpandedForm){
+				IType arrayType = Member.Parameters.Last().Type;
+				IType int32 = Member.Compilation.FindType(KnownTypeCode.Int32);
+				ResolveResult[] sizeArguments = { new ConstantResolveResult(int32, paramsArguments.Count) };
+				results[results.Length - 1] = new ArrayCreateResolveResult(arrayType, sizeArguments, paramsArguments);
+			}
+			
+			for (int i = 0; i < results.Length; i++) {
+				if (results[i] == null) {
+					if (Member.Parameters[i].IsOptional) {
+						results[i] = new ConstantResolveResult(Member.Parameters[i].Type, Member.Parameters[i].ConstantValue);
+					} else {
+						results[i] = ErrorResolveResult.UnknownError;
+					}
+				}
+			}
+			
+			return results;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpOperators.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpOperators.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpOperators.cs	(revision 11807)
@@ -0,0 +1,1059 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	sealed class CSharpOperators
+	{
+		readonly ICompilation compilation;
+		
+		private CSharpOperators(ICompilation compilation)
+		{
+			this.compilation = compilation;
+			InitParameterArrays();
+		}
+		
+		/// <summary>
+		/// Gets the CSharpOperators instance for the specified <see cref="ICompilation"/>.
+		/// This will make use of the context's cache manager (if available) to reuse the CSharpOperators instance.
+		/// </summary>
+		public static CSharpOperators Get(ICompilation compilation)
+		{
+			CacheManager cache = compilation.CacheManager;
+			CSharpOperators operators = (CSharpOperators)cache.GetShared(typeof(CSharpOperators));
+			if (operators == null) {
+				operators = (CSharpOperators)cache.GetOrAddShared(typeof(CSharpOperators), new CSharpOperators(compilation));
+			}
+			return operators;
+		}
+		
+		#region class OperatorMethod
+		OperatorMethod[] Lift(params OperatorMethod[] methods)
+		{
+			List<OperatorMethod> result = new List<OperatorMethod>(methods);
+			foreach (OperatorMethod method in methods) {
+				OperatorMethod lifted = method.Lift(this);
+				if (lifted != null)
+					result.Add(lifted);
+			}
+			return result.ToArray();
+		}
+		
+		IParameter[] normalParameters = new IParameter[(int)(TypeCode.String + 1 - TypeCode.Object)];
+		IParameter[] nullableParameters = new IParameter[(int)(TypeCode.Decimal + 1 - TypeCode.Boolean)];
+		
+		void InitParameterArrays()
+		{
+			for (TypeCode i = TypeCode.Object; i <= TypeCode.String; i++) {
+				normalParameters[i - TypeCode.Object] = new DefaultParameter(compilation.FindType(i), string.Empty);
+			}
+			for (TypeCode i = TypeCode.Boolean; i <= TypeCode.Decimal; i++) {
+				IType type = NullableType.Create(compilation, compilation.FindType(i));
+				nullableParameters[i - TypeCode.Boolean] = new DefaultParameter(type, string.Empty);
+			}
+		}
+		
+		IParameter MakeParameter(TypeCode code)
+		{
+			return normalParameters[code - TypeCode.Object];
+		}
+		
+		IParameter MakeNullableParameter(IParameter normalParameter)
+		{
+			for (TypeCode i = TypeCode.Boolean; i <= TypeCode.Decimal; i++) {
+				if (normalParameter == normalParameters[i - TypeCode.Object])
+					return nullableParameters[i - TypeCode.Boolean];
+			}
+			throw new ArgumentException();
+		}
+		
+		internal class OperatorMethod : IParameterizedMember
+		{
+			readonly ICompilation compilation;
+			readonly IList<IParameter> parameters = new List<IParameter>();
+			
+			protected OperatorMethod(ICompilation compilation)
+			{
+				this.compilation = compilation;
+			}
+			
+			public IList<IParameter> Parameters {
+				get { return parameters; }
+			}
+			
+			public IType ReturnType { get; internal set; }
+			
+			public ICompilation Compilation {
+				get { return compilation; }
+			}
+			
+			public virtual OperatorMethod Lift(CSharpOperators operators)
+			{
+				return null;
+			}
+			
+			ITypeDefinition IEntity.DeclaringTypeDefinition {
+				get { return null; }
+			}
+			
+			IType IEntity.DeclaringType {
+				get { return SpecialType.UnknownType; }
+			}
+			
+			IMember IMember.MemberDefinition {
+				get { return this; }
+			}
+			
+			IUnresolvedMember IMember.UnresolvedMember {
+				get { return null; }
+			}
+			
+			IList<IMember> IMember.ImplementedInterfaceMembers {
+				get { return EmptyList<IMember>.Instance; }
+			}
+			
+			bool IMember.IsVirtual {
+				get { return false; }
+			}
+			
+			bool IMember.IsOverride {
+				get { return false; }
+			}
+			
+			bool IMember.IsOverridable {
+				get { return false; }
+			}
+			
+			SymbolKind ISymbol.SymbolKind {
+				get { return SymbolKind.Operator; }
+			}
+			
+			[Obsolete("Use the SymbolKind property instead.")]
+			EntityType IEntity.EntityType {
+				get { return EntityType.Operator; }
+			}
+			
+			DomRegion IEntity.Region {
+				get { return DomRegion.Empty; }
+			}
+			
+			DomRegion IEntity.BodyRegion {
+				get { return DomRegion.Empty; }
+			}
+			
+			IList<IAttribute> IEntity.Attributes {
+				get { return EmptyList<IAttribute>.Instance; }
+			}
+			
+			Documentation.DocumentationComment IEntity.Documentation {
+				get { return null; }
+			}
+			
+			Accessibility IHasAccessibility.Accessibility {
+				get { return Accessibility.Public; }
+			}
+			
+			bool IEntity.IsStatic {
+				get { return true; }
+			}
+			
+			bool IEntity.IsAbstract {
+				get { return false; }
+			}
+			
+			bool IEntity.IsSealed {
+				get { return false; }
+			}
+			
+			bool IEntity.IsShadowing {
+				get { return false; }
+			}
+			
+			bool IEntity.IsSynthetic {
+				get { return true; }
+			}
+			
+			bool IHasAccessibility.IsPrivate {
+				get { return false; }
+			}
+			
+			bool IHasAccessibility.IsPublic {
+				get { return true; }
+			}
+			
+			bool IHasAccessibility.IsProtected {
+				get { return false; }
+			}
+			
+			bool IHasAccessibility.IsInternal {
+				get { return false; }
+			}
+			
+			bool IHasAccessibility.IsProtectedOrInternal {
+				get { return false; }
+			}
+			
+			bool IHasAccessibility.IsProtectedAndInternal {
+				get { return false; }
+			}
+			
+			bool IMember.IsExplicitInterfaceImplementation {
+				get { return false; }
+			}
+			
+			IAssembly IEntity.ParentAssembly {
+				get { return compilation.MainAssembly; }
+			}
+			
+			IMemberReference IMember.ToMemberReference()
+			{
+				throw new NotSupportedException();
+			}
+			
+			ISymbolReference ISymbol.ToReference()
+			{
+				throw new NotSupportedException();
+			}
+			
+			IMemberReference IMember.ToReference()
+			{
+				throw new NotSupportedException();
+			}
+
+			TypeParameterSubstitution IMember.Substitution {
+				get {
+					return TypeParameterSubstitution.Identity;
+				}
+			}
+
+			IMember IMember.Specialize(TypeParameterSubstitution substitution)
+			{
+				if (TypeParameterSubstitution.Identity.Equals(substitution))
+					return this;
+				throw new NotSupportedException();
+			}
+
+			string INamedElement.FullName {
+				get { return "operator"; }
+			}
+			
+			public string Name {
+				get { return "operator"; }
+			}
+			
+			string INamedElement.Namespace {
+				get { return string.Empty; }
+			}
+			
+			string INamedElement.ReflectionName {
+				get { return "operator"; }
+			}
+			
+			public override string ToString()
+			{
+				StringBuilder b = new StringBuilder();
+				b.Append(ReturnType + " operator(");
+				for (int i = 0; i < parameters.Count; i++) {
+					if (i > 0)
+						b.Append(", ");
+					b.Append(parameters[i].Type);
+				}
+				b.Append(')');
+				return b.ToString();
+			}
+		}
+		#endregion
+		
+		#region Unary operator class definitions
+		internal class UnaryOperatorMethod : OperatorMethod
+		{
+			public virtual bool CanEvaluateAtCompileTime { get { return false; } }
+			
+			public virtual object Invoke(CSharpResolver resolver, object input)
+			{
+				throw new NotSupportedException();
+			}
+			
+			public UnaryOperatorMethod(ICompilation compilaton) : base(compilaton)
+			{
+			}
+		}
+		
+		sealed class LambdaUnaryOperatorMethod<T> : UnaryOperatorMethod
+		{
+			readonly Func<T, T> func;
+			
+			public LambdaUnaryOperatorMethod(CSharpOperators operators, Func<T, T> func)
+				: base(operators.compilation)
+			{
+				TypeCode typeCode = Type.GetTypeCode(typeof(T));
+				this.ReturnType = operators.compilation.FindType(typeCode);
+				this.Parameters.Add(operators.MakeParameter(typeCode));
+				this.func = func;
+			}
+			
+			public override bool CanEvaluateAtCompileTime {
+				get { return true; }
+			}
+			
+			public override object Invoke(CSharpResolver resolver, object input)
+			{
+				if (input == null)
+					return null;
+				return func((T)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T)), input));
+			}
+			
+			public override OperatorMethod Lift(CSharpOperators operators)
+			{
+				return new LiftedUnaryOperatorMethod(operators, this);
+			}
+		}
+		
+		sealed class LiftedUnaryOperatorMethod : UnaryOperatorMethod, OverloadResolution.ILiftedOperator
+		{
+			UnaryOperatorMethod baseMethod;
+			
+			public LiftedUnaryOperatorMethod(CSharpOperators operators, UnaryOperatorMethod baseMethod) : base(operators.compilation)
+			{
+				this.baseMethod = baseMethod;
+				this.ReturnType = NullableType.Create(baseMethod.Compilation, baseMethod.ReturnType);
+				this.Parameters.Add(operators.MakeNullableParameter(baseMethod.Parameters[0]));
+			}
+			
+			public IList<IParameter> NonLiftedParameters {
+				get { return baseMethod.Parameters; }
+			}
+		}
+		#endregion
+		
+		#region Unary operator definitions
+		// C# 4.0 spec: §7.7.1 Unary plus operator
+		OperatorMethod[] unaryPlusOperators;
+		
+		public OperatorMethod[] UnaryPlusOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref unaryPlusOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref unaryPlusOperators, Lift(
+						new LambdaUnaryOperatorMethod<int>    (this, i => +i),
+						new LambdaUnaryOperatorMethod<uint>   (this, i => +i),
+						new LambdaUnaryOperatorMethod<long>   (this, i => +i),
+						new LambdaUnaryOperatorMethod<ulong>  (this, i => +i),
+						new LambdaUnaryOperatorMethod<float>  (this, i => +i),
+						new LambdaUnaryOperatorMethod<double> (this, i => +i),
+						new LambdaUnaryOperatorMethod<decimal>(this, i => +i)
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.7.2 Unary minus operator
+		OperatorMethod[] uncheckedUnaryMinusOperators;
+		
+		public OperatorMethod[] UncheckedUnaryMinusOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref uncheckedUnaryMinusOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref uncheckedUnaryMinusOperators, Lift(
+						new LambdaUnaryOperatorMethod<int>    (this, i => unchecked(-i)),
+						new LambdaUnaryOperatorMethod<long>   (this, i => unchecked(-i)),
+						new LambdaUnaryOperatorMethod<float>  (this, i => unchecked(-i)),
+						new LambdaUnaryOperatorMethod<double> (this, i => unchecked(-i)),
+						new LambdaUnaryOperatorMethod<decimal>(this, i => unchecked(-i))
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] checkedUnaryMinusOperators;
+		
+		public OperatorMethod[] CheckedUnaryMinusOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref checkedUnaryMinusOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref checkedUnaryMinusOperators, Lift(
+						new LambdaUnaryOperatorMethod<int>    (this, i => checked(-i)),
+						new LambdaUnaryOperatorMethod<long>   (this, i => checked(-i)),
+						new LambdaUnaryOperatorMethod<float>  (this, i => checked(-i)),
+						new LambdaUnaryOperatorMethod<double> (this, i => checked(-i)),
+						new LambdaUnaryOperatorMethod<decimal>(this, i => checked(-i))
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.7.3 Logical negation operator
+		OperatorMethod[] logicalNegationOperators;
+		
+		public OperatorMethod[] LogicalNegationOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref logicalNegationOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref logicalNegationOperators, Lift(
+						new LambdaUnaryOperatorMethod<bool>(this, b => !b)
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.7.4 Bitwise complement operator
+		OperatorMethod[] bitwiseComplementOperators;
+		
+		public OperatorMethod[] BitwiseComplementOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseComplementOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref bitwiseComplementOperators, Lift(
+						new LambdaUnaryOperatorMethod<int>  (this, i => ~i),
+						new LambdaUnaryOperatorMethod<uint> (this, i => ~i),
+						new LambdaUnaryOperatorMethod<long> (this, i => ~i),
+						new LambdaUnaryOperatorMethod<ulong>(this, i => ~i)
+					));
+				}
+			}
+		}
+		#endregion
+		
+		#region Binary operator class definitions
+		internal class BinaryOperatorMethod : OperatorMethod
+		{
+			public virtual bool CanEvaluateAtCompileTime { get { return false; } }
+			public virtual object Invoke(CSharpResolver resolver, object lhs, object rhs) {
+				throw new NotSupportedException();
+			}
+			
+			public BinaryOperatorMethod(ICompilation compilation) : base(compilation) {}
+		}
+		
+		sealed class LambdaBinaryOperatorMethod<T1, T2> : BinaryOperatorMethod
+		{
+			readonly Func<T1, T2, T1> checkedFunc;
+			readonly Func<T1, T2, T1> uncheckedFunc;
+			
+			public LambdaBinaryOperatorMethod(CSharpOperators operators, Func<T1, T2, T1> func)
+				: this(operators, func, func)
+			{
+			}
+			
+			public LambdaBinaryOperatorMethod(CSharpOperators operators, Func<T1, T2, T1> checkedFunc, Func<T1, T2, T1> uncheckedFunc)
+				: base(operators.compilation)
+			{
+				TypeCode t1 = Type.GetTypeCode(typeof(T1));
+				this.ReturnType = operators.compilation.FindType(t1);
+				this.Parameters.Add(operators.MakeParameter(t1));
+				this.Parameters.Add(operators.MakeParameter(Type.GetTypeCode(typeof(T2))));
+				this.checkedFunc = checkedFunc;
+				this.uncheckedFunc = uncheckedFunc;
+			}
+			
+			public override bool CanEvaluateAtCompileTime {
+				get { return true; }
+			}
+			
+			public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
+			{
+				if (lhs == null || rhs == null)
+					return null;
+				Func<T1, T2, T1> func = resolver.CheckForOverflow ? checkedFunc : uncheckedFunc;
+				return func((T1)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T1)), lhs),
+				            (T2)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T2)), rhs));
+			}
+			
+			public override OperatorMethod Lift(CSharpOperators operators)
+			{
+				return new LiftedBinaryOperatorMethod(operators, this);
+			}
+		}
+		
+		sealed class LiftedBinaryOperatorMethod : BinaryOperatorMethod, OverloadResolution.ILiftedOperator
+		{
+			readonly BinaryOperatorMethod baseMethod;
+			
+			public LiftedBinaryOperatorMethod(CSharpOperators operators, BinaryOperatorMethod baseMethod)
+				: base(operators.compilation)
+			{
+				this.baseMethod = baseMethod;
+				this.ReturnType = NullableType.Create(operators.compilation, baseMethod.ReturnType);
+				this.Parameters.Add(operators.MakeNullableParameter(baseMethod.Parameters[0]));
+				this.Parameters.Add(operators.MakeNullableParameter(baseMethod.Parameters[1]));
+			}
+			
+			public IList<IParameter> NonLiftedParameters {
+				get { return baseMethod.Parameters; }
+			}
+		}
+		#endregion
+		
+		#region Arithmetic operators
+		// C# 4.0 spec: §7.8.1 Multiplication operator
+		
+		OperatorMethod[] multiplicationOperators;
+		
+		public OperatorMethod[] MultiplicationOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref multiplicationOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref multiplicationOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,     int>    (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
+						new LambdaBinaryOperatorMethod<uint,    uint>   (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
+						new LambdaBinaryOperatorMethod<long,    long>   (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
+						new LambdaBinaryOperatorMethod<ulong,   ulong>  (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
+						new LambdaBinaryOperatorMethod<float,   float>  (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
+						new LambdaBinaryOperatorMethod<double,  double> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
+						new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a * b), (a, b) => unchecked(a * b))
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.8.2 Division operator
+		OperatorMethod[] divisionOperators;
+		
+		public OperatorMethod[] DivisionOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref divisionOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref divisionOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,     int>    (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
+						new LambdaBinaryOperatorMethod<uint,    uint>   (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
+						new LambdaBinaryOperatorMethod<long,    long>   (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
+						new LambdaBinaryOperatorMethod<ulong,   ulong>  (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
+						new LambdaBinaryOperatorMethod<float,   float>  (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
+						new LambdaBinaryOperatorMethod<double,  double> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
+						new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a / b), (a, b) => unchecked(a / b))
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.8.3 Remainder operator
+		OperatorMethod[] remainderOperators;
+		
+		public OperatorMethod[] RemainderOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref remainderOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref remainderOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,     int>    (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
+						new LambdaBinaryOperatorMethod<uint,    uint>   (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
+						new LambdaBinaryOperatorMethod<long,    long>   (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
+						new LambdaBinaryOperatorMethod<ulong,   ulong>  (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
+						new LambdaBinaryOperatorMethod<float,   float>  (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
+						new LambdaBinaryOperatorMethod<double,  double> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
+						new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a % b), (a, b) => unchecked(a % b))
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.8.3 Addition operator
+		OperatorMethod[] additionOperators;
+		
+		public OperatorMethod[] AdditionOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref additionOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref additionOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,     int>    (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new LambdaBinaryOperatorMethod<uint,    uint>   (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new LambdaBinaryOperatorMethod<long,    long>   (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new LambdaBinaryOperatorMethod<ulong,   ulong>  (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new LambdaBinaryOperatorMethod<float,   float>  (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new LambdaBinaryOperatorMethod<double,  double> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
+						new StringConcatenation(this, TypeCode.String, TypeCode.String),
+						new StringConcatenation(this, TypeCode.String, TypeCode.Object),
+						new StringConcatenation(this, TypeCode.Object, TypeCode.String)
+					));
+				}
+			}
+		}
+		
+		// not in this list, but handled manually: enum addition, delegate combination
+		sealed class StringConcatenation : BinaryOperatorMethod
+		{
+			bool canEvaluateAtCompileTime;
+			
+			public StringConcatenation(CSharpOperators operators, TypeCode p1, TypeCode p2)
+				: base(operators.compilation)
+			{
+				this.canEvaluateAtCompileTime = p1 == TypeCode.String && p2 == TypeCode.String;
+				this.ReturnType = operators.compilation.FindType(KnownTypeCode.String);
+				this.Parameters.Add(operators.MakeParameter(p1));
+				this.Parameters.Add(operators.MakeParameter(p2));
+			}
+			
+			public override bool CanEvaluateAtCompileTime {
+				get { return canEvaluateAtCompileTime; }
+			}
+			
+			public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
+			{
+				return string.Concat(lhs, rhs);
+			}
+		}
+		
+		// C# 4.0 spec: §7.8.4 Subtraction operator
+		OperatorMethod[] subtractionOperators;
+		
+		public OperatorMethod[] SubtractionOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref subtractionOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref subtractionOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,     int>    (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
+						new LambdaBinaryOperatorMethod<uint,    uint>   (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
+						new LambdaBinaryOperatorMethod<long,    long>   (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
+						new LambdaBinaryOperatorMethod<ulong,   ulong>  (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
+						new LambdaBinaryOperatorMethod<float,   float>  (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
+						new LambdaBinaryOperatorMethod<double,  double> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
+						new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a - b), (a, b) => unchecked(a - b))
+					));
+				}
+			}
+		}
+		
+		// C# 4.0 spec: §7.8.5 Shift operators
+		OperatorMethod[] shiftLeftOperators;
+		
+		public OperatorMethod[] ShiftLeftOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref shiftLeftOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref shiftLeftOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,   int>(this, (a, b) => a << b),
+						new LambdaBinaryOperatorMethod<uint,  int>(this, (a, b) => a << b),
+						new LambdaBinaryOperatorMethod<long,  int>(this, (a, b) => a << b),
+						new LambdaBinaryOperatorMethod<ulong, int>(this, (a, b) => a << b)
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] shiftRightOperators;
+		
+		public OperatorMethod[] ShiftRightOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref shiftRightOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref shiftRightOperators, Lift(
+						new LambdaBinaryOperatorMethod<int,   int>(this, (a, b) => a >> b),
+						new LambdaBinaryOperatorMethod<uint,  int>(this, (a, b) => a >> b),
+						new LambdaBinaryOperatorMethod<long,  int>(this, (a, b) => a >> b),
+						new LambdaBinaryOperatorMethod<ulong, int>(this, (a, b) => a >> b)
+					));
+				}
+			}
+		}
+		#endregion
+		
+		#region Equality operators
+		sealed class EqualityOperatorMethod : BinaryOperatorMethod
+		{
+			public readonly TypeCode Type;
+			public readonly bool Negate;
+			
+			public EqualityOperatorMethod(CSharpOperators operators, TypeCode type, bool negate)
+				: base(operators.compilation)
+			{
+				this.Negate = negate;
+				this.Type = type;
+				this.ReturnType = operators.compilation.FindType(KnownTypeCode.Boolean);
+				this.Parameters.Add(operators.MakeParameter(type));
+				this.Parameters.Add(operators.MakeParameter(type));
+			}
+			
+			public override bool CanEvaluateAtCompileTime {
+				get { return Type != TypeCode.Object; }
+			}
+			
+			public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
+			{
+				if (lhs == null && rhs == null)
+					return !Negate; // ==: true; !=: false
+				if (lhs == null || rhs == null)
+					return Negate; // ==: false; !=: true
+				lhs = resolver.CSharpPrimitiveCast(Type, lhs);
+				rhs = resolver.CSharpPrimitiveCast(Type, rhs);
+				bool equal;
+				if (Type == TypeCode.Single) {
+					equal = (float)lhs == (float)rhs;
+				} else if (Type == TypeCode.Double) {
+					equal = (double)lhs == (double)rhs;
+				} else {
+					equal = object.Equals(lhs, rhs);
+				}
+				return equal ^ Negate;
+			}
+			
+			public override OperatorMethod Lift(CSharpOperators operators)
+			{
+				if (Type == TypeCode.Object || Type == TypeCode.String)
+					return null;
+				else
+					return new LiftedEqualityOperatorMethod(operators, this);
+			}
+		}
+		
+		sealed class LiftedEqualityOperatorMethod : BinaryOperatorMethod, OverloadResolution.ILiftedOperator
+		{
+			readonly EqualityOperatorMethod baseMethod;
+			
+			public LiftedEqualityOperatorMethod(CSharpOperators operators, EqualityOperatorMethod baseMethod)
+				: base(operators.compilation)
+			{
+				this.baseMethod = baseMethod;
+				this.ReturnType = baseMethod.ReturnType;
+				IParameter p = operators.MakeNullableParameter(baseMethod.Parameters[0]);
+				this.Parameters.Add(p);
+				this.Parameters.Add(p);
+			}
+			
+			public override bool CanEvaluateAtCompileTime {
+				get { return baseMethod.CanEvaluateAtCompileTime; }
+			}
+			
+			public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
+			{
+				return baseMethod.Invoke(resolver, lhs, rhs);
+			}
+			
+			public IList<IParameter> NonLiftedParameters {
+				get { return baseMethod.Parameters; }
+			}
+		}
+		
+		// C# 4.0 spec: §7.10 Relational and type-testing operators
+		static readonly TypeCode[] valueEqualityOperatorsFor = {
+			TypeCode.Int32, TypeCode.UInt32,
+			TypeCode.Int64, TypeCode.UInt64,
+			TypeCode.Single, TypeCode.Double,
+			TypeCode.Decimal,
+			TypeCode.Boolean
+		};
+		
+		OperatorMethod[] valueEqualityOperators;
+		
+		public OperatorMethod[] ValueEqualityOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref valueEqualityOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref valueEqualityOperators, Lift(
+						valueEqualityOperatorsFor.Select(c => new EqualityOperatorMethod(this, c, false)).ToArray()
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] valueInequalityOperators;
+		
+		public OperatorMethod[] ValueInequalityOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref valueInequalityOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref valueInequalityOperators, Lift(
+						valueEqualityOperatorsFor.Select(c => new EqualityOperatorMethod(this, c, true)).ToArray()
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] referenceEqualityOperators;
+		
+		public OperatorMethod[] ReferenceEqualityOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref referenceEqualityOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref referenceEqualityOperators, Lift(
+						new EqualityOperatorMethod(this, TypeCode.Object, false),
+						new EqualityOperatorMethod(this, TypeCode.String, false)
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] referenceInequalityOperators;
+		
+		public OperatorMethod[] ReferenceInequalityOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref referenceInequalityOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref referenceInequalityOperators, Lift(
+						new EqualityOperatorMethod(this, TypeCode.Object, true),
+						new EqualityOperatorMethod(this, TypeCode.String, true)
+					));
+				}
+			}
+		}
+		#endregion
+		
+		#region Relational Operators
+		sealed class RelationalOperatorMethod<T1, T2> : BinaryOperatorMethod
+		{
+			readonly Func<T1, T2, bool> func;
+			
+			public RelationalOperatorMethod(CSharpOperators operators, Func<T1, T2, bool> func)
+				: base(operators.compilation)
+			{
+				this.ReturnType = operators.compilation.FindType(KnownTypeCode.Boolean);
+				this.Parameters.Add(operators.MakeParameter(Type.GetTypeCode(typeof(T1))));
+				this.Parameters.Add(operators.MakeParameter(Type.GetTypeCode(typeof(T2))));
+				this.func = func;
+			}
+			
+			public override bool CanEvaluateAtCompileTime {
+				get { return true; }
+			}
+			
+			public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
+			{
+				if (lhs == null || rhs == null)
+					return null;
+				return func((T1)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T1)), lhs),
+				            (T2)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T2)), rhs));
+			}
+			
+			public override OperatorMethod Lift(CSharpOperators operators)
+			{
+				var lifted = new LiftedBinaryOperatorMethod(operators, this);
+				lifted.ReturnType = this.ReturnType; // don't lift the return type for relational operators
+				return lifted;
+			}
+		}
+		
+		OperatorMethod[] lessThanOperators;
+		
+		public OperatorMethod[] LessThanOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref lessThanOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref lessThanOperators, Lift(
+						new RelationalOperatorMethod<int, int>        (this, (a, b) => a < b),
+						new RelationalOperatorMethod<uint, uint>      (this, (a, b) => a < b),
+						new RelationalOperatorMethod<long, long>      (this, (a, b) => a < b),
+						new RelationalOperatorMethod<ulong, ulong>    (this, (a, b) => a < b),
+						new RelationalOperatorMethod<float, float>    (this, (a, b) => a < b),
+						new RelationalOperatorMethod<double, double>  (this, (a, b) => a < b),
+						new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a < b)
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] lessThanOrEqualOperators;
+		
+		public OperatorMethod[] LessThanOrEqualOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref lessThanOrEqualOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref lessThanOrEqualOperators, Lift(
+						new RelationalOperatorMethod<int, int>        (this, (a, b) => a <= b),
+						new RelationalOperatorMethod<uint, uint>      (this, (a, b) => a <= b),
+						new RelationalOperatorMethod<long, long>      (this, (a, b) => a <= b),
+						new RelationalOperatorMethod<ulong, ulong>    (this, (a, b) => a <= b),
+						new RelationalOperatorMethod<float, float>    (this, (a, b) => a <= b),
+						new RelationalOperatorMethod<double, double>  (this, (a, b) => a <= b),
+						new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a <= b)
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] greaterThanOperators;
+		
+		public OperatorMethod[] GreaterThanOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref greaterThanOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref greaterThanOperators, Lift(
+						new RelationalOperatorMethod<int, int>        (this, (a, b) => a > b),
+						new RelationalOperatorMethod<uint, uint>      (this, (a, b) => a > b),
+						new RelationalOperatorMethod<long, long>      (this, (a, b) => a > b),
+						new RelationalOperatorMethod<ulong, ulong>    (this, (a, b) => a > b),
+						new RelationalOperatorMethod<float, float>    (this, (a, b) => a > b),
+						new RelationalOperatorMethod<double, double>  (this, (a, b) => a > b),
+						new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a > b)
+					));
+				}
+			}
+		}
+		
+		OperatorMethod[] greaterThanOrEqualOperators;
+		
+		public OperatorMethod[] GreaterThanOrEqualOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref greaterThanOrEqualOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref greaterThanOrEqualOperators, Lift(
+						new RelationalOperatorMethod<int, int>        (this, (a, b) => a >= b),
+						new RelationalOperatorMethod<uint, uint>      (this, (a, b) => a >= b),
+						new RelationalOperatorMethod<long, long>      (this, (a, b) => a >= b),
+						new RelationalOperatorMethod<ulong, ulong>    (this, (a, b) => a >= b),
+						new RelationalOperatorMethod<float, float>    (this, (a, b) => a >= b),
+						new RelationalOperatorMethod<double, double>  (this, (a, b) => a >= b),
+						new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a >= b)
+					));
+				}
+			}
+		}
+		#endregion
+		
+		#region Bitwise operators
+		OperatorMethod[] logicalAndOperators;
+		
+		public OperatorMethod[] LogicalAndOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref logicalAndOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref logicalAndOperators, new OperatorMethod[] {
+					                         	new LambdaBinaryOperatorMethod<bool, bool>(this, (a, b) => a & b)
+					                         });
+				}
+			}
+		}
+		
+		
+		OperatorMethod[] bitwiseAndOperators;
+		
+		public OperatorMethod[] BitwiseAndOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseAndOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref bitwiseAndOperators, Lift(
+						new LambdaBinaryOperatorMethod<int, int>    (this, (a, b) => a & b),
+						new LambdaBinaryOperatorMethod<uint, uint>  (this, (a, b) => a & b),
+						new LambdaBinaryOperatorMethod<long, long>  (this, (a, b) => a & b),
+						new LambdaBinaryOperatorMethod<ulong, ulong>(this, (a, b) => a & b),
+						this.LogicalAndOperators[0]
+					));
+				}
+			}
+		}
+		
+		
+		OperatorMethod[] logicalOrOperators;
+		
+		public OperatorMethod[] LogicalOrOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref logicalOrOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref logicalOrOperators, new OperatorMethod[] {
+					                         	new LambdaBinaryOperatorMethod<bool, bool>(this, (a, b) => a | b)
+					                         });
+				}
+			}
+		}
+		
+		OperatorMethod[] bitwiseOrOperators;
+		
+		public OperatorMethod[] BitwiseOrOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseOrOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref bitwiseOrOperators, Lift(
+						new LambdaBinaryOperatorMethod<int, int>    (this, (a, b) => a | b),
+						new LambdaBinaryOperatorMethod<uint, uint>  (this, (a, b) => a | b),
+						new LambdaBinaryOperatorMethod<long, long>  (this, (a, b) => a | b),
+						new LambdaBinaryOperatorMethod<ulong, ulong>(this, (a, b) => a | b),
+						this.LogicalOrOperators[0]
+					));
+				}
+			}
+		}
+		
+		// Note: the logic for the lifted bool? bitwise operators is wrong;
+		// we produce "true | null" = "null" when it should be true. However, this is irrelevant
+		// because bool? cannot be a compile-time type.
+		
+		OperatorMethod[] bitwiseXorOperators;
+
+		public OperatorMethod[] BitwiseXorOperators {
+			get {
+				OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseXorOperators);
+				if (ops != null) {
+					return ops;
+				} else {
+					return LazyInit.GetOrSet(ref bitwiseXorOperators, Lift(
+						new LambdaBinaryOperatorMethod<int, int>    (this, (a, b) => a ^ b),
+						new LambdaBinaryOperatorMethod<uint, uint>  (this, (a, b) => a ^ b),
+						new LambdaBinaryOperatorMethod<long, long>  (this, (a, b) => a ^ b),
+						new LambdaBinaryOperatorMethod<ulong, ulong>(this, (a, b) => a ^ b),
+						new LambdaBinaryOperatorMethod<bool, bool>  (this, (a, b) => a ^ b)
+					));
+				}
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpResolver.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpResolver.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CSharpResolver.cs	(revision 11807)
@@ -0,0 +1,2619 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Contains the main resolver logic.
+	/// </summary>
+	/// <remarks>
+	/// This class is thread-safe.
+	/// </remarks>
+	public class CSharpResolver : ICodeContext
+	{
+		static readonly ResolveResult ErrorResult = ErrorResolveResult.UnknownError;
+		readonly ICompilation compilation;
+		internal readonly CSharpConversions conversions;
+		readonly CSharpTypeResolveContext context;
+		readonly bool checkForOverflow;
+		readonly bool isWithinLambdaExpression;
+		
+		#region Constructor
+		public CSharpResolver(ICompilation compilation)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			this.compilation = compilation;
+			this.conversions = CSharpConversions.Get(compilation);
+			this.context = new CSharpTypeResolveContext(compilation.MainAssembly);
+			
+			var pc = compilation.MainAssembly.UnresolvedAssembly as CSharpProjectContent;
+			if (pc != null) {
+				this.checkForOverflow = pc.CompilerSettings.CheckForOverflow;
+			}
+		}
+		
+		public CSharpResolver(CSharpTypeResolveContext context)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			this.compilation = context.Compilation;
+			this.conversions = CSharpConversions.Get(compilation);
+			this.context = context;
+			if (context.CurrentTypeDefinition != null)
+				currentTypeDefinitionCache = new TypeDefinitionCache(context.CurrentTypeDefinition);
+		}
+		
+		private CSharpResolver(ICompilation compilation, CSharpConversions conversions, CSharpTypeResolveContext context, bool checkForOverflow, bool isWithinLambdaExpression, TypeDefinitionCache currentTypeDefinitionCache, ImmutableStack<IVariable> localVariableStack, ObjectInitializerContext objectInitializerStack)
+		{
+			this.compilation = compilation;
+			this.conversions = conversions;
+			this.context = context;
+			this.checkForOverflow = checkForOverflow;
+			this.isWithinLambdaExpression = isWithinLambdaExpression;
+			this.currentTypeDefinitionCache = currentTypeDefinitionCache;
+			this.localVariableStack = localVariableStack;
+			this.objectInitializerStack = objectInitializerStack;
+		}
+		#endregion
+		
+		#region Properties
+		/// <summary>
+		/// Gets the compilation used by the resolver.
+		/// </summary>
+		public ICompilation Compilation {
+			get { return compilation; }
+		}
+		
+		/// <summary>
+		/// Gets the current type resolve context.
+		/// </summary>
+		public CSharpTypeResolveContext CurrentTypeResolveContext {
+			get { return context; }
+		}
+
+		IAssembly ITypeResolveContext.CurrentAssembly {
+			get { return context.CurrentAssembly; }
+		}
+		
+		CSharpResolver WithContext(CSharpTypeResolveContext newContext)
+		{
+			return new CSharpResolver(compilation, conversions, newContext, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, objectInitializerStack);
+		}
+		
+		/// <summary>
+		/// Gets whether the current context is <c>checked</c>.
+		/// </summary>
+		public bool CheckForOverflow {
+			get { return checkForOverflow; }
+		}
+		
+		/// <summary>
+		/// Sets whether the current context is <c>checked</c>.
+		/// </summary>
+		public CSharpResolver WithCheckForOverflow(bool checkForOverflow)
+		{
+			if (checkForOverflow == this.checkForOverflow)
+				return this;
+			return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, objectInitializerStack);
+		}
+		
+		/// <summary>
+		/// Gets whether the resolver is currently within a lambda expression or anonymous method.
+		/// </summary>
+		public bool IsWithinLambdaExpression {
+			get { return isWithinLambdaExpression; }
+		}
+		
+		/// <summary>
+		/// Sets whether the resolver is currently within a lambda expression.
+		/// </summary>
+		public CSharpResolver WithIsWithinLambdaExpression(bool isWithinLambdaExpression)
+		{
+			return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, objectInitializerStack);
+		}
+		
+		/// <summary>
+		/// Gets the current member definition that is used to look up identifiers as parameters
+		/// or type parameters.
+		/// </summary>
+		public IMember CurrentMember {
+			get { return context.CurrentMember; }
+		}
+		
+		/// <summary>
+		/// Sets the current member definition.
+		/// </summary>
+		/// <remarks>Don't forget to also set CurrentTypeDefinition when setting CurrentMember;
+		/// setting one of the properties does not automatically set the other.</remarks>
+		public CSharpResolver WithCurrentMember(IMember member)
+		{
+			return WithContext(context.WithCurrentMember(member));
+		}
+		
+		ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember member)
+		{
+			return WithCurrentMember(member);
+		}
+		
+		/// <summary>
+		/// Gets the current using scope that is used to look up identifiers as class names.
+		/// </summary>
+		public ResolvedUsingScope CurrentUsingScope {
+			get { return context.CurrentUsingScope; }
+		}
+		
+		/// <summary>
+		/// Sets the current using scope that is used to look up identifiers as class names.
+		/// </summary>
+		public CSharpResolver WithCurrentUsingScope(ResolvedUsingScope usingScope)
+		{
+			return WithContext(context.WithUsingScope(usingScope));
+		}
+		#endregion
+		
+		#region Per-CurrentTypeDefinition Cache
+		readonly TypeDefinitionCache currentTypeDefinitionCache;
+		
+		/// <summary>
+		/// Gets the current type definition.
+		/// </summary>
+		public ITypeDefinition CurrentTypeDefinition {
+			get { return context.CurrentTypeDefinition; }
+		}
+		
+		/// <summary>
+		/// Sets the current type definition.
+		/// </summary>
+		public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition typeDefinition)
+		{
+			if (this.CurrentTypeDefinition == typeDefinition)
+				return this;
+			
+			TypeDefinitionCache newTypeDefinitionCache;
+			if (typeDefinition != null)
+				newTypeDefinitionCache = new TypeDefinitionCache(typeDefinition);
+			else
+				newTypeDefinitionCache = null;
+			
+			return new CSharpResolver(compilation, conversions, context.WithCurrentTypeDefinition(typeDefinition),
+			                          checkForOverflow, isWithinLambdaExpression, newTypeDefinitionCache, localVariableStack, objectInitializerStack);
+		}
+		
+		ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition typeDefinition)
+		{
+			return WithCurrentTypeDefinition(typeDefinition);
+		}
+		
+		sealed class TypeDefinitionCache
+		{
+			public readonly ITypeDefinition TypeDefinition;
+			public readonly Dictionary<string, ResolveResult> SimpleNameLookupCacheExpression = new Dictionary<string, ResolveResult>();
+			public readonly Dictionary<string, ResolveResult> SimpleNameLookupCacheInvocationTarget = new Dictionary<string, ResolveResult>();
+			public readonly Dictionary<string, ResolveResult> SimpleTypeLookupCache = new Dictionary<string, ResolveResult>();
+			
+			public TypeDefinitionCache(ITypeDefinition typeDefinition)
+			{
+				this.TypeDefinition = typeDefinition;
+			}
+		}
+		#endregion
+		
+		#region Local Variable Management
+		
+		// We store the local variables in an immutable stack.
+		// The beginning of a block is marked by a null entry.
+		
+		// This data structure is used to allow efficient cloning of the resolver with its local variable context.
+		readonly ImmutableStack<IVariable> localVariableStack = ImmutableStack<IVariable>.Empty;
+		
+		CSharpResolver WithLocalVariableStack(ImmutableStack<IVariable> stack)
+		{
+			return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, stack, objectInitializerStack);
+		}
+		
+		/// <summary>
+		/// Opens a new scope for local variables.
+		/// </summary>
+		public CSharpResolver PushBlock()
+		{
+			return WithLocalVariableStack(localVariableStack.Push(null));
+		}
+		
+		/// <summary>
+		/// Closes the current scope for local variables; removing all variables in that scope.
+		/// </summary>
+		public CSharpResolver PopBlock()
+		{
+			var stack = localVariableStack;
+			IVariable removedVar;
+			do {
+				removedVar = stack.Peek();
+				stack = stack.Pop();
+			} while (removedVar != null);
+			return WithLocalVariableStack(stack);
+		}
+		
+		/// <summary>
+		/// Adds a new variable or lambda parameter to the current block.
+		/// </summary>
+		public CSharpResolver AddVariable(IVariable variable)
+		{
+			if (variable == null)
+				throw new ArgumentNullException("variable");
+			return WithLocalVariableStack(localVariableStack.Push(variable));
+		}
+		
+		/// <summary>
+		/// Removes the variable that was just added.
+		/// </summary>
+		public CSharpResolver PopLastVariable()
+		{
+			if (localVariableStack.Peek() == null)
+				throw new InvalidOperationException("There is no variable within the current block.");
+			return WithLocalVariableStack(localVariableStack.Pop());
+		}
+		
+		/// <summary>
+		/// Gets all currently visible local variables and lambda parameters.
+		/// Does not include method parameters.
+		/// </summary>
+		public IEnumerable<IVariable> LocalVariables {
+			get {
+				return localVariableStack.Where(v => v != null);
+			}
+		}
+		#endregion
+		
+		#region Object Initializer Context
+		sealed class ObjectInitializerContext
+		{
+			internal readonly ResolveResult initializedObject;
+			internal readonly ObjectInitializerContext prev;
+			
+			public ObjectInitializerContext(ResolveResult initializedObject, CSharpResolver.ObjectInitializerContext prev)
+			{
+				this.initializedObject = initializedObject;
+				this.prev = prev;
+			}
+		}
+		
+		readonly ObjectInitializerContext objectInitializerStack;
+		
+		CSharpResolver WithObjectInitializerStack(ObjectInitializerContext stack)
+		{
+			return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, stack);
+		}
+		
+		/// <summary>
+		/// Pushes the type of the object that is currently being initialized.
+		/// </summary>
+		public CSharpResolver PushObjectInitializer(ResolveResult initializedObject)
+		{
+			if (initializedObject == null)
+				throw new ArgumentNullException("initializedObject");
+			return WithObjectInitializerStack(new ObjectInitializerContext(initializedObject, objectInitializerStack));
+		}
+		
+		public CSharpResolver PopObjectInitializer()
+		{
+			if (objectInitializerStack == null)
+				throw new InvalidOperationException();
+			return WithObjectInitializerStack(objectInitializerStack.prev);
+		}
+		
+		/// <summary>
+		/// Gets whether this context is within an object initializer.
+		/// </summary>
+		public bool IsInObjectInitializer {
+			get { return objectInitializerStack != null; }
+		}
+		
+		/// <summary>
+		/// Gets the current object initializer. This usually is an <see cref="InitializedObjectResolveResult"/>
+		/// or (for nested initializers) a semantic tree based on an <see cref="InitializedObjectResolveResult"/>.
+		/// Returns ErrorResolveResult if there is no object initializer.
+		/// </summary>
+		public ResolveResult CurrentObjectInitializer {
+			get {
+				return objectInitializerStack != null ? objectInitializerStack.initializedObject : ErrorResult;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the type of the object currently being initialized.
+		/// Returns SharedTypes.Unknown if no object initializer is currently open (or if the object initializer
+		/// has unknown type).
+		/// </summary>
+		public IType CurrentObjectInitializerType {
+			get { return CurrentObjectInitializer.Type; }
+		}
+		#endregion
+		
+		#region Clone
+		/// <summary>
+		/// Creates a copy of this CSharp resolver.
+		/// </summary>
+		[Obsolete("CSharpResolver is immutable, cloning is no longer necessary")]
+		public CSharpResolver Clone()
+		{
+			return this;
+		}
+		#endregion
+		
+		#region ResolveUnaryOperator
+		#region ResolveUnaryOperator method
+		public ResolveResult ResolveUnaryOperator(UnaryOperatorType op, ResolveResult expression)
+		{
+			if (expression.Type.Kind == TypeKind.Dynamic) {
+				if (op == UnaryOperatorType.Await) {
+					return new AwaitResolveResult(SpecialType.Dynamic, new DynamicInvocationResolveResult(new DynamicMemberResolveResult(expression, "GetAwaiter"), DynamicInvocationType.Invocation, EmptyList<ResolveResult>.Instance), SpecialType.Dynamic, null, null, null);
+				}
+				else {
+					return UnaryOperatorResolveResult(SpecialType.Dynamic, op, expression);
+				}
+			}
+			
+			// C# 4.0 spec: §7.3.3 Unary operator overload resolution
+			string overloadableOperatorName = GetOverloadableOperatorName(op);
+			if (overloadableOperatorName == null) {
+				switch (op) {
+					case UnaryOperatorType.Dereference:
+						PointerType p = expression.Type as PointerType;
+						if (p != null)
+							return UnaryOperatorResolveResult(p.ElementType, op, expression);
+						else
+							return ErrorResult;
+					case UnaryOperatorType.AddressOf:
+						return UnaryOperatorResolveResult(new PointerType(expression.Type), op, expression);
+					case UnaryOperatorType.Await: {
+						ResolveResult getAwaiterMethodGroup = ResolveMemberAccess(expression, "GetAwaiter", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
+						ResolveResult getAwaiterInvocation = ResolveInvocation(getAwaiterMethodGroup, new ResolveResult[0], argumentNames: null, allowOptionalParameters: false);
+
+						var lookup = CreateMemberLookup();
+						IMethod getResultMethod;
+						IType awaitResultType;
+						var getResultMethodGroup = lookup.Lookup(getAwaiterInvocation, "GetResult", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
+						if (getResultMethodGroup != null) {
+							var getResultOR = getResultMethodGroup.PerformOverloadResolution(compilation, new ResolveResult[0], allowExtensionMethods: false, conversions: conversions);
+							getResultMethod = getResultOR.FoundApplicableCandidate ? getResultOR.GetBestCandidateWithSubstitutedTypeArguments() as IMethod : null;
+							awaitResultType = getResultMethod != null ? getResultMethod.ReturnType : SpecialType.UnknownType;
+						}
+						else {
+							getResultMethod = null;
+							awaitResultType = SpecialType.UnknownType;
+						}
+
+						var isCompletedRR = lookup.Lookup(getAwaiterInvocation, "IsCompleted", EmptyList<IType>.Instance, false);
+						var isCompletedProperty = (isCompletedRR is MemberResolveResult ? ((MemberResolveResult)isCompletedRR).Member as IProperty : null);
+						if (isCompletedProperty != null && (!isCompletedProperty.ReturnType.IsKnownType(KnownTypeCode.Boolean) || !isCompletedProperty.CanGet))
+							isCompletedProperty = null;
+
+						var interfaceOnCompleted = compilation.FindType(KnownTypeCode.INotifyCompletion).GetMethods().FirstOrDefault(x => x.Name == "OnCompleted");
+						var interfaceUnsafeOnCompleted = compilation.FindType(KnownTypeCode.ICriticalNotifyCompletion).GetMethods().FirstOrDefault(x => x.Name == "UnsafeOnCompleted");
+
+						IMethod onCompletedMethod = null;
+						var candidates = getAwaiterInvocation.Type.GetMethods().Where(x => x.ImplementedInterfaceMembers.Select(y => y.MemberDefinition).Contains(interfaceUnsafeOnCompleted)).ToList();
+						if (candidates.Count == 0) {
+							candidates = getAwaiterInvocation.Type.GetMethods().Where(x => x.ImplementedInterfaceMembers.Select(y => y.MemberDefinition).Contains(interfaceOnCompleted)).ToList();
+							if (candidates.Count == 1)
+								onCompletedMethod = candidates[0];
+						}
+						else if (candidates.Count == 1) {
+							onCompletedMethod = candidates[0];
+						}
+
+						return new AwaitResolveResult(awaitResultType, getAwaiterInvocation, getAwaiterInvocation.Type, isCompletedProperty, onCompletedMethod, getResultMethod);
+					}
+
+					default:
+						return ErrorResolveResult.UnknownError;
+				}
+			}
+			// If the type is nullable, get the underlying type:
+			IType type = NullableType.GetUnderlyingType(expression.Type);
+			bool isNullable = NullableType.IsNullable(expression.Type);
+			
+			// the operator is overloadable:
+			OverloadResolution userDefinedOperatorOR = CreateOverloadResolution(new[] { expression });
+			foreach (var candidate in GetUserDefinedOperatorCandidates(type, overloadableOperatorName)) {
+				userDefinedOperatorOR.AddCandidate(candidate);
+			}
+			if (userDefinedOperatorOR.FoundApplicableCandidate) {
+				return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, UnaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
+			}
+			
+			expression = UnaryNumericPromotion(op, ref type, isNullable, expression);
+			CSharpOperators.OperatorMethod[] methodGroup;
+			CSharpOperators operators = CSharpOperators.Get(compilation);
+			switch (op) {
+				case UnaryOperatorType.Increment:
+				case UnaryOperatorType.Decrement:
+				case UnaryOperatorType.PostIncrement:
+				case UnaryOperatorType.PostDecrement:
+					// C# 4.0 spec: §7.6.9 Postfix increment and decrement operators
+					// C# 4.0 spec: §7.7.5 Prefix increment and decrement operators
+					TypeCode code = ReflectionHelper.GetTypeCode(type);
+					if ((code >= TypeCode.Char && code <= TypeCode.Decimal) || type.Kind == TypeKind.Enum || type.Kind == TypeKind.Pointer)
+						return UnaryOperatorResolveResult(expression.Type, op, expression, isNullable);
+					else
+						return new ErrorResolveResult(expression.Type);
+				case UnaryOperatorType.Plus:
+					methodGroup = operators.UnaryPlusOperators;
+					break;
+				case UnaryOperatorType.Minus:
+					methodGroup = CheckForOverflow ? operators.CheckedUnaryMinusOperators : operators.UncheckedUnaryMinusOperators;
+					break;
+				case UnaryOperatorType.Not:
+					methodGroup = operators.LogicalNegationOperators;
+					break;
+				case UnaryOperatorType.BitNot:
+					if (type.Kind == TypeKind.Enum) {
+						if (expression.IsCompileTimeConstant && !isNullable && expression.ConstantValue != null) {
+							// evaluate as (E)(~(U)x);
+							var U = compilation.FindType(expression.ConstantValue.GetType());
+							var unpackedEnum = new ConstantResolveResult(U, expression.ConstantValue);
+							var rr = ResolveUnaryOperator(op, unpackedEnum);
+							rr = WithCheckForOverflow(false).ResolveCast(type, rr);
+							if (rr.IsCompileTimeConstant)
+								return rr;
+						} 
+						return UnaryOperatorResolveResult(expression.Type, op, expression, isNullable);
+					} else {
+						methodGroup = operators.BitwiseComplementOperators;
+						break;
+					}
+				default:
+					throw new InvalidOperationException();
+			}
+			OverloadResolution builtinOperatorOR = CreateOverloadResolution(new[] { expression });
+			foreach (var candidate in methodGroup) {
+				builtinOperatorOR.AddCandidate(candidate);
+			}
+			CSharpOperators.UnaryOperatorMethod m = (CSharpOperators.UnaryOperatorMethod)builtinOperatorOR.BestCandidate;
+			IType resultType = m.ReturnType;
+			if (builtinOperatorOR.BestCandidateErrors != OverloadResolutionErrors.None) {
+				if (userDefinedOperatorOR.BestCandidate != null) {
+					// If there are any user-defined operators, prefer those over the built-in operators.
+					// It'll be a more informative error.
+					return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, UnaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
+				} else if (builtinOperatorOR.BestCandidateAmbiguousWith != null) {
+					// If the best candidate is ambiguous, just use the input type instead
+					// of picking one of the ambiguous overloads.
+					return new ErrorResolveResult(expression.Type);
+				} else {
+					return new ErrorResolveResult(resultType);
+				}
+			} else if (expression.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) {
+				object val;
+				try {
+					val = m.Invoke(this, expression.ConstantValue);
+				} catch (ArithmeticException) {
+					return new ErrorResolveResult(resultType);
+				}
+				return new ConstantResolveResult(resultType, val);
+			} else {
+				expression = Convert(expression, m.Parameters[0].Type, builtinOperatorOR.ArgumentConversions[0]);
+				return UnaryOperatorResolveResult(resultType, op, expression,
+				                                  builtinOperatorOR.BestCandidate is OverloadResolution.ILiftedOperator);
+			}
+		}
+		
+		OperatorResolveResult UnaryOperatorResolveResult(IType resultType, UnaryOperatorType op, ResolveResult expression, bool isLifted = false)
+		{
+			return new OperatorResolveResult(
+				resultType, UnaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow),
+				null, isLifted, new[] { expression });
+		}
+		#endregion
+		
+		#region UnaryNumericPromotion
+		ResolveResult UnaryNumericPromotion(UnaryOperatorType op, ref IType type, bool isNullable, ResolveResult expression)
+		{
+			// C# 4.0 spec: §7.3.6.1
+			TypeCode code = ReflectionHelper.GetTypeCode(type);
+			if (isNullable && type.Kind == TypeKind.Null)
+				code = TypeCode.SByte; // cause promotion of null to int32
+			switch (op) {
+				case UnaryOperatorType.Minus:
+					if (code == TypeCode.UInt32) {
+						type = compilation.FindType(KnownTypeCode.Int64);
+						return Convert(expression, MakeNullable(type, isNullable),
+						               isNullable ? Conversion.ImplicitNullableConversion : Conversion.ImplicitNumericConversion);
+					}
+					goto case UnaryOperatorType.Plus;
+				case UnaryOperatorType.Plus:
+				case UnaryOperatorType.BitNot:
+					if (code >= TypeCode.Char && code <= TypeCode.UInt16) {
+						type = compilation.FindType(KnownTypeCode.Int32);
+						return Convert(expression, MakeNullable(type, isNullable),
+						               isNullable ? Conversion.ImplicitNullableConversion : Conversion.ImplicitNumericConversion);
+					}
+					break;
+			}
+			return expression;
+		}
+		#endregion
+		
+		#region GetOverloadableOperatorName
+		static string GetOverloadableOperatorName(UnaryOperatorType op)
+		{
+			switch (op) {
+				case UnaryOperatorType.Not:
+					return "op_LogicalNot";
+				case UnaryOperatorType.BitNot:
+					return "op_OnesComplement";
+				case UnaryOperatorType.Minus:
+					return "op_UnaryNegation";
+				case UnaryOperatorType.Plus:
+					return "op_UnaryPlus";
+				case UnaryOperatorType.Increment:
+				case UnaryOperatorType.PostIncrement:
+					return "op_Increment";
+				case UnaryOperatorType.Decrement:
+				case UnaryOperatorType.PostDecrement:
+					return "op_Decrement";
+				default:
+					return null;
+			}
+		}
+		#endregion
+		#endregion
+		
+		#region ResolveBinaryOperator
+		#region ResolveBinaryOperator method
+		public ResolveResult ResolveBinaryOperator(BinaryOperatorType op, ResolveResult lhs, ResolveResult rhs)
+		{
+			if (lhs.Type.Kind == TypeKind.Dynamic || rhs.Type.Kind == TypeKind.Dynamic) {
+				lhs = Convert(lhs, SpecialType.Dynamic);
+				rhs = Convert(rhs, SpecialType.Dynamic);
+				return BinaryOperatorResolveResult(SpecialType.Dynamic, lhs, op, rhs);
+			}
+			
+			// C# 4.0 spec: §7.3.4 Binary operator overload resolution
+			string overloadableOperatorName = GetOverloadableOperatorName(op);
+			if (overloadableOperatorName == null) {
+				
+				// Handle logical and/or exactly as bitwise and/or:
+				// - If the user overloads a bitwise operator, that implicitly creates the corresponding logical operator.
+				// - If both inputs are compile-time constants, it doesn't matter that we don't short-circuit.
+				// - If inputs aren't compile-time constants, we don't evaluate anything, so again it doesn't matter that we don't short-circuit
+				if (op == BinaryOperatorType.ConditionalAnd) {
+					overloadableOperatorName = GetOverloadableOperatorName(BinaryOperatorType.BitwiseAnd);
+				} else if (op == BinaryOperatorType.ConditionalOr) {
+					overloadableOperatorName = GetOverloadableOperatorName(BinaryOperatorType.BitwiseOr);
+				} else if (op == BinaryOperatorType.NullCoalescing) {
+					// null coalescing operator is not overloadable and needs to be handled separately
+					return ResolveNullCoalescingOperator(lhs, rhs);
+				} else {
+					return ErrorResolveResult.UnknownError;
+				}
+			}
+			
+			// If the type is nullable, get the underlying type:
+			bool isNullable = NullableType.IsNullable(lhs.Type) || NullableType.IsNullable(rhs.Type);
+			IType lhsType = NullableType.GetUnderlyingType(lhs.Type);
+			IType rhsType = NullableType.GetUnderlyingType(rhs.Type);
+			
+			// the operator is overloadable:
+			OverloadResolution userDefinedOperatorOR = CreateOverloadResolution(new[] { lhs, rhs });
+			HashSet<IParameterizedMember> userOperatorCandidates = new HashSet<IParameterizedMember>();
+			userOperatorCandidates.UnionWith(GetUserDefinedOperatorCandidates(lhsType, overloadableOperatorName));
+			userOperatorCandidates.UnionWith(GetUserDefinedOperatorCandidates(rhsType, overloadableOperatorName));
+			foreach (var candidate in userOperatorCandidates) {
+				userDefinedOperatorOR.AddCandidate(candidate);
+			}
+			if (userDefinedOperatorOR.FoundApplicableCandidate) {
+				return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, BinaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
+			}
+			
+			if (lhsType.Kind == TypeKind.Null && rhsType.IsReferenceType == false
+			    || lhsType.IsReferenceType == false && rhsType.Kind == TypeKind.Null)
+			{
+				isNullable = true;
+			}
+			if (op == BinaryOperatorType.ShiftLeft || op == BinaryOperatorType.ShiftRight) {
+				// special case: the shift operators allow "var x = null << null", producing int?.
+				if (lhsType.Kind == TypeKind.Null && rhsType.Kind == TypeKind.Null)
+					isNullable = true;
+				// for shift operators, do unary promotion independently on both arguments
+				lhs = UnaryNumericPromotion(UnaryOperatorType.Plus, ref lhsType, isNullable, lhs);
+				rhs = UnaryNumericPromotion(UnaryOperatorType.Plus, ref rhsType, isNullable, rhs);
+			} else {
+				bool allowNullableConstants = op == BinaryOperatorType.Equality || op == BinaryOperatorType.InEquality;
+				if (!BinaryNumericPromotion(isNullable, ref lhs, ref rhs, allowNullableConstants))
+					return new ErrorResolveResult(lhs.Type);
+			}
+			// re-read underlying types after numeric promotion
+			lhsType = NullableType.GetUnderlyingType(lhs.Type);
+			rhsType = NullableType.GetUnderlyingType(rhs.Type);
+			
+			IEnumerable<CSharpOperators.OperatorMethod> methodGroup;
+			CSharpOperators operators = CSharpOperators.Get(compilation);
+			switch (op) {
+				case BinaryOperatorType.Multiply:
+					methodGroup = operators.MultiplicationOperators;
+					break;
+				case BinaryOperatorType.Divide:
+					methodGroup = operators.DivisionOperators;
+					break;
+				case BinaryOperatorType.Modulus:
+					methodGroup = operators.RemainderOperators;
+					break;
+				case BinaryOperatorType.Add:
+					methodGroup = operators.AdditionOperators;
+					{
+						if (lhsType.Kind == TypeKind.Enum) {
+							// E operator +(E x, U y);
+							IType underlyingType = MakeNullable(GetEnumUnderlyingType(lhsType), isNullable);
+							if (TryConvertEnum(ref rhs, underlyingType, ref isNullable, ref lhs)) {
+								return HandleEnumOperator(isNullable, lhsType, op, lhs, rhs);
+							}
+						}
+						if (rhsType.Kind == TypeKind.Enum) {
+							// E operator +(U x, E y);
+							IType underlyingType = MakeNullable(GetEnumUnderlyingType(rhsType), isNullable);
+							if (TryConvertEnum(ref lhs, underlyingType, ref isNullable, ref rhs)) {
+								return HandleEnumOperator(isNullable, rhsType, op, lhs, rhs);
+							}
+						}
+						
+						if (lhsType.Kind == TypeKind.Delegate && TryConvert(ref rhs, lhsType)) {
+							return BinaryOperatorResolveResult(lhsType, lhs, op, rhs);
+						} else if (rhsType.Kind == TypeKind.Delegate && TryConvert(ref lhs, rhsType)) {
+							return BinaryOperatorResolveResult(rhsType, lhs, op, rhs);
+						}
+						
+						if (lhsType is PointerType) {
+							methodGroup = new [] {
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int32),
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt32),
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int64),
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt64)
+							};
+						} else if (rhsType is PointerType) {
+							methodGroup = new [] {
+								PointerArithmeticOperator(rhsType, KnownTypeCode.Int32, rhsType),
+								PointerArithmeticOperator(rhsType, KnownTypeCode.UInt32, rhsType),
+								PointerArithmeticOperator(rhsType, KnownTypeCode.Int64, rhsType),
+								PointerArithmeticOperator(rhsType, KnownTypeCode.UInt64, rhsType)
+							};
+						}
+						if (lhsType.Kind == TypeKind.Null && rhsType.Kind == TypeKind.Null)
+							return new ErrorResolveResult(SpecialType.NullType);
+					}
+					break;
+				case BinaryOperatorType.Subtract:
+					methodGroup = operators.SubtractionOperators;
+					{
+						if (lhsType.Kind == TypeKind.Enum) {
+							// U operator –(E x, E y);
+							if (TryConvertEnum(ref rhs, lhs.Type, ref isNullable, ref lhs, allowConversionFromConstantZero: false)) {
+								return HandleEnumSubtraction(isNullable, lhsType, lhs, rhs);
+							}
+
+							// E operator –(E x, U y);
+							IType underlyingType = MakeNullable(GetEnumUnderlyingType(lhsType), isNullable);
+							if (TryConvertEnum(ref rhs, underlyingType, ref isNullable, ref lhs)) {
+								return HandleEnumOperator(isNullable, lhsType, op, lhs, rhs);
+							}
+						}
+						if (rhsType.Kind == TypeKind.Enum) {
+							// U operator –(E x, E y);
+							if (TryConvertEnum(ref lhs, rhs.Type, ref isNullable, ref rhs, allowConversionFromConstantZero: false)) {
+								return HandleEnumSubtraction(isNullable, rhsType, lhs, rhs);
+							}
+
+							// E operator -(U x, E y);
+							IType underlyingType = MakeNullable(GetEnumUnderlyingType(rhsType), isNullable);
+							if (TryConvertEnum(ref lhs, underlyingType, ref isNullable, ref rhs)) {
+								return HandleEnumOperator(isNullable, rhsType, op, lhs, rhs);
+							}
+						}
+						
+						if (lhsType.Kind == TypeKind.Delegate && TryConvert(ref rhs, lhsType)) {
+							return BinaryOperatorResolveResult(lhsType, lhs, op, rhs);
+						} else if (rhsType.Kind == TypeKind.Delegate && TryConvert(ref lhs, rhsType)) {
+							return BinaryOperatorResolveResult(rhsType, lhs, op, rhs);
+						}
+						
+						if (lhsType is PointerType) {
+							if (rhsType is PointerType) {
+								IType int64 = compilation.FindType(KnownTypeCode.Int64);
+								if (lhsType.Equals(rhsType)) {
+									return BinaryOperatorResolveResult(int64, lhs, op, rhs);
+								} else {
+									return new ErrorResolveResult(int64);
+								}
+							}
+							methodGroup = new [] {
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int32),
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt32),
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int64),
+								PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt64)
+							};
+						}
+						
+						if (lhsType.Kind == TypeKind.Null && rhsType.Kind == TypeKind.Null)
+							return new ErrorResolveResult(SpecialType.NullType);
+					}
+					break;
+				case BinaryOperatorType.ShiftLeft:
+					methodGroup = operators.ShiftLeftOperators;
+					break;
+				case BinaryOperatorType.ShiftRight:
+					methodGroup = operators.ShiftRightOperators;
+					break;
+				case BinaryOperatorType.Equality:
+				case BinaryOperatorType.InEquality:
+				case BinaryOperatorType.LessThan:
+				case BinaryOperatorType.GreaterThan:
+				case BinaryOperatorType.LessThanOrEqual:
+				case BinaryOperatorType.GreaterThanOrEqual:
+					{
+						if (lhsType.Kind == TypeKind.Enum && TryConvert(ref rhs, lhs.Type)) {
+							// bool operator op(E x, E y);
+							return HandleEnumComparison(op, lhsType, isNullable, lhs, rhs);
+						} else if (rhsType.Kind == TypeKind.Enum && TryConvert(ref lhs, rhs.Type)) {
+							// bool operator op(E x, E y);
+							return HandleEnumComparison(op, rhsType, isNullable, lhs, rhs);
+						} else if (lhsType is PointerType && rhsType is PointerType) {
+							return BinaryOperatorResolveResult(compilation.FindType(KnownTypeCode.Boolean), lhs, op, rhs);
+						}
+						if (op == BinaryOperatorType.Equality || op == BinaryOperatorType.InEquality) {
+							if (lhsType.IsReferenceType == true && rhsType.IsReferenceType == true) {
+								// If it's a reference comparison
+								if (op == BinaryOperatorType.Equality)
+									methodGroup = operators.ReferenceEqualityOperators;
+								else
+									methodGroup = operators.ReferenceInequalityOperators;
+								break;
+							} else if (lhsType.Kind == TypeKind.Null && IsNullableTypeOrNonValueType(rhs.Type)
+							           || IsNullableTypeOrNonValueType(lhs.Type) && rhsType.Kind == TypeKind.Null) {
+								// compare type parameter or nullable type with the null literal
+								return BinaryOperatorResolveResult(compilation.FindType(KnownTypeCode.Boolean), lhs, op, rhs);
+							}
+						}
+						switch (op) {
+							case BinaryOperatorType.Equality:
+								methodGroup = operators.ValueEqualityOperators;
+								break;
+							case BinaryOperatorType.InEquality:
+								methodGroup = operators.ValueInequalityOperators;
+								break;
+							case BinaryOperatorType.LessThan:
+								methodGroup = operators.LessThanOperators;
+								break;
+							case BinaryOperatorType.GreaterThan:
+								methodGroup = operators.GreaterThanOperators;
+								break;
+							case BinaryOperatorType.LessThanOrEqual:
+								methodGroup = operators.LessThanOrEqualOperators;
+								break;
+							case BinaryOperatorType.GreaterThanOrEqual:
+								methodGroup = operators.GreaterThanOrEqualOperators;
+								break;
+							default:
+								throw new InvalidOperationException();
+						}
+					}
+					break;
+				case BinaryOperatorType.BitwiseAnd:
+				case BinaryOperatorType.BitwiseOr:
+				case BinaryOperatorType.ExclusiveOr:
+					{
+						if (lhsType.Kind == TypeKind.Enum) {
+							// bool operator op(E x, E y);
+							if (TryConvertEnum(ref rhs, lhs.Type, ref isNullable, ref lhs)) {
+								return HandleEnumOperator(isNullable, lhsType, op, lhs, rhs);
+							}
+						}
+
+						if (rhsType.Kind == TypeKind.Enum) {
+							// bool operator op(E x, E y);
+							if (TryConvertEnum (ref lhs, rhs.Type, ref isNullable, ref rhs)) {
+								return HandleEnumOperator(isNullable, rhsType, op, lhs, rhs);
+							}
+						}
+						
+						switch (op) {
+							case BinaryOperatorType.BitwiseAnd:
+								methodGroup = operators.BitwiseAndOperators;
+								break;
+							case BinaryOperatorType.BitwiseOr:
+								methodGroup = operators.BitwiseOrOperators;
+								break;
+							case BinaryOperatorType.ExclusiveOr:
+								methodGroup = operators.BitwiseXorOperators;
+								break;
+							default:
+								throw new InvalidOperationException();
+						}
+					}
+					break;
+				case BinaryOperatorType.ConditionalAnd:
+					methodGroup = operators.LogicalAndOperators;
+					break;
+				case BinaryOperatorType.ConditionalOr:
+					methodGroup = operators.LogicalOrOperators;
+					break;
+				default:
+					throw new InvalidOperationException();
+			}
+			OverloadResolution builtinOperatorOR = CreateOverloadResolution(new[] { lhs, rhs });
+			foreach (var candidate in methodGroup) {
+				builtinOperatorOR.AddCandidate(candidate);
+			}
+			CSharpOperators.BinaryOperatorMethod m = (CSharpOperators.BinaryOperatorMethod)builtinOperatorOR.BestCandidate;
+			IType resultType = m.ReturnType;
+			if (builtinOperatorOR.BestCandidateErrors != OverloadResolutionErrors.None) {
+				// If there are any user-defined operators, prefer those over the built-in operators.
+				// It'll be a more informative error.
+				if (userDefinedOperatorOR.BestCandidate != null)
+					return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, BinaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
+				else
+					return new ErrorResolveResult(resultType);
+			} else if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) {
+				object val;
+				try {
+					val = m.Invoke(this, lhs.ConstantValue, rhs.ConstantValue);
+				} catch (ArithmeticException) {
+					return new ErrorResolveResult(resultType);
+				}
+				return new ConstantResolveResult(resultType, val);
+			} else {
+				lhs = Convert(lhs, m.Parameters[0].Type, builtinOperatorOR.ArgumentConversions[0]);
+				rhs = Convert(rhs, m.Parameters[1].Type, builtinOperatorOR.ArgumentConversions[1]);
+				return BinaryOperatorResolveResult(resultType, lhs, op, rhs,
+				                                   builtinOperatorOR.BestCandidate is OverloadResolution.ILiftedOperator);
+			}
+		}
+		
+		bool IsNullableTypeOrNonValueType(IType type)
+		{
+			return NullableType.IsNullable(type) || type.IsReferenceType != false;
+		}
+		
+		ResolveResult BinaryOperatorResolveResult(IType resultType, ResolveResult lhs, BinaryOperatorType op, ResolveResult rhs, bool isLifted = false)
+		{
+			return new OperatorResolveResult(
+				resultType, BinaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow),
+				null, isLifted, new[] { lhs, rhs });
+		}
+		#endregion
+		
+		#region Pointer arithmetic
+		CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, IType inputType1, KnownTypeCode inputType2)
+		{
+			return PointerArithmeticOperator(resultType, inputType1, compilation.FindType(inputType2));
+		}
+		
+		CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, KnownTypeCode inputType1, IType inputType2)
+		{
+			return PointerArithmeticOperator(resultType, compilation.FindType(inputType1), inputType2);
+		}
+		
+		CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, IType inputType1, IType inputType2)
+		{
+			return new CSharpOperators.BinaryOperatorMethod(compilation) {
+				ReturnType = resultType,
+				Parameters = {
+					new DefaultParameter(inputType1, string.Empty),
+					new DefaultParameter(inputType2, string.Empty)
+				}
+			};
+		}
+		#endregion
+		
+		#region Enum helper methods
+		IType GetEnumUnderlyingType(IType enumType)
+		{
+			ITypeDefinition def = enumType.GetDefinition();
+			return def != null ? def.EnumUnderlyingType : SpecialType.UnknownType;
+		}
+		
+		/// <summary>
+		/// Handle the case where an enum value is compared with another enum value
+		/// bool operator op(E x, E y);
+		/// </summary>
+		ResolveResult HandleEnumComparison(BinaryOperatorType op, IType enumType, bool isNullable, ResolveResult lhs, ResolveResult rhs)
+		{
+			// evaluate as ((U)x op (U)y)
+			IType elementType = GetEnumUnderlyingType(enumType);
+			if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && !isNullable && elementType.Kind != TypeKind.Enum) {
+				var rr = ResolveBinaryOperator(op, ResolveCast(elementType, lhs), ResolveCast(elementType, rhs));
+				if (rr.IsCompileTimeConstant)
+					return rr;
+			}
+			IType resultType = compilation.FindType(KnownTypeCode.Boolean);
+			return BinaryOperatorResolveResult(resultType, lhs, op, rhs, isNullable);
+		}
+		
+		/// <summary>
+		/// Handle the case where an enum value is subtracted from another enum value
+		/// U operator –(E x, E y);
+		/// </summary>
+		ResolveResult HandleEnumSubtraction(bool isNullable, IType enumType, ResolveResult lhs, ResolveResult rhs)
+		{
+			// evaluate as (U)((U)x – (U)y)
+			IType elementType = GetEnumUnderlyingType(enumType);
+			if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && !isNullable && elementType.Kind != TypeKind.Enum) {
+				var rr = ResolveBinaryOperator(BinaryOperatorType.Subtract, ResolveCast(elementType, lhs), ResolveCast(elementType, rhs));
+				rr = WithCheckForOverflow(false).ResolveCast(elementType, rr);
+				if (rr.IsCompileTimeConstant)
+					return rr;
+			}
+			IType resultType = MakeNullable(elementType, isNullable);
+			return BinaryOperatorResolveResult(resultType, lhs, BinaryOperatorType.Subtract, rhs, isNullable);
+		}
+		
+		/// <summary>
+		/// Handle the following enum operators:
+		/// E operator +(E x, U y);
+		/// E operator +(U x, E y);
+		/// E operator –(E x, U y);
+		/// E operator &amp;(E x, E y);
+		/// E operator |(E x, E y);
+		/// E operator ^(E x, E y);
+		/// </summary>
+		ResolveResult HandleEnumOperator(bool isNullable, IType enumType, BinaryOperatorType op, ResolveResult lhs, ResolveResult rhs)
+		{
+			// evaluate as (E)((U)x op (U)y)
+			if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && !isNullable) {
+				IType elementType = GetEnumUnderlyingType(enumType);
+				if (elementType.Kind != TypeKind.Enum) {
+					var rr = ResolveBinaryOperator(op, ResolveCast(elementType, lhs), ResolveCast(elementType, rhs));
+					rr = WithCheckForOverflow(false).ResolveCast(enumType, rr);
+					if (rr.IsCompileTimeConstant) // only report result if it's a constant; use the regular OperatorResolveResult codepath otherwise
+						return rr;
+				}
+			}
+			IType resultType = MakeNullable(enumType, isNullable);
+			return BinaryOperatorResolveResult(resultType, lhs, op, rhs, isNullable);
+		}
+		
+		IType MakeNullable(IType type, bool isNullable)
+		{
+			if (isNullable)
+				return NullableType.Create(compilation, type);
+			else
+				return type;
+		}
+		#endregion
+		
+		#region BinaryNumericPromotion
+		bool BinaryNumericPromotion(bool isNullable, ref ResolveResult lhs, ref ResolveResult rhs, bool allowNullableConstants)
+		{
+			// C# 4.0 spec: §7.3.6.2
+			TypeCode lhsCode = ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(lhs.Type));
+			TypeCode rhsCode = ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(rhs.Type));
+			// if one of the inputs is the null literal, promote that to the type of the other operand
+			if (isNullable && lhs.Type.Kind == TypeKind.Null && rhsCode >= TypeCode.Boolean && rhsCode <= TypeCode.Decimal) {
+				lhs = CastTo(rhsCode, isNullable, lhs, allowNullableConstants);
+				lhsCode = rhsCode;
+			} else if (isNullable && rhs.Type.Kind == TypeKind.Null && lhsCode >= TypeCode.Boolean && lhsCode <= TypeCode.Decimal) {
+				rhs = CastTo(lhsCode, isNullable, rhs, allowNullableConstants);
+				rhsCode = lhsCode;
+			}
+			bool bindingError = false;
+			if (lhsCode >= TypeCode.Char && lhsCode <= TypeCode.Decimal
+			    && rhsCode >= TypeCode.Char && rhsCode <= TypeCode.Decimal)
+			{
+				TypeCode targetType;
+				if (lhsCode == TypeCode.Decimal || rhsCode == TypeCode.Decimal) {
+					targetType = TypeCode.Decimal;
+					bindingError = (lhsCode == TypeCode.Single || lhsCode == TypeCode.Double
+					                || rhsCode == TypeCode.Single || rhsCode == TypeCode.Double);
+				} else if (lhsCode == TypeCode.Double || rhsCode == TypeCode.Double) {
+					targetType = TypeCode.Double;
+				} else if (lhsCode == TypeCode.Single || rhsCode == TypeCode.Single) {
+					targetType = TypeCode.Single;
+				} else if (lhsCode == TypeCode.UInt64 || rhsCode == TypeCode.UInt64) {
+					targetType = TypeCode.UInt64;
+					bindingError = IsSigned(lhsCode, lhs) || IsSigned(rhsCode, rhs);
+				} else if (lhsCode == TypeCode.Int64 || rhsCode == TypeCode.Int64) {
+					targetType = TypeCode.Int64;
+				} else if (lhsCode == TypeCode.UInt32 || rhsCode == TypeCode.UInt32) {
+					targetType = (IsSigned(lhsCode, lhs) || IsSigned(rhsCode, rhs)) ? TypeCode.Int64 : TypeCode.UInt32;
+				} else {
+					targetType = TypeCode.Int32;
+				}
+				lhs = CastTo(targetType, isNullable, lhs, allowNullableConstants);
+				rhs = CastTo(targetType, isNullable, rhs, allowNullableConstants);
+			}
+			return !bindingError;
+		}
+		
+		bool IsSigned(TypeCode code, ResolveResult rr)
+		{
+			// Determine whether the rr with code==ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(rr.Type))
+			// is a signed primitive type.
+			switch (code) {
+				case TypeCode.SByte:
+				case TypeCode.Int16:
+					return true;
+				case TypeCode.Int32:
+					// for int, consider implicit constant expression conversion
+					if (rr.IsCompileTimeConstant && rr.ConstantValue != null && (int)rr.ConstantValue >= 0)
+						return false;
+					else
+						return true;
+				case TypeCode.Int64:
+					// for long, consider implicit constant expression conversion
+					if (rr.IsCompileTimeConstant && rr.ConstantValue != null && (long)rr.ConstantValue >= 0)
+						return false;
+					else
+						return true;
+				default:
+					return false;
+			}
+		}
+		
+		ResolveResult CastTo(TypeCode targetType, bool isNullable, ResolveResult expression, bool allowNullableConstants)
+		{
+			IType elementType = compilation.FindType(targetType);
+			IType nullableType = MakeNullable(elementType, isNullable);
+			if (nullableType.Equals(expression.Type))
+				return expression;
+			if (allowNullableConstants && expression.IsCompileTimeConstant) {
+				if (expression.ConstantValue == null)
+					return new ConstantResolveResult(nullableType, null);
+				ResolveResult rr = ResolveCast(elementType, expression);
+				if (rr.IsError)
+					return rr;
+				Debug.Assert(rr.IsCompileTimeConstant);
+				return new ConstantResolveResult(nullableType, rr.ConstantValue);
+			} else {
+				return Convert(expression, nullableType,
+				               isNullable ? Conversion.ImplicitNullableConversion : Conversion.ImplicitNumericConversion);
+			}
+		}
+		#endregion
+		
+		#region GetOverloadableOperatorName
+		static string GetOverloadableOperatorName(BinaryOperatorType op)
+		{
+			switch (op) {
+				case BinaryOperatorType.Add:
+					return "op_Addition";
+				case BinaryOperatorType.Subtract:
+					return "op_Subtraction";
+				case BinaryOperatorType.Multiply:
+					return "op_Multiply";
+				case BinaryOperatorType.Divide:
+					return "op_Division";
+				case BinaryOperatorType.Modulus:
+					return "op_Modulus";
+				case BinaryOperatorType.BitwiseAnd:
+					return "op_BitwiseAnd";
+				case BinaryOperatorType.BitwiseOr:
+					return "op_BitwiseOr";
+				case BinaryOperatorType.ExclusiveOr:
+					return "op_ExclusiveOr";
+				case BinaryOperatorType.ShiftLeft:
+					return "op_LeftShift";
+				case BinaryOperatorType.ShiftRight:
+					return "op_RightShift";
+				case BinaryOperatorType.Equality:
+					return "op_Equality";
+				case BinaryOperatorType.InEquality:
+					return "op_Inequality";
+				case BinaryOperatorType.GreaterThan:
+					return "op_GreaterThan";
+				case BinaryOperatorType.LessThan:
+					return "op_LessThan";
+				case BinaryOperatorType.GreaterThanOrEqual:
+					return "op_GreaterThanOrEqual";
+				case BinaryOperatorType.LessThanOrEqual:
+					return "op_LessThanOrEqual";
+				default:
+					return null;
+			}
+		}
+		#endregion
+		
+		#region Null coalescing operator
+		ResolveResult ResolveNullCoalescingOperator(ResolveResult lhs, ResolveResult rhs)
+		{
+			if (NullableType.IsNullable(lhs.Type)) {
+				IType a0 = NullableType.GetUnderlyingType(lhs.Type);
+				if (TryConvert(ref rhs, a0)) {
+					return BinaryOperatorResolveResult(a0, lhs, BinaryOperatorType.NullCoalescing, rhs);
+				}
+			}
+			if (TryConvert(ref rhs, lhs.Type)) {
+				return BinaryOperatorResolveResult(lhs.Type, lhs, BinaryOperatorType.NullCoalescing, rhs);
+			}
+			if (TryConvert(ref lhs, rhs.Type)) {
+				return BinaryOperatorResolveResult(rhs.Type, lhs, BinaryOperatorType.NullCoalescing, rhs);
+			} else {
+				return new ErrorResolveResult(lhs.Type);
+			}
+		}
+		#endregion
+		#endregion
+		
+		#region Get user-defined operator candidates
+		IEnumerable<IParameterizedMember> GetUserDefinedOperatorCandidates(IType type, string operatorName)
+		{
+			if (operatorName == null)
+				return EmptyList<IMethod>.Instance;
+			TypeCode c = ReflectionHelper.GetTypeCode(type);
+			if (TypeCode.Boolean <= c && c <= TypeCode.Decimal || c == TypeCode.String) {
+				// The .NET framework contains some of C#'s built-in operators as user-defined operators.
+				// However, we must not use those as user-defined operators (we would skip numeric promotion).
+				return EmptyList<IMethod>.Instance;
+			}
+			// C# 4.0 spec: §7.3.5 Candidate user-defined operators
+			var operators = type.GetMethods(m => m.IsOperator && m.Name == operatorName).ToList();
+			LiftUserDefinedOperators(operators);
+			return operators;
+		}
+		
+		void LiftUserDefinedOperators(List<IMethod> operators)
+		{
+			int nonLiftedMethodCount = operators.Count;
+			// Construct lifted operators
+			for (int i = 0; i < nonLiftedMethodCount; i++) {
+				var liftedMethod = LiftUserDefinedOperator(operators[i]);
+				if (liftedMethod != null)
+					operators.Add(liftedMethod);
+			}
+		}
+		
+		LiftedUserDefinedOperator LiftUserDefinedOperator(IMethod m)
+		{
+			if (IsComparisonOperator(m)) {
+				if (!m.ReturnType.Equals(compilation.FindType(KnownTypeCode.Boolean)))
+					return null; // cannot lift this operator
+			} else {
+				if (!NullableType.IsNonNullableValueType(m.ReturnType))
+					return null; // cannot lift this operator
+			}
+			for (int i = 0; i < m.Parameters.Count; i++) {
+				if (!NullableType.IsNonNullableValueType(m.Parameters[i].Type))
+					return null; // cannot lift this operator
+			}
+			return new LiftedUserDefinedOperator(m);
+		}
+		
+		static bool IsComparisonOperator(IMethod m)
+		{
+			var type = OperatorDeclaration.GetOperatorType(m.Name);
+			return type.HasValue && type.Value.IsComparisonOperator();
+		}
+		
+		sealed class LiftedUserDefinedOperator : SpecializedMethod, OverloadResolution.ILiftedOperator
+		{
+			internal readonly IParameterizedMember nonLiftedOperator;
+			
+			public LiftedUserDefinedOperator(IMethod nonLiftedMethod)
+				: base((IMethod)nonLiftedMethod.MemberDefinition, nonLiftedMethod.Substitution)
+			{
+				this.nonLiftedOperator = nonLiftedMethod;
+				var substitution = new MakeNullableVisitor(nonLiftedMethod.Compilation, nonLiftedMethod.Substitution);
+				this.Parameters = base.CreateParameters(substitution);
+				// Comparison operators keep the 'bool' return type even when lifted.
+				if (IsComparisonOperator(nonLiftedMethod))
+					this.ReturnType = nonLiftedMethod.ReturnType;
+				else
+					this.ReturnType = nonLiftedMethod.ReturnType.AcceptVisitor(substitution);
+			}
+			
+			public IList<IParameter> NonLiftedParameters {
+				get { return nonLiftedOperator.Parameters; }
+			}
+			
+			public override bool Equals(object obj)
+			{
+				LiftedUserDefinedOperator op = obj as LiftedUserDefinedOperator;
+				return op != null && this.nonLiftedOperator.Equals(op.nonLiftedOperator);
+			}
+			
+			public override int GetHashCode()
+			{
+				return nonLiftedOperator.GetHashCode() ^ 0x7191254;
+			}
+		}
+		
+		sealed class MakeNullableVisitor : TypeVisitor
+		{
+			readonly ICompilation compilation;
+			readonly TypeParameterSubstitution typeParameterSubstitution;
+			
+			public MakeNullableVisitor(ICompilation compilation, TypeParameterSubstitution typeParameterSubstitution)
+			{
+				this.compilation = compilation;
+				this.typeParameterSubstitution = typeParameterSubstitution;
+			}
+			
+			public override IType VisitTypeDefinition(ITypeDefinition type)
+			{
+				return NullableType.Create(compilation, type.AcceptVisitor(typeParameterSubstitution));
+			}
+			
+			public override IType VisitTypeParameter(ITypeParameter type)
+			{
+				return NullableType.Create(compilation, type.AcceptVisitor(typeParameterSubstitution));
+			}
+			
+			public override IType VisitParameterizedType(ParameterizedType type)
+			{
+				return NullableType.Create(compilation, type.AcceptVisitor(typeParameterSubstitution));
+			}
+			
+			public override IType VisitOtherType(IType type)
+			{
+				return NullableType.Create(compilation, type.AcceptVisitor(typeParameterSubstitution));
+			}
+		}
+		
+		ResolveResult CreateResolveResultForUserDefinedOperator(OverloadResolution r, System.Linq.Expressions.ExpressionType operatorType)
+		{
+			if (r.BestCandidateErrors != OverloadResolutionErrors.None)
+				return r.CreateResolveResult(null);
+			IMethod method = (IMethod)r.BestCandidate;
+			return new OperatorResolveResult(method.ReturnType, operatorType, method,
+			                                 isLiftedOperator: method is OverloadResolution.ILiftedOperator,
+			                                 operands: r.GetArgumentsWithConversions());
+		}
+		#endregion
+		
+		#region ResolveCast
+		bool TryConvert(ref ResolveResult rr, IType targetType)
+		{
+			Conversion c = conversions.ImplicitConversion(rr, targetType);
+			if (c.IsValid) {
+				rr = Convert(rr, targetType, c);
+				return true;
+			} else {
+				return false;
+			}
+		}
+
+		/// <summary>
+		/// 
+		/// </summary>
+		/// <param name="rr">The input resolve result that should be converted.
+		/// If a conversion exists, it is applied to the resolve result</param>
+		/// <param name="targetType">The target type that we should convert to</param>
+		/// <param name="isNullable">Whether we are dealing with a lifted operator</param>
+		/// <param name="enumRR">The resolve result that is enum-typed.
+		/// If necessary, a nullable conversion is applied.</param>
+		/// <param name="allowConversionFromConstantZero">
+		/// Whether the conversion from the constant zero is allowed.
+		/// </param>
+		/// <returns>True if the conversion is successful; false otherwise.
+		/// If the conversion is not successful, the ref parameters will not be modified.</returns>
+		bool TryConvertEnum(ref ResolveResult rr, IType targetType, ref bool isNullable, ref ResolveResult enumRR, bool allowConversionFromConstantZero = true)
+		{
+			Conversion c;
+			if (!isNullable) {
+				// Try non-nullable
+				c = conversions.ImplicitConversion(rr, targetType);
+				if (c.IsValid && (allowConversionFromConstantZero || !c.IsEnumerationConversion)) {
+					rr = Convert(rr, targetType, c);
+					return true;
+				}
+			}
+			// make targetType nullable if it isn't already:
+			if (!targetType.IsKnownType(KnownTypeCode.NullableOfT))
+				targetType = NullableType.Create(compilation, targetType);
+			
+			c = conversions.ImplicitConversion(rr, targetType);
+			if (c.IsValid && (allowConversionFromConstantZero || !c.IsEnumerationConversion)) {
+				rr = Convert(rr, targetType, c);
+				isNullable = true;
+				// Also convert the enum-typed RR to nullable, if it isn't already
+				if (!enumRR.Type.IsKnownType(KnownTypeCode.NullableOfT)) {
+					var nullableType = NullableType.Create(compilation, enumRR.Type);
+					enumRR = new ConversionResolveResult(nullableType, enumRR, Conversion.ImplicitNullableConversion);
+				}
+				return true;
+			}
+			return false;
+		}
+		
+		ResolveResult Convert(ResolveResult rr, IType targetType)
+		{
+			return Convert(rr, targetType, conversions.ImplicitConversion(rr, targetType));
+		}
+		
+		ResolveResult Convert(ResolveResult rr, IType targetType, Conversion c)
+		{
+			if (c == Conversion.IdentityConversion)
+				return rr;
+			else if (rr.IsCompileTimeConstant && c != Conversion.None && !c.IsUserDefined)
+				return ResolveCast(targetType, rr);
+			else
+				return new ConversionResolveResult(targetType, rr, c, checkForOverflow);
+		}
+		
+		public ResolveResult ResolveCast(IType targetType, ResolveResult expression)
+		{
+			// C# 4.0 spec: §7.7.6 Cast expressions
+			Conversion c = conversions.ExplicitConversion(expression, targetType);
+			if (expression.IsCompileTimeConstant && !c.IsUserDefined) {
+				TypeCode code = ReflectionHelper.GetTypeCode(targetType);
+				if (code >= TypeCode.Boolean && code <= TypeCode.Decimal && expression.ConstantValue != null) {
+					try {
+						return new ConstantResolveResult(targetType, CSharpPrimitiveCast(code, expression.ConstantValue));
+					} catch (OverflowException) {
+						return new ErrorResolveResult(targetType);
+					} catch (InvalidCastException) {
+						return new ErrorResolveResult(targetType);
+					}
+				} else if (code == TypeCode.String) {
+					if (expression.ConstantValue == null || expression.ConstantValue is string)
+						return new ConstantResolveResult(targetType, expression.ConstantValue);
+					else
+						return new ErrorResolveResult(targetType);
+				} else if (targetType.Kind == TypeKind.Enum) {
+					code = ReflectionHelper.GetTypeCode(GetEnumUnderlyingType(targetType));
+					if (code >= TypeCode.SByte && code <= TypeCode.UInt64 && expression.ConstantValue != null) {
+						try {
+							return new ConstantResolveResult(targetType, CSharpPrimitiveCast(code, expression.ConstantValue));
+						} catch (OverflowException) {
+							return new ErrorResolveResult(targetType);
+						} catch (InvalidCastException) {
+							return new ErrorResolveResult(targetType);
+						}
+					}
+				}
+			}
+			return new ConversionResolveResult(targetType, expression, c, checkForOverflow);
+		}
+		
+		internal object CSharpPrimitiveCast(TypeCode targetType, object input)
+		{
+			return Utils.CSharpPrimitiveCast.Cast(targetType, input, this.CheckForOverflow);
+		}
+		#endregion
+		
+		#region ResolveSimpleName
+		public ResolveResult ResolveSimpleName(string identifier, IList<IType> typeArguments, bool isInvocationTarget = false)
+		{
+			// C# 4.0 spec: §7.6.2 Simple Names
+			
+			return LookupSimpleNameOrTypeName(
+				identifier, typeArguments,
+				isInvocationTarget ? NameLookupMode.InvocationTarget : NameLookupMode.Expression);
+		}
+		
+		public ResolveResult LookupSimpleNameOrTypeName(string identifier, IList<IType> typeArguments, NameLookupMode lookupMode)
+		{
+			// C# 4.0 spec: §3.8 Namespace and type names; §7.6.2 Simple Names
+			
+			if (identifier == null)
+				throw new ArgumentNullException("identifier");
+			if (typeArguments == null)
+				throw new ArgumentNullException("typeArguments");
+			
+			int k = typeArguments.Count;
+			
+			if (k == 0) {
+				if (lookupMode == NameLookupMode.Expression || lookupMode == NameLookupMode.InvocationTarget) {
+					// Look in local variables
+					foreach (IVariable v in this.LocalVariables) {
+						if (v.Name == identifier) {
+							return new LocalResolveResult(v);
+						}
+					}
+					// Look in parameters of current method
+					IParameterizedMember parameterizedMember = this.CurrentMember as IParameterizedMember;
+					if (parameterizedMember != null) {
+						foreach (IParameter p in parameterizedMember.Parameters) {
+							if (p.Name == identifier) {
+								return new LocalResolveResult(p);
+							}
+						}
+					}
+				}
+				
+				// look in type parameters of current method
+				IMethod m = this.CurrentMember as IMethod;
+				if (m != null) {
+					foreach (ITypeParameter tp in m.TypeParameters) {
+						if (tp.Name == identifier)
+							return new TypeResolveResult(tp);
+					}
+				}
+			}
+			
+			bool parameterizeResultType = !(typeArguments.Count != 0 && typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument));
+			
+			ResolveResult r = null;
+			if (currentTypeDefinitionCache != null) {
+				Dictionary<string, ResolveResult> cache = null;
+				bool foundInCache = false;
+				if (k == 0) {
+					switch (lookupMode) {
+						case NameLookupMode.Expression:
+							cache = currentTypeDefinitionCache.SimpleNameLookupCacheExpression;
+							break;
+						case NameLookupMode.InvocationTarget:
+							cache = currentTypeDefinitionCache.SimpleNameLookupCacheInvocationTarget;
+							break;
+						case NameLookupMode.Type:
+							cache = currentTypeDefinitionCache.SimpleTypeLookupCache;
+							break;
+					}
+					if (cache != null) {
+						lock (cache)
+							foundInCache = cache.TryGetValue(identifier, out r);
+					}
+				}
+				if (foundInCache) {
+					r = (r != null ? r.ShallowClone() : null);
+				} else {
+					r = LookInCurrentType(identifier, typeArguments, lookupMode, parameterizeResultType);
+					if (cache != null) {
+						// also cache missing members (r==null)
+						lock (cache)
+							cache[identifier] = r;
+					}
+				}
+				if (r != null)
+					return r;
+			}
+			
+			if (context.CurrentUsingScope == null) {
+				// If no using scope was specified, we still need to look in the global namespace:
+				r = LookInUsingScopeNamespace(null, compilation.RootNamespace, identifier, typeArguments, parameterizeResultType);
+			} else {
+				if (k == 0 && lookupMode != NameLookupMode.TypeInUsingDeclaration) {
+					if (context.CurrentUsingScope.ResolveCache.TryGetValue(identifier, out r)) {
+						r = (r != null ? r.ShallowClone() : null);
+					} else {
+						r = LookInCurrentUsingScope(identifier, typeArguments, false, false);
+						context.CurrentUsingScope.ResolveCache.TryAdd(identifier, r);
+					}
+				} else {
+					r = LookInCurrentUsingScope(identifier, typeArguments, lookupMode == NameLookupMode.TypeInUsingDeclaration, parameterizeResultType);
+				}
+			}
+			if (r != null)
+				return r;
+			
+			if (typeArguments.Count == 0 && identifier == "dynamic") {
+				return new TypeResolveResult(SpecialType.Dynamic);
+			} else {
+				return new UnknownIdentifierResolveResult(identifier, typeArguments.Count);
+			}
+		}
+		
+		public bool IsVariableReferenceWithSameType (ResolveResult rr, string identifier, out TypeResolveResult trr)
+		{
+			if (!(rr is MemberResolveResult || rr is LocalResolveResult)) {
+				trr = null;
+				return false;
+			}
+			trr = LookupSimpleNameOrTypeName (identifier, EmptyList<IType>.Instance, NameLookupMode.Type) as TypeResolveResult;
+			return trr != null && trr.Type.Equals (rr.Type);
+		}
+		
+		ResolveResult LookInCurrentType(string identifier, IList<IType> typeArguments, NameLookupMode lookupMode, bool parameterizeResultType)
+		{
+			int k = typeArguments.Count;
+			MemberLookup lookup = CreateMemberLookup(lookupMode);
+			// look in current type definitions
+			for (ITypeDefinition t = this.CurrentTypeDefinition; t != null; t = t.DeclaringTypeDefinition) {
+				if (k == 0) {
+					// Look for type parameter with that name
+					var typeParameters = t.TypeParameters;
+					// Look at all type parameters, including those copied from outer classes,
+					// so that we can fetch the version with the correct owner.
+					for (int i = 0; i < typeParameters.Count; i++) {
+						if (typeParameters[i].Name == identifier)
+							return new TypeResolveResult(typeParameters[i]);
+					}
+				}
+				
+				if (lookupMode == NameLookupMode.BaseTypeReference && t == this.CurrentTypeDefinition) {
+					// don't look in current type when resolving a base type reference
+					continue;
+				}
+				
+				ResolveResult r;
+				if (lookupMode == NameLookupMode.Expression || lookupMode == NameLookupMode.InvocationTarget) {
+					var targetResolveResult = (t == this.CurrentTypeDefinition ? ResolveThisReference() : new TypeResolveResult(t));
+					r = lookup.Lookup(targetResolveResult, identifier, typeArguments, lookupMode == NameLookupMode.InvocationTarget);
+				} else {
+					r = lookup.LookupType(t, identifier, typeArguments, parameterizeResultType);
+				}
+				if (!(r is UnknownMemberResolveResult)) // but do return AmbiguousMemberResolveResult
+					return r;
+			}
+			return null;
+		}
+		
+		ResolveResult LookInCurrentUsingScope(string identifier, IList<IType> typeArguments, bool isInUsingDeclaration, bool parameterizeResultType)
+		{
+			// look in current namespace definitions
+			ResolvedUsingScope currentUsingScope = this.CurrentUsingScope;
+			for (ResolvedUsingScope u = currentUsingScope; u != null; u = u.Parent) {
+				var resultInNamespace = LookInUsingScopeNamespace(u, u.Namespace, identifier, typeArguments, parameterizeResultType);
+				if (resultInNamespace != null)
+					return resultInNamespace;
+				// then look for aliases:
+				if (typeArguments.Count == 0) {
+					if (u.ExternAliases.Contains(identifier)) {
+						return ResolveExternAlias(identifier);
+					}
+					if (!(isInUsingDeclaration && u == currentUsingScope)) {
+						foreach (var pair in u.UsingAliases) {
+							if (pair.Key == identifier) {
+								return pair.Value.ShallowClone();
+							}
+						}
+					}
+				}
+				// finally, look in the imported namespaces:
+				if (!(isInUsingDeclaration && u == currentUsingScope)) {
+					IType firstResult = null;
+					foreach (var importedNamespace in u.Usings) {
+						ITypeDefinition def = importedNamespace.GetTypeDefinition(identifier, typeArguments.Count);
+						if (def != null) {
+							IType resultType;
+							if (parameterizeResultType && typeArguments.Count > 0)
+								resultType = new ParameterizedType(def, typeArguments);
+							else
+								resultType = def;
+							
+							if (firstResult == null || !TopLevelTypeDefinitionIsAccessible(firstResult.GetDefinition())) {
+								if (TopLevelTypeDefinitionIsAccessible(resultType.GetDefinition()))
+									firstResult = resultType;
+							} else if (TopLevelTypeDefinitionIsAccessible(def)) {
+								return new AmbiguousTypeResolveResult(firstResult);
+							}
+						}
+					}
+					if (firstResult != null)
+						return new TypeResolveResult(firstResult);
+				}
+				// if we didn't find anything: repeat lookup with parent namespace
+			}
+			return null;
+		}
+
+		ResolveResult LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespace n, string identifier, IList<IType> typeArguments, bool parameterizeResultType)
+		{
+			if (n == null)
+				return null;
+			// first look for a namespace
+			int k = typeArguments.Count;
+			if (k == 0) {
+				INamespace childNamespace = n.GetChildNamespace(identifier);
+				if (childNamespace != null) {
+					if (usingScope != null && usingScope.HasAlias(identifier))
+						return new AmbiguousTypeResolveResult(new UnknownType(null, identifier));
+					return new NamespaceResolveResult(childNamespace);
+				}
+			}
+			// then look for a type
+			ITypeDefinition def = n.GetTypeDefinition(identifier, k);
+			if (def != null) {
+				IType result = def;
+				if (parameterizeResultType && k > 0) {
+					result = new ParameterizedType(def, typeArguments);
+				}
+				if (usingScope != null && usingScope.HasAlias(identifier))
+					return new AmbiguousTypeResolveResult(result);
+				else
+					return new TypeResolveResult(result);
+			}
+			return null;
+		}
+		
+		bool TopLevelTypeDefinitionIsAccessible(ITypeDefinition typeDef)
+		{
+			if (typeDef.IsInternal) {
+				return typeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly);
+			}
+			return true;
+		}
+		
+		/// <summary>
+		/// Looks up an alias (identifier in front of :: operator)
+		/// </summary>
+		public ResolveResult ResolveAlias(string identifier)
+		{
+			if (identifier == "global")
+				return new NamespaceResolveResult(compilation.RootNamespace);
+			
+			for (ResolvedUsingScope n = this.CurrentUsingScope; n != null; n = n.Parent) {
+				if (n.ExternAliases.Contains(identifier)) {
+					return ResolveExternAlias(identifier);
+				}
+				foreach (var pair in n.UsingAliases) {
+					if (pair.Key == identifier) {
+						return (pair.Value as NamespaceResolveResult) ?? ErrorResult;
+					}
+				}
+			}
+			return ErrorResult;
+		}
+		
+		ResolveResult ResolveExternAlias(string alias)
+		{
+			INamespace ns = compilation.GetNamespaceForExternAlias(alias);
+			if (ns != null)
+				return new NamespaceResolveResult(ns);
+			else
+				return ErrorResult;
+		}
+		#endregion
+		
+		#region ResolveMemberAccess
+		public ResolveResult ResolveMemberAccess(ResolveResult target, string identifier, IList<IType> typeArguments, NameLookupMode lookupMode = NameLookupMode.Expression)
+		{
+			// C# 4.0 spec: §7.6.4
+			
+			bool parameterizeResultType = !(typeArguments.Count != 0 && typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument));
+			NamespaceResolveResult nrr = target as NamespaceResolveResult;
+			if (nrr != null) {
+				return ResolveMemberAccessOnNamespace(nrr, identifier, typeArguments, parameterizeResultType);
+			}
+			
+			if (target.Type.Kind == TypeKind.Dynamic)
+				return new DynamicMemberResolveResult(target, identifier);
+			
+			MemberLookup lookup = CreateMemberLookup(lookupMode);
+			ResolveResult result;
+			switch (lookupMode) {
+				case NameLookupMode.Expression:
+					result = lookup.Lookup(target, identifier, typeArguments, isInvocation: false);
+					break;
+				case NameLookupMode.InvocationTarget:
+					result = lookup.Lookup(target, identifier, typeArguments, isInvocation: true);
+					break;
+				case NameLookupMode.Type:
+				case NameLookupMode.TypeInUsingDeclaration:
+				case NameLookupMode.BaseTypeReference:
+					// Don't do the UnknownMemberResolveResult/MethodGroupResolveResult processing,
+					// it's only relevant for expressions.
+					return lookup.LookupType(target.Type, identifier, typeArguments, parameterizeResultType);
+				default:
+					throw new NotSupportedException("Invalid value for NameLookupMode");
+			}
+			if (result is UnknownMemberResolveResult) {
+				// We intentionally use all extension methods here, not just the eligible ones.
+				// Proper eligibility checking is only possible for the full invocation
+				// (after we know the remaining arguments).
+				// The eligibility check in GetExtensionMethods is only intended for code completion.
+				var extensionMethods = GetExtensionMethods(identifier, typeArguments);
+				if (extensionMethods.Count > 0) {
+					return new MethodGroupResolveResult(target, identifier, EmptyList<MethodListWithDeclaringType>.Instance, typeArguments) {
+						extensionMethods = extensionMethods
+					};
+				}
+			} else {
+				MethodGroupResolveResult mgrr = result as MethodGroupResolveResult;
+				if (mgrr != null) {
+					Debug.Assert(mgrr.extensionMethods == null);
+					// set the values that are necessary to make MethodGroupResolveResult.GetExtensionMethods() work
+					mgrr.resolver = this;
+				}
+			}
+			return result;
+		}
+		
+		[Obsolete("Use ResolveMemberAccess() with NameLookupMode.Type instead")]
+		public ResolveResult ResolveMemberType(ResolveResult target, string identifier, IList<IType> typeArguments)
+		{
+			return ResolveMemberAccess(target, identifier, typeArguments, NameLookupMode.Type);
+		}
+		
+		ResolveResult ResolveMemberAccessOnNamespace(NamespaceResolveResult nrr, string identifier, IList<IType> typeArguments, bool parameterizeResultType)
+		{
+			if (typeArguments.Count == 0) {
+				INamespace childNamespace = nrr.Namespace.GetChildNamespace(identifier);
+				if (childNamespace != null)
+					return new NamespaceResolveResult(childNamespace);
+			}
+			ITypeDefinition def = nrr.Namespace.GetTypeDefinition(identifier, typeArguments.Count);
+			if (def != null) {
+				if (parameterizeResultType && typeArguments.Count > 0)
+					return new TypeResolveResult(new ParameterizedType(def, typeArguments));
+				else
+					return new TypeResolveResult(def);
+			}
+			return ErrorResult;
+		}
+		
+		/// <summary>
+		/// Creates a MemberLookup instance using this resolver's settings.
+		/// </summary>
+		public MemberLookup CreateMemberLookup()
+		{
+			ITypeDefinition currentTypeDefinition = this.CurrentTypeDefinition;
+			bool isInEnumMemberInitializer = this.CurrentMember != null && this.CurrentMember.SymbolKind == SymbolKind.Field
+				&& currentTypeDefinition != null && currentTypeDefinition.Kind == TypeKind.Enum;
+			return new MemberLookup(currentTypeDefinition, this.Compilation.MainAssembly, isInEnumMemberInitializer);
+		}
+		
+		/// <summary>
+		/// Creates a MemberLookup instance using this resolver's settings.
+		/// </summary>
+		public MemberLookup CreateMemberLookup(NameLookupMode lookupMode)
+		{
+			if (lookupMode == NameLookupMode.BaseTypeReference && this.CurrentTypeDefinition != null) {
+				// When looking up a base type reference, treat us as being outside the current type definition
+				// for accessibility purposes.
+				// This avoids a stack overflow when referencing a protected class nested inside the base class
+				// of a parent class. (NameLookupTests.InnerClassInheritingFromProtectedBaseInnerClassShouldNotCauseStackOverflow)
+				return new MemberLookup(this.CurrentTypeDefinition.DeclaringTypeDefinition, this.Compilation.MainAssembly, false);
+			} else {
+				return CreateMemberLookup();
+			}
+		}
+		#endregion
+		
+		#region ResolveIdentifierInObjectInitializer
+		public ResolveResult ResolveIdentifierInObjectInitializer(string identifier)
+		{
+			MemberLookup memberLookup = CreateMemberLookup();
+			return memberLookup.Lookup(this.CurrentObjectInitializer, identifier, EmptyList<IType>.Instance, false);
+		}
+		#endregion
+		
+		#region GetExtensionMethods
+		/// <summary>
+		/// Gets all extension methods that are available in the current context.
+		/// </summary>
+		/// <param name="name">Name of the extension method. Pass null to retrieve all extension methods.</param>
+		/// <param name="typeArguments">Explicitly provided type arguments.
+		/// An empty list will return all matching extension method definitions;
+		/// a non-empty list will return <see cref="SpecializedMethod"/>s for all extension methods
+		/// with the matching number of type parameters.</param>
+		/// <remarks>
+		/// The results are stored in nested lists because they are grouped by using scope.
+		/// That is, for "using SomeExtensions; namespace X { using MoreExtensions; ... }",
+		/// the return value will be
+		/// new List {
+		///    new List { all extensions from MoreExtensions },
+		///    new List { all extensions from SomeExtensions }
+		/// }
+		/// </remarks>
+		public List<List<IMethod>> GetExtensionMethods(string name = null, IList<IType> typeArguments = null)
+		{
+			return GetExtensionMethods(null, name, typeArguments);
+		}
+		
+		/// <summary>
+		/// Gets the extension methods that are called 'name'
+		/// and are applicable with a first argument type of 'targetType'.
+		/// </summary>
+		/// <param name="targetType">Type of the 'this' argument</param>
+		/// <param name="name">Name of the extension method. Pass null to retrieve all extension methods.</param>
+		/// <param name="typeArguments">Explicitly provided type arguments.
+		/// An empty list will return all matching extension method definitions;
+		/// a non-empty list will return <see cref="SpecializedMethod"/>s for all extension methods
+		/// with the matching number of type parameters.</param>
+		/// <param name="substituteInferredTypes">
+		/// Specifies whether to produce a <see cref="SpecializedMethod"/>
+		/// when type arguments could be inferred from <paramref name="targetType"/>. This parameter
+		/// is only used for inferred types and has no effect if <paramref name="typeArguments"/> is non-empty.
+		/// </param>
+		/// <remarks>
+		/// The results are stored in nested lists because they are grouped by using scope.
+		/// That is, for "using SomeExtensions; namespace X { using MoreExtensions; ... }",
+		/// the return value will be
+		/// new List {
+		///    new List { all extensions from MoreExtensions },
+		///    new List { all extensions from SomeExtensions }
+		/// }
+		/// </remarks>
+		public List<List<IMethod>> GetExtensionMethods(IType targetType, string name = null, IList<IType> typeArguments = null, bool substituteInferredTypes = false)
+		{
+			var lookup = CreateMemberLookup();
+			List<List<IMethod>> extensionMethodGroups = new List<List<IMethod>>();
+			foreach (var inputGroup in GetAllExtensionMethods(lookup)) {
+				List<IMethod> outputGroup = new List<IMethod>();
+				foreach (var method in inputGroup) {
+					if (name != null && method.Name != name)
+						continue;
+					if (!lookup.IsAccessible(method, false))
+						continue;
+					IType[] inferredTypes;
+					if (typeArguments != null && typeArguments.Count > 0) {
+						if (method.TypeParameters.Count != typeArguments.Count)
+							continue;
+						var sm = method.Specialize(new TypeParameterSubstitution(null, typeArguments));
+						if (IsEligibleExtensionMethod(compilation, conversions, targetType, sm, false, out inferredTypes))
+							outputGroup.Add(sm);
+					} else {
+						if (IsEligibleExtensionMethod(compilation, conversions, targetType, method, true, out inferredTypes)) {
+							if (substituteInferredTypes && inferredTypes != null) {
+								outputGroup.Add(method.Specialize(new TypeParameterSubstitution(null, inferredTypes)));
+							} else {
+								outputGroup.Add(method);
+							}
+						}
+					}
+				}
+				if (outputGroup.Count > 0)
+					extensionMethodGroups.Add(outputGroup);
+			}
+			return extensionMethodGroups;
+		}
+		
+		/// <summary>
+		/// Checks whether the specified extension method is eligible on the target type.
+		/// </summary>
+		/// <param name="targetType">Target type that is passed as first argument to the extension method.</param>
+		/// <param name="method">The extension method.</param>
+		/// <param name="useTypeInference">Whether to perform type inference for the method.
+		/// Use <c>false</c> if <paramref name="method"/> is already parameterized (e.g. when type arguments were given explicitly).
+		/// Otherwise, use <c>true</c>.
+		/// </param>
+		/// <param name="outInferredTypes">If the method is generic and <paramref name="useTypeInference"/> is <c>true</c>,
+		/// and at least some of the type arguments could be inferred, this parameter receives the inferred type arguments.
+		/// Since only the type for the first parameter is considered, not all type arguments may be inferred.
+		/// If an array is returned, any slot with an uninferred type argument will be set to the method's
+		/// corresponding type parameter.
+		/// </param>
+		public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
+		{
+			if (targetType == null)
+				throw new ArgumentNullException("targetType");
+			if (method == null)
+				throw new ArgumentNullException("method");
+			var compilation = method.Compilation;
+			return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes);
+		}
+		
+		static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
+		{
+			outInferredTypes = null;
+			if (targetType == null)
+				return true;
+			if (method.Parameters.Count == 0)
+				return false;
+			IType thisParameterType = method.Parameters[0].Type;
+			if (useTypeInference && method.TypeParameters.Count > 0) {
+				// We need to infer type arguments from targetType:
+				TypeInference ti = new TypeInference(compilation, conversions);
+				ResolveResult[] arguments = { new ResolveResult(targetType) };
+				IType[] parameterTypes = { method.Parameters[0].Type };
+				bool success;
+				var inferredTypes = ti.InferTypeArguments(method.TypeParameters, arguments, parameterTypes, out success);
+				var substitution = new TypeParameterSubstitution(null, inferredTypes);
+				// Validate that the types that could be inferred (aren't unknown) satisfy the constraints:
+				bool hasInferredTypes = false;
+				for (int i = 0; i < inferredTypes.Length; i++) {
+					if (inferredTypes[i].Kind != TypeKind.Unknown && inferredTypes[i].Kind != TypeKind.UnboundTypeArgument) {
+						hasInferredTypes = true;
+						if (!OverloadResolution.ValidateConstraints(method.TypeParameters[i], inferredTypes[i], substitution, conversions))
+							return false;
+					} else {
+						inferredTypes[i] = method.TypeParameters[i]; // do not substitute types that could not be inferred
+					}
+				}
+				if (hasInferredTypes)
+					outInferredTypes = inferredTypes;
+				thisParameterType = thisParameterType.AcceptVisitor(substitution);
+			}
+			Conversion c = conversions.ImplicitConversion(targetType, thisParameterType);
+			return c.IsValid && (c.IsIdentityConversion || c.IsReferenceConversion || c.IsBoxingConversion);
+		}
+		
+		/// <summary>
+		/// Gets all extension methods available in the current using scope.
+		/// This list includes inaccessible methods.
+		/// </summary>
+		IList<List<IMethod>> GetAllExtensionMethods(MemberLookup lookup)
+		{
+			var currentUsingScope = context.CurrentUsingScope;
+			if (currentUsingScope == null)
+				return EmptyList<List<IMethod>>.Instance;
+			List<List<IMethod>> extensionMethodGroups = LazyInit.VolatileRead(ref currentUsingScope.AllExtensionMethods);
+			if (extensionMethodGroups != null) {
+				return extensionMethodGroups;
+			}
+			extensionMethodGroups = new List<List<IMethod>>();
+			List<IMethod> m;
+			for (ResolvedUsingScope scope = currentUsingScope; scope != null; scope = scope.Parent) {
+				INamespace ns = scope.Namespace;
+				if (ns != null) {
+					m = GetExtensionMethods(lookup, ns).ToList();
+					if (m.Count > 0)
+						extensionMethodGroups.Add(m);
+				}
+				
+				m = scope.Usings
+					.Distinct()
+					.SelectMany(importedNamespace =>  GetExtensionMethods(lookup, importedNamespace))
+					.ToList();
+				if (m.Count > 0)
+					extensionMethodGroups.Add(m);
+			}
+			return LazyInit.GetOrSet(ref currentUsingScope.AllExtensionMethods, extensionMethodGroups);
+		}
+		
+		IEnumerable<IMethod> GetExtensionMethods(MemberLookup lookup, INamespace ns)
+		{
+			// TODO: maybe make this a property on INamespace?
+			return
+				from c in ns.Types
+				where c.IsStatic && c.HasExtensionMethods && c.TypeParameters.Count == 0 && lookup.IsAccessible(c, false)
+				from m in c.Methods
+				where m.IsExtensionMethod
+				select m;
+		}
+		#endregion
+		
+		#region ResolveInvocation
+
+		IList<ResolveResult> AddArgumentNamesIfNecessary(ResolveResult[] arguments, string[] argumentNames) {
+			if (argumentNames == null) {
+				return arguments;
+			}
+			else {
+				var result = new ResolveResult[arguments.Length];
+				for (int i = 0; i < arguments.Length; i++) {
+					result[i] = (argumentNames[i] != null ? new NamedArgumentResolveResult(argumentNames[i], arguments[i]) : arguments[i]);
+				}
+				return result;
+			}
+		}
+
+		private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[] argumentNames, bool allowOptionalParameters)
+		{
+			// C# 4.0 spec: §7.6.5
+			
+			if (target.Type.Kind == TypeKind.Dynamic) {
+				return new DynamicInvocationResolveResult(target, DynamicInvocationType.Invocation, AddArgumentNamesIfNecessary(arguments, argumentNames));
+			}
+			
+			bool isDynamic = arguments.Any(a => a.Type.Kind == TypeKind.Dynamic);
+			MethodGroupResolveResult mgrr = target as MethodGroupResolveResult;
+			if (mgrr != null) {
+				if (isDynamic) {
+					// If we have dynamic arguments, we need to represent the invocation as a dynamic invocation if there is more than one applicable method.
+					var or2 = CreateOverloadResolution(arguments, argumentNames, mgrr.TypeArguments.ToArray());
+					var applicableMethods = mgrr.MethodsGroupedByDeclaringType.SelectMany(m => m, (x, m) => new { x.DeclaringType, Method = m }).Where(x => OverloadResolution.IsApplicable(or2.AddCandidate(x.Method))).ToList();
+
+					if (applicableMethods.Count > 1) {
+						ResolveResult actualTarget;
+						if (applicableMethods.All(x => x.Method.IsStatic) && !(mgrr.TargetResult is TypeResolveResult))
+							actualTarget = new TypeResolveResult(mgrr.TargetType);
+						else
+							actualTarget = mgrr.TargetResult;
+
+						var l = new List<MethodListWithDeclaringType>();
+						foreach (var m in applicableMethods) {
+							if (l.Count == 0 || l[l.Count - 1].DeclaringType != m.DeclaringType)
+								l.Add(new MethodListWithDeclaringType(m.DeclaringType));
+							l[l.Count - 1].Add(m.Method);
+						}
+						return new DynamicInvocationResolveResult(new MethodGroupResolveResult(actualTarget, mgrr.MethodName, l, mgrr.TypeArguments), DynamicInvocationType.Invocation, AddArgumentNamesIfNecessary(arguments, argumentNames));
+					}
+				}
+
+				OverloadResolution or = mgrr.PerformOverloadResolution(compilation, arguments, argumentNames, checkForOverflow: checkForOverflow, conversions: conversions, allowOptionalParameters: allowOptionalParameters);
+				if (or.BestCandidate != null) {
+					if (or.BestCandidate.IsStatic && !or.IsExtensionMethodInvocation && !(mgrr.TargetResult is TypeResolveResult))
+						return or.CreateResolveResult(new TypeResolveResult(mgrr.TargetType), returnTypeOverride: isDynamic ? SpecialType.Dynamic : null);
+					else
+						return or.CreateResolveResult(mgrr.TargetResult, returnTypeOverride: isDynamic ? SpecialType.Dynamic : null);
+				} else {
+					// No candidate found at all (not even an inapplicable one).
+					// This can happen with empty method groups (as sometimes used with extension methods)
+					return new UnknownMethodResolveResult(
+						mgrr.TargetType, mgrr.MethodName, mgrr.TypeArguments, CreateParameters(arguments, argumentNames));
+				}
+			}
+			UnknownMemberResolveResult umrr = target as UnknownMemberResolveResult;
+			if (umrr != null) {
+				return new UnknownMethodResolveResult(umrr.TargetType, umrr.MemberName, umrr.TypeArguments, CreateParameters(arguments, argumentNames));
+			}
+			UnknownIdentifierResolveResult uirr = target as UnknownIdentifierResolveResult;
+			if (uirr != null && CurrentTypeDefinition != null) {
+				return new UnknownMethodResolveResult(CurrentTypeDefinition, uirr.Identifier, EmptyList<IType>.Instance, CreateParameters(arguments, argumentNames));
+			}
+			IMethod invokeMethod = target.Type.GetDelegateInvokeMethod();
+			if (invokeMethod != null) {
+				OverloadResolution or = CreateOverloadResolution(arguments, argumentNames);
+				or.AddCandidate(invokeMethod);
+				return new CSharpInvocationResolveResult(
+					target, invokeMethod, //invokeMethod.ReturnType.Resolve(context),
+					or.GetArgumentsWithConversionsAndNames(), or.BestCandidateErrors,
+					isExpandedForm: or.BestCandidateIsExpandedForm,
+					isDelegateInvocation: true,
+					argumentToParameterMap: or.GetArgumentToParameterMap(),
+					returnTypeOverride: isDynamic ? SpecialType.Dynamic : null);
+			}
+			return ErrorResult;
+		}
+
+		/// <summary>
+		/// Resolves an invocation.
+		/// </summary>
+		/// <param name="target">The target of the invocation. Usually a MethodGroupResolveResult.</param>
+		/// <param name="arguments">
+		/// Arguments passed to the method.
+		/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
+		/// </param>
+		/// <param name="argumentNames">
+		/// The argument names. Pass the null string for positional arguments.
+		/// </param>
+		/// <returns>InvocationResolveResult or UnknownMethodResolveResult</returns>
+		public ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[] argumentNames = null)
+		{
+			return ResolveInvocation(target, arguments, argumentNames, allowOptionalParameters: true);
+		}
+		
+		List<IParameter> CreateParameters(ResolveResult[] arguments, string[] argumentNames)
+		{
+			List<IParameter> list = new List<IParameter>();
+			if (argumentNames == null) {
+				argumentNames = new string[arguments.Length];
+			} else {
+				if (argumentNames.Length != arguments.Length)
+					throw new ArgumentException();
+				argumentNames = (string[])argumentNames.Clone();
+			}
+			for (int i = 0; i < arguments.Length; i++) {
+				// invent argument names where necessary:
+				if (argumentNames[i] == null) {
+					string newArgumentName = GuessParameterName(arguments[i]);
+					if (argumentNames.Contains(newArgumentName)) {
+						// disambiguate argument name (e.g. add a number)
+						int num = 1;
+						string newName;
+						do {
+							newName = newArgumentName + num.ToString();
+							num++;
+						} while(argumentNames.Contains(newName));
+						newArgumentName = newName;
+					}
+					argumentNames[i] = newArgumentName;
+				}
+				
+				// create the parameter:
+				ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult;
+				if (brrr != null) {
+					list.Add(new DefaultParameter(arguments[i].Type, argumentNames[i], isRef: brrr.IsRef, isOut: brrr.IsOut));
+				} else {
+					// argument might be a lambda or delegate type, so we have to try to guess the delegate type
+					IType type = arguments[i].Type;
+					if (type.Kind == TypeKind.Null || type.Kind == TypeKind.Unknown) {
+						list.Add(new DefaultParameter(compilation.FindType(KnownTypeCode.Object), argumentNames[i]));
+					} else {
+						list.Add(new DefaultParameter(type, argumentNames[i]));
+					}
+				}
+			}
+			return list;
+		}
+		
+		static string GuessParameterName(ResolveResult rr)
+		{
+			MemberResolveResult mrr = rr as MemberResolveResult;
+			if (mrr != null)
+				return mrr.Member.Name;
+			
+			UnknownMemberResolveResult umrr = rr as UnknownMemberResolveResult;
+			if (umrr != null)
+				return umrr.MemberName;
+			
+			MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult;
+			if (mgrr != null)
+				return mgrr.MethodName;
+			
+			LocalResolveResult vrr = rr as LocalResolveResult;
+			if (vrr != null)
+				return MakeParameterName(vrr.Variable.Name);
+			
+			if (rr.Type.Kind != TypeKind.Unknown && !string.IsNullOrEmpty(rr.Type.Name)) {
+				return MakeParameterName(rr.Type.Name);
+			} else {
+				return "parameter";
+			}
+		}
+		
+		static string MakeParameterName(string variableName)
+		{
+			if (string.IsNullOrEmpty(variableName))
+				return "parameter";
+			if (variableName.Length > 1 && variableName[0] == '_')
+				variableName = variableName.Substring(1);
+			return char.ToLower(variableName[0]) + variableName.Substring(1);
+		}
+		
+		OverloadResolution CreateOverloadResolution(ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null)
+		{
+			var or = new OverloadResolution(compilation, arguments, argumentNames, typeArguments, conversions);
+			or.CheckForOverflow = checkForOverflow;
+			return or;
+		}
+		#endregion
+		
+		#region ResolveIndexer
+		/// <summary>
+		/// Resolves an indexer access.
+		/// </summary>
+		/// <param name="target">Target expression.</param>
+		/// <param name="arguments">
+		/// Arguments passed to the indexer.
+		/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
+		/// </param>
+		/// <param name="argumentNames">
+		/// The argument names. Pass the null string for positional arguments.
+		/// </param>
+		/// <returns>ArrayAccessResolveResult, InvocationResolveResult, or ErrorResolveResult</returns>
+		public ResolveResult ResolveIndexer(ResolveResult target, ResolveResult[] arguments, string[] argumentNames = null)
+		{
+			switch (target.Type.Kind) {
+				case TypeKind.Dynamic:
+					return new DynamicInvocationResolveResult(target, DynamicInvocationType.Indexing, AddArgumentNamesIfNecessary(arguments, argumentNames));
+					
+				case TypeKind.Array:
+				case TypeKind.Pointer:
+					// §7.6.6.1 Array access / §18.5.3 Pointer element access
+					AdjustArrayAccessArguments(arguments);
+					return new ArrayAccessResolveResult(((TypeWithElementType)target.Type).ElementType, target, arguments);
+			}
+			
+			// §7.6.6.2 Indexer access
+
+			MemberLookup lookup = CreateMemberLookup();
+			var indexers = lookup.LookupIndexers(target);
+
+			if (arguments.Any(a => a.Type.Kind == TypeKind.Dynamic)) {
+				// If we have dynamic arguments, we need to represent the invocation as a dynamic invocation if there is more than one applicable indexer.
+				var or2 = CreateOverloadResolution(arguments, argumentNames, null);
+				var applicableIndexers = indexers.SelectMany(x => x).Where(m => OverloadResolution.IsApplicable(or2.AddCandidate(m))).ToList();
+
+				if (applicableIndexers.Count > 1) {
+					return new DynamicInvocationResolveResult(target, DynamicInvocationType.Indexing, AddArgumentNamesIfNecessary(arguments, argumentNames));
+				}
+			}
+
+			OverloadResolution or = CreateOverloadResolution(arguments, argumentNames);
+			or.AddMethodLists(indexers);
+			if (or.BestCandidate != null) {
+				return or.CreateResolveResult(target);
+			} else {
+				return ErrorResult;
+			}
+		}
+		
+		/// <summary>
+		/// Converts all arguments to int,uint,long or ulong.
+		/// </summary>
+		void AdjustArrayAccessArguments(ResolveResult[] arguments)
+		{
+			for (int i = 0; i < arguments.Length; i++) {
+				if (!(TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.Int32)) ||
+				      TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.UInt32)) ||
+				      TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.Int64)) ||
+				      TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.UInt64))))
+				{
+					// conversion failed
+					arguments[i] = Convert(arguments[i], compilation.FindType(KnownTypeCode.Int32), Conversion.None);
+				}
+			}
+		}
+		#endregion
+		
+		#region ResolveObjectCreation
+		/// <summary>
+		/// Resolves an object creation.
+		/// </summary>
+		/// <param name="type">Type of the object to create.</param>
+		/// <param name="arguments">
+		/// Arguments passed to the constructor.
+		/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
+		/// </param>
+		/// <param name="argumentNames">
+		/// The argument names. Pass the null string for positional arguments.
+		/// </param>
+		/// <param name="allowProtectedAccess">
+		/// Whether to allow calling protected constructors.
+		/// This should be false except when resolving constructor initializers.
+		/// </param>
+		/// <param name="initializerStatements">
+		/// Statements for Objects/Collections initializer.
+		/// <see cref="InvocationResolveResult.InitializerStatements"/>
+		/// </param>
+		/// <returns>InvocationResolveResult or ErrorResolveResult</returns>
+		public ResolveResult ResolveObjectCreation(IType type, ResolveResult[] arguments, string[] argumentNames = null, bool allowProtectedAccess = false, IList<ResolveResult> initializerStatements = null)
+		{
+			if (type.Kind == TypeKind.Delegate && arguments.Length == 1) {
+				ResolveResult input = arguments[0];
+				IMethod invoke = input.Type.GetDelegateInvokeMethod();
+				if (invoke != null) {
+					input = new MethodGroupResolveResult(
+						input, invoke.Name,
+						methods: new[] { new MethodListWithDeclaringType(invoke.DeclaringType) { invoke } },
+						typeArguments: EmptyList<IType>.Instance
+					);
+				}
+				return Convert(input, type);
+			}
+			OverloadResolution or = CreateOverloadResolution(arguments, argumentNames);
+			MemberLookup lookup = CreateMemberLookup();
+			var allApplicable = (arguments.Any(a => a.Type.Kind == TypeKind.Dynamic) ? new List<IMethod>() : null);
+			foreach (IMethod ctor in type.GetConstructors()) {
+				if (lookup.IsAccessible(ctor, allowProtectedAccess)) {
+					var orErrors = or.AddCandidate(ctor);
+					if (allApplicable != null && OverloadResolution.IsApplicable(orErrors))
+						allApplicable.Add(ctor);
+				}
+				else
+					or.AddCandidate(ctor, OverloadResolutionErrors.Inaccessible);
+			}
+
+			if (allApplicable != null && allApplicable.Count > 1) {
+				// If we have dynamic arguments, we need to represent the invocation as a dynamic invocation if there is more than one applicable constructor.
+				return new DynamicInvocationResolveResult(new MethodGroupResolveResult(null, allApplicable[0].Name, new[] { new MethodListWithDeclaringType(type, allApplicable) }, null), DynamicInvocationType.ObjectCreation, AddArgumentNamesIfNecessary(arguments, argumentNames), initializerStatements);
+			}
+
+			if (or.BestCandidate != null) {
+				return or.CreateResolveResult(null, initializerStatements);
+			} else {
+				return new ErrorResolveResult(type);
+			}
+		}
+		#endregion
+		
+		#region ResolveSizeOf
+		/// <summary>
+		/// Resolves 'sizeof(type)'.
+		/// </summary>
+		public ResolveResult ResolveSizeOf(IType type)
+		{
+			IType int32 = compilation.FindType(KnownTypeCode.Int32);
+			int? size = null;
+			var typeForConstant = (type.Kind == TypeKind.Enum) ? type.GetDefinition().EnumUnderlyingType : type;
+
+			switch (ReflectionHelper.GetTypeCode(typeForConstant)) {
+				case TypeCode.Boolean:
+				case TypeCode.SByte:
+				case TypeCode.Byte:
+					size = 1;
+					break;
+				case TypeCode.Char:
+				case TypeCode.Int16:
+				case TypeCode.UInt16:
+					size = 2;
+					break;
+				case TypeCode.Int32:
+				case TypeCode.UInt32:
+				case TypeCode.Single:
+					size = 4;
+					break;
+				case TypeCode.Int64:
+				case TypeCode.UInt64:
+				case TypeCode.Double:
+					size = 8;
+					break;
+			}
+			return new SizeOfResolveResult(int32, type, size);
+		}
+		#endregion
+		
+		#region Resolve This/Base Reference
+		/// <summary>
+		/// Resolves 'this'.
+		/// </summary>
+		public ResolveResult ResolveThisReference()
+		{
+			ITypeDefinition t = CurrentTypeDefinition;
+			if (t != null) {
+				if (t.TypeParameterCount != 0) {
+					// Self-parameterize the type
+					return new ThisResolveResult(new ParameterizedType(t, t.TypeParameters));
+				} else {
+					return new ThisResolveResult(t);
+				}
+			}
+			return ErrorResult;
+		}
+		
+		/// <summary>
+		/// Resolves 'base'.
+		/// </summary>
+		public ResolveResult ResolveBaseReference()
+		{
+			ITypeDefinition t = CurrentTypeDefinition;
+			if (t != null) {
+				foreach (IType baseType in t.DirectBaseTypes) {
+					if (baseType.Kind != TypeKind.Unknown && baseType.Kind != TypeKind.Interface) {
+						return new ThisResolveResult(baseType, causesNonVirtualInvocation: true);
+					}
+				}
+			}
+			return ErrorResult;
+		}
+		#endregion
+		
+		#region ResolveConditional
+		/// <summary>
+		/// Converts the input to <c>bool</c> using the rules for boolean expressions.
+		/// That is, <c>operator true</c> is used if a regular conversion to <c>bool</c> is not possible.
+		/// </summary>
+		public ResolveResult ResolveCondition(ResolveResult input)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			IType boolean = compilation.FindType(KnownTypeCode.Boolean);
+			Conversion c = conversions.ImplicitConversion(input, boolean);
+			if (!c.IsValid) {
+				var opTrue = input.Type.GetMethods(m => m.IsOperator && m.Name == "op_True").FirstOrDefault();
+				if (opTrue != null) {
+					c = Conversion.UserDefinedConversion(opTrue, isImplicit: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
+				}
+			}
+			return Convert(input, boolean, c);
+		}
+		
+		/// <summary>
+		/// Converts the negated input to <c>bool</c> using the rules for boolean expressions.
+		/// Computes <c>!(bool)input</c> if the implicit cast to bool is valid; otherwise
+		/// computes <c>input.operator false()</c>.
+		/// </summary>
+		public ResolveResult ResolveConditionFalse(ResolveResult input)
+		{
+			if (input == null)
+				throw new ArgumentNullException("input");
+			IType boolean = compilation.FindType(KnownTypeCode.Boolean);
+			Conversion c = conversions.ImplicitConversion(input, boolean);
+			if (!c.IsValid) {
+				var opFalse = input.Type.GetMethods(m => m.IsOperator && m.Name == "op_False").FirstOrDefault();
+				if (opFalse != null) {
+					c = Conversion.UserDefinedConversion(opFalse, isImplicit: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
+					return Convert(input, boolean, c);
+				}
+			}
+			return ResolveUnaryOperator(UnaryOperatorType.Not, Convert(input, boolean, c));
+		}
+		
+		public ResolveResult ResolveConditional(ResolveResult condition, ResolveResult trueExpression, ResolveResult falseExpression)
+		{
+			// C# 4.0 spec §7.14: Conditional operator
+			
+			bool isValid;
+			IType resultType;
+			if (trueExpression.Type.Kind == TypeKind.Dynamic || falseExpression.Type.Kind == TypeKind.Dynamic) {
+				resultType = SpecialType.Dynamic;
+				isValid = TryConvert(ref trueExpression, resultType) & TryConvert(ref falseExpression, resultType);
+			} else if (HasType(trueExpression) && HasType(falseExpression)) {
+				Conversion t2f = conversions.ImplicitConversion(trueExpression, falseExpression.Type);
+				Conversion f2t = conversions.ImplicitConversion(falseExpression, trueExpression.Type);
+				// The operator is valid:
+				// a) if there's a conversion in one direction but not the other
+				// b) if there are conversions in both directions, and the types are equivalent
+				if (IsBetterConditionalConversion(t2f, f2t)) {
+					resultType = falseExpression.Type;
+					isValid = true;
+					trueExpression = Convert(trueExpression, resultType, t2f);
+				} else if (IsBetterConditionalConversion(f2t, t2f)) {
+					resultType = trueExpression.Type;
+					isValid = true;
+					falseExpression = Convert(falseExpression, resultType, f2t);
+				} else {
+					resultType = trueExpression.Type;
+					isValid = trueExpression.Type.Equals(falseExpression.Type);
+				}
+			} else if (HasType(trueExpression)) {
+				resultType = trueExpression.Type;
+				isValid = TryConvert(ref falseExpression, resultType);
+			} else if (HasType(falseExpression)) {
+				resultType = falseExpression.Type;
+				isValid = TryConvert(ref trueExpression, resultType);
+			} else {
+				return ErrorResult;
+			}
+			condition = ResolveCondition(condition);
+			if (isValid) {
+				if (condition.IsCompileTimeConstant && trueExpression.IsCompileTimeConstant && falseExpression.IsCompileTimeConstant) {
+					bool? val = condition.ConstantValue as bool?;
+					if (val == true)
+						return trueExpression;
+					else if (val == false)
+						return falseExpression;
+				}
+				return new OperatorResolveResult(resultType, System.Linq.Expressions.ExpressionType.Conditional,
+				                                 condition, trueExpression, falseExpression);
+			} else {
+				return new ErrorResolveResult(resultType);
+			}
+		}
+		
+		bool IsBetterConditionalConversion(Conversion c1, Conversion c2)
+		{
+			// Valid is better than ImplicitConstantExpressionConversion is better than invalid
+			if (!c1.IsValid)
+				return false;
+			if (c1 != Conversion.ImplicitConstantExpressionConversion && c2 == Conversion.ImplicitConstantExpressionConversion)
+				return true;
+			return !c2.IsValid;
+		}
+		
+		bool HasType(ResolveResult r)
+		{
+			return r.Type.Kind != TypeKind.Unknown && r.Type.Kind != TypeKind.Null;
+		}
+		#endregion
+		
+		#region ResolvePrimitive
+		public ResolveResult ResolvePrimitive(object value)
+		{
+			if (value == null) {
+				return new ResolveResult(SpecialType.NullType);
+			} else {
+				TypeCode typeCode = Type.GetTypeCode(value.GetType());
+				IType type = compilation.FindType(typeCode);
+				return new ConstantResolveResult(type, value);
+			}
+		}
+		#endregion
+		
+		#region ResolveDefaultValue
+		public ResolveResult ResolveDefaultValue(IType type)
+		{
+			return new ConstantResolveResult(type, GetDefaultValue(type));
+		}
+		
+		public static object GetDefaultValue(IType type)
+		{
+			ITypeDefinition typeDef = type.GetDefinition();
+			if (typeDef == null)
+				return null;
+			if (typeDef.Kind == TypeKind.Enum) {
+				typeDef = typeDef.EnumUnderlyingType.GetDefinition();
+				if (typeDef == null)
+					return null;
+			}
+			switch (typeDef.KnownTypeCode) {
+				case KnownTypeCode.Boolean:
+					return false;
+				case KnownTypeCode.Char:
+					return '\0';
+				case KnownTypeCode.SByte:
+					return (sbyte)0;
+				case KnownTypeCode.Byte:
+					return (byte)0;
+				case KnownTypeCode.Int16:
+					return (short)0;
+				case KnownTypeCode.UInt16:
+					return (ushort)0;
+				case KnownTypeCode.Int32:
+					return 0;
+				case KnownTypeCode.UInt32:
+					return 0U;
+				case KnownTypeCode.Int64:
+					return 0L;
+				case KnownTypeCode.UInt64:
+					return 0UL;
+				case KnownTypeCode.Single:
+					return 0f;
+				case KnownTypeCode.Double:
+					return 0.0;
+				case KnownTypeCode.Decimal:
+					return 0m;
+				default:
+					return null;
+			}
+		}
+		#endregion
+		
+		#region ResolveArrayCreation
+		/// <summary>
+		/// Resolves an array creation.
+		/// </summary>
+		/// <param name="elementType">
+		/// The array element type.
+		/// Pass null to resolve an implicitly-typed array creation.
+		/// </param>
+		/// <param name="sizeArguments">
+		/// The size arguments.
+		/// The length of this array will be used as the number of dimensions of the array type.
+		/// Negative values will be treated as errors.
+		/// </param>
+		/// <param name="initializerElements">
+		/// The initializer elements. May be null if no array initializer was specified.
+		/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
+		/// </param>
+		public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, int[] sizeArguments, ResolveResult[] initializerElements = null)
+		{
+			ResolveResult[] sizeArgResults = new ResolveResult[sizeArguments.Length];
+			for (int i = 0; i < sizeArguments.Length; i++) {
+				if (sizeArguments[i] < 0)
+					sizeArgResults[i] = ErrorResolveResult.UnknownError;
+				else
+					sizeArgResults[i] = new ConstantResolveResult(compilation.FindType(KnownTypeCode.Int32), sizeArguments[i]);
+			}
+			return ResolveArrayCreation(elementType, sizeArgResults, initializerElements);
+		}
+		
+		/// <summary>
+		/// Resolves an array creation.
+		/// </summary>
+		/// <param name="elementType">
+		/// The array element type.
+		/// Pass null to resolve an implicitly-typed array creation.
+		/// </param>
+		/// <param name="sizeArguments">
+		/// The size arguments.
+		/// The length of this array will be used as the number of dimensions of the array type.
+		/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
+		/// </param>
+		/// <param name="initializerElements">
+		/// The initializer elements. May be null if no array initializer was specified.
+		/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
+		/// </param>
+		public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, ResolveResult[] sizeArguments, ResolveResult[] initializerElements = null)
+		{
+			int dimensions = sizeArguments.Length;
+			if (dimensions == 0)
+				throw new ArgumentException("sizeArguments.Length must not be 0");
+			if (elementType == null) {
+				TypeInference typeInference = new TypeInference(compilation, conversions);
+				bool success;
+				elementType = typeInference.GetBestCommonType(initializerElements, out success);
+			}
+			IType arrayType = new ArrayType(compilation, elementType, dimensions);
+			
+			AdjustArrayAccessArguments(sizeArguments);
+			
+			if (initializerElements != null) {
+				for (int i = 0; i < initializerElements.Length; i++) {
+					initializerElements[i] = Convert(initializerElements[i], elementType);
+				}
+			}
+			return new ArrayCreateResolveResult(arrayType, sizeArguments, initializerElements);
+		}
+		#endregion
+		
+		public ResolveResult ResolveTypeOf(IType referencedType)
+		{
+			return new TypeOfResolveResult(compilation.FindType(KnownTypeCode.Type), referencedType);
+		}
+		
+		#region ResolveAssignment
+		public ResolveResult ResolveAssignment(AssignmentOperatorType op, ResolveResult lhs, ResolveResult rhs)
+		{
+			var linqOp = AssignmentExpression.GetLinqNodeType(op, this.CheckForOverflow);
+			var bop = AssignmentExpression.GetCorrespondingBinaryOperator(op);
+			if (bop == null) {
+				return new OperatorResolveResult(lhs.Type, linqOp, lhs, this.Convert(rhs, lhs.Type));
+			}
+			ResolveResult bopResult = ResolveBinaryOperator(bop.Value, lhs, rhs);
+			OperatorResolveResult opResult = bopResult as OperatorResolveResult;
+			if (opResult == null || opResult.Operands.Count != 2)
+				return bopResult;
+			return new OperatorResolveResult(lhs.Type, linqOp, opResult.UserDefinedOperatorMethod, opResult.IsLiftedOperator,
+			                                 new [] { lhs, opResult.Operands[1] });
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CastResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CastResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CastResolveResult.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents an explicitly applied conversion (CastExpression or AsExpression)
+	/// (a result belonging to an AST node; not implicitly inserted 'between' nodes).
+	/// </summary>
+	class CastResolveResult : ConversionResolveResult
+	{
+		// The reason this class exists is that for code like this:
+		//    int i = ...;
+		//    long n = 0;
+		//    n = n + (long)i;
+		// The resolver will produce (and process) an CastResolveResult for the cast,
+		// (with Conversion = implicit numeric conversion)
+		// and then pass it into CSharpResolver.ResolveBinaryOperator().
+		// That method normally wraps input arguments into another conversion
+		// (the implicit conversion applied by the operator).
+		// However, identity conversions do not cause the creation of ConversionResolveResult instances,
+		// so the OperatorResolveResult's argument will be the CastResolveResult
+		// of the cast.
+		// Without this class (and instead using ConversionResolveResult for both purposes),
+		// it would be hard for the conversion-processing code
+		// in the ResolveVisitor to distinguish the existing conversion from the CastExpression
+		// from an implicit conversion introduced by the binary operator.
+		// This would cause the conversion to be processed yet again.
+		// The following unit tests would fail without this class:
+		//  * CastTests.ExplicitConversion_In_Assignment
+		//  * FindReferencesTest.FindReferencesForOpImplicitInAssignment_ExplicitCast
+		//  * CS0029InvalidConversionIssueTests.ExplicitConversionFromUnknownType
+		
+		public CastResolveResult(ConversionResolveResult rr)
+			: base(rr.Type, rr.Input, rr.Conversion, rr.CheckForOverflow)
+		{
+		}
+		
+		public CastResolveResult(IType targetType, ResolveResult input, Conversion conversion, bool checkForOverflow)
+			: base(targetType, input, conversion, checkForOverflow)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CompositeResolveVisitorNavigator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CompositeResolveVisitorNavigator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/CompositeResolveVisitorNavigator.cs	(revision 11807)
@@ -0,0 +1,67 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	public sealed class CompositeResolveVisitorNavigator : IResolveVisitorNavigator
+	{
+		IResolveVisitorNavigator[] navigators;
+		
+		public CompositeResolveVisitorNavigator(params IResolveVisitorNavigator[] navigators)
+		{
+			if (navigators == null)
+				throw new ArgumentNullException("navigators");
+			this.navigators = navigators;
+			foreach (var n in navigators) {
+				if (n == null)
+					throw new ArgumentException("Array must not contain nulls.");
+			}
+		}
+		
+		public ResolveVisitorNavigationMode Scan(AstNode node)
+		{
+			bool needsScan = false;
+			foreach (var navigator in navigators) {
+				ResolveVisitorNavigationMode mode = navigator.Scan(node);
+				if (mode == ResolveVisitorNavigationMode.Resolve)
+					return mode; // resolve has highest priority
+				else if (mode == ResolveVisitorNavigationMode.Scan)
+					needsScan = true;
+			}
+			return needsScan ? ResolveVisitorNavigationMode.Scan : ResolveVisitorNavigationMode.Skip;
+		}
+		
+		public void Resolved(AstNode node, ResolveResult result)
+		{
+			foreach (var navigator in navigators) {
+				navigator.Resolved(node, result);
+			}
+		}
+		
+		public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+		{
+			foreach (var navigator in navigators) {
+				navigator.ProcessConversion(expression, result, conversion, targetType);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DetectSkippableNodesNavigator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DetectSkippableNodesNavigator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DetectSkippableNodesNavigator.cs	(revision 11807)
@@ -0,0 +1,88 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// When an <see cref="IResolveVisitorNavigator"/> is searching for specific nodes
+	/// (e.g. all IdentifierExpressions), it has to scan the whole syntax tree for those nodes.
+	/// However, scanning in the ResolveVisitor is expensive (e.g. any lambda that is scanned must be resolved),
+	/// so it makes sense to detect when a whole subtree is scan-only, and skip that tree instead.
+	/// 
+	/// The DetectSkippableNodesNavigator performs this job by running the input IResolveVisitorNavigator
+	/// over the whole AST, and detecting subtrees that are scan-only, and replaces them with Skip.
+	/// </summary>
+	public sealed class DetectSkippableNodesNavigator : IResolveVisitorNavigator
+	{
+		readonly Dictionary<AstNode, ResolveVisitorNavigationMode> dict = new Dictionary<AstNode, ResolveVisitorNavigationMode>();
+		IResolveVisitorNavigator navigator;
+		
+		public DetectSkippableNodesNavigator(IResolveVisitorNavigator navigator, AstNode root)
+		{
+			this.navigator = navigator;
+			Init(root);
+		}
+		
+		bool Init(AstNode node)
+		{
+			var mode = navigator.Scan(node);
+			if (mode == ResolveVisitorNavigationMode.Skip)
+				return false;
+			
+			bool needsResolve = (mode != ResolveVisitorNavigationMode.Scan);
+			
+			for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
+				needsResolve |= Init(child);
+			}
+			
+			if (needsResolve) {
+				// If this node or any child node needs resolving, store the mode in the dictionary.
+				dict.Add(node, mode);
+			}
+			return needsResolve;
+		}
+		
+		/// <inheritdoc/>
+		public ResolveVisitorNavigationMode Scan(AstNode node)
+		{
+			ResolveVisitorNavigationMode mode;
+			if (dict.TryGetValue(node, out mode)) {
+				return mode;
+			} else {
+				return ResolveVisitorNavigationMode.Skip;
+			}
+		}
+		
+		/// <inheritdoc/>
+		public void Resolved(AstNode node, ResolveResult result)
+		{
+			navigator.Resolved(node, result);
+		}
+		
+		/// <inheritdoc/>
+		public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+		{
+			navigator.ProcessConversion(expression, result, conversion, targetType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DynamicInvocationResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DynamicInvocationResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DynamicInvocationResolveResult.cs	(revision 11807)
@@ -0,0 +1,86 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	public enum DynamicInvocationType {
+		/// <summary>
+		/// The invocation is a normal invocation ( 'a(b)' ).
+		/// </summary>
+		Invocation,
+
+		/// <summary>
+		/// The invocation is an indexing ( 'a[b]' ).
+		/// </summary>
+		Indexing,
+
+		/// <summary>
+		/// The invocation is an object creation ( 'new a(b)' ). Also used when invoking a base constructor ( ' : base(a) ' ) and chaining constructors ( ' : this(a) ').
+		/// </summary>
+		ObjectCreation,
+	}
+
+	/// <summary>
+	/// Represents the result of an invocation of a member of a dynamic object.
+	/// </summary>
+	public class DynamicInvocationResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// Target of the invocation. Can be a dynamic expression or a <see cref="MethodGroupResolveResult"/>.
+		/// </summary>
+		public readonly ResolveResult Target;
+
+		/// <summary>
+		/// Type of the invocation.
+		/// </summary>
+		public readonly DynamicInvocationType InvocationType;
+
+		/// <summary>
+		/// Arguments for the call. Named arguments will be instances of <see cref="NamedArgumentResolveResult"/>.
+		/// </summary>
+		public readonly IList<ResolveResult> Arguments; 
+
+		/// <summary>
+		/// Gets the list of initializer statements that are appplied to the result of this invocation.
+		/// This is used to represent object and collection initializers.
+		/// With the initializer statements, the <see cref="InitializedObjectResolveResult"/> is used
+		/// to refer to the result of this invocation.
+		/// Initializer statements can only exist if the <see cref="InvocationType"/> is <see cref="DynamicInvocationType.ObjectCreation"/>.
+		/// </summary>
+		public readonly IList<ResolveResult> InitializerStatements;
+
+		public DynamicInvocationResolveResult(ResolveResult target, DynamicInvocationType invocationType, IList<ResolveResult> arguments, IList<ResolveResult> initializerStatements = null) : base(SpecialType.Dynamic) {
+			this.Target                = target;
+			this.InvocationType        = invocationType;
+			this.Arguments             = arguments ?? EmptyList<ResolveResult>.Instance;
+			this.InitializerStatements = initializerStatements ?? EmptyList<ResolveResult>.Instance;
+		}
+
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[Dynamic invocation ]");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DynamicMemberResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DynamicMemberResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/DynamicMemberResolveResult.cs	(revision 11807)
@@ -0,0 +1,57 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents the result of an access to a member of a dynamic object.
+	/// </summary>
+	public class DynamicMemberResolveResult : ResolveResult
+	{
+		/// <summary>
+		/// Target of the member access (a dynamic object).
+		/// </summary>
+		public readonly ResolveResult Target;
+
+		/// <summary>
+		/// Name of the accessed member.
+		/// </summary>
+		public readonly string Member;
+
+		public DynamicMemberResolveResult(ResolveResult target, string member) : base(SpecialType.Dynamic) {
+			this.Target = target;
+			this.Member = member;
+		}
+
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[Dynamic member '{0}']", Member);
+		}
+
+		public override IEnumerable<ResolveResult> GetChildResults() {
+			return new[] { Target };
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferenceSearchScope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferenceSearchScope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferenceSearchScope.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents a scope in which references are searched.
+	/// </summary>
+	public interface IFindReferenceSearchScope
+	{
+		/// <summary>
+		/// Gets the compilation in which the entity being search for was defined.
+		/// This is not necessarily the same compilation as is being searched in.
+		/// </summary>
+		ICompilation Compilation { get; }
+		
+		/// <summary>
+		/// Gets the search term. Only files that contain this identifier need to be parsed.
+		/// Can return null if all files need to be parsed.
+		/// </summary>
+		string SearchTerm { get; }
+		
+		/// <summary>
+		/// Gets the accessibility that defines the search scope.
+		/// </summary>
+		Accessibility Accessibility { get; }
+		
+		/// <summary>
+		/// Gets the top-level entity that defines the search scope.
+		/// </summary>
+		ITypeDefinition TopLevelTypeDefinition { get; }
+		
+		/// <summary>
+		/// Gets the file name that defines the search scope.
+		/// If null, all files are searched.
+		/// </summary>
+		string FileName { get; }
+		
+		/// <summary>
+		/// Creates a navigator that can find references to this entity and reports
+		/// them to the specified callback.
+		/// </summary>
+		IResolveVisitorNavigator GetNavigator(ICompilation compilation, FoundReferenceCallback callback);
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferencedEntities.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferencedEntities.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferencedEntities.cs	(revision 11807)
@@ -0,0 +1,100 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Find all entities that are referenced in the scanned AST.
+	/// </summary>
+	public sealed class FindReferencedEntities : IResolveVisitorNavigator
+	{
+		readonly Action<AstNode, IMember> memberReferenceFound;
+		readonly Action<AstNode, IType> typeReferenceFound;
+		
+		/// <summary>
+		/// Creates a new FindReferencedEntities instance that
+		/// looks for entity definitions.
+		/// The visitor will report type definitions and member definitions (not specialized members).
+		/// </summary>
+		public FindReferencedEntities(Action<AstNode, IEntity> referenceFound)
+		{
+			if (referenceFound == null)
+				throw new ArgumentNullException("referenceFound");
+			this.memberReferenceFound = (node, member) => referenceFound(node, member.MemberDefinition);
+			this.typeReferenceFound = (node, type) => {
+				var def = type.GetDefinition();
+				if (def != null)
+					referenceFound(node, def);
+			};
+		}
+		
+		/// <summary>
+		/// Creates a new FindReferencedEntities instance that
+		/// looks for types and members.
+		/// The visitor will report parameterized types and potentially specialized members.
+		/// </summary>
+		public FindReferencedEntities(Action<AstNode, IType> typeReferenceFound, Action<AstNode, IMember> memberReferenceFound)
+		{
+			if (typeReferenceFound == null)
+				throw new ArgumentNullException("typeReferenceFound");
+			if (memberReferenceFound == null)
+				throw new ArgumentNullException("memberReferenceFound");
+			this.typeReferenceFound = typeReferenceFound;
+			this.memberReferenceFound = memberReferenceFound;
+		}
+		
+		public ResolveVisitorNavigationMode Scan(AstNode node)
+		{
+			return ResolveVisitorNavigationMode.Resolve;
+		}
+		
+		public void Resolved(AstNode node, ResolveResult result)
+		{
+			if (ParenthesizedExpression.ActsAsParenthesizedExpression(node))
+				return;
+			
+			MemberResolveResult mrr = result as MemberResolveResult;
+			if (mrr != null) {
+				memberReferenceFound(node, mrr.Member);
+			}
+			TypeResolveResult trr = result as TypeResolveResult;
+			if (trr != null) {
+				typeReferenceFound(node, trr.Type);
+			}
+			ForEachResolveResult ferr = result as ForEachResolveResult;
+			if (ferr != null) {
+				Resolved(node, ferr.GetEnumeratorCall);
+				if (ferr.CurrentProperty != null)
+					memberReferenceFound(node, ferr.CurrentProperty);
+				if (ferr.MoveNextMethod != null)
+					memberReferenceFound(node, ferr.MoveNextMethod);
+			}
+		}
+		
+		public void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+		{
+			if (conversion.IsUserDefined || conversion.IsMethodGroupConversion) {
+				memberReferenceFound(expression, conversion.Method);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferences.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferences.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/FindReferences.cs	(revision 11807)
@@ -0,0 +1,1611 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp;
+using ICSharpCode.NRefactory.CSharp.Refactoring;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	public delegate void FoundReferenceCallback(AstNode astNode, ResolveResult result);
+	
+	/// <summary>
+	/// 'Find references' implementation.
+	/// </summary>
+	/// <remarks>
+	/// This class is thread-safe.
+	/// The intended multi-threaded usage is to call GetSearchScopes() once, and then
+	/// call FindReferencesInFile() concurrently on multiple threads (parallel foreach over all interesting files).
+	/// </remarks>
+	public sealed class FindReferences
+	{
+		#region Properties
+		/// <summary>
+		/// Specifies whether to find type references even if an alias is being used.
+		/// Aliases may be <c>var</c> or <c>using Alias = ...;</c>.
+		/// </summary>
+		public bool FindTypeReferencesEvenIfAliased { get; set; }
+		
+		/// <summary>
+		/// Specifies whether find references should only look for specialized matches
+		/// with equal type parameter substitution to the member we are searching for.
+		/// </summary>
+		public bool FindOnlySpecializedReferences { get; set; }
+		
+		/// <summary>
+		/// If this option is enabled, find references on a overridden member
+		/// will find calls to the base member.
+		/// </summary>
+		public bool FindCallsThroughVirtualBaseMethod { get; set; }
+		
+		/// <summary>
+		/// If this option is enabled, find references on a member implementing
+		/// an interface will also find calls to the interface.
+		/// </summary>
+		public bool FindCallsThroughInterface { get; set; }
+		
+		/// <summary>
+		/// If this option is enabled, find references will look for all references
+		/// to the virtual method slot.
+		/// </summary>
+		public bool WholeVirtualSlot { get; set; }
+		
+		//public bool FindAllOverloads { get; set; }
+		
+		/// <summary>
+		/// Specifies whether to look for references in documentation comments.
+		/// This will find entity references in <c>cref</c> attributes and
+		/// parameter references in <c>&lt;param&gt;</c> and <c>&lt;paramref&gt;</c> tags.
+		/// TODO: implement this feature.
+		/// </summary>
+		public bool SearchInDocumentationComments { get; set; }
+		#endregion
+		
+		#region GetEffectiveAccessibility
+		/// <summary>
+		/// Gets the effective accessibility of the specified entity -
+		/// that is, the accessibility viewed from the top level.
+		/// </summary>
+		/// <remarks>
+		/// internal member in public class -> internal
+		/// public member in internal class -> internal
+		/// protected member in public class -> protected
+		/// protected member in internal class -> protected and internal
+		/// </remarks>
+		public static Accessibility GetEffectiveAccessibility(IEntity entity)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			Accessibility a = entity.Accessibility;
+			for (ITypeDefinition declType = entity.DeclaringTypeDefinition; declType != null; declType = declType.DeclaringTypeDefinition) {
+				a = MergeAccessibility(declType.Accessibility, a);
+			}
+			return a;
+		}
+		
+		static Accessibility MergeAccessibility(Accessibility outer, Accessibility inner)
+		{
+			if (outer == inner)
+				return inner;
+			if (outer == Accessibility.None || inner == Accessibility.None)
+				return Accessibility.None;
+			if (outer == Accessibility.Private || inner == Accessibility.Private)
+				return Accessibility.Private;
+			if (outer == Accessibility.Public)
+				return inner;
+			if (inner == Accessibility.Public)
+				return outer;
+			// Inner and outer are both in { protected, internal, protected and internal, protected or internal }
+			// (but they aren't both the same)
+			if (outer == Accessibility.ProtectedOrInternal)
+				return inner;
+			if (inner == Accessibility.ProtectedOrInternal)
+				return outer;
+			// Inner and outer are both in { protected, internal, protected and internal },
+			// but aren't both the same, so the result is protected and internal.
+			return Accessibility.ProtectedAndInternal;
+		}
+		#endregion
+		
+		#region class SearchScope
+		sealed class SearchScope : IFindReferenceSearchScope
+		{
+			readonly Func<ICompilation, FindReferenceNavigator> factory;
+			
+			public SearchScope(Func<ICompilation, FindReferenceNavigator> factory)
+			{
+				this.factory = factory;
+			}
+			
+			public SearchScope(string searchTerm, Func<ICompilation, FindReferenceNavigator> factory)
+			{
+				this.searchTerm = searchTerm;
+				this.factory = factory;
+			}
+			
+			internal string searchTerm;
+			internal FindReferences findReferences;
+			internal ICompilation declarationCompilation;
+			internal Accessibility accessibility;
+			internal ITypeDefinition topLevelTypeDefinition;
+			internal string fileName;
+			
+			IResolveVisitorNavigator IFindReferenceSearchScope.GetNavigator(ICompilation compilation, FoundReferenceCallback callback)
+			{
+				FindReferenceNavigator n = factory(compilation);
+				if (n != null) {
+					n.callback = callback;
+					n.findReferences = findReferences;
+					return n;
+				} else {
+					return new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Skip, null);
+				}
+			}
+			
+			ICompilation IFindReferenceSearchScope.Compilation {
+				get { return declarationCompilation; }
+			}
+			
+			string IFindReferenceSearchScope.SearchTerm {
+				get { return searchTerm; }
+			}
+			
+			Accessibility IFindReferenceSearchScope.Accessibility {
+				get { return accessibility; }
+			}
+			
+			ITypeDefinition IFindReferenceSearchScope.TopLevelTypeDefinition {
+				get { return topLevelTypeDefinition; }
+			}
+			
+			string IFindReferenceSearchScope.FileName {
+				get { return fileName; }
+			}
+		}
+		
+		abstract class FindReferenceNavigator : IResolveVisitorNavigator
+		{
+			internal FoundReferenceCallback callback;
+			internal FindReferences findReferences;
+			
+			internal abstract bool CanMatch(AstNode node);
+			internal abstract bool IsMatch(ResolveResult rr);
+			
+			ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
+			{
+				if (CanMatch(node))
+					return ResolveVisitorNavigationMode.Resolve;
+				else
+					return ResolveVisitorNavigationMode.Scan;
+			}
+			
+			void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
+			{
+				if (CanMatch(node) && IsMatch(result)) {
+					ReportMatch(node, result);
+				}
+			}
+			
+			public virtual void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+			{
+			}
+			
+			protected void ReportMatch(AstNode node, ResolveResult result)
+			{
+				if (callback != null)
+					callback(node, result);
+			}
+			
+			internal virtual void NavigatorDone(CSharpAstResolver resolver, CancellationToken cancellationToken)
+			{
+			}
+		}
+		#endregion
+		
+		#region GetSearchScopes
+		public IList<IFindReferenceSearchScope> GetSearchScopes(ISymbol symbol)
+		{
+			if (symbol == null)
+				throw new ArgumentNullException("symbol");
+			switch (symbol.SymbolKind) {
+				case SymbolKind.Namespace:
+					return new[] { GetSearchScopeForNamespace((INamespace)symbol) };
+				case SymbolKind.TypeParameter:
+					return new[] { GetSearchScopeForTypeParameter((ITypeParameter)symbol) };
+			}
+			SearchScope scope;
+			SearchScope additionalScope = null;
+			IEntity entity = null;
+
+			if (symbol.SymbolKind == SymbolKind.Variable) {
+				var variable = (IVariable) symbol;
+				scope = GetSearchScopeForLocalVariable(variable);
+			} else if (symbol.SymbolKind == SymbolKind.Parameter) {
+				var par = (IParameter)symbol;
+				scope = GetSearchScopeForParameter(par);
+				entity = par.Owner;
+			} else {
+				entity = symbol as IEntity;
+				if (entity == null)
+					throw new NotSupportedException("Unsupported symbol type");
+				if (entity is IMember)
+					entity = NormalizeMember((IMember)entity);
+				switch (entity.SymbolKind) {
+					case SymbolKind.TypeDefinition:
+						scope = FindTypeDefinitionReferences((ITypeDefinition)entity, this.FindTypeReferencesEvenIfAliased, out additionalScope);
+						break;
+					case SymbolKind.Field:
+						if (entity.DeclaringTypeDefinition != null && entity.DeclaringTypeDefinition.Kind == TypeKind.Enum)
+							scope = FindMemberReferences(entity, m => new FindEnumMemberReferences((IField)m));
+						else
+							scope = FindMemberReferences(entity, m => new FindFieldReferences((IField)m));
+						break;
+					case SymbolKind.Property:
+						scope = FindMemberReferences(entity, m => new FindPropertyReferences((IProperty)m));
+						if (entity.Name == "Current")
+							additionalScope = FindEnumeratorCurrentReferences((IProperty)entity);
+						else if (entity.Name == "IsCompleted")
+							additionalScope = FindAwaiterIsCompletedReferences((IProperty)entity);
+						break;
+					case SymbolKind.Event:
+						scope = FindMemberReferences(entity, m => new FindEventReferences((IEvent)m));
+						break;
+					case SymbolKind.Method:
+						scope = GetSearchScopeForMethod((IMethod)entity);
+						break;
+					case SymbolKind.Indexer:
+						scope = FindIndexerReferences((IProperty)entity);
+						break;
+					case SymbolKind.Operator:
+						scope = GetSearchScopeForOperator((IMethod)entity);
+						break;
+					case SymbolKind.Constructor:
+						IMethod ctor = (IMethod)entity;
+						scope = FindObjectCreateReferences(ctor);
+						additionalScope = FindChainedConstructorReferences(ctor);
+						break;
+					case SymbolKind.Destructor:
+						scope = GetSearchScopeForDestructor((IMethod)entity);
+						break;
+					default:
+						throw new ArgumentException("Unknown entity type " + entity.SymbolKind);
+				}
+			}
+			var effectiveAccessibility = entity != null ? GetEffectiveAccessibility(entity) : Accessibility.Private;
+			var topLevelTypeDefinition = GetTopLevelTypeDefinition(entity);
+
+			if (scope.accessibility == Accessibility.None)
+				scope.accessibility = effectiveAccessibility;
+			scope.declarationCompilation = entity != null ? entity.Compilation : null;
+			scope.topLevelTypeDefinition = topLevelTypeDefinition;
+			scope.findReferences = this;
+			if (additionalScope != null) {
+				if (additionalScope.accessibility == Accessibility.None)
+					additionalScope.accessibility = effectiveAccessibility;
+				additionalScope.declarationCompilation = scope.declarationCompilation;
+				additionalScope.topLevelTypeDefinition = topLevelTypeDefinition;
+				additionalScope.findReferences = this;
+				return new[] { scope, additionalScope };
+			} else {
+				return new[] { scope };
+			}
+		}
+
+		public IList<IFindReferenceSearchScope> GetSearchScopes(IEnumerable<ISymbol> symbols)
+		{
+			if (symbols == null)
+				throw new ArgumentNullException("symbols");
+			return symbols.SelectMany(GetSearchScopes).ToList();
+		}
+		
+		static ITypeDefinition GetTopLevelTypeDefinition(IEntity entity)
+		{
+			if (entity == null)
+				return null;
+			ITypeDefinition topLevelTypeDefinition = entity.DeclaringTypeDefinition;
+			while (topLevelTypeDefinition != null && topLevelTypeDefinition.DeclaringTypeDefinition != null)
+				topLevelTypeDefinition = topLevelTypeDefinition.DeclaringTypeDefinition;
+			return topLevelTypeDefinition;
+		}
+		#endregion
+		
+		#region GetInterestingFileNames
+		/// <summary>
+		/// Gets the file names that possibly contain references to the element being searched for.
+		/// </summary>
+		public IEnumerable<CSharpUnresolvedFile> GetInterestingFiles(IFindReferenceSearchScope searchScope, ICompilation compilation)
+		{
+			if (searchScope == null)
+				throw new ArgumentNullException("searchScope");
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			var pc = compilation.MainAssembly.UnresolvedAssembly as IProjectContent;
+			if (pc == null)
+				throw new ArgumentException("Main assembly is not a project content");
+			if (searchScope.TopLevelTypeDefinition != null) {
+				ITypeDefinition topLevelTypeDef = compilation.Import(searchScope.TopLevelTypeDefinition);
+				if (topLevelTypeDef == null) {
+					// This compilation cannot have references to the target entity.
+					return EmptyList<CSharpUnresolvedFile>.Instance;
+				}
+				switch (searchScope.Accessibility) {
+					case Accessibility.None:
+					case Accessibility.Private:
+						if (topLevelTypeDef.ParentAssembly == compilation.MainAssembly)
+							return topLevelTypeDef.Parts.Select(p => p.UnresolvedFile).OfType<CSharpUnresolvedFile>().Distinct();
+						else
+							return EmptyList<CSharpUnresolvedFile>.Instance;
+					case Accessibility.Protected:
+						return GetInterestingFilesProtected(topLevelTypeDef);
+					case Accessibility.Internal:
+						if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
+							return pc.Files.OfType<CSharpUnresolvedFile>();
+						else
+							return EmptyList<CSharpUnresolvedFile>.Instance;
+					case Accessibility.ProtectedAndInternal:
+						if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
+							return GetInterestingFilesProtected(topLevelTypeDef);
+						else
+							return EmptyList<CSharpUnresolvedFile>.Instance;
+					case Accessibility.ProtectedOrInternal:
+						if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
+							return pc.Files.OfType<CSharpUnresolvedFile>();
+						else
+							return GetInterestingFilesProtected(topLevelTypeDef);
+					default:
+						return pc.Files.OfType<CSharpUnresolvedFile>();
+				}
+			} else {
+				if (searchScope.FileName == null)
+					return pc.Files.OfType<CSharpUnresolvedFile>();
+				else
+					return pc.Files.OfType<CSharpUnresolvedFile>().Where(f => f.FileName == searchScope.FileName);
+			}
+		}
+		
+		IEnumerable<CSharpUnresolvedFile> GetInterestingFilesProtected(ITypeDefinition referencedTypeDefinition)
+		{
+			return (from typeDef in referencedTypeDefinition.Compilation.MainAssembly.GetAllTypeDefinitions()
+			        where typeDef.IsDerivedFrom(referencedTypeDefinition)
+			        from part in typeDef.Parts
+			        select part.UnresolvedFile
+			       ).OfType<CSharpUnresolvedFile>().Distinct();
+		}
+		#endregion
+		
+		#region FindReferencesInFile
+		/// <summary>
+		/// Finds all references in the given file.
+		/// </summary>
+		/// <param name="searchScope">The search scope for which to look.</param>
+		/// <param name="resolver">AST resolver for the file to search in.</param>
+		/// <param name="callback">Callback used to report the references that were found.</param>
+		/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
+		public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpAstResolver resolver,
+		                                 FoundReferenceCallback callback, CancellationToken cancellationToken)
+		{
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			FindReferencesInFile(searchScope, resolver.UnresolvedFile, (SyntaxTree)resolver.RootNode, resolver.Compilation, callback, cancellationToken);
+		}
+		
+		/// <summary>
+		/// Finds all references in the given file.
+		/// </summary>
+		/// <param name="searchScopes">The search scopes for which to look.</param>
+		/// <param name="resolver">AST resolver for the file to search in.</param>
+		/// <param name="callback">Callback used to report the references that were found.</param>
+		/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
+		public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpAstResolver resolver,
+		                                 FoundReferenceCallback callback, CancellationToken cancellationToken)
+		{
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			FindReferencesInFile(searchScopes, resolver.UnresolvedFile, (SyntaxTree)resolver.RootNode, resolver.Compilation, callback, cancellationToken);
+		}
+		
+		/// <summary>
+		/// Finds all references in the given file.
+		/// </summary>
+		/// <param name="searchScope">The search scope for which to look.</param>
+		/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
+		/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
+		/// <param name="compilation">The compilation for the project that contains the file.</param>
+		/// <param name="callback">Callback used to report the references that were found.</param>
+		/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
+		public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
+		                                 ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
+		{
+			if (searchScope == null)
+				throw new ArgumentNullException("searchScope");
+			FindReferencesInFile(new[] { searchScope }, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
+		}
+		
+		/// <summary>
+		/// Finds all references in the given file.
+		/// </summary>
+		/// <param name="searchScopes">The search scopes for which to look.</param>
+		/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
+		/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
+		/// <param name="compilation">The compilation for the project that contains the file.</param>
+		/// <param name="callback">Callback used to report the references that were found.</param>
+		/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
+		public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
+		                                 ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
+		{
+			if (searchScopes == null)
+				throw new ArgumentNullException("searchScopes");
+			if (syntaxTree == null)
+				throw new ArgumentNullException("syntaxTree");
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (callback == null)
+				throw new ArgumentNullException("callback");
+			
+			if (searchScopes.Count == 0)
+				return;
+			var navigators = new IResolveVisitorNavigator[searchScopes.Count];
+			for (int i = 0; i < navigators.Length; i++) {
+				navigators[i] = searchScopes[i].GetNavigator(compilation, callback);
+			}
+			IResolveVisitorNavigator combinedNavigator;
+			if (searchScopes.Count == 1) {
+				combinedNavigator = navigators[0];
+			} else {
+				combinedNavigator = new CompositeResolveVisitorNavigator(navigators);
+			}
+			
+			cancellationToken.ThrowIfCancellationRequested();
+			combinedNavigator = new DetectSkippableNodesNavigator(combinedNavigator, syntaxTree);
+			cancellationToken.ThrowIfCancellationRequested();
+			CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
+			resolver.ApplyNavigator(combinedNavigator, cancellationToken);
+			foreach (var n in navigators) {
+				var frn = n as FindReferenceNavigator;
+				if (frn != null)
+					frn.NavigatorDone(resolver, cancellationToken);
+			}
+		}
+		#endregion
+		
+		#region RenameReferencesInFile
+
+		public static AstNode GetNodeToReplace(AstNode node)
+		{
+			if (node is ConstructorInitializer)
+				return null;
+			if (node is ObjectCreateExpression)
+				node = ((ObjectCreateExpression)node).Type;
+
+			if (node is InvocationExpression)
+				node = ((InvocationExpression)node).Target;
+
+			if (node is MemberReferenceExpression)
+				node = ((MemberReferenceExpression)node).MemberNameToken;
+
+			if (node is SimpleType)
+				node = ((SimpleType)node).IdentifierToken;
+
+			if (node is MemberType)
+				node = ((MemberType)node).MemberNameToken;
+
+			if (node is NamespaceDeclaration) {
+//				var nsd = ((NamespaceDeclaration)node);
+//				node = nsd.Identifiers.LastOrDefault (n => n.Name == memberName) ?? nsd.Identifiers.FirstOrDefault ();
+//				if (node == null)
+				return null;
+			}
+
+			if (node is TypeDeclaration)
+				node = ((TypeDeclaration)node).NameToken;
+			if (node is DelegateDeclaration)
+				node = ((DelegateDeclaration)node).NameToken;
+
+			if (node is EntityDeclaration)
+				node = ((EntityDeclaration)node).NameToken;
+
+			if (node is ParameterDeclaration)
+				node = ((ParameterDeclaration)node).NameToken;
+			if (node is ConstructorDeclaration)
+				node = ((ConstructorDeclaration)node).NameToken;
+			if (node is DestructorDeclaration)
+				node = ((DestructorDeclaration)node).NameToken;
+			if (node is NamedArgumentExpression)
+				node = ((NamedArgumentExpression)node).NameToken;
+			if (node is NamedExpression)
+				node = ((NamedExpression)node).NameToken;
+			if (node is VariableInitializer)
+				node = ((VariableInitializer)node).NameToken;
+
+			if (node is IdentifierExpression) {
+				node = ((IdentifierExpression)node).IdentifierToken;
+			}
+			return node;
+		}
+
+		public void RenameReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, string newName, CSharpAstResolver resolver,
+		                                   Action<RenameCallbackArguments> callback, Action<Error> errorCallback, CancellationToken cancellationToken = default (CancellationToken))
+		{
+			FindReferencesInFile(
+				searchScopes,
+				resolver,
+				delegate(AstNode astNode, ResolveResult result) {
+					var nodeToReplace = GetNodeToReplace(astNode);
+					if (nodeToReplace == null) {
+						errorCallback (new Error (ErrorType.Error, "no node to replace found."));
+						return;
+					}
+					callback (new RenameCallbackArguments(nodeToReplace, Identifier.Create(newName)));
+				},
+				cancellationToken);
+		}
+		#endregion
+		
+		#region Find TypeDefinition References
+		SearchScope FindTypeDefinitionReferences(ITypeDefinition typeDefinition, bool findTypeReferencesEvenIfAliased, out SearchScope additionalScope)
+		{
+			string searchTerm = null;
+			additionalScope = null;
+			if (!findTypeReferencesEvenIfAliased && KnownTypeReference.GetCSharpNameByTypeCode(typeDefinition.KnownTypeCode) == null) {
+				// We can optimize the search by looking only for the type references with the right identifier,
+				// but only if it's not a primitive type and we're not looking for indirect references (through an alias)
+				searchTerm = typeDefinition.Name;
+				if (searchTerm.Length > 9 && searchTerm.EndsWith("Attribute", StringComparison.Ordinal)) {
+					// The type might be an attribute, so we also need to look for the short form:
+					string shortForm = searchTerm.Substring(0, searchTerm.Length - 9);
+					additionalScope = FindTypeDefinitionReferences(typeDefinition, shortForm);
+				}
+			}
+			return FindTypeDefinitionReferences(typeDefinition, searchTerm);
+		}
+		
+		SearchScope FindTypeDefinitionReferences(ITypeDefinition typeDefinition, string searchTerm)
+		{
+			return new SearchScope(
+				searchTerm,
+				delegate (ICompilation compilation) {
+					ITypeDefinition imported = compilation.Import(typeDefinition);
+					if (imported != null)
+						return new FindTypeDefinitionReferencesNavigator(imported, searchTerm);
+					else
+						return null;
+				});
+		}
+		
+		sealed class FindTypeDefinitionReferencesNavigator : FindReferenceNavigator
+		{
+			readonly ITypeDefinition typeDefinition;
+			readonly string searchTerm;
+			
+			public FindTypeDefinitionReferencesNavigator(ITypeDefinition typeDefinition, string searchTerm)
+			{
+				this.typeDefinition = typeDefinition;
+				this.searchTerm = searchTerm;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				IdentifierExpression ident = node as IdentifierExpression;
+				if (ident != null)
+					return searchTerm == null || ident.Identifier == searchTerm;
+				
+				MemberReferenceExpression mre = node as MemberReferenceExpression;
+				if (mre != null)
+					return searchTerm == null || mre.MemberName == searchTerm;
+				
+				SimpleType st = node as SimpleType;
+				if (st != null)
+					return searchTerm == null || st.Identifier == searchTerm;
+				
+				MemberType mt = node as MemberType;
+				if (mt != null)
+					return searchTerm == null || mt.MemberName == searchTerm;
+				
+				if (searchTerm == null && node is PrimitiveType)
+					return true;
+				
+				TypeDeclaration typeDecl = node as TypeDeclaration;
+				if (typeDecl != null)
+					return searchTerm == null || typeDecl.Name == searchTerm;
+				
+				DelegateDeclaration delegateDecl = node as DelegateDeclaration;
+				if (delegateDecl != null)
+					return searchTerm == null || delegateDecl.Name == searchTerm;
+				
+				return false;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				TypeResolveResult trr = rr as TypeResolveResult;
+				return trr != null && typeDefinition.Equals(trr.Type.GetDefinition());
+			}
+		}
+		#endregion
+		
+		#region Find Member References
+		SearchScope FindMemberReferences(IEntity member, Func<IMember, FindMemberReferencesNavigator> factory)
+		{
+			string searchTerm = member.Name;
+			return new SearchScope(
+				searchTerm,
+				delegate(ICompilation compilation) {
+					IMember imported = compilation.Import((IMember)member);
+					return imported != null ? factory(imported) : null;
+				});
+		}
+		
+		class FindMemberReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IMember member;
+			readonly string searchTerm;
+			
+			public FindMemberReferencesNavigator(IMember member)
+			{
+				this.member = member;
+				this.searchTerm = member.Name;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				IdentifierExpression ident = node as IdentifierExpression;
+				if (ident != null)
+					return ident.Identifier == searchTerm;
+				
+				MemberReferenceExpression mre = node as MemberReferenceExpression;
+				if (mre != null)
+					return mre.MemberName == searchTerm;
+				
+				PointerReferenceExpression pre = node as PointerReferenceExpression;
+				if (pre != null)
+					return pre.MemberName == searchTerm;
+				
+				NamedExpression ne = node as NamedExpression;
+				if (ne != null)
+					return ne.Name == searchTerm;
+				
+				return false;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(member, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		
+		IMember NormalizeMember(IMember member)
+		{
+			if (WholeVirtualSlot && member.IsOverride)
+				member = InheritanceHelper.GetBaseMembers(member, false).FirstOrDefault(m => !m.IsOverride) ?? member;
+			if (!FindOnlySpecializedReferences)
+				member = member.MemberDefinition;
+			return member;
+		}
+		
+		bool IsMemberMatch(IMember member, IMember referencedMember, bool isVirtualCall)
+		{
+			referencedMember = NormalizeMember(referencedMember);
+			if (member.Equals(referencedMember))
+				return true;
+			if (FindCallsThroughInterface && member.DeclaringTypeDefinition != null && member.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
+				if (FindOnlySpecializedReferences) {
+					return referencedMember.ImplementedInterfaceMembers.Contains(member);
+				} else {
+					return referencedMember.ImplementedInterfaceMembers.Any(m => m.MemberDefinition.Equals(member));
+				}
+			}
+			if (!isVirtualCall)
+				return false;
+			bool isInterfaceCall = referencedMember.DeclaringTypeDefinition != null && referencedMember.DeclaringTypeDefinition.Kind == TypeKind.Interface;
+			if (FindCallsThroughVirtualBaseMethod && member.IsOverride && !WholeVirtualSlot && !isInterfaceCall) {
+				// Test if 'member' overrides 'referencedMember':
+				foreach (var baseMember in InheritanceHelper.GetBaseMembers(member, false)) {
+					if (FindOnlySpecializedReferences) {
+						if (baseMember.Equals(referencedMember))
+							return true;
+					} else {
+						if (baseMember.MemberDefinition.Equals(referencedMember))
+							return true;
+					}
+					if (!baseMember.IsOverride)
+						break;
+				}
+				return false;
+			} else if (FindCallsThroughInterface && isInterfaceCall) {
+				// Test if 'member' implements 'referencedMember':
+				if (FindOnlySpecializedReferences) {
+					return member.ImplementedInterfaceMembers.Contains(referencedMember);
+				} else {
+					return member.ImplementedInterfaceMembers.Any(m => m.MemberDefinition.Equals(referencedMember));
+				}
+			}
+			return false;
+		}
+		
+		/*
+		bool PerformVirtualLookup(IMember member, IMember referencedMember)
+		{
+			if (FindCallsThroughVirtualBaseMethod && member.IsOverride && !WholeVirtualSlot)
+				return true;
+			var typeDef = referencedMember.DeclaringTypeDefinition;
+			return FindCallsThroughInterface && typeDef != null && typeDef.Kind == TypeKind.Interface;
+		}*/
+		
+		sealed class FindFieldReferences : FindMemberReferencesNavigator
+		{
+			public FindFieldReferences(IField field) : base(field)
+			{
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				if (node is VariableInitializer) {
+					return node.Parent is FieldDeclaration;
+				}
+				return base.CanMatch(node);
+			}
+		}
+		
+		sealed class FindEnumMemberReferences : FindMemberReferencesNavigator
+		{
+			public FindEnumMemberReferences(IField field) : base(field)
+			{
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is EnumMemberDeclaration || base.CanMatch(node);
+			}
+		}
+		
+		sealed class FindPropertyReferences : FindMemberReferencesNavigator
+		{
+			public FindPropertyReferences(IProperty property) : base(property)
+			{
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is PropertyDeclaration || base.CanMatch(node);
+			}
+		}
+		
+		sealed class FindEventReferences : FindMemberReferencesNavigator
+		{
+			public FindEventReferences(IEvent ev) : base(ev)
+			{
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				if (node is VariableInitializer) {
+					return node.Parent is EventDeclaration;
+				}
+				return node is CustomEventDeclaration || base.CanMatch(node);
+			}
+		}
+		#endregion
+		
+		#region Find References to IEnumerator.Current
+		SearchScope FindEnumeratorCurrentReferences(IProperty property)
+		{
+			return new SearchScope(
+				delegate(ICompilation compilation) {
+					IProperty imported = compilation.Import(property);
+					return imported != null ? new FindEnumeratorCurrentReferencesNavigator(imported) : null;
+				});
+		}
+
+		SearchScope FindAwaiterIsCompletedReferences(IProperty property)
+		{
+			return new SearchScope(
+				delegate(ICompilation compilation) {
+					IProperty imported = compilation.Import(property);
+					return imported != null ? new FindAwaiterIsCompletedReferencesNavigator(imported) : null;
+				});
+		}
+		
+		sealed class FindEnumeratorCurrentReferencesNavigator : FindReferenceNavigator
+		{
+			IProperty property;
+			
+			public FindEnumeratorCurrentReferencesNavigator(IProperty property)
+			{
+				this.property = property;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is ForeachStatement;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				ForEachResolveResult ferr = rr as ForEachResolveResult;
+				return ferr != null && ferr.CurrentProperty != null && findReferences.IsMemberMatch(property, ferr.CurrentProperty, true);
+			}
+		}
+
+		sealed class FindAwaiterIsCompletedReferencesNavigator : FindReferenceNavigator
+		{
+			IProperty property;
+			
+			public FindAwaiterIsCompletedReferencesNavigator(IProperty property)
+			{
+				this.property = property;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is UnaryOperatorExpression;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				AwaitResolveResult arr = rr as AwaitResolveResult;
+				return arr != null && arr.IsCompletedProperty != null && findReferences.IsMemberMatch(property, arr.IsCompletedProperty, true);
+			}
+		}
+		#endregion
+		
+		#region Find Method References
+		SearchScope GetSearchScopeForMethod(IMethod method)
+		{
+			Type specialNodeType;
+			switch (method.Name) {
+				case "Add":
+					specialNodeType = typeof(ArrayInitializerExpression);
+					break;
+				case "Where":
+					specialNodeType = typeof(QueryWhereClause);
+					break;
+				case "Select":
+					specialNodeType = typeof(QuerySelectClause);
+					break;
+				case "SelectMany":
+					specialNodeType = typeof(QueryFromClause);
+					break;
+				case "Join":
+				case "GroupJoin":
+					specialNodeType = typeof(QueryJoinClause);
+					break;
+				case "OrderBy":
+				case "OrderByDescending":
+				case "ThenBy":
+				case "ThenByDescending":
+					specialNodeType = typeof(QueryOrdering);
+					break;
+				case "GroupBy":
+					specialNodeType = typeof(QueryGroupClause);
+					break;
+				case "Invoke":
+					if (method.DeclaringTypeDefinition != null && method.DeclaringTypeDefinition.Kind == TypeKind.Delegate)
+						specialNodeType = typeof(InvocationExpression);
+					else
+						specialNodeType = null;
+					break;
+				case "GetEnumerator":
+				case "MoveNext":
+					specialNodeType = typeof(ForeachStatement);
+					break;
+				case "GetAwaiter":
+				case "GetResult":
+				case "OnCompleted":
+				case "UnsafeOnCompleted":
+					specialNodeType = typeof(UnaryOperatorExpression);
+					break;
+				default:
+					specialNodeType = null;
+					break;
+			}
+			// Use searchTerm only if specialNodeType==null
+			string searchTerm = (specialNodeType == null) ? method.Name : null;
+			return new SearchScope(
+				searchTerm,
+				delegate (ICompilation compilation) {
+					IMethod imported = compilation.Import(method);
+					if (imported != null)
+						return new FindMethodReferences(imported, specialNodeType);
+					else
+						return null;
+				});
+		}
+		
+		sealed class FindMethodReferences : FindReferenceNavigator
+		{
+			readonly IMethod method;
+			readonly Type specialNodeType;
+			HashSet<Expression> potentialMethodGroupConversions = new HashSet<Expression>();
+			
+			public FindMethodReferences(IMethod method, Type specialNodeType)
+			{
+				this.method = method;
+				this.specialNodeType = specialNodeType;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				if (specialNodeType != null && node.GetType() == specialNodeType)
+					return true;
+				
+				Expression expr = node as Expression;
+				if (expr == null)
+					return node is MethodDeclaration;
+				
+				InvocationExpression ie = node as InvocationExpression;
+				if (ie != null) {
+					Expression target = ParenthesizedExpression.UnpackParenthesizedExpression(ie.Target);
+					
+					IdentifierExpression ident = target as IdentifierExpression;
+					if (ident != null)
+						return ident.Identifier == method.Name;
+					
+					MemberReferenceExpression mre = target as MemberReferenceExpression;
+					if (mre != null)
+						return mre.MemberName == method.Name;
+					
+					PointerReferenceExpression pre = target as PointerReferenceExpression;
+					if (pre != null)
+						return pre.MemberName == method.Name;
+				} else if (expr.Role != Roles.TargetExpression) {
+					// MemberReferences & Identifiers that aren't used in an invocation can still match the method
+					// as delegate name.
+					if (expr.GetChildByRole(Roles.Identifier).Name == method.Name)
+						potentialMethodGroupConversions.Add(expr);
+				}
+				return node is MethodDeclaration;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				if (specialNodeType != null) {
+					var ferr = rr as ForEachResolveResult;
+					if (ferr != null) {
+						return IsMatch(ferr.GetEnumeratorCall)
+							|| (ferr.MoveNextMethod != null && findReferences.IsMemberMatch(method, ferr.MoveNextMethod, true));
+					}
+					var arr = rr as AwaitResolveResult;
+					if (arr != null) {
+						return IsMatch(arr.GetAwaiterInvocation)
+							|| (arr.GetResultMethod != null && findReferences.IsMemberMatch(method, arr.GetResultMethod, true))
+							|| (arr.OnCompletedMethod != null && findReferences.IsMemberMatch(method, arr.OnCompletedMethod, true));
+					}
+				}
+				var mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(method, mrr.Member, mrr.IsVirtualCall);
+			}
+			
+			internal override void NavigatorDone(CSharpAstResolver resolver, CancellationToken cancellationToken)
+			{
+				foreach (var expr in potentialMethodGroupConversions) {
+					var conversion = resolver.GetConversion(expr, cancellationToken);
+					if (conversion.IsMethodGroupConversion && findReferences.IsMemberMatch(method, conversion.Method, conversion.IsVirtualMethodLookup)) {
+						IType targetType = resolver.GetExpectedType(expr, cancellationToken);
+						ResolveResult result = resolver.Resolve(expr, cancellationToken);
+						ReportMatch(expr, new ConversionResolveResult(targetType, result, conversion));
+					}
+				}
+				base.NavigatorDone(resolver, cancellationToken);
+			}
+		}
+		#endregion
+		
+		#region Find Indexer References
+		SearchScope FindIndexerReferences(IProperty indexer)
+		{
+			return new SearchScope(
+				delegate (ICompilation compilation) {
+					IProperty imported = compilation.Import(indexer);
+					if (imported != null)
+						return new FindIndexerReferencesNavigator(imported);
+					else
+						return null;
+				});
+		}
+		
+		sealed class FindIndexerReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IProperty indexer;
+			
+			public FindIndexerReferencesNavigator(IProperty indexer)
+			{
+				this.indexer = indexer;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is IndexerExpression || node is IndexerDeclaration;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(indexer, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		#endregion
+		
+		#region Find Operator References
+		SearchScope GetSearchScopeForOperator(IMethod op)
+		{
+			OperatorType? opType = OperatorDeclaration.GetOperatorType(op.Name);
+			if (opType == null)
+				return GetSearchScopeForMethod(op);
+			switch (opType.Value) {
+				case OperatorType.LogicalNot:
+					return FindUnaryOperator(op, UnaryOperatorType.Not);
+				case OperatorType.OnesComplement:
+					return FindUnaryOperator(op, UnaryOperatorType.BitNot);
+				case OperatorType.UnaryPlus:
+					return FindUnaryOperator(op, UnaryOperatorType.Plus);
+				case OperatorType.UnaryNegation:
+					return FindUnaryOperator(op, UnaryOperatorType.Minus);
+				case OperatorType.Increment:
+					return FindUnaryOperator(op, UnaryOperatorType.Increment);
+				case OperatorType.Decrement:
+					return FindUnaryOperator(op, UnaryOperatorType.Decrement);
+				case OperatorType.True:
+				case OperatorType.False:
+					// TODO: implement search for op_True/op_False correctly
+					return GetSearchScopeForMethod(op);
+				case OperatorType.Addition:
+					return FindBinaryOperator(op, BinaryOperatorType.Add);
+				case OperatorType.Subtraction:
+					return FindBinaryOperator(op, BinaryOperatorType.Subtract);
+				case OperatorType.Multiply:
+					return FindBinaryOperator(op, BinaryOperatorType.Multiply);
+				case OperatorType.Division:
+					return FindBinaryOperator(op, BinaryOperatorType.Divide);
+				case OperatorType.Modulus:
+					return FindBinaryOperator(op, BinaryOperatorType.Modulus);
+				case OperatorType.BitwiseAnd:
+					// TODO: an overloaded bitwise operator can also be called using the corresponding logical operator
+					// (if op_True/op_False is defined)
+					return FindBinaryOperator(op, BinaryOperatorType.BitwiseAnd);
+				case OperatorType.BitwiseOr:
+					return FindBinaryOperator(op, BinaryOperatorType.BitwiseOr);
+				case OperatorType.ExclusiveOr:
+					return FindBinaryOperator(op, BinaryOperatorType.ExclusiveOr);
+				case OperatorType.LeftShift:
+					return FindBinaryOperator(op, BinaryOperatorType.ShiftLeft);
+				case OperatorType.RightShift:
+					return FindBinaryOperator(op, BinaryOperatorType.ShiftRight);
+				case OperatorType.Equality:
+					return FindBinaryOperator(op, BinaryOperatorType.Equality);
+				case OperatorType.Inequality:
+					return FindBinaryOperator(op, BinaryOperatorType.InEquality);
+				case OperatorType.GreaterThan:
+					return FindBinaryOperator(op, BinaryOperatorType.GreaterThan);
+				case OperatorType.LessThan:
+					return FindBinaryOperator(op, BinaryOperatorType.LessThan);
+				case OperatorType.GreaterThanOrEqual:
+					return FindBinaryOperator(op, BinaryOperatorType.GreaterThanOrEqual);
+				case OperatorType.LessThanOrEqual:
+					return FindBinaryOperator(op, BinaryOperatorType.LessThanOrEqual);
+				case OperatorType.Implicit:
+					return FindOperator(op, m => new FindImplicitOperatorNavigator(m));
+				case OperatorType.Explicit:
+					return FindOperator(op, m => new FindExplicitOperatorNavigator(m));
+				default:
+					throw new InvalidOperationException("Invalid value for OperatorType");
+			}
+		}
+		
+		SearchScope FindOperator(IMethod op, Func<IMethod, FindReferenceNavigator> factory)
+		{
+			return new SearchScope(
+				delegate (ICompilation compilation) {
+					IMethod imported = compilation.Import(op);
+					return imported != null ? factory(imported) : null;
+				});
+		}
+		
+		SearchScope FindUnaryOperator(IMethod op, UnaryOperatorType operatorType)
+		{
+			return FindOperator(op, m => new FindUnaryOperatorNavigator(m, operatorType));
+		}
+		
+		sealed class FindUnaryOperatorNavigator : FindReferenceNavigator
+		{
+			readonly IMethod op;
+			readonly UnaryOperatorType operatorType;
+			
+			public FindUnaryOperatorNavigator(IMethod op, UnaryOperatorType operatorType)
+			{
+				this.op = op;
+				this.operatorType = operatorType;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				UnaryOperatorExpression uoe = node as UnaryOperatorExpression;
+				if (uoe != null) {
+					if (operatorType == UnaryOperatorType.Increment)
+						return uoe.Operator == UnaryOperatorType.Increment || uoe.Operator == UnaryOperatorType.PostIncrement;
+					else if (operatorType == UnaryOperatorType.Decrement)
+						return uoe.Operator == UnaryOperatorType.Decrement || uoe.Operator == UnaryOperatorType.PostDecrement;
+					else
+						return uoe.Operator == operatorType;
+				}
+				return node is OperatorDeclaration;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		
+		SearchScope FindBinaryOperator(IMethod op, BinaryOperatorType operatorType)
+		{
+			return FindOperator(op, m => new FindBinaryOperatorNavigator(m, operatorType));
+		}
+		
+		sealed class FindBinaryOperatorNavigator : FindReferenceNavigator
+		{
+			readonly IMethod op;
+			readonly BinaryOperatorType operatorType;
+			
+			public FindBinaryOperatorNavigator(IMethod op, BinaryOperatorType operatorType)
+			{
+				this.op = op;
+				this.operatorType = operatorType;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				BinaryOperatorExpression boe = node as BinaryOperatorExpression;
+				if (boe != null) {
+					return boe.Operator == operatorType;
+				}
+				return node is OperatorDeclaration;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		
+		sealed class FindImplicitOperatorNavigator : FindReferenceNavigator
+		{
+			readonly IMethod op;
+			
+			public FindImplicitOperatorNavigator(IMethod op)
+			{
+				this.op = op;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return true;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
+			}
+			
+			public override void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+			{
+				if (conversion.IsUserDefined && findReferences.IsMemberMatch(op, conversion.Method, conversion.IsVirtualMethodLookup)) {
+					ReportMatch(expression, result);
+				}
+			}
+		}
+		
+		sealed class FindExplicitOperatorNavigator : FindReferenceNavigator
+		{
+			readonly IMethod op;
+			
+			public FindExplicitOperatorNavigator(IMethod op)
+			{
+				this.op = op;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is CastExpression;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				ConversionResolveResult crr = rr as ConversionResolveResult;
+				return crr != null && crr.Conversion.IsUserDefined
+					&& findReferences.IsMemberMatch(op, crr.Conversion.Method, crr.Conversion.IsVirtualMethodLookup);
+			}
+		}
+		#endregion
+		
+		#region Find Constructor References
+		SearchScope FindObjectCreateReferences(IMethod ctor)
+		{
+			string searchTerm = null;
+			if (KnownTypeReference.GetCSharpNameByTypeCode(ctor.DeclaringTypeDefinition.KnownTypeCode) == null) {
+				// not a built-in type
+				searchTerm = ctor.DeclaringTypeDefinition.Name;
+				if (searchTerm.Length > 9 && searchTerm.EndsWith("Attribute", StringComparison.Ordinal)) {
+					// we also need to look for the short form
+					searchTerm = null;
+				}
+			}
+			return new SearchScope(
+				searchTerm,
+				delegate (ICompilation compilation) {
+					IMethod imported = compilation.Import(ctor);
+					if (imported != null)
+						return new FindObjectCreateReferencesNavigator(imported);
+					else
+						return null;
+				});
+		}
+		
+		sealed class FindObjectCreateReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IMethod ctor;
+			
+			public FindObjectCreateReferencesNavigator(IMethod ctor)
+			{
+				this.ctor = ctor;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is ObjectCreateExpression || node is ConstructorDeclaration || node is Attribute;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(ctor, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		
+		SearchScope FindChainedConstructorReferences(IMethod ctor)
+		{
+			SearchScope searchScope = new SearchScope(
+				delegate (ICompilation compilation) {
+					IMethod imported = compilation.Import(ctor);
+					if (imported != null)
+						return new FindChainedConstructorReferencesNavigator(imported);
+					else
+						return null;
+				});
+			if (ctor.DeclaringTypeDefinition.IsSealed)
+				searchScope.accessibility = Accessibility.Private;
+			else
+				searchScope.accessibility = Accessibility.Protected;
+			searchScope.accessibility = MergeAccessibility(GetEffectiveAccessibility(ctor), searchScope.accessibility);
+			return searchScope;
+		}
+		
+		sealed class FindChainedConstructorReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IMethod ctor;
+			
+			public FindChainedConstructorReferencesNavigator(IMethod ctor)
+			{
+				this.ctor = ctor;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is ConstructorInitializer;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(ctor, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		#endregion
+		
+		#region Find Destructor References
+		SearchScope GetSearchScopeForDestructor(IMethod dtor)
+		{
+			var scope = new SearchScope (
+				delegate (ICompilation compilation) {
+					IMethod imported = compilation.Import(dtor);
+					if (imported != null) {
+						return new FindDestructorReferencesNavigator (imported);
+					} else {
+						return null;
+					}
+				});
+			scope.accessibility = Accessibility.Private;
+			return scope;
+		}
+		
+		sealed class FindDestructorReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IMethod dtor;
+			
+			public FindDestructorReferencesNavigator (IMethod dtor)
+			{
+				this.dtor = dtor;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				return node is DestructorDeclaration;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				MemberResolveResult mrr = rr as MemberResolveResult;
+				return mrr != null && findReferences.IsMemberMatch(dtor, mrr.Member, mrr.IsVirtualCall);
+			}
+		}
+		#endregion
+
+		#region Find Local Variable References
+		/// <summary>
+		/// Finds all references of a given variable.
+		/// </summary>
+		/// <param name="variable">The variable for which to look.</param>
+		/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
+		/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
+		/// <param name="compilation">The compilation.</param>
+		/// <param name="callback">Callback used to report the references that were found.</param>
+		/// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
+		public void FindLocalReferences(IVariable variable, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
+		                                ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
+		{
+			if (variable == null)
+				throw new ArgumentNullException("variable");
+			var searchScope = new SearchScope(c => new FindLocalReferencesNavigator(variable));
+			searchScope.declarationCompilation = compilation;
+			FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
+		}
+		
+		SearchScope GetSearchScopeForLocalVariable(IVariable variable)
+		{
+			var scope = new SearchScope (
+				delegate {
+					return new FindLocalReferencesNavigator(variable);
+				}
+			);
+			scope.fileName = variable.Region.FileName;
+			return scope;
+		}
+		
+		class FindLocalReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IVariable variable;
+			
+			public FindLocalReferencesNavigator(IVariable variable)
+			{
+				this.variable = variable;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				var expr = node as IdentifierExpression;
+				if (expr != null)
+					return expr.TypeArguments.Count == 0 && variable.Name == expr.Identifier;
+				var vi = node as VariableInitializer;
+				if (vi != null)
+					return vi.Name == variable.Name;
+				var pd = node as ParameterDeclaration;
+				if (pd != null)
+					return pd.Name == variable.Name;
+				var id = node as Identifier;
+				if (id != null)
+					return id.Name == variable.Name;
+				return false;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				var lrr = rr as LocalResolveResult;
+				return lrr != null && lrr.Variable.Name == variable.Name && lrr.Variable.Region == variable.Region;
+			}
+		}
+		#endregion
+
+		#region Find Type Parameter References
+		/// <summary>
+		/// Finds all references of a given type parameter.
+		/// </summary>
+		/// <param name="typeParameter">The type parameter for which to look.</param>
+		/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
+		/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
+		/// <param name="compilation">The compilation.</param>
+		/// <param name="callback">Callback used to report the references that were found.</param>
+		/// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
+		[Obsolete("Use GetSearchScopes(typeParameter) instead")]
+		public void FindTypeParameterReferences(IType typeParameter, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
+		                                        ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
+		{
+			if (typeParameter == null)
+				throw new ArgumentNullException("typeParameter");
+			if (typeParameter.Kind != TypeKind.TypeParameter)
+				throw new ArgumentOutOfRangeException("typeParameter", "Only type parameters are allowed");
+			var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator((ITypeParameter)typeParameter));
+			searchScope.declarationCompilation = compilation;
+			searchScope.accessibility = Accessibility.Private;
+			FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
+		}
+		
+		SearchScope GetSearchScopeForTypeParameter(ITypeParameter tp)
+		{
+			var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator(tp));
+			var compilationProvider = tp as ICompilationProvider;
+			if (compilationProvider != null)
+				searchScope.declarationCompilation = compilationProvider.Compilation;
+			searchScope.topLevelTypeDefinition = GetTopLevelTypeDefinition(tp.Owner);
+			searchScope.accessibility = Accessibility.Private;
+			return searchScope;
+		}
+
+		class FindTypeParameterReferencesNavigator : FindReferenceNavigator
+		{
+			readonly ITypeParameter typeParameter;
+			
+			public FindTypeParameterReferencesNavigator(ITypeParameter typeParameter)
+			{
+				this.typeParameter = typeParameter;
+			}
+			
+			internal override bool CanMatch(AstNode node)
+			{
+				var type = node as SimpleType;
+				if (type != null)
+					return type.Identifier == typeParameter.Name;
+				var declaration = node as TypeParameterDeclaration;
+				if (declaration != null)
+					return declaration.Name == typeParameter.Name;
+				return false;
+			}
+			
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				var lrr = rr as TypeResolveResult;
+				return lrr != null && lrr.Type.Kind == TypeKind.TypeParameter && ((ITypeParameter)lrr.Type).Region == typeParameter.Region;
+			}
+		}
+		#endregion
+		
+		#region Find Namespace References
+		SearchScope GetSearchScopeForNamespace(INamespace ns)
+		{
+			var scope = new SearchScope (
+				delegate (ICompilation compilation) {
+					return new FindNamespaceNavigator (ns);
+				}
+			);
+			return scope;
+		}
+
+		sealed class FindNamespaceNavigator : FindReferenceNavigator
+		{
+			readonly INamespace ns;
+
+			public FindNamespaceNavigator (INamespace ns)
+			{
+				this.ns = ns;
+			}
+
+			internal override bool CanMatch(AstNode node)
+			{
+				var nsd = node as NamespaceDeclaration;
+				if (nsd != null && nsd.FullName.StartsWith(ns.FullName, StringComparison.Ordinal))
+					return true;
+
+				var ud = node as UsingDeclaration;
+				if (ud != null && ud.Namespace == ns.FullName)
+					return true;
+
+				var st = node as SimpleType;
+				if (st != null && st.Identifier == ns.Name)
+					return !st.AncestorsAndSelf.TakeWhile (n => n is AstType).Any (m => m.Role == NamespaceDeclaration.NamespaceNameRole);
+
+				var mt = node as MemberType;
+				if (mt != null && mt.MemberName == ns.Name)
+					return !mt.AncestorsAndSelf.TakeWhile (n => n is AstType).Any (m => m.Role == NamespaceDeclaration.NamespaceNameRole);
+
+				var identifer = node as IdentifierExpression;
+				if (identifer != null && identifer.Identifier == ns.Name)
+					return true;
+
+				var mrr = node as MemberReferenceExpression;
+				if (mrr != null && mrr.MemberName == ns.Name)
+					return true;
+
+
+				return false;
+			}
+
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				var nsrr = rr as NamespaceResolveResult;
+				return nsrr != null && nsrr.NamespaceName.StartsWith(ns.FullName, StringComparison.Ordinal);
+			}
+		}
+		#endregion
+		
+		#region Find Parameter References
+
+		SearchScope GetSearchScopeForParameter(IParameter parameter)
+		{
+			var scope = new SearchScope (
+				delegate {
+					return new FindParameterReferencesNavigator (parameter);
+				}
+			);
+			if (parameter.Owner == null) {
+				scope.fileName = parameter.Region.FileName;
+			}
+			return scope;
+		}
+
+		class FindParameterReferencesNavigator : FindReferenceNavigator
+		{
+			readonly IParameter parameter;
+
+			public FindParameterReferencesNavigator(IParameter parameter)
+			{
+				this.parameter = parameter;
+			}
+
+			internal override bool CanMatch(AstNode node)
+			{
+				var expr = node as IdentifierExpression;
+				if (expr != null)
+					return expr.TypeArguments.Count == 0 && parameter.Name == expr.Identifier;
+				var vi = node as VariableInitializer;
+				if (vi != null)
+					return vi.Name == parameter.Name;
+				var pd = node as ParameterDeclaration;
+				if (pd != null)
+					return pd.Name == parameter.Name;
+				var id = node as Identifier;
+				if (id != null)
+					return id.Name == parameter.Name;
+				var nae = node as NamedArgumentExpression;
+				if (nae != null)
+					return nae.Name == parameter.Name;
+				return false;
+			}
+
+			internal override bool IsMatch(ResolveResult rr)
+			{
+				var lrr = rr as LocalResolveResult;
+				if (lrr != null)
+					return lrr.Variable.Name == parameter.Name && lrr.Variable.Region == parameter.Region;
+
+				var nar = rr as NamedArgumentResolveResult;
+				return nar != null && nar.Parameter.Name == parameter.Name && nar.Parameter.Region == parameter.Region;
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/IResolveVisitorNavigator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/IResolveVisitorNavigator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/IResolveVisitorNavigator.cs	(revision 11807)
@@ -0,0 +1,103 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Allows controlling which nodes are resolved by the resolve visitor.
+	/// </summary>
+	/// <seealso cref="ResolveVisitor"/>
+	public interface IResolveVisitorNavigator
+	{
+		/// <summary>
+		/// Asks the navigator whether to scan, skip, or resolve a node.
+		/// </summary>
+		ResolveVisitorNavigationMode Scan(AstNode node);
+		
+		/// <summary>
+		/// Notifies the navigator that a node was resolved.
+		/// </summary>
+		/// <param name="node">The node that was resolved</param>
+		/// <param name="result">Resolve result</param>
+		void Resolved(AstNode node, ResolveResult result);
+		
+		/// <summary>
+		/// Notifies the navigator that an implicit conversion was applied.
+		/// </summary>
+		/// <param name="expression">The expression that was resolved.</param>
+		/// <param name="result">The resolve result of the expression.</param>
+		/// <param name="conversion">The conversion applied to the expressed.</param>
+		/// <param name="targetType">The target type of the conversion.</param>
+		void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType);
+	}
+	
+	/// <summary>
+	/// Represents the operation mode of the resolve visitor.
+	/// </summary>
+	/// <seealso cref="ResolveVisitor"/>
+	public enum ResolveVisitorNavigationMode
+	{
+		/// <summary>
+		/// Scan into the children of the current node, without resolving the current node.
+		/// </summary>
+		Scan,
+		/// <summary>
+		/// Skip the current node - do not scan into it; do not resolve it.
+		/// </summary>
+		Skip,
+		/// <summary>
+		/// Resolve the current node.
+		/// Subnodes which are not required for resolving the current node
+		/// will ask the navigator again whether they should be resolved.
+		/// </summary>
+		Resolve
+	}
+	
+	sealed class ConstantModeResolveVisitorNavigator : IResolveVisitorNavigator
+	{
+		readonly ResolveVisitorNavigationMode mode;
+		readonly IResolveVisitorNavigator targetForResolveCalls;
+		
+		public ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode mode, IResolveVisitorNavigator targetForResolveCalls)
+		{
+			this.mode = mode;
+			this.targetForResolveCalls = targetForResolveCalls;
+		}
+		
+		ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
+		{
+			return mode;
+		}
+		
+		void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
+		{
+			if (targetForResolveCalls != null)
+				targetForResolveCalls.Resolved(node, result);
+		}
+		
+		void IResolveVisitorNavigator.ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+		{
+			if (targetForResolveCalls != null)
+				targetForResolveCalls.ProcessConversion(expression, result, conversion, targetType);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/LambdaResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/LambdaResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/LambdaResolveResult.cs	(revision 11807)
@@ -0,0 +1,101 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Represents an anonymous method or lambda expression.
+	/// Note: the lambda has no type.
+	/// To retrieve the delegate type, look at the anonymous function conversion.
+	/// </summary>
+	public abstract class LambdaResolveResult : ResolveResult
+	{
+		protected LambdaResolveResult() : base(SpecialType.UnknownType)
+		{
+		}
+		
+		/// <summary>
+		/// Gets whether there is a parameter list.
+		/// This property always returns true for C# 3.0-lambdas, but may return false
+		/// for C# 2.0 anonymous methods.
+		/// </summary>
+		public abstract bool HasParameterList { get; }
+		
+		/// <summary>
+		/// Gets whether this lambda is using the C# 2.0 anonymous method syntax.
+		/// </summary>
+		public abstract bool IsAnonymousMethod { get; }
+		
+		/// <summary>
+		/// Gets whether the lambda parameters are implicitly typed.
+		/// </summary>
+		/// <remarks>This property returns false for anonymous methods without parameter list.</remarks>
+		public abstract bool IsImplicitlyTyped { get; }
+		
+		/// <summary>
+		/// Gets whether the lambda is async.
+		/// </summary>
+		public abstract bool IsAsync { get; }
+		
+		/// <summary>
+		/// Gets the return type inferred when the parameter types are inferred to be <paramref name="parameterTypes"/>
+		/// </summary>
+		/// <remarks>
+		/// This method determines the return type inferred from the lambda body, which is used as part of C# type inference.
+		/// Use the <see cref="ReturnType"/> property to retrieve the actual return type as determined by the target delegate type.
+		/// </remarks>
+		public abstract IType GetInferredReturnType(IType[] parameterTypes);
+		
+		/// <summary>
+		/// Gets the list of parameters.
+		/// </summary>
+		public abstract IList<IParameter> Parameters { get; }
+		
+		/// <summary>
+		/// Gets the return type of the lambda.
+		/// 
+		/// If the lambda is async, the return type includes <code>Task&lt;T&gt;</code>
+		/// </summary>
+		public abstract IType ReturnType { get; }
+		
+		/// <summary>
+		/// Gets whether the lambda body is valid for the given parameter types and return type.
+		/// </summary>
+		/// <returns>
+		/// Produces a conversion with <see cref="Conversion.IsAnonymousFunctionConversion"/>=<c>true</c> if the lambda is valid;
+		/// otherwise returns <see cref="Conversion.None"/>.
+		/// </returns>
+		public abstract Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions);
+		
+		/// <summary>
+		/// Gets the resolve result for the lambda body.
+		/// Returns a resolve result for 'void' for statement lambdas.
+		/// </summary>
+		public abstract ResolveResult Body { get; }
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			return new [] { this.Body };
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/Log.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/Log.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/Log.cs	(revision 11807)
@@ -0,0 +1,94 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Resolver logging helper.
+	/// Wraps System.Diagnostics.Debug so that resolver-specific logging can be enabled/disabled on demand.
+	/// (it's a huge amount of debug spew and slows down the resolver quite a bit)
+	/// </summary>
+	static class Log
+	{
+		const bool logEnabled = false;
+#if __MonoCS__
+		[Conditional("MCS_DEBUG")]
+#else
+		[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
+#endif
+		internal static void WriteLine(string text)
+		{
+			Debug.WriteLine(text);
+		}
+		
+#if __MonoCS__
+		[Conditional("MCS_DEBUG")]
+#else
+		[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
+#endif
+		internal static void WriteLine(string format, params object[] args)
+		{
+			Debug.WriteLine(format, args);
+		}
+		
+#if __MonoCS__
+		[Conditional("MCS_DEBUG")]
+#else
+		[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
+#endif
+		internal static void WriteCollection<T>(string text, IEnumerable<T> lines)
+		{
+			#if DEBUG
+			T[] arr = lines.ToArray();
+			if (arr.Length == 0) {
+				Debug.WriteLine(text + "<empty collection>");
+			} else {
+				Debug.WriteLine(text + (arr[0] != null ? arr[0].ToString() : "<null>"));
+				for (int i = 1; i < arr.Length; i++) {
+					Debug.WriteLine(new string(' ', text.Length) + (arr[i] != null ? arr[i].ToString() : "<null>"));
+				}
+			}
+			#endif
+		}
+		
+#if __MonoCS__
+		[Conditional("MCS_DEBUG")]
+#else
+		[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
+#endif
+		public static void Indent()
+		{
+			Debug.Indent();
+		}
+		
+#if __MonoCS__
+		[Conditional("MCS_DEBUG")]
+#else
+		[Conditional(logEnabled ? "DEBUG" : "LOG_DISABLED")]
+#endif
+		public static void Unindent()
+		{
+			Debug.Unindent();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/MemberLookup.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/MemberLookup.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/MemberLookup.cs	(revision 11807)
@@ -0,0 +1,696 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Implementation of member lookup (C# 4.0 spec, §7.4).
+	/// </summary>
+	public class MemberLookup
+	{
+		#region Static helper methods
+		/// <summary>
+		/// Gets whether the member is considered to be invocable.
+		/// </summary>
+		public static bool IsInvocable(IMember member)
+		{
+			if (member == null)
+				throw new ArgumentNullException("member");
+			// C# 4.0 spec, §7.4 member lookup
+			if (member is IEvent || member is IMethod)
+				return true;
+			IType returnType = member.ReturnType;
+			return returnType.Kind == TypeKind.Dynamic || returnType.Kind == TypeKind.Delegate;
+		}
+		#endregion
+		
+		readonly ITypeDefinition currentTypeDefinition;
+		readonly IAssembly currentAssembly;
+		readonly bool isInEnumMemberInitializer;
+		
+		public MemberLookup(ITypeDefinition currentTypeDefinition, IAssembly currentAssembly, bool isInEnumMemberInitializer = false)
+		{
+			this.currentTypeDefinition = currentTypeDefinition;
+			this.currentAssembly = currentAssembly;
+			this.isInEnumMemberInitializer = isInEnumMemberInitializer;
+		}
+		
+		#region IsAccessible
+		/// <summary>
+		/// Gets whether access to protected instance members of the target expression is possible.
+		/// </summary>
+		public bool IsProtectedAccessAllowed(ResolveResult targetResolveResult)
+		{
+			return targetResolveResult is ThisResolveResult || IsProtectedAccessAllowed(targetResolveResult.Type);
+		}
+		
+		/// <summary>
+		/// Gets whether access to protected instance members of the target type is possible.
+		/// </summary>
+		/// <remarks>
+		/// This method does not consider the special case of the 'base' reference. If possible, use the
+		/// <c>IsProtectedAccessAllowed(ResolveResult)</c> overload instead.
+		/// </remarks>
+		public bool IsProtectedAccessAllowed(IType targetType)
+		{
+			if (targetType.Kind == TypeKind.TypeParameter)
+				targetType = ((ITypeParameter)targetType).EffectiveBaseClass;
+			ITypeDefinition typeDef = targetType.GetDefinition();
+			if (typeDef == null)
+				return false;
+			for (ITypeDefinition c = currentTypeDefinition; c != null; c = c.DeclaringTypeDefinition) {
+				if (typeDef.IsDerivedFrom(c))
+					return true;
+			}
+			return false;
+		}
+		
+		/// <summary>
+		/// Gets whether <paramref name="entity"/> is accessible in the current class.
+		/// </summary>
+		/// <param name="entity">The entity to test</param>
+		/// <param name="allowProtectedAccess">
+		/// Whether protected access to instance members is allowed.
+		/// True if the type of the reference is derived from the current class.
+		/// Protected static members may be accessible even if false is passed for this parameter.
+		/// </param>
+		public bool IsAccessible(IEntity entity, bool allowProtectedAccess)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			// C# 4.0 spec, §3.5.2 Accessiblity domains
+			switch (entity.Accessibility) {
+				case Accessibility.None:
+					return false;
+				case Accessibility.Private:
+					// check for members of outer classes (private members of outer classes can be accessed)
+					for (var t = currentTypeDefinition; t != null; t = t.DeclaringTypeDefinition) {
+						if (t.Equals(entity.DeclaringTypeDefinition))
+							return true;
+					}
+					return false;
+				case Accessibility.Public:
+					return true;
+				case Accessibility.Protected:
+					return IsProtectedAccessible(allowProtectedAccess, entity);
+				case Accessibility.Internal:
+					return IsInternalAccessible(entity.ParentAssembly);
+				case Accessibility.ProtectedOrInternal:
+					return IsInternalAccessible(entity.ParentAssembly) || IsProtectedAccessible(allowProtectedAccess, entity);
+				case Accessibility.ProtectedAndInternal:
+					return IsInternalAccessible(entity.ParentAssembly) && IsProtectedAccessible(allowProtectedAccess, entity);
+				default:
+					throw new Exception("Invalid value for Accessibility");
+			}
+		}
+		
+		bool IsInternalAccessible(IAssembly assembly)
+		{
+			return assembly != null && currentAssembly != null && assembly.InternalsVisibleTo(currentAssembly);
+		}
+		
+		bool IsProtectedAccessible(bool allowProtectedAccess, IEntity entity)
+		{
+			// For static members and type definitions, we do not require the qualifying reference
+			// to be derived from the current class (allowProtectedAccess).
+			if (entity.IsStatic || entity.SymbolKind == SymbolKind.TypeDefinition)
+				allowProtectedAccess = true;
+			
+			for (var t = currentTypeDefinition; t != null; t = t.DeclaringTypeDefinition) {
+				if (t.Equals(entity.DeclaringTypeDefinition))
+					return true;
+				
+				// PERF: this might hurt performance as this method is called several times (once for each member)
+				// make sure resolving base types is cheap (caches?) or cache within the MemberLookup instance
+				if (allowProtectedAccess && t.IsDerivedFrom(entity.DeclaringTypeDefinition))
+					return true;
+			}
+			return false;
+		}
+		#endregion
+		
+		#region GetAccessibleMembers
+		/// <summary>
+		/// Retrieves all members that are accessible and not hidden (by being overridden or shadowed).
+		/// Returns both members and nested type definitions. Does not include extension methods.
+		/// </summary>
+		public IEnumerable<IEntity> GetAccessibleMembers(ResolveResult targetResolveResult)
+		{
+			if (targetResolveResult == null)
+				throw new ArgumentNullException("targetResolveResult");
+			
+			bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter;
+			bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);
+			
+			// maps the member name to the list of lookup groups
+			var lookupGroupDict = new Dictionary<string, List<LookupGroup>>();
+			
+			// This loop will handle base types before derived types.
+			// The loop performs three jobs:
+			// 1) It marks entries in lookup groups from base classes as removed when those members
+			//    are hidden by a derived class.
+			// 2) It adds a new lookup group with the members from a declaring type.
+			// 3) It replaces virtual members with the overridden version, placing the override in the
+			//    lookup group belonging to the base class.
+			foreach (IType type in targetResolveResult.Type.GetNonInterfaceBaseTypes()) {
+				
+				List<IEntity> entities = new List<IEntity>();
+				entities.AddRange(type.GetMembers(options: GetMemberOptions.IgnoreInheritedMembers));
+				if (!targetIsTypeParameter) {
+					var nestedTypes = type.GetNestedTypes(options: GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions);
+					// GetDefinition() might return null if some IType has a strange implementation of GetNestedTypes.
+					entities.AddRange(nestedTypes.Select(t => t.GetDefinition()).Where(td => td != null));
+				}
+				
+				foreach (var entityGroup in entities.GroupBy(e => e.Name)) {
+					
+					List<LookupGroup> lookupGroups = new List<LookupGroup>();
+					if (!lookupGroupDict.TryGetValue(entityGroup.Key, out lookupGroups))
+						lookupGroupDict.Add(entityGroup.Key, lookupGroups = new List<LookupGroup>());
+					
+					List<IType> newNestedTypes = null;
+					List<IParameterizedMember> newMethods = null;
+					IMember newNonMethod = null;
+					
+					IEnumerable<IType> typeBaseTypes = null;
+					
+					if (!targetIsTypeParameter) {
+						AddNestedTypes(type, entityGroup.OfType<IType>(), 0, lookupGroups, ref typeBaseTypes, ref newNestedTypes);
+					}
+					AddMembers(type, entityGroup.OfType<IMember>(), allowProtectedAccess, lookupGroups, false, ref typeBaseTypes, ref newMethods, ref newNonMethod);
+					
+					if (newNestedTypes != null || newMethods != null || newNonMethod != null)
+						lookupGroups.Add(new LookupGroup(type, newNestedTypes, newMethods, newNonMethod));
+				}
+			}
+			
+			foreach (List<LookupGroup> lookupGroups in lookupGroupDict.Values) {
+				// Remove interface members hidden by class members.
+				if (targetIsTypeParameter) {
+					// This can happen only with type parameters.
+					RemoveInterfaceMembersHiddenByClassMembers(lookupGroups);
+				}
+				
+				// Now report the results:
+				foreach (LookupGroup lookupGroup in lookupGroups) {
+					if (!lookupGroup.MethodsAreHidden) {
+						foreach (IMethod method in lookupGroup.Methods) {
+							yield return method;
+						}
+					}
+					if (!lookupGroup.NonMethodIsHidden) {
+						yield return lookupGroup.NonMethod;
+					}
+					if (lookupGroup.NestedTypes != null) {
+						foreach (IType type in lookupGroup.NestedTypes) {
+							ITypeDefinition typeDef = type.GetDefinition();
+							if (typeDef != null)
+								yield return typeDef;
+						}
+					}
+				}
+			}
+		}
+		#endregion
+		
+		#region class LookupGroup
+		sealed class LookupGroup
+		{
+			public readonly IType DeclaringType;
+			
+			// When a nested type is hidden, it is simply removed from the list.
+			public List<IType> NestedTypes;
+			
+			// When members are hidden, they are merely marked as hidden.
+			// We still need to store the hidden methods so that the 'override' processing can
+			// find them, so that it won't introduce the override as a new method.
+			public readonly List<IParameterizedMember> Methods;
+			public bool MethodsAreHidden;
+			
+			public IMember NonMethod;
+			public bool NonMethodIsHidden;
+			
+			public LookupGroup(IType declaringType, List<IType> nestedTypes, List<IParameterizedMember> methods, IMember nonMethod)
+			{
+				this.DeclaringType = declaringType;
+				this.NestedTypes = nestedTypes;
+				this.Methods = methods;
+				this.NonMethod = nonMethod;
+				this.MethodsAreHidden = (methods == null || methods.Count == 0);
+				this.NonMethodIsHidden = (nonMethod == null);
+			}
+			
+			public bool AllHidden {
+				get {
+					if (NestedTypes != null && NestedTypes.Count > 0)
+						return false;
+					return NonMethodIsHidden && MethodsAreHidden;
+				}
+			}
+		}
+		#endregion
+		
+		#region LookupType
+		public ResolveResult LookupType(IType declaringType, string name, IList<IType> typeArguments, bool parameterizeResultType = true)
+		{
+			if (declaringType == null)
+				throw new ArgumentNullException("declaringType");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			if (typeArguments == null)
+				throw new ArgumentNullException("typeArguments");
+			
+			int typeArgumentCount = typeArguments.Count;
+			Predicate<ITypeDefinition> filter = delegate (ITypeDefinition d) {
+				return InnerTypeParameterCount(d) == typeArgumentCount && d.Name == name && IsAccessible(d, true);
+			};
+			
+			List<LookupGroup> lookupGroups = new List<LookupGroup>();
+			if (declaringType.Kind != TypeKind.TypeParameter) {
+				foreach (IType type in declaringType.GetNonInterfaceBaseTypes()) {
+					List<IType> newNestedTypes = null;
+					IEnumerable<IType> typeBaseTypes = null;
+					
+					IEnumerable<IType> nestedTypes;
+					if (parameterizeResultType) {
+						nestedTypes = type.GetNestedTypes(typeArguments, filter, GetMemberOptions.IgnoreInheritedMembers);
+					} else {
+						nestedTypes = type.GetNestedTypes(filter, GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions);
+					}
+					AddNestedTypes(type, nestedTypes, typeArgumentCount, lookupGroups, ref typeBaseTypes, ref newNestedTypes);
+					
+					if (newNestedTypes != null)
+						lookupGroups.Add(new LookupGroup(type, newNestedTypes, null, null));
+				}
+			}
+			
+			lookupGroups.RemoveAll(g => g.AllHidden);
+			Debug.Assert(lookupGroups.All(g => g.NestedTypes != null && g.NestedTypes.Count > 0));
+			
+			if (lookupGroups.Count == 0) {
+				return new UnknownMemberResolveResult(declaringType, name, typeArguments);
+			}
+			
+			LookupGroup resultGroup = lookupGroups[lookupGroups.Count - 1];
+			
+			if (resultGroup.NestedTypes.Count > 1 || lookupGroups.Count > 1)
+				return new AmbiguousTypeResolveResult(resultGroup.NestedTypes[0]);
+			else
+				return new TypeResolveResult(resultGroup.NestedTypes[0]);
+		}
+		
+		static int InnerTypeParameterCount(IType type)
+		{
+			// inner types contain the type parameters of outer types. therefore this count has to been adjusted.
+			return type.TypeParameterCount - (type.DeclaringType != null ? type.DeclaringType.TypeParameterCount : 0);
+		}
+		#endregion
+		
+		#region Lookup
+		/// <summary>
+		/// Performs a member lookup.
+		/// </summary>
+		public ResolveResult Lookup(ResolveResult targetResolveResult, string name, IList<IType> typeArguments, bool isInvocation)
+		{
+			if (targetResolveResult == null)
+				throw new ArgumentNullException("targetResolveResult");
+			if (name == null)
+				throw new ArgumentNullException("name");
+			if (typeArguments == null)
+				throw new ArgumentNullException("typeArguments");
+			
+			bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter;
+			
+			bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);
+			Predicate<ITypeDefinition> nestedTypeFilter = delegate(ITypeDefinition entity) {
+				return entity.Name == name && IsAccessible(entity, allowProtectedAccess);
+			};
+			Predicate<IUnresolvedMember> memberFilter = delegate(IUnresolvedMember entity) {
+				// NOTE: Atm destructors can be looked up with 'Finalize'
+				return entity.SymbolKind != SymbolKind.Indexer &&
+				       entity.SymbolKind != SymbolKind.Operator && 
+				       entity.Name == name;
+			};
+			
+			List<LookupGroup> lookupGroups = new List<LookupGroup>();
+			// This loop will handle base types before derived types.
+			// The loop performs three jobs:
+			// 1) It marks entries in lookup groups from base classes as removed when those members
+			//    are hidden by a derived class.
+			// 2) It adds a new lookup group with the members from a declaring type.
+			// 3) It replaces virtual members with the overridden version, placing the override in the
+			//    lookup group belonging to the base class.
+			foreach (IType type in targetResolveResult.Type.GetNonInterfaceBaseTypes()) {
+				
+				List<IType> newNestedTypes = null;
+				List<IParameterizedMember> newMethods = null;
+				IMember newNonMethod = null;
+				
+				IEnumerable<IType> typeBaseTypes = null;
+				
+				if (!isInvocation && !targetIsTypeParameter) {
+					// Consider nested types only if it's not an invocation.
+					// type.GetNestedTypes() is checking the type parameter count for an exact match,
+					// so we don't need to do that in our filter.
+					var nestedTypes = type.GetNestedTypes(typeArguments, nestedTypeFilter, GetMemberOptions.IgnoreInheritedMembers);
+					AddNestedTypes(type, nestedTypes, typeArguments.Count, lookupGroups, ref typeBaseTypes, ref newNestedTypes);
+				}
+				
+				IEnumerable<IMember> members;
+				if (typeArguments.Count == 0) {
+					// Note: IsInvocable-checking cannot be done as part of the filter;
+					// because it must be done after type substitution.
+					members = type.GetMembers(memberFilter, GetMemberOptions.IgnoreInheritedMembers);
+					if (isInvocation)
+						members = members.Where(m => IsInvocable(m));
+				} else {
+					// No need to check for isInvocation/isInvocable here:
+					// we only fetch methods
+					members = type.GetMethods(typeArguments, memberFilter, GetMemberOptions.IgnoreInheritedMembers);
+				}
+				AddMembers(type, members, allowProtectedAccess, lookupGroups, false, ref typeBaseTypes, ref newMethods, ref newNonMethod);
+				
+				if (newNestedTypes != null || newMethods != null || newNonMethod != null)
+					lookupGroups.Add(new LookupGroup(type, newNestedTypes, newMethods, newNonMethod));
+			}
+			
+			// Remove interface members hidden by class members.
+			if (targetIsTypeParameter) {
+				// This can happen only with type parameters.
+				RemoveInterfaceMembersHiddenByClassMembers(lookupGroups);
+			}
+			
+			return CreateResult(targetResolveResult, lookupGroups, name, typeArguments);
+		}
+		#endregion
+		
+		#region Lookup Indexer
+		/// <summary>
+		/// Looks up the indexers on the target type.
+		/// </summary>
+		public IList<MethodListWithDeclaringType> LookupIndexers(ResolveResult targetResolveResult)
+		{
+			if (targetResolveResult == null)
+				throw new ArgumentNullException("targetResolveResult");
+			
+			IType targetType = targetResolveResult.Type;
+			bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);
+			Predicate<IUnresolvedProperty> filter = p => p.IsIndexer;
+			
+			List<LookupGroup> lookupGroups = new List<LookupGroup>();
+			foreach (IType type in targetType.GetNonInterfaceBaseTypes()) {
+				List<IParameterizedMember> newMethods = null;
+				IMember newNonMethod = null;
+				
+				IEnumerable<IType> typeBaseTypes = null;
+				
+				var members = type.GetProperties(filter, GetMemberOptions.IgnoreInheritedMembers);
+				AddMembers(type, members, allowProtectedAccess, lookupGroups, true, ref typeBaseTypes, ref newMethods, ref newNonMethod);
+				
+				if (newMethods != null || newNonMethod != null)
+					lookupGroups.Add(new LookupGroup(type, null, newMethods, newNonMethod));
+			}
+			
+			// Remove interface members hidden by class members.
+			if (targetType.Kind == TypeKind.TypeParameter) {
+				// This can happen only with type parameters.
+				RemoveInterfaceMembersHiddenByClassMembers(lookupGroups);
+			}
+			
+			// Remove all hidden groups
+			lookupGroups.RemoveAll(g => g.MethodsAreHidden || g.Methods.Count == 0);
+			
+			MethodListWithDeclaringType[] methodLists = new MethodListWithDeclaringType[lookupGroups.Count];
+			for (int i = 0; i < methodLists.Length; i++) {
+				methodLists[i] = new MethodListWithDeclaringType(lookupGroups[i].DeclaringType, lookupGroups[i].Methods);
+			}
+			return methodLists;
+		}
+		#endregion
+		
+		#region AddNestedTypes
+		/// <summary>
+		/// Adds the nested types to 'newNestedTypes' and removes any hidden members from the existing lookup groups.
+		/// </summary>
+		/// <param name="type">Declaring type of the nested types</param>
+		/// <param name="nestedTypes">List of nested types to add.</param>
+		/// <param name="typeArgumentCount">The number of type arguments - used for hiding types from the base class</param>
+		/// <param name="lookupGroups">List of existing lookup groups</param>
+		/// <param name="typeBaseTypes">The base types of 'type' (initialized on demand)</param>
+		/// <param name="newNestedTypes">The target list (created on demand).</param>
+		void AddNestedTypes(IType type, IEnumerable<IType> nestedTypes, int typeArgumentCount,
+		                    List<LookupGroup> lookupGroups,
+		                    ref IEnumerable<IType> typeBaseTypes,
+		                    ref List<IType> newNestedTypes)
+		{
+			foreach (IType nestedType in nestedTypes) {
+				// Remove all non-types declared in a base type of 'type',
+				// and all types with same number of type parameters declared in a base type of 'type'.
+				foreach (var lookupGroup in lookupGroups) {
+					if (lookupGroup.AllHidden)
+						continue; // everything is already hidden
+					if (typeBaseTypes == null)
+						typeBaseTypes = type.GetNonInterfaceBaseTypes();
+					
+					if (typeBaseTypes.Contains(lookupGroup.DeclaringType)) {
+						lookupGroup.MethodsAreHidden = true;
+						lookupGroup.NonMethodIsHidden = true;
+						if (lookupGroup.NestedTypes != null)
+							lookupGroup.NestedTypes.RemoveAll(t => InnerTypeParameterCount(t) == typeArgumentCount);
+					}
+				}
+				
+				// Add the new nested type.
+				if (newNestedTypes == null)
+					newNestedTypes = new List<IType>();
+				newNestedTypes.Add(nestedType);
+			}
+		}
+		#endregion
+		
+		#region AddMembers
+		/// <summary>
+		/// Adds members to 'newMethods'/'newNonMethod'.
+		/// Removes any members in the existing lookup groups that were hidden by added members.
+		/// Substitutes 'virtual' members in the existing lookup groups for added 'override' members.
+		/// </summary>
+		/// <param name="type">Declaring type of the members</param>
+		/// <param name="members">List of members to add.</param>
+		/// <param name="allowProtectedAccess">Whether protected members are accessible</param>
+		/// <param name="lookupGroups">List of existing lookup groups</param>
+		/// <param name="treatAllParameterizedMembersAsMethods">Whether to treat properties as methods</param>
+		/// <param name="typeBaseTypes">The base types of 'type' (initialized on demand)</param>
+		/// <param name="newMethods">The target list for methods (created on demand).</param>
+		/// <param name="newNonMethod">The target variable for non-method members.</param>
+		void AddMembers(IType type, IEnumerable<IMember> members,
+		                bool allowProtectedAccess,
+		                List<LookupGroup> lookupGroups,
+		                bool treatAllParameterizedMembersAsMethods,
+		                ref IEnumerable<IType> typeBaseTypes, ref List<IParameterizedMember> newMethods, ref IMember newNonMethod)
+		{
+			foreach (IMember member in members) {
+				if (!IsAccessible(member, allowProtectedAccess))
+					continue;
+				
+				IParameterizedMember method;
+				if (treatAllParameterizedMembersAsMethods)
+					method = member as IParameterizedMember;
+				else
+					method = member as IMethod;
+				
+				bool replacedVirtualMemberWithOverride = false;
+				if (member.IsOverride) {
+					// Replacing virtual member with override:
+					
+					// Go backwards so that we find the corresponding virtual member
+					// in the most-derived type
+					for (int i = lookupGroups.Count - 1; i >= 0 && !replacedVirtualMemberWithOverride; i--) {
+						if (typeBaseTypes == null)
+							typeBaseTypes = type.GetNonInterfaceBaseTypes();
+						
+						var lookupGroup = lookupGroups[i];
+						if (typeBaseTypes.Contains(lookupGroup.DeclaringType)) {
+							if (method != null) {
+								// Find the matching method, and replace it with the override
+								for (int j = 0; j < lookupGroup.Methods.Count; j++) {
+									if (SignatureComparer.Ordinal.Equals(method, lookupGroup.Methods[j])) {
+										lookupGroup.Methods[j] = method;
+										replacedVirtualMemberWithOverride = true;
+										break;
+									}
+								}
+							} else {
+								// If the member type matches, replace it with the override
+								if (lookupGroup.NonMethod != null && lookupGroup.NonMethod.SymbolKind == member.SymbolKind) {
+									lookupGroup.NonMethod = member;
+									replacedVirtualMemberWithOverride = true;
+									break;
+								}
+							}
+						}
+					}
+				}
+				// If the member wasn't an override, or if we didn't find any matching virtual method,
+				// proceed to add the member.
+				if (!replacedVirtualMemberWithOverride) {
+					// Make the member hide other members:
+					foreach (var lookupGroup in lookupGroups) {
+						if (lookupGroup.AllHidden)
+							continue; // everything is already hidden
+						if (typeBaseTypes == null)
+							typeBaseTypes = type.GetNonInterfaceBaseTypes();
+						
+						if (typeBaseTypes.Contains(lookupGroup.DeclaringType)) {
+							// Methods hide all non-methods; Non-methods hide everything
+							lookupGroup.NestedTypes = null;
+							lookupGroup.NonMethodIsHidden = true;
+							if (method == null) { // !(member is IMethod)
+								lookupGroup.MethodsAreHidden = true;
+							}
+						}
+					}
+					
+					// Add the new member
+					if (method != null) {
+						if (newMethods == null)
+							newMethods = new List<IParameterizedMember>();
+						newMethods.Add(method);
+					} else {
+						newNonMethod = member;
+					}
+				}
+			}
+		}
+		#endregion
+		
+		#region RemoveInterfaceMembersHiddenByClassMembers
+		void RemoveInterfaceMembersHiddenByClassMembers(List<LookupGroup> lookupGroups)
+		{
+			foreach (var classLookupGroup in lookupGroups) {
+				if (IsInterfaceOrSystemObject(classLookupGroup.DeclaringType))
+					continue;
+				// The current lookup groups contains class members that might hide interface members
+				bool hasNestedTypes = classLookupGroup.NestedTypes != null && classLookupGroup.NestedTypes.Count > 0;
+				if (hasNestedTypes || !classLookupGroup.NonMethodIsHidden) {
+					// Hide all members from interface types
+					foreach (var interfaceLookupGroup in lookupGroups) {
+						if (IsInterfaceOrSystemObject(interfaceLookupGroup.DeclaringType)) {
+							interfaceLookupGroup.NestedTypes = null;
+							interfaceLookupGroup.NonMethodIsHidden = true;
+							interfaceLookupGroup.MethodsAreHidden = true;
+						}
+					}
+				} else if (!classLookupGroup.MethodsAreHidden) {
+					foreach (var classMethod in classLookupGroup.Methods) {
+						// Hide all non-methods from interface types, and all methods with the same signature
+						// as a method in this class type.
+						foreach (var interfaceLookupGroup in lookupGroups) {
+							if (IsInterfaceOrSystemObject(interfaceLookupGroup.DeclaringType)) {
+								interfaceLookupGroup.NestedTypes = null;
+								interfaceLookupGroup.NonMethodIsHidden = true;
+								if (interfaceLookupGroup.Methods != null && !interfaceLookupGroup.MethodsAreHidden) {
+									// The mapping of virtual to overridden methods is already done,
+									// so we can simply remove the methods from the collection
+									interfaceLookupGroup.Methods.RemoveAll(
+										m => SignatureComparer.Ordinal.Equals(classMethod, m));
+								}
+							}
+						}
+					}
+				}
+			}
+		}
+		
+		static bool IsInterfaceOrSystemObject(IType type)
+		{
+			// return true if type is an interface or System.Object
+			if (type.Kind == TypeKind.Interface)
+				return true;
+			ITypeDefinition d = type.GetDefinition();
+			return d != null && d.KnownTypeCode == KnownTypeCode.Object;
+		}
+		#endregion
+		
+		#region CreateResult
+		ResolveResult CreateResult(ResolveResult targetResolveResult, List<LookupGroup> lookupGroups, string name, IList<IType> typeArguments)
+		{
+			// Remove all hidden groups
+			lookupGroups.RemoveAll(g => g.AllHidden);
+			
+			if (lookupGroups.Count == 0) {
+				// No members found
+				return new UnknownMemberResolveResult(targetResolveResult.Type, name, typeArguments);
+			}
+			
+			if (lookupGroups.Any(g => !g.MethodsAreHidden && g.Methods.Count > 0)) {
+				// If there are methods, make a MethodGroupResolveResult.
+				// Note that a conflict between a member and a method (possible with multiple interface inheritance)
+				// is only a warning, not an error, and the C# compiler will prefer the method group.
+				List<MethodListWithDeclaringType> methodLists = new List<MethodListWithDeclaringType>();
+				foreach (var lookupGroup in lookupGroups) {
+					if (!lookupGroup.MethodsAreHidden && lookupGroup.Methods.Count > 0) {
+						var methodListWithDeclType = new MethodListWithDeclaringType(lookupGroup.DeclaringType);
+						foreach (var method in lookupGroup.Methods) {
+							methodListWithDeclType.Add((IMethod)method);
+						}
+						methodLists.Add(methodListWithDeclType);
+					}
+				}
+				
+				return new MethodGroupResolveResult(targetResolveResult, name, methodLists, typeArguments);
+			}
+			
+			// If there are ambiguities, report the most-derived result (last group)
+			LookupGroup resultGroup = lookupGroups[lookupGroups.Count - 1];
+			if (resultGroup.NestedTypes != null && resultGroup.NestedTypes.Count > 0) {
+				if (resultGroup.NestedTypes.Count > 1 || !resultGroup.NonMethodIsHidden || lookupGroups.Count > 1)
+					return new AmbiguousTypeResolveResult(resultGroup.NestedTypes[0]);
+				else
+					return new TypeResolveResult(resultGroup.NestedTypes[0]);
+			}
+			
+			if (resultGroup.NonMethod.IsStatic && targetResolveResult is ThisResolveResult) {
+				targetResolveResult = new TypeResolveResult(targetResolveResult.Type);
+			}
+			
+			if (lookupGroups.Count > 1) {
+				return new AmbiguousMemberResolveResult(targetResolveResult, resultGroup.NonMethod);
+			} else {
+				if (isInEnumMemberInitializer) {
+					IField field = resultGroup.NonMethod as IField;
+					if (field != null && field.DeclaringTypeDefinition != null && field.DeclaringTypeDefinition.Kind == TypeKind.Enum) {
+						return new MemberResolveResult(
+							targetResolveResult, field,
+							field.DeclaringTypeDefinition.EnumUnderlyingType,
+							field.IsConst, field.ConstantValue);
+					}
+				}
+				return new MemberResolveResult(targetResolveResult, resultGroup.NonMethod);
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/MethodGroupResolveResult.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/MethodGroupResolveResult.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/MethodGroupResolveResult.cs	(revision 11807)
@@ -0,0 +1,292 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// A method list that belongs to a declaring type.
+	/// </summary>
+	public class MethodListWithDeclaringType : List<IParameterizedMember>
+	{
+		readonly IType declaringType;
+		
+		/// <summary>
+		/// The declaring type.
+		/// </summary>
+		/// <remarks>
+		/// Not all methods in this list necessarily have this as their declaring type.
+		/// For example, this program:
+		/// <code>
+		///  class Base {
+		///    public virtual void M() {}
+		///  }
+		///  class Derived : Base {
+		///    public override void M() {}
+		///    public void M(int i) {}
+		///  }
+		/// </code>
+		/// results in two lists:
+		///  <c>new MethodListWithDeclaringType(Base) { Derived.M() }</c>,
+		///  <c>new MethodListWithDeclaringType(Derived) { Derived.M(int) }</c>
+		/// </remarks>
+		public IType DeclaringType {
+			get { return declaringType; }
+		}
+		
+		public MethodListWithDeclaringType(IType declaringType)
+		{
+			this.declaringType = declaringType;
+		}
+		
+		public MethodListWithDeclaringType(IType declaringType, IEnumerable<IParameterizedMember> methods)
+			: base(methods)
+		{
+			this.declaringType = declaringType;
+		}
+	}
+	
+	/// <summary>
+	/// Represents a group of methods.
+	/// A method reference used to create a delegate is resolved to a MethodGroupResolveResult.
+	/// The MethodGroupResolveResult has no type.
+	/// To retrieve the delegate type or the chosen overload, look at the method group conversion.
+	/// </summary>
+	public class MethodGroupResolveResult : ResolveResult
+	{
+		readonly IList<MethodListWithDeclaringType> methodLists;
+		readonly IList<IType> typeArguments;
+		readonly ResolveResult targetResult;
+		readonly string methodName;
+		
+		public MethodGroupResolveResult(ResolveResult targetResult, string methodName, IList<MethodListWithDeclaringType> methods, IList<IType> typeArguments) : base(SpecialType.UnknownType)
+		{
+			if (methods == null)
+				throw new ArgumentNullException("methods");
+			this.targetResult = targetResult;
+			this.methodName = methodName;
+			this.methodLists = methods;
+			this.typeArguments = typeArguments ?? EmptyList<IType>.Instance;
+		}
+		
+		/// <summary>
+		/// Gets the resolve result for the target object.
+		/// </summary>
+		public ResolveResult TargetResult {
+			get { return targetResult; }
+		}
+		
+		/// <summary>
+		/// Gets the type of the reference to the target object.
+		/// </summary>
+		public IType TargetType {
+			get { return targetResult != null ? targetResult.Type : SpecialType.UnknownType; }
+		}
+		
+		/// <summary>
+		/// Gets the name of the methods in this group.
+		/// </summary>
+		public string MethodName {
+			get { return methodName; }
+		}
+		
+		/// <summary>
+		/// Gets the methods that were found.
+		/// This list does not include extension methods.
+		/// </summary>
+		public IEnumerable<IMethod> Methods {
+			get { return methodLists.SelectMany(m => m.Cast<IMethod>()); }
+		}
+		
+		/// <summary>
+		/// Gets the methods that were found, grouped by their declaring type.
+		/// This list does not include extension methods.
+		/// Base types come first in the list.
+		/// </summary>
+		public IEnumerable<MethodListWithDeclaringType> MethodsGroupedByDeclaringType {
+			get { return methodLists; }
+		}
+		
+		/// <summary>
+		/// Gets the type arguments that were explicitly provided.
+		/// </summary>
+		public IList<IType> TypeArguments {
+			get { return typeArguments; }
+		}
+		
+		/// <summary>
+		/// List of extension methods, used to avoid re-calculating it in ResolveInvocation() when it was already
+		/// calculated by ResolveMemberAccess().
+		/// </summary>
+		internal List<List<IMethod>> extensionMethods;
+		
+		// the resolver is used to fetch extension methods on demand
+		internal CSharpResolver resolver;
+		
+		/// <summary>
+		/// Gets all candidate extension methods.
+		/// Note: this includes candidates that are not eligible due to an inapplicable
+		/// this argument.
+		/// The candidates will only be specialized if the type arguments were provided explicitly.
+		/// </summary>
+		/// <remarks>
+		/// The results are stored in nested lists because they are grouped by using scope.
+		/// That is, for "using SomeExtensions; namespace X { using MoreExtensions; ... }",
+		/// the return value will be
+		/// new List {
+		///    new List { all extensions from MoreExtensions },
+		///    new List { all extensions from SomeExtensions }
+		/// }
+		/// </remarks>
+		public IEnumerable<IEnumerable<IMethod>> GetExtensionMethods()
+		{
+			if (resolver != null) {
+				Debug.Assert(extensionMethods == null);
+				try {
+					extensionMethods = resolver.GetExtensionMethods(methodName, typeArguments);
+				} finally {
+					resolver = null;
+				}
+			}
+			return extensionMethods ?? Enumerable.Empty<IEnumerable<IMethod>>();
+		}
+		
+		/// <summary>
+		/// Gets the eligible extension methods.
+		/// </summary>
+		/// <param name="substituteInferredTypes">
+		/// Specifies whether to produce a <see cref="SpecializedMethod"/>
+		/// when type arguments could be inferred from <see cref="TargetType"/>.
+		/// This setting is only used for inferred types and has no effect if the type parameters are
+		/// specified explicitly.
+		/// </param>
+		/// <remarks>
+		/// The results are stored in nested lists because they are grouped by using scope.
+		/// That is, for "using SomeExtensions; namespace X { using MoreExtensions; ... }",
+		/// the return value will be
+		/// new List {
+		///    new List { all extensions from MoreExtensions },
+		///    new List { all extensions from SomeExtensions }
+		/// }
+		/// </remarks>
+		public IEnumerable<IEnumerable<IMethod>> GetEligibleExtensionMethods(bool substituteInferredTypes)
+		{
+			var result = new List<List<IMethod>>();
+			foreach (var methodGroup in GetExtensionMethods()) {
+				var outputGroup = new List<IMethod>();
+				foreach (var method in methodGroup) {
+					IType[] inferredTypes;
+					if (CSharpResolver.IsEligibleExtensionMethod(this.TargetType, method, true, out inferredTypes)) {
+						if (substituteInferredTypes && inferredTypes != null) {
+							outputGroup.Add(method.Specialize(new TypeParameterSubstitution(null, inferredTypes)));
+						} else {
+							outputGroup.Add(method);
+						}
+					}
+				}
+				if (outputGroup.Count > 0)
+					result.Add(outputGroup);
+			}
+			return result;
+		}
+		
+		public override string ToString()
+		{
+			return string.Format("[{0} with {1} method(s)]", GetType().Name, this.Methods.Count());
+		}
+		
+		public OverloadResolution PerformOverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null,
+		                                                    bool allowExtensionMethods = true,
+		                                                    bool allowExpandingParams = true, 
+		                                                    bool allowOptionalParameters = true,
+		                                                    bool checkForOverflow = false, CSharpConversions conversions = null)
+		{
+			Log.WriteLine("Performing overload resolution for " + this);
+			Log.WriteCollection("  Arguments: ", arguments);
+			
+			var typeArgumentArray = this.TypeArguments.ToArray();
+			OverloadResolution or = new OverloadResolution(compilation, arguments, argumentNames, typeArgumentArray, conversions);
+			or.AllowExpandingParams = allowExpandingParams;
+			or.AllowOptionalParameters = allowOptionalParameters;
+			or.CheckForOverflow = checkForOverflow;
+			
+			or.AddMethodLists(methodLists);
+			
+			if (allowExtensionMethods && !or.FoundApplicableCandidate) {
+				// No applicable match found, so let's try extension methods.
+				
+				var extensionMethods = this.GetExtensionMethods();
+				
+				if (extensionMethods.Any()) {
+					Log.WriteLine("No candidate is applicable, trying {0} extension methods groups...", extensionMethods.Count());
+					ResolveResult[] extArguments = new ResolveResult[arguments.Length + 1];
+					extArguments[0] = new ResolveResult(this.TargetType);
+					arguments.CopyTo(extArguments, 1);
+					string[] extArgumentNames = null;
+					if (argumentNames != null) {
+						extArgumentNames = new string[argumentNames.Length + 1];
+						argumentNames.CopyTo(extArgumentNames, 1);
+					}
+					var extOr = new OverloadResolution(compilation, extArguments, extArgumentNames, typeArgumentArray, conversions);
+					extOr.AllowExpandingParams = allowExpandingParams;
+					extOr.AllowOptionalParameters = allowOptionalParameters;
+					extOr.IsExtensionMethodInvocation = true;
+					extOr.CheckForOverflow = checkForOverflow;
+					
+					foreach (var g in extensionMethods) {
+						foreach (var method in g) {
+							Log.Indent();
+							OverloadResolutionErrors errors = extOr.AddCandidate(method);
+							Log.Unindent();
+							or.LogCandidateAddingResult("  Extension", method, errors);
+						}
+						if (extOr.FoundApplicableCandidate)
+							break;
+					}
+					// For the lack of a better comparison function (the one within OverloadResolution
+					// cannot be used as it depends on the argument set):
+					if (extOr.FoundApplicableCandidate || or.BestCandidate == null) {
+						// Consider an extension method result better than the normal result only
+						// if it's applicable; or if there is no normal result.
+						or = extOr;
+					}
+				}
+			}
+			Log.WriteLine("Overload resolution finished, best candidate is {0}.", or.GetBestCandidateWithSubstitutedTypeArguments());
+			return or;
+		}
+		
+		public override IEnumerable<ResolveResult> GetChildResults()
+		{
+			if (targetResult != null)
+				return new[] { targetResult };
+			else
+				return Enumerable.Empty<ResolveResult>();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/NodeListResolveVisitorNavigator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/NodeListResolveVisitorNavigator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/NodeListResolveVisitorNavigator.cs	(revision 11807)
@@ -0,0 +1,76 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// <see cref="IResolveVisitorNavigator"/> implementation that resolves a list of nodes.
+	/// We will skip all nodes which are not the target nodes or ancestors of the target nodes.
+	/// </summary>
+	public class NodeListResolveVisitorNavigator : IResolveVisitorNavigator
+	{
+		readonly Dictionary<AstNode, ResolveVisitorNavigationMode> dict = new Dictionary<AstNode, ResolveVisitorNavigationMode>();
+		
+		/// <summary>
+		/// Creates a new NodeListResolveVisitorNavigator that resolves the specified nodes.
+		/// </summary>
+		public NodeListResolveVisitorNavigator(params AstNode[] nodes)
+			: this((IEnumerable<AstNode>)nodes)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new NodeListResolveVisitorNavigator that resolves the specified nodes.
+		/// </summary>
+		public NodeListResolveVisitorNavigator(IEnumerable<AstNode> nodes, bool scanOnly = false)
+		{
+			if (nodes == null)
+				throw new ArgumentNullException("nodes");
+			foreach (var node in nodes) {
+				dict[node] = scanOnly ? ResolveVisitorNavigationMode.Scan : ResolveVisitorNavigationMode.Resolve;
+				for (var ancestor = node.Parent; ancestor != null && !dict.ContainsKey(ancestor); ancestor = ancestor.Parent) {
+					dict.Add(ancestor, ResolveVisitorNavigationMode.Scan);
+				}
+			}
+		}
+		
+		/// <inheritdoc/>
+		public virtual ResolveVisitorNavigationMode Scan(AstNode node)
+		{
+			ResolveVisitorNavigationMode mode;
+			if (dict.TryGetValue(node, out mode)) {
+				return mode;
+			} else {
+				return ResolveVisitorNavigationMode.Skip;
+			}
+		}
+		
+		public virtual void Resolved(AstNode node, ResolveResult result)
+		{
+		}
+		
+		public virtual void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/OverloadResolution.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/OverloadResolution.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/OverloadResolution.cs	(revision 11807)
@@ -0,0 +1,960 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// C# overload resolution (C# 4.0 spec: §7.5).
+	/// </summary>
+	public class OverloadResolution
+	{
+		sealed class Candidate
+		{
+			public readonly IParameterizedMember Member;
+			
+			/// <summary>
+			/// Returns the normal form candidate, if this is an expanded candidate.
+			/// </summary>
+			public readonly bool IsExpandedForm;
+			
+			/// <summary>
+			/// Gets the parameter types. In the first step, these are the types without any substition.
+			/// After type inference, substitutions will be performed.
+			/// </summary>
+			public readonly IType[] ParameterTypes;
+			
+			/// <summary>
+			/// argument index -> parameter index; -1 for arguments that could not be mapped
+			/// </summary>
+			public int[] ArgumentToParameterMap;
+			
+			public OverloadResolutionErrors Errors;
+			public int ErrorCount;
+			
+			public bool HasUnmappedOptionalParameters;
+			
+			public IType[] InferredTypes;
+			
+			/// <summary>
+			/// Gets the original member parameters (before any substitution!)
+			/// </summary>
+			public readonly IList<IParameter> Parameters;
+			
+			/// <summary>
+			/// Gets the original method type parameters (before any substitution!)
+			/// </summary>
+			public readonly IList<ITypeParameter> TypeParameters;
+			
+			/// <summary>
+			/// Conversions applied to the arguments.
+			/// This field is set by the CheckApplicability step.
+			/// </summary>
+			public Conversion[] ArgumentConversions;
+			
+			public bool IsGenericMethod {
+				get {
+					IMethod method = Member as IMethod;
+					return method != null && method.TypeParameters.Count > 0;
+				}
+			}
+			
+			public int ArgumentsPassedToParamsArray {
+				get {
+					int count = 0;
+					if (IsExpandedForm) {
+						int paramsParameterIndex = this.Parameters.Count - 1;
+						foreach (int parameterIndex in ArgumentToParameterMap) {
+							if (parameterIndex == paramsParameterIndex)
+								count++;
+						}
+					}
+					return count;
+				}
+			}
+			
+			public Candidate(IParameterizedMember member, bool isExpanded)
+			{
+				this.Member = member;
+				this.IsExpandedForm = isExpanded;
+				IParameterizedMember memberDefinition = (IParameterizedMember)member.MemberDefinition;
+				// For specificialized methods, go back to the original parameters:
+				// (without any type parameter substitution, not even class type parameters)
+				// We'll re-substitute them as part of RunTypeInference().
+				this.Parameters = memberDefinition.Parameters;
+				IMethod methodDefinition = memberDefinition as IMethod;
+				if (methodDefinition != null && methodDefinition.TypeParameters.Count > 0) {
+					this.TypeParameters = methodDefinition.TypeParameters;
+				}
+				this.ParameterTypes = new IType[this.Parameters.Count];
+			}
+			
+			public void AddError(OverloadResolutionErrors newError)
+			{
+				this.Errors |= newError;
+				if (!IsApplicable(newError))
+					this.ErrorCount++;
+			}
+		}
+		
+		readonly ICompilation compilation;
+		readonly ResolveResult[] arguments;
+		readonly string[] argumentNames;
+		readonly CSharpConversions conversions;
+		//List<Candidate> candidates = new List<Candidate>();
+		Candidate bestCandidate;
+		Candidate bestCandidateAmbiguousWith;
+		IType[] explicitlyGivenTypeArguments;
+		bool bestCandidateWasValidated;
+		OverloadResolutionErrors bestCandidateValidationResult;
+		
+		#region Constructor
+		public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			if (arguments == null)
+				throw new ArgumentNullException("arguments");
+			if (argumentNames == null)
+				argumentNames = new string[arguments.Length];
+			else if (argumentNames.Length != arguments.Length)
+				throw new ArgumentException("argumentsNames.Length must be equal to arguments.Length");
+			this.compilation = compilation;
+			this.arguments = arguments;
+			this.argumentNames = argumentNames;
+			
+			// keep explicitlyGivenTypeArguments==null when no type arguments were specified
+			if (typeArguments != null && typeArguments.Length > 0)
+				this.explicitlyGivenTypeArguments = typeArguments;
+			
+			this.conversions = conversions ?? CSharpConversions.Get(compilation);
+			this.AllowExpandingParams = true;
+			this.AllowOptionalParameters = true;
+		}
+		#endregion
+		
+		#region Input Properties
+		/// <summary>
+		/// Gets/Sets whether the methods are extension methods that are being called using extension method syntax.
+		/// </summary>
+		/// <remarks>
+		/// Setting this property to true restricts the possible conversions on the first argument to
+		/// implicit identity, reference, or boxing conversions.
+		/// </remarks>
+		public bool IsExtensionMethodInvocation { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether expanding 'params' into individual elements is allowed.
+		/// The default value is true.
+		/// </summary>
+		public bool AllowExpandingParams { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether optional parameters may be left at their default value.
+		/// The default value is true.
+		/// If this property is set to false, optional parameters will be treated like regular parameters.
+		/// </summary>
+		public bool AllowOptionalParameters { get; set; }
+		
+		/// <summary>
+		/// Gets/Sets whether ConversionResolveResults created by this OverloadResolution
+		/// instance apply overflow checking.
+		/// The default value is false.
+		/// </summary>
+		public bool CheckForOverflow { get; set; }
+		
+		/// <summary>
+		/// Gets the arguments for which this OverloadResolution instance was created.
+		/// </summary>
+		public IList<ResolveResult> Arguments {
+			get { return arguments; }
+		}
+		#endregion
+		
+		#region AddCandidate
+		/// <summary>
+		/// Adds a candidate to overload resolution.
+		/// </summary>
+		/// <param name="member">The candidate member to add.</param>
+		/// <returns>The errors that prevent the member from being applicable, if any.
+		/// Note: this method does not return errors that do not affect applicability.</returns>
+		public OverloadResolutionErrors AddCandidate(IParameterizedMember member)
+		{
+			return AddCandidate(member, OverloadResolutionErrors.None);
+		}
+		
+		/// <summary>
+		/// Adds a candidate to overload resolution.
+		/// </summary>
+		/// <param name="member">The candidate member to add.</param>
+		/// <param name="additionalErrors">Additional errors that apply to the candidate.
+		/// This is used to represent errors during member lookup (e.g. OverloadResolutionErrors.Inaccessible)
+		/// in overload resolution.</param>
+		/// <returns>The errors that prevent the member from being applicable, if any.
+		/// Note: this method does not return errors that do not affect applicability.</returns>
+		public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors)
+		{
+			if (member == null)
+				throw new ArgumentNullException("member");
+			
+			Candidate c = new Candidate(member, false);
+			c.AddError(additionalErrors);
+			if (CalculateCandidate(c)) {
+				//candidates.Add(c);
+			}
+			
+			if (this.AllowExpandingParams && member.Parameters.Count > 0
+			    && member.Parameters[member.Parameters.Count - 1].IsParams)
+			{
+				Candidate expandedCandidate = new Candidate(member, true);
+				expandedCandidate.AddError(additionalErrors);
+				// consider expanded form only if it isn't obviously wrong
+				if (CalculateCandidate(expandedCandidate)) {
+					//candidates.Add(expandedCandidate);
+					
+					if (expandedCandidate.ErrorCount < c.ErrorCount)
+						return expandedCandidate.Errors;
+				}
+			}
+			return c.Errors;
+		}
+		
+		/// <summary>
+		/// Calculates applicability etc. for the candidate.
+		/// </summary>
+		/// <returns>True if the calculation was successful, false if the candidate should be removed without reporting an error</returns>
+		bool CalculateCandidate(Candidate candidate)
+		{
+			if (!ResolveParameterTypes(candidate, false))
+				return false;
+			MapCorrespondingParameters(candidate);
+			RunTypeInference(candidate);
+			CheckApplicability(candidate);
+			ConsiderIfNewCandidateIsBest(candidate);
+			return true;
+		}
+		
+		bool ResolveParameterTypes(Candidate candidate, bool useSpecializedParameters)
+		{
+			for (int i = 0; i < candidate.Parameters.Count; i++) {
+				IType type;
+				if (useSpecializedParameters) {
+					// Use the parameter type of the specialized non-generic method or indexer
+					Debug.Assert(!candidate.IsGenericMethod);
+					type = candidate.Member.Parameters[i].Type;
+				} else {
+					// Use the type of the original formal parameter
+					type = candidate.Parameters[i].Type;
+				}
+				if (candidate.IsExpandedForm && i == candidate.Parameters.Count - 1) {
+					ArrayType arrayType = type as ArrayType;
+					if (arrayType != null && arrayType.Dimensions == 1)
+						type = arrayType.ElementType;
+					else
+						return false; // error: cannot unpack params-array. abort considering the expanded form for this candidate
+				}
+				candidate.ParameterTypes[i] = type;
+			}
+			return true;
+		}
+		#endregion
+		
+		#region AddMethodLists
+		/// <summary>
+		/// Adds all candidates from the method lists.
+		/// 
+		/// This method implements the logic that causes applicable methods in derived types to hide
+		/// all methods in base types.
+		/// </summary>
+		/// <param name="methodLists">The methods, grouped by declaring type. Base types must come first in the list.</param>
+		public void AddMethodLists(IList<MethodListWithDeclaringType> methodLists)
+		{
+			if (methodLists == null)
+				throw new ArgumentNullException("methodLists");
+			// Base types come first, so go through the list backwards (derived types first)
+			bool[] isHiddenByDerivedType;
+			if (methodLists.Count > 1)
+				isHiddenByDerivedType = new bool[methodLists.Count];
+			else
+				isHiddenByDerivedType = null;
+			for (int i = methodLists.Count - 1; i >= 0; i--) {
+				if (isHiddenByDerivedType != null && isHiddenByDerivedType[i]) {
+					Log.WriteLine("  Skipping methods in {0} because they are hidden by an applicable method in a derived type", methodLists[i].DeclaringType);
+					continue;
+				}
+				
+				MethodListWithDeclaringType methodList = methodLists[i];
+				bool foundApplicableCandidateInCurrentList = false;
+				
+				for (int j = 0; j < methodList.Count; j++) {
+					IParameterizedMember method = methodList[j];
+					Log.Indent();
+					OverloadResolutionErrors errors = AddCandidate(method);
+					Log.Unindent();
+					LogCandidateAddingResult("  Candidate", method, errors);
+					
+					foundApplicableCandidateInCurrentList |= IsApplicable(errors);
+				}
+				
+				if (foundApplicableCandidateInCurrentList && i > 0) {
+					foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes()) {
+						for (int j = 0; j < i; j++) {
+							if (!isHiddenByDerivedType[j] && baseType.Equals(methodLists[j].DeclaringType))
+								isHiddenByDerivedType[j] = true;
+						}
+					}
+				}
+			}
+		}
+		
+		[Conditional("DEBUG")]
+		internal void LogCandidateAddingResult(string text, IParameterizedMember method, OverloadResolutionErrors errors)
+		{
+			#if DEBUG
+			Log.WriteLine(string.Format("{0} {1} = {2}{3}",
+			                            text, method,
+			                            errors == OverloadResolutionErrors.None ? "Success" : errors.ToString(),
+			                            this.BestCandidate == method ? " (best candidate so far)" :
+			                            this.BestCandidateAmbiguousWith == method ? " (ambiguous)" : ""
+			                           ));
+			#endif
+		}
+		#endregion
+		
+		#region MapCorrespondingParameters
+		void MapCorrespondingParameters(Candidate candidate)
+		{
+			// C# 4.0 spec: §7.5.1.1 Corresponding parameters
+			candidate.ArgumentToParameterMap = new int[arguments.Length];
+			for (int i = 0; i < arguments.Length; i++) {
+				candidate.ArgumentToParameterMap[i] = -1;
+				if (argumentNames[i] == null) {
+					// positional argument
+					if (i < candidate.ParameterTypes.Length) {
+						candidate.ArgumentToParameterMap[i] = i;
+					} else if (candidate.IsExpandedForm) {
+						candidate.ArgumentToParameterMap[i] = candidate.ParameterTypes.Length - 1;
+					} else {
+						candidate.AddError(OverloadResolutionErrors.TooManyPositionalArguments);
+					}
+				} else {
+					// named argument
+					for (int j = 0; j < candidate.Parameters.Count; j++) {
+						if (argumentNames[i] == candidate.Parameters[j].Name) {
+							candidate.ArgumentToParameterMap[i] = j;
+						}
+					}
+					if (candidate.ArgumentToParameterMap[i] < 0)
+						candidate.AddError(OverloadResolutionErrors.NoParameterFoundForNamedArgument);
+				}
+			}
+		}
+		#endregion
+		
+		#region RunTypeInference
+		void RunTypeInference(Candidate candidate)
+		{
+			if (candidate.TypeParameters == null) {
+				if (explicitlyGivenTypeArguments != null) {
+					// method does not expect type arguments, but was given some
+					candidate.AddError(OverloadResolutionErrors.WrongNumberOfTypeArguments);
+				}
+				// Grab new parameter types:
+				ResolveParameterTypes(candidate, true);
+				return;
+			}
+			ParameterizedType parameterizedDeclaringType = candidate.Member.DeclaringType as ParameterizedType;
+			IList<IType> classTypeArguments;
+			if (parameterizedDeclaringType != null) {
+				classTypeArguments = parameterizedDeclaringType.TypeArguments;
+			} else {
+				classTypeArguments = null;
+			}
+			// The method is generic:
+			if (explicitlyGivenTypeArguments != null) {
+				if (explicitlyGivenTypeArguments.Length == candidate.TypeParameters.Count) {
+					candidate.InferredTypes = explicitlyGivenTypeArguments;
+				} else {
+					candidate.AddError(OverloadResolutionErrors.WrongNumberOfTypeArguments);
+					// wrong number of type arguments given, so truncate the list or pad with UnknownType
+					candidate.InferredTypes = new IType[candidate.TypeParameters.Count];
+					for (int i = 0; i < candidate.InferredTypes.Length; i++) {
+						if (i < explicitlyGivenTypeArguments.Length)
+							candidate.InferredTypes[i] = explicitlyGivenTypeArguments[i];
+						else
+							candidate.InferredTypes[i] = SpecialType.UnknownType;
+					}
+				}
+			} else {
+				TypeInference ti = new TypeInference(compilation, conversions);
+				bool success;
+				candidate.InferredTypes = ti.InferTypeArguments(candidate.TypeParameters, arguments, candidate.ParameterTypes, out success, classTypeArguments);
+				if (!success)
+					candidate.AddError(OverloadResolutionErrors.TypeInferenceFailed);
+			}
+			// Now substitute in the formal parameters:
+			var substitution = new ConstraintValidatingSubstitution(classTypeArguments, candidate.InferredTypes, this);
+			for (int i = 0; i < candidate.ParameterTypes.Length; i++) {
+				candidate.ParameterTypes[i] = candidate.ParameterTypes[i].AcceptVisitor(substitution);
+			}
+			if (!substitution.ConstraintsValid)
+				candidate.AddError(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint);
+		}
+		
+		sealed class ConstraintValidatingSubstitution : TypeParameterSubstitution
+		{
+			readonly CSharpConversions conversions;
+			public bool ConstraintsValid = true;
+			
+			public ConstraintValidatingSubstitution(IList<IType> classTypeArguments, IList<IType> methodTypeArguments, OverloadResolution overloadResolution)
+				: base(classTypeArguments, methodTypeArguments)
+			{
+				this.conversions = overloadResolution.conversions;
+			}
+			
+			public override IType VisitParameterizedType(ParameterizedType type)
+			{
+				IType newType = base.VisitParameterizedType(type);
+				if (newType != type && ConstraintsValid) {
+					// something was changed, so we need to validate the constraints
+					ParameterizedType newParameterizedType = newType as ParameterizedType;
+					if (newParameterizedType != null) {
+						// C# 4.0 spec: §4.4.4 Satisfying constraints
+						var typeParameters = newParameterizedType.GetDefinition().TypeParameters;
+						var substitution = newParameterizedType.GetSubstitution();
+						for (int i = 0; i < typeParameters.Count; i++) {
+							if (!ValidateConstraints(typeParameters[i], newParameterizedType.GetTypeArgument(i), substitution, conversions)) {
+								ConstraintsValid = false;
+								break;
+							}
+						}
+					}
+				}
+				return newType;
+			}
+		}
+		#endregion
+		
+		#region Validate Constraints
+		OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate)
+		{
+			// If type inference already failed, we won't check the constraints:
+			if ((candidate.Errors & OverloadResolutionErrors.TypeInferenceFailed) != 0)
+				return OverloadResolutionErrors.None;
+			
+			if (candidate.TypeParameters == null || candidate.TypeParameters.Count == 0)
+				return OverloadResolutionErrors.None; // the method isn't generic
+			var substitution = GetSubstitution(candidate);
+			for (int i = 0; i < candidate.TypeParameters.Count; i++) {
+				if (!ValidateConstraints(candidate.TypeParameters[i], substitution.MethodTypeArguments[i], substitution))
+					return OverloadResolutionErrors.MethodConstraintsNotSatisfied;
+			}
+			return OverloadResolutionErrors.None;
+		}
+		
+		/// <summary>
+		/// Validates whether the given type argument satisfies the constraints for the given type parameter.
+		/// </summary>
+		/// <param name="typeParameter">The type parameter.</param>
+		/// <param name="typeArgument">The type argument.</param>
+		/// <param name="substitution">The substitution that defines how type parameters are replaced with type arguments.
+		/// The substitution is used to check constraints that depend on other type parameters (or recursively on the same type parameter).
+		/// May be null if no substitution should be used.</param>
+		/// <returns>True if the constraints are satisfied; false otherwise.</returns>
+		public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null)
+		{
+			if (typeParameter == null)
+				throw new ArgumentNullException("typeParameter");
+			if (typeArgument == null)
+				throw new ArgumentNullException("typeArgument");
+			return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation));
+		}
+		
+		internal static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution, CSharpConversions conversions)
+		{
+			switch (typeArgument.Kind) { // void, null, and pointers cannot be used as type arguments
+				case TypeKind.Void:
+				case TypeKind.Null:
+				case TypeKind.Pointer:
+					return false;
+			}
+			if (typeParameter.HasReferenceTypeConstraint) {
+				if (typeArgument.IsReferenceType != true)
+					return false;
+			}
+			if (typeParameter.HasValueTypeConstraint) {
+				if (!NullableType.IsNonNullableValueType(typeArgument))
+					return false;
+			}
+			if (typeParameter.HasDefaultConstructorConstraint) {
+				ITypeDefinition def = typeArgument.GetDefinition();
+				if (def != null && def.IsAbstract)
+					return false;
+				var ctors = typeArgument.GetConstructors(
+					m => m.Parameters.Count == 0 && m.Accessibility == Accessibility.Public,
+					GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions
+				);
+				if (!ctors.Any())
+					return false;
+			}
+			foreach (IType constraintType in typeParameter.DirectBaseTypes) {
+				IType c = constraintType;
+				if (substitution != null)
+					c = c.AcceptVisitor(substitution);
+				if (!conversions.IsConstraintConvertible(typeArgument, c))
+					return false;
+			}
+			return true;
+		}
+		#endregion
+		
+		#region CheckApplicability
+		/// <summary>
+		/// Returns whether a candidate with the given errors is still considered to be applicable.
+		/// </summary>
+		public static bool IsApplicable(OverloadResolutionErrors errors)
+		{
+			const OverloadResolutionErrors errorsThatDoNotMatterForApplicability =
+				OverloadResolutionErrors.AmbiguousMatch | OverloadResolutionErrors.MethodConstraintsNotSatisfied;
+			return (errors & ~errorsThatDoNotMatterForApplicability) == OverloadResolutionErrors.None;
+		}
+		
+		void CheckApplicability(Candidate candidate)
+		{
+			// C# 4.0 spec: §7.5.3.1 Applicable function member
+			
+			// Test whether parameters were mapped the correct number of arguments:
+			int[] argumentCountPerParameter = new int[candidate.ParameterTypes.Length];
+			foreach (int parameterIndex in candidate.ArgumentToParameterMap) {
+				if (parameterIndex >= 0)
+					argumentCountPerParameter[parameterIndex]++;
+			}
+			for (int i = 0; i < argumentCountPerParameter.Length; i++) {
+				if (candidate.IsExpandedForm && i == argumentCountPerParameter.Length - 1)
+					continue; // any number of arguments is fine for the params-array
+				if (argumentCountPerParameter[i] == 0) {
+					if (this.AllowOptionalParameters && candidate.Parameters[i].IsOptional)
+						candidate.HasUnmappedOptionalParameters = true;
+					else
+						candidate.AddError(OverloadResolutionErrors.MissingArgumentForRequiredParameter);
+				} else if (argumentCountPerParameter[i] > 1) {
+					candidate.AddError(OverloadResolutionErrors.MultipleArgumentsForSingleParameter);
+				}
+			}
+			
+			candidate.ArgumentConversions = new Conversion[arguments.Length];
+			// Test whether argument passing mode matches the parameter passing mode
+			for (int i = 0; i < arguments.Length; i++) {
+				int parameterIndex = candidate.ArgumentToParameterMap[i];
+				if (parameterIndex < 0) {
+					candidate.ArgumentConversions[i] = Conversion.None;
+					continue;
+				}
+				
+				ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult;
+				if (brrr != null) {
+					if ((brrr.IsOut && !candidate.Parameters[parameterIndex].IsOut) || (brrr.IsRef && !candidate.Parameters[parameterIndex].IsRef))
+						candidate.AddError(OverloadResolutionErrors.ParameterPassingModeMismatch);
+				} else {
+					if (candidate.Parameters[parameterIndex].IsOut || candidate.Parameters[parameterIndex].IsRef)
+						candidate.AddError(OverloadResolutionErrors.ParameterPassingModeMismatch);
+				}
+				IType parameterType = candidate.ParameterTypes[parameterIndex];
+				Conversion c = conversions.ImplicitConversion(arguments[i], parameterType);
+				candidate.ArgumentConversions[i] = c;
+				if (IsExtensionMethodInvocation && parameterIndex == 0) {
+					// First parameter to extension method must be an identity, reference or boxing conversion
+					if (!(c == Conversion.IdentityConversion || c == Conversion.ImplicitReferenceConversion || c == Conversion.BoxingConversion))
+						candidate.AddError(OverloadResolutionErrors.ArgumentTypeMismatch);
+				} else {
+					if ((!c.IsValid && !c.IsUserDefined && !c.IsMethodGroupConversion) && parameterType.Kind != TypeKind.Unknown)
+						candidate.AddError(OverloadResolutionErrors.ArgumentTypeMismatch);
+				}
+			}
+		}
+		#endregion
+		
+		#region BetterFunctionMember
+		/// <summary>
+		/// Returns 1 if c1 is better than c2; 2 if c2 is better than c1; or 0 if neither is better.
+		/// </summary>
+		int BetterFunctionMember(Candidate c1, Candidate c2)
+		{
+			// prefer applicable members (part of heuristic that produces a best candidate even if none is applicable)
+			if (c1.ErrorCount == 0 && c2.ErrorCount > 0)
+				return 1;
+			if (c1.ErrorCount > 0 && c2.ErrorCount == 0)
+				return 2;
+			
+			// C# 4.0 spec: §7.5.3.2 Better function member
+			bool c1IsBetter = false;
+			bool c2IsBetter = false;
+			for (int i = 0; i < arguments.Length; i++) {
+				int p1 = c1.ArgumentToParameterMap[i];
+				int p2 = c2.ArgumentToParameterMap[i];
+				if (p1 >= 0 && p2 < 0) {
+					c1IsBetter = true;
+				} else if (p1 < 0 && p2 >= 0) {
+					c2IsBetter = true;
+				} else if (p1 >= 0 && p2 >= 0) {
+					switch (conversions.BetterConversion(arguments[i], c1.ParameterTypes[p1], c2.ParameterTypes[p2])) {
+						case 1:
+							c1IsBetter = true;
+							break;
+						case 2:
+							c2IsBetter = true;
+							break;
+					}
+				}
+			}
+			if (c1IsBetter && !c2IsBetter)
+				return 1;
+			if (!c1IsBetter && c2IsBetter)
+				return 2;
+			
+			// prefer members with less errors (part of heuristic that produces a best candidate even if none is applicable)
+			if (c1.ErrorCount < c2.ErrorCount) return 1;
+			if (c1.ErrorCount > c2.ErrorCount) return 2;
+			
+			if (!c1IsBetter && !c2IsBetter) {
+				// we need the tie-breaking rules
+				
+				// non-generic methods are better
+				if (!c1.IsGenericMethod && c2.IsGenericMethod)
+					return 1;
+				else if (c1.IsGenericMethod && !c2.IsGenericMethod)
+					return 2;
+				
+				// non-expanded members are better
+				if (!c1.IsExpandedForm && c2.IsExpandedForm)
+					return 1;
+				else if (c1.IsExpandedForm && !c2.IsExpandedForm)
+					return 2;
+				
+				// prefer the member with less arguments mapped to the params-array
+				int r = c1.ArgumentsPassedToParamsArray.CompareTo(c2.ArgumentsPassedToParamsArray);
+				if (r < 0) return 1;
+				else if (r > 0) return 2;
+				
+				// prefer the member where no default values need to be substituted
+				if (!c1.HasUnmappedOptionalParameters && c2.HasUnmappedOptionalParameters)
+					return 1;
+				else if (c1.HasUnmappedOptionalParameters && !c2.HasUnmappedOptionalParameters)
+					return 2;
+				
+				// compare the formal parameters
+				r = MoreSpecificFormalParameters(c1, c2);
+				if (r != 0)
+					return r;
+				
+				// prefer non-lifted operators
+				ILiftedOperator lift1 = c1.Member as ILiftedOperator;
+				ILiftedOperator lift2 = c2.Member as ILiftedOperator;
+				if (lift1 == null && lift2 != null)
+					return 1;
+				if (lift1 != null && lift2 == null)
+					return 2;
+			}
+			return 0;
+		}
+		
+		/// <summary>
+		/// Implement this interface to give overload resolution a hint that the member represents a lifted operator,
+		/// which is used in the tie-breaking rules.
+		/// </summary>
+		public interface ILiftedOperator : IParameterizedMember
+		{
+			IList<IParameter> NonLiftedParameters { get; }
+		}
+		
+		int MoreSpecificFormalParameters(Candidate c1, Candidate c2)
+		{
+			// prefer the member with more formal parmeters (in case both have different number of optional parameters)
+			int r = c1.Parameters.Count.CompareTo(c2.Parameters.Count);
+			if (r > 0) return 1;
+			else if (r < 0) return 2;
+			
+			return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type), c2.Parameters.Select(p => p.Type));
+		}
+		
+		static int MoreSpecificFormalParameters(IEnumerable<IType> t1, IEnumerable<IType> t2)
+		{
+			bool c1IsBetter = false;
+			bool c2IsBetter = false;
+			foreach (var pair in t1.Zip(t2, (a,b) => new { Item1 = a, Item2 = b })) {
+				switch (MoreSpecificFormalParameter(pair.Item1, pair.Item2)) {
+					case 1:
+						c1IsBetter = true;
+						break;
+					case 2:
+						c2IsBetter = true;
+						break;
+				}
+			}
+			if (c1IsBetter && !c2IsBetter)
+				return 1;
+			if (!c1IsBetter && c2IsBetter)
+				return 2;
+			return 0;
+		}
+		
+		static int MoreSpecificFormalParameter(IType t1, IType t2)
+		{
+			if ((t1 is ITypeParameter) && !(t2 is ITypeParameter))
+				return 2;
+			if ((t2 is ITypeParameter) && !(t1 is ITypeParameter))
+				return 1;
+			
+			ParameterizedType p1 = t1 as ParameterizedType;
+			ParameterizedType p2 = t2 as ParameterizedType;
+			if (p1 != null && p2 != null && p1.TypeParameterCount == p2.TypeParameterCount) {
+				int r = MoreSpecificFormalParameters(p1.TypeArguments, p2.TypeArguments);
+				if (r > 0)
+					return r;
+			}
+			TypeWithElementType tew1 = t1 as TypeWithElementType;
+			TypeWithElementType tew2 = t2 as TypeWithElementType;
+			if (tew1 != null && tew2 != null) {
+				return MoreSpecificFormalParameter(tew1.ElementType, tew2.ElementType);
+			}
+			return 0;
+		}
+		#endregion
+		
+		#region ConsiderIfNewCandidateIsBest
+		void ConsiderIfNewCandidateIsBest(Candidate candidate)
+		{
+			if (bestCandidate == null) {
+				bestCandidate = candidate;
+				bestCandidateWasValidated = false;
+			} else {
+				switch (BetterFunctionMember(candidate, bestCandidate)) {
+					case 0:
+						// Overwrite 'bestCandidateAmbiguousWith' so that API users can
+						// detect the set of all ambiguous methods if they look at
+						// bestCandidateAmbiguousWith after each step.
+						bestCandidateAmbiguousWith = candidate;
+						break;
+					case 1:
+						bestCandidate = candidate;
+						bestCandidateWasValidated = false;
+						bestCandidateAmbiguousWith = null;
+						break;
+						// case 2: best candidate stays best
+				}
+			}
+		}
+		#endregion
+		
+		#region Output Properties
+		public IParameterizedMember BestCandidate {
+			get { return bestCandidate != null ? bestCandidate.Member : null; }
+		}
+		
+		/// <summary>
+		/// Returns the errors that apply to the best candidate.
+		/// This includes additional errors that do not affect applicability (e.g. AmbiguousMatch, MethodConstraintsNotSatisfied)
+		/// </summary>
+		public OverloadResolutionErrors BestCandidateErrors {
+			get {
+				if (bestCandidate == null)
+					return OverloadResolutionErrors.None;
+				if (!bestCandidateWasValidated) {
+					bestCandidateValidationResult = ValidateMethodConstraints(bestCandidate);
+					bestCandidateWasValidated = true;
+				}
+				OverloadResolutionErrors err = bestCandidate.Errors | bestCandidateValidationResult;
+				if (bestCandidateAmbiguousWith != null)
+					err |= OverloadResolutionErrors.AmbiguousMatch;
+				return err;
+			}
+		}
+		
+		public bool FoundApplicableCandidate {
+			get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); }
+		}
+		
+		public IParameterizedMember BestCandidateAmbiguousWith {
+			get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; }
+		}
+		
+		public bool BestCandidateIsExpandedForm {
+			get { return bestCandidate != null ? bestCandidate.IsExpandedForm : false; }
+		}
+		
+		public bool IsAmbiguous {
+			get { return bestCandidateAmbiguousWith != null; }
+		}
+		
+		public IList<IType> InferredTypeArguments {
+			get {
+				if (bestCandidate != null && bestCandidate.InferredTypes != null)
+					return bestCandidate.InferredTypes;
+				else
+					return EmptyList<IType>.Instance;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the implicit conversions that are being applied to the arguments.
+		/// </summary>
+		public IList<Conversion> ArgumentConversions {
+			get {
+				if (bestCandidate != null && bestCandidate.ArgumentConversions != null)
+					return bestCandidate.ArgumentConversions;
+				else
+					return Enumerable.Repeat(Conversion.None, arguments.Length).ToList();
+			}
+		}
+		
+		/// <summary>
+		/// Gets an array that maps argument indices to parameter indices.
+		/// For arguments that could not be mapped to any parameter, the value will be -1.
+		/// 
+		/// parameterIndex = GetArgumentToParameterMap()[argumentIndex]
+		/// </summary>
+		public IList<int> GetArgumentToParameterMap()
+		{
+			if (bestCandidate != null)
+				return bestCandidate.ArgumentToParameterMap;
+			else
+				return null;
+		}
+		
+		/// <summary>
+		/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
+		/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
+		/// to them when calling the method.
+		/// </summary>
+		public IList<ResolveResult> GetArgumentsWithConversions()
+		{
+			if (bestCandidate == null)
+				return arguments;
+			else
+				return GetArgumentsWithConversions(null, null);
+		}
+		
+		/// <summary>
+		/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
+		/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
+		/// to them when calling the method.
+		/// For arguments where an explicit argument name was provided, the argument will
+		/// be wrapped in a <see cref="NamedArgumentResolveResult"/>.
+		/// </summary>
+		public IList<ResolveResult> GetArgumentsWithConversionsAndNames()
+		{
+			if (bestCandidate == null)
+				return arguments;
+			else
+				return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments());
+		}
+		
+		IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments)
+		{
+			var conversions = this.ArgumentConversions;
+			ResolveResult[] args = new ResolveResult[arguments.Length];
+			for (int i = 0; i < args.Length; i++) {
+				var argument = arguments[i];
+				if (this.IsExtensionMethodInvocation && i == 0 && targetResolveResult != null)
+					argument = targetResolveResult;
+				int parameterIndex = bestCandidate.ArgumentToParameterMap[i];
+				if (parameterIndex >= 0 && conversions[i] != Conversion.IdentityConversion) {
+					// Wrap argument in ConversionResolveResult
+					IType parameterType = bestCandidate.ParameterTypes[parameterIndex];
+					if (parameterType.Kind != TypeKind.Unknown) {
+						if (arguments[i].IsCompileTimeConstant && conversions[i].IsValid && !conversions[i].IsUserDefined) {
+							argument = new CSharpResolver(compilation).WithCheckForOverflow(CheckForOverflow).ResolveCast(parameterType, argument);
+						} else {
+							argument = new ConversionResolveResult(parameterType, argument, conversions[i], CheckForOverflow);
+						}
+					}
+				}
+				if (bestCandidateForNamedArguments != null && argumentNames[i] != null) {
+					// Wrap argument in NamedArgumentResolveResult
+					if (parameterIndex >= 0) {
+						argument = new NamedArgumentResolveResult(bestCandidateForNamedArguments.Parameters[parameterIndex], argument, bestCandidateForNamedArguments);
+					} else {
+						argument = new NamedArgumentResolveResult(argumentNames[i], argument);
+					}
+				}
+				args[i] = argument;
+			}
+			return args;
+		}
+		
+		public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments()
+		{
+			if (bestCandidate == null)
+				return null;
+			IMethod method = bestCandidate.Member as IMethod;
+			if (method != null && method.TypeParameters.Count > 0) {
+				return ((IMethod)method.MemberDefinition).Specialize(GetSubstitution(bestCandidate));
+			} else {
+				return bestCandidate.Member;
+			}
+		}
+		
+		TypeParameterSubstitution GetSubstitution(Candidate candidate)
+		{
+			// Do not compose the substitutions, but merge them.
+			// This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce
+			return new TypeParameterSubstitution(candidate.Member.Substitution.ClassTypeArguments, candidate.InferredTypes);
+		}
+		
+		/// <summary>
+		/// Creates a ResolveResult representing the result of overload resolution.
+		/// </summary>
+		/// <param name="targetResolveResult">
+		/// The target expression of the call. May be <c>null</c> for static methods/constructors.
+		/// </param>
+		/// <param name="initializerStatements">
+		/// Statements for Objects/Collections initializer.
+		/// <see cref="InvocationResolveResult.InitializerStatements"/>
+		/// <param name="returnTypeOverride">
+		/// If not null, use this instead of the ReturnType of the member as the type of the created resolve result.
+		/// </param>
+		public CSharpInvocationResolveResult CreateResolveResult(ResolveResult targetResolveResult, IList<ResolveResult> initializerStatements = null, IType returnTypeOverride = null)
+		{
+			IParameterizedMember member = GetBestCandidateWithSubstitutedTypeArguments();
+			if (member == null)
+				throw new InvalidOperationException();
+
+			return new CSharpInvocationResolveResult(
+				this.IsExtensionMethodInvocation ? new TypeResolveResult(member.DeclaringType) : targetResolveResult,
+				member,
+				GetArgumentsWithConversions(targetResolveResult, member),
+				this.BestCandidateErrors,
+				this.IsExtensionMethodInvocation,
+				this.BestCandidateIsExpandedForm,
+				isDelegateInvocation: false,
+				argumentToParameterMap: this.GetArgumentToParameterMap(),
+				initializerStatements: initializerStatements,
+				returnTypeOverride: returnTypeOverride);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/OverloadResolutionErrors.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/OverloadResolutionErrors.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/OverloadResolutionErrors.cs	(revision 11807)
@@ -0,0 +1,87 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	[Flags]
+	public enum OverloadResolutionErrors
+	{
+		None = 0,
+		/// <summary>
+		/// Too many positional arguments (some could not be mapped to any parameter).
+		/// </summary>
+		TooManyPositionalArguments = 0x0001,
+		/// <summary>
+		/// A named argument could not be mapped to any parameter
+		/// </summary>
+		NoParameterFoundForNamedArgument = 0x0002,
+		/// <summary>
+		/// Type inference failed for a generic method.
+		/// </summary>
+		TypeInferenceFailed = 0x0004,
+		/// <summary>
+		/// Type arguments were explicitly specified, but did not match the number of type parameters.
+		/// </summary>
+		WrongNumberOfTypeArguments = 0x0008,
+		/// <summary>
+		/// After substituting type parameters with the inferred types; a constructed type within the formal parameters
+		/// does not satisfy its constraint.
+		/// </summary>
+		ConstructedTypeDoesNotSatisfyConstraint = 0x0010,
+		/// <summary>
+		/// No argument was mapped to a non-optional parameter
+		/// </summary>
+		MissingArgumentForRequiredParameter = 0x0020,
+		/// <summary>
+		/// Several arguments were mapped to a single (non-params-array) parameter
+		/// </summary>
+		MultipleArgumentsForSingleParameter = 0x0040,
+		/// <summary>
+		/// 'ref'/'out' passing mode doesn't match for at least 1 parameter
+		/// </summary>
+		ParameterPassingModeMismatch = 0x0080,
+		/// <summary>
+		/// Argument type cannot be converted to parameter type
+		/// </summary>
+		ArgumentTypeMismatch = 0x0100,
+		/// <summary>
+		/// There is no unique best overload.
+		/// This error does not apply to any single candidate, but only to the overall result of overload resolution.
+		/// </summary>
+		/// <remarks>
+		/// This error does not prevent a candidate from being applicable.
+		/// </remarks>
+		AmbiguousMatch = 0x0200,
+		/// <summary>
+		/// The member is not accessible.
+		/// </summary>
+		/// <remarks>
+		/// This error is generated by member lookup; not by overload resolution.
+		/// </remarks>
+		Inaccessible = 0x0400,
+		/// <summary>
+		/// A generic method 
+		/// </summary>
+		/// <remarks>
+		/// This error does not prevent a candidate from being applicable.
+		/// </remarks>
+		MethodConstraintsNotSatisfied = 0x0800
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ReducedExtensionMethod.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ReducedExtensionMethod.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ReducedExtensionMethod.cs	(revision 11807)
@@ -0,0 +1,455 @@
+﻿//
+// ReducedExtensionMethod.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	/// <summary>
+	/// An invocated extension method hides the extension parameter in its parameter list.
+	/// It's used to hide the internals of extension method invocation in certain situation to simulate the
+	/// syntactic way of writing extension methods on semantic level.
+	/// </summary>
+	public class ReducedExtensionMethod : IMethod
+	{
+		readonly IMethod baseMethod;
+
+		public ReducedExtensionMethod(IMethod baseMethod)
+		{
+			this.baseMethod = baseMethod;
+		}
+
+		public override bool Equals(object obj)
+		{
+			var other = obj as ReducedExtensionMethod;
+			if (other == null)
+				return false;
+			return baseMethod.Equals(other.baseMethod);
+		}
+		
+		public override int GetHashCode()
+		{
+			unchecked {
+				return baseMethod.GetHashCode() + 1;
+			}
+		}
+
+		public override string ToString()
+		{
+			return string.Format("[ReducedExtensionMethod: ReducedFrom={0}]", ReducedFrom);
+		}
+
+		#region IMember implementation
+
+		[Serializable]
+		public sealed class ReducedExtensionMethodMemberReference : IMemberReference
+		{
+			readonly IMethod baseMethod;
+
+			public ReducedExtensionMethodMemberReference (IMethod baseMethod)
+			{
+				this.baseMethod = baseMethod;
+			}
+
+			public IMember Resolve(ITypeResolveContext context)
+			{
+				return new ReducedExtensionMethod ((IMethod)baseMethod.ToReference ().Resolve (context));
+			}
+			
+			ISymbol ISymbolReference.Resolve(ITypeResolveContext context)
+			{
+				return Resolve(context);
+			}
+
+			public ITypeReference DeclaringTypeReference {
+				get {
+					return baseMethod.ToReference ().DeclaringTypeReference;
+				}
+			}
+		}
+
+		public IMemberReference ToMemberReference()
+		{
+			return new ReducedExtensionMethodMemberReference (baseMethod);
+		}
+		
+		public IMemberReference ToReference()
+		{
+			return new ReducedExtensionMethodMemberReference (baseMethod);
+		}
+		
+		ISymbolReference ISymbol.ToReference()
+		{
+			return ToReference();
+		}
+
+		public IMember MemberDefinition {
+			get {
+				return baseMethod.MemberDefinition;
+			}
+		}
+
+		public IUnresolvedMember UnresolvedMember {
+			get {
+				return baseMethod.UnresolvedMember;
+			}
+		}
+
+		public IType ReturnType {
+			get {
+				return baseMethod.ReturnType;
+			}
+		}
+
+		public System.Collections.Generic.IList<IMember> ImplementedInterfaceMembers {
+			get {
+				return baseMethod.ImplementedInterfaceMembers;
+			}
+		}
+
+		public bool IsExplicitInterfaceImplementation {
+			get {
+				return baseMethod.IsExplicitInterfaceImplementation;
+			}
+		}
+
+		public bool IsVirtual {
+			get {
+				return baseMethod.IsVirtual;
+			}
+		}
+
+		public bool IsOverride {
+			get {
+				return baseMethod.IsOverride;
+			}
+		}
+
+		public bool IsOverridable {
+			get {
+				return baseMethod.IsOverridable;
+			}
+		}
+
+		public TypeParameterSubstitution Substitution {
+			get {
+				return baseMethod.Substitution;
+			}
+		}
+
+		public IMethod Specialize(TypeParameterSubstitution substitution)
+		{
+			return new ReducedExtensionMethod((IMethod)baseMethod.Specialize(substitution));
+		}
+		
+		IMember IMember.Specialize(TypeParameterSubstitution substitution)
+		{
+			return Specialize(substitution);
+		}
+		
+		public bool IsParameterized {
+			get  { return baseMethod.IsParameterized; }
+		}
+
+		#endregion
+
+		#region IMethod implementation
+
+		public System.Collections.Generic.IList<IUnresolvedMethod> Parts {
+			get {
+				return baseMethod.Parts;
+			}
+		}
+
+		public System.Collections.Generic.IList<IAttribute> ReturnTypeAttributes {
+			get {
+				return baseMethod.ReturnTypeAttributes;
+			}
+		}
+
+		public System.Collections.Generic.IList<ITypeParameter> TypeParameters {
+			get {
+				return baseMethod.TypeParameters;
+			}
+		}
+
+		public bool IsExtensionMethod {
+			get {
+				return true;
+			}
+		}
+
+		public bool IsConstructor {
+			get {
+				return baseMethod.IsConstructor;
+			}
+		}
+
+		public bool IsDestructor {
+			get {
+				return baseMethod.IsDestructor;
+			}
+		}
+
+		public bool IsOperator {
+			get {
+				return baseMethod.IsOperator;
+			}
+		}
+
+		public bool IsPartial {
+			get {
+				return baseMethod.IsPartial;
+			}
+		}
+
+		public bool IsAsync {
+			get {
+				return baseMethod.IsAsync;
+			}
+		}
+
+		public bool HasBody {
+			get {
+				return baseMethod.HasBody;
+			}
+		}
+
+		public bool IsAccessor {
+			get {
+				return baseMethod.IsAccessor;
+			}
+		}
+
+		public IMember AccessorOwner {
+			get {
+				return baseMethod.AccessorOwner;
+			}
+		}
+
+		public IMethod ReducedFrom {
+			get {
+				return baseMethod;
+			}
+		}
+
+		public IList<IType> TypeArguments {
+			get {
+				return baseMethod.TypeArguments;
+			}
+		}
+		#endregion
+
+		#region IParameterizedMember implementation
+		List<IParameter> parameters;
+		public System.Collections.Generic.IList<IParameter> Parameters {
+			get {
+				if (parameters == null)
+					parameters = new List<IParameter> (baseMethod.Parameters.Skip (1));
+				return parameters;
+			}
+		}
+
+		#endregion
+
+		#region IEntity implementation
+
+		public SymbolKind SymbolKind {
+			get {
+				return baseMethod.SymbolKind;
+			}
+		}
+
+		[Obsolete("Use the SymbolKind property instead.")]
+		public EntityType EntityType {
+			get {
+				return baseMethod.EntityType;
+			}
+		}
+		
+		public DomRegion Region {
+			get {
+				return baseMethod.Region;
+			}
+		}
+
+		public DomRegion BodyRegion {
+			get {
+				return baseMethod.BodyRegion;
+			}
+		}
+
+		public ITypeDefinition DeclaringTypeDefinition {
+			get {
+				return baseMethod.DeclaringTypeDefinition;
+			}
+		}
+
+		public IType DeclaringType {
+			get {
+				return baseMethod.DeclaringType;
+			}
+		}
+
+		public IAssembly ParentAssembly {
+			get {
+				return baseMethod.ParentAssembly;
+			}
+		}
+
+		public System.Collections.Generic.IList<IAttribute> Attributes {
+			get {
+				return baseMethod.Attributes;
+			}
+		}
+
+		public ICSharpCode.NRefactory.Documentation.DocumentationComment Documentation {
+			get {
+				return baseMethod.Documentation;
+			}
+		}
+
+		public bool IsStatic {
+			get {
+				return false;
+			}
+		}
+
+		public bool IsAbstract {
+			get {
+				return baseMethod.IsAbstract;
+			}
+		}
+
+		public bool IsSealed {
+			get {
+				return baseMethod.IsSealed;
+			}
+		}
+
+		public bool IsShadowing {
+			get {
+				return baseMethod.IsShadowing;
+			}
+		}
+
+		public bool IsSynthetic {
+			get {
+				return baseMethod.IsSynthetic;
+			}
+		}
+
+		#endregion
+
+		#region IHasAccessibility implementation
+
+		public Accessibility Accessibility {
+			get {
+				return baseMethod.Accessibility;
+			}
+		}
+
+		public bool IsPrivate {
+			get {
+				return baseMethod.IsPrivate;
+			}
+		}
+
+		public bool IsPublic {
+			get {
+				return baseMethod.IsPublic;
+			}
+		}
+
+		public bool IsProtected {
+			get {
+				return baseMethod.IsProtected;
+			}
+		}
+
+		public bool IsInternal {
+			get {
+				return baseMethod.IsInternal;
+			}
+		}
+
+		public bool IsProtectedOrInternal {
+			get {
+				return baseMethod.IsProtectedOrInternal;
+			}
+		}
+
+		public bool IsProtectedAndInternal {
+			get {
+				return baseMethod.IsProtectedAndInternal;
+			}
+		}
+
+		#endregion
+
+		#region INamedElement implementation
+
+		public string FullName {
+			get {
+				return baseMethod.FullName;
+			}
+		}
+
+		public string Name {
+			get {
+				return baseMethod.Name;
+			}
+		}
+
+		public string ReflectionName {
+			get {
+				return baseMethod.ReflectionName;
+			}
+		}
+
+		public string Namespace {
+			get {
+				return baseMethod.Namespace;
+			}
+		}
+
+		#endregion
+
+		#region ICompilationProvider implementation
+
+		public ICompilation Compilation {
+			get {
+				return baseMethod.Compilation;
+			}
+		}
+
+		#endregion
+	}
+}
+
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/RenameCallbackArguments.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/RenameCallbackArguments.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/RenameCallbackArguments.cs	(revision 11807)
@@ -0,0 +1,41 @@
+﻿// Copyright (c) 2010-2014 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Arguments for the callback of <see cref="FindReferences.RenameReferencesInFile"/>.
+	/// </summary>
+	public class RenameCallbackArguments
+	{
+		public AstNode NodeToReplace { get; private set; }
+		public AstNode NewNode { get; private set; }
+		
+		public RenameCallbackArguments(AstNode nodeToReplace, AstNode newNode)
+		{
+			if (nodeToReplace == null)
+				throw new ArgumentNullException("nodeToReplace");
+			if (newNode == null)
+				throw new ArgumentNullException("newNode");
+			this.NodeToReplace = nodeToReplace;
+			this.NewNode = newNode;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ResolveAtLocation.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ResolveAtLocation.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ResolveAtLocation.cs	(revision 11807)
@@ -0,0 +1,124 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Helper class that resolves the node at a specified location.
+	/// Can be used for implementing tool tips.
+	/// </summary>
+	public static class ResolveAtLocation
+	{
+		public static ResolveResult Resolve (ICompilation compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location,
+		                                    CancellationToken cancellationToken = default(CancellationToken))
+		{
+			return Resolve (new Lazy<ICompilation>(() => compilation), unresolvedFile, syntaxTree, location, cancellationToken);
+		}
+		public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location,
+		                                    CancellationToken cancellationToken = default(CancellationToken))
+		{
+			AstNode node;
+			return Resolve(compilation, unresolvedFile, syntaxTree, location, out node, cancellationToken);
+		}
+		
+		public static ResolveResult Resolve (ICompilation compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
+		                                    CancellationToken cancellationToken = default(CancellationToken))
+		{
+			return Resolve (new Lazy<ICompilation>(() => compilation), unresolvedFile, syntaxTree, location, out node, cancellationToken);
+		}
+		public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
+		                                    CancellationToken cancellationToken = default(CancellationToken))
+		{
+			node = syntaxTree.GetNodeAt(location);
+			if (node == null || node is ArrayInitializerExpression)
+				return null;
+			if (node.Parent is UsingAliasDeclaration && node.Role == UsingAliasDeclaration.AliasRole) {
+				var r = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
+				return r.Resolve(((UsingAliasDeclaration)node.Parent).Import, cancellationToken);
+			}
+			if (CSharpAstResolver.IsUnresolvableNode(node)) {
+				if (node is Identifier) {
+					node = node.Parent;
+				} else if (node.NodeType == NodeType.Token) {
+					if (node.Parent is IndexerExpression || node.Parent is ConstructorInitializer || node.Role == IndexerDeclaration.ThisKeywordRole) {
+						// There's no other place where one could hover to see the indexer's tooltip,
+						// so we need to resolve it when hovering over the '[' or ']'.
+						// For constructor initializer, the same applies to the 'base'/'this' token.
+						node = node.Parent;
+					} else if (node.Parent is BinaryOperatorExpression || node.Parent is UnaryOperatorExpression) {
+						// Resolve user-defined operator
+						node = node.Parent;
+					} else {
+						return null;
+					}
+				} else {
+					// don't resolve arbitrary nodes - we don't want to show tooltips for everything
+					return null;
+				}
+			} else {
+				// It's a resolvable node.
+				// However, we usually don't want to show the tooltip everywhere
+				// For example, hovering with the mouse over an empty line between two methods causes
+				// node==TypeDeclaration, but we don't want to show any tooltip.
+				
+				if (!node.GetChildByRole(Roles.Identifier).IsNull) {
+					// We'll suppress the tooltip for resolvable nodes if there is an identifier that
+					// could be hovered over instead:
+					return null;
+				}
+			}
+
+			if (node == null)
+				return null;
+			if (node.Parent is ObjectCreateExpression && node.Role == Roles.Type) {
+				node = node.Parent;
+			} else if (node is ThisReferenceExpression && node.Parent is IndexerExpression) {
+				node = node.Parent;
+			}
+
+			InvocationExpression parentInvocation = null;
+			if ((node is IdentifierExpression || node is MemberReferenceExpression || node is PointerReferenceExpression) && node.Role != Roles.Argument) {
+				// we also need to resolve the invocation
+				parentInvocation = node.Parent as InvocationExpression;
+			}
+			
+			// TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused
+			CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
+			ResolveResult rr = resolver.Resolve(node, cancellationToken);
+			MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult;
+			if (mgrr != null) {
+				// For method groups, resolve the parent invocation instead.
+				if (parentInvocation != null)
+					return resolver.Resolve(parentInvocation);
+				if (node is Expression) {
+					// If it's not an invocation, try if it's a conversion to a delegate type:
+					Conversion c = resolver.GetConversion((Expression)node, cancellationToken);
+					if (c.IsMethodGroupConversion)
+						return new MemberResolveResult(mgrr.TargetResult, c.Method);
+				}
+			}
+			return rr;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ResolveVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ResolveVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/ResolveVisitor.cs	(revision 11807)
@@ -0,0 +1,4103 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using ICSharpCode.NRefactory.CSharp.Analysis;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	/// <summary>
+	/// Traverses the DOM and resolves expressions.
+	/// </summary>
+	/// <remarks>
+	/// The ResolveVisitor does two jobs at the same time: it tracks the resolve context (properties on CSharpResolver)
+	/// and it resolves the expressions visited.
+	/// To allow using the context tracking without having to resolve every expression in the file (e.g. when you want to resolve
+	/// only a single node deep within the DOM), you can use the <see cref="IResolveVisitorNavigator"/> interface.
+	/// The navigator allows you to switch the between scanning mode and resolving mode.
+	/// In scanning mode, the context is tracked (local variables registered etc.), but nodes are not resolved.
+	/// While scanning, the navigator will get asked about every node that the resolve visitor is about to enter.
+	/// This allows the navigator whether to keep scanning, whether switch to resolving mode, or whether to completely skip the
+	/// subtree rooted at that node.
+	/// 
+	/// In resolving mode, the context is tracked and nodes will be resolved.
+	/// The resolve visitor may decide that it needs to resolve other nodes as well in order to resolve the current node.
+	/// In this case, those nodes will be resolved automatically, without asking the navigator interface.
+	/// For child nodes that are not essential to resolving, the resolve visitor will switch back to scanning mode (and thus will
+	/// ask the navigator for further instructions).
+	/// 
+	/// Moreover, there is the <c>ResolveAll</c> mode - it works similar to resolving mode, but will not switch back to scanning mode.
+	/// The whole subtree will be resolved without notifying the navigator.
+	/// </remarks>
+	sealed class ResolveVisitor : IAstVisitor<ResolveResult>
+	{
+		// The ResolveVisitor is also responsible for handling lambda expressions.
+		
+		static readonly ResolveResult errorResult = ErrorResolveResult.UnknownError;
+		
+		CSharpResolver resolver;
+		/// <summary>Resolve result of the current LINQ query.</summary>
+		/// <remarks>We do not have to put this into the stored state (resolver) because
+		/// query expressions are always resolved in a single operation.</remarks>
+		ResolveResult currentQueryResult;
+		readonly CSharpUnresolvedFile unresolvedFile;
+		readonly Dictionary<AstNode, ResolveResult> resolveResultCache = new Dictionary<AstNode, ResolveResult>();
+		readonly Dictionary<AstNode, CSharpResolver> resolverBeforeDict = new Dictionary<AstNode, CSharpResolver>();
+		readonly Dictionary<AstNode, CSharpResolver> resolverAfterDict = new Dictionary<AstNode, CSharpResolver>();
+		readonly Dictionary<Expression, ConversionWithTargetType> conversionDict = new Dictionary<Expression, ConversionWithTargetType>();
+		
+		internal struct ConversionWithTargetType
+		{
+			public readonly Conversion Conversion;
+			public readonly IType TargetType;
+			
+			public ConversionWithTargetType(Conversion conversion, IType targetType)
+			{
+				this.Conversion = conversion;
+				this.TargetType = targetType;
+			}
+		}
+		
+		IResolveVisitorNavigator navigator;
+		bool resolverEnabled;
+		List<LambdaBase> undecidedLambdas;
+		internal CancellationToken cancellationToken;
+		
+		#region Constructor
+		static readonly IResolveVisitorNavigator skipAllNavigator = new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Skip, null);
+		
+		/// <summary>
+		/// Creates a new ResolveVisitor instance.
+		/// </summary>
+		public ResolveVisitor(CSharpResolver resolver, CSharpUnresolvedFile unresolvedFile)
+		{
+			if (resolver == null)
+				throw new ArgumentNullException("resolver");
+			this.resolver = resolver;
+			this.unresolvedFile = unresolvedFile;
+			this.navigator = skipAllNavigator;
+		}
+		
+		internal void SetNavigator(IResolveVisitorNavigator navigator)
+		{
+			this.navigator = navigator ?? skipAllNavigator;
+		}
+		
+		ResolveResult voidResult {
+			get {
+				return new ResolveResult(resolver.Compilation.FindType(KnownTypeCode.Void));
+			}
+		}
+		#endregion
+		
+		#region ResetContext
+		/// <summary>
+		/// Resets the visitor to the stored position, runs the action, and then reverts the visitor to the previous position.
+		/// </summary>
+		void ResetContext(CSharpResolver storedContext, Action action)
+		{
+			var oldResolverEnabled = this.resolverEnabled;
+			var oldResolver = this.resolver;
+			var oldQueryResult = this.currentQueryResult;
+			try {
+				this.resolverEnabled = false;
+				this.resolver = storedContext;
+				this.currentQueryResult = null;
+				
+				action();
+			} finally {
+				this.resolverEnabled = oldResolverEnabled;
+				this.resolver = oldResolver;
+				this.currentQueryResult = oldQueryResult;
+			}
+		}
+		#endregion
+		
+		#region Scan / Resolve
+		/// <summary>
+		/// Scans the AST rooted at the given node.
+		/// </summary>
+		public void Scan(AstNode node)
+		{
+			if (node == null || node.IsNull)
+				return;
+			switch (node.NodeType) {
+				case NodeType.Token:
+				case NodeType.Whitespace:
+					return; // skip tokens, identifiers, comments, etc.
+			}
+			// don't Scan again if the node was already resolved
+			if (resolveResultCache.ContainsKey(node)) {
+				// Restore state change caused by this node:
+				CSharpResolver newResolver;
+				if (resolverAfterDict.TryGetValue(node, out newResolver))
+					resolver = newResolver;
+				return;
+			}
+			
+			var mode = navigator.Scan(node);
+			switch (mode) {
+				case ResolveVisitorNavigationMode.Skip:
+					if (node is VariableDeclarationStatement || node is SwitchSection) {
+						// Enforce scanning of variable declarations.
+						goto case ResolveVisitorNavigationMode.Scan;
+					}
+					StoreCurrentState(node);
+					break;
+				case ResolveVisitorNavigationMode.Scan:
+					bool oldResolverEnabled = resolverEnabled;
+					var oldResolver = resolver;
+					resolverEnabled = false;
+					StoreCurrentState(node);
+					ResolveResult result = node.AcceptVisitor(this);
+					if (result != null) {
+						// If the node was resolved, store the result even though it wasn't requested.
+						// This is necessary so that Visit-methods that decide to always resolve are
+						// guaranteed to get called only once.
+						// This is used for lambda registration.
+						StoreResult(node, result);
+						if (resolver != oldResolver) {
+							// The node changed the resolver state:
+							resolverAfterDict.Add(node, resolver);
+						}
+						cancellationToken.ThrowIfCancellationRequested();
+					}
+					resolverEnabled = oldResolverEnabled;
+					break;
+				case ResolveVisitorNavigationMode.Resolve:
+					Resolve(node);
+					break;
+				default:
+					throw new InvalidOperationException("Invalid value for ResolveVisitorNavigationMode");
+			}
+		}
+		
+		/// <summary>
+		/// Equivalent to 'Scan', but also resolves the node at the same time.
+		/// This method should be only used if the CSharpResolver passed to the ResolveVisitor was manually set
+		/// to the correct state.
+		/// Otherwise, use <c>resolver.Scan(syntaxTree); var result = resolver.GetResolveResult(node);</c>
+		/// instead.
+		/// --
+		/// This method now is internal, because it is difficult to use correctly.
+		/// Users of the public API should use Scan()+GetResolveResult() instead.
+		/// </summary>
+		internal ResolveResult Resolve(AstNode node)
+		{
+			if (node == null || node.IsNull)
+				return errorResult;
+			bool oldResolverEnabled = resolverEnabled;
+			resolverEnabled = true;
+			ResolveResult result;
+			if (!resolveResultCache.TryGetValue(node, out result)) {
+				cancellationToken.ThrowIfCancellationRequested();
+				StoreCurrentState(node);
+				var oldResolver = resolver;
+				result = node.AcceptVisitor(this) ?? errorResult;
+				StoreResult(node, result);
+				if (resolver != oldResolver) {
+					// The node changed the resolver state:
+					resolverAfterDict.Add(node, resolver);
+				}
+			}
+			resolverEnabled = oldResolverEnabled;
+			return result;
+		}
+		
+		IType ResolveType(AstType type)
+		{
+			return Resolve(type).Type;
+		}
+		
+		void StoreCurrentState(AstNode node)
+		{
+			// It's possible that we re-visit an expression that we scanned over earlier,
+			// so we might have to overwrite an existing state.
+			
+			#if DEBUG
+			CSharpResolver oldResolver;
+			if (resolverBeforeDict.TryGetValue(node, out oldResolver)) {
+				Debug.Assert(oldResolver.LocalVariables.SequenceEqual(resolver.LocalVariables));
+			}
+			#endif
+			
+			resolverBeforeDict[node] = resolver;
+		}
+		
+		void StoreResult(AstNode node, ResolveResult result)
+		{
+			Debug.Assert(result != null);
+			if (node.IsNull)
+				return;
+			Log.WriteLine("Resolved '{0}' to {1}", node, result);
+			Debug.Assert(!CSharpAstResolver.IsUnresolvableNode(node));
+			// The state should be stored before the result is.
+			Debug.Assert(resolverBeforeDict.ContainsKey(node));
+			// Don't store results twice.
+			Debug.Assert(!resolveResultCache.ContainsKey(node));
+			// Don't use ConversionResolveResult as a result, because it can get
+			// confused with an implicit conversion.
+			Debug.Assert(!(result is ConversionResolveResult) || result is CastResolveResult);
+			resolveResultCache[node] = result;
+			if (navigator != null)
+				navigator.Resolved(node, result);
+		}
+		
+		void ScanChildren(AstNode node)
+		{
+			for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
+				Scan(child);
+			}
+		}
+		#endregion
+		
+		#region Process Conversions
+		sealed class AnonymousFunctionConversion : Conversion
+		{
+			public readonly IType ReturnType;
+			public readonly ExplicitlyTypedLambda ExplicitlyTypedLambda;
+			public readonly LambdaTypeHypothesis Hypothesis;
+			readonly bool isValid;
+			
+			public AnonymousFunctionConversion(IType returnType, LambdaTypeHypothesis hypothesis, bool isValid)
+			{
+				if (returnType == null)
+					throw new ArgumentNullException("returnType");
+				this.ReturnType = returnType;
+				this.Hypothesis = hypothesis;
+				this.isValid = isValid;
+			}
+			
+			public AnonymousFunctionConversion(IType returnType, ExplicitlyTypedLambda explicitlyTypedLambda, bool isValid)
+			{
+				if (returnType == null)
+					throw new ArgumentNullException("returnType");
+				this.ReturnType = returnType;
+				this.ExplicitlyTypedLambda = explicitlyTypedLambda;
+				this.isValid = isValid;
+			}
+			
+			public override bool IsValid {
+				get { return isValid; }
+			}
+			
+			public override bool IsImplicit {
+				get { return true; }
+			}
+			
+			public override bool IsAnonymousFunctionConversion {
+				get { return true; }
+			}
+		}
+		
+		/// <summary>
+		/// Convert 'rr' to the target type using the specified conversion.
+		/// </summary>
+		void ProcessConversion(Expression expr, ResolveResult rr, Conversion conversion, IType targetType)
+		{
+			AnonymousFunctionConversion afc = conversion as AnonymousFunctionConversion;
+			if (afc != null) {
+				Log.WriteLine("Processing conversion of anonymous function to " + targetType + "...");
+				
+				Log.Indent();
+				if (afc.Hypothesis != null)
+					afc.Hypothesis.MergeInto(this, afc.ReturnType);
+				if (afc.ExplicitlyTypedLambda != null)
+					afc.ExplicitlyTypedLambda.ApplyReturnType(this, afc.ReturnType);
+				Log.Unindent();
+			}
+			if (expr != null && !expr.IsNull && conversion != Conversion.IdentityConversion) {
+				navigator.ProcessConversion(expr, rr, conversion, targetType);
+				conversionDict[expr] = new ConversionWithTargetType(conversion, targetType);
+			}
+		}
+		
+		void ImportConversions(ResolveVisitor childVisitor)
+		{
+			foreach (var pair in childVisitor.conversionDict) {
+				conversionDict.Add(pair.Key, pair.Value);
+				navigator.ProcessConversion(pair.Key, resolveResultCache[pair.Key], pair.Value.Conversion, pair.Value.TargetType);
+			}
+		}
+		
+		/// <summary>
+		/// Convert 'rr' to the target type.
+		/// </summary>
+		void ProcessConversion(Expression expr, ResolveResult rr, IType targetType)
+		{
+			if (expr == null || expr.IsNull)
+				return;
+			ProcessConversion(expr, rr, resolver.conversions.ImplicitConversion(rr, targetType), targetType);
+		}
+		
+		/// <summary>
+		/// Resolves the specified expression and processes the conversion to targetType.
+		/// </summary>
+		void ResolveAndProcessConversion(Expression expr, IType targetType)
+		{
+			if (targetType.Kind == TypeKind.Unknown) {
+				// no need to resolve the expression right now
+				Scan(expr);
+			} else {
+				ProcessConversion(expr, Resolve(expr), targetType);
+			}
+		}
+		
+		void ProcessConversionResult(Expression expr, ConversionResolveResult rr)
+		{
+			if (rr != null && !(rr is CastResolveResult))
+				ProcessConversion(expr, rr.Input, rr.Conversion, rr.Type);
+		}
+		
+		void ProcessConversionResults(IEnumerable<Expression> expr, IEnumerable<ResolveResult> conversionResolveResults)
+		{
+			Debug.Assert(expr.Count() == conversionResolveResults.Count());
+			using (var e1 = expr.GetEnumerator()) {
+				using (var e2 = conversionResolveResults.GetEnumerator()) {
+					while (e1.MoveNext() && e2.MoveNext()) {
+						ProcessConversionResult(e1.Current, e2.Current as ConversionResolveResult);
+					}
+				}
+			}
+		}
+		
+		void MarkUnknownNamedArguments(IEnumerable<Expression> arguments)
+		{
+			foreach (var nae in arguments.OfType<NamedArgumentExpression>()) {
+				StoreCurrentState(nae);
+				StoreResult(nae, new NamedArgumentResolveResult(nae.Name, resolveResultCache[nae.Expression]));
+			}
+		}
+		
+		void ProcessInvocationResult(Expression target, IEnumerable<Expression> arguments, ResolveResult invocation)
+		{
+			if (invocation is CSharpInvocationResolveResult || invocation is DynamicInvocationResolveResult) {
+				int i = 0;
+				IList<ResolveResult> argumentsRR;
+				if (invocation is CSharpInvocationResolveResult) {
+					var csi = (CSharpInvocationResolveResult)invocation;
+					if (csi.IsExtensionMethodInvocation) {
+						Debug.Assert(arguments.Count() + 1 == csi.Arguments.Count);
+						ProcessConversionResult(target, csi.Arguments[0] as ConversionResolveResult);
+						i = 1;
+					} else {
+						Debug.Assert(arguments.Count() == csi.Arguments.Count);
+					}
+					argumentsRR = csi.Arguments;
+				}
+				else {
+					argumentsRR = ((DynamicInvocationResolveResult)invocation).Arguments;
+				}
+
+				foreach (Expression arg in arguments) {
+					ResolveResult argRR = argumentsRR[i++];
+					NamedArgumentExpression nae = arg as NamedArgumentExpression;
+					NamedArgumentResolveResult nrr = argRR as NamedArgumentResolveResult;
+					Debug.Assert((nae == null) == (nrr == null));
+					if (nae != null && nrr != null) {
+						StoreCurrentState(nae);
+						StoreResult(nae, nrr);
+						ProcessConversionResult(nae.Expression, nrr.Argument as ConversionResolveResult);
+					} else {
+						ProcessConversionResult(arg, argRR as ConversionResolveResult);
+					}
+				}
+			}
+			else {
+				MarkUnknownNamedArguments(arguments);
+			}
+		}
+		#endregion
+		
+		#region GetResolveResult
+		/// <summary>
+		/// Gets the resolve result for the specified node.
+		/// If the node was not resolved by the navigator, this method will resolve it.
+		/// </summary>
+		public ResolveResult GetResolveResult(AstNode node)
+		{
+			Debug.Assert(!CSharpAstResolver.IsUnresolvableNode(node));
+			
+			MergeUndecidedLambdas();
+			ResolveResult result;
+			if (resolveResultCache.TryGetValue(node, out result))
+				return result;
+			
+			AstNode parent;
+			CSharpResolver storedResolver = GetPreviouslyScannedContext(node, out parent);
+			ResetContext(
+				storedResolver,
+				delegate {
+					navigator = new NodeListResolveVisitorNavigator(node);
+					Debug.Assert(!resolverEnabled);
+					Scan(parent);
+					navigator = skipAllNavigator;
+				});
+			
+			MergeUndecidedLambdas();
+			return resolveResultCache[node];
+		}
+		
+		CSharpResolver GetPreviouslyScannedContext(AstNode node, out AstNode parent)
+		{
+			parent = node;
+			CSharpResolver storedResolver;
+			while (!resolverBeforeDict.TryGetValue(parent, out storedResolver)) {
+				AstNode tmp = parent.Parent;
+				if (tmp == null)
+					throw new InvalidOperationException("Could not find a resolver state for any parent of the specified node. Are you trying to resolve a node that is not a descendant of the CSharpAstResolver's root node?");
+				if (tmp.NodeType == NodeType.Whitespace)
+					return resolver; // special case: resolve expression within preprocessor directive
+				parent = tmp;
+			}
+			return storedResolver;
+		}
+		
+		/// <summary>
+		/// Gets the resolver state in front of the specified node.
+		/// If the node was not visited by a previous scanning process, the
+		/// AST will be scanned again to determine the state.
+		/// </summary>
+		public CSharpResolver GetResolverStateBefore(AstNode node)
+		{
+			MergeUndecidedLambdas();
+			CSharpResolver r;
+			if (resolverBeforeDict.TryGetValue(node, out r))
+				return r;
+			
+			AstNode parent;
+			CSharpResolver storedResolver = GetPreviouslyScannedContext(node, out parent);
+			ResetContext(
+				storedResolver,
+				delegate {
+					navigator = new NodeListResolveVisitorNavigator(new[] { node }, scanOnly: true);
+					Debug.Assert(!resolverEnabled);
+					// parent might already be resolved if 'node' is an unresolvable node
+					Scan(parent);
+					navigator = skipAllNavigator;
+				});
+			
+			MergeUndecidedLambdas();
+			while (node != null) {
+				if (resolverBeforeDict.TryGetValue(node, out r))
+					return r;
+				node = node.Parent;
+			}
+			return null;
+		}
+		
+		public CSharpResolver GetResolverStateAfter(AstNode node)
+		{
+			// Resolve the node to fill the resolverAfterDict
+			GetResolveResult(node);
+			CSharpResolver result;
+			if (resolverAfterDict.TryGetValue(node, out result))
+				return result;
+			else
+				return GetResolverStateBefore(node);
+		}
+		
+		public ConversionWithTargetType GetConversionWithTargetType(Expression expr)
+		{
+			GetResolverStateBefore(expr);
+			ResolveParentForConversion(expr);
+			ConversionWithTargetType result;
+			if (conversionDict.TryGetValue(expr, out result)) {
+				return result;
+			} else {
+				ResolveResult rr = GetResolveResult(expr);
+				return new ConversionWithTargetType(Conversion.IdentityConversion, rr.Type);
+			}
+		}
+		#endregion
+		
+		#region Track UsingScope
+		ResolveResult IAstVisitor<ResolveResult>.VisitSyntaxTree(SyntaxTree unit)
+		{
+			CSharpResolver previousResolver = resolver;
+			try {
+				if (unresolvedFile != null) {
+					resolver = resolver.WithCurrentUsingScope(unresolvedFile.RootUsingScope.Resolve(resolver.Compilation));
+				} else {
+					var cv = new TypeSystemConvertVisitor(unit.FileName ?? string.Empty);
+					ApplyVisitorToUsings(cv, unit.Children);
+					PushUsingScope(cv.UnresolvedFile.RootUsingScope);
+				}
+				ScanChildren(unit);
+				return voidResult;
+			} finally {
+				resolver = previousResolver;
+			}
+		}
+		
+		void ApplyVisitorToUsings(TypeSystemConvertVisitor visitor, IEnumerable<AstNode> children)
+		{
+			foreach (var child in children) {
+				if (child is ExternAliasDeclaration || child is UsingDeclaration || child is UsingAliasDeclaration) {
+					child.AcceptVisitor(visitor);
+				}
+			}
+		}
+		
+		void PushUsingScope(UsingScope usingScope)
+		{
+			usingScope.Freeze();
+			resolver = resolver.WithCurrentUsingScope(new ResolvedUsingScope(resolver.CurrentTypeResolveContext, usingScope));
+		}
+
+		ResolveResult IAstVisitor<ResolveResult>.VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+		{
+			CSharpResolver previousResolver = resolver;
+			try {
+				var nsName = namespaceDeclaration.NamespaceName;
+				AstNode child = namespaceDeclaration.FirstChild;
+
+				for (; child != null && child.Role != Roles.LBrace; child = child.NextSibling) {
+					Scan(child);
+				}
+
+				if (unresolvedFile != null) {
+					resolver = resolver.WithCurrentUsingScope(unresolvedFile.GetUsingScope(namespaceDeclaration.StartLocation).Resolve(resolver.Compilation));
+
+				} else {
+//					string fileName = namespaceDeclaration.GetRegion().FileName ?? string.Empty;
+					// Fetch parent using scope
+					// Create root using scope if necessary
+					if (resolver.CurrentUsingScope == null)
+						PushUsingScope(new UsingScope());
+					
+					// Create child using scope
+					DomRegion region = namespaceDeclaration.GetRegion();
+					var identifiers = namespaceDeclaration.Identifiers.ToList();
+					// For all but the last identifier:
+					UsingScope usingScope;
+					for (int i = 0; i < identifiers.Count - 1; i++) {
+						usingScope = new UsingScope(resolver.CurrentUsingScope.UnresolvedUsingScope, identifiers[i]);
+						usingScope.Region = region;
+						PushUsingScope(usingScope);
+					}
+					// Last using scope:
+					usingScope = new UsingScope(resolver.CurrentUsingScope.UnresolvedUsingScope, identifiers.Last());
+					usingScope.Region = region;
+					var cv = new TypeSystemConvertVisitor(new CSharpUnresolvedFile(), usingScope);
+					ApplyVisitorToUsings(cv, namespaceDeclaration.Children);
+					PushUsingScope(usingScope);
+				}
+				for (; child != null; child = child.NextSibling) {
+					Scan(child);
+				}
+
+				// merge undecided lambdas before leaving the using scope so that
+				// the resolver can make better use of its cache
+				MergeUndecidedLambdas();
+				if (resolver.CurrentUsingScope != null && resolver.CurrentUsingScope.Namespace != null)
+					return new NamespaceResolveResult(resolver.CurrentUsingScope.Namespace);
+				else
+					return null;
+			} finally {
+				resolver = previousResolver;
+			}
+		}
+		#endregion
+		
+		#region Track CurrentTypeDefinition
+		ResolveResult VisitTypeOrDelegate(AstNode typeDeclaration, string name, int typeParameterCount)
+		{
+			CSharpResolver previousResolver = resolver;
+			try {
+				ITypeDefinition newTypeDefinition = null;
+				if (resolver.CurrentTypeDefinition != null) {
+					int totalTypeParameterCount = resolver.CurrentTypeDefinition.TypeParameterCount + typeParameterCount;
+					foreach (ITypeDefinition nestedType in resolver.CurrentTypeDefinition.NestedTypes) {
+						if (nestedType.Name == name && nestedType.TypeParameterCount == totalTypeParameterCount) {
+							newTypeDefinition = nestedType;
+							break;
+						}
+					}
+				} else if (resolver.CurrentUsingScope != null) {
+					newTypeDefinition = resolver.CurrentUsingScope.Namespace.GetTypeDefinition(name, typeParameterCount);
+				}
+				if (newTypeDefinition != null)
+					resolver = resolver.WithCurrentTypeDefinition(newTypeDefinition);
+				
+				ScanChildren(typeDeclaration);
+				
+				// merge undecided lambdas before leaving the type definition so that
+				// the resolver can make better use of its cache
+				MergeUndecidedLambdas();
+				
+				return newTypeDefinition != null ? new TypeResolveResult(newTypeDefinition) : errorResult;
+			} finally {
+				resolver = previousResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			return VisitTypeOrDelegate(typeDeclaration, typeDeclaration.Name, typeDeclaration.TypeParameters.Count);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			return VisitTypeOrDelegate(delegateDeclaration, delegateDeclaration.Name, delegateDeclaration.TypeParameters.Count);
+		}
+		#endregion
+		
+		#region Track CurrentMember
+		ResolveResult IAstVisitor<ResolveResult>.VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			return VisitFieldOrEventDeclaration(fieldDeclaration, SymbolKind.Field);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			return VisitFieldOrEventDeclaration(fixedFieldDeclaration, SymbolKind.Field);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			return VisitFieldOrEventDeclaration(eventDeclaration, SymbolKind.Event);
+		}
+		
+		ResolveResult VisitFieldOrEventDeclaration(EntityDeclaration fieldOrEventDeclaration, SymbolKind symbolKind)
+		{
+			//int initializerCount = fieldOrEventDeclaration.GetChildrenByRole(Roles.Variable).Count;
+			CSharpResolver oldResolver = resolver;
+			for (AstNode node = fieldOrEventDeclaration.FirstChild; node != null; node = node.NextSibling) {
+				if (node.Role == Roles.Variable || node.Role == FixedFieldDeclaration.VariableRole) {
+					IMember member;
+					if (unresolvedFile != null) {
+						member = GetMemberFromLocation(node);
+					} else {
+						string name = ((VariableInitializer)node).Name;
+						member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, symbolKind, name);
+					}
+					resolver = resolver.WithCurrentMember(member);
+					
+					Scan(node);
+					
+					resolver = oldResolver;
+				} else {
+					Scan(node);
+				}
+			}
+			return voidResult;
+		}
+		
+		IMember GetMemberFromLocation(AstNode node)
+		{
+			ITypeDefinition typeDef = resolver.CurrentTypeDefinition;
+			if (typeDef == null)
+				return null;
+			TextLocation location = TypeSystemConvertVisitor.GetStartLocationAfterAttributes(node);
+			return typeDef.GetMembers(
+				delegate (IUnresolvedMember m) {
+					if (m.UnresolvedFile != unresolvedFile)
+						return false;
+					DomRegion region = m.Region;
+					return !region.IsEmpty && region.Begin <= location && region.End > location;
+				},
+				GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions
+			).FirstOrDefault();
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitVariableInitializer(VariableInitializer variableInitializer)
+		{
+			// Within the variable initializer, the newly declared variable is not yet available:
+			var resolverWithVariable = resolver;
+			if (variableInitializer.Parent is VariableDeclarationStatement)
+				resolver = resolver.PopLastVariable();
+			
+			ArrayInitializerExpression aie = variableInitializer.Initializer as ArrayInitializerExpression;
+			if (resolverEnabled || aie != null) {
+				ResolveResult result = errorResult;
+				if (variableInitializer.Parent is FieldDeclaration || variableInitializer.Parent is EventDeclaration) {
+					if (resolver.CurrentMember != null) {
+						result = new MemberResolveResult(null, resolver.CurrentMember, false);
+					}
+				} else {
+					string identifier = variableInitializer.Name;
+					foreach (IVariable v in resolverWithVariable.LocalVariables) {
+						if (v.Name == identifier) {
+							result = new LocalResolveResult(v);
+							break;
+						}
+					}
+				}
+				ArrayType arrayType = result.Type as ArrayType;
+				if (aie != null && arrayType != null) {
+					StoreCurrentState(aie);
+					List<Expression> initializerElements = new List<Expression>();
+					int[] sizes = new int[arrayType.Dimensions];
+					UnpackArrayInitializer(initializerElements, sizes, aie, 0, true);
+					ResolveResult[] initializerElementResults = new ResolveResult[initializerElements.Count];
+					for (int i = 0; i < initializerElementResults.Length; i++) {
+						initializerElementResults[i] = Resolve(initializerElements[i]);
+					}
+					var arrayCreation = resolver.ResolveArrayCreation(arrayType.ElementType, sizes, initializerElementResults);
+					StoreResult(aie, arrayCreation);
+					ProcessConversionResults(initializerElements, arrayCreation.InitializerElements);
+				} else if (variableInitializer.Parent is FixedStatement) {
+					var initRR = Resolve(variableInitializer.Initializer);
+					PointerType pointerType;
+					if (initRR.Type.Kind == TypeKind.Array) {
+						pointerType = new PointerType(((ArrayType)initRR.Type).ElementType);
+					} else if (ReflectionHelper.GetTypeCode(initRR.Type) == TypeCode.String) {
+						pointerType = new PointerType(resolver.Compilation.FindType(KnownTypeCode.Char));
+					} else {
+						pointerType = null;
+						ProcessConversion(variableInitializer.Initializer, initRR, result.Type);
+					}
+					if (pointerType != null) {
+						var conversion = resolver.conversions.ImplicitConversion(pointerType, result.Type);
+						if (conversion.IsIdentityConversion)
+							conversion = Conversion.ImplicitPointerConversion;
+						ProcessConversion(variableInitializer.Initializer, initRR, conversion, result.Type);
+					}
+				} else {
+					ResolveAndProcessConversion(variableInitializer.Initializer, result.Type);
+				}
+				resolver = resolverWithVariable;
+				return result;
+			} else {
+				Scan(variableInitializer.Initializer);
+				resolver = resolverWithVariable;
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitFixedVariableInitializer(FixedVariableInitializer fixedVariableInitializer)
+		{
+			if (resolverEnabled) {
+				ResolveResult result = errorResult;
+				if (resolver.CurrentMember != null) {
+					result = new MemberResolveResult(null, resolver.CurrentMember, false);
+				}
+				ResolveAndProcessConversion(fixedVariableInitializer.CountExpression, resolver.Compilation.FindType(KnownTypeCode.Int32));
+				return result;
+			} else {
+				ScanChildren(fixedVariableInitializer);
+				return null;
+			}
+		}
+		
+		ResolveResult VisitMethodMember(EntityDeclaration memberDeclaration)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				IMember member = null;
+				if (unresolvedFile != null) {
+					member = GetMemberFromLocation(memberDeclaration);
+				}
+				if (member == null) {
+					// Re-discover the method:
+					SymbolKind symbolKind = memberDeclaration.SymbolKind;
+					var parameterTypes = TypeSystemConvertVisitor.GetParameterTypes(memberDeclaration.GetChildrenByRole(Roles.Parameter), InterningProvider.Dummy);
+					if (symbolKind == SymbolKind.Constructor) {
+						string name = memberDeclaration.HasModifier(Modifiers.Static) ? ".cctor" : ".ctor";
+						member = AbstractUnresolvedMember.Resolve(
+							resolver.CurrentTypeResolveContext, symbolKind, name,
+							parameterTypeReferences: parameterTypes);
+					} else if (symbolKind == SymbolKind.Destructor) {
+						member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, symbolKind, "Finalize");
+					} else {
+						string[] typeParameterNames = memberDeclaration.GetChildrenByRole(Roles.TypeParameter).Select(tp => tp.Name).ToArray();
+						AstType explicitInterfaceAstType = memberDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole);
+						ITypeReference explicitInterfaceType = null;
+						if (!explicitInterfaceAstType.IsNull) {
+							explicitInterfaceType = explicitInterfaceAstType.ToTypeReference();
+						}
+						member = AbstractUnresolvedMember.Resolve(
+							resolver.CurrentTypeResolveContext, symbolKind, memberDeclaration.Name,
+							explicitInterfaceType, typeParameterNames, parameterTypes);
+					}
+				}
+				resolver = resolver.WithCurrentMember(member);
+				ScanChildren(memberDeclaration);
+				
+				if (member != null)
+					return new MemberResolveResult(null, member, false);
+				else
+					return errorResult;
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			return VisitMethodMember(methodDeclaration);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+		{
+			return VisitMethodMember(operatorDeclaration);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			return VisitMethodMember(constructorDeclaration);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			return VisitMethodMember(destructorDeclaration);
+		}
+		
+		// handle properties/indexers
+		ResolveResult VisitPropertyMember(EntityDeclaration propertyOrIndexerDeclaration)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				IMember member;
+				if (unresolvedFile != null) {
+					member = GetMemberFromLocation(propertyOrIndexerDeclaration);
+				} else {
+					// Re-discover the property:
+					string name = propertyOrIndexerDeclaration.Name;
+					var parameterTypeReferences = TypeSystemConvertVisitor.GetParameterTypes(propertyOrIndexerDeclaration.GetChildrenByRole(Roles.Parameter), InterningProvider.Dummy);
+					AstType explicitInterfaceAstType = propertyOrIndexerDeclaration.GetChildByRole(EntityDeclaration.PrivateImplementationTypeRole);
+					ITypeReference explicitInterfaceType = null;
+					if (!explicitInterfaceAstType.IsNull) {
+						explicitInterfaceType = explicitInterfaceAstType.ToTypeReference();
+					}
+					member = AbstractUnresolvedMember.Resolve(
+						resolver.CurrentTypeResolveContext, propertyOrIndexerDeclaration.SymbolKind, name,
+						explicitInterfaceType, parameterTypeReferences: parameterTypeReferences);
+				}
+				// We need to use the property as current member so that indexer parameters can be resolved correctly.
+				resolver = resolver.WithCurrentMember(member);
+				var resolverWithPropertyAsMember = resolver;
+				
+				for (AstNode node = propertyOrIndexerDeclaration.FirstChild; node != null; node = node.NextSibling) {
+					if (node.Role == PropertyDeclaration.GetterRole && member is IProperty) {
+						resolver = resolver.WithCurrentMember(((IProperty)member).Getter);
+						Scan(node);
+						resolver = resolverWithPropertyAsMember;
+					} else if (node.Role == PropertyDeclaration.SetterRole && member is IProperty) {
+						resolver = resolver.WithCurrentMember(((IProperty)member).Setter);
+						Scan(node);
+						resolver = resolverWithPropertyAsMember;
+					} else {
+						Scan(node);
+					}
+				}
+				if (member != null)
+					return new MemberResolveResult(null, member, false);
+				else
+					return errorResult;
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			return VisitPropertyMember(propertyDeclaration);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			return VisitPropertyMember(indexerDeclaration);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				IMember member;
+				if (unresolvedFile != null) {
+					member = GetMemberFromLocation(eventDeclaration);
+				} else {
+					string name = eventDeclaration.Name;
+					AstType explicitInterfaceAstType = eventDeclaration.PrivateImplementationType;
+					if (explicitInterfaceAstType.IsNull) {
+						member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, SymbolKind.Event, name);
+					} else {
+						member = AbstractUnresolvedMember.Resolve(resolver.CurrentTypeResolveContext, SymbolKind.Event, name,
+						                                          explicitInterfaceAstType.ToTypeReference());
+					}
+				}
+				resolver = resolver.WithCurrentMember(member);
+				var resolverWithEventAsMember = resolver;
+				
+				for (AstNode node = eventDeclaration.FirstChild; node != null; node = node.NextSibling) {
+					if (node.Role == CustomEventDeclaration.AddAccessorRole && member is IEvent) {
+						resolver = resolver.WithCurrentMember(((IEvent)member).AddAccessor);
+						Scan(node);
+						resolver = resolverWithEventAsMember;
+					} else if (node.Role == CustomEventDeclaration.RemoveAccessorRole && member is IEvent) {
+						resolver = resolver.WithCurrentMember(((IEvent)member).RemoveAccessor);
+						Scan(node);
+						resolver = resolverWithEventAsMember;
+					} else {
+						Scan(node);
+					}
+				}
+
+				if (member != null)
+					return new MemberResolveResult(null, member, false);
+				else
+					return errorResult;
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitParameterDeclaration(ParameterDeclaration parameterDeclaration)
+		{
+			ScanChildren(parameterDeclaration);
+			if (resolverEnabled) {
+				string name = parameterDeclaration.Name;
+				
+				if (parameterDeclaration.Parent is DocumentationReference) {
+					// create a dummy parameter
+					IType type = ResolveType(parameterDeclaration.Type);
+					switch (parameterDeclaration.ParameterModifier) {
+						case ParameterModifier.Ref:
+						case ParameterModifier.Out:
+							type = new ByReferenceType(type);
+							break;
+					}
+					return new LocalResolveResult(new DefaultParameter(
+						type, name,
+						isRef: parameterDeclaration.ParameterModifier == ParameterModifier.Ref,
+						isOut: parameterDeclaration.ParameterModifier == ParameterModifier.Out,
+						isParams: parameterDeclaration.ParameterModifier == ParameterModifier.Params));
+				}
+				
+				// Look in lambda parameters:
+				foreach (IParameter p in resolver.LocalVariables.OfType<IParameter>()) {
+					if (p.Name == name)
+						return new LocalResolveResult(p);
+				}
+				
+				IParameterizedMember pm = resolver.CurrentMember as IParameterizedMember;
+				if (pm == null && resolver.CurrentTypeDefinition != null) {
+					// Also consider delegate parameters:
+					pm = resolver.CurrentTypeDefinition.GetDelegateInvokeMethod();
+					// pm will be null if the current type isn't a delegate
+				}
+				if (pm != null) {
+					foreach (IParameter p in pm.Parameters) {
+						if (p.Name == name) {
+							return new LocalResolveResult(p);
+						}
+					}
+				}
+				
+				return errorResult;
+			} else {
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration)
+		{
+			ScanChildren(typeParameterDeclaration);
+			if (resolverEnabled) {
+				string name = typeParameterDeclaration.Name;
+				IMethod m = resolver.CurrentMember as IMethod;
+				if (m != null) {
+					foreach (var tp in m.TypeParameters) {
+						if (tp.Name == name)
+							return new TypeResolveResult(tp);
+					}
+				}
+				if (resolver.CurrentTypeDefinition != null) {
+					var typeParameters = resolver.CurrentTypeDefinition.TypeParameters;
+					// look backwards so that TPs in the current type take precedence over those copied from outer types
+					for (int i = typeParameters.Count - 1; i >= 0; i--) {
+						if (typeParameters[i].Name == name)
+							return new TypeResolveResult(typeParameters[i]);
+					}
+				}
+				return errorResult;
+			} else {
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				// Scan enum member attributes before setting resolver.CurrentMember, so that
+				// enum values used as attribute arguments have the correct type.
+				// (within an enum member, all other enum members are treated as having their underlying type)
+				foreach (var attributeSection in enumMemberDeclaration.Attributes)
+					Scan(attributeSection);
+				
+				IMember member = null;
+				if (unresolvedFile != null) {
+					member = GetMemberFromLocation(enumMemberDeclaration);
+				} else if (resolver.CurrentTypeDefinition != null) {
+					string name = enumMemberDeclaration.Name;
+					member = resolver.CurrentTypeDefinition.GetFields(f => f.Name == name, GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
+				}
+				resolver = resolver.WithCurrentMember(member);
+				
+				if (resolverEnabled && resolver.CurrentTypeDefinition != null) {
+					ResolveAndProcessConversion(enumMemberDeclaration.Initializer, resolver.CurrentTypeDefinition.EnumUnderlyingType);
+					if (resolverEnabled && member != null)
+						return new MemberResolveResult(null, member, false);
+					else
+						return errorResult;
+				} else {
+					Scan(enumMemberDeclaration.Initializer);
+					return null;
+				}
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		#endregion
+		
+		#region Track CheckForOverflow
+		ResolveResult IAstVisitor<ResolveResult>.VisitCheckedExpression(CheckedExpression checkedExpression)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				resolver = resolver.WithCheckForOverflow(true);
+				if (resolverEnabled) {
+					return Resolve(checkedExpression.Expression);
+				} else {
+					ScanChildren(checkedExpression);
+					return null;
+				}
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				resolver = resolver.WithCheckForOverflow(false);
+				if (resolverEnabled) {
+					return Resolve(uncheckedExpression.Expression);
+				} else {
+					ScanChildren(uncheckedExpression);
+					return null;
+				}
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitCheckedStatement(CheckedStatement checkedStatement)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				resolver = resolver.WithCheckForOverflow(true);
+				ScanChildren(checkedStatement);
+				return voidResult;
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUncheckedStatement(UncheckedStatement uncheckedStatement)
+		{
+			CSharpResolver oldResolver = resolver;
+			try {
+				resolver = resolver.WithCheckForOverflow(false);
+				ScanChildren(uncheckedStatement);
+				return voidResult;
+			} finally {
+				resolver = oldResolver;
+			}
+		}
+		#endregion
+		
+		#region Visit AnonymousTypeCreateExpression
+		static string GetAnonymousTypePropertyName(Expression expr, out Expression resolveExpr)
+		{
+			if (expr is NamedExpression) {
+				var namedArgExpr = (NamedExpression)expr;
+				resolveExpr = namedArgExpr.Expression;
+				return namedArgExpr.Name;
+			}
+			// no name given, so it's a projection initializer
+			if (expr is MemberReferenceExpression) {
+				resolveExpr = expr;
+				return ((MemberReferenceExpression)expr).MemberName;
+			}
+			if (expr is IdentifierExpression) {
+				resolveExpr = expr;
+				return ((IdentifierExpression)expr).Identifier;
+			}
+			resolveExpr = null;
+			return null;
+		}
+		
+		class AnonymousTypeMember
+		{
+			public readonly Expression Expression;
+			public readonly ResolveResult Initializer;
+			
+			public AnonymousTypeMember(Expression expression, ResolveResult initializer)
+			{
+				this.Expression = expression;
+				this.Initializer = initializer;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression)
+		{
+			// 7.6.10.6 Anonymous object creation expressions
+			List<IUnresolvedProperty> unresolvedProperties = new List<IUnresolvedProperty>();
+			List<AnonymousTypeMember> members = new List<AnonymousTypeMember>();
+			foreach (var expr in anonymousTypeCreateExpression.Initializers) {
+				Expression resolveExpr;
+				var name = GetAnonymousTypePropertyName(expr, out resolveExpr);
+				if (resolveExpr != null) {
+					var initRR = Resolve(resolveExpr);
+					var returnTypeRef = initRR.Type.ToTypeReference();
+					var property = new DefaultUnresolvedProperty();
+					property.Name = name;
+					property.Accessibility = Accessibility.Public;
+					property.ReturnType = returnTypeRef;
+					property.Getter = new DefaultUnresolvedMethod {
+						Name = "get_" + name,
+						Accessibility = Accessibility.Public,
+						ReturnType = returnTypeRef,
+						SymbolKind = SymbolKind.Accessor,
+						AccessorOwner = property
+					};
+					unresolvedProperties.Add(property);
+					members.Add(new AnonymousTypeMember(expr, initRR));
+				} else {
+					Scan(expr);
+				}
+			}
+			var anonymousType = new AnonymousType(resolver.Compilation, unresolvedProperties);
+			var properties = anonymousType.GetProperties().ToList();
+			Debug.Assert(properties.Count == members.Count);
+			List<ResolveResult> assignments = new List<ResolveResult>();
+			for (int i = 0; i < members.Count; i++) {
+				ResolveResult lhs = new MemberResolveResult(new InitializedObjectResolveResult(anonymousType), properties[i]);
+				ResolveResult rhs = members[i].Initializer;
+				ResolveResult assignment = resolver.ResolveAssignment(AssignmentOperatorType.Assign, lhs, rhs);
+				var ne = members[i].Expression as NamedExpression;
+				if (ne != null) {
+					StoreCurrentState(ne);
+					// ne.Expression was already resolved by the first loop
+					StoreResult(ne, lhs);
+				}
+				assignments.Add(assignment);
+			}
+			var anonymousCtor = DefaultResolvedMethod.GetDummyConstructor(resolver.Compilation, anonymousType);
+			return new InvocationResolveResult(null, anonymousCtor, initializerStatements: assignments);
+		}
+		#endregion
+		
+		#region Visit Expressions
+		ResolveResult IAstVisitor<ResolveResult>.VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
+		{
+			int dimensions = arrayCreateExpression.Arguments.Count;
+			IEnumerable<Expression> sizeArgumentExpressions;
+			ResolveResult[] sizeArguments;
+			IEnumerable<ArraySpecifier> additionalArraySpecifiers;
+			if (dimensions == 0) {
+				var firstSpecifier = arrayCreateExpression.AdditionalArraySpecifiers.FirstOrDefault();
+				if (firstSpecifier != null) {
+					dimensions = firstSpecifier.Dimensions;
+					additionalArraySpecifiers = arrayCreateExpression.AdditionalArraySpecifiers.Skip(1);
+				} else {
+					// No array specifiers (neither with nor without size) - can happen if there are syntax errors.
+					// Dimensions must be at least one; otherwise 'new ArrayType' will crash.
+					dimensions = 1;
+					additionalArraySpecifiers = arrayCreateExpression.AdditionalArraySpecifiers;
+				}
+				sizeArguments = null;
+				sizeArgumentExpressions = null;
+			} else {
+				sizeArgumentExpressions = arrayCreateExpression.Arguments;
+				sizeArguments = new ResolveResult[dimensions];
+				int pos = 0;
+				foreach (var node in sizeArgumentExpressions)
+					sizeArguments[pos++] = Resolve(node);
+				additionalArraySpecifiers = arrayCreateExpression.AdditionalArraySpecifiers;
+			}
+			
+			int[] sizes;
+			List<Expression> initializerElements;
+			ResolveResult[] initializerElementResults;
+			if (arrayCreateExpression.Initializer.IsNull) {
+				sizes = null;
+				initializerElements = null;
+				initializerElementResults = null;
+			} else {
+				StoreCurrentState(arrayCreateExpression.Initializer);
+				
+				initializerElements = new List<Expression>();
+				sizes = new int[dimensions];
+				UnpackArrayInitializer(initializerElements, sizes, arrayCreateExpression.Initializer, 0, true);
+				initializerElementResults = new ResolveResult[initializerElements.Count];
+				for (int i = 0; i < initializerElementResults.Length; i++) {
+					initializerElementResults[i] = Resolve(initializerElements[i]);
+				}
+				StoreResult(arrayCreateExpression.Initializer, voidResult);
+			}
+			
+			IType elementType;
+			if (arrayCreateExpression.Type.IsNull) {
+				elementType = null;
+			} else {
+				elementType = ResolveType(arrayCreateExpression.Type);
+				foreach (var spec in additionalArraySpecifiers.Reverse()) {
+					elementType = new ArrayType(resolver.Compilation, elementType, spec.Dimensions);
+				}
+			}
+			ArrayCreateResolveResult acrr;
+			if (sizeArguments != null) {
+				acrr = resolver.ResolveArrayCreation(elementType, sizeArguments, initializerElementResults);
+			} else if (sizes != null) {
+				acrr = resolver.ResolveArrayCreation(elementType, sizes, initializerElementResults);
+			} else {
+				// neither size arguments nor an initializer exist -> error
+				return new ErrorResolveResult(new ArrayType(resolver.Compilation, elementType ?? SpecialType.UnknownType, dimensions));
+			}
+			if (sizeArgumentExpressions != null)
+				ProcessConversionResults(sizeArgumentExpressions, acrr.SizeArguments);
+			if (acrr.InitializerElements != null)
+				ProcessConversionResults(initializerElements, acrr.InitializerElements);
+			return acrr;
+		}
+		
+		void UnpackArrayInitializer(List<Expression> elementList, int[] sizes, ArrayInitializerExpression initializer, int dimension, bool resolveNestedInitializersToVoid)
+		{
+			Debug.Assert(dimension < sizes.Length);
+			int elementCount = 0;
+			if (dimension + 1 < sizes.Length) {
+				foreach (var node in initializer.Elements) {
+					ArrayInitializerExpression aie = node as ArrayInitializerExpression;
+					if (aie != null) {
+						if (resolveNestedInitializersToVoid) {
+							StoreCurrentState(aie);
+							StoreResult(aie, voidResult);
+						}
+						UnpackArrayInitializer(elementList, sizes, aie, dimension + 1, resolveNestedInitializersToVoid);
+					} else {
+						elementList.Add(node);
+					}
+					elementCount++;
+				}
+			} else {
+				foreach (var expr in initializer.Elements) {
+					elementList.Add(expr);
+					elementCount++;
+				}
+			}
+			if (sizes[dimension] == 0) // 0 = uninitialized
+				sizes[dimension] = elementCount;
+			else if (sizes[dimension] != elementCount)
+				sizes[dimension] = -1; // -1 = error
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression)
+		{
+			// Array initializers are handled by their parent expression.
+			ScanChildren(arrayInitializerExpression);
+			return errorResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitAsExpression(AsExpression asExpression)
+		{
+			if (resolverEnabled) {
+				ResolveResult input = Resolve(asExpression.Expression);
+				var targetType = ResolveType(asExpression.Type);
+				return new CastResolveResult(targetType, input, Conversion.TryCast, resolver.CheckForOverflow);
+			} else {
+				ScanChildren(asExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitAssignmentExpression(AssignmentExpression assignmentExpression)
+		{
+			if (resolverEnabled) {
+				Expression left = assignmentExpression.Left;
+				Expression right = assignmentExpression.Right;
+				ResolveResult leftResult = Resolve(left);
+				ResolveResult rightResult = Resolve(right);
+				ResolveResult rr = resolver.ResolveAssignment(assignmentExpression.Operator, leftResult, rightResult);
+				ProcessConversionsInBinaryOperatorResult(left, right, rr);
+				return rr;
+			} else {
+				ScanChildren(assignmentExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitBaseReferenceExpression(BaseReferenceExpression baseReferenceExpression)
+		{
+			if (resolverEnabled) {
+				return resolver.ResolveBaseReference();
+			} else {
+				ScanChildren(baseReferenceExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+		{
+			if (resolverEnabled) {
+				Expression left = binaryOperatorExpression.Left;
+				Expression right = binaryOperatorExpression.Right;
+				ResolveResult leftResult = Resolve(left);
+				ResolveResult rightResult = Resolve(right);
+				ResolveResult rr = resolver.ResolveBinaryOperator(binaryOperatorExpression.Operator, leftResult, rightResult);
+				ProcessConversionsInBinaryOperatorResult(left, right, rr);
+				return rr;
+			} else {
+				ScanChildren(binaryOperatorExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult ProcessConversionsInBinaryOperatorResult(Expression left, Expression right, ResolveResult rr)
+		{
+			OperatorResolveResult orr = rr as OperatorResolveResult;
+			if (orr != null && orr.Operands.Count == 2) {
+				ProcessConversionResult(left, orr.Operands[0] as ConversionResolveResult);
+				ProcessConversionResult(right, orr.Operands[1] as ConversionResolveResult);
+			} else {
+				InvocationResolveResult irr = rr as InvocationResolveResult;
+				if (irr != null && irr.Arguments.Count == 2) {
+					ProcessConversionResult(left, irr.Arguments[0] as ConversionResolveResult);
+					ProcessConversionResult(right, irr.Arguments[1] as ConversionResolveResult);
+				}
+			}
+			return rr;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitCastExpression(CastExpression castExpression)
+		{
+			if (resolverEnabled) {
+				var targetType = ResolveType(castExpression.Type);
+				var expr = castExpression.Expression;
+				var rr = resolver.ResolveCast(targetType, Resolve(expr));
+				var crr = rr as ConversionResolveResult;
+				if (crr != null) {
+					Debug.Assert(!(crr is CastResolveResult));
+					ProcessConversion(expr, crr.Input, crr.Conversion, targetType);
+					rr = new CastResolveResult(crr);
+				}
+				return rr;
+			} else {
+				ScanChildren(castExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitConditionalExpression(ConditionalExpression conditionalExpression)
+		{
+			if (resolverEnabled) {
+				Expression condition = conditionalExpression.Condition;
+				Expression trueExpr = conditionalExpression.TrueExpression;
+				Expression falseExpr = conditionalExpression.FalseExpression;
+				
+				ResolveResult rr = resolver.ResolveConditional(Resolve(condition), Resolve(trueExpr), Resolve(falseExpr));
+				OperatorResolveResult corr = rr as OperatorResolveResult;
+				if (corr != null && corr.Operands.Count == 3) {
+					ProcessConversionResult(condition, corr.Operands[0] as ConversionResolveResult);
+					ProcessConversionResult(trueExpr, corr.Operands[1] as ConversionResolveResult);
+					ProcessConversionResult(falseExpr, corr.Operands[2] as ConversionResolveResult);
+				}
+				return rr;
+			} else {
+				ScanChildren(conditionalExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
+		{
+			if (resolverEnabled) {
+				return resolver.ResolveDefaultValue(ResolveType(defaultValueExpression.Type));
+			} else {
+				ScanChildren(defaultValueExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitDirectionExpression(DirectionExpression directionExpression)
+		{
+			if (resolverEnabled) {
+				ResolveResult rr = Resolve(directionExpression.Expression);
+				return new ByReferenceResolveResult(rr, directionExpression.FieldDirection == FieldDirection.Out);
+			} else {
+				ScanChildren(directionExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitIndexerExpression(IndexerExpression indexerExpression)
+		{
+			if (resolverEnabled || NeedsResolvingDueToNamedArguments(indexerExpression)) {
+				Expression target = indexerExpression.Target;
+				ResolveResult targetResult = Resolve(target);
+				string[] argumentNames;
+				ResolveResult[] arguments = GetArguments(indexerExpression.Arguments, out argumentNames);
+				ResolveResult rr = resolver.ResolveIndexer(targetResult, arguments, argumentNames);
+				ArrayAccessResolveResult aarr = rr as ArrayAccessResolveResult;
+				if (aarr != null) {
+					MarkUnknownNamedArguments(indexerExpression.Arguments);
+					ProcessConversionResults(indexerExpression.Arguments, aarr.Indexes);
+				} else {
+					ProcessInvocationResult(target, indexerExpression.Arguments, rr);
+				}
+				return rr;
+			} else {
+				ScanChildren(indexerExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitIsExpression(IsExpression isExpression)
+		{
+			if (resolverEnabled) {
+				ResolveResult input = Resolve(isExpression.Expression);
+				IType targetType = ResolveType(isExpression.Type);
+				IType booleanType = resolver.Compilation.FindType(KnownTypeCode.Boolean);
+				return new TypeIsResolveResult(input, targetType, booleanType);
+			} else {
+				ScanChildren(isExpression);
+				return null;
+			}
+		}
+		
+		// NamedArgumentExpression is "identifier: Expression"
+		ResolveResult IAstVisitor<ResolveResult>.VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression)
+		{
+			// The parent expression takes care of handling NamedArgumentExpressions
+			// by calling GetArguments().
+			// This method gets called only when scanning, or when the named argument is used
+			// in an invalid context.
+			if (resolverEnabled) {
+				return new NamedArgumentResolveResult(namedArgumentExpression.Name, Resolve(namedArgumentExpression.Expression));
+			} else {
+				Scan(namedArgumentExpression.Expression);
+				return null;
+			}
+		}
+		
+		// NamedExpression is "identifier = Expression" in object initializers and attributes
+		ResolveResult IAstVisitor<ResolveResult>.VisitNamedExpression(NamedExpression namedExpression)
+		{
+			// The parent expression takes care of handling NamedExpression
+			// by calling HandleObjectInitializer() or HandleNamedExpression().
+			// This method gets called only when scanning, or when the named expression is used
+			// in an invalid context.
+			ScanChildren(namedExpression);
+			return null;
+		}
+		
+		void HandleNamedExpression(NamedExpression namedExpression, List<ResolveResult> initializerStatements)
+		{
+			StoreCurrentState(namedExpression);
+			Expression rhs = namedExpression.Expression;
+			ResolveResult lhsRR = resolver.ResolveIdentifierInObjectInitializer(namedExpression.Name);
+			if (rhs is ArrayInitializerExpression) {
+				HandleObjectInitializer(lhsRR, (ArrayInitializerExpression)rhs, initializerStatements);
+			} else {
+				var rhsRR = Resolve(rhs);
+				var rr = resolver.ResolveAssignment(AssignmentOperatorType.Assign, lhsRR, rhsRR) as OperatorResolveResult;
+				if (rr != null) {
+					ProcessConversionResult(rhs, rr.Operands[1] as ConversionResolveResult);
+					initializerStatements.Add(rr);
+				}
+			}
+			StoreResult(namedExpression, lhsRR);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
+		{
+			return resolver.ResolvePrimitive(null);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
+		{
+			var typeResolveResult = Resolve(objectCreateExpression.Type);
+			if (typeResolveResult.IsError) {
+				ScanChildren (objectCreateExpression);
+				return typeResolveResult;
+			}
+			IType type = typeResolveResult.Type;
+			
+			List<ResolveResult> initializerStatements = null;
+			var initializer = objectCreateExpression.Initializer;
+			if (!initializer.IsNull) {
+				initializerStatements = new List<ResolveResult>();
+				HandleObjectInitializer(new InitializedObjectResolveResult(type), initializer, initializerStatements);
+			}
+			
+			string[] argumentNames;
+			ResolveResult[] arguments = GetArguments(objectCreateExpression.Arguments, out argumentNames);
+			
+			ResolveResult rr = resolver.ResolveObjectCreation(type, arguments, argumentNames, false, initializerStatements);
+			if (arguments.Length == 1 && rr.Type.Kind == TypeKind.Delegate) {
+				MarkUnknownNamedArguments(objectCreateExpression.Arguments);
+				// Apply conversion to argument if it directly wraps the argument
+				// (but not when creating a delegate from a delegate, as then there would be a MGRR for .Invoke in between)
+				// This is necessary for lambda type inference.
+				var crr = rr as ConversionResolveResult;
+				if (crr != null) {
+					if (objectCreateExpression.Arguments.Count == 1)
+						ProcessConversionResult(objectCreateExpression.Arguments.Single(), crr);
+					
+					// wrap the result so that the delegate creation is not handled as a reference
+					// to the target method - otherwise FindReferencedEntities would produce two results for
+					// the same delegate creation.
+					return new CastResolveResult(crr);
+				} else {
+					return rr;
+				}
+			} else {
+				// process conversions in all other cases
+				ProcessInvocationResult(null, objectCreateExpression.Arguments, rr);
+				return rr;
+			}
+		}
+		
+		void HandleObjectInitializer(ResolveResult initializedObject, ArrayInitializerExpression initializer, List<ResolveResult> initializerStatements)
+		{
+			StoreCurrentState(initializer);
+			resolver = resolver.PushObjectInitializer(initializedObject);
+			foreach (Expression element in initializer.Elements) {
+				ArrayInitializerExpression aie = element as ArrayInitializerExpression;
+				if (aie != null) {
+					StoreCurrentState(aie);
+					// constructor argument list in collection initializer
+					ResolveResult[] addArguments = new ResolveResult[aie.Elements.Count];
+					int i = 0;
+					foreach (var addArgument in aie.Elements) {
+						addArguments[i++] = Resolve(addArgument);
+					}
+					MemberLookup memberLookup = resolver.CreateMemberLookup();
+					var addRR = memberLookup.Lookup(initializedObject, "Add", EmptyList<IType>.Instance, true);
+					var mgrr = addRR as MethodGroupResolveResult;
+					if (mgrr != null) {
+						OverloadResolution or = mgrr.PerformOverloadResolution(resolver.Compilation, addArguments, null, false, false, false, resolver.CheckForOverflow, resolver.conversions);
+						var invocationRR = or.CreateResolveResult(initializedObject);
+						StoreResult(aie, invocationRR);
+						ProcessInvocationResult(null, aie.Elements, invocationRR);
+						initializerStatements.Add(invocationRR);
+					} else {
+						StoreResult(aie, addRR);
+					}
+				} else if (element is NamedExpression) {
+					HandleNamedExpression((NamedExpression)element, initializerStatements);
+				} else {
+					// unknown kind of expression
+					Scan(element);
+				}
+			}
+			resolver = resolver.PopObjectInitializer();
+			StoreResult(initializer, voidResult);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
+		{
+			if (resolverEnabled) {
+				return Resolve(parenthesizedExpression.Expression);
+			} else {
+				Scan(parenthesizedExpression.Expression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitPointerReferenceExpression(PointerReferenceExpression pointerReferenceExpression)
+		{
+			if (resolverEnabled) {
+				ResolveResult target = Resolve(pointerReferenceExpression.Target);
+				ResolveResult deferencedTarget = resolver.ResolveUnaryOperator(UnaryOperatorType.Dereference, target);
+				List<IType> typeArguments = new List<IType>();
+				foreach (AstType typeArgument in pointerReferenceExpression.TypeArguments) {
+					typeArguments.Add(ResolveType(typeArgument));
+				}
+				return resolver.ResolveMemberAccess(deferencedTarget, pointerReferenceExpression.MemberName,
+				                                    typeArguments,
+				                                    GetNameLookupMode(pointerReferenceExpression));
+			} else {
+				ScanChildren(pointerReferenceExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+		{
+			return resolver.ResolvePrimitive(primitiveExpression.Value);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitSizeOfExpression(SizeOfExpression sizeOfExpression)
+		{
+			return resolver.ResolveSizeOf(ResolveType(sizeOfExpression.Type));
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitStackAllocExpression(StackAllocExpression stackAllocExpression)
+		{
+			ResolveAndProcessConversion(stackAllocExpression.CountExpression, resolver.Compilation.FindType(KnownTypeCode.Int32));
+			return new ResolveResult(new PointerType(ResolveType(stackAllocExpression.Type)));
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitThisReferenceExpression(ThisReferenceExpression thisReferenceExpression)
+		{
+			return resolver.ResolveThisReference();
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitTypeOfExpression(TypeOfExpression typeOfExpression)
+		{
+			if (resolverEnabled) {
+				return resolver.ResolveTypeOf(ResolveType(typeOfExpression.Type));
+			} else {
+				Scan(typeOfExpression.Type);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression)
+		{
+			if (resolverEnabled) {
+				return Resolve(typeReferenceExpression.Type).ShallowClone();
+			} else {
+				Scan(typeReferenceExpression.Type);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+		{
+			if (resolverEnabled) {
+				Expression expr = unaryOperatorExpression.Expression;
+				ResolveResult input = Resolve(expr);
+				ITypeDefinition inputTypeDef = input.Type.GetDefinition();
+				if (input.IsCompileTimeConstant && expr is PrimitiveExpression && inputTypeDef != null) {
+					// Special cases for int.MinValue and long.MinValue
+					if (inputTypeDef.KnownTypeCode == KnownTypeCode.UInt32 && 2147483648.Equals(input.ConstantValue)) {
+						return new ConstantResolveResult(resolver.Compilation.FindType(KnownTypeCode.Int32), -2147483648);
+					} else if (inputTypeDef.KnownTypeCode == KnownTypeCode.UInt64 && 9223372036854775808.Equals(input.ConstantValue)) {
+						return new ConstantResolveResult(resolver.Compilation.FindType(KnownTypeCode.Int64), -9223372036854775808);
+					}
+				}
+				ResolveResult rr = resolver.ResolveUnaryOperator(unaryOperatorExpression.Operator, input);
+				OperatorResolveResult uorr = rr as OperatorResolveResult;
+				if (uorr != null && uorr.Operands.Count == 1) {
+					ProcessConversionResult(expr, uorr.Operands[0] as ConversionResolveResult);
+				} else {
+					InvocationResolveResult irr = rr as InvocationResolveResult;
+					if (irr != null && irr.Arguments.Count == 1) {
+						ProcessConversionResult(expr, irr.Arguments[0] as ConversionResolveResult);
+					}
+				}
+				return rr;
+			} else {
+				ScanChildren(unaryOperatorExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUndocumentedExpression(UndocumentedExpression undocumentedExpression)
+		{
+			ScanChildren(undocumentedExpression);
+			IType resultType;
+			switch (undocumentedExpression.UndocumentedExpressionType) {
+				case UndocumentedExpressionType.ArgListAccess:
+				case UndocumentedExpressionType.ArgList:
+					resultType = resolver.Compilation.FindType(typeof(RuntimeArgumentHandle));
+					break;
+				case UndocumentedExpressionType.RefValue:
+					var tre = undocumentedExpression.Arguments.ElementAtOrDefault(1) as TypeReferenceExpression;
+					if (tre != null)
+						resultType = ResolveType(tre.Type);
+					else
+						resultType = SpecialType.UnknownType;
+					break;
+				case UndocumentedExpressionType.RefType:
+					resultType = resolver.Compilation.FindType(KnownTypeCode.Type);
+					break;
+				case UndocumentedExpressionType.MakeRef:
+					resultType = resolver.Compilation.FindType(typeof(TypedReference));
+					break;
+				default:
+					throw new InvalidOperationException("Invalid value for UndocumentedExpressionType");
+			}
+			return new ResolveResult(resultType);
+		}
+		#endregion
+		
+		#region Visit Identifier/MemberReference/Invocation-Expression
+		// IdentifierExpression, MemberReferenceExpression and InvocationExpression
+		// are grouped together because they have to work together for
+		// "7.6.4.1 Identical simple names and type names" support
+		List<IType> ResolveTypeArguments(IEnumerable<AstType> typeArguments)
+		{
+			List<IType> result = new List<IType>();
+			foreach (AstType typeArgument in typeArguments) {
+				result.Add(ResolveType(typeArgument));
+			}
+			return result;
+		}
+		
+		/// <summary>
+		/// Gets and resolves the arguments; unpacking any NamedArgumentExpressions.
+		/// </summary>
+		/// <remarks>
+		/// Callers of GetArguments must also call either ProcessConversionsInInvocation or MarkUnknownNamedArguments
+		/// to ensure the named arguments get resolved.
+		/// Also, as named arguments get resolved by the parent node, the parent node must not scan
+		/// into the argument list without being resolved - see NeedsResolvingDueToNamedArguments().
+		/// </remarks>
+		ResolveResult[] GetArguments(IEnumerable<Expression> argumentExpressions, out string[] argumentNames)
+		{
+			argumentNames = null;
+			ResolveResult[] arguments = new ResolveResult[argumentExpressions.Count()];
+			int i = 0;
+			foreach (AstNode argument in argumentExpressions) {
+				NamedArgumentExpression nae = argument as NamedArgumentExpression;
+				AstNode argumentValue;
+				if (nae != null) {
+					if (argumentNames == null)
+						argumentNames = new string[arguments.Length];
+					argumentNames[i] = nae.Name;
+					argumentValue = nae.Expression;
+				} else {
+					argumentValue = argument;
+				}
+				arguments[i++] = Resolve(argumentValue);
+			}
+			return arguments;
+		}
+		
+		bool NeedsResolvingDueToNamedArguments(Expression nodeWithArguments)
+		{
+			for (AstNode child = nodeWithArguments.FirstChild; child != null; child = child.NextSibling) {
+				if (child is NamedArgumentExpression)
+					return true;
+			}
+			return false;
+		}
+
+		static NameLookupMode GetNameLookupMode(Expression expr)
+		{
+			InvocationExpression ie = expr.Parent as InvocationExpression;
+			if (ie != null && ie.Target == expr)
+				return NameLookupMode.InvocationTarget;
+			else
+				return NameLookupMode.Expression;
+		}
+
+		/// <summary>
+		/// Gets whether 'rr' is considered a static access on the target identifier.
+		/// </summary>
+		/// <param name="rr">Resolve Result of the MemberReferenceExpression</param>
+		/// <param name="invocationRR">Resolve Result of the InvocationExpression</param>
+		bool IsStaticResult(ResolveResult rr, ResolveResult invocationRR)
+		{
+			if (rr is TypeResolveResult)
+				return true;
+			MemberResolveResult mrr = (rr is MethodGroupResolveResult ? invocationRR : rr) as MemberResolveResult;
+			return mrr != null && mrr.Member.IsStatic;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitIdentifierExpression(IdentifierExpression identifierExpression)
+		{
+			// Note: this method is not called when it occurs in a situation where an ambiguity between
+			// simple names and type names might occur.
+			if (resolverEnabled) {
+				var typeArguments = ResolveTypeArguments(identifierExpression.TypeArguments);
+				var lookupMode = GetNameLookupMode(identifierExpression);
+				return resolver.LookupSimpleNameOrTypeName(
+					identifierExpression.Identifier, typeArguments, lookupMode);
+			} else {
+				ScanChildren(identifierExpression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+		{
+			// target = Resolve(identifierExpression = memberReferenceExpression.Target)
+			// trr = ResolveType(identifierExpression)
+			// rr = Resolve(memberReferenceExpression)
+			
+			IdentifierExpression identifierExpression = memberReferenceExpression.Target as IdentifierExpression;
+			if (identifierExpression != null && identifierExpression.TypeArguments.Count == 0) {
+				// Special handling for §7.6.4.1 Identicial simple names and type names
+				StoreCurrentState(identifierExpression);
+				ResolveResult target = resolver.ResolveSimpleName(identifierExpression.Identifier, EmptyList<IType>.Instance);
+				TypeResolveResult trr;
+				if (resolver.IsVariableReferenceWithSameType(target, identifierExpression.Identifier, out trr)) {
+					// It's ambiguous
+					ResolveResult rr = ResolveMemberReferenceOnGivenTarget(target, memberReferenceExpression);
+					ResolveResult simpleNameRR = IsStaticResult(rr, null) ? trr : target;
+					Log.WriteLine("Ambiguous simple name '{0}' was resolved to {1}", identifierExpression, simpleNameRR);
+					StoreResult(identifierExpression, simpleNameRR);
+					return rr;
+				} else {
+					// It's not ambiguous
+					Log.WriteLine("Simple name '{0}' was resolved to {1}", identifierExpression, target);
+					StoreResult(identifierExpression, target);
+					return ResolveMemberReferenceOnGivenTarget(target, memberReferenceExpression);
+				}
+			} else {
+				// Regular code path
+				if (resolverEnabled) {
+					ResolveResult target = Resolve(memberReferenceExpression.Target);
+					return ResolveMemberReferenceOnGivenTarget(target, memberReferenceExpression);
+				} else {
+					ScanChildren(memberReferenceExpression);
+					return null;
+				}
+			}
+		}
+		
+		ResolveResult ResolveMemberReferenceOnGivenTarget(ResolveResult target, MemberReferenceExpression memberReferenceExpression)
+		{
+			var typeArguments = ResolveTypeArguments(memberReferenceExpression.TypeArguments);
+			return resolver.ResolveMemberAccess(
+				target, memberReferenceExpression.MemberName, typeArguments,
+				GetNameLookupMode(memberReferenceExpression));
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitInvocationExpression(InvocationExpression invocationExpression)
+		{
+			// rr = Resolve(invocationExpression)
+			// target = Resolve(memberReferenceExpression = invocationExpression.Target)
+			// idRR = Resolve(identifierExpression = memberReferenceExpression.Target)
+			// trr = ResolveType(identifierExpression)
+			
+			MemberReferenceExpression mre = invocationExpression.Target as MemberReferenceExpression;
+			IdentifierExpression identifierExpression = mre != null ? mre.Target as IdentifierExpression : null;
+			if (identifierExpression != null && identifierExpression.TypeArguments.Count == 0) {
+				// Special handling for §7.6.4.1 Identicial simple names and type names
+				
+				StoreCurrentState(identifierExpression);
+				StoreCurrentState(mre);
+				
+				ResolveResult idRR = resolver.ResolveSimpleName(identifierExpression.Identifier, EmptyList<IType>.Instance);
+				ResolveResult target = ResolveMemberReferenceOnGivenTarget(idRR, mre);
+				Log.WriteLine("Member reference '{0}' on potentially-ambiguous simple-name was resolved to {1}", mre, target);
+				StoreResult(mre, target);
+				TypeResolveResult trr;
+				if (resolver.IsVariableReferenceWithSameType(idRR, identifierExpression.Identifier, out trr)) {
+					// It's ambiguous
+					ResolveResult rr = ResolveInvocationOnGivenTarget(target, invocationExpression);
+					ResolveResult simpleNameRR = IsStaticResult(target, rr) ? trr : idRR;
+					Log.WriteLine("Ambiguous simple name '{0}' was resolved to {1}",
+					              identifierExpression, simpleNameRR);
+					StoreResult(identifierExpression, simpleNameRR);
+					return rr;
+				} else {
+					// It's not ambiguous
+					Log.WriteLine("Simple name '{0}' was resolved to {1}", identifierExpression, idRR);
+					StoreResult(identifierExpression, idRR);
+					return ResolveInvocationOnGivenTarget(target, invocationExpression);
+				}
+			} else {
+				// Regular code path
+				if (resolverEnabled || NeedsResolvingDueToNamedArguments(invocationExpression)) {
+					ResolveResult target = Resolve(invocationExpression.Target);
+					return ResolveInvocationOnGivenTarget(target, invocationExpression);
+				} else {
+					ScanChildren(invocationExpression);
+					return null;
+				}
+			}
+		}
+		
+		ResolveResult ResolveInvocationOnGivenTarget(ResolveResult target, InvocationExpression invocationExpression)
+		{
+			string[] argumentNames;
+			ResolveResult[] arguments = GetArguments(invocationExpression.Arguments, out argumentNames);
+			ResolveResult rr = resolver.ResolveInvocation(target, arguments, argumentNames);
+			ProcessInvocationResult(invocationExpression.Target, invocationExpression.Arguments, rr);
+			return rr;
+		}
+		#endregion
+		
+		#region Lamdbas / Anonymous Functions
+		ResolveResult IAstVisitor<ResolveResult>.VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
+		{
+			return HandleExplicitlyTypedLambda(
+				anonymousMethodExpression.Parameters, anonymousMethodExpression.Body,
+				isAnonymousMethod: true,
+				hasParameterList: anonymousMethodExpression.HasParameterList,
+				isAsync: anonymousMethodExpression.IsAsync);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitLambdaExpression(LambdaExpression lambdaExpression)
+		{
+			bool isExplicitlyTyped = false;
+			bool isImplicitlyTyped = false;
+			foreach (var p in lambdaExpression.Parameters) {
+				isImplicitlyTyped |= p.Type.IsNull;
+				isExplicitlyTyped |= !p.Type.IsNull;
+			}
+			if (isExplicitlyTyped || !isImplicitlyTyped) {
+				return HandleExplicitlyTypedLambda(
+					lambdaExpression.Parameters, lambdaExpression.Body,
+					isAnonymousMethod: false, hasParameterList: true, isAsync: lambdaExpression.IsAsync);
+			} else {
+				return new ImplicitlyTypedLambda(lambdaExpression, this);
+			}
+		}
+		
+		#region Explicitly typed
+		ExplicitlyTypedLambda HandleExplicitlyTypedLambda(
+			AstNodeCollection<ParameterDeclaration> parameterDeclarations,
+			AstNode body, bool isAnonymousMethod, bool hasParameterList, bool isAsync)
+		{
+			CSharpResolver oldResolver = resolver;
+			List<IParameter> parameters = (hasParameterList || parameterDeclarations.Any()) ? new List<IParameter>() : null;
+			//bool oldIsWithinLambdaExpression = resolver.IsWithinLambdaExpression;
+			resolver = resolver.WithIsWithinLambdaExpression(true);
+			foreach (var pd in parameterDeclarations) {
+				IType type = ResolveType(pd.Type);
+				if (pd.ParameterModifier == ParameterModifier.Ref || pd.ParameterModifier == ParameterModifier.Out)
+					type = new ByReferenceType(type);
+				
+				IParameter p = new DefaultParameter(type, pd.Name,
+				                                    region: MakeRegion(pd),
+				                                    isRef: pd.ParameterModifier == ParameterModifier.Ref,
+				                                    isOut: pd.ParameterModifier == ParameterModifier.Out);
+				// The parameter declaration must be scanned in the current context (without the new parameter)
+				// in order to be consistent with the context in which we resolved pd.Type.
+				StoreCurrentState(pd);
+				StoreResult(pd, new LocalResolveResult(p));
+				ScanChildren(pd);
+				
+				resolver = resolver.AddVariable(p);
+				parameters.Add(p);
+			}
+			
+			var lambda = new ExplicitlyTypedLambda(parameters, isAnonymousMethod, isAsync, resolver, this, body);
+			
+			// Don't scan the lambda body here - we'll do that later when analyzing the ExplicitlyTypedLambda.
+			
+			resolver = oldResolver;
+			return lambda;
+		}
+		
+		DomRegion MakeRegion(AstNode node)
+		{
+			if (unresolvedFile != null)
+				return new DomRegion(unresolvedFile.FileName, node.StartLocation, node.EndLocation);
+			else
+				return node.GetRegion();
+		}
+		
+		sealed class ExplicitlyTypedLambda : LambdaBase
+		{
+			readonly IList<IParameter> parameters;
+			readonly bool isAnonymousMethod;
+			readonly bool isAsync;
+			
+			CSharpResolver storedContext;
+			ResolveVisitor visitor;
+			AstNode body;
+			ResolveResult bodyRR;
+			
+			IType inferredReturnType;
+			IList<Expression> returnExpressions;
+			IList<ResolveResult> returnValues;
+			bool isValidAsVoidMethod;
+			bool isEndpointUnreachable;
+			
+			// The actual return type is set when the lambda is applied by the conversion.
+			// For async lambdas, this includes the task type
+			IType actualReturnType;
+			
+			internal override bool IsUndecided {
+				get { return actualReturnType == null; }
+			}
+			
+			internal override AstNode LambdaExpression {
+				get { return body.Parent; }
+			}
+			
+			internal override AstNode BodyExpression {
+				get { return body; }
+			}
+			
+			public override ResolveResult Body {
+				get {
+					if (bodyRR != null)
+						return bodyRR;
+
+					if (body is Expression) {
+						Analyze();
+						if (returnValues.Count == 1) {
+							bodyRR = returnValues[0];
+							if (actualReturnType != null) {
+								IType unpackedActualReturnType = isAsync ? visitor.UnpackTask(actualReturnType) : actualReturnType;
+								if (unpackedActualReturnType.Kind != TypeKind.Void) {
+									var conv = storedContext.conversions.ImplicitConversion(bodyRR, unpackedActualReturnType);
+									if (!conv.IsIdentityConversion)
+										bodyRR = new ConversionResolveResult(unpackedActualReturnType, bodyRR, conv, storedContext.CheckForOverflow);
+								}
+							}
+							return bodyRR;
+						}
+					}
+					return bodyRR = visitor.voidResult;
+				}
+			}
+			
+			public ExplicitlyTypedLambda(IList<IParameter> parameters, bool isAnonymousMethod, bool isAsync, CSharpResolver storedContext, ResolveVisitor visitor, AstNode body)
+			{
+				this.parameters = parameters;
+				this.isAnonymousMethod = isAnonymousMethod;
+				this.isAsync = isAsync;
+				this.storedContext = storedContext;
+				this.visitor = visitor;
+				this.body = body;
+				
+				if (visitor.undecidedLambdas == null)
+					visitor.undecidedLambdas = new List<LambdaBase>();
+				visitor.undecidedLambdas.Add(this);
+				Log.WriteLine("Added undecided explicitly-typed lambda: " + this.LambdaExpression);
+			}
+			
+			public override IList<IParameter> Parameters {
+				get {
+					return parameters ?? EmptyList<IParameter>.Instance;
+				}
+			}
+			
+			bool Analyze()
+			{
+				// If it's not already analyzed
+				if (inferredReturnType == null) {
+					Log.WriteLine("Analyzing " + this.LambdaExpression + "...");
+					Log.Indent();
+					
+					visitor.ResetContext(
+						storedContext,
+						delegate {
+							var oldNavigator = visitor.navigator;
+							visitor.navigator = new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Resolve, oldNavigator);
+							visitor.AnalyzeLambda(body, isAsync, out isValidAsVoidMethod, out isEndpointUnreachable, out inferredReturnType, out returnExpressions, out returnValues);
+							visitor.navigator = oldNavigator;
+						});
+					Log.Unindent();
+					Log.WriteLine("Finished analyzing " + this.LambdaExpression);
+					
+					if (inferredReturnType == null)
+						throw new InvalidOperationException("AnalyzeLambda() didn't set inferredReturnType");
+				}
+				return true;
+			}
+			
+			public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
+			{
+				Log.WriteLine("Testing validity of {0} for return-type {1}...", this, returnType);
+				Log.Indent();
+				bool valid = Analyze() && IsValidLambda(isValidAsVoidMethod, isEndpointUnreachable, isAsync, returnValues, returnType, conversions);
+				Log.Unindent();
+				Log.WriteLine("{0} is {1} for return-type {2}", this, valid ? "valid" : "invalid", returnType);
+				return new AnonymousFunctionConversion(returnType, this, valid);
+			}
+			
+			public override IType GetInferredReturnType(IType[] parameterTypes)
+			{
+				Analyze();
+				return inferredReturnType;
+			}
+			
+			public override IType ReturnType {
+				get {
+					return actualReturnType ?? SpecialType.UnknownType;
+				}
+			}
+			
+			public override bool IsImplicitlyTyped {
+				get { return false; }
+			}
+			
+			public override bool IsAsync {
+				get { return isAsync; }
+			}
+			
+			public override bool IsAnonymousMethod {
+				get { return isAnonymousMethod; }
+			}
+			
+			public override bool HasParameterList {
+				get { return parameters != null; }
+			}
+			
+			public override string ToString()
+			{
+				return "[ExplicitlyTypedLambda " + this.LambdaExpression + "]";
+			}
+			
+			public void ApplyReturnType(ResolveVisitor parentVisitor, IType returnType)
+			{
+				if (returnType == null)
+					throw new ArgumentNullException("returnType");
+				if (parentVisitor != visitor) {
+					// Explicitly typed lambdas do not use a nested visitor
+					throw new InvalidOperationException();
+				}
+				if (actualReturnType != null) {
+					if (actualReturnType.Equals(returnType))
+						return; // return type already set
+					throw new InvalidOperationException("inconsistent return types for explicitly-typed lambda");
+				}
+				actualReturnType = returnType;
+				visitor.undecidedLambdas.Remove(this);
+				Analyze();
+				IType unpackedReturnType = isAsync ? visitor.UnpackTask(returnType) : returnType;
+				Log.WriteLine("Applying return type {0} to explicitly-typed lambda {1}", unpackedReturnType, this.LambdaExpression);
+				if (unpackedReturnType.Kind != TypeKind.Void || body is BlockStatement) {
+					for (int i = 0; i < returnExpressions.Count; i++) {
+						visitor.ProcessConversion(returnExpressions[i], returnValues[i], unpackedReturnType);
+					}
+				}
+			}
+			
+			internal override void EnforceMerge(ResolveVisitor parentVisitor)
+			{
+				ApplyReturnType(parentVisitor, SpecialType.UnknownType);
+			}
+		}
+		#endregion
+		
+		#region Implicitly typed
+		// Implicitly-typed lambdas are really complex, as the lambda depends on the target type (the delegate to which
+		// the lambda is converted), but figuring out the target type might involve overload resolution (for method
+		// calls in which the lambda is used as argument), which requires knowledge about the lamdba.
+		// 
+		// The implementation in NRefactory works like this:
+		// 1. The lambda resolves to a ImplicitlyTypedLambda (derived from LambdaResolveResult).
+		//     The lambda body is not resolved yet (one of the few places where ResolveVisitor
+		//     deviates from the usual depth-first AST traversal).
+		// 2. The parent statement is resolved as usual. This might require analyzing the lambda in detail (for example
+		//    as part of overload resolution). Such analysis happens using LambdaResolveResult.IsValid, where the caller
+		//    (i.e. the overload resolution algorithm) supplies the parameter types to the lambda body. For every IsValid()
+		//    call, a nested LambdaTypeHypothesis is constructed for analyzing the lambda using the supplied type assignment.
+		//    Multiple IsValid() calls may use several LambdaTypeHypothesis instances, one for each set of parameter types.
+		// 3. When the resolver reports the conversions that occurred as part of the parent statement (as with any
+		//    conversions), the results from the LambdaTypeHypothesis corresponding to the actually chosen
+		//    conversion are merged into the main resolver.
+		// 4. LambdaResolveResult.Body is set to the main resolve result from the chosen nested resolver. I think this
+		//    is the only place where NRefactory is mutating a ResolveResult (normally all resolve results are immutable).
+		//    As this step is guaranteed to occur before the resolver returns the LamdbaResolveResult to user code, the
+		//    mutation shouldn't cause any problems.
+		sealed class ImplicitlyTypedLambda : LambdaBase
+		{
+			readonly LambdaExpression lambda;
+			readonly QuerySelectClause selectClause;
+			
+			readonly CSharpResolver storedContext;
+			readonly CSharpUnresolvedFile unresolvedFile;
+			readonly List<LambdaTypeHypothesis> hypotheses = new List<LambdaTypeHypothesis>();
+			internal IList<IParameter> parameters = new List<IParameter>();
+			
+			internal IType actualReturnType;
+			internal LambdaTypeHypothesis winningHypothesis;
+			internal ResolveResult bodyResult;
+			internal readonly ResolveVisitor parentVisitor;
+			
+			internal override bool IsUndecided {
+				get { return winningHypothesis == null;  }
+			}
+			
+			internal override AstNode LambdaExpression {
+				get {
+					if (selectClause != null)
+						return selectClause.Expression;
+					else
+						return lambda;
+				}
+			}
+			
+			internal override AstNode BodyExpression {
+				get {
+					if (selectClause != null)
+						return selectClause.Expression;
+					else
+						return lambda.Body;
+				}
+			}
+			
+			public override ResolveResult Body {
+				get { return bodyResult; }
+			}
+			
+			private ImplicitlyTypedLambda(ResolveVisitor parentVisitor)
+			{
+				this.parentVisitor = parentVisitor;
+				this.storedContext = parentVisitor.resolver;
+				this.unresolvedFile = parentVisitor.unresolvedFile;
+				this.bodyResult = parentVisitor.voidResult;
+			}
+			
+			public ImplicitlyTypedLambda(LambdaExpression lambda, ResolveVisitor parentVisitor)
+				: this(parentVisitor)
+			{
+				this.lambda = lambda;
+				foreach (var pd in lambda.Parameters) {
+					parameters.Add(new DefaultParameter(SpecialType.UnknownType, pd.Name, region: parentVisitor.MakeRegion(pd)));
+				}
+				RegisterUndecidedLambda();
+			}
+			
+			public ImplicitlyTypedLambda(QuerySelectClause selectClause, IEnumerable<IParameter> parameters, ResolveVisitor parentVisitor)
+				: this(parentVisitor)
+			{
+				this.selectClause = selectClause;
+				foreach (IParameter p in parameters)
+					this.parameters.Add(p);
+				
+				RegisterUndecidedLambda();
+			}
+			
+			void RegisterUndecidedLambda()
+			{
+				if (parentVisitor.undecidedLambdas == null)
+					parentVisitor.undecidedLambdas = new List<LambdaBase>();
+				parentVisitor.undecidedLambdas.Add(this);
+				Log.WriteLine("Added undecided implicitly-typed lambda: " + this.LambdaExpression);
+			}
+			
+			public override IList<IParameter> Parameters {
+				get { return parameters; }
+			}
+			
+			public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
+			{
+				Log.WriteLine("Testing validity of {0} for parameters ({1}) and return-type {2}...",
+				              this, string.Join<IType>(", ", parameterTypes), returnType);
+				Log.Indent();
+				var hypothesis = GetHypothesis(parameterTypes);
+				Conversion c = hypothesis.IsValid(returnType, conversions);
+				Log.Unindent();
+				Log.WriteLine("{0} is {1} for return-type {2}", hypothesis, c.IsValid ? "valid" : "invalid", returnType);
+				return c;
+			}
+			
+			public override IType GetInferredReturnType(IType[] parameterTypes)
+			{
+				return GetHypothesis(parameterTypes).inferredReturnType;
+			}
+			
+			LambdaTypeHypothesis GetHypothesis(IType[] parameterTypes)
+			{
+				if (parameterTypes.Length != parameters.Count)
+					throw new ArgumentException("Incorrect parameter type count");
+				foreach (var h in hypotheses) {
+					bool ok = true;
+					for (int i = 0; i < parameterTypes.Length; i++) {
+						if (!parameterTypes[i].Equals(h.parameterTypes[i])) {
+							ok = false;
+							break;
+						}
+					}
+					if (ok)
+						return h;
+				}
+				ResolveVisitor visitor = new ResolveVisitor(storedContext, unresolvedFile);
+				var newHypothesis = new LambdaTypeHypothesis(this, parameterTypes, visitor, lambda != null ? lambda.Parameters : null, storedContext);
+				hypotheses.Add(newHypothesis);
+				return newHypothesis;
+			}
+			
+			/// <summary>
+			/// Get any hypothesis for this lambda.
+			/// This method is used as fallback if the lambda isn't merged the normal way (AnonymousFunctionConversion)
+			/// </summary>
+			internal LambdaTypeHypothesis GetAnyHypothesis()
+			{
+				if (winningHypothesis != null)
+					return winningHypothesis;
+				if (hypotheses.Count == 0) {
+					// make a new hypothesis with unknown parameter types
+					IType[] parameterTypes = new IType[parameters.Count];
+					for (int i = 0; i < parameterTypes.Length; i++) {
+						parameterTypes[i] = SpecialType.UnknownType;
+					}
+					return GetHypothesis(parameterTypes);
+				} else {
+					// We have the choice, so pick the hypothesis with the least missing parameter types
+					LambdaTypeHypothesis bestHypothesis = hypotheses[0];
+					int bestHypothesisUnknownParameters = bestHypothesis.CountUnknownParameters();
+					for (int i = 1; i < hypotheses.Count; i++) {
+						int c = hypotheses[i].CountUnknownParameters();
+						if (c < bestHypothesisUnknownParameters ||
+						    (c == bestHypothesisUnknownParameters && hypotheses[i].success && !bestHypothesis.success))
+						{
+							bestHypothesis = hypotheses[i];
+							bestHypothesisUnknownParameters = c;
+						}
+					}
+					return bestHypothesis;
+				}
+			}
+			
+			internal override void EnforceMerge(ResolveVisitor parentVisitor)
+			{
+				GetAnyHypothesis().MergeInto(parentVisitor, SpecialType.UnknownType);
+			}
+			
+			public override IType ReturnType {
+				get { return actualReturnType ?? SpecialType.UnknownType; }
+			}
+			
+			public override bool IsImplicitlyTyped {
+				get { return true; }
+			}
+			
+			public override bool IsAnonymousMethod {
+				get { return false; }
+			}
+			
+			public override bool HasParameterList {
+				get { return true; }
+			}
+			
+			public override bool IsAsync {
+				get { return lambda != null && lambda.IsAsync; }
+			}
+			
+			public override string ToString()
+			{
+				return "[ImplicitlyTypedLambda " + this.LambdaExpression + "]";
+			}
+		}
+		
+		/// <summary>
+		/// Every possible set of parameter types gets its own 'hypothetical world'.
+		/// It uses a nested ResolveVisitor that has its own resolve cache, so that resolve results cannot leave the hypothetical world.
+		/// 
+		/// Only after overload resolution is applied and the actual parameter types are known, the winning hypothesis will be merged
+		/// with the parent ResolveVisitor.
+		/// This is done when the AnonymousFunctionConversion is applied on the parent visitor.
+		/// </summary>
+		sealed class LambdaTypeHypothesis : IResolveVisitorNavigator
+		{
+			readonly ImplicitlyTypedLambda lambda;
+			readonly IParameter[] lambdaParameters;
+			internal readonly IType[] parameterTypes;
+			readonly ResolveVisitor visitor;
+			readonly CSharpResolver storedContext;
+			
+			internal readonly IType inferredReturnType;
+			IList<Expression> returnExpressions;
+			IList<ResolveResult> returnValues;
+			bool isValidAsVoidMethod;
+			bool isEndpointUnreachable;
+			internal bool success;
+			
+			public LambdaTypeHypothesis(ImplicitlyTypedLambda lambda, IType[] parameterTypes, ResolveVisitor visitor,
+			                            ICollection<ParameterDeclaration> parameterDeclarations, CSharpResolver storedContext)
+			{
+				Debug.Assert(parameterTypes.Length == lambda.Parameters.Count);
+				
+				this.lambda = lambda;
+				this.parameterTypes = parameterTypes;
+				this.visitor = visitor;
+				this.storedContext = storedContext;
+				visitor.SetNavigator(this);
+				
+				Log.WriteLine("Analyzing " + ToString() + "...");
+				Log.Indent();
+				CSharpResolver oldResolver = visitor.resolver;
+				visitor.resolver = visitor.resolver.WithIsWithinLambdaExpression(true);
+				lambdaParameters = new IParameter[parameterTypes.Length];
+				if (parameterDeclarations != null) {
+					int i = 0;
+					foreach (var pd in parameterDeclarations) {
+						lambdaParameters[i] = new DefaultParameter(parameterTypes[i], pd.Name, region: visitor.MakeRegion(pd));
+						visitor.resolver = visitor.resolver.AddVariable(lambdaParameters[i]);
+						i++;
+						visitor.Scan(pd);
+					}
+				} else {
+					for (int i = 0; i < parameterTypes.Length; i++) {
+						var p = lambda.Parameters[i];
+						lambdaParameters[i] = new DefaultParameter(parameterTypes[i], p.Name, region: p.Region);
+						visitor.resolver = visitor.resolver.AddVariable(lambdaParameters[i]);
+					}
+				}
+				
+				success = true;
+				visitor.AnalyzeLambda(lambda.BodyExpression, lambda.IsAsync, out isValidAsVoidMethod, out isEndpointUnreachable, out inferredReturnType, out returnExpressions, out returnValues);
+				visitor.resolver = oldResolver;
+				Log.Unindent();
+				Log.WriteLine("Finished analyzing " + ToString());
+			}
+			
+			ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
+			{
+				return ResolveVisitorNavigationMode.Resolve;
+			}
+			
+			void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
+			{
+				if (result.IsError)
+					success = false;
+			}
+			
+			void IResolveVisitorNavigator.ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
+			{
+				success &= conversion.IsValid;
+			}
+			
+			internal int CountUnknownParameters()
+			{
+				int c = 0;
+				foreach (IType t in parameterTypes) {
+					if (t.Kind == TypeKind.Unknown)
+						c++;
+				}
+				return c;
+			}
+			
+			public Conversion IsValid(IType returnType, CSharpConversions conversions)
+			{
+				bool valid = success && IsValidLambda(isValidAsVoidMethod, isEndpointUnreachable, lambda.IsAsync, returnValues, returnType, conversions);
+				return new AnonymousFunctionConversion(returnType, this, valid);
+			}
+			
+			public void MergeInto(ResolveVisitor parentVisitor, IType returnType)
+			{
+				if (returnType == null)
+					throw new ArgumentNullException("returnType");
+				if (parentVisitor != lambda.parentVisitor)
+					throw new InvalidOperationException("parent visitor mismatch");
+				
+				if (lambda.winningHypothesis == this)
+					return;
+				else if (lambda.winningHypothesis != null)
+					throw new InvalidOperationException("Trying to merge conflicting hypotheses");
+				
+				lambda.actualReturnType = returnType;
+				if (lambda.IsAsync)
+					returnType = parentVisitor.UnpackTask(returnType);
+				
+				lambda.winningHypothesis = this;
+				lambda.parameters = lambdaParameters; // replace untyped parameters with typed parameters
+				if (lambda.BodyExpression is Expression && returnValues.Count == 1) {
+					lambda.bodyResult = returnValues[0];
+					if (returnType.Kind != TypeKind.Void) {
+						var conv = storedContext.conversions.ImplicitConversion(lambda.bodyResult, returnType);
+						if (!conv.IsIdentityConversion)
+							lambda.bodyResult = new ConversionResolveResult(returnType, lambda.bodyResult, conv, storedContext.CheckForOverflow);
+					}
+				}
+				
+				Log.WriteLine("Applying return type {0} to implicitly-typed lambda {1}", returnType, lambda.LambdaExpression);
+				if (returnType.Kind != TypeKind.Void || lambda.BodyExpression is Statement) {
+					for (int i = 0; i < returnExpressions.Count; i++) {
+						visitor.ProcessConversion(returnExpressions[i], returnValues[i], returnType);
+					}
+				}
+				
+				visitor.MergeUndecidedLambdas();
+				Log.WriteLine("Merging " + ToString());
+				foreach (var pair in visitor.resolverBeforeDict) {
+					Debug.Assert(!parentVisitor.resolverBeforeDict.ContainsKey(pair.Key));
+					parentVisitor.resolverBeforeDict[pair.Key] = pair.Value;
+				}
+				foreach (var pair in visitor.resolverAfterDict) {
+					Debug.Assert(!parentVisitor.resolverAfterDict.ContainsKey(pair.Key));
+					parentVisitor.resolverAfterDict[pair.Key] = pair.Value;
+				}
+				foreach (var pair in visitor.resolveResultCache) {
+					parentVisitor.StoreResult(pair.Key, pair.Value);
+				}
+				parentVisitor.ImportConversions(visitor);
+				parentVisitor.undecidedLambdas.Remove(lambda);
+			}
+			
+			public override string ToString()
+			{
+				StringBuilder b = new StringBuilder();
+				b.Append("[LambdaTypeHypothesis (");
+				for (int i = 0; i < parameterTypes.Length; i++) {
+					if (i > 0) b.Append(", ");
+					b.Append(parameterTypes[i]);
+					b.Append(' ');
+					b.Append(lambda.Parameters[i].Name);
+				}
+				b.Append(") => ");
+				b.Append(lambda.BodyExpression.ToString());
+				b.Append(']');
+				return b.ToString();
+			}
+		}
+		#endregion
+		
+		#region MergeUndecidedLambdas
+		abstract class LambdaBase : LambdaResolveResult
+		{
+			internal abstract bool IsUndecided { get; }
+			internal abstract AstNode LambdaExpression { get; }
+			internal abstract AstNode BodyExpression { get; }
+			
+			internal abstract void EnforceMerge(ResolveVisitor parentVisitor);
+			
+			public override ResolveResult ShallowClone()
+			{
+				if (IsUndecided)
+					throw new NotSupportedException();
+				return base.ShallowClone();
+			}
+		}
+		
+		void MergeUndecidedLambdas()
+		{
+			if (undecidedLambdas == null || undecidedLambdas.Count == 0)
+				return;
+			Log.WriteLine("MergeUndecidedLambdas()...");
+			Log.Indent();
+			while (undecidedLambdas.Count > 0) {
+				LambdaBase lambda = undecidedLambdas[0];
+				// may happen caused by parse error l =>
+				if (lambda.LambdaExpression == null) {
+					undecidedLambdas.Remove (lambda);
+					continue;
+				}
+				ResolveParentForConversion(lambda.LambdaExpression);
+				if (lambda.IsUndecided) {
+					// Lambda wasn't merged by resolving its parent -> enforce merging
+					Log.WriteLine("Lambda wasn't merged by conversion - enforce merging");
+					lambda.EnforceMerge(this);
+				}
+			}
+			Log.Unindent();
+			Log.WriteLine("MergeUndecidedLambdas() finished.");
+		}
+		
+		void ResolveParentForConversion(AstNode expression)
+		{
+			AstNode parent = expression.Parent;
+			// Continue going upwards until we find a node that can be resolved and provides
+			// an expected type.
+			while (ParenthesizedExpression.ActsAsParenthesizedExpression(parent) || CSharpAstResolver.IsUnresolvableNode(parent)) {
+				parent = parent.Parent;
+			}
+			CSharpResolver storedResolver;
+			if (parent != null && resolverBeforeDict.TryGetValue(parent, out storedResolver)) {
+				Log.WriteLine("Trying to resolve '" + parent + "' in order to find the conversion applied to '" + expression + "'...");
+				Log.Indent();
+				ResetContext(storedResolver, delegate { Resolve(parent); });
+				Log.Unindent();
+			} else {
+				Log.WriteLine("Could not find a suitable parent for '" + expression + "'");
+			}
+		}
+		#endregion
+		
+		#region AnalyzeLambda
+		IType GetTaskType(IType resultType)
+		{
+			if (resultType.Kind == TypeKind.Unknown)
+				return SpecialType.UnknownType;
+			if (resultType.Kind == TypeKind.Void)
+				return resolver.Compilation.FindType(KnownTypeCode.Task);
+			
+			ITypeDefinition def = resolver.Compilation.FindType(KnownTypeCode.TaskOfT).GetDefinition();
+			if (def != null)
+				return new ParameterizedType(def, new[] { resultType });
+			else
+				return SpecialType.UnknownType;
+		}
+		
+		void AnalyzeLambda(AstNode body, bool isAsync, out bool isValidAsVoidMethod, out bool isEndpointUnreachable, out IType inferredReturnType, out IList<Expression> returnExpressions, out IList<ResolveResult> returnValues)
+		{
+			isEndpointUnreachable = false;
+			Expression expr = body as Expression;
+			if (expr != null) {
+				isValidAsVoidMethod = ExpressionPermittedAsStatement(expr);
+				returnExpressions = new [] { expr };
+				returnValues = new[] { Resolve(expr) };
+				inferredReturnType = returnValues[0].Type;
+			} else {
+				Scan(body);
+				
+				AnalyzeLambdaVisitor alv = new AnalyzeLambdaVisitor();
+				body.AcceptVisitor(alv);
+				isValidAsVoidMethod = (alv.ReturnExpressions.Count == 0);
+				if (alv.HasVoidReturnStatements) {
+					returnExpressions = EmptyList<Expression>.Instance;
+					returnValues = EmptyList<ResolveResult>.Instance;
+					inferredReturnType = resolver.Compilation.FindType(KnownTypeCode.Void);
+				} else {
+					returnExpressions = alv.ReturnExpressions;
+					returnValues = new ResolveResult[returnExpressions.Count];
+					for (int i = 0; i < returnValues.Count; i++) {
+						returnValues[i] = resolveResultCache[returnExpressions[i]];
+					}
+
+					// async lambdas without return statements are resolved as Task return types.
+					if (returnExpressions.Count == 0 && isAsync) {
+						inferredReturnType = resolver.Compilation.FindType(KnownTypeCode.Task);
+						Log.WriteLine("Lambda return type was inferred to: " + inferredReturnType);
+						return;
+					}
+
+					TypeInference ti = new TypeInference(resolver.Compilation, resolver.conversions);
+					bool tiSuccess;
+					inferredReturnType = ti.GetBestCommonType(returnValues, out tiSuccess);
+					// Failure to infer a return type does not make the lambda invalid,
+					// so we can ignore the 'tiSuccess' value
+					if (isValidAsVoidMethod && returnExpressions.Count == 0 && body is Statement) {
+						var reachabilityAnalysis = ReachabilityAnalysis.Create(
+							(Statement)body, (node, _) => resolveResultCache[node],
+							resolver.CurrentTypeResolveContext, cancellationToken);
+						isEndpointUnreachable = !reachabilityAnalysis.IsEndpointReachable((Statement)body);
+					}
+				}
+			}
+			if (isAsync)
+				inferredReturnType = GetTaskType(inferredReturnType);
+			Log.WriteLine("Lambda return type was inferred to: " + inferredReturnType);
+		}
+		
+		static bool ExpressionPermittedAsStatement(Expression expr)
+		{
+			UnaryOperatorExpression uoe = expr as UnaryOperatorExpression;
+			if (uoe != null) {
+				switch (uoe.Operator) {
+					case UnaryOperatorType.Increment:
+					case UnaryOperatorType.Decrement:
+					case UnaryOperatorType.PostIncrement:
+					case UnaryOperatorType.PostDecrement:
+					case UnaryOperatorType.Await:
+						return true;
+					default:
+						return false;
+				}
+			}
+			return expr is InvocationExpression
+				|| expr is ObjectCreateExpression
+				|| expr is AssignmentExpression;
+		}
+		
+		static bool IsValidLambda(bool isValidAsVoidMethod, bool isEndpointUnreachable, bool isAsync, IList<ResolveResult> returnValues, IType returnType, CSharpConversions conversions)
+		{
+			if (returnType.Kind == TypeKind.Void) {
+				// Lambdas that are valid statement lambdas or expression lambdas with a statement-expression
+				// can be converted to delegates with void return type.
+				// This holds for both async and regular lambdas.
+				return isValidAsVoidMethod;
+			} else if (isAsync && TaskType.IsTask(returnType) && returnType.TypeParameterCount == 0) {
+				// Additionally, async lambdas with the above property can be converted to non-generic Task.
+				return isValidAsVoidMethod;
+			} else {
+				if (returnValues.Count == 0)
+					return isEndpointUnreachable;
+				if (isAsync) {
+					// async lambdas must return Task<T>
+					if (!(TaskType.IsTask(returnType) && returnType.TypeParameterCount == 1))
+						return false;
+					// unpack Task<T> for testing the implicit conversions
+					returnType = ((ParameterizedType)returnType).GetTypeArgument(0);
+				}
+				foreach (ResolveResult returnRR in returnValues) {
+					if (!conversions.ImplicitConversion(returnRR, returnType).IsValid)
+						return false;
+				}
+				return true;
+			}
+		}
+		
+		IType UnpackTask(IType type)
+		{
+			return TaskType.UnpackTask(resolver.Compilation, type);
+		}
+		
+		sealed class AnalyzeLambdaVisitor : DepthFirstAstVisitor
+		{
+			public bool HasVoidReturnStatements;
+			public List<Expression> ReturnExpressions = new List<Expression>();
+			
+			public override void VisitReturnStatement(ReturnStatement returnStatement)
+			{
+				Expression expr = returnStatement.Expression;
+				if (expr.IsNull) {
+					HasVoidReturnStatements = true;
+				} else {
+					ReturnExpressions.Add(expr);
+				}
+			}
+			
+			public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
+			{
+				// don't go into nested lambdas
+			}
+			
+			public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
+			{
+				// don't go into nested lambdas
+			}
+		}
+		#endregion
+		#endregion
+		
+		#region ForEach Statement
+		ResolveResult IAstVisitor<ResolveResult>.VisitForeachStatement(ForeachStatement foreachStatement)
+		{
+			var compilation = resolver.Compilation;
+			ResolveResult expression = Resolve(foreachStatement.InExpression);
+			bool isImplicitlyTypedVariable = foreachStatement.VariableType.IsVar();
+			var memberLookup = resolver.CreateMemberLookup();
+			
+			IType collectionType, enumeratorType, elementType;
+			ResolveResult getEnumeratorInvocation;
+			ResolveResult currentRR = null;
+			// C# 4.0 spec: §8.8.4 The foreach statement
+			if (expression.Type.Kind == TypeKind.Array || expression.Type.Kind == TypeKind.Dynamic) {
+				collectionType = compilation.FindType(KnownTypeCode.IEnumerable);
+				enumeratorType = compilation.FindType(KnownTypeCode.IEnumerator);
+				if (expression.Type.Kind == TypeKind.Array) {
+					elementType = ((ArrayType)expression.Type).ElementType;
+				} else {
+					elementType = isImplicitlyTypedVariable ? SpecialType.Dynamic : compilation.FindType(KnownTypeCode.Object);
+				}
+				getEnumeratorInvocation = resolver.ResolveCast(collectionType, expression);
+				getEnumeratorInvocation = resolver.ResolveMemberAccess(getEnumeratorInvocation, "GetEnumerator", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
+				getEnumeratorInvocation = resolver.ResolveInvocation(getEnumeratorInvocation, new ResolveResult[0]);
+			} else {
+				var getEnumeratorMethodGroup = memberLookup.Lookup(expression, "GetEnumerator", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
+				if (getEnumeratorMethodGroup != null) {
+					var or = getEnumeratorMethodGroup.PerformOverloadResolution(
+						compilation, new ResolveResult[0],
+						allowExtensionMethods: false, allowExpandingParams: false, allowOptionalParameters: false);
+					if (or.FoundApplicableCandidate && !or.IsAmbiguous && !or.BestCandidate.IsStatic && or.BestCandidate.IsPublic) {
+						collectionType = expression.Type;
+						getEnumeratorInvocation = or.CreateResolveResult(expression);
+						enumeratorType = getEnumeratorInvocation.Type;
+						currentRR = memberLookup.Lookup(new ResolveResult(enumeratorType), "Current", EmptyList<IType>.Instance, false);
+						elementType = currentRR.Type;
+					} else {
+						CheckForEnumerableInterface(expression, out collectionType, out enumeratorType, out elementType, out getEnumeratorInvocation);
+					}
+				} else {
+					CheckForEnumerableInterface(expression, out collectionType, out enumeratorType, out elementType, out getEnumeratorInvocation);
+				}
+			}
+			IMethod moveNextMethod = null;
+			var moveNextMethodGroup = memberLookup.Lookup(new ResolveResult(enumeratorType), "MoveNext", EmptyList<IType>.Instance, false) as MethodGroupResolveResult;
+			if (moveNextMethodGroup != null) {
+				var or = moveNextMethodGroup.PerformOverloadResolution(
+					compilation, new ResolveResult[0],
+					allowExtensionMethods: false, allowExpandingParams: false, allowOptionalParameters: false);
+				moveNextMethod = or.GetBestCandidateWithSubstitutedTypeArguments() as IMethod;
+			}
+			
+			if (currentRR == null)
+				currentRR = memberLookup.Lookup(new ResolveResult(enumeratorType), "Current", EmptyList<IType>.Instance, false);
+			IProperty currentProperty = null;
+			if (currentRR is MemberResolveResult)
+				currentProperty = ((MemberResolveResult)currentRR).Member as IProperty;
+			// end of foreach resolve logic
+			// back to resolve visitor:
+			
+			resolver = resolver.PushBlock();
+			IVariable v;
+			if (isImplicitlyTypedVariable) {
+				StoreCurrentState(foreachStatement.VariableType);
+				StoreResult(foreachStatement.VariableType, new TypeResolveResult(elementType));
+				v = MakeVariable(elementType, foreachStatement.VariableNameToken);
+			} else {
+				IType variableType = ResolveType(foreachStatement.VariableType);
+				v = MakeVariable(variableType, foreachStatement.VariableNameToken);
+			}
+			StoreCurrentState(foreachStatement.VariableNameToken);
+			resolver = resolver.AddVariable(v);
+			
+			StoreResult(foreachStatement.VariableNameToken, new LocalResolveResult(v));
+			
+			Scan(foreachStatement.EmbeddedStatement);
+			resolver = resolver.PopBlock();
+			return new ForEachResolveResult(getEnumeratorInvocation, collectionType, enumeratorType, elementType,
+			                                v, currentProperty, moveNextMethod, voidResult.Type);
+		}
+		
+		void CheckForEnumerableInterface(ResolveResult expression, out IType collectionType, out IType enumeratorType, out IType elementType, out ResolveResult getEnumeratorInvocation)
+		{
+			var compilation = resolver.Compilation;
+			bool? isGeneric;
+			elementType = GetElementTypeFromIEnumerable(expression.Type, compilation, false, out isGeneric);
+			if (isGeneric == true) {
+				ITypeDefinition enumerableOfT = compilation.FindType(KnownTypeCode.IEnumerableOfT).GetDefinition();
+				if (enumerableOfT != null)
+					collectionType = new ParameterizedType(enumerableOfT, new [] { elementType });
+				else
+					collectionType = SpecialType.UnknownType;
+				
+				ITypeDefinition enumeratorOfT = compilation.FindType(KnownTypeCode.IEnumeratorOfT).GetDefinition();
+				if (enumeratorOfT != null)
+					enumeratorType = new ParameterizedType(enumeratorOfT, new [] { elementType });
+				else
+					enumeratorType = SpecialType.UnknownType;
+			} else if (isGeneric == false) {
+				collectionType = compilation.FindType(KnownTypeCode.IEnumerable);
+				enumeratorType = compilation.FindType(KnownTypeCode.IEnumerator);
+			} else {
+				collectionType = SpecialType.UnknownType;
+				enumeratorType = SpecialType.UnknownType;
+			}
+			getEnumeratorInvocation = resolver.ResolveCast(collectionType, expression);
+			getEnumeratorInvocation = resolver.ResolveMemberAccess(getEnumeratorInvocation, "GetEnumerator", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
+			getEnumeratorInvocation = resolver.ResolveInvocation(getEnumeratorInvocation, new ResolveResult[0]);
+		}
+		#endregion
+		
+		#region Local Variable Scopes (Block Statements)
+		ResolveResult IAstVisitor<ResolveResult>.VisitBlockStatement(BlockStatement blockStatement)
+		{
+			resolver = resolver.PushBlock();
+			ScanChildren(blockStatement);
+			resolver = resolver.PopBlock();
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUsingStatement(UsingStatement usingStatement)
+		{
+			resolver = resolver.PushBlock();
+			if (resolverEnabled) {
+				for (AstNode child = usingStatement.FirstChild; child != null; child = child.NextSibling) {
+					if (child.Role == UsingStatement.ResourceAcquisitionRole && child is Expression) {
+						ResolveAndProcessConversion((Expression)child, resolver.Compilation.FindType(KnownTypeCode.IDisposable));
+					} else {
+						Scan(child);
+					}
+				}
+			} else {
+				ScanChildren(usingStatement);
+			}
+			resolver = resolver.PopBlock();
+			return resolverEnabled ? voidResult : null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitFixedStatement(FixedStatement fixedStatement)
+		{
+			resolver = resolver.PushBlock();
+			IType type = ResolveType(fixedStatement.Type);
+			foreach (VariableInitializer vi in fixedStatement.Variables) {
+				resolver = resolver.AddVariable(MakeVariable(type, vi.NameToken));
+				Scan(vi);
+			}
+			Scan(fixedStatement.EmbeddedStatement);
+			resolver = resolver.PopBlock();
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitSwitchStatement(SwitchStatement switchStatement)
+		{
+			resolver = resolver.PushBlock();
+			ScanChildren(switchStatement);
+			resolver = resolver.PopBlock();
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitCatchClause(CatchClause catchClause)
+		{
+			resolver = resolver.PushBlock();
+			if (string.IsNullOrEmpty(catchClause.VariableName)) {
+				Scan(catchClause.Type);
+			} else {
+				//DomRegion region = MakeRegion(catchClause.VariableNameToken);
+				StoreCurrentState(catchClause.VariableNameToken);
+				IVariable v = MakeVariable(ResolveType(catchClause.Type), catchClause.VariableNameToken);
+				resolver = resolver.AddVariable(v);
+				StoreResult(catchClause.VariableNameToken, new LocalResolveResult(v));
+			}
+			Scan(catchClause.Body);
+			resolver = resolver.PopBlock();
+			return voidResult;
+		}
+		#endregion
+		
+		#region VariableDeclarationStatement
+		ResolveResult IAstVisitor<ResolveResult>.VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
+		{
+			bool isConst = (variableDeclarationStatement.Modifiers & Modifiers.Const) != 0;
+			if (!isConst && variableDeclarationStatement.Type.IsVar() && variableDeclarationStatement.Variables.Count == 1) {
+				VariableInitializer vi = variableDeclarationStatement.Variables.Single();
+				StoreCurrentState(variableDeclarationStatement.Type);
+				IType type = Resolve(vi.Initializer).Type;
+				StoreResult(variableDeclarationStatement.Type, new TypeResolveResult(type));
+				IVariable v = MakeVariable(type, vi.NameToken);
+				resolver = resolver.AddVariable(v);
+				Scan(vi);
+			} else {
+				IType type = ResolveType(variableDeclarationStatement.Type);
+
+				foreach (VariableInitializer vi in variableDeclarationStatement.Variables) {
+					IVariable v;
+					if (isConst) {
+						ResolveResult rr = Resolve(vi.Initializer);
+						rr = resolver.ResolveCast(type, rr);
+						v = MakeConstant(type, vi.NameToken, rr.ConstantValue);
+					} else {
+						v = MakeVariable(type, vi.NameToken);
+					}
+					resolver = resolver.AddVariable(v);
+					Scan(vi);
+				}
+			}
+			return voidResult;
+		}
+		#endregion
+		
+		#region Condition Statements
+		ResolveResult IAstVisitor<ResolveResult>.VisitForStatement(ForStatement forStatement)
+		{
+			resolver = resolver.PushBlock();
+			var result = HandleConditionStatement(forStatement);
+			resolver = resolver.PopBlock();
+			return result;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitIfElseStatement(IfElseStatement ifElseStatement)
+		{
+			return HandleConditionStatement(ifElseStatement);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitWhileStatement(WhileStatement whileStatement)
+		{
+			return HandleConditionStatement(whileStatement);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitDoWhileStatement(DoWhileStatement doWhileStatement)
+		{
+			return HandleConditionStatement(doWhileStatement);
+		}
+		
+		ResolveResult HandleConditionStatement(Statement conditionStatement)
+		{
+			if (resolverEnabled) {
+				for (AstNode child = conditionStatement.FirstChild; child != null; child = child.NextSibling) {
+					if (child.Role == Roles.Condition) {
+						Expression condition = (Expression)child;
+						ResolveResult conditionRR = Resolve(condition);
+						ResolveResult convertedRR = resolver.ResolveCondition(conditionRR);
+						if (convertedRR != conditionRR)
+							ProcessConversionResult(condition, convertedRR as ConversionResolveResult);
+					} else {
+						Scan(child);
+					}
+				}
+				return voidResult;
+			} else {
+				ScanChildren(conditionStatement);
+				return null;
+			}
+		}
+		#endregion
+		
+		#region Return Statements
+		ResolveResult IAstVisitor<ResolveResult>.VisitReturnStatement(ReturnStatement returnStatement)
+		{
+			if (resolverEnabled && !resolver.IsWithinLambdaExpression && resolver.CurrentMember != null) {
+				IType type = resolver.CurrentMember.ReturnType;
+				if (TaskType.IsTask(type)) {
+					var methodDecl = returnStatement.Ancestors.OfType<EntityDeclaration>().FirstOrDefault();
+					if (methodDecl != null && (methodDecl.Modifiers & Modifiers.Async) == Modifiers.Async)
+						type = UnpackTask(type);
+				}
+				ResolveAndProcessConversion(returnStatement.Expression, type);
+			} else {
+				Scan(returnStatement.Expression);
+			}
+			return resolverEnabled ? voidResult : null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitYieldReturnStatement(YieldReturnStatement yieldStatement)
+		{
+			if (resolverEnabled && resolver.CurrentMember != null) {
+				IType returnType = resolver.CurrentMember.ReturnType;
+				bool? isGeneric;
+				IType elementType = GetElementTypeFromIEnumerable(returnType, resolver.Compilation, true, out isGeneric);
+				ResolveAndProcessConversion(yieldStatement.Expression, elementType);
+			} else {
+				Scan(yieldStatement.Expression);
+			}
+			return resolverEnabled ? voidResult : null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
+		{
+			return voidResult;
+		}
+		#endregion
+		
+		#region Other statements
+		ResolveResult IAstVisitor<ResolveResult>.VisitExpressionStatement(ExpressionStatement expressionStatement)
+		{
+			ScanChildren(expressionStatement);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitLockStatement(LockStatement lockStatement)
+		{
+			ScanChildren(lockStatement);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitEmptyStatement(EmptyStatement emptyStatement)
+		{
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitBreakStatement(BreakStatement breakStatement)
+		{
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitContinueStatement(ContinueStatement continueStatement)
+		{
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitThrowStatement(ThrowStatement throwStatement)
+		{
+			if (resolverEnabled) {
+				ResolveAndProcessConversion(throwStatement.Expression, resolver.Compilation.FindType(KnownTypeCode.Exception));
+				return voidResult;
+			} else {
+				Scan(throwStatement.Expression);
+				return null;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitTryCatchStatement(TryCatchStatement tryCatchStatement)
+		{
+			ScanChildren(tryCatchStatement);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitGotoCaseStatement(GotoCaseStatement gotoCaseStatement)
+		{
+			ScanChildren(gotoCaseStatement);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitGotoDefaultStatement(GotoDefaultStatement gotoDefaultStatement)
+		{
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitGotoStatement(GotoStatement gotoStatement)
+		{
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitLabelStatement(LabelStatement labelStatement)
+		{
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUnsafeStatement(UnsafeStatement unsafeStatement)
+		{
+			resolver = resolver.PushBlock();
+			ScanChildren(unsafeStatement);
+			resolver = resolver.PopBlock();
+			return voidResult;
+		}
+		#endregion
+		
+		#region Local Variable Type Inference
+		IVariable MakeVariable(IType type, Identifier variableName)
+		{
+			return new SimpleVariable(MakeRegion(variableName), type, variableName.Name);
+		}
+		
+		IVariable MakeConstant(IType type, Identifier variableName, object constantValue)
+		{
+			return new SimpleConstant(MakeRegion(variableName), type, variableName.Name, constantValue);
+		}
+		
+		class SimpleVariable : IVariable
+		{
+			readonly DomRegion region;
+			readonly IType type;
+			readonly string name;
+			
+			public SimpleVariable(DomRegion region, IType type, string name)
+			{
+				Debug.Assert(type != null);
+				Debug.Assert(name != null);
+				this.region = region;
+				this.type = type;
+				this.name = name;
+			}
+			
+			public SymbolKind SymbolKind {
+				get { return SymbolKind.Variable; }
+			}
+			
+			public string Name {
+				get { return name; }
+			}
+			
+			public DomRegion Region {
+				get { return region; }
+			}
+			
+			public IType Type {
+				get { return type; }
+			}
+			
+			public virtual bool IsConst {
+				get { return false; }
+			}
+			
+			public virtual object ConstantValue {
+				get { return null; }
+			}
+			
+			public override string ToString()
+			{
+				return type.ToString() + " " + name + ";";
+			}
+
+			public ISymbolReference ToReference()
+			{
+				return new VariableReference(type.ToTypeReference(), name, region, IsConst, ConstantValue);
+			}
+		}
+		
+		sealed class SimpleConstant : SimpleVariable
+		{
+			readonly object constantValue;
+			
+			public SimpleConstant(DomRegion region, IType type, string name, object constantValue)
+				: base(region, type, name)
+			{
+				this.constantValue = constantValue;
+			}
+			
+			public override bool IsConst {
+				get { return true; }
+			}
+			
+			public override object ConstantValue {
+				get { return constantValue; }
+			}
+			
+			public override string ToString()
+			{
+				return Type.ToString() + " " + Name + " = " + new PrimitiveExpression(constantValue).ToString() + ";";
+			}
+		}
+		
+		static IType GetElementTypeFromIEnumerable(IType collectionType, ICompilation compilation, bool allowIEnumerator, out bool? isGeneric)
+		{
+			bool foundNonGenericIEnumerable = false;
+			foreach (IType baseType in collectionType.GetAllBaseTypes()) {
+				ITypeDefinition baseTypeDef = baseType.GetDefinition();
+				if (baseTypeDef != null) {
+					KnownTypeCode typeCode = baseTypeDef.KnownTypeCode;
+					if (typeCode == KnownTypeCode.IEnumerableOfT || (allowIEnumerator && typeCode == KnownTypeCode.IEnumeratorOfT)) {
+						ParameterizedType pt = baseType as ParameterizedType;
+						if (pt != null) {
+							isGeneric = true;
+							return pt.GetTypeArgument(0);
+						}
+					}
+					if (typeCode == KnownTypeCode.IEnumerable || (allowIEnumerator && typeCode == KnownTypeCode.IEnumerator))
+						foundNonGenericIEnumerable = true;
+				}
+			}
+			// System.Collections.IEnumerable found in type hierarchy -> Object is element type.
+			if (foundNonGenericIEnumerable) {
+				isGeneric = false;
+				return compilation.FindType(KnownTypeCode.Object);
+			}
+			isGeneric = null;
+			return SpecialType.UnknownType;
+		}
+		#endregion
+		
+		#region Attributes
+		ResolveResult IAstVisitor<ResolveResult>.VisitAttribute(Attribute attribute)
+		{
+			var type = ResolveType(attribute.Type);
+			
+			// Separate arguments into ctor arguments and non-ctor arguments:
+			var constructorArguments = attribute.Arguments.Where(a => !(a is NamedExpression));
+			var nonConstructorArguments = attribute.Arguments.OfType<NamedExpression>();
+			
+			// Scan the non-constructor arguments
+			resolver = resolver.PushObjectInitializer(new InitializedObjectResolveResult(type));
+			List<ResolveResult> initializerStatements = new List<ResolveResult>();
+			foreach (var arg in nonConstructorArguments)
+				HandleNamedExpression(arg, initializerStatements);
+			resolver = resolver.PopObjectInitializer();
+			
+			// Resolve the ctor arguments and find the matching ctor overload
+			string[] argumentNames;
+			ResolveResult[] arguments = GetArguments(constructorArguments, out argumentNames);
+			ResolveResult rr = resolver.ResolveObjectCreation(type, arguments, argumentNames, false, initializerStatements);
+			ProcessInvocationResult(null, constructorArguments, rr);
+			return rr;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitAttributeSection(AttributeSection attributeSection)
+		{
+			ScanChildren(attributeSection);
+			return voidResult;
+		}
+		#endregion
+		
+		#region Using Declaration
+		ResolveResult IAstVisitor<ResolveResult>.VisitUsingDeclaration(UsingDeclaration usingDeclaration)
+		{
+			ScanChildren(usingDeclaration);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration)
+		{
+			ScanChildren(usingDeclaration);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			return voidResult;
+		}
+		#endregion
+		
+		#region Type References
+		ResolveResult IAstVisitor<ResolveResult>.VisitPrimitiveType(PrimitiveType primitiveType)
+		{
+			if (!resolverEnabled)
+				return null;
+			KnownTypeCode typeCode = primitiveType.KnownTypeCode;
+			if (typeCode == KnownTypeCode.None && primitiveType.Parent is Constraint && primitiveType.Role == Roles.BaseType) {
+				switch (primitiveType.Keyword) {
+					case "class":
+					case "struct":
+					case "new":
+						return voidResult;
+				}
+			}
+			IType type = resolver.Compilation.FindType(typeCode);
+			return new TypeResolveResult(type);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitSimpleType(SimpleType simpleType)
+		{
+			if (!resolverEnabled) {
+				ScanChildren(simpleType);
+				return null;
+			}
+			
+			// Figure out the correct lookup mode:
+			NameLookupMode lookupMode = simpleType.GetNameLookupMode();
+			
+			var typeArguments = ResolveTypeArguments(simpleType.TypeArguments);
+			Identifier identifier = simpleType.IdentifierToken;
+			if (string.IsNullOrEmpty(identifier.Name))
+				return new TypeResolveResult(SpecialType.UnboundTypeArgument);
+			ResolveResult rr = resolver.LookupSimpleNameOrTypeName(identifier.Name, typeArguments, lookupMode);
+			if (simpleType.Parent is Attribute && !identifier.IsVerbatim) {
+				var withSuffix = resolver.LookupSimpleNameOrTypeName(identifier.Name + "Attribute", typeArguments, lookupMode);
+				if (AttributeTypeReference.PreferAttributeTypeWithSuffix(rr.Type, withSuffix.Type, resolver.Compilation))
+					return withSuffix;
+			}
+			return rr;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitMemberType(MemberType memberType)
+		{
+			ResolveResult target;
+			NameLookupMode lookupMode = memberType.GetNameLookupMode();
+			if (memberType.IsDoubleColon && memberType.Target is SimpleType) {
+				SimpleType t = (SimpleType)memberType.Target;
+				StoreCurrentState(t);
+				target = resolver.ResolveAlias(t.Identifier);
+				StoreResult(t, target);
+			} else {
+				if (!resolverEnabled) {
+					ScanChildren(memberType);
+					return null;
+				}
+				target = Resolve(memberType.Target);
+			}
+			var typeArguments = ResolveTypeArguments(memberType.TypeArguments);
+			Identifier identifier = memberType.MemberNameToken;
+			ResolveResult rr = resolver.ResolveMemberAccess(target, identifier.Name, typeArguments, lookupMode);
+			if (memberType.Parent is Attribute && !identifier.IsVerbatim) {
+				var withSuffix = resolver.ResolveMemberAccess(target, identifier.Name + "Attribute", typeArguments, lookupMode);
+				if (AttributeTypeReference.PreferAttributeTypeWithSuffix(rr.Type, withSuffix.Type, resolver.Compilation))
+					return withSuffix;
+			}
+			return rr;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitComposedType(ComposedType composedType)
+		{
+			if (!resolverEnabled) {
+				ScanChildren(composedType);
+				return null;
+			}
+			IType t = ResolveType(composedType.BaseType);
+			if (composedType.HasNullableSpecifier) {
+				t = NullableType.Create(resolver.Compilation, t);
+			}
+			for (int i = 0; i < composedType.PointerRank; i++) {
+				t = new PointerType(t);
+			}
+			foreach (var a in composedType.ArraySpecifiers.Reverse()) {
+				t = new ArrayType(resolver.Compilation, t, a.Dimensions);
+			}
+			return new TypeResolveResult(t);
+		}
+		#endregion
+		
+		#region Query Expressions
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryExpression(QueryExpression queryExpression)
+		{
+			resolver = resolver.PushBlock();
+			var oldQueryResult = currentQueryResult;
+			var oldCancellationToken = cancellationToken;
+			try {
+				// Because currentQueryResult isn't part of the stored state,
+				// query expressions must be resolved in a single operation.
+				// This means we can't allow cancellation within the query expression.
+				cancellationToken = CancellationToken.None;
+				currentQueryResult = null;
+				foreach (var clause in queryExpression.Clauses) {
+					currentQueryResult = Resolve(clause);
+				}
+				return WrapResult(currentQueryResult);
+			} finally {
+				currentQueryResult = oldQueryResult;
+				cancellationToken = oldCancellationToken;
+				resolver = resolver.PopBlock();
+			}
+		}
+		
+		IType GetTypeForQueryVariable(IType type)
+		{
+			bool? isGeneric;
+			// This assumes queries are only used on IEnumerable.
+			var result = GetElementTypeFromIEnumerable(type, resolver.Compilation, false, out isGeneric);
+
+			// If that fails try to resolve the Select method and resolve the projection.
+			if (result.Kind == TypeKind.Unknown) {
+				var selectAccess = resolver.ResolveMemberAccess(new ResolveResult (type), "Select", EmptyList<IType>.Instance);
+				ResolveResult[] arguments = {
+					new QueryExpressionLambda(1, voidResult) 
+				};
+				 
+				var rr = resolver.ResolveInvocation(selectAccess, arguments) as CSharpInvocationResolveResult; 
+				if (rr != null && rr.Arguments.Count == 2) {
+					var invokeMethod = rr.Arguments[1].Type.GetDelegateInvokeMethod();
+					if (invokeMethod != null && invokeMethod.Parameters.Count > 0)
+						return invokeMethod.Parameters[0].Type;
+				}
+			}
+			return result;
+		}
+		
+		ResolveResult MakeTransparentIdentifierResolveResult()
+		{
+			return new ResolveResult(new AnonymousType(resolver.Compilation, EmptyList<IUnresolvedProperty>.Instance));
+		}
+		
+		sealed class QueryExpressionLambdaConversion : Conversion
+		{
+			internal readonly IType[] ParameterTypes;
+			
+			public QueryExpressionLambdaConversion(IType[] parameterTypes)
+			{
+				this.ParameterTypes = parameterTypes;
+			}
+			
+			public override bool IsImplicit {
+				get { return true; }
+			}
+			
+			public override bool IsAnonymousFunctionConversion {
+				get { return true; }
+			}
+		}
+		
+		sealed class QueryExpressionLambda : LambdaResolveResult
+		{
+			readonly IParameter[] parameters;
+			readonly ResolveResult bodyExpression;
+			
+			internal IType[] inferredParameterTypes;
+			
+			public QueryExpressionLambda(int parameterCount, ResolveResult bodyExpression)
+			{
+				this.parameters = new IParameter[parameterCount];
+				for (int i = 0; i < parameterCount; i++) {
+					parameters[i] = new DefaultParameter(SpecialType.UnknownType, "x" + i);
+				}
+				this.bodyExpression = bodyExpression;
+			}
+			
+			public override IList<IParameter> Parameters {
+				get { return parameters; }
+			}
+			
+			public override Conversion IsValid(IType[] parameterTypes, IType returnType, CSharpConversions conversions)
+			{
+				if (parameterTypes.Length == parameters.Length) {
+					this.inferredParameterTypes = parameterTypes;
+					return new QueryExpressionLambdaConversion(parameterTypes);
+				} else {
+					return Conversion.None;
+				}
+			}
+			
+			public override bool IsAsync {
+				get { return false; }
+			}
+			
+			public override bool IsImplicitlyTyped {
+				get { return true; }
+			}
+			
+			public override bool IsAnonymousMethod {
+				get { return false; }
+			}
+			
+			public override bool HasParameterList {
+				get { return true; }
+			}
+			
+			public override ResolveResult Body {
+				get { return bodyExpression; }
+			}
+			
+			public override IType GetInferredReturnType(IType[] parameterTypes)
+			{
+				return bodyExpression.Type;
+			}
+			
+			public override IType ReturnType {
+				get {
+					return bodyExpression.Type;
+				}
+			}
+			
+			public override string ToString()
+			{
+				return string.Format("[QueryExpressionLambda ({0}) => {1}]", string.Join(",", parameters.Select(p => p.Name)), bodyExpression);
+			}
+		}
+		
+		QueryClause GetPreviousQueryClause(QueryClause clause)
+		{
+			for (AstNode node = clause.PrevSibling; node != null; node = node.PrevSibling) {
+				if (node.Role == QueryExpression.ClauseRole)
+					return (QueryClause)node;
+			}
+			return null;
+		}
+		
+		QueryClause GetNextQueryClause(QueryClause clause)
+		{
+			for (AstNode node = clause.NextSibling; node != null; node = node.NextSibling) {
+				if (node.Role == QueryExpression.ClauseRole)
+					return (QueryClause)node;
+			}
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryFromClause(QueryFromClause queryFromClause)
+		{
+			ResolveResult result = errorResult;
+			ResolveResult expr = Resolve(queryFromClause.Expression);
+			IVariable v;
+			if (queryFromClause.Type.IsNull) {
+				v = MakeVariable(GetTypeForQueryVariable(expr.Type), queryFromClause.IdentifierToken);
+				result = expr;
+			} else {
+				v = MakeVariable(ResolveType(queryFromClause.Type), queryFromClause.IdentifierToken);
+				
+				// resolve the .Cast<>() call
+				ResolveResult methodGroup = resolver.ResolveMemberAccess(expr, "Cast", new[] { v.Type }, NameLookupMode.InvocationTarget);
+				result = resolver.ResolveInvocation(methodGroup, new ResolveResult[0]);
+			}
+			
+			StoreCurrentState(queryFromClause.IdentifierToken);
+			resolver = resolver.AddVariable(v);
+			StoreResult(queryFromClause.IdentifierToken, new LocalResolveResult(v));
+			
+			if (currentQueryResult != null) {
+				// this is a second 'from': resolve the .SelectMany() call
+				QuerySelectClause selectClause = GetNextQueryClause(queryFromClause) as QuerySelectClause;
+				ResolveResult selectResult;
+				if (selectClause != null) {
+					// from ... from ... select - the SelectMany call also performs the Select operation
+					selectResult = Resolve(selectClause.Expression);
+				} else {
+					// from .. from ... ... - introduce a transparent identifier
+					selectResult = MakeTransparentIdentifierResolveResult();
+				}
+				ResolveResult methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "SelectMany", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
+				ResolveResult[] arguments = {
+					new QueryExpressionLambda(1, result),
+					new QueryExpressionLambda(2, selectResult)
+				};
+				result = resolver.ResolveInvocation(methodGroup, arguments);
+			}
+			if (result == expr)
+				return WrapResult(result);
+			else
+				return result;
+		}
+		
+		/// <summary>
+		/// Wraps the result in an identity conversion.
+		/// This is necessary so that '$from x in variable$ select x*2' does not resolve
+		/// to the LocalResolveResult for the variable, which would confuse find references.
+		/// </summary>
+		ResolveResult WrapResult(ResolveResult result)
+		{
+			return new CastResolveResult(result.Type, result, Conversion.IdentityConversion, resolver.CheckForOverflow);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause)
+		{
+			ResolveResult rr = Resolve(queryContinuationClause.PrecedingQuery);
+			IType variableType = GetTypeForQueryVariable(rr.Type);
+			StoreCurrentState(queryContinuationClause.IdentifierToken);
+			IVariable v = MakeVariable(variableType, queryContinuationClause.IdentifierToken);
+			resolver = resolver.AddVariable(v);
+			StoreResult(queryContinuationClause.IdentifierToken, new LocalResolveResult(v));
+			return WrapResult(rr);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryLetClause(QueryLetClause queryLetClause)
+		{
+			ResolveResult expr = Resolve(queryLetClause.Expression);
+			StoreCurrentState(queryLetClause.IdentifierToken);
+			IVariable v = MakeVariable(expr.Type, queryLetClause.IdentifierToken);
+			resolver = resolver.AddVariable(v);
+			StoreResult(queryLetClause.IdentifierToken, new LocalResolveResult(v));
+			if (currentQueryResult != null) {
+				// resolve the .Select() call
+				ResolveResult methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Select", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
+				ResolveResult[] arguments = { new QueryExpressionLambda(1, MakeTransparentIdentifierResolveResult()) };
+				return resolver.ResolveInvocation(methodGroup, arguments);
+			} else {
+				return errorResult;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryJoinClause(QueryJoinClause queryJoinClause)
+		{
+			// join v in expr on onExpr equals equalsExpr [into g]
+			ResolveResult inResult = null;
+			ResolveResult expr = Resolve(queryJoinClause.InExpression);
+			IType variableType;
+			if (queryJoinClause.Type.IsNull) {
+				variableType = GetTypeForQueryVariable(expr.Type);
+				inResult = expr;
+			} else {
+				variableType = ResolveType(queryJoinClause.Type);
+				
+				// resolve the .Cast<>() call
+				ResolveResult methodGroup = resolver.ResolveMemberAccess(expr, "Cast", new[] { variableType }, NameLookupMode.InvocationTarget);
+				inResult = resolver.ResolveInvocation(methodGroup, new ResolveResult[0]);
+			}
+			
+			// resolve the 'On' expression in a context that contains only the previously existing range variables:
+			// (before adding any variable)
+			ResolveResult onResult = Resolve(queryJoinClause.OnExpression);
+			
+			// scan the 'Equals' expression in a context that contains only the variable 'v'
+			CSharpResolver resolverOutsideQuery = resolver;
+			resolverOutsideQuery = resolverOutsideQuery.PopBlock(); // pop all variables from the current query expression
+			IVariable v = MakeVariable(variableType, queryJoinClause.JoinIdentifierToken);
+			resolverOutsideQuery = resolverOutsideQuery.AddVariable(v);
+			ResolveResult equalsResult = errorResult;
+			ResetContext(resolverOutsideQuery, delegate {
+			             	equalsResult = Resolve(queryJoinClause.EqualsExpression);
+			             });
+			StoreCurrentState(queryJoinClause.JoinIdentifierToken);
+			StoreResult(queryJoinClause.JoinIdentifierToken, new LocalResolveResult(v));
+			
+			if (queryJoinClause.IsGroupJoin) {
+				return ResolveGroupJoin(queryJoinClause, inResult, onResult, equalsResult);
+			} else {
+				resolver = resolver.AddVariable(v);
+				if (currentQueryResult != null) {
+					QuerySelectClause selectClause = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
+					ResolveResult selectResult;
+					if (selectClause != null) {
+						// from ... join ... select - the Join call also performs the Select operation
+						selectResult = Resolve(selectClause.Expression);
+					} else {
+						// from .. join ... ... - introduce a transparent identifier
+						selectResult = MakeTransparentIdentifierResolveResult();
+					}
+					
+					var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Join", EmptyList<IType>.Instance);
+					ResolveResult[] arguments = {
+						inResult,
+						new QueryExpressionLambda(1, onResult),
+						new QueryExpressionLambda(1, equalsResult),
+						new QueryExpressionLambda(2, selectResult)
+					};
+					return resolver.ResolveInvocation(methodGroup, arguments);
+				} else {
+					return errorResult;
+				}
+			}
+		}
+		
+		ResolveResult ResolveGroupJoin(QueryJoinClause queryJoinClause,
+		                               ResolveResult inResult, ResolveResult onResult, ResolveResult equalsResult)
+		{
+			Debug.Assert(queryJoinClause.IsGroupJoin);
+			
+			DomRegion intoIdentifierRegion = MakeRegion(queryJoinClause.IntoIdentifierToken);
+			
+			// We need to declare the group variable, but it's a bit tricky to determine its type:
+			// We'll have to resolve the GroupJoin invocation and take a look at the inferred types
+			// for the lambda given as last parameter.
+			var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "GroupJoin", EmptyList<IType>.Instance);
+			QuerySelectClause selectClause = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
+			LambdaResolveResult groupJoinLambda;
+			if (selectClause != null) {
+				// from ... join ... into g select - the GroupJoin call also performs the Select operation
+				IParameter[] selectLambdaParameters = {
+					new DefaultParameter(SpecialType.UnknownType, "<>transparentIdentifier"),
+					new DefaultParameter(SpecialType.UnknownType, queryJoinClause.IntoIdentifier, region: intoIdentifierRegion)
+				};
+				groupJoinLambda = new ImplicitlyTypedLambda(selectClause, selectLambdaParameters, this);
+			} else {
+				// from .. join ... ... - introduce a transparent identifier
+				groupJoinLambda = new QueryExpressionLambda(2, MakeTransparentIdentifierResolveResult());
+			}
+			
+			ResolveResult[] arguments = {
+				inResult,
+				new QueryExpressionLambda(1, onResult),
+				new QueryExpressionLambda(1, equalsResult),
+				groupJoinLambda
+			};
+			ResolveResult rr = resolver.ResolveInvocation(methodGroup, arguments);
+			InvocationResolveResult invocationRR = rr as InvocationResolveResult;
+			
+			IVariable groupVariable;
+			if (groupJoinLambda is ImplicitlyTypedLambda) {
+				var implicitlyTypedLambda = (ImplicitlyTypedLambda)groupJoinLambda;
+				
+				if (invocationRR != null && invocationRR.Arguments.Count > 0) {
+					ConversionResolveResult crr = invocationRR.Arguments[invocationRR.Arguments.Count - 1] as ConversionResolveResult;
+					if (crr != null)
+						ProcessConversion(null, crr.Input, crr.Conversion, crr.Type);
+				}
+				
+				implicitlyTypedLambda.EnforceMerge(this);
+				if (implicitlyTypedLambda.Parameters.Count == 2) {
+					StoreCurrentState(queryJoinClause.IntoIdentifierToken);
+					groupVariable = implicitlyTypedLambda.Parameters[1];
+				} else {
+					groupVariable = null;
+				}
+			} else {
+				Debug.Assert(groupJoinLambda is QueryExpressionLambda);
+				
+				// Add the variable if the query expression continues after the group join
+				// (there's no need to do this if there's only a select clause remaining, as
+				// we already handled that in the ImplicitlyTypedLambda).
+				
+				// Get the inferred type of the group variable:
+				IType[] inferredParameterTypes = null;
+				if (invocationRR != null && invocationRR.Arguments.Count > 0) {
+					ConversionResolveResult crr = invocationRR.Arguments[invocationRR.Arguments.Count - 1] as ConversionResolveResult;
+					if (crr != null && crr.Conversion is QueryExpressionLambdaConversion) {
+						inferredParameterTypes = ((QueryExpressionLambdaConversion)crr.Conversion).ParameterTypes;
+					}
+				}
+				if (inferredParameterTypes == null)
+					inferredParameterTypes = ((QueryExpressionLambda)groupJoinLambda).inferredParameterTypes;
+				
+				IType groupParameterType;
+				if (inferredParameterTypes != null && inferredParameterTypes.Length == 2)
+					groupParameterType = inferredParameterTypes[1];
+				else
+					groupParameterType = SpecialType.UnknownType;
+				
+				StoreCurrentState(queryJoinClause.IntoIdentifierToken);
+				groupVariable = MakeVariable(groupParameterType, queryJoinClause.IntoIdentifierToken);
+				resolver = resolver.AddVariable(groupVariable);
+			}
+			
+			if (groupVariable != null) {
+				StoreResult(queryJoinClause.IntoIdentifierToken, new LocalResolveResult(groupVariable));
+			}
+			
+			return rr;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryWhereClause(QueryWhereClause queryWhereClause)
+		{
+			ResolveResult condition = Resolve(queryWhereClause.Condition);
+			IType boolType = resolver.Compilation.FindType(KnownTypeCode.Boolean);
+			Conversion conversionToBool = resolver.conversions.ImplicitConversion(condition, boolType);
+			ProcessConversion(queryWhereClause.Condition, condition, conversionToBool, boolType);
+			if (currentQueryResult != null) {
+				if (conversionToBool != Conversion.IdentityConversion && conversionToBool != Conversion.None) {
+					condition = new ConversionResolveResult(boolType, condition, conversionToBool, resolver.CheckForOverflow);
+				}
+				
+				var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Where", EmptyList<IType>.Instance);
+				ResolveResult[] arguments = { new QueryExpressionLambda(1, condition) };
+				return resolver.ResolveInvocation(methodGroup, arguments);
+			} else {
+				return errorResult;
+			}
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQuerySelectClause(QuerySelectClause querySelectClause)
+		{
+			if (currentQueryResult == null) {
+				ScanChildren(querySelectClause);
+				return errorResult;
+			}
+			QueryClause previousQueryClause = GetPreviousQueryClause(querySelectClause);
+			// If the 'select' follows on a 'SelectMany', 'Join' or 'GroupJoin' clause, then the 'select' portion
+			// was already done as part of the previous clause.
+			if (((previousQueryClause is QueryFromClause && GetPreviousQueryClause(previousQueryClause) != null))
+			    || previousQueryClause is QueryJoinClause)
+			{
+				// GroupJoin already scans the following select clause in a different context,
+				// so we must not scan it again.
+				if (!(previousQueryClause is QueryJoinClause && ((QueryJoinClause)previousQueryClause).IsGroupJoin))
+					Scan(querySelectClause.Expression);
+				return WrapResult(currentQueryResult);
+			}
+			
+			QueryExpression query = querySelectClause.Parent as QueryExpression;
+			string rangeVariable = GetSingleRangeVariable(query);
+			if (rangeVariable != null) {
+				IdentifierExpression ident = ParenthesizedExpression.UnpackParenthesizedExpression(querySelectClause.Expression) as IdentifierExpression;
+				if (ident != null && ident.Identifier == rangeVariable && !ident.TypeArguments.Any()) {
+					// selecting the single identifier that is the range variable
+					if (query.Clauses.Count > 2) {
+						// only if the query is not degenerate:
+						// the Select call will be optimized away, so directly return the previous result
+						Scan(querySelectClause.Expression);
+						return WrapResult(currentQueryResult);
+					}
+				}
+			}
+			
+			ResolveResult expr = Resolve(querySelectClause.Expression);
+			var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Select", EmptyList<IType>.Instance);
+			ResolveResult[] arguments = { new QueryExpressionLambda(1, expr) };
+			return resolver.ResolveInvocation(methodGroup, arguments);
+		}
+		
+		/// <summary>
+		/// Gets the name of the range variable in the specified query.
+		/// If the query has multiple range variables, this method returns null.
+		/// </summary>
+		string GetSingleRangeVariable(QueryExpression query)
+		{
+			if (query == null)
+				return null;
+			foreach (QueryClause clause in query.Clauses.Skip(1)) {
+				if (clause is QueryFromClause || clause is QueryJoinClause || clause is QueryLetClause) {
+					// query has more than 1 range variable
+					return null;
+				}
+			}
+			QueryFromClause fromClause = query.Clauses.FirstOrDefault() as QueryFromClause;
+			if (fromClause != null)
+				return fromClause.Identifier;
+			QueryContinuationClause continuationClause = query.Clauses.FirstOrDefault() as QueryContinuationClause;
+			if (continuationClause != null)
+				return continuationClause.Identifier;
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryGroupClause(QueryGroupClause queryGroupClause)
+		{
+			if (currentQueryResult == null) {
+				ScanChildren(queryGroupClause);
+				return errorResult;
+			}
+			
+			// ... group projection by key
+			ResolveResult projection = Resolve(queryGroupClause.Projection);
+			ResolveResult key = Resolve(queryGroupClause.Key);
+			
+			var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "GroupBy", EmptyList<IType>.Instance);
+			ResolveResult[] arguments = {
+				new QueryExpressionLambda(1, key),
+				new QueryExpressionLambda(1, projection)
+			};
+			return resolver.ResolveInvocation(methodGroup, arguments);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryOrderClause(QueryOrderClause queryOrderClause)
+		{
+			foreach (QueryOrdering ordering in queryOrderClause.Orderings) {
+				currentQueryResult = Resolve(ordering);
+			}
+			return WrapResult(currentQueryResult);
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitQueryOrdering(QueryOrdering queryOrdering)
+		{
+			if (currentQueryResult == null) {
+				ScanChildren(queryOrdering);
+				return errorResult;
+			}
+			// ... orderby sortKey [descending]
+			ResolveResult sortKey = Resolve(queryOrdering.Expression);
+			
+			QueryOrderClause parentClause = queryOrdering.Parent as QueryOrderClause;
+			bool isFirst = (parentClause == null || parentClause.Orderings.FirstOrDefault() == queryOrdering);
+			string methodName = isFirst ? "OrderBy" : "ThenBy";
+			if (queryOrdering.Direction == QueryOrderingDirection.Descending)
+				methodName += "Descending";
+			
+			var methodGroup = resolver.ResolveMemberAccess(currentQueryResult, methodName, EmptyList<IType>.Instance);
+			ResolveResult[] arguments = {
+				new QueryExpressionLambda(1, sortKey),
+			};
+			return resolver.ResolveInvocation(methodGroup, arguments);
+		}
+		#endregion
+		
+		#region Constructor Initializer
+		ResolveResult IAstVisitor<ResolveResult>.VisitConstructorInitializer(ConstructorInitializer constructorInitializer)
+		{
+			ResolveResult target;
+			if (constructorInitializer.ConstructorInitializerType == ConstructorInitializerType.Base) {
+				target = resolver.ResolveBaseReference();
+			} else {
+				target = resolver.ResolveThisReference();
+			}
+			string[] argumentNames;
+			ResolveResult[] arguments = GetArguments(constructorInitializer.Arguments, out argumentNames);
+			ResolveResult rr = resolver.ResolveObjectCreation(target.Type, arguments, argumentNames, allowProtectedAccess: true);
+			ProcessInvocationResult(null, constructorInitializer.Arguments, rr);
+			return rr;
+		}
+		#endregion
+		
+		#region Other Nodes
+		// Token nodes
+		ResolveResult IAstVisitor<ResolveResult>.VisitIdentifier(Identifier identifier)
+		{
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitComment (Comment comment)
+		{
+			return null;
+		}
+
+		ResolveResult IAstVisitor<ResolveResult>.VisitNewLine (NewLineNode comment)
+		{
+			return null;
+		}
+
+		ResolveResult IAstVisitor<ResolveResult>.VisitWhitespace(WhitespaceNode whitespaceNode)
+		{
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitText(TextNode textNode)
+		{
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitPreProcessorDirective (PreProcessorDirective preProcessorDirective)
+		{
+			return null;
+		}
+
+		ResolveResult IAstVisitor<ResolveResult>.VisitCSharpTokenNode(CSharpTokenNode cSharpTokenNode)
+		{
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitArraySpecifier(ArraySpecifier arraySpecifier)
+		{
+			return null;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitNullNode(AstNode nullNode)
+		{
+			return null;
+		}
+
+		ResolveResult IAstVisitor<ResolveResult>.VisitErrorNode(AstNode errorNode)
+		{
+			return null;
+		}
+
+		ResolveResult IAstVisitor<ResolveResult>.VisitPatternPlaceholder(AstNode placeholder, ICSharpCode.NRefactory.PatternMatching.Pattern pattern)
+		{
+			return null;
+		}
+		
+		// Nodes where we just need to visit the children:
+		ResolveResult IAstVisitor<ResolveResult>.VisitAccessor(Accessor accessor)
+		{
+			ScanChildren(accessor);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitSwitchSection(SwitchSection switchSection)
+		{
+			ScanChildren(switchSection);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitCaseLabel(CaseLabel caseLabel)
+		{
+			ScanChildren(caseLabel);
+			return voidResult;
+		}
+		
+		ResolveResult IAstVisitor<ResolveResult>.VisitConstraint(Constraint constraint)
+		{
+			ScanChildren(constraint);
+			return voidResult;
+		}
+		#endregion
+		
+		#region Documentation Reference
+		ResolveResult IAstVisitor<ResolveResult>.VisitDocumentationReference(DocumentationReference documentationReference)
+		{
+			// Resolve child nodes:
+			ITypeDefinition declaringTypeDef;
+			if (documentationReference.DeclaringType.IsNull)
+				declaringTypeDef = resolver.CurrentTypeDefinition;
+			else
+				declaringTypeDef = ResolveType(documentationReference.DeclaringType).GetDefinition();
+			IType[] typeArguments = documentationReference.TypeArguments.Select(ResolveType).ToArray();
+			IType conversionOperatorReturnType = ResolveType(documentationReference.ConversionOperatorReturnType);
+			IParameter[] parameters = documentationReference.Parameters.Select(ResolveXmlDocParameter).ToArray();
+			
+			if (documentationReference.SymbolKind == SymbolKind.TypeDefinition) {
+				if (declaringTypeDef != null)
+					return new TypeResolveResult(declaringTypeDef);
+				else
+					return errorResult;
+			}
+			
+			if (documentationReference.SymbolKind == SymbolKind.None) {
+				// might be a type, member or ctor
+				string memberName = documentationReference.MemberName;
+				ResolveResult rr;
+				if (documentationReference.DeclaringType.IsNull) {
+					rr = resolver.LookupSimpleNameOrTypeName(memberName, typeArguments, NameLookupMode.Expression);
+				} else {
+					var target = Resolve(documentationReference.DeclaringType);
+					rr = resolver.ResolveMemberAccess(target, memberName, typeArguments);
+				}
+				// reduce to definition:
+				if (rr.IsError) {
+					return rr;
+				} else if (rr is TypeResolveResult) {
+					var typeDef = rr.Type.GetDefinition();
+					if (typeDef == null)
+						return errorResult;
+					if (documentationReference.HasParameterList) {
+						var ctors = typeDef.GetConstructors(options: GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions);
+						return FindByParameters(ctors, parameters);
+					} else {
+						return new TypeResolveResult(typeDef);
+					}
+				} else if (rr is MemberResolveResult) {
+					var mrr = (MemberResolveResult)rr;
+					return new MemberResolveResult(null, mrr.Member.MemberDefinition);
+				} else if (rr is MethodGroupResolveResult) {
+					var mgrr = (MethodGroupResolveResult)rr;
+					var methods = mgrr.MethodsGroupedByDeclaringType.Reverse()
+						.SelectMany(ml => ml.Select(m => (IParameterizedMember)m.MemberDefinition));
+					return FindByParameters(methods, parameters);
+				}
+				return rr;
+			}
+			
+			// Indexer or operator
+			if (declaringTypeDef == null)
+				return errorResult;
+			if (documentationReference.SymbolKind == SymbolKind.Indexer) {
+				var indexers = declaringTypeDef.Properties.Where(p => p.IsIndexer && !p.IsExplicitInterfaceImplementation);
+				return FindByParameters(indexers, parameters);
+			} else if (documentationReference.SymbolKind == SymbolKind.Operator) {
+				var opType = documentationReference.OperatorType;
+				string memberName = OperatorDeclaration.GetName(opType);
+				var methods = declaringTypeDef.Methods.Where(m => m.IsOperator && m.Name == memberName);
+				if (opType == OperatorType.Implicit || opType == OperatorType.Explicit) {
+					// conversion operator
+					foreach (var method in methods) {
+						if (ParameterListComparer.Instance.Equals(method.Parameters, parameters)) {
+							if (method.ReturnType.Equals(conversionOperatorReturnType))
+								return new MemberResolveResult(null, method);
+						}
+					}
+					return new MemberResolveResult(null, methods.FirstOrDefault());
+				} else {
+					// not a conversion operator
+					return FindByParameters(methods, parameters);
+				}
+			} else {
+				throw new NotSupportedException(); // unknown entity type
+			}
+		}
+		
+		IParameter ResolveXmlDocParameter(ParameterDeclaration p)
+		{
+			var lrr = Resolve(p) as LocalResolveResult;
+			if (lrr != null && lrr.IsParameter)
+				return (IParameter)lrr.Variable;
+			else
+				return new DefaultParameter(SpecialType.UnknownType, string.Empty);
+		}
+		
+		ResolveResult FindByParameters(IEnumerable<IParameterizedMember> methods, IList<IParameter> parameters)
+		{
+			foreach (var method in methods) {
+				if (ParameterListComparer.Instance.Equals(method.Parameters, parameters))
+					return new MemberResolveResult(null, method);
+			}
+			return new MemberResolveResult(null, methods.FirstOrDefault());
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/TypeInference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/TypeInference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Resolver/TypeInference.cs	(revision 11807)
@@ -0,0 +1,978 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp.Resolver
+{
+	public enum TypeInferenceAlgorithm
+	{
+		/// <summary>
+		/// C# 4.0 type inference.
+		/// </summary>
+		CSharp4,
+		/// <summary>
+		/// Improved algorithm (not part of any specification) using FindTypeInBounds for fixing.
+		/// </summary>
+		Improved,
+		/// <summary>
+		/// Improved algorithm (not part of any specification) using FindTypeInBounds for fixing;
+		/// uses <see cref="IntersectionType"/> to report all results (in case of ambiguities).
+		/// </summary>
+		ImprovedReturnAllResults
+	}
+	
+	/// <summary>
+	/// Implements C# 4.0 Type Inference (§7.5.2).
+	/// </summary>
+	public sealed class TypeInference
+	{
+		readonly ICompilation compilation;
+		readonly CSharpConversions conversions;
+		TypeInferenceAlgorithm algorithm = TypeInferenceAlgorithm.CSharp4;
+		
+		// determines the maximum generic nesting level; necessary to avoid infinite recursion in 'Improved' mode.
+		const int maxNestingLevel = 5;
+		int nestingLevel;
+		
+		#region Constructor
+		public TypeInference(ICompilation compilation)
+		{
+			if (compilation == null)
+				throw new ArgumentNullException("compilation");
+			this.compilation = compilation;
+			this.conversions = CSharpConversions.Get(compilation);
+		}
+		
+		internal TypeInference(ICompilation compilation, CSharpConversions conversions)
+		{
+			Debug.Assert(compilation != null);
+			Debug.Assert(conversions != null);
+			this.compilation = compilation;
+			this.conversions = conversions;
+		}
+		#endregion
+		
+		#region Properties
+		/// <summary>
+		/// Gets/Sets the type inference algorithm used.
+		/// </summary>
+		public TypeInferenceAlgorithm Algorithm {
+			get { return algorithm; }
+			set { algorithm = value; }
+		}
+		
+		TypeInference CreateNestedInstance()
+		{
+			TypeInference c = new TypeInference(compilation, conversions);
+			c.algorithm = algorithm;
+			c.nestingLevel = nestingLevel + 1;
+			return c;
+		}
+		#endregion
+		
+		TP[] typeParameters;
+		IType[] parameterTypes;
+		ResolveResult[] arguments;
+		bool[,] dependencyMatrix;
+		IList<IType> classTypeArguments;
+		
+		#region InferTypeArguments (main function)
+		/// <summary>
+		/// Performs type inference.
+		/// </summary>
+		/// <param name="typeParameters">The method type parameters that should be inferred.</param>
+		/// <param name="arguments">The arguments passed to the method.</param>
+		/// <param name="parameterTypes">The parameter types of the method.</param>
+		/// <param name="success">Out: whether type inference was successful</param>
+		/// <param name="classTypeArguments">
+		/// Class type arguments. These are substituted for class type parameters in the formal parameter types
+		/// when inferring a method group or lambda.
+		/// </param>
+		/// <returns>The inferred type arguments.</returns>
+		public IType[] InferTypeArguments(IList<ITypeParameter> typeParameters, IList<ResolveResult> arguments, IList<IType> parameterTypes, out bool success, IList<IType> classTypeArguments = null)
+		{
+			if (typeParameters == null)
+				throw new ArgumentNullException("typeParameters");
+			if (arguments == null)
+				throw new ArgumentNullException("arguments");
+			if (parameterTypes == null)
+				throw new ArgumentNullException("parameterTypes");
+			try {
+				this.typeParameters = new TP[typeParameters.Count];
+				for (int i = 0; i < this.typeParameters.Length; i++) {
+					if (i != typeParameters[i].Index)
+						throw new ArgumentException("Type parameter has wrong index");
+					if (typeParameters[i].OwnerType != SymbolKind.Method)
+						throw new ArgumentException("Type parameter must be owned by a method");
+					this.typeParameters[i] = new TP(typeParameters[i]);
+				}
+				this.parameterTypes = new IType[Math.Min(arguments.Count, parameterTypes.Count)];
+				this.arguments = new ResolveResult[this.parameterTypes.Length];
+				for (int i = 0; i < this.parameterTypes.Length; i++) {
+					if (arguments[i] == null || parameterTypes[i] == null)
+						throw new ArgumentNullException();
+					this.arguments[i] = arguments[i];
+					this.parameterTypes[i] = parameterTypes[i];
+				}
+				this.classTypeArguments = classTypeArguments;
+				Log.WriteLine("Type Inference");
+				Log.WriteLine("  Signature: M<" + string.Join<TP>(", ", this.typeParameters) + ">"
+				              + "(" + string.Join<IType>(", ", this.parameterTypes) + ")");
+				Log.WriteCollection("  Arguments: ", arguments);
+				Log.Indent();
+				
+				PhaseOne();
+				success = PhaseTwo();
+				
+				Log.Unindent();
+				Log.WriteLine("  Type inference finished " + (success ? "successfully" : "with errors") + ": " +
+				              "M<" + string.Join(", ", this.typeParameters.Select(tp => tp.FixedTo ?? SpecialType.UnknownType)) + ">");
+				return this.typeParameters.Select(tp => tp.FixedTo ?? SpecialType.UnknownType).ToArray();
+			} finally {
+				Reset();
+			}
+		}
+		
+		void Reset()
+		{
+			// clean up so that memory used by the operation can be garbage collected as soon as possible
+			this.typeParameters = null;
+			this.parameterTypes = null;
+			this.arguments = null;
+			this.dependencyMatrix = null;
+			this.classTypeArguments = null;
+		}
+		
+		/// <summary>
+		/// Infers type arguments for the <paramref name="typeParameters"/> occurring in the <paramref name="targetType"/>
+		/// so that the resulting type (after substition) satisfies the given bounds.
+		/// </summary>
+		public IType[] InferTypeArgumentsFromBounds(IList<ITypeParameter> typeParameters, IType targetType, IList<IType> lowerBounds, IList<IType> upperBounds, out bool success)
+		{
+			if (typeParameters == null)
+				throw new ArgumentNullException("typeParameters");
+			if (targetType == null)
+				throw new ArgumentNullException("targetType");
+			if (lowerBounds == null)
+				throw new ArgumentNullException("lowerBounds");
+			if (upperBounds == null)
+				throw new ArgumentNullException("upperBounds");
+			this.typeParameters = new TP[typeParameters.Count];
+			for (int i = 0; i < this.typeParameters.Length; i++) {
+				if (i != typeParameters[i].Index)
+					throw new ArgumentException("Type parameter has wrong index");
+				this.typeParameters[i] = new TP(typeParameters[i]);
+			}
+			foreach (IType b in lowerBounds) {
+				MakeLowerBoundInference(b, targetType);
+			}
+			foreach (IType b in upperBounds) {
+				MakeUpperBoundInference(b, targetType);
+			}
+			IType[] result = new IType[this.typeParameters.Length];
+			success = true;
+			for (int i = 0; i < result.Length; i++) {
+				success &= Fix(this.typeParameters[i]);
+				result[i] = this.typeParameters[i].FixedTo ?? SpecialType.UnknownType;
+			}
+			Reset();
+			return result;
+		}
+		#endregion
+		
+		sealed class TP
+		{
+			public readonly HashSet<IType> LowerBounds = new HashSet<IType>();
+			public readonly HashSet<IType> UpperBounds = new HashSet<IType>();
+			public IType ExactBound;
+			public bool MultipleDifferentExactBounds;
+			public readonly ITypeParameter TypeParameter;
+			public IType FixedTo;
+			
+			public bool IsFixed {
+				get { return FixedTo != null; }
+			}
+			
+			public bool HasBounds {
+				get { return LowerBounds.Count > 0 || UpperBounds.Count > 0 || ExactBound != null; }
+			}
+			
+			public TP(ITypeParameter typeParameter)
+			{
+				if (typeParameter == null)
+					throw new ArgumentNullException("typeParameter");
+				this.TypeParameter = typeParameter;
+			}
+			
+			public void AddExactBound(IType type)
+			{
+				// Exact bounds need to stored separately, not just as Lower+Upper bounds,
+				// due to TypeInferenceTests.GenericArgumentImplicitlyConvertibleToAndFromAnotherTypeList (see #281)
+				if (ExactBound == null)
+					ExactBound = type;
+				else if (!ExactBound.Equals(type))
+					MultipleDifferentExactBounds = true;
+			}
+			
+			public override string ToString()
+			{
+				return TypeParameter.Name;
+			}
+		}
+		
+		sealed class OccursInVisitor : TypeVisitor
+		{
+			readonly TP[] tp;
+			public readonly bool[] Occurs;
+			
+			public OccursInVisitor(TypeInference typeInference)
+			{
+				this.tp = typeInference.typeParameters;
+				this.Occurs = new bool[tp.Length];
+			}
+			
+			public override IType VisitTypeParameter(ITypeParameter type)
+			{
+				int index = type.Index;
+				if (index < tp.Length && tp[index].TypeParameter == type)
+					Occurs[index] = true;
+				return base.VisitTypeParameter(type);
+			}
+		}
+		
+		#region Inference Phases
+		void PhaseOne()
+		{
+			// C# 4.0 spec: §7.5.2.1 The first phase
+			Log.WriteLine("Phase One");
+			for (int i = 0; i < arguments.Length; i++) {
+				ResolveResult Ei = arguments[i];
+				IType Ti = parameterTypes[i];
+				
+				LambdaResolveResult lrr = Ei as LambdaResolveResult;
+				if (lrr != null) {
+					MakeExplicitParameterTypeInference(lrr, Ti);
+				}
+				if (lrr != null || Ei is MethodGroupResolveResult) {
+					// this is not in the spec???
+					if (OutputTypeContainsUnfixed(Ei, Ti) && !InputTypesContainsUnfixed(Ei, Ti)) {
+						MakeOutputTypeInference(Ei, Ti);
+					}
+				}
+				
+				if (IsValidType(Ei.Type)) {
+					if (Ti is ByReferenceType) {
+						MakeExactInference(Ei.Type, Ti);
+					} else {
+						MakeLowerBoundInference(Ei.Type, Ti);
+					}
+				}
+			}
+		}
+		
+		static bool IsValidType(IType type)
+		{
+			return type.Kind != TypeKind.Unknown && type.Kind != TypeKind.Null;
+		}
+		
+		bool PhaseTwo()
+		{
+			// C# 4.0 spec: §7.5.2.2 The second phase
+			Log.WriteLine("Phase Two");
+			// All unfixed type variables Xi which do not depend on any Xj are fixed.
+			List<TP> typeParametersToFix = new List<TP>();
+			foreach (TP Xi in typeParameters) {
+				if (Xi.IsFixed == false) {
+					if (!typeParameters.Any((TP Xj) => !Xj.IsFixed && DependsOn(Xi, Xj))) {
+						typeParametersToFix.Add(Xi);
+					}
+				}
+			}
+			// If no such type variables exist, all unfixed type variables Xi are fixed for which all of the following hold:
+			if (typeParametersToFix.Count == 0) {
+				Log.WriteLine("Type parameters cannot be fixed due to dependency cycles");
+				Log.WriteLine("Trying to break the cycle by fixing any TPs that have non-empty bounds...");
+				foreach (TP Xi in typeParameters) {
+					// Xi has a non­empty set of bounds
+					if (!Xi.IsFixed && Xi.HasBounds) {
+						// There is at least one type variable Xj that depends on Xi
+						if (typeParameters.Any((TP Xj) => DependsOn(Xj, Xi))) {
+							typeParametersToFix.Add(Xi);
+						}
+					}
+				}
+			}
+			// now fix 'em
+			bool errorDuringFix = false;
+			foreach (TP tp in typeParametersToFix) {
+				if (!Fix(tp))
+					errorDuringFix = true;
+			}
+			if (errorDuringFix)
+				return false;
+			bool unfixedTypeVariablesExist = typeParameters.Any((TP X) => X.IsFixed == false);
+			if (typeParametersToFix.Count == 0 && unfixedTypeVariablesExist) {
+				// If no such type variables exist and there are still unfixed type variables, type inference fails.
+				Log.WriteLine("Type inference fails: there are still unfixed TPs remaining");
+				return false;
+			} else if (!unfixedTypeVariablesExist) {
+				// Otherwise, if no further unfixed type variables exist, type inference succeeds.
+				return true;
+			} else {
+				// Otherwise, for all arguments ei with corresponding parameter type Ti
+				for (int i = 0; i < arguments.Length; i++) {
+					ResolveResult Ei = arguments[i];
+					IType Ti = parameterTypes[i];
+					// where the output types (§7.4.2.4) contain unfixed type variables Xj
+					// but the input types (§7.4.2.3) do not
+					if (OutputTypeContainsUnfixed(Ei, Ti) && !InputTypesContainsUnfixed(Ei, Ti)) {
+						// an output type inference (§7.4.2.6) is made for ei with type Ti.
+						Log.WriteLine("MakeOutputTypeInference for argument #" + i);
+						MakeOutputTypeInference(Ei, Ti);
+					}
+				}
+				// Then the second phase is repeated.
+				return PhaseTwo();
+			}
+		}
+		#endregion
+		
+		#region Input Types / Output Types (§7.5.2.3 + §7.5.2.4)
+		static readonly IType[] emptyTypeArray = new IType[0];
+		
+		IType[] InputTypes(ResolveResult e, IType t)
+		{
+			// C# 4.0 spec: §7.5.2.3 Input types
+			LambdaResolveResult lrr = e as LambdaResolveResult;
+			if (lrr != null && lrr.IsImplicitlyTyped || e is MethodGroupResolveResult) {
+				IMethod m = GetDelegateOrExpressionTreeSignature(t);
+				if (m != null) {
+					IType[] inputTypes = new IType[m.Parameters.Count];
+					for (int i = 0; i < inputTypes.Length; i++) {
+						inputTypes[i] = m.Parameters[i].Type;
+					}
+					return inputTypes;
+				}
+			}
+			return emptyTypeArray;
+		}
+		
+		IType[] OutputTypes(ResolveResult e, IType t)
+		{
+			// C# 4.0 spec: §7.5.2.4 Output types
+			LambdaResolveResult lrr = e as LambdaResolveResult;
+			if (lrr != null || e is MethodGroupResolveResult) {
+				IMethod m = GetDelegateOrExpressionTreeSignature(t);
+				if (m != null) {
+					return new[] { m.ReturnType };
+				}
+			}
+			return emptyTypeArray;
+		}
+		
+		static IMethod GetDelegateOrExpressionTreeSignature(IType t)
+		{
+			ParameterizedType pt = t as ParameterizedType;
+			if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Expression"
+			    && pt.Namespace == "System.Linq.Expressions")
+			{
+				t = pt.GetTypeArgument(0);
+			}
+			return t.GetDelegateInvokeMethod();
+		}
+		
+		bool InputTypesContainsUnfixed(ResolveResult argument, IType parameterType)
+		{
+			return AnyTypeContainsUnfixedParameter(InputTypes(argument, parameterType));
+		}
+		
+		bool OutputTypeContainsUnfixed(ResolveResult argument, IType parameterType)
+		{
+			return AnyTypeContainsUnfixedParameter(OutputTypes(argument, parameterType));
+		}
+		
+		bool AnyTypeContainsUnfixedParameter(IEnumerable<IType> types)
+		{
+			OccursInVisitor o = new OccursInVisitor(this);
+			foreach (var type in types) {
+				type.AcceptVisitor(o);
+			}
+			for (int i = 0; i < typeParameters.Length; i++) {
+				if (!typeParameters[i].IsFixed && o.Occurs[i])
+					return true;
+			}
+			return false;
+		}
+		#endregion
+		
+		#region DependsOn (§7.5.2.5)
+		// C# 4.0 spec: §7.5.2.5 Dependance
+		
+		void CalculateDependencyMatrix()
+		{
+			int n = typeParameters.Length;
+			dependencyMatrix = new bool[n, n];
+			for (int k = 0; k < arguments.Length; k++) {
+				OccursInVisitor input = new OccursInVisitor(this);
+				OccursInVisitor output = new OccursInVisitor(this);
+				foreach (var type in InputTypes(arguments[k], parameterTypes[k])) {
+					type.AcceptVisitor(input);
+				}
+				foreach (var type in OutputTypes(arguments[k], parameterTypes[k])) {
+					type.AcceptVisitor(output);
+				}
+				for (int i = 0; i < n; i++) {
+					for (int j = 0; j < n; j++) {
+						dependencyMatrix[i, j] |= input.Occurs[j] && output.Occurs[i];
+					}
+				}
+			}
+			// calculate transitive closure using Warshall's algorithm:
+			for (int i = 0; i < n; i++) {
+				for (int j = 0; j < n; j++) {
+					if (dependencyMatrix[i, j]) {
+						for (int k = 0; k < n; k++) {
+							if (dependencyMatrix[j, k])
+								dependencyMatrix[i, k] = true;
+						}
+					}
+				}
+			}
+		}
+		
+		bool DependsOn(TP x, TP y)
+		{
+			if (dependencyMatrix == null)
+				CalculateDependencyMatrix();
+			// x depends on y
+			return dependencyMatrix[x.TypeParameter.Index, y.TypeParameter.Index];
+		}
+		#endregion
+		
+		#region MakeOutputTypeInference (§7.5.2.6)
+		void MakeOutputTypeInference(ResolveResult e, IType t)
+		{
+			Log.WriteLine(" MakeOutputTypeInference from " + e + " to " + t);
+			// If E is an anonymous function with inferred return type  U (§7.5.2.12) and T is a delegate type or expression
+			// tree type with return type Tb, then a lower-bound inference (§7.5.2.9) is made from U to Tb.
+			LambdaResolveResult lrr = e as LambdaResolveResult;
+			if (lrr != null) {
+				IMethod m = GetDelegateOrExpressionTreeSignature(t);
+				if (m != null) {
+					IType inferredReturnType;
+					if (lrr.IsImplicitlyTyped) {
+						if (m.Parameters.Count != lrr.Parameters.Count)
+							return; // cannot infer due to mismatched parameter lists
+						TypeParameterSubstitution substitution = GetSubstitutionForFixedTPs();
+						IType[] inferredParameterTypes = new IType[m.Parameters.Count];
+						for (int i = 0; i < inferredParameterTypes.Length; i++) {
+							IType parameterType = m.Parameters[i].Type;
+							inferredParameterTypes[i] = parameterType.AcceptVisitor(substitution);
+						}
+						inferredReturnType = lrr.GetInferredReturnType(inferredParameterTypes);
+					} else {
+						inferredReturnType = lrr.GetInferredReturnType(null);
+					}
+					MakeLowerBoundInference(inferredReturnType, m.ReturnType);
+					return;
+				}
+			}
+			// Otherwise, if E is a method group and T is a delegate type or expression tree type
+			// with parameter types T1…Tk and return type Tb, and overload resolution
+			// of E with the types T1…Tk yields a single method with return type U, then a lower­-bound
+			// inference is made from U to Tb.
+			MethodGroupResolveResult mgrr = e as MethodGroupResolveResult;
+			if (mgrr != null) {
+				IMethod m = GetDelegateOrExpressionTreeSignature(t);
+				if (m != null) {
+					ResolveResult[] args = new ResolveResult[m.Parameters.Count];
+					TypeParameterSubstitution substitution = GetSubstitutionForFixedTPs();
+					for (int i = 0; i < args.Length; i++) {
+						IParameter param = m.Parameters[i];
+						IType parameterType = param.Type.AcceptVisitor(substitution);
+						if ((param.IsRef || param.IsOut) && parameterType.Kind == TypeKind.ByReference) {
+							parameterType = ((ByReferenceType)parameterType).ElementType;
+							args[i] = new ByReferenceResolveResult(parameterType, param.IsOut);
+						} else {
+							args[i] = new ResolveResult(parameterType);
+						}
+					}
+					var or = mgrr.PerformOverloadResolution(compilation,
+					                                        args,
+					                                        allowExpandingParams: false, allowOptionalParameters: false);
+					if (or.FoundApplicableCandidate && or.BestCandidateAmbiguousWith == null) {
+						IType returnType = or.GetBestCandidateWithSubstitutedTypeArguments().ReturnType;
+						MakeLowerBoundInference(returnType, m.ReturnType);
+					}
+				}
+				return;
+			}
+			// Otherwise, if E is an expression with type U, then a lower-bound inference is made from U to T.
+			if (IsValidType(e.Type)) {
+				MakeLowerBoundInference(e.Type, t);
+			}
+		}
+		
+		TypeParameterSubstitution GetSubstitutionForFixedTPs()
+		{
+			IType[] fixedTypes = new IType[typeParameters.Length];
+			for (int i = 0; i < fixedTypes.Length; i++) {
+				fixedTypes[i] = typeParameters[i].FixedTo ?? SpecialType.UnknownType;
+			}
+			return new TypeParameterSubstitution(classTypeArguments, fixedTypes);
+		}
+		#endregion
+		
+		#region MakeExplicitParameterTypeInference (§7.5.2.7)
+		void MakeExplicitParameterTypeInference(LambdaResolveResult e, IType t)
+		{
+			// C# 4.0 spec: §7.5.2.7 Explicit parameter type inferences
+			if (e.IsImplicitlyTyped || !e.HasParameterList)
+				return;
+			Log.WriteLine(" MakeExplicitParameterTypeInference from " + e + " to " + t);
+			IMethod m = GetDelegateOrExpressionTreeSignature(t);
+			if (m == null)
+				return;
+			for (int i = 0; i < e.Parameters.Count && i < m.Parameters.Count; i++) {
+				MakeExactInference(e.Parameters[i].Type, m.Parameters[i].Type);
+			}
+		}
+		#endregion
+		
+		#region MakeExactInference (§7.5.2.8)
+		/// <summary>
+		/// Make exact inference from U to V.
+		/// C# 4.0 spec: §7.5.2.8 Exact inferences
+		/// </summary>
+		void MakeExactInference(IType U, IType V)
+		{
+			Log.WriteLine("MakeExactInference from " + U + " to " + V);
+			
+			// If V is one of the unfixed Xi then U is added to the set of bounds for Xi.
+			TP tp = GetTPForType(V);
+			if (tp != null && tp.IsFixed == false) {
+				Log.WriteLine(" Add exact bound '" + U + "' to " + tp);
+				tp.AddExactBound(U);
+				return;
+			}
+			// Handle by reference types:
+			ByReferenceType brU = U as ByReferenceType;
+			ByReferenceType brV = V as ByReferenceType;
+			if (brU != null && brV != null) {
+				MakeExactInference(brU.ElementType, brV.ElementType);
+				return;
+			}
+			// Handle array types:
+			ArrayType arrU = U as ArrayType;
+			ArrayType arrV = V as ArrayType;
+			if (arrU != null && arrV != null && arrU.Dimensions == arrV.Dimensions) {
+				MakeExactInference(arrU.ElementType, arrV.ElementType);
+				return;
+			}
+			// Handle parameterized type:
+			ParameterizedType pU = U as ParameterizedType;
+			ParameterizedType pV = V as ParameterizedType;
+			if (pU != null && pV != null
+			    && object.Equals(pU.GetDefinition(), pV.GetDefinition())
+			    && pU.TypeParameterCount == pV.TypeParameterCount)
+			{
+				Log.Indent();
+				for (int i = 0; i < pU.TypeParameterCount; i++) {
+					MakeExactInference(pU.GetTypeArgument(i), pV.GetTypeArgument(i));
+				}
+				Log.Unindent();
+			}
+		}
+		
+		TP GetTPForType(IType v)
+		{
+			ITypeParameter p = v as ITypeParameter;
+			if (p != null) {
+				int index = p.Index;
+				if (index < typeParameters.Length && typeParameters[index].TypeParameter == p)
+					return typeParameters[index];
+			}
+			return null;
+		}
+		#endregion
+		
+		#region MakeLowerBoundInference (§7.5.2.9)
+		/// <summary>
+		/// Make lower bound inference from U to V.
+		/// C# 4.0 spec: §7.5.2.9 Lower-bound inferences
+		/// </summary>
+		void MakeLowerBoundInference(IType U, IType V)
+		{
+			Log.WriteLine(" MakeLowerBoundInference from " + U + " to " + V);
+			
+			// If V is one of the unfixed Xi then U is added to the set of bounds for Xi.
+			TP tp = GetTPForType(V);
+			if (tp != null && tp.IsFixed == false) {
+				Log.WriteLine("  Add lower bound '" + U + "' to " + tp);
+				tp.LowerBounds.Add(U);
+				return;
+			}
+			// Handle nullable covariance:
+			if (NullableType.IsNullable(U) && NullableType.IsNullable(V)) {
+				MakeLowerBoundInference(NullableType.GetUnderlyingType(U), NullableType.GetUnderlyingType(V));
+				return;
+			}
+			
+			// Handle array types:
+			ArrayType arrU = U as ArrayType;
+			ArrayType arrV = V as ArrayType;
+			ParameterizedType pV = V as ParameterizedType;
+			if (arrU != null && arrV != null && arrU.Dimensions == arrV.Dimensions) {
+				MakeLowerBoundInference(arrU.ElementType, arrV.ElementType);
+				return;
+			} else if (arrU != null && IsGenericInterfaceImplementedByArray(pV) && arrU.Dimensions == 1) {
+				MakeLowerBoundInference(arrU.ElementType, pV.GetTypeArgument(0));
+				return;
+			}
+			// Handle parameterized types:
+			if (pV != null) {
+				ParameterizedType uniqueBaseType = null;
+				foreach (IType baseU in U.GetAllBaseTypes()) {
+					ParameterizedType pU = baseU as ParameterizedType;
+					if (pU != null && object.Equals(pU.GetDefinition(), pV.GetDefinition()) && pU.TypeParameterCount == pV.TypeParameterCount) {
+						if (uniqueBaseType == null)
+							uniqueBaseType = pU;
+						else
+							return; // cannot make an inference because it's not unique
+					}
+				}
+				Log.Indent();
+				if (uniqueBaseType != null) {
+					for (int i = 0; i < uniqueBaseType.TypeParameterCount; i++) {
+						IType Ui = uniqueBaseType.GetTypeArgument(i);
+						IType Vi = pV.GetTypeArgument(i);
+						if (Ui.IsReferenceType == true) {
+							// look for variance
+							ITypeParameter Xi = pV.GetDefinition().TypeParameters[i];
+							switch (Xi.Variance) {
+								case VarianceModifier.Covariant:
+									MakeLowerBoundInference(Ui, Vi);
+									break;
+								case VarianceModifier.Contravariant:
+									MakeUpperBoundInference(Ui, Vi);
+									break;
+								default: // invariant
+									MakeExactInference(Ui, Vi);
+									break;
+							}
+						} else {
+							// not known to be a reference type
+							MakeExactInference(Ui, Vi);
+						}
+					}
+				}
+				Log.Unindent();
+			}
+		}
+		
+		static bool IsGenericInterfaceImplementedByArray(ParameterizedType rt)
+		{
+			if (rt == null || rt.TypeParameterCount != 1)
+				return false;
+			switch (rt.GetDefinition().KnownTypeCode) {
+				case KnownTypeCode.IEnumerableOfT:
+				case KnownTypeCode.ICollectionOfT:
+				case KnownTypeCode.IListOfT:
+				case KnownTypeCode.IReadOnlyCollectionOfT:
+				case KnownTypeCode.IReadOnlyListOfT:
+					return true;
+				default:
+					return false;
+			}
+		}
+		#endregion
+		
+		#region MakeUpperBoundInference (§7.5.2.10)
+		/// <summary>
+		/// Make upper bound inference from U to V.
+		/// C# 4.0 spec: §7.5.2.10 Upper-bound inferences
+		/// </summary>
+		void MakeUpperBoundInference(IType U, IType V)
+		{
+			Log.WriteLine(" MakeUpperBoundInference from " + U + " to " + V);
+			
+			// If V is one of the unfixed Xi then U is added to the set of bounds for Xi.
+			TP tp = GetTPForType(V);
+			if (tp != null && tp.IsFixed == false) {
+				Log.WriteLine("  Add upper bound '" + U + "' to " + tp);
+				tp.UpperBounds.Add(U);
+				return;
+			}
+			
+			// Handle array types:
+			ArrayType arrU = U as ArrayType;
+			ArrayType arrV = V as ArrayType;
+			ParameterizedType pU = U as ParameterizedType;
+			if (arrV != null && arrU != null && arrU.Dimensions == arrV.Dimensions) {
+				MakeUpperBoundInference(arrU.ElementType, arrV.ElementType);
+				return;
+			} else if (arrV != null && IsGenericInterfaceImplementedByArray(pU) && arrV.Dimensions == 1) {
+				MakeUpperBoundInference(pU.GetTypeArgument(0), arrV.ElementType);
+				return;
+			}
+			// Handle parameterized types:
+			if (pU != null) {
+				ParameterizedType uniqueBaseType = null;
+				foreach (IType baseV in V.GetAllBaseTypes()) {
+					ParameterizedType pV = baseV as ParameterizedType;
+					if (pV != null && object.Equals(pU.GetDefinition(), pV.GetDefinition()) && pU.TypeParameterCount == pV.TypeParameterCount) {
+						if (uniqueBaseType == null)
+							uniqueBaseType = pV;
+						else
+							return; // cannot make an inference because it's not unique
+					}
+				}
+				Log.Indent();
+				if (uniqueBaseType != null) {
+					for (int i = 0; i < uniqueBaseType.TypeParameterCount; i++) {
+						IType Ui = pU.GetTypeArgument(i);
+						IType Vi = uniqueBaseType.GetTypeArgument(i);
+						if (Ui.IsReferenceType == true) {
+							// look for variance
+							ITypeParameter Xi = pU.GetDefinition().TypeParameters[i];
+							switch (Xi.Variance) {
+								case VarianceModifier.Covariant:
+									MakeUpperBoundInference(Ui, Vi);
+									break;
+								case VarianceModifier.Contravariant:
+									MakeLowerBoundInference(Ui, Vi);
+									break;
+								default: // invariant
+									MakeExactInference(Ui, Vi);
+									break;
+							}
+						} else {
+							// not known to be a reference type
+							MakeExactInference(Ui, Vi);
+						}
+					}
+				}
+				Log.Unindent();
+			}
+		}
+		#endregion
+		
+		#region Fixing (§7.5.2.11)
+		bool Fix(TP tp)
+		{
+			Log.WriteLine(" Trying to fix " + tp);
+			Debug.Assert(!tp.IsFixed);
+			if (tp.ExactBound != null) {
+				// the exact bound will always be the result
+				tp.FixedTo = tp.ExactBound;
+				// check validity
+				if (tp.MultipleDifferentExactBounds)
+					return false;
+				return tp.LowerBounds.All(b => conversions.ImplicitConversion(b, tp.FixedTo).IsValid)
+					&& tp.UpperBounds.All(b => conversions.ImplicitConversion(tp.FixedTo, b).IsValid);
+			}
+			Log.Indent();
+			var types = CreateNestedInstance().FindTypesInBounds(tp.LowerBounds.ToArray(), tp.UpperBounds.ToArray());
+			Log.Unindent();
+			if (algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults) {
+				tp.FixedTo = IntersectionType.Create(types);
+				Log.WriteLine("  T was fixed " + (types.Count >= 1 ? "successfully" : "(with errors)") + " to " + tp.FixedTo);
+				return types.Count >= 1;
+			} else {
+				tp.FixedTo = GetFirstTypePreferNonInterfaces(types);
+				Log.WriteLine("  T was fixed " + (types.Count == 1 ? "successfully" : "(with errors)") + " to " + tp.FixedTo);
+				return types.Count == 1;
+			}
+		}
+		#endregion
+		
+		#region Finding the best common type of a set of expresssions
+		/// <summary>
+		/// Gets the best common type (C# 4.0 spec: §7.5.2.14) of a set of expressions.
+		/// </summary>
+		public IType GetBestCommonType(IList<ResolveResult> expressions, out bool success)
+		{
+			if (expressions == null)
+				throw new ArgumentNullException("expressions");
+			if (expressions.Count == 1) {
+				success = (expressions[0].Type.Kind != TypeKind.Unknown);
+				return expressions[0].Type;
+			}
+			Log.WriteCollection("GetBestCommonType() for ", expressions);
+			try {
+				ITypeParameter tp = DummyTypeParameter.GetMethodTypeParameter(0);
+				this.typeParameters = new TP[1] { new TP(tp) };
+				foreach (ResolveResult r in expressions) {
+					MakeOutputTypeInference(r, tp);
+				}
+				success = Fix(typeParameters[0]);
+				return typeParameters[0].FixedTo ?? SpecialType.UnknownType;
+			} finally {
+				Reset();
+			}
+		}
+		#endregion
+		
+		#region FindTypeInBounds
+		/// <summary>
+		/// Finds a type that satisfies the given lower and upper bounds.
+		/// </summary>
+		public IType FindTypeInBounds(IList<IType> lowerBounds, IList<IType> upperBounds)
+		{
+			if (lowerBounds == null)
+				throw new ArgumentNullException("lowerBounds");
+			if (upperBounds == null)
+				throw new ArgumentNullException("upperBounds");
+			
+			IList<IType> result = FindTypesInBounds(lowerBounds, upperBounds);
+			
+			if (algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults) {
+				return IntersectionType.Create(result);
+			} else {
+				// return any of the candidates (prefer non-interfaces)
+				return GetFirstTypePreferNonInterfaces(result);
+			}
+		}
+		
+		static IType GetFirstTypePreferNonInterfaces(IList<IType> result)
+		{
+			return result.FirstOrDefault(c => c.Kind != TypeKind.Interface)
+				?? result.FirstOrDefault() ?? SpecialType.UnknownType;
+		}
+		
+		IList<IType> FindTypesInBounds(IList<IType> lowerBounds, IList<IType> upperBounds)
+		{
+			// If there's only a single type; return that single type.
+			// If both inputs are empty, return the empty list.
+			if (lowerBounds.Count == 0 && upperBounds.Count <= 1)
+				return upperBounds;
+			if (upperBounds.Count == 0 && lowerBounds.Count <= 1)
+				return lowerBounds;
+			if (nestingLevel > maxNestingLevel)
+				return EmptyList<IType>.Instance;
+			
+			// Finds a type X so that "LB <: X <: UB"
+			Log.WriteCollection("FindTypesInBound, LowerBounds=", lowerBounds);
+			Log.WriteCollection("FindTypesInBound, UpperBounds=", upperBounds);
+			
+			// First try the Fixing algorithm from the C# spec (§7.5.2.11)
+			List<IType> candidateTypes = lowerBounds.Union(upperBounds)
+				.Where(c => lowerBounds.All(b => conversions.ImplicitConversion(b, c).IsValid))
+				.Where(c => upperBounds.All(b => conversions.ImplicitConversion(c, b).IsValid))
+				.ToList(); // evaluate the query only once
+
+			Log.WriteCollection("FindTypesInBound, Candidates=", candidateTypes);
+			
+			// According to the C# specification, we need to pick the most specific
+			// of the candidate types. (the type which has conversions to all others)
+			// However, csc actually seems to choose the least specific.
+			candidateTypes = candidateTypes.Where(
+				c => candidateTypes.All(o => conversions.ImplicitConversion(o, c).IsValid)
+			).ToList();
+
+			// If the specified algorithm produces a single candidate, we return
+			// that candidate.
+			// We also return the whole candidate list if we're not using the improved
+			// algorithm.
+			if (candidateTypes.Count == 1 || !(algorithm == TypeInferenceAlgorithm.Improved || algorithm == TypeInferenceAlgorithm.ImprovedReturnAllResults))
+			{
+				return candidateTypes;
+			}
+			candidateTypes.Clear();
+			
+			// Now try the improved algorithm
+			Log.Indent();
+			List<ITypeDefinition> candidateTypeDefinitions;
+			if (lowerBounds.Count > 0) {
+				// Find candidates by using the lower bounds:
+				var hashSet = new HashSet<ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions());
+				for (int i = 1; i < lowerBounds.Count; i++) {
+					hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions());
+				}
+				candidateTypeDefinitions = hashSet.ToList();
+			} else {
+				// Find candidates by looking at all classes in the project:
+				candidateTypeDefinitions = compilation.GetAllTypeDefinitions().ToList();
+			}
+			
+			// Now filter out candidates that violate the upper bounds:
+			foreach (IType ub in upperBounds) {
+				ITypeDefinition ubDef = ub.GetDefinition();
+				if (ubDef != null) {
+					candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef));
+				}
+			}
+			
+			foreach (ITypeDefinition candidateDef in candidateTypeDefinitions) {
+				// determine the type parameters for the candidate:
+				IType candidate;
+				if (candidateDef.TypeParameterCount == 0) {
+					candidate = candidateDef;
+				} else {
+					Log.WriteLine("Inferring arguments for candidate type definition: " + candidateDef);
+					bool success;
+					IType[] result = InferTypeArgumentsFromBounds(
+						candidateDef.TypeParameters,
+						new ParameterizedType(candidateDef, candidateDef.TypeParameters),
+						lowerBounds, upperBounds,
+						out success);
+					if (success) {
+						candidate = new ParameterizedType(candidateDef, result);
+					} else {
+						Log.WriteLine("Inference failed; ignoring candidate");
+						continue;
+					}
+				}
+				Log.WriteLine("Candidate type: " + candidate);
+				
+				if (upperBounds.Count == 0) {
+					// if there were only lower bounds, we aim for the most specific candidate:
+					
+					// if this candidate isn't made redundant by an existing, more specific candidate:
+					if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef))) {
+						// remove all existing candidates made redundant by this candidate:
+						candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition()));
+						// add new candidate
+						candidateTypes.Add(candidate);
+					}
+				} else {
+					// if there were upper bounds, we aim for the least specific candidate:
+					
+					// if this candidate isn't made redundant by an existing, less specific candidate:
+					if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition()))) {
+						// remove all existing candidates made redundant by this candidate:
+						candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef));
+						// add new candidate
+						candidateTypes.Add(candidate);
+					}
+				}
+			}
+			Log.Unindent();
+			return candidateTypes;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/AliasNamespaceReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/AliasNamespaceReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/AliasNamespaceReference.cs	(revision 11807)
@@ -0,0 +1,76 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Looks up an alias (identifier in front of :: operator).
+	/// </summary>
+	/// <remarks>
+	/// The member lookup performed by the :: operator is handled
+	/// by <see cref="MemberTypeOrNamespaceReference"/>.
+	/// </remarks>
+	[Serializable]
+	public sealed class AliasNamespaceReference : TypeOrNamespaceReference, ISupportsInterning
+	{
+		readonly string identifier;
+		
+		public AliasNamespaceReference(string identifier)
+		{
+			if (identifier == null)
+				throw new ArgumentNullException("identifier");
+			this.identifier = identifier;
+		}
+		
+		public string Identifier {
+			get { return identifier; }
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveAlias(identifier);
+		}
+		
+		public override IType ResolveType(CSharpResolver resolver)
+		{
+			// alias cannot refer to types
+			return SpecialType.UnknownType;
+		}
+		
+		public override string ToString()
+		{
+			return identifier + "::";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return identifier.GetHashCode();
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			AliasNamespaceReference anr = other as AliasNamespaceReference;
+			return anr != null && this.identifier == anr.identifier;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/AttributeTypeReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/AttributeTypeReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/AttributeTypeReference.cs	(revision 11807)
@@ -0,0 +1,91 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Type reference used within an attribute.
+	/// Looks up both 'withoutSuffix' and 'withSuffix' and returns the type that exists.
+	/// </summary>
+	[Serializable]
+	public sealed class AttributeTypeReference : ITypeReference, ISupportsInterning
+	{
+		readonly ITypeReference withoutSuffix, withSuffix;
+		
+		public AttributeTypeReference(ITypeReference withoutSuffix, ITypeReference withSuffix)
+		{
+			if (withoutSuffix == null)
+				throw new ArgumentNullException("withoutSuffix");
+			if (withSuffix == null)
+				throw new ArgumentNullException("withSuffix");
+			this.withoutSuffix = withoutSuffix;
+			this.withSuffix = withSuffix;
+		}
+		
+		public IType Resolve(ITypeResolveContext context)
+		{
+			IType t1 = withoutSuffix.Resolve(context);
+			IType t2 = withSuffix.Resolve(context);
+			return PreferAttributeTypeWithSuffix(t1, t2, context.Compilation) ? t2 : t1;
+		}
+		
+		internal static bool PreferAttributeTypeWithSuffix(IType t1, IType t2, ICompilation compilation)
+		{
+			if (t2.Kind == TypeKind.Unknown) return false;
+			if (t1.Kind == TypeKind.Unknown) return true;
+			
+			var attrTypeDef = compilation.FindType(KnownTypeCode.Attribute).GetDefinition();
+			if (attrTypeDef != null) {
+				bool t1IsAttribute = (t1.GetDefinition() != null && t1.GetDefinition().IsDerivedFrom(attrTypeDef));
+				bool t2IsAttribute = (t2.GetDefinition() != null && t2.GetDefinition().IsDerivedFrom(attrTypeDef));
+				if (t2IsAttribute && !t1IsAttribute)
+					return true;
+				// If both types exist and are attributes, C# considers that to be an ambiguity, but we are less strict.
+			}
+			return false;
+		}
+		
+		public override string ToString()
+		{
+			return withoutSuffix.ToString() + "[Attribute]";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				return withoutSuffix.GetHashCode() + 715613 * withSuffix.GetHashCode();
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			AttributeTypeReference atr = other as AttributeTypeReference;
+			return atr != null && this.withoutSuffix == atr.withoutSuffix && this.withSuffix == atr.withSuffix;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpAssembly.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpAssembly.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpAssembly.cs	(revision 11807)
@@ -0,0 +1,338 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	public class CSharpAssembly : IAssembly
+	{
+		readonly ICompilation compilation;
+		readonly ITypeResolveContext context;
+		readonly CSharpProjectContent projectContent;
+		IList<IAttribute> assemblyAttributes;
+		IList<IAttribute> moduleAttributes;
+		
+		internal CSharpAssembly(ICompilation compilation, CSharpProjectContent projectContent)
+		{
+			this.compilation = compilation;
+			this.projectContent = projectContent;
+			this.context = new SimpleTypeResolveContext(this);
+		}
+		
+		public bool IsMainAssembly {
+			get { return compilation.MainAssembly == this; }
+		}
+		
+		public IUnresolvedAssembly UnresolvedAssembly {
+			get { return projectContent; }
+		}
+		
+		public string AssemblyName {
+			get { return projectContent.AssemblyName; }
+		}
+		
+		public string FullAssemblyName {
+			get { return projectContent.FullAssemblyName; }
+		}
+		
+		public IList<IAttribute> AssemblyAttributes {
+			get {
+				return GetAttributes(ref assemblyAttributes, true);
+			}
+		}
+		
+		public IList<IAttribute> ModuleAttributes {
+			get {
+				return GetAttributes(ref moduleAttributes, false);
+			}
+		}
+		
+		IList<IAttribute> GetAttributes(ref IList<IAttribute> field, bool assemblyAttributes)
+		{
+			IList<IAttribute> result = LazyInit.VolatileRead(ref field);
+			if (result != null) {
+				return result;
+			} else {
+				result = new List<IAttribute>();
+				foreach (var unresolvedFile in projectContent.Files.OfType<CSharpUnresolvedFile>()) {
+					var attributes = assemblyAttributes ? unresolvedFile.AssemblyAttributes : unresolvedFile.ModuleAttributes;
+					var context = new CSharpTypeResolveContext(this, unresolvedFile.RootUsingScope.Resolve(compilation));
+					foreach (var unresolvedAttr in attributes) {
+						result.Add(unresolvedAttr.CreateResolvedAttribute(context));
+					}
+				}
+				return LazyInit.GetOrSet(ref field, result);
+			}
+		}
+		
+		NS rootNamespace;
+		
+		public INamespace RootNamespace {
+			get {
+				NS root = LazyInit.VolatileRead(ref this.rootNamespace);
+				if (root != null) {
+					return root;
+				} else {
+					root = new NS(this);
+					Dictionary<string, NS> dict = new Dictionary<string, NS>(compilation.NameComparer);
+					dict.Add(string.Empty, root);
+					// Add namespaces declared in C# files, even if they're empty:
+					foreach (var usingScope in projectContent.Files.OfType<CSharpUnresolvedFile>().SelectMany(f => f.UsingScopes)) {
+						GetOrAddNamespace(dict, usingScope.NamespaceName);
+					}
+					foreach (var pair in GetTypes()) {
+						NS ns = GetOrAddNamespace(dict, pair.Key.Namespace);
+						if (ns.types != null)
+							ns.types[pair.Key] = pair.Value;
+					}
+					return LazyInit.GetOrSet(ref this.rootNamespace, root);
+				}
+			}
+		}
+		
+		static NS GetOrAddNamespace(Dictionary<string, NS> dict, string fullName)
+		{
+			NS ns;
+			if (dict.TryGetValue(fullName, out ns))
+				return ns;
+			int pos = fullName.LastIndexOf('.');
+			NS parent;
+			string name;
+			if (pos < 0) {
+				parent = dict[string.Empty]; // root
+				name = fullName;
+			} else {
+				parent = GetOrAddNamespace(dict, fullName.Substring(0, pos));
+				name = fullName.Substring(pos + 1);
+			}
+			ns = new NS(parent, fullName, name);
+			parent.childNamespaces.Add(ns);
+			dict.Add(fullName, ns);
+			return ns;
+		}
+		
+		public ICompilation Compilation {
+			get { return compilation; }
+		}
+		
+		public bool InternalsVisibleTo(IAssembly assembly)
+		{
+			if (this == assembly)
+				return true;
+			foreach (string shortName in GetInternalsVisibleTo()) {
+				if (assembly.AssemblyName == shortName)
+					return true;
+			}
+			return false;
+		}
+		
+		volatile string[] internalsVisibleTo;
+		
+		string[] GetInternalsVisibleTo()
+		{
+			var result = this.internalsVisibleTo;
+			if (result != null) {
+				return result;
+			} else {
+				using (var busyLock = BusyManager.Enter(this)) {
+					Debug.Assert(busyLock.Success);
+					if (!busyLock.Success) {
+						return new string[0];
+					}
+					internalsVisibleTo = (
+						from attr in this.AssemblyAttributes
+						where attr.AttributeType.Name == "InternalsVisibleToAttribute"
+						&& attr.AttributeType.Namespace == "System.Runtime.CompilerServices"
+						&& attr.PositionalArguments.Count == 1
+						select GetShortName(attr.PositionalArguments.Single().ConstantValue as string)
+					).ToArray();
+				}
+				return internalsVisibleTo;
+			}
+		}
+		
+		static string GetShortName(string fullAssemblyName)
+		{
+			if (fullAssemblyName == null)
+				return null;
+			int pos = fullAssemblyName.IndexOf(',');
+			if (pos < 0)
+				return fullAssemblyName;
+			else
+				return fullAssemblyName.Substring(0, pos);
+		}
+		
+		Dictionary<TopLevelTypeName, ITypeDefinition> typeDict;
+		
+		Dictionary<TopLevelTypeName, ITypeDefinition> GetTypes()
+		{
+			var dict = LazyInit.VolatileRead(ref this.typeDict);
+			if (dict != null) {
+				return dict;
+			} else {
+				// Always use the ordinal comparer for the main dictionary so that partial classes
+				// get merged correctly.
+				// The compilation's comparer will be used for the per-namespace dictionaries.
+				var comparer = TopLevelTypeNameComparer.Ordinal;
+				dict = projectContent.TopLevelTypeDefinitions
+					.GroupBy(t => new TopLevelTypeName(t.Namespace, t.Name, t.TypeParameters.Count), comparer)
+					.ToDictionary(g => g.Key, g => CreateResolvedTypeDefinition(g.ToArray()), comparer);
+				return LazyInit.GetOrSet(ref this.typeDict, dict);
+			}
+		}
+		
+		ITypeDefinition CreateResolvedTypeDefinition(IUnresolvedTypeDefinition[] parts)
+		{
+			return new DefaultResolvedTypeDefinition(context, parts);
+		}
+		
+		public ITypeDefinition GetTypeDefinition(TopLevelTypeName topLevelTypeName)
+		{
+			ITypeDefinition def;
+			if (GetTypes().TryGetValue(topLevelTypeName, out def))
+				return def;
+			else
+				return null;
+		}
+		
+		public IEnumerable<ITypeDefinition> TopLevelTypeDefinitions {
+			get {
+				return GetTypes().Values;
+			}
+		}
+		
+		public override string ToString()
+		{
+			return "[CSharpAssembly " + this.AssemblyName + "]";
+		}
+		
+		sealed class NS : INamespace
+		{
+			readonly CSharpAssembly assembly;
+			readonly NS parentNamespace;
+			readonly string fullName;
+			readonly string name;
+			internal readonly List<NS> childNamespaces = new List<NS>();
+			internal readonly Dictionary<TopLevelTypeName, ITypeDefinition> types;
+			
+			public NS(CSharpAssembly assembly)
+			{
+				this.assembly = assembly;
+				this.fullName = string.Empty;
+				this.name = string.Empty;
+				// Our main dictionary for the CSharpAssembly is using an ordinal comparer.
+				// If the compilation's comparer isn't ordinal, we need to create a new dictionary with the compilation's comparer.
+				if (assembly.compilation.NameComparer != StringComparer.Ordinal) {
+					this.types = new Dictionary<TopLevelTypeName, ITypeDefinition>(new TopLevelTypeNameComparer(assembly.compilation.NameComparer));
+				}
+			}
+			
+			public NS(NS parentNamespace, string fullName, string name)
+			{
+				this.assembly = parentNamespace.assembly;
+				this.parentNamespace = parentNamespace;
+				this.fullName = fullName;
+				this.name = name;
+				if (parentNamespace.types != null)
+					this.types = new Dictionary<TopLevelTypeName, ITypeDefinition>(parentNamespace.types.Comparer);
+			}
+			
+			string INamespace.ExternAlias {
+				get { return null; }
+			}
+			
+			string INamespace.FullName {
+				get { return fullName; }
+			}
+			
+			public string Name {
+				get { return name; }
+			}
+			
+			SymbolKind ISymbol.SymbolKind {
+				get { return SymbolKind.Namespace; }
+			}
+			
+			INamespace INamespace.ParentNamespace {
+				get { return parentNamespace; }
+			}
+			
+			IEnumerable<INamespace> INamespace.ChildNamespaces {
+				get { return childNamespaces; }
+			}
+			
+			IEnumerable<ITypeDefinition> INamespace.Types {
+				get {
+					if (types != null)
+						return types.Values;
+					else
+						return (
+							from t in assembly.GetTypes()
+							where t.Key.Namespace == fullName
+							select t.Value
+						);
+				}
+			}
+			
+			ICompilation ICompilationProvider.Compilation {
+				get { return assembly.Compilation; }
+			}
+			
+			IEnumerable<IAssembly> INamespace.ContributingAssemblies {
+				get { return new [] { assembly }; }
+			}
+			
+			INamespace INamespace.GetChildNamespace(string name)
+			{
+				var nameComparer = assembly.compilation.NameComparer;
+				foreach (NS childNamespace in childNamespaces) {
+					if (nameComparer.Equals(name, childNamespace.name))
+						return childNamespace;
+				}
+				return null;
+			}
+			
+			ITypeDefinition INamespace.GetTypeDefinition(string name, int typeParameterCount)
+			{
+				var key = new TopLevelTypeName(fullName, name, typeParameterCount);
+				if (types != null) {
+					ITypeDefinition typeDef;
+					if (types.TryGetValue(key, out typeDef))
+						return typeDef;
+					else
+						return null;
+				} else {
+					return assembly.GetTypeDefinition(key);
+				}
+			}
+
+			public ISymbolReference ToReference()
+			{
+				return new NamespaceReference(new DefaultAssemblyReference(assembly.AssemblyName), fullName);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpAttribute.cs	(revision 11807)
@@ -0,0 +1,169 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	[Serializable]
+	public sealed class CSharpAttribute : IUnresolvedAttribute
+	{
+		ITypeReference attributeType;
+		DomRegion region;
+		IList<IConstantValue> positionalArguments;
+		IList<KeyValuePair<string, IConstantValue>> namedCtorArguments;
+		IList<KeyValuePair<string, IConstantValue>> namedArguments;
+		
+		public CSharpAttribute(ITypeReference attributeType, DomRegion region,
+		                       IList<IConstantValue> positionalArguments,
+		                       IList<KeyValuePair<string, IConstantValue>> namedCtorArguments,
+		                       IList<KeyValuePair<string, IConstantValue>> namedArguments)
+		{
+			if (attributeType == null)
+				throw new ArgumentNullException("attributeType");
+			this.attributeType = attributeType;
+			this.region = region;
+			this.positionalArguments = positionalArguments ?? EmptyList<IConstantValue>.Instance;
+			this.namedCtorArguments = namedCtorArguments ?? EmptyList<KeyValuePair<string, IConstantValue>>.Instance;
+			this.namedArguments = namedArguments ?? EmptyList<KeyValuePair<string, IConstantValue>>.Instance;
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+		}
+		
+		public ITypeReference AttributeType {
+			get { return attributeType; }
+		}
+		
+		public IAttribute CreateResolvedAttribute(ITypeResolveContext context)
+		{
+			return new CSharpResolvedAttribute((CSharpTypeResolveContext)context, this);
+		}
+		
+		sealed class CSharpResolvedAttribute : IAttribute
+		{
+			readonly CSharpTypeResolveContext context;
+			readonly CSharpAttribute unresolved;
+			readonly IType attributeType;
+			
+			IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
+			
+			public CSharpResolvedAttribute(CSharpTypeResolveContext context, CSharpAttribute unresolved)
+			{
+				this.context = context;
+				this.unresolved = unresolved;
+				// Pretty much any access to the attribute checks the type first, so
+				// we don't need to use lazy-loading for that.
+				this.attributeType = unresolved.AttributeType.Resolve(context);
+			}
+			
+			DomRegion IAttribute.Region {
+				get { return unresolved.Region; }
+			}
+			
+			IType IAttribute.AttributeType {
+				get { return attributeType; }
+			}
+			
+			ResolveResult ctorInvocation;
+			
+			InvocationResolveResult GetCtorInvocation()
+			{
+				ResolveResult rr = LazyInit.VolatileRead(ref this.ctorInvocation);
+				if (rr != null) {
+					return rr as InvocationResolveResult;
+				} else {
+					CSharpResolver resolver = new CSharpResolver(context);
+					int totalArgumentCount = unresolved.positionalArguments.Count + unresolved.namedCtorArguments.Count;
+					ResolveResult[] arguments = new ResolveResult[totalArgumentCount];
+					string[] argumentNames = new string[totalArgumentCount];
+					int i = 0;
+					while (i < unresolved.positionalArguments.Count) {
+						IConstantValue cv = unresolved.positionalArguments[i];
+						arguments[i] = cv.Resolve(context);
+						i++;
+					}
+					foreach (var pair in unresolved.namedCtorArguments) {
+						argumentNames[i] = pair.Key;
+						arguments[i] = pair.Value.Resolve(context);
+						i++;
+					}
+					rr = resolver.ResolveObjectCreation(attributeType, arguments, argumentNames);
+					return LazyInit.GetOrSet(ref this.ctorInvocation, rr) as InvocationResolveResult;
+				}
+			}
+			
+			IMethod IAttribute.Constructor {
+				get {
+					var invocation = GetCtorInvocation();
+					if (invocation != null)
+						return invocation.Member as IMethod;
+					else
+						return null;
+				}
+			}
+			
+			IList<ResolveResult> positionalArguments;
+			
+			IList<ResolveResult> IAttribute.PositionalArguments {
+				get {
+					var result = LazyInit.VolatileRead(ref this.positionalArguments);
+					if (result != null) {
+						return result;
+					} else {
+						var invocation = GetCtorInvocation();
+						if (invocation != null)
+							result = invocation.GetArgumentsForCall();
+						else
+							result = EmptyList<ResolveResult>.Instance;
+						return LazyInit.GetOrSet(ref this.positionalArguments, result);
+					}
+				}
+			}
+			
+			IList<KeyValuePair<IMember, ResolveResult>> IAttribute.NamedArguments {
+				get {
+					var namedArgs = LazyInit.VolatileRead(ref this.namedArguments);
+					if (namedArgs != null) {
+						return namedArgs;
+					} else {
+						namedArgs = new List<KeyValuePair<IMember, ResolveResult>>();
+						foreach (var pair in unresolved.namedArguments) {
+							IMember member = attributeType.GetMembers(m => (m.SymbolKind == SymbolKind.Field || m.SymbolKind == SymbolKind.Property) && m.Name == pair.Key).FirstOrDefault();
+							if (member != null) {
+								ResolveResult val = pair.Value.Resolve(context);
+								namedArgs.Add(new KeyValuePair<IMember, ResolveResult>(member, val));
+							}
+						}
+						return LazyInit.GetOrSet(ref this.namedArguments, namedArgs);
+					}
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpDocumentationComment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpDocumentationComment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpDocumentationComment.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// DocumentationComment with C# cref lookup.
+	/// </summary>
+	sealed class CSharpDocumentationComment : DocumentationComment
+	{
+		public CSharpDocumentationComment(ITextSource xmlDoc, ITypeResolveContext context) : base(xmlDoc, context)
+		{
+		}
+		
+		public override IEntity ResolveCref(string cref)
+		{
+			if (cref.Length > 2 && cref[1] == ':') {
+				// resolve ID string
+				return base.ResolveCref(cref);
+			}
+			var documentationReference = new CSharpParser().ParseDocumentationReference(cref);
+			var csharpContext = context as CSharpTypeResolveContext;
+			CSharpResolver resolver;
+			if (csharpContext != null) {
+				resolver = new CSharpResolver(csharpContext);
+			} else {
+				resolver = new CSharpResolver(context.Compilation);
+			}
+			var astResolver = new CSharpAstResolver(resolver, documentationReference);
+			var rr = astResolver.Resolve(documentationReference);
+			
+			MemberResolveResult mrr = rr as MemberResolveResult;
+			if (mrr != null)
+				return mrr.Member;
+			TypeResolveResult trr = rr as TypeResolveResult;
+			if (trr != null)
+				return trr.Type.GetDefinition();
+			return null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpTypeResolveContext.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpTypeResolveContext.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpTypeResolveContext.cs	(revision 11807)
@@ -0,0 +1,96 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	public sealed class CSharpTypeResolveContext : ITypeResolveContext
+	{
+		readonly IAssembly assembly;
+		readonly ResolvedUsingScope currentUsingScope;
+		readonly ITypeDefinition currentTypeDefinition;
+		readonly IMember currentMember;
+		readonly string[] methodTypeParameterNames;
+		
+		public CSharpTypeResolveContext(IAssembly assembly, ResolvedUsingScope usingScope = null, ITypeDefinition typeDefinition = null, IMember member = null)
+		{
+			if (assembly == null)
+				throw new ArgumentNullException("assembly");
+			this.assembly = assembly;
+			this.currentUsingScope = usingScope;
+			this.currentTypeDefinition = typeDefinition;
+			this.currentMember = member;
+		}
+		
+		private CSharpTypeResolveContext(IAssembly assembly, ResolvedUsingScope usingScope, ITypeDefinition typeDefinition, IMember member, string[] methodTypeParameterNames)
+		{
+			this.assembly = assembly;
+			this.currentUsingScope = usingScope;
+			this.currentTypeDefinition = typeDefinition;
+			this.currentMember = member;
+			this.methodTypeParameterNames = methodTypeParameterNames;
+		}
+		
+		public ResolvedUsingScope CurrentUsingScope {
+			get { return currentUsingScope; }
+		}
+		
+		public ICompilation Compilation {
+			get { return assembly.Compilation; }
+		}
+		
+		public IAssembly CurrentAssembly {
+			get { return assembly; }
+		}
+		
+		public ITypeDefinition CurrentTypeDefinition {
+			get { return currentTypeDefinition; }
+		}
+		
+		public IMember CurrentMember {
+			get { return currentMember; }
+		}
+		
+		public CSharpTypeResolveContext WithCurrentTypeDefinition(ITypeDefinition typeDefinition)
+		{
+			return new CSharpTypeResolveContext(assembly, currentUsingScope, typeDefinition, currentMember, methodTypeParameterNames);
+		}
+		
+		ITypeResolveContext ITypeResolveContext.WithCurrentTypeDefinition(ITypeDefinition typeDefinition)
+		{
+			return WithCurrentTypeDefinition(typeDefinition);
+		}
+		
+		public CSharpTypeResolveContext WithCurrentMember(IMember member)
+		{
+			return new CSharpTypeResolveContext(assembly, currentUsingScope, currentTypeDefinition, member, methodTypeParameterNames);
+		}
+		
+		ITypeResolveContext ITypeResolveContext.WithCurrentMember(IMember member)
+		{
+			return WithCurrentMember(member);
+		}
+		
+		public CSharpTypeResolveContext WithUsingScope(ResolvedUsingScope usingScope)
+		{
+			return new CSharpTypeResolveContext(assembly, usingScope, currentTypeDefinition, currentMember, methodTypeParameterNames);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpUnresolvedFile.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpUnresolvedFile.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpUnresolvedFile.cs	(revision 11807)
@@ -0,0 +1,213 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+using System.Linq;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Represents a file that was parsed and converted for the type system.
+	/// </summary>
+	[Serializable, FastSerializerVersion(TypeSystemConvertVisitor.version)]
+	public class CSharpUnresolvedFile : AbstractFreezable, IUnresolvedFile, IUnresolvedDocumentationProvider
+	{
+		// The 'FastSerializerVersion' attribute on CSharpUnresolvedFile must be incremented when fixing 
+		// bugs in the TypeSystemConvertVisitor
+		
+		string fileName = string.Empty;
+		readonly UsingScope rootUsingScope = new UsingScope();
+		IList<IUnresolvedTypeDefinition> topLevelTypeDefinitions = new List<IUnresolvedTypeDefinition>();
+		IList<IUnresolvedAttribute> assemblyAttributes = new List<IUnresolvedAttribute>();
+		IList<IUnresolvedAttribute> moduleAttributes = new List<IUnresolvedAttribute>();
+		IList<UsingScope> usingScopes = new List<UsingScope>();
+		IList<Error> errors = new List<Error> ();
+		Dictionary<IUnresolvedEntity, string> documentation;
+		
+		protected override void FreezeInternal()
+		{
+			base.FreezeInternal();
+			rootUsingScope.Freeze();
+			topLevelTypeDefinitions = FreezableHelper.FreezeListAndElements(topLevelTypeDefinitions);
+			assemblyAttributes = FreezableHelper.FreezeListAndElements(assemblyAttributes);
+			moduleAttributes = FreezableHelper.FreezeListAndElements(moduleAttributes);
+			usingScopes = FreezableHelper.FreezeListAndElements(usingScopes);
+		}
+		
+		public string FileName {
+			get { return fileName; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				fileName = value ?? string.Empty;
+			}
+		}
+		
+		DateTime? lastWriteTime;
+		
+		public DateTime? LastWriteTime {
+			get { return lastWriteTime; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				lastWriteTime = value;
+			}
+		}
+		
+		public UsingScope RootUsingScope {
+			get { return rootUsingScope; }
+		}
+		
+		public IList<Error> Errors {
+			get { return errors; }
+			internal set { errors = (List<Error>)value; }
+		}
+		
+		public IList<UsingScope> UsingScopes {
+			get { return usingScopes; }
+		}
+		
+		public IList<IUnresolvedTypeDefinition> TopLevelTypeDefinitions {
+			get { return topLevelTypeDefinitions; }
+		}
+		
+		public IList<IUnresolvedAttribute> AssemblyAttributes {
+			get { return assemblyAttributes; }
+		}
+		
+		public IList<IUnresolvedAttribute> ModuleAttributes {
+			get { return moduleAttributes; }
+		}
+		
+		public void AddDocumentation(IUnresolvedEntity entity, string xmlDocumentation)
+		{
+			FreezableHelper.ThrowIfFrozen(this);
+			if (documentation == null)
+				documentation = new Dictionary<IUnresolvedEntity, string>();
+			documentation.Add(entity, xmlDocumentation);
+		}
+		
+		public UsingScope GetUsingScope(TextLocation location)
+		{
+			foreach (UsingScope scope in usingScopes) {
+				if (scope.Region.IsInside(location.Line, location.Column))
+					return scope;
+			}
+			return rootUsingScope;
+		}
+		
+		public IUnresolvedTypeDefinition GetTopLevelTypeDefinition(TextLocation location)
+		{
+			return FindEntity(topLevelTypeDefinitions, location);
+		}
+		
+		public IUnresolvedTypeDefinition GetInnermostTypeDefinition(TextLocation location)
+		{
+			IUnresolvedTypeDefinition parent = null;
+			IUnresolvedTypeDefinition type = GetTopLevelTypeDefinition(location);
+			while (type != null) {
+				parent = type;
+				type = FindEntity(parent.NestedTypes, location);
+			}
+			return parent;
+		}
+		
+		public IUnresolvedMember GetMember(TextLocation location)
+		{
+			IUnresolvedTypeDefinition type = GetInnermostTypeDefinition(location);
+			if (type == null)
+				return null;
+			return FindEntity(type.Members, location);
+		}
+		
+		static T FindEntity<T>(IList<T> list, TextLocation location) where T : class, IUnresolvedEntity
+		{
+			// This could be improved using a binary search
+			foreach (T entity in list) {
+				if (entity.Region.IsInside(location.Line, location.Column))
+					return entity;
+			}
+			return null;
+		}
+		
+		public CSharpTypeResolveContext GetTypeResolveContext(ICompilation compilation, TextLocation loc)
+		{
+			var rctx = new CSharpTypeResolveContext (compilation.MainAssembly);
+			rctx = rctx.WithUsingScope (GetUsingScope (loc).Resolve (compilation));
+			var curDef = GetInnermostTypeDefinition (loc);
+			if (curDef != null) {
+				var resolvedDef = curDef.Resolve (rctx).GetDefinition ();
+				if (resolvedDef == null)
+					return rctx;
+				rctx = rctx.WithCurrentTypeDefinition (resolvedDef);
+				
+				var curMember = resolvedDef.Members.FirstOrDefault (m => m.Region.FileName == FileName && m.Region.Begin <= loc && loc < m.BodyRegion.End);
+				if (curMember != null)
+					rctx = rctx.WithCurrentMember (curMember);
+			}
+			
+			return rctx;
+		}
+		
+		public ICSharpCode.NRefactory.CSharp.Resolver.CSharpResolver GetResolver (ICompilation compilation, TextLocation loc)
+		{
+			return new ICSharpCode.NRefactory.CSharp.Resolver.CSharpResolver (GetTypeResolveContext (compilation, loc));
+		}
+		
+		public string GetDocumentation(IUnresolvedEntity entity)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			if (documentation == null)
+				return null;
+			string xmlDoc;
+			if (documentation.TryGetValue(entity, out xmlDoc))
+				return xmlDoc;
+			else
+				return null;
+		}
+		
+		public DocumentationComment GetDocumentation(IUnresolvedEntity entity, IEntity resolvedEntity)
+		{
+			if (entity == null)
+				throw new ArgumentNullException("entity");
+			if (resolvedEntity == null)
+				throw new ArgumentNullException("resolvedEntity");
+			string xmlDoc = GetDocumentation(entity);
+			if (xmlDoc == null)
+				return null;
+			var unresolvedTypeDef = entity as IUnresolvedTypeDefinition ?? entity.DeclaringTypeDefinition;
+			var resolvedTypeDef = resolvedEntity as ITypeDefinition ?? resolvedEntity.DeclaringTypeDefinition;
+			if (unresolvedTypeDef != null && resolvedTypeDef != null) {
+				// Strictly speaking, we would have to pass the parent context into CreateResolveContext,
+				// then transform the result using WithTypeDefinition().
+				// However, we can simplify this here because we know this is a C# type definition.
+				var context = unresolvedTypeDef.CreateResolveContext(new SimpleTypeResolveContext(resolvedTypeDef));
+				if (resolvedEntity is IMember)
+					context = context.WithCurrentMember((IMember)resolvedEntity);
+				return new CSharpDocumentationComment(new StringTextSource(xmlDoc), context);
+			} else {
+				return new DocumentationComment(new StringTextSource(xmlDoc), new SimpleTypeResolveContext(resolvedEntity));
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpUnresolvedTypeDefinition.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpUnresolvedTypeDefinition.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/CSharpUnresolvedTypeDefinition.cs	(revision 11807)
@@ -0,0 +1,50 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	[Serializable, FastSerializerVersion(TypeSystemConvertVisitor.version)]
+	public class CSharpUnresolvedTypeDefinition : DefaultUnresolvedTypeDefinition
+	{
+		readonly UsingScope usingScope;
+		
+		public CSharpUnresolvedTypeDefinition(UsingScope usingScope, string name)
+			: base(usingScope.NamespaceName, name)
+		{
+			this.usingScope = usingScope;
+			this.AddDefaultConstructorIfRequired = true;
+		}
+		
+		public CSharpUnresolvedTypeDefinition(CSharpUnresolvedTypeDefinition declaringTypeDefinition, string name)
+			: base(declaringTypeDefinition, name)
+		{
+			this.usingScope = declaringTypeDefinition.usingScope;
+			this.AddDefaultConstructorIfRequired = true;
+		}
+		
+		public override ITypeResolveContext CreateResolveContext(ITypeResolveContext parentContext)
+		{
+			return new CSharpTypeResolveContext(parentContext.CurrentAssembly, usingScope.Resolve(parentContext.Compilation), parentContext.CurrentTypeDefinition);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/ConstantValues.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/ConstantValues.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/ConstantValues.cs	(revision 11807)
@@ -0,0 +1,521 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.Analysis;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues
+{
+	// Contains representations for constant C# expressions.
+	// We use these instead of storing the full AST to reduce the memory usage.
+	
+	[Serializable]
+	public abstract class ConstantExpression : IConstantValue
+	{
+		public abstract ResolveResult Resolve(CSharpResolver resolver);
+		
+		public ResolveResult Resolve(ITypeResolveContext context)
+		{
+			var csContext = (CSharpTypeResolveContext)context;
+			if (context.CurrentAssembly != context.Compilation.MainAssembly) {
+				// The constant needs to be resolved in a different compilation.
+				IProjectContent pc = context.CurrentAssembly as IProjectContent;
+				if (pc != null) {
+					ICompilation nestedCompilation = context.Compilation.SolutionSnapshot.GetCompilation(pc);
+					if (nestedCompilation != null) {
+						var nestedContext = MapToNestedCompilation(csContext, nestedCompilation);
+						ResolveResult rr = Resolve(new CSharpResolver(nestedContext));
+						return MapToNewContext(rr, context);
+					}
+				}
+			}
+			// Resolve in current context.
+			return Resolve(new CSharpResolver(csContext));
+		}
+		
+		CSharpTypeResolveContext MapToNestedCompilation(CSharpTypeResolveContext context, ICompilation nestedCompilation)
+		{
+			var nestedContext = new CSharpTypeResolveContext(nestedCompilation.MainAssembly);
+			if (context.CurrentUsingScope != null) {
+				nestedContext = nestedContext.WithUsingScope(context.CurrentUsingScope.UnresolvedUsingScope.Resolve(nestedCompilation));
+			}
+			if (context.CurrentTypeDefinition != null) {
+				nestedContext = nestedContext.WithCurrentTypeDefinition(nestedCompilation.Import(context.CurrentTypeDefinition));
+			}
+			return nestedContext;
+		}
+		
+		static ResolveResult MapToNewContext(ResolveResult rr, ITypeResolveContext newContext)
+		{
+			if (rr is TypeOfResolveResult) {
+				return new TypeOfResolveResult(
+					rr.Type.ToTypeReference().Resolve(newContext),
+					((TypeOfResolveResult)rr).ReferencedType.ToTypeReference().Resolve(newContext));
+			} else if (rr is ArrayCreateResolveResult) {
+				ArrayCreateResolveResult acrr = (ArrayCreateResolveResult)rr;
+				return new ArrayCreateResolveResult(
+					acrr.Type.ToTypeReference().Resolve(newContext),
+					MapToNewContext(acrr.SizeArguments, newContext),
+					MapToNewContext(acrr.InitializerElements, newContext));
+			} else if (rr.IsCompileTimeConstant) {
+				return new ConstantResolveResult(
+					rr.Type.ToTypeReference().Resolve(newContext),
+					rr.ConstantValue
+				);
+			} else {
+				return new ErrorResolveResult(rr.Type.ToTypeReference().Resolve(newContext));
+			}
+		}
+		
+		static ResolveResult[] MapToNewContext(IList<ResolveResult> input, ITypeResolveContext newContext)
+		{
+			if (input == null)
+				return null;
+			ResolveResult[] output = new ResolveResult[input.Count];
+			for (int i = 0; i < output.Length; i++) {
+				output[i] = MapToNewContext(input[i], newContext);
+			}
+			return output;
+		}
+	}
+	
+	/// <summary>
+	/// Used for constants that could not be converted to IConstantValue.
+	/// </summary>
+	[Serializable]
+	public sealed class ErrorConstantValue : IConstantValue
+	{
+		readonly ITypeReference type;
+		
+		public ErrorConstantValue(ITypeReference type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			this.type = type;
+		}
+		
+		public ResolveResult Resolve(ITypeResolveContext context)
+		{
+			return new ErrorResolveResult(type.Resolve(context));
+		}
+	}
+	
+	/// <summary>
+	/// Increments an integer <see cref="IConstantValue"/> by a fixed amount without changing the type.
+	/// </summary>
+	[Serializable]
+	public sealed class IncrementConstantValue : IConstantValue, ISupportsInterning
+	{
+		readonly IConstantValue baseValue;
+		readonly int incrementAmount;
+		
+		public IncrementConstantValue(IConstantValue baseValue, int incrementAmount = 1)
+		{
+			if (baseValue == null)
+				throw new ArgumentNullException("baseValue");
+			IncrementConstantValue icv = baseValue as IncrementConstantValue;
+			if (icv != null) {
+				this.baseValue = icv.baseValue;
+				this.incrementAmount = icv.incrementAmount + incrementAmount;
+			} else {
+				this.baseValue = baseValue;
+				this.incrementAmount = incrementAmount;
+			}
+		}
+		
+		public ResolveResult Resolve(ITypeResolveContext context)
+		{
+			ResolveResult rr = baseValue.Resolve(context);
+			if (rr.IsCompileTimeConstant && rr.ConstantValue != null) {
+				object val = rr.ConstantValue;
+				TypeCode typeCode = Type.GetTypeCode(val.GetType());
+				if (typeCode >= TypeCode.SByte && typeCode <= TypeCode.UInt64) {
+					long intVal = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, val, false);
+					object newVal = CSharpPrimitiveCast.Cast(typeCode, unchecked(intVal + incrementAmount), false);
+					return new ConstantResolveResult(rr.Type, newVal);
+				}
+			}
+			return new ErrorResolveResult(rr.Type);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				return baseValue.GetHashCode() * 33 ^ incrementAmount;
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			IncrementConstantValue o = other as IncrementConstantValue;
+			return o != null && baseValue == o.baseValue && incrementAmount == o.incrementAmount;
+		}
+	}
+	
+	/// <summary>
+	/// C#'s equivalent to the SimpleConstantValue.
+	/// </summary>
+	[Serializable]
+	public sealed class PrimitiveConstantExpression : ConstantExpression, ISupportsInterning
+	{
+		readonly ITypeReference type;
+		readonly object value;
+		
+		public ITypeReference Type {
+			get { return type; }
+		}
+		
+		public object Value {
+			get { return value; }
+		}
+		
+		public PrimitiveConstantExpression(ITypeReference type, object value)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			this.type = type;
+			this.value = value;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return new ConstantResolveResult(type.Resolve(resolver.CurrentTypeResolveContext), value);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return type.GetHashCode() ^ (value != null ? value.GetHashCode() : 0);
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			PrimitiveConstantExpression scv = other as PrimitiveConstantExpression;
+			return scv != null && type == scv.type && value == scv.value;
+		}
+	}
+	
+	[Serializable]
+	public sealed class TypeOfConstantExpression : ConstantExpression
+	{
+		readonly ITypeReference type;
+		
+		public ITypeReference Type {
+			get { return type; }
+		}
+		
+		public TypeOfConstantExpression(ITypeReference type)
+		{
+			this.type = type;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveTypeOf(type.Resolve(resolver.CurrentTypeResolveContext));
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantCast : ConstantExpression, ISupportsInterning
+	{
+		readonly ITypeReference targetType;
+		readonly ConstantExpression expression;
+		readonly bool allowNullableConstants;
+		
+		public ConstantCast(ITypeReference targetType, ConstantExpression expression, bool allowNullableConstants)
+		{
+			if (targetType == null)
+				throw new ArgumentNullException("targetType");
+			if (expression == null)
+				throw new ArgumentNullException("expression");
+			this.targetType = targetType;
+			this.expression = expression;
+			this.allowNullableConstants = allowNullableConstants;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			var type = targetType.Resolve(resolver.CurrentTypeResolveContext);
+			var resolveResult = expression.Resolve(resolver);
+			if (allowNullableConstants && NullableType.IsNullable(type)) {
+				resolveResult = resolver.ResolveCast(NullableType.GetUnderlyingType(type), resolveResult);
+				if (resolveResult.IsCompileTimeConstant)
+					return new ConstantResolveResult(type, resolveResult.ConstantValue);
+			}
+			return resolver.ResolveCast(type, resolveResult);
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			unchecked {
+				return targetType.GetHashCode() + expression.GetHashCode() * 1018829;
+			}
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			ConstantCast cast = other as ConstantCast;
+			return cast != null
+				&& this.targetType == cast.targetType && this.expression == cast.expression && this.allowNullableConstants == cast.allowNullableConstants;
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantIdentifierReference : ConstantExpression
+	{
+		readonly string identifier;
+		readonly IList<ITypeReference> typeArguments;
+		
+		public ConstantIdentifierReference(string identifier, IList<ITypeReference> typeArguments = null)
+		{
+			if (identifier == null)
+				throw new ArgumentNullException("identifier");
+			this.identifier = identifier;
+			this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveSimpleName(identifier, typeArguments.Resolve(resolver.CurrentTypeResolveContext));
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantMemberReference : ConstantExpression
+	{
+		readonly ITypeReference targetType;
+		readonly ConstantExpression targetExpression;
+		readonly string memberName;
+		readonly IList<ITypeReference> typeArguments;
+		
+		public ConstantMemberReference(ITypeReference targetType, string memberName, IList<ITypeReference> typeArguments = null)
+		{
+			if (targetType == null)
+				throw new ArgumentNullException("targetType");
+			if (memberName == null)
+				throw new ArgumentNullException("memberName");
+			this.targetType = targetType;
+			this.memberName = memberName;
+			this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
+		}
+		
+		public ConstantMemberReference(ConstantExpression targetExpression, string memberName, IList<ITypeReference> typeArguments = null)
+		{
+			if (targetExpression == null)
+				throw new ArgumentNullException("targetExpression");
+			if (memberName == null)
+				throw new ArgumentNullException("memberName");
+			this.targetExpression = targetExpression;
+			this.memberName = memberName;
+			this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			ResolveResult rr;
+			if (targetType != null)
+				rr = new TypeResolveResult(targetType.Resolve(resolver.CurrentTypeResolveContext));
+			else
+				rr = targetExpression.Resolve(resolver);
+			return resolver.ResolveMemberAccess(rr, memberName, typeArguments.Resolve(resolver.CurrentTypeResolveContext));
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantCheckedExpression : ConstantExpression
+	{
+		readonly bool checkForOverflow;
+		readonly ConstantExpression expression;
+		
+		public ConstantCheckedExpression(bool checkForOverflow, ConstantExpression expression)
+		{
+			if (expression == null)
+				throw new ArgumentNullException("expression");
+			this.checkForOverflow = checkForOverflow;
+			this.expression = expression;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return expression.Resolve(resolver.WithCheckForOverflow(checkForOverflow));
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantDefaultValue : ConstantExpression, ISupportsInterning
+	{
+		readonly ITypeReference type;
+		
+		public ConstantDefaultValue(ITypeReference type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			this.type = type;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveDefaultValue(type.Resolve(resolver.CurrentTypeResolveContext));
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			return type.GetHashCode();
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			ConstantDefaultValue o = other as ConstantDefaultValue;
+			return o != null && this.type == o.type;
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantUnaryOperator : ConstantExpression
+	{
+		readonly UnaryOperatorType operatorType;
+		readonly ConstantExpression expression;
+		
+		public ConstantUnaryOperator(UnaryOperatorType operatorType, ConstantExpression expression)
+		{
+			if (expression == null)
+				throw new ArgumentNullException("expression");
+			this.operatorType = operatorType;
+			this.expression = expression;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveUnaryOperator(operatorType, expression.Resolve(resolver));
+		}
+	}
+
+	[Serializable]
+	public sealed class ConstantBinaryOperator : ConstantExpression
+	{
+		readonly ConstantExpression left;
+		readonly BinaryOperatorType operatorType;
+		readonly ConstantExpression right;
+		
+		public ConstantBinaryOperator(ConstantExpression left, BinaryOperatorType operatorType, ConstantExpression right)
+		{
+			if (left == null)
+				throw new ArgumentNullException("left");
+			if (right == null)
+				throw new ArgumentNullException("right");
+			this.left = left;
+			this.operatorType = operatorType;
+			this.right = right;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			ResolveResult lhs = left.Resolve(resolver);
+			ResolveResult rhs = right.Resolve(resolver);
+			return resolver.ResolveBinaryOperator(operatorType, lhs, rhs);
+		}
+	}
+	
+	[Serializable]
+	public sealed class ConstantConditionalOperator : ConstantExpression
+	{
+		readonly ConstantExpression condition, trueExpr, falseExpr;
+		
+		public ConstantConditionalOperator(ConstantExpression condition, ConstantExpression trueExpr, ConstantExpression falseExpr)
+		{
+			if (condition == null)
+				throw new ArgumentNullException("condition");
+			if (trueExpr == null)
+				throw new ArgumentNullException("trueExpr");
+			if (falseExpr == null)
+				throw new ArgumentNullException("falseExpr");
+			this.condition = condition;
+			this.trueExpr = trueExpr;
+			this.falseExpr = falseExpr;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveConditional(
+				condition.Resolve(resolver),
+				trueExpr.Resolve(resolver),
+				falseExpr.Resolve(resolver)
+			);
+		}
+	}
+	
+	/// <summary>
+	/// Represents an array creation (as used within an attribute argument)
+	/// </summary>
+	[Serializable]
+	public sealed class ConstantArrayCreation : ConstantExpression
+	{
+		// type may be null when the element is being inferred
+		readonly ITypeReference elementType;
+		readonly IList<ConstantExpression> arrayElements;
+		
+		public ConstantArrayCreation(ITypeReference type, IList<ConstantExpression> arrayElements)
+		{
+			if (arrayElements == null)
+				throw new ArgumentNullException("arrayElements");
+			this.elementType = type;
+			this.arrayElements = arrayElements;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			ResolveResult[] elements = new ResolveResult[arrayElements.Count];
+			for (int i = 0; i < elements.Length; i++) {
+				elements[i] = arrayElements[i].Resolve(resolver);
+			}
+			int[] sizeArguments = { elements.Length };
+			if (elementType != null) {
+				return resolver.ResolveArrayCreation(elementType.Resolve(resolver.CurrentTypeResolveContext), sizeArguments, elements);
+			} else {
+				return resolver.ResolveArrayCreation(null, sizeArguments, elements);
+			}
+		}
+	}
+
+	/// <summary>
+	/// Used for sizeof() expressions in constants.
+	/// </summary>
+	[Serializable]
+	public sealed class SizeOfConstantValue : ConstantExpression
+	{
+		readonly ITypeReference type;
+		
+		public SizeOfConstantValue(ITypeReference type)
+		{
+			if (type == null)
+				throw new ArgumentNullException("type");
+			this.type = type;
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			return resolver.ResolveSizeOf(type.Resolve(resolver.CurrentTypeResolveContext));
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/MemberTypeOrNamespaceReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/MemberTypeOrNamespaceReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/MemberTypeOrNamespaceReference.cs	(revision 11807)
@@ -0,0 +1,121 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Reference to a qualified type or namespace name.
+	/// </summary>
+	[Serializable]
+	public sealed class MemberTypeOrNamespaceReference : TypeOrNamespaceReference, ISupportsInterning
+	{
+		readonly TypeOrNamespaceReference target;
+		readonly string identifier;
+		readonly IList<ITypeReference> typeArguments;
+		readonly NameLookupMode lookupMode;
+		
+		public MemberTypeOrNamespaceReference(TypeOrNamespaceReference target, string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
+		{
+			if (target == null)
+				throw new ArgumentNullException("target");
+			if (identifier == null)
+				throw new ArgumentNullException("identifier");
+			this.target = target;
+			this.identifier = identifier;
+			this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
+			this.lookupMode = lookupMode;
+		}
+		
+		public string Identifier {
+			get { return identifier; }
+		}
+		
+		public TypeOrNamespaceReference Target {
+			get { return target; }
+		}
+		
+		public IList<ITypeReference> TypeArguments {
+			get { return typeArguments; }
+		}
+		
+		public NameLookupMode LookupMode {
+			get { return lookupMode; }
+		}
+		
+		/// <summary>
+		/// Adds a suffix to the identifier.
+		/// Does not modify the existing type reference, but returns a new one.
+		/// </summary>
+		public MemberTypeOrNamespaceReference AddSuffix(string suffix)
+		{
+			return new MemberTypeOrNamespaceReference(target, identifier + suffix, typeArguments, lookupMode);
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			ResolveResult targetRR = target.Resolve(resolver);
+			if (targetRR.IsError)
+				return targetRR;
+			IList<IType> typeArgs = typeArguments.Resolve(resolver.CurrentTypeResolveContext);
+			return resolver.ResolveMemberAccess(targetRR, identifier, typeArgs, lookupMode);
+		}
+		
+		public override IType ResolveType(CSharpResolver resolver)
+		{
+			TypeResolveResult trr = Resolve(resolver) as TypeResolveResult;
+			return trr != null ? trr.Type : new UnknownType(null, identifier, typeArguments.Count);
+		}
+		
+		public override string ToString()
+		{
+			if (typeArguments.Count == 0)
+				return target.ToString() + "." + identifier;
+			else
+				return target.ToString() + "." + identifier + "<" + string.Join(",", typeArguments) + ">";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			int hashCode = 0;
+			unchecked {
+				hashCode += 1000000007 * target.GetHashCode();
+				hashCode += 1000000033 * identifier.GetHashCode();
+				hashCode += 1000000087 * typeArguments.GetHashCode();
+				hashCode += 1000000021 * (int)lookupMode;
+			}
+			return hashCode;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			MemberTypeOrNamespaceReference o = other as MemberTypeOrNamespaceReference;
+			return o != null && this.target == o.target
+				&& this.identifier == o.identifier && this.typeArguments == o.typeArguments
+				&& this.lookupMode == o.lookupMode;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/MethodTypeParameterWithInheritedConstraints.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/MethodTypeParameterWithInheritedConstraints.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/MethodTypeParameterWithInheritedConstraints.cs	(revision 11807)
@@ -0,0 +1,121 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	[Serializable]
+	public sealed class MethodTypeParameterWithInheritedConstraints : DefaultUnresolvedTypeParameter
+	{
+		public MethodTypeParameterWithInheritedConstraints(int index, string name)
+			: base(SymbolKind.Method, index, name)
+		{
+		}
+		
+		static ITypeParameter ResolveBaseTypeParameter(IMethod parentMethod, int index)
+		{
+			IMethod baseMethod = null;
+			if (parentMethod.IsOverride) {
+				foreach (IMethod m in InheritanceHelper.GetBaseMembers(parentMethod, false).OfType<IMethod>()) {
+					if (!m.IsOverride) {
+						baseMethod = m;
+						break;
+					}
+				}
+			} else if (parentMethod.IsExplicitInterfaceImplementation && parentMethod.ImplementedInterfaceMembers.Count == 1) {
+				baseMethod = parentMethod.ImplementedInterfaceMembers[0] as IMethod;
+			}
+			if (baseMethod != null && index < baseMethod.TypeParameters.Count)
+				return baseMethod.TypeParameters[index];
+			else
+				return null;
+		}
+		
+		public override ITypeParameter CreateResolvedTypeParameter(ITypeResolveContext context)
+		{
+			if (context.CurrentMember is IMethod) {
+				return new ResolvedMethodTypeParameterWithInheritedConstraints(this, context);
+			} else {
+				return base.CreateResolvedTypeParameter(context);
+			}
+		}
+		
+		sealed class ResolvedMethodTypeParameterWithInheritedConstraints : AbstractTypeParameter
+		{
+			volatile ITypeParameter baseTypeParameter;
+			
+			public ResolvedMethodTypeParameterWithInheritedConstraints(MethodTypeParameterWithInheritedConstraints unresolved, ITypeResolveContext context)
+				: base(context.CurrentMember, unresolved.Index, unresolved.Name, unresolved.Variance,
+				       unresolved.Attributes.CreateResolvedAttributes(context), unresolved.Region)
+			{
+			}
+			
+			ITypeParameter GetBaseTypeParameter()
+			{
+				ITypeParameter baseTP = this.baseTypeParameter;
+				if (baseTP == null) {
+					// ResolveBaseTypeParameter() is idempotent, so this is thread-safe.
+					this.baseTypeParameter = baseTP = ResolveBaseTypeParameter((IMethod)this.Owner, this.Index);
+				}
+				return baseTP;
+			}
+			
+			public override bool HasValueTypeConstraint {
+				get {
+					ITypeParameter baseTP = GetBaseTypeParameter();
+					return baseTP != null ? baseTP.HasValueTypeConstraint : false;
+				}
+			}
+			
+			public override bool HasReferenceTypeConstraint {
+				get {
+					ITypeParameter baseTP = GetBaseTypeParameter();
+					return baseTP != null ? baseTP.HasReferenceTypeConstraint : false;
+				}
+			}
+			
+			public override bool HasDefaultConstructorConstraint {
+				get {
+					ITypeParameter baseTP = GetBaseTypeParameter();
+					return baseTP != null ? baseTP.HasDefaultConstructorConstraint : false;
+				}
+			}
+			
+			public override IEnumerable<IType> DirectBaseTypes {
+				get {
+					ITypeParameter baseTP = GetBaseTypeParameter();
+					if (baseTP != null) {
+						// Substitute occurrences of the base method's type parameters in the constraints
+						// with the type parameters from the
+						IMethod owner = (IMethod)this.Owner;
+						var substitution = new TypeParameterSubstitution(null, new ProjectedList<ITypeParameter, IType>(owner.TypeParameters, t => t));
+						return baseTP.DirectBaseTypes.Select(t => t.AcceptVisitor(substitution));
+					} else {
+						return EmptyList<IType>.Instance;
+					}
+				}
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/ResolvedUsingScope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/ResolvedUsingScope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/ResolvedUsingScope.cs	(revision 11807)
@@ -0,0 +1,210 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Resolved version of using scope.
+	/// </summary>
+	public class ResolvedUsingScope
+	{
+		readonly CSharpTypeResolveContext parentContext;
+		readonly UsingScope usingScope;
+		
+		internal readonly ConcurrentDictionary<string, ResolveResult> ResolveCache = new ConcurrentDictionary<string, ResolveResult>();
+		internal List<List<IMethod>> AllExtensionMethods;
+		
+		public ResolvedUsingScope(CSharpTypeResolveContext context, UsingScope usingScope)
+		{
+			if (context == null)
+				throw new ArgumentNullException("context");
+			if (usingScope == null)
+				throw new ArgumentNullException("usingScope");
+			this.parentContext = context;
+			this.usingScope = usingScope;
+			if (usingScope.Parent != null) {
+				if (context.CurrentUsingScope == null)
+					throw new InvalidOperationException();
+			} else {
+				if (context.CurrentUsingScope != null)
+					throw new InvalidOperationException();
+			}
+		}
+		
+		public UsingScope UnresolvedUsingScope {
+			get { return usingScope; }
+		}
+		
+		INamespace @namespace;
+		
+		public INamespace Namespace {
+			get {
+				INamespace result = LazyInit.VolatileRead(ref this.@namespace);
+				if (result != null) {
+					return result;
+				} else {
+					if (parentContext.CurrentUsingScope != null) {
+						result = parentContext.CurrentUsingScope.Namespace.GetChildNamespace(usingScope.ShortNamespaceName);
+						if (result == null)
+							result = new DummyNamespace(parentContext.CurrentUsingScope.Namespace, usingScope.ShortNamespaceName);
+					} else {
+						result = parentContext.Compilation.RootNamespace;
+					}
+					Debug.Assert(result != null);
+					return LazyInit.GetOrSet(ref this.@namespace, result);
+				}
+			}
+		}
+		
+		public ResolvedUsingScope Parent {
+			get { return parentContext.CurrentUsingScope; }
+		}
+		
+		IList<INamespace> usings;
+		
+		public IList<INamespace> Usings {
+			get {
+				var result = LazyInit.VolatileRead(ref this.usings);
+				if (result != null) {
+					return result;
+				} else {
+					result = new List<INamespace>();
+					CSharpResolver resolver = new CSharpResolver(parentContext.WithUsingScope(this));
+					foreach (var u in usingScope.Usings) {
+						INamespace ns = u.ResolveNamespace(resolver);
+						if (ns != null && !result.Contains(ns))
+							result.Add(ns);
+					}
+					return LazyInit.GetOrSet(ref this.usings, new ReadOnlyCollection<INamespace>(result));
+				}
+			}
+		}
+		
+		IList<KeyValuePair<string, ResolveResult>> usingAliases;
+		
+		public IList<KeyValuePair<string, ResolveResult>> UsingAliases {
+			get {
+				var result = LazyInit.VolatileRead(ref this.usingAliases);
+				if (result != null) {
+					return result;
+				} else {
+					CSharpResolver resolver = new CSharpResolver(parentContext.WithUsingScope(this));
+					result = new KeyValuePair<string, ResolveResult>[usingScope.UsingAliases.Count];
+					for (int i = 0; i < result.Count; i++) {
+						var rr = usingScope.UsingAliases[i].Value.Resolve(resolver);
+						if (rr is TypeResolveResult) {
+							rr = new AliasTypeResolveResult (usingScope.UsingAliases[i].Key, (TypeResolveResult)rr);
+						} else if (rr is NamespaceResolveResult) {
+							rr = new AliasNamespaceResolveResult (usingScope.UsingAliases[i].Key, (NamespaceResolveResult)rr);
+						}
+						result[i] = new KeyValuePair<string, ResolveResult>(
+							usingScope.UsingAliases[i].Key,
+							rr
+						);
+					}
+					return LazyInit.GetOrSet(ref this.usingAliases, result);
+				}
+			}
+		}
+		
+		public IList<string> ExternAliases {
+			get { return usingScope.ExternAliases; }
+		}
+		
+		/// <summary>
+		/// Gets whether this using scope has an alias (either using or extern)
+		/// with the specified name.
+		/// </summary>
+		public bool HasAlias(string identifier)
+		{
+			return usingScope.HasAlias(identifier);
+		}
+		
+		sealed class DummyNamespace : INamespace
+		{
+			readonly INamespace parentNamespace;
+			readonly string name;
+			
+			public DummyNamespace(INamespace parentNamespace, string name)
+			{
+				this.parentNamespace = parentNamespace;
+				this.name = name;
+			}
+			
+			public string ExternAlias { get; set; }
+			
+			string INamespace.FullName {
+				get { return NamespaceDeclaration.BuildQualifiedName(parentNamespace.FullName, name); }
+			}
+			
+			public string Name {
+				get { return name; }
+			}
+			
+			SymbolKind ISymbol.SymbolKind {
+				get { return SymbolKind.Namespace; }
+			}
+			
+			INamespace INamespace.ParentNamespace {
+				get { return parentNamespace; }
+			}
+			
+			IEnumerable<INamespace> INamespace.ChildNamespaces {
+				get { return EmptyList<INamespace>.Instance; }
+			}
+			
+			IEnumerable<ITypeDefinition> INamespace.Types {
+				get { return EmptyList<ITypeDefinition>.Instance; }
+			}
+			
+			IEnumerable<IAssembly> INamespace.ContributingAssemblies {
+				get { return EmptyList<IAssembly>.Instance; }
+			}
+			
+			ICompilation ICompilationProvider.Compilation {
+				get { return parentNamespace.Compilation; }
+			}
+			
+			INamespace INamespace.GetChildNamespace(string name)
+			{
+				return null;
+			}
+			
+			ITypeDefinition INamespace.GetTypeDefinition(string name, int typeParameterCount)
+			{
+				return null;
+			}
+
+			public ISymbolReference ToReference()
+			{
+				return new MergedNamespaceReference(ExternAlias, ((INamespace)this).FullName);
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/SimpleTypeOrNamespaceReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/SimpleTypeOrNamespaceReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/SimpleTypeOrNamespaceReference.cs	(revision 11807)
@@ -0,0 +1,109 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Represents a simple C# name. (a single non-qualified identifier with an optional list of type arguments)
+	/// </summary>
+	[Serializable]
+	public sealed class SimpleTypeOrNamespaceReference : TypeOrNamespaceReference, ISupportsInterning
+	{
+		readonly string identifier;
+		readonly IList<ITypeReference> typeArguments;
+		readonly NameLookupMode lookupMode;
+		
+		public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
+		{
+			if (identifier == null)
+				throw new ArgumentNullException("identifier");
+			this.identifier = identifier;
+			this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
+			this.lookupMode = lookupMode;
+		}
+		
+		public string Identifier {
+			get { return identifier; }
+		}
+		
+		public IList<ITypeReference> TypeArguments {
+			get { return typeArguments; }
+		}
+		
+		public NameLookupMode LookupMode {
+			get { return lookupMode; }
+		}
+		
+		/// <summary>
+		/// Adds a suffix to the identifier.
+		/// Does not modify the existing type reference, but returns a new one.
+		/// </summary>
+		public SimpleTypeOrNamespaceReference AddSuffix(string suffix)
+		{
+			return new SimpleTypeOrNamespaceReference(identifier + suffix, typeArguments, lookupMode);
+		}
+		
+		public override ResolveResult Resolve(CSharpResolver resolver)
+		{
+			var typeArgs = typeArguments.Resolve(resolver.CurrentTypeResolveContext);
+			return resolver.LookupSimpleNameOrTypeName(identifier, typeArgs, lookupMode);
+		}
+		
+		public override IType ResolveType(CSharpResolver resolver)
+		{
+			TypeResolveResult trr = Resolve(resolver) as TypeResolveResult;
+			return trr != null ? trr.Type : new UnknownType(null, identifier, typeArguments.Count);
+		}
+		
+		public override string ToString()
+		{
+			if (typeArguments.Count == 0)
+				return identifier;
+			else
+				return identifier + "<" + string.Join(",", typeArguments) + ">";
+		}
+		
+		int ISupportsInterning.GetHashCodeForInterning()
+		{
+			int hashCode = 0;
+			unchecked {
+				hashCode += 1000000021 * identifier.GetHashCode();
+				hashCode += 1000000033 * typeArguments.GetHashCode();
+				hashCode += 1000000087 * (int)lookupMode;
+			}
+			return hashCode;
+		}
+		
+		bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
+		{
+			SimpleTypeOrNamespaceReference o = other as SimpleTypeOrNamespaceReference;
+			return o != null && this.identifier == o.identifier
+				&& this.typeArguments == o.typeArguments && this.lookupMode == o.lookupMode;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/TypeOrNamespaceReference.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/TypeOrNamespaceReference.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/TypeOrNamespaceReference.cs	(revision 11807)
@@ -0,0 +1,80 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.CSharp.Resolver;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Represents a reference which could point to a type or namespace.
+	/// </summary>
+	[Serializable]
+	public abstract class TypeOrNamespaceReference : ITypeReference
+	{
+		/// <summary>
+		/// Resolves the reference and returns the ResolveResult.
+		/// </summary>
+		public abstract ResolveResult Resolve(CSharpResolver resolver);
+		
+		/// <summary>
+		/// Returns the type that is referenced; or an <c>UnknownType</c> if the type isn't found.
+		/// </summary>
+		public abstract IType ResolveType(CSharpResolver resolver);
+		
+		/// <summary>
+		/// Returns the namespace that is referenced; or null if no such namespace is found.
+		/// </summary>
+		public INamespace ResolveNamespace(CSharpResolver resolver)
+		{
+			NamespaceResolveResult nrr = Resolve(resolver) as NamespaceResolveResult;
+			return nrr != null ? nrr.Namespace : null;
+		}
+		
+		IType ITypeReference.Resolve(ITypeResolveContext context)
+		{
+			// Strictly speaking, we might have to resolve the type in a nested compilation, similar
+			// to what we're doing with ConstantExpression.
+			// However, in almost all cases this will work correctly - if the resulting type is only available in the
+			// nested compilation and not in this, we wouldn't be able to map it anyways.
+			var ctx = context as CSharpTypeResolveContext;
+			if (ctx == null) {
+				ctx = new CSharpTypeResolveContext(context.CurrentAssembly ?? context.Compilation.MainAssembly, null, context.CurrentTypeDefinition, context.CurrentMember);
+			}
+			return ResolveType(new CSharpResolver(ctx));
+			
+			// A potential issue might be this scenario:
+			
+			// Assembly 1:
+			//  class A { public class Nested {} }
+			
+			// Assembly 2: (references asm 1)
+			//  class B : A {}
+			
+			// Assembly 3: (references asm 1 and 2)
+			//  class C { public B.Nested Field; }
+			
+			// Assembly 4: (references asm 1 and 3, but not 2):
+			//  uses C.Field;
+			
+			// Here we would not be able to resolve 'B.Nested' in the compilation of assembly 4, as type B is missing there.
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/TypeSystemConvertVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/TypeSystemConvertVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/TypeSystemConvertVisitor.cs	(revision 11807)
@@ -0,0 +1,1333 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Text;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Produces type and member definitions from the DOM.
+	/// </summary>
+	public class TypeSystemConvertVisitor : DepthFirstAstVisitor<IUnresolvedEntity>
+	{
+		/// <summary>
+		/// Version of the C# type system loader.
+		/// Should be incremented when fixing bugs so that project contents cached on disk
+		/// (which might be incorrect due to the bug) are re-created.
+		/// </summary>
+		internal const int version = 2;
+		
+		readonly CSharpUnresolvedFile unresolvedFile;
+		UsingScope usingScope;
+		CSharpUnresolvedTypeDefinition currentTypeDefinition;
+		DefaultUnresolvedMethod currentMethod;
+		
+		InterningProvider interningProvider = new SimpleInterningProvider();
+		
+		/// <summary>
+		/// Gets/Sets the interning provider to use.
+		/// The default value is a new <see cref="SimpleInterningProvider"/> instance.
+		/// </summary>
+		public InterningProvider InterningProvider {
+			get { return interningProvider; }
+			set {
+				if (interningProvider == null)
+					throw new ArgumentNullException();
+				interningProvider = value;
+			}
+		}
+		
+		/// <summary>
+		/// Gets/Sets whether to ignore XML documentation.
+		/// The default value is false.
+		/// </summary>
+		public bool SkipXmlDocumentation { get; set; }
+		
+		/// <summary>
+		/// Creates a new TypeSystemConvertVisitor.
+		/// </summary>
+		/// <param name="fileName">The file name (used for DomRegions).</param>
+		public TypeSystemConvertVisitor(string fileName)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException("fileName");
+			this.unresolvedFile = new CSharpUnresolvedFile();
+			this.unresolvedFile.FileName = fileName;
+			this.usingScope = unresolvedFile.RootUsingScope;
+		}
+		
+		/// <summary>
+		/// Creates a new TypeSystemConvertVisitor and initializes it with a given context.
+		/// </summary>
+		/// <param name="unresolvedFile">The parsed file to which members should be added.</param>
+		/// <param name="currentUsingScope">The current using scope.</param>
+		/// <param name="currentTypeDefinition">The current type definition.</param>
+		public TypeSystemConvertVisitor(CSharpUnresolvedFile unresolvedFile, UsingScope currentUsingScope = null, CSharpUnresolvedTypeDefinition currentTypeDefinition = null)
+		{
+			if (unresolvedFile == null)
+				throw new ArgumentNullException("unresolvedFile");
+			this.unresolvedFile = unresolvedFile;
+			this.usingScope = currentUsingScope ?? unresolvedFile.RootUsingScope;
+			this.currentTypeDefinition = currentTypeDefinition;
+		}
+		
+		public CSharpUnresolvedFile UnresolvedFile {
+			get { return unresolvedFile; }
+		}
+		
+		DomRegion MakeRegion(TextLocation start, TextLocation end)
+		{
+			return new DomRegion(unresolvedFile.FileName, start.Line, start.Column, end.Line, end.Column);
+		}
+		
+		DomRegion MakeRegion(AstNode node)
+		{
+			if (node == null || node.IsNull)
+				return DomRegion.Empty;
+			else
+				return MakeRegion(GetStartLocationAfterAttributes(node), node.EndLocation);
+		}
+		
+		internal static TextLocation GetStartLocationAfterAttributes(AstNode node)
+		{
+			AstNode child = node.FirstChild;
+			// Skip attributes and comments between attributes for the purpose of
+			// getting a declaration's region.
+			while (child != null && (child is AttributeSection || child.NodeType == NodeType.Whitespace))
+				child = child.NextSibling;
+			return (child ?? node).StartLocation;
+		}
+		
+		DomRegion MakeBraceRegion(AstNode node)
+		{
+			if (node == null || node.IsNull)
+				return DomRegion.Empty;
+			else
+				return MakeRegion(node.GetChildByRole(Roles.LBrace).StartLocation,
+				                  node.GetChildByRole(Roles.RBrace).EndLocation);
+		}
+		
+		#region Compilation Unit
+		public override IUnresolvedEntity VisitSyntaxTree (SyntaxTree unit)
+		{
+			unresolvedFile.Errors = unit.Errors;
+			return base.VisitSyntaxTree (unit);
+		}
+		#endregion
+		
+		#region Using Declarations
+		public override IUnresolvedEntity VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration)
+		{
+			usingScope.ExternAliases.Add(externAliasDeclaration.Name);
+			return null;
+		}
+		
+		public override IUnresolvedEntity VisitUsingDeclaration(UsingDeclaration usingDeclaration)
+		{
+			var u = ConvertTypeReference(usingDeclaration.Import, NameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
+			if (u != null) {
+				usingScope.Usings.Add(u);
+			}
+			return null;
+		}
+		
+		public override IUnresolvedEntity VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration)
+		{
+			TypeOrNamespaceReference u = ConvertTypeReference(usingDeclaration.Import, NameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
+			if (u != null) {
+				usingScope.UsingAliases.Add(new KeyValuePair<string, TypeOrNamespaceReference>(usingDeclaration.Alias, u));
+			}
+			return null;
+		}
+		#endregion
+		
+		#region Namespace Declaration
+		public override IUnresolvedEntity VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
+		{
+			DomRegion region = MakeRegion(namespaceDeclaration);
+			UsingScope previousUsingScope = usingScope;
+			foreach (var ident in namespaceDeclaration.Identifiers) {
+				usingScope = new UsingScope(usingScope, ident);
+				usingScope.Region = region;
+			}
+			base.VisitNamespaceDeclaration(namespaceDeclaration);
+			unresolvedFile.UsingScopes.Add(usingScope); // add after visiting children so that nested scopes come first
+			usingScope = previousUsingScope;
+			return null;
+		}
+		#endregion
+		
+		#region Type Definitions
+		CSharpUnresolvedTypeDefinition CreateTypeDefinition(string name)
+		{
+			CSharpUnresolvedTypeDefinition newType;
+			if (currentTypeDefinition != null) {
+				newType = new CSharpUnresolvedTypeDefinition(currentTypeDefinition, name);
+				foreach (var typeParameter in currentTypeDefinition.TypeParameters)
+					newType.TypeParameters.Add(typeParameter);
+				currentTypeDefinition.NestedTypes.Add(newType);
+			} else {
+				newType = new CSharpUnresolvedTypeDefinition(usingScope, name);
+				unresolvedFile.TopLevelTypeDefinitions.Add(newType);
+			}
+			newType.UnresolvedFile = unresolvedFile;
+			newType.HasExtensionMethods = false; // gets set to true when an extension method is added
+			return newType;
+		}
+		
+		public override IUnresolvedEntity VisitTypeDeclaration(TypeDeclaration typeDeclaration)
+		{
+			var td = currentTypeDefinition = CreateTypeDefinition(typeDeclaration.Name);
+			td.Region = MakeRegion(typeDeclaration);
+			td.BodyRegion = MakeBraceRegion(typeDeclaration);
+			AddXmlDocumentation(td, typeDeclaration);
+			
+			ApplyModifiers(td, typeDeclaration.Modifiers);
+			switch (typeDeclaration.ClassType) {
+				case ClassType.Enum:
+					td.Kind = TypeKind.Enum;
+					break;
+				case ClassType.Interface:
+					td.Kind = TypeKind.Interface;
+					td.IsAbstract = true; // interfaces are implicitly abstract
+					break;
+				case ClassType.Struct:
+					td.Kind = TypeKind.Struct;
+					td.IsSealed = true; // enums/structs are implicitly sealed
+					break;
+			}
+			
+			ConvertAttributes(td.Attributes, typeDeclaration.Attributes);
+			
+			ConvertTypeParameters(td.TypeParameters, typeDeclaration.TypeParameters, typeDeclaration.Constraints, SymbolKind.TypeDefinition);
+			
+			foreach (AstType baseType in typeDeclaration.BaseTypes) {
+				td.BaseTypes.Add(ConvertTypeReference(baseType, NameLookupMode.BaseTypeReference));
+			}
+			
+			foreach (EntityDeclaration member in typeDeclaration.Members) {
+				member.AcceptVisitor(this);
+			}
+			
+			currentTypeDefinition = (CSharpUnresolvedTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
+			td.ApplyInterningProvider(interningProvider);
+			return td;
+		}
+		
+		public override IUnresolvedEntity VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
+		{
+			var td = currentTypeDefinition = CreateTypeDefinition(delegateDeclaration.Name);
+			td.Kind = TypeKind.Delegate;
+			td.Region = MakeRegion(delegateDeclaration);
+			td.BaseTypes.Add(KnownTypeReference.MulticastDelegate);
+			AddXmlDocumentation(td, delegateDeclaration);
+			
+			ApplyModifiers(td, delegateDeclaration.Modifiers);
+			td.IsSealed = true; // delegates are implicitly sealed
+			
+			ConvertTypeParameters(td.TypeParameters, delegateDeclaration.TypeParameters, delegateDeclaration.Constraints, SymbolKind.TypeDefinition);
+			
+			ITypeReference returnType = ConvertTypeReference(delegateDeclaration.ReturnType);
+			List<IUnresolvedParameter> parameters = new List<IUnresolvedParameter>();
+			ConvertParameters(parameters, delegateDeclaration.Parameters);
+			AddDefaultMethodsToDelegate(td, returnType, parameters);
+			
+			foreach (AttributeSection section in delegateDeclaration.Attributes) {
+				if (section.AttributeTarget == "return") {
+					List<IUnresolvedAttribute> returnTypeAttributes = new List<IUnresolvedAttribute>();
+					ConvertAttributes(returnTypeAttributes, section);
+					IUnresolvedMethod invokeMethod = (IUnresolvedMethod)td.Members.Single(m => m.Name == "Invoke");
+					IUnresolvedMethod endInvokeMethod = (IUnresolvedMethod)td.Members.Single(m => m.Name == "EndInvoke");
+					foreach (IUnresolvedAttribute attr in returnTypeAttributes) {
+						invokeMethod.ReturnTypeAttributes.Add(attr);
+						endInvokeMethod.ReturnTypeAttributes.Add(attr);
+					}
+				} else {
+					ConvertAttributes(td.Attributes, section);
+				}
+			}
+			
+			currentTypeDefinition = (CSharpUnresolvedTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
+			td.ApplyInterningProvider(interningProvider);
+			return td;
+		}
+		
+		static readonly IUnresolvedParameter delegateObjectParameter = MakeParameter(KnownTypeReference.Object, "object");
+		static readonly IUnresolvedParameter delegateIntPtrMethodParameter = MakeParameter(KnownTypeReference.IntPtr, "method");
+		static readonly IUnresolvedParameter delegateAsyncCallbackParameter = MakeParameter(typeof(AsyncCallback).ToTypeReference(), "callback");
+		static readonly IUnresolvedParameter delegateResultParameter = MakeParameter(typeof(IAsyncResult).ToTypeReference(), "result");
+		
+		static IUnresolvedParameter MakeParameter(ITypeReference type, string name)
+		{
+			DefaultUnresolvedParameter p = new DefaultUnresolvedParameter(type, name);
+			p.Freeze();
+			return p;
+		}
+		
+		/// <summary>
+		/// Adds the 'Invoke', 'BeginInvoke', 'EndInvoke' methods, and a constructor, to the <paramref name="delegateType"/>.
+		/// </summary>
+		public static void AddDefaultMethodsToDelegate(DefaultUnresolvedTypeDefinition delegateType, ITypeReference returnType, IEnumerable<IUnresolvedParameter> parameters)
+		{
+			if (delegateType == null)
+				throw new ArgumentNullException("delegateType");
+			if (returnType == null)
+				throw new ArgumentNullException("returnType");
+			if (parameters == null)
+				throw new ArgumentNullException("parameters");
+			
+			DomRegion region = delegateType.Region;
+			region = new DomRegion(region.FileName, region.BeginLine, region.BeginColumn); // remove end position
+			
+			DefaultUnresolvedMethod invoke = new DefaultUnresolvedMethod(delegateType, "Invoke");
+			invoke.Accessibility = Accessibility.Public;
+			invoke.IsSynthetic = true;
+			foreach (var p in parameters)
+				invoke.Parameters.Add(p);
+			invoke.ReturnType = returnType;
+			invoke.Region = region;
+			delegateType.Members.Add(invoke);
+			
+			DefaultUnresolvedMethod beginInvoke = new DefaultUnresolvedMethod(delegateType, "BeginInvoke");
+			beginInvoke.Accessibility = Accessibility.Public;
+			beginInvoke.IsSynthetic = true;
+			foreach (var p in parameters)
+				beginInvoke.Parameters.Add(p);
+			beginInvoke.Parameters.Add(delegateAsyncCallbackParameter);
+			beginInvoke.Parameters.Add(delegateObjectParameter);
+			beginInvoke.ReturnType = delegateResultParameter.Type;
+			beginInvoke.Region = region;
+			delegateType.Members.Add(beginInvoke);
+			
+			DefaultUnresolvedMethod endInvoke = new DefaultUnresolvedMethod(delegateType, "EndInvoke");
+			endInvoke.Accessibility = Accessibility.Public;
+			endInvoke.IsSynthetic = true;
+			endInvoke.Parameters.Add(delegateResultParameter);
+			endInvoke.ReturnType = invoke.ReturnType;
+			endInvoke.Region = region;
+			delegateType.Members.Add(endInvoke);
+			
+			DefaultUnresolvedMethod ctor = new DefaultUnresolvedMethod(delegateType, ".ctor");
+			ctor.SymbolKind = SymbolKind.Constructor;
+			ctor.Accessibility = Accessibility.Public;
+			ctor.IsSynthetic = true;
+			ctor.Parameters.Add(delegateObjectParameter);
+			ctor.Parameters.Add(delegateIntPtrMethodParameter);
+			ctor.ReturnType = delegateType;
+			ctor.Region = region;
+			delegateType.Members.Add(ctor);
+		}
+		#endregion
+		
+		#region Fields
+		public override IUnresolvedEntity VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
+		{
+			bool isSingleField = fieldDeclaration.Variables.Count == 1;
+			Modifiers modifiers = fieldDeclaration.Modifiers;
+			DefaultUnresolvedField field = null;
+			foreach (VariableInitializer vi in fieldDeclaration.Variables) {
+				field = new DefaultUnresolvedField(currentTypeDefinition, vi.Name);
+				
+				field.Region = isSingleField ? MakeRegion(fieldDeclaration) : MakeRegion(vi);
+				field.BodyRegion = MakeRegion(vi);
+				ConvertAttributes(field.Attributes, fieldDeclaration.Attributes);
+				AddXmlDocumentation(field, fieldDeclaration);
+				
+				ApplyModifiers(field, modifiers);
+				field.IsVolatile = (modifiers & Modifiers.Volatile) != 0;
+				field.IsReadOnly = (modifiers & Modifiers.Readonly) != 0;
+				
+				field.ReturnType = ConvertTypeReference(fieldDeclaration.ReturnType);
+				
+				if ((modifiers & Modifiers.Const) != 0) {
+					field.ConstantValue = ConvertConstantValue(field.ReturnType, vi.Initializer);
+					field.IsStatic = true;
+				}
+				
+				currentTypeDefinition.Members.Add(field);
+				field.ApplyInterningProvider(interningProvider);
+			}
+			return isSingleField ? field : null;
+		}
+		
+		public override IUnresolvedEntity VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
+		{
+			bool isSingleField = fixedFieldDeclaration.Variables.Count == 1;
+			Modifiers modifiers = fixedFieldDeclaration.Modifiers;
+			DefaultUnresolvedField field = null;
+			foreach (var vi in fixedFieldDeclaration.Variables) {
+				field = new DefaultUnresolvedField(currentTypeDefinition, vi.Name);
+
+				field.Region = isSingleField ? MakeRegion(fixedFieldDeclaration) : MakeRegion(vi);
+				field.BodyRegion = MakeRegion(vi);
+				ConvertAttributes(field.Attributes, fixedFieldDeclaration.Attributes);
+				AddXmlDocumentation(field, fixedFieldDeclaration);
+
+				ApplyModifiers(field, modifiers);
+
+				field.ReturnType = ConvertTypeReference(fixedFieldDeclaration.ReturnType);
+				field.IsFixed = true;
+				field.ConstantValue = ConvertConstantValue(field.ReturnType, vi.CountExpression);
+
+				currentTypeDefinition.Members.Add(field);
+				field.ApplyInterningProvider(interningProvider);
+			}
+			return isSingleField ? field : null;
+		}
+		
+		public override IUnresolvedEntity VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration)
+		{
+			DefaultUnresolvedField field = new DefaultUnresolvedField(currentTypeDefinition, enumMemberDeclaration.Name);
+			field.Region = field.BodyRegion = MakeRegion(enumMemberDeclaration);
+			ConvertAttributes(field.Attributes, enumMemberDeclaration.Attributes);
+			AddXmlDocumentation(field, enumMemberDeclaration);
+			
+			if (currentTypeDefinition.TypeParameters.Count == 0) {
+				field.ReturnType = currentTypeDefinition;
+			} else {
+				ITypeReference[] typeArgs = new ITypeReference[currentTypeDefinition.TypeParameters.Count];
+				for (int i = 0; i < typeArgs.Length; i++) {
+					typeArgs[i] = TypeParameterReference.Create(SymbolKind.TypeDefinition, i);
+				}
+				field.ReturnType = interningProvider.Intern(new ParameterizedTypeReference(currentTypeDefinition, typeArgs));
+			}
+			field.Accessibility = Accessibility.Public;
+			field.IsStatic = true;
+			if (!enumMemberDeclaration.Initializer.IsNull) {
+				field.ConstantValue = ConvertConstantValue(field.ReturnType, enumMemberDeclaration.Initializer);
+			} else {
+				DefaultUnresolvedField prevField = currentTypeDefinition.Members.LastOrDefault() as DefaultUnresolvedField;
+				if (prevField == null || prevField.ConstantValue == null) {
+					field.ConstantValue = ConvertConstantValue(field.ReturnType, new PrimitiveExpression(0));
+				} else {
+					field.ConstantValue = interningProvider.Intern(new IncrementConstantValue(prevField.ConstantValue));
+				}
+			}
+			
+			currentTypeDefinition.Members.Add(field);
+			field.ApplyInterningProvider(interningProvider);
+			return field;
+		}
+		#endregion
+		
+		#region Methods
+		public override IUnresolvedEntity VisitMethodDeclaration(MethodDeclaration methodDeclaration)
+		{
+			DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(currentTypeDefinition, methodDeclaration.Name);
+			currentMethod = m; // required for resolving type parameters
+			m.Region = MakeRegion(methodDeclaration);
+			m.BodyRegion = MakeRegion(methodDeclaration.Body);
+			AddXmlDocumentation(m, methodDeclaration);
+			
+			if (InheritsConstraints(methodDeclaration) && methodDeclaration.Constraints.Count == 0) {
+				int index = 0;
+				foreach (TypeParameterDeclaration tpDecl in methodDeclaration.TypeParameters) {
+					var tp = new MethodTypeParameterWithInheritedConstraints(index++, tpDecl.Name);
+					tp.Region = MakeRegion(tpDecl);
+					ConvertAttributes(tp.Attributes, tpDecl.Attributes);
+					tp.Variance = tpDecl.Variance;
+					tp.ApplyInterningProvider(interningProvider);
+					m.TypeParameters.Add(tp);
+				}
+			} else {
+				ConvertTypeParameters(m.TypeParameters, methodDeclaration.TypeParameters, methodDeclaration.Constraints, SymbolKind.Method);
+			}
+			m.ReturnType = ConvertTypeReference(methodDeclaration.ReturnType);
+			ConvertAttributes(m.Attributes, methodDeclaration.Attributes.Where(s => s.AttributeTarget != "return"));
+			ConvertAttributes(m.ReturnTypeAttributes, methodDeclaration.Attributes.Where(s => s.AttributeTarget == "return"));
+			
+			ApplyModifiers(m, methodDeclaration.Modifiers);
+			if (methodDeclaration.IsExtensionMethod) {
+				m.IsExtensionMethod = true;
+				currentTypeDefinition.HasExtensionMethods = true;
+			}
+			m.IsPartial = methodDeclaration.HasModifier(Modifiers.Partial);
+			m.IsAsync = methodDeclaration.HasModifier(Modifiers.Async);
+
+			m.HasBody = !methodDeclaration.Body.IsNull;
+			
+			ConvertParameters(m.Parameters, methodDeclaration.Parameters);
+			if (!methodDeclaration.PrivateImplementationType.IsNull) {
+				m.Accessibility = Accessibility.None;
+				m.IsExplicitInterfaceImplementation = true;
+				m.ExplicitInterfaceImplementations.Add(
+					interningProvider.Intern(new DefaultMemberReference(
+						m.SymbolKind,
+						ConvertTypeReference(methodDeclaration.PrivateImplementationType),
+						m.Name, m.TypeParameters.Count, GetParameterTypes(m.Parameters))));
+			}
+			
+			currentTypeDefinition.Members.Add(m);
+			currentMethod = null;
+			m.ApplyInterningProvider(interningProvider);
+			return m;
+		}
+		
+		IList<ITypeReference> GetParameterTypes(IList<IUnresolvedParameter> parameters)
+		{
+			if (parameters.Count == 0)
+				return EmptyList<ITypeReference>.Instance;
+			ITypeReference[] types = new ITypeReference[parameters.Count];
+			for (int i = 0; i < types.Length; i++) {
+				types[i] = parameters[i].Type;
+			}
+			return interningProvider.InternList(types);
+		}
+		
+		bool InheritsConstraints(MethodDeclaration methodDeclaration)
+		{
+			// overrides and explicit interface implementations inherit constraints
+			if ((methodDeclaration.Modifiers & Modifiers.Override) == Modifiers.Override)
+				return true;
+			return !methodDeclaration.PrivateImplementationType.IsNull;
+		}
+		
+		void ConvertTypeParameters(IList<IUnresolvedTypeParameter> output, AstNodeCollection<TypeParameterDeclaration> typeParameters,
+		                           AstNodeCollection<Constraint> constraints, SymbolKind ownerType)
+		{
+			// output might be non-empty when type parameters were copied from an outer class
+			int index = output.Count;
+			List<DefaultUnresolvedTypeParameter> list = new List<DefaultUnresolvedTypeParameter>();
+			foreach (TypeParameterDeclaration tpDecl in typeParameters) {
+				DefaultUnresolvedTypeParameter tp = new DefaultUnresolvedTypeParameter(ownerType, index++, tpDecl.Name);
+				tp.Region = MakeRegion(tpDecl);
+				ConvertAttributes(tp.Attributes, tpDecl.Attributes);
+				tp.Variance = tpDecl.Variance;
+				list.Add(tp);
+				output.Add(tp); // tp must be added to list here so that it can be referenced by constraints
+			}
+			foreach (Constraint c in constraints) {
+				foreach (var tp in list) {
+					if (tp.Name == c.TypeParameter.Identifier) {
+						foreach (AstType type in c.BaseTypes) {
+							PrimitiveType primType = type as PrimitiveType;
+							if (primType != null) {
+								if (primType.Keyword == "new") {
+									tp.HasDefaultConstructorConstraint = true;
+									continue;
+								} else if (primType.Keyword == "class") {
+									tp.HasReferenceTypeConstraint = true;
+									continue;
+								} else if (primType.Keyword == "struct") {
+									tp.HasValueTypeConstraint = true;
+									continue;
+								}
+							}
+							var lookupMode = (ownerType == SymbolKind.TypeDefinition) ? NameLookupMode.BaseTypeReference : NameLookupMode.Type;
+							tp.Constraints.Add(ConvertTypeReference(type, lookupMode));
+						}
+						break;
+					}
+				}
+			}
+			foreach (DefaultUnresolvedTypeParameter tp in list) {
+				tp.ApplyInterningProvider(interningProvider);
+			}
+		}
+		#endregion
+		
+		#region Operators
+		public override IUnresolvedEntity VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
+		{
+			DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(currentTypeDefinition, operatorDeclaration.Name);
+			m.SymbolKind = SymbolKind.Operator;
+			m.Region = MakeRegion(operatorDeclaration);
+			m.BodyRegion = MakeRegion(operatorDeclaration.Body);
+			AddXmlDocumentation(m, operatorDeclaration);
+			
+			m.ReturnType = ConvertTypeReference(operatorDeclaration.ReturnType);
+			ConvertAttributes(m.Attributes, operatorDeclaration.Attributes.Where(s => s.AttributeTarget != "return"));
+			ConvertAttributes(m.ReturnTypeAttributes, operatorDeclaration.Attributes.Where(s => s.AttributeTarget == "return"));
+			
+			ApplyModifiers(m, operatorDeclaration.Modifiers);
+			m.HasBody = !operatorDeclaration.Body.IsNull;
+			
+			ConvertParameters(m.Parameters, operatorDeclaration.Parameters);
+			
+			currentTypeDefinition.Members.Add(m);
+			m.ApplyInterningProvider(interningProvider);
+			return m;
+		}
+		#endregion
+		
+		#region Constructors
+		public override IUnresolvedEntity VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
+		{
+			Modifiers modifiers = constructorDeclaration.Modifiers;
+			bool isStatic = (modifiers & Modifiers.Static) != 0;
+			DefaultUnresolvedMethod ctor = new DefaultUnresolvedMethod(currentTypeDefinition, isStatic ? ".cctor" : ".ctor");
+			ctor.SymbolKind = SymbolKind.Constructor;
+			ctor.Region = MakeRegion(constructorDeclaration);
+			if (!constructorDeclaration.Initializer.IsNull) {
+				ctor.BodyRegion = MakeRegion(constructorDeclaration.Initializer.StartLocation, constructorDeclaration.EndLocation);
+			} else {
+				ctor.BodyRegion = MakeRegion(constructorDeclaration.Body);
+			}
+			ctor.ReturnType = KnownTypeReference.Void;
+			
+			ConvertAttributes(ctor.Attributes, constructorDeclaration.Attributes);
+			ConvertParameters(ctor.Parameters, constructorDeclaration.Parameters);
+			AddXmlDocumentation(ctor, constructorDeclaration);
+			ctor.HasBody = !constructorDeclaration.Body.IsNull;
+			
+			if (isStatic)
+				ctor.IsStatic = true;
+			else
+				ApplyModifiers(ctor, modifiers);
+			
+			currentTypeDefinition.Members.Add(ctor);
+			ctor.ApplyInterningProvider(interningProvider);
+			return ctor;
+		}
+		#endregion
+		
+		#region Destructors
+		public override IUnresolvedEntity VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
+		{
+			DefaultUnresolvedMethod dtor = new DefaultUnresolvedMethod(currentTypeDefinition, "Finalize");
+			dtor.SymbolKind = SymbolKind.Destructor;
+			dtor.Region = MakeRegion(destructorDeclaration);
+			dtor.BodyRegion = MakeRegion(destructorDeclaration.Body);
+			dtor.Accessibility = Accessibility.Protected;
+			dtor.IsOverride = true;
+			dtor.ReturnType = KnownTypeReference.Void;
+			dtor.HasBody = !destructorDeclaration.Body.IsNull;
+			
+			ConvertAttributes(dtor.Attributes, destructorDeclaration.Attributes);
+			AddXmlDocumentation(dtor, destructorDeclaration);
+			
+			currentTypeDefinition.Members.Add(dtor);
+			dtor.ApplyInterningProvider(interningProvider);
+			return dtor;
+		}
+		#endregion
+		
+		#region Properties / Indexers
+		public override IUnresolvedEntity VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
+		{
+			DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(currentTypeDefinition, propertyDeclaration.Name);
+			p.Region = MakeRegion(propertyDeclaration);
+			p.BodyRegion = MakeBraceRegion(propertyDeclaration);
+			ApplyModifiers(p, propertyDeclaration.Modifiers);
+			p.ReturnType = ConvertTypeReference(propertyDeclaration.ReturnType);
+			ConvertAttributes(p.Attributes, propertyDeclaration.Attributes);
+			AddXmlDocumentation(p, propertyDeclaration);
+			if (!propertyDeclaration.PrivateImplementationType.IsNull) {
+				p.Accessibility = Accessibility.None;
+				p.IsExplicitInterfaceImplementation = true;
+				p.ExplicitInterfaceImplementations.Add(interningProvider.Intern(new DefaultMemberReference(
+					p.SymbolKind, ConvertTypeReference(propertyDeclaration.PrivateImplementationType), p.Name)));
+			}
+			bool isExtern = propertyDeclaration.HasModifier(Modifiers.Extern);
+			p.Getter = ConvertAccessor(propertyDeclaration.Getter, p, "get_", isExtern);
+			p.Setter = ConvertAccessor(propertyDeclaration.Setter, p, "set_", isExtern);
+			currentTypeDefinition.Members.Add(p);
+			p.ApplyInterningProvider(interningProvider);
+			return p;
+		}
+		
+		public override IUnresolvedEntity VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
+		{
+			DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(currentTypeDefinition, "Item");
+			p.SymbolKind = SymbolKind.Indexer;
+			p.Region = MakeRegion(indexerDeclaration);
+			p.BodyRegion = MakeBraceRegion(indexerDeclaration);
+			ApplyModifiers(p, indexerDeclaration.Modifiers);
+			p.ReturnType = ConvertTypeReference(indexerDeclaration.ReturnType);
+			ConvertAttributes(p.Attributes, indexerDeclaration.Attributes);
+			AddXmlDocumentation(p, indexerDeclaration);
+			
+			ConvertParameters(p.Parameters, indexerDeclaration.Parameters);
+			
+			if (!indexerDeclaration.PrivateImplementationType.IsNull) {
+				p.Accessibility = Accessibility.None;
+				p.IsExplicitInterfaceImplementation = true;
+				p.ExplicitInterfaceImplementations.Add(interningProvider.Intern(new DefaultMemberReference(
+					p.SymbolKind, indexerDeclaration.PrivateImplementationType.ToTypeReference(), p.Name, 0, GetParameterTypes(p.Parameters))));
+			}
+			bool isExtern = indexerDeclaration.HasModifier(Modifiers.Extern);
+			p.Getter = ConvertAccessor(indexerDeclaration.Getter, p, "get_", isExtern);
+			p.Setter = ConvertAccessor(indexerDeclaration.Setter, p, "set_", isExtern);
+			
+			currentTypeDefinition.Members.Add(p);
+			p.ApplyInterningProvider(interningProvider);
+			return p;
+		}
+		
+		DefaultUnresolvedMethod ConvertAccessor(Accessor accessor, IUnresolvedMember p, string prefix, bool memberIsExtern)
+		{
+			if (accessor.IsNull)
+				return null;
+			var a = new DefaultUnresolvedMethod(currentTypeDefinition, prefix + p.Name);
+			a.SymbolKind = SymbolKind.Accessor;
+			a.AccessorOwner = p;
+			a.Accessibility = GetAccessibility(accessor.Modifiers) ?? p.Accessibility;
+			a.IsAbstract = p.IsAbstract;
+			a.IsOverride = p.IsOverride;
+			a.IsSealed = p.IsSealed;
+			a.IsStatic = p.IsStatic;
+			a.IsSynthetic = p.IsSynthetic;
+			a.IsVirtual = p.IsVirtual;
+			
+			a.Region = MakeRegion(accessor);
+			a.BodyRegion = MakeRegion(accessor.Body);
+			// An accessor has no body if both are true:
+			//  a) there's no body in the code
+			//  b) the member is either abstract or extern
+			a.HasBody = !(accessor.Body.IsNull && (p.IsAbstract || memberIsExtern));
+			if (p.SymbolKind == SymbolKind.Indexer) {
+				foreach (var indexerParam in ((IUnresolvedProperty)p).Parameters)
+					a.Parameters.Add(indexerParam);
+			}
+			DefaultUnresolvedParameter param = null;
+			if (accessor.Role == PropertyDeclaration.GetterRole) {
+				a.ReturnType = p.ReturnType;
+			} else {
+				param = new DefaultUnresolvedParameter(p.ReturnType, "value");
+				a.Parameters.Add(param);
+				a.ReturnType = KnownTypeReference.Void;
+			}
+			foreach (AttributeSection section in accessor.Attributes) {
+				if (section.AttributeTarget == "return") {
+					ConvertAttributes(a.ReturnTypeAttributes, section);
+				} else if (param != null && section.AttributeTarget == "param") {
+					ConvertAttributes(param.Attributes, section);
+				} else {
+					ConvertAttributes(a.Attributes, section);
+				}
+			}
+			if (p.IsExplicitInterfaceImplementation) {
+				a.IsExplicitInterfaceImplementation = true;
+				Debug.Assert(p.ExplicitInterfaceImplementations.Count == 1);
+				a.ExplicitInterfaceImplementations.Add(interningProvider.Intern(new DefaultMemberReference(
+					SymbolKind.Accessor,
+					p.ExplicitInterfaceImplementations[0].DeclaringTypeReference,
+					a.Name, 0, GetParameterTypes(a.Parameters)
+				)));
+			}
+			a.ApplyInterningProvider(interningProvider);
+			return a;
+		}
+		#endregion
+		
+		#region Events
+		public override IUnresolvedEntity VisitEventDeclaration(EventDeclaration eventDeclaration)
+		{
+			bool isSingleEvent = eventDeclaration.Variables.Count == 1;
+			Modifiers modifiers = eventDeclaration.Modifiers;
+			DefaultUnresolvedEvent ev = null;
+			foreach (VariableInitializer vi in eventDeclaration.Variables) {
+				ev = new DefaultUnresolvedEvent(currentTypeDefinition, vi.Name);
+				
+				ev.Region = isSingleEvent ? MakeRegion(eventDeclaration) : MakeRegion(vi);
+				ev.BodyRegion = MakeRegion(vi);
+				
+				ApplyModifiers(ev, modifiers);
+				AddXmlDocumentation(ev, eventDeclaration);
+				
+				ev.ReturnType = ConvertTypeReference(eventDeclaration.ReturnType);
+				
+				var valueParameter = new DefaultUnresolvedParameter(ev.ReturnType, "value");
+				ev.AddAccessor = CreateDefaultEventAccessor(ev, "add_" + ev.Name, valueParameter);
+				ev.RemoveAccessor = CreateDefaultEventAccessor(ev, "remove_" + ev.Name, valueParameter);
+				
+				foreach (AttributeSection section in eventDeclaration.Attributes) {
+					if (section.AttributeTarget == "method") {
+						foreach (var attrNode in section.Attributes) {
+							IUnresolvedAttribute attr = ConvertAttribute(attrNode);
+							ev.AddAccessor.Attributes.Add(attr);
+							ev.RemoveAccessor.Attributes.Add(attr);
+						}
+					} else if (section.AttributeTarget != "field") {
+						ConvertAttributes(ev.Attributes, section);
+					}
+				}
+				
+				currentTypeDefinition.Members.Add(ev);
+				ev.ApplyInterningProvider(interningProvider);
+			}
+			return isSingleEvent ? ev : null;
+		}
+		
+		DefaultUnresolvedMethod CreateDefaultEventAccessor(IUnresolvedEvent ev, string name, IUnresolvedParameter valueParameter)
+		{
+			var a = new DefaultUnresolvedMethod(currentTypeDefinition, name);
+			a.SymbolKind = SymbolKind.Accessor;
+			a.AccessorOwner = ev;
+			a.Region = ev.BodyRegion;
+			a.BodyRegion = DomRegion.Empty;
+			a.Accessibility = ev.Accessibility;
+			a.IsAbstract = ev.IsAbstract;
+			a.IsOverride = ev.IsOverride;
+			a.IsSealed = ev.IsSealed;
+			a.IsStatic = ev.IsStatic;
+			a.IsSynthetic = ev.IsSynthetic;
+			a.IsVirtual = ev.IsVirtual;
+			a.HasBody = true; // even if it's compiler-generated; the body still exists
+			a.ReturnType = KnownTypeReference.Void;
+			a.Parameters.Add(valueParameter);
+			return a;
+		}
+		
+		public override IUnresolvedEntity VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
+		{
+			DefaultUnresolvedEvent e = new DefaultUnresolvedEvent(currentTypeDefinition, eventDeclaration.Name);
+			e.Region = MakeRegion(eventDeclaration);
+			e.BodyRegion = MakeBraceRegion(eventDeclaration);
+			ApplyModifiers(e, eventDeclaration.Modifiers);
+			e.ReturnType = ConvertTypeReference(eventDeclaration.ReturnType);
+			ConvertAttributes(e.Attributes, eventDeclaration.Attributes);
+			AddXmlDocumentation(e, eventDeclaration);
+			
+			if (!eventDeclaration.PrivateImplementationType.IsNull) {
+				e.Accessibility = Accessibility.None;
+				e.IsExplicitInterfaceImplementation = true;
+				e.ExplicitInterfaceImplementations.Add(interningProvider.Intern(new DefaultMemberReference(
+					e.SymbolKind, eventDeclaration.PrivateImplementationType.ToTypeReference(), e.Name)));
+			}
+			
+			// custom events can't be extern; the non-custom event syntax must be used for extern events
+			e.AddAccessor = ConvertAccessor(eventDeclaration.AddAccessor, e, "add_", false);
+			e.RemoveAccessor = ConvertAccessor(eventDeclaration.RemoveAccessor, e, "remove_", false);
+			
+			currentTypeDefinition.Members.Add(e);
+			e.ApplyInterningProvider(interningProvider);
+			return e;
+		}
+		#endregion
+		
+		#region Modifiers
+		static void ApplyModifiers(DefaultUnresolvedTypeDefinition td, Modifiers modifiers)
+		{
+			td.Accessibility = GetAccessibility(modifiers) ?? (td.DeclaringTypeDefinition != null ? Accessibility.Private : Accessibility.Internal);
+			td.IsAbstract = (modifiers & (Modifiers.Abstract | Modifiers.Static)) != 0;
+			td.IsSealed = (modifiers & (Modifiers.Sealed | Modifiers.Static)) != 0;
+			td.IsShadowing = (modifiers & Modifiers.New) != 0;
+			td.IsPartial = (modifiers & Modifiers.Partial) != 0;
+		}
+		
+		static void ApplyModifiers(AbstractUnresolvedMember m, Modifiers modifiers)
+		{
+			// members from interfaces are always Public+Abstract. (NOTE: 'new' modifier is valid in interfaces as well.)
+			if (m.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
+				m.Accessibility = Accessibility.Public;
+				m.IsAbstract = true;
+				m.IsShadowing = (modifiers & Modifiers.New) != 0;
+				return;
+			}
+			m.Accessibility = GetAccessibility(modifiers) ?? Accessibility.Private;
+			m.IsAbstract = (modifiers & Modifiers.Abstract) != 0;
+			m.IsOverride = (modifiers & Modifiers.Override) != 0;
+			m.IsSealed = (modifiers & Modifiers.Sealed) != 0;
+			m.IsShadowing = (modifiers & Modifiers.New) != 0;
+			m.IsStatic = (modifiers & Modifiers.Static) != 0;
+			m.IsVirtual = (modifiers & Modifiers.Virtual) != 0;
+		}
+		
+		static Accessibility? GetAccessibility(Modifiers modifiers)
+		{
+			switch (modifiers & Modifiers.VisibilityMask) {
+				case Modifiers.Private:
+					return Accessibility.Private;
+				case Modifiers.Internal:
+					return Accessibility.Internal;
+				case Modifiers.Protected | Modifiers.Internal:
+					return Accessibility.ProtectedOrInternal;
+				case Modifiers.Protected:
+					return Accessibility.Protected;
+				case Modifiers.Public:
+					return Accessibility.Public;
+				default:
+					return null;
+			}
+		}
+		#endregion
+		
+		#region Attributes
+		public override IUnresolvedEntity VisitAttributeSection(AttributeSection attributeSection)
+		{
+			// non-assembly attributes are handled by their parent entity
+			if (attributeSection.AttributeTarget == "assembly") {
+				ConvertAttributes(unresolvedFile.AssemblyAttributes, attributeSection);
+			} else if (attributeSection.AttributeTarget == "module") {
+				ConvertAttributes(unresolvedFile.ModuleAttributes, attributeSection);
+			}
+			return null;
+		}
+		
+		void ConvertAttributes(IList<IUnresolvedAttribute> outputList, IEnumerable<AttributeSection> attributes)
+		{
+			foreach (AttributeSection section in attributes) {
+				ConvertAttributes(outputList, section);
+			}
+		}
+		
+		void ConvertAttributes(IList<IUnresolvedAttribute> outputList, AttributeSection attributeSection)
+		{
+			foreach (CSharp.Attribute attr in attributeSection.Attributes) {
+				outputList.Add(ConvertAttribute(attr));
+			}
+		}
+		
+		internal static ITypeReference ConvertAttributeType(AstType type, InterningProvider interningProvider)
+		{
+			ITypeReference tr = type.ToTypeReference(NameLookupMode.Type, interningProvider);
+			if (!type.GetChildByRole(Roles.Identifier).IsVerbatim) {
+				// Try to add "Attribute" suffix, but only if the identifier
+				// (=last identifier in fully qualified name) isn't a verbatim identifier.
+				SimpleTypeOrNamespaceReference st = tr as SimpleTypeOrNamespaceReference;
+				MemberTypeOrNamespaceReference mt = tr as MemberTypeOrNamespaceReference;
+				if (st != null)
+					return interningProvider.Intern(new AttributeTypeReference(st, interningProvider.Intern(st.AddSuffix("Attribute"))));
+				else if (mt != null)
+					return interningProvider.Intern(new AttributeTypeReference(mt, interningProvider.Intern(mt.AddSuffix("Attribute"))));
+			}
+			return tr;
+		}
+		
+		CSharpAttribute ConvertAttribute(CSharp.Attribute attr)
+		{
+			DomRegion region = MakeRegion(attr);
+			ITypeReference type = ConvertAttributeType(attr.Type, interningProvider);
+			List<IConstantValue> positionalArguments = null;
+			List<KeyValuePair<string, IConstantValue>> namedCtorArguments = null;
+			List<KeyValuePair<string, IConstantValue>> namedArguments = null;
+			foreach (Expression expr in attr.Arguments) {
+				NamedArgumentExpression nae = expr as NamedArgumentExpression;
+				if (nae != null) {
+					string name = interningProvider.Intern(nae.Name);
+					if (namedCtorArguments == null)
+						namedCtorArguments = new List<KeyValuePair<string, IConstantValue>>();
+					namedCtorArguments.Add(new KeyValuePair<string, IConstantValue>(name, ConvertAttributeArgument(nae.Expression)));
+				} else {
+					NamedExpression namedExpression = expr as NamedExpression;
+					if (namedExpression != null) {
+						string name = interningProvider.Intern(namedExpression.Name);
+						if (namedArguments == null)
+							namedArguments = new List<KeyValuePair<string, IConstantValue>>();
+						namedArguments.Add(new KeyValuePair<string, IConstantValue>(name, ConvertAttributeArgument(namedExpression.Expression)));
+					} else {
+						if (positionalArguments == null)
+							positionalArguments = new List<IConstantValue>();
+						positionalArguments.Add(ConvertAttributeArgument(expr));
+					}
+				}
+			}
+			return new CSharpAttribute(type, region, interningProvider.InternList(positionalArguments), namedCtorArguments, namedArguments);
+		}
+		#endregion
+		
+		#region Types
+		ITypeReference ConvertTypeReference(AstType type, NameLookupMode lookupMode = NameLookupMode.Type)
+		{
+			return type.ToTypeReference(lookupMode, interningProvider);
+		}
+		#endregion
+		
+		#region Constant Values
+		IConstantValue ConvertConstantValue(ITypeReference targetType, AstNode expression)
+		{
+			return ConvertConstantValue(targetType, expression, currentTypeDefinition, currentMethod, usingScope, interningProvider);
+		}
+		
+		internal static IConstantValue ConvertConstantValue(
+			ITypeReference targetType, AstNode expression,
+			IUnresolvedTypeDefinition parentTypeDefinition, IUnresolvedMethod parentMethodDefinition, UsingScope parentUsingScope,
+			InterningProvider interningProvider)
+		{
+			ConstantValueBuilder b = new ConstantValueBuilder(false, interningProvider);
+			ConstantExpression c = expression.AcceptVisitor(b);
+			if (c == null)
+				return new ErrorConstantValue(targetType);
+			PrimitiveConstantExpression pc = c as PrimitiveConstantExpression;
+			if (pc != null && pc.Type == targetType) {
+				// Save memory by directly using a SimpleConstantValue.
+				return interningProvider.Intern(new SimpleConstantValue(targetType, pc.Value));
+			}
+			// cast to the desired type
+			return interningProvider.Intern(new ConstantCast(targetType, c, true));
+		}
+		
+		IConstantValue ConvertAttributeArgument(Expression expression)
+		{
+			ConstantValueBuilder b = new ConstantValueBuilder(true, interningProvider);
+			return expression.AcceptVisitor(b);
+		}
+		
+		sealed class ConstantValueBuilder : DepthFirstAstVisitor<ConstantExpression>
+		{
+			readonly InterningProvider interningProvider;
+			readonly bool isAttributeArgument;
+			
+			public ConstantValueBuilder(bool isAttributeArgument, InterningProvider interningProvider)
+			{
+				this.interningProvider = interningProvider;
+				this.isAttributeArgument = isAttributeArgument;
+			}
+			
+			protected override ConstantExpression VisitChildren(AstNode node)
+			{
+				return null;
+			}
+			
+			public override ConstantExpression VisitNullReferenceExpression(NullReferenceExpression nullReferenceExpression)
+			{
+				return interningProvider.Intern(
+					new PrimitiveConstantExpression(KnownTypeReference.Object, null));
+			}
+
+			public override ConstantExpression VisitSizeOfExpression(SizeOfExpression sizeOfExpression) {
+				return new SizeOfConstantValue(sizeOfExpression.Type.ToTypeReference(NameLookupMode.Type, interningProvider));
+			}
+			
+			public override ConstantExpression VisitPrimitiveExpression(PrimitiveExpression primitiveExpression)
+			{
+				object val = interningProvider.InternValue(primitiveExpression.Value);
+				TypeCode typeCode = (val == null ? TypeCode.Object : Type.GetTypeCode(val.GetType()));
+				return interningProvider.Intern(
+					new PrimitiveConstantExpression(typeCode.ToTypeReference(), val));
+			}
+			
+			ITypeReference ConvertTypeReference(AstType type)
+			{
+				return type.ToTypeReference(NameLookupMode.Type, interningProvider);
+			}
+			
+			IList<ITypeReference> ConvertTypeArguments(AstNodeCollection<AstType> types)
+			{
+				int count = types.Count;
+				if (count == 0)
+					return null;
+				ITypeReference[] result = new ITypeReference[count];
+				int pos = 0;
+				foreach (AstType type in types) {
+					result[pos++] = ConvertTypeReference(type);
+				}
+				return interningProvider.InternList(result);
+			}
+			
+			public override ConstantExpression VisitIdentifierExpression(IdentifierExpression identifierExpression)
+			{
+				string identifier = interningProvider.Intern(identifierExpression.Identifier);
+				return new ConstantIdentifierReference(identifier, ConvertTypeArguments(identifierExpression.TypeArguments));
+			}
+			
+			public override ConstantExpression VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
+			{
+				string memberName = interningProvider.Intern(memberReferenceExpression.MemberName);
+				TypeReferenceExpression tre = memberReferenceExpression.Target as TypeReferenceExpression;
+				if (tre != null) {
+					// handle "int.MaxValue"
+					return new ConstantMemberReference(
+						ConvertTypeReference(tre.Type),
+						memberName,
+						ConvertTypeArguments(memberReferenceExpression.TypeArguments));
+				}
+				ConstantExpression v = memberReferenceExpression.Target.AcceptVisitor(this);
+				if (v == null)
+					return null;
+				return new ConstantMemberReference(
+					v, memberName,
+					ConvertTypeArguments(memberReferenceExpression.TypeArguments));
+			}
+			
+			public override ConstantExpression VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression)
+			{
+				return parenthesizedExpression.Expression.AcceptVisitor(this);
+			}
+			
+			public override ConstantExpression VisitCastExpression(CastExpression castExpression)
+			{
+				ConstantExpression v = castExpression.Expression.AcceptVisitor(this);
+				if (v == null)
+					return null;
+				var typeReference = ConvertTypeReference(castExpression.Type);
+				return interningProvider.Intern(new ConstantCast(typeReference, v, false));
+			}
+			
+			public override ConstantExpression VisitCheckedExpression(CheckedExpression checkedExpression)
+			{
+				ConstantExpression v = checkedExpression.Expression.AcceptVisitor(this);
+				if (v != null)
+					return new ConstantCheckedExpression(true, v);
+				else
+					return null;
+			}
+			
+			public override ConstantExpression VisitUncheckedExpression(UncheckedExpression uncheckedExpression)
+			{
+				ConstantExpression v = uncheckedExpression.Expression.AcceptVisitor(this);
+				if (v != null)
+					return new ConstantCheckedExpression(false, v);
+				else
+					return null;
+			}
+			
+			public override ConstantExpression VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
+			{
+				return interningProvider.Intern(
+					new ConstantDefaultValue(ConvertTypeReference(defaultValueExpression.Type)));
+			}
+			
+			public override ConstantExpression VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression)
+			{
+				ConstantExpression v = unaryOperatorExpression.Expression.AcceptVisitor(this);
+				if (v == null)
+					return null;
+				switch (unaryOperatorExpression.Operator) {
+					case UnaryOperatorType.Not:
+					case UnaryOperatorType.BitNot:
+					case UnaryOperatorType.Minus:
+					case UnaryOperatorType.Plus:
+						return new ConstantUnaryOperator(unaryOperatorExpression.Operator, v);
+					default:
+						return null;
+				}
+			}
+			
+			public override ConstantExpression VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression)
+			{
+				ConstantExpression left = binaryOperatorExpression.Left.AcceptVisitor(this);
+				ConstantExpression right = binaryOperatorExpression.Right.AcceptVisitor(this);
+				if (left == null || right == null)
+					return null;
+				return new ConstantBinaryOperator(left, binaryOperatorExpression.Operator, right);
+			}
+			
+			public override ConstantExpression VisitTypeOfExpression(TypeOfExpression typeOfExpression)
+			{
+				if (isAttributeArgument) {
+					return new TypeOfConstantExpression(ConvertTypeReference(typeOfExpression.Type));
+				} else {
+					return null;
+				}
+			}
+
+			public override ConstantExpression VisitObjectCreateExpression(ObjectCreateExpression objectCreateExpression)
+			{
+				if (!objectCreateExpression.Arguments.Any()) {
+					// built in primitive type constants can be created with new
+					// Todo: correctly resolve the type instead of doing the string approach
+					switch (objectCreateExpression.Type.ToString()) {
+						case "System.Boolean":
+						case "bool":
+							return new PrimitiveConstantExpression(KnownTypeReference.Boolean, new bool());
+						case "System.Char":
+						case "char":
+							return new PrimitiveConstantExpression(KnownTypeReference.Char, new char());
+						case "System.SByte":
+						case "sbyte":
+							return new PrimitiveConstantExpression(KnownTypeReference.SByte, new sbyte());
+						case "System.Byte":
+						case "byte":
+							return new PrimitiveConstantExpression(KnownTypeReference.Byte, new byte());
+						case "System.Int16":
+						case "short":
+							return new PrimitiveConstantExpression(KnownTypeReference.Int16, new short());
+						case "System.UInt16":
+						case "ushort":
+							return new PrimitiveConstantExpression(KnownTypeReference.UInt16, new ushort());
+						case "System.Int32":
+						case "int":
+							return new PrimitiveConstantExpression(KnownTypeReference.Int32, new int());
+						case "System.UInt32":
+						case "uint":
+							return new PrimitiveConstantExpression(KnownTypeReference.UInt32, new uint());
+						case "System.Int64":
+						case "long":
+							return new PrimitiveConstantExpression(KnownTypeReference.Int64, new long());
+						case "System.UInt64":
+						case "ulong":
+							return new PrimitiveConstantExpression(KnownTypeReference.UInt64, new ulong());
+						case "System.Single":
+						case "float":
+							return new PrimitiveConstantExpression(KnownTypeReference.Single, new float());
+						case "System.Double":
+						case "double":
+							return new PrimitiveConstantExpression(KnownTypeReference.Double, new double());
+						case "System.Decimal":
+						case "decimal":
+							return new PrimitiveConstantExpression(KnownTypeReference.Decimal, new decimal());
+					}
+				}
+
+				return null;
+			}
+
+			public override ConstantExpression VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression)
+			{
+				var initializer = arrayCreateExpression.Initializer;
+				// Attributes only allow one-dimensional arrays
+				if (isAttributeArgument && !initializer.IsNull && arrayCreateExpression.Arguments.Count < 2) {
+					ITypeReference type;
+					if (arrayCreateExpression.Type.IsNull) {
+						type = null;
+					} else {
+						type = ConvertTypeReference(arrayCreateExpression.Type);
+						foreach (var spec in arrayCreateExpression.AdditionalArraySpecifiers.Reverse()) {
+							type = interningProvider.Intern(new ArrayTypeReference(type, spec.Dimensions));
+						}
+					}
+					ConstantExpression[] elements = new ConstantExpression[initializer.Elements.Count];
+					int pos = 0;
+					foreach (Expression expr in initializer.Elements) {
+						ConstantExpression c = expr.AcceptVisitor(this);
+						if (c == null)
+							return null;
+						elements[pos++] = c;
+					}
+					return new ConstantArrayCreation(type, elements);
+				} else {
+					return null;
+				}
+			}
+		}
+		#endregion
+		
+		#region Parameters
+		void ConvertParameters(IList<IUnresolvedParameter> outputList, IEnumerable<ParameterDeclaration> parameters)
+		{
+			foreach (ParameterDeclaration pd in parameters) {
+				DefaultUnresolvedParameter p = new DefaultUnresolvedParameter(ConvertTypeReference(pd.Type), interningProvider.Intern(pd.Name));
+				p.Region = MakeRegion(pd);
+				ConvertAttributes(p.Attributes, pd.Attributes);
+				switch (pd.ParameterModifier) {
+					case ParameterModifier.Ref:
+						p.IsRef = true;
+						p.Type = interningProvider.Intern(new ByReferenceTypeReference(p.Type));
+						break;
+					case ParameterModifier.Out:
+						p.IsOut = true;
+						p.Type = interningProvider.Intern(new ByReferenceTypeReference(p.Type));
+						break;
+					case ParameterModifier.Params:
+						p.IsParams = true;
+						break;
+				}
+				if (!pd.DefaultExpression.IsNull)
+					p.DefaultValue = ConvertConstantValue(p.Type, pd.DefaultExpression);
+				outputList.Add(interningProvider.Intern(p));
+			}
+		}
+		
+		internal static IList<ITypeReference> GetParameterTypes(IEnumerable<ParameterDeclaration> parameters, InterningProvider interningProvider)
+		{
+			List<ITypeReference> result = new List<ITypeReference>();
+			foreach (ParameterDeclaration pd in parameters) {
+				ITypeReference type = pd.Type.ToTypeReference(NameLookupMode.Type, interningProvider);
+				if (pd.ParameterModifier == ParameterModifier.Ref || pd.ParameterModifier == ParameterModifier.Out)
+					type = interningProvider.Intern(new ByReferenceTypeReference(type));
+				result.Add(type);
+			}
+			return result;
+		}
+		#endregion
+		
+		#region XML Documentation
+		void AddXmlDocumentation(IUnresolvedEntity entity, AstNode entityDeclaration)
+		{
+			if (this.SkipXmlDocumentation)
+				return;
+			StringBuilder documentation = null;
+			// traverse children until the first non-whitespace node
+			for (AstNode node = entityDeclaration.FirstChild; node != null && node.NodeType == NodeType.Whitespace; node = node.NextSibling) {
+				Comment c = node as Comment;
+				if (c != null && c.IsDocumentation) {
+					if (documentation == null)
+						documentation = new StringBuilder();
+					if (c.CommentType == CommentType.MultiLineDocumentation) {
+						PrepareMultilineDocumentation(c.Content, documentation);
+					} else {
+						if (documentation.Length > 0)
+							documentation.AppendLine();
+						if (c.Content.Length > 0 && c.Content[0] == ' ')
+							documentation.Append(c.Content.Substring(1));
+						else
+							documentation.Append(c.Content);
+					}
+				}
+			}
+			if (documentation != null) {
+				unresolvedFile.AddDocumentation(entity, documentation.ToString());
+			}
+		}
+		
+		void PrepareMultilineDocumentation(string content, StringBuilder b)
+		{
+			using (var reader = new StringReader(content)) {
+				string firstLine = reader.ReadLine();
+				// Add first line only if it's not empty:
+				if (!string.IsNullOrWhiteSpace(firstLine)) {
+					if (firstLine[0] == ' ')
+						b.Append(firstLine, 1, firstLine.Length - 1);
+					else
+						b.Append(firstLine);
+				}
+				// Read lines into list:
+				List<string> lines = new List<string>();
+				string line;
+				while ((line = reader.ReadLine()) != null)
+					lines.Add(line);
+				// If the last line (the line with '*/' delimiter) is white space only, ignore it.
+				if (lines.Count > 0 && string.IsNullOrWhiteSpace(lines[lines.Count - 1]))
+					lines.RemoveAt(lines.Count - 1);
+				if (lines.Count > 0) {
+					// Extract pattern from lines[0]: whitespace, asterisk, whitespace
+					int patternLength = 0;
+					string secondLine = lines[0];
+					while (patternLength < secondLine.Length && char.IsWhiteSpace(secondLine[patternLength]))
+						patternLength++;
+					if (patternLength < secondLine.Length && secondLine[patternLength] == '*') {
+						patternLength++;
+						while (patternLength < secondLine.Length && char.IsWhiteSpace(secondLine[patternLength]))
+							patternLength++;
+					} else {
+						// no asterisk
+						patternLength = 0;
+					}
+					// Now reduce pattern length to the common pattern:
+					for (int i = 1; i < lines.Count; i++) {
+						line = lines[i];
+						if (line.Length < patternLength)
+							patternLength = line.Length;
+						for (int j = 0; j < patternLength; j++) {
+							if (secondLine[j] != line[j])
+								patternLength = j;
+						}
+					}
+					// Append the lines to the string builder:
+					for (int i = 0; i < lines.Count; i++) {
+						if (b.Length > 0 || i > 0)
+							b.Append(Environment.NewLine);
+						b.Append(lines[i], patternLength, lines[i].Length - patternLength);
+					}
+				}
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/UsingScope.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/UsingScope.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/TypeSystem/UsingScope.cs	(revision 11807)
@@ -0,0 +1,174 @@
+﻿// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.CSharp.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.CSharp.TypeSystem
+{
+	/// <summary>
+	/// Represents a scope that contains "using" statements.
+	/// This is either the file itself, or a namespace declaration.
+	/// </summary>
+	[Serializable]
+	public class UsingScope : AbstractFreezable
+	{
+		readonly UsingScope parent;
+		DomRegion region;
+		string shortName = "";
+		IList<TypeOrNamespaceReference> usings;
+		IList<KeyValuePair<string, TypeOrNamespaceReference>> usingAliases;
+		IList<string> externAliases;
+		
+		protected override void FreezeInternal()
+		{
+			usings = FreezableHelper.FreezeList(usings);
+			usingAliases = FreezableHelper.FreezeList(usingAliases);
+			externAliases = FreezableHelper.FreezeList(externAliases);
+			
+			// In current model (no child scopes), it makes sense to freeze the parent as well
+			// to ensure the whole lookup chain is immutable.
+			if (parent != null)
+				parent.Freeze();
+			
+			base.FreezeInternal();
+		}
+		
+		/// <summary>
+		/// Creates a new root using scope.
+		/// </summary>
+		public UsingScope()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new nested using scope.
+		/// </summary>
+		/// <param name="parent">The parent using scope.</param>
+		/// <param name="shortName">The short namespace name.</param>
+		public UsingScope(UsingScope parent, string shortName)
+		{
+			if (parent == null)
+				throw new ArgumentNullException("parent");
+			if (shortName == null)
+				throw new ArgumentNullException("shortName");
+			this.parent = parent;
+			this.shortName = shortName;
+		}
+		
+		public UsingScope Parent {
+			get { return parent; }
+		}
+		
+		public DomRegion Region {
+			get { return region; }
+			set {
+				FreezableHelper.ThrowIfFrozen(this);
+				region = value;
+			}
+		}
+		
+		public string ShortNamespaceName {
+			get {
+				return shortName;
+			}
+		}
+		
+		public string NamespaceName {
+			get {
+				if (parent != null)
+					return NamespaceDeclaration.BuildQualifiedName(parent.NamespaceName, shortName);
+				else
+					return shortName;
+			}
+//			set {
+//				if (value == null)
+//					throw new ArgumentNullException("NamespaceName");
+//				FreezableHelper.ThrowIfFrozen(this);
+//				namespaceName = value;
+//			}
+		}
+		
+		public IList<TypeOrNamespaceReference> Usings {
+			get {
+				if (usings == null)
+					usings = new List<TypeOrNamespaceReference>();
+				return usings;
+			}
+		}
+		
+		public IList<KeyValuePair<string, TypeOrNamespaceReference>> UsingAliases {
+			get {
+				if (usingAliases == null)
+					usingAliases = new List<KeyValuePair<string, TypeOrNamespaceReference>>();
+				return usingAliases;
+			}
+		}
+		
+		public IList<string> ExternAliases {
+			get {
+				if (externAliases == null)
+					externAliases = new List<string>();
+				return externAliases;
+			}
+		}
+		
+//		public IList<UsingScope> ChildScopes {
+//			get {
+//				if (childScopes == null)
+//					childScopes = new List<UsingScope>();
+//				return childScopes;
+//			}
+//		}
+		
+		/// <summary>
+		/// Gets whether this using scope has an alias (either using or extern)
+		/// with the specified name.
+		/// </summary>
+		public bool HasAlias(string identifier)
+		{
+			if (usingAliases != null) {
+				foreach (var pair in usingAliases) {
+					if (pair.Key == identifier)
+						return true;
+				}
+			}
+			return externAliases != null && externAliases.Contains(identifier);
+		}
+		
+		/// <summary>
+		/// Resolves the namespace represented by this using scope.
+		/// </summary>
+		public ResolvedUsingScope Resolve(ICompilation compilation)
+		{
+			CacheManager cache = compilation.CacheManager;
+			ResolvedUsingScope resolved = cache.GetShared(this) as ResolvedUsingScope;
+			if (resolved == null) {
+				var csContext = new CSharpTypeResolveContext(compilation.MainAssembly, parent != null ? parent.Resolve(compilation) : null);
+				resolved = (ResolvedUsingScope)cache.GetOrAddShared(this, new ResolvedUsingScope(csContext, this));
+			}
+			return resolved;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Util/CloneableStack.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Util/CloneableStack.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Util/CloneableStack.cs	(revision 11807)
@@ -0,0 +1,201 @@
+﻿//
+// CloneableStack.cs
+//
+// Author:
+//       Mike Krüger <mkrueger@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+using System;
+using System.Collections.Generic;
+using System.Collections;
+
+namespace ICSharpCode.NRefactory.CSharp
+{
+	class CloneableStack<T> : IEnumerable<T>, ICollection<T>, ICloneable, IEquatable<CloneableStack<T>>
+	{
+		int count;
+		StackItem top;
+
+		#region IEnumerable[T] implementation
+		public IEnumerator<T> GetEnumerator ()
+		{
+			return new StackItemEnumerator (top);
+		}
+
+		IEnumerator IEnumerable.GetEnumerator ()
+		{
+			return new StackItemEnumerator (top);
+		}
+		#endregion
+
+		#region ICloneable implementation
+		public CloneableStack<T> Clone ()
+		{
+			CloneableStack<T> result = new CloneableStack<T> ();
+			result.count = count;
+			result.top   = top;
+			return result;
+		}
+
+		object ICloneable.Clone ()
+		{
+			return Clone();
+		}
+		#endregion
+
+		public void Clear ()
+		{
+			top = null;
+			count = 0;
+		}
+
+		public void Push (T item)
+		{
+			top = new StackItem (top, item);
+			count++;
+		}
+
+		public T Peek ()
+		{
+			return top.Item;
+		}
+
+		public T Pop ()
+		{
+			T result = top.Item;
+			top = top.Parent;
+			count--;
+			return result;
+		}
+
+		#region IEquatable[T] implementation
+		public bool Equals (CloneableStack<T> other)
+		{
+			return ReferenceEquals (top, other.top);
+		}
+		#endregion
+
+		#region ICollection[T] implementation
+		void ICollection<T>.Add (T item)
+		{
+			Push (item);
+		}
+
+		void ICollection<T>.Clear ()
+		{
+			top = null;
+			count = 0;
+		}
+
+		bool ICollection<T>.Contains (T item)
+		{
+			foreach (T t in this) {
+				if (t.Equals (item))
+					return true;
+			}
+			return false;
+		}
+
+		void ICollection<T>.CopyTo (T[] array, int arrayIndex)
+		{
+			int idx = arrayIndex;
+			foreach (T t in this) {
+				array[idx++] = t;
+			}
+		}
+
+		bool ICollection<T>.Remove (T item)
+		{
+			throw new NotImplementedException ();
+		}
+
+		public int Count {
+			get {
+				return count;
+			}
+		}
+
+		bool ICollection<T>.IsReadOnly {
+			get {
+				return false;
+			}
+		}
+		#endregion
+
+		class StackItem
+		{
+			public readonly StackItem Parent;
+			public readonly T Item;
+
+			public StackItem (StackItem parent, T item)
+			{
+				Parent = parent;
+				Item = item;
+			}
+		}
+
+		class StackItemEnumerator : IEnumerator<T>
+		{
+			StackItem cur, first;
+
+			public StackItemEnumerator (StackItem cur)
+			{
+				this.cur = first = new StackItem (cur, default(T));
+			}
+
+			#region IDisposable implementation
+			void IDisposable.Dispose ()
+			{
+				cur = first = null;
+			}
+			#endregion
+
+			#region IEnumerator implementation
+			bool IEnumerator.MoveNext ()
+			{
+				if (cur == null)
+					return false;
+				cur = cur.Parent;
+				return cur != null;
+			}
+
+			void IEnumerator.Reset ()
+			{
+				cur = first;
+			}
+
+			object IEnumerator.Current {
+				get {
+					return cur.Item;
+				}
+			}
+			#endregion
+
+			#region IEnumerator[T] implementation
+			T IEnumerator<T>.Current {
+				get {
+					return cur.Item;
+				}
+			}
+			#endregion
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/ICSharpCode.NRefactory.CSharp.AstVerifier-5.5.0.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/ICSharpCode.NRefactory.CSharp.AstVerifier-5.5.0.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/ICSharpCode.NRefactory.CSharp.AstVerifier-5.5.0.csproj	(revision 11807)
@@ -0,0 +1,55 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{1300A468-14C1-4010-B128-C8F01CD8E511}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>ICSharpCode.NRefactory.CSharp.AstVerifier</RootNamespace>
+    <AssemblyName>ICSharpCode.NRefactory.CSharp.AstVerifier</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\..\..\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="NRefactory License.txt" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/NRefactory License.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/NRefactory License.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/NRefactory License.txt	(revision 11807)
@@ -0,0 +1,17 @@
+Copyright (c) 2010-2014 AlphaSierraPapa, Xamarin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this
+software and associated documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp.AstVerifier-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,36 @@
+﻿using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ICSharpCode.NRefactory.CSharp.AstVerifier")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("FH-Hagenberg")]
+[assembly: AssemblyProduct("NRefactory.CSharp.AstVerifier-5.5.0")]
+[assembly: AssemblyCopyright("Copyright © FH-Hagenberg 2014")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("88d377e1-a0e2-408f-bf20-2d68d06791ce")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/CecilLoader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/CecilLoader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/CecilLoader.cs	(revision 11807)
@@ -0,0 +1,1776 @@
+// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Threading;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.Semantics;
+using ICSharpCode.NRefactory.TypeSystem.Implementation;
+using ICSharpCode.NRefactory.Utils;
+using Mono.Cecil;
+
+
+namespace ICSharpCode.NRefactory.TypeSystem
+{
+	/// <summary>
+	/// Allows loading an IProjectContent from an already compiled assembly.
+	/// </summary>
+	/// <remarks>Instance methods are not thread-safe; you need to create multiple instances of CecilLoader
+	/// if you want to load multiple project contents in parallel.</remarks>
+	public sealed class CecilLoader : AssemblyLoader
+	{
+		/// <summary>
+		/// Version number of the cecil loader.
+		/// Should be incremented when fixing bugs in the cecil loader so that project contents cached on disk
+		/// (which might be incorrect due to the bug) are re-created.
+		/// </summary>
+		const int cecilLoaderVersion = 1;
+		
+		#region Options
+		// Most options are defined in the AssemblyLoader base class
+		
+		/// <summary>
+		/// Specifies whether to use lazy loading. The default is false.
+		/// If this property is set to true, the CecilLoader will not copy all the relevant information
+		/// out of the Cecil object model, but will maintain references to the Cecil objects.
+		/// This speeds up the loading process and avoids loading unnecessary information, but it causes
+		/// the Cecil objects to stay in memory (which can significantly increase memory usage).
+		/// It also prevents serialization of the Cecil-loaded type system.
+		/// </summary>
+		/// <remarks>
+		/// Because the type system can be used on multiple threads, but Cecil is not
+		/// thread-safe for concurrent read access, the CecilLoader will lock on the <see cref="ModuleDefinition"/> instance
+		/// for every delay-loading operation.
+		/// If you access the Cecil objects directly in your application, you may need to take the same lock.
+		/// </remarks>
+		public bool LazyLoad { get; set; }
+		
+		/// <summary>
+		/// This delegate gets executed whenever an entity was loaded.
+		/// </summary>
+		/// <remarks>
+		/// This callback may be to build a dictionary that maps between
+		/// entities and cecil objects.
+		/// Warning: if delay-loading is used and the type system is accessed by multiple threads,
+		/// the callback may be invoked concurrently on multiple threads.
+		/// </remarks>
+		[CLSCompliant(false)]
+		public Action<IUnresolvedEntity, MemberReference> OnEntityLoaded { get; set; }
+		
+		/// <summary>
+		/// Gets a value indicating whether this instance stores references to the cecil objects.
+		/// </summary>
+		/// <value>
+		/// <c>true</c> if this instance has references to the cecil objects; otherwise, <c>false</c>.
+		/// </value>
+		public bool HasCecilReferences { get { return typeSystemTranslationTable != null; } }
+		#endregion
+		
+		ModuleDefinition currentModule;
+		CecilUnresolvedAssembly currentAssembly;
+		
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class.
+		/// </summary>
+		public CecilLoader()
+		{
+		}
+		
+		/// <summary>
+		/// Initializes a new instance of the <see cref="ICSharpCode.NRefactory.TypeSystem.CecilLoader"/> class.
+		/// </summary>
+		/// <param name='createCecilReferences'>
+		/// If true references to the cecil objects are hold. In this case the cecil loader can do a type system -> cecil mapping.
+		/// </param>
+		[Obsolete("The built-in entity<->cecil mapping is obsolete. Use the OnEntityLoaded callback instead!")]
+		public CecilLoader(bool createCecilReferences) : this()
+		{
+			if (createCecilReferences)
+				typeSystemTranslationTable = new Dictionary<object, object> ();
+		}
+		
+		/// <summary>
+		/// Creates a nested CecilLoader for lazy-loading.
+		/// </summary>
+		private CecilLoader(CecilLoader loader)
+		{
+			// use a shared typeSystemTranslationTable
+			this.typeSystemTranslationTable = loader.typeSystemTranslationTable;
+			this.IncludeInternalMembers = loader.IncludeInternalMembers;
+			this.LazyLoad = loader.LazyLoad;
+			this.OnEntityLoaded = loader.OnEntityLoaded;
+			this.currentModule = loader.currentModule;
+			this.currentAssembly = loader.currentAssembly;
+			// don't use interning - the interning provider is most likely not thread-safe
+			this.interningProvider = InterningProvider.Dummy;
+			// don't use cancellation for delay-loaded members
+		}
+
+		#region Load From AssemblyDefinition
+		/// <summary>
+		/// Loads the assembly definition into a project content.
+		/// </summary>
+		/// <returns>Unresolved type system representing the assembly</returns>
+		[CLSCompliant(false)]
+		public IUnresolvedAssembly LoadAssembly(AssemblyDefinition assemblyDefinition)
+		{
+			if (assemblyDefinition == null)
+				throw new ArgumentNullException("assemblyDefinition");
+			return LoadModule(assemblyDefinition.MainModule);
+		}
+		
+		/// <summary>
+		/// Loads the module definition into a project content.
+		/// </summary>
+		/// <returns>Unresolved type system representing the assembly</returns>
+		[CLSCompliant(false)]
+		public IUnresolvedAssembly LoadModule(ModuleDefinition moduleDefinition)
+		{
+			if (moduleDefinition == null)
+				throw new ArgumentNullException("moduleDefinition");
+			
+			this.currentModule = moduleDefinition;
+			
+			// Read assembly and module attributes
+			IList<IUnresolvedAttribute> assemblyAttributes = new List<IUnresolvedAttribute>();
+			IList<IUnresolvedAttribute> moduleAttributes = new List<IUnresolvedAttribute>();
+			AssemblyDefinition assemblyDefinition = moduleDefinition.Assembly;
+			if (assemblyDefinition != null) {
+				AddAttributes(assemblyDefinition, assemblyAttributes);
+			}
+			AddAttributes(moduleDefinition, moduleAttributes);
+			
+			assemblyAttributes = interningProvider.InternList(assemblyAttributes);
+			moduleAttributes = interningProvider.InternList(moduleAttributes);
+			
+			this.currentAssembly = new CecilUnresolvedAssembly(assemblyDefinition != null ? assemblyDefinition.Name.FullName : moduleDefinition.Name, this.DocumentationProvider);
+			currentAssembly.Location = moduleDefinition.FullyQualifiedName;
+			currentAssembly.AssemblyAttributes.AddRange(assemblyAttributes);
+			currentAssembly.ModuleAttributes.AddRange(assemblyAttributes);
+			
+			// Register type forwarders:
+			foreach (ExportedType type in moduleDefinition.ExportedTypes) {
+				if (type.IsForwarder) {
+					int typeParameterCount;
+					string ns = type.Namespace;
+					string name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(type.Name, out typeParameterCount);
+					ns = interningProvider.Intern(ns);
+					name = interningProvider.Intern(name);
+					var typeRef = new GetClassTypeReference(GetAssemblyReference(type.Scope), ns, name, typeParameterCount);
+					typeRef = interningProvider.Intern(typeRef);
+					var key = new TopLevelTypeName(ns, name, typeParameterCount);
+					currentAssembly.AddTypeForwarder(key, typeRef);
+				}
+			}
+			
+			// Create and register all types:
+			CecilLoader cecilLoaderCloneForLazyLoading = LazyLoad ? new CecilLoader(this) : null;
+			List<TypeDefinition> cecilTypeDefs = new List<TypeDefinition>();
+			List<DefaultUnresolvedTypeDefinition> typeDefs = new List<DefaultUnresolvedTypeDefinition>();
+			foreach (TypeDefinition td in moduleDefinition.Types) {
+				this.CancellationToken.ThrowIfCancellationRequested();
+				if (this.IncludeInternalMembers || (td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public) {
+					string name = td.Name;
+					if (name.Length == 0)
+						continue;
+					
+					if (this.LazyLoad) {
+						var t = new LazyCecilTypeDefinition(cecilLoaderCloneForLazyLoading, td);
+						currentAssembly.AddTypeDefinition(t);
+						RegisterCecilObject(t, td);
+					} else {
+						var t = CreateTopLevelTypeDefinition(td);
+						cecilTypeDefs.Add(td);
+						typeDefs.Add(t);
+						currentAssembly.AddTypeDefinition(t);
+						// The registration will happen after the members are initialized
+					}
+				}
+			}
+			// Initialize the type's members:
+			for (int i = 0; i < typeDefs.Count; i++) {
+				InitTypeDefinition(cecilTypeDefs[i], typeDefs[i]);
+			}
+			
+			AddToTypeSystemTranslationTable(this.currentAssembly, assemblyDefinition);
+			// Freezing the assembly here is important:
+			// otherwise it will be frozen when a compilation is first created
+			// from it. But freezing has the effect of changing some collection instances
+			// (to ReadOnlyCollection). This hidden mutation was causing a crash
+			// when the FastSerializer was saving the assembly at the same time as
+			// the first compilation was created from it.
+			// By freezing the assembly now, we ensure it is usable on multiple
+			// threads without issues.
+			currentAssembly.Freeze();
+			
+			var result = this.currentAssembly;
+			this.currentAssembly = null;
+			this.currentModule = null;
+			return result;
+		}
+		
+		/// <summary>
+		/// Sets the current module.
+		/// This causes ReadTypeReference() to use <see cref="DefaultAssemblyReference.CurrentAssembly"/> for references
+		/// in that module.
+		/// </summary>
+		[CLSCompliant(false)]
+		public void SetCurrentModule(ModuleDefinition module)
+		{
+			this.currentModule = module;
+		}
+		
+		/// <summary>
+		/// Loads a type from Cecil.
+		/// </summary>
+		/// <param name="typeDefinition">The Cecil TypeDefinition.</param>
+		/// <returns>ITypeDefinition representing the Cecil type.</returns>
+		[CLSCompliant(false)]
+		public IUnresolvedTypeDefinition LoadType(TypeDefinition typeDefinition)
+		{
+			if (typeDefinition == null)
+				throw new ArgumentNullException("typeDefinition");
+			var td = CreateTopLevelTypeDefinition(typeDefinition);
+			InitTypeDefinition(typeDefinition, td);
+			return td;
+		}
+		#endregion
+		
+		#region IUnresolvedAssembly implementation
+		[Serializable, FastSerializerVersion(cecilLoaderVersion)]
+		sealed class CecilUnresolvedAssembly : DefaultUnresolvedAssembly, IDocumentationProvider
+		{
+			readonly IDocumentationProvider documentationProvider;
+			
+			public CecilUnresolvedAssembly(string fullAssemblyName, IDocumentationProvider documentationProvider)
+				: base(fullAssemblyName)
+			{
+				this.documentationProvider = documentationProvider;
+			}
+			
+			DocumentationComment IDocumentationProvider.GetDocumentation(IEntity entity)
+			{
+				if (documentationProvider != null)
+					return documentationProvider.GetDocumentation(entity);
+				else
+					return null;
+			}
+		}
+		#endregion
+		
+		#region Load Assembly From Disk
+		public override IUnresolvedAssembly LoadAssemblyFile(string fileName)
+		{
+			if (fileName == null)
+				throw new ArgumentNullException("fileName");
+			var param = new ReaderParameters { AssemblyResolver = new DummyAssemblyResolver() };
+			ModuleDefinition module = ModuleDefinition.ReadModule(fileName, param);
+			return LoadModule(module);
+		}
+		
+		// used to prevent Cecil from loading referenced assemblies
+		sealed class DummyAssemblyResolver : IAssemblyResolver
+		{
+			public AssemblyDefinition Resolve(AssemblyNameReference name)
+			{
+				return null;
+			}
+			
+			public AssemblyDefinition Resolve(string fullName)
+			{
+				return null;
+			}
+			
+			public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
+			{
+				return null;
+			}
+			
+			public AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
+			{
+				return null;
+			}
+		}
+		#endregion
+		
+		#region Read Type Reference
+		/// <summary>
+		/// Reads a type reference.
+		/// </summary>
+		/// <param name="type">The Cecil type reference that should be converted into
+		/// a type system type reference.</param>
+		/// <param name="typeAttributes">Attributes associated with the Cecil type reference.
+		/// This is used to support the 'dynamic' type.</param>
+		[CLSCompliant(false)]
+		public ITypeReference ReadTypeReference(TypeReference type, ICustomAttributeProvider typeAttributes = null)
+		{
+			int typeIndex = 0;
+			return CreateType(type, typeAttributes, ref typeIndex);
+		}
+		
+		ITypeReference CreateType(TypeReference type, ICustomAttributeProvider typeAttributes, ref int typeIndex)
+		{
+			while (type is OptionalModifierType || type is RequiredModifierType) {
+				type = ((TypeSpecification)type).ElementType;
+			}
+			if (type == null) {
+				return SpecialType.UnknownType;
+			}
+			
+			if (type is Mono.Cecil.ByReferenceType) {
+				typeIndex++;
+				return interningProvider.Intern(
+					new ByReferenceTypeReference(
+						CreateType(
+							(type as Mono.Cecil.ByReferenceType).ElementType,
+							typeAttributes, ref typeIndex)));
+			} else if (type is Mono.Cecil.PointerType) {
+				typeIndex++;
+				return interningProvider.Intern(
+					new PointerTypeReference(
+						CreateType(
+							(type as Mono.Cecil.PointerType).ElementType,
+							typeAttributes, ref typeIndex)));
+			} else if (type is Mono.Cecil.ArrayType) {
+				typeIndex++;
+				return interningProvider.Intern(
+					new ArrayTypeReference(
+						CreateType(
+							(type as Mono.Cecil.ArrayType).ElementType,
+							typeAttributes, ref typeIndex),
+						(type as Mono.Cecil.ArrayType).Rank));
+			} else if (type is GenericInstanceType) {
+				GenericInstanceType gType = (GenericInstanceType)type;
+				ITypeReference baseType = CreateType(gType.ElementType, typeAttributes, ref typeIndex);
+				ITypeReference[] para = new ITypeReference[gType.GenericArguments.Count];
+				for (int i = 0; i < para.Length; ++i) {
+					typeIndex++;
+					para[i] = CreateType(gType.GenericArguments[i], typeAttributes, ref typeIndex);
+				}
+				return interningProvider.Intern(new ParameterizedTypeReference(baseType, para));
+			} else if (type is GenericParameter) {
+				GenericParameter typeGP = (GenericParameter)type;
+				return TypeParameterReference.Create(typeGP.Owner is MethodDefinition ? SymbolKind.Method : SymbolKind.TypeDefinition, typeGP.Position);
+			} else if (type.IsNested) {
+				ITypeReference typeRef = CreateType(type.DeclaringType, typeAttributes, ref typeIndex);
+				int partTypeParameterCount;
+				string namepart = ReflectionHelper.SplitTypeParameterCountFromReflectionName(type.Name, out partTypeParameterCount);
+				namepart = interningProvider.Intern(namepart);
+				return interningProvider.Intern(new NestedTypeReference(typeRef, namepart, partTypeParameterCount));
+			} else {
+				string ns = interningProvider.Intern(type.Namespace ?? string.Empty);
+				string name = type.Name;
+				if (name == null)
+					throw new InvalidOperationException("type.Name returned null. Type: " + type.ToString());
+				
+				if (name == "Object" && ns == "System" && HasDynamicAttribute(typeAttributes, typeIndex)) {
+					return SpecialType.Dynamic;
+				} else {
+					int typeParameterCount;
+					name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(name, out typeParameterCount);
+					name = interningProvider.Intern(name);
+					if (currentAssembly != null) {
+						IUnresolvedTypeDefinition c = currentAssembly.GetTypeDefinition(ns, name, typeParameterCount);
+						if (c != null)
+							return c;
+					}
+					return interningProvider.Intern(new GetClassTypeReference(GetAssemblyReference(type.Scope), ns, name, typeParameterCount));
+				}
+			}
+		}
+		
+		IAssemblyReference GetAssemblyReference(IMetadataScope scope)
+		{
+			if (scope == null || scope == currentModule)
+				return DefaultAssemblyReference.CurrentAssembly;
+			else
+				return interningProvider.Intern(new DefaultAssemblyReference(scope.Name));
+		}
+		
+		static bool HasDynamicAttribute(ICustomAttributeProvider attributeProvider, int typeIndex)
+		{
+			if (attributeProvider == null || !attributeProvider.HasCustomAttributes)
+				return false;
+			foreach (CustomAttribute a in attributeProvider.CustomAttributes) {
+				TypeReference type = a.AttributeType;
+				if (type.Name == "DynamicAttribute" && type.Namespace == "System.Runtime.CompilerServices") {
+					if (a.ConstructorArguments.Count == 1) {
+						CustomAttributeArgument[] values = a.ConstructorArguments[0].Value as CustomAttributeArgument[];
+						if (values != null && typeIndex < values.Length && values[typeIndex].Value is bool)
+							return (bool)values[typeIndex].Value;
+					}
+					return true;
+				}
+			}
+			return false;
+		}
+		#endregion
+		
+		#region Read Attributes
+		#region Assembly Attributes
+		static readonly ITypeReference assemblyVersionAttributeTypeRef = typeof(System.Reflection.AssemblyVersionAttribute).ToTypeReference();
+		
+		void AddAttributes(AssemblyDefinition assembly, IList<IUnresolvedAttribute> outputList)
+		{
+			if (assembly.HasCustomAttributes) {
+				AddCustomAttributes(assembly.CustomAttributes, outputList);
+			}
+			if (assembly.HasSecurityDeclarations) {
+				AddSecurityAttributes(assembly.SecurityDeclarations, outputList);
+			}
+			
+			// AssemblyVersionAttribute
+			if (assembly.Name.Version != null) {
+				var assemblyVersion = new DefaultUnresolvedAttribute(assemblyVersionAttributeTypeRef, new[] { KnownTypeReference.String });
+				assemblyVersion.PositionalArguments.Add(CreateSimpleConstantValue(KnownTypeReference.String, assembly.Name.Version.ToString()));
+				outputList.Add(interningProvider.Intern(assemblyVersion));
+			}
+		}
+		
+		IConstantValue CreateSimpleConstantValue(ITypeReference type, object value)
+		{
+			return interningProvider.Intern(new SimpleConstantValue(type, interningProvider.InternValue(value)));
+		}
+		#endregion
+		
+		#region Module Attributes
+		void AddAttributes(ModuleDefinition module, IList<IUnresolvedAttribute> outputList)
+		{
+			if (module.HasCustomAttributes) {
+				AddCustomAttributes(module.CustomAttributes, outputList);
+			}
+		}
+		#endregion
+		
+		#region Parameter Attributes
+		static readonly IUnresolvedAttribute inAttribute = new DefaultUnresolvedAttribute(typeof(InAttribute).ToTypeReference());
+		static readonly IUnresolvedAttribute outAttribute = new DefaultUnresolvedAttribute(typeof(OutAttribute).ToTypeReference());
+		
+		void AddAttributes(ParameterDefinition parameter, DefaultUnresolvedParameter targetParameter)
+		{
+			if (!targetParameter.IsOut) {
+				if (parameter.IsIn)
+					targetParameter.Attributes.Add(inAttribute);
+				if (parameter.IsOut)
+					targetParameter.Attributes.Add(outAttribute);
+			}
+			if (parameter.HasCustomAttributes) {
+				AddCustomAttributes(parameter.CustomAttributes, targetParameter.Attributes);
+			}
+			if (parameter.HasMarshalInfo) {
+				targetParameter.Attributes.Add(ConvertMarshalInfo(parameter.MarshalInfo));
+			}
+		}
+		#endregion
+		
+		#region Method Attributes
+		static readonly ITypeReference dllImportAttributeTypeRef = typeof(DllImportAttribute).ToTypeReference();
+		static readonly SimpleConstantValue trueValue = new SimpleConstantValue(KnownTypeReference.Boolean, true);
+		static readonly SimpleConstantValue falseValue = new SimpleConstantValue(KnownTypeReference.Boolean, false);
+		static readonly ITypeReference callingConventionTypeRef = typeof(CallingConvention).ToTypeReference();
+		static readonly IUnresolvedAttribute preserveSigAttribute = new DefaultUnresolvedAttribute(typeof(PreserveSigAttribute).ToTypeReference());
+		static readonly ITypeReference methodImplAttributeTypeRef = typeof(MethodImplAttribute).ToTypeReference();
+		static readonly ITypeReference methodImplOptionsTypeRef = typeof(MethodImplOptions).ToTypeReference();
+		
+		static bool HasAnyAttributes(MethodDefinition methodDefinition)
+		{
+			if (methodDefinition.HasPInvokeInfo)
+				return true;
+			if ((methodDefinition.ImplAttributes & ~MethodImplAttributes.CodeTypeMask) != 0)
+				return true;
+			if (methodDefinition.MethodReturnType.HasFieldMarshal)
+				return true;
+			return methodDefinition.HasCustomAttributes || methodDefinition.MethodReturnType.HasCustomAttributes;
+		}
+		
+		void AddAttributes(MethodDefinition methodDefinition, IList<IUnresolvedAttribute> attributes, IList<IUnresolvedAttribute> returnTypeAttributes)
+		{
+			MethodImplAttributes implAttributes = methodDefinition.ImplAttributes & ~MethodImplAttributes.CodeTypeMask;
+			
+			#region DllImportAttribute
+			if (methodDefinition.HasPInvokeInfo && methodDefinition.PInvokeInfo != null) {
+				PInvokeInfo info = methodDefinition.PInvokeInfo;
+				var dllImport = new DefaultUnresolvedAttribute(dllImportAttributeTypeRef, new[] { KnownTypeReference.String });
+				dllImport.PositionalArguments.Add(CreateSimpleConstantValue(KnownTypeReference.String, info.Module.Name));
+				
+				if (info.IsBestFitDisabled)
+					dllImport.AddNamedFieldArgument("BestFitMapping", falseValue);
+				if (info.IsBestFitEnabled)
+					dllImport.AddNamedFieldArgument("BestFitMapping", trueValue);
+				
+				CallingConvention callingConvention;
+				switch (info.Attributes & PInvokeAttributes.CallConvMask) {
+					case (PInvokeAttributes)0:
+						Debug.WriteLine ("P/Invoke calling convention not set on:" + methodDefinition.FullName);
+						callingConvention = 0;
+						break;
+					case PInvokeAttributes.CallConvCdecl:
+						callingConvention = CallingConvention.Cdecl;
+						break;
+					case PInvokeAttributes.CallConvFastcall:
+						callingConvention = CallingConvention.FastCall;
+						break;
+					case PInvokeAttributes.CallConvStdCall:
+						callingConvention = CallingConvention.StdCall;
+						break;
+					case PInvokeAttributes.CallConvThiscall:
+						callingConvention = CallingConvention.ThisCall;
+						break;
+					case PInvokeAttributes.CallConvWinapi:
+						callingConvention = CallingConvention.Winapi;
+						break;
+					default:
+						throw new NotSupportedException("unknown calling convention");
+				}
+				if (callingConvention != CallingConvention.Winapi)
+					dllImport.AddNamedFieldArgument("CallingConvention", CreateSimpleConstantValue(callingConventionTypeRef, (int)callingConvention));
+				
+				CharSet charSet = CharSet.None;
+				switch (info.Attributes & PInvokeAttributes.CharSetMask) {
+					case PInvokeAttributes.CharSetAnsi:
+						charSet = CharSet.Ansi;
+						break;
+					case PInvokeAttributes.CharSetAuto:
+						charSet = CharSet.Auto;
+						break;
+					case PInvokeAttributes.CharSetUnicode:
+						charSet = CharSet.Unicode;
+						break;
+				}
+				if (charSet != CharSet.None)
+					dllImport.AddNamedFieldArgument("CharSet", CreateSimpleConstantValue(charSetTypeRef, (int)charSet));
+				
+				if (!string.IsNullOrEmpty(info.EntryPoint) && info.EntryPoint != methodDefinition.Name)
+					dllImport.AddNamedFieldArgument("EntryPoint", CreateSimpleConstantValue(KnownTypeReference.String, info.EntryPoint));
+				
+				if (info.IsNoMangle)
+					dllImport.AddNamedFieldArgument("ExactSpelling", trueValue);
+				
+				if ((implAttributes & MethodImplAttributes.PreserveSig) == MethodImplAttributes.PreserveSig)
+					implAttributes &= ~MethodImplAttributes.PreserveSig;
+				else
+					dllImport.AddNamedFieldArgument("PreserveSig", falseValue);
+				
+				if (info.SupportsLastError)
+					dllImport.AddNamedFieldArgument("SetLastError", trueValue);
+				
+				if (info.IsThrowOnUnmappableCharDisabled)
+					dllImport.AddNamedFieldArgument("ThrowOnUnmappableChar", falseValue);
+				if (info.IsThrowOnUnmappableCharEnabled)
+					dllImport.AddNamedFieldArgument("ThrowOnUnmappableChar", trueValue);
+				
+				attributes.Add(interningProvider.Intern(dllImport));
+			}
+			#endregion
+			
+			#region PreserveSigAttribute
+			if (implAttributes == MethodImplAttributes.PreserveSig) {
+				attributes.Add(preserveSigAttribute);
+				implAttributes = 0;
+			}
+			#endregion
+			
+			#region MethodImplAttribute
+			if (implAttributes != 0) {
+				var methodImpl = new DefaultUnresolvedAttribute(methodImplAttributeTypeRef, new[] { methodImplOptionsTypeRef });
+				methodImpl.PositionalArguments.Add(CreateSimpleConstantValue(methodImplOptionsTypeRef, (int)implAttributes));
+				attributes.Add(interningProvider.Intern(methodImpl));
+			}
+			#endregion
+			
+			if (methodDefinition.HasCustomAttributes) {
+				AddCustomAttributes(methodDefinition.CustomAttributes, attributes);
+			}
+			if (methodDefinition.HasSecurityDeclarations) {
+				AddSecurityAttributes(methodDefinition.SecurityDeclarations, attributes);
+			}
+			if (methodDefinition.MethodReturnType.HasMarshalInfo) {
+				returnTypeAttributes.Add(ConvertMarshalInfo(methodDefinition.MethodReturnType.MarshalInfo));
+			}
+			if (methodDefinition.MethodReturnType.HasCustomAttributes) {
+				AddCustomAttributes(methodDefinition.MethodReturnType.CustomAttributes, returnTypeAttributes);
+			}
+		}
+		#endregion
+		
+		#region Type Attributes
+		static readonly DefaultUnresolvedAttribute serializableAttribute = new DefaultUnresolvedAttribute(typeof(SerializableAttribute).ToTypeReference());
+		static readonly DefaultUnresolvedAttribute comImportAttribute = new DefaultUnresolvedAttribute(typeof(ComImportAttribute).ToTypeReference());
+		static readonly ITypeReference structLayoutAttributeTypeRef = typeof(StructLayoutAttribute).ToTypeReference();
+		static readonly ITypeReference layoutKindTypeRef = typeof(LayoutKind).ToTypeReference();
+		static readonly ITypeReference charSetTypeRef = typeof(CharSet).ToTypeReference();
+		
+		void AddAttributes(TypeDefinition typeDefinition, IUnresolvedTypeDefinition targetEntity)
+		{
+			// SerializableAttribute
+			if (typeDefinition.IsSerializable)
+				targetEntity.Attributes.Add(serializableAttribute);
+			
+			// ComImportAttribute
+			if (typeDefinition.IsImport)
+				targetEntity.Attributes.Add(comImportAttribute);
+			
+			#region StructLayoutAttribute
+			LayoutKind layoutKind = LayoutKind.Auto;
+			switch (typeDefinition.Attributes & TypeAttributes.LayoutMask) {
+				case TypeAttributes.SequentialLayout:
+					layoutKind = LayoutKind.Sequential;
+					break;
+				case TypeAttributes.ExplicitLayout:
+					layoutKind = LayoutKind.Explicit;
+					break;
+			}
+			CharSet charSet = CharSet.None;
+			switch (typeDefinition.Attributes & TypeAttributes.StringFormatMask) {
+				case TypeAttributes.AnsiClass:
+					charSet = CharSet.Ansi;
+					break;
+				case TypeAttributes.AutoClass:
+					charSet = CharSet.Auto;
+					break;
+				case TypeAttributes.UnicodeClass:
+					charSet = CharSet.Unicode;
+					break;
+			}
+			LayoutKind defaultLayoutKind = (typeDefinition.IsValueType && !typeDefinition.IsEnum) ? LayoutKind.Sequential: LayoutKind.Auto;
+			if (layoutKind != defaultLayoutKind || charSet != CharSet.Ansi || typeDefinition.PackingSize > 0 || typeDefinition.ClassSize > 0) {
+				DefaultUnresolvedAttribute structLayout = new DefaultUnresolvedAttribute(structLayoutAttributeTypeRef, new[] { layoutKindTypeRef });
+				structLayout.PositionalArguments.Add(CreateSimpleConstantValue(layoutKindTypeRef, (int)layoutKind));
+				if (charSet != CharSet.Ansi) {
+					structLayout.AddNamedFieldArgument("CharSet", CreateSimpleConstantValue(charSetTypeRef, (int)charSet));
+				}
+				if (typeDefinition.PackingSize > 0) {
+					structLayout.AddNamedFieldArgument("Pack", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)typeDefinition.PackingSize));
+				}
+				if (typeDefinition.ClassSize > 0) {
+					structLayout.AddNamedFieldArgument("Size", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)typeDefinition.ClassSize));
+				}
+				targetEntity.Attributes.Add(interningProvider.Intern(structLayout));
+			}
+			#endregion
+			
+			if (typeDefinition.HasCustomAttributes) {
+				AddCustomAttributes(typeDefinition.CustomAttributes, targetEntity.Attributes);
+			}
+			if (typeDefinition.HasSecurityDeclarations) {
+				AddSecurityAttributes(typeDefinition.SecurityDeclarations, targetEntity.Attributes);
+			}
+		}
+		#endregion
+		
+		#region Field Attributes
+		static readonly ITypeReference fieldOffsetAttributeTypeRef = typeof(FieldOffsetAttribute).ToTypeReference();
+		static readonly IUnresolvedAttribute nonSerializedAttribute = new DefaultUnresolvedAttribute(typeof(NonSerializedAttribute).ToTypeReference());
+		
+		void AddAttributes(FieldDefinition fieldDefinition, IUnresolvedEntity targetEntity)
+		{
+			// FieldOffsetAttribute
+			if (fieldDefinition.HasLayoutInfo) {
+				DefaultUnresolvedAttribute fieldOffset = new DefaultUnresolvedAttribute(fieldOffsetAttributeTypeRef, new[] { KnownTypeReference.Int32 });
+				fieldOffset.PositionalArguments.Add(CreateSimpleConstantValue(KnownTypeReference.Int32, fieldDefinition.Offset));
+				targetEntity.Attributes.Add(interningProvider.Intern(fieldOffset));
+			}
+			
+			// NonSerializedAttribute
+			if (fieldDefinition.IsNotSerialized) {
+				targetEntity.Attributes.Add(nonSerializedAttribute);
+			}
+			
+			if (fieldDefinition.HasMarshalInfo) {
+				targetEntity.Attributes.Add(ConvertMarshalInfo(fieldDefinition.MarshalInfo));
+			}
+			
+			if (fieldDefinition.HasCustomAttributes) {
+				AddCustomAttributes(fieldDefinition.CustomAttributes, targetEntity.Attributes);
+			}
+		}
+		#endregion
+		
+		#region Event Attributes
+		void AddAttributes(EventDefinition eventDefinition, IUnresolvedEntity targetEntity)
+		{
+			if (eventDefinition.HasCustomAttributes) {
+				AddCustomAttributes(eventDefinition.CustomAttributes, targetEntity.Attributes);
+			}
+		}
+		#endregion
+		
+		#region Property Attributes
+		void AddAttributes(PropertyDefinition propertyDefinition, IUnresolvedEntity targetEntity)
+		{
+			if (propertyDefinition.HasCustomAttributes) {
+				AddCustomAttributes(propertyDefinition.CustomAttributes, targetEntity.Attributes);
+			}
+		}
+		#endregion
+		
+		#region MarshalAsAttribute (ConvertMarshalInfo)
+		static readonly ITypeReference marshalAsAttributeTypeRef = typeof(MarshalAsAttribute).ToTypeReference();
+		static readonly ITypeReference unmanagedTypeTypeRef = typeof(UnmanagedType).ToTypeReference();
+		
+		IUnresolvedAttribute ConvertMarshalInfo(MarshalInfo marshalInfo)
+		{
+			DefaultUnresolvedAttribute attr = new DefaultUnresolvedAttribute(marshalAsAttributeTypeRef, new[] { unmanagedTypeTypeRef });
+			attr.PositionalArguments.Add(CreateSimpleConstantValue(unmanagedTypeTypeRef, (int)marshalInfo.NativeType));
+			
+			FixedArrayMarshalInfo fami = marshalInfo as FixedArrayMarshalInfo;
+			if (fami != null) {
+				attr.AddNamedFieldArgument("SizeConst", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)fami.Size));
+				if (fami.ElementType != NativeType.None)
+					attr.AddNamedFieldArgument("ArraySubType", CreateSimpleConstantValue(unmanagedTypeTypeRef, (int)fami.ElementType));
+			}
+			SafeArrayMarshalInfo sami = marshalInfo as SafeArrayMarshalInfo;
+			if (sami != null && sami.ElementType != VariantType.None) {
+				attr.AddNamedFieldArgument("SafeArraySubType", CreateSimpleConstantValue(typeof(VarEnum).ToTypeReference(), (int)sami.ElementType));
+			}
+			ArrayMarshalInfo ami = marshalInfo as ArrayMarshalInfo;
+			if (ami != null) {
+				if (ami.ElementType != NativeType.Max)
+					attr.AddNamedFieldArgument("ArraySubType", CreateSimpleConstantValue(unmanagedTypeTypeRef, (int)ami.ElementType));
+				if (ami.Size >= 0)
+					attr.AddNamedFieldArgument("SizeConst", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)ami.Size));
+				if (ami.SizeParameterMultiplier != 0 && ami.SizeParameterIndex >= 0)
+					attr.AddNamedFieldArgument("SizeParamIndex", CreateSimpleConstantValue(KnownTypeReference.Int16, (short)ami.SizeParameterIndex));
+			}
+			CustomMarshalInfo cmi = marshalInfo as CustomMarshalInfo;
+			if (cmi != null) {
+				if (cmi.ManagedType != null)
+					attr.AddNamedFieldArgument("MarshalType", CreateSimpleConstantValue(KnownTypeReference.String, cmi.ManagedType.FullName));
+				if (!string.IsNullOrEmpty(cmi.Cookie))
+					attr.AddNamedFieldArgument("MarshalCookie", CreateSimpleConstantValue(KnownTypeReference.String, cmi.Cookie));
+			}
+			FixedSysStringMarshalInfo fssmi = marshalInfo as FixedSysStringMarshalInfo;
+			if (fssmi != null) {
+				attr.AddNamedFieldArgument("SizeConst", CreateSimpleConstantValue(KnownTypeReference.Int32, (int)fssmi.Size));
+			}
+			
+			return InterningProvider.Intern(attr);
+		}
+		#endregion
+		
+		#region Custom Attributes (ReadAttribute)
+		void AddCustomAttributes(Mono.Collections.Generic.Collection<CustomAttribute> attributes, IList<IUnresolvedAttribute> targetCollection)
+		{
+			foreach (var cecilAttribute in attributes) {
+				TypeReference type = cecilAttribute.AttributeType;
+				if (type.Namespace == "System.Runtime.CompilerServices") {
+					if (type.Name == "DynamicAttribute" || type.Name == "ExtensionAttribute" || type.Name == "DecimalConstantAttribute")
+						continue;
+				} else if (type.Name == "ParamArrayAttribute" && type.Namespace == "System") {
+					continue;
+				}
+				targetCollection.Add(ReadAttribute(cecilAttribute));
+			}
+		}
+		
+		[CLSCompliant(false)]
+		public IUnresolvedAttribute ReadAttribute(CustomAttribute attribute)
+		{
+			if (attribute == null)
+				throw new ArgumentNullException("attribute");
+			MethodReference ctor = attribute.Constructor;
+			ITypeReference attributeType = ReadTypeReference(attribute.AttributeType);
+			IList<ITypeReference> ctorParameterTypes = EmptyList<ITypeReference>.Instance;
+			if (ctor.HasParameters) {
+				ctorParameterTypes = new ITypeReference[ctor.Parameters.Count];
+				for (int i = 0; i < ctorParameterTypes.Count; i++) {
+					ctorParameterTypes[i] = ReadTypeReference(ctor.Parameters[i].ParameterType);
+				}
+				ctorParameterTypes = interningProvider.InternList(ctorParameterTypes);
+			}
+			return interningProvider.Intern(new UnresolvedAttributeBlob(attributeType, ctorParameterTypes, attribute.GetBlob()));
+		}
+		#endregion
+		
+		#region Security Attributes
+		/// <summary>
+		/// Reads a security declaration.
+		/// </summary>
+		[CLSCompliant(false)]
+		public IList<IUnresolvedAttribute> ReadSecurityDeclaration(SecurityDeclaration secDecl)
+		{
+			if (secDecl == null)
+				throw new ArgumentNullException("secDecl");
+			var result = new List<IUnresolvedAttribute>();
+			AddSecurityAttributes(secDecl, result);
+			return result;
+		}
+		
+		void AddSecurityAttributes(Mono.Collections.Generic.Collection<SecurityDeclaration> securityDeclarations, IList<IUnresolvedAttribute> targetCollection)
+		{
+			foreach (var secDecl in securityDeclarations) {
+				AddSecurityAttributes(secDecl, targetCollection);
+			}
+		}
+		
+		void AddSecurityAttributes(SecurityDeclaration secDecl, IList<IUnresolvedAttribute> targetCollection)
+		{
+			byte[] blob;
+			try {
+				blob = secDecl.GetBlob();
+			} catch (NotSupportedException) {
+				return; // https://github.com/icsharpcode/SharpDevelop/issues/284
+			}
+			var blobSecDecl = new UnresolvedSecurityDeclarationBlob((int)secDecl.Action, blob);
+			targetCollection.AddRange(blobSecDecl.UnresolvedAttributes);
+		}
+		#endregion
+		#endregion
+		
+		#region Read Type Definition
+		DefaultUnresolvedTypeDefinition CreateTopLevelTypeDefinition(TypeDefinition typeDefinition)
+		{
+			string name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(typeDefinition.Name);
+			var td = new DefaultUnresolvedTypeDefinition(typeDefinition.Namespace, name);
+			if (typeDefinition.HasGenericParameters)
+				InitTypeParameters(typeDefinition, td.TypeParameters);
+			return td;
+		}
+		
+		static void InitTypeParameters(TypeDefinition typeDefinition, IList<IUnresolvedTypeParameter> typeParameters)
+		{
+			// Type parameters are initialized within the constructor so that the class can be put into the type storage
+			// before the rest of the initialization runs - this allows it to be available for early binding as soon as possible.
+			for (int i = 0; i < typeDefinition.GenericParameters.Count; i++) {
+				if (typeDefinition.GenericParameters[i].Position != i)
+					throw new InvalidOperationException("g.Position != i");
+				typeParameters.Add(new DefaultUnresolvedTypeParameter(
+					SymbolKind.TypeDefinition, i, typeDefinition.GenericParameters[i].Name));
+			}
+		}
+		
+		void InitTypeParameterConstraints(TypeDefinition typeDefinition, IList<IUnresolvedTypeParameter> typeParameters)
+		{
+			for (int i = 0; i < typeParameters.Count; i++) {
+				var tp = (DefaultUnresolvedTypeParameter)typeParameters[i];
+				AddConstraints(tp, typeDefinition.GenericParameters[i]);
+				tp.ApplyInterningProvider(interningProvider);
+			}
+		}
+		
+		void InitTypeDefinition(TypeDefinition typeDefinition, DefaultUnresolvedTypeDefinition td)
+		{
+			td.Kind = GetTypeKind(typeDefinition);
+			InitTypeModifiers(typeDefinition, td);
+			InitTypeParameterConstraints(typeDefinition, td.TypeParameters);
+			
+			// nested types can be initialized only after generic parameters were created
+			InitNestedTypes(typeDefinition, td, td.NestedTypes);
+			AddAttributes(typeDefinition, td);
+			td.HasExtensionMethods = HasExtensionAttribute(typeDefinition);
+			
+			InitBaseTypes(typeDefinition, td.BaseTypes);
+			
+			td.AddDefaultConstructorIfRequired = (td.Kind == TypeKind.Struct || td.Kind == TypeKind.Enum);
+			InitMembers(typeDefinition, td, td.Members);
+			td.ApplyInterningProvider(interningProvider);
+			td.Freeze();
+			RegisterCecilObject(td, typeDefinition);
+		}
+		
+		void InitBaseTypes(TypeDefinition typeDefinition, IList<ITypeReference> baseTypes)
+		{
+			// set base classes
+			if (typeDefinition.IsEnum) {
+				foreach (FieldDefinition enumField in typeDefinition.Fields) {
+					if (!enumField.IsStatic) {
+						baseTypes.Add(ReadTypeReference(enumField.FieldType));
+						break;
+					}
+				}
+			} else {
+				if (typeDefinition.BaseType != null) {
+					baseTypes.Add(ReadTypeReference(typeDefinition.BaseType));
+				}
+				if (typeDefinition.HasInterfaces) {
+					foreach (TypeReference iface in typeDefinition.Interfaces) {
+						baseTypes.Add(ReadTypeReference(iface));
+					}
+				}
+			}
+		}
+		
+		void InitNestedTypes(TypeDefinition typeDefinition, IUnresolvedTypeDefinition declaringTypeDefinition, IList<IUnresolvedTypeDefinition> nestedTypes)
+		{
+			if (!typeDefinition.HasNestedTypes)
+				return;
+			foreach (TypeDefinition nestedTypeDef in typeDefinition.NestedTypes) {
+				TypeAttributes visibility = nestedTypeDef.Attributes & TypeAttributes.VisibilityMask;
+				if (this.IncludeInternalMembers
+				    || visibility == TypeAttributes.NestedPublic
+				    || visibility == TypeAttributes.NestedFamily
+				    || visibility == TypeAttributes.NestedFamORAssem)
+				{
+					string name = nestedTypeDef.Name;
+					int pos = name.LastIndexOf('/');
+					if (pos > 0)
+						name = name.Substring(pos + 1);
+					name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(name);
+					var nestedType = new DefaultUnresolvedTypeDefinition(declaringTypeDefinition, name);
+					InitTypeParameters(nestedTypeDef, nestedType.TypeParameters);
+					nestedTypes.Add(nestedType);
+					InitTypeDefinition(nestedTypeDef, nestedType);
+				}
+			}
+		}
+		
+		static TypeKind GetTypeKind(TypeDefinition typeDefinition)
+		{
+			// set classtype
+			if (typeDefinition.IsInterface) {
+				return TypeKind.Interface;
+			} else if (typeDefinition.IsEnum) {
+				return TypeKind.Enum;
+			} else if (typeDefinition.IsValueType) {
+				return TypeKind.Struct;
+			} else if (IsDelegate(typeDefinition)) {
+				return TypeKind.Delegate;
+			} else if (IsModule(typeDefinition)) {
+				return TypeKind.Module;
+			} else {
+				return TypeKind.Class;
+			}
+		}
+		
+		static void InitTypeModifiers(TypeDefinition typeDefinition, AbstractUnresolvedEntity td)
+		{
+			td.IsSealed = typeDefinition.IsSealed;
+			td.IsAbstract = typeDefinition.IsAbstract;
+			switch (typeDefinition.Attributes & TypeAttributes.VisibilityMask) {
+				case TypeAttributes.NotPublic:
+				case TypeAttributes.NestedAssembly:
+					td.Accessibility = Accessibility.Internal;
+					break;
+				case TypeAttributes.Public:
+				case TypeAttributes.NestedPublic:
+					td.Accessibility = Accessibility.Public;
+					break;
+				case TypeAttributes.NestedPrivate:
+					td.Accessibility = Accessibility.Private;
+					break;
+				case TypeAttributes.NestedFamily:
+					td.Accessibility = Accessibility.Protected;
+					break;
+				case TypeAttributes.NestedFamANDAssem:
+					td.Accessibility = Accessibility.ProtectedAndInternal;
+					break;
+				case TypeAttributes.NestedFamORAssem:
+					td.Accessibility = Accessibility.ProtectedOrInternal;
+					break;
+			}
+		}
+		
+		static bool IsDelegate(TypeDefinition type)
+		{
+			if (type.BaseType != null && type.BaseType.Namespace == "System") {
+				if (type.BaseType.Name == "MulticastDelegate")
+					return true;
+				if (type.BaseType.Name == "Delegate" && type.Name != "MulticastDelegate")
+					return true;
+			}
+			return false;
+		}
+		
+		static bool IsModule(TypeDefinition type)
+		{
+			if (!type.HasCustomAttributes)
+				return false;
+			foreach (var att in type.CustomAttributes) {
+				if (att.AttributeType.FullName == "Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute"
+				    || att.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGlobalScopeAttribute")
+				{
+					return true;
+				}
+			}
+			return false;
+		}
+		
+		void InitMembers(TypeDefinition typeDefinition, IUnresolvedTypeDefinition td, IList<IUnresolvedMember> members)
+		{
+			if (typeDefinition.HasMethods) {
+				foreach (MethodDefinition method in typeDefinition.Methods) {
+					if (IsVisible(method.Attributes) && !IsAccessor(method.SemanticsAttributes)) {
+						SymbolKind type = SymbolKind.Method;
+						if (method.IsSpecialName) {
+							if (method.IsConstructor)
+								type = SymbolKind.Constructor;
+							else if (method.Name.StartsWith("op_", StringComparison.Ordinal))
+								type = SymbolKind.Operator;
+						}
+						members.Add(ReadMethod(method, td, type));
+					}
+				}
+			}
+			if (typeDefinition.HasFields) {
+				foreach (FieldDefinition field in typeDefinition.Fields) {
+					if (IsVisible(field.Attributes) && !field.IsSpecialName) {
+						members.Add(ReadField(field, td));
+					}
+				}
+			}
+			if (typeDefinition.HasProperties) {
+				string defaultMemberName = null;
+				var defaultMemberAttribute = typeDefinition.CustomAttributes.FirstOrDefault(
+					a => a.AttributeType.FullName == typeof(System.Reflection.DefaultMemberAttribute).FullName);
+				if (defaultMemberAttribute != null && defaultMemberAttribute.ConstructorArguments.Count == 1) {
+					defaultMemberName = defaultMemberAttribute.ConstructorArguments[0].Value as string;
+				}
+				foreach (PropertyDefinition property in typeDefinition.Properties) {
+					bool getterVisible = property.GetMethod != null && IsVisible(property.GetMethod.Attributes);
+					bool setterVisible = property.SetMethod != null && IsVisible(property.SetMethod.Attributes);
+					if (getterVisible || setterVisible) {
+						SymbolKind type = SymbolKind.Property;
+						if (property.HasParameters) {
+							// Try to detect indexer:
+							if (property.Name == defaultMemberName) {
+								type = SymbolKind.Indexer; // normal indexer
+							} else if (property.Name.EndsWith(".Item", StringComparison.Ordinal) && (property.GetMethod ?? property.SetMethod).HasOverrides) {
+								// explicit interface implementation of indexer
+								type = SymbolKind.Indexer;
+								// We can't really tell parameterized properties and indexers apart in this case without
+								// resolving the interface, so we rely on the "Item" naming convention instead.
+							}
+						}
+						members.Add(ReadProperty(property, td, type));
+					}
+				}
+			}
+			if (typeDefinition.HasEvents) {
+				foreach (EventDefinition ev in typeDefinition.Events) {
+					if (ev.AddMethod != null && IsVisible(ev.AddMethod.Attributes)) {
+						members.Add(ReadEvent(ev, td));
+					}
+				}
+			}
+		}
+		
+		static bool IsAccessor(MethodSemanticsAttributes semantics)
+		{
+			return !(semantics == MethodSemanticsAttributes.None || semantics == MethodSemanticsAttributes.Other);
+		}
+		#endregion
+		
+		#region Lazy-Loaded Type Definition
+		/// <summary>
+		/// Given an assembly that was created by the CecilLoader with lazy-loading enabled,
+		/// this method will eagerly load all classes, and free any references to the source Cecil objects.
+		/// 
+		/// The intended usage pattern for this method is:
+		/// 1. use lazy-loading to improve the latency when new assemblies have to be loaded
+		/// 2. later, when the CPU is idle, call FinishLazyLoading() to free up the memory consumed by the Cecil objects
+		/// </summary>
+		public static void FinishLazyLoading(IUnresolvedAssembly assembly)
+		{
+			if (assembly == null)
+				throw new ArgumentNullException("assembly");
+			foreach (var type in assembly.TopLevelTypeDefinitions) {
+				var lctd = type as LazyCecilTypeDefinition;
+				if (lctd != null)
+					lctd.InitAndReleaseReferences();
+			}
+		}
+		
+		sealed class LazyCecilTypeDefinition : AbstractUnresolvedEntity, IUnresolvedTypeDefinition
+		{
+			// loader + cecilTypeDef, used for lazy-loading; and set to null after lazy loading is complete
+			CecilLoader loader;
+			TypeDefinition cecilTypeDef;
+			
+			readonly string namespaceName;
+			readonly TypeKind kind;
+			readonly IList<IUnresolvedTypeParameter> typeParameters;
+			
+			// lazy-loaded fields
+			IList<ITypeReference> baseTypes;
+			IList<IUnresolvedTypeDefinition> nestedTypes;
+			IList<IUnresolvedMember> members;
+			
+			public LazyCecilTypeDefinition(CecilLoader loader, TypeDefinition typeDefinition)
+			{
+				this.loader = loader;
+				this.cecilTypeDef = typeDefinition;
+				this.SymbolKind = SymbolKind.TypeDefinition;
+				this.namespaceName = typeDefinition.Namespace;
+				this.Name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(typeDefinition.Name);
+				var tps = new List<IUnresolvedTypeParameter>();
+				InitTypeParameters(typeDefinition, tps);
+				this.typeParameters = FreezableHelper.FreezeList(tps);
+				
+				this.kind = GetTypeKind(typeDefinition);
+				InitTypeModifiers(typeDefinition, this);
+				loader.InitTypeParameterConstraints(typeDefinition, typeParameters);
+				
+				loader.AddAttributes(typeDefinition, this);
+				flags[FlagHasExtensionMethods] = HasExtensionAttribute(typeDefinition);
+				
+				this.ApplyInterningProvider(loader.interningProvider);
+				this.Freeze();
+			}
+			
+			public override string Namespace {
+				get { return namespaceName; }
+				set { throw new NotSupportedException(); }
+			}
+			
+			public override string ReflectionName {
+				get { return this.FullTypeName.ReflectionName; }
+			}
+			
+			public FullTypeName FullTypeName {
+				get {
+					return new TopLevelTypeName(namespaceName, this.Name, typeParameters.Count);
+				}
+			}
+			
+			public TypeKind Kind {
+				get { return kind; }
+			}
+			
+			public IList<IUnresolvedTypeParameter> TypeParameters {
+				get { return typeParameters; }
+			}
+			
+			public IList<ITypeReference> BaseTypes {
+				get {
+					var result = LazyInit.VolatileRead(ref this.baseTypes);
+					if (result != null) {
+						return result;
+					} else {
+						return LazyInit.GetOrSet(ref this.baseTypes, TryInitBaseTypes());
+					}
+				}
+			}
+			
+			IList<ITypeReference> TryInitBaseTypes()
+			{
+				var loader = LazyInit.VolatileRead(ref this.loader);
+				var cecilTypeDef = LazyInit.VolatileRead(ref this.cecilTypeDef);
+				if (loader == null || cecilTypeDef == null) {
+					// Cannot initialize because the references to loader/cecilTypeDef
+					// have already been cleared.
+					// This can only happen if the class was loaded by another thread concurrently to the TryInitBaseTypes() call,
+					// so the GetOrSet() call in the property will retrieve the value set by the other thread.
+					return null;
+				}
+				lock (loader.currentModule) {
+					var result = new List<ITypeReference>();
+					loader.InitBaseTypes(cecilTypeDef, result);
+					return FreezableHelper.FreezeList(result);
+				}
+			}
+			
+			public IList<IUnresolvedTypeDefinition> NestedTypes {
+				get {
+					var result = LazyInit.VolatileRead(ref this.nestedTypes);
+					if (result != null) {
+						return result;
+					} else {
+						return LazyInit.GetOrSet(ref this.nestedTypes, TryInitNestedTypes());
+					}
+				}
+			}
+			
+			IList<IUnresolvedTypeDefinition> TryInitNestedTypes()
+			{
+				var loader = LazyInit.VolatileRead(ref this.loader);
+				var cecilTypeDef = LazyInit.VolatileRead(ref this.cecilTypeDef);
+				if (loader == null || cecilTypeDef == null) {
+					// Cannot initialize because the references to loader/cecilTypeDef
+					// have already been cleared.
+					// This can only happen if the class was loaded by another thread concurrently to the TryInitNestedTypes() call,
+					// so the GetOrSet() call in the property will retrieve the value set by the other thread.
+					return null;
+				}
+				lock (loader.currentModule) {
+					var result = new List<IUnresolvedTypeDefinition>();
+					loader.InitNestedTypes(cecilTypeDef, this, result);
+					return FreezableHelper.FreezeList(result);
+				}
+			}
+			
+			public IList<IUnresolvedMember> Members {
+				get {
+					var result = LazyInit.VolatileRead(ref this.members);
+					if (result != null) {
+						return result;
+					} else {
+						return LazyInit.GetOrSet(ref this.members, TryInitMembers());
+					}
+				}
+			}
+			
+			IList<IUnresolvedMember> TryInitMembers()
+			{
+				var loader = LazyInit.VolatileRead(ref this.loader);
+				var cecilTypeDef = LazyInit.VolatileRead(ref this.cecilTypeDef);
+				if (loader == null || cecilTypeDef == null) {
+					// Cannot initialize because the references to loader/cecilTypeDef
+					// have already been cleared.
+					// This can only happen if the class was loaded by another thread concurrently to the TryInitMembers() call,
+					// so the GetOrSet() call in the property will retrieve the value set by the other thread.
+					return null;
+				}
+				lock (loader.currentModule) {
+					if (this.members != null)
+						return this.members;
+					var result = new List<IUnresolvedMember>();
+					loader.InitMembers(cecilTypeDef, this, result);
+					return FreezableHelper.FreezeList(result);
+				}
+			}
+			
+			public void InitAndReleaseReferences()
+			{
+				if (LazyInit.VolatileRead(ref this.baseTypes) == null)
+					LazyInit.GetOrSet(ref this.baseTypes, TryInitBaseTypes());
+				if (LazyInit.VolatileRead(ref this.nestedTypes) == null)
+					LazyInit.GetOrSet(ref this.nestedTypes, TryInitNestedTypes());
+				if (LazyInit.VolatileRead(ref this.members) == null)
+					LazyInit.GetOrSet(ref this.members, TryInitMembers());
+				Thread.MemoryBarrier(); // commit lazily-initialized fields to memory before nulling out the references
+				// Allow the GC to collect the cecil type definition
+				loader = null;
+				cecilTypeDef = null;
+			}
+			
+			public IEnumerable<IUnresolvedMethod> Methods {
+				get { return Members.OfType<IUnresolvedMethod>(); }
+			}
+			
+			public IEnumerable<IUnresolvedProperty> Properties {
+				get { return Members.OfType<IUnresolvedProperty>(); }
+			}
+			
+			public IEnumerable<IUnresolvedField> Fields {
+				get { return Members.OfType<IUnresolvedField>(); }
+			}
+			
+			public IEnumerable<IUnresolvedEvent> Events {
+				get { return Members.OfType<IUnresolvedEvent>(); }
+			}
+			
+			public bool AddDefaultConstructorIfRequired {
+				get { return kind == TypeKind.Struct || kind == TypeKind.Enum; }
+			}
+			
+			public bool? HasExtensionMethods {
+				get { return flags[FlagHasExtensionMethods]; }
+				// we always return true or false, never null.
+				// FlagHasNoExtensionMethods is unused in LazyCecilTypeDefinition
+			}
+			
+			public bool IsPartial {
+				get { return false; }
+			}
+			
+			public override object Clone()
+			{
+				throw new NotSupportedException();
+			}
+			
+			public IType Resolve(ITypeResolveContext context)
+			{
+				if (context == null)
+					throw new ArgumentNullException("context");
+				if (context.CurrentAssembly == null)
+					throw new ArgumentException("An ITypeDefinition cannot be resolved in a context without a current assembly.");
+				return context.CurrentAssembly.GetTypeDefinition(this.FullTypeName)
+					?? (IType)new UnknownType(this.Namespace, this.Name, this.TypeParameters.Count);
+			}
+			
+			public ITypeResolveContext CreateResolveContext(ITypeResolveContext parentContext)
+			{
+				return parentContext;
+			}
+		}
+		#endregion
+		
+		#region Read Method
+		[CLSCompliant(false)]
+		public IUnresolvedMethod ReadMethod(MethodDefinition method, IUnresolvedTypeDefinition parentType, SymbolKind methodType = SymbolKind.Method)
+		{
+			return ReadMethod(method, parentType, methodType, null);
+		}
+		
+		IUnresolvedMethod ReadMethod(MethodDefinition method, IUnresolvedTypeDefinition parentType, SymbolKind methodType, IUnresolvedMember accessorOwner)
+		{
+			if (method == null)
+				return null;
+			DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(parentType, method.Name);
+			m.SymbolKind = methodType;
+			m.AccessorOwner = accessorOwner;
+			m.HasBody = method.HasBody;
+			if (method.HasGenericParameters) {
+				for (int i = 0; i < method.GenericParameters.Count; i++) {
+					if (method.GenericParameters[i].Position != i)
+						throw new InvalidOperationException("g.Position != i");
+					m.TypeParameters.Add(new DefaultUnresolvedTypeParameter(
+						SymbolKind.Method, i, method.GenericParameters[i].Name));
+				}
+				for (int i = 0; i < method.GenericParameters.Count; i++) {
+					var tp = (DefaultUnresolvedTypeParameter)m.TypeParameters[i];
+					AddConstraints(tp, method.GenericParameters[i]);
+					tp.ApplyInterningProvider(interningProvider);
+				}
+			}
+			
+			m.ReturnType = ReadTypeReference(method.ReturnType, typeAttributes: method.MethodReturnType);
+			
+			if (HasAnyAttributes(method))
+				AddAttributes(method, m.Attributes, m.ReturnTypeAttributes);
+			TranslateModifiers(method, m);
+			
+			if (method.HasParameters) {
+				foreach (ParameterDefinition p in method.Parameters) {
+					m.Parameters.Add(ReadParameter(p));
+				}
+			}
+			
+			// mark as extension method if the attribute is set
+			if (method.IsStatic && HasExtensionAttribute(method)) {
+				m.IsExtensionMethod = true;
+			}
+
+			int lastDot = method.Name.LastIndexOf('.');
+			if (lastDot >= 0 && method.HasOverrides) {
+				// To be consistent with the parser-initialized type system, shorten the method name:
+				m.Name = method.Name.Substring(lastDot + 1);
+				m.IsExplicitInterfaceImplementation = true;
+				foreach (var or in method.Overrides) {
+					m.ExplicitInterfaceImplementations.Add(new DefaultMemberReference(
+						accessorOwner != null ? SymbolKind.Accessor : SymbolKind.Method,
+						ReadTypeReference(or.DeclaringType),
+						or.Name, or.GenericParameters.Count, m.Parameters.Select(p => p.Type).ToList()));
+				}
+			}
+
+			FinishReadMember(m, method);
+			return m;
+		}
+		
+		static bool HasExtensionAttribute(ICustomAttributeProvider provider)
+		{
+			if (provider.HasCustomAttributes) {
+				foreach (var attr in provider.CustomAttributes) {
+					if (attr.AttributeType.Name == "ExtensionAttribute" && attr.AttributeType.Namespace == "System.Runtime.CompilerServices")
+						return true;
+				}
+			}
+			return false;
+		}
+		
+		bool IsVisible(MethodAttributes att)
+		{
+			att &= MethodAttributes.MemberAccessMask;
+			return IncludeInternalMembers
+				|| att == MethodAttributes.Public
+				|| att == MethodAttributes.Family
+				|| att == MethodAttributes.FamORAssem;
+		}
+		
+		static Accessibility GetAccessibility(MethodAttributes attr)
+		{
+			switch (attr & MethodAttributes.MemberAccessMask) {
+				case MethodAttributes.Public:
+					return Accessibility.Public;
+				case MethodAttributes.FamANDAssem:
+					return Accessibility.ProtectedAndInternal;
+				case MethodAttributes.Assembly:
+					return Accessibility.Internal;
+				case MethodAttributes.Family:
+					return Accessibility.Protected;
+				case MethodAttributes.FamORAssem:
+					return Accessibility.ProtectedOrInternal;
+				default:
+					return Accessibility.Private;
+			}
+		}
+		
+		void TranslateModifiers(MethodDefinition method, AbstractUnresolvedMember m)
+		{
+			if (m.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
+				// interface members don't have modifiers, but we want to handle them as "public abstract"
+				m.Accessibility = Accessibility.Public;
+				m.IsAbstract = true;
+			} else {
+				m.Accessibility = GetAccessibility(method.Attributes);
+				if (method.IsAbstract) {
+					m.IsAbstract = true;
+					m.IsOverride = !method.IsNewSlot;
+				} else if (method.IsFinal) {
+					if (!method.IsNewSlot) {
+						m.IsSealed = true;
+						m.IsOverride = true;
+					}
+				} else if (method.IsVirtual) {
+					if (method.IsNewSlot)
+						m.IsVirtual = true;
+					else
+						m.IsOverride = true;
+				}
+				m.IsStatic = method.IsStatic;
+			}
+		}
+		#endregion
+		
+		#region Read Parameter
+		[CLSCompliant(false)]
+		public IUnresolvedParameter ReadParameter(ParameterDefinition parameter)
+		{
+			if (parameter == null)
+				throw new ArgumentNullException("parameter");
+			var type = ReadTypeReference(parameter.ParameterType, typeAttributes: parameter);
+			var p = new DefaultUnresolvedParameter(type, interningProvider.Intern(parameter.Name));
+			
+			if (parameter.ParameterType is Mono.Cecil.ByReferenceType) {
+				if (!parameter.IsIn && parameter.IsOut)
+					p.IsOut = true;
+				else
+					p.IsRef = true;
+			}
+			AddAttributes(parameter, p);
+			
+			if (parameter.IsOptional) {
+				p.DefaultValue = CreateSimpleConstantValue(type, parameter.Constant);
+			}
+			
+			if (parameter.ParameterType is Mono.Cecil.ArrayType) {
+				foreach (CustomAttribute att in parameter.CustomAttributes) {
+					if (att.AttributeType.FullName == typeof(ParamArrayAttribute).FullName) {
+						p.IsParams = true;
+						break;
+					}
+				}
+			}
+			
+			return interningProvider.Intern(p);
+		}
+		#endregion
+		
+		#region Read Field
+		bool IsVisible(FieldAttributes att)
+		{
+			att &= FieldAttributes.FieldAccessMask;
+			return IncludeInternalMembers
+				|| att == FieldAttributes.Public
+				|| att == FieldAttributes.Family
+				|| att == FieldAttributes.FamORAssem;
+		}
+
+		decimal? TryDecodeDecimalConstantAttribute(CustomAttribute attribute)
+		{
+			if (attribute.ConstructorArguments.Count != 5)
+				return null;
+
+			BlobReader reader = new BlobReader(attribute.GetBlob(), null);
+			if (reader.ReadUInt16() != 0x0001) {
+				Debug.WriteLine("Unknown blob prolog");
+				return null;
+			}
+
+			// DecimalConstantAttribute has the arguments (byte scale, byte sign, uint hi, uint mid, uint low) or (byte scale, byte sign, int hi, int mid, int low)
+			// Both of these invoke the Decimal constructor (int lo, int mid, int hi, bool isNegative, byte scale) with explicit argument conversions if required.
+			var ctorArgs = new object[attribute.ConstructorArguments.Count];
+			for (int i = 0; i < ctorArgs.Length; i++) {
+				switch (attribute.ConstructorArguments[i].Type.FullName) {
+					case "System.Byte":
+						ctorArgs[i] = reader.ReadByte();
+						break;
+					case "System.Int32":
+						ctorArgs[i] = reader.ReadInt32();
+						break;
+					case "System.UInt32":
+						ctorArgs[i] = unchecked((int)reader.ReadUInt32());
+						break;
+					default:
+						return null;
+				}
+			}
+
+			if (!ctorArgs.Select(a => a.GetType()).SequenceEqual(new[] { typeof(byte), typeof(byte), typeof(int), typeof(int), typeof(int) }))
+				return null;
+
+			return new decimal((int)ctorArgs[4], (int)ctorArgs[3], (int)ctorArgs[2], (byte)ctorArgs[1] != 0, (byte)ctorArgs[0]);
+		}
+		
+		[CLSCompliant(false)]
+		public IUnresolvedField ReadField(FieldDefinition field, IUnresolvedTypeDefinition parentType)
+		{
+			if (field == null)
+				throw new ArgumentNullException("field");
+			if (parentType == null)
+				throw new ArgumentNullException("parentType");
+			
+			DefaultUnresolvedField f = new DefaultUnresolvedField(parentType, field.Name);
+			f.Accessibility = GetAccessibility(field.Attributes);
+			f.IsReadOnly = field.IsInitOnly;
+			f.IsStatic = field.IsStatic;
+			f.ReturnType = ReadTypeReference(field.FieldType, typeAttributes: field);
+			if (field.HasConstant) {
+				f.ConstantValue = CreateSimpleConstantValue(f.ReturnType, field.Constant);
+			}
+			else {
+				var decConstant = field.CustomAttributes.FirstOrDefault(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.DecimalConstantAttribute");
+				if (decConstant != null) {
+					var constValue = TryDecodeDecimalConstantAttribute(decConstant);
+					if (constValue != null)
+						f.ConstantValue = CreateSimpleConstantValue(f.ReturnType, constValue);
+				}
+			}
+			AddAttributes(field, f);
+			
+			RequiredModifierType modreq = field.FieldType as RequiredModifierType;
+			if (modreq != null && modreq.ModifierType.FullName == typeof(IsVolatile).FullName) {
+				f.IsVolatile = true;
+			}
+			
+			FinishReadMember(f, field);
+			return f;
+		}
+		
+		static Accessibility GetAccessibility(FieldAttributes attr)
+		{
+			switch (attr & FieldAttributes.FieldAccessMask) {
+				case FieldAttributes.Public:
+					return Accessibility.Public;
+				case FieldAttributes.FamANDAssem:
+					return Accessibility.ProtectedAndInternal;
+				case FieldAttributes.Assembly:
+					return Accessibility.Internal;
+				case FieldAttributes.Family:
+					return Accessibility.Protected;
+				case FieldAttributes.FamORAssem:
+					return Accessibility.ProtectedOrInternal;
+				default:
+					return Accessibility.Private;
+			}
+		}
+		#endregion
+		
+		#region Type Parameter Constraints
+		void AddConstraints(DefaultUnresolvedTypeParameter tp, GenericParameter g)
+		{
+			switch (g.Attributes & GenericParameterAttributes.VarianceMask) {
+				case GenericParameterAttributes.Contravariant:
+					tp.Variance = VarianceModifier.Contravariant;
+					break;
+				case GenericParameterAttributes.Covariant:
+					tp.Variance = VarianceModifier.Covariant;
+					break;
+			}
+			
+			tp.HasReferenceTypeConstraint = g.HasReferenceTypeConstraint;
+			tp.HasValueTypeConstraint = g.HasNotNullableValueTypeConstraint;
+			tp.HasDefaultConstructorConstraint = g.HasDefaultConstructorConstraint;
+			
+			if (g.HasConstraints) {
+				foreach (TypeReference constraint in g.Constraints) {
+					tp.Constraints.Add(ReadTypeReference(constraint));
+				}
+			}
+		}
+		#endregion
+		
+		#region Read Property
+
+		Accessibility MergePropertyAccessibility (Accessibility left, Accessibility right)
+		{
+			if (left == Accessibility.Public || right == Accessibility.Public)
+				return Accessibility.Public;
+
+			if (left == Accessibility.ProtectedOrInternal || right == Accessibility.ProtectedOrInternal)
+				return Accessibility.ProtectedOrInternal;
+
+			if (left == Accessibility.Protected && right == Accessibility.Internal ||
+			    left == Accessibility.Internal && right == Accessibility.Protected)
+				return Accessibility.ProtectedOrInternal;
+
+			if (left == Accessibility.Protected || right == Accessibility.Protected)
+				return Accessibility.Protected;
+
+			if (left == Accessibility.Internal || right == Accessibility.Internal)
+				return Accessibility.Internal;
+
+			if (left == Accessibility.ProtectedAndInternal || right == Accessibility.ProtectedAndInternal)
+				return Accessibility.ProtectedAndInternal;
+
+			return left;
+		}
+
+		[CLSCompliant(false)]
+		public IUnresolvedProperty ReadProperty(PropertyDefinition property, IUnresolvedTypeDefinition parentType, SymbolKind propertyType = SymbolKind.Property)
+		{
+			if (property == null)
+				throw new ArgumentNullException("property");
+			if (parentType == null)
+				throw new ArgumentNullException("parentType");
+			DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(parentType, property.Name);
+			p.SymbolKind = propertyType;
+			TranslateModifiers(property.GetMethod ?? property.SetMethod, p);
+			if (property.GetMethod != null && property.SetMethod != null)
+				p.Accessibility = MergePropertyAccessibility (GetAccessibility (property.GetMethod.Attributes), GetAccessibility (property.SetMethod.Attributes));
+
+			p.ReturnType = ReadTypeReference(property.PropertyType, typeAttributes: property);
+			
+			p.Getter = ReadMethod(property.GetMethod, parentType, SymbolKind.Accessor, p);
+			p.Setter = ReadMethod(property.SetMethod, parentType, SymbolKind.Accessor, p);
+			
+			if (property.HasParameters) {
+				foreach (ParameterDefinition par in property.Parameters) {
+					p.Parameters.Add(ReadParameter(par));
+				}
+			}
+			AddAttributes(property, p);
+
+			var accessor = p.Getter ?? p.Setter;
+			if (accessor != null && accessor.IsExplicitInterfaceImplementation) {
+				p.Name = property.Name.Substring(property.Name.LastIndexOf('.') + 1);
+				p.IsExplicitInterfaceImplementation = true;
+				foreach (var mr in accessor.ExplicitInterfaceImplementations) {
+					p.ExplicitInterfaceImplementations.Add(new AccessorOwnerMemberReference(mr));
+				}
+			}
+
+			FinishReadMember(p, property);
+			return p;
+		}
+		#endregion
+		
+		#region Read Event
+		[CLSCompliant(false)]
+		public IUnresolvedEvent ReadEvent(EventDefinition ev, IUnresolvedTypeDefinition parentType)
+		{
+			if (ev == null)
+				throw new ArgumentNullException("ev");
+			if (parentType == null)
+				throw new ArgumentNullException("parentType");
+			
+			DefaultUnresolvedEvent e = new DefaultUnresolvedEvent(parentType, ev.Name);
+			TranslateModifiers(ev.AddMethod, e);
+			e.ReturnType = ReadTypeReference(ev.EventType, typeAttributes: ev);
+			
+			e.AddAccessor    = ReadMethod(ev.AddMethod,    parentType, SymbolKind.Accessor, e);
+			e.RemoveAccessor = ReadMethod(ev.RemoveMethod, parentType, SymbolKind.Accessor, e);
+			e.InvokeAccessor = ReadMethod(ev.InvokeMethod, parentType, SymbolKind.Accessor, e);
+			
+			AddAttributes(ev, e);
+			
+			var accessor = e.AddAccessor ?? e.RemoveAccessor ?? e.InvokeAccessor;
+			if (accessor != null && accessor.IsExplicitInterfaceImplementation) {
+				e.Name = ev.Name.Substring(ev.Name.LastIndexOf('.') + 1);
+				e.IsExplicitInterfaceImplementation = true;
+				foreach (var mr in accessor.ExplicitInterfaceImplementations) {
+					e.ExplicitInterfaceImplementations.Add(new AccessorOwnerMemberReference(mr));
+				}
+			}
+
+			FinishReadMember(e, ev);
+			
+			return e;
+		}
+		#endregion
+		
+		#region FinishReadMember / Interning
+		void FinishReadMember(AbstractUnresolvedMember member, MemberReference cecilDefinition)
+		{
+			member.ApplyInterningProvider(interningProvider);
+			member.Freeze();
+			RegisterCecilObject(member, cecilDefinition);
+		}
+		#endregion
+		
+		#region Type system translation table
+		readonly Dictionary<object, object> typeSystemTranslationTable;
+		
+		void RegisterCecilObject(IUnresolvedEntity typeSystemObject, MemberReference cecilObject)
+		{
+			if (OnEntityLoaded != null)
+				OnEntityLoaded(typeSystemObject, cecilObject);
+			
+			AddToTypeSystemTranslationTable(typeSystemObject, cecilObject);
+		}
+		
+		void AddToTypeSystemTranslationTable(object typeSystemObject, object cecilObject)
+		{
+			if (typeSystemTranslationTable != null) {
+				// When lazy-loading, the dictionary might be shared between multiple cecil-loaders that are used concurrently
+				lock (typeSystemTranslationTable) {
+					typeSystemTranslationTable[typeSystemObject] = cecilObject;
+				}
+			}
+		}
+		
+		T InternalGetCecilObject<T> (object typeSystemObject) where T : class
+		{
+			if (typeSystemObject == null)
+				throw new ArgumentNullException ("typeSystemObject");
+			if (!HasCecilReferences)
+				throw new NotSupportedException ("This instance contains no cecil references.");
+			object result;
+			lock (typeSystemTranslationTable) {
+				if (!typeSystemTranslationTable.TryGetValue (typeSystemObject, out result))
+					return null;
+			}
+			return result as T;
+		}
+		
+		[CLSCompliant(false)]
+		public AssemblyDefinition GetCecilObject (IUnresolvedAssembly content)
+		{
+			return InternalGetCecilObject<AssemblyDefinition> (content);
+		}
+		
+		[CLSCompliant(false)]
+		public TypeDefinition GetCecilObject (IUnresolvedTypeDefinition type)
+		{
+			if (type == null)
+				throw new ArgumentNullException ("type");
+			return InternalGetCecilObject<TypeDefinition> (type);
+		}
+		
+		[CLSCompliant(false)]
+		public MethodDefinition GetCecilObject (IUnresolvedMethod method)
+		{
+			return InternalGetCecilObject<MethodDefinition> (method);
+		}
+		
+		[CLSCompliant(false)]
+		public FieldDefinition GetCecilObject (IUnresolvedField field)
+		{
+			return InternalGetCecilObject<FieldDefinition> (field);
+		}
+		
+		[CLSCompliant(false)]
+		public EventDefinition GetCecilObject (IUnresolvedEvent evt)
+		{
+			return InternalGetCecilObject<EventDefinition> (evt);
+		}
+		
+		[CLSCompliant(false)]
+		public PropertyDefinition GetCecilObject (IUnresolvedProperty property)
+		{
+			return InternalGetCecilObject<PropertyDefinition> (property);
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/ICSharpCode.NRefactory License-5.5.0.txt	(revision 11807)
@@ -0,0 +1,17 @@
+Copyright (c) 2010-2014 AlphaSierraPapa, Xamarin
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this
+software and associated documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/ICSharpCode.NRefactory.Cecil-5.5.0.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/ICSharpCode.NRefactory.Cecil-5.5.0.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/ICSharpCode.NRefactory.Cecil-5.5.0.csproj	(revision 11807)
@@ -0,0 +1,116 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{6661EE06-91D3-489B-AE80-BC951EA65E9A}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>ICSharpCode.NRefactory.Cecil</RootNamespace>
+    <AssemblyName>ICSharpCode.NRefactory.Cecil</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="CecilLoader.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Content Include="ICSharpCode.NRefactory License-5.5.0.txt" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\..\HeuristicLab.Cecil\0.9.5\Mono.Cecil-0.9.5\Mono.Cecil-0.9.5.csproj">
+      <Project>{ccf26bbc-5555-46ec-81f9-5b253cd24170}</Project>
+      <Name>Mono.Cecil-0.9.5</Name>
+      <Private>False</Private>
+    </ProjectReference>
+    <ProjectReference Include="..\NRefactory-5.5.0\ICSharpCode.NRefactory-5.5.0.csproj">
+      <Project>{1022483b-7cf4-4162-827f-984b64eaf8b3}</Project>
+      <Name>ICSharpCode.NRefactory-5.5.0</Name>
+      <Private>False</Private>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Cecil-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,38 @@
+﻿using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ICSharpCode.NRefactory.Cecil")]
+[assembly: AssemblyDescription("Cecil Assembly Loader for NRefactory")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("ICSharpCode")]
+[assembly: AssemblyProduct("SharpDevelop/MonoDevelop")]
+[assembly: AssemblyCopyright("Copyright 2010-2014 AlphaSierraPapa and Xamarin Inc.")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+[assembly: CLSCompliant(true)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("555f6032-12fe-42e3-ba15-fcaa108e75f7")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.0.0.0")]
+[assembly: AssemblyFileVersion("5.5.0")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlAttribute.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlAttribute.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlAttribute.cs	(revision 11807)
@@ -0,0 +1,118 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Name-value pair in a tag
+	/// </summary>
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
+	public class AXmlAttribute : AXmlObject
+	{
+		internal AXmlAttribute(AXmlObject parent, int startOffset, InternalAttribute internalObject)
+			: base(parent, startOffset, internalObject)
+		{
+		}
+		
+		internal InternalAttribute InternalAttribute {
+			get { return (InternalAttribute)internalObject; }
+		}
+		
+		/// <summary> Name with namespace prefix - exactly as in source file </summary>
+		public string Name { get { return InternalAttribute.Name; } }
+		
+		/// <summary> Unquoted and dereferenced value of the attribute </summary>
+		public string Value { get { return InternalAttribute.Value; } }
+		
+		/// <summary>Gets the segment for the attribute name</summary>
+		public ISegment NameSegment {
+			get { return new XmlSegment(startOffset, startOffset + Name.Length); }
+		}
+		
+		/// <summary>Gets the segment for the attribute value, including the quotes</summary>
+		public ISegment ValueSegment {
+			get { return new XmlSegment(startOffset + Name.Length + InternalAttribute.EqualsSignLength, this.EndOffset); }
+		}
+		/// <summary> The element containing this attribute </summary>
+		/// <returns> Null if orphaned </returns>
+		public AXmlElement ParentElement {
+			get {
+				AXmlTag tag = this.Parent as AXmlTag;
+				if (tag != null) {
+					return tag.Parent as AXmlElement;
+				}
+				return null;
+			}
+		}
+		
+		/// <summary> The part of name before ":"</summary>
+		/// <returns> Empty string if not found </returns>
+		public string Prefix {
+			get {
+				return GetNamespacePrefix(this.Name);
+			}
+		}
+		
+		/// <summary> The part of name after ":" </summary>
+		/// <returns> Whole name if ":" not found </returns>
+		public string LocalName {
+			get {
+				return GetLocalName(this.Name);
+			}
+		}
+		
+		/// <summary>
+		/// Resolved namespace of the name.  Empty string if not found
+		/// From the specification: "The namespace name for an unprefixed attribute name always has no value."
+		/// </summary>
+		public string Namespace {
+			get {
+				if (string.IsNullOrEmpty(this.Prefix)) return NoNamespace;
+				
+				AXmlElement elem = this.ParentElement;
+				if (elem != null) {
+					return elem.LookupNamespace(this.Prefix) ?? NoNamespace;
+				}
+				return NoNamespace; // Orphaned attribute
+			}
+		}
+		
+		/// <summary> Attribute is declaring namespace ("xmlns" or "xmlns:*") </summary>
+		public bool IsNamespaceDeclaration {
+			get {
+				return this.Name == "xmlns" || this.Prefix == "xmlns";
+			}
+		}
+		
+		/// <inheritdoc/>
+		public override void AcceptVisitor(AXmlVisitor visitor)
+		{
+			visitor.VisitAttribute(this);
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} '{1}={2}']", base.ToString(), this.Name, this.Value);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlDocument.cs	(revision 11807)
@@ -0,0 +1,58 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+using System.Xml;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// The root object of the XML document
+	/// </summary>
+	public class AXmlDocument : AXmlObject
+	{
+		internal AXmlDocument(AXmlObject parent, int startOffset, InternalDocument internalObject)
+			: base(parent, startOffset, internalObject)
+		{
+		}
+		
+		internal override ObjectIterator CreateIteratorForReader()
+		{
+			return new ObjectIterator(internalObject.NestedObjects, startOffset);
+		}
+		
+		/// <inheritdoc/>
+		public override void AcceptVisitor(AXmlVisitor visitor)
+		{
+			visitor.VisitDocument(this);
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} Chld:{1}]", base.ToString(), this.Children.Count);
+		}
+		
+		/// <summary>
+		/// Represents an empty document.
+		/// </summary>
+		public readonly static AXmlDocument Empty = new AXmlDocument(null, 0, new InternalDocument());
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlElement.cs	(revision 11807)
@@ -0,0 +1,243 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Xml;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// XML element.
+	/// </summary>
+	public class AXmlElement : AXmlObject, IXmlNamespaceResolver
+	{
+		internal AXmlElement(AXmlObject parent, int startOffset, InternalElement internalObject)
+			: base(parent, startOffset, internalObject)
+		{
+			Log.Assert(internalObject.NestedObjects[0] is InternalTag, "First child of element must be start tag");
+		}
+		
+		/// <summary> No tags are missing anywhere within this element (recursive) </summary>
+		public bool IsProperlyNested {
+			get { return ((InternalElement)internalObject).IsPropertyNested; }
+		}
+		
+		/// <summary>The start or empty-element tag for this element.</summary>
+		public AXmlTag StartTag {
+			get { return (AXmlTag)this.Children[0]; }
+		}
+		
+		/// <summary>Name with namespace prefix - exactly as in source</summary>
+		public string Name {
+			get { return ((InternalTag)internalObject.NestedObjects[0]).Name; }
+		}
+		
+		/// <summary>Gets whether an end tag exists for this node.</summary>
+		public bool HasEndTag {
+			get { return ((InternalElement)internalObject).HasEndTag; }
+		}
+		
+		/// <summary> The end tag, if there is any. Returns null for empty elements "&lt;Element/>" and missing end tags in malformed XML.</summary>
+		public AXmlTag EndTag {
+			get {
+				if (HasEndTag)
+					return (AXmlTag)this.Children[this.Children.Count - 1];
+				else
+					return null;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the attributes.
+		/// </summary>
+		public IEnumerable<AXmlAttribute> Attributes {
+			get {
+				return ((AXmlTag)this.Children[0]).Children.OfType<AXmlAttribute>();
+			}
+		}
+		
+		/// <summary>
+		/// Gets the content (all children except for the start and end tags)
+		/// </summary>
+		public IEnumerable<AXmlObject> Content {
+			get {
+				int end = this.Children.Count;
+				if (HasEndTag)
+					end--;
+				for (int i = 1; i < end; i++) {
+					yield return this.Children[i];
+				}
+			}
+		}
+		
+		/// <summary> The part of name before ":" </summary>
+		/// <returns> Empty string if not found </returns>
+		public string Prefix {
+			get { return ((InternalElement)internalObject).Prefix; }
+		}
+		
+		/// <summary> The part of name after ":" </summary>
+		/// <returns> Empty string if not found </returns>
+		public string LocalName {
+			get { return ((InternalElement)internalObject).LocalName; }
+		}
+		
+		/// <summary> Resolved namespace of the name </summary>
+		/// <returns> Empty string if prefix is not found </returns>
+		public string Namespace {
+			get {
+				string prefix = this.Prefix;
+				return LookupNamespace(prefix);
+			}
+		}
+		
+		/// <summary> Find the default namespace for this context </summary>
+		[Obsolete("Use LookupNamespace(string.Empty) instead")]
+		public string FindDefaultNamespace()
+		{
+			return LookupNamespace(string.Empty) ?? NoNamespace;
+		}
+		
+		/// <summary>
+		/// Recursively resolve given prefix in this context.  Prefix must have some value.
+		/// </summary>
+		/// <returns> Empty string if prefix is not found </returns>
+		[Obsolete("Use LookupNamespace() instead")]
+		public string ResolvePrefix(string prefix)
+		{
+			return LookupNamespace(prefix) ?? NoNamespace;
+		}
+		
+		/// <summary>
+		/// Recursively resolve given prefix in this context.
+		/// </summary>
+		/// <returns><c>null</c> if prefix is not found</returns>
+		public string LookupNamespace(string prefix)
+		{
+			if (prefix == null)
+				throw new ArgumentNullException("prefix");
+			
+			// Implicit namespaces
+			if (prefix == "xml") return XmlNamespace;
+			if (prefix == "xmlns") return XmlnsNamespace;
+			
+			string lookFor = (prefix.Length > 0 ? "xmlns:" + prefix : "xmlns");
+			for (AXmlElement current = this; current != null; current = current.Parent as AXmlElement) {
+				foreach (var attr in current.Attributes) {
+					if (attr.Name == lookFor)
+						return attr.Value;
+				}
+			}
+			return null; // Can not find prefix
+		}
+		
+		/// <summary>
+		/// Gets the prefix that is mapped to the specified namespace URI.
+		/// </summary>
+		/// <returns>The prefix that is mapped to the namespace URI; null if the namespace URI is not mapped to a prefix.</returns>
+		public string LookupPrefix(string namespaceName)
+		{
+			if (namespaceName == null)
+				throw new ArgumentNullException("namespaceName");
+			
+			if (namespaceName == XmlNamespace)
+				return "xml";
+			if (namespaceName == XmlnsNamespace)
+				return "xmlns";
+			for (AXmlElement current = this; current != null; current = current.Parent as AXmlElement) {
+				foreach (var attr in current.Attributes) {
+					if (attr.Value == namespaceName) {
+						if (attr.Name.StartsWith("xmlns:", StringComparison.Ordinal))
+							return attr.LocalName;
+						else if (attr.Name == "xmlns")
+							return string.Empty;
+					}
+				}
+			}
+			return null; // Can not find prefix
+		}
+		
+		/// <summary>
+		/// Gets a collection of defined prefix-namespace mappings that are currently in scope.
+		/// </summary>
+		public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
+		{
+			var result = new Dictionary<string, string>();
+			if (scope == XmlNamespaceScope.All) {
+				result["xml"] = XmlNamespace;
+				//result["xmlns"] = XmlnsNamespace; xmlns should not be included in GetNamespacesInScope() results
+			}
+			for (AXmlElement current = this; current != null; current = current.Parent as AXmlElement) {
+				foreach (var attr in current.Attributes) {
+					if (attr.Name.StartsWith("xmlns:", StringComparison.Ordinal)) {
+						string prefix = attr.LocalName;
+						if (!result.ContainsKey(prefix)) {
+							result.Add(prefix, attr.Value);
+						}
+					} else if (attr.Name == "xmlns" && !result.ContainsKey(string.Empty)) {
+						result.Add(string.Empty, attr.Value);
+					}
+				}
+				if (scope == XmlNamespaceScope.Local)
+					break;
+			}
+			return result;
+		}
+		
+		/// <summary>
+		/// Get unquoted value of attribute.
+		/// It looks in the no namespace (empty string).
+		/// </summary>
+		/// <returns>Null if not found</returns>
+		public string GetAttributeValue(string localName)
+		{
+			return GetAttributeValue(string.Empty, localName);
+		}
+		
+		/// <summary>
+		/// Get unquoted value of attribute
+		/// </summary>
+		/// <param name="namespace">Namespace.  Can be no namepace (empty string), which is the default for attributes.</param>
+		/// <param name="localName">Local name - text after ":"</param>
+		/// <returns>Null if not found</returns>
+		public string GetAttributeValue(string @namespace, string localName)
+		{
+			@namespace = @namespace ?? string.Empty;
+			foreach (AXmlAttribute attr in this.Attributes) {
+				if (attr.LocalName == localName && attr.Namespace == @namespace)
+					return attr.Value;
+			}
+			return null;
+		}
+		
+		/// <inheritdoc/>
+		public override void AcceptVisitor(AXmlVisitor visitor)
+		{
+			visitor.VisitElement(this);
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} '{1}' Attr:{2} Chld:{3} Nest:{4}]", base.ToString(), this.Name, this.StartTag.Children.Count, this.Children.Count, this.IsProperlyNested ? "Ok" : "Bad");
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlObject.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlObject.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlObject.cs	(revision 11807)
@@ -0,0 +1,246 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Xml;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// XML object. Base class for all nodes in the XML document.
+	/// </summary>
+	public abstract class AXmlObject : ISegment
+	{
+		/// <summary> Empty string.  The namespace used if there is no "xmlns" specified </summary>
+		internal static readonly string NoNamespace = string.Empty;
+		
+		/// <summary> Namespace for "xml:" prefix: "http://www.w3.org/XML/1998/namespace" </summary>
+		public static readonly string XmlNamespace = "http://www.w3.org/XML/1998/namespace";
+		
+		/// <summary> Namesapce for "xmlns:" prefix: "http://www.w3.org/2000/xmlns/" </summary>
+		public static readonly string XmlnsNamespace = "http://www.w3.org/2000/xmlns/";
+		
+		readonly AXmlObject parent;
+		internal readonly int startOffset;
+		internal readonly InternalObject internalObject;
+		IList<AXmlObject> children;
+		
+		internal AXmlObject(AXmlObject parent, int startOffset, InternalObject internalObject)
+		{
+			this.parent = parent;
+			this.startOffset = startOffset;
+			this.internalObject = internalObject;
+		}
+		
+		/// <summary>
+		/// Creates an XML reader that reads from this document.
+		/// </summary>
+		/// <remarks>
+		/// The reader will ignore comments and processing instructions; and will not have line information.
+		/// </remarks>
+		public XmlReader CreateReader()
+		{
+			return new AXmlReader(CreateIteratorForReader());
+		}
+		
+		/// <summary>
+		/// Creates an XML reader that reads from this document.
+		/// </summary>
+		/// <param name="settings">Reader settings.
+		/// Currently, only <c>IgnoreComments</c> is supported.</param>
+		/// <remarks>
+		/// The reader will not have line information.
+		/// </remarks>
+		public XmlReader CreateReader(XmlReaderSettings settings)
+		{
+			return new AXmlReader(CreateIteratorForReader(), settings);
+		}
+		
+		/// <summary>
+		/// Creates an XML reader that reads from this document.
+		/// </summary>
+		/// <param name="settings">Reader settings.
+		/// Currently, only <c>IgnoreComments</c> is supported.</param>
+		/// <param name="document">
+		/// The document that was used to parse the XML. It is used to convert offsets to line information.
+		/// </param>
+		public XmlReader CreateReader(XmlReaderSettings settings, IDocument document)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			return new AXmlReader(CreateIteratorForReader(), settings, document.GetLocation);
+		}
+		
+		/// <summary>
+		/// Creates an XML reader that reads from this document.
+		/// </summary>
+		/// <param name="settings">Reader settings.
+		/// Currently, only <c>IgnoreComments</c> is supported.</param>
+		/// <param name="offsetToTextLocation">
+		/// A function for converting offsets to line information.
+		/// </param>
+		public XmlReader CreateReader(XmlReaderSettings settings, Func<int, TextLocation> offsetToTextLocation)
+		{
+			return new AXmlReader(CreateIteratorForReader(), settings, offsetToTextLocation);
+		}
+		
+		internal virtual ObjectIterator CreateIteratorForReader()
+		{
+			return new ObjectIterator(new[] { internalObject }, startOffset);
+		}
+		
+		/// <summary>
+		/// Gets the parent node.
+		/// </summary>
+		public AXmlObject Parent {
+			get { return parent; }
+		}
+		
+		/// <summary>
+		/// Gets the list of child objects.
+		/// </summary>
+		public IList<AXmlObject> Children {
+			get {
+				var result = LazyInit.VolatileRead(ref this.children);
+				if (result != null) {
+					return result;
+				} else {
+					if (internalObject.NestedObjects != null) {
+						var array = new AXmlObject[internalObject.NestedObjects.Length];
+						for (int i = 0; i < array.Length; i++) {
+							array[i] = internalObject.NestedObjects[i].CreatePublicObject(this, startOffset);
+						}
+						result = Array.AsReadOnly(array);
+					} else {
+						result = EmptyList<AXmlObject>.Instance;
+					}
+					return LazyInit.GetOrSet(ref this.children, result);
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Gets a child fully containg the given offset.
+		/// Goes recursively down the tree.
+		/// Special case if at the end of attribute or text
+		/// </summary>
+		public AXmlObject GetChildAtOffset(int offset)
+		{
+			foreach(AXmlObject child in this.Children) {
+				if (offset == child.EndOffset && (child is AXmlAttribute || child is AXmlText))
+					return child;
+				if (child.StartOffset < offset && offset < child.EndOffset) {
+					return child.GetChildAtOffset(offset);
+				}
+			}
+			return this; // No children at offset
+		}
+		
+		/// <summary>
+		/// The error that occured in the context of this node (excluding nested nodes)
+		/// </summary>
+		public IEnumerable<SyntaxError> MySyntaxErrors {
+			get {
+				if (internalObject.SyntaxErrors != null) {
+					return internalObject.SyntaxErrors.Select(e => new SyntaxError(startOffset + e.RelativeStart, startOffset + e.RelativeEnd, e.Description));
+				} else {
+					return EmptyList<SyntaxError>.Instance;
+				}
+			}
+		}
+		
+		/// <summary>
+		/// The error that occured in the context of this node and all nested nodes.
+		/// It has O(n) cost.
+		/// </summary>
+		public IEnumerable<SyntaxError> SyntaxErrors {
+			get {
+				return TreeTraversal.PreOrder(this, n => n.Children).SelectMany(obj => obj.MySyntaxErrors);
+			}
+		}
+		
+		/// <summary> Get all ancestors of this node </summary>
+		public IEnumerable<AXmlObject> Ancestors {
+			get {
+				AXmlObject curr = this.Parent;
+				while(curr != null) {
+					yield return curr;
+					curr = curr.Parent;
+				}
+			}
+		}
+		
+		#region Helper methods
+		
+		/// <summary> The part of name before ":" </summary>
+		/// <returns> Empty string if not found </returns>
+		internal static string GetNamespacePrefix(string name)
+		{
+			if (string.IsNullOrEmpty(name)) return string.Empty;
+			int colonIndex = name.IndexOf(':');
+			if (colonIndex != -1) {
+				return name.Substring(0, colonIndex);
+			} else {
+				return string.Empty;
+			}
+		}
+		
+		/// <summary> The part of name after ":" </summary>
+		/// <returns> Whole name if ":" not found </returns>
+		internal static string GetLocalName(string name)
+		{
+			if (string.IsNullOrEmpty(name)) return string.Empty;
+			int colonIndex = name.IndexOf(':');
+			if (colonIndex != -1) {
+				return name.Remove(0, colonIndex + 1);
+			} else {
+				return name ?? string.Empty;
+			}
+		}
+		
+		#endregion
+		
+		/// <summary> Call appropriate visit method on the given visitor </summary>
+		public abstract void AcceptVisitor(AXmlVisitor visitor);
+		
+		/// <summary>
+		/// Gets the start offset of the segment.
+		/// </summary>
+		public int StartOffset {
+			get { return startOffset; }
+		}
+		
+		int ISegment.Offset {
+			get { return startOffset; }
+		}
+		
+		/// <inheritdoc/>
+		public int Length {
+			get { return internalObject.Length; }
+		}
+		
+		/// <inheritdoc/>
+		public int EndOffset {
+			get { return startOffset + internalObject.Length; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlParser.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlParser.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlParser.cs	(revision 11807)
@@ -0,0 +1,146 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// XML parser that is error tolerant.
+	/// </summary>
+	public class AXmlParser
+	{
+		/// <summary>
+		/// Generate syntax error when seeing entity reference other then the built-in ones
+		/// </summary>
+		public bool UnknownEntityReferenceIsError { get; set; }
+		
+		IList<AXmlObject> CreatePublic(IList<InternalObject> internalObjects)
+		{
+			var publicObjects = new AXmlObject[internalObjects.Count];
+			int pos = 0;
+			for (int i = 0; i < internalObjects.Count; i++) {
+				publicObjects[i] = internalObjects[i].CreatePublicObject(null, pos);
+				pos += internalObjects[i].Length;
+			}
+			return Array.AsReadOnly(publicObjects);
+		}
+		
+		/// <summary>
+		/// Parses a document into a flat list of tags.
+		/// </summary>
+		/// <returns>Parsed tag soup.</returns>
+		public IList<AXmlObject> ParseTagSoup(ITextSource textSource,
+		                                      CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			var reader = new TagReader(this, textSource, false);
+			var internalObjects = reader.ReadAllObjects(cancellationToken);
+			return CreatePublic(internalObjects);
+		}
+		
+		/// <summary>
+		/// Parses a document incrementally into a flat list of tags.
+		/// </summary>
+		/// <param name="oldParserState">The parser state from a previous call to ParseIncremental(). Use null for the first call.</param>
+		/// <param name="newTextSource">The text source for the new document version.</param>
+		/// <param name="newParserState">Out: the new parser state, pass this to the next ParseIncremental() call.</param>
+		/// <param name="cancellationToken">Optional: cancellation token.</param>
+		/// <returns>Parsed tag soup.</returns>
+		public IList<AXmlObject> ParseTagSoupIncremental(
+			IncrementalParserState oldParserState, ITextSource newTextSource, out IncrementalParserState newParserState,
+			CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (newTextSource == null)
+				throw new ArgumentNullException("newTextSource");
+			var internalObjects = InternalParseIncremental(oldParserState, newTextSource, out newParserState, false, cancellationToken);
+			return CreatePublic(internalObjects);
+		}
+		
+		List<InternalObject> InternalParseIncremental(
+			IncrementalParserState oldParserState, ITextSource newTextSource, out IncrementalParserState newParserState,
+			bool collapseProperlyNestedElements, CancellationToken cancellationToken)
+		{
+			var reader = new TagReader(this, newTextSource, collapseProperlyNestedElements);
+			ITextSourceVersion newVersion = newTextSource.Version;
+			var reuseMap = oldParserState != null ? oldParserState.GetReuseMapTo(newVersion) : null;
+			
+			List<InternalObject> internalObjects;
+			if (reuseMap != null)
+				internalObjects = reader.ReadAllObjectsIncremental(oldParserState.Objects, reuseMap, cancellationToken);
+			else
+				internalObjects = reader.ReadAllObjects(cancellationToken);
+			
+			if (newVersion != null)
+				newParserState = new IncrementalParserState(newTextSource.TextLength, newVersion, internalObjects.ToArray());
+			else
+				newParserState = null;
+			
+			return internalObjects;
+		}
+		
+		/// <summary>
+		/// Parses a document.
+		/// </summary>
+		public AXmlDocument Parse(ITextSource textSource, CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (textSource == null)
+				throw new ArgumentNullException("textSource");
+			var reader = new TagReader(this, textSource, true);
+			var internalObjects = reader.ReadAllObjects(cancellationToken);
+			var heuristic = new TagMatchingHeuristics(textSource);
+			return new AXmlDocument(null, 0, heuristic.CreateDocument(internalObjects, cancellationToken));
+		}
+		
+		/// <summary>
+		/// Parses a document incrementally into a flat list of tags.
+		/// </summary>
+		/// <param name="oldParserState">The parser state from a previous call to ParseIncremental(). Use null for the first call.</param>
+		/// <param name="newTextSource">The text source for the new document version.</param>
+		/// <param name="newParserState">Out: the new parser state, pass this to the next ParseIncremental() call.</param>
+		/// <param name="cancellationToken">Optional: cancellation token.</param>
+		/// <returns>Parsed tag soup.</returns>
+		public AXmlDocument ParseIncremental(
+			IncrementalParserState oldParserState, ITextSource newTextSource, out IncrementalParserState newParserState,
+			CancellationToken cancellationToken = default(CancellationToken))
+		{
+			if (newTextSource == null)
+				throw new ArgumentNullException("newTextSource");
+			var internalObjects = InternalParseIncremental(oldParserState, newTextSource, out newParserState, true, cancellationToken);
+			var heuristic = new TagMatchingHeuristics(newTextSource);
+			return new AXmlDocument(null, 0, heuristic.CreateDocument(internalObjects, cancellationToken));
+		}
+		
+		/// <summary>
+		/// Checks whether the given name is a valid XML name.
+		/// </summary>
+		public static bool IsValidXmlName(string name)
+		{
+			if (string.IsNullOrWhiteSpace(name))
+				throw new ArgumentException("The XML name cannot be null, empty or consist solely of white space", "name");
+			return TagReader.IsValidName(name);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlReader.cs	(revision 11807)
@@ -0,0 +1,478 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Xml;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// XmlReader implementation that reads from an <see cref="AXmlDocument"/>.
+	/// </summary>
+	sealed class AXmlReader : XmlReader, IXmlLineInfo
+	{
+		readonly ObjectIterator objectIterator;
+		readonly XmlReaderSettings settings;
+		Func<int, TextLocation> offsetToTextLocation;
+		readonly XmlNameTable nameTable;
+		readonly XmlNamespaceManager nsManager;
+		ReadState readState = ReadState.Initial;
+		XmlNodeType elementNodeType = XmlNodeType.None;
+		IList<InternalAttribute> attributes;
+		int attributeIndex = -1;
+		bool inAttributeValue;
+		
+		internal AXmlReader(ObjectIterator objectIterator, XmlReaderSettings settings = null, Func<int, TextLocation> offsetToTextLocation = null)
+		{
+			this.objectIterator = objectIterator;
+			this.settings = settings ?? new XmlReaderSettings();
+			this.offsetToTextLocation = offsetToTextLocation;
+			this.nameTable = this.settings.NameTable ?? new NameTable();
+			this.nsManager = new XmlNamespaceManager(this.nameTable);
+			objectIterator.StopAtElementEnd = true;
+		}
+		
+		public override void ResolveEntity()
+		{
+			throw new NotSupportedException();
+		}
+		
+		public override ReadState ReadState {
+			get { return readState; }
+		}
+		
+		public override XmlReaderSettings Settings {
+			get { return settings; }
+		}
+		
+		public override bool ReadAttributeValue()
+		{
+			if (attributeIndex >= 0 && !inAttributeValue) {
+				inAttributeValue = true;
+				return true;
+			}
+			return false;
+		}
+		
+		public override bool Read()
+		{
+			switch (readState) {
+				case ReadState.Initial:
+					readState = ReadState.Interactive;
+					return ReadCurrentPosition();
+				case ReadState.Interactive:
+					LeaveNode();
+					objectIterator.MoveInto();
+					return ReadCurrentPosition();
+				default:
+					return false;
+			}
+		}
+		
+		bool ReadCurrentPosition()
+		{
+			attributes = null;
+			attributeIndex = -1;
+			inAttributeValue = false;
+			while (true) {
+				var obj = objectIterator.CurrentObject;
+				if (obj == null) {
+					readState = ReadState.EndOfFile;
+					elementNodeType = XmlNodeType.None;
+					return false;
+				} else if (objectIterator.IsAtElementEnd) {
+					if (IsEmptyElement) {
+						// Don't report EndElement for empty elements
+						nsManager.PopScope();
+					} else {
+						elementNodeType = XmlNodeType.EndElement;
+						return true;
+					}
+				} else if (obj is InternalElement) {
+					// element start
+					elementNodeType = XmlNodeType.Element;
+					InternalTag startTag = ((InternalTag)obj.NestedObjects[0]);
+					nsManager.PushScope();
+					if (startTag.NestedObjects != null) {
+						attributes = startTag.NestedObjects.OfType<InternalAttribute>().ToList();
+						for (int i = 0; i < attributes.Count; i++) {
+							var attr = attributes[i];
+							if (attr.Name.StartsWith("xmlns:", StringComparison.Ordinal))
+								nsManager.AddNamespace(AXmlObject.GetLocalName(attr.Name), attr.Value);
+							else if (attr.Name == "xmlns")
+								nsManager.AddNamespace(string.Empty, attr.Value);
+						}
+					}
+					return true;
+				} else if (obj is InternalText) {
+					InternalText text = (InternalText)obj;
+					if (text.ContainsOnlyWhitespace) {
+						elementNodeType = XmlNodeType.Whitespace;
+					} else {
+						elementNodeType = XmlNodeType.Text;
+					}
+					return true;
+				} else if (obj is InternalTag) {
+					InternalTag tag = (InternalTag)obj;
+					if (tag.IsStartOrEmptyTag || tag.IsEndTag) {
+						// start/end tags can be skipped as the parent InternalElement already handles them
+					} else if (tag.IsComment && !settings.IgnoreComments) {
+						elementNodeType = XmlNodeType.Comment;
+						return true;
+					} else if (tag.IsProcessingInstruction && !settings.IgnoreProcessingInstructions) {
+						if (tag.Name == "xml") {
+							elementNodeType = XmlNodeType.XmlDeclaration;
+							attributes = tag.NestedObjects.OfType<InternalAttribute>().ToList();
+						} else {
+							elementNodeType = XmlNodeType.ProcessingInstruction;
+						}
+						return true;
+					} else if (tag.IsCData) {
+						elementNodeType = XmlNodeType.CDATA;
+						return true;
+					} else {
+						// TODO all other tags
+					}
+				} else {
+					throw new NotSupportedException();
+				}
+				objectIterator.MoveInto();
+			}
+		}
+		
+		void LeaveNode()
+		{
+			if (elementNodeType == XmlNodeType.EndElement) {
+				nsManager.PopScope();
+			}
+		}
+		
+		public override void Skip()
+		{
+			if (readState == ReadState.Interactive) {
+				MoveToElement();
+				LeaveNode();
+				objectIterator.MoveNext();
+				ReadCurrentPosition();
+			}
+		}
+		
+		public override string Prefix {
+			get {
+				if (readState != ReadState.Interactive)
+					return string.Empty;
+				if (attributeIndex >= 0) {
+					if (inAttributeValue)
+						return string.Empty;
+					return nameTable.Add(AXmlObject.GetNamespacePrefix(attributes[attributeIndex].Name));
+				}
+				InternalElement element = objectIterator.CurrentObject as InternalElement;
+				return element != null ? nameTable.Add(element.Prefix) : string.Empty;
+			}
+		}
+		
+		public override string NamespaceURI {
+			get {
+				if (readState != ReadState.Interactive)
+					return string.Empty;
+				if (attributeIndex >= 0 && !inAttributeValue && attributes[attributeIndex].Name == "xmlns")
+					return AXmlObject.XmlnsNamespace;
+				return LookupNamespace(this.Prefix) ?? string.Empty;
+			}
+		}
+		
+		public override string LocalName {
+			get {
+				if (readState != ReadState.Interactive)
+					return string.Empty;
+				if (attributeIndex >= 0) {
+					if (inAttributeValue)
+						return string.Empty;
+					return nameTable.Add(AXmlObject.GetLocalName(attributes[attributeIndex].Name));
+				}
+				string result;
+				switch (elementNodeType) {
+					case XmlNodeType.Element:
+					case XmlNodeType.EndElement:
+						result = ((InternalElement)objectIterator.CurrentObject).LocalName;
+						break;
+					case XmlNodeType.XmlDeclaration:
+						result = "xml";
+						break;
+					default:
+						return string.Empty;
+				}
+				return nameTable.Add(result);
+			}
+		}
+		
+		public override string Name {
+			get {
+				if (readState != ReadState.Interactive)
+					return string.Empty;
+				if (attributeIndex >= 0) {
+					if (inAttributeValue)
+						return string.Empty;
+					return nameTable.Add(attributes[attributeIndex].Name);
+				}
+				string result;
+				switch (elementNodeType) {
+					case XmlNodeType.Element:
+					case XmlNodeType.EndElement:
+						result = ((InternalElement)objectIterator.CurrentObject).Name;
+						break;
+					case XmlNodeType.XmlDeclaration:
+						result = "xml";
+						break;
+					default:
+						return string.Empty;
+				}
+				return nameTable.Add(result);
+			}
+		}
+		
+		public override bool IsEmptyElement {
+			get {
+				if (readState != ReadState.Interactive || attributeIndex >= 0)
+					return false;
+				InternalElement element = objectIterator.CurrentObject as InternalElement;
+				return element != null && element.NestedObjects.Length == 1;
+			}
+		}
+		
+		public override string Value {
+			get {
+				if (readState != ReadState.Interactive)
+					return string.Empty;
+				if (attributeIndex >= 0)
+					return attributes[attributeIndex].Value;
+				switch (elementNodeType) {
+					case XmlNodeType.Text:
+					case XmlNodeType.Whitespace:
+						return ((InternalText)objectIterator.CurrentObject).Value;
+					case XmlNodeType.Comment:
+					case XmlNodeType.CDATA:
+						var nestedObjects = objectIterator.CurrentObject.NestedObjects;
+						if (nestedObjects.Length == 1)
+							return ((InternalText)nestedObjects[0]).Value;
+						else
+							return string.Empty;
+					case XmlNodeType.XmlDeclaration:
+						StringBuilder b = new StringBuilder();
+						foreach (var attr in objectIterator.CurrentObject.NestedObjects.OfType<InternalAttribute>()) {
+							if (b.Length > 0)
+								b.Append(' ');
+							b.Append(attr.Name);
+							b.Append('=');
+							b.Append('"');
+							b.Append(attr.Value);
+							b.Append('"');
+						}
+						return b.ToString();
+					default:
+						return string.Empty;
+				}
+			}
+		}
+		
+		public override bool HasValue {
+			get {
+				if (readState != ReadState.Interactive)
+					return false;
+				if (attributeIndex >= 0)
+					return true;
+				switch (elementNodeType) {
+					case XmlNodeType.Text:
+					case XmlNodeType.Whitespace:
+					case XmlNodeType.Comment:
+					case XmlNodeType.XmlDeclaration:
+					case XmlNodeType.CDATA:
+						return true;
+					default:
+						return false;
+				}
+			}
+		}
+		
+		public override XmlNodeType NodeType {
+			get {
+				if (attributeIndex >= 0)
+					return inAttributeValue ? XmlNodeType.Text : XmlNodeType.Attribute;
+				else
+					return elementNodeType;
+			}
+		}
+		
+		public override XmlNameTable NameTable {
+			get { return nameTable; }
+		}
+		
+		public override bool MoveToFirstAttribute()
+		{
+			return DoMoveToAttribute(0);
+		}
+		
+		public override bool MoveToNextAttribute()
+		{
+			return DoMoveToAttribute(attributeIndex + 1);
+		}
+		
+		public override void MoveToAttribute(int i)
+		{
+			if (!DoMoveToAttribute(i))
+				throw new ArgumentOutOfRangeException("i");
+		}
+		
+		bool DoMoveToAttribute(int i)
+		{
+			if (i >= 0 && i < this.AttributeCount) {
+				attributeIndex = i;
+				inAttributeValue = false;
+				return true;
+			}
+			return false;
+		}
+		
+		public override bool MoveToElement()
+		{
+			if (attributeIndex >= 0) {
+				attributeIndex = -1;
+				inAttributeValue = false;
+				return true;
+			}
+			return false;
+		}
+		
+		int GetAttributeIndex(string name)
+		{
+			if (attributes == null)
+				return -1;
+			for (int i = 0; i < attributes.Count; i++) {
+				if (attributes[i].Name == name)
+					return i;
+			}
+			return -1;
+		}
+		
+		int GetAttributeIndex(string name, string ns)
+		{
+			if (attributes == null)
+				return -1;
+			for (int i = 0; i < attributes.Count; i++) {
+				if (AXmlObject.GetLocalName(attributes[i].Name) == name && (LookupNamespace(AXmlObject.GetNamespacePrefix(attributes[i].Name)) ?? string.Empty) == ns)
+					return i;
+			}
+			return -1;
+		}
+		
+		public override bool MoveToAttribute(string name, string ns)
+		{
+			return DoMoveToAttribute(GetAttributeIndex(name, ns));
+		}
+		
+		public override bool MoveToAttribute(string name)
+		{
+			return DoMoveToAttribute(GetAttributeIndex(name));
+		}
+		
+		public override string LookupNamespace(string prefix)
+		{
+			return nsManager.LookupNamespace(prefix);
+		}
+		
+		public override string GetAttribute(int i)
+		{
+			if (attributes == null || i < 0 || i >= attributes.Count)
+				return null;
+			return attributes[i].Value;
+		}
+		
+		public override string GetAttribute(string name, string namespaceURI)
+		{
+			return GetAttribute(GetAttributeIndex(name, namespaceURI));
+		}
+		
+		public override string GetAttribute(string name)
+		{
+			return GetAttribute(GetAttributeIndex(name));
+		}
+		
+		public override bool EOF {
+			get { return readState == ReadState.EndOfFile; }
+		}
+		
+		public override int Depth {
+			get {
+				if (attributeIndex < 0)
+					return objectIterator.Depth;
+				else
+					return objectIterator.Depth + (inAttributeValue ? 2 : 1);
+			}
+		}
+		
+		public override void Close()
+		{
+			readState = ReadState.Closed;
+			offsetToTextLocation = null;
+		}
+		
+		public override string BaseURI {
+			get { return string.Empty; }
+		}
+		
+		public override int AttributeCount {
+			get { return attributes != null ? attributes.Count : 0; }
+		}
+		
+		int CurrentPosition {
+			get {
+				if (attributeIndex < 0)
+					return objectIterator.CurrentPosition;
+				else
+					return objectIterator.CurrentPosition + attributes[attributeIndex].StartRelativeToParent;
+			}
+		}
+		
+		public int LineNumber {
+			get {
+				if (offsetToTextLocation != null)
+					return offsetToTextLocation(CurrentPosition).Line;
+				else
+					return 0;
+			}
+		}
+		
+		public int LinePosition {
+			get {
+				if (offsetToTextLocation != null)
+					return offsetToTextLocation(CurrentPosition).Column - 1;
+				else
+					return 0;
+			}
+		}
+		
+		bool IXmlLineInfo.HasLineInfo()
+		{
+			return offsetToTextLocation != null;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlTag.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlTag.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlTag.cs	(revision 11807)
@@ -0,0 +1,98 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Represents any markup starting with "&lt;" and (hopefully) ending with ">"
+	/// </summary>
+	public class AXmlTag : AXmlObject
+	{
+		/// <summary> These identify the start of DTD elements </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification="ReadOnlyCollection is immutable")]
+		public static readonly ReadOnlyCollection<string> DtdNames = new ReadOnlyCollection<string>(
+			new string[] {"<!DOCTYPE", "<!NOTATION", "<!ELEMENT", "<!ATTLIST", "<!ENTITY" } );
+		
+		new readonly InternalTag internalObject;
+		
+		internal AXmlTag(AXmlObject parent, int startOffset, InternalTag internalObject)
+			: base(parent, startOffset, internalObject)
+		{
+			this.internalObject = internalObject;
+		}
+		
+		/// <summary> Opening bracket - usually "&lt;" </summary>
+		public string OpeningBracket {
+			get { return internalObject.OpeningBracket; }
+		}
+		
+		/// <summary> Name following the opening bracket </summary>
+		public string Name {
+			get { return internalObject.Name; }
+		}
+		
+		/// <summary> Gets the segment containing the tag name </summary>
+		public ISegment NameSegment {
+			get {
+				int start = startOffset + internalObject.RelativeNameStart;
+				return new XmlSegment(start, start + internalObject.Name.Length);
+			}
+		}
+		
+		/// <summary> Closing bracket - usually "&gt;" </summary>
+		public string ClosingBracket {
+			get { return internalObject.ClosingBracket; }
+		}
+		
+		/// <summary> True if tag starts with "&lt;" </summary>
+		public bool IsStartOrEmptyTag       { get { return internalObject.IsStartOrEmptyTag; } }
+		/// <summary> True if tag starts with "&lt;" and ends with "&gt;" </summary>
+		public bool IsStartTag              { get { return internalObject.IsStartTag; } }
+		/// <summary> True if tag starts with "&lt;" and does not end with "&gt;" </summary>
+		public bool IsEmptyTag              { get { return internalObject.IsEmptyTag; } }
+		/// <summary> True if tag starts with "&lt;/" </summary>
+		public bool IsEndTag                { get { return internalObject.IsEndTag; } }
+		/// <summary> True if tag starts with "&lt;?" </summary>
+		public bool IsProcessingInstruction { get { return internalObject.IsProcessingInstruction; } }
+		/// <summary> True if tag starts with "&lt;!--" </summary>
+		public bool IsComment               { get { return internalObject.IsComment; } }
+		/// <summary> True if tag starts with "&lt;![CDATA[" </summary>
+		public bool IsCData                 { get { return internalObject.IsCData; } }
+		/// <summary> True if tag starts with one of the DTD starts </summary>
+		public bool IsDocumentType          { get { return internalObject.IsDocumentType; } }
+		/// <summary> True if tag starts with "&lt;!" </summary>
+		public bool IsUnknownBang           { get { return internalObject.IsUnknownBang; } }
+		
+		/// <inheritdoc/>
+		public override void AcceptVisitor(AXmlVisitor visitor)
+		{
+			visitor.VisitTag(this);
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} '{1}{2}{3}' Attr:{4}]", base.ToString(), this.OpeningBracket, this.Name, this.ClosingBracket, this.Children.Count);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlText.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlText.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlText.cs	(revision 11807)
@@ -0,0 +1,63 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Globalization;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Whitespace or character data
+	/// </summary>
+	public class AXmlText : AXmlObject
+	{
+		internal AXmlText(AXmlObject parent, int startOffset, InternalText internalObject)
+			: base(parent, startOffset, internalObject)
+		{
+		}
+		
+//		/// <summary> The type of the text node </summary>
+//		public TextType Type {
+//			get { return ((InternalText)internalObject).Type; }
+//		}
+		
+		/// <summary> The text with all entity references resloved </summary>
+		public string Value {
+			get { return ((InternalText)internalObject).Value; }
+		}
+		
+		/// <summary> True if the text contains only whitespace characters </summary>
+		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace",
+		                                                 Justification = "System.Xml also uses 'Whitespace'")]
+		public bool ContainsOnlyWhitespace {
+			get { return ((InternalText)internalObject).ContainsOnlyWhitespace; }
+		}
+		
+		/// <inheritdoc/>
+		public override void AcceptVisitor(AXmlVisitor visitor)
+		{
+			visitor.VisitText(this);
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			return string.Format(CultureInfo.InvariantCulture, "[{0} Text.Length={1}]", base.ToString(), this.Value.Length);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlVisitor.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlVisitor.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/AXmlVisitor.cs	(revision 11807)
@@ -0,0 +1,62 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Text;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Derive from this class to create visitor for the XML tree
+	/// </summary>
+	public abstract class AXmlVisitor
+	{
+		/// <summary> Visit AXmlDocument </summary>
+		public virtual void VisitDocument(AXmlDocument document)
+		{
+			foreach (AXmlObject child in document.Children)
+				child.AcceptVisitor(this);
+		}
+		
+		/// <summary> Visit AXmlElement </summary>
+		public virtual void VisitElement(AXmlElement element)
+		{
+			foreach (AXmlObject child in element.Children)
+				child.AcceptVisitor(this);
+		}
+		
+		/// <summary> Visit AXmlTag </summary>
+		public virtual void VisitTag(AXmlTag tag)
+		{
+			foreach (AXmlObject child in tag.Children)
+				child.AcceptVisitor(this);
+		}
+		
+		/// <summary> Visit AXmlAttribute </summary>
+		public virtual void VisitAttribute(AXmlAttribute attribute)
+		{
+			
+		}
+		
+		/// <summary> Visit AXmlText </summary>
+		public virtual void VisitText(AXmlText text)
+		{
+			
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/DocumentationElement.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/DocumentationElement.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/DocumentationElement.cs	(revision 11807)
@@ -0,0 +1,285 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using ICSharpCode.NRefactory.Documentation;
+using ICSharpCode.NRefactory.TypeSystem;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Represents an element in the XML documentation.
+	/// Any occurrences of "&lt;inheritdoc/>" are replaced with the inherited documentation.
+	/// </summary>
+	public class XmlDocumentationElement
+	{
+		/// <summary>
+		/// Gets the XML documentation element for the specified entity.
+		/// Returns null if no documentation is found.
+		/// </summary>
+		public static XmlDocumentationElement Get(IEntity entity, bool inheritDocIfMissing = true)
+		{
+			if (entity == null)
+				return null;
+			var documentationComment = entity.Documentation;
+			if (documentationComment != null) {
+				return Create(documentationComment, entity);
+			}
+			
+			IMember member = entity as IMember;
+			if (inheritDocIfMissing && member != null) {
+				if (member.SymbolKind == SymbolKind.Constructor) {
+					// For constructors, the documentation of the base class ctor
+					// isn't really suitable as constructors are not inherited.
+					// We'll use the type's documentation instead:
+					return Get(entity.DeclaringTypeDefinition, inheritDocIfMissing);
+				}
+				foreach (IMember baseMember in InheritanceHelper.GetBaseMembers(member, includeImplementedInterfaces: true)) {
+					documentationComment = baseMember.Documentation;
+					if (documentationComment != null)
+						return Create(documentationComment, baseMember);
+				}
+			}
+			return null;
+		}
+		
+		static XmlDocumentationElement Create(DocumentationComment documentationComment, IEntity declaringEntity)
+		{
+			var doc = new AXmlParser().Parse(documentationComment.Xml);
+			return new XmlDocumentationElement(doc, declaringEntity, documentationComment.ResolveCref);
+		}
+		
+		readonly AXmlObject xmlObject;
+		readonly AXmlElement element;
+		readonly IEntity declaringEntity;
+		readonly Func<string, IEntity> crefResolver;
+		volatile string textContent;
+		
+		/// <summary>
+		/// Inheritance level; used to prevent cyclic doc inheritance.
+		/// </summary>
+		int nestingLevel;
+		
+		/// <summary>
+		/// Creates a new documentation element.
+		/// </summary>
+		public XmlDocumentationElement(AXmlElement element, IEntity declaringEntity, Func<string, IEntity> crefResolver)
+		{
+			if (element == null)
+				throw new ArgumentNullException("element");
+			this.element = element;
+			this.xmlObject = element;
+			this.declaringEntity = declaringEntity;
+			this.crefResolver = crefResolver;
+		}
+		
+		/// <summary>
+		/// Creates a new documentation element.
+		/// </summary>
+		public XmlDocumentationElement(AXmlDocument document, IEntity declaringEntity, Func<string, IEntity> crefResolver)
+		{
+			if (document == null)
+				throw new ArgumentNullException("document");
+			this.xmlObject = document;
+			this.declaringEntity = declaringEntity;
+			this.crefResolver = crefResolver;
+		}
+		
+		/// <summary>
+		/// Creates a new documentation element.
+		/// </summary>
+		public XmlDocumentationElement(string text, IEntity declaringEntity)
+		{
+			if (text == null)
+				throw new ArgumentNullException("text");
+			this.declaringEntity = declaringEntity;
+			this.textContent = text;
+		}
+		
+		/// <summary>
+		/// Gets the entity on which this documentation was originally declared.
+		/// May return null.
+		/// </summary>
+		public IEntity DeclaringEntity {
+			get { return declaringEntity; }
+		}
+		
+		IEntity referencedEntity;
+		volatile bool referencedEntityInitialized;
+		
+		/// <summary>
+		/// Gets the entity referenced by the 'cref' attribute.
+		/// May return null.
+		/// </summary>
+		public IEntity ReferencedEntity {
+			get {
+				if (!referencedEntityInitialized) {
+					string cref = GetAttribute("cref");
+					if (cref != null && crefResolver != null)
+						referencedEntity = crefResolver(cref);
+					referencedEntityInitialized = true;
+				}
+				return referencedEntity;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the element name.
+		/// </summary>
+		public string Name {
+			get {
+				return element != null ? element.Name : string.Empty;
+			}
+		}
+		
+		/// <summary>
+		/// Gets the attribute value.
+		/// </summary>
+		public string GetAttribute(string name)
+		{
+			return element != null ? element.GetAttributeValue(name) : string.Empty;
+		}
+		
+		/// <summary>
+		/// Gets whether this is a pure text node.
+		/// </summary>
+		public bool IsTextNode {
+			get { return xmlObject == null; }
+		}
+		
+		/// <summary>
+		/// Gets the text content.
+		/// </summary>
+		public string TextContent {
+			get {
+				if (textContent == null) {
+					StringBuilder b = new StringBuilder();
+					foreach (var child in this.Children)
+						b.Append(child.TextContent);
+					textContent = b.ToString();
+				}
+				return textContent;
+			}
+		}
+		
+		IList<XmlDocumentationElement> children;
+		
+		/// <summary>
+		/// Gets the child elements.
+		/// </summary>
+		public IList<XmlDocumentationElement> Children {
+			get {
+				if (xmlObject == null)
+					return EmptyList<XmlDocumentationElement>.Instance;
+				return LazyInitializer.EnsureInitialized(
+					ref this.children,
+					() => CreateElements(xmlObject.Children, declaringEntity, crefResolver, nestingLevel));
+			}
+		}
+		
+		static readonly string[] doNotInheritIfAlreadyPresent = {
+			"example", "exclude", "filterpriority", "preliminary", "summary",
+			"remarks", "returns", "threadsafety", "value"
+		};
+		
+		static List<XmlDocumentationElement> CreateElements(IEnumerable<AXmlObject> childObjects, IEntity declaringEntity, Func<string, IEntity> crefResolver, int nestingLevel)
+		{
+			List<XmlDocumentationElement> list = new List<XmlDocumentationElement>();
+			foreach (var child in childObjects) {
+				var childText = child as AXmlText;
+				var childTag = child as AXmlTag;
+				var childElement = child as AXmlElement;
+				if (childText != null) {
+					list.Add(new XmlDocumentationElement(childText.Value, declaringEntity));
+				} else if (childTag != null && childTag.IsCData) {
+					foreach (var text in childTag.Children.OfType<AXmlText>())
+						list.Add(new XmlDocumentationElement(text.Value, declaringEntity));
+				} else if (childElement != null) {
+					if (nestingLevel < 5 && childElement.Name == "inheritdoc") {
+						string cref = childElement.GetAttributeValue("cref");
+						IEntity inheritedFrom = null;
+						DocumentationComment inheritedDocumentation = null;
+						if (cref != null) {
+							inheritedFrom = crefResolver(cref);
+							if (inheritedFrom != null)
+								inheritedDocumentation = inheritedFrom.Documentation;
+						} else {
+							foreach (IMember baseMember in InheritanceHelper.GetBaseMembers((IMember)declaringEntity, includeImplementedInterfaces: true)) {
+								inheritedDocumentation = baseMember.Documentation;
+								if (inheritedDocumentation != null) {
+									inheritedFrom = baseMember;
+									break;
+								}
+							}
+						}
+						
+						if (inheritedDocumentation != null) {
+							var doc = new AXmlParser().Parse(inheritedDocumentation.Xml);
+							
+							// XPath filter not yet implemented
+							if (childElement.Parent is AXmlDocument && childElement.GetAttributeValue("select") == null) {
+								// Inheriting documentation at the root level
+								List<string> doNotInherit = new List<string>();
+								doNotInherit.Add("overloads");
+								doNotInherit.AddRange(childObjects.OfType<AXmlElement>().Select(e => e.Name).Intersect(
+									doNotInheritIfAlreadyPresent));
+								
+								var inheritedChildren = doc.Children.Where(
+									inheritedObject => {
+										AXmlElement inheritedElement = inheritedObject as AXmlElement;
+										return !(inheritedElement != null && doNotInherit.Contains(inheritedElement.Name));
+									});
+								
+								list.AddRange(CreateElements(inheritedChildren, inheritedFrom, inheritedDocumentation.ResolveCref, nestingLevel + 1));
+							}
+						}
+					} else {
+						list.Add(new XmlDocumentationElement(childElement, declaringEntity, crefResolver) { nestingLevel = nestingLevel });
+					}
+				}
+			}
+			if (list.Count > 0 && list[0].IsTextNode) {
+				if (string.IsNullOrWhiteSpace(list[0].textContent))
+					list.RemoveAt(0);
+				else
+					list[0].textContent = list[0].textContent.TrimStart();
+			}
+			if (list.Count > 0 && list[list.Count - 1].IsTextNode) {
+				if (string.IsNullOrWhiteSpace(list[list.Count - 1].textContent))
+					list.RemoveAt(list.Count - 1);
+				else
+					list[list.Count - 1].textContent = list[list.Count - 1].textContent.TrimEnd();
+			}
+			return list;
+		}
+		
+		/// <inheritdoc/>
+		public override string ToString()
+		{
+			if (element != null)
+				return "<" + element.Name + ">";
+			else
+				return this.TextContent;
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ICSharpCode.NRefactory.Xml-5.5.0.csproj
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ICSharpCode.NRefactory.Xml-5.5.0.csproj	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ICSharpCode.NRefactory.Xml-5.5.0.csproj	(revision 11807)
@@ -0,0 +1,135 @@
+﻿<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{C5AE5D30-AE8C-4017-B741-99E084281000}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>ICSharpCode.NRefactory.Xml</RootNamespace>
+    <AssemblyName>ICSharpCode.NRefactory.Xml</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x86</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
+    <DebugSymbols>true</DebugSymbols>
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE;DEBUG</DefineConstants>
+    <DebugType>full</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
+    <OutputPath>$(SolutionDir)\bin\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <Optimize>true</Optimize>
+    <DebugType>pdbonly</DebugType>
+    <PlatformTarget>x64</PlatformTarget>
+    <ErrorReport>prompt</ErrorReport>
+    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
+    <Prefer32Bit>false</Prefer32Bit>
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+  </PropertyGroup>
+  <PropertyGroup>
+    <SignAssembly>true</SignAssembly>
+  </PropertyGroup>
+  <PropertyGroup>
+    <AssemblyOriginatorKeyFile>HeuristicLab.snk</AssemblyOriginatorKeyFile>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="AXmlAttribute.cs" />
+    <Compile Include="AXmlDocument.cs" />
+    <Compile Include="AXmlElement.cs" />
+    <Compile Include="AXmlObject.cs" />
+    <Compile Include="AXmlParser.cs" />
+    <Compile Include="AXmlReader.cs" />
+    <Compile Include="AXmlTag.cs" />
+    <Compile Include="AXmlText.cs" />
+    <Compile Include="AXmlVisitor.cs" />
+    <Compile Include="DocumentationElement.cs" />
+    <Compile Include="IncrementalParserState.cs" />
+    <Compile Include="InternalDocument.cs" />
+    <Compile Include="Log.cs" />
+    <Compile Include="ObjectIterator.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="ReuseEqualityComparer.cs" />
+    <Compile Include="SyntaxError.cs" />
+    <Compile Include="TagMatchingHeuristics.cs" />
+    <Compile Include="TagReader.cs" />
+    <Compile Include="TextType.cs" />
+    <Compile Include="TokenReader.cs" />
+    <Compile Include="XmlSegment.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="HeuristicLab.snk" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\NRefactory-5.5.0\ICSharpCode.NRefactory-5.5.0.csproj">
+      <Project>{1022483b-7cf4-4162-827f-984b64eaf8b3}</Project>
+      <Name>ICSharpCode.NRefactory-5.5.0</Name>
+      <Private>False</Private>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/IncrementalParserState.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/IncrementalParserState.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/IncrementalParserState.cs	(revision 11807)
@@ -0,0 +1,115 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Encapsulates the state of the incremental tag soup parser.
+	/// </summary>
+	public class IncrementalParserState
+	{
+		internal readonly int TextLength;
+		internal readonly ITextSourceVersion Version;
+		internal readonly InternalObject[] Objects;
+		
+		internal IncrementalParserState(int textLength, ITextSourceVersion version, InternalObject[] objects)
+		{
+			this.TextLength = textLength;
+			this.Version = version;
+			this.Objects = objects;
+		}
+		
+		internal List<UnchangedSegment> GetReuseMapTo(ITextSourceVersion newVersion)
+		{
+			ITextSourceVersion oldVersion = this.Version;
+			if (oldVersion == null || newVersion == null)
+				return null;
+			if (!oldVersion.BelongsToSameDocumentAs(newVersion))
+				return null;
+			List<UnchangedSegment> reuseMap = new List<UnchangedSegment>();
+			reuseMap.Add(new UnchangedSegment(0, 0, this.TextLength));
+			foreach (var change in oldVersion.GetChangesTo(newVersion)) {
+				bool needsSegmentRemoval = false;
+				for (int i = 0; i < reuseMap.Count; i++) {
+					UnchangedSegment segment = reuseMap[i];
+					if (segment.NewOffset + segment.Length <= change.Offset) {
+						// change is completely after this segment
+						continue;
+					}
+					if (change.Offset + change.RemovalLength <= segment.NewOffset) {
+						// change is completely before this segment
+						segment.NewOffset += change.InsertionLength - change.RemovalLength;
+						reuseMap[i] = segment;
+						continue;
+					}
+					// Change is overlapping segment.
+					// Split segment into two parts: the part before change, and the part after change.
+					var segmentBefore = new UnchangedSegment(segment.OldOffset, segment.NewOffset, change.Offset - segment.NewOffset);
+					Debug.Assert(segmentBefore.Length < segment.Length);
+					
+					int lengthAtEnd = segment.NewOffset + segment.Length - (change.Offset + change.RemovalLength);
+					var segmentAfter = new UnchangedSegment(
+						segment.OldOffset + segment.Length - lengthAtEnd,
+						change.Offset + change.InsertionLength,
+						lengthAtEnd);
+					Debug.Assert(segmentAfter.Length < segment.Length);
+					Debug.Assert(segmentBefore.Length + segmentAfter.Length <= segment.Length);
+					Debug.Assert(segmentBefore.NewOffset + segmentBefore.Length <= segmentAfter.NewOffset);
+					Debug.Assert(segmentBefore.OldOffset + segmentBefore.Length <= segmentAfter.OldOffset);
+					if (segmentBefore.Length > 0 && segmentAfter.Length > 0) {
+						reuseMap[i] = segmentBefore;
+						reuseMap.Insert(++i, segmentAfter);
+					} else if (segmentBefore.Length > 0) {
+						reuseMap[i] = segmentBefore;
+					} else {
+						reuseMap[i] = segmentAfter;
+						if (segmentAfter.Length <= 0)
+							needsSegmentRemoval = true;
+					}
+				}
+				if (needsSegmentRemoval)
+					reuseMap.RemoveAll(s => s.Length <= 0);
+			}
+			return reuseMap;
+		}
+	}
+	
+	struct UnchangedSegment
+	{
+		public int OldOffset;
+		public int NewOffset;
+		public int Length;
+		
+		public UnchangedSegment(int oldOffset, int newOffset, int length)
+		{
+			this.OldOffset = oldOffset;
+			this.NewOffset = newOffset;
+			this.Length = length;
+		}
+		
+		public override string ToString()
+		{
+			return string.Format("[UnchangedSegment OldOffset={0}, NewOffset={1}, Length={2}]", OldOffset, NewOffset, Length);
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/InternalDocument.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/InternalDocument.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/InternalDocument.cs	(revision 11807)
@@ -0,0 +1,175 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	internal abstract class InternalObject
+	{
+		public int StartRelativeToParent;
+		public int Length;
+		/// <summary>Length that was touched to parsed this object.</summary>
+		public int LengthTouched;
+		public InternalSyntaxError[] SyntaxErrors;
+		public InternalObject[] NestedObjects;
+		
+		public InternalObject SetStartRelativeToParent(int newStartRelativeToParent)
+		{
+			if (newStartRelativeToParent == StartRelativeToParent)
+				return this;
+			InternalObject obj = (InternalObject)MemberwiseClone();
+			obj.StartRelativeToParent = newStartRelativeToParent;
+			return obj;
+		}
+		
+		public abstract AXmlObject CreatePublicObject(AXmlObject parent, int parentStartOffset);
+	}
+	
+	sealed class InternalDocument : InternalObject
+	{
+		public override AXmlObject CreatePublicObject(AXmlObject parent, int parentStartOffset)
+		{
+			return new AXmlDocument(parent, (parent != null ? parentStartOffset + StartRelativeToParent : parentStartOffset), this);
+		}
+	}
+	
+	sealed class InternalText : InternalObject
+	{
+		public TextType Type;
+		public bool ContainsOnlyWhitespace;
+		public string Value;
+		
+		public override AXmlObject CreatePublicObject(AXmlObject parent, int parentStartOffset)
+		{
+			return new AXmlText(parent, (parent != null ? parentStartOffset + StartRelativeToParent : parentStartOffset), this);
+		}
+		
+		public override string ToString()
+		{
+			return "Text: " + this.Value.Replace("\n", "\\n").Replace("\r", "\\r");
+		}
+	}
+	
+	sealed class InternalTag : InternalObject
+	{
+		public string OpeningBracket;
+		public int RelativeNameStart;
+		public string Name;
+		public string ClosingBracket;
+		
+		/// <summary> True if tag starts with "&lt;" </summary>
+		public bool IsStartOrEmptyTag       { get { return OpeningBracket == "<"; } }
+		/// <summary> True if tag starts with "&lt;" and ends with "&gt;" </summary>
+		public bool IsStartTag              { get { return OpeningBracket == "<" && ClosingBracket == ">"; } }
+		/// <summary> True if tag starts with "&lt;" and does not end with "&gt;" </summary>
+		public bool IsEmptyTag              { get { return OpeningBracket == "<" && ClosingBracket != ">" ; } }
+		/// <summary> True if tag starts with "&lt;/" </summary>
+		public bool IsEndTag                { get { return OpeningBracket == "</"; } }
+		/// <summary> True if tag starts with "&lt;?" </summary>
+		public bool IsProcessingInstruction { get { return OpeningBracket == "<?"; } }
+		/// <summary> True if tag starts with "&lt;!--" </summary>
+		public bool IsComment               { get { return OpeningBracket == "<!--"; } }
+		/// <summary> True if tag starts with "&lt;![CDATA[" </summary>
+		public bool IsCData                 { get { return OpeningBracket == "<![CDATA["; } }
+		/// <summary> True if tag starts with one of the DTD starts </summary>
+		public bool IsDocumentType          { get { return AXmlTag.DtdNames.Contains(OpeningBracket); } }
+		/// <summary> True if tag starts with "&lt;!" </summary>
+		public bool IsUnknownBang           { get { return OpeningBracket == "<!"; } }
+		
+		public override AXmlObject CreatePublicObject(AXmlObject parent, int parentStartOffset)
+		{
+			return new AXmlTag(parent, (parent != null ? parentStartOffset + StartRelativeToParent : parentStartOffset), this);
+		}
+		
+		public override string ToString()
+		{
+			return "Tag: " + OpeningBracket + Name + ClosingBracket;
+		}
+		
+		public InternalTag AddSyntaxError(string description)
+		{
+			if (this.SyntaxErrors != null && this.SyntaxErrors.Length > 0)
+				return this; // don't add error if there already is one
+			InternalTag tag = (InternalTag)MemberwiseClone();
+			tag.SyntaxErrors = new InternalSyntaxError[] { new InternalSyntaxError(0, Length, description) };
+			return tag;
+		}
+	}
+	
+	struct InternalSyntaxError
+	{
+		public readonly int RelativeStart;
+		public readonly int RelativeEnd;
+		public readonly string Description;
+		
+		public InternalSyntaxError(int relativeStart, int relativeEnd, string description)
+		{
+			this.RelativeStart = relativeStart;
+			this.RelativeEnd = relativeEnd;
+			this.Description = description;
+		}
+	}
+	
+	sealed class InternalAttribute : InternalObject
+	{
+		public string Name;
+		public int EqualsSignLength; // length of equals sign including the surrounding whitespace
+		public string Value;
+		
+		public override AXmlObject CreatePublicObject(AXmlObject parent, int parentStartOffset)
+		{
+			return new AXmlAttribute(parent, (parent != null ? parentStartOffset + StartRelativeToParent : parentStartOffset), this);
+		}
+		
+		public override string ToString()
+		{
+			return "Attribute: " + Name + "='" + Value + "'";
+		}
+	}
+	
+	sealed class InternalElement : InternalObject
+	{
+		public bool HasEndTag;
+		public bool IsPropertyNested;
+		public readonly string Name;
+		
+		public InternalElement(InternalTag tag)
+		{
+			this.Name = tag.Name;
+		}
+		
+		public string Prefix {
+			get { return AXmlObject.GetNamespacePrefix(Name); }
+		}
+		
+		public string LocalName {
+			get { return AXmlObject.GetLocalName(Name); }
+		}
+		
+		public override AXmlObject CreatePublicObject(AXmlObject parent, int parentStartOffset)
+		{
+			return new AXmlElement(parent, (parent != null ? parentStartOffset + StartRelativeToParent : parentStartOffset), this);
+		}
+		
+		public override string ToString()
+		{
+			return "Element: " + NestedObjects[0].ToString();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/Log.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/Log.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/Log.cs	(revision 11807)
@@ -0,0 +1,88 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.Runtime.Serialization;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	static class Log
+	{
+		/// <summary> Throws exception if condition is false </summary>
+		internal static void Assert(bool condition, string message)
+		{
+			if (!condition) {
+				throw new InternalException("Assertion failed: " + message);
+			}
+		}
+
+		/// <summary> Throws exception if condition is false </summary>
+		[Conditional("DEBUG")]
+		internal static void DebugAssert(bool condition, string message)
+		{
+			if (!condition) {
+				throw new InternalException("Assertion failed: " + message);
+			}
+		}
+
+		[Conditional("DEBUG")]
+		internal static void WriteLine(string text, params object[] pars)
+		{
+			//System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "XML: " + text, pars));
+		}
+	}
+	
+	
+	/// <summary>
+	/// Exception used for internal errors in XML parser.
+	/// This exception indicates a bug in NRefactory.
+	/// </summary>
+	[Serializable]
+	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic", Justification = "This exception is not public because it is not supposed to be caught by user code - it indicates a bug in AvalonEdit.")]
+	class InternalException : Exception
+	{
+		/// <summary>
+		/// Creates a new InternalException instance.
+		/// </summary>
+		public InternalException() : base()
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new InternalException instance.
+		/// </summary>
+		public InternalException(string message) : base(message)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new InternalException instance.
+		/// </summary>
+		public InternalException(string message, Exception innerException) : base(message, innerException)
+		{
+		}
+		
+		/// <summary>
+		/// Creates a new InternalException instance.
+		/// </summary>
+		protected InternalException(SerializationInfo info, StreamingContext context) : base(info, context)
+		{
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ObjectIterator.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ObjectIterator.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ObjectIterator.cs	(revision 11807)
@@ -0,0 +1,109 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Iterates through an internal object tree.
+	/// </summary>
+	sealed class ObjectIterator
+	{
+		Stack<InternalObject[]> listStack = new Stack<InternalObject[]>();
+		Stack<int> indexStack = new Stack<int>();
+		
+		InternalObject[] objects;
+		int currentIndex;
+		InternalObject currentObject;
+		int currentPosition;
+		internal bool StopAtElementEnd;
+		bool isAtElementEnd;
+		
+		public ObjectIterator(InternalObject[] objects, int startPosition = 0)
+		{
+			this.currentPosition = startPosition;
+			this.objects = objects;
+			if (objects.Length > 0)
+				this.currentObject = objects[0];
+		}
+		
+		public InternalObject CurrentObject {
+			get { return currentObject; }
+		}
+		
+		public int CurrentPosition {
+			get { return currentPosition; }
+		}
+		
+		public bool IsAtElementEnd {
+			get { return isAtElementEnd; }
+		}
+		
+		public int Depth {
+			get { return listStack.Count; }
+		}
+		
+		public void MoveNext()
+		{
+			if (currentObject == null)
+				return;
+			currentIndex++;
+			currentPosition += currentObject.Length;
+			isAtElementEnd = false;
+			while (currentIndex >= objects.Length && listStack.Count > 0) {
+				objects = listStack.Pop();
+				currentIndex = indexStack.Pop();
+				if (this.StopAtElementEnd) {
+					isAtElementEnd = true;
+					break;
+				} else {
+					currentIndex++;
+				}
+			}
+			currentObject = (currentIndex < objects.Length ? objects[currentIndex] : null);
+		}
+		
+		public void MoveInto()
+		{
+			if (isAtElementEnd || !(currentObject is InternalElement)) {
+				MoveNext();
+			} else {
+				listStack.Push(objects);
+				indexStack.Push(currentIndex);
+				objects = currentObject.NestedObjects;
+				currentIndex = 0;
+				currentObject = objects[0];
+			}
+		}
+		
+		/// <summary>
+		/// Skips all nodes in front of 'position'
+		/// </summary>
+		public void SkipTo(int position)
+		{
+			while (currentObject != null && currentPosition < position) {
+				if (currentPosition + currentObject.Length <= position)
+					MoveNext();
+				else
+					MoveInto();
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/Properties/AssemblyInfo.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/Properties/AssemblyInfo.cs	(revision 11807)
@@ -0,0 +1,38 @@
+﻿using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following 
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ICSharpCode.NRefactory.Xml")]
+[assembly: AssemblyDescription("Error-tolerant XML parser")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("ICSharpCode")]
+[assembly: AssemblyProduct("SharpDevelop/MonoDevelop")]
+[assembly: AssemblyCopyright("Copyright 2010-2014 AlphaSierraPapa and Xamarin Inc.")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible 
+// to COM components.  If you need to access a type in this assembly from 
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+[assembly: CLSCompliant(true)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("96ec7d96-1821-4572-a309-ba3b1ff93b24")]
+
+// Version information for an assembly consists of the following four values:
+//
+//      Major Version
+//      Minor Version 
+//      Build Number
+//      Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers 
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("5.0.0.0")]
+[assembly: AssemblyFileVersion("5.5.0")]
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ReuseEqualityComparer.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ReuseEqualityComparer.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/ReuseEqualityComparer.cs	(revision 11807)
@@ -0,0 +1,52 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// Determines whether two objects are identical (one is a reused version of the other).
+	/// </summary>
+	public class ReuseEqualityComparer : IEqualityComparer<AXmlObject>
+	{
+		/// <summary>
+		/// Determines whether two objects are identical (one is a reused version of the other).
+		/// </summary>
+		public bool Equals(AXmlObject x, AXmlObject y)
+		{
+			if (x == y)
+				return true;
+			if (x == null || y == null)
+				return false;
+			return x.internalObject == y.internalObject;
+		}
+		
+		/// <summary>
+		/// Gets the object's hash code so that reused versions of an object have the same hash code.
+		/// </summary>
+		public int GetHashCode(AXmlObject obj)
+		{
+			if (obj == null)
+				return 0;
+			else
+				return obj.internalObject.GetHashCode();
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/SyntaxError.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/SyntaxError.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/SyntaxError.cs	(revision 11807)
@@ -0,0 +1,73 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary>
+	/// A syntax error.
+	/// </summary>
+	public class SyntaxError : ISegment
+	{
+		readonly int startOffset;
+		readonly int endOffset;
+		readonly string description;
+		
+		/// <summary>
+		/// Creates a new syntax error.
+		/// </summary>
+		public SyntaxError(int startOffset, int endOffset, string description)
+		{
+			if (description == null)
+				throw new ArgumentNullException("description");
+			this.startOffset = startOffset;
+			this.endOffset = endOffset;
+			this.description = description;
+		}
+		
+		/// <summary>
+		/// Gets a description of the syntax error.
+		/// </summary>
+		public string Description {
+			get { return description; }
+		}
+		
+		/// <summary>
+		/// Gets the start offset of the segment.
+		/// </summary>
+		public int StartOffset {
+			get { return startOffset; }
+		}
+		
+		int ISegment.Offset {
+			get { return startOffset; }
+		}
+		
+		/// <inheritdoc/>
+		public int Length {
+			get { return endOffset - startOffset; }
+		}
+		
+		/// <inheritdoc/>
+		public int EndOffset {
+			get { return endOffset; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TagMatchingHeuristics.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TagMatchingHeuristics.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TagMatchingHeuristics.cs	(revision 11807)
@@ -0,0 +1,352 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading;
+using ICSharpCode.NRefactory.Editor;
+using ICSharpCode.NRefactory.Utils;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	class TagMatchingHeuristics
+	{
+		readonly ITextSource textSource;
+		
+		const int MaxConfigurationCount = 30;
+		
+		public TagMatchingHeuristics(ITextSource textSource)
+		{
+			this.textSource = textSource;
+		}
+		
+		public InternalDocument CreateDocument(List<InternalObject> tagSoup, CancellationToken cancellationToken)
+		{
+			var stack = InsertPlaceholderTags(tagSoup, cancellationToken);
+			InternalDocument doc = new InternalDocument();
+			var docElements = CreateElements(ref stack);
+			docElements.Reverse(); // reverse due to stack
+			doc.NestedObjects = new InternalObject[docElements.Count];
+			int pos = 0;
+			for (int i = 0; i < docElements.Count; i++) {
+				doc.NestedObjects[i] = docElements[i].SetStartRelativeToParent(pos);
+				pos += doc.NestedObjects[i].Length;
+			}
+			doc.Length = pos;
+			return doc;
+		}
+		
+		#region Heuristic implementation - Inserting place holders into object stream
+		// Tags used to guide the element creation
+		static readonly InternalTag StartTagPlaceholder = new InternalTag { OpeningBracket = "<", ClosingBracket = ">" };
+		static readonly InternalTag EndTagPlaceholder = new InternalTag { OpeningBracket = "</", ClosingBracket = ">" };
+		
+		class OpenTagStack
+		{
+			readonly OpenTagStack prev;
+			public readonly string Name;
+			public readonly int IndentationLevel;
+			readonly int hashCode;
+			
+			public OpenTagStack()
+			{
+			}
+			
+			private OpenTagStack(OpenTagStack prev, string name, int indentationLevel)
+			{
+				this.prev = prev;
+				this.Name = name;
+				this.IndentationLevel = indentationLevel;
+				unchecked {
+					this.hashCode = prev.hashCode * 27 + (name.GetHashCode() ^ indentationLevel);
+				}
+			}
+			
+			public bool IsEmpty {
+				get { return prev == null; }
+			}
+			
+			public OpenTagStack Push(string name, int indentationLevel)
+			{
+				return new OpenTagStack(this, name, indentationLevel);
+			}
+			
+			public OpenTagStack Pop()
+			{
+				return prev;
+			}
+			
+			public override int GetHashCode()
+			{
+				return hashCode;
+			}
+			
+			public override bool Equals(object obj)
+			{
+				OpenTagStack o = obj as OpenTagStack;
+				if (o != null && hashCode == o.hashCode && IndentationLevel == o.IndentationLevel && Name == o.Name) {
+					if (prev == o.prev)
+						return true;
+					if (prev == null || o.prev == null)
+						return false;
+					return prev.Equals(o.prev);
+				}
+				return false;
+			}
+		}
+		
+		struct Configuration
+		{
+			public readonly OpenTagStack OpenTags;
+			public readonly ImmutableStack<InternalObject> Document;
+			public readonly uint Cost;
+			
+			public Configuration(OpenTagStack openTags, ImmutableStack<InternalObject> document, uint cost)
+			{
+				this.OpenTags = openTags;
+				this.Document = document;
+				this.Cost = cost;
+			}
+		}
+		
+		struct ConfigurationList
+		{
+			internal Configuration[] configurations;
+			internal int count;
+			
+			public static ConfigurationList Create()
+			{
+				return new ConfigurationList {
+					configurations = new Configuration[MaxConfigurationCount],
+					count = 0
+				};
+			}
+			
+			public void Clear()
+			{
+				this.count = 0;
+			}
+			
+			public void Add(OpenTagStack openTags, ImmutableStack<InternalObject> document, uint cost)
+			{
+				Add(new Configuration(openTags, document, cost));
+			}
+			
+			public void Add(Configuration configuration)
+			{
+				for (int i = 0; i < count; i++) {
+					if (configuration.OpenTags.Equals(configurations[i].OpenTags)) {
+						// We found an existing configuration with the same state.
+						// Either replace it, or drop this configurations --
+						// we don't want to add multiple configurations with the same state.
+						if (configuration.Cost < configurations[i].Cost)
+							configurations[i] = configuration;
+						return;
+					}
+				}
+				if (count < configurations.Length) {
+					configurations[count++] = configuration;
+				} else {
+					int index = 0;
+					uint maxCost = configurations[0].Cost;
+					for (int i = 1; i < configurations.Length; i++) {
+						if (configurations[i].Cost < maxCost) {
+							maxCost = configurations[i].Cost;
+							index = i;
+						}
+					}
+					configurations[index] = configuration;
+				}
+			}
+		}
+		
+		const uint InfiniteCost = uint.MaxValue;
+		const uint MissingEndTagCost = 10;
+		const uint IgnoreEndTagCost = 10;
+		const uint MismatchedNameCost = 6;
+		
+		int GetIndentationBefore(int position)
+		{
+			int indentation = 0;
+			while (--position >= 0) {
+				char c = textSource.GetCharAt(position);
+				switch (c) {
+					case ' ':
+						indentation++;
+						break;
+					case '\t':
+						indentation += 4;
+						break;
+					case '\n':
+						return indentation;
+					default:
+						return -1;
+				}
+			}
+			return indentation;
+		}
+		
+		ImmutableStack<InternalObject> InsertPlaceholderTags(List<InternalObject> objects, CancellationToken cancellationToken)
+		{
+			// Calculate indentation levels in front of the tags:
+			int[] indentationBeforeTags = new int[objects.Count];
+			int pos = 0;
+			for (int i = 0; i < objects.Count; i++) {
+				if (objects[i] is InternalTag)
+					indentationBeforeTags[i] = GetIndentationBefore(pos);
+				pos += objects[i].Length;
+			}
+			
+			// Create initial configuration:
+			ConfigurationList listA = ConfigurationList.Create();
+			ConfigurationList listB = ConfigurationList.Create();
+			listA.Add(new Configuration(new OpenTagStack(), ImmutableStack<InternalObject>.Empty, 0));
+			
+			for (int i = 0; i < indentationBeforeTags.Length; i++) {
+				cancellationToken.ThrowIfCancellationRequested();
+				ProcessObject(objects[i], indentationBeforeTags[i], listA, ref listB);
+				Swap(ref listA, ref listB);
+			}
+			
+			Configuration cheapestConfiguration = new Configuration(null, null, InfiniteCost);
+			for (int i = 0; i < listA.count; i++) {
+				Configuration c = listA.configurations[i];
+				if (c.Cost < cheapestConfiguration.Cost) {
+					while (!c.OpenTags.IsEmpty) {
+						c = new Configuration(c.OpenTags.Pop(), c.Document.Push(EndTagPlaceholder), c.Cost + MissingEndTagCost);
+					}
+					if (c.Cost < cheapestConfiguration.Cost)
+						cheapestConfiguration = c;
+				}
+			}
+			Log.WriteLine("Best configuration has cost {0}", cheapestConfiguration.Cost);
+			return cheapestConfiguration.Document;
+		}
+		
+		static void Swap(ref ConfigurationList a, ref ConfigurationList b)
+		{
+			ConfigurationList tmp = a;
+			a = b;
+			b = tmp;
+		}
+		
+		void ProcessObject(InternalObject obj, int indentationLevel, ConfigurationList oldConfigurations, ref ConfigurationList newConfigurations)
+		{
+			newConfigurations.Clear();
+			InternalTag tag = obj as InternalTag;
+			for (int i = 0; i < oldConfigurations.count; i++) {
+				Configuration c = oldConfigurations.configurations[i];
+				if (c.Cost == InfiniteCost)
+					continue;
+				if (tag != null && tag.IsStartTag) {
+					// Push start tag
+					newConfigurations.Add(
+						c.OpenTags.Push(tag.Name, indentationLevel),
+						c.Document.Push(obj),
+						c.Cost
+					);
+				} else if (tag != null && tag.IsEndTag) {
+					// We can ignore this end tag
+					newConfigurations.Add(
+						c.OpenTags,
+						c.Document.Push(StartTagPlaceholder).Push(obj),
+						c.Cost + IgnoreEndTagCost
+					);
+					// We can match this end tag with one of the currently open tags
+					var openTags = c.OpenTags;
+					var documentWithInsertedEndTags = c.Document;
+					uint newCost = c.Cost;
+					while (!openTags.IsEmpty) {
+						uint matchCost = 0;
+						if (openTags.IndentationLevel >= 0 && indentationLevel >= 0)
+							matchCost += (uint)Math.Abs(openTags.IndentationLevel - indentationLevel);
+						if (openTags.Name != tag.Name)
+							matchCost += MismatchedNameCost;
+						newConfigurations.Add(
+							openTags.Pop(),
+							documentWithInsertedEndTags.Push(obj),
+							newCost + matchCost
+						);
+						newCost += MissingEndTagCost;
+						openTags = openTags.Pop();
+						documentWithInsertedEndTags = documentWithInsertedEndTags.Push(EndTagPlaceholder);
+					}
+				} else {
+					newConfigurations.Add(
+						c.OpenTags,
+						c.Document.Push(obj),
+						c.Cost
+					);
+				}
+			}
+		}
+		#endregion
+		
+		#region Create Elements from stack with place holders
+		List<InternalObject> CreateElements(ref ImmutableStack<InternalObject> inputObjects)
+		{
+			List<InternalObject> objects = new List<InternalObject>();
+			while (!inputObjects.IsEmpty) {
+				var obj = inputObjects.Peek();
+				var tag = obj as InternalTag;
+				if (tag != null && tag.IsStartTag)
+					break;
+				inputObjects = inputObjects.Pop();
+				if (tag != null && tag.IsEndTag) {
+					if (inputObjects.Peek() == StartTagPlaceholder) {
+						objects.Add(tag.AddSyntaxError("Matching opening tag was not found"));
+						inputObjects = inputObjects.Pop();
+					} else {
+						var childElements = CreateElements(ref inputObjects);
+						var startTag = (InternalTag)inputObjects.Peek();
+						inputObjects = inputObjects.Pop();
+						childElements.Add(startTag);
+						childElements.Reverse();
+						if (tag != EndTagPlaceholder) {
+							// add end tag
+							if (startTag.Name != tag.Name) {
+								childElements.Add(tag.AddSyntaxError("Expected '</" + startTag.Name + ">'. End tag must have same name as start tag."));
+							} else {
+								childElements.Add(tag);
+							}
+						}
+						InternalElement e = new InternalElement(startTag);
+						e.HasEndTag = (tag != EndTagPlaceholder);
+						e.NestedObjects = new InternalObject[childElements.Count];
+						int pos = 0;
+						for (int i = 0; i < childElements.Count; i++) {
+							e.NestedObjects[i] = childElements[i].SetStartRelativeToParent(pos);
+							pos += e.NestedObjects[i].Length;
+						}
+						e.Length = pos;
+						if (tag == EndTagPlaceholder) {
+							e.SyntaxErrors = new [] { new InternalSyntaxError(pos, pos, "Missing '</" + startTag.Name + ">'") };
+						}
+						objects.Add(e);
+					}
+				} else {
+					objects.Add(obj);
+				}
+			}
+			return objects;
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TagReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TagReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TagReader.cs	(revision 11807)
@@ -0,0 +1,836 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	class TagReader : TokenReader
+	{
+		readonly AXmlParser tagSoupParser;
+		readonly Stack<string> elementNameStack;
+		
+		public TagReader(AXmlParser tagSoupParser, ITextSource input, bool collapseProperlyNestedElements) : base(input)
+		{
+			this.tagSoupParser = tagSoupParser;
+			if (collapseProperlyNestedElements)
+				elementNameStack = new Stack<string>();
+		}
+		
+		public List<InternalObject> ReadAllObjects(CancellationToken cancellationToken)
+		{
+			while (HasMoreData()) {
+				cancellationToken.ThrowIfCancellationRequested();
+				ReadObject();
+			}
+			return objects;
+		}
+		
+		public List<InternalObject> ReadAllObjectsIncremental(InternalObject[] oldObjects, List<UnchangedSegment> reuseMap, CancellationToken cancellationToken)
+		{
+			ObjectIterator oldObjectIterator = new ObjectIterator(oldObjects);
+			int reuseMapIndex = 0;
+			while (reuseMapIndex < reuseMap.Count) {
+				var reuseEntry = reuseMap[reuseMapIndex];
+				while (this.CurrentLocation < reuseEntry.NewOffset) {
+					cancellationToken.ThrowIfCancellationRequested();
+					ReadObject();
+				}
+				if (this.CurrentLocation >= reuseEntry.NewOffset + reuseEntry.Length) {
+					reuseMapIndex++;
+					continue;
+				}
+				Debug.Assert(reuseEntry.NewOffset <= this.CurrentLocation && this.CurrentLocation < reuseEntry.NewOffset + reuseEntry.Length);
+				// reuse the nodes within this reuseEntry starting at oldOffset:
+				int oldOffset = this.CurrentLocation - reuseEntry.NewOffset + reuseEntry.OldOffset;
+				// seek to oldOffset in the oldObjects array:
+				oldObjectIterator.SkipTo(oldOffset);
+				if (oldObjectIterator.CurrentPosition == oldOffset) {
+					// reuse old objects within this reuse entry:
+					int reuseEnd = reuseEntry.OldOffset + reuseEntry.Length;
+					while (oldObjectIterator.CurrentObject != null && oldObjectIterator.CurrentPosition + oldObjectIterator.CurrentObject.LengthTouched < reuseEnd) {
+						StoreObject(oldObjectIterator.CurrentObject);
+						Skip(oldObjectIterator.CurrentObject.Length);
+						oldObjectIterator.MoveNext();
+					}
+					reuseMapIndex++; // go to next re-use map
+				} else {
+					// We are in a region where old objects are available, but aren't aligned correctly.
+					// Don't skip this reuse entry, and read a single object so that we can re-align
+					ReadObject();
+				}
+			}
+			while (HasMoreData()) {
+				cancellationToken.ThrowIfCancellationRequested();
+				ReadObject();
+			}
+			return objects;
+		}
+		
+		void StoreObject(InternalObject obj)
+		{
+			objects.Add(obj);
+			
+			// Now combine properly-nested elements:
+			if (elementNameStack == null)
+				return; // parsing tag soup
+			InternalTag tag = obj as InternalTag;
+			if (tag == null)
+				return;
+			if (tag.IsEmptyTag) {
+				// the tag is its own element
+				objects[objects.Count - 1] = new InternalElement(tag) {
+					Length = tag.Length,
+					LengthTouched = tag.LengthTouched,
+					IsPropertyNested = true,
+					StartRelativeToParent = tag.StartRelativeToParent,
+					NestedObjects = new [] { tag.SetStartRelativeToParent(0) }
+				};
+			} else if (tag.IsStartTag) {
+				elementNameStack.Push(tag.Name);
+			} else if (tag.IsEndTag && elementNameStack.Count > 0) {
+				// Now look for the start element:
+				int startIndex = objects.Count - 2;
+				bool ok = false;
+				string expectedName = elementNameStack.Pop();
+				if (tag.Name == expectedName) {
+					while (startIndex > 0) {
+						var startTag = objects[startIndex] as InternalTag;
+						if (startTag != null) {
+							if (startTag.IsStartTag) {
+								ok = (startTag.Name == expectedName);
+								break;
+							} else if (startTag.IsEndTag) {
+								break;
+							}
+						}
+						startIndex--;
+					}
+				}
+				if (ok) {
+					// We found a correct nesting, let's create an element:
+					InternalObject[] nestedObjects = new InternalObject[objects.Count - startIndex];
+					int oldStartRelativeToParent = objects[startIndex].StartRelativeToParent;
+					int pos = 0;
+					int maxLengthTouched = 0;
+					for (int i = 0; i < nestedObjects.Length; i++) {
+						nestedObjects[i] = objects[startIndex + i].SetStartRelativeToParent(pos);
+						maxLengthTouched = Math.Max(maxLengthTouched, pos + nestedObjects[i].LengthTouched);
+						pos += nestedObjects[i].Length;
+					}
+					objects.RemoveRange(startIndex, nestedObjects.Length);
+					objects.Add(
+						new InternalElement((InternalTag)nestedObjects[0]) {
+							HasEndTag = true,
+							IsPropertyNested = true,
+							Length = pos,
+							LengthTouched = maxLengthTouched,
+							StartRelativeToParent = oldStartRelativeToParent,
+							NestedObjects = nestedObjects
+						});
+				} else {
+					// Mismatched name - the nesting isn't properly;
+					// clear the whole stack so that none of the currently open elements are closed as properly-nested.
+					elementNameStack.Clear();
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Reads one or more objects.
+		/// </summary>
+		void ReadObject()
+		{
+			if (TryPeek('<')) {
+				ReadTag();
+			} else {
+				ReadText(TextType.CharacterData);
+			}
+		}
+		
+		#region BeginInternalObject / EndInternalObject
+		List<InternalObject> objects = new List<InternalObject>();
+		int internalObjectStartPosition;
+		
+		int CurrentRelativeLocation {
+			get { return CurrentLocation - internalObjectStartPosition; }
+		}
+		
+		struct InternalObjectFrame
+		{
+			public readonly InternalObject InternalObject;
+			public readonly int ParentStartPosition;
+			
+			public InternalObjectFrame(InternalObject internalObject, int parentStartPosition)
+			{
+				this.InternalObject = internalObject;
+				this.ParentStartPosition = parentStartPosition;
+			}
+		}
+		
+		InternalObjectFrame BeginInternalObject(InternalObject internalObject)
+		{
+			return BeginInternalObject(internalObject, this.CurrentLocation);
+		}
+		
+		InternalObjectFrame BeginInternalObject(InternalObject internalObject, int beginLocation)
+		{
+			internalObject.StartRelativeToParent = beginLocation - internalObjectStartPosition;
+			
+			var frame = new InternalObjectFrame(internalObject, internalObjectStartPosition);
+			
+			internalObjectStartPosition = CurrentLocation;
+			return frame;
+		}
+		
+		void EndInternalObject(InternalObjectFrame frame, bool storeNewObject = true)
+		{
+			frame.InternalObject.Length = this.CurrentLocation - internalObjectStartPosition;
+			frame.InternalObject.LengthTouched = this.MaxTouchedLocation - internalObjectStartPosition;
+			frame.InternalObject.SyntaxErrors = GetSyntaxErrors();
+			if (storeNewObject)
+				StoreObject(frame.InternalObject);
+			internalObjectStartPosition = frame.ParentStartPosition;
+		}
+		#endregion
+		
+		#region Read Tag
+		/// <summary>
+		/// Context: "&lt;"
+		/// </summary>
+		void ReadTag()
+		{
+			AssertHasMoreData();
+			
+			int tagStart = this.CurrentLocation;
+			InternalTag tag = new InternalTag();
+			var frame = BeginInternalObject(tag);
+			
+			// Read the opening bracket
+			// It identifies the type of tag and parsing behavior for the rest of it
+			tag.OpeningBracket = ReadOpeningBracket();
+			
+			if (tag.IsUnknownBang && !TryPeekWhiteSpace())
+				OnSyntaxError(tagStart, this.CurrentLocation, "Unknown tag");
+			
+			if (tag.IsStartOrEmptyTag || tag.IsEndTag || tag.IsProcessingInstruction) {
+				// Read the name
+				TryMoveToNonWhiteSpace();
+				tag.RelativeNameStart = this.CurrentRelativeLocation;
+				string name;
+				if (TryReadName(out name)) {
+					if (!IsValidName(name)) {
+						OnSyntaxError(this.CurrentLocation - name.Length, this.CurrentLocation, "The name '{0}' is invalid", name);
+					}
+				} else {
+					OnSyntaxError("Element name expected");
+				}
+				tag.Name = name;
+			} else {
+				tag.Name = string.Empty;
+			}
+			
+			bool isXmlDeclr = tag.Name == "xml" && tag.IsProcessingInstruction;
+			int oldObjectCount = objects.Count;
+			
+			if (tag.IsStartOrEmptyTag || tag.IsEndTag || isXmlDeclr) {
+				// Read attributes for the tag
+				while (HasMoreData()) {
+					// Chech for all forbiden 'name' characters first - see ReadName
+					TryMoveToNonWhiteSpace();
+					if (TryPeek('<')) break;
+					string endBr;
+					int endBrStart = this.CurrentLocation; // Just peek
+					if (TryReadClosingBracket(out endBr)) {  // End tag
+						GoBack(endBrStart);
+						break;
+					}
+					
+					// We have "=\'\"" or name - read attribute
+					int attrStartOffset = this.CurrentLocation;
+					ReadAttribute();
+					if (tag.IsEndTag)
+						OnSyntaxError(attrStartOffset, this.CurrentLocation, "Attribute not allowed in end tag.");
+				}
+			} else if (tag.IsDocumentType) {
+				ReadContentOfDTD();
+			} else {
+				int start = this.CurrentLocation;
+				if (tag.IsComment) {
+					ReadText(TextType.Comment);
+				} else if (tag.IsCData) {
+					ReadText(TextType.CData);
+				} else if (tag.IsProcessingInstruction) {
+					ReadText(TextType.ProcessingInstruction);
+				} else if (tag.IsUnknownBang) {
+					ReadText(TextType.UnknownBang);
+				} else {
+					throw new InternalException(string.Format(CultureInfo.InvariantCulture, "Unknown opening bracket '{0}'", tag.OpeningBracket));
+				}
+				// Backtrack at complete start
+				if (IsEndOfFile() || (tag.IsUnknownBang && TryPeek('<'))) {
+					GoBack(start);
+					objects.RemoveRange(oldObjectCount, objects.Count - oldObjectCount);
+				}
+			}
+			
+			// Read closing bracket
+			string bracket;
+			TryReadClosingBracket(out bracket);
+			tag.ClosingBracket = bracket;
+			
+			// Error check
+			int brStart = this.CurrentLocation - (tag.ClosingBracket ?? string.Empty).Length;
+			int brEnd = this.CurrentLocation;
+			if (tag.Name == null) {
+				// One error was reported already
+			} else if (tag.IsStartOrEmptyTag) {
+				if (tag.ClosingBracket != ">" && tag.ClosingBracket != "/>") OnSyntaxError(brStart, brEnd, "'>' or '/>' expected");
+			} else if (tag.IsEndTag) {
+				if (tag.ClosingBracket != ">") OnSyntaxError(brStart, brEnd, "'>' expected");
+			} else if (tag.IsComment) {
+				if (tag.ClosingBracket != "-->") OnSyntaxError(brStart, brEnd, "'-->' expected");
+			} else if (tag.IsCData) {
+				if (tag.ClosingBracket != "]]>") OnSyntaxError(brStart, brEnd, "']]>' expected");
+			} else if (tag.IsProcessingInstruction) {
+				if (tag.ClosingBracket != "?>") OnSyntaxError(brStart, brEnd, "'?>' expected");
+			} else if (tag.IsUnknownBang) {
+				if (tag.ClosingBracket != ">") OnSyntaxError(brStart, brEnd, "'>' expected");
+			} else if (tag.IsDocumentType) {
+				if (tag.ClosingBracket != ">") OnSyntaxError(brStart, brEnd, "'>' expected");
+			} else {
+				throw new InternalException(string.Format(CultureInfo.InvariantCulture, "Unknown opening bracket '{0}'", tag.OpeningBracket));
+			}
+			
+			// Attribute name may not apper multiple times
+			if (objects.Count > oldObjectCount) {
+				// Move nested objects into tag.NestedObjects:
+				tag.NestedObjects = new InternalObject[objects.Count - oldObjectCount];
+				objects.CopyTo(oldObjectCount, tag.NestedObjects, 0, tag.NestedObjects.Length);
+				objects.RemoveRange(oldObjectCount, objects.Count - oldObjectCount);
+				
+				// Look for duplicate attributes:
+				HashSet<string> attributeNames = new HashSet<string>();
+				foreach (var obj in tag.NestedObjects) {
+					InternalAttribute attr = obj as InternalAttribute;
+					if (attr != null && !attributeNames.Add(attr.Name)) {
+						int attrStart = tagStart + attr.StartRelativeToParent;
+						OnSyntaxError(attrStart, attrStart + attr.Name.Length, "Attribute with name '{0}' already exists", attr.Name);
+					}
+				}
+			}
+			
+			EndInternalObject(frame);
+		}
+		#endregion
+		
+		#region Read DTD
+		void ReadContentOfDTD()
+		{
+			int start = this.CurrentLocation;
+			while (HasMoreData()) {
+				TryMoveToNonWhiteSpace();            // Skip whitespace
+				if (TryRead('\'')) TryMoveTo('\'');  // Skip single quoted string TODO: Bug
+				if (TryRead('\"')) TryMoveTo('\"');  // Skip single quoted string
+				if (TryRead('[')) {                  // Start of nested infoset
+					// Reading infoset
+					while (HasMoreData()) {
+						TryMoveToAnyOf('<', ']');
+						if (TryPeek('<')) {
+							if (start != this.CurrentLocation) {  // Two following tags
+								MakeText(start, this.CurrentLocation);
+							}
+							ReadTag();
+							start = this.CurrentLocation;
+						}
+						if (TryPeek(']')) break;
+					}
+				}
+				TryRead(']');                        // End of nested infoset
+				if (TryPeek('>')) break;             // Proper closing
+				if (TryPeek('<')) break;             // Malformed XML
+				TryMoveNext();                       // Skip anything else
+			}
+			if (start != this.CurrentLocation) {
+				MakeText(start, this.CurrentLocation);
+			}
+		}
+		
+		void MakeText(int start, int end)
+		{
+			Log.DebugAssert(end > start, "Empty text");
+			Log.DebugAssert(end == this.CurrentLocation, "end == current location");
+			
+			InternalText text = new InternalText();
+			var frame = BeginInternalObject(text, start);
+			text.Type = TextType.Other;
+			text.Value = GetText(start, end);
+			EndInternalObject(frame);
+		}
+		#endregion
+		
+		#region Read Brackets
+		/// <summary>
+		/// Reads any of the know opening brackets.  (only full bracket)
+		/// Context: "&lt;"
+		/// </summary>
+		string ReadOpeningBracket()
+		{
+			// We are using a lot of string literals so that the memory instances are shared
+			//int start = this.CurrentLocation;
+			if (TryRead('<')) {
+				if (TryRead('/')) {
+					return "</";
+				} else if (TryRead('?')) {
+					return "<?";
+				} else if (TryRead('!')) {
+					if (TryRead("--")) {
+						return "<!--";
+					} else if (TryRead("[CDATA[")) {
+						return "<![CDATA[";
+					} else {
+						foreach (string dtdName in AXmlTag.DtdNames) {
+							// the dtdName includes "<!"
+							if (TryRead(dtdName.Remove(0, 2))) return dtdName;
+						}
+						return "<!";
+					}
+				} else {
+					return "<";
+				}
+			} else {
+				throw new InternalException("'<' expected");
+			}
+		}
+		
+		/// <summary>
+		/// Reads any of the know closing brackets.  (only full bracket)
+		/// Context: any
+		/// </summary>
+		bool TryReadClosingBracket(out string bracket)
+		{
+			// We are using a lot of string literals so that the memory instances are shared
+			if (TryRead('>')) {
+				bracket = ">";
+			} else 	if (TryRead("/>")) {
+				bracket = "/>";
+			} else 	if (TryRead("?>")) {
+				bracket = "?>";
+			} else if (TryRead("-->")) {
+				bracket = "-->";
+			} else if (TryRead("]]>")) {
+				bracket = "]]>";
+			} else {
+				bracket = string.Empty;
+				return false;
+			}
+			return true;
+		}
+		#endregion
+		
+		#region Attributes
+		/// <summary>
+		/// Context: name or "=\'\""
+		/// </summary>
+		void ReadAttribute()
+		{
+			AssertHasMoreData();
+			
+			InternalAttribute attr = new InternalAttribute();
+			var frame = BeginInternalObject(attr);
+			
+			// Read name
+			string name;
+			if (TryReadName(out name)) {
+				if (!IsValidName(name)) {
+					OnSyntaxError(this.CurrentLocation - name.Length, this.CurrentLocation, "The name '{0}' is invalid", name);
+				}
+			} else {
+				OnSyntaxError("Attribute name expected");
+			}
+			attr.Name = name;
+			
+			// Read equals sign and surrounding whitespace
+			int checkpoint = this.CurrentLocation;
+			TryMoveToNonWhiteSpace();
+			if (TryRead('=')) {
+				int chk2 = this.CurrentLocation;
+				TryMoveToNonWhiteSpace();
+				if (!TryPeek('"') && !TryPeek('\'')) {
+					// Do not read whitespace if quote does not follow
+					GoBack(chk2);
+				}
+				attr.EqualsSignLength = this.CurrentLocation - checkpoint;
+			} else {
+				GoBack(checkpoint);
+				OnSyntaxError("'=' expected");
+				attr.EqualsSignLength = 0;
+			}
+			
+			// Read attribute value
+			int start = this.CurrentLocation;
+			char quoteChar = TryPeek('"') ? '"' : '\'';
+			bool startsWithQuote;
+			if (TryRead(quoteChar)) {
+				startsWithQuote = true;
+				int valueStart = this.CurrentLocation;
+				TryMoveToAnyOf(quoteChar, '<');
+				if (TryRead(quoteChar)) {
+					if (!TryPeekAnyOf(' ', '\t', '\n', '\r', '/', '>', '?')) {
+						if (TryPeekPrevious('=', 2) || (TryPeekPrevious('=', 3) && TryPeekPrevious(' ', 2))) {
+							// This actually most likely means that we are in the next attribute value
+							GoBack(valueStart);
+							ReadAttributeValue(quoteChar);
+							if (TryRead(quoteChar)) {
+								OnSyntaxError("White space or end of tag expected");
+							} else {
+								OnSyntaxError("Quote {0} expected (or add whitespace after the following one)", quoteChar);
+							}
+						} else {
+							OnSyntaxError("White space or end of tag expected");
+						}
+					}
+				} else {
+					// '<' or end of file
+					GoBack(valueStart);
+					ReadAttributeValue(quoteChar);
+					OnSyntaxError("Quote {0} expected", quoteChar);
+				}
+			} else {
+				startsWithQuote = false;
+				int valueStart = this.CurrentLocation;
+				ReadAttributeValue(null);
+				TryRead('\"');
+				TryRead('\'');
+				if (valueStart == this.CurrentLocation) {
+					OnSyntaxError("Attribute value expected");
+				} else {
+					OnSyntaxError(valueStart, this.CurrentLocation, "Attribute value must be quoted");
+				}
+			}
+			string val = GetText(start, this.CurrentLocation);
+			val = Unquote(val);
+			attr.Value = Dereference(val, startsWithQuote ? start + 1 : start);
+			
+			EndInternalObject(frame);
+		}
+		
+		/// <summary>
+		/// Read everything up to quote (excluding), opening/closing tag or attribute signature
+		/// </summary>
+		void ReadAttributeValue(char? quote)
+		{
+			while (HasMoreData()) {
+				// What is next?
+				int start = this.CurrentLocation;
+				TryMoveToNonWhiteSpace();  // Read white space (if any)
+				if (quote.HasValue) {
+					if (TryPeek(quote.Value)) return;
+				} else {
+					if (TryPeek('"') || TryPeek('\'')) return;
+				}
+				// Opening/closing tag
+				string endBr;
+				if (TryPeek('<') || TryReadClosingBracket(out endBr)) {
+					GoBack(start);
+					return;
+				}
+				// Try reading attribute signature
+				if (TryReadName()) {
+					int nameEnd = this.CurrentLocation;
+					if (TryMoveToNonWhiteSpace() && TryRead("=") &&
+					    TryMoveToNonWhiteSpace() && TryPeekAnyOf('"', '\''))
+					{
+						// Start of attribute.  Great
+						GoBack(start);
+						return;  // Done
+					} else {
+						// Just some gargabe - make it part of the value
+						GoBack(nameEnd);
+						continue;  // Read more
+					}
+				}
+				TryMoveNext(); // Accept everyting else
+			}
+		}
+		
+		/// <summary> Remove quoting from the given string </summary>
+		static string Unquote(string quoted)
+		{
+			if (string.IsNullOrEmpty(quoted)) return string.Empty;
+			char first = quoted[0];
+			if (quoted.Length == 1) return (first == '"' || first == '\'') ? string.Empty : quoted;
+			char last  = quoted[quoted.Length - 1];
+			if (first == '"' || first == '\'') {
+				if (first == last) {
+					// Remove both quotes
+					return quoted.Substring(1, quoted.Length - 2);
+				} else {
+					// Remove first quote
+					return quoted.Remove(0, 1);
+				}
+			} else {
+				if (last == '"' || last == '\'') {
+					// Remove last quote
+					return quoted.Substring(0, quoted.Length - 1);
+				} else {
+					// Keep whole string
+					return quoted;
+				}
+			}
+		}
+		#endregion
+		
+		#region Text
+		/// <summary>
+		/// Reads text.
+		/// </summary>
+		void ReadText(TextType type)
+		{
+			var text = new InternalText();
+			var frame = BeginInternalObject(text);
+			text.Type = type;
+			
+			int start = this.CurrentLocation;
+			int fragmentEnd = inputLength;
+			
+			// Whitespace would be skipped anyway by any operation
+			TryMoveToNonWhiteSpace(fragmentEnd);
+			int wsEnd = this.CurrentLocation;
+			
+			// Try move to the terminator given by the context
+			if (type == TextType.WhiteSpace) {
+				TryMoveToNonWhiteSpace(fragmentEnd);
+			} else if (type == TextType.CharacterData) {
+				while(true) {
+					if (!TryMoveToAnyOf(new char[] {'<', ']'}, fragmentEnd)) break; // End of fragment
+					if (TryPeek('<')) break;
+					if (TryPeek(']')) {
+						if (TryPeek("]]>")) {
+							OnSyntaxError(this.CurrentLocation, this.CurrentLocation + 3, "']]>' is not allowed in text");
+						}
+						TryMoveNext();
+						continue;
+					}
+					throw new InternalException("Infinite loop");
+				}
+			} else if (type == TextType.Comment) {
+				// Do not report too many errors
+				bool errorReported = false;
+				while(true) {
+					if (!TryMoveTo('-', fragmentEnd)) break; // End of fragment
+					if (TryPeek("-->")) break;
+					if (TryPeek("--") && !errorReported) {
+						OnSyntaxError(this.CurrentLocation, this.CurrentLocation + 2, "'--' is not allowed in comment");
+						errorReported = true;
+					}
+					TryMoveNext();
+				}
+			} else if (type == TextType.CData) {
+				while(true) {
+					// We can not use use TryMoveTo("]]>", fragmentEnd) because it may incorectly accept "]" at the end of fragment
+					if (!TryMoveTo(']', fragmentEnd)) break; // End of fragment
+					if (TryPeek("]]>")) break;
+					TryMoveNext();
+				}
+			} else if (type == TextType.ProcessingInstruction) {
+				while(true) {
+					if (!TryMoveTo('?', fragmentEnd)) break; // End of fragment
+					if (TryPeek("?>")) break;
+					TryMoveNext();
+				}
+			} else if (type == TextType.UnknownBang) {
+				TryMoveToAnyOf(new char[] {'<', '>'}, fragmentEnd);
+			} else {
+				throw new InternalException("Unknown type " + type);
+			}
+			
+			text.ContainsOnlyWhitespace = (wsEnd == this.CurrentLocation);
+			
+			string escapedValue = GetText(start, this.CurrentLocation);
+			if (type == TextType.CharacterData) {
+				text.Value = Dereference(escapedValue, start);
+			} else {
+				text.Value = escapedValue;
+			}
+			text.Value = GetCachedString(text.Value);
+			
+			EndInternalObject(frame, storeNewObject: this.CurrentLocation > start);
+		}
+		#endregion
+		
+		#region Dereference
+		const int maxEntityLength = 16; // The longest built-in one is 10 ("&#1114111;")
+		
+		string Dereference(string text, int textLocation)
+		{
+			StringBuilder sb = null;  // The dereferenced text so far (all up to 'curr')
+			int curr = 0;
+			while(true) {
+				// Reached end of input
+				if (curr == text.Length) {
+					if (sb != null) {
+						return sb.ToString();
+					} else {
+						return text;
+					}
+				}
+				
+				// Try to find reference
+				int start = text.IndexOf('&', curr);
+				
+				// No more references found
+				if (start == -1) {
+					if (sb != null) {
+						sb.Append(text, curr, text.Length - curr); // Add rest
+						return sb.ToString();
+					} else {
+						return text;
+					}
+				}
+				
+				// Append text before the enitiy reference
+				if (sb == null) sb = new StringBuilder(text.Length);
+				sb.Append(text, curr, start - curr);
+				curr = start;
+				
+				// Process the entity
+				int errorLoc = textLocation + sb.Length;
+				
+				// Find entity name
+				int end = text.IndexOfAny(new char[] {'&', ';'}, start + 1, Math.Min(maxEntityLength, text.Length - (start + 1)));
+				if (end == -1 || text[end] == '&') {
+					// Not found
+					OnSyntaxError(errorLoc, errorLoc + 1, "Entity reference must be terminated with ';'");
+					// Keep '&'
+					sb.Append('&');
+					curr++;
+					continue;  // Restart and next character location
+				}
+				string name = text.Substring(start + 1, end - (start + 1));
+				
+				// Resolve the name
+				string replacement;
+				if (name.Length == 0) {
+					replacement = null;
+					OnSyntaxError(errorLoc + 1, errorLoc + 1, "Entity name expected");
+				} else if (name == "amp") {
+					replacement = "&";
+				} else if (name == "lt") {
+					replacement = "<";
+				} else if (name == "gt") {
+					replacement = ">";
+				} else if (name == "apos") {
+					replacement = "'";
+				} else if (name == "quot") {
+					replacement = "\"";
+				} else if (name.Length > 0 && name[0] == '#') {
+					int num;
+					if (name.Length > 1 && name[1] == 'x') {
+						if (!int.TryParse(name.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture.NumberFormat, out num)) {
+							num = -1;
+							OnSyntaxError(errorLoc + 3, errorLoc + 1 + name.Length, "Hexadecimal code of unicode character expected");
+						}
+					} else {
+						if (!int.TryParse(name.Substring(1), NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out num)) {
+							num = -1;
+							OnSyntaxError(errorLoc + 2, errorLoc + 1 + name.Length, "Numeric code of unicode character expected");
+						}
+					}
+					if (num != -1) {
+						try {
+							replacement = char.ConvertFromUtf32(num);
+						} catch (ArgumentOutOfRangeException) {
+							replacement = null;
+							OnSyntaxError(errorLoc + 2, errorLoc + 1 + name.Length, "Invalid unicode character U+{0:X} ({0})", num);
+						}
+					} else {
+						replacement = null;
+					}
+				} else if (!IsValidName(name)) {
+					replacement = null;
+					OnSyntaxError(errorLoc + 1, errorLoc + 1, "Invalid entity name");
+				} else {
+					replacement = null;
+					if (tagSoupParser.UnknownEntityReferenceIsError) {
+						OnSyntaxError(errorLoc, errorLoc + 1 + name.Length + 1, "Unknown entity reference '{0}'", name);
+					}
+				}
+				
+				// Append the replacement to output
+				if (replacement != null) {
+					sb.Append(replacement);
+				} else {
+					sb.Append('&');
+					sb.Append(name);
+					sb.Append(';');
+				}
+				curr = end + 1;
+				continue;
+			}
+		}
+		#endregion
+		
+		#region Syntax Errors
+		List<InternalSyntaxError> syntaxErrors = new List<InternalSyntaxError>();
+		
+		InternalSyntaxError[] GetSyntaxErrors()
+		{
+			if (syntaxErrors.Count > 0) {
+				var arr = syntaxErrors.ToArray();
+				syntaxErrors.Clear();
+				return arr;
+			} else {
+				return null;
+			}
+		}
+		
+		void OnSyntaxError(string message, params object[] args)
+		{
+			OnSyntaxError(this.CurrentLocation, this.CurrentLocation + 1, message, args);
+		}
+		
+		void OnSyntaxError(int start, int end, string message, params object[] args)
+		{
+			if (end <= start) end = start + 1;
+			string formattedMessage = string.Format(CultureInfo.InvariantCulture, message, args);
+			Log.WriteLine("Syntax error ({0}-{1}): {2}", start, end, formattedMessage);
+			syntaxErrors.Add(new InternalSyntaxError(start - internalObjectStartPosition, end - internalObjectStartPosition, formattedMessage));
+		}
+		#endregion
+		
+		#region Helper functions
+		internal static bool IsValidName(string name)
+		{
+			try {
+				System.Xml.XmlConvert.VerifyName(name);
+				return true;
+			} catch (System.Xml.XmlException) {
+				return false;
+			}
+		}
+		#endregion
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TextType.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TextType.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TextType.cs	(revision 11807)
@@ -0,0 +1,47 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	/// <summary> Identifies the context in which the text occured </summary>
+	enum TextType
+	{
+		/// <summary> Ends with non-whitespace </summary>
+		WhiteSpace,
+		
+		/// <summary> Ends with "&lt;";  "]]&gt;" is error </summary>
+		CharacterData,
+		
+		/// <summary> Ends with "-->";  "--" is error </summary>
+		Comment,
+		
+		/// <summary> Ends with "]]&gt;" </summary>
+		CData,
+		
+		/// <summary> Ends with "?>" </summary>
+		ProcessingInstruction,
+		
+		/// <summary> Ends with "&lt;" or ">" </summary>
+		UnknownBang,
+		
+		/// <summary> Unknown </summary>
+		Other
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TokenReader.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TokenReader.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/TokenReader.cs	(revision 11807)
@@ -0,0 +1,350 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	class TokenReader
+	{
+		protected readonly ITextSource input;
+		protected readonly int inputLength;
+		int currentLocation;
+		
+		// CurrentLocation is assumed to be touched and the fact does not
+		//   have to be recorded in this variable.
+		// This stores any value bigger than that if applicable.
+		// Actual value is max(currentLocation, maxTouchedLocation).
+		int maxTouchedLocation;
+		
+		public int InputLength {
+			get { return inputLength; }
+		}
+		
+		public int CurrentLocation {
+			get { return currentLocation; }
+		}
+		
+		public int MaxTouchedLocation {
+			// add 1 to currentLocation because single-char-peek does not increment maxTouchedLocation
+			get { return Math.Max(currentLocation + 1, maxTouchedLocation); }
+		}
+		
+		public TokenReader(ITextSource input)
+		{
+			this.input = input;
+			this.inputLength = input.TextLength;
+		}
+		
+		protected bool IsEndOfFile()
+		{
+			return currentLocation == inputLength;
+		}
+		
+		protected bool HasMoreData()
+		{
+			return currentLocation < inputLength;
+		}
+		
+		protected void AssertHasMoreData()
+		{
+			Log.Assert(HasMoreData(), "Unexpected end of file");
+		}
+		
+		protected bool TryMoveNext()
+		{
+			if (currentLocation == inputLength) return false;
+			
+			currentLocation++;
+			return true;
+		}
+		
+		protected void Skip(int count)
+		{
+			Log.Assert(currentLocation + count <= inputLength, "Skipping after the end of file");
+			currentLocation += count;
+		}
+		
+		protected void GoBack(int oldLocation)
+		{
+			Log.Assert(oldLocation <= currentLocation, "Trying to move forward");
+			// add 1 because single-char-peek does not increment maxTouchedLocation
+			maxTouchedLocation = Math.Max(maxTouchedLocation, currentLocation + 1);
+			currentLocation = oldLocation;
+		}
+		
+		protected bool TryRead(char c)
+		{
+			if (currentLocation == inputLength) return false;
+			
+			if (input.GetCharAt(currentLocation) == c) {
+				currentLocation++;
+				return true;
+			} else {
+				return false;
+			}
+		}
+		
+		protected bool TryReadAnyOf(params char[] c)
+		{
+			if (currentLocation == inputLength) return false;
+			
+			if (c.Contains(input.GetCharAt(currentLocation))) {
+				currentLocation++;
+				return true;
+			} else {
+				return false;
+			}
+		}
+		
+		protected bool TryRead(string text)
+		{
+			if (TryPeek(text)) {
+				currentLocation += text.Length;
+				return true;
+			} else {
+				return false;
+			}
+		}
+		
+		protected bool TryPeekPrevious(char c, int back)
+		{
+			if (currentLocation - back == inputLength) return false;
+			if (currentLocation - back < 0 ) return false;
+			
+			return input.GetCharAt(currentLocation - back) == c;
+		}
+		
+		protected bool TryPeek(char c)
+		{
+			if (currentLocation == inputLength) return false;
+			
+			return input.GetCharAt(currentLocation) == c;
+		}
+		
+		protected bool TryPeekAnyOf(params char[] chars)
+		{
+			if (currentLocation == inputLength) return false;
+			
+			return chars.Contains(input.GetCharAt(currentLocation));
+		}
+		
+		protected bool TryPeek(string text)
+		{
+			if (!TryPeek(text[0])) return false; // Early exit
+			
+			maxTouchedLocation = Math.Max(maxTouchedLocation, currentLocation + text.Length);
+			// The following comparison 'touches' the end of file - it does depend on the end being there
+			if (currentLocation + text.Length > inputLength) return false;
+			
+			return input.GetText(currentLocation, text.Length) == text;
+		}
+		
+		protected bool TryPeekWhiteSpace()
+		{
+			if (currentLocation == inputLength) return false;
+			
+			char c = input.GetCharAt(currentLocation);
+			return ((int)c <= 0x20) && (c == ' ' || c == '\t' || c == '\n' || c == '\r');
+		}
+		
+		// The move functions do not have to move if already at target
+		// The move functions allow 'overriding' of the document length
+		
+		protected bool TryMoveTo(char c)
+		{
+			return TryMoveTo(c, inputLength);
+		}
+		
+		protected bool TryMoveTo(char c, int inputLength)
+		{
+			if (currentLocation == inputLength) return false;
+			int index = input.IndexOf(c, currentLocation, inputLength - currentLocation);
+			if (index != -1) {
+				currentLocation = index;
+				return true;
+			} else {
+				currentLocation = inputLength;
+				return false;
+			}
+		}
+		
+		protected bool TryMoveToAnyOf(params char[] c)
+		{
+			return TryMoveToAnyOf(c, inputLength);
+		}
+		
+		protected bool TryMoveToAnyOf(char[] c, int inputLength)
+		{
+			if (currentLocation == inputLength) return false;
+			int index = input.IndexOfAny(c, currentLocation, inputLength - currentLocation);
+			if (index != -1) {
+				currentLocation = index;
+				return true;
+			} else {
+				currentLocation = inputLength;
+				return false;
+			}
+		}
+		
+		protected bool TryMoveTo(string text)
+		{
+			return TryMoveTo(text, inputLength);
+		}
+		
+		protected bool TryMoveTo(string text, int inputLength)
+		{
+			if (currentLocation == inputLength) return false;
+			int index = input.IndexOf(text, currentLocation, inputLength - currentLocation, StringComparison.Ordinal);
+			if (index != -1) {
+				maxTouchedLocation = index + text.Length;
+				currentLocation = index;
+				return true;
+			} else {
+				currentLocation = inputLength;
+				return false;
+			}
+		}
+		
+		protected bool TryMoveToNonWhiteSpace()
+		{
+			return TryMoveToNonWhiteSpace(inputLength);
+		}
+		
+		protected bool TryMoveToNonWhiteSpace(int inputLength)
+		{
+			while(true) {
+				if (currentLocation == inputLength) return false; // Reject end of file
+				char c = input.GetCharAt(currentLocation);
+				if (((int)c <= 0x20) && (c == ' ' || c == '\t' || c == '\n' || c == '\r')) {
+					currentLocation++;                            // Accept white-space
+					continue;
+				} else {
+					return true;  // Found non-white-space
+				}
+			}
+		}
+		
+		/// <summary>
+		/// Read a name token.
+		/// The following characters are not allowed:
+		///   ""         End of file
+		///   " \n\r\t"  Whitesapce
+		///   "=\'\""    Attribute value
+		///   "&lt;>/?"  Tags
+		/// </summary>
+		/// <returns>Returns the length of the name</returns>
+		protected bool TryReadName()
+		{
+			int start = currentLocation;
+			// Keep reading up to invalid character
+			while (HasMoreData()) {
+				char c = input.GetCharAt(currentLocation);
+				if (0x41 <= (int)c) {                                   // Accpet from 'A' onwards
+					currentLocation++;
+					continue;
+				}
+				if (c == ' ' || c == '\n' || c == '\r' || c == '\t' ||  // Reject whitesapce
+				    c == '=' || c == '\'' || c == '"'  ||               // Reject attributes
+				    c == '<' || c == '>'  || c == '/'  || c == '?') {   // Reject tags
+					break;
+				} else {
+					currentLocation++;
+					continue;                                            // Accept other character
+				}
+			}
+			return currentLocation > start;
+		}
+		
+		protected bool TryReadName(out string name)
+		{
+			int start = currentLocation;
+			if (TryReadName()) {
+				name = GetCachedString(GetText(start, currentLocation));
+				return true;
+			} else {
+				name = string.Empty;
+				return false;
+			}
+		}
+		
+		protected string GetText(int start, int end)
+		{
+			Log.Assert(end <= currentLocation, "Reading ahead of current location");
+			return input.GetText(start, end - start);
+		}
+		
+		Dictionary<string, string> stringCache = new Dictionary<string, string>();
+		
+		#if DEBUG
+		int stringCacheRequestedCount;
+		int stringCacheRequestedSize;
+		int stringCacheStoredCount;
+		int stringCacheStoredSize;
+		#endif
+		
+		internal void PrintStringCacheStats()
+		{
+			#if DEBUG
+			Log.WriteLine("String cache: Requested {0} ({1} bytes);  Actaully stored {2} ({3} bytes); {4}% stored", stringCacheRequestedCount, stringCacheRequestedSize, stringCacheStoredCount, stringCacheStoredSize, stringCacheRequestedSize == 0 ? 0 : stringCacheStoredSize * 100 / stringCacheRequestedSize);
+			#endif
+		}
+		
+		[Conditional("DEBUG")]
+		void AddToRequestedSize(string text)
+		{
+			#if DEBUG
+			stringCacheRequestedCount += 1;
+			stringCacheRequestedSize += 8 + 2 * text.Length;
+			#endif
+		}
+		
+		[Conditional("DEBUG")]
+		void AddToStoredSize(string text)
+		{
+			#if DEBUG
+			stringCacheStoredCount += 1;
+			stringCacheStoredSize += 8 + 2 * text.Length;
+			#endif
+		}
+		
+		protected string GetCachedString(string cached)
+		{
+			AddToRequestedSize(cached);
+			// Do not bother with long strings
+			if (cached.Length > 32) {
+				AddToStoredSize(cached);
+				return cached;
+			}
+			string result;
+			if (stringCache.TryGetValue(cached, out result)) {
+				// Get the instance from the cache instead
+				return result;
+			} else {
+				// Add to cache
+				AddToStoredSize(cached);
+				stringCache.Add(cached, cached);
+				return cached;
+			}
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/XmlSegment.cs
===================================================================
--- /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/XmlSegment.cs	(revision 11807)
+++ /trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.Xml-5.5.0/XmlSegment.cs	(revision 11807)
@@ -0,0 +1,48 @@
+﻿// Copyright (c) 2009-2013 AlphaSierraPapa for the SharpDevelop Team
+// 
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this
+// software and associated documentation files (the "Software"), to deal in the Software
+// without restriction, including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
+// to whom the Software is furnished to do so, subject to the following conditions:
+// 
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+using System;
+using ICSharpCode.NRefactory.Editor;
+
+namespace ICSharpCode.NRefactory.Xml
+{
+	sealed class XmlSegment : ISegment
+	{
+		readonly int startOffset, endOffset;
+		
+		public XmlSegment(int startOffset, int endOffset)
+		{
+			if (endOffset < startOffset)
+				throw new ArgumentOutOfRangeException();
+			this.startOffset = startOffset;
+			this.endOffset = endOffset;
+		}
+		
+		int ISegment.Offset {
+			get { return startOffset; }
+		}
+		
+		int ISegment.Length {
+			get { return endOffset - startOffset; }
+		}
+		
+		int ISegment.EndOffset {
+			get { return endOffset; }
+		}
+	}
+}
Index: /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/HeuristicLab.Operators.Programmable.Views-3.3.csproj
===================================================================
--- /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/HeuristicLab.Operators.Programmable.Views-3.3.csproj	(revision 11806)
+++ /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/HeuristicLab.Operators.Programmable.Views-3.3.csproj	(revision 11807)
@@ -128,7 +128,7 @@
   </ItemGroup>
   <ItemGroup>
-    <ProjectReference Include="..\..\HeuristicLab.CodeEditor\3.3\HeuristicLab.CodeEditor-3.3.csproj">
-      <Project>{489CFE09-FDF7-4C89-BAB5-BD09CADD61AD}</Project>
-      <Name>HeuristicLab.CodeEditor-3.3</Name>
+    <ProjectReference Include="..\..\HeuristicLab.CodeEditor\3.4\HeuristicLab.CodeEditor-3.4.csproj">
+      <Project>{C38691AE-ECB4-489A-A05D-B035554E0168}</Project>
+      <Name>HeuristicLab.CodeEditor-3.4</Name>
       <Private>False</Private>
     </ProjectReference>
Index: /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/Plugin.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/Plugin.cs.frame	(revision 11806)
+++ /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/Plugin.cs.frame	(revision 11807)
@@ -28,5 +28,5 @@
   [Plugin("HeuristicLab.Operators.Programmable.Views", "3.3.10.$WCREV$")]
   [PluginFile("HeuristicLab.Operators.Programmable.Views-3.3.dll", PluginFileType.Assembly)]
-  [PluginDependency("HeuristicLab.CodeEditor", "3.3")]
+  [PluginDependency("HeuristicLab.CodeEditor", "3.4")]
   [PluginDependency("HeuristicLab.Common.Resources", "3.3")]
   [PluginDependency("HeuristicLab.Core", "3.3")]
Index: /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/ProgrammableOperatorView.cs
===================================================================
--- /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/ProgrammableOperatorView.cs	(revision 11806)
+++ /trunk/sources/HeuristicLab.Operators.Programmable.Views/3.3/ProgrammableOperatorView.cs	(revision 11807)
@@ -82,23 +82,19 @@
       base.OnContentChanged();
       if (ProgrammableOperator == null) {
-        codeEditor.UserCode = "";
+        codeEditor.UserCode = string.Empty;
         assembliesTreeView.Nodes.Clear();
         parameterCollectionView.Content = null;
       } else {
         codeEditor.Prefix = GetGeneratedPrefix();
-        codeEditor.Suffix = String.Format("    {0}\n  }}\n}}", ProgrammableOperator.MethodSuffix);
+        codeEditor.Suffix = String.Format("    {0}{1}  }}{1}}}", ProgrammableOperator.MethodSuffix, Environment.NewLine);
         codeEditor.UserCode = ProgrammableOperator.Code;
-        if (codeEditor.UserCode == "")
-          codeEditor.UserCode = "    \n    \n    \n    \n";
+        if (codeEditor.UserCode == string.Empty)
+          codeEditor.UserCode = string.Format("    {0}", Environment.NewLine);
         InitializeAssemblyList();
         InitializeNamespacesList();
-        foreach (var a in ProgrammableOperator.SelectedAssemblies) {
-          codeEditor.AddAssembly(a);
-        }
+        codeEditor.AddAssemblies(ProgrammableOperator.SelectedAssemblies);
         codeEditor.ScrollAfterPrefix();
-        codeEditor.ShowCompileErrors(ProgrammableOperator.CompileErrors, "ProgrammableOperator");
-        showCodeButton.Enabled =
-          ProgrammableOperator.CompilationUnitCode != null &&
-          ProgrammableOperator.CompilationUnitCode.Length > 0;
+        codeEditor.ShowCompileErrors(ProgrammableOperator.CompileErrors);
+        showCodeButton.Enabled = !string.IsNullOrEmpty(ProgrammableOperator.CompilationUnitCode);
         parameterCollectionView.Content = ProgrammableOperator.Parameters;
         if (ProgrammableOperator.CompileErrors == null) {
Index: /trunk/sources/HeuristicLab.Scripting.Views/3.3/HeuristicLab.Scripting.Views-3.3.csproj
===================================================================
--- /trunk/sources/HeuristicLab.Scripting.Views/3.3/HeuristicLab.Scripting.Views-3.3.csproj	(revision 11806)
+++ /trunk/sources/HeuristicLab.Scripting.Views/3.3/HeuristicLab.Scripting.Views-3.3.csproj	(revision 11807)
@@ -118,8 +118,7 @@
   </ItemGroup>
   <ItemGroup>
-    <ProjectReference Include="..\..\HeuristicLab.CodeEditor\3.3\HeuristicLab.CodeEditor-3.3.csproj">
-      <Project>{489cfe09-fdf7-4c89-bab5-bd09cadd61ad}</Project>
-      <Name>HeuristicLab.CodeEditor-3.3</Name>
-      <Private>False</Private>
+    <ProjectReference Include="..\..\HeuristicLab.CodeEditor\3.4\HeuristicLab.CodeEditor-3.4.csproj">
+      <Project>{c38691ae-ecb4-489a-a05d-b035554e0168}</Project>
+      <Name>HeuristicLab.CodeEditor-3.4</Name>
     </ProjectReference>
     <ProjectReference Include="..\..\HeuristicLab.Collections\3.3\HeuristicLab.Collections-3.3.csproj">
Index: /trunk/sources/HeuristicLab.Scripting.Views/3.3/Plugin.cs.frame
===================================================================
--- /trunk/sources/HeuristicLab.Scripting.Views/3.3/Plugin.cs.frame	(revision 11806)
+++ /trunk/sources/HeuristicLab.Scripting.Views/3.3/Plugin.cs.frame	(revision 11807)
@@ -25,5 +25,5 @@
   [Plugin("HeuristicLab.Scripting.Views", "3.3.10.$WCREV$")]
   [PluginFile("HeuristicLab.Scripting.Views-3.3.dll", PluginFileType.Assembly)]
-  [PluginDependency("HeuristicLab.CodeEditor", "3.3")]
+  [PluginDependency("HeuristicLab.CodeEditor", "3.4")]
   [PluginDependency("HeuristicLab.Collections", "3.3")]
   [PluginDependency("HeuristicLab.Common", "3.3")]
Index: /trunk/sources/HeuristicLab.Scripting.Views/3.3/ScriptView.Designer.cs
===================================================================
--- /trunk/sources/HeuristicLab.Scripting.Views/3.3/ScriptView.Designer.cs	(revision 11806)
+++ /trunk/sources/HeuristicLab.Scripting.Views/3.3/ScriptView.Designer.cs	(revision 11807)
@@ -19,4 +19,8 @@
  */
 #endregion
+
+using System.Collections.Generic;
+using System.Reflection;
+using HeuristicLab.Common;
 
 namespace HeuristicLab.Scripting.Views {
@@ -46,5 +50,4 @@
     private void InitializeComponent() {
       this.components = new System.ComponentModel.Container();
-      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScriptView));
       this.compilationLabel = new System.Windows.Forms.Label();
       this.imageList = new System.Windows.Forms.ImageList(this.components);
@@ -214,10 +217,14 @@
       this.codeEditor.TabIndex = 0;
       this.codeEditor.UserCode = "";
+      this.codeEditor.AssembliesLoaded += new System.EventHandler<EventArgs<IEnumerable<Assembly>>>(this.codeEditor_AssembliesLoaded);
+      this.codeEditor.AssembliesLoading += new System.EventHandler<EventArgs<IEnumerable<Assembly>>>(this.codeEditor_AssembliesLoading);
+      this.codeEditor.AssembliesUnloaded += new System.EventHandler<EventArgs<IEnumerable<Assembly>>>(this.codeEditor_AssembliesUnloaded);
+      this.codeEditor.AssembliesUnloading += new System.EventHandler<EventArgs<IEnumerable<Assembly>>>(this.codeEditor_AssembliesUnloading);
       this.codeEditor.TextEditorTextChanged += new System.EventHandler(this.codeEditor_TextEditorTextChanged);
       // 
       // splitContainer1
       // 
-      this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
-            | System.Windows.Forms.AnchorStyles.Left) 
+      this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+            | System.Windows.Forms.AnchorStyles.Left)
             | System.Windows.Forms.AnchorStyles.Right)));
       this.splitContainer1.Location = new System.Drawing.Point(0, 56);
Index: /trunk/sources/HeuristicLab.Scripting.Views/3.3/ScriptView.cs
===================================================================
--- /trunk/sources/HeuristicLab.Scripting.Views/3.3/ScriptView.cs	(revision 11806)
+++ /trunk/sources/HeuristicLab.Scripting.Views/3.3/ScriptView.cs	(revision 11807)
@@ -22,8 +22,11 @@
 using System;
 using System.CodeDom.Compiler;
+using System.Collections.Generic;
 using System.Drawing;
 using System.Globalization;
 using System.Linq;
+using System.Reflection;
 using System.Windows.Forms;
+using HeuristicLab.Common;
 using HeuristicLab.Common.Resources;
 using HeuristicLab.Core.Views;
@@ -35,4 +38,8 @@
   [Content(typeof(Script), true)]
   public partial class ScriptView : NamedItemView {
+    private const string AssembliesLoadingMessage = "Loading Assemblies";
+    private const string AssembliesUnloadingMessage = "Unloading Assemblies";
+    private const int SilentAssemblyLoadingOperationLimit = 10;
+
     #region Properties
     public new Script Content {
@@ -73,8 +80,6 @@
         codeEditor.UserCode = string.Empty;
       } else {
-        if (codeEditor.UserCode != Content.Code)
-          codeEditor.UserCode = Content.Code;
-        foreach (var asm in Content.GetAssemblies())
-          codeEditor.AddAssembly(asm);
+        codeEditor.UserCode = Content.Code;
+        codeEditor.AddAssembliesAsync(Content.GetAssemblies());
         if (Content.CompileErrors == null) {
           compilationLabel.ForeColor = SystemColors.ControlDarkDark;
@@ -131,5 +136,4 @@
         Locked = false;
         codeEditor.Focus();
-        OnContentChanged();
       }
     }
@@ -157,5 +161,5 @@
       }
 
-      codeEditor.ShowCompileErrors(Content.CompileErrors, ".cs");
+      codeEditor.ShowCompileErrors(Content.CompileErrors);
 
       AdjustErrorListViewColumnSizes();
@@ -167,10 +171,26 @@
         ch.Width = -2;
     }
+
+    #region ProgressView
+    private bool progressViewCreated;
+
+    private void AddProgressView(string progressMessage) {
+      var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
+      mainForm.AddOperationProgressToView(this, progressMessage);
+      progressViewCreated = true;
+    }
+
+    private void RemoveProgressView() {
+      if (!progressViewCreated) return;
+      var mainForm = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>();
+      mainForm.RemoveOperationProgressFromView(this);
+      progressViewCreated = false;
+    }
+    #endregion
     #endregion
 
     #region Event Handlers
     private void Content_CodeChanged(object sender, EventArgs e) {
-      if (InvokeRequired)
-        Invoke(new EventHandler(Content_CodeChanged), sender, e);
+      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_CodeChanged, sender, e);
       else {
         codeEditor.UserCode = Content.Code;
@@ -196,4 +216,36 @@
     }
     #endregion
+
+    private void codeEditor_AssembliesLoading(object sender, EventArgs<IEnumerable<Assembly>> e) {
+      if (InvokeRequired) Invoke((Action<object, EventArgs<IEnumerable<Assembly>>>)codeEditor_AssembliesLoading, sender, e);
+      else {
+        int nrOfAssemblies = e.Value.Count();
+        if (nrOfAssemblies > SilentAssemblyLoadingOperationLimit)
+          AddProgressView(AssembliesLoadingMessage);
+      }
+    }
+
+    private void codeEditor_AssembliesLoaded(object sender, EventArgs<IEnumerable<Assembly>> e) {
+      if (InvokeRequired) Invoke((Action<object, EventArgs<IEnumerable<Assembly>>>)codeEditor_AssembliesLoaded, sender, e);
+      else {
+        RemoveProgressView();
+      }
+    }
+
+    private void codeEditor_AssembliesUnloading(object sender, EventArgs<IEnumerable<Assembly>> e) {
+      if (InvokeRequired) Invoke((Action<object, EventArgs<IEnumerable<Assembly>>>)codeEditor_AssembliesUnloading, sender, e);
+      else {
+        int nrOfAssemblies = e.Value.Count();
+        if (nrOfAssemblies > SilentAssemblyLoadingOperationLimit)
+          AddProgressView(AssembliesUnloadingMessage);
+      }
+    }
+
+    private void codeEditor_AssembliesUnloaded(object sender, EventArgs<IEnumerable<Assembly>> e) {
+      if (InvokeRequired) Invoke((Action<object, EventArgs<IEnumerable<Assembly>>>)codeEditor_AssembliesUnloaded, sender, e);
+      else {
+        RemoveProgressView();
+      }
+    }
   }
 }
